Files
psp_api/src/modules/tspProviders/sales-invoice-tsp.service.ts
T

986 lines
31 KiB
TypeScript
Raw Normal View History

import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
import {
CustomerType,
Prisma,
TspProviderCustomerType,
TspProviderRequestType,
TspProviderResponseStatus,
} from 'generated/prisma/client'
import {
TspProviderActionResponseDto,
TspProviderCorrectionInvoicePayloadDto,
TspProviderCorrectionSendPayloadDto,
TspProviderCorrectionSendResponseDto,
TspProviderOriginalSendPayloadDto,
2026-05-04 11:21:49 +03:30
TspProviderRevokePayloadDto,
TspProviderSendItemResultDto,
} from './dto/provider-switch.dto'
import { SalesInvoiceTspSwitchService } from './sales-invoice-tsp-switch.service'
type ItemTspRow = {
tsp_provider: string | null
tax_id: string | null
}
@Injectable()
export class SalesInvoiceTspService {
constructor(
private readonly prisma: PrismaService,
private readonly tspSwitchService: SalesInvoiceTspSwitchService,
private sharedSaleInvoiceCreateService: SharedSaleInvoiceCreateService,
) {}
async originalSend(
posId: string,
invoice_id: string,
): Promise<TspProviderActionResponseDto> {
const payload = await this.buildPayload(invoice_id, posId)
const attempt = await this.prisma.saleInvoiceTspAttempts.create({
data: {
attempt_no: 1,
invoice_id,
status: TspProviderResponseStatus.QUEUED,
request_payload: JSON.parse(JSON.stringify(payload)),
message: 'در حال ارسال به سامانه مالیاتی...',
},
})
const result = await this.trySend(payload)
return await this.onCreateCorrectionResult(result, attempt.id)
}
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
// if (!invoice_ids.length) return
// const payloads: TspProviderOriginalSendPayloadDto[] = []
// for (const invoiceId of invoice_ids) {
// const posId = await this.getPosId(consumer_id, invoiceId)
// payloads.push(await this.buildPayload(invoiceId, posId))
// }
// const bulkResult = await this.tspSwitchService.sendBulk(payloads)
// const allItemResults = bulkResult.flatMap(result => result.items)
// await this.persistAttemptResults(allItemResults)
}
async get(
invoice_id: string,
pos_id: string,
consumer_id: string,
): Promise<TspProviderActionResponseDto> {
const [attempt, pos] = await this.prisma.$transaction(async tx => [
await tx.saleInvoiceTspAttempts.findFirst({
where: {
invoice_id,
invoice: {
pos: {
id: pos_id,
},
},
},
orderBy: {
attempt_no: 'desc',
},
}),
await tx.pos.findUnique({
where: {
id: pos_id,
complex: {
business_activity: {
consumer_id,
},
},
},
select: {
complex: {
select: {
business_activity: {
select: {
partner_token: true,
consumer: {
select: {
legal: {
select: {
partner: {
select: {
tsp_provider: true,
},
},
},
},
individual: {
select: {
partner: {
select: {
tsp_provider: true,
},
},
},
},
},
},
},
},
},
},
},
}),
])
if (!attempt) {
throw new NotFoundException('صورت‌حساب ارسالی فاکتور شما به سامانه یافت نشد.')
}
if (!pos) {
throw new NotFoundException('مشکلی در ساختار اطلاعات ورودی شما وجود دارد.')
}
const { business_activity } = pos.complex
const { partner } = (business_activity.consumer.individual ||
business_activity.consumer.legal)!
const result = await this.tspSwitchService.get(
partner.tsp_provider,
invoice_id,
business_activity.partner_token,
)
console.log('getResult', result)
if (!result) {
throw new NotFoundException('نتیجه ارسال فاکتور یافت نشد.')
}
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
where: {
id: attempt.id,
},
data: {
response_payload: JSON.parse(JSON.stringify(result)),
status: result.status,
received_at: result.received_at,
},
select: {
status: true,
invoice: true,
message: true,
},
})
return {
invoice: updatedAttempt.invoice,
status: updatedAttempt.status,
message: updatedAttempt.message,
}
}
async correctionSend(
consumerAccountId: string,
posId: string,
complexId: string,
businessId: string,
ref_invoice_id: string,
dataToUpdate: TspProviderCorrectionInvoicePayloadDto,
): Promise<TspProviderActionResponseDto> {
const [newInvoice, attempt, correctionPayload] = await this.prisma.$transaction(
async tx => {
const relatedInvoice = await tx.salesInvoice.findUnique({
where: {
id: ref_invoice_id,
},
include: {
customer: {
select: {
type: true,
},
},
tsp_attempts: {
orderBy: {
attempt_no: 'desc',
},
take: 1,
},
},
})
if (!relatedInvoice) {
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
}
2026-05-04 11:21:49 +03:30
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
throw new BadRequestException(
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
)
}
if (!relatedInvoice.tax_id) {
throw new BadRequestException(
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
)
}
2026-05-04 11:21:49 +03:30
const newInvoice = await this.sharedSaleInvoiceCreateService.create({
data: {
customer_type: relatedInvoice.customer?.type || CustomerType.UNKNOWN,
invoice_date: new Date(),
payments: dataToUpdate.payments,
items: dataToUpdate.items,
total_amount: dataToUpdate.total_amount,
customer_id: relatedInvoice.customer_id || undefined,
},
businessId,
complexId,
posId,
consumerAccountId,
main_invoice_id: relatedInvoice.main_id || relatedInvoice.id,
ref_invoice_id: relatedInvoice.id,
type: TspProviderRequestType.CORRECTION,
})
2026-05-04 11:21:49 +03:30
const correctionPayload = await this.buildCorrectionPayload(tx, newInvoice.id)
2026-05-04 11:21:49 +03:30
const attempt = await tx.saleInvoiceTspAttempts.create({
data: {
attempt_no: 1,
invoice_id: newInvoice.id,
message: 'در حال ارسال به سامانه مالیاتی...',
status: TspProviderResponseStatus.QUEUED,
request_payload: JSON.parse(JSON.stringify(correctionPayload)),
},
})
return [newInvoice, attempt, correctionPayload]
},
)
const result = await this.trySend(correctionPayload)
console.log('sendResult')
console.log(result)
return this.onCreateCorrectionResult(result, attempt.id)
// const countByGoodId = (goodIds: string[]): Map<string, number> => {
// const counts = new Map<string, number>()
// for (const goodId of goodIds) {
// counts.set(goodId, (counts.get(goodId) ?? 0) + 1)
// }
// return counts
// }
// const updatedGoodIds = dataToUpdate.items.map(item => item.good_id!)
// const previousGoodIds = lastAttempt.invoice.items.map(item => item.good_id)
// const updatedCounts = countByGoodId(updatedGoodIds)
// const previousCounts = countByGoodId(previousGoodIds)
// let isBackFromSale = false
// if (updatedCounts.size !== previousCounts.size) {
// isBackFromSale = true
// } else {
// for (const [goodId, count] of updatedCounts) {
// if (previousCounts.get(goodId) !== count) {
// isBackFromSale = true
// break
// }
// }
// }
}
2026-05-04 11:21:49 +03:30
async revoke(
consumerAccountId: string,
posId: string,
complexId: string,
businessId: string,
ref_invoice_id: string,
): Promise<TspProviderActionResponseDto> {
const [newInvoice, attempt, revokePayload] = await this.prisma.$transaction(
async tx => {
const relatedInvoice = await tx.salesInvoice.findUnique({
where: {
id: ref_invoice_id,
2026-05-04 11:21:49 +03:30
},
include: {
customer: {
select: {
type: true,
},
},
tsp_attempts: {
orderBy: {
attempt_no: 'desc',
},
take: 1,
},
payments: {
include: {
terminal_info: true,
},
},
items: true,
},
})
2026-05-04 11:21:49 +03:30
if (!relatedInvoice) {
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
}
2026-05-04 11:21:49 +03:30
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
throw new BadRequestException(
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
)
}
2026-05-04 11:21:49 +03:30
if (!relatedInvoice.tax_id) {
throw new BadRequestException(
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
)
}
2026-05-04 11:21:49 +03:30
const payments = relatedInvoice.payments.reduce(
(acc, payment) => {
const amount = Number(payment.amount)
switch (payment.payment_method) {
case 'CASH':
acc.cash = (acc.cash || 0) + amount
break
case 'SET_OFF':
acc.set_off = (acc.set_off || 0) + amount
break
case 'CARD':
acc.card = (acc.card || 0) + amount
break
case 'BANK':
acc.bank = (acc.bank || 0) + amount
break
case 'CHEQUE':
acc.check = (acc.check || 0) + amount
break
case 'OTHER':
acc.other = (acc.other || 0) + amount
break
case 'TERMINAL':
acc.terminals = payment.terminal_info
? {
amount,
terminalId: payment.terminal_info.terminal_id,
stan: payment.terminal_info.stan,
rrn: payment.terminal_info.rrn,
customer_card_no:
payment.terminal_info.customer_card_no || undefined,
transaction_date_time: payment.terminal_info.transaction_date_time,
description: payment.terminal_info.description || undefined,
}
: acc.terminals
break
default:
break
}
return acc
},
{} as {
terminals?: {
amount?: number
terminalId: string
stan: string
rrn: string
customer_card_no?: string
transaction_date_time: Date
description?: string
}
cash?: number
set_off?: number
card?: number
bank?: number
check?: number
other?: number
},
)
const newInvoice = await this.sharedSaleInvoiceCreateService.create({
data: {
customer_type: relatedInvoice.customer?.type || CustomerType.UNKNOWN,
invoice_date: new Date(),
payments,
items: relatedInvoice.items.map(item => ({
unit_price: Number(item.unit_price),
quantity: Number(item.quantity),
total_amount: Number(item.total_amount),
discount_amount: Number(item.discount || 0),
invoice_id: '',
good_id: item.good_id,
service_id: item.service_id || undefined,
payload: item.payload as any,
notes: item.notes || '',
})),
total_amount: Number(relatedInvoice.total_amount),
customer_id: relatedInvoice.customer_id || undefined,
},
businessId,
complexId,
posId,
consumerAccountId,
main_invoice_id: relatedInvoice.main_id || relatedInvoice.id,
ref_invoice_id: relatedInvoice.id,
2026-05-04 11:21:49 +03:30
type: TspProviderRequestType.REVOKE,
})
2026-05-04 11:21:49 +03:30
const payload = await this.buildRevokePayload(newInvoice.id, posId)
const attempt = await tx.saleInvoiceTspAttempts.create({
data: {
attempt_no: 1,
invoice_id: newInvoice.id,
message: 'در حال ارسال به سامانه مالیاتی...',
status: TspProviderResponseStatus.QUEUED,
request_payload: JSON.parse(JSON.stringify(payload)),
},
})
return [newInvoice, attempt, payload]
},
)
const result = await this.tspSwitchService.revoke(revokePayload)
return await this.onCreateCorrectionResult(result, attempt.id)
2026-05-04 11:21:49 +03:30
}
private async getPosId(
consumer_account_id: string,
invoice_id: string,
): Promise<string> {
const now = new Date()
console.log(consumer_account_id, invoice_id)
const saleInvoice = await this.prisma.salesInvoice.findUnique({
where: {
id: invoice_id,
pos: {
complex: {
business_activity: {
consumer: {
accounts: {
some: {
id: consumer_account_id,
},
},
},
},
},
},
},
select: {
pos: {
select: {
id: true,
complex: {
select: {
business_activity: {
select: {
name: true,
license_activation: {
select: {
expires_at: true,
license_renews: {
select: {
expires_at: true,
},
},
},
},
},
},
},
},
},
},
},
})
if (!saleInvoice) {
throw new NotFoundException('متاسفانه فاکتور مورد نظر یافت نشد.')
}
const { license_activation, name: businessName } =
saleInvoice.pos.complex.business_activity
let expired = !license_activation || false
if (license_activation) {
const { expires_at, license_renews } = license_activation
if (expires_at < now) {
for (const renew of license_renews) {
if (renew.expires_at > now) {
expired = false
break
}
}
}
}
if (expired) {
throw new NotFoundException(`متاسفانه مجوز ${businessName} منقضی شده است.`)
}
return saleInvoice.pos.id
}
2026-05-04 11:21:49 +03:30
private async buildRevokePayload(
invoiceId: string,
posId: string,
): Promise<TspProviderRevokePayloadDto> {
const invoice = await this.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,
2026-05-04 11:21:49 +03:30
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!,
}
}
private async buildCorrectionPayload(
tx: Prisma.TransactionClient,
invoice_id: string,
): Promise<TspProviderCorrectionSendPayloadDto> {
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)!
const returnData: TspProviderCorrectionSendPayloadDto = {
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<string, any>)?.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,
2026-05-04 11:21:49 +03:30
}
return returnData
2026-05-04 11:21:49 +03:30
}
private async buildPayload(
invoiceId: string,
posId: string,
): Promise<TspProviderOriginalSendPayloadDto> {
const invoice = await this.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,
},
},
},
},
},
})
console.log(invoiceId, posId)
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<string, any>)?.discount || '0'),
good_id: item.good_id,
service_id: item.service_id,
payload: item.payload,
good_snapshot: item.good_snapshot,
})),
}
}
private async tryCorrection(
payload: TspProviderCorrectionSendPayloadDto,
): Promise<TspProviderCorrectionSendResponseDto | null> {
const taxResult = await this.tspSwitchService.correction(payload)
return taxResult || null
}
private async trySend(
payload: TspProviderOriginalSendPayloadDto,
): Promise<TspProviderSendItemResultDto | null> {
const taxResult = await this.tspSwitchService.send(payload)
return taxResult || null
}
private async onCreateCorrectionResult(
result: any,
attempt_id: string,
): Promise<TspProviderActionResponseDto> {
if (result) {
if (result.hasError) {
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
where: {
id: attempt_id,
},
data: {
response_payload: JSON.parse(JSON.stringify(result)),
status: result.status,
message: result.message?.toString() || 'وجود مشکل در ارسال به سامانه مالیاتی',
},
select: {
status: true,
invoice: true,
message: true,
},
})
return {
invoice: updatedAttempt.invoice,
status: updatedAttempt.status,
message: updatedAttempt.message,
}
}
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
where: {
id: attempt_id,
},
data: {
response_payload: JSON.parse(JSON.stringify(result)),
status: result.status,
sent_at: result.sent_at,
received_at: result.received_at,
message: 'ارسال با موفقیت انجام شد.',
},
select: {
status: true,
invoice: true,
message: true,
},
})
return {
invoice: updatedAttempt.invoice,
status: updatedAttempt.status,
message: updatedAttempt.message,
}
} else {
throw new NotFoundException(
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
)
}
}
}
// {"type": "ORIGINAL", "items": [{"sku": "2720000044726", "good_id": "01KQHY48M299C9BG2D06DMWK4E", "payload": {"karat": "18", "wages": 40000000, "profit": 48000000, "commission": 40000000}, "sku_vat": "0", "discount": "0", "quantity": 2, "service_id": null, "unit_price": 200000000, "measure_unit": "63", "total_amount": 540800000, "good_snapshot": {"good": {"id": "01KQHY48M299C9BG2D06DMWK4E", "sku": {"id": "01KQHXE2D4XEFSDK4DSV2J6GT2", "VAT": "0", "code": "2720000044726", "name": "گوشواره طلا زیورالات ساخته شده از طلا"}, "name": "گوشواره", "barcode": null, "category": {"id": "01KQHY48CF6X2TK2AG09MKDVKQ", "name": "زیورآلات"}, "image_url": null, "local_sku": null, "measure_unit": {"id": "01KQHY489HE02787SE8TWDE18S", "code": "63", "name": "گرم"}, "pricing_model": "GOLD", "base_sale_price": "0"}}, "invoice_item_id": "01KQMZTMDC4M4T7VE9GFZJEW4E"}], "payments": [{"amount": 540800000, "paid_at": "2026-05-02T18:39:46.000Z", "payment_method": "CASH"}], "fiscal_id": "A296T3", "tsp_token": "pfFE6QxOJxUIhzkpUCPWYMR5", "invoice_id": "98c3377d-4e42-4703-97f0-38c3b3c8e87f", "invoice_date": "2026-05-02T18:39:46.000Z", "total_amount": 540800000, "tsp_provider": "NAMA", "customer_type": "Unknown", "economic_code": "14003579468", "invoice_number": 13, "invoice_template": "GOLD_JEWELRY"}