From 7d225d5934d4be26efcd6f69626eb45d4232d80e Mon Sep 17 00:00:00 2001
From: Patrick Schiller
Date: Thu, 3 Dec 2026 23:59:53 +0100
Subject: [PATCH] feat: add scheduled workday accounting
Signed-off-by: Patrick Schiller
---
.../api/scheduled-workday-account.e2e.spec.ts | 191 ++++++++++++
.../src/api/terminal-booking.e2e.spec.ts | 106 +++++++
.../src/api/work-schedules.e2e.spec.ts | 237 ++++++++++++++
.../api/working-time-comparisons.e2e.spec.ts | 68 ++++
apps/api/openapi.json | 53 ++++
apps/api/src/app/accounts/accounts.service.ts | 13 +-
.../src/app/employees/employees.service.ts | 17 +-
apps/api/src/app/reports/reports.dto.ts | 14 +
apps/api/src/app/reports/reports.service.ts | 24 +-
.../app/terminals/terminal-auth.service.ts | 1 +
.../src/app/terminals/terminals.service.ts | 1 +
.../src/app/time-entries/scheduled-workday.ts | 263 ++++++++++++++++
.../app/time-entries/time-entries.service.ts | 1 +
.../scheduled-workday-policy.ts | 207 +++++++++++++
.../app/work-schedules/work-schedules.dto.ts | 41 +++
.../work-schedules/work-schedules.service.ts | 179 ++++++++---
apps/web/src/api/client.ts | 10 +
apps/web/src/api/generated.ts | 15 +
apps/web/src/app/i18n.tsx | 22 ++
apps/web/src/app/working-time-i18n.ts | 12 +
.../src/routes/AdminSchedulesPage.spec.tsx | 105 ++++++-
apps/web/src/routes/AdminSchedulesPage.tsx | 290 +++++++++++-------
.../src/routes/AdminWorkingTimesPage.spec.tsx | 105 +++++++
apps/web/src/routes/AdminWorkingTimesPage.tsx | 236 ++++++++++----
apps/web/src/routes/DashboardPage.spec.tsx | 17 +-
apps/web/src/routes/DashboardPage.tsx | 14 +-
docs/TEAM_MODE.md | 23 ++
libs/shared/src/lib/work-time/index.ts | 1 +
.../lib/work-time/scheduled-workday.spec.ts | 132 ++++++++
.../src/lib/work-time/scheduled-workday.ts | 72 +++++
.../shared/src/lib/work-time/terminal-time.ts | 14 +-
.../migration.sql | 16 +
prisma/schema.prisma | 15 +
33 files changed, 2290 insertions(+), 225 deletions(-)
create mode 100644 apps/api-e2e/src/api/scheduled-workday-account.e2e.spec.ts
create mode 100644 apps/api/src/app/time-entries/scheduled-workday.ts
create mode 100644 apps/api/src/app/work-schedules/scheduled-workday-policy.ts
create mode 100644 libs/shared/src/lib/work-time/scheduled-workday.spec.ts
create mode 100644 libs/shared/src/lib/work-time/scheduled-workday.ts
create mode 100644 prisma/migrations/20261203220000_scheduled_workday_accounting/migration.sql
diff --git a/apps/api-e2e/src/api/scheduled-workday-account.e2e.spec.ts b/apps/api-e2e/src/api/scheduled-workday-account.e2e.spec.ts
new file mode 100644
index 0000000..b5e993d
--- /dev/null
+++ b/apps/api-e2e/src/api/scheduled-workday-account.e2e.spec.ts
@@ -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 =>
+ (
+ await ctx.http
+ .get(`/api/accounts/${employee.id}`)
+ .set('Authorization', authorization)
+ .expect(200)
+ ).body.overtimeMinutes;
+
+ const entry = (
+ clockIn: Date,
+ clockOut: Date | null,
+ overrides: Partial = {},
+ ) =>
+ 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);
+ });
+});
diff --git a/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts b/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts
index c9773f6..26463c6 100644
--- a/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts
+++ b/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts
@@ -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);
diff --git a/apps/api-e2e/src/api/work-schedules.e2e.spec.ts b/apps/api-e2e/src/api/work-schedules.e2e.spec.ts
index c7d1e3a..0245fab 100644
--- a/apps/api-e2e/src/api/work-schedules.e2e.spec.ts
+++ b/apps/api-e2e/src/api/work-schedules.e2e.spec.ts
@@ -1,3 +1,4 @@
+import { WorkSchedulesService } from '../../../api/src/app/work-schedules/work-schedules.service';
import {
createTestApp,
login,
@@ -40,6 +41,21 @@ describe('WorkSchedules — CRUD + assignment', () => {
],
};
+ const scheduledWorkday = {
+ regularStart: '07:00',
+ regularEnd: '16:00',
+ breakRules: [{ afterMinutes: 30, breakMinutes: 30 }],
+ };
+
+ const terminalRules = {
+ startTimes: ['07:00'],
+ fixedBreaks: [],
+ earlyStartMinutes: 5,
+ breakStartToleranceMinutes: 0,
+ breakEndToleranceMinutes: 0,
+ shortBreakMinutes: 0,
+ };
+
it('non-HR cannot create a schedule (401 without token, 403 as employee)', async () => {
await ctx.http.post('/api/work-schedules').send(samplePayload).expect(401);
await seedEmployee(ctx.prisma, {
@@ -159,4 +175,225 @@ describe('WorkSchedules — CRUD + assignment', () => {
});
expect(updatedEmployee?.workScheduleId).toBe(created.body.id);
});
+
+ it('validates daily assessment and requires explicitly changing incompatible modes', async () => {
+ const token = await setupHR();
+ const authorization = `Bearer ${token}`;
+ const create = (body: object) =>
+ ctx.http
+ .post('/api/work-schedules')
+ .set('Authorization', authorization)
+ .send(body);
+
+ await create({
+ ...samplePayload,
+ scheduledWorkday: { ...scheduledWorkday, regularEnd: '07:00' },
+ }).expect(400);
+ await create({
+ ...samplePayload,
+ scheduledWorkday: { regularStart: '07:00', regularEnd: '16:00' },
+ }).expect(400);
+ await create({
+ ...samplePayload,
+ scheduledWorkday: {
+ ...scheduledWorkday,
+ breakRules: [{ afterMinutes: 29, breakMinutes: 30 }],
+ },
+ }).expect(400);
+ await create({ ...samplePayload, scheduledWorkday, terminalRules }).expect(
+ 400,
+ );
+ const created = await create({ ...samplePayload, scheduledWorkday }).expect(
+ 201,
+ );
+ expect(created.body.scheduledWorkday).toEqual(scheduledWorkday);
+ expect(created.body.terminalRules).toBeNull();
+
+ const update = (body: object) =>
+ ctx.http
+ .put(`/api/work-schedules/${created.body.id}`)
+ .set('Authorization', authorization)
+ .send(body);
+ await update({ ...samplePayload, terminalRules }).expect(400);
+ const omitted = await update(samplePayload).expect(200);
+ expect(omitted.body.scheduledWorkday).toEqual(scheduledWorkday);
+ const swapped = await update({
+ ...samplePayload,
+ scheduledWorkday: null,
+ terminalRules,
+ }).expect(200);
+ expect(swapped.body.scheduledWorkday).toBeNull();
+ expect(swapped.body.terminalRules).toEqual(terminalRules);
+
+ await update({ ...samplePayload, scheduledWorkday }).expect(400);
+ const reread = await ctx.http
+ .get(`/api/work-schedules/${created.body.id}`)
+ .expect(200);
+ expect(reread.body.terminalRules).toEqual(terminalRules);
+ expect(reread.body.scheduledWorkday).toBeNull();
+ });
+
+ it('changes the effective terminal mode in both directions at the next local date', async () => {
+ const token = await setupHR();
+ const person = await seedEmployee(ctx.prisma, {
+ personalNo: '2100',
+ firstName: 'Alex',
+ lastName: 'Example',
+ email: 'alex@shift-mode.test',
+ });
+ const authorization = `Bearer ${token}`;
+ const plan = await ctx.http
+ .post('/api/work-schedules')
+ .set('Authorization', authorization)
+ .send({ ...samplePayload, isDefault: true, terminalRules })
+ .expect(201);
+ const update = (body: object) =>
+ ctx.http
+ .put(`/api/work-schedules/${plan.body.id}`)
+ .set('Authorization', authorization)
+ .send({ ...samplePayload, isDefault: true, ...body });
+ const schedules = ctx.app.get(WorkSchedulesService);
+ const now = new Date();
+ const tomorrow = new Date(
+ now.getFullYear(),
+ now.getMonth(),
+ now.getDate() + 1,
+ 12,
+ );
+ const todayDate = new Date(
+ Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()),
+ );
+ const tomorrowDate = new Date(
+ Date.UTC(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate()),
+ );
+
+ await update({ terminalRules: null, scheduledWorkday }).expect(200);
+ expect(
+ (await schedules.resolveForEmployee(person.id, ctx.prisma, now))
+ .terminalRules,
+ ).toEqual(terminalRules);
+ expect(
+ (await schedules.resolveForEmployee(person.id, ctx.prisma, tomorrow))
+ .terminalRules,
+ ).toBeNull();
+
+ const effectiveVersion =
+ await ctx.prisma.scheduledWorkdayPolicyVersion.findUniqueOrThrow({
+ where: {
+ employeeId_effectiveOn: {
+ employeeId: person.id,
+ effectiveOn: tomorrowDate,
+ },
+ },
+ });
+ expect(effectiveVersion.rule).toEqual({
+ ...scheduledWorkday,
+ workingDays: 31,
+ holidayCalendar: 'DE-NW',
+ holidayDates: [],
+ });
+ expect(effectiveVersion.previousTerminalRules).toEqual(terminalRules);
+
+ // Advance the persisted effective date rather than changing the clock used by auth.
+ await ctx.prisma.scheduledWorkdayPolicyVersion.update({
+ where: {
+ employeeId_effectiveOn: {
+ employeeId: person.id,
+ effectiveOn: tomorrowDate,
+ },
+ },
+ data: { effectiveOn: todayDate },
+ });
+ await update({ scheduledWorkday: null, terminalRules }).expect(200);
+ expect(
+ (await schedules.resolveForEmployee(person.id, ctx.prisma, now))
+ .terminalRules,
+ ).toBeNull();
+ expect(
+ (await schedules.resolveForEmployee(person.id, ctx.prisma, tomorrow))
+ .terminalRules,
+ ).toEqual(terminalRules);
+ const versions = await ctx.prisma.scheduledWorkdayPolicyVersion.findMany({
+ where: { employeeId: person.id },
+ orderBy: { effectiveOn: 'asc' },
+ });
+ expect(versions).toMatchObject([
+ { effectiveOn: todayDate, rule: effectiveVersion.rule },
+ { effectiveOn: tomorrowDate, rule: null },
+ ]);
+ });
+
+ it('keeps the effective day and replaces the pending assignment after more than one change', async () => {
+ const token = await setupHR();
+ const person = await seedEmployee(ctx.prisma, {
+ personalNo: '2200',
+ firstName: 'Sam',
+ lastName: 'Example',
+ email: 'sam@assignment.test',
+ });
+ const authorization = `Bearer ${token}`;
+ const create = (body: object) =>
+ ctx.http
+ .post('/api/work-schedules')
+ .set('Authorization', authorization)
+ .send(body);
+ await create({
+ ...samplePayload,
+ name: 'Default assessed day',
+ isDefault: true,
+ scheduledWorkday,
+ }).expect(201);
+ const otherRule = { ...scheduledWorkday, regularStart: '08:00' };
+ const other = await create({
+ ...samplePayload,
+ name: 'Other assessed day',
+ scheduledWorkday: otherRule,
+ }).expect(201);
+
+ const now = new Date();
+ const today = new Date(
+ Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()),
+ );
+ const next = new Date(
+ Date.UTC(now.getFullYear(), now.getMonth(), now.getDate() + 1),
+ );
+ await ctx.prisma.scheduledWorkdayPolicyVersion.update({
+ where: {
+ employeeId_effectiveOn: { employeeId: person.id, effectiveOn: next },
+ },
+ data: { effectiveOn: today },
+ });
+ await ctx.http
+ .post(`/api/work-schedules/${other.body.id}/assign`)
+ .set('Authorization', authorization)
+ .send({ employeeId: person.id })
+ .expect(201);
+ expect(
+ await ctx.prisma.scheduledWorkdayPolicyVersion.findUnique({
+ where: {
+ employeeId_effectiveOn: { employeeId: person.id, effectiveOn: next },
+ },
+ }),
+ ).toMatchObject({ rule: otherRule });
+
+ await ctx.http
+ .put(`/api/employees/${person.id}`)
+ .set('Authorization', authorization)
+ .send({ workScheduleId: null, holidayCalendar: 'NONE' })
+ .expect(200);
+ const versions = await ctx.prisma.scheduledWorkdayPolicyVersion.findMany({
+ where: { employeeId: person.id },
+ orderBy: { effectiveOn: 'asc' },
+ });
+ expect(versions).toMatchObject([
+ {
+ effectiveOn: today,
+ rule: { ...scheduledWorkday, holidayCalendar: 'DE-NW' },
+ },
+ {
+ effectiveOn: next,
+ rule: { ...scheduledWorkday, holidayCalendar: 'NONE' },
+ },
+ ]);
+ });
});
diff --git a/apps/api-e2e/src/api/working-time-comparisons.e2e.spec.ts b/apps/api-e2e/src/api/working-time-comparisons.e2e.spec.ts
index 2f7e5dc..f9a929e 100644
--- a/apps/api-e2e/src/api/working-time-comparisons.e2e.spec.ts
+++ b/apps/api-e2e/src/api/working-time-comparisons.e2e.spec.ts
@@ -188,6 +188,74 @@ describe('Scoped working-time period comparisons', () => {
});
});
+ it('reports recorded late minutes independently of a balanced credited day', async () => {
+ const { direct, foreign, manager, snapshot, entry, report } =
+ await fixture();
+ await snapshot(direct.id, { weeklyHours: 42.5 });
+ await ctx.prisma.scheduledWorkdayPolicyVersion.create({
+ data: {
+ employeeId: direct.id,
+ effectiveOn: new Date('2026-08-11'),
+ rule: {
+ regularStart: '07:00',
+ regularEnd: '16:00',
+ workingDays: 31,
+ holidayCalendar: 'NONE',
+ holidayDates: [],
+ breakRules: [{ afterMinutes: 30, breakMinutes: 30 }],
+ },
+ },
+ });
+ const first = await entry(
+ direct.id,
+ '2026-08-12T05:05:00Z',
+ '2026-08-12T10:00:00Z',
+ );
+ const second = await entry(
+ direct.id,
+ '2026-08-12T10:00:00Z',
+ '2026-08-12T14:05:00Z',
+ { status: 'Pending' },
+ );
+ await entry(foreign.id, '2026-08-12T06:00:00Z', '2026-08-12T14:00:00Z');
+
+ const single = await report('2026-08-12', '2026-08-12', direct.id);
+ expect(single.comparisons).toMatchObject([
+ { actualMinutes: 510, targetMinutes: 510, differenceMinutes: 0 },
+ ]);
+ expect(single.rows).toMatchObject([
+ {
+ id: first.id,
+ grossMinutes: 295,
+ creditedGrossMinutes: 295,
+ breakMinutes: 30,
+ netMinutes: 265,
+ afterRegularEndMinutes: 0,
+ },
+ {
+ id: second.id,
+ creditedGrossMinutes: 245,
+ breakMinutes: 0,
+ netMinutes: 245,
+ afterRegularEndMinutes: 5,
+ status: 'Pending',
+ },
+ ]);
+ const broader = await report('2026-08-11', '2026-08-13');
+ expect(broader.rows.filter((row) => row.employeeId === direct.id)).toEqual(
+ single.rows,
+ );
+ const legacy = broader.rows.find((row) => row.employeeId === foreign.id);
+ expect(legacy?.grossMinutes).toBe(480);
+ expect(legacy).not.toHaveProperty('afterRegularEndMinutes');
+
+ await ctx.http
+ .get('/api/reports/working-times')
+ .query({ from: '2026-08-12', to: '2026-08-12', employeeId: foreign.id })
+ .set('Authorization', `Bearer ${await login(ctx.http, manager.email)}`)
+ .expect(403);
+ });
+
it('nulls the whole target/difference on any daily gap but retains actual minutes and known date coverage', async () => {
const { direct, snapshot, entry, report } = await fixture();
await snapshot(direct.id, { effectiveTo: new Date('2026-08-11') });
diff --git a/apps/api/openapi.json b/apps/api/openapi.json
index a75db80..9c13292 100644
--- a/apps/api/openapi.json
+++ b/apps/api/openapi.json
@@ -7014,6 +7014,29 @@
"shortBreakMinutes"
]
},
+ "ScheduledWorkdayDto": {
+ "type": "object",
+ "properties": {
+ "regularStart": {
+ "type": "string",
+ "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
+ "example": "07:00"
+ },
+ "regularEnd": {
+ "type": "string",
+ "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
+ "example": "16:00"
+ },
+ "breakRules": {
+ "description": "Break deductions applied once per local workday.",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/BreakRuleDto"
+ }
+ }
+ },
+ "required": ["regularStart", "regularEnd", "breakRules"]
+ },
"CoreTimeWindowResponse": {
"type": "object",
"properties": {
@@ -7086,6 +7109,15 @@
}
]
},
+ "scheduledWorkday": {
+ "nullable": true,
+ "type": "object",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ScheduledWorkdayDto"
+ }
+ ]
+ },
"coreTimes": {
"type": "array",
"items": {
@@ -7111,6 +7143,7 @@
"workingDays",
"breakRules",
"terminalRules",
+ "scheduledWorkday",
"coreTimes",
"employeeCount",
"updatedAt"
@@ -7195,6 +7228,16 @@
}
]
},
+ "scheduledWorkday": {
+ "nullable": true,
+ "description": "Optional daily assessment, effective from the next local date. Cannot be combined with terminalRules. Null disables; omission preserves.",
+ "type": "object",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ScheduledWorkdayDto"
+ }
+ ]
+ },
"coreTimes": {
"type": "array",
"items": {
@@ -7945,6 +7988,16 @@
"type": "number",
"minimum": 0
},
+ "creditedGrossMinutes": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Credited gross duration under the optional scheduled workday rule."
+ },
+ "afterRegularEndMinutes": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Recorded duration after the regular workday end, before any break deduction."
+ },
"breakMinutes": {
"type": "number",
"minimum": 0
diff --git a/apps/api/src/app/accounts/accounts.service.ts b/apps/api/src/app/accounts/accounts.service.ts
index 95bdefd..1ff7f06 100644
--- a/apps/api/src/app/accounts/accounts.service.ts
+++ b/apps/api/src/app/accounts/accounts.service.ts
@@ -11,6 +11,7 @@ import { EmployeesService } from '../employees/employees.service';
import { PrismaService } from '../prisma/prisma.service';
import { WorkSchedulesService } from '../work-schedules/work-schedules.service';
import { loadCaptureSummaries } from '../time-entries/capture-summary';
+import { loadScheduledWorkdaySummaries } from '../time-entries/scheduled-workday';
import type { JwtUser } from '../auth/jwt.strategy';
import { VacationBalanceService } from './vacation-balance.service';
import type { AccountDto } from './accounts.dto';
@@ -46,6 +47,7 @@ export class AccountsService {
employeeId: true,
clockIn: true,
clockOut: true,
+ approvalMode: true,
breakRules: true,
terminalCapture: true,
captureGroupId: true,
@@ -53,14 +55,23 @@ export class AccountsService {
voidedAt: true,
},
});
+ const scheduled = await loadScheduledWorkdaySummaries(
+ tx,
+ entries,
+ 'account',
+ );
const grouped = await loadCaptureSummaries(
tx,
entries.filter(
- (entry) => entry.captureGroupId || entry.terminalCapture,
+ (entry) =>
+ !scheduled.has(entry.id) &&
+ (entry.captureGroupId || entry.terminalCapture),
),
);
return entries.reduce((minutes, entry) => {
if (!entry.clockOut) return minutes;
+ const daySummary = scheduled.get(entry.id);
+ if (daySummary) return minutes + daySummary.netMinutes;
if (entry.captureGroupId || entry.terminalCapture)
return minutes + (grouped.get(entry.id)?.netMinutes ?? 0);
const gross = Math.floor(
diff --git a/apps/api/src/app/employees/employees.service.ts b/apps/api/src/app/employees/employees.service.ts
index d937d3b..757a224 100644
--- a/apps/api/src/app/employees/employees.service.ts
+++ b/apps/api/src/app/employees/employees.service.ts
@@ -10,6 +10,7 @@ import * as bcrypt from 'bcrypt';
import type { JwtUser } from '../auth/jwt.strategy';
import { PrismaService } from '../prisma/prisma.service';
import { TerminalAuditService } from '../terminals/terminal-audit.service';
+import { prepareScheduledWorkdayVersions } from '../work-schedules/scheduled-workday-policy';
import {
toEmployeeDto,
type CreateEmployeeDto,
@@ -113,7 +114,7 @@ export class EmployeesService {
throw new ForbiddenException(
'Enable Team mode before creating another employee',
);
- return tx.employee.create({
+ const employee = await tx.employee.create({
data: {
personalNo: dto.personalNo,
firstName: dto.firstName,
@@ -139,6 +140,11 @@ export class EmployeesService {
},
include: { workSchedule: true },
});
+ const saveVersions = await prepareScheduledWorkdayVersions(tx, {
+ id: employee.id,
+ });
+ await saveVersions();
+ return employee;
});
return toEmployeeDto(created);
} catch (err) {
@@ -238,11 +244,20 @@ export class EmployeesService {
'Cannot remove the last active administrator',
);
}
+ const affectsScheduledWorkday =
+ dto.workScheduleId !== undefined ||
+ dto.bundesland !== undefined ||
+ dto.holidayCalendar !== undefined ||
+ dto.holidayDates !== undefined;
+ const saveVersions = affectsScheduledWorkday
+ ? await prepareScheduledWorkdayVersions(tx, { id })
+ : undefined;
const employee = await tx.employee.update({
where: { id },
data,
include: { workSchedule: true },
});
+ await saveVersions?.();
if (
dto.isActive !== undefined &&
dto.isActive !== lockedCurrent.isActive
diff --git a/apps/api/src/app/reports/reports.dto.ts b/apps/api/src/app/reports/reports.dto.ts
index 9b39af6..4cf2041 100644
--- a/apps/api/src/app/reports/reports.dto.ts
+++ b/apps/api/src/app/reports/reports.dto.ts
@@ -108,6 +108,20 @@ export class WorkingTimeReportRowDto {
@ApiProperty({ minimum: 0 })
grossMinutes!: number;
+ @ApiPropertyOptional({
+ minimum: 0,
+ description:
+ 'Credited gross duration under the optional scheduled workday rule.',
+ })
+ creditedGrossMinutes?: number;
+
+ @ApiPropertyOptional({
+ minimum: 0,
+ description:
+ 'Recorded duration after the regular workday end, before any break deduction.',
+ })
+ afterRegularEndMinutes?: number;
+
@ApiProperty({ minimum: 0 })
breakMinutes!: number;
diff --git a/apps/api/src/app/reports/reports.service.ts b/apps/api/src/app/reports/reports.service.ts
index ab573c2..33c5525 100644
--- a/apps/api/src/app/reports/reports.service.ts
+++ b/apps/api/src/app/reports/reports.service.ts
@@ -11,6 +11,7 @@ import {
terminalBreakEvidence,
terminalSummaryForRange,
} from '../time-entries/capture-summary';
+import { loadScheduledWorkdaySummaries } from '../time-entries/scheduled-workday';
import { toTerminalCaptureDto } from '../time-entries/time-entries.dto';
import {
type WorkingTimeReportEmployeeDto,
@@ -567,11 +568,10 @@ export class ReportsService {
}),
]);
- const summaries = await this.workingTimeCaptureSummaries(
- entries,
- status,
- tx,
- );
+ const [summaries, scheduledSummaries] = await Promise.all([
+ this.workingTimeCaptureSummaries(entries, status, tx),
+ loadScheduledWorkdaySummaries(tx, entries),
+ ]);
const rows: WorkingTimeReportRowDto[] = [];
for (const entry of entries) {
const summary = summaries.get(entry.id);
@@ -579,6 +579,7 @@ export class ReportsService {
const duration = entry.clockOut.getTime() - entry.clockIn.getTime();
if (duration <= 0) continue;
const terminalCapture = toTerminalCaptureDto(entry);
+ const scheduledSummary = scheduledSummaries.get(entry.id);
const clippedEnd = Math.min(
entry.clockOut.getTime(),
toExclusive.getTime(),
@@ -605,7 +606,9 @@ export class ReportsService {
const grossMinutes =
terminalSummary?.grossMinutes ?? (rowEnd - cursor.getTime()) / 60_000;
const breakMinutes =
- terminalSummary?.breakMinutes ?? summary.breakMinutes * ratio;
+ scheduledSummary?.breakMinutes ??
+ terminalSummary?.breakMinutes ??
+ summary.breakMinutes * ratio;
rows.push({
id: entry.id,
employeeId: entry.employeeId,
@@ -645,8 +648,15 @@ export class ReportsService {
}
: {}),
grossMinutes,
+ ...(scheduledSummary
+ ? {
+ creditedGrossMinutes: scheduledSummary.creditedGrossMinutes,
+ afterRegularEndMinutes: scheduledSummary.afterRegularEndMinutes,
+ }
+ : {}),
breakMinutes,
- netMinutes: grossMinutes - breakMinutes,
+ netMinutes:
+ scheduledSummary?.netMinutes ?? grossMinutes - breakMinutes,
});
cursor = new Date(rowEnd);
}
diff --git a/apps/api/src/app/terminals/terminal-auth.service.ts b/apps/api/src/app/terminals/terminal-auth.service.ts
index 9e4e542..8e2293c 100644
--- a/apps/api/src/app/terminals/terminal-auth.service.ts
+++ b/apps/api/src/app/terminals/terminal-auth.service.ts
@@ -889,6 +889,7 @@ export class TerminalAuthService {
const schedule = await this.schedules.resolveForEmployee(
employeeId,
tx,
+ now,
);
const activity =
dto.activityId === undefined
diff --git a/apps/api/src/app/terminals/terminals.service.ts b/apps/api/src/app/terminals/terminals.service.ts
index 65e58b3..e1933dc 100644
--- a/apps/api/src/app/terminals/terminals.service.ts
+++ b/apps/api/src/app/terminals/terminals.service.ts
@@ -718,6 +718,7 @@ export class TerminalsService {
const schedule = await this.schedules.resolveForEmployee(
employeeId,
tx,
+ bookingNow,
);
const booked = await bookTerminalTime(
tx,
diff --git a/apps/api/src/app/time-entries/scheduled-workday.ts b/apps/api/src/app/time-entries/scheduled-workday.ts
new file mode 100644
index 0000000..8818296
--- /dev/null
+++ b/apps/api/src/app/time-entries/scheduled-workday.ts
@@ -0,0 +1,263 @@
+import type { Prisma, TimeEntry } from '@prisma/client';
+import {
+ holidayProviderForCalendar,
+ summarizeScheduledWorkday,
+ uniqueLocalMinute,
+ type BreakRule,
+ type ScheduledWorkdayInterval,
+ type ScheduledWorkdaySummary,
+} from 'shared';
+import { parseScheduledWorkdayPolicy } from '../work-schedules/scheduled-workday-policy';
+
+type EntrySelection = Pick<
+ TimeEntry,
+ 'id' | 'employeeId' | 'clockIn' | 'clockOut' | 'approvalMode'
+>;
+
+type Workday = {
+ from: Date;
+ to: Date;
+ regularStart: Date;
+ regularEnd: Date;
+ breakRules: BreakRule[];
+ entries: ScheduledWorkdayInterval[];
+ useLegacy: boolean;
+};
+
+function localMidnight(instant: Date): Date {
+ return new Date(instant.getFullYear(), instant.getMonth(), instant.getDate());
+}
+
+function nextLocalMidnight(day: Date): Date {
+ return new Date(day.getFullYear(), day.getMonth(), day.getDate() + 1);
+}
+
+function localDateKey(day: Date): number {
+ return Date.UTC(day.getFullYear(), day.getMonth(), day.getDate());
+}
+
+function wallMinutes(value: string): number {
+ const [hour, minute] = value.split(':').map(Number);
+ return hour * 60 + minute;
+}
+
+/**
+ * Load complete local days before selecting the requested rows. This keeps
+ * the daily deduction stable across row selection and report filters.
+ */
+export async function loadScheduledWorkdaySummaries(
+ tx: Prisma.TransactionClient,
+ entries: readonly EntrySelection[],
+ consumer: 'report' | 'account' = 'report',
+): Promise
+ {schedule.scheduledWorkday && (
+
+ {t('schedules.scheduledWorkdaySummary', {
+ start: schedule.scheduledWorkday.regularStart,
+ end: schedule.scheduledWorkday.regularEnd,
+ })}
+
+ )}
{t('schedules.workingDays')}:{' '}
{weekdayLabel(schedule.workingDays, labels)}
@@ -535,6 +672,9 @@ function ScheduleEditor({ state, onClose, onSaved }: ScheduleEditorProps) {
isDefault: draft.isDefault,
workingDays: draft.workingDays,
breakRules: draft.breakRules,
+ ...(draft.scheduledWorkday !== undefined
+ ? { scheduledWorkday: draft.scheduledWorkday }
+ : {}),
...(draft.terminalRules !== undefined
? {
terminalRules: draft.terminalRules
@@ -590,19 +730,17 @@ function ScheduleEditor({ state, onClose, onSaved }: ScheduleEditorProps) {
const valid = useMemo(() => {
if (!draft.name.trim()) return false;
if (draft.frameStart >= draft.frameEnd) return false;
+ if (!validBreakRules(draft.breakRules)) return false;
+ const day = draft.scheduledWorkday;
if (
- !draft.breakRules.every(
- (rule) =>
- Number.isInteger(rule.afterMinutes) &&
- rule.afterMinutes >= 0 &&
- rule.afterMinutes <= 1440 &&
- Number.isInteger(rule.breakMinutes) &&
- rule.breakMinutes >= 0 &&
- rule.breakMinutes <= rule.afterMinutes,
- )
+ day &&
+ (draft.terminalRules ||
+ !wallTime.test(day.regularStart) ||
+ !wallTime.test(day.regularEnd) ||
+ day.regularStart >= day.regularEnd ||
+ !validBreakRules(day.breakRules))
)
return false;
- if (draft.breakRules.length > 50) return false;
if (
draft.terminalRules &&
!validTerminalRules(
@@ -712,110 +850,56 @@ function ScheduleEditor({ state, onClose, onSaved }: ScheduleEditorProps) {
-
-
-
{t('schedules.breakRules')}
-
-
+ />
+ {t('schedules.scheduledWorkday')}
+
- {t('schedules.breakRulesHint')}
+ {t('schedules.scheduledWorkdayHint')}
- {draft.breakRules.map((rule, index) => (
-
-
-
-
- setDraft({
- ...draft,
- breakRules: draft.breakRules.map((current, i) =>
- i === index
- ? {
- ...current,
- afterMinutes: Number(event.target.value),
- }
- : current,
- ),
- })
- }
- />
-
-
-
-
- setDraft({
- ...draft,
- breakRules: draft.breakRules.map((current, i) =>
- i === index
- ? {
- ...current,
- breakMinutes: Number(event.target.value),
- }
- : current,
- ),
- })
- }
- />
-
-
-
- ))}
-
+ {draft.scheduledWorkday && (
+
+ setDraft({ ...draft, scheduledWorkday })
+ }
+ />
+ )}
+