QPAT commited on
Commit
8c6372a
·
1 Parent(s): 7bd0c6c

Refactoring code

Browse files
Files changed (25) hide show
  1. src/main/java/com/attendenceSystem/module/attendance/api/AttendanceManagerApiController.java +1 -1
  2. src/main/java/com/attendenceSystem/module/attendance/service/AttendanceService.java +2 -2
  3. src/main/java/com/attendenceSystem/module/attendance/service/impl/AttendanceServiceImpl.java +52 -56
  4. src/main/java/com/attendenceSystem/module/dashboard/service/impl/DashboardServiceImpl.java +98 -76
  5. src/main/java/com/attendenceSystem/module/faceid/api/FaceIdApiController.java +2 -2
  6. src/main/java/com/attendenceSystem/module/faceid/entity/FaceProfile.java +0 -1
  7. src/main/java/com/attendenceSystem/module/faceid/entity/FaceSample.java +0 -1
  8. src/main/java/com/attendenceSystem/module/log/entity/AuditLog.java +0 -1
  9. src/main/java/com/attendenceSystem/module/otp/api/OtpApiController.java +2 -2
  10. src/main/java/com/attendenceSystem/module/otp/entity/Otp.java +0 -1
  11. src/main/java/com/attendenceSystem/module/otp/mapper/request/SendOtpRequestMapper.java +0 -1
  12. src/main/java/com/attendenceSystem/module/otp/service/{OptService.java → OtpService.java} +1 -1
  13. src/main/java/com/attendenceSystem/module/otp/service/impl/OtpServiceImpl.java +2 -2
  14. src/main/java/com/attendenceSystem/module/report/entity/Report.java +3 -1
  15. src/main/java/com/attendenceSystem/module/report/service/impl/ReportServiceImpl.java +10 -36
  16. src/main/java/com/attendenceSystem/module/storage/exception/FileStorageException.java +11 -0
  17. src/main/java/com/attendenceSystem/module/storage/provider/LocalStorageProvider.java +23 -17
  18. src/main/java/com/attendenceSystem/module/storage/provider/StorageProvider.java +1 -1
  19. src/main/java/com/attendenceSystem/module/storage/service/impl/FileStorageServiceImpl.java +34 -22
  20. src/main/java/com/attendenceSystem/module/user/api/AdminAccountApiController.java +0 -1
  21. src/main/java/com/attendenceSystem/module/user/api/UserApiController.java +0 -2
  22. src/main/java/com/attendenceSystem/module/user/controller/AuthController.java +0 -2
  23. src/main/java/com/attendenceSystem/module/user/entity/User.java +0 -1
  24. src/main/java/com/attendenceSystem/module/user/mapper/response/UserResponseMapper.java +0 -3
  25. src/main/java/com/attendenceSystem/module/user/service/impl/AuthServiceImpl.java +2 -7
src/main/java/com/attendenceSystem/module/attendance/api/AttendanceManagerApiController.java CHANGED
@@ -56,7 +56,7 @@ public class AttendanceManagerApiController {
56
  // Invalid status, ignore
57
  }
58
  }
59
- List<AttendanceResponse> list = attendanceService.getManagerAttendanceList(departmentId, startDate, endDate, attendanceStatus);
60
  return ResponseEntity.ok(list);
61
  }
62
  }
 
56
  // Invalid status, ignore
57
  }
58
  }
59
+ List<AttendanceResponse> list = attendanceService.getManagerAttendanceList(startDate, endDate, attendanceStatus);
60
  return ResponseEntity.ok(list);
61
  }
62
  }
