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> { + const selectedIds = new Set(); + const datesByEmployee = new Map>(); + let lastDate = Number.NEGATIVE_INFINITY; + for (const entry of entries) { + if (!entry.clockOut || entry.approvalMode === 'Solo') continue; + selectedIds.add(entry.id); + const date = localDateKey(entry.clockIn); + const days = datesByEmployee.get(entry.employeeId) ?? new Set(); + days.add(date); + datesByEmployee.set(entry.employeeId, days); + lastDate = Math.max(lastDate, date); + } + if (!datesByEmployee.size) return new Map(); + + const versions = await tx.scheduledWorkdayPolicyVersion.findMany({ + where: { + employeeId: { in: [...datesByEmployee.keys()] }, + effectiveOn: { lte: new Date(lastDate) }, + }, + orderBy: { effectiveOn: 'asc' }, + }); + const employeeVersions = new Map(); + for (const version of versions) { + const history = employeeVersions.get(version.employeeId) ?? []; + history.push(version); + employeeVersions.set(version.employeeId, history); + } + + const scheduledDays = new Map>(); + let minTime = Number.POSITIVE_INFINITY; + let maxTime = Number.NEGATIVE_INFINITY; + for (const [employeeId, dates] of datesByEmployee) { + const history = employeeVersions.get(employeeId); + if (!history) continue; + let version = 0; + for (const date of [...dates].sort((a, b) => a - b)) { + while (version < history.length && +history[version].effectiveOn <= date) + version += 1; + const policy = parseScheduledWorkdayPolicy(history[version - 1]?.rule); + if (!policy) continue; + + const localDate = new Date(date); + const weekday = 1 << ((localDate.getUTCDay() + 6) % 7); + if ( + !(policy.workingDays & weekday) || + holidayProviderForCalendar( + policy.holidayCalendar, + policy.holidayDates, + ).isHoliday(localDate) + ) + continue; + + const from = new Date( + localDate.getUTCFullYear(), + localDate.getUTCMonth(), + localDate.getUTCDate(), + ); + const to = nextLocalMidnight(from); + const regularStart = uniqueLocalMinute( + from, + wallMinutes(policy.regularStart), + ); + const regularEnd = uniqueLocalMinute( + from, + wallMinutes(policy.regularEnd), + ); + // A boundary that does not exist or is ambiguous at a clock change + // leaves the recorded booking under the existing calculation. + if (!regularStart || !regularEnd || regularStart >= regularEnd) continue; + const days = scheduledDays.get(employeeId) ?? new Map(); + days.set(date, { + from, + to, + regularStart, + regularEnd, + breakRules: policy.breakRules, + entries: [], + useLegacy: false, + }); + scheduledDays.set(employeeId, days); + minTime = Math.min(minTime, +from); + maxTime = Math.max(maxTime, +to); + } + } + if (!scheduledDays.size) return new Map(); + + const dayEntries = await tx.timeEntry.findMany({ + where: { + employeeId: { in: [...scheduledDays.keys()] }, + clockIn: { lt: new Date(maxTime) }, + OR: [ + { clockOut: { gt: new Date(minTime) } }, + { clockOut: null, clockIn: { gte: new Date(minTime) } }, + ], + }, + select: { + id: true, + employeeId: true, + clockIn: true, + clockOut: true, + approvalMode: true, + bookingDate: true, + terminalCapture: true, + captureGroupId: true, + status: true, + voidedAt: true, + }, + }); + const groupIds = [ + ...new Set( + dayEntries.flatMap(({ captureGroupId }) => + captureGroupId ? [captureGroupId] : [], + ), + ), + ]; + if (groupIds.length) { + // A project switch at exactly midnight can split an overnight capture + // into otherwise same-day rows. Include siblings outside the visible day. + const groups = await tx.timeEntry.groupBy({ + by: ['employeeId', 'captureGroupId'], + where: { + employeeId: { in: [...scheduledDays.keys()] }, + captureGroupId: { in: groupIds }, + clockOut: { not: null }, + voidedAt: null, + status: { not: 'Rejected' }, + OR: [{ approvalMode: null }, { approvalMode: 'Team' }], + }, + _min: { clockIn: true }, + _max: { clockOut: true }, + }); + for (const { employeeId, _min, _max } of groups) { + const firstPunch = _min.clockIn; + const lastPunch = _max.clockOut; + if ( + !firstPunch || + !lastPunch || + lastPunch <= nextLocalMidnight(firstPunch) + ) + continue; + const days = scheduledDays.get(employeeId); + if (!days) continue; + const rangeEnd = Math.min(maxTime, +lastPunch); + for ( + let day = localMidnight(new Date(Math.max(+firstPunch, minTime))); + +day < rangeEnd; + day = nextLocalMidnight(day) + ) { + const current = days.get(localDateKey(day)); + if (current) current.useLegacy = true; + } + } + } + + for (const entry of dayEntries) { + if (entry.approvalMode === 'Solo') continue; + const days = scheduledDays.get(entry.employeeId); + if (!days) continue; + + const active = !entry.voidedAt && entry.status !== 'Rejected'; + // The existing time account includes ungrouped closed entries, even if + // cancelled or rejected. The working-time report uses its own status scope. + const eligible = + entry.clockOut && + (consumer === 'account' + ? active || (!entry.captureGroupId && !entry.terminalCapture) + : active && + (entry.status === 'Approved' || entry.status === 'Pending')); + if (!active && !eligible) continue; + + const entryEnd = Math.min( + maxTime, + entry.clockOut ? +entry.clockOut : +entry.clockIn + 1, + ); + for ( + let day = localMidnight(new Date(Math.max(+entry.clockIn, minTime))); + +day < entryEnd; + day = nextLocalMidnight(day) + ) { + const current = days.get(localDateKey(day)); + if (!current) continue; + if ( + entry.terminalCapture || + entry.bookingDate || + entry.clockIn < current.from || + (entry.clockOut && entry.clockOut > current.to) + ) { + current.useLegacy = true; + continue; + } + if (eligible) current.entries.push(entry); + } + } + + const summaries = new Map(); + for (const days of scheduledDays.values()) { + for (const day of days.values()) { + if (day.useLegacy) continue; + const calculated = summarizeScheduledWorkday( + day.entries, + day.regularStart, + day.regularEnd, + day.breakRules, + ); + for (const [id, summary] of calculated) { + if (selectedIds.has(id)) summaries.set(id, summary); + } + } + } + return summaries; +} diff --git a/apps/api/src/app/time-entries/time-entries.service.ts b/apps/api/src/app/time-entries/time-entries.service.ts index 97900d6..634af37 100644 --- a/apps/api/src/app/time-entries/time-entries.service.ts +++ b/apps/api/src/app/time-entries/time-entries.service.ts @@ -621,6 +621,7 @@ export class TimeEntriesService { const schedule = await this.schedules.resolveForEmployee( employeeId, tx, + bookingNow, ); const terminalCapture = !policy.isSolo && schedule.terminalRules diff --git a/apps/api/src/app/work-schedules/scheduled-workday-policy.ts b/apps/api/src/app/work-schedules/scheduled-workday-policy.ts new file mode 100644 index 0000000..b02ff8a --- /dev/null +++ b/apps/api/src/app/work-schedules/scheduled-workday-policy.ts @@ -0,0 +1,207 @@ +import { Prisma } from '@prisma/client'; +import { + parseBreakRules, + parseTerminalRules, + type BreakRule, + type TerminalRules, +} from 'shared'; + +export type ScheduledWorkday = { + regularStart: string; + regularEnd: string; + breakRules: BreakRule[]; +}; + +export type ScheduledWorkdayPolicy = ScheduledWorkday & { + workingDays: number; + holidayCalendar: string; + holidayDates: string[]; +}; + +export function parseScheduledWorkday(value: unknown): ScheduledWorkday | null { + if (value == null) return null; + const { regularStart, regularEnd, breakRules } = value as ScheduledWorkday; + const hhmm = /^([01]\d|2[0-3]):[0-5]\d$/; + if ( + typeof regularStart !== 'string' || + typeof regularEnd !== 'string' || + !hhmm.test(regularStart) || + !hhmm.test(regularEnd) || + regularStart >= regularEnd + ) { + throw new Error('Regular start must be before regular end on the same day'); + } + return { regularStart, regularEnd, breakRules: parseBreakRules(breakRules) }; +} + +export function parseScheduledWorkdayPolicy( + value: unknown, +): ScheduledWorkdayPolicy | null { + const rule = parseScheduledWorkday(value); + if (!rule) return null; + const { workingDays, holidayCalendar, holidayDates } = + value as ScheduledWorkdayPolicy; + return { ...rule, workingDays, holidayCalendar, holidayDates }; +} + +const dayScheduleSelect = { + scheduledWorkday: true, + terminalRules: true, + workingDays: true, +} satisfies Prisma.WorkScheduleSelect; + +function nextLocalDate(now: Date): Date { + return new Date( + Date.UTC(now.getFullYear(), now.getMonth(), now.getDate() + 1), + ); +} + +function splitVersions( + versions: readonly T[], + effectiveOn: Date, +): { pending?: T; current?: T } { + const [first, second] = versions; + return first?.effectiveOn.getTime() === effectiveOn.getTime() + ? { pending: first, current: second } + : { current: first }; +} + +function effectiveTerminalRules( + current: { rule: unknown } | undefined, + pending: { rule: unknown; previousTerminalRules: unknown } | undefined, + live: unknown, +): TerminalRules | null { + if (current?.rule != null) return null; + return parseTerminalRules( + pending?.rule != null ? pending.previousTerminalRules : live, + ); +} + +export async function resolveEffectiveTerminalRules( + db: Pick, + employeeId: string, + live: unknown, + now: Date, +): Promise { + const effectiveOn = nextLocalDate(now); + const versions = await db.scheduledWorkdayPolicyVersion.findMany({ + where: { employeeId, effectiveOn: { lte: effectiveOn } }, + orderBy: { effectiveOn: 'desc' }, + take: 2, + }); + const { current, pending } = splitVersions(versions, effectiveOn); + return effectiveTerminalRules(current, pending, live); +} + +/** + * Called under the installation advisory lock, before a schedule or assignment + * mutation. The callback sees the final state and can replace a pending + * version on the same day. Today's version remains effective. + */ +export async function prepareScheduledWorkdayVersions( + tx: Prisma.TransactionClient, + where: Prisma.EmployeeWhereInput, +): Promise<() => Promise> { + const effectiveOn = nextLocalDate(new Date()); + const previous = await tx.employee.findMany({ + where, + select: { + id: true, + workSchedule: { select: { terminalRules: true } }, + scheduledWorkdayVersions: { + where: { effectiveOn: { lte: effectiveOn } }, + orderBy: { effectiveOn: 'desc' }, + take: 2, + }, + }, + }); + if (!previous.length) return () => Promise.resolve(); + + const previousDefault = previous.some((person) => !person.workSchedule) + ? await tx.workSchedule.findFirst({ + where: { isDefault: true }, + select: { terminalRules: true }, + }) + : null; + + return async () => { + const ids = previous.map((person) => person.id); + const employees = await tx.employee.findMany({ + where: { id: { in: ids } }, + select: { + id: true, + holidayCalendar: true, + holidayDates: true, + workSchedule: { select: dayScheduleSelect }, + }, + }); + const newDefault = employees.some((person) => !person.workSchedule) + ? await tx.workSchedule.findFirst({ + where: { isDefault: true }, + select: dayScheduleSelect, + }) + : null; + + const oldById = new Map(previous.map((person) => [person.id, person])); + const superseded: string[] = []; + const changes: { + employeeId: string; + rule: ScheduledWorkdayPolicy | null; + previousTerminalRules: TerminalRules | null; + }[] = []; + for (const employee of employees) { + const old = oldById.get(employee.id); + if (!old) continue; + const schedule = employee.workSchedule ?? newDefault; + const scheduled = parseScheduledWorkday(schedule?.scheduledWorkday); + const next = + scheduled && schedule + ? { + ...scheduled, + workingDays: schedule.workingDays, + holidayCalendar: employee.holidayCalendar, + holidayDates: employee.holidayDates, + } + : null; + const { current, pending } = splitVersions( + old.scheduledWorkdayVersions, + effectiveOn, + ); + const active = parseScheduledWorkdayPolicy(current?.rule); + if (JSON.stringify(active) === JSON.stringify(next)) { + if (pending) superseded.push(employee.id); + continue; + } + const priorSchedule = old.workSchedule ?? previousDefault; + changes.push({ + employeeId: employee.id, + rule: next, + previousTerminalRules: next + ? effectiveTerminalRules( + current, + pending, + priorSchedule?.terminalRules, + ) + : null, + }); + } + if (superseded.length) { + await tx.scheduledWorkdayPolicyVersion.deleteMany({ + where: { effectiveOn, employeeId: { in: superseded } }, + }); + } + if (changes.length) { + await tx.$executeRaw` + INSERT INTO "ScheduledWorkdayPolicyVersion" + ("employeeId", "effectiveOn", "rule", "previousTerminalRules") + SELECT changes."employeeId", ${effectiveOn.toISOString().slice(0, 10)}::date, + changes."rule", changes."previousTerminalRules" + FROM jsonb_to_recordset(${JSON.stringify(changes)}::jsonb) + AS changes("employeeId" uuid, "rule" jsonb, "previousTerminalRules" jsonb) + ON CONFLICT ("employeeId", "effectiveOn") DO UPDATE SET + "rule" = EXCLUDED."rule", + "previousTerminalRules" = EXCLUDED."previousTerminalRules" + `; + } + }; +} diff --git a/apps/api/src/app/work-schedules/work-schedules.dto.ts b/apps/api/src/app/work-schedules/work-schedules.dto.ts index 21726a1..d77f421 100644 --- a/apps/api/src/app/work-schedules/work-schedules.dto.ts +++ b/apps/api/src/app/work-schedules/work-schedules.dto.ts @@ -5,6 +5,7 @@ import { IsBoolean, IsEnum, IsInt, + IsObject, IsOptional, IsString, IsUUID, @@ -23,6 +24,11 @@ import { type TerminalRules, } from 'shared'; +import { + parseScheduledWorkday, + type ScheduledWorkday, +} from './scheduled-workday-policy'; + const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/; const HHMM_PATTERN = '^([01]\\d|2[0-3]):[0-5]\\d$'; @@ -75,6 +81,26 @@ export class BreakRuleDto implements BreakRule { breakMinutes!: number; } +export class ScheduledWorkdayDto implements ScheduledWorkday { + @ApiProperty({ pattern: HHMM_PATTERN, example: '07:00' }) + @Matches(HHMM) + regularStart!: string; + + @ApiProperty({ pattern: HHMM_PATTERN, example: '16:00' }) + @Matches(HHMM) + regularEnd!: string; + + @ApiProperty({ + type: [BreakRuleDto], + description: 'Break deductions applied once per local workday.', + }) + @IsArray() + @ArrayMaxSize(50) + @ValidateNested({ each: true }) + @Type(() => BreakRuleDto) + breakRules!: BreakRuleDto[]; +} + export class FixedTerminalBreakDto { @ApiProperty({ pattern: HHMM_PATTERN, example: '13:00' }) @Matches(HHMM) @@ -193,6 +219,18 @@ export class UpsertWorkScheduleDto { @Type(() => TerminalRulesDto) terminalRules?: TerminalRulesDto | null; + @ApiPropertyOptional({ + type: ScheduledWorkdayDto, + nullable: true, + description: + 'Optional daily assessment, effective from the next local date. Cannot be combined with terminalRules. Null disables; omission preserves.', + }) + @IsOptional() + @IsObject() + @ValidateNested() + @Type(() => ScheduledWorkdayDto) + scheduledWorkday?: ScheduledWorkdayDto | null; + @ApiProperty({ type: [CoreTimeWindowDto] }) @IsArray() @ValidateNested({ each: true }) @@ -256,6 +294,8 @@ export class WorkScheduleResponse { breakRules!: BreakRule[]; @ApiProperty({ type: TerminalRulesDto, nullable: true }) terminalRules!: TerminalRules | null; + @ApiProperty({ type: ScheduledWorkdayDto, nullable: true }) + scheduledWorkday!: ScheduledWorkday | null; @ApiProperty({ type: [CoreTimeWindowResponse] }) coreTimes!: CoreTimeWindowResponse[]; @ApiProperty({ minimum: 0 }) @@ -278,6 +318,7 @@ export function toScheduleResponse( workingDays: schedule.workingDays, breakRules: parseBreakRules(schedule.breakRules), terminalRules: parseTerminalRules(schedule.terminalRules), + scheduledWorkday: parseScheduledWorkday(schedule.scheduledWorkday), coreTimes: schedule.coreTimes.map((c) => ({ id: c.id, label: c.label, diff --git a/apps/api/src/app/work-schedules/work-schedules.service.ts b/apps/api/src/app/work-schedules/work-schedules.service.ts index a0e9ec7..aeaacd3 100644 --- a/apps/api/src/app/work-schedules/work-schedules.service.ts +++ b/apps/api/src/app/work-schedules/work-schedules.service.ts @@ -23,6 +23,11 @@ import { type TerminalRules, } from 'shared'; import { PrismaService } from '../prisma/prisma.service'; +import { + parseScheduledWorkday, + prepareScheduledWorkdayVersions, + resolveEffectiveTerminalRules, +} from './scheduled-workday-policy'; import { toScheduleResponse, type BulkAssignResult, @@ -100,8 +105,12 @@ export class WorkSchedulesService { async create(dto: UpsertWorkScheduleDto): Promise { assertValidScheduleTimes(dto); - const terminalRules = terminalRuleInput(dto); + const { terminalRules, scheduledWorkday } = scheduleModeInput(dto); return this.prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; + const saveVersions = dto.isDefault + ? await prepareScheduledWorkdayVersions(tx, { workScheduleId: null }) + : undefined; if (dto.isDefault) { await tx.workSchedule.updateMany({ where: { isDefault: true }, @@ -122,6 +131,7 @@ export class WorkSchedulesService { ? undefined : parseBreakRules(dto.breakRules), terminalRules, + scheduledWorkday, coreTimes: { create: dto.coreTimes.map((c) => ({ label: c.label ?? null, @@ -133,6 +143,7 @@ export class WorkSchedulesService { }, include: { coreTimes: { orderBy: { start: 'asc' } } }, }); + await saveVersions?.(); return toScheduleResponse(created, 0); } catch (err) { if (isUniqueViolation(err)) { @@ -149,10 +160,20 @@ export class WorkSchedulesService { id: string, dto: UpsertWorkScheduleDto, ): Promise { - await this.findOrThrow(id); assertValidScheduleTimes(dto); - const terminalRules = terminalRuleInput(dto); return this.prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; + const current = await this.findOrThrow(id, tx); + const { terminalRules, scheduledWorkday } = scheduleModeInput( + dto, + current, + ); + const saveVersions = await prepareScheduledWorkdayVersions( + tx, + current.isDefault || dto.isDefault + ? { OR: [{ workScheduleId: id }, { workScheduleId: null }] } + : { workScheduleId: id }, + ); if (dto.isDefault) { await tx.workSchedule.updateMany({ where: { isDefault: true, NOT: { id } }, @@ -175,6 +196,7 @@ export class WorkSchedulesService { ? undefined : parseBreakRules(dto.breakRules), terminalRules, + scheduledWorkday, coreTimes: { create: dto.coreTimes.map((c) => ({ label: c.label ?? null, @@ -186,6 +208,7 @@ export class WorkSchedulesService { }, include: { coreTimes: { orderBy: { start: 'asc' } } }, }); + await saveVersions(); const count = await tx.employee.count({ where: { workScheduleId: id }, }); @@ -202,35 +225,54 @@ export class WorkSchedulesService { } async remove(id: string): Promise { - await this.findOrThrow(id); - await this.prisma.workSchedule.delete({ where: { id } }); + await this.prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; + const current = await this.findOrThrow(id, tx); + const saveVersions = await prepareScheduledWorkdayVersions( + tx, + current.isDefault + ? { OR: [{ workScheduleId: id }, { workScheduleId: null }] } + : { workScheduleId: id }, + ); + await tx.workSchedule.delete({ where: { id } }); + await saveVersions(); + }); } async assignToEmployee( scheduleId: string, employeeId: string, ): Promise { - await this.findOrThrow(scheduleId); - const employee = await this.prisma.employee.findUnique({ - where: { id: employeeId }, - }); - if (!employee) - throw new NotFoundException(`Employee ${employeeId} not found`); - await this.prisma.employee.update({ - where: { id: employeeId }, - data: { workScheduleId: scheduleId }, - }); + await this.setAssignment(employeeId, scheduleId); } async unassignFromEmployee(employeeId: string): Promise { - const employee = await this.prisma.employee.findUnique({ - where: { id: employeeId }, - }); - if (!employee) - throw new NotFoundException(`Employee ${employeeId} not found`); - await this.prisma.employee.update({ - where: { id: employeeId }, - data: { workScheduleId: null }, + await this.setAssignment(employeeId, null); + } + + private async setAssignment( + employeeId: string, + scheduleId: string | null, + ): Promise { + await this.prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; + if (scheduleId) await this.findOrThrow(scheduleId, tx); + const employee = await tx.employee.findUnique({ + where: { id: employeeId }, + select: { workScheduleId: true }, + }); + if (!employee) + throw new NotFoundException(`Employee ${employeeId} not found`); + if (employee.workScheduleId === scheduleId) return; + + const saveVersions = await prepareScheduledWorkdayVersions(tx, { + id: employeeId, + }); + await tx.employee.update({ + where: { id: employeeId }, + data: { workScheduleId: scheduleId }, + }); + await saveVersions(); }); } @@ -239,22 +281,27 @@ export class WorkSchedulesService { timeModel: TimeModel, overrideExisting: boolean, ): Promise { - await this.findOrThrow(scheduleId); - const where = overrideExisting - ? { timeModel, isActive: true } - : { timeModel, isActive: true, workScheduleId: null }; - const result = await this.prisma.employee.updateMany({ - where, - data: { workScheduleId: scheduleId }, - }); - const totalForModel = await this.prisma.employee.count({ - where: { timeModel, isActive: true }, + return this.prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; + await this.findOrThrow(scheduleId, tx); + const where = overrideExisting + ? { timeModel, isActive: true } + : { timeModel, isActive: true, workScheduleId: null }; + const saveVersions = await prepareScheduledWorkdayVersions(tx, where); + const result = await tx.employee.updateMany({ + where, + data: { workScheduleId: scheduleId }, + }); + await saveVersions(); + const totalForModel = await tx.employee.count({ + where: { timeModel, isActive: true }, + }); + return { + scheduleId, + assigned: result.count, + skipped: totalForModel - result.count, + }; }); - return { - scheduleId, - assigned: result.count, - skipped: totalForModel - result.count, - }; } /** @@ -265,8 +312,11 @@ export class WorkSchedulesService { */ async resolveForEmployee( employeeId: string, - db: Pick = this - .prisma, + db: Pick< + Prisma.TransactionClient, + 'employee' | 'workSchedule' | 'scheduledWorkdayPolicyVersion' + > = this.prisma, + at = new Date(), ): Promise { const employee = await db.employee.findUnique({ where: { id: employeeId }, @@ -288,6 +338,12 @@ export class WorkSchedulesService { where: { isDefault: true }, include: { coreTimes: { orderBy: { start: 'asc' } } }, }); + const terminalRules = await resolveEffectiveTerminalRules( + db, + employeeId, + schedule?.terminalRules, + at, + ); if (!schedule) { return { scheduleId: null, @@ -298,7 +354,7 @@ export class WorkSchedulesService { holidayProvider, holidayCalendar, breakRules: [], - terminalRules: null, + terminalRules, terminalExactStart: employee.terminalExactStart, terminalScheduledStart: employee.terminalScheduledStart, }; @@ -312,14 +368,17 @@ export class WorkSchedulesService { holidayProvider, holidayCalendar, breakRules: parseBreakRules(schedule.breakRules), - terminalRules: parseTerminalRules(schedule.terminalRules), + terminalRules, terminalExactStart: employee.terminalExactStart, terminalScheduledStart: employee.terminalScheduledStart, }; } - private async findOrThrow(id: string) { - const row = await this.prisma.workSchedule.findUnique({ + private async findOrThrow( + id: string, + db: Pick = this.prisma, + ) { + const row = await db.workSchedule.findUnique({ where: { id }, include: { coreTimes: { orderBy: { start: 'asc' } } }, }); @@ -328,10 +387,36 @@ export class WorkSchedulesService { } } -function terminalRuleInput(dto: UpsertWorkScheduleDto) { - if (dto.terminalRules === undefined) return undefined; +function scheduleModeInput( + dto: UpsertWorkScheduleDto, + current?: Pick, +) { try { - return parseTerminalRules(dto.terminalRules) ?? Prisma.DbNull; + const terminal = parseTerminalRules( + dto.terminalRules === undefined + ? current?.terminalRules + : dto.terminalRules, + ); + const scheduled = parseScheduledWorkday( + dto.scheduledWorkday === undefined + ? current?.scheduledWorkday + : dto.scheduledWorkday, + ); + if (terminal && scheduled) { + throw new Error( + 'Terminal rules and scheduled workday assessment cannot both be enabled', + ); + } + return { + terminalRules: + dto.terminalRules === undefined + ? undefined + : (terminal ?? Prisma.DbNull), + scheduledWorkday: + dto.scheduledWorkday === undefined + ? undefined + : (scheduled ?? Prisma.DbNull), + }; } catch (err) { throw new BadRequestException((err as Error).message); } diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 19b4ca2..0d9319e 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -565,6 +565,8 @@ export interface WorkingTimeReportRowDto { clockOut: string; status: EntryStatus; grossMinutes: number; + creditedGrossMinutes?: number | null; + afterRegularEndMinutes?: number | null; breakMinutes: number; netMinutes: number; clockInLocation?: WorkingTimeReportLocationDto | null; @@ -779,6 +781,12 @@ export interface BreakRuleDto { breakMinutes: number; } +export interface ScheduledWorkdayDto { + regularStart: string; + regularEnd: string; + breakRules: BreakRuleDto[]; +} + export interface WorkScheduleDto { id: string; name: string; @@ -789,6 +797,7 @@ export interface WorkScheduleDto { workingDays: number; breakRules: BreakRuleDto[]; terminalRules?: TerminalRulesDto | null; + scheduledWorkday?: ScheduledWorkdayDto | null; coreTimes: CoreTimeWindowDto[]; employeeCount: number; updatedAt: string; @@ -803,6 +812,7 @@ export interface UpsertWorkSchedulePayload { workingDays: number; breakRules: BreakRuleDto[]; terminalRules?: TerminalRulesDto | null; + scheduledWorkday?: ScheduledWorkdayDto | null; coreTimes: Array<{ label: string | null; start: string; diff --git a/apps/web/src/api/generated.ts b/apps/web/src/api/generated.ts index e0ad8ba..30fe85e 100644 --- a/apps/web/src/api/generated.ts +++ b/apps/web/src/api/generated.ts @@ -2540,6 +2540,14 @@ export interface components { /** @description 0 disables short-break rounding. */ shortBreakMinutes: number; }; + ScheduledWorkdayDto: { + /** @example 07:00 */ + regularStart: string; + /** @example 16:00 */ + regularEnd: string; + /** @description Break deductions applied once per local workday. */ + breakRules: components['schemas']['BreakRuleDto'][]; + }; CoreTimeWindowResponse: { /** Format: uuid */ id: string; @@ -2559,6 +2567,7 @@ export interface components { workingDays: number; breakRules: components['schemas']['BreakRuleDto'][]; terminalRules: components['schemas']['TerminalRulesDto'] | null; + scheduledWorkday: components['schemas']['ScheduledWorkdayDto'] | null; coreTimes: components['schemas']['CoreTimeWindowResponse'][]; employeeCount: number; /** Format: date-time */ @@ -2595,6 +2604,8 @@ export interface components { breakRules: components['schemas']['BreakRuleDto'][]; /** @description Null disables terminal breaks. Omission preserves the rule on update. */ terminalRules?: components['schemas']['TerminalRulesDto'] | null; + /** @description Optional daily assessment, effective from the next local date. Cannot be combined with terminalRules. Null disables; omission preserves. */ + scheduledWorkday?: components['schemas']['ScheduledWorkdayDto'] | null; coreTimes: components['schemas']['CoreTimeWindowDto'][]; }; AssignToEmployeeDto: { @@ -2830,6 +2841,10 @@ export interface components { /** @enum {string} */ status: 'Pending' | 'Approved'; grossMinutes: number; + /** @description Credited gross duration under the optional scheduled workday rule. */ + creditedGrossMinutes?: number; + /** @description Recorded duration after the regular workday end, before any break deduction. */ + afterRegularEndMinutes?: number; breakMinutes: number; netMinutes: number; clockInLocation?: diff --git a/apps/web/src/app/i18n.tsx b/apps/web/src/app/i18n.tsx index 6e6cf10..fc2c280 100644 --- a/apps/web/src/app/i18n.tsx +++ b/apps/web/src/app/i18n.tsx @@ -183,6 +183,17 @@ const de: Catalog = { 'schedules.breakAfter': 'Ab Anwesenheit (Minuten)', 'schedules.breakMinutes': 'Gesamtabzug (Minuten)', 'schedules.breakRuleSummary': 'ab {after} min: {deduction} min', + 'schedules.scheduledWorkday': 'Regulären Arbeitstag berechnen', + 'schedules.regularStart': 'Regulärer Beginn', + 'schedules.regularEnd': 'Reguläres Ende', + 'schedules.dailyBreakRules': 'Pausenabzug pro Arbeitstag', + 'schedules.dailyBreakRulesHint': + 'Die größte zutreffende Pause wird einmal auf die angerechnete Dauer des Arbeitstags angewendet. Regeln passend zu Vertrag und örtlichen Vorgaben festlegen.', + 'schedules.scheduledWorkdayHint': + 'Der Genehmigungsrahmen gilt separat. Änderungen der Tagesberechnung gelten ab dem nächsten Kalendertag in der Zeitzone der Installation.', + 'schedules.workdayModes': + 'Wähle pro Arbeitszeitplan die Tagesberechnung oder das Stempeln von Pausen am Terminal.', + 'schedules.scheduledWorkdaySummary': 'Regulärer Arbeitstag: {start}–{end}', 'schedules.frame': 'Rahmen', 'schedules.frameStart': 'Rahmen Start', 'schedules.frameEnd': 'Rahmen Ende', @@ -1006,6 +1017,17 @@ const en: Catalog = { 'schedules.breakAfter': 'Attendance threshold (minutes)', 'schedules.breakMinutes': 'Total deduction (minutes)', 'schedules.breakRuleSummary': 'at {after} min: {deduction} min', + 'schedules.scheduledWorkday': 'Calculate scheduled workdays', + 'schedules.regularStart': 'Scheduled start', + 'schedules.regularEnd': 'Scheduled end', + 'schedules.dailyBreakRules': 'Daily break deduction', + 'schedules.dailyBreakRulesHint': + 'The largest matching break is deducted once from the credited duration of the workday. Set rules according to the contract and local requirements.', + 'schedules.scheduledWorkdayHint': + 'The approval frame applies separately. Changes to this calculation take effect on the next calendar day in the installation time zone.', + 'schedules.workdayModes': + 'Choose either scheduled workday calculation or terminal break stamping for each work schedule.', + 'schedules.scheduledWorkdaySummary': 'Scheduled workday: {start}–{end}', 'schedules.frame': 'Working-time frame', 'schedules.frameStart': 'Frame start', 'schedules.frameEnd': 'Frame end', diff --git a/apps/web/src/app/working-time-i18n.ts b/apps/web/src/app/working-time-i18n.ts index 8b09a6d..398be2d 100644 --- a/apps/web/src/app/working-time-i18n.ts +++ b/apps/web/src/app/working-time-i18n.ts @@ -5,6 +5,12 @@ export const workingTimeDe: Record = { 'Eigene Teammitglieder – der Server begrenzt die Auswahl und Auswertung auf dein zugewiesenes Team.', 'reports.scope.HRAdmin': 'Alle Mitarbeiter:innen – HR kann organisationsweit auswerten.', + 'reports.creditedGross': 'Anrechenbares Brutto', + 'reports.afterRegularEnd': 'Nach regulärem Ende', + 'reports.afterRegularEndDay': 'Tagessumme: {duration}', + 'reports.workdayNotApplicable': 'Nicht anwendbar', + 'reports.workdayMetricsHint': + 'Die Zeit nach regulärem Ende ist die erfasste Dauer in diesem Zeitraum. Abzüge und Soll/Ist-Differenzen stehen in eigenen Feldern.', 'reports.period': 'Zeitraum', 'reports.week': 'Woche', 'reports.month': 'Monat', @@ -92,6 +98,12 @@ export const workingTimeEn: Record = { 'Your team members – the server restricts the selection and report to your assigned team.', 'reports.scope.HRAdmin': 'All employees – HR can report across the organisation.', + 'reports.creditedGross': 'Credited gross time', + 'reports.afterRegularEnd': 'After scheduled end', + 'reports.afterRegularEndDay': 'Day total: {duration}', + 'reports.workdayNotApplicable': 'Not applicable', + 'reports.workdayMetricsHint': + 'Time after scheduled end is the duration recorded in that interval. Break deductions and target/actual differences are shown separately.', 'reports.period': 'Period', 'reports.week': 'Week', 'reports.month': 'Month', diff --git a/apps/web/src/routes/AdminSchedulesPage.spec.tsx b/apps/web/src/routes/AdminSchedulesPage.spec.tsx index cb9b0af..cccddf5 100644 --- a/apps/web/src/routes/AdminSchedulesPage.spec.tsx +++ b/apps/web/src/routes/AdminSchedulesPage.spec.tsx @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { fireEvent, screen, waitFor, within } from '@testing-library/react'; import { renderWithProviders } from '../test-utils'; import { AdminSchedulesPage } from './AdminSchedulesPage'; @@ -76,6 +76,109 @@ it('saves explicitly enabled terminal rules with fixed and short break settings' ); }); +it('saves scheduled workday hours and deductions separately from the approval frame', async () => { + renderWithProviders(); + fireEvent.click(screen.getByRole('button', { name: 'Neuer Plan' })); + fireEvent.change(screen.getByLabelText('Name'), { + target: { value: 'Fixed schedule' }, + }); + fireEvent.change(screen.getByLabelText('Rahmen Ende'), { + target: { value: '23:00' }, + }); + const terminal = screen.getByRole('checkbox', { + name: 'Pausen am Terminal stempeln', + }); + const scheduled = screen.getByRole('checkbox', { + name: 'Regulären Arbeitstag berechnen', + }); + fireEvent.click(terminal); + expect(scheduled.disabled).toBe(true); + fireEvent.click(terminal); + fireEvent.click(scheduled); + expect(terminal.disabled).toBe(true); + expect(screen.getByText(/ab dem nächsten Kalendertag/)).toBeTruthy(); + + const regularEnd = screen.getByLabelText('Reguläres Ende'); + const save = screen.getByRole('button', { + name: 'Speichern', + }); + fireEvent.change(regularEnd, { target: { value: '06:00' } }); + expect(save.disabled).toBe(true); + fireEvent.change(regularEnd, { target: { value: '16:00' } }); + + const dayRules = within( + screen.getByRole('group', { name: 'Pausenabzug pro Arbeitstag' }), + ); + fireEvent.click( + dayRules.getByRole('button', { name: 'Pausenregel hinzufügen' }), + ); + fireEvent.change(dayRules.getByLabelText('Ab Anwesenheit (Minuten)'), { + target: { value: '30' }, + }); + fireEvent.change(dayRules.getByLabelText('Gesamtabzug (Minuten)'), { + target: { value: '30' }, + }); + fireEvent.click(save); + + await waitFor(() => + expect(createWorkSchedule).toHaveBeenCalledWith( + expect.objectContaining({ + frameEnd: '23:00', + breakRules: [], + scheduledWorkday: { + regularStart: '07:00', + regularEnd: '16:00', + breakRules: [{ afterMinutes: 30, breakMinutes: 30 }], + }, + terminalRules: null, + }), + ), + ); +}); + +it('explicitly clears the scheduled workday policy when switching modes', async () => { + workSchedules.mockResolvedValue([ + { + id: 'schedule-1', + name: 'Fixed schedule', + frameStart: '06:00', + frameEnd: '23:00', + workingDays: 31, + coreTimes: [], + isDefault: false, + employeeCount: 0, + breakRules: [{ afterMinutes: 360, breakMinutes: 30 }], + scheduledWorkday: { + regularStart: '07:00', + regularEnd: '16:00', + breakRules: [{ afterMinutes: 30, breakMinutes: 30 }], + }, + }, + ]); + renderWithProviders(); + fireEvent.click(await screen.findByRole('button', { name: 'Bearbeiten' })); + expect( + screen.getByLabelText('Regulärer Beginn').value, + ).toBe('07:00'); + fireEvent.click( + screen.getByRole('checkbox', { name: 'Regulären Arbeitstag berechnen' }), + ); + fireEvent.click( + screen.getByRole('checkbox', { name: 'Pausen am Terminal stempeln' }), + ); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(updateWorkSchedule).toHaveBeenCalledWith( + 'schedule-1', + expect.objectContaining({ + breakRules: [{ afterMinutes: 360, breakMinutes: 30 }], + scheduledWorkday: null, + terminalRules: expect.objectContaining({ startTimes: [] }), + }), + ), + ); +}); + it('preserves existing break rules when editing and allows adding a contract-specific rule', async () => { workSchedules.mockResolvedValue([ { diff --git a/apps/web/src/routes/AdminSchedulesPage.tsx b/apps/web/src/routes/AdminSchedulesPage.tsx index 633d8d4..deebb17 100644 --- a/apps/web/src/routes/AdminSchedulesPage.tsx +++ b/apps/web/src/routes/AdminSchedulesPage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useId, useMemo, useState } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { Plus, Trash2 } from 'lucide-react'; import { Alert, AlertDescription } from '@/components/ui/alert'; @@ -19,6 +19,7 @@ import { api, type CoreTimeWindowDto, type BreakRuleDto, + type ScheduledWorkdayDto, type TerminalRulesDto, type WorkScheduleDto, } from '../api/client'; @@ -56,6 +57,7 @@ interface FormDraft { workingDays: number; breakRules: BreakRuleDto[]; terminalRules?: TerminalRulesDto | null; + scheduledWorkday?: ScheduledWorkdayDto | null; terminalStarts: string; cores: CoreDraft[]; } @@ -82,6 +84,7 @@ function fromSchedule(s: WorkScheduleDto): FormDraft { workingDays: s.workingDays, breakRules: s.breakRules ?? [], terminalRules: s.terminalRules ?? undefined, + scheduledWorkday: s.scheduledWorkday ?? undefined, terminalStarts: s.terminalRules?.startTimes.join(', ') ?? '', cores: s.coreTimes.map((c) => ({ label: c.label ?? '', @@ -130,6 +133,132 @@ function validTerminalRules(rule: TerminalRulesDto, starts: string[]) { ); } +function validBreakRules(rules: BreakRuleDto[]) { + return ( + rules.length <= 50 && + rules.every( + ({ afterMinutes, breakMinutes }) => + Number.isInteger(afterMinutes) && + afterMinutes >= 0 && + afterMinutes <= 1440 && + Number.isInteger(breakMinutes) && + breakMinutes >= 0 && + breakMinutes <= afterMinutes, + ) + ); +} + +function BreakRulesFields({ + label, + hint, + rules, + onChange, +}: { + label: string; + hint: string; + rules: BreakRuleDto[]; + onChange: (rules: BreakRuleDto[]) => void; +}) { + const { t } = useI18n(); + const id = useId(); + return ( +
+
+

+ {label} +

+ +
+

{hint}

+ {rules.map((rule, index) => ( +
+ {(['afterMinutes', 'breakMinutes'] as const).map((field) => ( + + ))} + +
+ ))} +
+ ); +} + +function ScheduledWorkdayFields({ + rule, + onChange, +}: { + rule: ScheduledWorkdayDto; + onChange: (rule: ScheduledWorkdayDto) => void; +}) { + const { t } = useI18n(); + return ( + <> +
+ {(['regularStart', 'regularEnd'] as const).map((field) => ( + + ))} +
+ onChange({ ...rule, breakRules })} + /> + + ); +} + function TerminalRulesFields({ rule, starts, @@ -392,6 +521,14 @@ function ScheduleCard({ {t('schedules.frame')}:{' '} {schedule.frameStart}–{schedule.frameEnd}

+ {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 }) + } + /> + )} +