Files
ApiCore/ApiCore-Backend/test/automation.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

377 lines
13 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 { 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;
triggerType: string;
active: boolean;
config: Record<string, unknown> | null;
actionTemplate: string | null;
}
describe('Automation rules (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const adminEmail = `automation-e2e-admin-${Date.now()}@example.com`;
const staffEmail = `automation-e2e-staff-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let adminId: string;
let staffId: string;
let adminToken: string;
let staffToken: string;
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();
prisma = app.get(PrismaService);
const passwordHash = await bcrypt.hash(password, 12);
const admin = await prisma.user.create({
data: {
email: adminEmail,
passwordHash,
name: 'Automation E2E Admin',
role: { connect: { key: 'ADMIN' } },
},
});
adminId = admin.id;
const staff = await prisma.user.create({
data: {
email: staffEmail,
passwordHash,
name: 'Automation E2E Staff',
role: { connect: { key: 'STAFF' } },
},
});
staffId = staff.id;
adminToken = (await login(app, adminEmail, password)).accessToken;
staffToken = (await login(app, staffEmail, password)).accessToken;
const apiary = await prisma.apiary.create({
data: { name: `Automation Stand ${Date.now()}` },
});
apiaryId = apiary.id;
const colony = await prisma.colony.create({
data: {
code: `AUTO-${Date.now()}`,
apiaryId,
colonyType: 'PRODUCTION_COLONY',
},
});
colonyId = colony.id;
});
afterAll(async () => {
// 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 } });
await prisma.refreshToken.deleteMany({
where: { userId: { in: [adminId, staffId] } },
});
await prisma.auditLog.deleteMany({
where: { userId: { in: [adminId, staffId] } },
});
await prisma.user.deleteMany({ where: { id: { in: [adminId, staffId] } } });
await app.close();
});
it('rejects a non-admin listing automation rules', () => {
return request(app.getHttpServer())
.get('/api/v1/automation-rules')
.set('Authorization', `Bearer ${staffToken}`)
.expect(403);
});
it('seeds every fixed trigger for an admin', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/automation-rules')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
const rules = response.body as AutomationRuleBody[];
const triggerTypes = rules.map((rule) => rule.triggerType).sort();
expect(triggerTypes).toEqual(
[...Object.values(AutomationTriggerType)].sort(),
);
const varroaRule = rules.find(
(rule) => rule.triggerType === 'VARROA_THRESHOLD',
);
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 record('inspections', { queenSeen: false, eggsPresent: false });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
});
expect(tasks).toHaveLength(1);
expect(tasks[0].title).toContain('Kontrolle');
const notifications = await prisma.notification.findMany({
where: { relatedId: colonyId },
});
expect(notifications).toHaveLength(1);
});
it('does not trigger when the queen was seen', async () => {
await record('inspections', { queenSeen: true, eggsPresent: false });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
});
expect(tasks).toHaveLength(1);
});
it('triggers a feeding task when feed status is kritisch', async () => {
await record('inspections', { feedStatus: 'kritisch' });
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
});
expect(tasks).toHaveLength(2);
expect(tasks.some((task) => task.title.includes('Fütterung'))).toBe(true);
});
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())
.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(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 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 },
});
try {
const response = await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${varroaRuleId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ config: null })
.expect(200);
expect((response.body as { config: unknown }).config).toBeNull();
await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${varroaRuleId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ active: null })
.expect(400);
} finally {
// The rule is shared by every suite - put its config back.
await prisma.automationRule.update({
where: { id: varroaRuleId },
data: {
config:
before.config === null
? Prisma.DbNull
: (before.config as Prisma.InputJsonValue),
},
});
}
});
/**
* 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 () => {
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' },
});
try {
await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${swarmRuleId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ active: false })
.expect(200);
await highSwarmMood();
expect(await swarmTasks()).toBe(1);
} finally {
await prisma.automationRule.update({
where: { id: swarmRuleId },
data: { active: true },
});
}
});
});