diff --git a/src/main/java/com/heftyb/dms/ScheduledTasks.java b/src/main/java/com/heftyb/dms/ScheduledTasks.java index 929df17..998c9a7 100644 --- a/src/main/java/com/heftyb/dms/ScheduledTasks.java +++ b/src/main/java/com/heftyb/dms/ScheduledTasks.java @@ -3,27 +3,34 @@ import com.heftyb.dms.timekeeping.TimeClockPunchSet; import com.heftyb.dms.timekeeping.TimePunchCode; import com.heftyb.dms.timekeeping.services.TimeClockService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.stream.Collectors; - @Component public class ScheduledTasks { + private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); + private final TimeClockService timeClockService; public ScheduledTasks(final TimeClockService timeClockService) { this.timeClockService = timeClockService; } + /** + * Closes every shift still open at midnight. Each shift is closed directly rather than looked up + * by date, since a shift open at 00:00 started the previous day. A failure on one shift is logged + * and does not stop the rest. + */ @Scheduled(cron = "0 0 0 * * *") public void clockAllUsersOut() { - List punchSets = timeClockService.findAllTimeClockPunchSets() - .stream().filter(ps -> ps.getOut() == null).collect(Collectors.toList()); - - for(TimeClockPunchSet ps : punchSets) { - timeClockService.clockOut(ps.getEmployee().getUser().getUsername(), TimePunchCode.SYSTEM); + for (TimeClockPunchSet shift : timeClockService.findOpenTimeClockPunchSets()) { + try { + timeClockService.closeTimeClockPunchSet(shift, TimePunchCode.SYSTEM); + } catch (RuntimeException e) { + log.error("Could not auto clock out time clock punch set {}", shift.getId(), e); + } } } } diff --git a/src/main/java/com/heftyb/dms/timekeeping/repositories/TimeClockPunchSetRepository.java b/src/main/java/com/heftyb/dms/timekeeping/repositories/TimeClockPunchSetRepository.java index ca6d3a4..f0c7015 100644 --- a/src/main/java/com/heftyb/dms/timekeeping/repositories/TimeClockPunchSetRepository.java +++ b/src/main/java/com/heftyb/dms/timekeeping/repositories/TimeClockPunchSetRepository.java @@ -15,4 +15,6 @@ public interface TimeClockPunchSetRepository extends CrudRepository findByEmployeeAndPayPeriod(Employee employee, PayPeriod period); List findByEmployeeAndDate(Employee employee, LocalDate date); + + List findByOutIsNull(); } diff --git a/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockService.java b/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockService.java index 2e5fca7..2a4954c 100644 --- a/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockService.java +++ b/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockService.java @@ -44,10 +44,14 @@ public interface TimeClockService { TimeClockPunchSet findCurrentTimeClockPunchSetByUser(User u); + List findOpenTimeClockPunchSets(); + void clockIn(String username, TimePunchCode code); void clockOut(String username, TimePunchCode code); + void closeTimeClockPunchSet(TimeClockPunchSet punchSet, TimePunchCode code); + List findAllJobTimePunchSets(); JobTimePunchSet findJobTimePunchSetById(long id); diff --git a/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImp.java b/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImp.java index 008e627..cd83984 100644 --- a/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImp.java +++ b/src/main/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImp.java @@ -20,7 +20,6 @@ import jakarta.transaction.Transactional; import org.springframework.stereotype.Service; -import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; @@ -176,16 +175,6 @@ public void deleteTimeClockPunchSet(long id) { timeClockPunchRepo.deleteById(id); } - public boolean isToday(Date date) { - Calendar t = Calendar.getInstance(); - Calendar d = Calendar.getInstance(); - d.setTime(date); - - return t.get(Calendar.DAY_OF_MONTH) == d.get(Calendar.DAY_OF_MONTH) && - t.get(Calendar.MONTH) == d.get(Calendar.MONTH) && - t.get(Calendar.YEAR) == d.get(Calendar.YEAR); - } - @Override public List findCurrentUsersTimeClockPunchSets(User user) { return timeClockPunchRepo.findByEmployee(user.getEmployee()); @@ -214,11 +203,8 @@ public TimeClockPunchSet findCurrentTimeClockPunchSetByUser(User user) { .orElseThrow(() -> new UserNotFoundException( String.format("Error: could not find user: %s", user.getId()) )); - List punchSets = timeClockPunchRepo.findByEmployee(u.getEmployee()) - .stream().filter( - ps -> isToday(Date.from(Instant.from(ps.getDate()))) - ) - .collect(Collectors.toList()); + List punchSets = new ArrayList<>( + timeClockPunchRepo.findByEmployeeAndDate(u.getEmployee(), LocalDate.now())); punchSets.sort(Comparator.comparing(TimeClockPunchSet::getInPunchTime).reversed()); if (!punchSets.isEmpty() && punchSets.get(0).getOut() == null) { @@ -242,21 +228,31 @@ public void clockIn(String username, TimePunchCode code) { employeeService.setEmployeeClockedIn(user.getEmployee().getId(), true); } + @Override + public List findOpenTimeClockPunchSets() { + return timeClockPunchRepo.findByOutIsNull(); + } + @Override public void clockOut(String username, TimePunchCode code) { User user = userService.findUserByUsername(username); - TimePunchOut punchOut = new TimePunchOut(user.getEmployee(), LocalDateTime.now(), code); - TimeClockPunchSet punchSet = findCurrentTimeClockPunchSetByUser(user); if (punchSet.getIn() == null || punchSet.getOut() != null) { - throw new TimeClockException(String.format("Error: Could not clock out, no matching TimeClockPunchSet was found!")); - } else { - punchOut = saveTimePunchOut(punchOut); - punchSet.setOut(punchOut); - saveTimeClockPunchSet(punchSet); - employeeService.setEmployeeClockedIn(user.getEmployee().getId(), false); + throw new TimeClockException("Error: Could not clock out, no matching TimeClockPunchSet was found!"); } + closeTimeClockPunchSet(punchSet, code); + } + + @Transactional + @Override + public void closeTimeClockPunchSet(TimeClockPunchSet punchSet, TimePunchCode code) { + Employee employee = punchSet.getEmployee(); + TimePunchOut punchOut = saveTimePunchOut(new TimePunchOut(employee, LocalDateTime.now(), code)); + + punchSet.setOut(punchOut); + saveTimeClockPunchSet(punchSet); + employeeService.setEmployeeClockedIn(employee.getId(), false); } @Override diff --git a/src/test/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImpTest.java b/src/test/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImpTest.java new file mode 100644 index 0000000..279d79d --- /dev/null +++ b/src/test/java/com/heftyb/dms/timekeeping/services/TimeClockServiceImpTest.java @@ -0,0 +1,132 @@ +package com.heftyb.dms.timekeeping.services; + +import com.heftyb.dms.ScheduledTasks; +import com.heftyb.dms.account.PayPeriod; +import com.heftyb.dms.account.repositories.PayPeriodRepository; +import com.heftyb.dms.crm.Employee; +import com.heftyb.dms.crm.repositories.EmployeeRepository; +import com.heftyb.dms.exceptions.TimeClockException; +import com.heftyb.dms.timekeeping.TimeClockPunchSet; +import com.heftyb.dms.timekeeping.TimePunchCode; +import com.heftyb.dms.timekeeping.TimePunchIn; +import com.heftyb.dms.timekeeping.repositories.TimeClockPunchSetRepository; +import com.heftyb.dms.timekeeping.repositories.TimePunchInRepository; +import com.heftyb.dms.users.User; +import com.heftyb.dms.users.repositories.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@SpringBootTest +@ActiveProfiles("test") +@Transactional +class TimeClockServiceImpTest { + + @Autowired + private TimeClockService timeClockService; + + @Autowired + private ScheduledTasks scheduledTasks; + + @Autowired + private TimeClockPunchSetRepository punchSetRepo; + + @Autowired + private TimePunchInRepository punchInRepo; + + @Autowired + private EmployeeRepository employeeRepo; + + @Autowired + private UserRepository userRepo; + + @Autowired + private PayPeriodRepository payPeriodRepo; + + private PayPeriod currentPeriod; + private Employee sam; + + @BeforeEach + void setUp() { + PayPeriod period = new PayPeriod(); + period.setStartDate(daysFromToday(-3)); + period.setEndDate(daysFromToday(10)); + currentPeriod = payPeriodRepo.save(period); + + sam = employee("sam"); + } + + @Test + void clockOutClosesTheOpenShift() { + timeClockService.clockIn("sam", TimePunchCode.IN); + + timeClockService.clockOut("sam", TimePunchCode.OUT); + + assertThat(punchSetRepo.findByEmployee(sam)) + .singleElement() + .satisfies(shift -> assertThat(shift.getOut().getCode()).isEqualTo(TimePunchCode.OUT)); + assertThat(sam.isClockedIn()).isFalse(); + } + + @Test + void clockOutWithoutAnOpenShiftIsRejected() { + assertThatThrownBy(() -> timeClockService.clockOut("sam", TimePunchCode.OUT)) + .isInstanceOf(TimeClockException.class); + } + + @Test + void midnightJobClosesShiftsThatStartedTheDayBefore() { + TimeClockPunchSet shift = openShift(sam, LocalDate.now().minusDays(1).atTime(22, 0), currentPeriod); + + scheduledTasks.clockAllUsersOut(); + + assertThat(punchSetRepo.findById(shift.getId())) + .get() + .satisfies(s -> assertThat(s.getOut().getCode()).isEqualTo(TimePunchCode.SYSTEM)); + } + + @Test + void midnightJobKeepsGoingWhenOneShiftCannotBeClosed() { + // A shift with no pay period cannot be saved again, so closing it fails + openShift(employee("broken"), LocalDate.now().minusDays(1).atTime(21, 0), null); + TimeClockPunchSet shift = openShift(sam, LocalDate.now().minusDays(1).atTime(22, 0), currentPeriod); + + scheduledTasks.clockAllUsersOut(); + + assertThat(punchSetRepo.findById(shift.getId())) + .get() + .satisfies(s -> assertThat(s.getOut()).isNotNull()); + } + + private TimeClockPunchSet openShift(Employee employee, LocalDateTime start, PayPeriod period) { + TimePunchIn in = punchInRepo.save(new TimePunchIn(employee, start, TimePunchCode.IN)); + return punchSetRepo.save(new TimeClockPunchSet(start.toLocalDate(), in, employee, period)); + } + + private Employee employee(String username) { + Employee e = new Employee(); + e.setFirstName(username); + e.setLastName("Tester"); + e.setPreferredName(username); + e = employeeRepo.save(e); + + User user = userRepo.save(new User(username, "unused", username + "@example.com", e)); + e.setUser(user); + return e; + } + + private static Date daysFromToday(int days) { + return Date.from(LocalDate.now().plusDays(days).atStartOfDay(ZoneId.systemDefault()).toInstant()); + } +} diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties index 3be8764..92d6f41 100644 --- a/src/test/resources/application-test.properties +++ b/src/test/resources/application-test.properties @@ -1,6 +1,9 @@ # In-memory H2 standing in for SQL Server so the test suite runs without a database server. # YEAR is reserved in H2 but used as a column name (appointments.year), hence NON_KEYWORDS. -spring.datasource.url=jdbc:h2:mem:dms;MODE=MSSQLServer;NON_KEYWORDS=YEAR;DB_CLOSE_DELAY=-1 +# No MODE=MSSQLServer: it lets only one NULL into a unique index, like SQL Server, but +# Hibernate's H2 dialect emits plain unique indexes where the SQL Server dialect emits +# filtered ones (WHERE col IS NOT NULL), so the mode rejects data SQL Server accepts. +spring.datasource.url=jdbc:h2:mem:dms;NON_KEYWORDS=YEAR;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop