Files
ApiCore/ApiCore-Backend/test/automation.e2e-spec.ts
T
Nick SzaunigandClaude Opus 5.5 d99a697739 feat: T4 waves 1-2 - rule configs, schema, suggestions core, season, rule forms
- Rule configs with typed parsers and registry; Berlin day helpers
- Schema: T4 enums, Suggestion table, feed vocabulary (feedStatus as
  ColonyCondition with legacy text mapping), split queen source,
  varroa sample size; migration harness for data migrations
- SuggestionsService: propose/refresh/resolve/obsolete/expire,
  accept/dismiss/reopen incl. bulk, lock order, concurrency e2e
- SeasonService: phenology-based segments, inspection/varroa due dates,
  queen age; TimeEventsStep with JobPartialFailure
- Frontend: per-rule settings forms with visible value sources

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

466 lines
16 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';
import { DEFAULT_RULES } from '../src/automation/rule-config';
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;
});
const NEW_TRIGGERS = [
'INSPECTION_INTERVAL',
'QUEEN_CELLS_SWARM_CHECK',
'QUEEN_ACCEPTANCE_CHECK',
'SPLIT_SCHEDULE',
'COLONY_ENDED_CLEANUP',
'WITHDRAWAL_ENDED',
'HONEY_WATER_CONTENT',
'SEASON_AUTOPILOT',
'PHENOLOGY',
] as const;
it('lists the nine new rules with their defaults', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/automation-rules')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
const rules = response.body as AutomationRuleBody[];
for (const trigger of NEW_TRIGGERS) {
const rule = rules.find((entry) => entry.triggerType === trigger);
expect(rule).toBeDefined();
expect(rule!.active).toBe(DEFAULT_RULES[trigger].active ?? true);
expect(rule!.config).toEqual(DEFAULT_RULES[trigger].config);
expect(rule!.actionTemplate).toBe('');
}
// Existing rules keep their stored config; a fresh database has the new defaults.
const varroa = rules.find(
(rule) => rule.triggerType === 'VARROA_THRESHOLD',
);
expect(varroa?.config).toBeTruthy();
});
it('PATCH a rule with an invalid known value answers 400 with the field', async () => {
const rules = (
await request(app.getHttpServer())
.get('/api/v1/automation-rules')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200)
).body as AutomationRuleBody[];
const autopilot = rules.find(
(rule) => rule.triggerType === 'SEASON_AUTOPILOT',
)!;
const res = await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${autopilot.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ config: { queenMaxAgeYears: 0 } })
.expect(400);
const body = res.body as {
message: string;
issues: { field: string; message: string }[];
};
expect(body.message).toBe('Die Einstellung ist ungültig.');
expect(body.issues).toEqual([
expect.objectContaining({ field: 'queenMaxAgeYears' }),
]);
// Nothing was written.
const stored = await prisma.automationRule.findUniqueOrThrow({
where: { id: autopilot.id },
});
expect(stored.config).toEqual(autopilot.config);
});
it('PATCH keeps unknown keys and saves a valid config', async () => {
const rule = await prisma.automationRule.findUniqueOrThrow({
where: { triggerType: 'SEASON_AUTOPILOT' },
});
try {
await request(app.getHttpServer())
.patch(`/api/v1/automation-rules/${rule.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ config: { queenMaxAgeYears: 3, futureKey: 'x' } })
.expect(200);
const stored = await prisma.automationRule.findUniqueOrThrow({
where: { id: rule.id },
});
expect(stored.config).toEqual({ queenMaxAgeYears: 3, futureKey: 'x' });
} finally {
await prisma.automationRule.update({
where: { id: rule.id },
data: { config: rule.config as Prisma.InputJsonValue },
});
}
});
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: 'CRITICAL' });
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: 'CRITICAL' })
.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 },
});
}
});
});