feat(backend): Automatisierungen mit drei fest hinterlegten Triggern (Modul 30)

Neues AutomationModule mit AutomationRule-Modell (ein Row je Trigger-Typ,
per Unique Constraint erzwungen). Drei fest im Code hinterlegte Trigger,
die Admins nur aktivieren/deaktivieren bzw. deren Konfiguration/Aufgaben-
text anpassen können:

- QUEENLESS_NO_EGGS: Königin nicht gesehen UND keine Stifte vorhanden
  (bei Durchsicht) → Kontrollaufgabe
- VARROA_THRESHOLD: Varroa-Schwellenwert überschritten (konfigurierbar,
  Standard 10 Milben/Tag) → Behandlungsprüfung
- FEED_STATUS_CRITICAL: Futterstatus "kritisch" (bei Durchsicht) →
  Fütterungsaufgabe

Jeder ausgelöste Trigger erzeugt eine Task UND eine Notification sowie
einen Audit-Log-Eintrag; Tasks lösen zusätzlich das bestehende
task.created-Webhook aus. InspectionsService und VarroaService rufen
die Auswertung direkt nach dem jeweiligen Erstellen auf.

Neue Endpunkte (nur Administrator): GET/PATCH /automation-rules.

Unit-Tests für AutomationService (alle drei Trigger, Deaktivierung,
Update mit Audit-Log) sowie E2E-Tests (Rollen-Check, alle drei Trigger
end-to-end über echte Inspection-/Varroa-Endpunkte, Deaktivierung
verhindert weitere Trigger). E2E-Suite zweimal hintereinander grün
verifiziert (Idempotenz der globalen Regel-Zeilen sichergestellt).
Migration auf Dev- und Test-Datenbank angewendet.
This commit is contained in:
Nick Szaunig committed 2026-08-24 17:25:42 +02:00
1 parent 42a2be31b4
commit 3f47a6ae8d
15 files changed
+733

No files matched your search

