feat(backend): Abfuellungen und Produkte (Modul 23)

ProductsModule (GET/POST /products, GET/PATCH /products/:id) und
BottlingModule (GET/POST /bottling-batches) mit transaktionaler
Reduzierung der HoneyBatch-Restmenge beim Abfuellen; Ablehnung bei
Abfuellmenge > verfuegbarer Menge. Neue Prisma-Modelle Product und
BottlingBatch (Migration bottling_products).
This commit is contained in:
Nick Szaunig committed 2026-08-22 11:08:09 +02:00
1 parent 8b7fd61c1c
commit e82cae257b
17 files changed
+916 -2

No files matched your search

@@ -0,0 +1,34 @@
import { Body, Controller, Get, Param, 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 { BottlingService } from './bottling.service';
@ApiTags('bottling')
@ApiBearerAuth()
@Controller('bottling-batches')
export class BottlingController {
constructor(private readonly bottlingService: BottlingService) {}
@Get()
findAll(@Query('honeyBatchId') honeyBatchId?: string) {
return this.bottlingService.findAll({ honeyBatchId });
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.bottlingService.findById(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post()
create(
@Body() dto: CreateBottlingBatchDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.bottlingService.create(dto, actor.id);
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { BottlingController } from './bottling.controller';
import { BottlingService } from './bottling.service';
@Module({
controllers: [BottlingController],
providers: [BottlingService],
})
export class BottlingModule {}
@@ -0,0 +1,124 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { BottlingService } from './bottling.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('BottlingService', () => {
let service: BottlingService;
let prisma: {
honeyBatch: { findUnique: jest.Mock; update: jest.Mock };
product: { findUnique: jest.Mock };
bottlingBatch: {
findUnique: jest.Mock;
findMany: jest.Mock;
create: jest.Mock;
};
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
let tx: {
bottlingBatch: { create: jest.Mock };
honeyBatch: { update: jest.Mock };
};
beforeEach(() => {
tx = {
bottlingBatch: { create: jest.fn() },
honeyBatch: { update: jest.fn() },
};
prisma = {
honeyBatch: { findUnique: jest.fn(), update: jest.fn() },
product: { findUnique: jest.fn() },
bottlingBatch: {
findUnique: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
},
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
};
auditLog = { record: jest.fn() };
service = new BottlingService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('throws NotFoundException when the honey batch does not exist', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce(null);
await expect(
service.create(
{
honeyBatchId: 'missing',
date: '2026-01-01',
jarSize: 500,
jarCount: 10,
bestBeforeDate: '2027-01-01',
lotNumber: 'L-1',
},
'user-1',
),
).rejects.toBeInstanceOf(NotFoundException);
});
it('rejects when the bottled amount exceeds the available honey batch amount', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({
id: 'h1',
amount: 5,
});
await expect(
service.create(
{
honeyBatchId: 'h1',
date: '2026-01-01',
jarSize: 500,
jarCount: 20,
bestBeforeDate: '2027-01-01',
lotNumber: 'L-1',
},
'user-1',
),
).rejects.toBeInstanceOf(BadRequestException);
});
it('creates a bottling batch and reduces the honey batch amount transactionally', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({
id: 'h1',
amount: 25,
});
tx.bottlingBatch.create.mockResolvedValueOnce({
id: 'b1',
totalAmount: 25,
});
prisma.bottlingBatch.findUnique.mockResolvedValueOnce({
id: 'b1',
totalAmount: 25,
});
const result = await service.create(
{
honeyBatchId: 'h1',
date: '2026-01-01',
jarSize: 500,
jarCount: 50,
bestBeforeDate: '2027-01-01',
lotNumber: 'L-1',
},
'user-1',
);
expect(result).toEqual({ id: 'b1', totalAmount: 25 });
expect(tx.honeyBatch.update).toHaveBeenCalledWith({
where: { id: 'h1' },
data: { amount: 0, status: 'BOTTLED' },
});
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'BottlingBatch',
action: 'CREATE',
}),
);
});
});
@@ -0,0 +1,108 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { BottlingBatch } from '../../generated/prisma';
import { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
const bottlingBatchInclude = {
honeyBatch: true,
product: true,
} as const;
export interface BottlingBatchFilter {
honeyBatchId?: string;
}
@Injectable()
export class BottlingService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll(filter: BottlingBatchFilter = {}) {
return this.prisma.bottlingBatch.findMany({
where: { honeyBatchId: filter.honeyBatchId },
include: bottlingBatchInclude,
orderBy: { date: 'desc' },
});
}
async findById(id: string) {
const bottlingBatch = await this.prisma.bottlingBatch.findUnique({
where: { id },
include: bottlingBatchInclude,
});
if (!bottlingBatch) {
throw new NotFoundException('Bottling batch not found');
}
return bottlingBatch;
}
async create(dto: CreateBottlingBatchDto, actingUserId: string) {
const honeyBatch = await this.prisma.honeyBatch.findUnique({
where: { id: dto.honeyBatchId },
});
if (!honeyBatch) {
throw new NotFoundException('Honey batch not found');
}
if (dto.productId) {
const product = await this.prisma.product.findUnique({
where: { id: dto.productId },
});
if (!product) {
throw new NotFoundException('Product not found');
}
}
const totalAmount = (dto.jarSize * dto.jarCount) / 1000;
if (honeyBatch.amount !== null && totalAmount > honeyBatch.amount) {
throw new BadRequestException(
'Abfüllmenge übersteigt die verfügbare Menge der Honigcharge',
);
}
const bottlingBatch: BottlingBatch = await this.prisma.$transaction(
async (tx) => {
const created = await tx.bottlingBatch.create({
data: {
honeyBatchId: dto.honeyBatchId,
productId: dto.productId,
date: new Date(dto.date),
jarSize: dto.jarSize,
jarCount: dto.jarCount,
totalAmount,
bestBeforeDate: new Date(dto.bestBeforeDate),
lotNumber: dto.lotNumber,
userId: actingUserId,
},
});
await tx.honeyBatch.update({
where: { id: dto.honeyBatchId },
data: {
amount:
honeyBatch.amount !== null
? honeyBatch.amount - totalAmount
: null,
status: 'BOTTLED',
},
});
return created;
},
);
await this.auditLog.record({
entityType: 'BottlingBatch',
entityId: bottlingBatch.id,
action: 'CREATE',
userId: actingUserId,
afterData: bottlingBatch,
});
return this.findById(bottlingBatch.id);
}
}
@@ -0,0 +1,42 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDateString,
IsInt,
IsNumber,
IsOptional,
IsPositive,
IsString,
} from 'class-validator';
export class CreateBottlingBatchDto {
@ApiProperty()
@IsString()
honeyBatchId!: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
productId?: string;
@ApiProperty()
@IsDateString()
date!: string;
@ApiProperty({ description: 'Glasgröße in Gramm' })
@IsNumber()
@IsPositive()
jarSize!: number;
@ApiProperty()
@IsInt()
@IsPositive()
jarCount!: number;
@ApiProperty()
@IsDateString()
bestBeforeDate!: string;
@ApiProperty()
@IsString()
lotNumber!: string;
}