From e52a6057a297fca542a43b02466dcd9064ee1b6d Mon Sep 17 00:00:00 2001 From: Nick Szaunig Date: Tue, 6 Oct 2026 00:02:35 +0200 Subject: [PATCH] Bestandsabgleich umgesetzt --- .../dto/create-raw-material-lot.dto.ts | 49 ++++++ .../dto/update-raw-material-lot.dto.ts | 54 +++++++ .../raw-materials/raw-materials.controller.ts | 105 +++++++++++++ .../src/raw-materials/raw-materials.module.ts | 11 ++ .../raw-materials/raw-materials.service.ts | 147 ++++++++++++++++++ 5 files changed, 366 insertions(+) create mode 100644 ApiCore-Frontend/src/raw-materials/dto/create-raw-material-lot.dto.ts create mode 100644 ApiCore-Frontend/src/raw-materials/dto/update-raw-material-lot.dto.ts create mode 100644 ApiCore-Frontend/src/raw-materials/raw-materials.controller.ts create mode 100644 ApiCore-Frontend/src/raw-materials/raw-materials.module.ts create mode 100644 ApiCore-Frontend/src/raw-materials/raw-materials.service.ts diff --git a/ApiCore-Frontend/src/raw-materials/dto/create-raw-material-lot.dto.ts b/ApiCore-Frontend/src/raw-materials/dto/create-raw-material-lot.dto.ts new file mode 100644 index 0000000..194a265 --- /dev/null +++ b/ApiCore-Frontend/src/raw-materials/dto/create-raw-material-lot.dto.ts @@ -0,0 +1,49 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { + IsDateString, + IsEnum, + IsInt, + IsNotEmpty, + IsOptional, + IsPositive, + IsString, + MaxLength, +} from 'class-validator'; +import { RawMaterialKind } from '../../../generated/prisma'; + +export class CreateRawMaterialLotDto { + @ApiProperty({ enum: RawMaterialKind }) + @IsEnum(RawMaterialKind) + kind!: RawMaterialKind; + + @ApiProperty() + @IsString() + @IsNotEmpty() + @MaxLength(100) + lotNumber!: string; + + @ApiProperty({ description: 'Gewinnungsdatum' }) + @IsDateString() + date!: string; + + @ApiProperty({ description: 'Gewonnene Menge in Gramm' }) + @IsInt() + @IsPositive() + quantity!: number; + + @ApiPropertyOptional({ description: 'Stand, von dem der Rohstoff stammt' }) + @IsOptional() + @IsString() + apiaryId?: string; + + @ApiPropertyOptional({ description: 'Ernte, bei der er anfiel (z. B. Entdeckelungswachs)' }) + @IsOptional() + @IsString() + harvestId?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MaxLength(2000) + notes?: string; +} diff --git a/ApiCore-Frontend/src/raw-materials/dto/update-raw-material-lot.dto.ts b/ApiCore-Frontend/src/raw-materials/dto/update-raw-material-lot.dto.ts new file mode 100644 index 0000000..1472f65 --- /dev/null +++ b/ApiCore-Frontend/src/raw-materials/dto/update-raw-material-lot.dto.ts @@ -0,0 +1,54 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { + IsDateString, + IsInt, + IsNotEmpty, + IsOptional, + IsPositive, + IsString, + MaxLength, + ValidateIf, +} from 'class-validator'; + +/** + * Corrects a raw material lot entered with a typo. The kind stays fixed - + * wax that went into candles does not turn into propolis afterwards. + * `apiaryId: null` / `harvestId: null` remove the origin. + */ +export class UpdateRawMaterialLotDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + @IsNotEmpty() + @MaxLength(100) + lotNumber?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsDateString() + date?: string; + + @ApiPropertyOptional({ description: 'Gewonnene Menge in Gramm' }) + @IsOptional() + @IsInt() + @IsPositive() + quantity?: number; + + @ApiPropertyOptional({ nullable: true }) + @IsOptional() + @ValidateIf((_object, value) => value !== null) + @IsString() + apiaryId?: string | null; + + @ApiPropertyOptional({ nullable: true }) + @IsOptional() + @ValidateIf((_object, value) => value !== null) + @IsString() + harvestId?: string | null; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MaxLength(2000) + notes?: string; +} diff --git a/ApiCore-Frontend/src/raw-materials/raw-materials.controller.ts b/ApiCore-Frontend/src/raw-materials/raw-materials.controller.ts new file mode 100644 index 0000000..4930991 --- /dev/null +++ b/ApiCore-Frontend/src/raw-materials/raw-materials.controller.ts @@ -0,0 +1,105 @@ +import { + Body, + Controller, + Delete, + Get, + Param, + Patch, + Post, + Query, +} from '@nestjs/common'; +import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { RequirePermission } from '../auth/decorators/require-permission.decorator'; +import { CurrentUser } from '../auth/decorators/current-user.decorator'; +import type { AuthenticatedUser } from '../auth/types/authenticated-user'; +import { Idempotent } from '../common/idempotency/idempotent.decorator'; +import { StockService } from '../stock/stock.service'; +import { WithdrawStockDto } from '../stock/dto/withdraw-stock.dto'; +import { CorrectStockDto } from '../stock/dto/correct-stock.dto'; +import { RawMaterialKind } from '../../generated/prisma'; +import { CreateRawMaterialLotDto } from './dto/create-raw-material-lot.dto'; +import { UpdateRawMaterialLotDto } from './dto/update-raw-material-lot.dto'; +import { RawMaterialsService } from './raw-materials.service'; + +const KINDS = Object.values(RawMaterialKind) as string[]; + +@ApiTags('raw-materials') +@ApiBearerAuth() +@Controller('raw-material-lots') +export class RawMaterialsController { + constructor( + private readonly lots: RawMaterialsService, + private readonly stock: StockService, + ) {} + + @RequirePermission('raw-material:read') + @Get() + findAll(@Query('kind') kind?: string) { + return this.lots.findAll({ + kind: kind && KINDS.includes(kind) ? (kind as RawMaterialKind) : undefined, + }); + } + + @RequirePermission('raw-material:read') + @Get(':id') + findOne(@Param('id') id: string) { + return this.lots.findById(id); + } + + @RequirePermission('raw-material:read') + @Get(':id/stock') + async stockOf(@Param('id') id: string) { + await this.lots.findById(id); + return this.stock.stockOf({ kind: 'raw', id }); + } + + @RequirePermission('raw-material:create') + @Idempotent() + @Post() + create( + @Body() dto: CreateRawMaterialLotDto, + @CurrentUser() actor: AuthenticatedUser, + ) { + return this.lots.create(dto, actor.id); + } + + @RequirePermission('raw-material:withdraw') + @Idempotent() + @Post(':id/withdrawals') + async withdraw( + @Param('id') id: string, + @Body() dto: WithdrawStockDto, + @CurrentUser() actor: AuthenticatedUser, + ) { + await this.lots.findById(id); + return this.stock.withdraw({ kind: 'raw', id }, dto, actor.id); + } + + @RequirePermission('raw-material:withdraw') + @Idempotent() + @Post(':id/corrections') + async correct( + @Param('id') id: string, + @Body() dto: CorrectStockDto, + @CurrentUser() actor: AuthenticatedUser, + ) { + await this.lots.findById(id); + return this.stock.correct({ kind: 'raw', id }, dto, actor.id); + } + + @RequirePermission('raw-material:update') + @Patch(':id') + update( + @Param('id') id: string, + @Body() dto: UpdateRawMaterialLotDto, + @CurrentUser() actor: AuthenticatedUser, + ) { + return this.lots.update(id, dto, actor.id); + } + + @RequirePermission('raw-material:delete') + @Delete(':id') + remove(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) { + return this.lots.remove(id, actor.id); + } +} diff --git a/ApiCore-Frontend/src/raw-materials/raw-materials.module.ts b/ApiCore-Frontend/src/raw-materials/raw-materials.module.ts new file mode 100644 index 0000000..33e2584 --- /dev/null +++ b/ApiCore-Frontend/src/raw-materials/raw-materials.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { StockModule } from '../stock/stock.module'; +import { RawMaterialsController } from './raw-materials.controller'; +import { RawMaterialsService } from './raw-materials.service'; + +@Module({ + imports: [StockModule], + controllers: [RawMaterialsController], + providers: [RawMaterialsService], +}) +export class RawMaterialsModule {} diff --git a/ApiCore-Frontend/src/raw-materials/raw-materials.service.ts b/ApiCore-Frontend/src/raw-materials/raw-materials.service.ts new file mode 100644 index 0000000..2c37b77 --- /dev/null +++ b/ApiCore-Frontend/src/raw-materials/raw-materials.service.ts @@ -0,0 +1,147 @@ +import { + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { AuditLogService } from '../audit/audit-log.service'; +import { StockService } from '../stock/stock.service'; +import { RawMaterialKind } from '../../generated/prisma'; +import { CreateRawMaterialLotDto } from './dto/create-raw-material-lot.dto'; +import { UpdateRawMaterialLotDto } from './dto/update-raw-material-lot.dto'; + +const include = { + apiary: { select: { id: true, name: true } }, + harvest: { select: { id: true, date: true } }, + // Forward traceability: which production batches this lot went into. + usedIn: { + select: { + id: true, + quantity: true, + productionBatch: { + select: { + id: true, + lotNumber: true, + product: { select: { id: true, name: true } }, + }, + }, + }, + orderBy: { createdAt: 'desc' as const }, + }, +} as const; + +export interface RawMaterialLotFilter { + kind?: RawMaterialKind; +} + +/** + * Raw material lots (beeswax, propolis) in grams. Their stock lives in the + * same movement ledger as bottlings and production batches: withdrawals and + * inventory counts by hand, consumption when a production batch is made. + */ +@Injectable() +export class RawMaterialsService { + constructor( + private readonly prisma: PrismaService, + private readonly auditLog: AuditLogService, + private readonly stock: StockService, + ) {} + + async findAll(filter: RawMaterialLotFilter = {}) { + const lots = await this.prisma.rawMaterialLot.findMany({ + where: { kind: filter.kind }, + include, + orderBy: { date: 'desc' }, + }); + const remaining = await this.stock.remainingByRawMaterialLot( + lots.map((lot) => lot.id), + ); + return lots.map((lot) => ({ + ...lot, + remainingCount: remaining.get(lot.id) ?? lot.quantity, + })); + } + + async findById(id: string) { + const lot = await this.prisma.rawMaterialLot.findUnique({ + where: { id }, + include, + }); + if (!lot) throw new NotFoundException('Raw material lot not found'); + const remaining = await this.stock.remainingByRawMaterialLot([id]); + return { ...lot, remainingCount: remaining.get(id) ?? lot.quantity }; + } + + async create(dto: CreateRawMaterialLotDto, actingUserId: string) { + // A duplicate lotNumber surfaces as P2002 and becomes a 409 in + // AllExceptionsFilter; an unknown apiary/harvest as a foreign-key error. + const lot = await this.prisma.rawMaterialLot.create({ + data: { + kind: dto.kind, + lotNumber: dto.lotNumber, + date: new Date(dto.date), + quantity: dto.quantity, + apiaryId: dto.apiaryId, + harvestId: dto.harvestId, + notes: dto.notes, + userId: actingUserId, + }, + }); + await this.auditLog.record({ + entityType: 'RawMaterialLot', + entityId: lot.id, + action: 'CREATE', + userId: actingUserId, + afterData: lot, + }); + return this.findById(lot.id); + } + + async update( + id: string, + dto: UpdateRawMaterialLotDto, + actingUserId: string, + ) { + const before = await this.findById(id); + await this.prisma.rawMaterialLot.update({ + where: { id }, + data: { + lotNumber: dto.lotNumber, + date: dto.date ? new Date(dto.date) : undefined, + quantity: dto.quantity, + apiaryId: dto.apiaryId, + harvestId: dto.harvestId, + notes: dto.notes, + }, + }); + const after = await this.findById(id); + await this.auditLog.record({ + entityType: 'RawMaterialLot', + entityId: id, + action: 'UPDATE', + userId: actingUserId, + beforeData: before, + afterData: after, + }); + return after; + } + + /** Only for lots entered by mistake: once anything was booked, it stays. */ + async remove(id: string, actingUserId: string) { + const before = await this.findById(id); + if (await this.stock.hasMovements({ kind: 'raw', id })) { + throw new ConflictException( + 'Rohstoff-Charge hat bereits Bewegungen (Verbrauch, Entnahme oder Inventur) und kann nicht gelöscht werden', + ); + } + await this.prisma.rawMaterialLot.delete({ where: { id } }); + await this.auditLog.record({ + entityType: 'RawMaterialLot', + entityId: id, + action: 'DELETE', + userId: actingUserId, + beforeData: before, + }); + return { id }; + } +}