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) {} 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, }, }, }, }, }, }, account: { select: { role: true, consumer: { select: { first_name: true, last_name: true, }, }, account: { select: { username: true, }, }, }, }, created_at: true, } async findAll(consumer_id: string, customer_id: string, page = 1, pageSize = 10) { const salesWhere: SalesInvoiceWhereInput = { customer_id, pos: { complex: { business_activity: { consumer_id, }, }, }, } const [accounts, count] = await this.prisma.$transaction(async tx => [ await tx.salesInvoice.findMany({ where: salesWhere, select: { ...this.defaultSelect, _count: { select: { items: true, }, }, }, skip: (page - 1) * pageSize, take: 10, }), await tx.salesInvoice.count({ where: salesWhere, }), ]) const mappedAccounts = accounts.map(account => { const { _count, ...rest } = account return { ...rest, items_count: _count.items, } }) return ResponseMapper.paginate(mappedAccounts, { count, page, pageSize, }) } async findOne(consumer_id: string, customer_id: string, id: string) { const account = 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, unit_type: true, category: { select: { id: true, name: true, image_url: true, }, }, }, }, }, }, payments: { select: { amount: true, paid_at: true, payment_method: true, }, }, }, }) return ResponseMapper.single(account) } }