feat: Bearbeiten für alle Log-Einträge (Aufgaben, Durchsichten, Behandlungen, Fütterungen, Varroa-Messungen, Ernten, Schleuderungen, Abfüllungen)

Bisher liessen sich diese acht Objekttypen nur anlegen, nie nachträglich
korrigieren – Aufgaben hatten zwar schon einen PATCH-Endpunkt, aber
keine Bearbeiten-UI, die übrigen sieben hatten weder Backend- noch
Frontend-Unterstützung. Jetzt bekommt jeder Typ einen PATCH :id
Endpunkt (UpdateXDto per PartialType(PickType(...)) nach demselben
Muster wie UpdateColonyDto/UpdateApiaryDto, mit Audit-Log-Eintrag
inkl. Vorher-/Nachher-Stand) sowie eine Bearbeiten-UI:

- Aufgaben: Dialog auf der Aufgabenliste
- Durchsichten/Behandlungen/Fütterungen/Varroa-Messungen: Dialog pro
  Listeneintrag auf der Volk-Detailseite
- Ernten: Dialog auf der eigenen Ernte-Detailseite
- Schleuderungen: Dialog direkt in der Rückverfolgbarkeits-Karte der
  Honigcharge (keine eigene Detailseite nötig); Erntezeilen dort
  verlinken jetzt zur Ernte-Detailseite statt sie zu duplizieren
- Abfüllungen: Dialog auf der Abfüllungs-Detailseite, bewusst nur
  Datum/MHD/Losnummer editierbar – Glasgröße/-anzahl bleiben
  unveränderlich, weil sie bereits unumkehrbar die Honigcharge-Menge
  reduziert haben

Relationsstiftende Fremdschlüssel (colonyId, apiaryId/colonyIds,
harvestIds, honeyBatchId) bleiben überall bewusst nicht editierbar,
konsistent mit dem bestehenden apiaryId-Ausschluss bei UpdateColonyDto.
This commit is contained in:
Nick Szaunig committed 2026-08-25 04:28:37 +02:00
1 parent 63ab0e842d
commit 68f459001a
58 files changed
+1909 -60

No files matched your search

