feat(backend): Honigchargen-Modul (Modul 11)

HoneyBatchesModule inkl. Honigmessungen und
Rückverfolgbarkeits-Endpunkt, der eine Charge über die Schleuderung
und Ernte bis zu den Ursprungsvölkern zurückverfolgt.
This commit is contained in:
Nick Szaunig committed 2026-08-22 00:37:09 +02:00
1 parent 5c2c0608d1
commit cf625552d1
9 files changed
+474 -1

No files matched your search

@@ -0,0 +1,32 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNumber, IsOptional, IsString } from 'class-validator';
export class CreateHoneyBatchDto {
@ApiProperty()
@IsString()
batchNumber!: string;
@ApiProperty()
@IsString()
extractionId!: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
honeyType?: string;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
amount?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
waterContent?: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
storageContainerId?: string;
}
@@ -0,0 +1,27 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsNumber, IsOptional, IsString } from 'class-validator';
export class CreateHoneyMeasurementDto {
@ApiProperty()
@IsNumber()
waterContent!: number;
@ApiProperty()
@IsDateString()
measuredAt!: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
device?: string;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
temperature?: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,50 @@
import { Body, Controller, Get, Param, 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 { CreateHoneyBatchDto } from './dto/create-honey-batch.dto';
import { CreateHoneyMeasurementDto } from './dto/create-honey-measurement.dto';
import { HoneyBatchesService } from './honey-batches.service';
@ApiTags('honey-batches')
@ApiBearerAuth()
@Controller('honey-batches')
export class HoneyBatchesController {
constructor(private readonly honeyBatchesService: HoneyBatchesService) {}
@Get()
findAll() {
return this.honeyBatchesService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.honeyBatchesService.findById(id);
}
@Get(':id/traceability')
traceability(@Param('id') id: string) {
return this.honeyBatchesService.traceability(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post()
create(
@Body() dto: CreateHoneyBatchDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.honeyBatchesService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post(':id/measurements')
addMeasurement(
@Param('id') id: string,
@Body() dto: CreateHoneyMeasurementDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.honeyBatchesService.addMeasurement(id, dto, actor.id);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { HoneyBatchesController } from './honey-batches.controller';
import { HoneyBatchesService } from './honey-batches.service';
@Module({
controllers: [HoneyBatchesController],
providers: [HoneyBatchesService],
exports: [HoneyBatchesService],
})
export class HoneyBatchesModule {}
@@ -0,0 +1,98 @@
import { NotFoundException } from '@nestjs/common';
import { HoneyBatchesService } from './honey-batches.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('HoneyBatchesService', () => {
let service: HoneyBatchesService;
let prisma: {
honeyBatch: {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
};
honeyMeasurement: { create: jest.Mock };
};
let auditLog: { record: jest.Mock };
const extraction = {
id: 'extraction-1',
date: new Date(),
room: 'Raum 1',
harvests: [
{
harvest: {
id: 'harvest-1',
date: new Date(),
apiaryId: 'apiary-1',
colonies: [{ colony: { id: 'colony-1', code: 'V-001' } }],
},
},
],
};
const honeyBatch = {
id: 'batch-1',
batchNumber: 'HC-2026-001',
honeyType: 'Blütenhonig',
amount: 20,
status: 'RAW',
measurements: [],
extraction,
};
beforeEach(() => {
prisma = {
honeyBatch: {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
},
honeyMeasurement: { create: jest.fn() },
};
auditLog = { record: jest.fn() };
service = new HoneyBatchesService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.honeyBatch.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create stores the batch and returns it with relations', async () => {
prisma.honeyBatch.create.mockResolvedValue(honeyBatch);
prisma.honeyBatch.findUnique.mockResolvedValue(honeyBatch);
await service.create(
{ batchNumber: 'HC-2026-001', extractionId: 'extraction-1' },
'user-1',
);
const [[createArg]] = prisma.honeyBatch.create.mock.calls as [
[{ data: { batchNumber: string; extractionId: string } }],
];
expect(createArg.data.batchNumber).toBe('HC-2026-001');
expect(createArg.data.extractionId).toBe('extraction-1');
});
it('traceability flattens the extraction, harvest, and colony chain', async () => {
prisma.honeyBatch.findUnique.mockResolvedValue(honeyBatch);
const result = await service.traceability('batch-1');
expect(result.honeyBatch.batchNumber).toBe('HC-2026-001');
expect(result.extraction.id).toBe('extraction-1');
expect(result.harvests).toEqual([
{
id: 'harvest-1',
date: extraction.harvests[0].harvest.date,
apiaryId: 'apiary-1',
colonies: [{ id: 'colony-1', code: 'V-001' }],
},
]);
});
});
@@ -0,0 +1,109 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { CreateHoneyBatchDto } from './dto/create-honey-batch.dto';
import { CreateHoneyMeasurementDto } from './dto/create-honey-measurement.dto';
const honeyBatchInclude = {
measurements: true,
extraction: {
include: {
harvests: {
include: {
harvest: { include: { colonies: { include: { colony: true } } } },
},
},
},
},
} as const;
@Injectable()
export class HoneyBatchesService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll() {
return this.prisma.honeyBatch.findMany({
include: honeyBatchInclude,
orderBy: { createdAt: 'desc' },
});
}
async findById(id: string) {
const honeyBatch = await this.prisma.honeyBatch.findUnique({
where: { id },
include: honeyBatchInclude,
});
if (!honeyBatch) {
throw new NotFoundException('Honey batch not found');
}
return honeyBatch;
}
async create(dto: CreateHoneyBatchDto, actingUserId: string) {
const honeyBatch = await this.prisma.honeyBatch.create({
data: { ...dto },
});
await this.auditLog.record({
entityType: 'HoneyBatch',
entityId: honeyBatch.id,
action: 'CREATE',
userId: actingUserId,
afterData: honeyBatch,
});
return this.findById(honeyBatch.id);
}
async addMeasurement(
id: string,
dto: CreateHoneyMeasurementDto,
actingUserId: string,
) {
await this.findById(id);
const measurement = await this.prisma.honeyMeasurement.create({
data: {
...dto,
measuredAt: new Date(dto.measuredAt),
honeyBatchId: id,
userId: actingUserId,
},
});
await this.auditLog.record({
entityType: 'HoneyMeasurement',
entityId: measurement.id,
action: 'CREATE',
userId: actingUserId,
afterData: measurement,
});
return this.findById(id);
}
async traceability(id: string) {
const honeyBatch = await this.findById(id);
return {
honeyBatch: {
id: honeyBatch.id,
batchNumber: honeyBatch.batchNumber,
honeyType: honeyBatch.honeyType,
amount: honeyBatch.amount,
status: honeyBatch.status,
},
extraction: {
id: honeyBatch.extraction.id,
date: honeyBatch.extraction.date,
room: honeyBatch.extraction.room,
},
harvests: honeyBatch.extraction.harvests.map((entry) => ({
id: entry.harvest.id,
date: entry.harvest.date,
apiaryId: entry.harvest.apiaryId,
colonies: entry.harvest.colonies.map((hc) => ({
id: hc.colony.id,
code: hc.colony.code,
})),
})),
};
}
}