feat: implement correction and original send functionality for Nama provider
- Added new DTOs for correction requests and responses in `nama-provider.dto.ts`. - Updated `nama-provider.adapter.ts` to include `originalSend` and `correctionSend` methods. - Enhanced `nama-provider.util.ts` with mapping functions for correction requests. - Created operational guidelines for agents in `AGENT.md`. - Updated Prisma migrations to support new invoice types and relationships. - Introduced new service and DTO for creating sales invoices in `sale-invoice-create.service.ts` and `sale-invoice-create.dto.ts`. - Added utility for handling Prisma errors in `prisma-error.util.ts`.
This commit is contained in:
@@ -1,16 +1,21 @@
|
||||
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 { CreateSalesInvoiceDto } from '../pos/sales-invoices/dto/create-sales-invoice.dto'
|
||||
import {
|
||||
TspProviderActionResponseDto,
|
||||
TspProviderCorrectionInvoicePayloadDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from './dto/provider-switch.dto'
|
||||
import { SalesInvoiceTspSwitchService } from './sales-invoice-tsp-switch.service'
|
||||
|
||||
@@ -19,81 +24,51 @@ type ItemTspRow = {
|
||||
tax_id: string | null
|
||||
}
|
||||
|
||||
type IAttempt = any
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceTspService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly tspSwitchService: SalesInvoiceTspSwitchService,
|
||||
private sharedSaleInvoiceCreateService: SharedSaleInvoiceCreateService,
|
||||
) {}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string): Promise<IAttempt> {
|
||||
const posId = await this.getPosId(consumer_id, invoice_id)
|
||||
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,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
},
|
||||
})
|
||||
|
||||
const sendResult = await this.trySend(payload)
|
||||
const result = await this.trySend(payload)
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(sendResult)
|
||||
|
||||
if (sendResult) {
|
||||
if (sendResult.hasError) {
|
||||
throw new Error(sendResult.message || '')
|
||||
}
|
||||
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: attempt.id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(sendResult)),
|
||||
status: sendResult.status,
|
||||
tax_id: sendResult.tax_id,
|
||||
sent_at: sendResult.sent_at,
|
||||
received_at: sendResult.received_at,
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
return await this.onCreateCorrectionResult(result, attempt.id)
|
||||
}
|
||||
|
||||
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
|
||||
if (!invoice_ids.length) return
|
||||
|
||||
const payloads: TspProviderSendPayloadDto[] = []
|
||||
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)
|
||||
// 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<IAttempt> {
|
||||
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: {
|
||||
@@ -190,206 +165,307 @@ export class SalesInvoiceTspService {
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
message: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
}
|
||||
|
||||
async update(
|
||||
consumer_id: string,
|
||||
invoice_id: string,
|
||||
dataToUpdate: CreateSalesInvoiceDto,
|
||||
): Promise<IAttempt> {
|
||||
const posId = await this.getPosId(consumer_id, invoice_id)
|
||||
const payload = await this.buildPayload(invoice_id, posId)
|
||||
|
||||
const lastAttempt = await this.prisma.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
invoice_id,
|
||||
invoice: {
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
include: {
|
||||
invoice: {
|
||||
include: {
|
||||
items: {
|
||||
include: {
|
||||
good: true,
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!relatedInvoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
|
||||
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
if (!relatedInvoice.tax_id) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
const correctionPayload = await this.buildCorrectionPayload(tx, newInvoice.id)
|
||||
|
||||
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
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
include: {
|
||||
customer: {
|
||||
select: {
|
||||
type: true,
|
||||
},
|
||||
},
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
payments: {
|
||||
include: {
|
||||
terminal_info: true,
|
||||
},
|
||||
},
|
||||
items: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (!lastAttempt) {
|
||||
throw new NotFoundException('صورتحساب ارسالی فاکتور شما به سامانه یافت نشد.')
|
||||
}
|
||||
|
||||
if (lastAttempt.status === TspProviderResponseStatus.QUEUED) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور هنوز به سامانه مالیاتی ارسال نشده است یا در صف ارسال قرار دارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
if (!relatedInvoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: 1,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
},
|
||||
})
|
||||
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
const sendResult = await this.trySend(payload)
|
||||
if (!relatedInvoice.tax_id) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(sendResult)
|
||||
|
||||
if (sendResult) {
|
||||
if (sendResult.hasError) {
|
||||
throw new Error(sendResult.message || '')
|
||||
}
|
||||
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: attempt.id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(sendResult)),
|
||||
status: sendResult.status,
|
||||
tax_id: sendResult.tax_id,
|
||||
sent_at: sendResult.sent_at,
|
||||
received_at: sendResult.received_at,
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async revoke(
|
||||
pos_id: string,
|
||||
invoice_id: string,
|
||||
): Promise<TspProviderRevokeResponseDto> {
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
invoice_id,
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
tax_id: true,
|
||||
status: true,
|
||||
attempt_no: true,
|
||||
invoice: {
|
||||
select: {
|
||||
invoice_number: true,
|
||||
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
|
||||
},
|
||||
)
|
||||
|
||||
if (!attempt) {
|
||||
throw new NotFoundException('صورتحساب ارسالی فاکتور شما به سامانه یافت نشد.')
|
||||
}
|
||||
if (attempt.status === TspProviderResponseStatus.QUEUED) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور هنوز به سامانه مالیاتی ارسال نشده است یا در صف ارسال قرار دارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
const payload = await this.buildRevokePayload(invoice_id, pos_id)
|
||||
|
||||
const result = await this.tspSwitchService.revoke(payload)
|
||||
|
||||
if (result) {
|
||||
await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: attempt.attempt_no + 1,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.REVOKED,
|
||||
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,
|
||||
type: TspProviderRequestType.REVOKE,
|
||||
received_at: new Date(),
|
||||
request_payload: JSON.parse(JSON.stringify(result.request_payload)),
|
||||
sent_at: result.sent_at ? new Date(result.sent_at) : new Date(),
|
||||
response_payload: JSON.parse(JSON.stringify(result)),
|
||||
tax_id: result.tax_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
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)
|
||||
}
|
||||
|
||||
private async getPosId(consumer_id: string, invoice_id: string): Promise<string> {
|
||||
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_id,
|
||||
consumer: {
|
||||
accounts: {
|
||||
some: {
|
||||
id: consumer_account_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -462,6 +538,7 @@ export class SalesInvoiceTspService {
|
||||
total_amount: true,
|
||||
invoice_date: true,
|
||||
invoice_number: true,
|
||||
tax_id: true,
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
created_at: 'asc',
|
||||
@@ -470,7 +547,6 @@ export class SalesInvoiceTspService {
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
},
|
||||
},
|
||||
pos: {
|
||||
@@ -532,14 +608,147 @@ export class SalesInvoiceTspService {
|
||||
fiscal_id: invoice.pos.complex.business_activity.fiscal_id,
|
||||
tsp_token: invoice.pos.complex.business_activity.partner_token,
|
||||
tsp_provider: partner.tsp_provider!,
|
||||
last_attempt_tax_id: invoice.tsp_attempts[0].tax_id!,
|
||||
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,
|
||||
}
|
||||
return returnData
|
||||
}
|
||||
|
||||
private async buildPayload(
|
||||
invoiceId: string,
|
||||
posId: string,
|
||||
): Promise<TspProviderSendPayloadDto> {
|
||||
): Promise<TspProviderOriginalSendPayloadDto> {
|
||||
const invoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoiceId,
|
||||
@@ -644,6 +853,8 @@ export class SalesInvoiceTspService {
|
||||
},
|
||||
})
|
||||
|
||||
console.log(invoiceId, posId)
|
||||
|
||||
if (!invoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
@@ -667,7 +878,7 @@ export class SalesInvoiceTspService {
|
||||
card_number: payment.terminal_info ? payment.terminal_info.stan : undefined,
|
||||
tracking_code: payment.terminal_info ? payment.terminal_info.rrn : undefined,
|
||||
})),
|
||||
type: TspProviderRequestType.MAIN,
|
||||
type: TspProviderRequestType.ORIGINAL,
|
||||
tsp_provider: partner.tsp_provider!,
|
||||
customer_type: invoice.customer?.type
|
||||
? TspProviderCustomerType.Known
|
||||
@@ -696,62 +907,79 @@ export class SalesInvoiceTspService {
|
||||
}
|
||||
}
|
||||
|
||||
private async tryCorrection(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto | null> {
|
||||
const taxResult = await this.tspSwitchService.correction(payload)
|
||||
|
||||
return taxResult || null
|
||||
}
|
||||
|
||||
private async trySend(
|
||||
payload: TspProviderSendPayloadDto,
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto | null> {
|
||||
const taxResult = await this.tspSwitchService.send(payload)
|
||||
|
||||
return taxResult || null
|
||||
}
|
||||
|
||||
private async persistAttemptResults(
|
||||
itemResults: TspProviderSendItemResultDto[],
|
||||
): Promise<any> {
|
||||
if (!itemResults.length) return
|
||||
|
||||
const attemptsResult = [] as any[]
|
||||
console.log('persistAttemptResults')
|
||||
|
||||
for (const itemResult of itemResults) {
|
||||
const attempt = await this.prisma.$transaction(async tx => {
|
||||
const lastAttempt = await tx.saleInvoiceTspAttempts.findFirst({
|
||||
private async onCreateCorrectionResult(
|
||||
result: any,
|
||||
attempt_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
if (result) {
|
||||
if (result.hasError) {
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
invoice_id: itemResult.invoice_id,
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
})
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: lastAttempt!.id,
|
||||
id: attempt_id,
|
||||
},
|
||||
data: {
|
||||
status: itemResult.status,
|
||||
tax_id: itemResult.tax_id,
|
||||
request_payload: JSON.parse(JSON.stringify(itemResult.request_payload)),
|
||||
response_payload: JSON.parse(JSON.stringify(itemResult.response_payload)),
|
||||
error_message: itemResult.message,
|
||||
sent_at: itemResult.sent_at ? new Date(itemResult.sent_at) : new Date(),
|
||||
received_at: itemResult.received_at
|
||||
? new Date(itemResult.received_at)
|
||||
: new Date(),
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
return attempt
|
||||
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,
|
||||
},
|
||||
})
|
||||
attemptsResult.push(attempt)
|
||||
|
||||
return {
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
console.log(attemptsResult)
|
||||
|
||||
return attemptsResult
|
||||
}
|
||||
}
|
||||
|
||||
// {"type": "MAIN", "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"}
|
||||
// {"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"}
|
||||
|
||||
Reference in New Issue
Block a user