From 4b19d2aff953fb113ad7300142726df879b046ff Mon Sep 17 00:00:00 2001 From: Patrick Schiller <39913537+patrickschiller@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:24:30 +0100 Subject: [PATCH] feat: capture project activities at PIN terminals Co-authored-by: patrickschiller <39913537+patrickschiller@users.noreply.github.com> Signed-off-by: Patrick Schiller <39913537+patrickschiller@users.noreply.github.com> --- .../src/api/project-activities.e2e.spec.ts | 331 ++++++++ apps/api-e2e/src/api/projects.e2e.spec.ts | 133 ++- apps/api-e2e/src/api/solo-time.e2e.spec.ts | 46 + .../api/terminal-activity-state.e2e.spec.ts | 452 ++++++++++ .../api/terminal-activity-switch.e2e.spec.ts | 783 ++++++++++++++++++ .../src/api/terminal-booking.e2e.spec.ts | 379 ++++++++- apps/api-e2e/src/api/terminals.e2e.spec.ts | 106 +++ .../src/api/time-entry-activities.e2e.spec.ts | 482 +++++++++++ apps/api/openapi.json | 511 +++++++++++- apps/api/src/app/accounts/accounts.service.ts | 56 +- .../src/app/erp-export/erp-export.service.ts | 76 +- .../src/app/projects/projects.controller.ts | 73 ++ apps/api/src/app/projects/projects.dto.ts | 78 +- apps/api/src/app/projects/projects.service.ts | 150 +++- .../app/requests/time-adjustments.service.ts | 6 +- .../terminals/terminal-activity-selection.ts | 83 ++ .../app/terminals/terminal-auth.controller.ts | 34 + .../src/app/terminals/terminal-auth.dto.ts | 58 +- .../app/terminals/terminal-auth.service.ts | 530 +++++++++--- .../app/terminals/terminal-booking.service.ts | 100 ++- .../app/terminals/terminal-security-locks.ts | 4 + apps/api/src/app/terminals/terminals.dto.ts | 35 +- .../src/app/terminals/terminals.service.ts | 27 +- .../time-entries/time-entries.controller.ts | 20 + .../src/app/time-entries/time-entries.dto.ts | 47 +- .../app/time-entries/time-entries.service.ts | 204 ++++- .../time-entry-approvals.service.ts | 23 +- .../work-schedules/work-schedules.service.ts | 11 +- apps/web-e2e/src/terminal-pin.spec.ts | 241 +++++- apps/web/src/api/client.ts | 39 +- apps/web/src/api/generated.ts | 381 ++++++++- apps/web/src/api/terminal-device.spec.ts | 59 ++ apps/web/src/api/terminal-device.ts | 29 +- apps/web/src/app/i18n.tsx | 64 ++ apps/web/src/app/terminal-pin-i18n.ts | 36 + .../timeentries/TimeEntryApprovals.spec.tsx | 2 + .../web/src/routes/AdminProjectsPage.spec.tsx | 363 ++++++-- apps/web/src/routes/AdminProjectsPage.tsx | 4 +- .../src/routes/AdminTerminalsPage.spec.tsx | 85 +- apps/web/src/routes/AdminTerminalsPage.tsx | 99 ++- apps/web/src/routes/BookingPage.spec.tsx | 241 +++++- apps/web/src/routes/BookingPage.tsx | 171 +++- apps/web/src/routes/KioskPage.spec.tsx | 82 +- apps/web/src/routes/KioskPinPanel.spec.tsx | 318 ++++++- apps/web/src/routes/KioskPinPanel.tsx | 390 +++++++-- .../web/src/routes/ProjectActivityCatalog.tsx | 324 ++++++++ .../migration.sql | 49 ++ .../migration.sql | 19 + prisma/schema.prisma | 31 +- 49 files changed, 7339 insertions(+), 526 deletions(-) create mode 100644 apps/api-e2e/src/api/project-activities.e2e.spec.ts create mode 100644 apps/api-e2e/src/api/terminal-activity-state.e2e.spec.ts create mode 100644 apps/api-e2e/src/api/terminal-activity-switch.e2e.spec.ts create mode 100644 apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts create mode 100644 apps/api/src/app/terminals/terminal-activity-selection.ts create mode 100644 apps/web/src/routes/ProjectActivityCatalog.tsx create mode 100644 prisma/migrations/20261127235453_terminal_activity_catalog/migration.sql create mode 100644 prisma/migrations/20261128021500_terminal_activity_redemption/migration.sql diff --git a/apps/api-e2e/src/api/project-activities.e2e.spec.ts b/apps/api-e2e/src/api/project-activities.e2e.spec.ts new file mode 100644 index 0000000..0dc22ea --- /dev/null +++ b/apps/api-e2e/src/api/project-activities.e2e.spec.ts @@ -0,0 +1,331 @@ +import { randomUUID } from 'node:crypto'; +import { ProjectsService } from '../../../api/src/app/projects/projects.service'; +import { + createTestApp, + login, + seedEmployee, + seedProject, + type TestContext, +} from '../support/test-app'; + +describe('Project activity catalog', () => { + let ctx: TestContext; + + beforeAll(async () => { + ctx = await createTestApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.reset(); + }); + + const catalog = (id: string) => `/api/projects/${id}/activities`; + + async function fixture() { + const manager = await seedEmployee(ctx.prisma, { + personalNo: '01', + firstName: 'Project', + lastName: 'Manager', + email: 'catalog-manager@test.local', + role: 'Manager', + }); + const hr = await seedEmployee(ctx.prisma, { + personalNo: '02', + firstName: 'HR', + lastName: 'Admin', + email: 'catalog-hr@test.local', + role: 'HRAdmin', + }); + const worker = await seedEmployee(ctx.prisma, { + personalNo: '03', + firstName: 'Project', + lastName: 'Worker', + email: 'catalog-worker@test.local', + }); + const project = await seedProject(ctx.prisma, { + code: 'CATALOG', + assigneeIds: [worker.id], + }); + return { project, manager, hr, worker }; + } + + it('requires Manager or HRAdmin for every endpoint, including the admin list', async () => { + const { project, worker, manager, hr } = await fixture(); + const path = catalog(project.id); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Sorting' }, + }); + const workerToken = await login(ctx.http, worker.email); + const requests = [ + () => ctx.http.get(path), + () => ctx.http.post(path).send({ name: 'Planting' }), + () => ctx.http.put(`${path}/${activity.id}`).send({ name: 'Packing' }), + () => ctx.http.delete(`${path}/${activity.id}`), + ]; + for (const request of requests) { + await request().expect(401); + await request().auth(workerToken, { type: 'bearer' }).expect(403); + } + + const managerToken = await login(ctx.http, manager.email); + const hrToken = await login(ctx.http, hr.email); + const listed = await ctx.http + .get(path) + .auth(managerToken, { type: 'bearer' }) + .expect(200); + expect(listed.body).toEqual([ + expect.objectContaining({ id: activity.id, name: 'Sorting' }), + ]); + await ctx.http + .post(path) + .auth(hrToken, { type: 'bearer' }) + .send({ name: 'Planting' }) + .expect(201); + }); + + it('rechecks write authority before touching the catalog', async () => { + const { manager, project } = await fixture(); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Sorting' }, + }); + const actor = { + id: manager.id, + email: manager.email, + role: manager.role, + authVersion: manager.authVersion, + }; + await ctx.prisma.employee.update({ + where: { id: manager.id }, + data: { role: 'Employee' }, + }); + const service = ctx.app.get(ProjectsService); + await expect( + service.createActivity(project.id, { name: 'Unauthorized' }, actor), + ).rejects.toMatchObject({ status: 403 }); + await expect( + service.updateActivity( + project.id, + activity.id, + { name: 'Unauthorized' }, + actor, + ), + ).rejects.toMatchObject({ status: 403 }); + await expect( + service.removeActivity(project.id, activity.id, actor), + ).rejects.toMatchObject({ status: 403 }); + expect(await ctx.prisma.activity.findMany()).toEqual([activity]); + }); + + it('validates input and lists both active and inactive entries by their sort order', async () => { + const { project, manager } = await fixture(); + const path = catalog(project.id); + const token = await login(ctx.http, manager.email); + for (const body of [ + { name: ' ' }, + { name: 17 }, + { name: 'Invalid status', isActive: 'false' }, + { name: 'Null status', isActive: null }, + { name: 'Invalid sort', sortOrder: 2.5 }, + { name: 'Out of range', sortOrder: 2_147_483_648 }, + ]) { + await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send(body) + .expect(400); + } + const created = await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: ' Planting ' }) + .expect(201); + expect(created.body).toEqual({ + id: expect.any(String), + projectId: project.id, + name: 'Planting', + isActive: true, + sortOrder: 0, + hasBookings: false, + createdAt: expect.any(String), + updatedAt: expect.any(String), + }); + await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: 'Packing', sortOrder: 2, isActive: false }) + .expect(201); + await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: 'Harvest', sortOrder: 2 }) + .expect(201); + + const updated = await ctx.http + .put(`${path}/${created.body.id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'Weeding', sortOrder: 3 }) + .expect(200); + expect(updated.body).toEqual( + expect.objectContaining({ + name: 'Weeding', + sortOrder: 3, + isActive: true, + }), + ); + const listed = await ctx.http + .get(path) + .auth(token, { type: 'bearer' }) + .expect(200); + expect(listed.body).toEqual([ + expect.objectContaining({ name: 'Harvest', isActive: true }), + expect.objectContaining({ name: 'Packing', isActive: false }), + expect.objectContaining({ name: 'Weeding', isActive: true }), + ]); + }); + + it('enforces names per project on create and rename, even for inactive entries', async () => { + const { project, manager } = await fixture(); + const path = catalog(project.id); + const otherProject = await seedProject(ctx.prisma, { code: 'OTHER' }); + const token = await login(ctx.http, manager.email); + await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting', isActive: false }) + .expect(201); + const created = await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: 'Packing' }) + .expect(201); + await ctx.http + .post(path) + .auth(token, { type: 'bearer' }) + .send({ name: ' Sorting ' }) + .expect(409); + await ctx.http + .put(`${path}/${created.body.id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting' }) + .expect(409); + await ctx.http + .post(catalog(otherProject.id)) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting' }) + .expect(201); + expect( + await ctx.prisma.activity.findUniqueOrThrow({ + where: { id: created.body.id }, + }), + ).toMatchObject({ name: 'Packing' }); + }); + + it('returns 404 for missing projects and never mutates an activity through another project', async () => { + const { project, hr } = await fixture(); + const wrongPath = catalog( + (await seedProject(ctx.prisma, { code: 'OTHER' })).id, + ); + const missingPath = catalog(randomUUID()); + const token = await login(ctx.http, hr.email); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Sorting' }, + }); + const listed = await ctx.http + .get(wrongPath) + .auth(token, { type: 'bearer' }) + .expect(200); + expect(listed.body).toEqual([]); + await ctx.http.get(missingPath).auth(token, { type: 'bearer' }).expect(404); + await ctx.http + .post(missingPath) + .auth(token, { type: 'bearer' }) + .send({ name: 'Invalid' }) + .expect(404); + await ctx.http + .put(`${wrongPath}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'Invalid' }) + .expect(404); + await ctx.http + .delete(`${wrongPath}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .expect(404); + expect( + await ctx.prisma.activity.findUnique({ where: { id: activity.id } }), + ).toEqual(activity); + }); + + it('maps the booking FK rejection to 409 but allows deactivation without altering the booking', async () => { + const { project, worker, manager } = await fixture(); + const path = catalog(project.id); + const token = await login(ctx.http, manager.email); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Sorting', sortOrder: 4 }, + }); + const entry = await ctx.prisma.timeEntry.create({ + data: { + employeeId: worker.id, + projectId: project.id, + activityId: activity.id, + clockIn: new Date('2026-11-23T07:00:00Z'), + }, + }); + + const result = await ctx.http + .delete(`${path}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .expect(409); + expect(result.body.message).toContain('deactivate it instead'); + const deactivated = await ctx.http + .put(`${path}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting', isActive: false }) + .expect(200); + expect(deactivated.body).toMatchObject({ + isActive: false, + sortOrder: 4, + hasBookings: true, + }); + const renamed = await ctx.http + .put(`${path}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting station' }) + .expect(200); + expect(renamed.body).toMatchObject({ + name: 'Sorting station', + isActive: false, + hasBookings: true, + }); + await ctx.http + .delete(`${path}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .expect(409); + expect( + await ctx.prisma.timeEntry.findUnique({ where: { id: entry.id } }), + ).toEqual(entry); + }); + + it('deletes an unbooked activity and clears an employee’s last selection', async () => { + const { project, worker, hr } = await fixture(); + const token = await login(ctx.http, hr.email); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Sorting' }, + }); + await ctx.prisma.employee.update({ + where: { id: worker.id }, + data: { lastTerminalActivityId: activity.id }, + }); + await ctx.http + .delete(`${catalog(project.id)}/${activity.id}`) + .auth(token, { type: 'bearer' }) + .expect(204); + expect( + await ctx.prisma.activity.findUnique({ where: { id: activity.id } }), + ).toBeNull(); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ where: { id: worker.id } }), + ).toMatchObject({ lastTerminalActivityId: null }); + }); +}); diff --git a/apps/api-e2e/src/api/projects.e2e.spec.ts b/apps/api-e2e/src/api/projects.e2e.spec.ts index 1b9abec..245a191 100644 --- a/apps/api-e2e/src/api/projects.e2e.spec.ts +++ b/apps/api-e2e/src/api/projects.e2e.spec.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto'; import { createTestApp, login, @@ -381,53 +382,117 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { expect(res.body.serviceOrders[0].bookedMinutes).toBe(120); }); - it('project report lists activities for Manager/HRAdmin only', async () => { - const { manager, worker } = await fixture(); + it('project report prefers catalog names and keeps legacy activities and gross hours for Manager/HRAdmin only', async () => { + const { hr, manager, worker } = await fixture(); const managerToken = await login(ctx.http, manager.email); + const hrToken = await login(ctx.http, hr.email); const workerToken = await login(ctx.http, worker.email); const project = await seedProject(ctx.prisma, { code: 'P-REPORT', + name: 'Customer project', assigneeIds: [worker.id], - serviceOrders: [{ orderNo: 'SA-1', title: 'Beratung' }], }); - const order = project.serviceOrders[0]; - const clockIn = new Date(Date.now() - 3 * 60 * 60 * 1000); - await ctx.prisma.timeEntry.create({ - data: { - employeeId: worker.id, - clockIn, - clockOut: new Date(clockIn.getTime() + 90 * 60 * 1000), - status: 'Approved', - projectId: project.id, - serviceOrderId: order.id, - activity: 'Kundentermin vorbereitet', - }, + const entry = { employeeId: worker.id, projectId: project.id }; + const catalog = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Original catalog name' }, + }); + const next = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Packen' }, + }); + const captureGroupId = randomUUID(); + const day = '2026-07-01'; + const at = (time: string) => new Date(`${day}T${time}+02:00`); + await ctx.prisma.timeEntry.createMany({ + data: [ + { + ...entry, + clockIn: at('08:00:00'), + clockOut: at('12:00:30'), + status: 'Approved', + source: 'Terminal', + captureGroupId, + activityId: catalog.id, + activity: 'Old free text', + }, + { + ...entry, + clockIn: at('12:00:30'), + clockOut: at('16:00:00'), + status: 'Pending', + source: 'Terminal', + captureGroupId, + activityId: next.id, + }, + ], + }); + const catalogName = 'Sortieren, prüfen; "Süd"'; + await ctx.prisma.activity.update({ + where: { id: catalog.id }, + data: { name: catalogName, isActive: false }, + }); + const order = await ctx.prisma.serviceOrder.create({ + data: { projectId: project.id, orderNo: 'SA-1', title: 'Beratung' }, + }); + const freeText = 'Kundentermin vorbereitet'; + await ctx.prisma.timeEntry.createMany({ + data: [ + { + ...entry, + clockIn: at('16:30:00'), + clockOut: at('18:00:00'), + serviceOrderId: order.id, + status: 'Approved', + activity: freeText, + }, + { + ...entry, + clockIn: at('18:00:00'), + clockOut: at('18:30:00'), + serviceOrderId: order.id, + status: 'Approved', + }, + ], }); - await ctx.http.get(`/api/projects/${project.id}/report`).expect(401); + const report = `/api/projects/${project.id}/report`; + await ctx.http.get(report).expect(401); await ctx.http - .get(`/api/projects/${project.id}/report`) - .set('Authorization', `Bearer ${workerToken}`) + .get(report) + .auth(workerToken, { type: 'bearer' }) .expect(403); - const res = await ctx.http - .get(`/api/projects/${project.id}/report`) - .set('Authorization', `Bearer ${managerToken}`) - .expect(200); - expect(res.body.projectCode).toBe('P-REPORT'); - expect(res.body.rows.length).toBe(1); - expect(res.body.rows[0].employeeName).toBe('Willi Worker'); - expect(res.body.rows[0].orderNo).toBe('SA-1'); - expect(res.body.rows[0].grossMinutes).toBe(90); - expect(res.body.rows[0].activity).toBe('Kundentermin vorbereitet'); - expect(res.body.totalGrossMinutes).toBe(90); + const row = { date: day, employeeName: 'Willi Worker' }; + const noOrder = { orderNo: null, orderTitle: null }; + const withOrder = { orderNo: order.orderNo, orderTitle: order.title }; + for (const token of [managerToken, hrToken]) { + const res = await ctx.http + .get(report) + .auth(token, { type: 'bearer' }) + .expect(200); + expect(res.body).toEqual({ + projectCode: project.code, + projectName: project.name, + from: null, + to: null, + rows: [ + { ...row, ...noOrder, grossMinutes: 240.5, activity: catalogName }, + { ...row, ...noOrder, grossMinutes: 239.5, activity: next.name }, + { ...row, ...withOrder, grossMinutes: 90, activity: freeText }, + { ...row, ...withOrder, grossMinutes: 30, activity: null }, + ], + totalGrossMinutes: 600, + }); + } // A window in the past excludes the entry. const filtered = await ctx.http - .get( - `/api/projects/${project.id}/report?from=2000-01-01T00:00:00.000Z&to=2000-12-31T00:00:00.000Z`, - ) - .set('Authorization', `Bearer ${managerToken}`) + .get(report) + .auth(managerToken, { type: 'bearer' }) + .query({ + from: '2000-01-01T00:00:00.000Z', + to: '2000-12-31T00:00:00.000Z', + }) .expect(200); - expect(filtered.body.rows.length).toBe(0); + expect(filtered.body.rows).toEqual([]); + expect(filtered.body.totalGrossMinutes).toBe(0); }); }); diff --git a/apps/api-e2e/src/api/solo-time.e2e.spec.ts b/apps/api-e2e/src/api/solo-time.e2e.spec.ts index d49ad39..a27ea8e 100644 --- a/apps/api-e2e/src/api/solo-time.e2e.spec.ts +++ b/apps/api-e2e/src/api/solo-time.e2e.spec.ts @@ -122,6 +122,52 @@ describe('Solo working-time actions', () => { .expect(201); }); + it('preserves a historical catalog activity on correction unless its project changes', async () => { + const { owner, auth } = await fixture(); + const project = await seedProject(ctx.prisma, { + code: 'HISTORICAL', + assigneeIds: [owner.id], + }); + const activity = await ctx.prisma.activity.create({ + data: { projectId: project.id, name: 'Catalog activity' }, + }); + const created = await ctx.http + .post('/api/timeentries/manual') + .set('Authorization', auth) + .send({ ...interval, projectId: project.id, activity: 'Historical text' }) + .expect(201); + const id: string = created.body.id; + await ctx.prisma.timeEntry.update({ + where: { id }, + data: { activityId: activity.id }, + }); + + const same = await ctx.http + .patch(`/api/timeentries/${id}/correct`) + .set('Authorization', auth) + .send({ ...interval, revision: 0, reason: 'Retain project' }) + .expect(200); + expect(same.body).toMatchObject({ + projectId: project.id, + activityId: activity.id, + catalogActivityName: activity.name, + activity: 'Historical text', + }); + + const unassigned = await ctx.http + .patch(`/api/timeentries/${id}/correct`) + .set('Authorization', auth) + .send({ ...interval, revision: 1, reason: 'Unassign', projectId: null }) + .expect(200); + expect(unassigned.body).toMatchObject({ + ...interval, + projectId: null, + activityId: null, + catalogActivityName: null, + activity: 'Historical text', + }); + }); + it('serializes concurrent manual inserts and does not create a losing audit row', async () => { const { auth } = await fixture(); const responses = await Promise.all( diff --git a/apps/api-e2e/src/api/terminal-activity-state.e2e.spec.ts b/apps/api-e2e/src/api/terminal-activity-state.e2e.spec.ts new file mode 100644 index 0000000..174c5bf --- /dev/null +++ b/apps/api-e2e/src/api/terminal-activity-state.e2e.spec.ts @@ -0,0 +1,452 @@ +import { createHash } from 'node:crypto'; +import { listEligibleTerminalActivities } from '../../../api/src/app/terminals/terminal-activity-selection'; +import { + createTestApp, + login, + seedEmployee, + seedProject, + type TestContext, +} from '../support/test-app'; + +jest.mock('../../../api/src/app/terminals/terminal-activity-selection', () => { + const eligibility = jest.requireActual< + typeof import('../../../api/src/app/terminals/terminal-activity-selection') + >('../../../api/src/app/terminals/terminal-activity-selection'); + return { + ...eligibility, + listEligibleTerminalActivities: jest.fn( + eligibility.listEligibleTerminalActivities, + ), + }; +}); + +describe('Device- and grant-bound terminal activity state', () => { + let ctx: TestContext; + const kiosk = '/api/terminals/kiosk'; + const empty = { enabled: true, activities: [], selectedActivityId: null }; + + beforeAll(async () => { + ctx = await createTestApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.reset(); + }); + + async function pair(terminalId: string, hrToken: string) { + const pairing = await ctx.http + .post(`/api/terminals/${terminalId}/pairing`) + .auth(hrToken, { type: 'bearer' }) + .expect(201); + const paired = await ctx.http + .post('/api/terminals/pair') + .send({ pairingCode: pairing.body.pairingCode }) + .expect(201); + return paired.body.deviceToken as string; + } + + async function terminal(hrToken: string, enabled?: boolean) { + const created = await ctx.http + .post('/api/terminals') + .auth(hrToken, { type: 'bearer' }) + .send({ + name: 'Synthetic activity terminal', + displayText: 'Synthetic kiosk', + locationLabel: 'Synthetic reception', + timeZone: 'Europe/Berlin', + enforceGeofence: false, + isActive: true, + allowedAuthMethods: ['QR', 'PIN'], + ...(enabled === undefined ? {} : { activitySelectionEnabled: enabled }), + }) + .expect(201); + const terminalId = created.body.id as string; + return { terminalId, device: await pair(terminalId, hrToken) }; + } + + async function worker(hrToken: string, personalNo: string) { + const employee = await seedEmployee(ctx.prisma, { + personalNo, + firstName: 'Test', + lastName: 'Worker', + email: `worker-${personalNo}@activity-state.test`, + }); + const reset = await ctx.http + .post(`/api/employees/${employee.id}/terminal-credentials/pin/reset`) + .auth(hrToken, { type: 'bearer' }) + .send({}) + .expect(201); + return { id: employee.id, personalNo, pin: reset.body.pin as string }; + } + + async function fixture(enabled = true) { + const hr = await seedEmployee(ctx.prisma, { + personalNo: 'ACTIVITY-HR', + firstName: 'Test', + lastName: 'Admin', + email: 'hr@activity-state.test', + role: 'HRAdmin', + }); + const hrToken = await login(ctx.http, hr.email); + return { + hrToken, + worker: await worker(hrToken, '000031'), + ...(await terminal(hrToken, enabled ? true : undefined)), + }; + } + + const challenge = (device: string) => + ctx.http.post(`${kiosk}/challenge`).auth(device, { type: 'bearer' }); + + function identify( + device: string, + payload: string, + personalNo: string, + pin: string, + ) { + return ctx.http + .post(`${kiosk}/identify`) + .auth(device, { type: 'bearer' }) + .send({ method: 'PIN', challengePayload: payload, personalNo, pin }); + } + + async function grant( + device: string, + employee: { personalNo: string; pin: string }, + ) { + const issued = await challenge(device).expect(201); + const found = await identify( + device, + issued.body.payload, + employee.personalNo, + employee.pin, + ).expect(201); + return found.body.grant as string; + } + + function state( + device: string, + grantToken: string, + extra: Record = {}, + ) { + return ctx.http + .post(`${kiosk}/activity-state`) + .auth(device, { type: 'bearer' }) + .send({ grant: grantToken, ...extra }); + } + + function book(device: string, grantToken: string) { + return ctx.http + .post(`${kiosk}/book`) + .auth(device, { type: 'bearer' }) + .send({ grant: grantToken, action: 'clock-in' }); + } + + async function catalog( + employeeId: string, + code: string, + options: { + projectActive?: boolean; + activityActive?: boolean; + orderActive?: boolean; + assigned?: boolean; + } = {}, + ) { + const { + projectActive, + activityActive, + orderActive, + assigned = true, + } = options; + const project = await seedProject(ctx.prisma, { + code, + name: `Project ${code}`, + isActive: projectActive, + assigneeIds: assigned ? [employeeId] : [], + serviceOrders: + orderActive === undefined + ? [] + : [ + { + orderNo: 'ORDER-1', + title: 'Synthetic service order', + isActive: orderActive, + }, + ], + }); + const activity = await ctx.prisma.activity.create({ + data: { + projectId: project.id, + name: `Activity ${code}`, + isActive: activityActive, + }, + }); + return { + project, + activity, + dto: { + id: activity.id, + name: activity.name, + projectId: project.id, + projectName: project.name, + }, + }; + } + + const remember = (employeeId: string, activityId: string) => + ctx.prisma.employee.update({ + where: { id: employeeId }, + data: { lastTerminalActivityId: activityId }, + }); + + function expectNoActivityState(body: Record) { + expect(body).not.toHaveProperty('activities'); + expect(body).not.toHaveProperty('selectedActivityId'); + } + + it('shows only active activities of active assigned projects without active orders and preselects the eligible remembered item', async () => { + const f = await fixture(); + const preferred = await catalog(f.worker.id, 'NO-ORDERS'); + const inactiveOrder = await catalog(f.worker.id, 'INACTIVE-ORDER', { + orderActive: false, + }); + await catalog(f.worker.id, 'INACTIVE-ACTIVITY', { activityActive: false }); + await catalog(f.worker.id, 'INACTIVE-PROJECT', { projectActive: false }); + await catalog(f.worker.id, 'UNASSIGNED', { assigned: false }); + await catalog(f.worker.id, 'ACTIVE-ORDER', { orderActive: true }); + const archived = await catalog(f.worker.id, 'ARCHIVED-CUSTOMER'); + await ctx.prisma.project.update({ + where: { id: archived.project.id }, + data: { + customer: { create: { name: 'Archived Customer', isActive: false } }, + }, + }); + await remember(f.worker.id, preferred.activity.id); + + const response = await state( + f.device, + await grant(f.device, f.worker), + ).expect(200); + expect(response.headers['cache-control']).toContain('no-store'); + expect(response.body).toEqual({ + enabled: true, + activities: expect.arrayContaining([preferred.dto, inactiveOrder.dto]), + selectedActivityId: preferred.activity.id, + }); + expect(response.body.activities).toHaveLength(2); + expect(await ctx.prisma.timeEntry.count()).toBe(0); + expect(await ctx.prisma.terminalChallengeRedemption.count()).toBe(0); + expect( + (await ctx.prisma.terminalBookingGrant.findFirstOrThrow()).consumedAt, + ).toBeNull(); + }); + + it('immediately drops a remembered choice when catalog eligibility changes, even on the same grant', async () => { + const f = await fixture(); + const { project, activity, dto } = await catalog(f.worker.id, 'LIVE', { + orderActive: false, + }); + await remember(f.worker.id, activity.id); + const token = await grant(f.device, f.worker); + const read = async () => (await state(f.device, token).expect(200)).body; + const offered = { + enabled: true, + activities: [dto], + selectedActivityId: activity.id, + }; + expect(await read()).toEqual(offered); + + await ctx.prisma.activity.update({ + where: { id: activity.id }, + data: { isActive: false }, + }); + expect(await read()).toEqual(empty); + await ctx.prisma.activity.update({ + where: { id: activity.id }, + data: { isActive: true }, + }); + + await ctx.prisma.project.update({ + where: { id: project.id }, + data: { isActive: false }, + }); + expect(await read()).toEqual(empty); + await ctx.prisma.project.update({ + where: { id: project.id }, + data: { isActive: true }, + }); + + await ctx.prisma.serviceOrder.updateMany({ + where: { projectId: project.id }, + data: { isActive: true }, + }); + expect(await read()).toEqual(empty); + await ctx.prisma.serviceOrder.updateMany({ + where: { projectId: project.id }, + data: { isActive: false }, + }); + expect(await read()).toEqual(offered); + + await ctx.prisma.projectAssignment.deleteMany({ + where: { projectId: project.id, employeeId: f.worker.id }, + }); + expect(await read()).toEqual(empty); + }); + + it('offers no selection by default and honors a live terminal toggle without consuming the grant', async () => { + const f = await fixture(false); + const choice = await catalog(f.worker.id, 'DEFAULT-OFF'); + await remember(f.worker.id, choice.activity.id); + const token = await grant(f.device, f.worker); + const read = async () => (await state(f.device, token).expect(200)).body; + expect(await read()).toEqual({ ...empty, enabled: false }); + await ctx.http + .put(`/api/terminals/${f.terminalId}`) + .auth(f.hrToken, { type: 'bearer' }) + .send({ activitySelectionEnabled: true }) + .expect(200); + expect(await read()).toEqual({ + enabled: true, + activities: [choice.dto], + selectedActivityId: choice.activity.id, + }); + const receipt = await book(f.device, token).expect(201); + expect((await book(f.device, token).expect(201)).body).toEqual( + receipt.body, + ); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + employeeId: f.worker.id, + projectId: null, + activityId: null, + }); + expectNoActivityState((await state(f.device, token).expect(409)).body); + }); + + it('does not expose activity state to display, challenge, invalid PIN or a different device', async () => { + const f = await fixture(); + const choice = await catalog(f.worker.id, 'PRIVATE'); + await remember(f.worker.id, choice.activity.id); + const foreign = await terminal(f.hrToken, true); + const qr = await ctx.http + .get(kiosk) + .auth(f.device, { type: 'bearer' }) + .expect(200); + const issued = await challenge(f.device).expect(201); + const wrongPin = `${f.worker.pin[0] === '0' ? '1' : '0'}${f.worker.pin.slice(1)}`; + const invalid = await identify( + f.device, + issued.body.payload, + f.worker.personalNo, + wrongPin, + ).expect(401); + const token = await grant(f.device, f.worker); + const noDevice = await ctx.http + .post(`${kiosk}/activity-state`) + .send({ grant: token }) + .expect(401); + const grantAsDevice = await state(token, token).expect(401); + const noGrant = await ctx.http + .post(`${kiosk}/activity-state`) + .auth(f.device, { type: 'bearer' }) + .send({}) + .expect(400); + const invalidGrant = await state(f.device, issued.body.payload).expect(409); + const foreignDevice = await state(foreign.device, token).expect(409); + const replacement = await pair(f.terminalId, f.hrToken); + const wrongPairing = await state(replacement, token).expect(409); + const revokedPairing = await state(f.device, token).expect(401); + + for (const response of [ + qr, + issued, + invalid, + noDevice, + grantAsDevice, + noGrant, + invalidGrant, + foreignDevice, + wrongPairing, + revokedPairing, + ]) { + expectNoActivityState(response.body); + expect(JSON.stringify(response.body)).not.toContain(choice.activity.id); + expect(JSON.stringify(response.body)).not.toContain(choice.activity.name); + } + }); + + it('uses only the grant employee even if another employee is supplied in the request', async () => { + const f = await fixture(); + const other = await worker(f.hrToken, '000032'); + const own = await catalog(f.worker.id, 'OWN'); + const foreign = await catalog(other.id, 'FOREIGN'); + await remember(f.worker.id, own.activity.id); + await remember(other.id, foreign.activity.id); + const first = await grant(f.device, f.worker); + const second = await grant(f.device, other); + + expect( + ( + await state(f.device, first, { + employeeId: other.id, + personalNo: other.personalNo, + }).expect(200) + ).body, + ).toEqual({ + enabled: true, + activities: [own.dto], + selectedActivityId: own.activity.id, + }); + expect((await state(f.device, second).expect(200)).body).toEqual({ + enabled: true, + activities: [foreign.dto], + selectedActivityId: foreign.activity.id, + }); + }); + + it('rejects both expired grants and an unread grant revoked by a PIN reset', async () => { + const f = await fixture(); + const choice = await catalog(f.worker.id, 'REVOKED'); + await remember(f.worker.id, choice.activity.id); + const expired = await grant(f.device, f.worker); + await ctx.prisma.terminalBookingGrant.update({ + where: { tokenHash: createHash('sha256').update(expired).digest('hex') }, + data: { expiresAt: new Date(Date.now() - 1_000) }, + }); + expectNoActivityState((await state(f.device, expired).expect(409)).body); + + const revoked = await grant(f.device, f.worker); + await ctx.http + .post(`/api/employees/${f.worker.id}/terminal-credentials/pin/reset`) + .auth(f.hrToken, { type: 'bearer' }) + .send({}) + .expect(201); + expectNoActivityState((await state(f.device, revoked).expect(409)).body); + }); + + it('keeps the same grant usable for basic clock-in if the optional catalog cannot be loaded', async () => { + const f = await fixture(); + const choice = await catalog(f.worker.id, 'UNAVAILABLE'); + await remember(f.worker.id, choice.activity.id); + const token = await grant(f.device, f.worker); + jest + .mocked(listEligibleTerminalActivities) + .mockRejectedValueOnce(new Error('Synthetic catalog outage')); + + const failure = await state(f.device, token).expect(500); + expectNoActivityState(failure.body); + expect(JSON.stringify(failure.body)).not.toContain( + 'Synthetic catalog outage', + ); + expect( + (await ctx.prisma.terminalBookingGrant.findFirstOrThrow()).consumedAt, + ).toBeNull(); + await book(f.device, token).expect(201); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + employeeId: f.worker.id, + projectId: null, + activityId: null, + }); + }); +}); diff --git a/apps/api-e2e/src/api/terminal-activity-switch.e2e.spec.ts b/apps/api-e2e/src/api/terminal-activity-switch.e2e.spec.ts new file mode 100644 index 0000000..6a7fa7e --- /dev/null +++ b/apps/api-e2e/src/api/terminal-activity-switch.e2e.spec.ts @@ -0,0 +1,783 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { + createTestApp, + login, + seedEmployee, + seedProject, + type TestContext, +} from '../support/test-app'; + +describe('Authenticated terminal activity choice and switch', () => { + const kiosk = '/api/terminals/kiosk'; + const day = '2026-11-23'; + const at = (time: string) => + new Date(`${day}T${time.length === 5 ? `${time}:00` : time}+01:00`); + const coordinates = { + latitude: 49.7913, + longitude: 9.9534, + accuracyMeters: 8, + }; + const position = () => ({ + ...coordinates, + positionTimestamp: new Date().toISOString(), + }); + const breakRules = [{ afterMinutes: 360, breakMinutes: 30 }]; + let ctx: TestContext; + + beforeAll(async () => { + ctx = await createTestApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.reset(); + }); + afterEach(() => { + jest.useRealTimers(); + }); + + function setTime(time: string) { + jest.useFakeTimers({ + doNotFake: ['nextTick', 'setImmediate', 'setInterval', 'setTimeout'], + }); + jest.setSystemTime(at(time)); + } + + async function terminal( + hrToken: string, + { enabled = true, geofenced = false } = {}, + ) { + const created = await ctx.http + .post('/api/terminals') + .auth(hrToken, { type: 'bearer' }) + .send({ + name: enabled ? 'Activity switch kiosk' : 'Plain clock-out kiosk', + displayText: 'Synthetic kiosk', + locationLabel: 'Synthetic location', + timeZone: 'Europe/Berlin', + enforceGeofence: geofenced, + isActive: true, + allowedAuthMethods: ['QR', 'PIN'], + activitySelectionEnabled: enabled, + ...(geofenced + ? { + latitude: coordinates.latitude, + longitude: coordinates.longitude, + radiusMeters: 100, + maxAccuracyMeters: 50, + } + : {}), + }) + .expect(201); + const terminalId = created.body.id as string; + const pairing = await ctx.http + .post(`/api/terminals/${terminalId}/pairing`) + .auth(hrToken, { type: 'bearer' }) + .expect(201); + const paired = await ctx.http + .post('/api/terminals/pair') + .send({ pairingCode: pairing.body.pairingCode }) + .expect(201); + return { terminalId, deviceToken: paired.body.deviceToken as string }; + } + + async function fixture(options: Parameters[1] = {}) { + const hr = await seedEmployee(ctx.prisma, { + personalNo: 'ACTIVITY-SWITCH-HR', + firstName: 'Test', + lastName: 'Admin', + email: 'hr@activity-switch.test', + role: 'HRAdmin', + }); + const schedule = await ctx.prisma.workSchedule.create({ + data: { + name: 'Synthetic shift policy', + frameStart: '07:00', + frameEnd: '23:00', + breakRules, + }, + }); + const employee = await seedEmployee(ctx.prisma, { + personalNo: '000039', + firstName: 'Test', + lastName: 'Worker', + email: 'worker@activity-switch.test', + workScheduleId: schedule.id, + }); + const hrToken = await login(ctx.http, hr.email); + const pin = await ctx.http + .post(`/api/employees/${employee.id}/terminal-credentials/pin/reset`) + .auth(hrToken, { type: 'bearer' }) + .send({}) + .expect(201); + return { + hr, + employee, + hrToken, + schedule, + pin: pin.body.pin as string, + ...(await terminal(hrToken, options)), + }; + } + + async function catalog(employeeId: string, code: string) { + const project = await seedProject(ctx.prisma, { + code, + assigneeIds: [employeeId], + }); + return ctx.prisma.activity.create({ + data: { name: `Activity ${code}`, projectId: project.id }, + }); + } + + function identify( + f: Awaited>, + challengePayload: string, + ) { + return ctx.http + .post(`${kiosk}/identify`) + .auth(f.deviceToken, { type: 'bearer' }) + .send({ + method: 'PIN', + personalNo: f.employee.personalNo, + pin: f.pin, + challengePayload, + }); + } + + async function grant(f: Awaited>) { + const challenge = await ctx.http + .post(`${kiosk}/challenge`) + .auth(f.deviceToken, { type: 'bearer' }) + .expect(201); + const challengePayload = challenge.body.payload as string; + const identified = await identify(f, challengePayload).expect(201); + return { + challengePayload, + ...(identified.body as { + grant: string; + action: 'clock-in' | 'clock-out'; + }), + }; + } + + function activity( + device: string, + token: string, + activityId: unknown, + extra: Record = {}, + ) { + return ctx.http + .post(`${kiosk}/activity`) + .auth(device, { type: 'bearer' }) + .send({ grant: token, activityId, ...extra }); + } + + function book( + device: string, + token: string, + action: 'clock-in' | 'clock-out', + extra: Record = {}, + ) { + return ctx.http + .post(`${kiosk}/book`) + .auth(device, { type: 'bearer' }) + .send({ grant: token, action, ...extra }); + } + + function activityState(device: string, token: string) { + return ctx.http + .post(`${kiosk}/activity-state`) + .auth(device, { type: 'bearer' }) + .send({ grant: token }) + .expect(200); + } + + async function remembered(employeeId: string) { + return ( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: employeeId }, + select: { lastTerminalActivityId: true }, + }) + ).lastTerminalActivityId; + } + + function storedGrant(token: string) { + return ctx.prisma.terminalBookingGrant.findUniqueOrThrow({ + where: { tokenHash: createHash('sha256').update(token).digest('hex') }, + }); + } + + it('remembers a no-entry choice without clocking in and keeps physical booking separate', async () => { + setTime('08:00'); + const f = await fixture(); + const other = await terminal(f.hrToken, { enabled: false }); + const chosen = await catalog(f.employee.id, 'REMEMBERED'); + const session = await grant(f); + const siblingGrant = await identify(f, session.challengePayload).expect( + 201, + ); + + await ctx.http + .post(`${kiosk}/activity`) + .send({ grant: session.grant, activityId: chosen.id }) + .expect(401); + await activity(f.hrToken, session.grant, chosen.id).expect(401); + await activity(other.deviceToken, session.grant, chosen.id).expect(409); + for (const invalid of [undefined, null, 'not a UUID', [chosen.id]]) { + await activity(f.deviceToken, session.grant, invalid).expect(400); + } + expect(await remembered(f.employee.id)).toBeNull(); + + const result = await activity( + f.deviceToken, + session.grant, + chosen.id, + ).expect(200); + expect(result.body).toEqual({ outcome: 'remembered' }); + expect(result.headers['cache-control']).toContain('no-store'); + expect(await remembered(f.employee.id)).toBe(chosen.id); + expect(await ctx.prisma.timeEntry.count()).toBe(0); + expect((await storedGrant(session.grant)).consumedAt).toEqual(at('08:00')); + const replay = await activity( + f.deviceToken, + session.grant, + chosen.id, + ).expect(409); + expect(replay.body.code).toBe('TERMINAL_GRANT_CONSUMED'); + const siblingReplay = await book( + f.deviceToken, + siblingGrant.body.grant, + 'clock-in', + ).expect(409); + expect(siblingReplay.body.code).toBe('TERMINAL_CHALLENGE_REPLAYED'); + + const next = await grant(f); + expect(next.action).toBe('clock-in'); + const preference = await activityState(f.deviceToken, next.grant); + expect(preference.body.selectedActivityId).toBe(chosen.id); + await book(f.deviceToken, next.grant, 'clock-in').expect(201); + setTime('09:00'); + const stop = await grant(f); + expect(stop.action).toBe('clock-out'); + // Clock-out never requires choosing or even loading activities first. + const receipt = await book(f.deviceToken, stop.grant, 'clock-out').expect( + 201, + ); + expect(receipt.body).toMatchObject({ + action: 'clock-out', + bookedAt: at('09:00').toISOString(), + }); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + clockIn: at('08:00'), + clockOut: at('09:00'), + terminalId: f.terminalId, + clockOutTerminalId: f.terminalId, + projectId: null, + activityId: null, + captureGroupId: null, + }); + expect(await remembered(f.employee.id)).toBe(chosen.id); + }); + + it('allocates one 30-minute break across an eight-hour shift, even in filtered results, without copying GPS to a logical boundary', async () => { + setTime('08:00'); + const f = await fixture({ geofenced: true }); + const plain = await terminal(f.hrToken, { enabled: false }); + const first = await catalog(f.employee.id, 'FIRST'); + const second = await catalog(f.employee.id, 'SECOND'); + await ctx.prisma.project.update({ + where: { id: second.projectId }, + data: { defaultBillable: true }, + }); + const accountPath = `/api/accounts/${f.employee.id}`; + const emptyBalance = await ctx.http + .get(accountPath) + .auth(f.hrToken, { type: 'bearer' }) + .expect(200); + + const opening = await grant(f); + expect(opening.action).toBe('clock-in'); + const choices = await activityState(f.deviceToken, opening.grant); + expect(choices.body).toMatchObject({ + enabled: true, + selectedActivityId: null, + activities: expect.arrayContaining([ + expect.objectContaining({ id: first.id }), + expect.objectContaining({ id: second.id }), + ]), + }); + const originalReceipt = await book( + f.deviceToken, + opening.grant, + 'clock-in', + { + activityId: first.id, + ...position(), + }, + ).expect(201); + const original = await ctx.prisma.timeEntry.findFirstOrThrow(); + expect( + (await book(f.deviceToken, opening.grant, 'clock-in').expect(201)).body, + ).toEqual(originalReceipt.body); + + // A schedule change does not change the break snapshot already captured + // for the attendance, even on segments created after the change. + await ctx.prisma.workSchedule.update({ + where: { id: f.schedule.id }, + data: { breakRules: [] }, + }); + setTime('12:00'); + const session = await grant(f); + expect(session.action).toBe('clock-out'); + const switchingChoices = await activityState(f.deviceToken, session.grant); + expect(switchingChoices.body).toMatchObject({ + selectedActivityId: first.id, + activities: expect.arrayContaining([ + expect.objectContaining({ id: second.id }), + ]), + }); + await activity(f.deviceToken, session.grant, second.id).expect(400); + await activity(f.deviceToken, session.grant, second.id, { + ...position(), + latitude: 50.1, + }).expect(403); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toEqual(original); + expect((await storedGrant(session.grant)).consumedAt).toBeNull(); + + const switched = await activity(f.deviceToken, session.grant, second.id, { + ...position(), + employeeId: randomUUID(), + projectId: randomUUID(), + serviceOrderId: randomUUID(), + clockIn: at('11:00').toISOString(), + billable: false, + }).expect(200); + expect(switched.body).toEqual({ outcome: 'switched' }); + const [start, open] = await ctx.prisma.timeEntry.findMany({ + orderBy: { clockIn: 'asc' }, + }); + expect(start).toMatchObject({ + id: original.id, + employeeId: f.employee.id, + clockIn: at('08:00'), + clockOut: at('12:00'), + revision: original.revision + 1, + activityId: first.id, + projectId: first.projectId, + terminalId: f.terminalId, + clockInChallengeId: original.clockInChallengeId, + latitude: original.latitude, + longitude: original.longitude, + positionTimestamp: at('08:00'), + status: 'Approved', + requiresApproval: false, + breakRules, + }); + expect(Number(start.latitude)).toBeCloseTo(coordinates.latitude); + expect(Number(start.longitude)).toBeCloseTo(coordinates.longitude); + expect(start.captureGroupId).toEqual(expect.any(String)); + expect(start).toMatchObject({ + clockOutTerminalId: null, + clockOutChallengeId: null, + clockOutLatitude: null, + clockOutLongitude: null, + clockOutPositionTimestamp: null, + clockOutTerminalLocationLabel: null, + }); + expect(open).toMatchObject({ + employeeId: f.employee.id, + captureGroupId: start.captureGroupId, + clockIn: start.clockOut, + clockOut: null, + status: 'Open', + source: 'Terminal', + approvalMode: 'Team', + activityId: second.id, + projectId: second.projectId, + serviceOrderId: null, + billable: true, + breakRules, + latitude: null, + longitude: null, + positionTimestamp: null, + terminalId: null, + clockInChallengeId: null, + terminalLocationLabel: null, + }); + expect(await remembered(f.employee.id)).toBe(second.id); + + const audit = await ctx.prisma.terminalAuditEvent.findFirstOrThrow({ + where: { event: 'ActivitySelectionAccepted' }, + }); + expect(audit).toMatchObject({ + employeeId: f.employee.id, + terminalId: f.terminalId, + method: 'PIN', + action: null, + result: 'SUCCESS', + }); + for (const secret of [ + session.grant, + second.id, + second.name, + second.projectId, + ]) + expect(audit.canonicalPayload).not.toContain(secret); + expect(audit.canonicalPayload).not.toMatch( + /latitude|longitude|accuracyMeters|positionTimestamp/, + ); + + setTime('16:00'); + const stopping = await grant({ ...f, ...plain }); + expect(stopping.action).toBe('clock-out'); + await book(plain.deviceToken, stopping.grant, 'clock-out').expect(201); + const end = await ctx.prisma.timeEntry.findUniqueOrThrow({ + where: { id: open.id }, + }); + expect(end).toMatchObject({ + clockOut: at('16:00'), + clockOutTerminalId: plain.terminalId, + activityId: second.id, + projectId: second.projectId, + status: 'Approved', + clockOutLatitude: null, + }); + expect(end.clockOutChallengeId).toEqual(expect.any(String)); + expect(await ctx.prisma.timeEntry.count()).toBe(2); + const physicalArrival = + await ctx.prisma.terminalChallengeRedemption.findFirstOrThrow({ + where: { timeEntryId: original.id, action: 'clock-in' }, + }); + expect(physicalArrival).toMatchObject({ + challengeId: original.clockInChallengeId, + action: 'clock-in', + timeEntryId: original.id, + }); + + const reportToken = await login(ctx.http, f.hr.email); + const finishedBalance = await ctx.http + .get(accountPath) + .auth(reportToken, { type: 'bearer' }) + .expect(200); + expect( + finishedBalance.body.overtimeMinutes - emptyBalance.body.overtimeMinutes, + ).toBe(450); + const report = await ctx.http + .get('/api/reports/working-times') + .auth(reportToken, { type: 'bearer' }) + .query({ from: day, to: day, employeeId: f.employee.id }) + .expect(200); + expect(report.body.totals).toEqual({ + grossMinutes: 480, + breakMinutes: 30, + netMinutes: 450, + }); + const summary = { grossMinutes: 240, breakMinutes: 15, netMinutes: 225 }; + for (const segment of [start, end]) { + // An exact start filter hides the other segment from each time-entry + // and ERP response, but not from the break allocation. + const clockIn = segment.clockIn.toISOString(); + const filtered = await ctx.http + .get('/api/timeentries') + .auth(reportToken, { type: 'bearer' }) + .query({ employeeId: f.employee.id, from: clockIn, to: clockIn }) + .expect(200); + expect(filtered.body).toEqual([ + expect.objectContaining({ id: segment.id, summary }), + ]); + const customer = await ctx.http + .get(`/api/projects/${segment.projectId}/report`) + .auth(reportToken, { type: 'bearer' }) + .query({ from: clockIn, to: clockIn }) + .expect(200); + expect(customer.body.totalGrossMinutes).toBe(240); + expect(customer.body.rows).toHaveLength(1); + const erp = await ctx.http + .get('/api/erp/timeentries') + .set('X-API-Key', process.env.ERP_API_KEY ?? 'e2e-erp-key') + .query({ from: clockIn, to: clockIn, pageSize: 1 }) + .expect(200); + expect(erp.body).toEqual([ + expect.objectContaining({ id: segment.id, netMinutes: 225 }), + ]); + } + }); + + it('keeps fractional switch boundaries in project totals and supports ordinary QR clock-out', async () => { + setTime('08:00'); + const f = await fixture(); + const first = await catalog(f.employee.id, 'FRACTIONAL'); + const second = await ctx.prisma.activity.create({ + data: { projectId: first.projectId, name: 'Second activity' }, + }); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + setTime('12:00:30'); + await activity(f.deviceToken, (await grant(f)).grant, second.id).expect( + 200, + ); + setTime('16:00'); + const kioskState = await ctx.http + .get(kiosk) + .auth(f.deviceToken, { type: 'bearer' }) + .expect(200); + const employeeToken = await login(ctx.http, f.employee.email); + const qrReceipt = await ctx.http + .post('/api/terminals/scan') + .auth(employeeToken, { type: 'bearer' }) + .send({ + qrPayload: kioskState.body.challenge.payload, + action: 'clock-out', + }) + .expect(201); + expect(qrReceipt.body.entry).toMatchObject({ + clockIn: at('12:00:30').toISOString(), + clockOut: at('16:00').toISOString(), + projectId: first.projectId, + summary: { + grossMinutes: 239.5, + breakMinutes: 30 * (239.5 / 480), + netMinutes: 239.5 - 30 * (239.5 / 480), + }, + }); + const hrToken = await login(ctx.http, f.hr.email); + const report = await ctx.http + .get(`/api/projects/${first.projectId}/report`) + .auth(hrToken, { type: 'bearer' }) + .expect(200); + expect(report.body.totalGrossMinutes).toBe(480); + expect( + report.body.rows.map((row: { grossMinutes: number }) => row.grossMinutes), + ).toEqual([240.5, 239.5]); + const project = await ctx.http + .get(`/api/projects/${first.projectId}`) + .auth(hrToken, { type: 'bearer' }) + .expect(200); + expect(project.body.bookedMinutes).toBe(480); + }); + + it('recomputes special approval for each segment instead of copying the first status or flags', async () => { + setTime('06:00'); + const f = await fixture(); + const first = await catalog(f.employee.id, 'EARLY'); + const second = await catalog(f.employee.id, 'REGULAR'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + status: 'Open', + requiresApproval: true, + }); + + setTime('08:00'); + await activity(f.deviceToken, (await grant(f)).grant, second.id).expect( + 200, + ); + expect( + await ctx.prisma.timeEntry.findMany({ orderBy: { clockIn: 'asc' } }), + ).toEqual([ + expect.objectContaining({ + clockIn: at('06:00'), + clockOut: at('08:00'), + requiresApproval: true, + status: 'Pending', + }), + expect.objectContaining({ + clockIn: at('08:00'), + clockOut: null, + requiresApproval: false, + status: 'Open', + }), + ]); + + setTime('10:00'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-out').expect(201); + expect( + await ctx.prisma.timeEntry.findFirstOrThrow({ + where: { activityId: second.id }, + }), + ).toMatchObject({ + clockOut: at('10:00'), + requiresApproval: false, + status: 'Approved', + }); + }); + + it('rechecks active service orders and the per-terminal switch, leaving plain clock-out available', async () => { + setTime('08:00'); + const f = await fixture(); + const first = await catalog(f.employee.id, 'ALLOWED'); + const second = await catalog(f.employee.id, 'NOW-EXCLUDED'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + const original = await ctx.prisma.timeEntry.findFirstOrThrow(); + + const atSameInstant = await grant(f); + const tooEarly = await activity( + f.deviceToken, + atSameInstant.grant, + second.id, + ).expect(409); + expect(tooEarly.body.code).toBe('TERMINAL_ACTIVITY_SWITCH_TOO_EARLY'); + expect((await storedGrant(atSameInstant.grant)).consumedAt).toBeNull(); + expect(await ctx.prisma.timeEntry.findMany()).toEqual([original]); + + setTime('12:00'); + const session = await grant(f); + const before = await activityState(f.deviceToken, session.grant); + expect(before.body.activities).toContainEqual( + expect.objectContaining({ id: second.id }), + ); + await ctx.prisma.serviceOrder.create({ + data: { projectId: second.projectId, orderNo: 'NEW', title: 'New order' }, + }); + const excluded = await activity( + f.deviceToken, + session.grant, + second.id, + ).expect(409); + expect(excluded.body.code).toBe('TERMINAL_ACTIVITY_UNAVAILABLE'); + await ctx.http + .put(`/api/terminals/${f.terminalId}`) + .auth(await login(ctx.http, f.hr.email), { type: 'bearer' }) + .send({ activitySelectionEnabled: false }) + .expect(200); + const disabled = await activity( + f.deviceToken, + session.grant, + first.id, + ).expect(403); + expect(disabled.body.code).toBe('TERMINAL_ACTIVITY_DISABLED'); + expect((await storedGrant(session.grant)).consumedAt).toBeNull(); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toEqual(original); + expect(await ctx.prisma.timeEntry.count()).toBe(1); + expect(await remembered(f.employee.id)).toBe(first.id); + + await book(f.deviceToken, session.grant, 'clock-out').expect(201); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + id: original.id, + activityId: first.id, + clockOut: at('12:00'), + clockOutTerminalId: f.terminalId, + }); + }); + + it('keeps repeat selection of the open activity a no-op and serializes concurrent requests for another', async () => { + setTime('08:00'); + const f = await fixture(); + const first = await catalog(f.employee.id, 'UNCHANGED'); + const second = await catalog(f.employee.id, 'CONCURRENT'); + const third = await catalog(f.employee.id, 'REPEATED'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + const original = await ctx.prisma.timeEntry.findFirstOrThrow(); + + setTime('12:00'); + const same = await grant(f); + const unchanged = await activity( + f.deviceToken, + same.grant, + first.id, + ).expect(200); + expect(unchanged.body).toEqual({ outcome: 'unchanged' }); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toEqual(original); + expect((await storedGrant(same.grant)).consumedAt).toEqual(at('12:00')); + + const session = await grant(f); + const attempts = await Promise.all([ + activity(f.deviceToken, session.grant, second.id), + activity(f.deviceToken, session.grant, second.id), + ]); + expect(attempts.map(({ status }) => status).sort()).toEqual([200, 409]); + expect(attempts.find(({ status }) => status === 200)?.body).toEqual({ + outcome: 'switched', + }); + expect(await ctx.prisma.timeEntry.count()).toBe(2); + expect( + await ctx.prisma.timeEntry.findMany({ where: { clockOut: null } }), + ).toEqual([expect.objectContaining({ activityId: second.id })]); + + setTime('13:00'); + await activity(f.deviceToken, (await grant(f)).grant, third.id).expect(200); + const [start, middle, end] = await ctx.prisma.timeEntry.findMany({ + orderBy: { clockIn: 'asc' }, + }); + expect(start.captureGroupId).toEqual(expect.any(String)); + expect(middle).toMatchObject({ + activityId: second.id, + clockIn: start.clockOut, + clockOut: at('13:00'), + captureGroupId: start.captureGroupId, + }); + expect(end).toMatchObject({ + activityId: third.id, + clockIn: middle.clockOut, + clockOut: null, + captureGroupId: start.captureGroupId, + }); + }); + + it('rolls back the close, remembered choice and grant if PostgreSQL rejects creation of the new segment', async () => { + setTime('08:00'); + const f = await fixture(); + const first = await catalog(f.employee.id, 'ROLLBACK-ORIGINAL'); + const blocked = await catalog(f.employee.id, 'ROLLBACK-TARGET'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + const original = await ctx.prisma.timeEntry.findFirstOrThrow(); + const count = await ctx.prisma.terminalChallengeRedemption.count(); + setTime('12:00'); + const session = await grant(f); + + // Only the new segment in this isolated database fixture should fail. + // The open-entry unique index forces a successful switch to close first. + await ctx.prisma.$executeRawUnsafe(` + CREATE FUNCTION "testRejectActivitySwitch"() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + IF EXISTS ( + SELECT 1 FROM "Activity" + WHERE "id" = NEW."activityId" AND "name" = 'Activity ROLLBACK-TARGET' + ) THEN + RAISE EXCEPTION 'test: reject activity segment insertion'; + END IF; + RETURN NEW; + END; + $$ + `); + try { + await ctx.prisma.$executeRawUnsafe(` + CREATE TRIGGER "testRejectActivitySwitch" + BEFORE INSERT ON "TimeEntry" FOR EACH ROW + EXECUTE FUNCTION "testRejectActivitySwitch"() + `); + await activity(f.deviceToken, session.grant, blocked.id).expect(500); + expect(await ctx.prisma.timeEntry.findMany()).toEqual([original]); + expect(await remembered(f.employee.id)).toBe(first.id); + expect((await storedGrant(session.grant)).consumedAt).toBeNull(); + expect(await ctx.prisma.terminalChallengeRedemption.count()).toBe(count); + expect( + await ctx.prisma.terminalAuditEvent.count({ + where: { event: 'ActivitySelectionAccepted' }, + }), + ).toBe(0); + } finally { + await ctx.prisma.$executeRawUnsafe( + 'DROP TRIGGER IF EXISTS "testRejectActivitySwitch" ON "TimeEntry"', + ); + await ctx.prisma.$executeRawUnsafe( + 'DROP FUNCTION "testRejectActivitySwitch"()', + ); + } + + await activity(f.deviceToken, session.grant, blocked.id).expect(200); + expect(await ctx.prisma.timeEntry.count()).toBe(2); + expect(await remembered(f.employee.id)).toBe(blocked.id); + }); +}); 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 b2e63a8..7d89597 100644 --- a/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts +++ b/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts @@ -1,8 +1,10 @@ -import { createHmac } from 'node:crypto'; +import { createHmac, randomUUID } from 'node:crypto'; +import { EventsGateway } from '../../../api/src/app/events/events.gateway'; import { createTestApp, login, seedEmployee, + seedProject, type TestContext, } from '../support/test-app'; @@ -18,7 +20,11 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { await ctx.reset(); }); - async function terminal(hrToken: string, geofence = false) { + async function terminal( + hrToken: string, + geofence = false, + activitySelectionEnabled?: boolean, + ) { const result = await ctx.http .post('/api/terminals') .set('Authorization', `Bearer ${hrToken}`) @@ -30,6 +36,7 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { enforceGeofence: geofence, isActive: true, allowedAuthMethods: ['QR', 'PIN'], + activitySelectionEnabled, ...(geofence ? { latitude: 49.7913, @@ -57,7 +64,15 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { }; } - async function fixture(geofence = false, ownerOnly = false) { + async function fixture({ + geofence = false, + ownerOnly = false, + activitySelectionEnabled, + }: { + geofence?: boolean; + ownerOnly?: boolean; + activitySelectionEnabled?: boolean; + } = {}) { const hr = await seedEmployee(ctx.prisma, { personalNo: 'BOOK-HR', firstName: 'Hannah', @@ -84,7 +99,7 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { employee, hrToken, pin: reset.body.pin as string, - ...(await terminal(hrToken, geofence)), + ...(await terminal(hrToken, geofence, activitySelectionEnabled)), }; } @@ -127,6 +142,274 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { .send({ grant: token, ...(action ? { action } : {}), ...extra }); } + async function activity(employeeId: string, code: string) { + const project = await seedProject(ctx.prisma, { + code, + assigneeIds: [employeeId], + serviceOrders: [ + { orderNo: 'INACTIVE', title: 'Inactive order', isActive: false }, + ], + }); + return ctx.prisma.activity.create({ + data: { projectId: project.id, name: `Activity ${code}` }, + }); + } + + function activityState(deviceToken: string, grantToken: string) { + return ctx.http + .post('/api/terminals/kiosk/activity-state') + .auth(deviceToken, { type: 'bearer' }) + .send({ grant: grantToken }); + } + + async function expectUnbooked(employeeId: string, remembered: string | null) { + expect(await ctx.prisma.timeEntry.count()).toBe(0); + expect(await ctx.prisma.terminalChallengeRedemption.count()).toBe(0); + expect( + await ctx.prisma.terminalBookingGrant.count({ + where: { consumedAt: { not: null } }, + }), + ).toBe(0); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: employeeId }, + }), + ).toMatchObject({ lastTerminalActivityId: remembered }); + } + + it('derives an eligible activity’s project, remembers it, and preserves it on plain clock-out', async () => { + const f = await fixture({ activitySelectionEnabled: true }); + const chosen = await activity(f.employee.id, 'CHOSEN'); + const other = await activity(f.hr.id, 'OTHER'); + const project = await ctx.prisma.project.update({ + where: { id: chosen.projectId }, + data: { defaultBillable: true }, + include: { serviceOrders: true }, + }); + const plainTerminal = await terminal(f.hrToken); + const identified = await grant(f); + const broadcast = jest.spyOn(ctx.app.get(EventsGateway), 'broadcast'); + try { + const { body } = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + projectId: other.projectId, + employeeId: f.hr.id, + serviceOrderId: project.serviceOrders[0].id, + billable: false, + }).expect(201); + expect(Object.keys(body).sort()).toEqual([ + 'action', + 'bookedAt', + 'code', + 'receiptId', + ]); + const entry = await ctx.prisma.timeEntry.findFirstOrThrow(); + expect(entry).toMatchObject({ + employeeId: f.employee.id, + projectId: chosen.projectId, + activityId: chosen.id, + serviceOrderId: null, + activity: null, + billable: true, + source: 'Terminal', + status: 'Open', + clockOut: null, + }); + const next = await grant(f); + expect( + (await activityState(f.deviceToken, next.grant).expect(200)).body, + ).toMatchObject({ selectedActivityId: chosen.id }); + await ctx.prisma.activity.update({ + where: { id: chosen.id }, + data: { isActive: false }, + }); + const retry = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }).expect(201); + expect(retry.body).toEqual(body); + expect(broadcast.mock.calls).toEqual([ + [ + 'time-entry:created', + { + id: entry.id, + employeeId: f.employee.id, + clockIn: entry.clockIn.toISOString(), + }, + ], + ]); + + const closing = await grant({ ...f, ...plainTerminal }); + expect(closing.action).toBe('clock-out'); + const forbiddenSelection = await book( + plainTerminal.deviceToken, + closing.grant, + 'clock-out', + { + activityId: other.id, + }, + ).expect(400); + expect(forbiddenSelection.body.code).toBe( + 'TERMINAL_ACTIVITY_CLOCK_IN_ONLY', + ); + expect( + (await ctx.prisma.timeEntry.findFirstOrThrow()).clockOut, + ).toBeNull(); + await book(plainTerminal.deviceToken, closing.grant, 'clock-out').expect( + 201, + ); + expect(await ctx.prisma.timeEntry.count()).toBe(1); + const closed = await ctx.prisma.timeEntry.findFirstOrThrow(); + expect(closed).toMatchObject({ + id: entry.id, + clockOutTerminalId: plainTerminal.terminalId, + activityId: chosen.id, + projectId: chosen.projectId, + }); + expect(closed.clockOut).not.toBeNull(); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: f.employee.id }, + }), + ).toMatchObject({ lastTerminalActivityId: chosen.id }); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: f.hr.id }, + }), + ).toMatchObject({ lastTerminalActivityId: null }); + const audits = await ctx.prisma.terminalAuditEvent.findMany({ + where: { timeEntryId: entry.id }, + }); + expect(audits).toHaveLength(2); + for (const audit of audits) { + expect(audit.canonicalPayload).not.toContain(chosen.id); + expect(audit.canonicalPayload).not.toContain(chosen.name); + expect(audit.canonicalPayload).not.toContain(project.id); + } + } finally { + broadcast.mockRestore(); + } + }); + + it.each([ + 'inactive activity', + 'inactive project', + 'removed assignment', + 'active service order', + 'archived customer', + 'deleted activity', + ] as const)( + 'rechecks previously offered activity after %s', + async (change) => { + const f = await fixture({ activitySelectionEnabled: true }); + const chosen = await activity(f.employee.id, 'STALE'); + const identified = await grant(f); + const { body } = await activityState( + f.deviceToken, + identified.grant, + ).expect(200); + expect(body.activities).toEqual([ + expect.objectContaining({ id: chosen.id }), + ]); + + const activityWhere = { id: chosen.id }; + const projectWhere = { id: chosen.projectId }; + switch (change) { + case 'inactive activity': + await ctx.prisma.activity.update({ + where: activityWhere, + data: { isActive: false }, + }); + break; + case 'inactive project': + await ctx.prisma.project.update({ + where: projectWhere, + data: { isActive: false }, + }); + break; + case 'removed assignment': + await ctx.prisma.projectAssignment.deleteMany({ + where: { projectId: chosen.projectId, employeeId: f.employee.id }, + }); + break; + case 'active service order': + await ctx.prisma.serviceOrder.updateMany({ + where: { projectId: chosen.projectId }, + data: { isActive: true }, + }); + break; + case 'archived customer': + await ctx.prisma.project.update({ + where: projectWhere, + data: { + customer: { + create: { name: 'Archived Customer', isActive: false }, + }, + }, + }); + break; + case 'deleted activity': + await ctx.prisma.activity.delete({ where: activityWhere }); + break; + } + const denied = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }).expect(409); + expect(denied.body.code).toBe('TERMINAL_ACTIVITY_UNAVAILABLE'); + expect(JSON.stringify(denied.body)).not.toContain(chosen.id); + await expectUnbooked(f.employee.id, null); + await book(f.deviceToken, identified.grant, 'clock-in').expect(201); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + activityId: null, + projectId: null, + serviceOrderId: null, + }); + }, + ); + + it('rejects malformed activity IDs and preserves the grant after a terminal is toggled off', async () => { + const f = await fixture({ activitySelectionEnabled: true }); + const remembered = await activity(f.employee.id, 'REMEMBERED'); + const attempted = await activity(f.employee.id, 'ATTEMPTED'); + await ctx.prisma.employee.update({ + where: { id: f.employee.id }, + data: { lastTerminalActivityId: remembered.id }, + }); + const identified = await grant(f); + for (const activityId of ['not-a-uuid', null, 42, [attempted.id]]) { + await book(f.deviceToken, identified.grant, 'clock-in', { + activityId, + }).expect(400); + } + const unknown = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: randomUUID(), + }).expect(409); + expect(unknown.body.code).toBe('TERMINAL_ACTIVITY_UNAVAILABLE'); + await ctx.http + .put(`/api/terminals/${f.terminalId}`) + .auth(f.hrToken, { type: 'bearer' }) + .send({ activitySelectionEnabled: false }) + .expect(200); + const disabled = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: attempted.id, + }).expect(403); + expect(disabled.body.code).toBe('TERMINAL_ACTIVITY_DISABLED'); + await expectUnbooked(f.employee.id, remembered.id); + await book(f.deviceToken, identified.grant, 'clock-in').expect(201); + const closing = await grant(f); + await book(f.deviceToken, closing.grant, 'clock-out').expect(201); + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + activityId: null, + projectId: null, + serviceOrderId: null, + clockOut: expect.any(Date), + }); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: f.employee.id }, + }), + ).toMatchObject({ lastTerminalActivityId: remembered.id }); + }); + it('requires an explicit action, rejects a status mismatch, and commits one minimal confirmation', async () => { const f = await fixture(); const identified = await grant(f); @@ -210,14 +493,20 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { expect(await ctx.prisma.timeEntry.count()).toBe(1); }); - it('serializes two terminals so simultaneous clock-ins cannot silently become a clock-out', async () => { - const f = await fixture(); - const other = await terminal(f.hrToken); + it('serializes competing activities so the other clock-in cannot close the entry or change the remembered activity', async () => { + const f = await fixture({ activitySelectionEnabled: true }); + const other = await terminal(f.hrToken, false, true); + const firstChoice = await activity(f.employee.id, 'FIRST'); + const secondChoice = await activity(f.employee.id, 'SECOND'); const first = await grant(f); const second = await grant({ ...f, ...other }); const results = await Promise.all([ - book(f.deviceToken, first.grant, 'clock-in'), - book(other.deviceToken, second.grant, 'clock-in'), + book(f.deviceToken, first.grant, 'clock-in', { + activityId: firstChoice.id, + }), + book(other.deviceToken, second.grant, 'clock-in', { + activityId: secondChoice.id, + }), ]); expect(results.map((result) => result.status).sort()).toEqual([201, 409]); expect(results.find((result) => result.status === 409)?.body.code).toBe( @@ -227,6 +516,16 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { expect( await ctx.prisma.timeEntry.count({ where: { clockOut: null } }), ).toBe(1); + const winner = results[0].status === 201 ? firstChoice : secondChoice; + expect(await ctx.prisma.timeEntry.findFirstOrThrow()).toMatchObject({ + activityId: winner.id, + projectId: winner.projectId, + }); + expect( + await ctx.prisma.employee.findUniqueOrThrow({ + where: { id: f.employee.id }, + }), + ).toMatchObject({ lastTerminalActivityId: winner.id }); expect(await ctx.prisma.terminalChallengeRedemption.count()).toBe(1); const stopped = await grant(f); expect(stopped.action).toBe('clock-out'); @@ -452,7 +751,7 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { }); it('retains an unconsumed grant after missing, stale or outside-geofence positions', async () => { - const f = await fixture(true); + const f = await fixture({ geofence: true }); const identified = await grant(f); expect(identified.requiresLocation).toBe(true); await book(f.deviceToken, identified.grant, 'clock-in').expect(400); @@ -488,7 +787,7 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { }); it('checks Team mode inside a booking transaction queued behind a committed Solo switch', async () => { - const f = await fixture(false, true); + const f = await fixture({ ownerOnly: true }); const identified = await grant(f); await ctx.prisma.installationSettings.upsert({ where: { id: 1 }, @@ -608,8 +907,14 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { ).toMatchObject({ result: event.result, hash: event.hash }); }); - it('rolls back the booking, redemption and grant consumption if the success audit cannot be inserted', async () => { - const f = await fixture(); + it('rolls back the booking, remembered activity, redemption and grant consumption if success audit fails', async () => { + const f = await fixture({ activitySelectionEnabled: true }); + const remembered = await activity(f.employee.id, 'PREVIOUS'); + const chosen = await activity(f.employee.id, 'NEW'); + await ctx.prisma.employee.update({ + where: { id: f.employee.id }, + data: { lastTerminalActivityId: remembered.id }, + }); const identified = await grant(f); // This transient fault exists only in the connection checked by ctx.reset(). // It rejects a success audit while allowing the durable rejection audit. @@ -623,13 +928,11 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { .$executeRawUnsafe(`CREATE TRIGGER e2e_terminal_booking_audit_failure BEFORE INSERT ON "TerminalAuditEvent" FOR EACH ROW EXECUTE FUNCTION e2e_reject_terminal_booking_audit()`); - const result = await book(f.deviceToken, identified.grant, 'clock-in'); + const result = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }); expect(result.status).toBeGreaterThanOrEqual(500); - expect(await ctx.prisma.timeEntry.count()).toBe(0); - expect(await ctx.prisma.terminalChallengeRedemption.count()).toBe(0); - expect( - (await ctx.prisma.terminalBookingGrant.findFirstOrThrow()).consumedAt, - ).toBeNull(); + await expectUnbooked(f.employee.id, remembered.id); } finally { await ctx.prisma.$executeRawUnsafe( 'DROP TRIGGER IF EXISTS e2e_terminal_booking_audit_failure ON "TerminalAuditEvent"', @@ -638,7 +941,43 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { 'DROP FUNCTION IF EXISTS e2e_reject_terminal_booking_audit()', ); } - await book(f.deviceToken, identified.grant, 'clock-in').expect(201); + await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }).expect(201); expect(await ctx.prisma.timeEntry.count()).toBe(1); }); + + it('returns a retriable booking conflict if the activity FK fails after validation', async () => { + const f = await fixture({ activitySelectionEnabled: true }); + const chosen = await activity(f.employee.id, 'FK-CONFLICT'); + const identified = await grant(f); + // Fault-inject a disappearing activity immediately before INSERT, only + // on this suite's isolated PostgreSQL database. + await ctx.prisma.$executeRaw` + CREATE FUNCTION e2e_remove_activity_before_booking() + RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + DELETE FROM "Activity" WHERE id = NEW."activityId"; + RETURN NEW; + END $$ + `; + try { + await ctx.prisma.$executeRaw` + CREATE TRIGGER e2e_activity_fk_failure BEFORE INSERT ON "TimeEntry" + FOR EACH ROW EXECUTE FUNCTION e2e_remove_activity_before_booking() + `; + const result = await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }).expect(409); + expect(result.body.code).toBe('TERMINAL_BOOKING_CONFLICT'); + await expectUnbooked(f.employee.id, null); + } finally { + await ctx.prisma + .$executeRaw`DROP TRIGGER IF EXISTS e2e_activity_fk_failure ON "TimeEntry"`; + await ctx.prisma + .$executeRaw`DROP FUNCTION IF EXISTS e2e_remove_activity_before_booking()`; + } + await book(f.deviceToken, identified.grant, 'clock-in', { + activityId: chosen.id, + }).expect(201); + }); }); diff --git a/apps/api-e2e/src/api/terminals.e2e.spec.ts b/apps/api-e2e/src/api/terminals.e2e.spec.ts index 1dce618..96a55c6 100644 --- a/apps/api-e2e/src/api/terminals.e2e.spec.ts +++ b/apps/api-e2e/src/api/terminals.e2e.spec.ts @@ -153,6 +153,112 @@ describe('Tablet terminals', () => { expect(await ctx.prisma.terminalSupportPrompt.count()).toBe(1); }); + it('defaults activity selection off and persists each terminal setting', async () => { + const { hrToken } = await actors(); + const authorization = `Bearer ${hrToken}`; + const created = await createTerminal(hrToken); + const id = created.body.id as string; + expect(created.body.activitySelectionEnabled).toBe(false); + const paired = await pairTerminal(hrToken, id); + + const optedIn = await ctx.http + .post('/api/terminals') + .set('Authorization', authorization) + .send({ + ...TERMINAL_INPUT, + name: 'Nebeneingang', + activitySelectionEnabled: true, + }) + .expect(201); + expect(optedIn.body.activitySelectionEnabled).toBe(true); + + const enabled = await ctx.http + .put(`/api/terminals/${id}`) + .set('Authorization', authorization) + .send({ activitySelectionEnabled: true }) + .expect(200); + expect(enabled.body).toMatchObject({ + activitySelectionEnabled: true, + authConfigVersion: created.body.authConfigVersion, + isPaired: true, + }); + await kiosk(paired.body.deviceToken); + + const renamed = await ctx.http + .put(`/api/terminals/${id}`) + .set('Authorization', authorization) + .send({ name: 'Neuer Haupteingang' }) + .expect(200); + expect(renamed.body.activitySelectionEnabled).toBe(true); + const reread = await ctx.http + .get(`/api/terminals/${id}`) + .set('Authorization', authorization) + .expect(200); + expect(reread.body.activitySelectionEnabled).toBe(true); + + const disabled = await ctx.http + .put(`/api/terminals/${id}`) + .set('Authorization', authorization) + .send({ activitySelectionEnabled: false }) + .expect(200); + expect(disabled.body).toMatchObject({ + activitySelectionEnabled: false, + authConfigVersion: created.body.authConfigVersion, + isPaired: true, + }); + const listed = await ctx.http + .get('/api/terminals') + .set('Authorization', authorization) + .expect(200); + expect(listed.body).toHaveLength(2); + expect(listed.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id, activitySelectionEnabled: false }), + expect.objectContaining({ + id: optedIn.body.id, + activitySelectionEnabled: true, + }), + ]), + ); + }); + + it('requires a boolean when setting activity selection on create or update', async () => { + const { hrToken } = await actors(); + const authorization = `Bearer ${hrToken}`; + const created = await createTerminal(hrToken); + + for (const activitySelectionEnabled of ['false', null]) { + await ctx.http + .post('/api/terminals') + .set('Authorization', authorization) + .send({ ...TERMINAL_INPUT, activitySelectionEnabled }) + .expect(400); + await ctx.http + .put(`/api/terminals/${created.body.id}`) + .set('Authorization', authorization) + .send({ activitySelectionEnabled }) + .expect(400); + } + }); + + it('does not expose activity selection settings to managers or employees', async () => { + const { hrToken, managerToken, firstToken } = await actors(); + const created = await createTerminal(hrToken); + const terminalPath = `/api/terminals/${created.body.id}`; + + for (const token of [managerToken, firstToken]) { + await ctx.http + .get(terminalPath) + .set('Authorization', `Bearer ${token}`) + .expect(403); + await ctx.http + .put(terminalPath) + .set('Authorization', `Bearer ${token}`) + .send({ activitySelectionEnabled: true }) + .expect(403); + } + }); + it('restricts administration to HRAdmin and records the opt-in prompt once', async () => { const { hrToken, managerToken } = await actors(); await ctx.http diff --git a/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts b/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts new file mode 100644 index 0000000..5ed3dd0 --- /dev/null +++ b/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts @@ -0,0 +1,482 @@ +import { randomUUID } from 'node:crypto'; +import { + createTestApp, + login, + seedEmployee, + seedProject, + type TestContext, +} from '../support/test-app'; + +describe('Time entry activity corrections', () => { + const entries = '/api/timeentries'; + const historicalText = 'Historical customer-facing note'; + const at = (hour: number) => + new Date(Date.UTC(2026, 10, 23, hour - 1)).toISOString(); + let ctx: TestContext; + + beforeAll(async () => { + ctx = await createTestApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.reset(); + }); + + async function employee(label: string, role?: 'Manager' | 'HRAdmin') { + return seedEmployee(ctx.prisma, { + personalNo: label, + firstName: 'Synthetic', + lastName: label, + email: `${label}@editor.test`, + role, + }); + } + + async function activity(projectId: string, name: string, isActive = true) { + return ctx.prisma.activity.create({ data: { projectId, name, isActive } }); + } + + async function fixture() { + const worker = await employee('worker'); + const other = await employee('other'); + // Manager is intentionally not the entry owner's supervisor or assigned to + // the entry's project; the existing editor permits privileged corrections. + const manager = await employee('manager', 'Manager'); + const hr = await employee('hr', 'HRAdmin'); + const assigned = await seedProject(ctx.prisma, { + code: 'EDITOR', + assigneeIds: [worker.id], + }); + const second = await seedProject(ctx.prisma, { + code: 'EDITOR-SECOND', + assigneeIds: [worker.id], + serviceOrders: [ + { orderNo: 'ORDER', title: 'Active order' }, + { orderNo: 'OLD', title: 'Inactive order', isActive: false }, + ], + }); + const foreign = await seedProject(ctx.prisma, { + code: 'EDITOR-FOREIGN', + assigneeIds: [other.id, manager.id, hr.id], + }); + const inactive = await seedProject(ctx.prisma, { + code: 'EDITOR-INACTIVE', + isActive: false, + assigneeIds: [worker.id], + }); + return { + worker, + other, + manager, + hr, + assigned, + second, + foreign, + inactive, + current: await activity(assigned.id, 'Planting'), + replacement: await activity(assigned.id, 'Sorting'), + retired: await activity(assigned.id, 'Retired', false), + secondActivity: await activity(second.id, 'Packing'), + foreignActivity: await activity(foreign.id, 'Other project work'), + inactiveActivity: await activity(inactive.id, 'Inactive project work'), + }; + } + + function closedEntry( + employeeId: string, + projectId: string | null, + activityId: string | null, + ) { + return ctx.prisma.timeEntry.create({ + data: { + employeeId, + projectId, + activityId, + activity: historicalText, + clockIn: at(8), + clockOut: at(16), + status: 'Approved', + source: 'Terminal', + captureGroupId: randomUUID(), + breakRules: [{ afterMinutes: 360, breakMinutes: 30 }], + }, + }); + } + + function options(entryId: string, token?: string, projectId?: string) { + const request = ctx.http.get(`${entries}/${entryId}/activity-options`); + if (token) request.auth(token, { type: 'bearer' }); + if (projectId) request.query({ projectId }); + return request; + } + + function correction(entryId: string, token?: string) { + const request = ctx.http.patch(`${entries}/${entryId}`); + return token ? request.auth(token, { type: 'bearer' }) : request; + } + + it('authorizes choices and edits by entry ownership or role, without changing the admin catalog permissions', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const worker = await login(ctx.http, f.worker.email); + const other = await login(ctx.http, f.other.email); + await options(entry.id).expect(401); + await correction(entry.id) + .send({ activityId: f.replacement.id }) + .expect(401); + await options(entry.id, other).expect(403); + await correction(entry.id, other) + .send({ activityId: f.replacement.id }) + .expect(403); + await ctx.http + .get(`/api/projects/${f.assigned.id}/activities`) + .auth(worker, { type: 'bearer' }) + .expect(403); + + for (const [email, next] of [ + [f.worker.email, f.replacement], + [f.manager.email, f.current], + [f.hr.email, f.replacement], + ] as const) { + const actor = await login(ctx.http, email); + const listed = await options(entry.id, actor).expect(200); + expect(listed.body).toEqual([ + { id: f.current.id, name: f.current.name }, + { id: f.replacement.id, name: f.replacement.name }, + ]); + const changed = await correction(entry.id, actor) + .send({ activityId: next.id }) + .expect(200); + expect(changed.body.activityId).toBe(next.id); + expect(changed.body.catalogActivityName).toBe(next.name); + } + }); + + it('replaces and clears the catalog reference on an approved entry without touching attendance or historical free text', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.retired.id); + const token = await login(ctx.http, f.worker.email); + const listed = await ctx.http + .get(entries) + .query({ employeeId: f.worker.id }) + .auth(token, { type: 'bearer' }) + .expect(200); + expect(listed.body).toEqual([ + expect.objectContaining({ + id: entry.id, + activityId: f.retired.id, + catalogActivityName: f.retired.name, + }), + ]); + const invariant = { + id: entry.id, + projectId: f.assigned.id, + serviceOrderId: null, + activity: historicalText, + clockIn: at(8), + clockOut: at(16), + captureGroupId: entry.captureGroupId, + status: 'Approved', + summary: { grossMinutes: 480, breakMinutes: 30, netMinutes: 450 }, + }; + for (const selection of [f.replacement, null]) { + const changed = await correction(entry.id, token) + .send({ activityId: selection?.id ?? null }) + .expect(200); + expect(changed.body).toMatchObject({ + ...invariant, + activityId: selection?.id ?? null, + catalogActivityName: selection?.name ?? null, + }); + } + expect( + await ctx.prisma.timeEntry.findUniqueOrThrow({ where: { id: entry.id } }), + ).toMatchObject({ + activityId: null, + activity: historicalText, + clockIn: entry.clockIn, + clockOut: entry.clockOut, + captureGroupId: entry.captureGroupId, + }); + }); + + it('lists only active activities in active projects assigned to the entry owner', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const manager = await login(ctx.http, f.manager.email); + const listed = await options(entry.id, manager, f.second.id).expect(200); + expect(listed.body).toEqual([ + { id: f.secondActivity.id, name: f.secondActivity.name }, + ]); + const archivedCustomer = await ctx.prisma.customer.create({ + data: { name: 'Archived customer', isActive: false }, + }); + await ctx.prisma.project.update({ + where: { id: f.second.id }, + data: { customerId: archivedCustomer.id }, + }); + for (const project of [f.foreign, f.inactive, f.second]) { + const result = await options(entry.id, manager, project.id).expect(200); + expect(result.body).toEqual([]); + } + await options(entry.id, manager, 'not-a-uuid').expect(400); + await ctx.prisma.projectAssignment.delete({ + where: { + employeeId_projectId: { + employeeId: f.worker.id, + projectId: f.assigned.id, + }, + }, + }); + const revoked = await options(entry.id, manager).expect(200); + expect(revoked.body).toEqual([]); + await correction(entry.id, manager) + .send({ activityId: f.replacement.id }) + .expect(400); + const cleared = await correction(entry.id, manager) + .send({ activityId: null }) + .expect(200); + expect(cleared.body).toMatchObject({ + activityId: null, + projectId: f.assigned.id, + activity: historicalText, + }); + }); + + it('does not invalidate a manager-approved frame when only the activity changes', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const frameApproved = await ctx.prisma.timeEntry.update({ + where: { id: entry.id }, + data: { + clockIn: at(6), + requiresApproval: true, + frameApproverId: f.manager.id, + frameApprovedRevision: entry.revision, + }, + }); + const token = await login(ctx.http, f.worker.email); + await correction(entry.id, token) + .send({ activityId: f.replacement.id }) + .expect(200); + expect( + await ctx.prisma.timeEntry.findUniqueOrThrow({ where: { id: entry.id } }), + ).toMatchObject({ + activityId: f.replacement.id, + clockIn: frameApproved.clockIn, + clockOut: frameApproved.clockOut, + status: 'Approved', + requiresApproval: true, + frameApproverId: f.manager.id, + revision: frameApproved.revision + 1, + frameApprovedRevision: frameApproved.revision + 1, + }); + }); + + it('rejects invalid activity, project and service-order combinations without partially mutating the entry', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const token = await login(ctx.http, f.worker.email); + const order = f.second.serviceOrders.find( + (candidate) => candidate.isActive, + ); + const retiredOrder = f.second.serviceOrders.find( + (candidate) => !candidate.isActive, + ); + if (!order || !retiredOrder) + throw new Error('Expected active and inactive fixture orders'); + for (const [body, status] of [ + [{ activityId: 'not-a-uuid' }, 400], + [{ activityId: randomUUID() }, 400], + [{ activityId: f.retired.id }, 400], + [{ activityId: f.secondActivity.id }, 400], + [{ projectId: null, activityId: f.current.id }, 400], + [{ projectId: f.foreign.id, activityId: f.foreignActivity.id }, 403], + [{ projectId: f.inactive.id, activityId: f.inactiveActivity.id }, 400], + [{ projectId: f.second.id, activityId: f.secondActivity.id }, 400], + [ + { + projectId: f.assigned.id, + serviceOrderId: order.id, + activityId: f.replacement.id, + }, + 404, + ], + [ + { + projectId: f.second.id, + serviceOrderId: retiredOrder.id, + activityId: f.secondActivity.id, + }, + 400, + ], + ] as const) { + await correction(entry.id, token).send(body).expect(status); + } + expect( + await ctx.prisma.timeEntry.findUniqueOrThrow({ where: { id: entry.id } }), + ).toEqual(entry); + + const moved = await correction(entry.id, token) + .send({ + projectId: f.second.id, + serviceOrderId: order.id, + activityId: f.secondActivity.id, + }) + .expect(200); + expect(moved.body).toMatchObject({ + projectId: f.second.id, + serviceOrderId: order.id, + activityId: f.secondActivity.id, + activity: historicalText, + clockIn: at(8), + clockOut: at(16), + }); + await ctx.prisma.serviceOrder.update({ + where: { id: order.id }, + data: { isActive: false }, + }); + const otherActivity = await activity(f.second.id, 'Dispatch'); + await correction(entry.id, token) + .send({ activityId: otherActivity.id }) + .expect(400); + }); + + it('corrects an old project-only booking when an active service order was introduced later', async () => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const token = await login(ctx.http, f.worker.email); + await ctx.prisma.serviceOrder.create({ + data: { + projectId: f.assigned.id, + orderNo: 'AFTER', + title: 'Added after booking', + }, + }); + const listed = await options(entry.id, token).expect(200); + expect(listed.body).toContainEqual({ + id: f.replacement.id, + name: f.replacement.name, + }); + const changed = await correction(entry.id, token) + .send({ activityId: f.replacement.id }) + .expect(200); + expect(changed.body).toMatchObject({ + projectId: f.assigned.id, + serviceOrderId: null, + activityId: f.replacement.id, + activity: historicalText, + }); + const repeatedTarget = await correction(entry.id, token) + .send({ + projectId: f.assigned.id, + serviceOrderId: null, + activityId: f.current.id, + }) + .expect(200); + expect(repeatedTarget.body).toMatchObject({ + projectId: f.assigned.id, + serviceOrderId: null, + activityId: f.current.id, + }); + }); + + it.each(['move', 'unassign'] as const)( + 'clears an incompatible activity on %s without rewriting free text', + async (operation) => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const token = await login(ctx.http, f.worker.email); + const projectId = operation === 'move' ? f.second.id : null; + const serviceOrderId = projectId + ? f.second.serviceOrders.find((order) => order.isActive)?.id + : null; + const changed = await correction(entry.id, token) + .send({ projectId, serviceOrderId }) + .expect(200); + expect(changed.body).toMatchObject({ + projectId, + serviceOrderId, + activityId: null, + catalogActivityName: null, + activity: historicalText, + }); + }, + ); + + it.each(['inherit', 'move', 'unassign'] as const)( + 'keeps structured references only on original-project segments when splitting (%s)', + async (operation) => { + const f = await fixture(); + const entry = await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const token = await login(ctx.http, f.worker.email); + const target = + operation === 'inherit' + ? {} + : operation === 'unassign' + ? { projectId: null } + : { + projectId: f.second.id, + serviceOrderId: f.second.serviceOrders.find( + (order) => order.isActive, + )?.id, + }; + const result = await ctx.http + .post(`${entries}/${entry.id}/split`) + .auth(token, { type: 'bearer' }) + .send({ at: at(12), ...target }) + .expect(201); + expect(result.body.first).toMatchObject({ + clockIn: at(8), + clockOut: at(12), + projectId: f.assigned.id, + activityId: f.current.id, + catalogActivityName: f.current.name, + }); + expect(result.body.second).toMatchObject({ + clockIn: at(12), + clockOut: at(16), + projectId: operation === 'inherit' ? f.assigned.id : target.projectId, + activityId: operation === 'inherit' ? f.current.id : null, + catalogActivityName: operation === 'inherit' ? f.current.name : null, + }); + }, + ); + + it('clears the reference on a reallocated prefix but retains it in the original-project suffix', async () => { + const f = await fixture(); + await closedEntry(f.worker.id, f.assigned.id, f.current.id); + const token = await login(ctx.http, f.worker.email); + const result = await ctx.http + .post(`${entries}/book-project`) + .auth(token, { type: 'bearer' }) + .send({ + employeeId: f.worker.id, + from: at(8), + to: at(12), + projectId: f.second.id, + serviceOrderId: f.second.serviceOrders.find((order) => order.isActive) + ?.id, + }) + .expect(201); + expect(result.body.entries).toEqual([ + expect.objectContaining({ + clockIn: at(8), + clockOut: at(12), + projectId: f.second.id, + activityId: null, + catalogActivityName: null, + }), + expect.objectContaining({ + clockIn: at(12), + clockOut: at(16), + projectId: f.assigned.id, + activityId: f.current.id, + catalogActivityName: f.current.name, + activity: historicalText, + }), + ]); + }); +}); diff --git a/apps/api/openapi.json b/apps/api/openapi.json index 9fab72d..cd026ef 100644 --- a/apps/api/openapi.json +++ b/apps/api/openapi.json @@ -1625,6 +1625,187 @@ "tags": ["projects"] } }, + "/api/projects/{id}/activities": { + "get": { + "operationId": "ProjectsController_listActivities", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Full project catalog, including inactive activities.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ActivityDto" + } + } + } + } + }, + "404": { + "description": "Project not found." + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["projects"] + }, + "post": { + "operationId": "ProjectsController_createActivity", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpsertActivityDto" + } + } + } + }, + "responses": { + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActivityDto" + } + } + } + }, + "404": { + "description": "Project not found." + }, + "409": { + "description": "Activity name already exists in this project." + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["projects"] + } + }, + "/api/projects/{id}/activities/{activityId}": { + "put": { + "operationId": "ProjectsController_updateActivity", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + }, + { + "name": "activityId", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpsertActivityDto" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActivityDto" + } + } + } + }, + "404": { + "description": "Activity not found in this project." + }, + "409": { + "description": "Activity name already exists in this project." + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["projects"] + }, + "delete": { + "operationId": "ProjectsController_removeActivity", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + }, + { + "name": "activityId", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "" + }, + "404": { + "description": "Activity not found in this project." + }, + "409": { + "description": "Activity is referenced by a time entry." + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["projects"] + } + }, "/api/projects/{id}/assignments/{employeeId}": { "put": { "operationId": "ProjectsController_assign", @@ -2631,6 +2812,52 @@ "tags": ["time-entries"] } }, + "/api/timeentries/{id}/activity-options": { + "get": { + "operationId": "TimeEntriesController_activityOptions", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + }, + { + "name": "projectId", + "required": false, + "in": "query", + "schema": { + "type": "string", + "format": "uuid" + }, + "description": "Proposed booking project; defaults to the entry’s project." + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TimeEntryActivityOptionDto" + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["time-entries"] + } + }, "/api/timeentries/{id}/split": { "post": { "operationId": "TimeEntriesController_split", @@ -2732,6 +2959,74 @@ "tags": ["terminal-auth"] } }, + "/api/terminals/kiosk/activity-state": { + "post": { + "operationId": "TerminalAuthController_activityState", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/KioskGrantDto" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/KioskActivityStateDto" + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["terminal-auth"] + } + }, + "/api/terminals/kiosk/activity": { + "post": { + "operationId": "TerminalAuthController_selectActivity", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SelectKioskActivityDto" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SelectKioskActivityResultDto" + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": ["terminal-auth"] + } + }, "/api/terminals/kiosk/book": { "post": { "operationId": "TerminalAuthController_book", @@ -6744,6 +7039,71 @@ }, "required": ["orderNo", "title"] }, + "ActivityDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "projectId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "isActive": { + "type": "boolean" + }, + "sortOrder": { + "type": "integer" + }, + "hasBookings": { + "type": "boolean", + "description": "A referenced activity can be deactivated but not deleted." + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "projectId", + "name", + "isActive", + "sortOrder", + "hasBookings", + "createdAt", + "updatedAt" + ] + }, + "UpsertActivityDto": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "isActive": { + "type": "boolean", + "description": "Defaults to true on creation; omitted values stay unchanged on update." + }, + "sortOrder": { + "type": "integer", + "minimum": 0, + "maximum": 2147483647, + "description": "Defaults to 0 on creation; omitted values stay unchanged on update." + } + }, + "required": ["name"] + }, "SoloReportRowDto": { "type": "object", "properties": { @@ -7365,6 +7725,15 @@ "type": "string", "nullable": true }, + "activityId": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "catalogActivityName": { + "type": "string", + "nullable": true + }, "summary": { "nullable": true, "type": "object", @@ -7414,6 +7783,8 @@ "serviceOrderNo", "serviceOrderTitle", "activity", + "activityId", + "catalogActivityName", "summary" ] }, @@ -8055,9 +8426,28 @@ "type": "string", "nullable": true, "maxLength": 500 + }, + "activityId": { + "type": "string", + "format": "uuid", + "nullable": true, + "description": "Active catalog activity of the effective project. Null clears it; omission preserves it unless the project changes." } } }, + "TimeEntryActivityOptionDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + } + }, + "required": ["id", "name"] + }, "SplitTimeEntryDto": { "type": "object", "properties": { @@ -8156,15 +8546,109 @@ "requiresLocation" ] }, - "BookTerminalDto": { + "KioskGrantDto": { "type": "object", "properties": { "grant": { + "type": "string", + "description": "Short-lived grant returned by kiosk identification.", + "writeOnly": true + } + }, + "required": ["grant"] + }, + "KioskActivityDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { "type": "string" }, - "action": { + "projectId": { "type": "string", - "enum": ["clock-in", "clock-out"] + "format": "uuid" + }, + "projectName": { + "type": "string" + } + }, + "required": ["id", "name", "projectId", "projectName"] + }, + "KioskActivityStateDto": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "activities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/KioskActivityDto" + } + }, + "selectedActivityId": { + "type": "string", + "format": "uuid", + "nullable": true + } + }, + "required": ["enabled", "activities", "selectedActivityId"] + }, + "SelectKioskActivityDto": { + "type": "object", + "properties": { + "grant": { + "type": "string", + "description": "Short-lived grant returned by kiosk identification.", + "writeOnly": true + }, + "latitude": { + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "longitude": { + "type": "number", + "minimum": -180, + "maximum": 180 + }, + "accuracyMeters": { + "type": "number", + "minimum": 0 + }, + "positionTimestamp": { + "type": "string", + "format": "date-time" + }, + "activityId": { + "type": "string", + "format": "uuid", + "description": "Eligible activity to remember or switch to." + } + }, + "required": ["grant", "activityId"] + }, + "SelectKioskActivityResultDto": { + "type": "object", + "properties": { + "outcome": { + "type": "string", + "enum": ["remembered", "switched", "unchanged"], + "description": "Successful selection consumes the PIN grant and challenge." + } + }, + "required": ["outcome"] + }, + "BookTerminalDto": { + "type": "object", + "properties": { + "grant": { + "type": "string", + "description": "Short-lived grant returned by kiosk identification.", + "writeOnly": true }, "latitude": { "type": "number", @@ -8183,6 +8667,15 @@ "positionTimestamp": { "type": "string", "format": "date-time" + }, + "action": { + "type": "string", + "enum": ["clock-in", "clock-out"] + }, + "activityId": { + "type": "string", + "format": "uuid", + "description": "Eligible catalog activity for clock-in only. Omit for plain booking." } }, "required": ["grant", "action"] @@ -8612,6 +9105,9 @@ "isActive": { "type": "boolean" }, + "activitySelectionEnabled": { + "type": "boolean" + }, "isPaired": { "type": "boolean" }, @@ -8653,6 +9149,7 @@ "enforceGeofence", "timeZone", "isActive", + "activitySelectionEnabled", "isPaired", "deviceCount", "devices", @@ -8731,6 +9228,10 @@ "isActive": { "type": "boolean", "default": false + }, + "activitySelectionEnabled": { + "type": "boolean", + "description": "Allow activity selection at this terminal. Defaults to false." } }, "required": ["name", "displayText", "locationLabel"] @@ -8806,6 +9307,10 @@ "isActive": { "type": "boolean", "default": false + }, + "activitySelectionEnabled": { + "type": "boolean", + "description": "Allow activity selection at this terminal. Omit to leave unchanged." } } }, diff --git a/apps/api/src/app/accounts/accounts.service.ts b/apps/api/src/app/accounts/accounts.service.ts index 058705b..04c8d88 100644 --- a/apps/api/src/app/accounts/accounts.service.ts +++ b/apps/api/src/app/accounts/accounts.service.ts @@ -10,6 +10,7 @@ import type { HolidayProvider } from 'shared'; 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 type { JwtUser } from '../auth/jwt.strategy'; import { VacationBalanceService } from './vacation-balance.service'; import type { AccountDto } from './accounts.dto'; @@ -32,25 +33,44 @@ export class AccountsService { const yearStart = new Date(Date.UTC(year, 0, 1)); // Sum net minutes from completed time entries YTD. - const entries = await this.prisma.timeEntry.findMany({ - where: { - employeeId, - clockIn: { gte: yearStart }, - clockOut: { not: null }, + const netMinutesYtd = await this.prisma.$transaction( + async (tx) => { + const entries = await tx.timeEntry.findMany({ + where: { + employeeId, + clockIn: { gte: yearStart }, + clockOut: { not: null }, + }, + select: { + id: true, + employeeId: true, + clockIn: true, + clockOut: true, + breakRules: true, + captureGroupId: true, + status: true, + voidedAt: true, + }, + }); + const grouped = await loadCaptureSummaries( + tx, + entries.filter((entry) => entry.captureGroupId), + ); + return entries.reduce((minutes, entry) => { + if (!entry.clockOut) return minutes; + if (entry.captureGroupId) + return minutes + (grouped.get(entry.id)?.netMinutes ?? 0); + const gross = Math.floor( + (entry.clockOut.getTime() - entry.clockIn.getTime()) / 60_000, + ); + return ( + minutes + + calculateNetMinutes(gross, parseBreakRules(entry.breakRules)) + ); + }, 0); }, - select: { clockIn: true, clockOut: true, breakRules: true }, - }); - let netMinutesYtd = 0; - for (const e of entries) { - if (!e.clockOut) continue; - const gross = Math.floor( - (e.clockOut.getTime() - e.clockIn.getTime()) / 60_000, - ); - netMinutesYtd += calculateNetMinutes( - gross, - parseBreakRules(e.breakRules), - ); - } + { isolationLevel: 'RepeatableRead' }, + ); // Soll-Befreiung: Vacation (approved) + Sickness + Training count as // excused working days — their absence on a workday is not a deficit. diff --git a/apps/api/src/app/erp-export/erp-export.service.ts b/apps/api/src/app/erp-export/erp-export.service.ts index 759ae8f..a44d19d 100644 --- a/apps/api/src/app/erp-export/erp-export.service.ts +++ b/apps/api/src/app/erp-export/erp-export.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'; import { Prisma } from '@prisma/client'; import { summarize, parseBreakRules } from 'shared'; import { PrismaService } from '../prisma/prisma.service'; +import { loadCaptureSummaries } from '../time-entries/capture-summary'; export interface ErpTimeEntryDto { id: string; @@ -38,38 +39,49 @@ export class ErpExportService { if (from) (where.clockIn as Prisma.DateTimeFilter).gte = from; if (to) (where.clockIn as Prisma.DateTimeFilter).lte = to; } - const rows = await this.prisma.timeEntry.findMany({ - where, - orderBy: { clockIn: 'asc' }, - include: { - employee: { select: { personalNo: true } }, - project: { select: { code: true, name: true } }, - serviceOrder: { select: { orderNo: true, title: true } }, - }, - skip, - take, - }); - return rows - .filter((r) => r.clockOut !== null) - .map((r) => { - const summary = summarize( - r.clockIn, - r.clockOut, - parseBreakRules(r.breakRules), + return this.prisma.$transaction( + async (tx) => { + const rows = await tx.timeEntry.findMany({ + where, + orderBy: { clockIn: 'asc' }, + include: { + employee: { select: { personalNo: true } }, + project: { select: { code: true, name: true } }, + serviceOrder: { select: { orderNo: true, title: true } }, + }, + skip, + take, + }); + // A date filter, page limit or pending approval must not start a new + // break calculation for the otherwise eligible segments. + const grouped = await loadCaptureSummaries( + tx, + rows.filter((entry) => entry.captureGroupId), ); - return { - id: r.id, - employeeId: r.employeeId, - personalNo: r.employee.personalNo, - clockIn: r.clockIn.toISOString(), - clockOut: (r.clockOut as Date).toISOString(), - netMinutes: summary.netMinutes, - projectCode: r.project?.code ?? null, - projectName: r.project?.name ?? null, - orderNo: r.serviceOrder?.orderNo ?? null, - orderTitle: r.serviceOrder?.title ?? null, - activity: r.activity, - }; - }); + return rows.flatMap((r) => { + if (!r.clockOut) return []; + const summary = r.captureGroupId + ? grouped.get(r.id) + : summarize(r.clockIn, r.clockOut, parseBreakRules(r.breakRules)); + if (!summary) return []; + return [ + { + id: r.id, + employeeId: r.employeeId, + personalNo: r.employee.personalNo, + clockIn: r.clockIn.toISOString(), + clockOut: r.clockOut.toISOString(), + netMinutes: summary.netMinutes, + projectCode: r.project?.code ?? null, + projectName: r.project?.name ?? null, + orderNo: r.serviceOrder?.orderNo ?? null, + orderTitle: r.serviceOrder?.title ?? null, + activity: r.activity, + }, + ]; + }); + }, + { isolationLevel: 'RepeatableRead' }, + ); } } diff --git a/apps/api/src/app/projects/projects.controller.ts b/apps/api/src/app/projects/projects.controller.ts index 0a07075..b3da37a 100644 --- a/apps/api/src/app/projects/projects.controller.ts +++ b/apps/api/src/app/projects/projects.controller.ts @@ -14,7 +14,10 @@ import { } from '@nestjs/common'; import { ApiBearerAuth, + ApiConflictResponse, ApiCreatedResponse, + ApiNoContentResponse, + ApiNotFoundResponse, ApiOkResponse, ApiTags, } from '@nestjs/swagger'; @@ -26,6 +29,8 @@ import { CurrentUser } from '../auth/current-user.decorator'; import type { JwtUser } from '../auth/jwt.strategy'; import { SoloProjectAccessGuard } from './solo-project-access.guard'; import { + ActivityDto, + UpsertActivityDto, UpsertProjectDto, UpsertServiceOrderDto, BookableProjectDto, @@ -166,6 +171,74 @@ export class ProjectsController { return this.projects.removeServiceOrder(id, orderId, user); } + @Get(':id/activities') + @ApiOkResponse({ + type: [ActivityDto], + description: 'Full project catalog, including inactive activities.', + }) + @ApiNotFoundResponse({ description: 'Project not found.' }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Manager', 'HRAdmin') + listActivities( + @Param('id', new ParseUUIDPipe()) id: string, + ): Promise { + return this.projects.listActivities(id); + } + + @Post(':id/activities') + @ApiCreatedResponse({ type: ActivityDto }) + @ApiNotFoundResponse({ description: 'Project not found.' }) + @ApiConflictResponse({ + description: 'Activity name already exists in this project.', + }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Manager', 'HRAdmin') + createActivity( + @Param('id', new ParseUUIDPipe()) id: string, + @Body() dto: UpsertActivityDto, + @CurrentUser() user: JwtUser, + ): Promise { + return this.projects.createActivity(id, dto, user); + } + + @Put(':id/activities/:activityId') + @ApiOkResponse({ type: ActivityDto }) + @ApiNotFoundResponse({ description: 'Activity not found in this project.' }) + @ApiConflictResponse({ + description: 'Activity name already exists in this project.', + }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Manager', 'HRAdmin') + updateActivity( + @Param('id', new ParseUUIDPipe()) id: string, + @Param('activityId', new ParseUUIDPipe()) activityId: string, + @Body() dto: UpsertActivityDto, + @CurrentUser() user: JwtUser, + ): Promise { + return this.projects.updateActivity(id, activityId, dto, user); + } + + @Delete(':id/activities/:activityId') + @ApiNoContentResponse() + @ApiNotFoundResponse({ description: 'Activity not found in this project.' }) + @ApiConflictResponse({ + description: 'Activity is referenced by a time entry.', + }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Manager', 'HRAdmin') + @HttpCode(HttpStatus.NO_CONTENT) + removeActivity( + @Param('id', new ParseUUIDPipe()) id: string, + @Param('activityId', new ParseUUIDPipe()) activityId: string, + @CurrentUser() user: JwtUser, + ): Promise { + return this.projects.removeActivity(id, activityId, user); + } + @Put(':id/assignments/:employeeId') @ApiBearerAuth() @UseGuards(JwtAuthGuard, RolesGuard) diff --git a/apps/api/src/app/projects/projects.dto.ts b/apps/api/src/app/projects/projects.dto.ts index 29d09d9..54ffaeb 100644 --- a/apps/api/src/app/projects/projects.dto.ts +++ b/apps/api/src/app/projects/projects.dto.ts @@ -1,14 +1,19 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; import { IsBoolean, + IsInt, IsNumber, IsOptional, IsString, IsUUID, + Matches, + Max, MaxLength, Min, + ValidateIf, } from 'class-validator'; -import type { Project, ServiceOrder } from '@prisma/client'; +import type { Activity, Project, ServiceOrder } from '@prisma/client'; export class UpsertProjectDto { @ApiProperty({ maxLength: 40, example: 'PRJ-001' }) @@ -105,6 +110,77 @@ export class ServiceOrderDto { bookedNetMinutes?: number; } +const MAX_SORT_ORDER = 2_147_483_647; + +export class UpsertActivityDto { + @ApiProperty({ minLength: 1, maxLength: 200 }) + @Transform(({ obj }) => obj.name) + @IsString() + @Matches(/\S/) + @MaxLength(200) + name!: string; + + @ApiPropertyOptional({ + description: + 'Defaults to true on creation; omitted values stay unchanged on update.', + }) + // Implicit conversion would turn the string "false" into true. + @Transform(({ obj }) => obj.isActive) + @ValidateIf((_object, value) => value !== undefined) + @IsBoolean() + isActive?: boolean; + + @ApiPropertyOptional({ + type: 'integer', + minimum: 0, + maximum: MAX_SORT_ORDER, + description: + 'Defaults to 0 on creation; omitted values stay unchanged on update.', + }) + @Transform(({ obj }) => obj.sortOrder) + @ValidateIf((_object, value) => value !== undefined) + @IsInt() + @Min(0) + @Max(MAX_SORT_ORDER) + sortOrder?: number; +} + +export class ActivityDto { + @ApiProperty({ format: 'uuid' }) + id!: string; + @ApiProperty({ format: 'uuid' }) + projectId!: string; + @ApiProperty() + name!: string; + @ApiProperty() + isActive!: boolean; + @ApiProperty({ type: 'integer' }) + sortOrder!: number; + @ApiProperty({ + description: 'A referenced activity can be deactivated but not deleted.', + }) + hasBookings!: boolean; + @ApiProperty({ format: 'date-time' }) + createdAt!: string; + @ApiProperty({ format: 'date-time' }) + updatedAt!: string; +} + +export function toActivityDto( + activity: Activity & { _count: { timeEntries: number } }, +): ActivityDto { + return { + id: activity.id, + projectId: activity.projectId, + name: activity.name, + isActive: activity.isActive, + sortOrder: activity.sortOrder, + hasBookings: activity._count.timeEntries > 0, + createdAt: activity.createdAt.toISOString(), + updatedAt: activity.updatedAt.toISOString(), + }; +} + export class ProjectDto { @ApiProperty({ format: 'uuid' }) id!: string; diff --git a/apps/api/src/app/projects/projects.service.ts b/apps/api/src/app/projects/projects.service.ts index 6ec5bb1..bed5442 100644 --- a/apps/api/src/app/projects/projects.service.ts +++ b/apps/api/src/app/projects/projects.service.ts @@ -16,7 +16,9 @@ import { import { calculateCaptureSummaries } from '../time-entries/capture-summary'; import type { JwtUser } from '../auth/jwt.strategy'; import { + type ActivityDto, EMPTY_IST_STATS, + toActivityDto, toProjectDto, toServiceOrderDto, type BookableProjectDto, @@ -25,10 +27,15 @@ import { type ProjectIstStats, type ProjectReportDto, type ServiceOrderDto, + type UpsertActivityDto, type UpsertProjectDto, type UpsertServiceOrderDto, } from './projects.dto'; +const ACTIVITY_BOOKING_COUNT = { + _count: { select: { timeEntries: true } }, +} as const; + interface IstRow { projectId: string; serviceOrderId: string | null; @@ -333,6 +340,101 @@ export class ProjectsService { this.broadcast(projectId); } + /** The management catalog includes inactive entries so they can be reactivated. */ + async listActivities(projectId: string): Promise { + const project = await this.prisma.project.findUnique({ + where: { id: projectId }, + select: { + activities: { + orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }, { id: 'asc' }], + include: ACTIVITY_BOOKING_COUNT, + }, + }, + }); + if (!project) throw new NotFoundException(`Project ${projectId} not found`); + return project.activities.map(toActivityDto); + } + + async createActivity( + projectId: string, + dto: UpsertActivityDto, + actor: JwtUser, + ): Promise { + const name = dto.name.trim(); + try { + const activity = await this.mutate(actor, (tx) => + tx.activity.create({ + data: { + project: { connect: { id: projectId } }, + name, + isActive: dto.isActive, + sortOrder: dto.sortOrder, + }, + include: ACTIVITY_BOOKING_COUNT, + }), + ); + this.broadcast(projectId); + return toActivityDto(activity); + } catch (err) { + if (isUniqueViolation(err)) throw activityNameConflict(name); + if (isPrismaError(err, 'P2025') || isPrismaError(err, 'P2003')) { + throw new NotFoundException(`Project ${projectId} not found`); + } + throw err; + } + } + + async updateActivity( + projectId: string, + activityId: string, + dto: UpsertActivityDto, + actor: JwtUser, + ): Promise { + const name = dto.name.trim(); + try { + const activity = await this.mutate(actor, (tx) => + tx.activity.update({ + where: { projectId_id: { projectId, id: activityId } }, + data: { name, isActive: dto.isActive, sortOrder: dto.sortOrder }, + include: ACTIVITY_BOOKING_COUNT, + }), + ); + this.broadcast(projectId); + return toActivityDto(activity); + } catch (err) { + if (isUniqueViolation(err)) throw activityNameConflict(name); + if (isPrismaError(err, 'P2025')) + throw activityNotFound(projectId, activityId); + throw err; + } + } + + async removeActivity( + projectId: string, + activityId: string, + actor: JwtUser, + ): Promise { + try { + // The booking FK decides this atomically, including concurrent inserts. + // An employee's last selection is not a booking and is cleared by the DB. + await this.mutate(actor, (tx) => + tx.activity.delete({ + where: { projectId_id: { projectId, id: activityId } }, + }), + ); + } catch (err) { + if (isPrismaError(err, 'P2025')) + throw activityNotFound(projectId, activityId); + if (isPrismaError(err, 'P2003')) { + throw new ConflictException( + 'Activity has booked time entries and cannot be deleted — deactivate it instead', + ); + } + throw err; + } + this.broadcast(projectId); + } + /** Idempotent: assigning an already-assigned employee is a no-op success. */ async assign( projectId: string, @@ -514,9 +616,15 @@ export class ProjectsService { const entries = await this.prisma.timeEntry.findMany({ where, orderBy: { clockIn: 'asc' }, - include: { + select: { + clockIn: true, + clockOut: true, + captureGroupId: true, + activity: true, employee: { select: { firstName: true, lastName: true } }, serviceOrder: { select: { orderNo: true, title: true } }, + // Historical bookings retain their catalog name after deactivation. + catalogActivity: { select: { name: true } }, }, }); const rows = entries.map((e) => ({ @@ -524,8 +632,10 @@ export class ProjectsService { employeeName: `${e.employee.firstName} ${e.employee.lastName}`, orderNo: e.serviceOrder?.orderNo ?? null, orderTitle: e.serviceOrder?.title ?? null, - grossMinutes: summarize(e.clockIn, e.clockOut as Date).grossMinutes, - activity: e.activity, + grossMinutes: e.captureGroupId + ? ((e.clockOut as Date).getTime() - e.clockIn.getTime()) / 60_000 + : summarize(e.clockIn, e.clockOut as Date).grossMinutes, + activity: e.catalogActivity?.name ?? e.activity, })); return { projectCode: project.code, @@ -539,7 +649,8 @@ export class ProjectsService { /** * Gross booked minutes per project and service order (closed, non-rejected - * entries). FLOOR-per-entry rounding matches summarize() in libs/shared. + * entries). Keep legacy minute rounding on ungrouped bookings only; rounding + * each new segment would remove time at a fractional-minute switch boundary. */ private async loadIstStats( projectId?: string, @@ -549,7 +660,10 @@ export class ProjectsService { const rows = projectId ? await this.prisma.$queryRaw` SELECT "projectId", "serviceOrderId", - COALESCE(SUM(FLOOR(EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60)), 0)::int AS minutes + SUM(CASE WHEN "captureGroupId" IS NULL + THEN FLOOR(EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60) + ELSE EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60 + END)::double precision AS minutes FROM "TimeEntry" WHERE "projectId" = ${projectId}::uuid AND "clockOut" IS NOT NULL @@ -559,7 +673,10 @@ export class ProjectsService { ` : await this.prisma.$queryRaw` SELECT "projectId", "serviceOrderId", - COALESCE(SUM(FLOOR(EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60)), 0)::int AS minutes + SUM(CASE WHEN "captureGroupId" IS NULL + THEN FLOOR(EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60) + ELSE EXTRACT(EPOCH FROM ("clockOut" - "clockIn")) / 60 + END)::double precision AS minutes FROM "TimeEntry" WHERE "projectId" IS NOT NULL AND "clockOut" IS NOT NULL @@ -742,3 +859,24 @@ function isUniqueViolation(err: unknown): boolean { (err as { code?: string }).code === 'P2002' ); } + +function isPrismaError(error: unknown, code: string): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && error.code === code + ); +} + +function activityNameConflict(name: string): ConflictException { + return new ConflictException( + `An activity named "${name}" already exists in this project`, + ); +} + +function activityNotFound( + projectId: string, + activityId: string, +): NotFoundException { + return new NotFoundException( + `Activity ${activityId} not found in project ${projectId}`, + ); +} diff --git a/apps/api/src/app/requests/time-adjustments.service.ts b/apps/api/src/app/requests/time-adjustments.service.ts index 365d813..8d0db59 100644 --- a/apps/api/src/app/requests/time-adjustments.service.ts +++ b/apps/api/src/app/requests/time-adjustments.service.ts @@ -10,6 +10,7 @@ import { PrismaService } from '../prisma/prisma.service'; import { WorkSchedulesService } from '../work-schedules/work-schedules.service'; import { calculateCaptureSummaries } from '../time-entries/capture-summary'; import { + TIME_ENTRY_ALLOCATION_INCLUDE, toTimeEntryDto, type TimeEntryDto, } from '../time-entries/time-entries.dto'; @@ -56,10 +57,7 @@ export class TimeAdjustmentsService { status: { in: ['Pending', 'Approved'] }, OR: [{ approvalMode: null }, { approvalMode: { not: 'Solo' } }], }, - include: { - project: { select: { code: true, name: true } }, - serviceOrder: { select: { orderNo: true, title: true } }, - }, + include: TIME_ENTRY_ALLOCATION_INCLUDE, orderBy: [{ clockIn: 'desc' }, { id: 'asc' }], }); const summaries = calculateCaptureSummaries(rows); diff --git a/apps/api/src/app/terminals/terminal-activity-selection.ts b/apps/api/src/app/terminals/terminal-activity-selection.ts new file mode 100644 index 0000000..d91fbf4 --- /dev/null +++ b/apps/api/src/app/terminals/terminal-activity-selection.ts @@ -0,0 +1,83 @@ +import { ConflictException, ForbiddenException } from '@nestjs/common'; +import type { Prisma } from '@prisma/client'; +import type { KioskActivityDto } from './terminal-auth.dto'; + +/** Shared by kiosk reads and mutations; mutations must check inside their transaction. */ +export function terminalActivityEligibility( + employeeId: string, +): Prisma.ActivityWhereInput { + return { + isActive: true, + project: { + isActive: true, + assignments: { some: { employeeId } }, + serviceOrders: { none: { isActive: true } }, + // Like other project bookings, a project of an archived customer is not bookable. + OR: [{ customerId: null }, { customer: { isActive: true } }], + }, + }; +} + +export type TerminalActivityTarget = { + activityId: string; + projectId: string; + billable: boolean; +}; + +/** Requires the installation lock shared by terminal and catalog mutations. */ +export async function resolveTerminalActivity( + tx: Prisma.TransactionClient, + employeeId: string, + activityId: string, + selectionEnabled: boolean, +): Promise { + if (!selectionEnabled) + throw new ForbiddenException({ + code: 'TERMINAL_ACTIVITY_DISABLED', + message: 'Activity selection is disabled at this terminal', + }); + + const activity = await tx.activity.findFirst({ + where: { id: activityId, ...terminalActivityEligibility(employeeId) }, + select: { + id: true, + projectId: true, + project: { select: { defaultBillable: true } }, + }, + }); + if (!activity) + throw new ConflictException({ + code: 'TERMINAL_ACTIVITY_UNAVAILABLE', + message: 'Activity is no longer available for this booking', + }); + return { + activityId: activity.id, + projectId: activity.projectId, + billable: activity.project.defaultBillable, + }; +} + +export async function listEligibleTerminalActivities( + tx: Prisma.TransactionClient, + employeeId: string, +): Promise { + const activities = await tx.activity.findMany({ + where: terminalActivityEligibility(employeeId), + select: { + id: true, + name: true, + projectId: true, + project: { select: { name: true } }, + }, + orderBy: [ + { project: { name: 'asc' } }, + { projectId: 'asc' }, + { sortOrder: 'asc' }, + { name: 'asc' }, + ], + }); + return activities.map(({ project, ...activity }) => ({ + ...activity, + projectName: project.name, + })); +} diff --git a/apps/api/src/app/terminals/terminal-auth.controller.ts b/apps/api/src/app/terminals/terminal-auth.controller.ts index e3e42c8..527fbff 100644 --- a/apps/api/src/app/terminals/terminal-auth.controller.ts +++ b/apps/api/src/app/terminals/terminal-auth.controller.ts @@ -3,7 +3,9 @@ import { Controller, Get, Header, + HttpCode, HttpException, + HttpStatus, Post, Query, Res, @@ -31,6 +33,10 @@ import { IdentifyChallengeDto, IdentifyTerminalDto, IdentifyTerminalResultDto, + KioskActivityStateDto, + KioskGrantDto, + SelectKioskActivityDto, + SelectKioskActivityResultDto, TerminalAuditPageDto, TerminalAuditQueryDto, } from './terminal-auth.dto'; @@ -84,6 +90,34 @@ export class TerminalAuthController { this.auth.identify(dto, device), ); } + @Post('kiosk/activity-state') + @UseGuards(TerminalDeviceGuard) + @HttpCode(HttpStatus.OK) + @Header('Cache-Control', 'no-store') + @ApiOkResponse({ type: KioskActivityStateDto }) + activityState( + @Body() dto: KioskGrantDto, + @CurrentTerminalDevice() device: TerminalDevicePrincipal, + @Res({ passthrough: true }) response: LimitResponse, + ) { + return this.limitedResponse(response, () => + this.auth.activityState(dto, device), + ); + } + @Post('kiosk/activity') + @UseGuards(TerminalDeviceGuard) + @HttpCode(HttpStatus.OK) + @Header('Cache-Control', 'no-store') + @ApiOkResponse({ type: SelectKioskActivityResultDto }) + selectActivity( + @Body() dto: SelectKioskActivityDto, + @CurrentTerminalDevice() device: TerminalDevicePrincipal, + @Res({ passthrough: true }) response: LimitResponse, + ) { + return this.limitedResponse(response, () => + this.auth.selectActivity(dto, device), + ); + } @Post('kiosk/book') @UseGuards(TerminalDeviceGuard) @Header('Cache-Control', 'no-store') diff --git a/apps/api/src/app/terminals/terminal-auth.dto.ts b/apps/api/src/app/terminals/terminal-auth.dto.ts index e7da43d..62fe4af 100644 --- a/apps/api/src/app/terminals/terminal-auth.dto.ts +++ b/apps/api/src/app/terminals/terminal-auth.dto.ts @@ -13,6 +13,7 @@ import { MaxLength, Min, MinLength, + ValidateIf, } from 'class-validator'; // Preserve lexical credentials even with the application's implicit conversion. @@ -55,16 +56,30 @@ export class IdentifyTerminalResultDto { | 'clock-out'; @ApiProperty() requiresLocation!: boolean; } -export class BookTerminalDto { - @ApiProperty() +export class KioskGrantDto { + @ApiProperty({ + description: 'Short-lived grant returned by kiosk identification.', + writeOnly: true, + }) @exactString() @IsString() @MinLength(32) @MaxLength(256) grant!: string; - @ApiProperty({ enum: ['clock-in', 'clock-out'] }) - @IsIn(['clock-in', 'clock-out']) - action!: 'clock-in' | 'clock-out'; +} +export class KioskActivityDto { + @ApiProperty({ format: 'uuid' }) id!: string; + @ApiProperty() name!: string; + @ApiProperty({ format: 'uuid' }) projectId!: string; + @ApiProperty() projectName!: string; +} +export class KioskActivityStateDto { + @ApiProperty() enabled!: boolean; + @ApiProperty({ type: [KioskActivityDto] }) activities!: KioskActivityDto[]; + @ApiProperty({ type: String, format: 'uuid', nullable: true }) + selectedActivityId!: string | null; +} +class KioskPositionedGrantDto extends KioskGrantDto { @ApiPropertyOptional({ minimum: -90, maximum: 90 }) @IsOptional() @IsNumber() @@ -87,6 +102,39 @@ export class BookTerminalDto { @IsDateString() positionTimestamp?: string; } + +export class BookTerminalDto extends KioskPositionedGrantDto { + @ApiProperty({ enum: ['clock-in', 'clock-out'] }) + @IsIn(['clock-in', 'clock-out']) + action!: 'clock-in' | 'clock-out'; + @ApiPropertyOptional({ + format: 'uuid', + description: + 'Eligible catalog activity for clock-in only. Omit for plain booking.', + }) + @exactString() + @ValidateIf((_, value: unknown) => value !== undefined) + @IsUUID() + activityId?: string; +} + +export class SelectKioskActivityDto extends KioskPositionedGrantDto { + @ApiProperty({ + format: 'uuid', + description: 'Eligible activity to remember or switch to.', + }) + @exactString() + @IsUUID() + activityId!: string; +} + +export class SelectKioskActivityResultDto { + @ApiProperty({ + enum: ['remembered', 'switched', 'unchanged'], + description: 'Successful selection consumes the PIN grant and challenge.', + }) + outcome!: 'remembered' | 'switched' | 'unchanged'; +} export class BookTerminalResultDto { @ApiProperty({ enum: ['TERMINAL_BOOKED'] }) code!: 'TERMINAL_BOOKED'; @ApiProperty({ enum: ['clock-in', 'clock-out'] }) action!: diff --git a/apps/api/src/app/terminals/terminal-auth.service.ts b/apps/api/src/app/terminals/terminal-auth.service.ts index 17d0620..40a7675 100644 --- a/apps/api/src/app/terminals/terminal-auth.service.ts +++ b/apps/api/src/app/terminals/terminal-auth.service.ts @@ -1,4 +1,5 @@ import { + BadRequestException, ConflictException, ForbiddenException, HttpException, @@ -14,15 +15,34 @@ import { EventsGateway } from '../events/events.gateway'; import { TerminalAuditService } from './terminal-audit.service'; import { TerminalPinService } from './terminal-pin.service'; import { TerminalsService } from './terminals.service'; -import { lockTerminalSecurity } from './terminal-security-locks'; -import { bookTerminalTime } from './terminal-booking.service'; +import { + assertTerminalTeamMode, + lockTerminalSecurity, +} from './terminal-security-locks'; +import { + listEligibleTerminalActivities, + resolveTerminalActivity, +} from './terminal-activity-selection'; +import { + bookTerminalTime, + findOpenTerminalEntry, + switchTerminalActivity, +} from './terminal-booking.service'; import type { TerminalDevicePrincipal } from './terminal-device.guard'; import type { BookTerminalDto, BookTerminalResultDto, IdentifyTerminalDto, + KioskActivityStateDto, + KioskGrantDto, + SelectKioskActivityDto, + SelectKioskActivityResultDto, } from './terminal-auth.dto'; +type AuthenticatedDevice = Prisma.TerminalDeviceGetPayload<{ + include: { terminal: true }; +}>; + const hash = (value: string) => createHash('sha256').update(value).digest('hex'); const MINUTE = 60_000; @@ -43,7 +63,7 @@ export class TerminalAuthService { private async device( tx: Prisma.TransactionClient, principal: TerminalDevicePrincipal, - ) { + ): Promise { const device = await tx.terminalDevice.findUnique({ where: { id: principal.id }, include: { terminal: true }, @@ -113,7 +133,7 @@ export class TerminalAuthService { } private async reserve( principal: TerminalDevicePrincipal, - kind: 'challenge' | 'identify' | 'book', + kind: 'challenge' | 'identify' | 'book' | 'activity-state', ) { const result = await this.prisma.$transaction(async (tx) => { await lockTerminalSecurity(tx); @@ -253,7 +273,7 @@ export class TerminalAuthService { where: { deviceId: device.id, expiresAt: { lt: new Date(now.getTime() - 3 * MINUTE) }, - redemptions: { none: {} }, + redemptions: { none: { timeEntryId: { not: null } } }, clockInTimeEntries: { none: {} }, clockOutTimeEntries: { none: {} }, }, @@ -510,149 +530,394 @@ export class TerminalAuthService { }; } - async book( - dto: BookTerminalDto, + private async deviceGrant( + tx: Prisma.TransactionClient, + device: AuthenticatedDevice, + grantToken: string, + ): Promise { + const grant = await tx.terminalBookingGrant.findUnique({ + where: { tokenHash: hash(grantToken) }, + }); + if ( + !grant || + grant.deviceId !== device.id || + grant.terminalId !== device.terminalId + ) + throw new ConflictException({ + code: 'TERMINAL_GRANT_INVALID', + message: 'Booking permission is invalid', + }); + return grant; + } + + private assertGrantEmployeeActive(employee: { isActive: boolean } | null) { + if (!employee?.isActive) + throw new ConflictException({ + code: 'TERMINAL_GRANT_INVALID', + message: 'Booking permission is no longer valid', + }); + } + + private async validateFreshGrant( + tx: Prisma.TransactionClient, + device: AuthenticatedDevice, + grant: TerminalBookingGrant, + now: Date, + ) { + this.method(device.terminal.allowedAuthMethods); + const credential = await tx.terminalCredential.findUnique({ + where: { employeeId: grant.employeeId }, + }); + const pinState = await tx.terminalAuthAttemptState.findUnique({ + where: { key: `pin:${grant.employeeId}` }, + }); + if ( + (pinState?.lockedUntil && pinState.lockedUntil > now) || + !credential || + credential.revokedAt || + credential.id !== grant.credentialId || + credential.version !== grant.credentialVersion || + grant.authConfigVersion !== device.terminal.authConfigVersion + ) + throw new ConflictException({ + code: 'TERMINAL_GRANT_REVOKED', + message: 'Booking permission was revoked', + }); + if (grant.expiresAt <= now) + throw new ConflictException({ + code: 'TERMINAL_GRANT_EXPIRED', + message: 'Booking permission expired', + }); + const challenge = await tx.terminalChallenge.findUnique({ + where: { id: grant.challengeId }, + include: { terminal: true }, + }); + if ( + !challenge || + challenge.purpose !== 'KioskIdentify' || + challenge.deviceId !== device.id || + challenge.terminalId !== device.terminalId || + challenge.expiresAt <= now || + challenge.rootDate.toISOString().slice(0, 10) !== + this.terminals.dateKey(now, device.terminal.timeZone) + ) + throw new ConflictException({ + code: 'TERMINAL_GRANT_EXPIRED', + message: 'Booking challenge expired', + }); + if ( + await tx.terminalChallengeRedemption.findUnique({ + where: { + challengeId_employeeId: { + challengeId: challenge.id, + employeeId: grant.employeeId, + }, + }, + }) + ) + throw new ConflictException({ + code: 'TERMINAL_CHALLENGE_REPLAYED', + message: 'Identification challenge was already used', + }); + return challenge; + } + + async activityState( + dto: KioskGrantDto, principal: TerminalDevicePrincipal, - ): Promise { - const reservedDevice = await this.reserve(principal, 'book'); - let employeeId: string | undefined; - try { - const result = await this.prisma.$transaction(async (tx) => { - await lockTerminalSecurity(tx); + ): Promise { + await this.reserve(principal, 'activity-state'); + // Authorization and the catalog belong to one fresh snapshot. Do not + // hold the installation/employee locks across an optional catalog read. + return this.prisma.$transaction( + async (tx) => { + await assertTerminalTeamMode(tx); const device = await this.device(tx, principal); - const grant = await tx.terminalBookingGrant.findUnique({ - where: { tokenHash: hash(dto.grant) }, - }); - if ( - !grant || - grant.deviceId !== device.id || - grant.terminalId !== device.terminalId - ) - throw new ConflictException({ - code: 'TERMINAL_GRANT_INVALID', - message: 'Booking permission is invalid', - }); - employeeId = grant.employeeId; - await lockTerminalSecurity(tx, employeeId); + const grant = await this.deviceGrant(tx, device, dto.grant); const employee = await tx.employee.findUnique({ - where: { id: employeeId }, - select: { isActive: true }, + where: { id: grant.employeeId }, + select: { isActive: true, lastTerminalActivityId: true }, }); - if (!employee?.isActive) + this.assertGrantEmployeeActive(employee); + if (grant.consumedAt) throw new ConflictException({ - code: 'TERMINAL_GRANT_INVALID', - message: 'Booking permission is no longer valid', + code: 'TERMINAL_GRANT_CONSUMED', + message: 'Booking permission was already used', }); - const now = new Date(); - if (grant.consumedAt) { - if ( - grant.action !== dto.action || - now.getTime() > grant.consumedAt.getTime() + 2 * MINUTE - ) + await this.validateFreshGrant(tx, device, grant, new Date()); + if (!device.terminal.activitySelectionEnabled) + return { enabled: false, activities: [], selectedActivityId: null }; + const activities = await listEligibleTerminalActivities( + tx, + grant.employeeId, + ); + const remembered = employee?.lastTerminalActivityId ?? null; + return { + enabled: true, + activities, + selectedActivityId: activities.some(({ id }) => id === remembered) + ? remembered + : null, + }; + }, + { isolationLevel: 'RepeatableRead' }, + ); + } + + async selectActivity( + dto: SelectKioskActivityDto, + principal: TerminalDevicePrincipal, + ): Promise { + // An alternate PIN write action must not double the booking write budget. + const reservedDevice = await this.reserve(principal, 'book'); + let employeeId: string | undefined; + let result: SelectKioskActivityResultDto & { + switched: { + previousId: string; + nextId: string; + employeeId: string; + at: Date; + } | null; + }; + try { + result = await this.prisma.$transaction( + async (tx) => { + await lockTerminalSecurity(tx); + const device = await this.device(tx, principal); + const grant = await this.deviceGrant(tx, device, dto.grant); + employeeId = grant.employeeId; + await lockTerminalSecurity(tx, employeeId); + const employee = await tx.employee.findUnique({ + where: { id: employeeId }, + select: { isActive: true, lastTerminalActivityId: true }, + }); + this.assertGrantEmployeeActive(employee); + if (grant.consumedAt) throw new ConflictException({ code: 'TERMINAL_GRANT_CONSUMED', message: 'Booking permission was already used', }); + + const now = new Date(); + const challenge = await this.validateFreshGrant( + tx, + device, + grant, + now, + ); + // Enforce the physical presence policy without storing coordinates + // or turning a virtual segment boundary into a physical punch. + this.terminals.evaluateTerminalPosition(dto, device.terminal, now); + const activity = await resolveTerminalActivity( + tx, + employeeId, + dto.activityId, + device.terminal.activitySelectionEnabled, + ); + const open = await findOpenTerminalEntry(tx, employeeId); + const next = + open && open.activityId !== activity.activityId + ? await switchTerminalActivity( + tx, + open, + activity, + now, + (await this.schedules.resolveForEmployee(employeeId, tx)) + .frame, + ) + : null; + const outcome: SelectKioskActivityResultDto['outcome'] = next + ? 'switched' + : open + ? 'unchanged' + : 'remembered'; + if (employee?.lastTerminalActivityId !== activity.activityId) + await tx.employee.update({ + where: { id: employeeId }, + data: { lastTerminalActivityId: activity.activityId }, + }); + + await tx.terminalChallengeRedemption.create({ + data: { + challengeId: challenge.id, + employeeId, + timeEntryId: next?.id ?? null, + action: 'activity', + }, + }); + await tx.terminalBookingGrant.update({ + where: { id: grant.id }, + data: { + consumedAt: now, + action: 'activity', + timeEntryId: next?.id ?? null, + }, + }); + await this.audit.append(tx, { + event: 'ActivitySelectionAccepted', + result: 'SUCCESS', + method: 'PIN', + employeeId, + terminalId: device.terminalId, + deviceId: device.id, + terminalName: device.terminal.name, + locationLabel: device.terminal.locationLabel, + timeEntryId: next?.id, + }); return { - response: this.receipt(grant), - entry: null, - action: dto.action, + outcome, + switched: + next && open + ? { previousId: open.id, nextId: next.id, employeeId, at: now } + : null, }; - } - this.method(device.terminal.allowedAuthMethods); - const credential = await tx.terminalCredential.findUnique({ - where: { employeeId }, - }); - const pinState = await tx.terminalAuthAttemptState.findUnique({ - where: { key: `pin:${employeeId}` }, - }); - if ( - (pinState?.lockedUntil && pinState.lockedUntil > now) || - !credential || - credential.revokedAt || - credential.id !== grant.credentialId || - credential.version !== grant.credentialVersion || - grant.authConfigVersion !== device.terminal.authConfigVersion + }, + { isolationLevel: 'ReadCommitted' }, + ); + } catch (error) { + await this.audit.failure({ + event: 'ActivitySelectionRejected', + result: 'REQUEST_REJECTED', + method: 'PIN', + employeeId, + terminalId: reservedDevice.terminalId, + deviceId: reservedDevice.id, + terminalName: reservedDevice.terminal.name, + locationLabel: reservedDevice.terminal.locationLabel, + }); + if ( + ['P2002', 'P2003', 'P2034'].includes( + (error as { code?: string }).code ?? '', ) - throw new ConflictException({ - code: 'TERMINAL_GRANT_REVOKED', - message: 'Booking permission was revoked', - }); - if (grant.expiresAt <= now) - throw new ConflictException({ - code: 'TERMINAL_GRANT_EXPIRED', - message: 'Booking permission expired', - }); - const challenge = await tx.terminalChallenge.findUnique({ - where: { id: grant.challengeId }, - include: { terminal: true }, + ) + throw new ConflictException({ + code: 'TERMINAL_BOOKING_CONFLICT', + message: 'Booking state changed', }); - if ( - !challenge || - challenge.purpose !== 'KioskIdentify' || - challenge.deviceId !== device.id || - challenge.terminalId !== device.terminalId || - challenge.expiresAt <= now || - challenge.rootDate.toISOString().slice(0, 10) !== - this.terminals.dateKey(now, device.terminal.timeZone) - ) - throw new ConflictException({ - code: 'TERMINAL_GRANT_EXPIRED', - message: 'Booking challenge expired', + throw error; + } + + if (result.switched) { + const { previousId, nextId, employeeId, at } = result.switched; + this.events.broadcast('time-entry:updated', { + id: previousId, + employeeId, + clockOut: at.toISOString(), + }); + this.events.broadcast('time-entry:created', { + id: nextId, + employeeId, + clockIn: at.toISOString(), + }); + } + return { outcome: result.outcome }; + } + + async book( + dto: BookTerminalDto, + principal: TerminalDevicePrincipal, + ): Promise { + const reservedDevice = await this.reserve(principal, 'book'); + let employeeId: string | undefined; + try { + const result = await this.prisma.$transaction( + async (tx) => { + await lockTerminalSecurity(tx); + const device = await this.device(tx, principal); + const grant = await this.deviceGrant(tx, device, dto.grant); + employeeId = grant.employeeId; + await lockTerminalSecurity(tx, employeeId); + const employee = await tx.employee.findUnique({ + where: { id: employeeId }, + select: { isActive: true }, }); - if ( - await tx.terminalChallengeRedemption.findUnique({ - where: { - challengeId_employeeId: { challengeId: challenge.id, employeeId }, + this.assertGrantEmployeeActive(employee); + const now = new Date(); + if (dto.action === 'clock-out' && dto.activityId !== undefined) + throw new BadRequestException({ + code: 'TERMINAL_ACTIVITY_CLOCK_IN_ONLY', + message: 'Only clock-in accepts an activity selection', + }); + if (grant.consumedAt) { + if ( + grant.action !== dto.action || + now.getTime() > grant.consumedAt.getTime() + 2 * MINUTE + ) + throw new ConflictException({ + code: 'TERMINAL_GRANT_CONSUMED', + message: 'Booking permission was already used', + }); + return { + response: this.receipt(grant), + entry: null, + action: dto.action, + }; + } + const challenge = await this.validateFreshGrant( + tx, + device, + grant, + now, + ); + const position = this.terminals.evaluateTerminalPosition( + dto, + device.terminal, + now, + ); + const schedule = await this.schedules.resolveForEmployee(employeeId); + const activity = + dto.activityId === undefined + ? undefined + : await resolveTerminalActivity( + tx, + employeeId, + dto.activityId, + device.terminal.activitySelectionEnabled, + ); + const booked = await bookTerminalTime( + tx, + employeeId, + challenge, + now, + schedule, + position, + dto.action, + activity, + ); + if (activity) + await tx.employee.update({ + where: { id: employeeId }, + data: { lastTerminalActivityId: activity.activityId }, + }); + const consumed = await tx.terminalBookingGrant.update({ + where: { id: grant.id }, + data: { + consumedAt: now, + action: dto.action, + timeEntryId: booked.entry.id, + bookedAt: now, }, - }) - ) - throw new ConflictException({ - code: 'TERMINAL_CHALLENGE_REPLAYED', - message: 'Identification challenge was already used', }); - const position = this.terminals.evaluateTerminalPosition( - dto, - device.terminal, - now, - ); - const schedule = await this.schedules.resolveForEmployee(employeeId); - const booked = await bookTerminalTime( - tx, - employeeId, - challenge, - now, - schedule, - position, - dto.action, - ); - const consumed = await tx.terminalBookingGrant.update({ - where: { id: grant.id }, - data: { - consumedAt: now, + await this.audit.append(tx, { + event: 'BookingAccepted', + result: 'SUCCESS', + method: 'PIN', action: dto.action, + employeeId, + terminalId: device.terminalId, + deviceId: device.id, + terminalName: device.terminal.name, + locationLabel: device.terminal.locationLabel, timeEntryId: booked.entry.id, - bookedAt: now, - }, - }); - await this.audit.append(tx, { - event: 'BookingAccepted', - result: 'SUCCESS', - method: 'PIN', - action: dto.action, - employeeId, - terminalId: device.terminalId, - deviceId: device.id, - terminalName: device.terminal.name, - locationLabel: device.terminal.locationLabel, - timeEntryId: booked.entry.id, - }); - return { - response: this.receipt(consumed), - entry: booked.entry, - action: booked.action, - }; - }); + }); + return { + response: this.receipt(consumed), + entry: booked.entry, + action: booked.action, + }; + }, + { isolationLevel: 'ReadCommitted' }, + ); if (result.entry) this.events.broadcast( result.action === 'clock-in' @@ -679,7 +944,12 @@ export class TerminalAuthService { terminalName: reservedDevice.terminal.name, locationLabel: reservedDevice.terminal.locationLabel, }); - if ((error as { code?: string }).code === 'P2002') + const code = (error as { code?: string }).code; + // A concurrent database change can still invalidate the catalog FK. + if ( + code === 'P2002' || + (dto.activityId !== undefined && (code === 'P2003' || code === 'P2034')) + ) throw new ConflictException({ code: 'TERMINAL_BOOKING_CONFLICT', message: 'Booking state changed', diff --git a/apps/api/src/app/terminals/terminal-booking.service.ts b/apps/api/src/app/terminals/terminal-booking.service.ts index a67f7b7..93457dc 100644 --- a/apps/api/src/app/terminals/terminal-booking.service.ts +++ b/apps/api/src/app/terminals/terminal-booking.service.ts @@ -3,14 +3,16 @@ import { ConflictException, NotFoundException, } from '@nestjs/common'; -import type { - Prisma, - Terminal, - TerminalChallenge, - TimeEntry, -} from '@prisma/client'; -import { requiresSpecialApproval } from 'shared'; +import type { Terminal, TerminalChallenge, TimeEntry } from '@prisma/client'; +import { Prisma } from '@prisma/client'; +import { randomUUID } from 'node:crypto'; +import { requiresSpecialApproval, type FrameTimeRule } from 'shared'; import type { WorkSchedulesService } from '../work-schedules/work-schedules.service'; +import { + TIME_ENTRY_ALLOCATION_INCLUDE as ENTRY_INCLUDE, + type TimeEntryWithAllocation, +} from '../time-entries/time-entries.dto'; +import type { TerminalActivityTarget } from './terminal-activity-selection'; export type TerminalPosition = { latitude: number; @@ -19,10 +21,74 @@ export type TerminalPosition = { positionTimestamp: Date; distanceMeters: number; } | null; -const ENTRY_INCLUDE = { - project: { select: { code: true, name: true } }, - serviceOrder: { select: { orderNo: true, title: true } }, -} as const; +export function findOpenTerminalEntry( + tx: Prisma.TransactionClient, + employeeId: string, +) { + return tx.timeEntry.findFirst({ + where: { employeeId, clockOut: null, voidedAt: null }, + orderBy: { clockIn: 'desc' }, + }); +} + +/** A virtual boundary, not two physical terminal bookings. */ +export async function switchTerminalActivity( + tx: Prisma.TransactionClient, + open: TimeEntry, + activity: TerminalActivityTarget, + at: Date, + frame: FrameTimeRule, +) { + if (at <= open.clockIn) + throw new ConflictException({ + code: 'TERMINAL_ACTIVITY_SWITCH_TOO_EARLY', + message: 'Clock has not advanced; retry the activity switch', + }); + + const captureGroupId = open.captureGroupId ?? randomUUID(); + const start = open.captureGroupId + ? await tx.timeEntry.findFirst({ + where: { employeeId: open.employeeId, captureGroupId }, + orderBy: [{ clockIn: 'asc' }, { id: 'asc' }], + select: { breakRules: true }, + }) + : open; + const requiresApproval = requiresSpecialApproval(open.clockIn, at, frame); + const closed = await tx.timeEntry.updateMany({ + where: { + id: open.id, + clockOut: null, + voidedAt: null, + revision: open.revision, + }, + data: { + captureGroupId, + clockOut: at, + revision: { increment: 1 }, + status: requiresApproval ? 'Pending' : 'Approved', + requiresApproval, + frameApproverId: null, + frameApprovedRevision: null, + }, + }); + if (closed.count !== 1) + throw new ConflictException('Time entry was already changed'); + + return tx.timeEntry.create({ + data: { + ...activity, + employeeId: open.employeeId, + clockIn: at, + source: 'Terminal', + status: 'Open', + approvalMode: open.approvalMode, + captureGroupId, + breakRules: (start ?? open).breakRules ?? Prisma.JsonNull, + requiresApproval: requiresSpecialApproval(at, null, frame), + }, + select: { id: true }, + }); +} /** Shared QR/PIN write path. Caller owns security locks, validation and audit. */ export async function bookTerminalTime( @@ -33,11 +99,9 @@ export async function bookTerminalTime( schedule: Awaited>, position: TerminalPosition, expectedAction?: 'clock-in' | 'clock-out', + activity?: TerminalActivityTarget, ) { - const open = await tx.timeEntry.findFirst({ - where: { employeeId, clockOut: null, voidedAt: null }, - orderBy: { clockIn: 'desc' }, - }); + const open = await findOpenTerminalEntry(tx, employeeId); const action = open ? 'clock-out' : 'clock-in'; if (expectedAction && expectedAction !== action) { throw new ConflictException({ @@ -47,10 +111,7 @@ export async function bookTerminalTime( }); } - let booked: TimeEntry & { - project: { code: string; name: string } | null; - serviceOrder: { orderNo: string; title: string } | null; - }; + let booked: TimeEntryWithAllocation; if (action === 'clock-in') { const today = localTodayAsUtcDate(bookingNow); const dailyBlock = await tx.timeEntry.findFirst({ @@ -62,6 +123,7 @@ export async function bookTerminalTime( } booked = await tx.timeEntry.create({ data: { + ...activity, employeeId, clockIn: bookingNow, source: 'Terminal', diff --git a/apps/api/src/app/terminals/terminal-security-locks.ts b/apps/api/src/app/terminals/terminal-security-locks.ts index 14e48c2..919332f 100644 --- a/apps/api/src/app/terminals/terminal-security-locks.ts +++ b/apps/api/src/app/terminals/terminal-security-locks.ts @@ -10,6 +10,10 @@ export async function lockTerminalSecurity( await tx.$executeRaw`SELECT pg_advisory_xact_lock(7261500)`; if (employeeId) await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${employeeId}, 0))`; + await assertTerminalTeamMode(tx); +} + +export async function assertTerminalTeamMode(tx: Prisma.TransactionClient) { const settings = await tx.installationSettings.findUnique({ where: { id: 1 }, select: { mode: true }, diff --git a/apps/api/src/app/terminals/terminals.dto.ts b/apps/api/src/app/terminals/terminals.dto.ts index 0484809..e00841b 100644 --- a/apps/api/src/app/terminals/terminals.dto.ts +++ b/apps/api/src/app/terminals/terminals.dto.ts @@ -1,4 +1,10 @@ -import { ApiProperty, ApiPropertyOptional, PartialType } from '@nestjs/swagger'; +import { + ApiProperty, + ApiPropertyOptional, + OmitType, + PartialType, +} from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; import { IsBoolean, IsArray, @@ -136,9 +142,30 @@ export class CreateTerminalDto { @IsOptional() @IsBoolean() isActive?: boolean; + + @ApiPropertyOptional({ + description: + 'Allow activity selection at this terminal. Defaults to false.', + }) + // Do not let implicit conversion turn the string "false" into true. + @Transform(({ obj }) => obj.activitySelectionEnabled) + @ValidateIf((_object, value) => value !== undefined) + @IsBoolean() + activitySelectionEnabled?: boolean; } -export class UpdateTerminalDto extends PartialType(CreateTerminalDto) {} +export class UpdateTerminalDto extends PartialType( + OmitType(CreateTerminalDto, ['activitySelectionEnabled'] as const), +) { + @ApiPropertyOptional({ + description: + 'Allow activity selection at this terminal. Omit to leave unchanged.', + }) + @Transform(({ obj }) => obj.activitySelectionEnabled) + @ValidateIf((_object, value) => value !== undefined) + @IsBoolean() + activitySelectionEnabled?: boolean; +} export class TerminalDeviceDto { @ApiProperty({ format: 'uuid' }) @@ -198,6 +225,9 @@ export class TerminalDto { @ApiProperty() isActive!: boolean; + @ApiProperty() + activitySelectionEnabled!: boolean; + @ApiProperty() isPaired!: boolean; @@ -387,6 +417,7 @@ export function toTerminalDto(terminal: TerminalWithDevices): TerminalDto { maxAccuracyMeters: terminal.maxAccuracyMeters, timeZone: terminal.timeZone, isActive: terminal.isActive, + activitySelectionEnabled: terminal.activitySelectionEnabled, isPaired: activeDevices.length > 0, deviceCount: activeDevices.length, activatedAt: terminal.activatedAt?.toISOString() ?? null, diff --git a/apps/api/src/app/terminals/terminals.service.ts b/apps/api/src/app/terminals/terminals.service.ts index b5d4c11..f845f85 100644 --- a/apps/api/src/app/terminals/terminals.service.ts +++ b/apps/api/src/app/terminals/terminals.service.ts @@ -9,7 +9,7 @@ import { UnauthorizedException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { Prisma, type Terminal, type TimeEntry } from '@prisma/client'; +import { Prisma, type Terminal } from '@prisma/client'; import { createHash, createHmac, randomBytes } from 'node:crypto'; import { bookTerminalTime } from './terminal-booking.service'; import { TerminalAuditService } from './terminal-audit.service'; @@ -21,6 +21,7 @@ import { import { EventsGateway } from '../events/events.gateway'; import { PrismaService } from '../prisma/prisma.service'; import { WorkSchedulesService } from '../work-schedules/work-schedules.service'; +import { loadCaptureSummaries } from '../time-entries/capture-summary'; import { toTimeEntryDto } from '../time-entries/time-entries.dto'; import { toTerminalDto, @@ -493,7 +494,7 @@ export class TerminalsService { where: { terminalId: device.terminalId, expiresAt: { lt: cleanupBefore }, - redemptions: { none: {} }, + redemptions: { none: { timeEntryId: { not: null } } }, clockInTimeEntries: { none: {} }, clockOutTimeEntries: { none: {} }, }, @@ -606,6 +607,7 @@ export class TerminalsService { await this.prisma.terminalChallengeRedemption.count({ where: { employeeId, + action: { in: ['clock-in', 'clock-out'] }, createdAt: { gt: new Date(now.getTime() - 60_000) }, }, }); @@ -660,10 +662,7 @@ export class TerminalsService { const schedule = await this.schedules.resolveForEmployee(employeeId); let action: BookingAction = 'clock-in'; let acceptedPosition = position; - let entry: TimeEntry & { - project: { code: string; name: string } | null; - serviceOrder: { orderNo: string; title: string } | null; - }; + let entry: ScanTerminalResultDto['entry']; try { const result = await this.prisma.$transaction( async (tx) => { @@ -743,7 +742,12 @@ export class TerminalsService { }, false, ); - return booked.entry; + const entryDto = toTimeEntryDto(booked.entry); + if (booked.entry.captureGroupId) { + const summaries = await loadCaptureSummaries(tx, [booked.entry]); + entryDto.summary = summaries.get(booked.entry.id) ?? null; + } + return entryDto; }, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }, ); @@ -762,18 +766,18 @@ export class TerminalsService { this.events.broadcast('time-entry:created', { id: entry.id, employeeId: entry.employeeId, - clockIn: entry.clockIn.toISOString(), + clockIn: entry.clockIn, }); } else { this.events.broadcast('time-entry:updated', { id: entry.id, employeeId: entry.employeeId, - clockOut: entry.clockOut?.toISOString() ?? null, + clockOut: entry.clockOut, }); } return { action, - entry: toTimeEntryDto(entry), + entry, distanceMeters: acceptedPosition === null ? null @@ -819,6 +823,7 @@ export class TerminalsService { enforceGeofence, ...geofence, timeZone, + activitySelectionEnabled: dto.activitySelectionEnabled, }; } @@ -883,6 +888,8 @@ export class TerminalsService { this.assertTimeZone(timeZone); data.timeZone = timeZone; } + if (dto.activitySelectionEnabled !== undefined) + data.activitySelectionEnabled = dto.activitySelectionEnabled; if (dto.isActive !== undefined) data.isActive = dto.isActive; if (dto.isActive === false) { data.pairingCodeHash = null; diff --git a/apps/api/src/app/time-entries/time-entries.controller.ts b/apps/api/src/app/time-entries/time-entries.controller.ts index 11cb3bb..9327803 100644 --- a/apps/api/src/app/time-entries/time-entries.controller.ts +++ b/apps/api/src/app/time-entries/time-entries.controller.ts @@ -37,6 +37,7 @@ import { VoidTimeEntryDto, SwitchProjectDto, TimeEntryAuditDto, + TimeEntryActivityOptionDto, SplitTimeEntryDto, UpdateTimeEntryDto, BookProjectRangeResult, @@ -231,6 +232,25 @@ export class TimeEntriesController { return this.entries.update(id, dto, user); } + @Get(':id/activity-options') + @ApiQuery({ + name: 'projectId', + required: false, + schema: { type: 'string', format: 'uuid' }, + description: 'Proposed booking project; defaults to the entry’s project.', + }) + @ApiOkResponse({ type: TimeEntryActivityOptionDto, isArray: true }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard) + activityOptions( + @Param('id', new ParseUUIDPipe()) id: string, + @CurrentUser() user: JwtUser, + @Query('projectId', new ParseUUIDPipe({ optional: true })) + projectId?: string, + ): Promise { + return this.entries.activityOptions(id, user, projectId); + } + @Post(':id/split') @ApiCreatedResponse({ type: SplitTimeEntryResult }) @ApiBearerAuth() diff --git a/apps/api/src/app/time-entries/time-entries.dto.ts b/apps/api/src/app/time-entries/time-entries.dto.ts index b3d60b7..613b442 100644 --- a/apps/api/src/app/time-entries/time-entries.dto.ts +++ b/apps/api/src/app/time-entries/time-entries.dto.ts @@ -17,7 +17,7 @@ import { ValidateNested, } from 'class-validator'; import { Type } from 'class-transformer'; -import type { TimeEntry } from '@prisma/client'; +import type { Prisma, TimeEntry } from '@prisma/client'; import { summarize, parseBreakRules, type TimeSummary } from 'shared'; const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; @@ -214,7 +214,8 @@ export class ClockOutDto { /** * Retroactive booking-target update. At least one key must be present. * Sending projectId re-specifies the target completely (the conditional- - * mandatory service-order rule applies); activity is editable on its own. + * mandatory service-order rule applies when changing the target). Free text + * and the structured activity can each be edited on their own. */ export class UpdateTimeEntryDto { @ApiPropertyOptional({ type: String, nullable: true, maxLength: 2000 }) @@ -252,6 +253,25 @@ export class UpdateTimeEntryDto { @IsString() @MaxLength(500) activity?: string | null; + + @ApiPropertyOptional({ + type: String, + format: 'uuid', + nullable: true, + description: + 'Active catalog activity of the effective project. Null clears it; omission preserves it unless the project changes.', + }) + @IsOptional() + @IsUUID() + activityId?: string | null; +} + +export class TimeEntryActivityOptionDto { + @ApiProperty({ format: 'uuid' }) + id!: string; + + @ApiProperty() + name!: string; } export class SplitTimeEntryDto { @@ -515,6 +535,12 @@ export class TimeEntryDto { @ApiProperty({ type: String, nullable: true }) activity!: string | null; + @ApiProperty({ type: String, format: 'uuid', nullable: true }) + activityId!: string | null; + + @ApiProperty({ type: String, nullable: true }) + catalogActivityName!: string | null; + @ApiProperty({ type: TimeSummaryDto, nullable: true }) summary!: TimeSummary | null; } @@ -532,9 +558,20 @@ export class BookProjectRangeResult { entries!: TimeEntryDto[]; } +export const TIME_ENTRY_ALLOCATION_INCLUDE = { + project: { select: { code: true, name: true } }, + serviceOrder: { select: { orderNo: true, title: true } }, + catalogActivity: { select: { name: true } }, +} as const satisfies Prisma.TimeEntryInclude; + +export type TimeEntryWithAllocation = Prisma.TimeEntryGetPayload<{ + include: typeof TIME_ENTRY_ALLOCATION_INCLUDE; +}>; + type TimeEntryWithRelations = TimeEntry & { - project?: { code: string; name: string } | null; - serviceOrder?: { orderNo: string; title: string } | null; + project?: TimeEntryWithAllocation['project']; + serviceOrder?: TimeEntryWithAllocation['serviceOrder']; + catalogActivity?: TimeEntryWithAllocation['catalogActivity']; }; export function toTimeEntryDto(e: TimeEntryWithRelations): TimeEntryDto { @@ -590,6 +627,8 @@ export function toTimeEntryDto(e: TimeEntryWithRelations): TimeEntryDto { serviceOrderNo: e.serviceOrder?.orderNo ?? null, serviceOrderTitle: e.serviceOrder?.title ?? null, activity: e.activity ?? null, + activityId: e.activityId ?? null, + catalogActivityName: e.catalogActivity?.name ?? null, summary: e.clockOut && !e.voidedAt && e.status !== 'Rejected' ? summarize(e.clockIn, e.clockOut, parseBreakRules(e.breakRules)) 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 86c692d..6091c43 100644 --- a/apps/api/src/app/time-entries/time-entries.service.ts +++ b/apps/api/src/app/time-entries/time-entries.service.ts @@ -36,6 +36,7 @@ import type { ProxyManualTimeEntryDto, } from './proxy-time-entry.dto'; import { + TIME_ENTRY_ALLOCATION_INCLUDE as ENTRY_INCLUDE, toTimeEntryDto, type BookProjectRangeDto, type BookProjectRangeResult, @@ -45,7 +46,9 @@ import { type DailyBlockOptionDto, type SplitTimeEntryDto, type SplitTimeEntryResult, + type TimeEntryActivityOptionDto, type TimeEntryDto, + type TimeEntryWithAllocation, type UpdateTimeEntryDto, type ManualTimeEntryDto, type CorrectTimeEntryDto, @@ -54,15 +57,6 @@ import { type TimeEntryAuditDto, } from './time-entries.dto'; -const PROJECT_SELECT = { select: { code: true, name: true } } as const; -const SERVICE_ORDER_SELECT = { - select: { orderNo: true, title: true }, -} as const; -const ENTRY_INCLUDE = { - project: PROJECT_SELECT, - serviceOrder: SERVICE_ORDER_SELECT, -} as const; - /** Booking-target fields carried by every project booking path. */ interface BookingTarget { projectId: string | null; @@ -871,12 +865,47 @@ export class TimeEntriesService { return (await this.withCaptureSummaries([updated]))[0]; } + /** Read-only catalog choices bound to an editable entry and its employee. */ + async activityOptions( + id: string, + user: JwtUser, + projectId?: string, + ): Promise { + return this.prisma.$transaction( + async (tx) => { + const entry = await tx.timeEntry.findUnique({ + where: { id }, + select: { employeeId: true, projectId: true, voidedAt: true }, + }); + if (!entry) throw new NotFoundException(`Time entry ${id} not found`); + this.assertSelfOrAdmin(entry.employeeId, user); + await this.assertTransactionAccess( + tx, + entry.employeeId, + undefined, + user.id, + ); + const targetProject = projectId ?? entry.projectId; + if (!targetProject || entry.voidedAt) return []; + return tx.activity.findMany({ + where: this.catalogActivityEligibility( + entry.employeeId, + targetProject, + ), + select: { id: true, name: true }, + orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }, { id: 'asc' }], + }); + }, + { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }, + ); + } + /** * Retroactively updates the booking target (project / service order) and - * the activity of an entry. Sending projectId re-specifies the target - * completely; activity is editable on its own without project validation - * (keeps legacy entries editable). Allowed regardless of approval status — - * attendance totals never change here. + * activities of an entry. Free text remains independently editable. A + * catalog correction can retain an unchanged historical booking target; + * a different target must satisfy the current booking rules. Attendance + * totals never change here, regardless of approval status. */ async update( id: string, @@ -887,19 +916,39 @@ export class TimeEntriesService { dto.projectId === undefined && dto.serviceOrderId === undefined && dto.activity === undefined && + dto.activityId === undefined && dto.billable === undefined && dto.note === undefined ) { throw new BadRequestException( - 'At least one of projectId, serviceOrderId, activity must be provided', + 'At least one of projectId, serviceOrderId, activity, activityId, billable, or note must be provided', ); } const entry = await this.findOrThrow(id); await this.assertAccess(entry.employeeId, user); this.assertMutable(entry, dto.revision); + const nextProjectId = + dto.projectId === undefined ? entry.projectId : dto.projectId; + const nextServiceOrderId = + dto.projectId !== undefined + ? (dto.serviceOrderId ?? null) + : dto.serviceOrderId === undefined + ? entry.serviceOrderId + : dto.serviceOrderId; + const replacesTarget = + (dto.projectId !== undefined || dto.serviceOrderId !== undefined) && + (dto.activityId === undefined || + nextProjectId !== entry.projectId || + nextServiceOrderId !== entry.serviceOrderId); + const activityOnly = + dto.activityId !== undefined && + !replacesTarget && + dto.activity === undefined && + dto.note === undefined && + dto.billable === undefined; const data: Prisma.TimeEntryUncheckedUpdateInput = {}; - if (dto.projectId !== undefined) { + if (replacesTarget && dto.projectId !== undefined) { const target = await this.resolveBookingTarget( entry.employeeId, dto.projectId, @@ -910,7 +959,7 @@ export class TimeEntriesService { data.projectId = target.projectId; data.serviceOrderId = target.serviceOrderId; data.billable = target.billable; - } else if (dto.serviceOrderId !== undefined) { + } else if (replacesTarget && dto.serviceOrderId !== undefined) { if (dto.serviceOrderId !== null && entry.projectId === null) { throw new BadRequestException('serviceOrderId requires a projectId'); } @@ -939,25 +988,53 @@ export class TimeEntriesService { throw new BadRequestException('revision is required in Solo mode'); const current = await tx.timeEntry.findUniqueOrThrow({ where: { id } }); this.assertMutable(current, dto.revision, entry.revision); - if (dto.projectId !== undefined || dto.serviceOrderId !== undefined) { - await this.assertTargetStillBookable(tx, { - projectId: - dto.projectId === undefined ? current.projectId : dto.projectId, - serviceOrderId: - dto.projectId !== undefined - ? (data.serviceOrderId as string | null) - : (dto.serviceOrderId ?? null), - activity: current.activity, - billable: current.billable, - }); + if (replacesTarget) { + await this.assertTargetStillBookable( + tx, + { projectId: nextProjectId, serviceOrderId: nextServiceOrderId }, + current.employeeId, + ); + } + if (dto.activityId) { + // The installation lock acquired above also serializes catalog, + // assignment and order changes. Recheck against their live state. + if ( + !nextProjectId || + !(await tx.activity.findFirst({ + where: { + id: dto.activityId, + ...this.catalogActivityEligibility( + current.employeeId, + nextProjectId, + nextServiceOrderId, + ), + }, + select: { id: true }, + })) + ) { + throw new BadRequestException( + 'Activity is not available for this booking project or service order', + ); + } } + // Catalog-only corrections do not change the frame facts a manager or + // HR already reviewed. Keep any current manager sign-off on this revision. + const invalidatesFrameApproval = + !activityOnly && + current.approvalMode !== 'Solo' && + current.requiresApproval; const before = await this.auditSnapshot(tx, current); const row = await tx.timeEntry.update({ where: { id }, data: { ...data, + ...(dto.activityId !== undefined + ? { activityId: dto.activityId } + : nextProjectId !== current.projectId + ? { activityId: null } + : {}), revision: { increment: 1 }, - ...(current.approvalMode !== 'Solo' && current.requiresApproval + ...(invalidatesFrameApproval ? { frameApproverId: null, frameApprovedRevision: null, @@ -967,11 +1044,13 @@ export class TimeEntriesService { ? { status: 'Pending' as const } : {}), } - : {}), + : activityOnly && current.frameApprovedRevision === current.revision + ? { frameApprovedRevision: current.revision + 1 } + : {}), }, include: ENTRY_INCLUDE, }); - if (current.approvalMode !== 'Solo' && current.requiresApproval) + if (invalidatesFrameApproval) await this.writeAudit( tx, row, @@ -980,7 +1059,11 @@ export class TimeEntriesService { before, null, ); - if (isSolo || current.approvalMode === 'Solo') + if ( + isSolo || + current.approvalMode === 'Solo' || + dto.activityId !== undefined + ) await this.writeAudit(tx, row, user.id, 'BookingUpdated', before, null); return row; }); @@ -1068,7 +1151,7 @@ export class TimeEntriesService { const current = await tx.timeEntry.findUniqueOrThrow({ where: { id } }); this.assertMutable(current, dto.revision, entry.revision); if (dto.projectId !== undefined) - await this.assertTargetStillBookable(tx, second); + await this.assertTargetStillBookable(tx, second, current.employeeId); const before = await this.auditSnapshot(tx, current); const captureGroupId = entry.captureGroupId ?? @@ -1120,6 +1203,7 @@ export class TimeEntriesService { clockOutTerminalId: entry.clockOutTerminalId, clockOutChallengeId: entry.clockOutChallengeId, ...second, + activityId: this.activityForProject(current, second.projectId), }, include: ENTRY_INCLUDE, }); @@ -1220,7 +1304,7 @@ export class TimeEntriesService { undefined, user.id, ); - await this.assertTargetStillBookable(tx, target); + await this.assertTargetStillBookable(tx, target, dto.employeeId); const overlapping = await tx.timeEntry.findMany({ where: { employeeId: dto.employeeId, @@ -1248,12 +1332,7 @@ export class TimeEntriesService { 'Time entries changed; reload before booking the range', ); } - const changed: Array< - TimeEntry & { - project: { code: string; name: string } | null; - serviceOrder: { orderNo: string; title: string } | null; - } - > = []; + const changed: TimeEntryWithAllocation[] = []; for (const entry of overlapping) { const before = await this.auditSnapshot(tx, entry); const end = entry.clockOut as Date; @@ -1292,6 +1371,7 @@ export class TimeEntriesService { ? ('Pending' as const) : ('Approved' as const), ...booking, + activityId: this.activityForProject(entry, booking.projectId), ...(clockOut.getTime() === end.getTime() ? this.clockOutAudit(entry) : this.clearClockOutAudit()), @@ -1448,7 +1528,7 @@ export class TimeEntriesService { const current = await tx.timeEntry.findUniqueOrThrow({ where: { id } }); this.assertMutable(current, dto.revision, entry.revision); if (dto.projectId !== undefined || dto.serviceOrderId !== undefined) - await this.assertTargetStillBookable(tx, target); + await this.assertTargetStillBookable(tx, target, current.employeeId); await this.assertNoOverlap(tx, user.id, clockIn, clockOut, id); const before = await this.auditSnapshot(tx, current); const corrected = await tx.timeEntry.update({ @@ -1458,6 +1538,7 @@ export class TimeEntriesService { clockOut, ...target, ...(dto.note !== undefined ? { note: dto.note } : {}), + activityId: this.activityForProject(current, target.projectId), // A corrected block becomes an ordinary interval; the audit retains its date. bookingDate: current.source === 'DailyBlock' ? null : current.bookingDate, @@ -1712,6 +1793,34 @@ export class TimeEntriesService { }; } + private activityForProject( + entry: TimeEntry, + projectId: string | null, + ): string | null { + return projectId === entry.projectId ? entry.activityId : null; + } + + private catalogActivityEligibility( + employeeId: string, + projectId: string, + serviceOrderId?: string | null, + ): Prisma.ActivityWhereInput { + return { + projectId, + isActive: true, + project: { + isActive: true, + assignments: { some: { employeeId } }, + OR: [{ customerId: null }, { customer: { isActive: true } }], + // This also verifies the order belongs to the effective project. + // No order is OK for an unchanged historical project-level entry. + ...(serviceOrderId + ? { serviceOrders: { some: { id: serviceOrderId, isActive: true } } } + : {}), + }, + }; + } + /** Union-walk over sorted entries; throws 400 with the covered windows. */ private assertRangeCovered(from: Date, to: Date, sorted: TimeEntry[]): void { let cursor = from.getTime(); @@ -1865,7 +1974,8 @@ export class TimeEntriesService { private async assertTargetStillBookable( tx: Prisma.TransactionClient, - target: BookingTarget, + target: Pick, + employeeId?: string, ): Promise { if (!target.projectId) return; const initial = await tx.project.findUnique({ @@ -1890,6 +2000,17 @@ export class TimeEntriesService { throw new ConflictException( 'Project customer changed; reload before booking', ); + if ( + employeeId && + !(await tx.projectAssignment.findUnique({ + where: { + employeeId_projectId: { employeeId, projectId: target.projectId }, + }, + select: { employeeId: true }, + })) + ) { + throw new ForbiddenException('Employee is not assigned to the project'); + } if (target.serviceOrderId) { const order = await tx.serviceOrder.findUnique({ where: { id: target.serviceOrderId }, @@ -2058,6 +2179,7 @@ export class TimeEntriesService { projectId: entry.projectId, serviceOrderId: entry.serviceOrderId, activity: entry.activity, + activityId: entry.activityId, note: entry.note, billable: entry.billable, revision: entry.revision, diff --git a/apps/api/src/app/time-entries/time-entry-approvals.service.ts b/apps/api/src/app/time-entries/time-entry-approvals.service.ts index e53afae..216f0dd 100644 --- a/apps/api/src/app/time-entries/time-entry-approvals.service.ts +++ b/apps/api/src/app/time-entries/time-entry-approvals.service.ts @@ -10,7 +10,10 @@ import type { TimeSummary } from 'shared'; import type { JwtUser } from '../auth/jwt.strategy'; import { PrismaService } from '../prisma/prisma.service'; import { EventsGateway } from '../events/events.gateway'; -import { toTimeEntryDto } from './time-entries.dto'; +import { + TIME_ENTRY_ALLOCATION_INCLUDE, + toTimeEntryDto, +} from './time-entries.dto'; import { loadCaptureSummaries } from './capture-summary'; import { type DecideTimeEntryApprovalDto, @@ -20,8 +23,7 @@ import { } from './time-entry-approvals.dto'; const APPROVAL_INCLUDE = { - project: { select: { code: true, name: true } }, - serviceOrder: { select: { orderNo: true, title: true } }, + ...TIME_ENTRY_ALLOCATION_INCLUDE, employee: { select: { id: true, @@ -44,8 +46,19 @@ const APPROVAL_INCLUDE = { type ReviewEntry = Prisma.TimeEntryGetPayload<{ include: typeof APPROVAL_INCLUDE; }>; +type ReviewStateInput = Pick< + ReviewEntry, + | 'voidedAt' + | 'clockOut' + | 'status' + | 'employee' + | 'employeeId' + | 'frameApproverId' + | 'frameApprovedRevision' + | 'revision' +>; -function validManager(row: ReviewEntry): boolean { +function validManager(row: ReviewStateInput): boolean { const manager = row.employee.manager; return ( !!manager?.isActive && @@ -54,7 +67,7 @@ function validManager(row: ReviewEntry): boolean { ); } -export function frameApprovalState(row: ReviewEntry): EntryApprovalState { +export function frameApprovalState(row: ReviewStateInput): EntryApprovalState { if (row.voidedAt) return 'Voided'; if (!row.clockOut || row.status === 'Open') return 'Open'; if (row.status === 'Approved') return 'Approved'; 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 4550d17..9b5ffff 100644 --- a/apps/api/src/app/work-schedules/work-schedules.service.ts +++ b/apps/api/src/app/work-schedules/work-schedules.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import type { + Prisma, TimeModel, WorkSchedule, WorkScheduleCoreTime, @@ -253,8 +254,12 @@ export class WorkSchedulesService { * 2. The schedule with isDefault = true — fallback * 3. Built-in DEFAULT_FRAME with no core windows — final fallback */ - async resolveForEmployee(employeeId: string): Promise { - const employee = await this.prisma.employee.findUnique({ + async resolveForEmployee( + employeeId: string, + db: Pick = this + .prisma, + ): Promise { + const employee = await db.employee.findUnique({ where: { id: employeeId }, include: { workSchedule: { include: { coreTimes: { orderBy: { start: 'asc' } } } }, @@ -270,7 +275,7 @@ export class WorkSchedulesService { const schedule = employee.workSchedule ? employee.workSchedule - : await this.prisma.workSchedule.findFirst({ + : await db.workSchedule.findFirst({ where: { isDefault: true }, include: { coreTimes: { orderBy: { start: 'asc' } } }, }); diff --git a/apps/web-e2e/src/terminal-pin.spec.ts b/apps/web-e2e/src/terminal-pin.spec.ts index ec70686..0e3d578 100644 --- a/apps/web-e2e/src/terminal-pin.spec.ts +++ b/apps/web-e2e/src/terminal-pin.spec.ts @@ -3,14 +3,26 @@ import { test as base, expect, type APIRequestContext, + type Locator, type Page, } from '@playwright/test'; +type TimeEntry = { + id: string; + clockIn: string; + clockOut: string | null; + captureGroupId: string | null; + activityId: string | null; +}; + type TerminalFixture = { employeeId: string; + terminalId: string; personalNo: string; pin: string; pairingCode: string; + listEntries: () => Promise; + catalog?: { projectId: string; first: string; second: string }; }; function assertLocalTestTarget(baseURL: string | undefined) { @@ -30,8 +42,12 @@ function assertLocalTestTarget(baseURL: string | undefined) { } /** Real API + isolated synthetic records. Never target a production installation. */ -const test = base.extend<{ terminal: TerminalFixture }>({ - terminal: async ({ request, baseURL }, use) => { +const test = base.extend<{ + activitySelectionEnabled: boolean; + terminal: TerminalFixture; +}>({ + activitySelectionEnabled: [false, { option: true }], + terminal: async ({ request, baseURL, activitySelectionEnabled }, use) => { // Check before the first request: these tests create and revoke HR records. assertLocalTestTarget(baseURL); const login = await request.post('/api/auth/login', { @@ -47,6 +63,8 @@ const test = base.extend<{ terminal: TerminalFixture }>({ const personalNo = `00-pin-${suffix}`; let employeeId: string | undefined; let terminalId: string | undefined; + let projectId: string | undefined; + const project = { code: `PIN-${suffix}`, name: `E2E project ${suffix}` }; try { const employee = await request.post('/api/employees', { headers, @@ -84,10 +102,12 @@ const test = base.extend<{ terminal: TerminalFixture }>({ maxAccuracyMeters: null, isActive: true, allowedAuthMethods: ['PIN'], + activitySelectionEnabled, }, }); expect(created.ok()).toBe(true); - terminalId = (await created.json()).id; + const terminalRecord = (await created.json()) as { id: string }; + terminalId = terminalRecord.id; const reset = await request.post( `/api/employees/${employeeId}/terminal-credentials/pin/reset`, { headers, data: {} }, @@ -100,14 +120,59 @@ const test = base.extend<{ terminal: TerminalFixture }>({ ); expect(pairing.ok()).toBe(true); const { pairingCode } = await pairing.json(); + let catalog: TerminalFixture['catalog']; + if (activitySelectionEnabled) { + const createdProject = await request.post('/api/projects', { + headers, + data: project, + }); + expect(createdProject.ok()).toBe(true); + const projectRecord = (await createdProject.json()) as { id: string }; + projectId = projectRecord.id; + const assignment = await request.put( + `/api/projects/${projectId}/assignments/${employeeId}`, + { headers }, + ); + expect(assignment.status()).toBe(204); + const addActivity = async (name: string) => { + const response = await request.post( + `/api/projects/${projectId}/activities`, + { headers, data: { name } }, + ); + expect(response.ok()).toBe(true); + return ((await response.json()) as { id: string }).id; + }; + catalog = { + projectId, + first: await addActivity('Synthetic picking'), + second: await addActivity('Synthetic sorting'), + }; + } await use({ employeeId: employeeRecord.id, + terminalId: terminalRecord.id, personalNo, pin, pairingCode, + catalog, + listEntries: async () => { + const response = await request.get('/api/timeentries', { + headers, + params: { employeeId: employeeRecord.id }, + }); + expect(response.ok()).toBe(true); + return (await response.json()) as TimeEntry[]; + }, }); } finally { await cleanup(request, headers, terminalId, employeeId); + if (projectId) { + // Booked history is deliberately not deleted. This test target is disposable. + await request.put(`/api/projects/${projectId}`, { + headers, + data: { ...project, isActive: false }, + }); + } } }, }); @@ -147,6 +212,39 @@ async function identify( await page.getByRole('button', { name: 'Anmeldung prüfen' }).click(); } +async function book( + page: Page, + button: Locator, + action: 'clock-in' | 'clock-out', +) { + const [response] = await Promise.all([ + page.waitForResponse( + (response) => + new URL(response.url()).pathname === '/api/terminals/kiosk/book' && + response.request().method() === 'POST', + ), + button.click(), + ]); + expect(response.status()).toBe(201); + const receipt = (await response.json()) as { + action: string; + bookedAt: string; + }; + expect(receipt.action).toBe(action); + await expect( + page.getByText( + action === 'clock-in' ? 'Einstempeln bestätigt' : 'Ausstempeln bestätigt', + { exact: true }, + ), + ).toBeVisible(); + return receipt.bookedAt; +} + +function required(value: T | undefined, description: string): T { + if (value === undefined) throw new Error(`Missing ${description}`); + return value; +} + test('Terminal PIN: paired PIN-only terminal explicitly clocks in and out without an employee session', async ({ page, terminal, @@ -187,6 +285,143 @@ test('Terminal PIN: paired PIN-only terminal explicitly clocks in and out withou await expect(page.getByLabel('Terminal-PIN', { exact: true })).toHaveCount(0); }); +test.describe('Terminal PIN with the activity picker enabled', () => { + test.use({ activitySelectionEnabled: true }); + + test('switches activity within one attendance and still clocks out with one tap', async ({ + page, + terminal, + }) => { + const catalog = required(terminal.catalog, 'synthetic activity catalog'); + const picking = page.getByRole('button', { name: /^Synthetic picking/ }); + const sorting = page.getByRole('button', { name: /^Synthetic sorting/ }); + const clockIn = page.getByRole('button', { name: 'Jetzt einstempeln' }); + const clockOut = page.getByRole('button', { name: 'Jetzt ausstempeln' }); + const finish = page.getByRole('button', { name: 'Vorgang beenden' }); + + await pair(page, terminal); + await identify(page, terminal); + await picking.click(); + await expect(picking).toHaveAttribute('aria-pressed', 'true'); + const arrival = await book(page, clockIn, 'clock-in'); + const opened = await terminal.listEntries(); + expect(opened).toEqual([ + expect.objectContaining({ + clockIn: arrival, + clockOut: null, + activityId: catalog.first, + projectId: catalog.projectId, + terminalId: terminal.terminalId, + }), + ]); + + await finish.click(); + await identify(page, terminal); + await expect(picking).toHaveAttribute('aria-pressed', 'true'); + await sorting.click(); + await page.getByRole('button', { name: 'Tätigkeit wechseln' }).click(); + await expect( + page.getByText('Tätigkeit gewechselt', { exact: true }), + ).toBeVisible(); + + const switched = await terminal.listEntries(); + expect(switched).toHaveLength(2); + const first = required( + switched.find((entry) => entry.activityId === catalog.first), + 'original activity segment', + ); + const second = required( + switched.find((entry) => entry.activityId === catalog.second), + 'new activity segment', + ); + expect(first).toMatchObject({ + id: opened[0].id, + clockIn: arrival, + clockOut: expect.any(String), + captureGroupId: expect.any(String), + clockOutTerminalId: null, + }); + expect(second).toMatchObject({ + clockIn: first.clockOut, + clockOut: null, + captureGroupId: first.captureGroupId, + projectId: catalog.projectId, + }); + expect(Date.parse(second.clockIn)).toBeGreaterThan(Date.parse(arrival)); + + await finish.click(); + await identify(page, terminal); + await expect(sorting).toHaveAttribute('aria-pressed', 'true'); + // No interaction with the optional picker is needed before or after clock-out. + const departure = await book(page, clockOut, 'clock-out'); + await expect( + page.getByRole('button', { name: 'Tätigkeit wechseln' }), + ).toHaveCount(0); + expect(Date.parse(departure)).toBeGreaterThan(Date.parse(second.clockIn)); + const closed = await terminal.listEntries(); + expect(closed).toHaveLength(2); + expect(closed).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: first.id, + activityId: catalog.first, + clockIn: arrival, + clockOut: first.clockOut, + captureGroupId: first.captureGroupId, + clockOutTerminalId: null, + }), + expect.objectContaining({ + id: second.id, + activityId: catalog.second, + projectId: catalog.projectId, + clockIn: first.clockOut, + clockOut: departure, + captureGroupId: first.captureGroupId, + clockOutTerminalId: terminal.terminalId, + }), + ]), + ); + }); + + test('clocks in and out normally when no activity is selected', async ({ + page, + terminal, + }) => { + await pair(page, terminal); + await identify(page, terminal); + await expect( + page.getByRole('button', { name: /^Synthetic picking/ }), + ).toBeVisible(); + await page + .getByRole('button', { name: 'Ohne Tätigkeit', exact: true }) + .click(); + const arrival = await book( + page, + page.getByRole('button', { name: 'Jetzt einstempeln' }), + 'clock-in', + ); + await page.getByRole('button', { name: 'Vorgang beenden' }).click(); + await identify(page, terminal); + const departure = await book( + page, + page.getByRole('button', { name: 'Jetzt ausstempeln' }), + 'clock-out', + ); + expect(await terminal.listEntries()).toEqual([ + expect.objectContaining({ + clockIn: arrival, + clockOut: departure, + source: 'Terminal', + terminalId: terminal.terminalId, + clockOutTerminalId: terminal.terminalId, + projectId: null, + activityId: null, + captureGroupId: null, + }), + ]); + }); +}); + test('Terminal PIN: incorrect PIN preserves pairing and cancellation does not clock in', async ({ page, terminal, diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 6461608..2a76d6f 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -1,3 +1,5 @@ +import type { components } from './generated'; + const baseUrl = import.meta.env.VITE_API_BASE_URL ?? ''; export type EmployeeRole = 'Employee' | 'Manager' | 'HRAdmin'; @@ -353,6 +355,8 @@ export interface TimeEntryDto { serviceOrderNo: string | null; serviceOrderTitle: string | null; activity: string | null; + activityId: string | null; + catalogActivityName: string | null; summary: TimeSummaryDto | null; } @@ -433,8 +437,12 @@ export interface UpdateTimeEntryPayload { projectId?: string | null; serviceOrderId?: string | null; activity?: string | null; + activityId?: string | null; } +export type TimeEntryActivityOptionDto = + components['schemas']['TimeEntryActivityOptionDto']; + export interface SplitTimeEntryPayload { at: string; projectId?: string | null; @@ -481,6 +489,9 @@ export interface ServiceOrderDto { bookedMinutes: number; } +export type ActivityDto = components['schemas']['ActivityDto']; +export type UpsertActivityPayload = components['schemas']['UpsertActivityDto']; + export interface ProjectDto { id: string; code: string; @@ -845,6 +856,7 @@ export interface TerminalDto { radiusMeters: number | null; maxAccuracyMeters: number | null; isActive: boolean; + activitySelectionEnabled: boolean; isPaired: boolean; deviceCount: number; activatedAt: string | null; @@ -873,6 +885,7 @@ export interface UpsertTerminalPayload { radiusMeters: number | null; maxAccuracyMeters: number | null; isActive: boolean; + activitySelectionEnabled?: boolean; } export interface TerminalPairingDto { @@ -1275,6 +1288,10 @@ export const api = { method: 'POST', body: JSON.stringify(payload), }), + timeEntryActivityOptions: (id: string, projectId: string) => + request( + `/api/timeentries/${id}/activity-options?${new URLSearchParams({ projectId })}`, + ), updateTimeEntry: (id: string, payload: UpdateTimeEntryPayload) => request(`/api/timeentries/${id}`, { method: 'PATCH', @@ -1342,6 +1359,26 @@ export const api = { }), deleteProject: (id: string) => request(`/api/projects/${id}`, { method: 'DELETE' }), + projectActivities: (projectId: string) => + request(`/api/projects/${projectId}/activities`), + createActivity: (projectId: string, payload: UpsertActivityPayload) => + request(`/api/projects/${projectId}/activities`, { + method: 'POST', + body: JSON.stringify(payload), + }), + updateActivity: ( + projectId: string, + activityId: string, + payload: UpsertActivityPayload, + ) => + request( + `/api/projects/${projectId}/activities/${activityId}`, + { method: 'PUT', body: JSON.stringify(payload) }, + ), + deleteActivity: (projectId: string, activityId: string) => + request(`/api/projects/${projectId}/activities/${activityId}`, { + method: 'DELETE', + }), createServiceOrder: (projectId: string, payload: UpsertServiceOrderPayload) => request(`/api/projects/${projectId}/service-orders`, { method: 'POST', @@ -1635,7 +1672,7 @@ export const api = { method: 'POST', body: JSON.stringify(payload), }), - updateTerminal: (id: string, payload: UpsertTerminalPayload) => + updateTerminal: (id: string, payload: Partial) => request(`/api/terminals/${id}`, { method: 'PUT', body: JSON.stringify(payload), diff --git a/apps/web/src/api/generated.ts b/apps/web/src/api/generated.ts index 35792d4..ea0da87 100644 --- a/apps/web/src/api/generated.ts +++ b/apps/web/src/api/generated.ts @@ -580,6 +580,38 @@ export interface paths { patch?: never; trace?: never; }; + '/api/projects/{id}/activities': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations['ProjectsController_listActivities']; + put?: never; + post: operations['ProjectsController_createActivity']; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/api/projects/{id}/activities/{activityId}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put: operations['ProjectsController_updateActivity']; + post?: never; + delete: operations['ProjectsController_removeActivity']; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/api/projects/{id}/assignments/{employeeId}': { parameters: { query?: never; @@ -916,6 +948,22 @@ export interface paths { patch: operations['TimeEntriesController_update']; trace?: never; }; + '/api/timeentries/{id}/activity-options': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations['TimeEntriesController_activityOptions']; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/api/timeentries/{id}/split': { parameters: { query?: never; @@ -964,6 +1012,38 @@ export interface paths { patch?: never; trace?: never; }; + '/api/terminals/kiosk/activity-state': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations['TerminalAuthController_activityState']; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/api/terminals/kiosk/activity': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations['TerminalAuthController_selectActivity']; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/api/terminals/kiosk/book': { parameters: { query?: never; @@ -2495,6 +2575,28 @@ export interface components { /** @description Null inherits the project default. */ defaultBillable?: Record | null; }; + ActivityDto: { + /** Format: uuid */ + id: string; + /** Format: uuid */ + projectId: string; + name: string; + isActive: boolean; + sortOrder: number; + /** @description A referenced activity can be deactivated but not deleted. */ + hasBookings: boolean; + /** Format: date-time */ + createdAt: string; + /** Format: date-time */ + updatedAt: string; + }; + UpsertActivityDto: { + name: string; + /** @description Defaults to true on creation; omitted values stay unchanged on update. */ + isActive?: boolean; + /** @description Defaults to 0 on creation; omitted values stay unchanged on update. */ + sortOrder?: number; + }; SoloReportRowDto: { grossMinutes: number; breakMinutes: number; @@ -2685,6 +2787,9 @@ export interface components { serviceOrderNo: string | null; serviceOrderTitle: string | null; activity: string | null; + /** Format: uuid */ + activityId: string | null; + catalogActivityName: string | null; summary: components['schemas']['TimeSummaryDto'] | null; }; TimeEntryApprovalDto: { @@ -2919,6 +3024,16 @@ export interface components { /** Format: uuid */ serviceOrderId?: string | null; activity?: string | null; + /** + * Format: uuid + * @description Active catalog activity of the effective project. Null clears it; omission preserves it unless the project changes. + */ + activityId?: string | null; + }; + TimeEntryActivityOptionDto: { + /** Format: uuid */ + id: string; + name: string; }; SplitTimeEntryDto: { /** @description Required for Solo entries. */ @@ -2954,15 +3069,60 @@ export interface components { action: 'clock-in' | 'clock-out'; requiresLocation: boolean; }; + KioskGrantDto: { + /** @description Short-lived grant returned by kiosk identification. */ + grant: string; + }; + KioskActivityDto: { + /** Format: uuid */ + id: string; + name: string; + /** Format: uuid */ + projectId: string; + projectName: string; + }; + KioskActivityStateDto: { + enabled: boolean; + activities: components['schemas']['KioskActivityDto'][]; + /** Format: uuid */ + selectedActivityId: string | null; + }; + SelectKioskActivityDto: { + /** @description Short-lived grant returned by kiosk identification. */ + grant: string; + latitude?: number; + longitude?: number; + accuracyMeters?: number; + /** Format: date-time */ + positionTimestamp?: string; + /** + * Format: uuid + * @description Eligible activity to remember or switch to. + */ + activityId: string; + }; + SelectKioskActivityResultDto: { + /** + * @description Successful selection consumes the PIN grant and challenge. + * @enum {string} + */ + outcome: 'remembered' | 'switched' | 'unchanged'; + }; BookTerminalDto: { + /** @description Short-lived grant returned by kiosk identification. */ grant: string; - /** @enum {string} */ - action: 'clock-in' | 'clock-out'; latitude?: number; longitude?: number; accuracyMeters?: number; /** Format: date-time */ positionTimestamp?: string; + /** @enum {string} */ + action: 'clock-in' | 'clock-out'; + /** + * Format: uuid + * @description Eligible catalog activity for clock-in only. Omit for plain booking. + */ + activityId?: string; }; BookTerminalResultDto: { /** @enum {string} */ @@ -3097,6 +3257,7 @@ export interface components { maxAccuracyMeters?: number | null; timeZone: string; isActive: boolean; + activitySelectionEnabled: boolean; isPaired: boolean; deviceCount: number; /** Format: date-time */ @@ -3147,6 +3308,8 @@ export interface components { timeZone: string; /** @default false */ isActive: boolean; + /** @description Allow activity selection at this terminal. Defaults to false. */ + activitySelectionEnabled?: boolean; }; UpdateTerminalDto: { /** @@ -3186,6 +3349,8 @@ export interface components { timeZone: string; /** @default false */ isActive: boolean; + /** @description Allow activity selection at this terminal. Omit to leave unchanged. */ + activitySelectionEnabled?: boolean; }; PairingCodeDto: { /** @example ABC23-DEFG4 */ @@ -4758,6 +4923,148 @@ export interface operations { }; }; }; + ProjectsController_listActivities: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Full project catalog, including inactive activities. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['ActivityDto'][]; + }; + }; + /** @description Project not found. */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + ProjectsController_createActivity: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + 'application/json': components['schemas']['UpsertActivityDto']; + }; + }; + responses: { + 201: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['ActivityDto']; + }; + }; + /** @description Project not found. */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Activity name already exists in this project. */ + 409: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + ProjectsController_updateActivity: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + activityId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + 'application/json': components['schemas']['UpsertActivityDto']; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['ActivityDto']; + }; + }; + /** @description Activity not found in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Activity name already exists in this project. */ + 409: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + ProjectsController_removeActivity: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + activityId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Activity not found in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Activity is referenced by a time entry. */ + 409: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; ProjectsController_assign: { parameters: { query?: never; @@ -5274,6 +5581,30 @@ export interface operations { }; }; }; + TimeEntriesController_activityOptions: { + parameters: { + query?: { + /** @description Proposed booking project; defaults to the entry’s project. */ + projectId?: string; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['TimeEntryActivityOptionDto'][]; + }; + }; + }; + }; TimeEntriesController_split: { parameters: { query?: never; @@ -5341,6 +5672,52 @@ export interface operations { }; }; }; + TerminalAuthController_activityState: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + 'application/json': components['schemas']['KioskGrantDto']; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['KioskActivityStateDto']; + }; + }; + }; + }; + TerminalAuthController_selectActivity: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + 'application/json': components['schemas']['SelectKioskActivityDto']; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + 'application/json': components['schemas']['SelectKioskActivityResultDto']; + }; + }; + }; + }; TerminalAuthController_book: { parameters: { query?: never; diff --git a/apps/web/src/api/terminal-device.spec.ts b/apps/web/src/api/terminal-device.spec.ts index 8915383..9a9cca6 100644 --- a/apps/web/src/api/terminal-device.spec.ts +++ b/apps/web/src/api/terminal-device.spec.ts @@ -2,7 +2,9 @@ import { vi } from 'vitest'; import { bookAtKiosk, identifyAtKiosk, + loadKioskActivityState, readTerminalDeviceToken, + selectKioskActivity, storeTerminalDeviceToken, } from './terminal-device'; @@ -39,6 +41,63 @@ it('sends kiosk credentials only with the device bearer and never refreshes an e ); }); +it('reads optional activity state without sending the PIN grant in the URL', async () => { + fetchMock.mockResolvedValue( + new Response( + JSON.stringify({ + enabled: true, + activities: [], + selectedActivityId: null, + }), + ), + ); + const { signal } = new AbortController(); + await expect( + loadKioskActivityState('device', 'grant', signal), + ).resolves.toMatchObject({ + enabled: true, + selectedActivityId: null, + }); + expect(fetchMock).toHaveBeenCalledWith( + '/api/terminals/kiosk/activity-state', + expect.objectContaining({ + method: 'POST', + credentials: 'omit', + cache: 'no-store', + headers: expect.objectContaining({ Authorization: 'Bearer device' }), + body: JSON.stringify({ grant: 'grant' }), + signal, + }), + ); +}); + +it('selects an activity through the device-only action, not the booking endpoint', async () => { + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ outcome: 'switched' })), + ); + const payload = { + grant: 'grant', + activityId: 'c6a70bd1-744f-4d1c-bcef-5a38ce6c1c2c', + }; + const { signal } = new AbortController(); + await expect(selectKioskActivity('device', payload, signal)).resolves.toEqual( + { + outcome: 'switched', + }, + ); + expect(fetchMock).toHaveBeenCalledWith( + '/api/terminals/kiosk/activity', + expect.objectContaining({ + method: 'POST', + credentials: 'omit', + cache: 'no-store', + headers: expect.objectContaining({ Authorization: 'Bearer device' }), + body: JSON.stringify(payload), + signal, + }), + ); +}); + it('preserves pairing for incorrect PINs but clears a confirmed device revocation', async () => { const values = new Map(); vi.spyOn(window, 'localStorage', 'get').mockReturnValue({ diff --git a/apps/web/src/api/terminal-device.ts b/apps/web/src/api/terminal-device.ts index c3baaa8..9581519 100644 --- a/apps/web/src/api/terminal-device.ts +++ b/apps/web/src/api/terminal-device.ts @@ -3,6 +3,7 @@ import { type TerminalDto, type TerminalBookingAction, } from './client'; +import type { components } from './generated'; const baseUrl = import.meta.env.VITE_API_BASE_URL ?? ''; @@ -45,14 +46,13 @@ export interface TerminalIdentifyResult { requiresLocation: boolean; } -export interface KioskBookingPayload { - grant: string; - action: TerminalBookingAction; - latitude?: number; - longitude?: number; - accuracyMeters?: number; - positionTimestamp?: string; -} +export type KioskActivityState = components['schemas']['KioskActivityStateDto']; + +export type KioskBookingPayload = components['schemas']['BookTerminalDto']; +export type KioskActivitySelectionPayload = + components['schemas']['SelectKioskActivityDto']; +export type KioskActivitySelectionResult = + components['schemas']['SelectKioskActivityResultDto']; export interface KioskBookingResult { code: 'TERMINAL_BOOKED'; @@ -201,3 +201,16 @@ export const bookAtKiosk = ( payload: KioskBookingPayload, signal?: AbortSignal, ) => kioskPost(token, 'book', payload, signal); + +export const loadKioskActivityState = ( + token: string, + grant: string, + signal?: AbortSignal, +) => kioskPost(token, 'activity-state', { grant }, signal); + +export const selectKioskActivity = ( + token: string, + payload: KioskActivitySelectionPayload, + signal?: AbortSignal, +) => + kioskPost(token, 'activity', payload, signal); diff --git a/apps/web/src/app/i18n.tsx b/apps/web/src/app/i18n.tsx index 539b0d5..c0fb5d2 100644 --- a/apps/web/src/app/i18n.tsx +++ b/apps/web/src/app/i18n.tsx @@ -409,6 +409,14 @@ const de: Catalog = { 'booking.serviceOrderRequired': 'Service-Auftrag (Pflicht)', 'booking.activityForReport': 'Tätigkeit (für die Kundenauswertung)', 'booking.activityPlaceholder': 'z. B. Konzept für Startseite erstellt', + 'booking.catalogActivity': 'Tätigkeit aus dem Katalog', + 'booking.noCatalogActivity': '— ohne Katalogtätigkeit —', + 'booking.currentCatalogActivity': '{name} (aktuell)', + 'booking.unavailableCatalogActivity': 'Nicht verfügbare Katalogtätigkeit', + 'booking.catalogActivitiesEmpty': + 'Keine aktiven Katalogtätigkeiten verfügbar.', + 'booking.catalogActivitiesFailed': + 'Katalogtätigkeiten konnten nicht geladen werden.', 'booking.dailyBlockHint': 'Alternativ kannst du dein Tages-Soll von {net} als abgeschlossenen Block buchen.', 'booking.dailyBlockAction': 'Tagesblock buchen', @@ -540,6 +548,29 @@ const de: Catalog = { 'projects.overbooked': 'Überbucht', 'projects.serviceOrders': 'Service-Aufträge', 'projects.noServiceOrders': 'Keine Service-Aufträge.', + 'projects.activities': 'Tätigkeiten', + 'projects.activityCatalog': 'Tätigkeiten – {project}', + 'projects.activityCatalogHint': + 'Verwalte den Tätigkeitskatalog für dieses Projekt.', + 'projects.noActivities': 'Noch keine Tätigkeiten angelegt.', + 'projects.activityName': 'Name der Tätigkeit', + 'projects.addActivity': 'Tätigkeit hinzufügen', + 'projects.renameActivity': '{name} umbenennen', + 'projects.activateActivity': '{name} aktivieren', + 'projects.deactivateActivity': '{name} deaktivieren', + 'projects.deleteActivity': '{name} löschen', + 'projects.deleteActivityConfirm': '„{name}“ dauerhaft löschen?', + 'projects.activityHasBookings': + 'Hat Zeitbuchungen und kann nicht gelöscht werden.', + 'projects.activityDeleteConflict': + 'Diese Tätigkeit hat Zeitbuchungen und kann nicht gelöscht werden. Deaktiviere sie stattdessen.', + 'projects.activityDuplicate': + 'In diesem Projekt gibt es bereits eine Tätigkeit mit diesem Namen.', + 'projects.activitiesLoadFailed': + 'Der Tätigkeitskatalog konnte nicht geladen werden.', + 'projects.activitiesRetry': 'Tätigkeiten neu laden', + 'projects.activitySaved': 'Tätigkeit gespeichert.', + 'projects.activityDeleted': 'Tätigkeit gelöscht.', 'projects.edit': 'Projekt bearbeiten', 'projects.editorDescription': 'Der Projekt-Code ist eindeutig und erscheint im ERP-Export. Die PLAN-Zeit deckelt die Summe der Auftrags-PLAN-Zeiten.', @@ -626,6 +657,9 @@ const de: Catalog = { 'terminals.locationLabel': 'Angezeigter Ort', 'terminals.displayText': 'Anzeigetext', 'terminals.logoUrl': 'Logo (PNG, JPEG oder WebP, maximal 60 KiB)', + 'terminals.activitySelection': 'Tätigkeitsauswahl am Terminal erlauben', + 'terminals.activitySelectionHint': + 'Mitarbeitende können beim Einstempeln eine verfügbare Projekttätigkeit auswählen.', 'terminals.geofence': 'Standortprüfung', 'terminals.enforceGeofence': 'GPS-Standort beim Scannen prüfen', 'terminals.geofenceHint': @@ -1190,6 +1224,12 @@ const en: Catalog = { 'booking.serviceOrderRequired': 'Service order (required)', 'booking.activityForReport': 'Activity (for the customer report)', 'booking.activityPlaceholder': 'e.g. created homepage concept', + 'booking.catalogActivity': 'Catalog activity', + 'booking.noCatalogActivity': '— no catalog activity —', + 'booking.currentCatalogActivity': '{name} (current)', + 'booking.unavailableCatalogActivity': 'Unavailable catalog activity', + 'booking.catalogActivitiesEmpty': 'No active catalog activities available.', + 'booking.catalogActivitiesFailed': 'Catalog activities could not be loaded.', 'booking.dailyBlockHint': 'Alternatively, book your daily target of {net} as one completed block.', 'booking.dailyBlockAction': 'Book daily block', @@ -1321,6 +1361,27 @@ const en: Catalog = { 'projects.overbooked': 'Overbooked', 'projects.serviceOrders': 'Service orders', 'projects.noServiceOrders': 'No service orders.', + 'projects.activities': 'Activities', + 'projects.activityCatalog': 'Activities – {project}', + 'projects.activityCatalogHint': + 'Manage the activity catalog for this project.', + 'projects.noActivities': 'No activities yet.', + 'projects.activityName': 'Activity name', + 'projects.addActivity': 'Add activity', + 'projects.renameActivity': 'Rename {name}', + 'projects.activateActivity': 'Activate {name}', + 'projects.deactivateActivity': 'Deactivate {name}', + 'projects.deleteActivity': 'Delete {name}', + 'projects.deleteActivityConfirm': 'Permanently delete “{name}”?', + 'projects.activityHasBookings': 'Has time entries and cannot be deleted.', + 'projects.activityDeleteConflict': + 'This activity has time entries and cannot be deleted. Deactivate it instead.', + 'projects.activityDuplicate': + 'An activity with this name already exists in this project.', + 'projects.activitiesLoadFailed': 'The activity catalog could not be loaded.', + 'projects.activitiesRetry': 'Reload activities', + 'projects.activitySaved': 'Activity saved.', + 'projects.activityDeleted': 'Activity deleted.', 'projects.edit': 'Edit project', 'projects.editorDescription': 'The project code is unique and appears in the ERP export. Planned project time limits the total planned service-order time.', @@ -1407,6 +1468,9 @@ const en: Catalog = { 'terminals.locationLabel': 'Displayed location', 'terminals.displayText': 'Display text', 'terminals.logoUrl': 'Logo (PNG, JPEG, or WebP; no more than 60 KiB)', + 'terminals.activitySelection': 'Allow activity selection at this terminal', + 'terminals.activitySelectionHint': + 'Employees can select an available project activity when clocking in.', 'terminals.geofence': 'Location check', 'terminals.enforceGeofence': 'Check GPS location when scanning', 'terminals.geofenceHint': diff --git a/apps/web/src/app/terminal-pin-i18n.ts b/apps/web/src/app/terminal-pin-i18n.ts index 181fbe6..2719e1e 100644 --- a/apps/web/src/app/terminal-pin-i18n.ts +++ b/apps/web/src/app/terminal-pin-i18n.ts @@ -34,6 +34,22 @@ export const terminalPinDe = { 'terminalPin.confirmHint': 'Eine Anmeldung allein bucht keine Zeit.', 'terminalPin.clockIn': 'Jetzt einstempeln', 'terminalPin.clockOut': 'Jetzt ausstempeln', + 'terminalPin.activityOptionsIn': 'Tätigkeit zum Einstempeln (optional)', + 'terminalPin.activityOptionsOut': 'Andere Tätigkeit wählen (optional)', + 'terminalPin.activityNone': 'Ohne Tätigkeit', + 'terminalPin.activityLoading': 'Tätigkeiten werden geladen …', + 'terminalPin.activityUnavailable': + 'Tätigkeiten sind gerade nicht verfügbar. Stempeln ist weiterhin möglich.', + 'terminalPin.activityApply': 'Tätigkeitswahl übernehmen', + 'terminalPin.activitySwitch': 'Tätigkeit wechseln', + 'terminalPin.activityApplyHint': + 'Bei einer offenen Buchung wechselt die Tätigkeit. Sonst wird die Wahl nur vorgemerkt.', + 'terminalPin.activitySubmitting': 'Tätigkeit wird übernommen …', + 'terminalPin.activityOutcome.remembered': 'Tätigkeit vorgemerkt', + 'terminalPin.activityOutcome.switched': 'Tätigkeit gewechselt', + 'terminalPin.activityOutcome.unchanged': 'Tätigkeit ist bereits aktiv', + 'terminalPin.activityUncertain': + 'Die Tätigkeitsänderung konnte nicht bestätigt werden. Bitte erneut anmelden und den Zeitstatus prüfen.', 'terminalPin.submitting': 'Buchung wird bestätigt …', 'terminalPin.locating': 'Aktueller Standort wird ermittelt …', 'terminalPin.successIn': 'Einstempeln bestätigt', @@ -82,6 +98,8 @@ export const terminalPinDe = { 'terminalPin.event.IdentificationAccepted': 'Anmeldung bestätigt', 'terminalPin.event.BookingAccepted': 'Buchung bestätigt', 'terminalPin.event.BookingRejected': 'Buchung abgelehnt', + 'terminalPin.event.ActivitySelectionAccepted': 'Tätigkeitswahl bestätigt', + 'terminalPin.event.ActivitySelectionRejected': 'Tätigkeitswahl abgelehnt', 'terminalPin.event.AuditViewed': 'Protokoll eingesehen', 'terminalPin.event.TerminalCreated': 'Terminal angelegt', 'terminalPin.event.TerminalUpdated': 'Terminal geändert', @@ -131,6 +149,22 @@ export const terminalPinEn: Record = { 'terminalPin.confirmHint': 'Signing in alone does not book any time.', 'terminalPin.clockIn': 'Clock in now', 'terminalPin.clockOut': 'Clock out now', + 'terminalPin.activityOptionsIn': 'Activity for clock-in (optional)', + 'terminalPin.activityOptionsOut': 'Choose another activity (optional)', + 'terminalPin.activityNone': 'No activity', + 'terminalPin.activityLoading': 'Loading activities …', + 'terminalPin.activityUnavailable': + 'Activities are temporarily unavailable. You can still clock in or out.', + 'terminalPin.activityApply': 'Apply activity choice', + 'terminalPin.activitySwitch': 'Switch activity', + 'terminalPin.activityApplyHint': + 'If you are clocked in, this switches the activity. Otherwise, it only remembers your choice.', + 'terminalPin.activitySubmitting': 'Applying activity …', + 'terminalPin.activityOutcome.remembered': 'Activity remembered', + 'terminalPin.activityOutcome.switched': 'Activity switched', + 'terminalPin.activityOutcome.unchanged': 'Activity is already current', + 'terminalPin.activityUncertain': + 'The activity change could not be confirmed. Sign in again and check your time status.', 'terminalPin.submitting': 'Confirming booking …', 'terminalPin.locating': 'Getting current location …', 'terminalPin.successIn': 'Clock-in confirmed', @@ -177,6 +211,8 @@ export const terminalPinEn: Record = { 'terminalPin.event.IdentificationAccepted': 'Sign-in confirmed', 'terminalPin.event.BookingAccepted': 'Booking confirmed', 'terminalPin.event.BookingRejected': 'Booking rejected', + 'terminalPin.event.ActivitySelectionAccepted': 'Activity selection confirmed', + 'terminalPin.event.ActivitySelectionRejected': 'Activity selection rejected', 'terminalPin.event.AuditViewed': 'Audit log viewed', 'terminalPin.event.TerminalCreated': 'Terminal created', 'terminalPin.event.TerminalUpdated': 'Terminal updated', diff --git a/apps/web/src/components/timeentries/TimeEntryApprovals.spec.tsx b/apps/web/src/components/timeentries/TimeEntryApprovals.spec.tsx index 7362c07..766ee23 100644 --- a/apps/web/src/components/timeentries/TimeEntryApprovals.spec.tsx +++ b/apps/web/src/components/timeentries/TimeEntryApprovals.spec.tsx @@ -52,6 +52,8 @@ const entry: TimeEntryDto = { serviceOrderNo: null, serviceOrderTitle: null, activity: null, + activityId: null, + catalogActivityName: null, summary: { grossMinutes: 720, breakMinutes: 45, netMinutes: 675 }, }; function approval( diff --git a/apps/web/src/routes/AdminProjectsPage.spec.tsx b/apps/web/src/routes/AdminProjectsPage.spec.tsx index 4316234..e66e7c3 100644 --- a/apps/web/src/routes/AdminProjectsPage.spec.tsx +++ b/apps/web/src/routes/AdminProjectsPage.spec.tsx @@ -1,5 +1,10 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, screen, waitFor, within } from '@testing-library/react'; +import { + ApiError, + type ActivityDto, + type ProjectReportDto, +} from '../api/client'; import { renderWithProviders } from '../test-utils'; const projectsMock = vi.fn(); @@ -14,8 +19,13 @@ const deleteServiceOrderMock = vi.fn(); const assignProjectMock = vi.fn(); const unassignProjectMock = vi.fn(); const projectReportMock = vi.fn(); +const projectActivitiesMock = vi.fn(); +const createActivityMock = vi.fn(); +const updateActivityMock = vi.fn(); +const deleteActivityMock = vi.fn(); -vi.mock('../api/client', () => ({ +vi.mock('../api/client', async (importOriginal) => ({ + ...(await importOriginal()), api: { projects: (...args: unknown[]) => projectsMock(...args), employeeDirectory: (...args: unknown[]) => employeeDirectoryMock(...args), @@ -29,6 +39,10 @@ vi.mock('../api/client', () => ({ assignProject: (...args: unknown[]) => assignProjectMock(...args), unassignProject: (...args: unknown[]) => unassignProjectMock(...args), projectReport: (...args: unknown[]) => projectReportMock(...args), + projectActivities: (...args: unknown[]) => projectActivitiesMock(...args), + createActivity: (...args: unknown[]) => createActivityMock(...args), + updateActivity: (...args: unknown[]) => updateActivityMock(...args), + deleteActivity: (...args: unknown[]) => deleteActivityMock(...args), }, })); @@ -100,6 +114,59 @@ const EMPLOYEES = [ }, ]; +const CUSTOMER_REPORT = { + projectCode: 'PRJ-001', + projectName: 'Website Relaunch', + from: null, + to: null, + rows: [ + { + date: '2026-07-01', + employeeName: 'Anna Müller', + orderNo: null, + orderTitle: null, + grossMinutes: 240, + activity: 'Sortieren, prüfen; "Süd"', + }, + { + date: '2026-07-01', + employeeName: 'Anna Müller', + orderNo: 'SA-001', + orderTitle: 'Konzeption', + grossMinutes: 90, + activity: 'Wireframes erstellt', + }, + ], + totalGrossMinutes: 330, +} satisfies ProjectReportDto; + +const BOOKED: ActivityDto = { + id: 'a-1', + projectId: 'p-1', + name: 'Sortieren', + isActive: true, + sortOrder: 1, + hasBookings: true, + createdAt: '2026-11-28T08:00:00.000Z', + updatedAt: '2026-11-28T08:00:00.000Z', +}; +const UNUSED: ActivityDto = { + ...BOOKED, + id: 'a-2', + name: 'Packen', + isActive: false, + sortOrder: 2, + hasBookings: false, +}; + +async function openCatalog(project = 'PRJ-001', heading = 'Tätigkeiten') { + const name = `${heading} – ${project}`; + const trigger = await screen.findByRole('button', { name }); + fireEvent.click(trigger); + const dialog = await screen.findByRole('dialog', { name }); + return { trigger, dialog: within(dialog) }; +} + describe('AdminProjectsPage', () => { beforeEach(() => { role = 'HRAdmin'; @@ -109,27 +176,17 @@ describe('AdminProjectsPage', () => { .mockClear() .mockResolvedValue([{ employeeId: 'e-1', projectId: 'p-1' }]); createProjectMock.mockClear().mockResolvedValue(PROJECTS[0]); + projectActivitiesMock.mockReset().mockResolvedValue([]); + createActivityMock.mockReset(); + updateActivityMock.mockReset(); + deleteActivityMock.mockReset(); assignProjectMock.mockClear().mockResolvedValue(undefined); unassignProjectMock.mockClear().mockResolvedValue(undefined); - projectReportMock.mockClear().mockResolvedValue({ - projectCode: 'PRJ-001', - projectName: 'Website Relaunch', - from: null, - to: null, - rows: [ - { - date: '2026-06-10', - employeeName: 'Anna Müller', - orderNo: 'SA-001', - orderTitle: 'Konzeption', - grossMinutes: 90, - activity: 'Wireframes erstellt', - }, - ], - totalGrossMinutes: 90, - }); + projectReportMock.mockClear().mockResolvedValue(CUSTOMER_REPORT); }); + afterEach(() => vi.restoreAllMocks()); + it('blocks plain employees with an alert and loads nothing', async () => { role = 'Employee'; const { AdminProjectsPage } = await import('./AdminProjectsPage'); @@ -138,6 +195,8 @@ describe('AdminProjectsPage', () => { screen.getByText(/Managern und HR-Admins vorbehalten/i), ).toBeDefined(); expect(projectsMock).not.toHaveBeenCalled(); + expect(projectActivitiesMock).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: /Tätigkeiten/ })).toBeNull(); }); it('is accessible for Managers too', async () => { @@ -254,7 +313,7 @@ describe('AdminProjectsPage', () => { }); }); - it('opens the customer report dialog and renders activity rows', async () => { + it('shows catalog and legacy activity labels in the existing customer report column', async () => { const { AdminProjectsPage } = await import('./AdminProjectsPage'); renderWithProviders(); await waitFor(() => { @@ -262,56 +321,248 @@ describe('AdminProjectsPage', () => { }); fireEvent.click(screen.getAllByRole('button', { name: /Auswertung/i })[0]); - await waitFor(() => { - expect(projectReportMock).toHaveBeenCalledWith( - 'p-1', - undefined, - undefined, + const dialog = await screen.findByRole('dialog'); + const table = within(await within(dialog).findByRole('table')); + expect(projectReportMock).toHaveBeenCalledWith('p-1', undefined, undefined); + expect(table.getAllByRole('columnheader')).toHaveLength(5); + expect( + table.getByRole('columnheader', { name: 'Tätigkeit' }), + ).toBeDefined(); + for (const { activity } of CUSTOMER_REPORT.rows) { + expect(table.getByRole('cell', { name: activity })).toBeDefined(); + } + expect(table.getByRole('cell', { name: '5,5 h' })).toBeDefined(); + }); + + it.each(['Manager', 'HRAdmin'])( + 'loads only the opened project catalog for %s and identifies inactive and booked activities', + async (actorRole) => { + role = actorRole; + projectActivitiesMock.mockImplementation(async (projectId) => + projectId === 'p-1' ? [BOOKED, UNUSED] : [], ); - expect(screen.getByText('Wireframes erstellt')).toBeDefined(); - // Appears in the matrix AND the report table once the dialog is open. - expect(screen.getAllByText('Anna Müller').length).toBeGreaterThan(1); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + await screen.findByText('Website Relaunch'); + expect(projectActivitiesMock).not.toHaveBeenCalled(); + + const { trigger, dialog } = await openCatalog(); + const [firstRow, secondRow] = await dialog.findAllByRole('listitem'); + expect(within(firstRow).getByText('Sortieren')).toBeDefined(); + expect(within(firstRow).getByText('Aktiv')).toBeDefined(); + expect( + within(firstRow).getByText(/kann nicht gelöscht werden/), + ).toBeDefined(); + expect( + dialog.queryByRole('button', { name: 'Sortieren löschen' }), + ).toBeNull(); + expect(within(secondRow).getByText('Inaktiv')).toBeDefined(); + expect( + dialog.getByRole('button', { name: 'Packen löschen' }), + ).toBeDefined(); + expect(projectActivitiesMock.mock.calls).toEqual([['p-1']]); + + fireEvent.click(dialog.getByRole('button', { name: 'Schließen' })); + await waitFor(() => expect(document.activeElement).toBe(trigger)); + const { dialog: other } = await openCatalog('PRJ-002'); + expect( + await other.findByText('Noch keine Tätigkeiten angelegt.'), + ).toBeDefined(); + expect(other.queryByText('Sortieren')).toBeNull(); + expect(projectActivitiesMock.mock.calls).toEqual([['p-1'], ['p-2']]); + }, + ); + + it('creates a trimmed activity through the form and refreshes the list', async () => { + const created = { ...UNUSED, name: 'Pflügen', isActive: true }; + projectActivitiesMock + .mockResolvedValueOnce([]) + .mockResolvedValue([created]); + createActivityMock.mockResolvedValue(created); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog(); + const input = await dialog.findByLabelText('Name der Tätigkeit'); + const submit = dialog.getByRole('button', { name: 'Tätigkeit hinzufügen' }); + fireEvent.change(input, { target: { value: ' ' } }); + expect(submit).toHaveProperty('disabled', true); + fireEvent.change(input, { target: { value: ' Pflügen ' } }); + const form = submit.closest('form'); + if (!form) throw new Error('Activity input must belong to a form'); + fireEvent.submit(form); + + expect(await dialog.findByText('Pflügen')).toBeDefined(); + expect(createActivityMock).toHaveBeenCalledWith('p-1', { name: 'Pflügen' }); + expect(await dialog.findByText('Tätigkeit gespeichert.')).toBeDefined(); + expect(input).toHaveProperty('value', ''); + }); + + it('renames a booked activity and changes activation in both directions without resetting other fields', async () => { + const renamed = { ...BOOKED, name: 'Vorsortieren' }; + const deactivated = { ...renamed, isActive: false }; + projectActivitiesMock + .mockResolvedValueOnce([BOOKED]) + .mockResolvedValueOnce([renamed]) + .mockResolvedValueOnce([deactivated]) + .mockResolvedValue([renamed]); + updateActivityMock.mockResolvedValue(renamed); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog(); + + fireEvent.click( + await dialog.findByRole('button', { name: 'Sortieren umbenennen' }), + ); + const input = dialog.getByLabelText('Name der Tätigkeit'); + expect(document.activeElement).toBe(input); + expect(input).toHaveProperty('value', 'Sortieren'); + fireEvent.change(input, { target: { value: 'Vorsortieren' } }); + fireEvent.click(dialog.getByRole('button', { name: 'Speichern' })); + const deactivate = await dialog.findByRole('button', { + name: 'Vorsortieren deaktivieren', }); + await waitFor(() => expect(deactivate).toHaveProperty('disabled', false)); + fireEvent.click(deactivate); + const activate = await dialog.findByRole('button', { + name: 'Vorsortieren aktivieren', + }); + await waitFor(() => expect(activate).toHaveProperty('disabled', false)); + expect(dialog.getByText('Inaktiv')).toBeDefined(); + expect( + dialog.queryByRole('button', { name: 'Vorsortieren löschen' }), + ).toBeNull(); + fireEvent.click(activate); + expect(await dialog.findByText('Aktiv')).toBeDefined(); + + expect(updateActivityMock.mock.calls).toEqual([ + ['p-1', 'a-1', { name: 'Vorsortieren' }], + ['p-1', 'a-1', { name: 'Vorsortieren', isActive: false }], + ['p-1', 'a-1', { name: 'Vorsortieren', isActive: true }], + ]); + }); + + it('deletes an unused activity only after confirmation', async () => { + const confirm = vi + .spyOn(window, 'confirm') + .mockReturnValueOnce(false) + .mockReturnValue(true); + projectActivitiesMock.mockResolvedValueOnce([UNUSED]).mockResolvedValue([]); + deleteActivityMock.mockResolvedValue(undefined); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog(); + const remove = await dialog.findByRole('button', { + name: 'Packen löschen', + }); + fireEvent.click(remove); + expect(deleteActivityMock).not.toHaveBeenCalled(); + expect(confirm).toHaveBeenCalledWith('„Packen“ dauerhaft löschen?'); + fireEvent.click(remove); + expect(await dialog.findByText('Tätigkeit gelöscht.')).toBeDefined(); + expect(dialog.queryByText('Packen')).toBeNull(); + expect(deleteActivityMock).toHaveBeenCalledExactlyOnceWith('p-1', 'a-2'); + }); + + it('surfaces a duplicate conflict without losing the entered name', async () => { + createActivityMock.mockRejectedValue( + new ApiError(409, 'Duplicate activity'), + ); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog(); + const input = await dialog.findByLabelText('Name der Tätigkeit'); + fireEvent.change(input, { target: { value: 'Sortieren' } }); + fireEvent.click( + dialog.getByRole('button', { name: 'Tätigkeit hinzufügen' }), + ); + expect((await dialog.findByRole('alert')).textContent).toMatch( + /bereits eine Tätigkeit/, + ); + expect(input).toHaveProperty('value', 'Sortieren'); + }); + + it('refreshes delete eligibility on a conflict from a new booking', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(true); + const newlyBooked = { ...UNUSED, isActive: true, hasBookings: true }; + projectActivitiesMock + .mockResolvedValueOnce([{ ...UNUSED, isActive: true }]) + .mockResolvedValue([newlyBooked]); + deleteActivityMock.mockRejectedValue( + new ApiError(409, 'Booking reference'), + ); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog(); + fireEvent.click( + await dialog.findByRole('button', { name: 'Packen löschen' }), + ); + expect((await dialog.findByRole('alert')).textContent).toMatch( + /Deaktiviere sie stattdessen/, + ); + await waitFor(() => + expect( + dialog.queryByRole('button', { name: 'Packen löschen' }), + ).toBeNull(), + ); + expect( + dialog.getByRole('button', { name: 'Packen deaktivieren' }), + ).toBeDefined(); + }); + + it('shows an English load error with a retry that loads the catalog', async () => { + vi.spyOn(window, 'localStorage', 'get').mockReturnValue({ + getItem: () => 'en', + setItem: vi.fn(), + } as unknown as Storage); + projectActivitiesMock + .mockRejectedValueOnce(new Error('Offline')) + .mockResolvedValue([BOOKED]); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog('PRJ-001', 'Activities'); + expect((await dialog.findByRole('alert')).textContent).toContain( + 'The activity catalog could not be loaded.', + ); + fireEvent.click(dialog.getByRole('button', { name: 'Reload activities' })); + expect( + await dialog.findByText('Has time entries and cannot be deleted.'), + ).toBeDefined(); + expect(dialog.getByLabelText('Activity name')).toBeDefined(); }); }); describe('project report CSV locales', () => { it.each([ - ['en-GB', 'Date,Employee,Service order,hours,Activity', '1.50'], - ['de-DE', 'Datum;Mitarbeiter:in;Service-Auftrag;Stunden;Tätigkeit', '1,50'], + { + languageTag: 'en-GB', + lines: [ + 'Date,Employee,Service order,hours,Activity', + '2026-07-01,Anna Müller,,4.00,"Sortieren, prüfen; ""Süd"""', + '2026-07-01,Anna Müller,SA-001 Konzeption,1.50,Wireframes erstellt', + 'Total,,,5.50,', + ], + }, + { + languageTag: 'de-DE', + lines: [ + 'Datum;Mitarbeiter:in;Service-Auftrag;Stunden;Tätigkeit', + '2026-07-01;Anna Müller;;"4,00";"Sortieren, prüfen; ""Süd"""', + '2026-07-01;Anna Müller;SA-001 Konzeption;"1,50";Wireframes erstellt', + 'Gesamt;;;"5,50";', + ], + }, ])( - 'uses %s headers and decimal conventions and escapes punctuation', - async (languageTag, header, hours) => { + 'exports catalog and legacy labels with $languageTag escaping, hours and totals', + async ({ languageTag, lines }) => { const { reportToCsv } = await import('./AdminProjectsPage'); const { catalogs } = await import('../app/i18n'); const catalog = languageTag.startsWith('de') ? catalogs.de : catalogs.en; const csv = reportToCsv( - { - projectCode: 'PROJECT-1', - projectName: 'Synthetic project', - from: null, - to: null, - rows: [ - { - date: '2026-07-01', - employeeName: 'Alex Example', - orderNo: null, - orderTitle: null, - grossMinutes: 90, - activity: 'Review, design; "approved"', - }, - ], - totalGrossMinutes: 90, - }, + CUSTOMER_REPORT, languageTag, (key) => catalog[key], ); - expect(csv.startsWith('\uFEFF' + header)).toBe(true); - expect(csv).toContain(hours); - expect(csv.split('\r\n').at(-1)).toBe( - languageTag === 'de-DE' ? 'Gesamt;;;"1,50";' : 'Total,,,1.50,', - ); - expect(csv).toContain('"Review, design; ""approved"""'); + expect(csv).toBe('\uFEFF' + lines.join('\r\n')); }, ); }); diff --git a/apps/web/src/routes/AdminProjectsPage.tsx b/apps/web/src/routes/AdminProjectsPage.tsx index c1b03c7..ea767b4 100644 --- a/apps/web/src/routes/AdminProjectsPage.tsx +++ b/apps/web/src/routes/AdminProjectsPage.tsx @@ -25,6 +25,7 @@ import { } from '../api/client'; import { useCurrentUser } from '../app/auth'; import { useI18n } from '../app/i18n'; +import { ProjectActivityCatalog } from './ProjectActivityCatalog'; interface ProjectDraft { code: string; @@ -270,7 +271,8 @@ function ProjectCard({ )} -
+
+ diff --git a/apps/web/src/routes/AdminTerminalsPage.spec.tsx b/apps/web/src/routes/AdminTerminalsPage.spec.tsx index e606143..548e743 100644 --- a/apps/web/src/routes/AdminTerminalsPage.spec.tsx +++ b/apps/web/src/routes/AdminTerminalsPage.spec.tsx @@ -5,6 +5,7 @@ import { AdminTerminalsPage } from './AdminTerminalsPage'; const terminalsMock = vi.fn(); const createTerminalMock = vi.fn(); +const updateTerminalMock = vi.fn(); const terminalSupportPromptMock = vi.fn(); const dismissTerminalSupportPromptMock = vi.fn(); const revokeTerminalDeviceMock = vi.fn(); @@ -14,7 +15,7 @@ vi.mock('../api/client', () => ({ api: { terminals: (...args: unknown[]) => terminalsMock(...args), createTerminal: (...args: unknown[]) => createTerminalMock(...args), - updateTerminal: vi.fn(), + updateTerminal: (...args: unknown[]) => updateTerminalMock(...args), deactivateTerminal: vi.fn(), deleteTerminalPermanently: (...args: unknown[]) => deleteTerminalPermanentlyMock(...args), @@ -45,6 +46,7 @@ describe('AdminTerminalsPage', () => { vi.clearAllMocks(); terminalsMock.mockResolvedValue([]); createTerminalMock.mockResolvedValue({ id: 'terminal-1' }); + updateTerminalMock.mockResolvedValue({ id: 'terminal-1' }); terminalSupportPromptMock.mockResolvedValue({ shownAt: null }); dismissTerminalSupportPromptMock.mockResolvedValue(undefined); revokeTerminalDeviceMock.mockResolvedValue(undefined); @@ -57,6 +59,11 @@ describe('AdminTerminalsPage', () => { fireEvent.click( await screen.findByRole('button', { name: 'Terminal einrichten' }), ); + expect( + screen.getByRole('switch', { + name: 'Tätigkeitsauswahl am Terminal erlauben', + }), + ).toHaveProperty('checked', false); fireEvent.change(screen.getByLabelText('Interner Name'), { target: { value: 'Empfang' }, }); @@ -72,6 +79,7 @@ describe('AdminTerminalsPage', () => { await waitFor(() => expect(createTerminalMock).toHaveBeenCalledTimes(1)); expect(createTerminalMock).toHaveBeenCalledWith( expect.objectContaining({ + activitySelectionEnabled: false, enforceGeofence: false, latitude: null, longitude: null, @@ -90,6 +98,79 @@ describe('AdminTerminalsPage', () => { expect(dismissTerminalSupportPromptMock).toHaveBeenCalledTimes(1); }); + it.each([ + { activitySelectionEnabled: false, change: 'activity' }, + { activitySelectionEnabled: true, change: 'activity' }, + { activitySelectionEnabled: true, change: 'name' }, + { activitySelectionEnabled: false, change: 'both' }, + ])( + 'loads activity selection set to $activitySelectionEnabled and saves a $change change', + async ({ activitySelectionEnabled, change }) => { + terminalsMock.mockResolvedValue([ + { + id: 'terminal-1', + name: 'Empfang', + displayText: 'Willkommen', + locationLabel: 'Würzburg', + logoUrl: null, + timeZone: 'Europe/Berlin', + activitySelectionEnabled, + enforceGeofence: false, + latitude: null, + longitude: null, + radiusMeters: null, + maxAccuracyMeters: null, + isActive: true, + isPaired: false, + deviceCount: 0, + activatedAt: null, + lastSeenAt: null, + devices: [], + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }, + ]); + + renderWithProviders(); + fireEvent.click( + await screen.findByRole('button', { name: 'Bearbeiten' }), + ); + const activitySelection = screen.getByRole('switch', { + name: 'Tätigkeitsauswahl am Terminal erlauben', + }); + expect(activitySelection).toHaveProperty( + 'checked', + activitySelectionEnabled, + ); + if (change !== 'name') fireEvent.click(activitySelection); + if (change !== 'activity') { + fireEvent.change(screen.getByLabelText('Interner Name'), { + target: { value: 'Neuer Empfang' }, + }); + } + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + + await waitFor(() => expect(updateTerminalMock).toHaveBeenCalledTimes(1)); + const [id, payload] = updateTerminalMock.mock.calls[0]; + expect(id).toBe('terminal-1'); + if (change === 'activity') { + expect(payload).toEqual({ + activitySelectionEnabled: !activitySelectionEnabled, + }); + } else { + expect(payload).toMatchObject({ name: 'Neuer Empfang' }); + if (change === 'name') { + expect(payload).not.toHaveProperty('activitySelectionEnabled'); + } else { + expect(payload).toHaveProperty( + 'activitySelectionEnabled', + !activitySelectionEnabled, + ); + } + } + }, + ); + it('rejects oversized logos before they can be submitted', async () => { renderWithProviders(); fireEvent.click( @@ -132,6 +213,7 @@ describe('AdminTerminalsPage', () => { locationLabel: 'Würzburg', logoUrl: null, timeZone: 'Europe/Berlin', + activitySelectionEnabled: false, enforceGeofence: false, latitude: null, longitude: null, @@ -171,6 +253,7 @@ describe('AdminTerminalsPage', () => { locationLabel: 'Würzburg', logoUrl: null, timeZone: 'Europe/Berlin', + activitySelectionEnabled: false, enforceGeofence: true, latitude: 49.7913, longitude: 9.9534, diff --git a/apps/web/src/routes/AdminTerminalsPage.tsx b/apps/web/src/routes/AdminTerminalsPage.tsx index cf6ee58..40925fb 100644 --- a/apps/web/src/routes/AdminTerminalsPage.tsx +++ b/apps/web/src/routes/AdminTerminalsPage.tsx @@ -411,30 +411,49 @@ export function AdminTerminalsPage() { ); } -function TerminalEditor({ - terminal, - onClose, - onSaved, -}: { - terminal: TerminalDto | null; - onClose: () => void; - onSaved: (activated: boolean) => void | Promise; -}) { - const { t } = useI18n(); - const [draft, setDraft] = useState({ +function initialTerminalDraft( + terminal: TerminalDto | null, +): UpsertTerminalPayload { + return { name: terminal?.name ?? '', displayText: terminal?.displayText ?? '', locationLabel: terminal?.locationLabel ?? '', logoUrl: terminal?.logoUrl ?? null, timeZone: terminal?.timeZone ?? getBrowserTimeZone(), allowedAuthMethods: terminal?.allowedAuthMethods ?? ['QR'], + activitySelectionEnabled: terminal?.activitySelectionEnabled ?? false, enforceGeofence: terminal?.enforceGeofence ?? true, latitude: terminal?.latitude ?? null, longitude: terminal?.longitude ?? null, radiusMeters: terminal?.radiusMeters ?? null, maxAccuracyMeters: terminal?.maxAccuracyMeters ?? null, isActive: terminal?.isActive ?? true, - }); + }; +} + +function terminalPayload(draft: UpsertTerminalPayload): UpsertTerminalPayload { + return draft.enforceGeofence + ? draft + : { + ...draft, + latitude: null, + longitude: null, + radiusMeters: null, + maxAccuracyMeters: null, + }; +} + +function TerminalEditor({ + terminal, + onClose, + onSaved, +}: { + terminal: TerminalDto | null; + onClose: () => void; + onSaved: (activated: boolean) => void | Promise; +}) { + const { t } = useI18n(); + const [draft, setDraft] = useState(() => initialTerminalDraft(terminal)); const [error, setError] = useState(null); const [locating, setLocating] = useState(false); const wasActive = terminal?.isActive ?? false; @@ -444,18 +463,27 @@ function TerminalEditor({ mutationFn: () => { if (!draft.allowedAuthMethods?.length) throw new Error(t('terminalPin.chooseMethod')); - const payload: UpsertTerminalPayload = draft.enforceGeofence - ? draft - : { - ...draft, - latitude: null, - longitude: null, - radiusMeters: null, - maxAccuracyMeters: null, - }; - return terminal - ? api.updateTerminal(terminal.id, payload) - : api.createTerminal(payload); + const payload = terminalPayload(draft); + if (!terminal) return api.createTerminal(payload); + + const { activitySelectionEnabled, ...otherSettings } = payload; + const previous = terminalPayload(initialTerminalDraft(terminal)); + if (activitySelectionEnabled === previous.activitySelectionEnabled) { + return api.updateTerminal(terminal.id, otherSettings); + } + + // Sending unchanged auth settings would invalidate active kiosk grants. + const changedOtherSettings = ( + Object.keys(otherSettings) as Array + ).some((key) => + key === 'allowedAuthMethods' + ? otherSettings[key]?.join(',') !== previous[key]?.join(',') + : otherSettings[key] !== previous[key], + ); + return api.updateTerminal( + terminal.id, + changedOtherSettings ? payload : { activitySelectionEnabled }, + ); }, onSuccess: async () => { await onSaved(draft.isActive && !wasActive); @@ -623,6 +651,29 @@ function TerminalEditor({

)} +
+ +

+ {t('terminals.activitySelectionHint')} +

+

{t('terminals.geofence')}

diff --git a/apps/web/src/routes/BookingPage.spec.tsx b/apps/web/src/routes/BookingPage.spec.tsx index f445ffc..d882a30 100644 --- a/apps/web/src/routes/BookingPage.spec.tsx +++ b/apps/web/src/routes/BookingPage.spec.tsx @@ -1,5 +1,6 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi, beforeEach } from 'vitest'; +import { fireEvent, screen, waitFor, within } from '@testing-library/react'; +import type { EmployeeRole } from '../api/client'; import { renderWithProviders } from '../test-utils'; const timeEntriesMock = vi.fn().mockResolvedValue([]); @@ -10,6 +11,7 @@ const clockOutMock = vi.fn(); const dailyBlockOptionMock = vi.fn(); const createDailyBlockMock = vi.fn(); const bookableProjectsMock = vi.fn().mockResolvedValue([]); +const activityOptionsMock = vi.fn(); const updateTimeEntryMock = vi.fn(); const splitTimeEntryMock = vi.fn(); const bookProjectRangeMock = vi.fn(); @@ -26,6 +28,8 @@ vi.mock('../api/client', () => ({ dailyBlockOption: (...args: unknown[]) => dailyBlockOptionMock(...args), createDailyBlock: (...args: unknown[]) => createDailyBlockMock(...args), bookableProjects: (...args: unknown[]) => bookableProjectsMock(...args), + timeEntryActivityOptions: (...args: unknown[]) => + activityOptionsMock(...args), updateTimeEntry: (...args: unknown[]) => updateTimeEntryMock(...args), splitTimeEntry: (...args: unknown[]) => splitTimeEntryMock(...args), bookProjectRange: (...args: unknown[]) => bookProjectRangeMock(...args), @@ -33,13 +37,14 @@ vi.mock('../api/client', () => ({ }, })); +let currentRole: EmployeeRole = 'Employee'; vi.mock('../app/auth', () => ({ useCurrentUser: () => ({ id: 'emp-1', email: 'e@test', firstName: 'Test', lastName: 'User', - role: 'Employee', + role: currentRole, }), useAuth: () => ({ user: null, @@ -73,6 +78,8 @@ function entryFixture(overrides: Record = {}) { serviceOrderNo: null, serviceOrderTitle: null, activity: null, + activityId: null, + catalogActivityName: null, summary: { grossMinutes: 480, breakMinutes: 30, netMinutes: 450 }, ...overrides, }; @@ -93,6 +100,7 @@ const PROJECTS = [ describe('BookingPage', () => { beforeEach(() => { + currentRole = 'Employee'; timeEntriesMock.mockClear().mockResolvedValue([]); timeEntryApprovalsMock.mockClear().mockResolvedValue([]); approvalHistoryMock.mockClear().mockResolvedValue([]); @@ -113,13 +121,16 @@ describe('BookingPage', () => { entryFixture({ source: 'DailyBlock', status: 'Approved' }), ); bookableProjectsMock.mockClear().mockResolvedValue([]); - updateTimeEntryMock.mockClear(); + activityOptionsMock.mockReset().mockResolvedValue([]); + updateTimeEntryMock.mockReset().mockResolvedValue(entryFixture()); splitTimeEntryMock.mockClear(); bookProjectRangeMock.mockClear(); violationsMock.mockClear().mockResolvedValue([]); onlineState = true; }); + afterEach(() => vi.restoreAllMocks()); + it('makes own approval status, next reviewer and history discoverable beside bookings', async () => { timeEntryApprovalsMock.mockResolvedValue([ { @@ -209,6 +220,8 @@ describe('BookingPage', () => { fireEvent.change(screen.getByLabelText(/Tätigkeit/i), { target: { value: 'Daten migriert' }, }); + expect(screen.queryByLabelText('Tätigkeit aus dem Katalog')).toBeNull(); + expect(activityOptionsMock).not.toHaveBeenCalled(); const kommen = screen .getAllByRole('button') @@ -225,6 +238,7 @@ describe('BookingPage', () => { }), ); }); + expect(clockInMock.mock.calls[0][0]).not.toHaveProperty('activityId'); }); it('disables "Kommen" until the mandatory service order is chosen', async () => { @@ -413,6 +427,225 @@ describe('BookingPage', () => { expect(screen.getByRole('button', { name: 'Aufteilen' })).toBeDefined(); }); + it('changes only the catalog reference on an approved booking with a historical missing service order', async () => { + const original = entryFixture({ + status: 'Approved', + requiresApproval: true, + projectId: 'p-2', + projectCode: 'PRJ-002', + projectName: 'ERP-Einführung', + activityId: 'old', + catalogActivityName: 'Pflügen', + activity: ' Historisch erfasster Text ', + }); + bookableProjectsMock.mockResolvedValue(PROJECTS); + timeEntriesMock.mockResolvedValue([original]); + activityOptionsMock.mockResolvedValue([{ id: 'new', name: 'Sortieren' }]); + updateTimeEntryMock.mockImplementation(async () => { + const corrected = { + ...original, + activityId: 'new', + catalogActivityName: 'Sortieren', + }; + timeEntriesMock.mockResolvedValue([corrected]); + return corrected; + }); + const { BookingPage } = await import('./BookingPage'); + renderWithProviders(); + const row = (await screen.findByText('Genehmigt')).closest('li'); + const before = row?.textContent; + fireEvent.click(await screen.findByRole('button', { name: 'Projekt' })); + const dialog = within( + screen.getByRole('dialog', { name: 'Buchung bearbeiten' }), + ); + const picker = dialog.getByLabelText( + 'Tätigkeit aus dem Katalog', + ); + expect(picker.value).toBe('old'); + expect( + dialog.getByLabelText( + 'Tätigkeit (für die Kundenauswertung)', + ).value, + ).toBe(original.activity); + expect( + dialog.getByLabelText('Service-Auftrag').value, + ).toBe(''); + expect( + screen.getByRole('dialog').querySelector('input[type="datetime-local"]'), + ).toBeNull(); + expect( + (dialog.getByRole('button', { name: 'Speichern' }) as HTMLButtonElement) + .disabled, + ).toBe(true); + await dialog.findByRole('option', { name: 'Sortieren' }); + expect(activityOptionsMock).toHaveBeenCalledExactlyOnceWith('t-1', 'p-2'); + fireEvent.change(picker, { target: { value: 'new' } }); + fireEvent.click(dialog.getByRole('button', { name: 'Speichern' })); + + await waitFor(() => + expect(updateTimeEntryMock).toHaveBeenCalledExactlyOnceWith('t-1', { + activityId: 'new', + }), + ); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + expect( + (await screen.findByText('Genehmigt')).closest('li')?.textContent, + ).toBe(before); + }); + + it('scopes the English picker to the new project without carrying the old activity or bypassing its required order', async () => { + vi.spyOn(window, 'localStorage', 'get').mockReturnValue({ + length: 1, + clear: vi.fn(), + getItem: (key) => (key === 'openclockwork.locale' ? 'en' : null), + key: () => 'openclockwork.locale', + removeItem: vi.fn(), + setItem: vi.fn(), + }); + bookableProjectsMock.mockResolvedValue(PROJECTS); + timeEntriesMock.mockResolvedValue([ + entryFixture({ + projectId: 'p-1', + projectCode: 'PRJ-001', + activityId: 'old', + catalogActivityName: 'Old project activity', + }), + ]); + activityOptionsMock.mockImplementation(async (_id, projectId) => + projectId === 'p-1' + ? [{ id: 'old', name: 'Old project activity' }] + : [{ id: 'new-project-activity', name: 'Rollout' }], + ); + const { BookingPage } = await import('./BookingPage'); + renderWithProviders(); + fireEvent.click(await screen.findByRole('button', { name: 'Project' })); + const dialog = within(screen.getByRole('dialog', { name: 'Edit booking' })); + await dialog.findByRole('option', { name: 'Old project activity' }); + + fireEvent.change(dialog.getByLabelText('Project'), { + target: { value: 'p-2' }, + }); + await dialog.findByRole('option', { name: 'Rollout' }); + expect( + dialog.queryByRole('option', { name: 'Old project activity' }), + ).toBeNull(); + const picker = dialog.getByLabelText('Catalog activity'); + expect(picker.value).toBe(''); + fireEvent.change(picker, { target: { value: 'new-project-activity' } }); + const save = dialog.getByRole('button', { + name: 'Save', + }); + expect(save.disabled).toBe(true); + fireEvent.change(dialog.getByLabelText('Service order (required)'), { + target: { value: 'so-1' }, + }); + expect(save.disabled).toBe(false); + fireEvent.click(save); + + expect(activityOptionsMock.mock.calls).toEqual([ + ['t-1', 'p-1'], + ['t-1', 'p-2'], + ]); + await waitFor(() => + expect(updateTimeEntryMock).toHaveBeenCalledExactlyOnceWith('t-1', { + projectId: 'p-2', + serviceOrderId: 'so-1', + activityId: 'new-project-activity', + }), + ); + }); + + it('shows a historical activity and allows explicitly removing it if the catalog fails to load', async () => { + timeEntriesMock.mockResolvedValue([ + entryFixture({ + projectId: 'historical-project', + projectName: 'Altes Projekt', + activityId: 'archived', + catalogActivityName: 'Archivierte Tätigkeit', + activity: 'Freier Text', + }), + ]); + activityOptionsMock.mockRejectedValue(new Error('network error')); + const { BookingPage } = await import('./BookingPage'); + renderWithProviders(); + fireEvent.click(await screen.findByRole('button', { name: 'Projekt' })); + const dialog = within( + screen.getByRole('dialog', { name: 'Buchung bearbeiten' }), + ); + expect( + await dialog.findByText( + 'Katalogtätigkeiten konnten nicht geladen werden.', + ), + ).toBeDefined(); + expect(dialog.getByLabelText('Projekt').value).toBe( + 'historical-project', + ); + const picker = dialog.getByLabelText( + 'Tätigkeit aus dem Katalog', + ); + expect(picker.value).toBe('archived'); + expect( + dialog.getByRole('option', { name: 'Archivierte Tätigkeit (aktuell)' }), + ).toBeDefined(); + fireEvent.change(picker, { target: { value: '' } }); + fireEvent.click(dialog.getByRole('button', { name: 'Speichern' })); + + await waitFor(() => + expect(updateTimeEntryMock).toHaveBeenCalledExactlyOnceWith('t-1', { + activityId: null, + }), + ); + }); + + it('does not offer the editor or load catalog options for another employee’s entry as an employee', async () => { + timeEntriesMock.mockResolvedValue([ + entryFixture({ employeeId: 'someone-else' }), + ]); + const { BookingPage } = await import('./BookingPage'); + renderWithProviders(); + + await screen.findByText(/8h 00min/); + expect(screen.queryByRole('button', { name: 'Projekt' })).toBeNull(); + expect(activityOptionsMock).not.toHaveBeenCalled(); + }); + + it.each(['Manager', 'HRAdmin'] as const)( + 'uses the entry-scoped catalog when a %s edits a supplied foreign entry', + async (role) => { + currentRole = role; + timeEntriesMock.mockResolvedValue([ + entryFixture({ + employeeId: 'someone-else', + projectId: 'owner-project', + }), + ]); + activityOptionsMock.mockResolvedValue([ + { id: 'owner-activity', name: 'Tätigkeit des Projekts' }, + ]); + const { BookingPage } = await import('./BookingPage'); + renderWithProviders(); + fireEvent.click(await screen.findByRole('button', { name: 'Projekt' })); + const dialog = within( + screen.getByRole('dialog', { name: 'Buchung bearbeiten' }), + ); + await dialog.findByRole('option', { name: 'Tätigkeit des Projekts' }); + fireEvent.change(dialog.getByLabelText('Tätigkeit aus dem Katalog'), { + target: { value: 'owner-activity' }, + }); + fireEvent.click(dialog.getByRole('button', { name: 'Speichern' })); + + expect(activityOptionsMock).toHaveBeenCalledExactlyOnceWith( + 't-1', + 'owner-project', + ); + await waitFor(() => + expect(updateTimeEntryMock).toHaveBeenCalledExactlyOnceWith('t-1', { + activityId: 'owner-activity', + }), + ); + }, + ); + it('books a retroactive range through the Nachtrag dialog', async () => { bookableProjectsMock.mockResolvedValue(PROJECTS); bookProjectRangeMock.mockResolvedValue({ entries: [entryFixture()] }); diff --git a/apps/web/src/routes/BookingPage.tsx b/apps/web/src/routes/BookingPage.tsx index ad17be8..eab9357 100644 --- a/apps/web/src/routes/BookingPage.tsx +++ b/apps/web/src/routes/BookingPage.tsx @@ -26,6 +26,7 @@ import { type ClockInPayload, type DailyBlockOptionDto, type TimeEntryDto, + type UpdateTimeEntryPayload, } from '../api/client'; import { useCurrentUser } from '../app/auth'; import { useOnline } from '../app/use-online'; @@ -151,17 +152,27 @@ function BookingTargetFields({ target, onChange, noProjectLabel, + currentEntry, }: { idPrefix: string; projects: BookableProjectDto[]; target: BookingTargetState; onChange: (next: BookingTargetState) => void; noProjectLabel?: string; + currentEntry?: TimeEntryDto; }) { const { t } = useI18n(); const resolvedNoProjectLabel = noProjectLabel ?? t('booking.noProject'); const project = projects.find((p) => p.id === target.projectId); const needsOrder = !!project && project.serviceOrders.length > 0; + const historicalProject = + !project && + target.projectId !== '' && + target.projectId === currentEntry?.projectId; + const historicalOrder = + target.serviceOrderId !== '' && + target.serviceOrderId === currentEntry?.serviceOrderId && + !project?.serviceOrders.some((order) => order.id === target.serviceOrderId); return (
@@ -179,6 +190,13 @@ function BookingTargetFields({ className="flex h-9 w-full rounded-md border border-input bg-background px-2 text-sm" > + {historicalProject && ( + + )} {projects.map((p) => (
- {needsOrder && ( + {(needsOrder || historicalOrder) && (
setActivityId(event.target.value)} + disabled={activityId === '' && options.length === 0} + className="flex h-9 w-full rounded-md border border-input bg-background px-2 text-sm" + > + + {activityId !== '' && !selectedActivity && ( + + )} + {options.map((option) => ( + + ))} + + {(catalog.isPending || catalog.isError || options.length === 0) && ( +

+ {t( + catalog.isError + ? 'booking.catalogActivitiesFailed' + : catalog.isPending + ? 'common.loading' + : 'booking.catalogActivitiesEmpty', + )} +

+ )} +
+ )} {error && ( {error} @@ -883,7 +1000,7 @@ function EntryEditDialog({ {t('common.cancel')} + ); + return (
{t('terminalPin.confirmHint')}

- +

+ {t('terminalPin.activityApplyHint')} +

+
)} -
) : phase === 'uncertain' ? (
@@ -454,10 +665,7 @@ export function KioskPinPanel({ @@ -466,16 +674,20 @@ export function KioskPinPanel({

{t( - result.action === 'clock-in' - ? 'terminalPin.successIn' - : 'terminalPin.successOut', + result.kind === 'activity' + ? `terminalPin.activityOutcome.${result.outcome}` + : result.receipt.action === 'clock-in' + ? 'terminalPin.successIn' + : 'terminalPin.successOut', )}

-

- {t('terminalPin.successTime', { - time: formatDateTime(result.bookedAt), - })} -

+ {result.kind === 'booking' && ( +

+ {t('terminalPin.successTime', { + time: formatDateTime(result.receipt.bookedAt), + })} +

+ )}
) : (

@@ -484,7 +696,9 @@ export function KioskPinPanel({ ? 'terminalPin.identifying' : phase === 'locating' ? 'terminalPin.locating' - : 'terminalPin.submitting', + : phase === 'applying-activity' + ? 'terminalPin.activitySubmitting' + : 'terminalPin.submitting', )}

)} @@ -501,3 +715,63 @@ export function KioskPinPanel({
); } + +function KioskActivityPicker({ + options, + clockIn, + onChoose, +}: { + options: Extract; + clockIn: boolean; + onChoose: (id: string | null) => void; +}) { + const { t } = useI18n(); + const label = t( + clockIn + ? 'terminalPin.activityOptionsIn' + : 'terminalPin.activityOptionsOut', + ); + const choiceClass = + 'h-auto min-h-14 w-full justify-between whitespace-normal text-left aria-pressed:border-slate-800 aria-pressed:bg-slate-100 aria-pressed:text-slate-950'; + return ( +
+

{label}

+ {options.activities.length > 0 && ( +
+ {options.activities.map((activity) => ( + + ))} +
+ )} + {clockIn && ( + + )} +
+ ); +} diff --git a/apps/web/src/routes/ProjectActivityCatalog.tsx b/apps/web/src/routes/ProjectActivityCatalog.tsx new file mode 100644 index 0000000..dd2a515 --- /dev/null +++ b/apps/web/src/routes/ProjectActivityCatalog.tsx @@ -0,0 +1,324 @@ +import { useId, useRef, useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { ListChecks, Pencil, Trash2 } from 'lucide-react'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { api, ApiError, type ProjectDto } from '../api/client'; +import { useI18n } from '../app/i18n'; + +export function ProjectActivityCatalog({ + project, +}: { + project: Pick; +}) { + const { t } = useI18n(); + const heading = t('projects.activityCatalog', { project: project.code }); + return ( + + + + + + + {heading} + + {t('projects.activityCatalogHint')} + + + + + + + + + + + ); +} + +type Change = + | { kind: 'create'; name: string } + | { kind: 'rename'; id: string; name: string } + | { kind: 'toggle'; id: string; name: string; isActive: boolean } + | { kind: 'delete'; id: string }; + +function ActivityCatalogContent({ projectId }: { projectId: string }) { + const { t } = useI18n(); + const queryClient = useQueryClient(); + const queryKey = ['projects', projectId, 'activities'] as const; + const refresh = () => + queryClient.invalidateQueries({ queryKey, exact: true }); + const catalog = useQuery({ + queryKey, + queryFn: () => api.projectActivities(projectId), + }); + + const nameId = useId(); + const nameInput = useRef(null); + const [draft, setDraft] = useState(''); + const [editingId, setEditingId] = useState(null); + + const clearForm = () => { + setDraft(''); + setEditingId(null); + }; + + const change = useMutation({ + mutationFn: async (action: Change) => { + switch (action.kind) { + case 'create': + await api.createActivity(projectId, { name: action.name }); + break; + case 'rename': + await api.updateActivity(projectId, action.id, { name: action.name }); + break; + case 'toggle': + await api.updateActivity(projectId, action.id, { + name: action.name, + isActive: action.isActive, + }); + break; + case 'delete': + await api.deleteActivity(projectId, action.id); + break; + } + }, + onSuccess: async (_, action) => { + if ( + action.kind === 'create' || + action.kind === 'rename' || + (action.kind === 'delete' && action.id === editingId) + ) { + clearForm(); + } + await refresh(); + if (action.kind === 'delete') nameInput.current?.focus(); + }, + onError: (error) => { + if ( + error instanceof ApiError && + (error.status === 409 || error.status === 404) + ) { + // Another manager or a new time entry may have changed the catalog. + void refresh(); + } + }, + }); + + const isDelete = change.variables?.kind === 'delete'; + const isConflict = + change.error instanceof ApiError && change.error.status === 409; + const errorKey = isConflict + ? isDelete + ? 'projects.activityDeleteConflict' + : 'projects.activityDuplicate' + : isDelete + ? 'common.deleteFailed' + : 'common.saveFailed'; + const name = draft.trim(); + + return ( + <> + {catalog.isPending &&

{t('common.loading')}

} + {catalog.isError && ( + + +

{t('projects.activitiesLoadFailed')}

+ +
+
+ )} + {change.isError && ( + + {t(errorKey)} + + )} + {change.isPending && ( +

+ {t('common.saving')} +

+ )} + {change.isSuccess && ( +

+ {t(isDelete ? 'projects.activityDeleted' : 'projects.activitySaved')} +

+ )} + {catalog.data && ( + <> +
{ + event.preventDefault(); + if (!name || change.isPending) return; + change.mutate( + editingId + ? { kind: 'rename', id: editingId, name } + : { kind: 'create', name }, + ); + }} + > +
+ + setDraft(event.target.value)} + /> +
+ + {editingId && ( + + )} +
+ {catalog.data.length === 0 ? ( +

+ {t('projects.noActivities')} +

+ ) : ( +
    + {catalog.data.map((activity) => { + const variables = { name: activity.name }; + return ( +
  • +
    +
    + + {activity.name} + + + {t( + activity.isActive + ? 'common.active' + : 'common.inactive', + )} + +
    + {activity.hasBookings && ( +

    + {t('projects.activityHasBookings')} +

    + )} +
    +
    + + + {!activity.hasBookings && ( + + )} +
    +
  • + ); + })} +
+ )} + + )} + + ); +} diff --git a/prisma/migrations/20261127235453_terminal_activity_catalog/migration.sql b/prisma/migrations/20261127235453_terminal_activity_catalog/migration.sql new file mode 100644 index 0000000..7a09bb4 --- /dev/null +++ b/prisma/migrations/20261127235453_terminal_activity_catalog/migration.sql @@ -0,0 +1,49 @@ +BEGIN; + +-- AlterTable +ALTER TABLE "Employee" ADD COLUMN "lastTerminalActivityId" UUID; + +-- AlterTable +ALTER TABLE "TimeEntry" ADD COLUMN "activityId" UUID; + +-- AlterTable +ALTER TABLE "Terminal" ADD COLUMN "activitySelectionEnabled" BOOLEAN NOT NULL DEFAULT false; + +-- CreateTable +CREATE TABLE "Activity" ( + "id" UUID NOT NULL, + "projectId" UUID NOT NULL, + "name" TEXT NOT NULL, + "isActive" BOOLEAN NOT NULL DEFAULT true, + "sortOrder" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Activity_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "Activity_projectId_isActive_sortOrder_idx" ON "Activity"("projectId", "isActive", "sortOrder"); +CREATE UNIQUE INDEX "Activity_projectId_name_key" ON "Activity"("projectId", "name"); +CREATE UNIQUE INDEX "Activity_projectId_id_key" ON "Activity"("projectId", "id"); +CREATE INDEX "Employee_lastTerminalActivityId_idx" ON "Employee"("lastTerminalActivityId"); +CREATE INDEX "TimeEntry_activityId_idx" ON "TimeEntry"("activityId"); + +-- AddForeignKey +ALTER TABLE "Activity" + ADD CONSTRAINT "Activity_projectId_fkey" + FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "Employee" + ADD CONSTRAINT "Employee_lastTerminalActivityId_fkey" + FOREIGN KEY ("lastTerminalActivityId") REFERENCES "Activity"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- The CHECK closes the nullable composite foreign key's project-less case. +ALTER TABLE "TimeEntry" + ADD CONSTRAINT "TimeEntry_activity_requires_project_chk" + CHECK ("activityId" IS NULL OR "projectId" IS NOT NULL), + ADD CONSTRAINT "TimeEntry_projectId_activityId_fkey" + FOREIGN KEY ("projectId", "activityId") REFERENCES "Activity"("projectId", "id") + ON DELETE RESTRICT ON UPDATE CASCADE; + +COMMIT; diff --git a/prisma/migrations/20261128021500_terminal_activity_redemption/migration.sql b/prisma/migrations/20261128021500_terminal_activity_redemption/migration.sql new file mode 100644 index 0000000..6182f48 --- /dev/null +++ b/prisma/migrations/20261128021500_terminal_activity_redemption/migration.sql @@ -0,0 +1,19 @@ +-- A PIN activity selection uses the same one-use challenge even without a booking. +ALTER TABLE "TerminalChallengeRedemption" + ALTER COLUMN "timeEntryId" DROP NOT NULL, + DROP CONSTRAINT "TerminalChallengeRedemption_action_chk", + ADD CONSTRAINT "TerminalChallengeRedemption_action_chk" CHECK ( + "action" = 'activity' + OR ("action" IN ('clock-in', 'clock-out') AND "timeEntryId" IS NOT NULL) + ); + +-- Keep the original physical receipt invariant; an activity choice is not a receipt. +ALTER TABLE "TerminalBookingGrant" + DROP CONSTRAINT "TerminalBookingGrant_consumption_chk", + ADD CONSTRAINT "TerminalBookingGrant_consumption_chk" CHECK ( + ("consumedAt" IS NULL AND "action" IS NULL AND "timeEntryId" IS NULL AND "bookedAt" IS NULL) + OR ("consumedAt" IS NOT NULL AND "action" IS NOT NULL AND ( + ("action" IN ('clock-in', 'clock-out') AND "timeEntryId" IS NOT NULL AND "bookedAt" IS NOT NULL) + OR ("action" = 'activity' AND "bookedAt" IS NULL) + )) + ); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8998ca5..732c95d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -153,6 +153,8 @@ model Employee { projectAssignments ProjectAssignment[] terminalChallengeRedemptions TerminalChallengeRedemption[] terminalCredential TerminalCredential? + lastTerminalActivityId String? @db.Uuid + lastTerminalActivity Activity? @relation(fields: [lastTerminalActivityId], references: [id], onDelete: SetNull) ownedInstallation InstallationSettings? soloPolicies SoloPolicy[] personalDays PersonalDay[] @@ -165,6 +167,7 @@ model Employee { @@index([role]) @@index([managerId]) @@index([workScheduleId]) + @@index([lastTerminalActivityId]) } // Frame and core working hours. A schedule is assigned per Employee @@ -261,6 +264,9 @@ model TimeEntry { serviceOrder ServiceOrder? @relation(fields: [projectId, serviceOrderId], references: [projectId, id], onDelete: Restrict) /// Customer-facing description of the work performed (Tätigkeit). activity String? + activityId String? @db.Uuid + /// The composite relation keeps the catalog activity in the booked project. + catalogActivity Activity? @relation(fields: [projectId, activityId], references: [projectId, id], onDelete: Restrict) /// Local calendar date for DailyBlock entries. Null for all other entry sources. bookingDate DateTime? @db.Date createdAt DateTime @default(now()) @@ -272,6 +278,7 @@ model TimeEntry { @@index([status]) @@index([projectId]) @@index([serviceOrderId]) + @@index([activityId]) @@index([terminalId]) @@index([clockOutTerminalId]) @@index([clockInChallengeId]) @@ -288,6 +295,7 @@ model Terminal { logoUrl String? allowedAuthMethods String[] @default(["QR"]) authConfigVersion Int @default(0) + activitySelectionEnabled Boolean @default(false) enforceGeofence Boolean @default(true) latitude Decimal? @db.Decimal(9, 6) longitude Decimal? @db.Decimal(9, 6) @@ -356,8 +364,9 @@ model TerminalChallengeRedemption { challenge TerminalChallenge @relation(fields: [challengeId], references: [id], onDelete: Cascade) employeeId String @db.Uuid employee Employee @relation(fields: [employeeId], references: [id], onDelete: Restrict) - timeEntryId String @db.Uuid - timeEntry TimeEntry @relation(fields: [timeEntryId], references: [id], onDelete: Restrict) + /// A preference-only activity selection consumes the challenge without a booking. + timeEntryId String? @db.Uuid + timeEntry TimeEntry? @relation(fields: [timeEntryId], references: [id], onDelete: Restrict) action String @db.VarChar(9) createdAt DateTime @default(now()) @@ -483,6 +492,7 @@ model Project { /// service-order planHours must not exceed this (service-enforced). planHours Decimal? @db.Decimal(8, 2) serviceOrders ServiceOrder[] + activities Activity[] assignments ProjectAssignment[] timeEntries TimeEntry[] createdAt DateTime @default(now()) @@ -492,6 +502,23 @@ model Project { @@index([customerId]) } +model Activity { + id String @id @default(uuid()) @db.Uuid + projectId String @db.Uuid + project Project @relation(fields: [projectId], references: [id], onDelete: Cascade) + name String + isActive Boolean @default(true) + sortOrder Int @default(0) + timeEntries TimeEntry[] + lastUsedBy Employee[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([projectId, name]) + @@unique([projectId, id]) + @@index([projectId, isActive, sortOrder]) +} + model ServiceOrder { id String @id @default(uuid()) @db.Uuid projectId String @db.Uuid