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
191 changes: 191 additions & 0 deletions apps/api-e2e/src/api/scheduled-workday-account.e2e.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { randomUUID } from 'node:crypto';
import type { Prisma } from '@prisma/client';
import { loadScheduledWorkdaySummaries } from '../../../api/src/app/time-entries/scheduled-workday';
import {
createTestApp,
login,
seedEmployee,
type TestContext,
} from '../support/test-app';

describe('Scheduled team workday in the time account', () => {
let ctx: TestContext;

beforeAll(async () => {
ctx = await createTestApp();
});
afterAll(async () => {
await ctx.close();
});
beforeEach(async () => {
await ctx.reset();
jest.useFakeTimers({
doNotFake: ['nextTick', 'setImmediate', 'setInterval', 'setTimeout'],
});
jest.setSystemTime(new Date('2026-01-07T18:00:00Z'));
});
afterEach(() => {
jest.useRealTimers();
});

async function fixture(regularStart = '07:00', afterMinutes = 30) {
const employee = await seedEmployee(ctx.prisma, {
personalNo: 'WORKDAY',
firstName: 'Synthetic',
lastName: 'Workday',
email: 'scheduled-workday@test.local',
holidayCalendar: 'NONE',
});
const authorization = `Bearer ${await login(ctx.http, employee.email)}`;
await ctx.prisma.scheduledWorkdayPolicyVersion.create({
data: {
employeeId: employee.id,
effectiveOn: new Date('2026-01-01'),
rule: {
regularStart,
regularEnd: '16:00',
breakRules: [{ afterMinutes, breakMinutes: 30 }],
workingDays: 31,
holidayCalendar: 'NONE',
holidayDates: [],
},
},
});

const balance = async (): Promise<number> =>
(
await ctx.http
.get(`/api/accounts/${employee.id}`)
.set('Authorization', authorization)
.expect(200)
).body.overtimeMinutes;

const entry = (
clockIn: Date,
clockOut: Date | null,
overrides: Partial<Prisma.TimeEntryUncheckedCreateInput> = {},
) =>
ctx.prisma.timeEntry.create({
data: {
employeeId: employee.id,
clockIn,
clockOut,
approvalMode: 'Team',
status: clockOut ? 'Approved' : 'Open',
...overrides,
},
});

return { balance, entry };
}

const at = (day: number, hour: number, minute: number) =>
new Date(2026, 0, day, hour, minute);

it('uses one deduction across closed entries, with a split and later correction', async () => {
const { entry, balance } = await fixture();
const before = await balance();
await entry(at(5, 6, 55), at(5, 11, 0), { status: 'Pending' });
const afternoon = await entry(at(5, 11, 15), null);
expect(await balance()).toBe(before + 210);

await ctx.prisma.timeEntry.update({
where: { id: afternoon.id },
data: { clockOut: at(5, 16, 10), status: 'Approved' },
});
expect(await balance()).toBe(before + 505);

await ctx.prisma.timeEntry.update({
where: { id: afternoon.id },
data: { clockOut: at(5, 14, 0) },
});
await entry(at(5, 14, 0), at(5, 16, 10));
expect(await balance()).toBe(before + 505);

await ctx.prisma.timeEntry.update({
where: { id: afternoon.id },
data: { clockIn: at(5, 11, 30) },
});
expect(await balance()).toBe(before + 490);
});

it('keeps the existing calculation on both sides of a midnight booking', async () => {
const { entry, balance } = await fixture();
const before = await balance();
await entry(at(5, 6, 55), at(5, 8, 0));
await entry(at(5, 23, 50), at(6, 0, 20));
await entry(at(6, 6, 55), at(6, 8, 0));

expect(await balance()).toBe(before + 160);
});

it('preserves overnight handling when a capture was split exactly at midnight', async () => {
const { entry, balance } = await fixture();
const before = await balance();
const captureGroupId = randomUUID();
await entry(at(5, 6, 55), at(5, 8, 0));
await entry(at(5, 23, 50), at(6, 0, 0), { captureGroupId });
const afterMidnight = await entry(at(6, 0, 0), at(6, 0, 20), {
captureGroupId,
});
const nextMorning = await entry(at(6, 6, 55), at(6, 8, 0));

const visibleDay = await ctx.prisma.$transaction((tx) =>
loadScheduledWorkdaySummaries(tx, [afterMidnight, nextMorning]),
);
expect(visibleDay.size).toBe(0);
expect(await balance()).toBe(before + 160);
});

it('keeps the assessed terminal pause and existing calculation for a mixed day', async () => {
const { entry, balance } = await fixture();
const before = await balance();
const clockIn = at(5, 6, 55);
const clockOut = at(5, 11, 0);
const pauseStart = at(5, 9, 0).toISOString();
const pauseEnd = at(5, 9, 37).toISOString();
await entry(clockIn, clockOut, {
source: 'Terminal',
terminalCapture: {
rules: {
startTimes: ['07:00'],
earlyStartMinutes: 5,
fixedBreaks: [],
breakStartToleranceMinutes: 0,
breakEndToleranceMinutes: 0,
shortBreakMinutes: 0,
},
originalClockIn: clockIn.toISOString(),
originalClockOut: clockOut.toISOString(),
assessedClockIn: at(5, 7, 0).toISOString(),
startFinding: null,
pauses: [
{
originalStart: pauseStart,
originalEnd: pauseEnd,
correctedEnd: null,
assessedStart: pauseStart,
assessedEnd: pauseEnd,
kind: 'actual',
outsideTolerance: false,
},
],
},
});
await entry(at(5, 11, 15), at(5, 16, 10));

expect(await balance()).toBe(before + 498);
});

it('calculates the complete day before the existing UTC account selection', async () => {
const { entry, balance } = await fixture('00:00', 60);
const before = await balance();

// Under the suite's Europe/Berlin timezone the first recording ends
// before UTC year-start, but still carries this local day's deduction.
await entry(at(1, 0, 0), at(1, 0, 50));
await entry(at(1, 6, 0), at(1, 7, 30));

expect(await balance()).toBe(before + 90);
});
});
106 changes: 106 additions & 0 deletions apps/api-e2e/src/api/terminal-booking.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,112 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => {
return { id: plan.body.id as string, input };
}

