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:
@@ -39,9 +39,9 @@ export class GuildsService {
|
||||
const guild = await this.prisma.guild.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
business_activities: {
|
||||
omit: {
|
||||
guild_id: true,
|
||||
_count: {
|
||||
select: {
|
||||
business_activities: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
+47
-23
@@ -5,7 +5,6 @@ import {
|
||||
import {
|
||||
PartnerAccountQuotaChargeTransactionSelect,
|
||||
PartnerAccountQuotaChargeTransactionWhereInput,
|
||||
PartnerAccountQuotaCreditCreateInput,
|
||||
} from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
@@ -18,6 +17,8 @@ export class PartnerAccountChargeTransactionService {
|
||||
|
||||
private readonly TRACKING_CODE_LENGTH = 8
|
||||
private readonly TRACKING_CODE_MAX_ATTEMPTS = 5
|
||||
private readonly QUOTA_BATCH_SIZE = 200
|
||||
private readonly MAX_QUANTITY_PER_REQUEST = 1000
|
||||
|
||||
private readonly mappedTransaction = (transaction: any) => {
|
||||
const { allocations, purchased_count, _count, ...rest } = transaction
|
||||
@@ -90,19 +91,28 @@ export class PartnerAccountChargeTransactionService {
|
||||
}
|
||||
|
||||
async create(partner_id: string, data: ChargeAccountQuotaDto) {
|
||||
if (data.quantity > this.MAX_QUANTITY_PER_REQUEST) {
|
||||
throw new BadRequestException(
|
||||
`تعداد درخواستی بیش از حد مجاز است. حداکثر ${this.MAX_QUANTITY_PER_REQUEST} عدد مجاز است.`,
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.prisma.$transaction(async tx => {
|
||||
let transaction: { id: string } | null = null
|
||||
const transaction = await this.prisma.$transaction(async tx => {
|
||||
let createdTransaction: { id: string } | null = null
|
||||
|
||||
for (let attempt = 0; attempt < this.TRACKING_CODE_MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
transaction = await tx.partnerAccountQuotaChargeTransaction.create({
|
||||
createdTransaction = await tx.partnerAccountQuotaChargeTransaction.create({
|
||||
data: {
|
||||
activation_expires_at: data.activated_expires_at,
|
||||
tracking_code: generateTrackingCode('AQC', this.TRACKING_CODE_LENGTH),
|
||||
purchased_count: data.quantity,
|
||||
partner: { connect: { id: partner_id } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
})
|
||||
break
|
||||
} catch (error) {
|
||||
@@ -116,33 +126,47 @@ export class PartnerAccountChargeTransactionService {
|
||||
}
|
||||
}
|
||||
|
||||
if (!transaction) {
|
||||
if (!createdTransaction) {
|
||||
throw new BadRequestException('متاسفانه مشکلی پیش آمده است.')
|
||||
}
|
||||
|
||||
const creditCreationPromises: any[] = []
|
||||
for (let i = 0; i < data.quantity; i++) {
|
||||
const credit: PartnerAccountQuotaCreditCreateInput = {
|
||||
charge_transaction: {
|
||||
connect: {
|
||||
id: transaction.id,
|
||||
},
|
||||
},
|
||||
}
|
||||
return createdTransaction
|
||||
})
|
||||
|
||||
creditCreationPromises.push(
|
||||
tx.partnerAccountQuotaCredit.create({ data: credit }),
|
||||
)
|
||||
}
|
||||
const createdCredits = await Promise.all(creditCreationPromises)
|
||||
this.scheduleQuotaCreditProvisioning(transaction.id, data.quantity)
|
||||
|
||||
if (createdCredits.some(createdCredit => createdCredit.activation_id === null)) {
|
||||
throw new BadRequestException('متاسفانه مشکلی پیش آمده است. ')
|
||||
}
|
||||
return { transaction, createdCredits }
|
||||
return ResponseMapper.create({
|
||||
transaction_id: transaction.id,
|
||||
charged_license_count: data.quantity,
|
||||
status: 'QUEUED',
|
||||
})
|
||||
} catch (error) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleQuotaCreditProvisioning(transactionId: string, quantity: number) {
|
||||
setTimeout(() => {
|
||||
this.provisionQuotaCreditsInBackground(transactionId, quantity).catch(() => null)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
private async provisionQuotaCreditsInBackground(
|
||||
transactionId: string,
|
||||
quantity: number,
|
||||
) {
|
||||
let createdCount = 0
|
||||
|
||||
while (createdCount < quantity) {
|
||||
const batchSize = Math.min(this.QUOTA_BATCH_SIZE, quantity - createdCount)
|
||||
|
||||
await this.prisma.partnerAccountQuotaCredit.createMany({
|
||||
data: Array.from({ length: batchSize }, () => ({
|
||||
charge_transaction_id: transactionId,
|
||||
})),
|
||||
})
|
||||
|
||||
createdCount += batchSize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+46
-25
@@ -5,7 +5,6 @@ import {
|
||||
import {
|
||||
LicenseChargeTransactionSelect,
|
||||
LicenseChargeTransactionWhereInput,
|
||||
LicenseCreateInput,
|
||||
} from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
@@ -18,6 +17,8 @@ export class PartnerLicenseChargeTransactionService {
|
||||
|
||||
private readonly TRACKING_CODE_LENGTH = 8
|
||||
private readonly TRACKING_CODE_MAX_ATTEMPTS = 5
|
||||
private readonly LICENSE_BATCH_SIZE = 200
|
||||
private readonly MAX_QUANTITY_PER_REQUEST = 1000
|
||||
|
||||
private readonly mappedTransaction = (transaction: any) => {
|
||||
const { licenses, purchased_count, _count, ...rest } = transaction
|
||||
@@ -78,7 +79,7 @@ export class PartnerLicenseChargeTransactionService {
|
||||
}
|
||||
|
||||
async findOne(partner_id: string, id: string) {
|
||||
const transaction = this.prisma.licenseChargeTransaction.findUniqueOrThrow({
|
||||
const transaction = await this.prisma.licenseChargeTransaction.findUniqueOrThrow({
|
||||
where: {
|
||||
id,
|
||||
partner_id,
|
||||
@@ -89,19 +90,29 @@ export class PartnerLicenseChargeTransactionService {
|
||||
}
|
||||
|
||||
async create(partner_id: string, data: ChargeLicenseDto) {
|
||||
if (data.quantity > this.MAX_QUANTITY_PER_REQUEST) {
|
||||
throw new BadRequestException(
|
||||
`تعداد درخواستی بیش از حد مجاز است. حداکثر ${this.MAX_QUANTITY_PER_REQUEST} عدد مجاز است.`,
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.prisma.$transaction(async tx => {
|
||||
let transaction: { id: string } | null = null
|
||||
const transaction = await this.prisma.$transaction(async tx => {
|
||||
let createdTransaction: { id: string; purchased_count: number } | null = null
|
||||
|
||||
for (let attempt = 0; attempt < this.TRACKING_CODE_MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
transaction = await tx.licenseChargeTransaction.create({
|
||||
createdTransaction = await tx.licenseChargeTransaction.create({
|
||||
data: {
|
||||
activation_expires_at: data.activated_expires_at,
|
||||
tracking_code: generateTrackingCode('LIC', this.TRACKING_CODE_LENGTH),
|
||||
purchased_count: data.quantity,
|
||||
partner: { connect: { id: partner_id } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
purchased_count: true,
|
||||
},
|
||||
})
|
||||
break
|
||||
} catch (error) {
|
||||
@@ -115,33 +126,43 @@ export class PartnerLicenseChargeTransactionService {
|
||||
}
|
||||
}
|
||||
|
||||
if (!transaction) {
|
||||
if (!createdTransaction) {
|
||||
throw new BadRequestException('متاسفانه مشکلی پیش آمده است.')
|
||||
}
|
||||
|
||||
const licenseCreationPromises: any[] = []
|
||||
for (let i = 0; i < data.quantity; i++) {
|
||||
const license: LicenseCreateInput = {
|
||||
charge_transaction: {
|
||||
connect: {
|
||||
id: transaction.id,
|
||||
},
|
||||
},
|
||||
}
|
||||
return createdTransaction
|
||||
})
|
||||
|
||||
licenseCreationPromises.push(tx.license.create({ data: license }))
|
||||
}
|
||||
const createdLicenses = await Promise.all(licenseCreationPromises)
|
||||
|
||||
if (
|
||||
createdLicenses.some(createdLicense => createdLicense.activation_id === null)
|
||||
) {
|
||||
throw new BadRequestException('متاسفانه مشکلی پیش آمده است. ')
|
||||
}
|
||||
return { transaction, createdLicenses }
|
||||
this.scheduleLicenseProvisioning(transaction.id, transaction.purchased_count)
|
||||
return ResponseMapper.create({
|
||||
transaction_id: transaction.id,
|
||||
charged_license_count: transaction.purchased_count,
|
||||
status: 'QUEUED',
|
||||
})
|
||||
} catch (error) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleLicenseProvisioning(transactionId: string, quantity: number) {
|
||||
setTimeout(() => {
|
||||
this.provisionLicensesInBackground(transactionId, quantity).catch(() => null)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
private async provisionLicensesInBackground(transactionId: string, quantity: number) {
|
||||
let createdCount = 0
|
||||
|
||||
while (createdCount < quantity) {
|
||||
const batchSize = Math.min(this.LICENSE_BATCH_SIZE, quantity - createdCount)
|
||||
|
||||
await this.prisma.license.createMany({
|
||||
data: Array.from({ length: batchSize }, () => ({
|
||||
charge_transaction_id: transactionId,
|
||||
})),
|
||||
})
|
||||
|
||||
createdCount += batchSize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { UploadedFileTypes } from '@/common/enums/enums'
|
||||
import { translateEnumValue } from '@/common/utils'
|
||||
import { PasswordUtil } from '@/common/utils/password.util'
|
||||
import {
|
||||
AccountStatus,
|
||||
@@ -87,6 +88,7 @@ export class PartnersService {
|
||||
license_charge_transactions,
|
||||
account_quota_charge_transactions,
|
||||
license_renew_charge_transactions,
|
||||
status,
|
||||
...rest
|
||||
} = partner
|
||||
|
||||
@@ -127,6 +129,7 @@ export class PartnersService {
|
||||
})
|
||||
return {
|
||||
...rest,
|
||||
status: translateEnumValue('PartnerStatus', status),
|
||||
licenses_status,
|
||||
license_renew_status,
|
||||
account_quota_status,
|
||||
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
import type { SalesInvoiceItemsService } from '../sales-invoice-items.service'
|
||||
|
||||
export type SalesInvoiceItemsServiceCreateResponseDto = Awaited<ReturnType<SalesInvoiceItemsService['create']>>
|
||||
export type SalesInvoiceItemsServiceFindAllResponseDto = Awaited<ReturnType<SalesInvoiceItemsService['findAll']>>
|
||||
export type SalesInvoiceItemsServiceFindOneResponseDto = Awaited<ReturnType<SalesInvoiceItemsService['findOne']>>
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common'
|
||||
import { SalesInvoiceItemsService } from './sales-invoice-items.service'
|
||||
|
||||
@Controller('sales_invoice_items')
|
||||
export class SalesInvoiceItemsController {
|
||||
constructor(private readonly salesInvoiceItemsService: SalesInvoiceItemsService) {}
|
||||
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.salesInvoiceItemsService.findAll()
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.salesInvoiceItemsService.findOne(+id)
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() data: any) {
|
||||
return this.salesInvoiceItemsService.create(data)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { SalesInvoiceItemsController } from './sales-invoice-items.controller'
|
||||
import { SalesInvoiceItemsService } from './sales-invoice-items.service'
|
||||
|
||||
@Module({
|
||||
controllers: [SalesInvoiceItemsController],
|
||||
providers: [SalesInvoiceItemsService],
|
||||
})
|
||||
export class SalesInvoiceItemsModule {}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceItemsService {
|
||||
findAll() {
|
||||
// TODO: Implement fetching all sales invoice items
|
||||
return []
|
||||
}
|
||||
|
||||
findOne(id: number) {
|
||||
// TODO: Implement fetching a single sales invoice item
|
||||
return {}
|
||||
}
|
||||
|
||||
create(data: any) {
|
||||
// TODO: Implement sales invoice item creation
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -230,7 +230,7 @@ export class SalesInvoicesService {
|
||||
}
|
||||
|
||||
async create(data: CreateSalesInvoiceDto, posInfo: IPosPayload) {
|
||||
const salesInvoice = await this.sharedSaleInvoiceCreateService.create({
|
||||
let salesInvoice = await this.sharedSaleInvoiceCreateService.create({
|
||||
data,
|
||||
businessId: posInfo.business_id,
|
||||
complexId: posInfo.complex_id,
|
||||
@@ -240,7 +240,13 @@ export class SalesInvoicesService {
|
||||
})
|
||||
|
||||
if (data.send_to_tsp) {
|
||||
await this.salesInvoiceTaxService.originalSend(salesInvoice.id, posInfo.pos_id)
|
||||
const providerResponse = await this.salesInvoiceTaxService.originalSend(
|
||||
salesInvoice.id,
|
||||
posInfo.pos_id,
|
||||
)
|
||||
if (providerResponse?.invoice) {
|
||||
salesInvoice = providerResponse?.invoice as any
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseMapper.create(salesInvoice)
|
||||
|
||||
@@ -231,12 +231,12 @@ export class TspProviderSendItemResultDto {
|
||||
})
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
request_payload: Object
|
||||
provider_request_payload: Object
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
response_payload?: unknown
|
||||
provider_response_payload?: Object
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsBoolean()
|
||||
@@ -291,7 +291,7 @@ export class TspProviderGetResultDto {
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
response_payload?: unknown
|
||||
provider_response_payload?: Object
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
@@ -359,12 +359,12 @@ export class TspProviderRevokeResponseDto {
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
request_payload?: unknown
|
||||
provider_request_payload?: unknown
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
response_payload?: unknown
|
||||
provider_response_payload?: unknown
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
import {
|
||||
TspProviderBulkSendResultDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
@@ -18,17 +18,25 @@ export class SalesInvoiceTspSwitchService {
|
||||
private resolveSwitch(providerCode: string) {
|
||||
const normalizedCode = providerCode.trim().toUpperCase() || ''
|
||||
|
||||
let adapter: NamaProviderSwitchAdapter | null = null
|
||||
switch (normalizedCode) {
|
||||
case 'NAMA':
|
||||
default:
|
||||
return this.namaAdapter
|
||||
adapter = this.namaAdapter
|
||||
}
|
||||
|
||||
if (!adapter) {
|
||||
throw new BadRequestException(
|
||||
`${providerCode} برای ارسال انتخاب شده است که در حال حاضر پشتیبانی نمی شود.`,
|
||||
)
|
||||
}
|
||||
return adapter
|
||||
}
|
||||
|
||||
async send(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
|
||||
return adapter.originalSend(payload)
|
||||
}
|
||||
|
||||
@@ -36,6 +44,7 @@ export class SalesInvoiceTspSwitchService {
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
|
||||
return adapter.correctionSend(payload)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,12 +95,12 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
|
||||
const result: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: payload,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
sent_at: new Date().toISOString(),
|
||||
response_payload: providerResponse,
|
||||
provider_response_payload: JSON.parse(JSON.stringify(providerResponse)),
|
||||
received_at: providerResponse.tsp_update_time,
|
||||
sent_at: new Date().toISOString(),
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: this.namaProviderUtils.mapResponseStatus(
|
||||
providerResponse.status as NamaProviderResponseStatus,
|
||||
@@ -112,7 +112,7 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
this.logger.error('NAMA send failed', err)
|
||||
const failure: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: payload,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: true,
|
||||
message: (err as Error).message,
|
||||
sent_at: new Date().toISOString(),
|
||||
@@ -143,11 +143,11 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
|
||||
const result: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
sent_at: new Date().toISOString(),
|
||||
response_payload: providerResponse,
|
||||
provider_response_payload: JSON.parse(JSON.stringify(providerResponse)),
|
||||
received_at: providerResponse.tsp_update_time,
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: this.namaProviderUtils.mapResponseStatus(
|
||||
@@ -160,7 +160,7 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
this.logger.error('NAMA send failed', err)
|
||||
const failure: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: true,
|
||||
message: (err as Error).message,
|
||||
sent_at: new Date().toISOString(),
|
||||
@@ -201,7 +201,7 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
const result: TspProviderGetResultDto = {
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
response_payload: providerResponse,
|
||||
provider_response_payload: providerResponse,
|
||||
sent_at: new Date().toISOString(),
|
||||
received_at: providerResponse.tsp_update_time || new Date().toISOString(),
|
||||
tax_id: providerResponse.tax_id,
|
||||
@@ -248,11 +248,11 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
|
||||
const result: TspProviderRevokeResponseDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
sent_at: new Date().toISOString(),
|
||||
response_payload: providerResponse,
|
||||
provider_response_payload: providerResponse,
|
||||
received_at: providerResponse.tsp_update_time,
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: this.namaProviderUtils.mapResponseStatus(
|
||||
@@ -265,7 +265,7 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
this.logger.error('NAMA Revoke failed', err)
|
||||
const failure: TspProviderRevokeResponseDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
provider_request_payload: JSON.parse(JSON.stringify(mappedRequest)),
|
||||
hasError: true,
|
||||
message: (err as Error).message,
|
||||
sent_at: new Date().toISOString(),
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
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<number> {
|
||||
let attemptNumber = 1
|
||||
|
||||
const existingAttempt = await 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
|
||||
}
|
||||
|
||||
export async function buildRevokePayload(
|
||||
prisma: PrismaService,
|
||||
invoiceId: string,
|
||||
posId: string,
|
||||
): Promise<TspProviderRevokePayloadDto> {
|
||||
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<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)!
|
||||
|
||||
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<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,
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildPayload(
|
||||
prisma: PrismaService,
|
||||
invoiceId: string,
|
||||
posId: string,
|
||||
): Promise<TspProviderOriginalSendPayloadDto> {
|
||||
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<string, any>)?.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<TspProviderSendItemResultDto | null>
|
||||
},
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto | null> {
|
||||
return (await tspSwitchService.send(payload)) || null
|
||||
}
|
||||
|
||||
export async function onResult(
|
||||
prisma: PrismaService,
|
||||
result: any,
|
||||
attempt_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
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,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user