import { Injectable } from '@nestjs/common' import { ResponseMapper } from '../common/response/response-mapper' import { Prisma } from '../generated/prisma/client' import { PrismaService } from '../prisma/prisma.service' import { CreatePurchaseReceiptDto } from './dto/create-purchase-receipt.dto' @Injectable() export class PurchaseReceiptsService { constructor(private prisma: PrismaService) {} async create(dto: CreatePurchaseReceiptDto) { const data: Prisma.PurchaseReceiptCreateInput = { code: dto.code, totalAmount: new Prisma.Decimal(dto.totalAmount), description: dto.description ?? null, supplier: { connect: { id: dto.supplierId } }, inventory: { connect: { id: dto.inventoryId } }, items: dto.items?.length ? { create: dto.items.map((item, idx) => { const mapped = { count: new Prisma.Decimal(item.count ?? 0), unitPrice: new Prisma.Decimal(item.unitPrice ?? 0), totalAmount: new Prisma.Decimal(item.totalAmount ?? 0), description: item.description ?? null, product: { connect: { id: item.productId } }, } return mapped }), } : undefined, } const item = await this.prisma.purchaseReceipt.create({ data, include: { items: true }, omit: { supplierId: true, inventoryId: true, }, }) return ResponseMapper.create(item) } async findAll() { const items = await this.prisma.purchaseReceipt.findMany({ include: { supplier: true, inventory: true }, }) return ResponseMapper.list(items) } async findOne(id: number) { const item = await this.prisma.purchaseReceipt.findUnique({ where: { id }, include: { supplier: { select: { id: true, firstName: true, lastName: true, }, }, inventory: { select: { id: true, name: true, }, }, items: true, }, }) if (!item) return null return ResponseMapper.single(item) } async update(id: number, data: any) { const payload: any = { ...data } if (Object.prototype.hasOwnProperty.call(payload, 'supplierId')) { if (payload.supplierId === null) payload.supplier = { disconnect: true } else payload.supplier = { connect: { id: Number(payload.supplierId) } } delete payload.supplierId } if (Object.prototype.hasOwnProperty.call(payload, 'inventoryId')) { if (payload.inventoryId === null) payload.inventory = { disconnect: true } else payload.inventory = { connect: { id: Number(payload.inventoryId) } } delete payload.inventoryId } const item = await this.prisma.purchaseReceipt.update({ where: { id }, data: payload, }) return ResponseMapper.update(item) } async remove(id: number) { const item = await this.prisma.purchaseReceipt.delete({ where: { id } }) return ResponseMapper.single(item) } }