@@ -1,10 +1,19 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
Query,
} 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 { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
import { UpdateBottlingBatchDto } from './dto/update-bottling-batch.dto';
import { BottlingService } from './bottling.service';
@ApiTags('bottling')
@@ -31,4 +40,14 @@ export class BottlingController {
) {
return this.bottlingService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateBottlingBatchDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.bottlingService.update(id, dto, actor.id);
}
}
@@ -13,6 +13,7 @@ describe('BottlingService', () => {
findUnique: jest.Mock;
findMany: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
$transaction: jest.Mock;
};
@@ -34,6 +35,7 @@ describe('BottlingService', () => {
findUnique: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
@@ -124,4 +126,35 @@ describe('BottlingService', () => {
}),
);
});
it('update writes an audit log entry with before and after data', async () => {
const before = { id: 'b1', lotNumber: 'L-1' };
const updated = { id: 'b1', lotNumber: 'L-2' };
prisma.bottlingBatch.findUnique
.mockResolvedValueOnce(before)
.mockResolvedValueOnce(updated);
prisma.bottlingBatch.update.mockResolvedValue(updated);
const result = await service.update('b1', { lotNumber: 'L-2' }, 'user-1');
expect(result).toEqual(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'BottlingBatch',
entityId: 'b1',
action: 'UPDATE',
beforeData: before,
afterData: updated,
}),
);
});
it('rejects updating to a product that does not exist', async () => {
prisma.bottlingBatch.findUnique.mockResolvedValueOnce({ id: 'b1' });
prisma.product.findUnique.mockResolvedValueOnce(null);
await expect(
service.update('b1', { productId: 'missing' }, 'user-1'),
).rejects.toBeInstanceOf(NotFoundException);
});
});
@@ -8,6 +8,7 @@ import { AuditLogService } from '../audit/audit-log.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { BottlingBatch } from '../../generated/prisma';
import { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
import { UpdateBottlingBatchDto } from './dto/update-bottling-batch.dto';
const bottlingBatchInclude = {
honeyBatch: true,
@@ -109,4 +110,36 @@ export class BottlingService {
await this.webhooks.dispatch('batch.updated', created.honeyBatch);
return created;
}
async update(id: string, dto: UpdateBottlingBatchDto, actingUserId: string) {
const before = await this.findById(id);
if (dto.productId) {
const product = await this.prisma.product.findUnique({
where: { id: dto.productId },
});
if (!product) {
throw new NotFoundException('Product not found');
}
}
await this.prisma.bottlingBatch.update({
where: { id },
data: {
...dto,
date: dto.date ? new Date(dto.date) : undefined,
bestBeforeDate: dto.bestBeforeDate
? new Date(dto.bestBeforeDate)
: undefined,
},
});
const bottlingBatch = await this.findById(id);
await this.auditLog.record({
entityType: 'BottlingBatch',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: bottlingBatch,
});
return bottlingBatch;
}
}
@@ -0,0 +1,11 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateBottlingBatchDto } from './create-bottling-batch.dto';
export class UpdateBottlingBatchDto extends PartialType(
PickType(CreateBottlingBatchDto, [
'productId',
'date',
'bestBeforeDate',
'lotNumber',
] as const),
) {}
@@ -0,0 +1,13 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateExtractionDto } from './create-extraction.dto';
export class UpdateExtractionDto extends PartialType(
PickType(CreateExtractionDto, [
'date',
'amount',
'room',
'waterContent',
'temperature',
'notes',
] as const),
) {}
@@ -1,10 +1,11 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } 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 { CreateExtractionDto } from './dto/create-extraction.dto';
import { UpdateExtractionDto } from './dto/update-extraction.dto';
import { ExtractionsService } from './extractions.service';
@ApiTags('extractions')
@@ -31,4 +32,14 @@ export class ExtractionsController {
) {
return this.extractionsService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateExtractionDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.extractionsService.update(id, dto, actor.id);
}
}
@@ -6,7 +6,7 @@ import { AuditLogService } from '../audit/audit-log.service';
describe('ExtractionsService', () => {
let service: ExtractionsService;
let prisma: {
extraction: { findUnique: jest.Mock };
extraction: { findUnique: jest.Mock; update: jest.Mock };
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
@@ -23,7 +23,7 @@ describe('ExtractionsService', () => {
extractionHarvest: { createMany: jest.fn() },
};
prisma = {
extraction: { findUnique: jest.fn() },
extraction: { findUnique: jest.fn(), update: jest.fn() },
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
@@ -58,4 +58,29 @@ describe('ExtractionsService', () => {
{ extractionId: extraction.id, harvestId: 'harvest-2' },
]);
});
it('update writes an audit log entry with before and after data', async () => {
const updated = { ...extraction, notes: 'geändert' };
prisma.extraction.findUnique
.mockResolvedValueOnce(extraction)
.mockResolvedValueOnce(updated);
prisma.extraction.update.mockResolvedValue(updated);
const result = await service.update(
'extraction-1',
{ notes: 'geändert' },
'user-1',
);
expect(result).toEqual(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'Extraction',
entityId: 'extraction-1',
action: 'UPDATE',
beforeData: extraction,
afterData: updated,
}),
);
});
});
@@ -2,6 +2,7 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { CreateExtractionDto } from './dto/create-extraction.dto';
import { UpdateExtractionDto } from './dto/update-extraction.dto';
const extractionInclude = {
harvests: {
@@ -66,4 +67,22 @@ export class ExtractionsService {
});
return this.findById(extraction.id);
}
async update(id: string, dto: UpdateExtractionDto, actingUserId: string) {
const before = await this.findById(id);
await this.prisma.extraction.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
});
const extraction = await this.findById(id);
await this.auditLog.record({
entityType: 'Extraction',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: extraction,
});
return extraction;
}
}
@@ -0,0 +1,14 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateFeedingDto } from './create-feeding.dto';
export class UpdateFeedingDto extends PartialType(
PickType(CreateFeedingDto, [
'date',
'feedType',
'product',
'amount',
'unit',
'batchNumber',
'notes',
] as const),
) {}
@@ -1,10 +1,11 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } 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 { CreateFeedingDto } from './dto/create-feeding.dto';
import { UpdateFeedingDto } from './dto/update-feeding.dto';
import { FeedingsService } from './feedings.service';
@ApiTags('feedings')
@@ -31,4 +32,14 @@ export class FeedingsController {
) {
return this.feedingsService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateFeedingDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.feedingsService.update(id, dto, actor.id);
}
}
@@ -10,6 +10,7 @@ describe('FeedingsService', () => {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
groupBy: jest.Mock;
};
};
@@ -23,6 +24,7 @@ describe('FeedingsService', () => {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
groupBy: jest.fn(),
},
};
@@ -61,6 +63,29 @@ describe('FeedingsService', () => {
expect(createArg.data.userId).toBe('user-1');
});
it('update writes an audit log entry with before and after data', async () => {
prisma.feeding.findUnique.mockResolvedValue(feeding);
const updated = { ...feeding, notes: 'geändert' };
prisma.feeding.update.mockResolvedValue(updated);
const result = await service.update(
'feeding-1',
{ notes: 'geändert' },
'user-1',
);
expect(result).toBe(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'Feeding',
entityId: 'feeding-1',
action: 'UPDATE',
beforeData: feeding,
afterData: updated,
}),
);
});
it('summaryByColony sums amounts per unit', async () => {
prisma.feeding.groupBy.mockResolvedValue([
{ unit: 'l', _sum: { amount: 5.5 } },
@@ -3,6 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { Feeding } from '../../generated/prisma';
import { CreateFeedingDto } from './dto/create-feeding.dto';
import { UpdateFeedingDto } from './dto/update-feeding.dto';
export interface FeedingSummaryEntry {
unit: string;
@@ -60,4 +61,25 @@ export class FeedingsService {
});
return feeding;
}
async update(
id: string,
dto: UpdateFeedingDto,
actingUserId: string,
): Promise<Feeding> {
const before = await this.findById(id);
const feeding = await this.prisma.feeding.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
});
await this.auditLog.record({
entityType: 'Feeding',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: feeding,
});
return feeding;
}
}
@@ -0,0 +1,13 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateHarvestDto } from './create-harvest.dto';
export class UpdateHarvestDto extends PartialType(
PickType(CreateHarvestDto, [
'date',
'honeyType',
'honeySuperCount',
'grossWeight',
'netWeight',
'notes',
] as const),
) {}
@@ -1,10 +1,11 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } 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 { CreateHarvestDto } from './dto/create-harvest.dto';
import { UpdateHarvestDto } from './dto/update-harvest.dto';
import { HarvestsService } from './harvests.service';
@ApiTags('harvests')
@@ -31,4 +32,14 @@ export class HarvestsController {
) {
return this.harvestsService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateHarvestDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.harvestsService.update(id, dto, actor.id);
}
}
@@ -7,7 +7,7 @@ import { WebhooksService } from '../webhooks/webhooks.service';
describe('HarvestsService', () => {
let service: HarvestsService;
let prisma: {
harvest: { findUnique: jest.Mock };
harvest: { findUnique: jest.Mock; update: jest.Mock };
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
@@ -24,7 +24,7 @@ describe('HarvestsService', () => {
harvestColony: { createMany: jest.fn() },
};
prisma = {
harvest: { findUnique: jest.fn() },
harvest: { findUnique: jest.fn(), update: jest.fn() },
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
@@ -65,4 +65,29 @@ describe('HarvestsService', () => {
{ harvestId: harvest.id, colonyId: 'colony-2' },
]);
});
it('update writes an audit log entry with before and after data', async () => {
const updated = { ...harvest, notes: 'geändert' };
prisma.harvest.findUnique
.mockResolvedValueOnce(harvest)
.mockResolvedValueOnce(updated);
prisma.harvest.update.mockResolvedValue(updated);
const result = await service.update(
'harvest-1',
{ notes: 'geändert' },
'user-1',
);
expect(result).toEqual(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'Harvest',
entityId: 'harvest-1',
action: 'UPDATE',
beforeData: harvest,
afterData: updated,
}),
);
});
});
@@ -3,6 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { CreateHarvestDto } from './dto/create-harvest.dto';
import { UpdateHarvestDto } from './dto/update-harvest.dto';
const harvestInclude = {
colonies: { include: { colony: true } },
@@ -67,4 +68,22 @@ export class HarvestsService {
await this.webhooks.dispatch('harvest.created', created);
return created;
}
async update(id: string, dto: UpdateHarvestDto, actingUserId: string) {
const before = await this.findById(id);
await this.prisma.harvest.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
});
const harvest = await this.findById(id);
await this.auditLog.record({
entityType: 'Harvest',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: harvest,
});
return harvest;
}
}
@@ -0,0 +1,27 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateInspectionDto } from './create-inspection.dto';
export class UpdateInspectionDto extends PartialType(
PickType(CreateInspectionDto, [
'date',
'weather',
'temperature',
'colonyStrength',
'broodAmount',
'broodPattern',
'openBroodPresent',
'cappedBroodPresent',
'eggsPresent',
'queenSeen',
'queenCellsPresent',
'swarmMood',
'gentleness',
'combBehavior',
'feedStatus',
'honeySuperStatus',
'healthIssues',
'varroaIssues',
'measures',
'notes',
] as const),
) {}
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Role } from '../../generated/prisma';
import { Roles } from '../auth/decorators/roles.decorator';
@@ -6,6 +6,7 @@ import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { CreateInspectionDto } from './dto/create-inspection.dto';
import { CreateTaskFromInspectionDto } from './dto/create-task-from-inspection.dto';
import { UpdateInspectionDto } from './dto/update-inspection.dto';
import { InspectionsService } from './inspections.service';
@ApiTags('inspections')
@@ -33,6 +34,16 @@ export class InspectionsController {
return this.inspectionsService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateInspectionDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.inspectionsService.update(id, dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Post(':id/create-task')
createTask(
@@ -3,6 +3,7 @@ import { InspectionsService } from './inspections.service';
import { PrismaService } from '../prisma/prisma.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { AutomationService } from '../automation/automation.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('InspectionsService', () => {
let service: InspectionsService;
@@ -11,9 +12,11 @@ describe('InspectionsService', () => {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
task: { create: jest.Mock };
};
let auditLog: { record: jest.Mock };
const inspection = {
id: 'inspection-1',
@@ -27,6 +30,7 @@ describe('InspectionsService', () => {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
task: { create: jest.fn() },
};
@@ -34,10 +38,12 @@ describe('InspectionsService', () => {
const automation = {
evaluateInspection: jest.fn().mockResolvedValue(undefined),
};
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
service = new InspectionsService(
prisma as unknown as PrismaService,
webhooks as unknown as WebhooksService,
automation as unknown as AutomationService,
auditLog as unknown as AuditLogService,
);
});
@@ -63,6 +69,29 @@ describe('InspectionsService', () => {
expect(createArg.data.userId).toBe('user-1');
});
it('update writes an audit log entry with before and after data', async () => {
prisma.inspection.findUnique.mockResolvedValue(inspection);
const updated = { ...inspection, notes: 'geändert' };
prisma.inspection.update.mockResolvedValue(updated);
const result = await service.update(
'inspection-1',
{ notes: 'geändert' },
'user-1',
);
expect(result).toBe(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'Inspection',
entityId: 'inspection-1',
action: 'UPDATE',
beforeData: inspection,
afterData: updated,
}),
);
});
it('createTaskFromInspection links the task to the inspection and its colony', async () => {
prisma.inspection.findUnique.mockResolvedValue(inspection);
prisma.task.create.mockResolvedValue({ id: 'task-1' });
@@ -2,9 +2,11 @@ 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 { AuditLogService } from '../audit/audit-log.service';
import { Inspection, Task } from '../../generated/prisma';
import { CreateInspectionDto } from './dto/create-inspection.dto';
import { CreateTaskFromInspectionDto } from './dto/create-task-from-inspection.dto';
import { UpdateInspectionDto } from './dto/update-inspection.dto';
@Injectable()
export class InspectionsService {
@@ -12,6 +14,7 @@ export class InspectionsService {
private readonly prisma: PrismaService,
private readonly webhooks: WebhooksService,
private readonly automation: AutomationService,
private readonly auditLog: AuditLogService,
) {}
async findAll(): Promise<Inspection[]> {
@@ -47,6 +50,27 @@ export class InspectionsService {
return inspection;
}
async update(
id: string,
dto: UpdateInspectionDto,
actingUserId: string,
): Promise<Inspection> {
const before = await this.findById(id);
const inspection = await this.prisma.inspection.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
});
await this.auditLog.record({
entityType: 'Inspection',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: inspection,
});
return inspection;
}
async createTaskFromInspection(
id: string,
dto: CreateTaskFromInspectionDto,
@@ -0,0 +1,17 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateTreatmentDto } from './create-treatment.dto';
export class UpdateTreatmentDto extends PartialType(
PickType(CreateTreatmentDto, [
'date',
'startDate',
'endDate',
'product',
'activeIngredient',
'amount',
'method',
'reason',
'batchNumber',
'notes',
] as const),
) {}
@@ -1,10 +1,11 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } 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 { CreateTreatmentDto } from './dto/create-treatment.dto';
import { UpdateTreatmentDto } from './dto/update-treatment.dto';
import { TreatmentsService } from './treatments.service';
@ApiTags('treatments')
@@ -31,4 +32,14 @@ export class TreatmentsController {
) {
return this.treatmentsService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateTreatmentDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.treatmentsService.update(id, dto, actor.id);
}
}
@@ -10,6 +10,7 @@ describe('TreatmentsService', () => {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
@@ -26,6 +27,7 @@ describe('TreatmentsService', () => {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
};
auditLog = { record: jest.fn() };
@@ -58,6 +60,29 @@ describe('TreatmentsService', () => {
expect(createArg.data.product).toBe('Ameisensäure');
});
it('update writes an audit log entry with before and after data', async () => {
prisma.treatment.findUnique.mockResolvedValue(treatment);
const updated = { ...treatment, notes: 'geändert' };
prisma.treatment.update.mockResolvedValue(updated);
const result = await service.update(
'treatment-1',
{ notes: 'geändert' },
'user-1',
);
expect(result).toBe(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'Treatment',
entityId: 'treatment-1',
action: 'UPDATE',
beforeData: treatment,
afterData: updated,
}),
);
});
it('findByColony orders results chronologically', async () => {
prisma.treatment.findMany.mockResolvedValue([treatment]);
@@ -3,6 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { Treatment } from '../../generated/prisma';
import { CreateTreatmentDto } from './dto/create-treatment.dto';
import { UpdateTreatmentDto } from './dto/update-treatment.dto';
@Injectable()
export class TreatmentsService {
@@ -52,4 +53,30 @@ export class TreatmentsService {
});
return treatment;
}
async update(
id: string,
dto: UpdateTreatmentDto,
actingUserId: string,
): Promise<Treatment> {
const before = await this.findById(id);
const treatment = await this.prisma.treatment.update({
where: { id },
data: {
...dto,
date: dto.date ? new Date(dto.date) : undefined,
startDate: dto.startDate ? new Date(dto.startDate) : undefined,
endDate: dto.endDate ? new Date(dto.endDate) : undefined,
},
});
await this.auditLog.record({
entityType: 'Treatment',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: treatment,
});
return treatment;
}
}
@@ -0,0 +1,14 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { CreateVarroaMeasurementDto } from './create-varroa-measurement.dto';
export class UpdateVarroaMeasurementDto extends PartialType(
PickType(CreateVarroaMeasurementDto, [
'date',
'method',
'durationMinutes',
'miteCount',
'calculatedValue',
'assessment',
'notes',
] as const),
) {}
@@ -1,10 +1,11 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post } 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 { CreateVarroaMeasurementDto } from './dto/create-varroa-measurement.dto';
import { UpdateVarroaMeasurementDto } from './dto/update-varroa-measurement.dto';
import { VarroaService } from './varroa.service';
@ApiTags('varroa-measurements')
@@ -31,4 +32,14 @@ export class VarroaController {
) {
return this.varroaService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateVarroaMeasurementDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.varroaService.update(id, dto, actor.id);
}
}
@@ -11,9 +11,11 @@ describe('VarroaService', () => {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
let automation: { evaluateVarroaMeasurement: jest.Mock };
const measurement = {
id: 'varroa-1',
@@ -27,10 +29,11 @@ describe('VarroaService', () => {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
};
auditLog = { record: jest.fn() };
const automation = {
automation = {
evaluateVarroaMeasurement: jest.fn().mockResolvedValue(undefined),
};
service = new VarroaService(
@@ -62,6 +65,30 @@ describe('VarroaService', () => {
expect(createArg.data.userId).toBe('user-1');
});
it('update writes an audit log entry and re-evaluates automation', async () => {
prisma.varroaMeasurement.findUnique.mockResolvedValue(measurement);
const updated = { ...measurement, miteCount: 12 };
prisma.varroaMeasurement.update.mockResolvedValue(updated);
const result = await service.update(
'varroa-1',
{ miteCount: 12 },
'user-1',
);
expect(result).toBe(updated);
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'VarroaMeasurement',
entityId: 'varroa-1',
action: 'UPDATE',
beforeData: measurement,
afterData: updated,
}),
);
expect(automation.evaluateVarroaMeasurement).toHaveBeenCalledWith(updated);
});
it('findByColony orders results chronologically', async () => {
prisma.varroaMeasurement.findMany.mockResolvedValue([measurement]);
@@ -4,6 +4,7 @@ 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';
import { UpdateVarroaMeasurementDto } from './dto/update-varroa-measurement.dto';
@Injectable()
export class VarroaService {
@@ -53,4 +54,26 @@ export class VarroaService {
await this.automation.evaluateVarroaMeasurement(measurement);
return measurement;
}
async update(
id: string,
dto: UpdateVarroaMeasurementDto,
actingUserId: string,
): Promise<VarroaMeasurement> {
const before = await this.findById(id);
const measurement = await this.prisma.varroaMeasurement.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
});
await this.auditLog.record({
entityType: 'VarroaMeasurement',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: measurement,
});
await this.automation.evaluateVarroaMeasurement(measurement);
return measurement;
}
}