feat: T4 wave 4 - rules suggest, takeover, chains, autopilot A1-A3, suggestions page, varroa bands UI

- Automation rules propose suggestions instead of creating tasks;
  notify per rule config; corrected varroa measurements refresh or
  resolve their suggestion
- Inspection values can be taken over into the colony card
  (occupiedFrames 0-40, strength deprecated); warning counts use the
  same visibility rule as the notification list
- Biotech chains: swarm check after queen cells, queen acceptance
  check, split schedules (raise own, queen cell, queen)
- Season autopilot core with A1 inspection due, A2 varroa measurement,
  A3 recheck after treatment; colony sync and daily step
- Frontend: suggestions page with groups, bulk accept, undo, paging,
  focus management and permission gating
- Frontend: varroa traffic light from seasonal bands, sample size,
  one range request for the colony chart
- Notifications: mark-read answers 404 for rows the user may no
  longer see

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 15:22:36 +02:00
1 parent 64a2b7dad9
commit 02eb16924e
142 files changed
+11847 -1251

No files matched your search

+152 -92
View File
@@ -50,6 +50,24 @@ describe('Automation rules (e2e)', () => {
return id;
}
const suggestionsOf = (ruleKey?: AutomationTriggerType) =>
prisma.suggestion.findMany({
where: { colonyId, source: 'RULE', ...(ruleKey ? { ruleKey } : {}) },
orderBy: { createdAt: 'asc' },
});
// Other sources (the season autopilot) propose on the same events.
const ruleSuggestionCount = () =>
prisma.suggestion.count({ where: { colonyId, source: 'RULE' } });
const tasksOfColony = () =>
prisma.task.count({ where: { relatedId: colonyId } });
// Settles every open suggestion, so the one-open-thing guard cannot be
// what keeps a new one from appearing - only the missing evaluation may.
const dismissOpen = () =>
prisma.suggestion.updateMany({
where: { colonyId, status: 'OPEN' },
data: { status: 'DISMISSED' },
});
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
@@ -91,15 +109,15 @@ describe('Automation rules (e2e)', () => {
});
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 },
// Rule suggestions 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 suggestionIds = (
await prisma.suggestion.findMany({
where: { colonyId },
select: { id: true },
})
).map((task) => task.id);
).map((suggestion) => suggestion.id);
const byColony = { where: { colonyId }, select: { id: true } };
const recordIds = [
...(await prisma.inspection.findMany(byColony)),
@@ -108,7 +126,7 @@ describe('Automation rules (e2e)', () => {
await prisma.auditLog.deleteMany({
where: {
OR: [
{ entityType: 'Task', entityId: { in: ruleTaskIds } },
{ entityType: 'Suggestion', entityId: { in: suggestionIds } },
{
entityType: 'AutomationRule',
afterData: { path: ['relatedId'], equals: colonyId },
@@ -117,13 +135,15 @@ describe('Automation rules (e2e)', () => {
},
});
await prisma.domainEvent.deleteMany({
where: { aggregateId: { in: [...ruleTaskIds, ...recordIds] } },
where: { aggregateId: { in: recordIds } },
});
await prisma.calendarSyncOutboxEntry.deleteMany({
where: { sourceId: { in: [...ruleTaskIds, ...recordIds] } },
where: { sourceId: { in: recordIds } },
});
await prisma.task.deleteMany({ where: { relatedId: colonyId } });
await prisma.notification.deleteMany({ where: { relatedId: colonyId } });
await prisma.notification.deleteMany({
where: { relatedType: 'Suggestion', relatedId: { in: suggestionIds } },
});
await prisma.suggestion.deleteMany({ where: { colonyId } });
await prisma.varroaMeasurement.deleteMany({ where: { colonyId } });
await prisma.swarmControlCheck.deleteMany({ where: { colonyId } });
await prisma.inspection.deleteMany({ where: { colonyId } });
@@ -254,19 +274,32 @@ describe('Automation rules (e2e)', () => {
}
});
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 },
it('proposes a queen check and notifies when queen not seen and no eggs present', async () => {
const inspectionId = await record('inspections', {
queenSeen: false,
eggsPresent: false,
});
expect(tasks).toHaveLength(1);
expect(tasks[0].title).toContain('Kontrolle');
const suggestions = await suggestionsOf();
expect(suggestions).toHaveLength(1);
expect(suggestions[0]).toMatchObject({
ruleKey: 'QUEENLESS_NO_EGGS',
source: 'RULE',
mode: 'PLAN',
intent: 'QUEEN_CHECK',
status: 'OPEN',
priority: 'HIGH',
reasonCode: 'QUEENLESS_NO_EGGS',
requiredPermission: 'inspections:read',
dedupeKey: `QUEENLESS_NO_EGGS:${colonyId}:${inspectionId}`,
});
// The rule proposes, it creates no task.
expect(await tasksOfColony()).toBe(0);
const notifications = await prisma.notification.findMany({
where: { relatedId: colonyId },
where: { relatedType: 'Suggestion', relatedId: suggestions[0].id },
});
// One copy per user who may read tasks, never a broadcast.
// One copy per user who may read tasks and inspections, 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(
@@ -277,31 +310,28 @@ describe('Automation rules (e2e)', () => {
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);
expect(await suggestionsOf()).toHaveLength(1);
});
it('triggers a feeding task when feed status is kritisch', async () => {
it('proposes feeding when feed status is kritisch, without a notification', 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);
const suggestions = await suggestionsOf('FEED_STATUS_CRITICAL');
expect(suggestions).toHaveLength(1);
expect(suggestions[0]).toMatchObject({ intent: 'FEED', status: 'OPEN' });
// The rule is off for notifications by default (notify: false).
expect(
await prisma.notification.count({
where: { relatedType: 'Suggestion', relatedId: suggestions[0].id },
}),
).toBe(0);
expect(await tasksOfColony()).toBe(0);
});
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 dismissOpen();
const before = await ruleSuggestionCount();
await request(app.getHttpServer())
.patch(`/api/v1/inspections/${id}`)
@@ -310,57 +340,74 @@ describe('Automation rules (e2e)', () => {
.expect(200);
await drainDomainEvents(app, [id]);
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
expect(await ruleSuggestionCount()).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', {
it('proposes a treatment check when the mite fall is red', async () => {
const id = await record('varroa-measurements', {
method: 'NATURAL_MITE_FALL',
miteCount: 20,
// One day on the board: 20 mites per day, above the default 10.
date: '2026-08-10T00:00:00.000Z',
// One day on the board: 20 mites per day, above the limit of 10.
durationMinutes: 24 * 60,
});
const tasks = await prisma.task.findMany({
where: { relatedId: colonyId },
const suggestions = await suggestionsOf('VARROA_THRESHOLD');
expect(suggestions).toHaveLength(1);
expect(suggestions[0]).toMatchObject({
intent: 'VARROA_TREAT',
reasonCode: 'VARROA_RED',
status: 'OPEN',
requiredPermission: 'varroa:read',
evidence: {
colonyId,
measurementId: id,
measuredOn: '2026-08-10',
value: 20,
redAbove: 10,
unit: 'MITES_PER_DAY',
},
});
expect(tasks).toHaveLength(before + 1);
expect(tasks.some((task) => task.title.includes('Behandlung'))).toBe(true);
expect(await tasksOfColony()).toBe(0);
});
it('does not compare a sample-based count against the per-day threshold', async () => {
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
it('rates a sample-based count with the percentage band', async () => {
await dismissOpen();
const before = await ruleSuggestionCount();
// Summer band: red above 5 %. 5 of 500 bees is 1 %: yellow, no proposal.
await record('varroa-measurements', {
method: 'POWDERED_SUGAR',
miteCount: 5,
sampleBees: 500,
date: '2026-07-10T00:00:00.000Z',
});
const before = await prisma.task.count({ where: { relatedId: colonyId } });
expect(await ruleSuggestionCount()).toBe(before);
// 50 of 500 bees is 10 %: red.
await record('varroa-measurements', {
method: 'POWDERED_SUGAR',
miteCount: 50,
sampleBees: 500,
date: '2026-07-11T00:00:00.000Z',
});
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
const red = await prisma.suggestion.findMany({
where: { colonyId, status: 'OPEN', ruleKey: 'VARROA_THRESHOLD' },
});
expect(red).toHaveLength(1);
expect(red[0].evidence).toMatchObject({ unit: 'PERCENT', value: 10 });
});
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.
it('re-evaluates a corrected varroa measurement against the limit', async () => {
await dismissOpen();
const before = await ruleSuggestionCount();
// Five mites per day: yellow in August, no proposal.
const id = await record('varroa-measurements', {
method: 'NATURAL_MITE_FALL',
miteCount: 5,
date: '2026-08-20T00:00:00.000Z',
durationMinutes: 24 * 60,
});
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before,
);
expect(await ruleSuggestionCount()).toBe(before);
// The count was miscounted: 25 mites per day.
await request(app.getHttpServer())
@@ -370,16 +417,35 @@ describe('Automation rules (e2e)', () => {
.expect(200);
await drainDomainEvents(app, [id]);
const tasks = await prisma.task.findMany({
where: {
relatedId: colonyId,
sourceAutomationTrigger: 'VARROA_THRESHOLD',
},
const open = await prisma.suggestion.findMany({
where: { colonyId, status: 'OPEN', ruleKey: 'VARROA_THRESHOLD' },
});
expect(tasks.filter((task) => task.status === 'OPEN')).toHaveLength(1);
expect(await prisma.task.count({ where: { relatedId: colonyId } })).toBe(
before + 1,
);
expect(open).toHaveLength(1);
expect(open[0].dedupeKey).toBe(`VARROA_THRESHOLD:${colonyId}:${id}`);
expect(await ruleSuggestionCount()).toBe(before + 1);
// Corrected again while still red: the open suggestion follows the value.
const correct = async (miteCount: number) => {
await request(app.getHttpServer())
.patch(`/api/v1/varroa-measurements/${id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ miteCount })
.expect(200);
await drainDomainEvents(app, [id]);
};
await correct(30);
const refreshed = await prisma.suggestion.findUniqueOrThrow({
where: { id: open[0].id },
});
expect(refreshed.status).toBe('OPEN');
expect(refreshed.evidence).toMatchObject({ value: 30 });
// Corrected below the limit: the condition is gone, the suggestion resolves.
await correct(1);
const resolved = await prisma.suggestion.findUniqueOrThrow({
where: { id: open[0].id },
});
expect(resolved).toMatchObject({ status: 'RESOLVED', dedupeKey: null });
});
it('lets an admin clear a rule config, which falls back to its defaults', async () => {
@@ -430,25 +496,19 @@ describe('Automation rules (e2e)', () => {
swarmMood: 'HIGH',
})
.expect(201);
const swarmTasks = () =>
prisma.task.count({
where: {
relatedId: colonyId,
sourceAutomationTrigger: 'SWARM_MOOD_HIGH',
},
const swarmSuggestions = () =>
prisma.suggestion.count({
where: { colonyId, ruleKey: '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.)
// While active, high swarm mood leaves a suggestion - 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
expect(await swarmSuggestions()).toBe(1);
// Settle it so the one-open-thing guard cannot be what keeps a new one
// from appearing - only the deactivation may.
await prisma.task.updateMany({
where: { relatedId: colonyId },
data: { status: 'DONE' },
});
await dismissOpen();
try {
await request(app.getHttpServer())
@@ -459,7 +519,7 @@ describe('Automation rules (e2e)', () => {
await highSwarmMood();
expect(await swarmTasks()).toBe(1);
expect(await swarmSuggestions()).toBe(1);
} finally {
await prisma.automationRule.update({
where: { id: swarmRuleId },