feat(backend): Ernten- und Schleuderungs-Module (Modul 10)

HarvestsModule und ExtractionsModule als Fundament der
Rückverfolgbarkeitskette: eine Ernte kann mehrere Völker umfassen,
eine Schleuderung mehrere Ernten zusammenführen.
This commit is contained in:
Nick Szaunig committed 2026-08-22 00:25:36 +02:00
1 parent d71785d531
commit 340397b34d
14 files changed
+705 -1

No files matched your search

@@ -0,0 +1,51 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
ArrayMinSize,
IsArray,
IsDateString,
IsInt,
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
export class CreateHarvestDto {
@ApiProperty()
@IsString()
apiaryId!: string;
@ApiProperty()
@IsDateString()
date!: string;
@ApiProperty({ type: [String] })
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
colonyIds!: string[];
@ApiPropertyOptional()
@IsOptional()
@IsString()
honeyType?: string;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
honeySuperCount?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
grossWeight?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
netWeight?: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,34 @@
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 { CreateHarvestDto } from './dto/create-harvest.dto';
import { HarvestsService } from './harvests.service';
@ApiTags('harvests')
@ApiBearerAuth()
@Controller('harvests')
export class HarvestsController {
constructor(private readonly harvestsService: HarvestsService) {}
@Get()
findAll() {
return this.harvestsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.harvestsService.findById(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Post()
create(
@Body() dto: CreateHarvestDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.harvestsService.create(dto, actor.id);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { HarvestsController } from './harvests.controller';
import { HarvestsService } from './harvests.service';
@Module({
controllers: [HarvestsController],
providers: [HarvestsService],
exports: [HarvestsService],
})
export class HarvestsModule {}
@@ -0,0 +1,65 @@
import { NotFoundException } from '@nestjs/common';
import { HarvestsService } from './harvests.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('HarvestsService', () => {
let service: HarvestsService;
let prisma: {
harvest: { findUnique: jest.Mock };
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
let tx: {
harvest: { create: jest.Mock };
harvestColony: { createMany: jest.Mock };
};
const harvest = { id: 'harvest-1', apiaryId: 'apiary-1', date: new Date() };
beforeEach(() => {
tx = {
harvest: { create: jest.fn().mockResolvedValue(harvest) },
harvestColony: { createMany: jest.fn() },
};
prisma = {
harvest: { findUnique: jest.fn() },
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
};
auditLog = { record: jest.fn() };
service = new HarvestsService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.harvest.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create links every colony to the harvest inside a transaction', async () => {
prisma.harvest.findUnique.mockResolvedValue(harvest);
await service.create(
{
apiaryId: 'apiary-1',
date: '2026-07-01',
colonyIds: ['colony-1', 'colony-2'],
},
'user-1',
);
const [[createArg]] = tx.harvestColony.createMany.mock.calls as [
[{ data: { harvestId: string; colonyId: string }[] }],
];
expect(createArg.data).toEqual([
{ harvestId: harvest.id, colonyId: 'colony-1' },
{ harvestId: harvest.id, colonyId: 'colony-2' },
]);
});
});
@@ -0,0 +1,66 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { CreateHarvestDto } from './dto/create-harvest.dto';
const harvestInclude = {
colonies: { include: { colony: true } },
} as const;
@Injectable()
export class HarvestsService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll() {
return this.prisma.harvest.findMany({
include: harvestInclude,
orderBy: { date: 'desc' },
});
}
async findById(id: string) {
const harvest = await this.prisma.harvest.findUnique({
where: { id },
include: harvestInclude,
});
if (!harvest) {
throw new NotFoundException('Harvest not found');
}
return harvest;
}
async create(dto: CreateHarvestDto, actingUserId: string) {
const harvest = await this.prisma.$transaction(async (tx) => {
const created = await tx.harvest.create({
data: {
apiaryId: dto.apiaryId,
date: new Date(dto.date),
honeyType: dto.honeyType,
honeySuperCount: dto.honeySuperCount,
grossWeight: dto.grossWeight,
netWeight: dto.netWeight,
notes: dto.notes,
userId: actingUserId,
},
});
await tx.harvestColony.createMany({
data: dto.colonyIds.map((colonyId) => ({
harvestId: created.id,
colonyId,
})),
});
return created;
});
await this.auditLog.record({
entityType: 'Harvest',
entityId: harvest.id,
action: 'CREATE',
userId: actingUserId,
afterData: harvest,
});
return this.findById(harvest.id);
}
}