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

+4
View File
@@ -14,6 +14,8 @@ import { TasksModule } from './tasks/tasks.module';
import { VarroaModule } from './varroa/varroa.module';
import { TreatmentsModule } from './treatments/treatments.module';
import { FeedingsModule } from './feedings/feedings.module';
import { HarvestsModule } from './harvests/harvests.module';
import { ExtractionsModule } from './extractions/extractions.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard';
@@ -33,6 +35,8 @@ import { RolesGuard } from './auth/guards/roles.guard';
VarroaModule,
TreatmentsModule,
FeedingsModule,
HarvestsModule,
ExtractionsModule,
],
controllers: [],
providers: [
@@ -0,0 +1,46 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
ArrayMinSize,
IsArray,
IsDateString,
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
export class CreateExtractionDto {
@ApiProperty()
@IsDateString()
date!: string;
@ApiProperty({ type: [String] })
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
harvestIds!: string[];
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
amount?: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
room?: string;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
waterContent?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
temperature?: 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 { CreateExtractionDto } from './dto/create-extraction.dto';
import { ExtractionsService } from './extractions.service';
@ApiTags('extractions')
@ApiBearerAuth()
@Controller('extractions')
export class ExtractionsController {
constructor(private readonly extractionsService: ExtractionsService) {}
@Get()
findAll() {
return this.extractionsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.extractionsService.findById(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post()
create(
@Body() dto: CreateExtractionDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.extractionsService.create(dto, actor.id);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ExtractionsController } from './extractions.controller';
import { ExtractionsService } from './extractions.service';
@Module({
controllers: [ExtractionsController],
providers: [ExtractionsService],
exports: [ExtractionsService],
})
export class ExtractionsModule {}
@@ -0,0 +1,61 @@
import { NotFoundException } from '@nestjs/common';
import { ExtractionsService } from './extractions.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('ExtractionsService', () => {
let service: ExtractionsService;
let prisma: {
extraction: { findUnique: jest.Mock };
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
let tx: {
extraction: { create: jest.Mock };
extractionHarvest: { createMany: jest.Mock };
};
const extraction = { id: 'extraction-1', date: new Date() };
beforeEach(() => {
tx = {
extraction: { create: jest.fn().mockResolvedValue(extraction) },
extractionHarvest: { createMany: jest.fn() },
};
prisma = {
extraction: { findUnique: jest.fn() },
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
};
auditLog = { record: jest.fn() };
service = new ExtractionsService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.extraction.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create links every harvest to the extraction inside a transaction', async () => {
prisma.extraction.findUnique.mockResolvedValue(extraction);
await service.create(
{ date: '2026-07-05', harvestIds: ['harvest-1', 'harvest-2'] },
'user-1',
);
const [[createArg]] = tx.extractionHarvest.createMany.mock.calls as [
[{ data: { extractionId: string; harvestId: string }[] }],
];
expect(createArg.data).toEqual([
{ extractionId: extraction.id, harvestId: 'harvest-1' },
{ extractionId: extraction.id, harvestId: 'harvest-2' },
]);
});
});
@@ -0,0 +1,69 @@
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';
const extractionInclude = {
harvests: {
include: {
harvest: { include: { colonies: { include: { colony: true } } } },
},
},
} as const;
@Injectable()
export class ExtractionsService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll() {
return this.prisma.extraction.findMany({
include: extractionInclude,
orderBy: { date: 'desc' },
});
}
async findById(id: string) {
const extraction = await this.prisma.extraction.findUnique({
where: { id },
include: extractionInclude,
});
if (!extraction) {
throw new NotFoundException('Extraction not found');
}
return extraction;
}
async create(dto: CreateExtractionDto, actingUserId: string) {
const extraction = await this.prisma.$transaction(async (tx) => {
const created = await tx.extraction.create({
data: {
date: new Date(dto.date),
amount: dto.amount,
room: dto.room,
waterContent: dto.waterContent,
temperature: dto.temperature,
notes: dto.notes,
userId: actingUserId,
},
});
await tx.extractionHarvest.createMany({
data: dto.harvestIds.map((harvestId) => ({
extractionId: created.id,
harvestId,
})),
});
return created;
});
await this.auditLog.record({
entityType: 'Extraction',
entityId: extraction.id,
action: 'CREATE',
userId: actingUserId,
afterData: extraction,
});
return this.findById(extraction.id);
}
}
@@ -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);
}
}