it.each([
{ method: 'web', start: '04:55', end: '14:00', net: 510, late: 0 },
{ method: 'QR', start: '05:05', end: '14:05', net: 510, late: 5 },
{ method: 'PIN', start: '05:05', end: '14:00', net: 505, late: 0 },
])(
'keeps $method punches and reviews the original interval under a scheduled workday',
async ({ method, start, end, net, late }) => {
jest.useFakeTimers({
doNotFake: ['nextTick', 'setImmediate', 'setInterval', 'setTimeout'],
});
try {
jest.setSystemTime(new Date('2026-08-11T12:00:00Z'));
const f = await fixture();
const plan = await ctx.http
.post('/api/work-schedules')
.set('Authorization', `Bearer ${f.hrToken}`)
.send({
name: 'Scheduled workday',
frameStart: '07:00',
frameEnd: '16:00',
coreTimes: [],
scheduledWorkday: {
regularStart: '07:00',
regularEnd: '16:00',
breakRules: [{ afterMinutes: 30, breakMinutes: 30 }],
},
})
.expect(201);
await ctx.http
.post(`/api/work-schedules/${plan.body.id}/assign`)
.set('Authorization', `Bearer ${f.hrToken}`)
.send({ employeeId: f.employee.id })
.expect(201);

const punch = async (action: 'clock-in' | 'clock-out') => {
if (method === 'PIN') {
await book(f.deviceToken, (await grant(f)).grant, action).expect(
201,
);
return;
}
const employeeToken = await login(ctx.http, f.employee.email);
if (method === 'QR') {
const kiosk = await ctx.http
.get('/api/terminals/kiosk')
.set('Authorization', `Bearer ${f.deviceToken}`)
.expect(200);
await ctx.http
.post('/api/terminals/scan')
.set('Authorization', `Bearer ${employeeToken}`)
.send({ qrPayload: kiosk.body.challenge.payload, action })
.expect(201);
return;
}
await ctx.http
.post(`/api/timeentries/${action}`)
.set('Authorization', `Bearer ${employeeToken}`)
.send({})
.expect(201);
};
const clockIn = new Date(`2026-08-12T${start}:00Z`);
const clockOut = new Date(`2026-08-12T${end}:00Z`);
jest.setSystemTime(clockIn);
await punch('clock-in');
jest.setSystemTime(new Date('2026-08-12T14:00:00Z'));
const timer = await ctx.prisma.timeEntry.findFirstOrThrow({
where: { employeeId: f.employee.id },
});
expect(timer).toMatchObject({ clockIn, clockOut: null });
jest.setSystemTime(clockOut);
await punch('clock-out');
const closed = await ctx.prisma.timeEntry.findUniqueOrThrow({
where: { id: timer.id },
});
expect(closed).toMatchObject({
clockIn,
clockOut,
status: method === 'PIN' ? 'Approved' : 'Pending',
terminalCapture: null,
});

const hrToken = await login(ctx.http, f.hr.email);
const report = await ctx.http
.get('/api/reports/working-times')
.query({
from: '2026-08-12',
to: '2026-08-12',
employeeId: f.employee.id,
})
.set('Authorization', `Bearer ${hrToken}`)
.expect(200);
expect(report.body.rows).toHaveLength(1);
expect(report.body.rows[0]).toMatchObject({
clockIn: clockIn.toISOString(),
clockOut: clockOut.toISOString(),
netMinutes: net,
breakMinutes: 30,
afterRegularEndMinutes: late,
status: closed.status,
});
} finally {
jest.useRealTimers();
}
},
);

it('records PIN and QR pause punches atomically and keeps the rules of the open shift', async () => {
const f = await fixture();
const secondTerminal = await terminal(f.hrToken);
Expand Down
Loading