import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { WebhooksService } from '../webhooks/webhooks.service'; import { Inspection, Task } from '../../generated/prisma'; import { CreateInspectionDto } from './dto/create-inspection.dto'; import { CreateTaskFromInspectionDto } from './dto/create-task-from-inspection.dto'; @Injectable() export class InspectionsService { constructor( private readonly prisma: PrismaService, private readonly webhooks: WebhooksService, ) {} async findAll(): Promise { return this.prisma.inspection.findMany({ orderBy: { date: 'desc' } }); } async findById(id: string): Promise { const inspection = await this.prisma.inspection.findUnique({ where: { id }, }); if (!inspection) { throw new NotFoundException('Inspection not found'); } return inspection; } async findByColony(colonyId: string): Promise { return this.prisma.inspection.findMany({ where: { colonyId }, orderBy: { date: 'desc' }, }); } async create( dto: CreateInspectionDto, actingUserId: string, ): Promise { const inspection = await this.prisma.inspection.create({ data: { ...dto, date: new Date(dto.date), userId: actingUserId }, }); await this.webhooks.dispatch('inspection.created', inspection); return inspection; } async createTaskFromInspection( id: string, dto: CreateTaskFromInspectionDto, actingUserId: string, ): Promise { const inspection = await this.findById(id); return this.prisma.task.create({ data: { title: dto.title, description: dto.description, priority: dto.priority, dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined, assignedUserId: dto.assignedUserId, createdByUserId: actingUserId, relatedType: 'COLONY', relatedId: inspection.colonyId, sourceInspectionId: inspection.id, }, }); } }