Files
ApiCore/ApiCore-Backend/test/tasks.e2e-spec.ts
T
Nick SzaunigandClaude Opus 5.5 cdd30cf3ee feat: platform backbone and field capture complete (checkpoint)
Platform backbone (plan 2026-10-13-plattform-rueckgrat), all tasks reviewed:
- webhooks with delivery table, retries and stable delivery id
- calendar handlers; a finished task removes its Outlook event
- tasks, automations, inspections, varroa, treatments, feedings,
  harvests, colonies, wintering, stock and bottling record domain events
  in the same transaction; legacy post-commit calls removed
- row locks through one helper (lockRowForUpdate, lockRowsForShare,
  lockRowsForUpdate)
- job framework with JobRun, cli exit codes, cleanup, task templates,
  daily evaluation, hourly app-backup and the rekey job
- system API and page "Verwaltung > System" with retry
- @nestjs/schedule removed, guard tests against in-process schedulers

Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), all tasks reviewed:
- inspection photo offline without metadata
- bulk capture for treatments, feedings and varroa (backend + frontend)
- offline stand mode with service worker, offline pages and packs
- offline session, cold start and logout on shared devices

Docs: ARCHITECTURE.md assumptions and sections updated, TASKS.md.
Gates: backend lint, typecheck, 1770 unit, 420 e2e, build, no schema
drift; frontend lint, typecheck, 913 tests, build. Not rolled out.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 11:36:38 +02:00

229 lines
7.2 KiB
TypeScript

