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,3 +1,7 @@
|
||||
import {
|
||||
SharedCreateSalesInvoiceItemDto,
|
||||
SharedCreateSalesInvoicePaymentsDto,
|
||||
} from '@/common/services/saleInvoices/sale-invoice-create.dto'
|
||||
import {
|
||||
CustomerType,
|
||||
InvoiceTemplateType,
|
||||
@@ -10,6 +14,7 @@ import {
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
@@ -142,7 +147,7 @@ export class TspProviderSendItemPayloadDto {
|
||||
payload?: unknown
|
||||
}
|
||||
|
||||
export class TspProviderSendPayloadDto {
|
||||
export class TspProviderOriginalSendPayloadDto {
|
||||
@ApiProperty({ required: true, enum: TspProviderRequestType })
|
||||
@IsEnum(TspProviderRequestType)
|
||||
type: TspProviderRequestType
|
||||
@@ -219,11 +224,14 @@ export class TspProviderSendItemResultDto {
|
||||
@IsString()
|
||||
tax_id?: string | null
|
||||
|
||||
@ApiProperty({ required: true, nullable: true, type: TspProviderSendPayloadDto })
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
nullable: true,
|
||||
type: TspProviderOriginalSendPayloadDto,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
@Type(() => TspProviderSendPayloadDto)
|
||||
request_payload: TspProviderSendPayloadDto
|
||||
request_payload: Object
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@@ -260,6 +268,8 @@ export class TspProviderBulkSendResultDto {
|
||||
items: TspProviderSendItemResultDto[]
|
||||
}
|
||||
|
||||
///////////// GET RELATED DTOs /////////////
|
||||
|
||||
export class TspProviderGetResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@@ -292,6 +302,8 @@ export class TspProviderGetResultDto {
|
||||
received_at: string
|
||||
}
|
||||
|
||||
///////////// REVOKE RELATED DTOs /////////////
|
||||
|
||||
export class TspProviderRevokePayloadDto {
|
||||
@ApiProperty({ required: true, nullable: true })
|
||||
@IsNumber()
|
||||
@@ -319,7 +331,7 @@ export class TspProviderRevokePayloadDto {
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
last_attempt_tax_id: string
|
||||
last_tax_id: string
|
||||
}
|
||||
|
||||
export class TspProviderRevokeResponseDto {
|
||||
@@ -363,10 +375,55 @@ export class TspProviderRevokeResponseDto {
|
||||
received_at: string
|
||||
}
|
||||
|
||||
///////////// CORRECTION RELATED DTOs /////////////
|
||||
export class TspProviderCorrectionInvoicePayloadDto {
|
||||
@ApiProperty({ type: [SharedCreateSalesInvoiceItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SharedCreateSalesInvoiceItemDto)
|
||||
@ArrayMinSize(1)
|
||||
items: SharedCreateSalesInvoiceItemDto[]
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: true, type: SharedCreateSalesInvoicePaymentsDto })
|
||||
@IsObject()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SharedCreateSalesInvoicePaymentsDto)
|
||||
payments: SharedCreateSalesInvoicePaymentsDto
|
||||
}
|
||||
export class TspProviderCorrectionSendPayloadDto extends TspProviderOriginalSendPayloadDto {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
last_tax_id: string
|
||||
}
|
||||
|
||||
export class TspProviderCorrectionSendResponseDto {}
|
||||
|
||||
export class TspProviderActionResponseDto {
|
||||
@IsObject()
|
||||
invoice: object
|
||||
|
||||
@IsString()
|
||||
message: string
|
||||
|
||||
@IsEnum(TspProviderResponseStatus)
|
||||
status: TspProviderResponseStatus
|
||||
}
|
||||
|
||||
export interface IProviderSwitchAdapter {
|
||||
readonly code: string
|
||||
send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto>
|
||||
sendBulk(payloads: TspProviderSendPayloadDto[]): Promise<TspProviderBulkSendResultDto[]>
|
||||
originalSend(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto>
|
||||
sendBulk(
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]>
|
||||
correctionSend(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto>
|
||||
get(invoiceId: string, tsp_token: string): Promise<TspProviderGetResultDto>
|
||||
revoke(payload: TspProviderRevokePayloadDto): Promise<TspProviderRevokeResponseDto>
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
TspProviderBulkSendResultDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderGetResultDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from './dto/provider-switch.dto'
|
||||
import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
|
||||
@@ -23,15 +25,24 @@ export class SalesInvoiceTspSwitchService {
|
||||
}
|
||||
}
|
||||
|
||||
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
|
||||
async send(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
return adapter.send(payload)
|
||||
return adapter.originalSend(payload)
|
||||
}
|
||||
|
||||
async correction(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
return adapter.correctionSend(payload)
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TspProviderSendPayloadDto[],
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]> {
|
||||
const groupedByProvider = new Map<string, TspProviderSendPayloadDto[]>()
|
||||
const groupedByProvider = new Map<string, TspProviderOriginalSendPayloadDto[]>()
|
||||
|
||||
for (const payload of payloads) {
|
||||
const key = payload.tsp_provider?.trim().toUpperCase() || 'NAMA'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { HttpClientUtil } from '@/common/utils'
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { NamaProviderUtils } from '@/modules/tspProviders/switch/nama/nama-provider.util'
|
||||
import { PrismaModule } from '@/prisma/prisma.module'
|
||||
import { Module } from '@nestjs/common'
|
||||
@@ -14,6 +15,7 @@ import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
NamaProviderUtils,
|
||||
SharedSaleInvoiceCreateService,
|
||||
],
|
||||
exports: [
|
||||
HttpClientUtil,
|
||||
@@ -21,6 +23,7 @@ import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
NamaProviderUtils,
|
||||
SharedSaleInvoiceCreateService,
|
||||
],
|
||||
})
|
||||
export class SaleInvoiceTspModule {}
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -9,11 +9,13 @@ import { Injectable, Logger } from '@nestjs/common'
|
||||
import {
|
||||
IProviderSwitchAdapter,
|
||||
TspProviderBulkSendResultDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderGetResultDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from '../../dto/provider-switch.dto'
|
||||
import {
|
||||
NamaProviderGetResponseDto,
|
||||
@@ -73,7 +75,9 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
]
|
||||
}
|
||||
|
||||
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
|
||||
async originalSend(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto> {
|
||||
const mappedRequest = this.namaProviderUtils.mapToNamaRequestDto(payload)
|
||||
try {
|
||||
console.log(mappedRequest)
|
||||
@@ -120,12 +124,60 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
async correctionSend(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto> {
|
||||
const mappedRequest = this.namaProviderUtils.mapToNamaRequestDto(payload)
|
||||
|
||||
try {
|
||||
const response = await this.httpClient.request(
|
||||
this.buildSendUrl(),
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(mappedRequest),
|
||||
},
|
||||
this.createRequestInterceptors(payload.tsp_token),
|
||||
)
|
||||
const providerResponse: NamaProviderSendItemResponseDto = await response.json()
|
||||
this.logger.debug('NAMA provider response', providerResponse)
|
||||
|
||||
const result: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
sent_at: new Date().toISOString(),
|
||||
response_payload: providerResponse,
|
||||
received_at: providerResponse.tsp_update_time,
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: this.namaProviderUtils.mapResponseStatus(
|
||||
providerResponse.status as NamaProviderResponseStatus,
|
||||
),
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (err) {
|
||||
this.logger.error('NAMA send failed', err)
|
||||
const failure: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
hasError: true,
|
||||
message: (err as Error).message,
|
||||
sent_at: new Date().toISOString(),
|
||||
received_at: new Date().toISOString(),
|
||||
tax_id: null,
|
||||
status: TspProviderResponseStatus.NOT_SEND,
|
||||
}
|
||||
return failure
|
||||
}
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TspProviderSendPayloadDto[],
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]> {
|
||||
const result: TspProviderBulkSendResultDto[] = []
|
||||
for (const payload of payloads) {
|
||||
const itemResults = await this.send(payload)
|
||||
const itemResults = await this.originalSend(payload)
|
||||
result.push({
|
||||
invoice_id: payload.invoice_id,
|
||||
items: [itemResults],
|
||||
|
||||
@@ -383,3 +383,163 @@ export class NamaProviderRevokeResponseDto {
|
||||
@IsString()
|
||||
tsp_update_time: string
|
||||
}
|
||||
|
||||
/////////////// Correction DTOs ///////////////
|
||||
export class NamaProviderCorrectionBodyItemDto {
|
||||
@ApiProperty({ required: true, description: 'شناسه کالا / خدمت' })
|
||||
@IsString()
|
||||
sstid: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: `نرخ مالیات بر ارزش افزوده`,
|
||||
})
|
||||
@IsString()
|
||||
vra: string
|
||||
|
||||
// @ApiProperty()
|
||||
// @IsString()
|
||||
// sstt: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'مبلغ واحد',
|
||||
})
|
||||
@IsString()
|
||||
fee: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'مبلغ تخفیف',
|
||||
})
|
||||
@IsString()
|
||||
dis: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'واحد اندازه گیری',
|
||||
})
|
||||
@IsString()
|
||||
mu: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'تعداد / مقدار',
|
||||
})
|
||||
@IsString()
|
||||
am: string
|
||||
|
||||
@ApiProperty({
|
||||
description: ' اجرت ساخت (طلا)',
|
||||
})
|
||||
@IsString()
|
||||
consfee: string
|
||||
|
||||
@ApiProperty({
|
||||
description: 'حق العمل',
|
||||
})
|
||||
@IsString()
|
||||
bros: string
|
||||
|
||||
@ApiProperty({
|
||||
description: 'سود فروشنده',
|
||||
})
|
||||
@IsString()
|
||||
spro: string
|
||||
}
|
||||
|
||||
export class NamaProviderCorrectionHeaderDto {
|
||||
@ApiProperty({ required: true, description: 'موضوع صورتحساب' })
|
||||
@IsString()
|
||||
ins: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'الگوی صورتحساب' })
|
||||
@IsString()
|
||||
inp: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'نوع صورتحساب' })
|
||||
@IsString()
|
||||
inty: string
|
||||
|
||||
// @ApiProperty({required: true})
|
||||
// @IsString()
|
||||
// unique_tax_code: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'سریال صورتحساب داخلی حافظه مالیاتی' })
|
||||
@IsString()
|
||||
inno: string
|
||||
|
||||
// @ApiProperty({ required: true })
|
||||
// @IsString()
|
||||
// tins: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'تاریخ و زمان صدور صورتحساب به صورت timestamp',
|
||||
})
|
||||
@IsString()
|
||||
indatim: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'نام مشتری' })
|
||||
@IsString()
|
||||
name: string
|
||||
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description:
|
||||
'نوع شخصیت خریدار (در صورتیکه خریدار نوع ۲ باشه باید ۱ یا ۲ گذاشته بشه)',
|
||||
})
|
||||
@IsString()
|
||||
tob: string
|
||||
|
||||
@ApiProperty({ description: 'آدرس' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
address?: string
|
||||
|
||||
@ApiProperty({ description: 'شماره موبایل' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mobile?: string
|
||||
|
||||
@ApiProperty({
|
||||
description: `شماره ملی / شناسه ملی / شناسه مشارکت مدنی / کد فراگیر خریدار`,
|
||||
})
|
||||
@IsString()
|
||||
bid: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'روش تسویه' })
|
||||
@IsString()
|
||||
setm: string
|
||||
}
|
||||
|
||||
export class NamaProviderCorrectionRequestDto {
|
||||
@ApiProperty({ type: [NamaProviderCorrectionBodyItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NamaProviderCorrectionBodyItemDto)
|
||||
body: NamaProviderCorrectionBodyItemDto[]
|
||||
|
||||
@ApiProperty({ type: [NamaProviderPaymentInfoDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NamaProviderPaymentInfoDto)
|
||||
payment: NamaProviderPaymentInfoDto[]
|
||||
|
||||
@ApiProperty({ type: NamaProviderCorrectionHeaderDto })
|
||||
@ValidateNested()
|
||||
@Type(() => NamaProviderCorrectionHeaderDto)
|
||||
header: NamaProviderCorrectionHeaderDto
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
uuid: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
economic_code: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
fiscal_id: string
|
||||
}
|
||||
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
import {
|
||||
CustomerInfoDto,
|
||||
PaymentInfoDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from '../../dto/provider-switch.dto'
|
||||
import {
|
||||
NamaProviderCorrectionRequestDto,
|
||||
NamaProviderPaymentInfoDto,
|
||||
NamaProviderRequestDto,
|
||||
NamaProviderResponseStatus,
|
||||
@@ -35,7 +37,9 @@ export class NamaProviderUtils {
|
||||
}
|
||||
}
|
||||
|
||||
mapToNamaRequestDto(payload: TspProviderSendPayloadDto): NamaProviderRequestDto {
|
||||
mapToNamaRequestDto(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): NamaProviderRequestDto {
|
||||
return {
|
||||
uuid: payload.invoice_id,
|
||||
economic_code: payload.economic_code,
|
||||
@@ -66,6 +70,39 @@ export class NamaProviderUtils {
|
||||
}
|
||||
}
|
||||
|
||||
mapToNamaCorrectionDto(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): NamaProviderCorrectionRequestDto {
|
||||
return {
|
||||
uuid: payload.invoice_id,
|
||||
economic_code: payload.economic_code,
|
||||
fiscal_id: payload.fiscal_id,
|
||||
payment: this.mapPayments(payload.payments),
|
||||
header: {
|
||||
ins: this.mapTspProviderRequestType(TspProviderRequestType.CORRECTION),
|
||||
inp: this.mapInvoiceTemplate(payload.invoice_template),
|
||||
inty: this.mapTspProviderCustomerType(payload.customer_type),
|
||||
inno: payload.invoice_number.toString(),
|
||||
tins: '',
|
||||
indatim: payload.invoice_date.getTime() + '',
|
||||
setm: '1',
|
||||
...this.mapCustomerInfo(payload.customer),
|
||||
},
|
||||
body: payload.items.map(item => ({
|
||||
sstid: item.sku,
|
||||
vra: item.sku_vat,
|
||||
// sstt: item.unit_type,
|
||||
fee: String(item.unit_price),
|
||||
dis: String(item.discount),
|
||||
mu: item.measure_unit,
|
||||
am: String(item.quantity),
|
||||
consfee: '0',
|
||||
bros: '0',
|
||||
spro: '0',
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
mapRevokeToNamaRequestDto(
|
||||
payload: TspProviderRevokePayloadDto,
|
||||
): NamaProviderRevokeRequestDto {
|
||||
@@ -76,7 +113,7 @@ export class NamaProviderUtils {
|
||||
header: {
|
||||
inno: payload.invoice_number.toString(),
|
||||
ins: this.mapTspProviderRequestType(TspProviderRequestType.REVOKE),
|
||||
irtaxid: payload.last_attempt_tax_id,
|
||||
irtaxid: payload.last_tax_id,
|
||||
indatim: new Date().getTime() + '',
|
||||
},
|
||||
}
|
||||
@@ -84,9 +121,9 @@ export class NamaProviderUtils {
|
||||
|
||||
private mapTspProviderRequestType(type: TspProviderRequestType) {
|
||||
switch (type) {
|
||||
case TspProviderRequestType.MAIN:
|
||||
case TspProviderRequestType.ORIGINAL:
|
||||
return '1'
|
||||
case TspProviderRequestType.UPDATE:
|
||||
case TspProviderRequestType.CORRECTION:
|
||||
return '2'
|
||||
case TspProviderRequestType.REVOKE:
|
||||
return '3'
|
||||
|
||||
Reference in New Issue
Block a user