- Schema III: per-user notifications (broadcast fan-out migration, category, link, requiredPermissions filter), notification preferences and settings endpoints, calendar withdrawal switch, occupiedFrames - Suggestions API: list/summary with permission visibility and paging, accept/dismiss/reopen incl. bulk, SuggestionView on all responses - Varroa traffic light by season and method, young colonies, treatment effect window, sample-based percentage; shared withdrawal-window helper on Berlin calendar days; GET /varroa-measurements/thresholds - ColonySplit and QueenAssigned domain events with calendar and webhook handlers - Outbox claims compare against now() rounded to timestamp(3); fixes the flaky e2e claims of rows written with SQL now() Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
471 lines
16 KiB
TypeScript
471 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 },
|
|
});
|
|
// One copy per user who may read tasks, never a broadcast.
|
|
expect(notifications.length).toBeGreaterThan(0);
|
|
expect(notifications.every((n) => n.category === 'SUGGESTION')).toBe(true);
|
|
expect(new Set(notifications.map((n) => n.userId)).size).toBe(
|
|
notifications.length,
|
|
);
|
|
});
|
|
|
|
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 },
|
|
});
|
|
}
|
|
});
|
|
});
|