Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions src/main/java/com/heftyb/dms/ScheduledTasks.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<TimeClockPunchSet> 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);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ public interface TimeClockPunchSetRepository extends CrudRepository<TimeClockPun
List<TimeClockPunchSet> findByEmployeeAndPayPeriod(Employee employee, PayPeriod period);

List<TimeClockPunchSet> findByEmployeeAndDate(Employee employee, LocalDate date);

List<TimeClockPunchSet> findByOutIsNull();
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,14 @@ public interface TimeClockService {

TimeClockPunchSet findCurrentTimeClockPunchSetByUser(User u);

List<TimeClockPunchSet> findOpenTimeClockPunchSets();

void clockIn(String username, TimePunchCode code);

void clockOut(String username, TimePunchCode code);

void closeTimeClockPunchSet(TimeClockPunchSet punchSet, TimePunchCode code);

List<JobTimePunchSet> findAllJobTimePunchSets();

JobTimePunchSet findJobTimePunchSetById(long id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.*;
Expand Down Expand Up @@ -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<TimeClockPunchSet> findCurrentUsersTimeClockPunchSets(User user) {
return timeClockPunchRepo.findByEmployee(user.getEmployee());
Expand Down Expand Up @@ -214,11 +203,8 @@ public TimeClockPunchSet findCurrentTimeClockPunchSetByUser(User user) {
.orElseThrow(() -> new UserNotFoundException(
String.format("Error: could not find user: %s", user.getId())
));
List<TimeClockPunchSet> punchSets = timeClockPunchRepo.findByEmployee(u.getEmployee())
.stream().filter(
ps -> isToday(Date.from(Instant.from(ps.getDate())))
)
.collect(Collectors.toList());
List<TimeClockPunchSet> punchSets = new ArrayList<>(
timeClockPunchRepo.findByEmployeeAndDate(u.getEmployee(), LocalDate.now()));
punchSets.sort(Comparator.comparing(TimeClockPunchSet::getInPunchTime).reversed());

if (!punchSets.isEmpty() && punchSets.get(0).getOut() == null) {
Expand All @@ -242,21 +228,31 @@ public void clockIn(String username, TimePunchCode code) {
employeeService.setEmployeeClockedIn(user.getEmployee().getId(), true);
}

@Override
public List<TimeClockPunchSet> 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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());
}
}
5 changes: 4 additions & 1 deletion src/test/resources/application-test.properties
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Loading