refactor: remove SalesInvoiceItemsService and update sales invoice handling
- Deleted SalesInvoiceItemsService as it was not implemented. - Changed variable declaration from `const` to `let` in SalesInvoicesService for sales invoice creation. - Updated response handling after sending to TSP provider in SalesInvoicesService. - Renamed payload properties in TspProvider DTOs for clarity. - Enhanced error handling in SalesInvoiceTspSwitchService for unsupported providers. - Refactored SalesInvoiceTspService to utilize utility functions for payload building and sending. - Updated PrismaService to increase connection limit and utilize dynamic options. - Added new migration scripts to update database schema for sale_invoice_tsp_attempts. - Introduced utility functions for building payloads and handling responses in sales invoice processing.
This commit is contained in:
@@ -1,22 +1,24 @@
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
|
||||
import { TspProviderCustomerType } from 'common/enums/enums'
|
||||
import {
|
||||
CustomerType,
|
||||
Prisma,
|
||||
TspProviderRequestType,
|
||||
TspProviderResponseStatus,
|
||||
} from 'generated/prisma/client'
|
||||
import {
|
||||
TspProviderActionResponseDto,
|
||||
TspProviderCorrectionInvoicePayloadDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderSendItemResultDto,
|
||||
} from './dto/provider-switch.dto'
|
||||
import { SalesInvoiceTspSwitchService } from './sales-invoice-tsp-switch.service'
|
||||
import {
|
||||
buildCorrectionPayload,
|
||||
buildPayload,
|
||||
buildRevokePayload,
|
||||
getOriginalResendAttemptNumber,
|
||||
onResult,
|
||||
trySend,
|
||||
} from './utils/sales-invoice-tsp.utils'
|
||||
|
||||
type ItemTspRow = {
|
||||
tsp_provider: string | null
|
||||
@@ -35,23 +37,23 @@ export class SalesInvoiceTspService {
|
||||
posId: string,
|
||||
invoice_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
const payload = await this.buildPayload(invoice_id, posId)
|
||||
const payload = await buildPayload(this.prisma, invoice_id, posId)
|
||||
|
||||
const attemptNumber = await this.getOriginalResendAttemptNumber(invoice_id)
|
||||
const attemptNumber = await getOriginalResendAttemptNumber(this.prisma, invoice_id)
|
||||
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: attemptNumber,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
raw_request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await this.trySend(payload)
|
||||
const result = await trySend(this.tspSwitchService, payload)
|
||||
|
||||
return await this.onResult(result, attempt.id)
|
||||
return await onResult(this.prisma, result, attempt.id)
|
||||
}
|
||||
|
||||
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
|
||||
@@ -160,7 +162,7 @@ export class SalesInvoiceTspService {
|
||||
id: attempt.id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(result)),
|
||||
provider_response_payload: JSON.parse(JSON.stringify(result)),
|
||||
status: result.status,
|
||||
received_at: result.received_at,
|
||||
},
|
||||
@@ -241,7 +243,7 @@ export class SalesInvoiceTspService {
|
||||
type: TspProviderRequestType.CORRECTION,
|
||||
})
|
||||
|
||||
const correctionPayload = await this.buildCorrectionPayload(tx, newInvoice.id)
|
||||
const correctionPayload = await buildCorrectionPayload(tx, newInvoice.id)
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
@@ -249,7 +251,8 @@ export class SalesInvoiceTspService {
|
||||
invoice_id: newInvoice.id,
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
request_payload: JSON.parse(JSON.stringify(correctionPayload)),
|
||||
sent_at: new Date().toISOString(),
|
||||
raw_request_payload: JSON.parse(JSON.stringify(correctionPayload)),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -257,11 +260,11 @@ export class SalesInvoiceTspService {
|
||||
},
|
||||
)
|
||||
|
||||
const result = await this.trySend(correctionPayload)
|
||||
const result = await trySend(this.tspSwitchService, correctionPayload)
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(result)
|
||||
return this.onResult(result, attempt.id)
|
||||
return onResult(this.prisma, result, attempt.id)
|
||||
|
||||
// const countByGoodId = (goodIds: string[]): Map<string, number> => {
|
||||
// const counts = new Map<string, number>()
|
||||
@@ -428,7 +431,7 @@ export class SalesInvoiceTspService {
|
||||
type: TspProviderRequestType.REVOKE,
|
||||
})
|
||||
|
||||
const payload = await this.buildRevokePayload(newInvoice.id, posId)
|
||||
const payload = await buildRevokePayload(this.prisma, newInvoice.id, posId)
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
@@ -436,7 +439,7 @@ export class SalesInvoiceTspService {
|
||||
invoice_id: newInvoice.id,
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
raw_request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -446,496 +449,6 @@ export class SalesInvoiceTspService {
|
||||
|
||||
const result = await this.tspSwitchService.revoke(revokePayload)
|
||||
|
||||
return await this.onResult(result, attempt.id)
|
||||
}
|
||||
|
||||
private async getOriginalResendAttemptNumber(invoice_id: string): Promise<number> {
|
||||
let attemptNumber = 1
|
||||
|
||||
const existingAttempt = await this.prisma.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
invoice_id,
|
||||
},
|
||||
include: {
|
||||
invoice: {
|
||||
select: {
|
||||
type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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,
|
||||
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,
|
||||
}
|
||||
return returnData
|
||||
}
|
||||
|
||||
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 trySend(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto | null> {
|
||||
const taxResult = await this.tspSwitchService.send(payload)
|
||||
|
||||
return taxResult || null
|
||||
}
|
||||
|
||||
private async onResult(
|
||||
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:
|
||||
result.message?.toString() || 'فاکتور با موفقیت به سامانه مالیاتی ارسال شد.',
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
message: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
return await onResult(this.prisma, result, attempt.id)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user