feat(backend): Fütterungen-Modul (Modul 9)

FeedingsModule mit Erfassung, Colony-Historie und
Mengensummen-Endpunkt je Einheit.
This commit is contained in:
Nick Szaunig committed 2026-08-22 00:14:41 +02:00
1 parent 1f71ac9e3c
commit cc0aaf0a31
9 files changed
+382 -1

No files matched your search

+2
View File
@@ -13,6 +13,7 @@ import { InspectionsModule } from './inspections/inspections.module';
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 { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard';
@@ -31,6 +32,7 @@ import { RolesGuard } from './auth/guards/roles.guard';
TasksModule,
VarroaModule,
TreatmentsModule,
FeedingsModule,
],
controllers: [],
providers: [
@@ -0,0 +1,20 @@
import { Controller, Get, Param } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { FeedingsService } from './feedings.service';
@ApiTags('feedings')
@ApiBearerAuth()
@Controller('colonies')
export class ColonyFeedingsController {
constructor(private readonly feedingsService: FeedingsService) {}
@Get(':id/feedings')
findByColony(@Param('id') id: string) {
return this.feedingsService.findByColony(id);
}
@Get(':id/feedings/summary')
summaryByColony(@Param('id') id: string) {
return this.feedingsService.summaryByColony(id);
}
}
@@ -0,0 +1,46 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDateString,
IsEnum,
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
import { FeedType } from '../../../generated/prisma';
export class CreateFeedingDto {
@ApiProperty()
@IsString()
colonyId!: string;
@ApiProperty()
@IsDateString()
date!: string;
@ApiProperty({ enum: FeedType })
@IsEnum(FeedType)
feedType!: FeedType;
@ApiPropertyOptional()
@IsOptional()
@IsString()
product?: string;
@ApiProperty()
@IsNumber()
amount!: number;
@ApiProperty()
@IsString()
unit!: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
batchNumber?: string;
@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 { CreateFeedingDto } from './dto/create-feeding.dto';
import { FeedingsService } from './feedings.service';
@ApiTags('feedings')
@ApiBearerAuth()
@Controller('feedings')
export class FeedingsController {
constructor(private readonly feedingsService: FeedingsService) {}
@Get()
findAll() {
return this.feedingsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.feedingsService.findById(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER, Role.STAFF)
@Post()
create(
@Body() dto: CreateFeedingDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.feedingsService.create(dto, actor.id);
}
}
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { FeedingsController } from './feedings.controller';
import { ColonyFeedingsController } from './colony-feedings.controller';
import { FeedingsService } from './feedings.service';
@Module({
controllers: [FeedingsController, ColonyFeedingsController],
providers: [FeedingsService],
exports: [FeedingsService],
})
export class FeedingsModule {}
@@ -0,0 +1,73 @@
import { NotFoundException } from '@nestjs/common';
import { FeedingsService } from './feedings.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('FeedingsService', () => {
let service: FeedingsService;
let prisma: {
feeding: {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
groupBy: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
const feeding = { id: 'feeding-1', colonyId: 'colony-1', date: new Date() };
beforeEach(() => {
prisma = {
feeding: {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
groupBy: jest.fn(),
},
};
auditLog = { record: jest.fn() };
service = new FeedingsService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.feeding.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create stores the acting user as the feeder', async () => {
prisma.feeding.create.mockResolvedValue(feeding);
await service.create(
{
colonyId: 'colony-1',
date: '2026-01-01',
feedType: 'SUGAR_WATER',
amount: 2,
unit: 'l',
},
'user-1',
);
const [[createArg]] = prisma.feeding.create.mock.calls as [
[{ data: { colonyId: string; userId: string } }],
];
expect(createArg.data.colonyId).toBe('colony-1');
expect(createArg.data.userId).toBe('user-1');
});
it('summaryByColony sums amounts per unit', async () => {
prisma.feeding.groupBy.mockResolvedValue([
{ unit: 'l', _sum: { amount: 5.5 } },
]);
const summary = await service.summaryByColony('colony-1');
expect(summary).toEqual([{ unit: 'l', totalAmount: 5.5 }]);
});
});
@@ -0,0 +1,63 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { Feeding } from '../../generated/prisma';
import { CreateFeedingDto } from './dto/create-feeding.dto';
export interface FeedingSummaryEntry {
unit: string;
totalAmount: number;
}
@Injectable()
export class FeedingsService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll(): Promise<Feeding[]> {
return this.prisma.feeding.findMany({ orderBy: { date: 'desc' } });
}
async findById(id: string): Promise<Feeding> {
const feeding = await this.prisma.feeding.findUnique({ where: { id } });
if (!feeding) {
throw new NotFoundException('Feeding not found');
}
return feeding;
}
async findByColony(colonyId: string): Promise<Feeding[]> {
return this.prisma.feeding.findMany({
where: { colonyId },
orderBy: { date: 'asc' },
});
}
async summaryByColony(colonyId: string): Promise<FeedingSummaryEntry[]> {
const grouped = await this.prisma.feeding.groupBy({
by: ['unit'],
where: { colonyId },
_sum: { amount: true },
});
return grouped.map((entry) => ({
unit: entry.unit,
totalAmount: entry._sum.amount ?? 0,
}));
}
async create(dto: CreateFeedingDto, actingUserId: string): Promise<Feeding> {
const feeding = await this.prisma.feeding.create({
data: { ...dto, date: new Date(dto.date), userId: actingUserId },
});
await this.auditLog.record({
entityType: 'Feeding',
entityId: feeding.id,
action: 'CREATE',
userId: actingUserId,
afterData: feeding,
});
return feeding;
}
}