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'; import { UpdateFeedingDto } from './dto/update-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 { return this.prisma.feeding.findMany({ orderBy: { date: 'desc' } }); } async findById(id: string): Promise { const feeding = await this.prisma.feeding.findUnique({ where: { id } }); if (!feeding) { throw new NotFoundException('Feeding not found'); } return feeding; } async findByColony(colonyId: string): Promise { return this.prisma.feeding.findMany({ where: { colonyId }, orderBy: { date: 'asc' }, }); } async summaryByColony(colonyId: string): Promise { 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 { 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; } async update( id: string, dto: UpdateFeedingDto, actingUserId: string, ): Promise { const before = await this.findById(id); const feeding = await this.prisma.feeding.update({ where: { id }, data: { ...dto, date: dto.date ? new Date(dto.date) : undefined }, }); await this.auditLog.record({ entityType: 'Feeding', entityId: id, action: 'UPDATE', userId: actingUserId, beforeData: before, afterData: feeding, }); return feeding; } }