import { QUERY_CONSTANTS } from '@/common/queryConstants' import { SharedSaleInvoicePaginationService } from '@/common/services/saleInvoices/sale-invoice-pagination.service' import { translateEnumValue } from '@/common/utils' import { TspProviderResponseStatus } from '@/generated/prisma/enums' import { SalesInvoiceWhereInput } from '@/generated/prisma/models' import { PrismaService } from '@/prisma/prisma.service' import { Injectable, NotFoundException } from '@nestjs/common' import { ResponseMapper } from 'common/response/response-mapper' @Injectable() export class CustomerSaleInvoicesService { constructor( private readonly prisma: PrismaService, private readonly sharedSaleInvoicePaginationService: SharedSaleInvoicePaginationService, ) {} async findAll( consumer_id: string, customer_id: string, requestedPage = 1, requestedPerPage = 10, ) { const { page, perPage, skip, take } = this.sharedSaleInvoicePaginationService.normalize(requestedPage, requestedPerPage) 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: { ...QUERY_CONSTANTS.SALE_INVOICE.summarySelect, pos: { select: { name: true, complex: { select: { name: true, business_activity: { select: { name: true, }, }, }, }, }, }, _count: { select: { items: true, }, }, }, skip, take, }), await tx.salesInvoice.count({ where: salesWhere, }), ]) const mappedAccounts = saleInvoices.map(saleInvoice => { const { _count, consumer_account, last_tsp_status, ...rest } = saleInvoice return { ...rest, items_count: _count.items, status: translateEnumValue('TspProviderResponseStatus', last_tsp_status), } }) return ResponseMapper.paginate(mappedAccounts, { total, page, perPage, }) } async findOne(consumer_id: string, customer_id: string, id: string) { const invoice = await this.prisma.salesInvoice.findUnique({ where: { id, customer_id, pos: { complex: { business_activity: { consumer_id, }, }, }, }, select: { ...QUERY_CONSTANTS.SALE_INVOICE.select, }, }) if (invoice) { const { type, ...rest } = invoice const mappedInvoice = { ...rest, type: translateEnumValue('TspProviderRequestType', type), status: translateEnumValue( 'TspProviderResponseStatus', invoice.last_tsp_status || TspProviderResponseStatus.NOT_SEND, ), settlement_type: translateEnumValue( 'InvoiceSettlementType', invoice.settlement_type, ), } return ResponseMapper.single(mappedInvoice) } throw new NotFoundException('صورت‌حساب مورد نظر شما یافت نشد.') } }