import { INestApplication } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import request from 'supertest';
import { App } from 'supertest/types';
import { PrismaService } from '../src/prisma/prisma.service';
import { createTestApp } from './utils/create-test-app';
import { login } from './utils/api';
import { drainDomainEvents } from './utils/domain-events';
interface TaskBody {
id: string;
status: string;
completedAt: string | null;
dueDate: string | null;
}
describe('Tasks (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const staffEmail = `tasks-e2e-staff-${Date.now()}@example.com`;
const readonlyEmail = `tasks-e2e-readonly-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let staffId: string;
let readonlyId: string;
let staffToken: string;
let readonlyToken: string;
let taskId: string;
const taskIds: string[] = [];
const eventsOf = (id: string, type: string) =>
prisma.domainEvent.findMany({
where: { aggregateType: 'Task', aggregateId: id, type },
include: { deliveries: true },
});
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
const passwordHash = await bcrypt.hash(password, 12);
const staff = await prisma.user.create({
data: {
email: staffEmail,
passwordHash,
name: 'Staff',
role: { connect: { key: 'STAFF' } },
},
});
staffId = staff.id;
const readonly = await prisma.user.create({
data: {
email: readonlyEmail,
passwordHash,
name: 'Readonly',
role: { connect: { key: 'READONLY' } },
},
});
readonlyId = readonly.id;
staffToken = (await login(app, staffEmail, password)).accessToken;
readonlyToken = (await login(app, readonlyEmail, password)).accessToken;
});
afterAll(async () => {
// Deliveries go with their event (ON DELETE CASCADE).
await prisma.domainEvent.deleteMany({
where: { aggregateType: 'Task', aggregateId: { in: taskIds } },
});
await prisma.task.deleteMany({ where: { id: { in: taskIds } } });
await prisma.refreshToken.deleteMany({
where: { userId: { in: [staffId, readonlyId] } },
});
await prisma.auditLog.deleteMany({
where: { userId: { in: [staffId, readonlyId] } },
});
await prisma.user.deleteMany({
where: { id: { in: [staffId, readonlyId] } },
});
await app.close();
});
it('rejects create for a READONLY user', () => {
return request(app.getHttpServer())
.post('/api/v1/tasks')
.set('Authorization', `Bearer ${readonlyToken}`)
.send({ title: 'Beute prüfen' })
.expect(403);
});
it('lets a STAFF user create a task', async () => {
const response = await request(app.getHttpServer())
.post('/api/v1/tasks')
.set('Authorization', `Bearer ${staffToken}`)
.send({ title: 'Beute prüfen', priority: 'HIGH' })
.expect(201);
const task = response.body as TaskBody;
taskId = task.id;
taskIds.push(taskId);
expect(task.status).toBe('OPEN');
});
it('POST /tasks leaves a TaskCreated event whose calendar and webhook deliveries are DONE after draining', async () => {
const response = await request(app.getHttpServer())
.post('/api/v1/tasks')
.set('Authorization', `Bearer ${staffToken}`)
.send({ title: 'Mit Termin', dueDate: '2027-05-01T00:00:00.000Z' })
.expect(201);
const id = (response.body as TaskBody).id;
taskIds.push(id);
// Recorded in the request's transaction, next to the audit entry.
const [recorded] = await eventsOf(id, 'TaskCreated');
expect(recorded).toMatchObject({
status: 'PENDING',
actorUserId: staffId,
payload: {
relatedType: 'GENERAL',
relatedId: null,
dueDate: '2027-05-01',
},
});
await expect(
prisma.auditLog.count({
where: {
entityType: 'Task',
entityId: id,
action: 'CREATE',
userId: staffId,
},
}),
).resolves.toBe(1);
await drainDomainEvents(app, [id]);
const [drained, ...more] = await eventsOf(id, 'TaskCreated');
expect(more).toHaveLength(0);
expect(drained.status).toBe('DONE');
expect(drained.deliveries).toEqual(
expect.arrayContaining([
expect.objectContaining({
handler: 'calendar-sync.task',
status: 'DONE',
}),
expect.objectContaining({
handler: 'webhooks.forward',
status: 'DONE',
}),
]),
);
expect(drained.deliveries.every((entry) => entry.status === 'DONE')).toBe(
true,
);
});
it('lists tasks filtered by status', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/tasks?status=OPEN')
.set('Authorization', `Bearer ${readonlyToken}`)
.expect(200);
const tasks = response.body as TaskBody[];
expect(tasks.some((entry) => entry.id === taskId)).toBe(true);
});
it('clears the due date on null and audits the edit', async () => {
await request(app.getHttpServer())
.patch(`/api/v1/tasks/${taskId}`)
.set('Authorization', `Bearer ${staffToken}`)
.send({ dueDate: '2026-08-01T00:00:00.000Z' })
.expect(200);
const response = await request(app.getHttpServer())
.patch(`/api/v1/tasks/${taskId}`)
.set('Authorization', `Bearer ${staffToken}`)
.send({ dueDate: null })
.expect(200);
expect((response.body as TaskBody).dueDate).toBeNull();
const auditEntry = await prisma.auditLog.findFirst({
where: {
entityType: 'Task',
entityId: taskId,
action: 'UPDATE',
userId: staffId,
},
orderBy: { timestamp: 'desc' },
});
expect(auditEntry?.afterData).toEqual(
expect.objectContaining({ dueDate: null }),
);
const updates = await eventsOf(taskId, 'TaskUpdated');
expect(updates.map((event) => event.payload)).toEqual(
expect.arrayContaining([
{ status: 'OPEN', dueDate: '2026-08-01' },
{ status: 'OPEN', dueDate: null },
]),
);
expect(updates).toHaveLength(2);
});
it('rejects null for the required title', () => {
return request(app.getHttpServer())
.patch(`/api/v1/tasks/${taskId}`)
.set('Authorization', `Bearer ${staffToken}`)
.send({ title: null })
.expect(400);
});
it('completes a task and records TaskCompleted once, also when completed again', async () => {
const response = await request(app.getHttpServer())
.post(`/api/v1/tasks/${taskId}/complete`)
.set('Authorization', `Bearer ${staffToken}`)
.expect(201);
const task = response.body as TaskBody;
expect(task.status).toBe('DONE');
expect(task.completedAt).not.toBeNull();
const repeated = await request(app.getHttpServer())
.post(`/api/v1/tasks/${taskId}/complete`)
.set('Authorization', `Bearer ${staffToken}`)
.expect(201);
expect((repeated.body as TaskBody).completedAt).toBe(task.completedAt);
const completions = await eventsOf(taskId, 'TaskCompleted');
expect(completions).toHaveLength(1);
expect(completions[0]).toMatchObject({
actorUserId: staffId,
payload: { relatedType: 'GENERAL', relatedId: null },
});
});
});