+2
View File
@@ -30,6 +30,7 @@ import { NotificationsModule } from './notifications/notifications.module';
import { StatisticsModule } from './statistics/statistics.module';
import { WebhooksModule } from './webhooks/webhooks.module';
import { DocumentsModule } from './documents/documents.module';
import { AutomationModule } from './automation/automation.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard';
@@ -65,6 +66,7 @@ import { RolesGuard } from './auth/guards/roles.guard';
StatisticsModule,
WebhooksModule,
DocumentsModule,
AutomationModule,
],
controllers: [],
providers: [
@@ -0,0 +1,30 @@
import { Body, Controller, Get, Param, Patch } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Role } from '../../generated/prisma';
import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { AutomationService } from './automation.service';
import { UpdateAutomationRuleDto } from './dto/update-automation-rule.dto';
@ApiTags('automation-rules')
@ApiBearerAuth()
@Roles(Role.ADMIN)
@Controller('automation-rules')
export class AutomationController {
constructor(private readonly automationService: AutomationService) {}
@Get()
findAll() {
return this.automationService.findAll();
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateAutomationRuleDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.automationService.update(id, dto, actor.id);
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { NotificationsModule } from '../notifications/notifications.module';
import { AutomationController } from './automation.controller';
import { AutomationService } from './automation.service';
@Module({
imports: [NotificationsModule],
controllers: [AutomationController],
providers: [AutomationService],
exports: [AutomationService],
})
export class AutomationModule {}
@@ -0,0 +1,210 @@
import { NotFoundException } from '@nestjs/common';
import { AutomationService } from './automation.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { NotificationsService } from '../notifications/notifications.service';
import { WebhooksService } from '../webhooks/webhooks.service';
describe('AutomationService', () => {
let service: AutomationService;
let prisma: {
automationRule: {
upsert: jest.Mock;
findMany: jest.Mock;
findUnique: jest.Mock;
update: jest.Mock;
};
task: { create: jest.Mock };
};
let auditLog: { record: jest.Mock };
let notifications: { record: jest.Mock };
let webhooks: { dispatch: jest.Mock };
const queenlessRule = {
id: 'rule-1',
triggerType: 'QUEENLESS_NO_EGGS',
active: true,
config: {},
actionTemplate: 'Kontrolle empfohlen',
};
const feedRule = {
id: 'rule-2',
triggerType: 'FEED_STATUS_CRITICAL',
active: true,
config: {},
actionTemplate: 'Fütterung erforderlich',
};
const varroaRule = {
id: 'rule-3',
triggerType: 'VARROA_THRESHOLD',
active: true,
config: { thresholdMitesPerDay: 10 },
actionTemplate: 'Behandlung prüfen',
};
beforeEach(() => {
prisma = {
automationRule: {
upsert: jest.fn().mockResolvedValue(undefined),
findMany: jest.fn(),
findUnique: jest.fn(),
update: jest.fn(),
},
task: { create: jest.fn().mockResolvedValue({ id: 'task-1' }) },
};
auditLog = { record: jest.fn() };
notifications = { record: jest.fn() };
webhooks = { dispatch: jest.fn().mockResolvedValue(undefined) };
service = new AutomationService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
notifications as unknown as NotificationsService,
webhooks as unknown as WebhooksService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.automationRule.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('findAll seeds the three default rules before returning them', async () => {
prisma.automationRule.findMany.mockResolvedValue([
queenlessRule,
varroaRule,
feedRule,
]);
const result = await service.findAll();
expect(prisma.automationRule.upsert).toHaveBeenCalledTimes(3);
expect(result).toHaveLength(3);
});
describe('evaluateInspection', () => {
it('creates a task and notification when queen not seen and no eggs present', async () => {
prisma.automationRule.findMany.mockResolvedValue([queenlessRule]);
await service.evaluateInspection({
id: 'inspection-1',
colonyId: 'colony-1',
queenSeen: false,
eggsPresent: false,
feedStatus: null,
} as never);
expect(prisma.task.create).toHaveBeenCalledTimes(1);
const [[taskArg]] = prisma.task.create.mock.calls as [
[{ data: { relatedId: string; sourceInspectionId?: string } }],
];
expect(taskArg.data.relatedId).toBe('colony-1');
expect(taskArg.data.sourceInspectionId).toBe('inspection-1');
expect(notifications.record).toHaveBeenCalledTimes(1);
});
it('does not trigger when the queen was seen', async () => {
prisma.automationRule.findMany.mockResolvedValue([queenlessRule]);
await service.evaluateInspection({
id: 'inspection-2',
colonyId: 'colony-1',
queenSeen: true,
eggsPresent: false,
feedStatus: null,
} as never);
expect(prisma.task.create).not.toHaveBeenCalled();
});
it('triggers when feed status is kritisch, case-insensitive', async () => {
prisma.automationRule.findMany.mockResolvedValue([feedRule]);
await service.evaluateInspection({
id: 'inspection-3',
colonyId: 'colony-1',
queenSeen: true,
eggsPresent: true,
feedStatus: 'Kritisch',
} as never);
expect(prisma.task.create).toHaveBeenCalledTimes(1);
});
it('does not trigger a deactivated rule', async () => {
prisma.automationRule.findMany.mockResolvedValue([]);
await service.evaluateInspection({
id: 'inspection-4',
colonyId: 'colony-1',
queenSeen: false,
eggsPresent: false,
feedStatus: 'kritisch',
} as never);
expect(prisma.task.create).not.toHaveBeenCalled();
});
});
describe('evaluateVarroaMeasurement', () => {
it('creates a task when the calculated value meets the threshold', async () => {
prisma.automationRule.findUnique.mockResolvedValue(varroaRule);
await service.evaluateVarroaMeasurement({
id: 'measurement-1',
colonyId: 'colony-1',
calculatedValue: 12,
miteCount: null,
} as never);
expect(prisma.task.create).toHaveBeenCalledTimes(1);
});
it('does not trigger when below the threshold', async () => {
prisma.automationRule.findUnique.mockResolvedValue(varroaRule);
await service.evaluateVarroaMeasurement({
id: 'measurement-2',
colonyId: 'colony-1',
calculatedValue: 5,
miteCount: null,
} as never);
expect(prisma.task.create).not.toHaveBeenCalled();
});
it('falls back to miteCount when calculatedValue is null', async () => {
prisma.automationRule.findUnique.mockResolvedValue(varroaRule);
await service.evaluateVarroaMeasurement({
id: 'measurement-3',
colonyId: 'colony-1',
calculatedValue: null,
miteCount: 15,
} as never);
expect(prisma.task.create).toHaveBeenCalledTimes(1);
});
});
describe('update', () => {
it('records an audit log entry with before/after data', async () => {
prisma.automationRule.findUnique.mockResolvedValue(varroaRule);
prisma.automationRule.update.mockResolvedValue({
...varroaRule,
active: false,
});
await service.update('rule-3', { active: false }, 'user-1');
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'AutomationRule',
entityId: 'rule-3',
action: 'UPDATE',
}),
);
});
});
});
@@ -0,0 +1,179 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { NotificationsService } from '../notifications/notifications.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import {
AutomationRule,
AutomationTriggerType,
Inspection,
Prisma,
VarroaMeasurement,
} from '../../generated/prisma';
import { UpdateAutomationRuleDto } from './dto/update-automation-rule.dto';
interface RuleDefaults {
config: Record<string, unknown>;
actionTemplate: string;
}
const DEFAULT_RULES: Record<AutomationTriggerType, RuleDefaults> = {
QUEENLESS_NO_EGGS: {
config: {},
actionTemplate:
'Kontrolle empfohlen: Königin nicht gesehen und keine Stifte vorhanden.',
},
VARROA_THRESHOLD: {
config: { thresholdMitesPerDay: 10 },
actionTemplate: 'Behandlung prüfen: Varroa-Schwellenwert überschritten.',
},
FEED_STATUS_CRITICAL: {
config: {},
actionTemplate: 'Fütterung erforderlich: Futterstatus kritisch.',
},
};
@Injectable()
export class AutomationService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
private readonly notifications: NotificationsService,
private readonly webhooks: WebhooksService,
) {}
private async ensureDefaults(): Promise<void> {
for (const triggerType of Object.keys(
DEFAULT_RULES,
) as AutomationTriggerType[]) {
const defaults = DEFAULT_RULES[triggerType];
await this.prisma.automationRule.upsert({
where: { triggerType },
update: {},
create: {
triggerType,
config: defaults.config as Prisma.InputJsonValue,
actionTemplate: defaults.actionTemplate,
},
});
}
}
async findAll(): Promise<AutomationRule[]> {
await this.ensureDefaults();
return this.prisma.automationRule.findMany({
orderBy: { triggerType: 'asc' },
});
}
async findById(id: string): Promise<AutomationRule> {
const rule = await this.prisma.automationRule.findUnique({
where: { id },
});
if (!rule) {
throw new NotFoundException('Automation rule not found');
}
return rule;
}
async update(
id: string,
dto: UpdateAutomationRuleDto,
actingUserId: string,
): Promise<AutomationRule> {
const before = await this.findById(id);
const rule = await this.prisma.automationRule.update({
where: { id },
data: {
...dto,
config: dto.config as Prisma.InputJsonValue | undefined,
},
});
await this.auditLog.record({
entityType: 'AutomationRule',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: rule,
});
return rule;
}
async evaluateInspection(inspection: Inspection): Promise<void> {
await this.ensureDefaults();
const rules = await this.prisma.automationRule.findMany({
where: {
triggerType: { in: ['QUEENLESS_NO_EGGS', 'FEED_STATUS_CRITICAL'] },
active: true,
},
});
const ruleByType = new Map(rules.map((rule) => [rule.triggerType, rule]));
const queenlessRule = ruleByType.get('QUEENLESS_NO_EGGS');
if (
queenlessRule &&
inspection.queenSeen === false &&
inspection.eggsPresent === false
) {
await this.triggerAction(
queenlessRule,
inspection.colonyId,
inspection.id,
);
}
const feedRule = ruleByType.get('FEED_STATUS_CRITICAL');
if (feedRule && inspection.feedStatus?.toLowerCase() === 'kritisch') {
await this.triggerAction(feedRule, inspection.colonyId, inspection.id);
}
}
async evaluateVarroaMeasurement(
measurement: VarroaMeasurement,
): Promise<void> {
await this.ensureDefaults();
const rule = await this.prisma.automationRule.findUnique({
where: { triggerType: 'VARROA_THRESHOLD' },
});
if (!rule || !rule.active) {
return;
}
const config = rule.config as { thresholdMitesPerDay?: number } | null;
const threshold = config?.thresholdMitesPerDay ?? 10;
const value = measurement.calculatedValue ?? measurement.miteCount;
if (value !== null && value >= threshold) {
await this.triggerAction(rule, measurement.colonyId);
}
}
private async triggerAction(
rule: AutomationRule,
colonyId: string,
sourceInspectionId?: string,
): Promise<void> {
const title = rule.actionTemplate ?? 'Automatisierte Aufgabe';
const task = await this.prisma.task.create({
data: {
title,
priority: 'HIGH',
relatedType: 'COLONY',
relatedId: colonyId,
sourceInspectionId,
},
});
await this.webhooks.dispatch('task.created', task);
await this.notifications.record({
priority: 'WARNUNG',
message: title,
relatedType: 'COLONY',
relatedId: colonyId,
});
await this.auditLog.record({
entityType: 'AutomationRule',
entityId: rule.id,
action: 'CREATE',
afterData: { taskId: task.id, colonyId, triggerType: rule.triggerType },
});
}
}
@@ -0,0 +1,19 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsBoolean, IsObject, IsOptional, IsString } from 'class-validator';
export class UpdateAutomationRuleDto {
@ApiPropertyOptional()
@IsOptional()
@IsBoolean()
active?: boolean;
@ApiPropertyOptional({ type: Object })
@IsOptional()
@IsObject()
config?: Record<string, unknown>;
@ApiPropertyOptional()
@IsOptional()
@IsString()
actionTemplate?: string;
}
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { AutomationModule } from '../automation/automation.module';
import { InspectionsController } from './inspections.controller';
import { ColonyInspectionsController } from './colony-inspections.controller';
import { InspectionsService } from './inspections.service';
@Module({
imports: [AutomationModule],
controllers: [InspectionsController, ColonyInspectionsController],
providers: [InspectionsService],
exports: [InspectionsService],
@@ -2,6 +2,7 @@ import { NotFoundException } from '@nestjs/common';
import { InspectionsService } from './inspections.service';
import { PrismaService } from '../prisma/prisma.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { AutomationService } from '../automation/automation.service';
describe('InspectionsService', () => {
let service: InspectionsService;
@@ -30,9 +31,13 @@ describe('InspectionsService', () => {
task: { create: jest.fn() },
};
const webhooks = { dispatch: jest.fn().mockResolvedValue(undefined) };
const automation = {
evaluateInspection: jest.fn().mockResolvedValue(undefined),
};
service = new InspectionsService(
prisma as unknown as PrismaService,
webhooks as unknown as WebhooksService,
automation as unknown as AutomationService,
);
});
@@ -1,6 +1,7 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { AutomationService } from '../automation/automation.service';
import { Inspection, Task } from '../../generated/prisma';
import { CreateInspectionDto } from './dto/create-inspection.dto';
import { CreateTaskFromInspectionDto } from './dto/create-task-from-inspection.dto';
@@ -10,6 +11,7 @@ export class InspectionsService {
constructor(
private readonly prisma: PrismaService,
private readonly webhooks: WebhooksService,
private readonly automation: AutomationService,
) {}
async findAll(): Promise<Inspection[]> {
@@ -41,6 +43,7 @@ export class InspectionsService {
data: { ...dto, date: new Date(dto.date), userId: actingUserId },
});
await this.webhooks.dispatch('inspection.created', inspection);
await this.automation.evaluateInspection(inspection);
return inspection;
}
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { AutomationModule } from '../automation/automation.module';
import { VarroaController } from './varroa.controller';
import { ColonyVarroaMeasurementsController } from './colony-varroa-measurements.controller';
import { VarroaService } from './varroa.service';
@Module({
imports: [AutomationModule],
controllers: [VarroaController, ColonyVarroaMeasurementsController],
providers: [VarroaService],
exports: [VarroaService],
@@ -2,6 +2,7 @@ import { NotFoundException } from '@nestjs/common';
import { VarroaService } from './varroa.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { AutomationService } from '../automation/automation.service';
describe('VarroaService', () => {
let service: VarroaService;
@@ -29,9 +30,13 @@ describe('VarroaService', () => {
},
};
auditLog = { record: jest.fn() };
const automation = {
evaluateVarroaMeasurement: jest.fn().mockResolvedValue(undefined),
};
service = new VarroaService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
automation as unknown as AutomationService,
);
});
@@ -1,6 +1,7 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { AutomationService } from '../automation/automation.service';
import { VarroaMeasurement } from '../../generated/prisma';
import { CreateVarroaMeasurementDto } from './dto/create-varroa-measurement.dto';
@@ -9,6 +10,7 @@ export class VarroaService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
private readonly automation: AutomationService,
) {}
async findAll(): Promise<VarroaMeasurement[]> {
@@ -48,6 +50,7 @@ export class VarroaService {
userId: actingUserId,
afterData: measurement,
});
await this.automation.evaluateVarroaMeasurement(measurement);
return measurement;
}
}