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..f5d2061 --- /dev/null +++ b/apps/api-e2e/src/api/project-activities.e2e.spec.ts @@ -0,0 +1,453 @@ +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('blocks activities until the last service order, even inactive, is deleted', async () => { + const { project, manager } = await fixture(); + const token = await login(ctx.http, manager.email); + const orders = `/api/projects/${project.id}/service-orders`; + const orderDto = { orderNo: 'ORDER-1', title: 'Service order' }; + const order = await ctx.http + .post(orders) + .auth(token, { type: 'bearer' }) + .send(orderDto) + .expect(201); + + const addActivity = () => + ctx.http + .post(catalog(project.id)) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting' }); + + const activeConflict = await addActivity().expect(409); + expect(activeConflict.body.code).toBe('PROJECT_HAS_SERVICE_ORDERS'); + await ctx.http + .put(`${orders}/${order.body.id}`) + .auth(token, { type: 'bearer' }) + .send({ ...orderDto, isActive: false }) + .expect(200); + const inactiveConflict = await addActivity().expect(409); + expect(inactiveConflict.body.code).toBe('PROJECT_HAS_SERVICE_ORDERS'); + await ctx.http + .delete(`${orders}/${order.body.id}`) + .auth(token, { type: 'bearer' }) + .expect(204); + + await addActivity().expect(201); + }); + + it('blocks service orders until the last activity, even inactive, is deleted', async () => { + const { project, manager } = await fixture(); + const token = await login(ctx.http, manager.email); + const projectPath = `/api/projects/${project.id}`; + const activity = await ctx.http + .post(catalog(project.id)) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting' }) + .expect(201); + + const addOrder = () => + ctx.http + .post(`${projectPath}/service-orders`) + .auth(token, { type: 'bearer' }) + .send({ orderNo: 'ORDER-1', title: 'Service order' }); + + const activeConflict = await addOrder().expect(409); + expect(activeConflict.body.code).toBe('PROJECT_HAS_ACTIVITIES'); + const activityPath = `${catalog(project.id)}/${activity.body.id}`; + await ctx.http + .put(activityPath) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting', isActive: false }) + .expect(200); + const inactiveConflict = await addOrder().expect(409); + expect(inactiveConflict.body.code).toBe('PROJECT_HAS_ACTIVITIES'); + + const item = await ctx.http.get(projectPath).expect(200); + expect(item.body.activityCount).toBe(1); + const listed = await ctx.http.get('/api/projects').expect(200); + expect(listed.body).toContainEqual( + expect.objectContaining({ id: project.id, activityCount: 1 }), + ); + const edited = await ctx.http + .put(projectPath) + .auth(token, { type: 'bearer' }) + .send({ code: project.code, name: 'Updated project' }) + .expect(200); + expect(edited.body.activityCount).toBe(1); + + await ctx.http.delete(activityPath).auth(token, { type: 'bearer' }).expect(204); + const empty = await ctx.http.get(projectPath).expect(200); + expect(empty.body.activityCount).toBe(0); + await addOrder().expect(201); + }); + + it('allows only one of concurrent activity and service-order creations', async () => { + const { project, manager } = await fixture(); + const token = await login(ctx.http, manager.email); + const [activity, order] = await Promise.all([ + ctx.http + .post(catalog(project.id)) + .auth(token, { type: 'bearer' }) + .send({ name: 'Sorting' }), + ctx.http + .post(`/api/projects/${project.id}/service-orders`) + .auth(token, { type: 'bearer' }) + .send({ orderNo: 'ORDER-1', title: 'Service order' }), + ]); + + expect([activity.status, order.status].sort()).toEqual([201, 409]); + if (activity.status === 201) { + expect(order.body.code).toBe('PROJECT_HAS_ACTIVITIES'); + } else { + expect(activity.body.code).toBe('PROJECT_HAS_SERVICE_ORDERS'); + } + const saved = await ctx.http.get(`/api/projects/${project.id}`).expect(200); + expect(saved.body.activityCount).toBe(activity.status === 201 ? 1 : 0); + expect(saved.body.serviceOrders).toHaveLength(order.status === 201 ? 1 : 0); + }); + + it('preserves legacy mixed projects, edits and booked activity history', 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 legacyOrder = await ctx.prisma.serviceOrder.create({ + data: { projectId: project.id, orderNo: 'LEGACY', title: 'Legacy order' }, + }); + const projectPath = `/api/projects/${project.id}`; + 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 mixed = await ctx.http.get(projectPath).expect(200); + expect(mixed.body).toMatchObject({ + activityCount: 1, + serviceOrders: [expect.objectContaining({ id: legacyOrder.id })], + }); + const orderPath = `${projectPath}/service-orders/${legacyOrder.id}`; + await ctx.http + .put(orderPath) + .auth(token, { type: 'bearer' }) + .send({ orderNo: 'LEGACY', title: 'Legacy archived', isActive: false }) + .expect(200); + + 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); + await ctx.http.delete(orderPath).auth(token, { type: 'bearer' }).expect(204); + 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..64fbdf9 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, @@ -67,6 +68,7 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { expect(created.body.code).toBe('P-1'); expect(created.body.isActive).toBe(true); expect(created.body.assignedEmployeeCount).toBe(0); + expect(created.body.activityCount).toBe(0); }); it('HRAdmin may create; duplicate codes are rejected with 409', async () => { @@ -381,53 +383,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 cee1233..ed185df 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..6e4f0c8 --- /dev/null +++ b/apps/api-e2e/src/api/terminal-activity-state.e2e.spec.ts @@ -0,0 +1,513 @@ +import { createHash } from 'node:crypto'; +import { listEligibleTerminalActivities } from '../../../api/src/app/terminals/terminal-activity-selection'; +import type { KioskActivityProjectDto } from '../../../api/src/app/terminals/terminal-auth.dto'; +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, + projects: [], + 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, activityId?: string) { + return ctx.http + .post(`${kiosk}/book`) + .auth(device, { type: 'bearer' }) + .send({ grant: grantToken, action: 'clock-in', activityId }); + } + + function projectOption( + project: Pick, + unavailableReason: KioskActivityProjectDto['unavailableReason'] = null, + ): KioskActivityProjectDto { + return { + id: project.id, + code: project.code, + name: project.name, + unavailableReason, + }; + } + + async function catalog( + employeeId: string, + code: string, + options: { + projectName?: string; + activityName?: string; + projectActive?: boolean; + activityActive?: boolean; + orderActive?: boolean; + assigned?: boolean; + } = {}, + ) { + const { + projectName = `Project ${code}`, + activityName = `Activity ${code}`, + projectActive, + activityActive, + orderActive, + assigned = true, + } = options; + const project = await seedProject(ctx.prisma, { + code, + name: projectName, + 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: activityName, + isActive: activityActive, + }, + }); + return { + project, + activity, + dto: { + id: activity.id, + name: activity.name, + projectId: project.id, + projectName: project.name, + projectCode: project.code, + }, + }; + } + + const remember = (employeeId: string, activityId: string) => + ctx.prisma.employee.update({ + where: { id: employeeId }, + data: { lastTerminalActivityId: activityId }, + }); + + function expectNoActivityState(body: Record) { + expect(body).not.toHaveProperty('projects'); + expect(body).not.toHaveProperty('activities'); + expect(body).not.toHaveProperty('selectedActivityId'); + } + + it('lists active assigned projects by code, including unavailable projects, without allowing unavailable bookings', async () => { + const f = await fixture(); + const labels = { + projectName: 'Synthetic shared project name', + activityName: 'Synthetic shared activity name', + }; + const preferred = await catalog(f.worker.id, 'NO-ORDERS', labels); + const secondEligible = await catalog(f.worker.id, 'SECOND', labels); + const inactiveOrder = await catalog(f.worker.id, 'INACTIVE-ORDER', { + orderActive: false, + }); + const noActivity = await seedProject(ctx.prisma, { + code: 'NO-ACTIVITY', + assigneeIds: [f.worker.id], + }); + const inactiveActivity = 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 }); + const activeOrder = 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 token = await grant(f.device, f.worker); + const response = await state(f.device, token).expect(200); + expect(response.headers['cache-control']).toContain('no-store'); + expect(response.body).toEqual({ + enabled: true, + projects: expect.arrayContaining([ + projectOption(preferred.project), + projectOption(secondEligible.project), + projectOption(inactiveOrder.project, 'SERVICE_ORDERS'), + projectOption(noActivity, 'NO_ACTIVE_ACTIVITIES'), + projectOption(inactiveActivity.project, 'NO_ACTIVE_ACTIVITIES'), + projectOption(activeOrder.project, 'SERVICE_ORDERS'), + projectOption(archived.project, 'ARCHIVED_CUSTOMER'), + ]), + activities: expect.arrayContaining([preferred.dto, secondEligible.dto]), + selectedActivityId: preferred.activity.id, + }); + expect(response.body.projects).toHaveLength(7); + expect(response.body.activities).toHaveLength(2); + + const blocked = await book(f.device, token, activeOrder.activity.id).expect( + 409, + ); + expect(blocked.body.code).toBe('TERMINAL_ACTIVITY_UNAVAILABLE'); + 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'); + 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, + projects: [projectOption(project)], + 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, + projects: [projectOption(project, 'NO_ACTIVE_ACTIVITIES')], + }); + 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 }, + }); + + // A legacy mixed catalog remains blocked even if its order is inactive. + const order = await ctx.prisma.serviceOrder.create({ + data: { + projectId: project.id, + orderNo: 'LEGACY', + title: 'Inactive legacy order', + isActive: false, + }, + }); + expect(await read()).toEqual({ + ...empty, + projects: [projectOption(project, 'SERVICE_ORDERS')], + }); + await book(f.device, token, activity.id).expect(409); + await ctx.prisma.serviceOrder.delete({ where: { id: order.id } }); + 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, + projects: [projectOption(choice.project)], + 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, + projects: [projectOption(own.project)], + activities: [own.dto], + selectedActivityId: own.activity.id, + }); + expect((await state(f.device, second).expect(200)).body).toEqual({ + enabled: true, + projects: [projectOption(foreign.project)], + 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..a97d42b --- /dev/null +++ b/apps/api-e2e/src/api/terminal-activity-switch.e2e.spec.ts @@ -0,0 +1,878 @@ +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'; + pauseAction?: 'pause-start' | 'pause-end'; + }), + }; + } + + 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' | 'pause-start' | 'pause-end', + 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('deducts a physical break once after a switch and rejects another switch while paused', async () => { + setTime('08:00'); + const f = await fixture(); + await ctx.prisma.workSchedule.update({ + where: { id: f.schedule.id }, + data: { + terminalRules: { + startTimes: [], + fixedBreaks: [], + earlyStartMinutes: 0, + breakStartToleranceMinutes: 0, + breakEndToleranceMinutes: 0, + shortBreakMinutes: 0, + }, + }, + }); + const first = await catalog(f.employee.id, 'BEFORE-PAUSE'); + const second = await catalog(f.employee.id, 'AFTER-SWITCH'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-in', { + activityId: first.id, + }).expect(201); + + setTime('12:00'); + await activity(f.deviceToken, (await grant(f)).grant, second.id).expect( + 200, + ); + setTime('12:15'); + const startingPause = await grant(f); + expect(startingPause.pauseAction).toBe('pause-start'); + await book(f.deviceToken, startingPause.grant, 'pause-start').expect(201); + + setTime('12:45'); + const endingPause = await grant(f); + expect(endingPause.pauseAction).toBe('pause-end'); + const denied = await activity( + f.deviceToken, + endingPause.grant, + first.id, + ).expect(409); + expect(denied.body.code).toBe('TERMINAL_ACTIVITY_PAUSED'); + await book(f.deviceToken, endingPause.grant, 'pause-end').expect(201); + + setTime('16:00'); + await book(f.deviceToken, (await grant(f)).grant, 'clock-out').expect(201); + const [start, end] = await ctx.prisma.timeEntry.findMany({ + where: { employeeId: f.employee.id }, + orderBy: { clockIn: 'asc' }, + }); + expect(start.clockOut).toEqual(end.clockIn); + expect(start.captureGroupId).toBeTruthy(); + expect(end.captureGroupId).toBe(start.captureGroupId); + expect(end.terminalCapture).toEqual(start.terminalCapture); + expect(end.terminalCapture).toMatchObject({ + pauses: [ + { + originalStart: at('12:15').toISOString(), + originalEnd: at('12:45').toISOString(), + }, + ], + }); + + const hrToken = await login(ctx.http, f.hr.email); + const report = await ctx.http + .get('/api/reports/working-times') + .auth(hrToken, { 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 filtered = await ctx.http + .get('/api/timeentries') + .auth(hrToken, { type: 'bearer' }) + .query({ + employeeId: f.employee.id, + from: end.clockIn.toISOString(), + to: end.clockIn.toISOString(), + }) + .expect(200); + expect(filtered.body).toEqual([ + expect.objectContaining({ + id: end.id, + summary: { grossMinutes: 240, breakMinutes: 30, netMinutes: 210 }, + }), + ]); + }); + + 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 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: 'LEGACY', + title: 'Inactive legacy order', + isActive: false, + }, + }); + 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 e719f72..c9773f6 100644 --- a/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts +++ b/apps/api-e2e/src/api/terminal-booking.e2e.spec.ts @@ -1,24 +1,29 @@ -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'; describe('Atomic, explicit terminal PIN bookings and audits', () => { let ctx: TestContext; - beforeAll(async () => { + beforeEach(async () => { + // Pairing also has an in-memory rate limit, independent of the database. ctx = await createTestApp(); + await ctx.reset(); }); - afterAll(async () => { + afterEach(async () => { await ctx.close(); }); - beforeEach(async () => { - 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 +35,7 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { enforceGeofence: geofence, isActive: true, allowedAuthMethods: ['QR', 'PIN'], + activitySelectionEnabled, ...(geofence ? { latitude: 49.7913, @@ -57,7 +63,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 +98,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)), }; } @@ -410,6 +424,280 @@ describe('Atomic, explicit terminal PIN bookings and audits', () => { }, ); + async function activity(employeeId: string, code: string) { + const project = await seedProject(ctx.prisma, { + code, + assigneeIds: [employeeId], + }); + 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 }, + }); + const foreignOrder = await ctx.prisma.serviceOrder.create({ + data: { + projectId: other.projectId, + orderNo: 'OTHER', + title: 'Other order', + }, + }); + 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: foreignOrder.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.create({ + data: { + projectId: chosen.projectId, + orderNo: 'NEW', + title: 'New order', + }, + }); + 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); @@ -493,14 +781,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( @@ -510,6 +804,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'); @@ -735,7 +1039,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); @@ -771,7 +1075,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 }, @@ -891,8 +1195,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. @@ -906,13 +1216,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"', @@ -921,7 +1229,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 5970e07..a75db80 100644 --- a/apps/api/openapi.json +++ b/apps/api/openapi.json @@ -1608,6 +1608,9 @@ } } } + }, + "409": { + "description": "Project contains activities (PROJECT_HAS_ACTIVITIES), the order number already exists, or the order exceeds the project plan." } }, "security": [ @@ -1701,6 +1704,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": "Project contains service orders (PROJECT_HAS_SERVICE_ORDERS) or the activity name already exists." + } + }, + "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", @@ -2759,6 +2943,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", @@ -2860,6 +3090,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", @@ -7029,6 +7327,10 @@ "$ref": "#/components/schemas/ServiceOrderDto" } }, + "activityCount": { + "type": "number", + "description": "Number of active and inactive activities." + }, "assignedEmployeeCount": { "type": "number" }, @@ -7049,6 +7351,7 @@ "defaultBillable", "bookedMinutes", "serviceOrders", + "activityCount", "assignedEmployeeCount", "updatedAt" ] @@ -7182,6 +7485,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": { @@ -7896,6 +8264,15 @@ "type": "string", "nullable": true }, + "activityId": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "catalogActivityName": { + "type": "string", + "nullable": true + }, "summary": { "nullable": true, "type": "object", @@ -7948,6 +8325,8 @@ "serviceOrderNo", "serviceOrderTitle", "activity", + "activityId", + "catalogActivityName", "summary" ] }, @@ -8611,9 +8990,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": { @@ -8716,15 +9114,143 @@ "requiresLocation" ] }, - "BookTerminalDto": { + "KioskGrantDto": { "type": "object", "properties": { "grant": { + "type": "string", + "description": "Short-lived grant returned by kiosk identification.", + "writeOnly": true + } + }, + "required": ["grant"] + }, + "KioskActivityProjectDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "code": { "type": "string" }, - "action": { + "name": { + "type": "string" + }, + "unavailableReason": { "type": "string", - "enum": ["clock-in", "clock-out", "pause-start", "pause-end"] + "enum": [ + "SERVICE_ORDERS", + "NO_ACTIVE_ACTIVITIES", + "ARCHIVED_CUSTOMER" + ], + "nullable": true + } + }, + "required": ["id", "code", "name", "unavailableReason"] + }, + "KioskActivityDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "projectId": { + "type": "string", + "format": "uuid" + }, + "projectName": { + "type": "string" + }, + "projectCode": { + "type": "string" + } + }, + "required": ["id", "name", "projectId", "projectName", "projectCode"] + }, + "KioskActivityStateDto": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/KioskActivityProjectDto" + } + }, + "activities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/KioskActivityDto" + } + }, + "selectedActivityId": { + "type": "string", + "format": "uuid", + "nullable": true + } + }, + "required": ["enabled", "projects", "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", @@ -8743,6 +9269,15 @@ "positionTimestamp": { "type": "string", "format": "date-time" + }, + "action": { + "type": "string", + "enum": ["clock-in", "clock-out", "pause-start", "pause-end"] + }, + "activityId": { + "type": "string", + "format": "uuid", + "description": "Eligible catalog activity for clock-in only. Omit for plain booking." } }, "required": ["grant", "action"] @@ -9180,6 +9715,9 @@ "isActive": { "type": "boolean" }, + "activitySelectionEnabled": { + "type": "boolean" + }, "isPaired": { "type": "boolean" }, @@ -9221,6 +9759,7 @@ "enforceGeofence", "timeZone", "isActive", + "activitySelectionEnabled", "isPaired", "deviceCount", "devices", @@ -9299,6 +9838,10 @@ "isActive": { "type": "boolean", "default": false + }, + "activitySelectionEnabled": { + "type": "boolean", + "description": "Allow activity selection at this terminal. Defaults to false." } }, "required": ["name", "displayText", "locationLabel"] @@ -9374,6 +9917,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 2b4fcef..95bdefd 100644 --- a/apps/api/src/app/accounts/accounts.service.ts +++ b/apps/api/src/app/accounts/accounts.service.ts @@ -10,9 +10,9 @@ 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 { loadCaptureSummaries } from '../time-entries/capture-summary'; import type { AccountDto } from './accounts.dto'; @Injectable() @@ -33,43 +33,47 @@ 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 }, - }, - select: { - id: true, - employeeId: true, - clockIn: true, - clockOut: true, - breakRules: true, - terminalCapture: true, - captureGroupId: true, - status: true, - voidedAt: true, + 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, + terminalCapture: true, + captureGroupId: true, + status: true, + voidedAt: true, + }, + }); + const grouped = await loadCaptureSummaries( + tx, + entries.filter( + (entry) => entry.captureGroupId || entry.terminalCapture, + ), + ); + return entries.reduce((minutes, entry) => { + if (!entry.clockOut) return minutes; + if (entry.captureGroupId || entry.terminalCapture) + 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); }, - }); - const terminalSummaries = await loadCaptureSummaries( - this.prisma, - entries.filter((entry) => entry.terminalCapture), + { isolationLevel: 'RepeatableRead' }, ); - let netMinutesYtd = 0; - for (const e of entries) { - if (!e.clockOut) continue; - if (e.terminalCapture) { - netMinutesYtd += terminalSummaries.get(e.id)?.netMinutes ?? 0; - continue; - } - const gross = Math.floor( - (e.clockOut.getTime() - e.clockIn.getTime()) / 60_000, - ); - netMinutesYtd += calculateNetMinutes( - gross, - parseBreakRules(e.breakRules), - ); - } // 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 235dc8b..74c4ad7 100644 --- a/apps/api/src/app/erp-export/erp-export.service.ts +++ b/apps/api/src/app/erp-export/erp-export.service.ts @@ -40,41 +40,52 @@ 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 } }, + 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 || entry.terminalCapture, + ), + ); + return rows.flatMap((r) => { + if (!r.clockOut) return []; + const netMinutes = + r.captureGroupId || r.terminalCapture + ? (grouped.get(r.id)?.netMinutes ?? 0) + : summarize(r.clockIn, r.clockOut, parseBreakRules(r.breakRules)) + .netMinutes; + return [ + { + id: r.id, + employeeId: r.employeeId, + personalNo: r.employee.personalNo, + clockIn: r.clockIn.toISOString(), + clockOut: r.clockOut.toISOString(), + netMinutes, + projectCode: r.project?.code ?? null, + projectName: r.project?.name ?? null, + orderNo: r.serviceOrder?.orderNo ?? null, + orderTitle: r.serviceOrder?.title ?? null, + activity: r.activity, + }, + ]; + }); }, - skip, - take, - }); - const terminalSummaries = await loadCaptureSummaries( - this.prisma, - rows.filter((entry) => entry.terminalCapture), + { isolationLevel: 'RepeatableRead' }, ); - return rows - .filter((r) => r.clockOut !== null) - .map((r) => { - const netMinutes = r.terminalCapture - ? (terminalSummaries.get(r.id)?.netMinutes ?? 0) - : summarize(r.clockIn, r.clockOut, parseBreakRules(r.breakRules)) - .netMinutes; - return { - id: r.id, - employeeId: r.employeeId, - personalNo: r.employee.personalNo, - clockIn: r.clockIn.toISOString(), - clockOut: (r.clockOut as Date).toISOString(), - netMinutes, - projectCode: r.project?.code ?? null, - projectName: r.project?.name ?? null, - orderNo: r.serviceOrder?.orderNo ?? null, - orderTitle: r.serviceOrder?.title ?? null, - activity: r.activity, - }; - }); } } diff --git a/apps/api/src/app/projects/projects.controller.ts b/apps/api/src/app/projects/projects.controller.ts index 0a07075..6da54bc 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, @@ -128,6 +133,10 @@ export class ProjectsController { @Post(':id/service-orders') @ApiCreatedResponse({ type: ServiceOrderDto }) + @ApiConflictResponse({ + description: + 'Project contains activities (PROJECT_HAS_ACTIVITIES), the order number already exists, or the order exceeds the project plan.', + }) @ApiBearerAuth() @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Manager', 'HRAdmin') @@ -166,6 +175,75 @@ 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: + 'Project contains service orders (PROJECT_HAS_SERVICE_ORDERS) or the activity name already exists.', + }) + @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..33ca43b 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; @@ -132,6 +208,8 @@ export class ProjectDto { bookedMinutes!: number; @ApiProperty({ type: [ServiceOrderDto] }) serviceOrders!: ServiceOrderDto[]; + @ApiProperty({ description: 'Number of active and inactive activities.' }) + activityCount!: number; @ApiProperty() assignedEmployeeCount!: number; @ApiProperty({ format: 'date-time' }) @@ -231,8 +309,8 @@ export function toProjectDto( p: Project & { serviceOrders: ServiceOrder[]; customer?: { name: string } | null; + _count: { activities: number; assignments: number }; }, - assignedEmployeeCount: number, stats: ProjectIstStats = EMPTY_IST_STATS, ): ProjectDto { return { @@ -257,7 +335,8 @@ export function toProjectDto( (stats.netMinutes === undefined ? undefined : 0), ), ), - assignedEmployeeCount, + activityCount: p._count.activities, + assignedEmployeeCount: p._count.assignments, updatedAt: p.updatedAt.toISOString(), }; } diff --git a/apps/api/src/app/projects/projects.service.ts b/apps/api/src/app/projects/projects.service.ts index 6ec5bb1..25940a1 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,21 @@ import { type ProjectIstStats, type ProjectReportDto, type ServiceOrderDto, + type UpsertActivityDto, type UpsertProjectDto, type UpsertServiceOrderDto, } from './projects.dto'; +const PROJECT_DTO_INCLUDE = { + customer: { select: { name: true } }, + serviceOrders: { orderBy: { orderNo: 'asc' } }, + _count: { select: { assignments: true, activities: true } }, +} as const satisfies Prisma.ProjectInclude; + +const ACTIVITY_BOOKING_COUNT = { + _count: { select: { timeEntries: true } }, +} as const; + interface IstRow { projectId: string; serviceOrderId: string | null; @@ -54,27 +67,19 @@ export class ProjectsService { this.prisma.project.findMany({ where: includeInactive ? undefined : { isActive: true }, orderBy: { code: 'asc' }, - include: { - customer: { select: { name: true } }, - serviceOrders: { orderBy: { orderNo: 'asc' } }, - _count: { select: { assignments: true } }, - }, + include: PROJECT_DTO_INCLUDE, }), this.loadIstStats(), ]); return rows.map((r) => - toProjectDto(r, r._count.assignments, stats.get(r.id) ?? EMPTY_IST_STATS), + toProjectDto(r, stats.get(r.id) ?? EMPTY_IST_STATS), ); } async getById(id: string): Promise { const row = await this.findOrThrow(id); const stats = await this.loadIstStats(id); - return toProjectDto( - row, - row._count.assignments, - stats.get(id) ?? EMPTY_IST_STATS, - ); + return toProjectDto(row, stats.get(id) ?? EMPTY_IST_STATS); } async create(dto: UpsertProjectDto, actor: JwtUser): Promise { @@ -96,16 +101,12 @@ export class ProjectsService { ? { create: { employeeId: actor.id } } : undefined, }, - include: { - serviceOrders: true, - customer: { select: { name: true } }, - }, + include: PROJECT_DTO_INCLUDE, }); }); this.broadcast(created.id); return toProjectDto( created, - solo ? 1 : 0, solo ? { ...EMPTY_IST_STATS, netMinutes: 0, netByOrder: new Map() } : EMPTY_IST_STATS, @@ -177,20 +178,12 @@ export class ProjectsService { customerId: dto.customerId, defaultBillable: dto.defaultBillable, }, - include: { - customer: { select: { name: true } }, - serviceOrders: { orderBy: { orderNo: 'asc' } }, - _count: { select: { assignments: true } }, - }, + include: PROJECT_DTO_INCLUDE, }); }); this.broadcast(id); const stats = await this.loadIstStats(id); - return toProjectDto( - updated, - updated._count.assignments, - stats.get(id) ?? EMPTY_IST_STATS, - ); + return toProjectDto(updated, stats.get(id) ?? EMPTY_IST_STATS); } catch (err) { if (isUniqueViolation(err)) { throw new ConflictException( @@ -225,6 +218,12 @@ export class ProjectsService { try { const created = await this.mutate(actor, async (tx) => { const project = await this.findOrThrow(projectId, tx); + if (project._count.activities > 0) { + throw new ConflictException({ + code: 'PROJECT_HAS_ACTIVITIES', + message: 'A project with activities cannot add service orders', + }); + } this.assertOrderPlanFits( project, project.serviceOrders, @@ -333,6 +332,113 @@ 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, async (tx) => { + const project = await tx.project.findUnique({ + where: { id: projectId }, + select: { serviceOrders: { select: { id: true }, take: 1 } }, + }); + if (!project) + throw new NotFoundException(`Project ${projectId} not found`); + if (project.serviceOrders.length > 0) { + throw new ConflictException({ + code: 'PROJECT_HAS_SERVICE_ORDERS', + message: 'A project with service orders cannot add activities', + }); + } + return 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 +620,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 +636,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 +653,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 +664,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 +677,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 @@ -676,23 +797,26 @@ export class ProjectsService { actor: JwtUser, action: (tx: Prisma.TransactionClient, solo: boolean) => Promise, ): Promise { - return this.prisma.$transaction(async (tx) => { - await tx.$executeRaw`SELECT pg_advisory_xact_lock(${INSTALLATION_LOCK})`; - const employee = await tx.employee.findUnique({ - where: { id: actor.id }, - }); - if ( - !employee?.isActive || - !['Manager', 'HRAdmin'].includes(employee.role) || - (actor.authVersion ?? 0) !== employee.authVersion - ) - throw new ForbiddenException( - 'Project management session is no longer authorized', - ); - const solo = (await this.installation.getSettings(tx)).mode === 'Solo'; - if (solo) await this.installation.requireOwner(actor.id, tx); - return action(tx, solo); - }); + return this.prisma.$transaction( + async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(${INSTALLATION_LOCK})`; + const employee = await tx.employee.findUnique({ + where: { id: actor.id }, + }); + if ( + !employee?.isActive || + !['Manager', 'HRAdmin'].includes(employee.role) || + (actor.authVersion ?? 0) !== employee.authVersion + ) + throw new ForbiddenException( + 'Project management session is no longer authorized', + ); + const solo = (await this.installation.getSettings(tx)).mode === 'Solo'; + if (solo) await this.installation.requireOwner(actor.id, tx); + return action(tx, solo); + }, + { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }, + ); } private async findOrThrow( @@ -701,11 +825,7 @@ export class ProjectsService { ) { const row = await tx.project.findUnique({ where: { id }, - include: { - customer: { select: { name: true } }, - serviceOrders: { orderBy: { orderNo: 'asc' } }, - _count: { select: { assignments: true } }, - }, + include: PROJECT_DTO_INCLUDE, }); if (!row) throw new NotFoundException(`Project ${id} not found`); return row; @@ -742,3 +862,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/reports/reports.service.ts b/apps/api/src/app/reports/reports.service.ts index 6347274..ab573c2 100644 --- a/apps/api/src/app/reports/reports.service.ts +++ b/apps/api/src/app/reports/reports.service.ts @@ -711,7 +711,8 @@ export class ReportsService { tx: Prisma.TransactionClient, ) { const terminalGroups = entries.flatMap((entry) => - entry.terminalCapture && entry.captureGroupId + (entry.terminalCapture || entry.source === 'Terminal') && + entry.captureGroupId ? [entry.captureGroupId] : [], ); diff --git a/apps/api/src/app/requests/time-adjustments.service.ts b/apps/api/src/app/requests/time-adjustments.service.ts index 8da13d2..74a1c99 100644 --- a/apps/api/src/app/requests/time-adjustments.service.ts +++ b/apps/api/src/app/requests/time-adjustments.service.ts @@ -14,6 +14,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'; @@ -60,10 +61,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..63fe000 --- /dev/null +++ b/apps/api/src/app/terminals/terminal-activity-selection.ts @@ -0,0 +1,127 @@ +import { ConflictException, ForbiddenException } from '@nestjs/common'; +import type { Prisma } from '@prisma/client'; +import type { + KioskActivityDto, + KioskActivityProjectDto, +} from './terminal-auth.dto'; + +function assignedActiveProject(employeeId: string): Prisma.ProjectWhereInput { + return { + isActive: true, + assignments: { some: { employeeId } }, + }; +} + +/** Shared by kiosk reads and mutations; mutations must check inside their transaction. */ +export function terminalActivityEligibility( + employeeId: string, +): Prisma.ActivityWhereInput { + return { + isActive: true, + project: { + ...assignedActiveProject(employeeId), + serviceOrders: { none: {} }, + // 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, code: true } }, + }, + orderBy: [ + { project: { name: 'asc' } }, + { projectId: 'asc' }, + { sortOrder: 'asc' }, + { name: 'asc' }, + ], + }); + return activities.map(({ project, ...activity }) => ({ + ...activity, + projectName: project.name, + projectCode: project.code, + })); +} + +/** List assigned projects even when their activities are unavailable to the kiosk. */ +export async function listAssignedTerminalProjects( + tx: Prisma.TransactionClient, + employeeId: string, + activities: readonly KioskActivityDto[], +): Promise { + const availableProjects = new Set( + activities.map(({ projectId }) => projectId), + ); + const projects = await tx.project.findMany({ + where: assignedActiveProject(employeeId), + select: { + id: true, + code: true, + name: true, + customer: { select: { isActive: true } }, + serviceOrders: { + select: { id: true }, + take: 1, + }, + }, + orderBy: [{ name: 'asc' }, { code: 'asc' }], + }); + return projects.map(({ customer, serviceOrders, ...project }) => { + let unavailableReason: KioskActivityProjectDto['unavailableReason'] = null; + if (!availableProjects.has(project.id)) { + if (customer?.isActive === false) unavailableReason = 'ARCHIVED_CUSTOMER'; + else if (serviceOrders.length) unavailableReason = 'SERVICE_ORDERS'; + else unavailableReason = 'NO_ACTIVE_ACTIVITIES'; + } + return { ...project, unavailableReason }; + }); +} 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 c2bb2da..d4e964e 100644 --- a/apps/api/src/app/terminals/terminal-auth.dto.ts +++ b/apps/api/src/app/terminals/terminal-auth.dto.ts @@ -18,6 +18,7 @@ import { MaxLength, Min, MinLength, + ValidateIf, } from 'class-validator'; // Preserve lexical credentials even with the application's implicit conversion. @@ -62,16 +63,47 @@ export class IdentifyTerminalResultDto { pauseAction?: TerminalPauseAction; @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: TERMINAL_BOOKING_ACTIONS }) - @IsIn(TERMINAL_BOOKING_ACTIONS) - action!: TerminalBookingAction; +} +export class KioskActivityDto { + @ApiProperty({ format: 'uuid' }) id!: string; + @ApiProperty() name!: string; + @ApiProperty({ format: 'uuid' }) projectId!: string; + @ApiProperty() projectName!: string; + @ApiProperty() projectCode!: string; +} +const KIOSK_PROJECT_UNAVAILABLE_REASONS = [ + 'SERVICE_ORDERS', + 'NO_ACTIVE_ACTIVITIES', + 'ARCHIVED_CUSTOMER', +] as const; + +export class KioskActivityProjectDto { + @ApiProperty({ format: 'uuid' }) id!: string; + @ApiProperty() code!: string; + @ApiProperty() name!: string; + @ApiProperty({ enum: KIOSK_PROJECT_UNAVAILABLE_REASONS, nullable: true }) + unavailableReason!: (typeof KIOSK_PROJECT_UNAVAILABLE_REASONS)[number] | null; +} + +export class KioskActivityStateDto { + @ApiProperty() enabled!: boolean; + @ApiProperty({ type: [KioskActivityProjectDto] }) + projects!: KioskActivityProjectDto[]; + @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() @@ -94,6 +126,39 @@ export class BookTerminalDto { @IsDateString() positionTimestamp?: string; } + +export class BookTerminalDto extends KioskPositionedGrantDto { + @ApiProperty({ enum: TERMINAL_BOOKING_ACTIONS }) + @IsIn(TERMINAL_BOOKING_ACTIONS) + action!: TerminalBookingAction; + @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: TERMINAL_BOOKING_ACTIONS }) diff --git a/apps/api/src/app/terminals/terminal-auth.service.ts b/apps/api/src/app/terminals/terminal-auth.service.ts index e5e3a9b..9e4e542 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, @@ -15,15 +16,35 @@ 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 { + listAssignedTerminalProjects, + 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; @@ -44,7 +65,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 }, @@ -114,7 +135,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); @@ -254,7 +275,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: {} }, }, @@ -515,153 +536,414 @@ 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, + projects: [], + activities: [], + selectedActivityId: null, + }; + const activities = await listEligibleTerminalActivities( + tx, + grant.employeeId, + ); + const projects = await listAssignedTerminalProjects( + tx, + grant.employeeId, + activities, + ); + const remembered = employee?.lastTerminalActivityId ?? null; + return { + enabled: true, + projects, + 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 open = await findOpenTerminalEntry(tx, employeeId); + if (availableTerminalPause(open?.terminalCapture) === 'pause-end') + throw new ConflictException({ + code: 'TERMINAL_ACTIVITY_PAUSED', + message: 'End the open pause before selecting an activity', + }); + const activity = await resolveTerminalActivity( + tx, + employeeId, + dto.activityId, + device.terminal.activitySelectionEnabled, + ); + 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-in' && 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, + tx, + ); + 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, + { id: grant.pauseEntryId, revision: grant.pauseRevision }, + 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, - tx, - ); - const booked = await bookTerminalTime( - tx, - employeeId, - challenge, - now, - schedule, - position, - dto.action, - { id: grant.pauseEntryId, revision: grant.pauseRevision }, - ); - 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' @@ -688,7 +970,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 cfeacd0..d6b3e05 100644 --- a/apps/api/src/app/terminals/terminal-booking.service.ts +++ b/apps/api/src/app/terminals/terminal-booking.service.ts @@ -3,11 +3,11 @@ import { ConflictException, NotFoundException, } from '@nestjs/common'; -import type { +import { Prisma, - Terminal, - TerminalChallenge, - TimeEntry, + type Terminal, + type TerminalChallenge, + type TimeEntry, } from '@prisma/client'; import { randomUUID } from 'node:crypto'; import { @@ -18,9 +18,16 @@ import { openTerminalPause, readTerminalCapture, requiresSpecialApproval, + type FrameTimeRule, type TerminalBookingAction, + type TerminalCapture, } 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; @@ -29,10 +36,94 @@ 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' }, + }); +} + +/** Terminal capture describes the physical attendance shared by its segments. */ +export async function syncTerminalCapture( + tx: Prisma.TransactionClient, + entry: Pick, + terminalCapture: TerminalCapture | undefined, +) { + if (!terminalCapture || !entry.captureGroupId) return; + await tx.timeEntry.updateMany({ + where: { + id: { not: entry.id }, + employeeId: entry.employeeId, + captureGroupId: entry.captureGroupId, + voidedAt: null, + status: { not: 'Rejected' }, + }, + data: { terminalCapture }, + }); +} + +/** 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, + terminalCapture: readTerminalCapture(open.terminalCapture) ?? undefined, + requiresApproval: requiresSpecialApproval(at, null, frame), + }, + select: { id: true }, + }); +} /** Shared QR/PIN write path. Caller owns security locks, validation and audit. */ export async function bookTerminalTime( @@ -44,11 +135,9 @@ export async function bookTerminalTime( position: TerminalPosition, expectedAction?: TerminalBookingAction, expectedPause?: { id: string | null; revision: number | null }, + activity?: TerminalActivityTarget, ) { - const open = await tx.timeEntry.findFirst({ - where: { employeeId, clockOut: null, voidedAt: null }, - orderBy: { clockIn: 'desc' }, - }); + const open = await findOpenTerminalEntry(tx, employeeId); const defaultAction = open ? 'clock-out' : 'clock-in'; const action = expectedAction ?? defaultAction; const isPause = action === 'pause-start' || action === 'pause-end'; @@ -67,10 +156,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({ @@ -90,6 +176,7 @@ export async function bookTerminalTime( : undefined; booked = await tx.timeEntry.create({ data: { + ...activity, employeeId, clockIn: bookingNow, source: 'Terminal', @@ -130,17 +217,19 @@ export async function bookTerminalTime( if (bookingNow <= previousStamp) { throw new ConflictException('The punch must follow the previous stamp'); } + const terminalCapture = + action === 'pause-start' + ? openTerminalPause(capture, bookingNow) + : finishTerminalPause(capture, bookingNow); booked = await tx.timeEntry.update({ where: { id: open.id, clockOut: null, revision: open.revision }, data: { - terminalCapture: - action === 'pause-start' - ? openTerminalPause(capture, bookingNow) - : finishTerminalPause(capture, bookingNow), + terminalCapture, revision: { increment: 1 }, }, include: ENTRY_INCLUDE, }); + await syncTerminalCapture(tx, open, terminalCapture); } else { if (!open) throw new ConflictException('No open entry to close'); if (bookingNow <= open.clockIn) { @@ -151,11 +240,12 @@ export async function bookTerminalTime( bookingNow, schedule.frame, ); + const terminalCapture = closeTerminalCapture(open.terminalCapture, bookingNow); const updated = await tx.timeEntry.updateMany({ where: { id: open.id, clockOut: null }, data: { clockOut: bookingNow, - terminalCapture: closeTerminalCapture(open.terminalCapture, bookingNow), + terminalCapture, revision: { increment: 1 }, status: requires ? 'Pending' : 'Approved', requiresApproval: requires, @@ -180,6 +270,7 @@ export async function bookTerminalTime( if (updated.count !== 1) { throw new ConflictException('Time entry was already closed'); } + await syncTerminalCapture(tx, open, terminalCapture); const row = await tx.timeEntry.findUnique({ where: { id: open.id }, include: ENTRY_INCLUDE, 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 bd7e83c..19c611e 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, @@ -138,9 +144,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' }) @@ -200,6 +227,9 @@ export class TerminalDto { @ApiProperty() isActive!: boolean; + @ApiProperty() + activitySelectionEnabled!: boolean; + @ApiProperty() isPaired!: boolean; @@ -410,6 +440,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 6fc21ca..65e58b3 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 type { TerminalBookingAction } from 'shared'; import { bookTerminalTime } from './terminal-booking.service'; @@ -22,6 +22,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: { not: 'activity' }, createdAt: { gt: new Date(now.getTime() - 60_000) }, }, }); @@ -659,10 +661,7 @@ export class TerminalsService { let action: TerminalBookingAction = '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) => { @@ -750,7 +749,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 }, ); @@ -769,18 +773,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 @@ -826,6 +830,7 @@ export class TerminalsService { enforceGeofence, ...geofence, timeZone, + activitySelectionEnabled: dto.activitySelectionEnabled, }; } @@ -890,6 +895,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 a1e86ec..687e2dd 100644 --- a/apps/api/src/app/time-entries/time-entries.controller.ts +++ b/apps/api/src/app/time-entries/time-entries.controller.ts @@ -41,6 +41,7 @@ import { VoidTimeEntryDto, SwitchProjectDto, TimeEntryAuditDto, + TimeEntryActivityOptionDto, SplitTimeEntryDto, UpdateTimeEntryDto, BookProjectRangeResult, @@ -260,6 +261,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 e37b522..382bbf9 100644 --- a/apps/api/src/app/time-entries/time-entries.dto.ts +++ b/apps/api/src/app/time-entries/time-entries.dto.ts @@ -18,7 +18,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 { availableTerminalPause, parseBreakRules, @@ -225,7 +225,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 }) @@ -263,6 +264,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 { @@ -572,6 +592,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; @@ -592,9 +618,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 toTerminalCaptureDto( @@ -666,6 +703,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, ...(capture ? { terminalCapture: capture } : {}), summary: e.clockOut && !e.voidedAt && e.status !== 'Rejected' 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 ad7bd93..97900d6 100644 --- a/apps/api/src/app/time-entries/time-entries.service.ts +++ b/apps/api/src/app/time-entries/time-entries.service.ts @@ -29,6 +29,7 @@ import { } from '../work-schedules/work-schedules.service'; import { ProjectsService } from '../projects/projects.service'; import { InstallationService } from '../installation/installation.service'; +import { syncTerminalCapture } from '../terminals/terminal-booking.service'; import { calculateCaptureSummaries, loadCaptureSummaries, @@ -40,6 +41,7 @@ import type { ProxyManualTimeEntryDto, } from './proxy-time-entry.dto'; import { + TIME_ENTRY_ALLOCATION_INCLUDE as ENTRY_INCLUDE, toTimeEntryDto, type BookProjectRangeDto, type BookProjectRangeResult, @@ -49,7 +51,9 @@ import { type DailyBlockOptionDto, type SplitTimeEntryDto, type SplitTimeEntryResult, + type TimeEntryActivityOptionDto, type TimeEntryDto, + type TimeEntryWithAllocation, type UpdateTimeEntryDto, type ManualTimeEntryDto, type CorrectTimeEntryDto, @@ -59,15 +63,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,14 +866,15 @@ export class TimeEntriesService { open.id, ); const before = await this.auditSnapshot(tx, open); + const terminalCapture = closeTerminalCapture( + open.terminalCapture, + bookingNow, + ); const result = await tx.timeEntry.updateMany({ where: { id: open.id, clockOut: null }, data: { clockOut: bookingNow, - terminalCapture: closeTerminalCapture( - open.terminalCapture, - bookingNow, - ), + terminalCapture, status: requires ? 'Pending' : 'Approved', requiresApproval: requires, frameApproverId: null, @@ -901,6 +897,7 @@ export class TimeEntriesService { if (result.count !== 1) { throw new ConflictException('Time entry was already closed'); } + await syncTerminalCapture(tx, open, terminalCapture); const row = await tx.timeEntry.findUnique({ where: { id: open.id }, include: ENTRY_INCLUDE, @@ -927,12 +924,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, @@ -943,19 +975,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, @@ -966,7 +1018,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'); } @@ -995,25 +1047,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, @@ -1023,11 +1103,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, @@ -1036,7 +1118,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; }); @@ -1124,7 +1210,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 ?? @@ -1178,6 +1264,7 @@ export class TimeEntriesService { clockOutTerminalId: entry.clockOutTerminalId, clockOutChallengeId: entry.clockOutChallengeId, ...second, + activityId: this.activityForProject(current, second.projectId), }, include: ENTRY_INCLUDE, }); @@ -1278,7 +1365,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, @@ -1306,12 +1393,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; @@ -1350,6 +1432,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()), @@ -1610,7 +1693,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({ @@ -1620,6 +1703,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, @@ -1874,6 +1958,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(); @@ -2027,7 +2139,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({ @@ -2052,6 +2165,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 }, @@ -2220,6 +2344,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/web-e2e/src/terminal-pin.spec.ts b/apps/web-e2e/src/terminal-pin.spec.ts index ec70686..6ca9966 100644 --- a/apps/web-e2e/src/terminal-pin.spec.ts +++ b/apps/web-e2e/src/terminal-pin.spec.ts @@ -1,16 +1,37 @@ import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; 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 SyntheticProject = { + id: string; + code: string; + name: string; + activities: { id: string; name: string }[]; +}; + type TerminalFixture = { employeeId: string; + employeeName: string; + terminalId: string; personalNo: string; pin: string; pairingCode: string; + listEntries: () => Promise; + projects: SyntheticProject[]; }; function assertLocalTestTarget(baseURL: string | undefined) { @@ -30,8 +51,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<{ + catalogMode: 'disabled' | 'single' | 'multiple' | 'with-service-orders'; + terminal: TerminalFixture; +}>({ + catalogMode: ['disabled', { option: true }], + terminal: async ({ request, baseURL, catalogMode }, use) => { // Check before the first request: these tests create and revoke HR records. assertLocalTestTarget(baseURL); const login = await request.post('/api/auth/login', { @@ -45,15 +70,17 @@ const test = base.extend<{ terminal: TerminalFixture }>({ const headers = { Authorization: `Bearer ${accessToken}` }; const suffix = randomUUID().slice(0, 12); const personalNo = `00-pin-${suffix}`; + const lastName = `Terminal-${suffix}`; let employeeId: string | undefined; let terminalId: string | undefined; + const projects: SyntheticProject[] = []; try { const employee = await request.post('/api/employees', { headers, data: { personalNo, firstName: 'Synthetic', - lastName: 'Terminal', + lastName, email: `pin-${suffix}@example.test`, password: 'synthetic-test-password', role: 'Employee', @@ -84,10 +111,12 @@ const test = base.extend<{ terminal: TerminalFixture }>({ maxAccuracyMeters: null, isActive: true, allowedAuthMethods: ['PIN'], + activitySelectionEnabled: catalogMode !== 'disabled', }, }); 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 +129,96 @@ const test = base.extend<{ terminal: TerminalFixture }>({ ); expect(pairing.ok()).toBe(true); const { pairingCode } = await pairing.json(); + const createProject = async (code: string, activityNames: string[]) => { + const name = `E2E project ${suffix}`; + const createdProject = await request.post('/api/projects', { + headers, + data: { code, name }, + }); + expect(createdProject.ok()).toBe(true); + const { id } = (await createdProject.json()) as { id: string }; + const project: SyntheticProject = { id, code, name, activities: [] }; + projects.push(project); + for (const activityName of activityNames) { + const response = await request.post( + `/api/projects/${id}/activities`, + { + headers, + data: { name: activityName }, + }, + ); + expect(response.ok()).toBe(true); + const activity = (await response.json()) as { id: string }; + project.activities.push({ id: activity.id, name: activityName }); + } + return project; + }; + const assignProject = async (project: SyntheticProject) => { + const assignment = await request.put( + `/api/projects/${project.id}/assignments/${employeeId}`, + { headers }, + ); + expect(assignment.status()).toBe(204); + }; + if (catalogMode === 'single') { + const project = await createProject(`PIN-${suffix}`, [ + 'Synthetic picking', + 'Synthetic sorting', + ]); + await assignProject(project); + } else if (catalogMode !== 'disabled') { + const first = await createProject( + `PIN-A-${suffix}`, + catalogMode === 'with-service-orders' ? [] : ['Synthetic picking'], + ); + const second = await createProject(`PIN-B-${suffix}`, [ + 'Synthetic sorting', + ]); + if (catalogMode === 'with-service-orders') { + for (const orderNo of ['ORDER-A', 'ORDER-B']) { + const order = await request.post( + `/api/projects/${first.id}/service-orders`, + { + headers, + data: { + orderNo, + title: `Synthetic service order ${orderNo}`, + isActive: true, + }, + }, + ); + expect(order.status()).toBe(201); + } + await assignProject(first); + await assignProject(second); + } + } await use({ employeeId: employeeRecord.id, + employeeName: `Synthetic ${lastName}`, + terminalId: terminalRecord.id, personalNo, pin, pairingCode, + projects, + 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); + for (const { id, code, name } of projects) { + // Booked history is deliberately not deleted. This test target is disposable. + await request.put(`/api/projects/${id}`, { + headers, + data: { code, name, isActive: false }, + }); + } } }, }); @@ -147,6 +258,72 @@ async function identify( await page.getByRole('button', { name: 'Anmeldung prüfen' }).click(); } +function projectButton(page: Page, project: SyntheticProject) { + return page + .getByRole('group', { name: 'Projekt auswählen' }) + .getByRole('button', { + name: `${project.code} ${project.name}`, + exact: true, + }); +} + +function projectCard(page: Page, project: SyntheticProject) { + return page + .getByRole('button', { name: `Tätigkeiten – ${project.code}`, exact: true }) + .locator('../..'); +} + +async function openActivityCatalog(page: Page, project: SyntheticProject) { + const name = `Tätigkeiten – ${project.code}`; + await page.getByRole('button', { name, exact: true }).click(); + return page.getByRole('dialog', { name, exact: true }); +} + +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; +} + +async function signInAsHr(page: Page) { + await page.goto('/'); + await page + .getByLabel('E-Mail', { exact: true }) + .fill(process.env.SMOKE_EMAIL ?? 'hannah.roth@openclockwork.test'); + await page + .getByLabel('Passwort', { exact: true }) + .fill(process.env.SMOKE_PASSWORD ?? 'openclockwork'); + await page.getByRole('button', { name: 'Anmelden', exact: true }).click(); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); +} + test('Terminal PIN: paired PIN-only terminal explicitly clocks in and out without an employee session', async ({ page, terminal, @@ -187,6 +364,401 @@ 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({ catalogMode: 'single' }); + + test('switches activity within one attendance and still clocks out with one tap', async ({ + page, + terminal, + }) => { + const project = required(terminal.projects[0], 'synthetic project'); + const [firstActivity, secondActivity] = project.activities; + 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 expect(projectButton(page, project)).toBeVisible(); + await expect(picking).toHaveCount(0); + await projectButton(page, project).click(); + 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: firstActivity.id, + projectId: project.id, + terminalId: terminal.terminalId, + }), + ]); + + await finish.click(); + await identify(page, terminal); + await projectButton(page, project).click(); + 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 === firstActivity.id), + 'original activity segment', + ); + const second = required( + switched.find((entry) => entry.activityId === secondActivity.id), + '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: project.id, + }); + expect(Date.parse(second.clockIn)).toBeGreaterThan(Date.parse(arrival)); + + await finish.click(); + await identify(page, terminal); + // 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: firstActivity.id, + clockIn: arrival, + clockOut: first.clockOut, + captureGroupId: first.captureGroupId, + clockOutTerminalId: null, + }), + expect.objectContaining({ + id: second.id, + activityId: secondActivity.id, + projectId: project.id, + 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( + projectButton(page, required(terminal.projects[0], 'synthetic project')), + ).toBeVisible(); + 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.describe('Terminal PIN with multiple projects', () => { + test.use({ catalogMode: 'multiple' }); + + test('keeps both matrix assignments, switches projects without a gap and exports each activity', async ({ + baseURL, + browser, + page, + terminal, + }) => { + const [first, second] = terminal.projects; + const [firstActivity] = first.activities; + const [secondActivity] = second.activities; + const admin = await browser.newPage({ baseURL, locale: 'de-DE' }); + try { + await signInAsHr(admin); + await admin.goto('/admin/projects'); + const assignment = (project: SyntheticProject) => + admin.getByRole('checkbox', { + name: `${terminal.employeeName} – ${project.code}`, + exact: true, + }); + for (const project of terminal.projects) { + const checkbox = assignment(project); + await expect(checkbox).not.toBeChecked(); + const [response] = await Promise.all([ + admin.waitForResponse( + (response) => + response.request().method() === 'PUT' && + new URL(response.url()).pathname === + `/api/projects/${project.id}/assignments/${terminal.employeeId}`, + ), + checkbox.click(), + ]); + expect(response.status()).toBe(204); + } + await admin.reload(); + for (const project of terminal.projects) + await expect(assignment(project)).toBeChecked(); + + const picking = page.getByRole('button', { name: /^Synthetic picking/ }); + const sorting = page.getByRole('button', { name: /^Synthetic sorting/ }); + const finish = page.getByRole('button', { name: 'Vorgang beenden' }); + + await pair(page, terminal); + await identify(page, terminal); + await expect(projectButton(page, first)).toBeVisible(); + await expect(projectButton(page, second)).toBeVisible(); + await expect(picking).toHaveCount(0); + await expect(sorting).toHaveCount(0); + await projectButton(page, first).click(); + await expect(sorting).toHaveCount(0); + await picking.click(); + expect(await terminal.listEntries()).toEqual([]); + const arrival = await book( + page, + page.getByRole('button', { name: 'Jetzt einstempeln' }), + 'clock-in', + ); + expect(await terminal.listEntries()).toEqual([ + expect.objectContaining({ + activityId: firstActivity.id, + projectId: first.id, + clockIn: arrival, + clockOut: null, + }), + ]); + + await finish.click(); + await identify(page, terminal); + await expect(projectButton(page, first)).toBeVisible(); + await projectButton(page, second).click(); + await expect(picking).toHaveCount(0); + await sorting.click(); + await page.getByRole('button', { name: 'Tätigkeit wechseln' }).click(); + await expect( + page.getByText('Tätigkeit gewechselt', { exact: true }), + ).toBeVisible(); + + await finish.click(); + await identify(page, terminal); + const departure = await book( + page, + page.getByRole('button', { name: 'Jetzt ausstempeln' }), + 'clock-out', + ); + const segments = await terminal.listEntries(); + expect(segments).toHaveLength(2); + const firstSegment = required( + segments.find((segment) => segment.activityId === firstActivity.id), + 'first project segment', + ); + expect(firstSegment).toMatchObject({ + projectId: first.id, + captureGroupId: expect.any(String), + clockIn: arrival, + clockOut: expect.any(String), + }); + expect(segments).toContainEqual( + expect.objectContaining({ + projectId: second.id, + activityId: secondActivity.id, + captureGroupId: firstSegment.captureGroupId, + clockIn: firstSegment.clockOut, + clockOut: departure, + }), + ); + + for (const project of terminal.projects) { + const [activity] = project.activities; + await projectCard(admin, project) + .getByRole('button', { name: 'Auswertung', exact: true }) + .click(); + const report = admin.getByRole('dialog', { + name: `Auswertung ${project.code} · ${project.name}`, + exact: true, + }); + await expect( + report.getByRole('columnheader', { name: 'Tätigkeit' }), + ).toBeVisible(); + await expect( + report.getByRole('cell', { name: activity.name, exact: true }), + ).toBeVisible(); + await expect(report.getByRole('row')).toHaveCount(3); + + const [download] = await Promise.all([ + admin.waitForEvent('download'), + report.getByRole('button', { name: 'CSV herunterladen' }).click(), + ]); + expect(download.suggestedFilename()).toBe( + `${project.code.toLowerCase()}-report.csv`, + ); + const lines = (await readFile(await download.path(), 'utf8')).split( + '\r\n', + ); + expect(lines).toHaveLength(3); + expect(lines[0]).toMatch(/;Tätigkeit$/); + expect(lines[1].split(';').at(-1)).toBe(activity.name); + expect(lines[2]).toMatch(/^Gesamt;/); + await report + .getByRole('button', { name: 'Schließen', exact: true }) + .click(); + } + } finally { + await admin.close(); + } + }); +}); + +test.describe('Terminal PIN with service orders on an assigned project', () => { + test.use({ catalogMode: 'with-service-orders' }); + + test('shows both assigned projects before activities and explains which one is blocked', async ({ + page, + terminal, + }) => { + const [blocked, available] = terminal.projects; + const [eligibleActivity] = available.activities; + const blockedProject = projectButton(page, blocked); + const availableProject = projectButton(page, available); + const activity = page.getByRole('button', { name: /^Synthetic sorting/ }); + + await pair(page, terminal); + await identify(page, terminal); + await expect(blockedProject).toBeVisible(); + await expect(blockedProject).toBeDisabled(); + await expect(blockedProject).toHaveAccessibleDescription( + 'Service-Aufträge vorhanden', + ); + await expect(availableProject).toBeVisible(); + await expect(availableProject).toBeEnabled(); + await expect(activity).toHaveCount(0); + + await availableProject.click(); + await activity.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({ + projectId: available.id, + activityId: eligibleActivity.id, + clockIn: arrival, + clockOut: departure, + }), + ]); + }); + + test('HR sees the mutual exclusion of service orders and activity catalogs in Projects', async ({ + page, + terminal, + }) => { + const [orderProject, activityProject] = terminal.projects; + await signInAsHr(page); + await page.goto('/admin/projects'); + + const expectActivityCreationBlocked = async () => { + const catalog = await openActivityCatalog(page, orderProject); + await expect( + catalog.getByText( + 'Neue Tätigkeiten sind erst möglich, wenn alle Service-Aufträge gelöscht sind.', + { exact: true }, + ), + ).toBeVisible(); + await expect( + catalog.getByLabel('Name der Tätigkeit', { exact: true }), + ).toBeDisabled(); + await expect( + catalog.getByRole('button', { + name: 'Tätigkeit hinzufügen', + exact: true, + }), + ).toBeDisabled(); + await catalog + .getByRole('button', { name: 'Schließen', exact: true }) + .click(); + }; + + await expectActivityCreationBlocked(); + const orderCard = projectCard(page, orderProject); + for (const orderNo of ['ORDER-A', 'ORDER-B']) { + const row = orderCard + .getByRole('listitem') + .filter({ hasText: `Synthetic service order ${orderNo}` }); + await row + .getByRole('button', { name: 'Deaktivieren', exact: true }) + .click(); + await expect( + row.getByRole('button', { name: 'Aktivieren', exact: true }), + ).toBeVisible(); + } + await expectActivityCreationBlocked(); + + const activityCard = projectCard(page, activityProject); + await expect( + activityCard.getByText( + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + { exact: true }, + ), + ).toBeVisible(); + await expect( + activityCard.getByLabel('Auftragsnr.', { exact: true }), + ).toBeDisabled(); + await expect( + activityCard.getByRole('button', { name: 'Hinzufügen', exact: true }), + ).toBeDisabled(); + }); +}); + test('Terminal PIN: incorrect PIN preserves pairing and cancellation does not clock in', async ({ page, terminal, @@ -225,15 +797,7 @@ test('Terminal PIN: HR can inspect PIN status and the real audit log without red page, terminal, }) => { - await page.goto('/'); - await page - .getByLabel('E-Mail') - .fill(process.env.SMOKE_EMAIL ?? 'hannah.roth@openclockwork.test'); - await page - .getByLabel('Passwort') - .fill(process.env.SMOKE_PASSWORD ?? 'openclockwork'); - await page.getByRole('button', { name: 'Anmelden' }).click(); - await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await signInAsHr(page); await page.goto('/admin/employees'); const row = page.getByRole('row').filter({ hasText: terminal.personalNo }); await row.getByRole('button', { name: 'Terminal-PIN verwalten' }).click(); @@ -244,14 +808,31 @@ test('Terminal PIN: HR can inspect PIN status and the real audit log without red await page.goto('/admin/settings/terminals'); await page.getByRole('button', { name: 'Protokoll laden' }).click(); - await page.getByLabel('Methode', { exact: true }).selectOption('PIN'); - await expect( - page - .getByRole('row') - .filter({ hasText: terminal.employeeId }) - .filter({ - has: page.locator('[title="PinReset"]'), - }), - ).toBeVisible(); + const waitForPinAudit = () => + page.waitForResponse((response) => { + const url = new URL(response.url()); + return ( + url.pathname === '/api/terminals/audit-events' && + url.searchParams.get('method') === 'PIN' && + response.ok() + ); + }); + await Promise.all([ + waitForPinAudit(), + page.getByLabel('Methode', { exact: true }).selectOption('PIN'), + ]); + const auditRow = page + .getByRole('row') + .filter({ hasText: terminal.employeeId }) + .filter({ has: page.locator('[title="PinReset"]') }); + const next = page.getByRole('button', { name: 'Nächste Seite', exact: true }); + const reload = page.getByRole('button', { name: 'Protokoll laden' }); + // Parallel booking scenarios can add more events than fit on the first page. + for (let scanned = 0; scanned < 8; scanned += 1) { + await expect(reload).toBeEnabled(); + if ((await auditRow.isVisible()) || !(await next.isEnabled())) break; + await Promise.all([waitForPinAudit(), next.click()]); + } + await expect(auditRow).toBeVisible(); await expect(page.locator('output')).toHaveCount(0); }); diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index d0ef099..19b4ca2 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -366,6 +366,8 @@ export interface TimeEntryDto { serviceOrderNo: string | null; serviceOrderTitle: string | null; activity: string | null; + activityId: string | null; + catalogActivityName: string | null; summary: TimeSummaryDto | null; terminalCapture?: TerminalCaptureDto; } @@ -447,8 +449,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; @@ -495,6 +501,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; @@ -504,6 +513,7 @@ export interface ProjectDto { planHours: number | null; bookedMinutes: number; serviceOrders: ServiceOrderDto[]; + activityCount: number; assignedEmployeeCount: number; updatedAt: string; } @@ -863,6 +873,7 @@ export interface TerminalDto { radiusMeters: number | null; maxAccuracyMeters: number | null; isActive: boolean; + activitySelectionEnabled: boolean; isPaired: boolean; deviceCount: number; activatedAt: string | null; @@ -891,6 +902,7 @@ export interface UpsertTerminalPayload { radiusMeters: number | null; maxAccuracyMeters: number | null; isActive: boolean; + activitySelectionEnabled?: boolean; } export interface TerminalPairingDto { @@ -1311,6 +1323,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', @@ -1378,6 +1394,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', @@ -1671,7 +1707,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 52fb34f..e0ad8ba 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; @@ -932,6 +964,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; @@ -980,6 +1028,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; @@ -2559,6 +2639,8 @@ export interface components { bookedNetMinutes?: number; bookedMinutes: number; serviceOrders: components['schemas']['ServiceOrderDto'][]; + /** @description Number of active and inactive activities. */ + activityCount: number; assignedEmployeeCount: number; /** Format: date-time */ updatedAt: string; @@ -2604,6 +2686,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; @@ -2824,6 +2928,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; terminalCapture?: components['schemas']['TerminalCaptureDto']; }; @@ -3067,6 +3174,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. */ @@ -3104,15 +3221,74 @@ export interface components { pauseAction?: 'pause-start' | 'pause-end'; requiresLocation: boolean; }; + KioskGrantDto: { + /** @description Short-lived grant returned by kiosk identification. */ + grant: string; + }; + KioskActivityProjectDto: { + /** Format: uuid */ + id: string; + code: string; + name: string; + /** @enum {string|null} */ + unavailableReason: + | 'SERVICE_ORDERS' + | 'NO_ACTIVE_ACTIVITIES' + | 'ARCHIVED_CUSTOMER' + | null; + }; + KioskActivityDto: { + /** Format: uuid */ + id: string; + name: string; + /** Format: uuid */ + projectId: string; + projectName: string; + projectCode: string; + }; + KioskActivityStateDto: { + enabled: boolean; + projects: components['schemas']['KioskActivityProjectDto'][]; + 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' | 'pause-start' | 'pause-end'; latitude?: number; longitude?: number; accuracyMeters?: number; /** Format: date-time */ positionTimestamp?: string; + /** @enum {string} */ + action: 'clock-in' | 'clock-out' | 'pause-start' | 'pause-end'; + /** + * Format: uuid + * @description Eligible catalog activity for clock-in only. Omit for plain booking. + */ + activityId?: string; }; BookTerminalResultDto: { /** @enum {string} */ @@ -3250,6 +3426,7 @@ export interface components { maxAccuracyMeters?: number | null; timeZone: string; isActive: boolean; + activitySelectionEnabled: boolean; isPaired: boolean; deviceCount: number; /** Format: date-time */ @@ -3300,6 +3477,8 @@ export interface components { timeZone: string; /** @default false */ isActive: boolean; + /** @description Allow activity selection at this terminal. Defaults to false. */ + activitySelectionEnabled?: boolean; }; UpdateTerminalDto: { /** @@ -3339,6 +3518,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 */ @@ -4883,6 +5064,13 @@ export interface operations { 'application/json': components['schemas']['ServiceOrderDto']; }; }; + /** @description Project contains activities (PROJECT_HAS_ACTIVITIES), the order number already exists, or the order exceeds the project plan. */ + 409: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; ProjectsController_updateServiceOrder: { @@ -4931,6 +5119,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 Project contains service orders (PROJECT_HAS_SERVICE_ORDERS) or the activity name already exists. */ + 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; @@ -5493,6 +5823,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; @@ -5560,6 +5914,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..1822711 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,64 @@ 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, + projects: [], + 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 85d57a5..4bdf829 100644 --- a/apps/web/src/api/terminal-device.ts +++ b/apps/web/src/api/terminal-device.ts @@ -4,6 +4,7 @@ import { type TerminalBookingAction, type TerminalPauseAction, } from './client'; +import type { components } from './generated'; const baseUrl = import.meta.env.VITE_API_BASE_URL ?? ''; @@ -47,14 +48,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'; @@ -203,3 +203,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 668399e..6e6cf10 100644 --- a/apps/web/src/app/i18n.tsx +++ b/apps/web/src/app/i18n.tsx @@ -413,6 +413,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', @@ -544,6 +552,33 @@ const de: Catalog = { 'projects.overbooked': 'Überbucht', 'projects.serviceOrders': 'Service-Aufträge', 'projects.noServiceOrders': 'Keine Service-Aufträge.', + 'projects.serviceOrderBlockedByActivities': + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + 'projects.activityBlockedByServiceOrders': + 'Neue Tätigkeiten sind erst möglich, wenn alle Service-Aufträge gelöscht sind.', + '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.', @@ -633,6 +668,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': @@ -1193,6 +1231,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', @@ -1324,6 +1368,31 @@ const en: Catalog = { 'projects.overbooked': 'Overbooked', 'projects.serviceOrders': 'Service orders', 'projects.noServiceOrders': 'No service orders.', + 'projects.serviceOrderBlockedByActivities': + 'To add a service order, delete all activities for this project first.', + 'projects.activityBlockedByServiceOrders': + 'To add an activity, delete all service orders for this project first.', + '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.', @@ -1413,6 +1482,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/solo-errors.ts b/apps/web/src/app/solo-errors.ts index 937efc7..efd50fb 100644 --- a/apps/web/src/app/solo-errors.ts +++ b/apps/web/src/app/solo-errors.ts @@ -62,6 +62,7 @@ const messageKeys: Record = { 'Email is already in use': 'solo.error.emailUsed', }; const codeKeys: Record = { + PROJECT_HAS_ACTIVITIES: 'projects.serviceOrderBlockedByActivities', DAILY_BLOCK_TIME_ENTRY_CONFLICT: 'solo.error.dailyBlockTimeConflict', DAILY_BLOCK_ABSENCE_CONFLICT: 'solo.error.dayOverlap', DAILY_BLOCK_DISABLED: 'solo.error.dailyBlockDisabled', diff --git a/apps/web/src/app/terminal-pin-i18n.ts b/apps/web/src/app/terminal-pin-i18n.ts index 71e3dfa..f5cc7c5 100644 --- a/apps/web/src/app/terminal-pin-i18n.ts +++ b/apps/web/src/app/terminal-pin-i18n.ts @@ -34,6 +34,30 @@ export const terminalPinDe = { 'terminalPin.confirmHint': 'Eine Anmeldung allein bucht keine Zeit.', 'terminalPin.clockIn': 'Jetzt einstempeln', 'terminalPin.clockOut': 'Jetzt ausstempeln', + 'terminalPin.chooseProject': 'Projekt auswählen', + 'terminalPin.backToProjects': 'Zurück zur Projektauswahl', + 'terminalPin.projectUnavailable.SERVICE_ORDERS': 'Service-Aufträge vorhanden', + 'terminalPin.projectUnavailable.NO_ACTIVE_ACTIVITIES': + 'Keine aktiven Tätigkeiten', + 'terminalPin.projectUnavailable.ARCHIVED_CUSTOMER': 'Kunde archiviert', + 'terminalPin.activityChanged': + 'Die Tätigkeit ist nicht mehr verfügbar. Wählen Sie erneut oder stempeln Sie direkt.', + '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', @@ -123,6 +147,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', @@ -172,6 +198,29 @@ 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.chooseProject': 'Choose project', + 'terminalPin.backToProjects': 'Back to projects', + 'terminalPin.projectUnavailable.SERVICE_ORDERS': 'Service orders exist', + 'terminalPin.projectUnavailable.NO_ACTIVE_ACTIVITIES': 'No active activities', + 'terminalPin.projectUnavailable.ARCHIVED_CUSTOMER': 'Customer archived', + 'terminalPin.activityChanged': + 'This activity is no longer available. Choose again or use the direct clock action.', + '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', @@ -259,6 +308,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..2a52680 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), }, })); @@ -70,6 +84,7 @@ const PROJECTS = [ bookedMinutes: 10 * 60, }, ], + activityCount: 0, assignedEmployeeCount: 1, updatedAt: new Date().toISOString(), }, @@ -82,6 +97,7 @@ const PROJECTS = [ planHours: null, bookedMinutes: 0, serviceOrders: [], + activityCount: 0, assignedEmployeeCount: 0, updatedAt: new Date().toISOString(), }, @@ -100,36 +116,81 @@ 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'; - projectsMock.mockClear().mockResolvedValue(PROJECTS); + projectsMock.mockReset().mockResolvedValue(PROJECTS); employeeDirectoryMock.mockClear().mockResolvedValue(EMPLOYEES); projectAssignmentsMock .mockClear() .mockResolvedValue([{ employeeId: 'e-1', projectId: 'p-1' }]); createProjectMock.mockClear().mockResolvedValue(PROJECTS[0]); + createServiceOrderMock.mockReset().mockResolvedValue(undefined); + deleteServiceOrderMock.mockReset().mockResolvedValue(undefined); + 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 +199,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 +317,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 +325,390 @@ 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('blocks new activities for an inactive service order and unlocks after removal', async () => { + const project = PROJECTS[0]; + const inactiveOrder = { ...project.serviceOrders[0], isActive: false }; + projectsMock + .mockResolvedValueOnce([{ ...project, serviceOrders: [inactiveOrder] }]) + .mockResolvedValue([{ ...project, serviceOrders: [] }]); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + + const { dialog } = await openCatalog(); + const add = await dialog.findByRole('button', { + name: 'Tätigkeit hinzufügen', + }); + expect(add).toHaveProperty('disabled', true); + expect( + dialog.getByText( + 'Neue Tätigkeiten sind erst möglich, wenn alle Service-Aufträge gelöscht sind.', + ), + ).toBeDefined(); + fireEvent.click(add); + expect(createActivityMock).not.toHaveBeenCalled(); + fireEvent.click(dialog.getByRole('button', { name: 'Schließen' })); + + const order = screen.getByText('Konzeption').closest('li'); + if (!order) throw new Error('Expected the existing service-order row'); + fireEvent.click(within(order).getByRole('button', { name: 'Löschen' })); + await waitFor(() => expect(screen.queryByText('Konzeption')).toBeNull()); + expect(deleteServiceOrderMock).toHaveBeenCalledWith('p-1', 'so-1'); + + const reopened = (await openCatalog()).dialog; + fireEvent.change(await reopened.findByLabelText('Name der Tätigkeit'), { + target: { value: 'Planen' }, + }); + expect( + reopened.getByRole('button', { name: 'Tätigkeit hinzufügen' }), + ).toHaveProperty('disabled', false); + }); + + it('blocks new service orders for an inactive activity and unlocks after removal', async () => { + const project = PROJECTS[0]; + projectsMock + .mockResolvedValueOnce([{ ...project, activityCount: 1 }]) + .mockResolvedValue([{ ...project, activityCount: 0 }]); + projectActivitiesMock.mockResolvedValueOnce([UNUSED]).mockResolvedValue([]); + vi.spyOn(window, 'confirm').mockReturnValue(true); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + + const add = await screen.findByRole('button', { name: 'Hinzufügen' }); + expect(add).toHaveProperty('disabled', true); + expect( + screen.getByText( + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + ), + ).toBeDefined(); + fireEvent.click(add); + expect(createServiceOrderMock).not.toHaveBeenCalled(); + const order = screen.getByText('Konzeption').closest('li'); + if (!order) throw new Error('Expected the existing service-order row'); + expect( + within(order).getByRole('button', { name: 'Bearbeiten' }), + ).toHaveProperty('disabled', false); + + const { dialog } = await openCatalog(); + fireEvent.click( + await dialog.findByRole('button', { name: 'Packen löschen' }), + ); + await dialog.findByText('Tätigkeit gelöscht.'); + expect(deleteActivityMock).toHaveBeenCalledWith('p-1', 'a-2'); + fireEvent.click(dialog.getByRole('button', { name: 'Schließen' })); + + await waitFor(() => + expect( + screen.queryByText( + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + ), + ).toBeNull(), + ); + fireEvent.change(screen.getByLabelText('Auftragsnr.'), { + target: { value: 'SA-002' }, + }); + fireEvent.change(screen.getByLabelText('Titel'), { + target: { value: 'Umsetzung' }, + }); + expect(add).toHaveProperty('disabled', false); + }); + + it('refreshes service orders after a stale activity creation conflict', async () => { + const project = PROJECTS[0]; + projectsMock + .mockResolvedValueOnce([{ ...project, serviceOrders: [] }]) + .mockResolvedValue([project]); + createActivityMock.mockRejectedValue( + new ApiError(409, 'Order conflict', 'PROJECT_HAS_SERVICE_ORDERS'), + ); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + + const { dialog } = await openCatalog(); + const input = await dialog.findByLabelText('Name der Tätigkeit'); + fireEvent.change(input, { target: { value: 'Planen' } }); + const add = dialog.getByRole('button', { name: 'Tätigkeit hinzufügen' }); + fireEvent.click(add); + await dialog.findByText( + 'Neue Tätigkeiten sind erst möglich, wenn alle Service-Aufträge gelöscht sind.', + ); + expect(add).toHaveProperty('disabled', true); + expect(input).toHaveProperty('value', 'Planen'); + expect(projectsMock).toHaveBeenCalledTimes(2); + }); + + it('refreshes the activity count after a stale order creation conflict', async () => { + const project = PROJECTS[1]; + projectsMock + .mockResolvedValueOnce([project]) + .mockResolvedValue([{ ...project, activityCount: 1 }]); + createServiceOrderMock.mockRejectedValue( + new ApiError(409, 'Activity conflict', 'PROJECT_HAS_ACTIVITIES'), + ); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + + const orderNo = await screen.findByLabelText('Auftragsnr.'); + fireEvent.change(orderNo, { target: { value: 'SA-001' } }); + fireEvent.change(screen.getByLabelText('Titel'), { + target: { value: 'Umsetzung' }, + }); + const add = screen.getByRole('button', { name: 'Hinzufügen' }); + fireEvent.click(add); + await screen.findByText( + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + ); + expect(add).toHaveProperty('disabled', true); + expect(orderNo).toHaveProperty('value', 'SA-001'); + expect(projectsMock).toHaveBeenCalledTimes(2); + }); + + it('creates a trimmed activity through the form and refreshes the list', async () => { + const created = { + ...UNUSED, + projectId: 'p-2', + name: 'Pflügen', + isActive: true, + }; + projectActivitiesMock + .mockResolvedValueOnce([]) + .mockResolvedValue([created]); + createActivityMock.mockResolvedValue(created); + const { AdminProjectsPage } = await import('./AdminProjectsPage'); + renderWithProviders(); + const { dialog } = await openCatalog('PRJ-002'); + 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-2', { 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('PRJ-002'); + 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..fc7aa81 100644 --- a/apps/web/src/routes/AdminProjectsPage.tsx +++ b/apps/web/src/routes/AdminProjectsPage.tsx @@ -17,6 +17,7 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { api, + ApiError, type EmployeeDirectoryDto, type ProjectAssignmentDto, type ProjectDto, @@ -25,6 +26,7 @@ import { } from '../api/client'; import { useCurrentUser } from '../app/auth'; import { useI18n } from '../app/i18n'; +import { ProjectActivityCatalog } from './ProjectActivityCatalog'; interface ProjectDraft { code: string; @@ -217,7 +219,7 @@ interface ProjectCardProps { project: ProjectDto; onEdit: () => void; onReport: () => void; - onChanged: () => void; + onChanged: () => Promise; } function ProjectCard({ @@ -270,7 +272,8 @@ function ProjectCard({ )} -
+
+ @@ -300,11 +303,13 @@ function ServiceOrderList({ onChanged, }: { project: ProjectDto; - onChanged: () => void; + onChanged: () => Promise; }) { const { t } = useI18n(); const [draft, setDraft] = useState({ orderNo: '', title: '', planHours: '' }); - const [error, setError] = useState(null); + const createBlocked = project.activityCount > 0; + const createBlockedMessage = t('projects.serviceOrderBlockedByActivities'); + const blockingHintId = 'so-create-blocked-' + project.id; const create = useMutation({ mutationFn: () => @@ -315,12 +320,16 @@ function ServiceOrderList({ }), onSuccess: () => { setDraft({ orderNo: '', title: '', planHours: '' }); - setError(null); - onChanged(); + return onChanged(); + }, + onError: async (error) => { + if (error instanceof ApiError && error.code === 'PROJECT_HAS_ACTIVITIES') + await onChanged(); }, - onError: (e) => - setError(e instanceof Error ? e.message : t('projects.createFailed')), }); + const blockedConflict = + create.error instanceof ApiError && + create.error.code === 'PROJECT_HAS_ACTIVITIES'; return (
@@ -343,7 +352,16 @@ function ServiceOrderList({ ))} )} -
+ {createBlocked && ( +

+ {createBlockedMessage} +

+ )} +
- {error && ( +
+ {create.isError && !(blockedConflict && createBlocked) && ( - {error} + + {blockedConflict + ? createBlockedMessage + : create.error instanceof Error + ? create.error.message + : t('projects.createFailed')} + )}
@@ -408,7 +435,7 @@ function ServiceOrderRow({ }: { projectId: string; order: ServiceOrderDto; - onChanged: () => void; + onChanged: () => Promise; }) { const { t } = useI18n(); const [editing, setEditing] = useState(false); diff --git a/apps/web/src/routes/AdminTerminalsPage.spec.tsx b/apps/web/src/routes/AdminTerminalsPage.spec.tsx index 2460e4d..2a36d70 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' }, }); @@ -76,6 +83,7 @@ describe('AdminTerminalsPage', () => { expect(createTerminalMock).toHaveBeenCalledWith( expect.objectContaining({ isActive: true, + activitySelectionEnabled: false, enforceGeofence: false, latitude: null, longitude: null, @@ -88,6 +96,79 @@ describe('AdminTerminalsPage', () => { expect(dismissTerminalSupportPromptMock).not.toHaveBeenCalled(); }); + 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( @@ -130,6 +211,7 @@ describe('AdminTerminalsPage', () => { locationLabel: 'Würzburg', logoUrl: null, timeZone: 'Europe/Berlin', + activitySelectionEnabled: false, enforceGeofence: false, latitude: null, longitude: null, @@ -169,6 +251,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 66887ee..26a57ea 100644 --- a/apps/web/src/routes/AdminTerminalsPage.tsx +++ b/apps/web/src/routes/AdminTerminalsPage.tsx @@ -391,30 +391,49 @@ export function AdminTerminalsPage() { ); } -function TerminalEditor({ - terminal, - onClose, - onSaved, -}: { - terminal: TerminalDto | null; - onClose: () => void; - onSaved: () => 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: () => Promise; +}) { + const { t } = useI18n(); + const [draft, setDraft] = useState(() => initialTerminalDraft(terminal)); const [error, setError] = useState(null); const [locating, setLocating] = useState(false); const timeZoneOptions = getTimeZoneOptions([draft.timeZone]); @@ -423,18 +442,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: onSaved, onError: (saveError) => @@ -600,6 +628,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 d802733..2684ad8 100644 --- a/apps/web/src/routes/BookingPage.spec.tsx +++ b/apps/web/src/routes/BookingPage.spec.tsx @@ -1,6 +1,6 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; -import { ApiError } from '../api/client'; +import { afterEach, describe, expect, it, vi, beforeEach } from 'vitest'; +import { fireEvent, screen, waitFor, within } from '@testing-library/react'; +import { ApiError, type EmployeeRole } from '../api/client'; import { renderWithProviders } from '../test-utils'; const employeeMock = vi.fn(); @@ -12,6 +12,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(); @@ -30,6 +31,8 @@ vi.mock('../api/client', async (importOriginal) => ({ 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), @@ -37,13 +40,14 @@ vi.mock('../api/client', async (importOriginal) => ({ }, })); +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, @@ -77,6 +81,8 @@ function entryFixture(overrides: Record = {}) { serviceOrderNo: null, serviceOrderTitle: null, activity: null, + activityId: null, + catalogActivityName: null, summary: { grossMinutes: 480, breakMinutes: 30, netMinutes: 450 }, ...overrides, }; @@ -97,6 +103,7 @@ const PROJECTS = [ describe('BookingPage', () => { beforeEach(() => { + currentRole = 'Employee'; employeeMock.mockReset().mockResolvedValue({ allowWebTimeBooking: true }); timeEntriesMock.mockClear().mockResolvedValue([]); timeEntryApprovalsMock.mockClear().mockResolvedValue([]); @@ -118,13 +125,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([ { @@ -277,6 +287,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') @@ -293,6 +305,7 @@ describe('BookingPage', () => { }), ); }); + expect(clockInMock.mock.calls[0][0]).not.toHaveProperty('activityId'); }); it('disables "Kommen" until the mandatory service order is chosen', async () => { @@ -515,6 +528,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 2a76851..c926873 100644 --- a/apps/web/src/routes/BookingPage.tsx +++ b/apps/web/src/routes/BookingPage.tsx @@ -29,6 +29,7 @@ import { type DailyBlockOptionDto, type EmployeeDto, type TimeEntryDto, + type UpdateTimeEntryPayload, } from '../api/client'; import { useCurrentUser } from '../app/auth'; import { useOnline } from '../app/use-online'; @@ -163,17 +164,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 (
@@ -191,6 +202,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} @@ -962,7 +1079,7 @@ function EntryEditDialog({ {t('common.cancel')} + ); + return (
{t('terminalPin.confirmHint')}

- - {identity.pauseAction && ( + {bookingButton} + {pauseAction && ( )} + {activityOptions?.state === 'loading' && ( +

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

+ )} + {activityOptions?.state === 'failed' && ( +

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

+ )} + {activityOptions?.state === 'ready' && ( + + updateActivityOptions((previous) => ({ + ...previous, + selection: + project && !project.unavailableReason + ? openActivityProject( + project, + previous.rememberedActivityId, + ) + : null, + })) + } + onChoose={(activityId) => + updateActivityOptions((previous) => + previous.selection + ? { + ...previous, + selection: { + ...previous.selection, + activityId, + chosen: true, + }, + } + : previous, + ) + } + /> + )} + {selection?.chosen && selectedActivityId && ( +
+ +

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

+
+ )}
) : phase === 'uncertain' ? (
@@ -471,10 +767,7 @@ export function KioskPinPanel({ @@ -483,18 +776,22 @@ export function KioskPinPanel({

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

-

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

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

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

+ )}
) : (

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

)} @@ -520,3 +819,123 @@ export function KioskPinPanel({
); } + +function KioskActivityPicker({ + options, + clockIn, + onOpenProject, + onChoose, +}: { + options: Extract; + clockIn: boolean; + onOpenProject: (project: ActivityProject | null) => void; + onChoose: (id: string | null) => void; +}) { + const { t } = useI18n(); + const { projects, selection } = options; + const showProjects = projects.length > 0 && !selection; + const selectedActivityId = selection?.activityId ?? null; + const label = t( + showProjects + ? 'terminalPin.chooseProject' + : 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'; + const listClass = 'max-h-56 space-y-2 overflow-y-auto p-1'; + return ( +
+ {selection && ( + + )} +

{label}

+ {showProjects && ( +
+ {projects.map((project) => { + const reason = project.unavailableReason; + const reasonId = 'kiosk-project-reason-' + project.id; + return ( + + ); + })} +
+ )} + {selection && ( +

+ {selection.project.code} · {selection.project.name} +

+ )} + {selection && ( +
+ {selection.project.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..3dff865 --- /dev/null +++ b/apps/web/src/routes/ProjectActivityCatalog.tsx @@ -0,0 +1,355 @@ +import { useEffect, 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')} + + + 0} + /> + + + + + + + + ); +} + +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, + createBlocked, +}: { + projectId: string; + createBlocked: boolean; +}) { + const { t } = useI18n(); + const queryClient = useQueryClient(); + const queryKey = ['projects', projectId, 'activities'] as const; + const refresh = (includeCounts: boolean) => + includeCounts + ? queryClient.invalidateQueries({ queryKey: ['projects'] }) + : 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); + + useEffect(() => { + if (editingId) nameInput.current?.focus(); + }, [editingId]); + + 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(action.kind === 'create' || action.kind === 'delete'); + if (action.kind === 'delete') nameInput.current?.focus(); + }, + onError: async (error) => { + if ( + error instanceof ApiError && + (error.status === 409 || error.status === 404) + ) { + // Another manager or a new time entry may have changed the catalog. + await refresh(error.code === 'PROJECT_HAS_SERVICE_ORDERS'); + } + }, + }); + + const isDelete = change.variables?.kind === 'delete'; + const isConflict = + change.error instanceof ApiError && change.error.status === 409; + const blockedConflict = + change.error instanceof ApiError && + change.error.code === 'PROJECT_HAS_SERVICE_ORDERS'; + const errorKey = blockedConflict + ? 'projects.activityBlockedByServiceOrders' + : isConflict + ? isDelete + ? 'projects.activityDeleteConflict' + : 'projects.activityDuplicate' + : isDelete + ? 'common.deleteFailed' + : 'common.saveFailed'; + const name = draft.trim(); + const editorBlocked = createBlocked && !editingId; + const blockingHintId = nameId + '-blocked'; + + return ( + <> + {catalog.isPending &&

{t('common.loading')}

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

{t('projects.activitiesLoadFailed')}

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

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

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

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

+ )} + {createBlocked && ( +

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

+ )} + {catalog.data && ( + <> +
{ + event.preventDefault(); + if (!name || change.isPending || editorBlocked) 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/apps/web/src/routes/solo/SoloPages.spec.tsx b/apps/web/src/routes/solo/SoloPages.spec.tsx index dda9ea0..4b3e925 100644 --- a/apps/web/src/routes/solo/SoloPages.spec.tsx +++ b/apps/web/src/routes/solo/SoloPages.spec.tsx @@ -683,6 +683,36 @@ describe('Solo work flows', () => { await waitFor(() => expect(remove).toHaveBeenCalledWith('customer-1')); }); + it('keeps new service orders disabled when a Solo project already has an activity', async () => { + vi.mocked(soloApi.projects).mockResolvedValue([ + { + id: 'project-1', + code: 'PROJ', + name: 'Example project', + description: null, + isActive: true, + planHours: null, + customerId: null, + customerName: null, + defaultBillable: false, + bookedMinutes: 0, + activityCount: 1, + assignedEmployeeCount: 1, + updatedAt: '2026-09-08T08:00:00Z', + serviceOrders: [], + }, + ]); + renderWithProviders(); + const add = await screen.findByRole('button', { + name: 'Auftrag anlegen', + description: + 'Neue Service-Aufträge sind erst möglich, wenn alle Tätigkeiten gelöscht sind.', + }); + expect(add).toHaveProperty('disabled', true); + fireEvent.click(add); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + it.each(['project', 'order'] as const)( 'confirms the exact unused %s before deletion', async (kind) => { @@ -698,6 +728,7 @@ describe('Solo work flows', () => { customerName: null, defaultBillable: false, bookedMinutes: 0, + activityCount: 0, assignedEmployeeCount: 1, updatedAt: '2026-09-08T08:00:00Z', serviceOrders: [ diff --git a/apps/web/src/routes/solo/SoloProjectsPage.tsx b/apps/web/src/routes/solo/SoloProjectsPage.tsx index 2171747..2651a31 100644 --- a/apps/web/src/routes/solo/SoloProjectsPage.tsx +++ b/apps/web/src/routes/solo/SoloProjectsPage.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { useQuery } from '@tanstack/react-query'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import { Link } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Card, CardContent } from '@/components/ui/card'; @@ -11,7 +11,7 @@ import { DialogHeader, DialogTitle, } from '@/components/ui/dialog'; -import { api } from '../../api/client'; +import { api, ApiError } from '../../api/client'; import { soloApi, type SoloProject, @@ -164,6 +164,12 @@ export function SoloProjectsPage() { )}
+ {project.activityCount > 0 && ( +

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

+ )} {project.serviceOrders.length > 0 && (

{t('solo.orders')}

@@ -261,7 +275,14 @@ export function SoloProjectsPage() { /> )} {orderEdit && ( - setOrderEdit(null)} /> + id === orderEdit.project.id) ?? + orderEdit.project + } + order={orderEdit.order} + close={() => setOrderEdit(null)} + /> )} {deleting && ( 0; const [orderNo, setOrderNo] = useState(order?.orderNo ?? ''); const [title, setTitle] = useState(order?.title ?? ''); const [plan, setPlan] = useState(order?.planHours?.toString() ?? ''); @@ -433,20 +456,35 @@ function OrderEditor({ className="space-y-4" onSubmit={(event) => { event.preventDefault(); - void action.run( - () => - soloApi.saveOrder(project.id, order?.id ?? null, { + if (createBlocked) return; + void action.run(async () => { + try { + return await soloApi.saveOrder(project.id, order?.id ?? null, { orderNo: orderNo.trim(), title: title.trim(), planHours: plan === '' ? null : Number(plan), isActive: order?.isActive ?? true, defaultBillable: billable === '' ? null : billable === 'true', - }), - close, - ); + }); + } catch (error) { + if ( + error instanceof ApiError && + error.code === 'PROJECT_HAS_ACTIVITIES' + ) + await queryClient.invalidateQueries({ + queryKey: ['solo-projects'], + }); + throw error; + } + }, close); }} > + {createBlocked && !action.error && ( +

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

+ )} {t('common.cancel')} -
diff --git a/apps/web/src/routes/solo/SoloTimesPage.tsx b/apps/web/src/routes/solo/SoloTimesPage.tsx index a1c1083..a262fea 100644 --- a/apps/web/src/routes/solo/SoloTimesPage.tsx +++ b/apps/web/src/routes/solo/SoloTimesPage.tsx @@ -594,6 +594,7 @@ function EntryDialog({ isActive: false, planHours: null, bookedMinutes: 0, + activityCount: 0, assignedEmployeeCount: 1, updatedAt: '', customerId: null, diff --git a/docs/LOCAL_PIN_DOCKER_TEST.de.md b/docs/LOCAL_PIN_DOCKER_TEST.de.md index 26cc770..590f7f6 100644 --- a/docs/LOCAL_PIN_DOCKER_TEST.de.md +++ b/docs/LOCAL_PIN_DOCKER_TEST.de.md @@ -1,10 +1,8 @@ -# OpenClockwork 2.2.1 mit PIN lokal im Docker testen +# OpenClockwork mit PIN lokal im Docker testen -Version 2.2.1 enthält weiterhin die in 2.1.0 eingeführte QR/PIN-Implementierung -von Inkrement A. API und Web -verwenden die zusammen gebauten Images `openclockwork-api:2.2.1-pin-local` und -`openclockwork-web:2.2.1-pin-local`. Nach dem Neubau muss die API unter -`/api/health` Version `2.2.1` melden. +Docker Compose baut API und Web aus demselben Checkout. Die Image-Tags stehen +in `docker-compose.pin-test.yml`. Nach dem Neubau muss die API unter +`/api/health` die Version aus `package.json` des gebauten Checkouts melden. Die lokale PIN-Abnahme und die Release-Freigabe für 2.1.0 wurden am 11.10.2026 vom Nutzer bestätigt. Damit ist keine zusätzliche Zielgeräte-/OS- @@ -35,7 +33,8 @@ docker compose -p openclockwork-pin-test -f docker-compose.pin-test.yml run --rm HR: `hannah.roth@openclockwork.test`, Passwort `openclockwork`. Die Mitarbeiterliste enthält weitere synthetische Konten und Personalnummern. HR konfiguriert QR/PIN und vergibt einen PIN; er wird bei jeder Vergabe zufällig -erzeugt und einmal angezeigt. Unter `/kiosk/pair` mit dem HR-Pairing-Code koppeln. +erzeugt und einmal angezeigt. Die von HR erzeugte Kiosk-URL öffnen oder den +Kopplungscode unter `/kiosk` eingeben. Zum Desktoptest den Geofence bewusst ausschalten; für GPS/Tablet-Abnahme einen vertrauenswürdigen HTTPS-Ursprung mit passender CORS-Konfiguration verwenden. @@ -48,6 +47,34 @@ bleiben aktiv: Mitarbeiter sehen eigene Personaldaten, Manager ihr direktes Team und HR alle Mitarbeiter; PIN-Verwaltung bleibt HR vorbehalten. Details zu Grenzen und Betrieb: [QR/PIN-Betriebsanleitung](TERMINAL_AUTH_OPERATIONS.de.md). +## Projekt und Tätigkeit am PIN-Terminal + +1. In der Projektverwaltung zwei aktive Projekte mit je einer aktiven + Tätigkeit anlegen und beide demselben synthetischen Mitarbeiter über die + Zuweisungsmatrix zuordnen. Damit ein Projekt am Kiosk buchbar ist, braucht es + mindestens eine aktive Tätigkeit, einen aktiven oder keinen Kunden und eine + leere Auftragsliste. Unter **Projekte** lassen sich für ein Projekt + entweder Service-Aufträge oder Tätigkeiten anlegen. Deaktivierte Einträge + zählen mit. Bei älteren gemischten Projekten sind Neuanlagen in beiden + Katalogen gesperrt. Bestehende Einträge bleiben verwaltbar. +2. In der Terminalverwaltung **Tätigkeitsauswahl am Terminal erlauben** + aktivieren. Nach der Anmeldung per PIN erscheint zuerst die Liste der + zugewiesenen aktiven Projekte mit Name und Code. Das gilt auch bei einem + einzigen buchbaren Projekt. Projekte mit Service-Aufträgen, ohne + aktive Tätigkeit oder mit archiviertem Kunden erscheinen ausgegraut und + zeigen den Grund. Erst nach Wahl eines buchbaren Projekts erscheinen dessen + Tätigkeiten. **Zurück zur Projektauswahl** öffnet die Projektliste erneut. +3. Die Tätigkeit wählen und **Jetzt einstempeln** bestätigen. Für einen Wechsel + erneut per PIN anmelden, das zweite Projekt und dessen Tätigkeit wählen und + **Tätigkeit wechseln** bestätigen. **Jetzt ausstempeln** bleibt nach PIN + direkt erreichbar. **Ohne Tätigkeit** ist beim Einstempeln verfügbar. +4. In **Arbeitszeiten** den Mitarbeiter und Testtag auswählen. Das Ende des + ersten Abschnitts muss dem Beginn des zweiten entsprechen. In **Projekte** + für beide Projekte die **Auswertung** und **CSV herunterladen** prüfen. + Jeder Bericht enthält die Tätigkeit und den Abschnitt seines Projekts. + +## Audit-Export + Audit-Testadapter im separaten Exportvolume. Bei jeder Wiederholung frische Dateinamen für Export und Anker wählen: Die Werkzeuge überschreiben keine Dateien, und das Volume bleibt nach `down` erhalten. 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..3399af3 --- /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', 'pause-start', 'pause-end') 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', 'pause-start', 'pause-end') 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 da0a0f4..bc993dd 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -157,6 +157,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[] @@ -169,6 +171,7 @@ model Employee { @@index([role]) @@index([managerId]) @@index([workScheduleId]) + @@index([lastTerminalActivityId]) } // Frame and core working hours. A schedule is assigned per Employee @@ -268,6 +271,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()) @@ -279,6 +285,7 @@ model TimeEntry { @@index([status]) @@index([projectId]) @@index([serviceOrderId]) + @@index([activityId]) @@index([terminalId]) @@index([clockOutTerminalId]) @@index([clockInChallengeId]) @@ -295,6 +302,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) @@ -363,8 +371,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(16) createdAt DateTime @default(now()) @@ -490,6 +499,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()) @@ -499,6 +509,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