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]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-10-14 11:36:38 +02:00
1 parent c01a38835a
commit cdd30cf3ee
288 files changed
+39165 -2853

No files matched your search

+177 -77
View File
@@ -6,6 +6,7 @@ import { PrismaService } from '../src/prisma/prisma.service';
import { AutomationTriggerType, Prisma } from '../generated/prisma';
import { createTestApp } from './utils/create-test-app';
import { login } from './utils/api';
import { drainDomainEvents } from './utils/domain-events';
interface AutomationRuleBody {
id: string;
@@ -28,6 +29,25 @@ describe('Automation rules (e2e)', () => {
let apiaryId: string;
let colonyId: string;
let varroaRuleId: string;
let swarmRuleId: string;
/**
* Records an inspection or varroa measurement and runs the handlers of
* its event - the rules evaluate there, not in the request.
*/
async function record(path: string, body: object): Promise<string> {
const response = await request(app.getHttpServer())
.post(`/api/v1/${path}`)
.set(
'Authorization',
`Bearer ${path === 'inspections' ? staffToken : adminToken}`,
)
.send({ colonyId, date: new Date().toISOString(), ...body })
.expect(201);
const id = (response.body as { id: string }).id;
await drainDomainEvents(app, [id]);
return id;
}
beforeAll(async () => {
app = await createTestApp();
@@ -70,13 +90,41 @@ describe('Automation rules (e2e)', () => {
});
afterAll(async () => {
await prisma.automationRule.updateMany({
where: { triggerType: 'VARROA_THRESHOLD' },
data: { active: true },
// Rule tasks and the rules' own entries are written without a user -
// they are not covered by the userId cleanup below. Deliveries go with
// their event (ON DELETE CASCADE).
const ruleTaskIds = (
await prisma.task.findMany({
where: { relatedId: colonyId },
select: { id: true },
})
).map((task) => task.id);
const byColony = { where: { colonyId }, select: { id: true } };
const recordIds = [
...(await prisma.inspection.findMany(byColony)),
...(await prisma.varroaMeasurement.findMany(byColony)),
].map((record) => record.id);
await prisma.auditLog.deleteMany({
where: {
OR: [
{ entityType: 'Task', entityId: { in: ruleTaskIds } },
{
entityType: 'AutomationRule',
afterData: { path: ['relatedId'], equals: colonyId },
},
],
},
});
await prisma.domainEvent.deleteMany({
where: { aggregateId: { in: [...ruleTaskIds, ...recordIds] } },
});
await prisma.calendarSyncOutboxEntry.deleteMany({
where: { sourceId: { in: [...ruleTaskIds, ...recordIds] } },
});
await prisma.task.deleteMany({ where: { relatedId: colonyId } });
await prisma.notification.deleteMany({ where: { relatedId: colonyId } });
await prisma.varroaMeasurement.deleteMany({ where: { colonyId } });
await prisma.swarmControlCheck.deleteMany({ where: { colonyId } });
await prisma.inspection.deleteMany({ where: { colonyId } });
await prisma.colony.deleteMany({ where: { id: colonyId } });
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
@@ -112,19 +160,13 @@ describe('Automation rules (e2e)', () => {
);
expect(varroaRule).toBeDefined();
varroaRuleId = varroaRule!.id;
swarmRuleId = rules.find(
(rule) => rule.triggerType === 'SWARM_MOOD_HIGH',
)!.id;
});
it('creates a task and notification when queen not seen and no eggs present', async () => {
await request(app.getHttpServer())
.post('/api/v1/inspections')
.set('Authorization', `Bearer ${staffToken}`)
.send({
colonyId,
date: new Date().toISOString(),
queenSeen: false,
eggsPresent: false,
})
.expect(201);
await record('inspections', { queenSeen: false, eggsPresent: false });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
@@ -139,16 +181,7 @@ describe('Automation rules (e2e)', () => {
});
it('does not trigger when the queen was seen', async () => {
await request(app.getHttpServer())
.post('/api/v1/inspections')
.set('Authorization', `Bearer ${staffToken}`)
.send({
colonyId,
date: new Date().toISOString(),
queenSeen: true,
eggsPresent: false,
})
.expect(201);
await record('inspections', { queenSeen: true, eggsPresent: false });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
@@ -157,15 +190,7 @@ describe('Automation rules (e2e)', () => {
});
it('triggers a feeding task when feed status is kritisch', async () => {
await request(app.getHttpServer())
.post('/api/v1/inspections')
.set('Authorization', `Bearer ${staffToken}`)
.send({
colonyId,
date: new Date().toISOString(),
feedStatus: 'kritisch',
})
.expect(201);
await record('inspections', { feedStatus: 'kritisch' });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
@@ -174,44 +199,95 @@ describe('Automation rules (e2e)', () => {
expect(tasks.some((task) => task.title.includes('Fütterung'))).toBe(true);
});
it('triggers a treatment check when the varroa threshold is exceeded', async () => {
it('evaluates no rule on a corrected inspection', async () => {
const before = await prisma.task.count({ where: { relatedId: colonyId } });
const id = await record('inspections', { queenSeen: true });
// Close the open tasks so the one-open-task guard cannot be what keeps
// a new task from appearing - only the missing evaluation may.
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
});
await request(app.getHttpServer())
.post('/api/v1/varroa-measurements')
.set('Authorization', `Bearer ${adminToken}`)
.send({
colonyId,
date: new Date().toISOString(),
method: 'NATURAL_MITE_FALL',
miteCount: 20,
// One day on the board: 20 mites per day, above the default 10.
durationMinutes: 24 * 60,
})
.expect(201);
.patch(`/api/v1/inspections/${id}`)
.set('Authorization', `Bearer ${staffToken}`)
.send({ queenSeen: false, eggsPresent: false, feedStatus: 'kritisch' })
.expect(200);
await drainDomainEvents(app, [id]);
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
});
it('triggers a treatment check when the varroa threshold is exceeded', async () => {
const before = await prisma.task.count({ where: { relatedId: colonyId } });
await record('varroa-measurements', {
method: 'NATURAL_MITE_FALL',
miteCount: 20,
// One day on the board: 20 mites per day, above the default 10.
durationMinutes: 24 * 60,
});
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
});
expect(tasks).toHaveLength(3);
expect(tasks).toHaveLength(before + 1);
expect(tasks.some((task) => task.title.includes('Behandlung'))).toBe(true);
});
it('does not compare a sample-based count against the per-day threshold', async () => {
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
});
const before = await prisma.task.count({ where: { relatedId: colonyId } });
await request(app.getHttpServer())
.post('/api/v1/varroa-measurements')
.set('Authorization', `Bearer ${adminToken}`)
.send({
colonyId,
date: new Date().toISOString(),
method: 'POWDERED_SUGAR',
miteCount: 50,
})
.expect(201);
await record('varroa-measurements', {
method: 'POWDERED_SUGAR',
miteCount: 50,
});
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
});
it('re-evaluates a corrected varroa measurement against the threshold', async () => {
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
});
const before = await prisma.task.count({ where: { relatedId: colonyId } });
// Five mites per day: below the threshold.
const id = await record('varroa-measurements', {
method: 'NATURAL_MITE_FALL',
miteCount: 5,
durationMinutes: 24 * 60,
});
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
// The count was miscounted: 25 mites per day.
await request(app.getHttpServer())
.patch(`/api/v1/varroa-measurements/${id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ miteCount: 25 })
.expect(200);
await drainDomainEvents(app, [id]);
const tasks = await prisma.task.findMany({
where: {
relatedId: colonyId,
sourceAutomationTrigger: 'VARROA_THRESHOLD',
},
});
expect(tasks.filter((task) => task.status === 'OPEN')).toHaveLength(1);
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before + 1,
);
});
it('lets an admin clear a rule config, which falls back to its defaults', async () => {
const before = await prisma.automationRule.findUniqueOrThrow({
where: { id: varroaRuleId },
@@ -243,34 +319,58 @@ describe('Automation rules (e2e)', () => {
}
});
/**
* Deactivates SWARM_MOOD_HIGH, not a rule other e2e files rely on: the
* rule rows are shared, and switching off VARROA_THRESHOLD here would make
* a parallel file's varroa test see no task. Only swarm-control.e2e
* evaluates this rule, with checks that never trigger it (LOW or none).
*/
it('lets an admin deactivate a rule, preventing further triggers', async () => {
await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${varroaRuleId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ active: false })
.expect(200);
// Close the earlier tasks so the one-open-task-per-rule guard cannot be
// what keeps a new task from appearing - only the deactivation may.
const highSwarmMood = () =>
request(app.getHttpServer())
.post('/api/v1/swarm-control-checks')
.set('Authorization', `Bearer ${adminToken}`)
.send({
colonyId,
date: new Date().toISOString(),
swarmMood: 'HIGH',
})
.expect(201);
const swarmTasks = () =>
prisma.task.count({
where: {
relatedId: colonyId,
sourceAutomationTrigger: 'SWARM_MOOD_HIGH',
},
});
// While active, high swarm mood leaves a task - the rule really fires.
// (Swarm checks stay on the post-commit path: evaluated before the
// response, no event to drain.)
await highSwarmMood();
expect(await swarmTasks()).toBe(1);
// Close it so the one-open-task guard cannot be what keeps a new task
// from appearing - only the deactivation may.
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
});
await request(app.getHttpServer())
.post('/api/v1/varroa-measurements')
.set('Authorization', `Bearer ${adminToken}`)
.send({
colonyId,
date: new Date().toISOString(),
method: 'NATURAL_MITE_FALL',
miteCount: 30,
durationMinutes: 24 * 60,
})
.expect(201);
try {
await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${swarmRuleId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ active: false })
.expect(200);
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
});
expect(tasks).toHaveLength(3);
await highSwarmMood();
expect(await swarmTasks()).toBe(1);
} finally {
await prisma.automationRule.update({
where: { id: swarmRuleId },
data: { active: true },
});
}
});
});