Files
ApiCore/ApiCore-Backend/test/follow-up-controls.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

216 lines
6.8 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 RuleBody {
id: string;
triggerType: string;
active: boolean;
}
/**
* Follow-up checks after a treatment or feeding: off by default (no built-in
* intervals), due relative to the measure itself, never duplicated.
*/
describe('Follow-up controls (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const suffix = `${Date.now()}-${Math.round(Math.random() * 1e6)}`;
let token: string;
let apiaryId: string;
const colonyIds: string[] = [];
const server = () => app.getHttpServer();
const auth = () => ({ Authorization: `Bearer ${token}` });
async function rule(triggerType: string): Promise<RuleBody> {
const response = await request(server())
.get('/api/v1/automation-rules')
.set(auth())
.expect(200);
const found = (response.body as RuleBody[]).find(
(r) => r.triggerType === triggerType,
);
if (!found) throw new Error(`rule ${triggerType} missing`);
return found;
}
async function newColony(code: string) {
const colony = await prisma.colony.create({
data: {
code: `${code}-${suffix}`,
apiaryId,
colonyType: 'PRODUCTION_COLONY',
},
});
colonyIds.push(colony.id);
return colony;
}
// The follow-up check comes from the TreatmentRecorded handler, not from
// the request: the helper drains the events of this treatment.
async function treat(colonyId: string, body: Record<string, unknown> = {}) {
const response = await request(server())
.post('/api/v1/treatments')
.set(auth())
.send({
colonyId,
date: '2026-08-01T00:00:00.000Z',
product: 'Testmittel',
...body,
})
.expect(201);
await drainDomainEvents(app, [(response.body as { id: string }).id]);
}
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
await prisma.user.create({
data: {
email: `followup-${suffix}@example.com`,
passwordHash: await bcrypt.hash('SuperSecret123!', 12),
name: 'Follow-up',
role: { connect: { key: 'ADMIN' } },
},
});
token = (
await login(app, `followup-${suffix}@example.com`, 'SuperSecret123!')
).accessToken;
apiaryId = (
await prisma.apiary.create({ data: { name: `Follow-up ${suffix}` } })
).id;
});
afterAll(async () => {
// Leave the shared rules as other suites expect them: off.
await prisma.automationRule.updateMany({
where: {
triggerType: { in: ['TREATMENT_FOLLOW_UP', 'FEEDING_FOLLOW_UP'] },
},
data: { active: false, config: {} },
});
// Follow-up tasks are written without a user: remove their audit entry
// and TaskCreated (deliveries go with the event, ON DELETE CASCADE).
const followUpTaskIds = (
await prisma.task.findMany({
where: { relatedId: { in: colonyIds } },
select: { id: true },
})
).map((task) => task.id);
await prisma.auditLog.deleteMany({
where: { entityType: 'Task', entityId: { in: followUpTaskIds } },
});
const measureIds = [
...(await prisma.treatment.findMany({
where: { colonyId: { in: colonyIds } },
select: { id: true },
})),
...(await prisma.feeding.findMany({
where: { colonyId: { in: colonyIds } },
select: { id: true },
})),
].map((measure) => measure.id);
await prisma.domainEvent.deleteMany({
where: { aggregateId: { in: measureIds } },
});
await prisma.auditLog.deleteMany({
where: { entityId: { in: measureIds } },
});
await prisma.domainEvent.deleteMany({
where: { aggregateType: 'Task', aggregateId: { in: followUpTaskIds } },
});
await app.close();
});
it('ships both follow-up rules switched off, without a built-in interval', async () => {
const treatmentRule = await rule('TREATMENT_FOLLOW_UP');
const feedingRule = await rule('FEEDING_FOLLOW_UP');
expect(treatmentRule.active).toBe(false);
expect(feedingRule.active).toBe(false);
const colony = await newColony('OFF');
await treat(colony.id);
expect(await prisma.task.count({ where: { relatedId: colony.id } })).toBe(
0,
);
});
it('suggests a check due the configured days after the treatment ended', async () => {
const treatmentRule = await rule('TREATMENT_FOLLOW_UP');
await request(server())
.patch(`/api/v1/automation-rules/${treatmentRule.id}`)
.set(auth())
.send({ active: true, config: { dueInDays: 14 } })
.expect(200);
const colony = await newColony('TREAT');
await treat(colony.id, {
startDate: '2026-08-01T00:00:00.000Z',
endDate: '2026-08-10T00:00:00.000Z',
});
const tasks = await prisma.task.findMany({
where: {
relatedId: colony.id,
sourceAutomationTrigger: 'TREATMENT_FOLLOW_UP',
},
});
expect(tasks).toHaveLength(1);
expect(tasks[0].dueDate?.toISOString()).toBe('2026-08-24T00:00:00.000Z');
expect(tasks[0].description).toContain('Testmittel');
expect(tasks[0].status).toBe('OPEN');
// A second treatment while the check is still open adds nothing.
await treat(colony.id, { date: '2026-08-12T00:00:00.000Z' });
expect(
await prisma.task.count({
where: {
relatedId: colony.id,
sourceAutomationTrigger: 'TREATMENT_FOLLOW_UP',
},
}),
).toBe(1);
});
it('suggests a check after a feeding, counted from the feeding date', async () => {
const feedingRule = await rule('FEEDING_FOLLOW_UP');
await request(server())
.patch(`/api/v1/automation-rules/${feedingRule.id}`)
.set(auth())
.send({ active: true, config: { dueInDays: 7 } })
.expect(200);
const colony = await newColony('FEED');
const response = await request(server())
.post('/api/v1/feedings')
.set(auth())
.send({
colonyId: colony.id,
date: '2026-09-01T00:00:00.000Z',
feedType: 'SUGAR_WATER',
amount: 5,
unit: 'l',
})
.expect(201);
// Not before the FeedingRecorded handler ran.
expect(await prisma.task.count({ where: { relatedId: colony.id } })).toBe(
0,
);
await drainDomainEvents(app, [(response.body as { id: string }).id]);
const task = await prisma.task.findFirstOrThrow({
where: {
relatedId: colony.id,
sourceAutomationTrigger: 'FEEDING_FOLLOW_UP',
},
});
expect(task.dueDate?.toISOString()).toBe('2026-09-08T00:00:00.000Z');
});
});