import { QUERY_CONSTANTS } from '@/common/queryConstants' import consumer_mappersUtil from '@/common/utils/mappers/consumer_mappers.util' import { SalesInvoiceSelect, SalesInvoiceWhereInput } from '@/generated/prisma/models' import { PrismaService } from '@/prisma/prisma.service' import { Injectable } from '@nestjs/common' import { ResponseMapper } from 'common/response/response-mapper' @Injectable() export class CustomerSaleInvoicesService { constructor(private readonly prisma: PrismaService) {} private readonly defaultSelect: SalesInvoiceSelect = { id: true, code: true, invoice_date: true, notes: true, total_amount: true, pos: { select: { id: true, name: true, complex: { select: { id: true, name: true, business_activity: { select: { id: true, name: true, }, }, }, }, }, }, consumer_account: { select: { role: true, consumer: { select: { ...QUERY_CONSTANTS.CONSUMER.infoSelect, }, }, account: { select: { username: true, }, }, }, }, created_at: true, } async findAll(consumer_id: string, customer_id: string, page = 1, perPage = 10) { const salesWhere: SalesInvoiceWhereInput = { customer_id, pos: { complex: { business_activity: { consumer_id, }, }, }, } const [saleInvoices, total] = await this.prisma.$transaction(async tx => [ await tx.salesInvoice.findMany({ where: salesWhere, select: { ...this.defaultSelect, _count: { select: { items: true, }, }, }, skip: (page - 1) * perPage, take: 10, }), await tx.salesInvoice.count({ where: salesWhere, }), ]) const mappedAccounts = saleInvoices.map(saleInvoice => { const { _count, consumer_account, ...rest } = saleInvoice const { consumer, ...restConsumerAccount } = consumer_account as any const mappedConsumer = consumer_mappersUtil(consumer) return { ...rest, items_count: _count.items, consumer_account: { ...restConsumerAccount, consumer: mappedConsumer, }, } }) return ResponseMapper.paginate(mappedAccounts, { total, page, perPage, }) } async findOne(consumer_id: string, customer_id: string, id: string) { const saleInvoice = await this.prisma.salesInvoice.findUniqueOrThrow({ where: { id, customer_id, pos: { complex: { business_activity: { consumer_id, }, }, }, }, select: { ...this.defaultSelect, items: { select: { id: true, notes: true, unit_price: true, discount: true, quantity: true, total_amount: true, payload: true, good: { select: { id: true, name: true, pricing_model: true, measure_unit: { select: { id: true, name: true, }, }, category: { select: { id: true, name: true, image_url: true, }, }, }, }, }, }, payments: { select: { amount: true, paid_at: true, payment_method: true, }, }, }, }) const { _count, consumer_account, ...rest } = saleInvoice const { consumer, ...restConsumerAccount } = consumer_account as any const mappedConsumer = consumer_mappersUtil(consumer) return ResponseMapper.single({ ...rest, items_count: _count.items, consumer_account: { ...restConsumerAccount, consumer: mappedConsumer, }, }) } }