src/main/java/com/attendenceSystem/module/attendance/service/AttendanceService.java CHANGED
@@ -32,9 +32,9 @@ public interface AttendanceService {
32
 
33
  ManagerStatsResponse getManagerStats(String departmentId, LocalDate startDate, LocalDate endDate, AttendanceStatus status);
34
 
35
- List<AttendanceResponse> getManagerAttendanceList(String departmentId, LocalDate startDate, LocalDate endDate);
36
 
37
- List<AttendanceResponse> getManagerAttendanceList(String departmentId, LocalDate startDate, LocalDate endDate, AttendanceStatus status);
38
 
39
  LeaveRequestResponse createLeaveRequest(CreateLeaveRequest request);
40
 
 
32
 
33
  ManagerStatsResponse getManagerStats(String departmentId, LocalDate startDate, LocalDate endDate, AttendanceStatus status);
34
 
35
+ List<AttendanceResponse> getManagerAttendanceList(LocalDate startDate, LocalDate endDate);
36
 
37
+ List<AttendanceResponse> getManagerAttendanceList(LocalDate startDate, LocalDate endDate, AttendanceStatus status);
38
 
39
  LeaveRequestResponse createLeaveRequest(CreateLeaveRequest request);
40
 
src/main/java/com/attendenceSystem/module/attendance/service/impl/AttendanceServiceImpl.java CHANGED
@@ -3,7 +3,10 @@ package com.attendenceSystem.module.attendance.service.impl;
3
  import java.time.LocalDate;
4
  import java.time.LocalDateTime;
5
  import java.util.List;
 
6
  import java.util.Optional;
 
 
7
 
8
  import org.springframework.beans.factory.annotation.Value;
9
  import org.springframework.dao.DataIntegrityViolationException;
@@ -128,6 +131,7 @@ public class AttendanceServiceImpl implements AttendanceService {
128
  attendanceRecordRepository.save(attendance);
129
  return attendanceResponseMapper.fromEntity(attendance);
130
  }
 
131
  @Override
132
  public Page<AttendanceResponse> getAttendanceHistory(final Pageable pageable) {
133
  User user = getCurrentUser();
@@ -142,20 +146,10 @@ public class AttendanceServiceImpl implements AttendanceService {
142
  return getManagerStats(departmentId, startDate, endDate, null);
143
  }
144
 
145
- @Override
146
- public List<AttendanceResponse> getManagerAttendanceList(String departmentId, LocalDate startDate, LocalDate endDate) {
147
- return getManagerAttendanceList(departmentId, startDate, endDate, null);
148
- }
149
-
150
- private List<AttendanceRecord> getFilteredRecords(LocalDate startDate, LocalDate endDate, AttendanceStatus status) {
151
- if (status != null) {
152
- return attendanceRecordRepository.findByAttendanceDateBetweenAndStatus(startDate, endDate, status);
153
- }
154
- return attendanceRecordRepository.findByAttendanceDateBetween(startDate, endDate);
155
- }
156
-
157
- public ManagerStatsResponse getManagerStats(String departmentId, LocalDate startDate, LocalDate endDate, AttendanceStatus status) {
158
  List<User> employees;
 
159
  if (departmentId != null && !departmentId.isEmpty()) {
160
  Department dept = Department.fromValue(departmentId);
161
  if (dept == null) {
@@ -186,26 +180,27 @@ public class AttendanceServiceImpl implements AttendanceService {
186
  long lateArrivals = 0;
187
  long absent = 0;
188
 
 
 
 
 
 
 
189
  for (User emp : employees) {
190
- boolean hasRecord = false;
191
- for (AttendanceRecord record : records) {
192
- if (record.getUser() != null && record.getUser().getId().equals(emp.getId())) {
193
- hasRecord = true;
194
- if (record.getStatus() == AttendanceStatus.LATE) {
195
- lateArrivals++;
196
- }
197
- checkedIn++;
198
- if (record.getCheckOutTime() != null) {
199
- checkedOut++;
200
- }
201
- break;
202
- }
203
- }
204
- if (!hasRecord) {
205
  absent++;
 
 
 
 
 
 
 
 
206
  }
207
  }
208
-
209
  return ManagerStatsResponse.builder()
210
  .totalEmployees(totalEmployees)
211
  .checkedIn(checkedIn)
@@ -215,18 +210,14 @@ public class AttendanceServiceImpl implements AttendanceService {
215
  .build();
216
  }
217
 
218
- public List<AttendanceResponse> getManagerAttendanceList(String departmentId, LocalDate startDate, LocalDate endDate, AttendanceStatus status) {
219
- List<User> employees;
220
- if (departmentId != null && !departmentId.isEmpty()) {
221
- Department dept = Department.fromValue(departmentId);
222
- if (dept == null) {
223
- employees = userRepository.findByRoleNot(Role.ADMIN);
224
- } else {
225
- employees = userRepository.findByDepartmentAndRoleNot(dept, Role.ADMIN);
226
- }
227
- } else {
228
- employees = userRepository.findByRoleNot(Role.ADMIN);
229
- }
230
  DateRange dateRange = getDateRange(startDate, endDate);
231
 
232
  List<AttendanceRecord> records = getFilteredRecords(dateRange.startDate(), dateRange.endDate(), status);
@@ -234,9 +225,12 @@ public class AttendanceServiceImpl implements AttendanceService {
234
  return records.stream()
235
  .map(attendanceResponseMapper::fromEntity)
236
  .sorted((a, b) -> {
237
- if (a.attendanceDate() == null && b.attendanceDate() == null) return 0;
238
- if (a.attendanceDate() == null) return 1;
239
- if (b.attendanceDate() == null) return -1;
 
 
 
240
  return b.attendanceDate().compareTo(a.attendanceDate());
241
  })
242
  .toList();
@@ -306,19 +300,21 @@ public class AttendanceServiceImpl implements AttendanceService {
306
  }
307
 
308
  private DateRange getDateRange(LocalDate startDate, LocalDate endDate) {
309
- LocalDate effectiveStartDate = startDate;
310
- LocalDate effectiveEndDate = endDate;
311
- if (effectiveStartDate == null && effectiveEndDate == null) {
312
- LocalDate today = todayDate();
313
- effectiveStartDate = today.minusMonths(6);
314
- effectiveEndDate = today;
315
- } else if (effectiveStartDate != null && effectiveEndDate == null) {
316
- effectiveEndDate = effectiveStartDate;
317
- } else if (effectiveStartDate == null && effectiveEndDate != null) {
318
- effectiveStartDate = effectiveEndDate;
319
- }
320
- return new DateRange(effectiveStartDate, effectiveEndDate);
321
  }
322
 
 
 
 
 
 
 
323
 
324
  }
 
3
  import java.time.LocalDate;
4
  import java.time.LocalDateTime;
5
  import java.util.List;
6
+ import java.util.Map;
7
  import java.util.Optional;
8
+ import java.util.function.Function;
9
+ import java.util.stream.Collectors;
10
 
11
  import org.springframework.beans.factory.annotation.Value;
12
  import org.springframework.dao.DataIntegrityViolationException;
 
131
  attendanceRecordRepository.save(attendance);
132
  return attendanceResponseMapper.fromEntity(attendance);
133
  }
134
+
135
  @Override
136
  public Page<AttendanceResponse> getAttendanceHistory(final Pageable pageable) {
137
  User user = getCurrentUser();
 
146
  return getManagerStats(departmentId, startDate, endDate, null);
147
  }
148
 
149
+ public ManagerStatsResponse getManagerStats(String departmentId, LocalDate startDate, LocalDate endDate,
150
+ AttendanceStatus status) {
 
 
 
 
 
 
 
 
 
 
 
151
  List<User> employees;
152
+
153
  if (departmentId != null && !departmentId.isEmpty()) {
154
  Department dept = Department.fromValue(departmentId);
155
  if (dept == null) {
 
180
  long lateArrivals = 0;
181
  long absent = 0;
182
 
183
+ Map<Long, AttendanceRecord> attendanceMap = records.stream()
184
+ .filter(r -> r.getUser() != null)
185
+ .collect(Collectors.toMap(
186
+ r -> r.getUser().getId(),
187
+ Function.identity(),
188
+ (a, b) -> a));
189
  for (User emp : employees) {
190
+ AttendanceRecord record = attendanceMap.get(emp.getId());
191
+ if (record == null){
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  absent++;
193
+ continue;
194
+ }
195
+ checkedIn++;
196
+ if(record.getStatus() == AttendanceStatus.LATE) {
197
+ lateArrivals++;
198
+ }
199
+ if (record.getCheckOutTime() !=null){
200
+ checkedOut++;
201
  }
202
  }
203
+ //
204
  return ManagerStatsResponse.builder()
205
  .totalEmployees(totalEmployees)
206
  .checkedIn(checkedIn)
 
210
  .build();
211
  }
212
 
213
+ @Override
214
+ public List<AttendanceResponse> getManagerAttendanceList(LocalDate startDate,
215
+ LocalDate endDate) {
216
+ return getManagerAttendanceList(startDate, endDate, null);
217
+ }
218
+
219
+ public List<AttendanceResponse> getManagerAttendanceList(LocalDate startDate,
220
+ LocalDate endDate, AttendanceStatus status) {
 
 
 
 
221
  DateRange dateRange = getDateRange(startDate, endDate);
222
 
223
  List<AttendanceRecord> records = getFilteredRecords(dateRange.startDate(), dateRange.endDate(), status);
 
225
  return records.stream()
226
  .map(attendanceResponseMapper::fromEntity)
227
  .sorted((a, b) -> {
228
+ if (a.attendanceDate() == null && b.attendanceDate() == null)
229
+ return 0;
230
+ if (a.attendanceDate() == null)
231
+ return 1;
232
+ if (b.attendanceDate() == null)
233
+ return -1;
234
  return b.attendanceDate().compareTo(a.attendanceDate());
235
  })
236
  .toList();
 
300
  }
301
 
302
  private DateRange getDateRange(LocalDate startDate, LocalDate endDate) {
303
+ LocalDate today = todayDate();
304
+
305
+ startDate = startDate == null
306
+ ? (endDate == null ? today.minusMonths(6) : endDate) : startDate;
307
+
308
+ endDate = endDate == null
309
+ ? startDate : endDate;
310
+ return new DateRange(startDate, endDate);
 
 
 
 
311
  }
312
 
313
+ private List<AttendanceRecord> getFilteredRecords(LocalDate startDate, LocalDate endDate, AttendanceStatus status) {
314
+ if (status != null) {
315
+ return attendanceRecordRepository.findByAttendanceDateBetweenAndStatus(startDate, endDate, status);
316
+ }
317
+ return attendanceRecordRepository.findByAttendanceDateBetween(startDate, endDate);
318
+ }
319
 
320
  }
src/main/java/com/attendenceSystem/module/dashboard/service/impl/DashboardServiceImpl.java CHANGED
@@ -3,6 +3,7 @@ package com.attendenceSystem.module.dashboard.service.impl;
3
  import java.time.DayOfWeek;
4
  import java.time.LocalDate;
5
  import java.time.temporal.TemporalAdjusters;
 
6
  import java.util.Locale;
7
  import java.util.stream.IntStream;
8
 
@@ -11,10 +12,12 @@ import org.springframework.data.domain.PageRequest;
11
  import org.springframework.stereotype.Service;
12
 
13
  import com.attendenceSystem.module.attendance.dto.response.AttendanceResponse;
 
14
  import com.attendenceSystem.module.attendance.mapper.response.AttendanceResponseMapper;
15
  import com.attendenceSystem.module.attendance.repository.AttendanceRecordRepository;
16
  import com.attendenceSystem.module.dashboard.dto.response.AccountTypeDistributionResponse;
17
  import com.attendenceSystem.module.dashboard.dto.response.AdminDashboardResponse;
 
18
  import com.attendenceSystem.module.dashboard.dto.response.EmployeeDashboardResponse;
19
  import com.attendenceSystem.module.dashboard.dto.response.ManagerDashboardResponse;
20
  import com.attendenceSystem.module.dashboard.mapper.response.DashboardResponseMapper;
@@ -33,88 +36,107 @@ import lombok.RequiredArgsConstructor;
33
  @Service
34
  @RequiredArgsConstructor
35
  public class DashboardServiceImpl implements DashboardService {
36
- private final UserRepository userRepository;
37
- private final AttendanceRecordRepository attendanceRecordRepository;
38
- private final ReportRepository reportRepository;
39
- private final AttendanceResponseMapper attendanceResponseMapper;
40
- private final DashboardResponseMapper dashboardResponseMapper;
41
 
42
- @Override
43
- public AdminDashboardResponse getAdminDashboard() {
44
- long totalAccounts = userRepository.count();
45
- long activeAccounts = userRepository.countByStatus(Status.ACTIVE);
46
- long inactiveAccounts = userRepository.countByStatus(Status.INACTIVE);
47
- long pendingAccounts = userRepository.countByStatus(Status.PENDING);
48
- var accountTypeDistribution = java.util.Arrays.stream(Role.values())
49
- .map(role -> new AccountTypeDistributionResponse(
50
- role.name(),
51
- roleLabel(role),
52
- userRepository.countByRole(role)))
53
- .toList();
54
- return dashboardResponseMapper.toAdminDashboardResponse(totalAccounts, activeAccounts, inactiveAccounts,
55
- pendingAccounts, accountTypeDistribution);
56
- }
 
 
 
 
57
 
58
- private String roleLabel(Role role) {
59
- String roleName = role.name().toLowerCase(Locale.ROOT);
60
- return roleName.substring(0, 1).toUpperCase(Locale.ROOT) + roleName.substring(1);
61
- }
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- @Override
64
- public ManagerDashboardResponse getManagerDashboard() {
65
- long totalEmployees = userRepository.countByRoleNot(Role.ADMIN);
66
- LocalDate today = LocalDate.now();
67
- long presentToday = attendanceRecordRepository.countByAttendanceDateAndStatus(today, com.attendenceSystem.module.attendance.entity.enums.AttendanceStatus.PRESENT);
68
- long lateToday = attendanceRecordRepository.countByAttendanceDateAndStatus(today, com.attendenceSystem.module.attendance.entity.enums.AttendanceStatus.LATE);
69
- long attendedToday = presentToday + lateToday;
70
- long absentToday = Math.max(0, totalEmployees - attendedToday);
71
- Page<AttendanceResponse> attendanceHistory = attendanceRecordRepository
72
- .findAllByOrderByAttendanceDateDesc(PageRequest.of(0, 10))
73
- .map(attendanceResponseMapper::fromEntity);
 
 
 
 
 
 
 
74
 
75
- var monday = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY).adjustInto(today);
76
- var weeklyStats = IntStream.rangeClosed(2, 6)
77
- .mapToObj(dayOfWeek -> {
78
- LocalDate date = ((LocalDate) monday).plusDays(dayOfWeek - DayOfWeek.MONDAY.getValue());
79
- long present = attendanceRecordRepository.countByAttendanceDateAndStatus(date, com.attendenceSystem.module.attendance.entity.enums.AttendanceStatus.PRESENT);
80
- long late = attendanceRecordRepository.countByAttendanceDateAndStatus(date, com.attendenceSystem.module.attendance.entity.enums.AttendanceStatus.LATE);
81
- long attended = present + late;
82
- long absent = Math.max(0, totalEmployees - attended);
83
- return new com.attendenceSystem.module.dashboard.dto.response.DailyAttendanceStats(
84
- "T" + (dayOfWeek - 1),
85
- present,
86
- late,
87
- absent
88
- );
89
- })
90
- .toList();
91
 
92
- return dashboardResponseMapper.toManagerDashboardResponse(totalEmployees, presentToday, lateToday, absentToday,
93
- attendanceHistory, weeklyStats);
94
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- @Override
97
- public EmployeeDashboardResponse getEmployeeDashboard() {
98
- User user = getCurrentUser();
99
- long totalReports = reportRepository.countByEmployee(user);
100
- long acceptedReports = reportRepository.countByEmployeeAndStatus(user, ReportStatus.ACCEPTED);
101
- long rejectedReports = reportRepository.countByEmployeeAndStatus(user, ReportStatus.REJECTED);
102
- long totalDays = attendanceRecordRepository.count();
103
- long attendedDays = attendanceRecordRepository.countByCheckInTimeNotNullAndCheckOutTimeNotNull();
104
- String attendenceRate = DashboardCalculator.showResultStr(attendedDays, totalDays);
105
- Page<AttendanceResponse> attendanceHistory = attendanceRecordRepository
106
- .findByUser(user, PageRequest.of(0, 10))
107
- .map(attendanceResponseMapper::fromEntity);
108
- return dashboardResponseMapper.toEmployeeDashboardResponse(totalReports, acceptedReports, rejectedReports,
109
- attendenceRate, attendanceHistory);
110
- }
111
 
112
- private User getCurrentUser() {
113
- String username = SecurityUtil.getCurrentUserName();
114
- if (username == null) {
115
- throw new IllegalArgumentException("Không tìm thấy người dùng");
116
  }
117
- return userRepository.findByUsername(username)
118
- .orElseThrow(() -> new IllegalArgumentException("Không tìm thấy người dùng"));
119
- }
120
  }
 
3
  import java.time.DayOfWeek;
4
  import java.time.LocalDate;
5
  import java.time.temporal.TemporalAdjusters;
6
+ import java.util.Arrays;
7
  import java.util.Locale;
8
  import java.util.stream.IntStream;
9
 
 
12
  import org.springframework.stereotype.Service;
13
 
14
  import com.attendenceSystem.module.attendance.dto.response.AttendanceResponse;
15
+ import com.attendenceSystem.module.attendance.entity.enums.AttendanceStatus;
16
  import com.attendenceSystem.module.attendance.mapper.response.AttendanceResponseMapper;
17
  import com.attendenceSystem.module.attendance.repository.AttendanceRecordRepository;
18
  import com.attendenceSystem.module.dashboard.dto.response.AccountTypeDistributionResponse;
19
  import com.attendenceSystem.module.dashboard.dto.response.AdminDashboardResponse;
20
+ import com.attendenceSystem.module.dashboard.dto.response.DailyAttendanceStats;
21
  import com.attendenceSystem.module.dashboard.dto.response.EmployeeDashboardResponse;
22
  import com.attendenceSystem.module.dashboard.dto.response.ManagerDashboardResponse;
23
  import com.attendenceSystem.module.dashboard.mapper.response.DashboardResponseMapper;
 
36
  @Service
37
  @RequiredArgsConstructor
38
  public class DashboardServiceImpl implements DashboardService {
39
+ private final UserRepository userRepository;
40
+ private final AttendanceRecordRepository attendanceRecordRepository;
41
+ private final ReportRepository reportRepository;
42
+ private final AttendanceResponseMapper attendanceResponseMapper;
43
+ private final DashboardResponseMapper dashboardResponseMapper;
44
 
45
+ @Override
46
+ public AdminDashboardResponse getAdminDashboard() {
47
+ long totalAccounts = userRepository.count();
48
+ long activeAccounts = userRepository.countByStatus(Status.ACTIVE);
49
+ long inactiveAccounts = userRepository.countByStatus(Status.INACTIVE);
50
+ long pendingAccounts = userRepository.countByStatus(Status.PENDING);
51
+ var accountTypeDistribution = Arrays.stream(Role.values())
52
+ .map(role -> new AccountTypeDistributionResponse(
53
+ role.name(),
54
+ roleLabel(role),
55
+ userRepository.countByRole(role)))
56
+ .toList();
57
+ return dashboardResponseMapper.toAdminDashboardResponse(
58
+ totalAccounts,
59
+ activeAccounts,
60
+ inactiveAccounts,
61
+ pendingAccounts,
62
+ accountTypeDistribution);
63
+ }
64
 
65
+ @Override
66
+ public ManagerDashboardResponse getManagerDashboard() {
67
+ long totalEmployees = userRepository.countByRoleNot(Role.ADMIN);
68
+ LocalDate today = LocalDate.now();
69
+ long presentToday = attendanceRecordRepository.countByAttendanceDateAndStatus(
70
+ today,
71
+ AttendanceStatus.PRESENT);
72
+ long lateToday = attendanceRecordRepository.countByAttendanceDateAndStatus(
73
+ today,
74
+ AttendanceStatus.LATE);
75
+ long attendedToday = presentToday + lateToday;
76
+ long absentToday = Math.max(0, totalEmployees - attendedToday);
77
+ Page<AttendanceResponse> attendanceHistory = attendanceRecordRepository
78
+ .findAllByOrderByAttendanceDateDesc(PageRequest.of(0, 10))
79
+ .map(attendanceResponseMapper::fromEntity);
80
 
81
+ var monday = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY).adjustInto(today);
82
+ var weeklyStats = IntStream.rangeClosed(2, 6)
83
+ .mapToObj(dayOfWeek -> {
84
+ LocalDate date = ((LocalDate) monday)
85
+ .plusDays(dayOfWeek - DayOfWeek.MONDAY.getValue());
86
+ long present = attendanceRecordRepository.countByAttendanceDateAndStatus(date,
87
+ AttendanceStatus.PRESENT);
88
+ long late = attendanceRecordRepository.countByAttendanceDateAndStatus(date,
89
+ AttendanceStatus.LATE);
90
+ long attended = present + late;
91
+ long absent = Math.max(0, totalEmployees - attended);
92
+ return new DailyAttendanceStats(
93
+ "T" + (dayOfWeek - 1),
94
+ present,
95
+ late,
96
+ absent);
97
+ })
98
+ .toList();
99
 
100
+ return dashboardResponseMapper.toManagerDashboardResponse(
101
+ totalEmployees,
102
+ presentToday,
103
+ lateToday,
104
+ absentToday,
105
+ attendanceHistory,
106
+ weeklyStats);
107
+ }
 
 
 
 
 
 
 
 
108
 
109
+ @Override
110
+ public EmployeeDashboardResponse getEmployeeDashboard() {
111
+ User user = getCurrentUser();
112
+ long totalReports = reportRepository.countByEmployee(user);
113
+ long acceptedReports = reportRepository.countByEmployeeAndStatus(user, ReportStatus.ACCEPTED);
114
+ long rejectedReports = reportRepository.countByEmployeeAndStatus(user, ReportStatus.REJECTED);
115
+ long totalDays = attendanceRecordRepository.count();
116
+ long attendedDays = attendanceRecordRepository.countByCheckInTimeNotNullAndCheckOutTimeNotNull();
117
+ String attendenceRate = DashboardCalculator.showResultStr(attendedDays, totalDays);
118
+ Page<AttendanceResponse> attendanceHistory = attendanceRecordRepository
119
+ .findByUser(user, PageRequest.of(0, 10))
120
+ .map(attendanceResponseMapper::fromEntity);
121
+ return dashboardResponseMapper.toEmployeeDashboardResponse(
122
+ totalReports,
123
+ acceptedReports,
124
+ rejectedReports,
125
+ attendenceRate,
126
+ attendanceHistory);
127
+ }
128
 
129
+ private User getCurrentUser() {
130
+ String username = SecurityUtil.getCurrentUserName();
131
+ if (username == null) {
132
+ throw new IllegalArgumentException("Không tìm thấy người dùng");
133
+ }
134
+ return userRepository.findByUsername(username)
135
+ .orElseThrow(() -> new IllegalArgumentException("Không tìm thấy người dùng"));
136
+ }
 
 
 
 
 
 
 
137
 
138
+ private String roleLabel(Role role) {
139
+ String roleName = role.name().toLowerCase(Locale.ROOT);
140
+ return roleName.substring(0, 1).toUpperCase(Locale.ROOT) + roleName.substring(1);
 
141
  }
 
 
 
142
  }
src/main/java/com/attendenceSystem/module/faceid/api/FaceIdApiController.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.faceid.api;
2
 
3
- import java.io.IOException;
4
  import java.nio.file.Path;
5
  import java.nio.file.Paths;
6
  import java.util.Base64;
@@ -23,6 +22,7 @@ import com.attendenceSystem.module.faceid.entity.FaceSample;
23
  import com.attendenceSystem.module.faceid.repository.FaceProfileRepository;
24
  import com.attendenceSystem.module.faceid.repository.FaceSampleRepository;
25
  import com.attendenceSystem.module.faceid.service.FaceIdAttendanceService;
 
26
  import com.attendenceSystem.module.storage.provider.StorageProvider;
27
  import com.attendenceSystem.module.user.entity.User;
28
  import com.attendenceSystem.module.user.repository.UserRepository;
@@ -217,7 +217,7 @@ public class FaceIdApiController {
217
  if (path != null) {
218
  storageProvider.delete(path);
219
  }
220
- } catch (IOException e) {
221
  log.warn("Không thể xóa file: {}", url);
222
  }
223
  }
 
1
  package com.attendenceSystem.module.faceid.api;
2
 
 
3
  import java.nio.file.Path;
4
  import java.nio.file.Paths;
5
  import java.util.Base64;
 
22
  import com.attendenceSystem.module.faceid.repository.FaceProfileRepository;
23
  import com.attendenceSystem.module.faceid.repository.FaceSampleRepository;
24
  import com.attendenceSystem.module.faceid.service.FaceIdAttendanceService;
25
+ import com.attendenceSystem.module.storage.exception.FileStorageException;
26
  import com.attendenceSystem.module.storage.provider.StorageProvider;
27
  import com.attendenceSystem.module.user.entity.User;
28
  import com.attendenceSystem.module.user.repository.UserRepository;
 
217
  if (path != null) {
218
  storageProvider.delete(path);
219
  }
220
+ } catch (FileStorageException e) {
221
  log.warn("Không thể xóa file: {}", url);
222
  }
223
  }
src/main/java/com/attendenceSystem/module/faceid/entity/FaceProfile.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.faceid.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import org.hibernate.annotations.CreationTimestamp;
 
1
  package com.attendenceSystem.module.faceid.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import org.hibernate.annotations.CreationTimestamp;
src/main/java/com/attendenceSystem/module/faceid/entity/FaceSample.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.faceid.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import org.hibernate.annotations.CreationTimestamp;
 
1
  package com.attendenceSystem.module.faceid.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import org.hibernate.annotations.CreationTimestamp;
src/main/java/com/attendenceSystem/module/log/entity/AuditLog.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.log.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import org.hibernate.annotations.CreationTimestamp;
 
1
  package com.attendenceSystem.module.log.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import org.hibernate.annotations.CreationTimestamp;
src/main/java/com/attendenceSystem/module/otp/api/OtpApiController.java CHANGED
@@ -10,7 +10,7 @@ import com.attendenceSystem.constant.Routes;
10
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
11
  import com.attendenceSystem.module.otp.dto.request.VerifyOtpRequest;
12
  import com.attendenceSystem.module.otp.dto.response.OtpResponse;
13
- import com.attendenceSystem.module.otp.service.OptService;
14
 
15
  import jakarta.validation.Valid;
16
  import lombok.RequiredArgsConstructor;
@@ -20,7 +20,7 @@ import lombok.RequiredArgsConstructor;
20
  @RequiredArgsConstructor
21
  public class OtpApiController {
22
 
23
- private final OptService otpService;
24
 
25
  @PostMapping(Routes.Otp.SEND)
26
  public ResponseEntity<OtpResponse> sendOtp(@Valid @RequestBody SendOtpRequest request) {
 
10
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
11
  import com.attendenceSystem.module.otp.dto.request.VerifyOtpRequest;
12
  import com.attendenceSystem.module.otp.dto.response.OtpResponse;
13
+ import com.attendenceSystem.module.otp.service.OtpService;
14
 
15
  import jakarta.validation.Valid;
16
  import lombok.RequiredArgsConstructor;
 
20
  @RequiredArgsConstructor
21
  public class OtpApiController {
22
 
23
+ private final OtpService otpService;
24
 
25
  @PostMapping(Routes.Otp.SEND)
26
  public ResponseEntity<OtpResponse> sendOtp(@Valid @RequestBody SendOtpRequest request) {
src/main/java/com/attendenceSystem/module/otp/entity/Otp.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.otp.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
 
1
  package com.attendenceSystem.module.otp.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
src/main/java/com/attendenceSystem/module/otp/mapper/request/SendOtpRequestMapper.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.otp.mapper.request;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
 
1
  package com.attendenceSystem.module.otp.mapper.request;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
src/main/java/com/attendenceSystem/module/otp/service/{OptService.java → OtpService.java} RENAMED
@@ -5,7 +5,7 @@ import com.attendenceSystem.module.otp.dto.request.VerifyOtpRequest;
5
  import com.attendenceSystem.module.otp.dto.response.OtpResponse;
6
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
7
 
8
- public interface OptService {
9
  OtpResponse send(SendOtpRequest request);
10
  OtpResponse verify(VerifyOtpRequest request);
11
  void invalidate(String destination, OtpPurpose purpose);
 
5
  import com.attendenceSystem.module.otp.dto.response.OtpResponse;
6
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
7
 
8
+ public interface OtpService {
9
  OtpResponse send(SendOtpRequest request);
10
  OtpResponse verify(VerifyOtpRequest request);
11
  void invalidate(String destination, OtpPurpose purpose);
src/main/java/com/attendenceSystem/module/otp/service/impl/OtpServiceImpl.java CHANGED
@@ -16,14 +16,14 @@ import com.attendenceSystem.module.otp.exception.OtpNotFoundException;
16
  import com.attendenceSystem.module.otp.mapper.request.SendOtpRequestMapper;
17
  import com.attendenceSystem.module.otp.mapper.response.OtpResponseMapper;
18
  import com.attendenceSystem.module.otp.repository.OtpRepository;
19
- import com.attendenceSystem.module.otp.service.OptService;
20
  import com.attendenceSystem.module.otp.service.OtpSender;
21
 
22
  import lombok.RequiredArgsConstructor;
23
 
24
  @Service
25
  @RequiredArgsConstructor
26
- public class OtpServiceImpl implements OptService {
27
  private final OtpRepository otpRepository;
28
  private final OtpSender otpSender;
29
 
 
16
  import com.attendenceSystem.module.otp.mapper.request.SendOtpRequestMapper;
17
  import com.attendenceSystem.module.otp.mapper.response.OtpResponseMapper;
18
  import com.attendenceSystem.module.otp.repository.OtpRepository;
19
+ import com.attendenceSystem.module.otp.service.OtpService;
20
  import com.attendenceSystem.module.otp.service.OtpSender;
21
 
22
  import lombok.RequiredArgsConstructor;
23
 
24
  @Service
25
  @RequiredArgsConstructor
26
+ public class OtpServiceImpl implements OtpService {
27
  private final OtpRepository otpRepository;
28
  private final OtpSender otpSender;
29
 
src/main/java/com/attendenceSystem/module/report/entity/Report.java CHANGED
@@ -1,8 +1,9 @@
1
  package com.attendenceSystem.module.report.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
 
 
6
  import com.attendenceSystem.module.report.entity.enums.ReportStatus;
7
  import com.attendenceSystem.module.user.entity.User;
8
 
@@ -59,6 +60,7 @@ public class Report {
59
  @Column(name = "reject_reason", length = 1000)
60
  private String rejectReason;
61
 
 
62
  @Column(name = "created_at", nullable = false, updatable = false)
63
  private LocalDateTime createdAt;
64
 
 
1
  package com.attendenceSystem.module.report.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
+ import org.hibernate.annotations.CreationTimestamp;
6
+
7
  import com.attendenceSystem.module.report.entity.enums.ReportStatus;
8
  import com.attendenceSystem.module.user.entity.User;
9
 
 
60
  @Column(name = "reject_reason", length = 1000)
61
  private String rejectReason;
62
 
63
+ @CreationTimestamp
64
  @Column(name = "created_at", nullable = false, updatable = false)
65
  private LocalDateTime createdAt;
66
 
src/main/java/com/attendenceSystem/module/report/service/impl/ReportServiceImpl.java CHANGED
@@ -1,15 +1,8 @@
1
  package com.attendenceSystem.module.report.service.impl;
2
 
3
- import java.io.File;
4
  import java.io.IOException;
5
- import java.nio.file.Files;
6
- import java.nio.file.Path;
7
- import java.nio.file.Paths;
8
- import java.time.Instant;
9
- import java.time.LocalDateTime;
10
  import java.util.ArrayList;
11
  import java.util.List;
12
- import java.util.UUID;
13
 
14
  import org.springframework.data.domain.Page;
15
  import org.springframework.data.domain.Pageable;
@@ -28,6 +21,7 @@ import com.attendenceSystem.module.report.mapper.response.ReportResponseMapper;
28
  import com.attendenceSystem.module.report.repository.ReportRepository;
29
  import com.attendenceSystem.module.report.repository.ReportShareRepository;
30
  import com.attendenceSystem.module.report.service.ReportService;
 
31
  import com.attendenceSystem.module.user.entity.User;
32
  import com.attendenceSystem.module.user.repository.UserRepository;
33
  import com.attendenceSystem.util.SecurityUtil;
@@ -44,6 +38,7 @@ public class ReportServiceImpl implements ReportService {
44
  private final ReportRepository reportRepository;
45
  private final ReportShareRepository reportShareRepository;
46
  private final UserRepository userRepository;
 
47
 
48
  @Value("${app.storage.upload-dir:uploads}")
49
  private String storageBaseDir;
@@ -54,15 +49,18 @@ public class ReportServiceImpl implements ReportService {
54
  User employee = findCurrentUser();
55
 
56
  Report report = CreateReportRequestMapper.toEntity(request, employee);
57
- report.setCreatedAt(LocalDateTime.now());
58
 
59
  // Xử lý upload files
60
  if (request.getFiles() != null && request.getFiles().length > 0) {
61
  List<String> filePaths = new ArrayList<>();
62
  for (MultipartFile file : request.getFiles()) {
63
  if (!file.isEmpty()) {
64
- String filePath = saveFile(file);
65
- filePaths.add(filePath);
 
 
 
 
66
  }
67
  }
68
  if (!filePaths.isEmpty()) {
@@ -90,32 +88,6 @@ public class ReportServiceImpl implements ReportService {
90
  return ReportResponseMapper.fromEntity(savedReport);
91
  }
92
 
93
- private String saveFile(MultipartFile file) {
94
- try {
95
- // Tạo thư mục nếu chưa tồn tại
96
- String reportUploadDir = storageBaseDir + "/reports";
97
- Path uploadPath = Paths.get(reportUploadDir);
98
- if (!Files.exists(uploadPath)) {
99
- Files.createDirectories(uploadPath);
100
- }
101
-
102
- // Tạo tên file unique
103
- String originalFilename = file.getOriginalFilename();
104
- String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
105
- String uniqueFilename = UUID.randomUUID().toString() + extension;
106
-
107
- // Lưu file
108
- Path filePath = uploadPath.resolve(uniqueFilename);
109
- file.transferTo(filePath.toFile());
110
-
111
- // Trả về relative path
112
- return reportUploadDir + "/" + uniqueFilename;
113
- } catch (IOException e) {
114
- log.error("Failed to save file", e);
115
- throw new RuntimeException("Không thể lưu file: " + e.getMessage());
116
- }
117
- }
118
-
119
  @Override
120
  public Page<ReportResponse> getAllReports(final Pageable pageable) {
121
  return reportRepository.findAllByOrderByCreatedAtDesc(pageable)
@@ -152,4 +124,6 @@ public class ReportServiceImpl implements ReportService {
152
  .orElseThrow(() -> new IllegalArgumentException(
153
  "Không tìm thấy người dùng với tên đăng nhập: " + currentUsername));
154
  }
 
 
155
  }
 
1
  package com.attendenceSystem.module.report.service.impl;
2
 
 
3
  import java.io.IOException;
 
 
 
 
 
4
  import java.util.ArrayList;
5
  import java.util.List;
 
6
 
7
  import org.springframework.data.domain.Page;
8
  import org.springframework.data.domain.Pageable;
 
21
  import com.attendenceSystem.module.report.repository.ReportRepository;
22
  import com.attendenceSystem.module.report.repository.ReportShareRepository;
23
  import com.attendenceSystem.module.report.service.ReportService;
24
+ import com.attendenceSystem.module.storage.service.FileStorageService;
25
  import com.attendenceSystem.module.user.entity.User;
26
  import com.attendenceSystem.module.user.repository.UserRepository;
27
  import com.attendenceSystem.util.SecurityUtil;
 
38
  private final ReportRepository reportRepository;
39
  private final ReportShareRepository reportShareRepository;
40
  private final UserRepository userRepository;
41
+ private final FileStorageService fileStorageService;
42
 
43
  @Value("${app.storage.upload-dir:uploads}")
44
  private String storageBaseDir;
 
49
  User employee = findCurrentUser();
50
 
51
  Report report = CreateReportRequestMapper.toEntity(request, employee);
 
52
 
53
  // Xử lý upload files
54
  if (request.getFiles() != null && request.getFiles().length > 0) {
55
  List<String> filePaths = new ArrayList<>();
56
  for (MultipartFile file : request.getFiles()) {
57
  if (!file.isEmpty()) {
58
+ try {
59
+ String filePath = fileStorageService.saveFile(file, "reports");
60
+ filePaths.add(filePath);
61
+ } catch (IOException e) {
62
+ throw new RuntimeException("Không thể lưu file đính kèm: " + e.getMessage(), e);
63
+ }
64
  }
65
  }
66
  if (!filePaths.isEmpty()) {
 
88
  return ReportResponseMapper.fromEntity(savedReport);
89
  }
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  @Override
92
  public Page<ReportResponse> getAllReports(final Pageable pageable) {
93
  return reportRepository.findAllByOrderByCreatedAtDesc(pageable)
 
124
  .orElseThrow(() -> new IllegalArgumentException(
125
  "Không tìm thấy người dùng với tên đăng nhập: " + currentUsername));
126
  }
127
+
128
+
129
  }
src/main/java/com/attendenceSystem/module/storage/exception/FileStorageException.java ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.attendenceSystem.module.storage.exception;
2
+
3
+ public class FileStorageException extends RuntimeException{
4
+ public FileStorageException(String message){
5
+ super(message);
6
+ }
7
+
8
+ public FileStorageException(String message, Throwable cause){
9
+ super(message, cause);
10
+ }
11
+ }
src/main/java/com/attendenceSystem/module/storage/provider/LocalStorageProvider.java CHANGED
@@ -13,6 +13,8 @@ import org.springframework.core.io.Resource;
13
  import org.springframework.stereotype.Component;
14
  import org.springframework.web.multipart.MultipartFile;
15
 
 
 
16
  @Component
17
  public class LocalStorageProvider implements StorageProvider {
18
 
@@ -29,21 +31,6 @@ public class LocalStorageProvider implements StorageProvider {
29
  }
30
  }
31
 
32
- /**
33
- * Chuẩn hóa đường dẫn relative: loại bỏ dấu "/" ở đầu để tránh
34
- * rootDir.resolve() coi là đường dẫn tuyệt đối.
35
- */
36
- private String normalizeRelativePath(String path) {
37
- if (path == null)
38
- return null;
39
- String normalized = path;
40
- // Loại bỏ dấu "/" hoặc "\" ở đầu để tránh path traversal false positive
41
- while (normalized.startsWith("/") || normalized.startsWith("\\")) {
42
- normalized = normalized.substring(1);
43
- }
44
- return normalized;
45
- }
46
-
47
  @Override
48
  public void save(Path targetPath, MultipartFile file) throws IOException {
49
  // Chuẩn hóa path để tránh dấu "/" ở đầu gây lỗi path traversal
@@ -80,7 +67,7 @@ public class LocalStorageProvider implements StorageProvider {
80
  }
81
 
82
  @Override
83
- public void delete(String path) throws IOException {
84
  String normalizedPath = normalizeRelativePath(path);
85
  Path fullPath = rootDir.resolve(normalizedPath).normalize();
86
 
@@ -89,7 +76,11 @@ public class LocalStorageProvider implements StorageProvider {
89
  throw new SecurityException("Path traversal không hợp lệ: " + path);
90
  }
91
 
92
- Files.deleteIfExists(fullPath);
 
 
 
 
93
  }
94
 
95
  @Override
@@ -124,4 +115,19 @@ public class LocalStorageProvider implements StorageProvider {
124
 
125
  Files.write(fullPath, data);
126
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  }
 
13
  import org.springframework.stereotype.Component;
14
  import org.springframework.web.multipart.MultipartFile;
15
 
16
+ import com.attendenceSystem.module.storage.exception.FileStorageException;
17
+
18
  @Component
19
  public class LocalStorageProvider implements StorageProvider {
20
 
 
31
  }
32
  }
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  @Override
35
  public void save(Path targetPath, MultipartFile file) throws IOException {
36
  // Chuẩn hóa path để tránh dấu "/" ở đầu gây lỗi path traversal
 
67
  }
68
 
69
  @Override
70
+ public void delete(String path) {
71
  String normalizedPath = normalizeRelativePath(path);
72
  Path fullPath = rootDir.resolve(normalizedPath).normalize();
73
 
 
76
  throw new SecurityException("Path traversal không hợp lệ: " + path);
77
  }
78
 
79
+ try {
80
+ Files.deleteIfExists(resolvePath(path));
81
+ } catch (IOException e) {
82
+ throw new FileStorageException("Không thể xóa file", e);
83
+ }
84
  }
85
 
86
  @Override
 
115
 
116
  Files.write(fullPath, data);
117
  }
118
+
119
+ /**
120
+ * Chuẩn hóa đường dẫn relative: loại bỏ dấu "/" ở đầu để tránh
121
+ * rootDir.resolve() coi là đường dẫn tuyệt đối.
122
+ */
123
+ private String normalizeRelativePath(String path) {
124
+ if (path == null)
125
+ return null;
126
+ String normalized = path;
127
+ // Loại bỏ dấu "/" hoặc "\" ở đầu để tránh path traversal false positive
128
+ while (normalized.startsWith("/") || normalized.startsWith("\\")) {
129
+ normalized = normalized.substring(1);
130
+ }
131
+ return normalized;
132
+ }
133
  }
src/main/java/com/attendenceSystem/module/storage/provider/StorageProvider.java CHANGED
@@ -32,7 +32,7 @@ public interface StorageProvider {
32
  * @param path đường dẫn file (relative)
33
  * @throws IOException nếu lỗi I/O
34
  */
35
- void delete(String path) throws IOException;
36
 
37
  /**
38
  * Tạo đường dẫn public để truy cập file (URL cho web)
 
32
  * @param path đường dẫn file (relative)
33
  * @throws IOException nếu lỗi I/O
34
  */
35
+ void delete(String path);
36
 
37
  /**
38
  * Tạo đường dẫn public để truy cập file (URL cho web)
src/main/java/com/attendenceSystem/module/storage/service/impl/FileStorageServiceImpl.java CHANGED
@@ -14,6 +14,7 @@ import org.springframework.util.StringUtils;
14
  import org.springframework.web.multipart.MultipartFile;
15
 
16
  import com.attendenceSystem.constant.FileConstants;
 
17
  import com.attendenceSystem.module.storage.provider.StorageProvider;
18
  import com.attendenceSystem.module.storage.service.FileStorageService;
19
 
@@ -29,7 +30,7 @@ public class FileStorageServiceImpl implements FileStorageService {
29
  @Override
30
  public String saveFile(
31
  final MultipartFile file,
32
- final String directory) throws IOException {
33
 
34
  if (file == null || file.isEmpty()) {
35
  throw new IllegalArgumentException(
@@ -48,23 +49,27 @@ public class FileStorageServiceImpl implements FileStorageService {
48
  validateDirectory(directory);
49
 
50
  // Tính SHA-256 hash từ nội dung file
51
- String fileHash;
52
- try {
53
- fileHash = sha256Hex(file);
54
- } catch (NoSuchAlgorithmException e) {
55
- throw new IOException("Lỗi khi tính hash file", e);
56
- }
57
 
58
  String fileName = fileHash + "." + extension;
59
  String relativePath = directory + "/" + fileName;
60
  Path targetPath = Paths.get(directory, fileName);
61
 
62
  // Lưu file qua StorageProvider
63
- storageProvider.save(targetPath, file);
 
 
 
 
64
 
65
  // Detect và kiểm tra MIME type từ file đã lưu
66
  Path savedPath = storageProvider.resolvePath(relativePath);
67
- String detectedMime = Files.probeContentType(savedPath);
 
 
 
 
 
68
  String expectedMime = FileConstants.ALLOWED_EXTENSION_MIME.get(extension.toLowerCase());
69
  if (detectedMime == null || expectedMime == null || !expectedMime.equals(detectedMime)) {
70
  // Xóa file nếu MIME type không khớp
@@ -92,21 +97,28 @@ public class FileStorageServiceImpl implements FileStorageService {
92
  storageProvider.delete(path);
93
  }
94
 
95
- private String sha256Hex(final MultipartFile file) throws IOException, NoSuchAlgorithmException {
96
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
97
- byte[] buffer = new byte[8192];
98
- int bytesRead;
99
- try (InputStream is = file.getInputStream()) {
100
- while ((bytesRead = is.read(buffer)) != -1) {
101
- digest.update(buffer, 0, bytesRead);
 
 
102
  }
 
 
 
 
 
 
 
 
 
 
 
103
  }
104
- byte[] hashBytes = digest.digest();
105
- StringBuilder hexString = new StringBuilder();
106
- for (byte b : hashBytes) {
107
- hexString.append(String.format("%02x", b));
108
- }
109
- return hexString.toString();
110
  }
111
 
112
  private void validateDirectory(final String directory) {
 
14
  import org.springframework.web.multipart.MultipartFile;
15
 
16
  import com.attendenceSystem.constant.FileConstants;
17
+ import com.attendenceSystem.module.storage.exception.FileStorageException;
18
  import com.attendenceSystem.module.storage.provider.StorageProvider;
19
  import com.attendenceSystem.module.storage.service.FileStorageService;
20
 
 
30
  @Override
31
  public String saveFile(
32
  final MultipartFile file,
33
+ final String directory) {
34
 
35
  if (file == null || file.isEmpty()) {
36
  throw new IllegalArgumentException(
 
49
  validateDirectory(directory);
50
 
51
  // Tính SHA-256 hash từ nội dung file
52
+ String fileHash = sha256Hex(file);
 
 
 
 
 
53
 
54
  String fileName = fileHash + "." + extension;
55
  String relativePath = directory + "/" + fileName;
56
  Path targetPath = Paths.get(directory, fileName);
57
 
58
  // Lưu file qua StorageProvider
59
+ try {
60
+ storageProvider.save(targetPath, file);
61
+ } catch (IOException e) {
62
+ throw new FileStorageException("Không thể lưu file", e);
63
+ }
64
 
65
  // Detect và kiểm tra MIME type từ file đã lưu
66
  Path savedPath = storageProvider.resolvePath(relativePath);
67
+ String detectedMime;
68
+ try {
69
+ detectedMime = Files.probeContentType(savedPath);
70
+ } catch (IOException e) {
71
+ throw new FileStorageException("Không thể xác định MIME type", e);
72
+ }
73
  String expectedMime = FileConstants.ALLOWED_EXTENSION_MIME.get(extension.toLowerCase());
74
  if (detectedMime == null || expectedMime == null || !expectedMime.equals(detectedMime)) {
75
  // Xóa file nếu MIME type không khớp
 
97
  storageProvider.delete(path);
98
  }
99
 
100
+ private String sha256Hex(final MultipartFile file) {
101
+ try {
102
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
103
+ byte[] buffer = new byte[8192];
104
+ int bytesRead;
105
+ try (InputStream is = file.getInputStream()) {
106
+ while ((bytesRead = is.read(buffer)) != -1) {
107
+ digest.update(buffer, 0, bytesRead);
108
+ }
109
  }
110
+
111
+ byte[] hashBytes = digest.digest();
112
+ StringBuilder hexString = new StringBuilder();
113
+ for (byte b : hashBytes) {
114
+ hexString.append(String.format("%02x", b));
115
+ }
116
+ return hexString.toString();
117
+ } catch (IOException e) {
118
+ throw new FileStorageException("Không thể đọc nội dung file", e);
119
+ } catch (NoSuchAlgorithmException e) {
120
+ throw new IllegalStateException("SHA-256 không được hỗ trợ", e);
121
  }
 
 
 
 
 
 
122
  }
123
 
124
  private void validateDirectory(final String directory) {
src/main/java/com/attendenceSystem/module/user/api/AdminAccountApiController.java CHANGED
@@ -7,7 +7,6 @@ import org.springframework.http.ResponseEntity;
7
  import org.springframework.web.bind.annotation.PatchMapping;
8
  import org.springframework.web.bind.annotation.PathVariable;
9
  import org.springframework.web.bind.annotation.RequestMapping;
10
- import org.springframework.web.bind.annotation.ResponseBody;
11
  import org.springframework.web.bind.annotation.RestController;
12
 
13
  import com.attendenceSystem.constant.Routes;
 
7
  import org.springframework.web.bind.annotation.PatchMapping;
8
  import org.springframework.web.bind.annotation.PathVariable;
9
  import org.springframework.web.bind.annotation.RequestMapping;
 
10
  import org.springframework.web.bind.annotation.RestController;
11
 
12
  import com.attendenceSystem.constant.Routes;
src/main/java/com/attendenceSystem/module/user/api/UserApiController.java CHANGED
@@ -1,7 +1,6 @@
1
  package com.attendenceSystem.module.user.api;
2
 
3
  import org.springframework.http.ResponseEntity;
4
- import org.springframework.web.bind.annotation.GetMapping;
5
  import org.springframework.web.bind.annotation.PatchMapping;
6
  import org.springframework.web.bind.annotation.PutMapping;
7
  import org.springframework.web.bind.annotation.RequestBody;
@@ -13,7 +12,6 @@ import com.attendenceSystem.module.user.dto.request.ChangePasswordRequest;
13
  import com.attendenceSystem.module.user.dto.request.UpdatePasswordWithOtpRequest;
14
  import com.attendenceSystem.module.user.dto.request.UpdateUserInformationRequest;
15
  import com.attendenceSystem.module.user.dto.response.UserInformationResponse;
16
- import com.attendenceSystem.module.user.dto.response.UserResponse;
17
  import com.attendenceSystem.module.user.service.UserService;
18
 
19
  import jakarta.validation.Valid;
 
1
  package com.attendenceSystem.module.user.api;
2
 
3
  import org.springframework.http.ResponseEntity;
 
4
  import org.springframework.web.bind.annotation.PatchMapping;
5
  import org.springframework.web.bind.annotation.PutMapping;
6
  import org.springframework.web.bind.annotation.RequestBody;
 
12
  import com.attendenceSystem.module.user.dto.request.UpdatePasswordWithOtpRequest;
13
  import com.attendenceSystem.module.user.dto.request.UpdateUserInformationRequest;
14
  import com.attendenceSystem.module.user.dto.response.UserInformationResponse;
 
15
  import com.attendenceSystem.module.user.service.UserService;
16
 
17
  import jakarta.validation.Valid;
src/main/java/com/attendenceSystem/module/user/controller/AuthController.java CHANGED
@@ -1,10 +1,8 @@
1
  package com.attendenceSystem.module.user.controller;
2
 
3
- import org.springframework.security.core.Authentication;
4
  import org.springframework.security.authentication.DisabledException;
5
  import org.springframework.security.core.AuthenticationException;
6
  import org.springframework.security.core.context.SecurityContextHolder;
7
- import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
8
  import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
9
  import org.springframework.stereotype.Controller;
10
  import org.springframework.ui.Model;
 
1
  package com.attendenceSystem.module.user.controller;
2
 
 
3
  import org.springframework.security.authentication.DisabledException;
4
  import org.springframework.security.core.AuthenticationException;
5
  import org.springframework.security.core.context.SecurityContextHolder;
 
6
  import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
7
  import org.springframework.stereotype.Controller;
8
  import org.springframework.ui.Model;
src/main/java/com/attendenceSystem/module/user/entity/User.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.user.entity;
2
 
3
- import java.time.Instant;
4
  import java.time.LocalDateTime;
5
 
6
  import org.hibernate.annotations.CreationTimestamp;
 
1
  package com.attendenceSystem.module.user.entity;
2
 
 
3
  import java.time.LocalDateTime;
4
 
5
  import org.hibernate.annotations.CreationTimestamp;
src/main/java/com/attendenceSystem/module/user/mapper/response/UserResponseMapper.java CHANGED
@@ -1,6 +1,5 @@
1
  package com.attendenceSystem.module.user.mapper.response;
2
 
3
- import java.time.ZoneId;
4
 
5
  import org.springframework.stereotype.Component;
6
 
@@ -13,8 +12,6 @@ import lombok.RequiredArgsConstructor;
13
  @RequiredArgsConstructor
14
  public class UserResponseMapper {
15
 
16
- private final ZoneId applicationZoneId;
17
-
18
  public UserResponse fromEntity(User user) {
19
  return UserResponse.builder()
20
  .id(user.getId())
 
1
  package com.attendenceSystem.module.user.mapper.response;
2
 
 
3
 
4
  import org.springframework.stereotype.Component;
5
 
 
12
  @RequiredArgsConstructor
13
  public class UserResponseMapper {
14
 
 
 
15
  public UserResponse fromEntity(User user) {
16
  return UserResponse.builder()
17
  .id(user.getId())
src/main/java/com/attendenceSystem/module/user/service/impl/AuthServiceImpl.java CHANGED
@@ -20,7 +20,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
20
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
21
  import com.attendenceSystem.module.otp.dto.request.VerifyOtpRequest;
22
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
23
- import com.attendenceSystem.module.otp.service.OptService;
24
  import com.attendenceSystem.module.user.dto.request.LoginRequest;
25
  import com.attendenceSystem.module.user.dto.request.RegisterRequest;
26
  import com.attendenceSystem.module.user.dto.response.UserResponse;
@@ -28,7 +28,6 @@ import com.attendenceSystem.module.user.entity.User;
28
  import com.attendenceSystem.module.user.entity.enums.Status;
29
  import com.attendenceSystem.module.user.repository.UserRepository;
30
  import com.attendenceSystem.module.user.service.AuthService;
31
- import com.attendenceSystem.util.SecurityUtil;
32
 
33
  import jakarta.servlet.http.HttpServletRequest;
34
  import jakarta.servlet.http.HttpServletResponse;
@@ -41,7 +40,7 @@ public class AuthServiceImpl implements AuthService {
41
  private final UserRepository userRepository;
42
  private final AuthenticationManager authenticationManager;
43
  private final PasswordEncoder passwordEncoder;
44
- private final OptService otpService;
45
 
46
  @Transactional
47
  @Override
@@ -135,8 +134,4 @@ public class AuthServiceImpl implements AuthService {
135
  private boolean existsByKeyword(final String keyword) {
136
  return userRepository.existsByUsernameOrEmail(keyword, keyword);
137
  }
138
-
139
- private boolean isAuthenticated() {
140
- return SecurityUtil.isAuthenticated();
141
- }
142
  }
 
20
  import com.attendenceSystem.module.otp.dto.request.SendOtpRequest;
21
  import com.attendenceSystem.module.otp.dto.request.VerifyOtpRequest;
22
  import com.attendenceSystem.module.otp.entity.enums.OtpPurpose;
23
+ import com.attendenceSystem.module.otp.service.OtpService;
24
  import com.attendenceSystem.module.user.dto.request.LoginRequest;
25
  import com.attendenceSystem.module.user.dto.request.RegisterRequest;
26
  import com.attendenceSystem.module.user.dto.response.UserResponse;
 
28
  import com.attendenceSystem.module.user.entity.enums.Status;
29
  import com.attendenceSystem.module.user.repository.UserRepository;
30
  import com.attendenceSystem.module.user.service.AuthService;
 
31
 
32
  import jakarta.servlet.http.HttpServletRequest;
33
  import jakarta.servlet.http.HttpServletResponse;
 
40
  private final UserRepository userRepository;
41
  private final AuthenticationManager authenticationManager;
42
  private final PasswordEncoder passwordEncoder;
43
+ private final OtpService otpService;
44
 
45
  @Transactional
46
  @Override
 
134
  private boolean existsByKeyword(final String keyword) {
135
  return userRepository.existsByUsernameOrEmail(keyword, keyword);
136
  }
 
 
 
 
137
  }