import { PrismaService } from '@/prisma/prisma.service' import { BadRequestException, NotFoundException } from '@nestjs/common' import { TspProviderCustomerType } from 'common/enums/enums' import { Prisma, TspProviderRequestType, TspProviderResponseStatus, } from 'generated/prisma/client' import { TspProviderActionResponseDto, TspProviderCorrectionSendPayloadDto, TspProviderOriginalSendPayloadDto, TspProviderRevokePayloadDto, TspProviderSendItemResultDto, } from '../dto/provider-switch.dto' export async function getOriginalResendAttemptNumber( prisma: PrismaService, invoice_id: string, ): Promise { let attemptNumber = 1 const existingAttempt = await prisma.saleInvoiceTspAttempts.findFirst({ where: { invoice_id, }, include: { invoice: { select: { type: true, }, }, }, orderBy: { created_at: 'desc', }, }) if (existingAttempt) { attemptNumber = existingAttempt.attempt_no + 1 if (existingAttempt.invoice.type !== TspProviderRequestType.ORIGINAL) { throw new BadRequestException( 'فقط فاکتورهای اصلی قابل ارسال مجدد به سامانه مالیاتی هستند.', ) } if (existingAttempt.status === TspProviderResponseStatus.SUCCESS) { throw new BadRequestException( 'فاکتور تایید شده از طرف سازمان مالیاتی قابل ارسال مجدد نیست.', ) } if (existingAttempt.status === TspProviderResponseStatus.QUEUED) { throw new BadRequestException( 'در حال حاضر فاکتور شما در حال بررسی توسط سازمان مالیاتی است.', ) } } return attemptNumber } export async function buildRevokePayload( prisma: PrismaService, invoiceId: string, posId: string, ): Promise { const invoice = await prisma.salesInvoice.findUnique({ where: { id: invoiceId, pos_id: posId, }, select: { id: true, code: true, total_amount: true, invoice_date: true, invoice_number: true, tax_id: true, tsp_attempts: { orderBy: { created_at: 'asc', }, take: 1, select: { id: true, status: true, }, }, pos: { select: { complex: { select: { business_activity: { select: { fiscal_id: true, economic_code: true, partner_token: true, guild: { select: { invoice_template: true, }, }, consumer: { select: { legal: { select: { partner: { select: { tsp_provider: true, }, }, }, }, individual: { select: { partner: { select: { tsp_provider: true, }, }, }, }, }, }, }, }, }, }, }, }, }, }) if (!invoice) { throw new NotFoundException('فاکتور مورد نظر یافت نشد.') } const { partner } = (invoice.pos.complex.business_activity.consumer.legal || invoice.pos.complex.business_activity.consumer.individual)! return { invoice_id: invoice.id, invoice_number: invoice.invoice_number, economic_code: invoice.pos.complex.business_activity.economic_code, fiscal_id: invoice.pos.complex.business_activity.fiscal_id, tsp_token: invoice.pos.complex.business_activity.partner_token, tsp_provider: partner.tsp_provider!, last_tax_id: invoice.tax_id!, } } export async function buildCorrectionPayload( tx: Prisma.TransactionClient, invoice_id: string, ): Promise { const invoice = await tx.salesInvoice.findUnique({ where: { id: invoice_id, }, select: { id: true, code: true, total_amount: true, invoice_date: true, invoice_number: true, items: true, pos: { select: { complex: { select: { business_activity: { select: { fiscal_id: true, economic_code: true, partner_token: true, guild: { select: { invoice_template: true, }, }, consumer: { select: { legal: { select: { partner: { select: { tsp_provider: true, }, }, }, }, individual: { select: { partner: { select: { tsp_provider: true, }, }, }, }, }, }, }, }, }, }, }, }, customer: { select: { type: true, individual: true, legal: true, }, }, reference_invoice: { select: { tax_id: true, }, }, payments: { include: { terminal_info: true, }, }, }, }) if (!invoice) { throw Error() } const { partner } = (invoice.pos.complex.business_activity.consumer.legal || invoice.pos.complex.business_activity.consumer.individual)! return { items: invoice.items.map(item => ({ invoice_item_id: item.id, quantity: Number(item.quantity), unit_price: Number(item.unit_price), total_amount: Number(item.total_amount), measure_unit: item.measure_unit_code, sku: item.sku_code, sku_vat: String(item.sku_vat), discount: String((item.payload as Record)?.discount || '0'), good_id: item.good_id, service_id: item.service_id, payload: item.payload, good_snapshot: item.good_snapshot, })), payments: invoice.payments.map(payment => ({ amount: Number(payment.amount), payment_method: payment.payment_method, paid_at: payment.paid_at, card_number: payment.terminal_info ? payment.terminal_info.stan : undefined, tracking_code: payment.terminal_info ? payment.terminal_info.rrn : undefined, })), total_amount: Number(invoice.total_amount), last_tax_id: invoice.reference_invoice!.tax_id!, invoice_number: invoice.invoice_number, invoice_id: invoice.id, economic_code: invoice.pos.complex.business_activity.economic_code, fiscal_id: invoice.pos.complex.business_activity.fiscal_id, tsp_token: invoice.pos.complex.business_activity.partner_token, type: TspProviderRequestType.CORRECTION, tsp_provider: partner.tsp_provider!, invoice_template: invoice.pos.complex.business_activity.guild.invoice_template, invoice_date: new Date(), customer_type: invoice.customer?.type ? TspProviderCustomerType.KNOWN : TspProviderCustomerType.UNKNOWN, customer: invoice.customer?.type ? { type: invoice.customer.type, legal_info: invoice.customer.legal ?? undefined, individual_info: invoice.customer.individual ?? undefined, } : undefined, } } export async function buildPayload( prisma: PrismaService, invoiceId: string, posId: string, ): Promise { const invoice = await prisma.salesInvoice.findUnique({ where: { id: invoiceId, pos_id: posId, }, select: { id: true, code: true, total_amount: true, invoice_date: true, invoice_number: true, items: { select: { id: true, quantity: true, unit_price: true, total_amount: true, measure_unit_code: true, measure_unit_text: true, sku_code: true, sku_vat: true, good_id: true, service_id: true, payload: true, good_snapshot: true, }, }, pos: { select: { complex: { select: { business_activity: { select: { fiscal_id: true, economic_code: true, partner_token: true, guild: { select: { invoice_template: true, }, }, consumer: { select: { legal: { select: { partner: { select: { tsp_provider: true, }, }, }, }, individual: { select: { partner: { select: { tsp_provider: true, }, }, }, }, }, }, }, }, }, }, }, }, customer: { select: { type: true, individual: { select: { first_name: true, last_name: true, national_id: true, mobile_number: true, }, }, legal: { select: { name: true, economic_code: true, }, }, }, }, payments: { select: { amount: true, payment_method: true, paid_at: true, terminal_info: { select: { stan: true, rrn: true, }, }, }, }, }, }) if (!invoice) { throw new NotFoundException('فاکتور مورد نظر یافت نشد.') } const { partner } = (invoice.pos.complex.business_activity.consumer.legal || invoice.pos.complex.business_activity.consumer.individual)! return { invoice_id: invoice.id, invoice_number: invoice.invoice_number, invoice_date: invoice.invoice_date, total_amount: Number(invoice.total_amount), economic_code: invoice.pos.complex.business_activity.economic_code, fiscal_id: invoice.pos.complex.business_activity.fiscal_id, invoice_template: invoice.pos.complex.business_activity.guild.invoice_template, tsp_token: invoice.pos.complex.business_activity.partner_token, payments: invoice.payments.map(payment => ({ amount: Number(payment.amount), payment_method: payment.payment_method, paid_at: payment.paid_at, card_number: payment.terminal_info ? payment.terminal_info.stan : undefined, tracking_code: payment.terminal_info ? payment.terminal_info.rrn : undefined, })), type: TspProviderRequestType.ORIGINAL, tsp_provider: partner.tsp_provider!, customer_type: invoice.customer?.type ? TspProviderCustomerType.KNOWN : TspProviderCustomerType.UNKNOWN, customer: invoice.customer?.type ? { type: invoice.customer.type, legal_info: invoice.customer.legal ?? undefined, individual_info: invoice.customer.individual ?? undefined, } : undefined, items: invoice.items.map(item => ({ invoice_item_id: item.id, quantity: Number(item.quantity), unit_price: Number(item.unit_price), total_amount: Number(item.total_amount), measure_unit: item.measure_unit_code, sku: item.sku_code, sku_vat: String(item.sku_vat), discount: String((item.payload as Record)?.discount || '0'), good_id: item.good_id, service_id: item.service_id, payload: item.payload, good_snapshot: item.good_snapshot, })), } } export async function trySend( tspSwitchService: { send( payload: TspProviderOriginalSendPayloadDto, ): Promise }, payload: TspProviderOriginalSendPayloadDto, ): Promise { return (await tspSwitchService.send(payload)) || null } export async function onResult( prisma: PrismaService, result: any, attempt_id: string, ): Promise { if (result) { if (result.hasError) { const updatedAttempt = await prisma.saleInvoiceTspAttempts.update({ where: { id: attempt_id, }, data: { provider_request_payload: result.provider_request_payload, provider_response_payload: JSON.parse(JSON.stringify(result)), status: result.status, sent_at: result.sent_at || new Date().toISOString(), received_at: result.received_at || new Date().toISOString(), message: result.message?.toString() || 'وجود مشکل در ارسال به سامانه مالیاتی', }, select: { status: true, invoice: true, message: true, }, }) return { invoice: updatedAttempt.invoice, status: updatedAttempt.status, message: updatedAttempt.message, } } const updatedAttempt = await prisma.saleInvoiceTspAttempts.update({ where: { id: attempt_id, }, data: { provider_request_payload: result.provider_request_payload, provider_response_payload: JSON.parse(JSON.stringify(result)), status: result.status, sent_at: result.sent_at, received_at: result.received_at, message: result.message?.toString() || 'فاکتور با موفقیت به سامانه مالیاتی ارسال شد.', }, select: { status: true, invoice: true, message: true, }, }) return { invoice: updatedAttempt.invoice, status: updatedAttempt.status, message: updatedAttempt.message, } } const updatedAttempt = await prisma.saleInvoiceTspAttempts.update({ where: { id: attempt_id, }, data: { provider_response_payload: {}, status: TspProviderResponseStatus.FAILURE, message: 'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.', received_at: new Date().toISOString(), }, select: { status: true, invoice: true, message: true, }, }) return { invoice: updatedAttempt.invoice, status: updatedAttempt.status, message: updatedAttempt.message, } }