feat: implement SalesInvoiceTspSwitchService and SalesInvoiceTspService for handling TSP provider interactions

- Add SalesInvoiceTspSwitchService to manage TSP provider selection and sending invoices.
- Introduce SalesInvoiceTspService for creating, sending, and retrieving sales invoices.
- Implement NamaProviderSwitchAdapter for communication with the NAMA TSP provider API.
- Define DTOs for request and response structures specific to the NAMA provider.
- Enhance error handling and logging for TSP provider interactions.
This commit is contained in:
2026-05-03 16:23:17 +03:30
parent ad470d2166
commit a486127ade
62 changed files with 4136 additions and 5015 deletions
@@ -0,0 +1,300 @@
import {
CustomerType,
InvoiceTemplateType,
PaymentMethodType,
TspProviderCustomerType,
TspProviderRequestType,
TspProviderResponseStatus,
TspProviderType,
} from '@/generated/prisma/enums'
import { ApiProperty } from '@nestjs/swagger'
import { Type } from 'class-transformer'
import {
IsArray,
IsBoolean,
IsDateString,
IsEnum,
IsNumber,
IsObject,
IsOptional,
IsString,
Min,
ValidateNested,
} from 'class-validator'
export class CustomerLegalInfoDto {
@ApiProperty({ required: true })
@IsString()
name: string
@ApiProperty({ required: true })
@IsString()
economic_code: string
}
export class CustomerIndividualInfoDto {
@ApiProperty({ required: true })
@IsString()
first_name: string
@ApiProperty({ required: true })
@IsString()
last_name: string
@ApiProperty({ required: true })
@IsString()
national_id: string
@ApiProperty({ required: true })
@IsString()
mobile_number: string
}
export class CustomerInfoDto {
@ApiProperty({ required: true, enum: CustomerType })
@IsEnum(CustomerType)
type: CustomerType
@ApiProperty({})
@Type(() => CustomerLegalInfoDto)
@ValidateNested({ each: true })
legal_info?: CustomerLegalInfoDto
@ApiProperty({})
@Type(() => CustomerIndividualInfoDto)
@ValidateNested({ each: true })
individual_info?: CustomerIndividualInfoDto
}
export class PaymentInfoDto {
@ApiProperty({ required: true, enum: PaymentMethodType })
@IsEnum(PaymentMethodType)
payment_method: PaymentMethodType
@ApiProperty({ required: true })
@IsNumber({ allowInfinity: false, allowNaN: false })
@Min(10_000)
amount: number
@ApiProperty({ required: false })
@IsOptional()
@IsString()
tracking_code?: string
@ApiProperty({ required: false })
@IsOptional()
@IsString()
card_number?: string
@ApiProperty({ required: false })
@IsOptional()
@IsDateString()
paid_at?: Date
}
export class TspProviderSendItemPayloadDto {
@ApiProperty({ required: true })
@IsString()
sku: string
@ApiProperty({ required: true })
@IsString()
sku_vat: string
@ApiProperty()
@IsOptional()
@IsString()
discount: string
@ApiProperty({ required: true })
@IsNumber()
unit_price: number
@ApiProperty()
@IsString()
invoice_item_id: string
@ApiProperty()
@IsNumber()
quantity: number
@ApiProperty()
@IsNumber()
total_amount: number
@ApiProperty({ required: true })
@IsString()
measure_unit: string
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
good_id?: string | null
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
service_id?: string | null
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
payload?: unknown
}
export class TspProviderSendPayloadDto {
@ApiProperty({ required: true, enum: TspProviderRequestType })
@IsEnum(TspProviderRequestType)
type: TspProviderRequestType
@ApiProperty({ required: true, enum: TspProviderCustomerType })
@IsEnum(TspProviderCustomerType)
customer_type: TspProviderCustomerType
@ApiProperty({ type: [TspProviderSendItemPayloadDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => TspProviderSendItemPayloadDto)
items: TspProviderSendItemPayloadDto[]
@ApiProperty({ required: false })
@Type(() => CustomerInfoDto)
@ValidateNested({ each: true })
customer?: CustomerInfoDto
@ApiProperty({ required: true, nullable: true })
@IsNumber()
invoice_number: number
@ApiProperty({ required: true, nullable: true })
@IsDateString()
invoice_date: Date
@ApiProperty({ required: true, nullable: true })
@IsString()
invoice_id: string
@ApiProperty()
@IsNumber()
total_amount: number
@ApiProperty({ required: true, enum: TspProviderType })
@IsEnum(TspProviderType)
tsp_provider: TspProviderType
@ApiProperty({ required: true, nullable: true })
@IsString()
economic_code: string
@ApiProperty({ required: true, nullable: true })
@IsString()
fiscal_id: string
@ApiProperty({ required: true, type: [PaymentInfoDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => PaymentInfoDto)
payments: PaymentInfoDto[]
@ApiProperty({ required: true, enum: InvoiceTemplateType })
@IsEnum(InvoiceTemplateType)
invoice_template: InvoiceTemplateType
@ApiProperty({ required: true })
@IsString()
tsp_token: string
}
export class TspProviderSendItemResultDto {
@ApiProperty()
@IsString()
invoice_id: string
@ApiProperty({ enum: TspProviderResponseStatus })
@IsEnum(TspProviderResponseStatus)
status: TspProviderResponseStatus
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
tax_id?: string | null
@ApiProperty({ required: true, nullable: true, type: TspProviderSendPayloadDto })
@IsOptional()
@IsObject()
@Type(() => TspProviderSendPayloadDto)
request_payload: TspProviderSendPayloadDto
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
response_payload?: unknown
@ApiProperty({ required: true })
@IsBoolean()
hasError: boolean
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
message?: string | null
@ApiProperty({ required: true })
@IsDateString()
sent_at: string
@ApiProperty({ required: true })
@IsDateString()
received_at: string
}
export class TspProviderBulkSendResultDto {
@ApiProperty()
@IsString()
invoice_id: string
@ApiProperty({ type: [TspProviderSendItemResultDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => TspProviderSendItemResultDto)
items: TspProviderSendItemResultDto[]
}
export class TspProviderGetResultDto {
@ApiProperty()
@IsString()
tax_id: string
@ApiProperty({ enum: TspProviderResponseStatus })
@IsEnum(TspProviderResponseStatus)
status: TspProviderResponseStatus
@ApiProperty({ required: true })
@IsBoolean()
hasError: boolean
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
message?: string | null
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
response_payload?: unknown
@ApiProperty({ required: true })
@IsDateString()
sent_at: string
@ApiProperty({ required: true })
@IsDateString()
received_at: string
}
export interface IProviderSwitchAdapter {
readonly code: string
send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto>
sendBulk(payloads: TspProviderSendPayloadDto[]): Promise<TspProviderBulkSendResultDto[]>
get(invoiceId: string, tsp_token: string): Promise<TspProviderGetResultDto>
}
@@ -0,0 +1,59 @@
import { Injectable } from '@nestjs/common'
import {
TspProviderBulkSendResultDto,
TspProviderGetResultDto,
TspProviderSendItemResultDto,
TspProviderSendPayloadDto,
} from './dto/provider-switch.dto'
import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
@Injectable()
export class SalesInvoiceTspSwitchService {
constructor(private readonly namaAdapter: NamaProviderSwitchAdapter) {}
private resolveSwitch(providerCode: string) {
const normalizedCode = providerCode.trim().toUpperCase() || ''
switch (normalizedCode) {
case 'NAMA':
default:
return this.namaAdapter
}
}
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
const adapter = this.resolveSwitch(payload.tsp_provider)
return adapter.send(payload)
}
async sendBulk(
payloads: TspProviderSendPayloadDto[],
): Promise<TspProviderBulkSendResultDto[]> {
const groupedByProvider = new Map<string, TspProviderSendPayloadDto[]>()
for (const payload of payloads) {
const key = payload.tsp_provider?.trim().toUpperCase() || 'NAMA'
const currentGroup = groupedByProvider.get(key) || []
currentGroup.push(payload)
groupedByProvider.set(key, currentGroup)
}
const result: TspProviderBulkSendResultDto[] = []
for (const [providerCode, groupedPayloads] of groupedByProvider.entries()) {
const adapter = this.resolveSwitch(providerCode)
const providerResult = await adapter.sendBulk(groupedPayloads)
result.push(...providerResult)
}
return result
}
async get(
providerCode: string,
invoiceId: string,
tspToken: string,
): Promise<TspProviderGetResultDto> {
const adapter = this.resolveSwitch(providerCode)
return await adapter.get(invoiceId, tspToken)
}
}
@@ -0,0 +1,595 @@
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
import {
TspProviderCustomerType,
TspProviderRequestType,
TspProviderResponseStatus,
} from 'generated/prisma/client'
import { CreateSalesInvoiceDto } from '../pos/sales-invoices/dto/create-sales-invoice.dto'
import {
TspProviderSendItemResultDto,
TspProviderSendPayloadDto,
} from './dto/provider-switch.dto'
import { SalesInvoiceTspSwitchService } from './sales-invoice-tsp-switch.service'
type ItemTspRow = {
tsp_provider: string | null
tax_id: string | null
}
type IAttempt = any
@Injectable()
export class SalesInvoiceTspService {
constructor(
private readonly prisma: PrismaService,
private readonly tspSwitchService: SalesInvoiceTspSwitchService,
) {}
async send(consumer_id: string, invoice_id: string): Promise<IAttempt> {
const posId = await this.getPosId(consumer_id, invoice_id)
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)),
},
})
const sendResult = 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(
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
)
}
}
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)
}
async get(invoice_id: string, pos_id: string, consumer_id: string): Promise<IAttempt> {
const [attempt, pos] = await this.prisma.$transaction(async tx => [
await tx.saleInvoiceTspAttempts.findFirst({
where: {
invoice_id,
invoice: {
pos: {
id: pos_id,
},
},
},
orderBy: {
attempt_no: 'desc',
},
}),
await tx.pos.findUnique({
where: {
id: pos_id,
complex: {
business_activity: {
consumer_id,
},
},
},
select: {
complex: {
select: {
business_activity: {
select: {
partner_token: true,
consumer: {
select: {
legal: {
select: {
partner: {
select: {
tsp_provider: true,
},
},
},
},
individual: {
select: {
partner: {
select: {
tsp_provider: true,
},
},
},
},
},
},
},
},
},
},
},
}),
])
if (!attempt) {
throw new NotFoundException('صورت‌حساب ارسالی فاکتور شما به سامانه یافت نشد.')
}
if (!pos) {
throw new NotFoundException('مشکلی در ساختار اطلاعات ورودی شما وجود دارد.')
}
const { business_activity } = pos.complex
const { partner } = (business_activity.consumer.individual ||
business_activity.consumer.legal)!
const result = await this.tspSwitchService.get(
partner.tsp_provider,
invoice_id,
business_activity.partner_token,
)
console.log('getResult', result)
if (!result) {
throw new NotFoundException('نتیجه ارسال فاکتور یافت نشد.')
}
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
where: {
id: attempt.id,
},
data: {
response_payload: JSON.parse(JSON.stringify(result)),
status: result.status,
received_at: result.received_at,
},
select: {
status: true,
invoice: true,
},
})
return {
...updatedAttempt.invoice,
status: updatedAttempt.status,
}
}
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,
},
},
},
},
},
orderBy: {
attempt_no: 'desc',
},
include: {
invoice: {
include: {
items: {
include: {
good: true,
},
},
payments: {
include: {
terminal_info: true,
},
},
},
},
},
})
if (!lastAttempt || lastAttempt?.status === TspProviderResponseStatus.QUEUED) {
throw new BadRequestException(
'فاکتور هنوز به سامانه مالیاتی ارسال نشده است یا در صف ارسال قرار دارد. لطفا بعدا تلاش کنید.',
)
}
let isUpdated = false
let isBackFromSale = false
for (let item of dataToUpdate.items) {
const lastAttemptInvoiceItem = lastAttempt.invoice.items.find(
prevItem => prevItem.good_id === item.good_id,
)
if (!lastAttemptInvoiceItem) {
isBackFromSale = true
break
}
}
if (dataToUpdate.total_amount !== lastAttempt.invoice.total_amount.toNumber()) {
isUpdated = true
}
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)),
},
})
const sendResult = 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(
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
)
}
}
private async getPosId(consumer_id: string, invoice_id: string): Promise<string> {
const now = new Date()
const saleInvoice = await this.prisma.salesInvoice.findUnique({
where: {
id: invoice_id,
pos: {
complex: {
business_activity: {
consumer_id,
},
},
},
},
select: {
pos: {
select: {
id: true,
complex: {
select: {
business_activity: {
select: {
name: true,
license_activation: {
select: {
expires_at: true,
license_renews: {
select: {
expires_at: true,
},
},
},
},
},
},
},
},
},
},
},
})
if (!saleInvoice) {
throw new NotFoundException('متاسفانه فاکتور مورد نظر یافت نشد.')
}
const { license_activation, name: businessName } =
saleInvoice.pos.complex.business_activity
let expired = !license_activation || false
if (license_activation) {
const { expires_at, license_renews } = license_activation
if (expires_at < now) {
for (const renew of license_renews) {
if (renew.expires_at > now) {
expired = false
break
}
}
}
}
if (expired) {
throw new NotFoundException(`متاسفانه مجوز ${businessName} منقضی شده است.`)
}
return saleInvoice.pos.id
}
private async buildPayload(
invoiceId: string,
posId: string,
): Promise<TspProviderSendPayloadDto> {
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,
},
},
},
},
},
})
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.MAIN,
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: TspProviderSendPayloadDto,
): 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({
where: {
invoice_id: itemResult.invoice_id,
},
orderBy: {
attempt_no: 'desc',
},
select: {
id: true,
},
})
const attempt = await tx.saleInvoiceTspAttempts.update({
where: {
id: lastAttempt!.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(),
},
})
return attempt
})
attemptsResult.push(attempt)
}
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"}
@@ -0,0 +1,340 @@
import {
createEnsureSuccessResponseInterceptor,
createHeaderRequestInterceptor,
FetchRequestInterceptor,
} from '@/common/interceptors/fetch-request.interceptor'
import { HttpClientUtil } from '@/common/utils/http-client.util'
import {
CustomerType,
InvoiceTemplateType,
PaymentMethodType,
TspProviderCustomerType,
TspProviderRequestType,
TspProviderResponseStatus,
} from '@/generated/prisma/enums'
import { Injectable, Logger } from '@nestjs/common'
import {
CustomerInfoDto,
IProviderSwitchAdapter,
PaymentInfoDto,
TspProviderBulkSendResultDto,
TspProviderGetResultDto,
TspProviderSendItemResultDto,
TspProviderSendPayloadDto,
} from '../../dto/provider-switch.dto'
import {
NamaProviderGetResponseDto,
NamaProviderPaymentInfoDto,
NamaProviderRequestDto,
NamaProviderResponseStatus,
NamaProviderSendItemResponseDto,
} from './nama-provider.dto'
@Injectable()
export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
readonly code = 'NAMA'
private readonly logger = new Logger(NamaProviderSwitchAdapter.name)
private readonly sandboxBaseUrl =
process.env.NAMA_PROVIDER_SANDBOX_URL || 'https://external-api-dev.namatsp.ir'
private readonly productionBaseUrl =
process.env.NAMA_PROVIDER_PRODUCTION_URL || 'https://api.nama.ir'
private readonly sendPath = '/api/v1/invoices/single-send'
private readonly sendBulkPath = '/api/v1/invoices'
private readonly checkBulkStatus = '/api/v1/invoices/check-by-uuids'
private readonly getPath = '/api/v1/invoices'
constructor(private readonly httpClient: HttpClientUtil) {}
private get baseUrl() {
return this.sandboxBaseUrl
// return process.env.NODE_ENV === 'production'
// ? this.productionBaseUrl
// : this.sandboxBaseUrl
}
private buildSendUrl() {
return `${this.baseUrl}${this.sendPath}`
}
private buildGetUrl(invoiceId: string) {
return `${this.baseUrl}${this.getPath}/${invoiceId}`
}
private createRequestInterceptors(token: string): FetchRequestInterceptor[] {
return [
createHeaderRequestInterceptor({
'Content-Type': 'application/json',
Authorization: token,
}),
createEnsureSuccessResponseInterceptor(),
{
onError: (context, error) => {
this.logger.error(`NAMA request failed: ${context.url}`, error)
return Promise.reject(error)
},
},
]
}
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
const mappedRequest = this.mapToNamaRequestDto(payload)
try {
console.log(mappedRequest)
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: payload,
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.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: payload,
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[],
): Promise<TspProviderBulkSendResultDto[]> {
const result: TspProviderBulkSendResultDto[] = []
for (const payload of payloads) {
const itemResults = await this.send(payload)
result.push({
invoice_id: payload.invoice_id,
items: [itemResults],
})
}
return result
}
async get(invoiceId: string, tsp_token: string): Promise<TspProviderGetResultDto> {
try {
const response = await this.httpClient.request(
this.buildGetUrl(invoiceId),
{
method: 'GET',
},
this.createRequestInterceptors(tsp_token),
)
const providerResponse: NamaProviderGetResponseDto = await response.json()
this.logger.debug('NAMA provider response', providerResponse)
const result: TspProviderGetResultDto = {
hasError: !response.ok,
message: providerResponse.message,
response_payload: providerResponse,
sent_at: new Date().toISOString(),
received_at: providerResponse.tsp_update_time || new Date().toISOString(),
tax_id: providerResponse.tax_id,
status: this.mapResponseStatus(
providerResponse.status as NamaProviderResponseStatus,
),
}
return result
} catch (err) {
this.logger.error('NAMA send failed', err)
// const failure: TspProviderGetResultDto = {
// invoice_id: invoiceId,
// hasError: true,
// message: (err as Error).message,
// received_at: new Date().toISOString(),
// tax_id: null,
// status: TspProviderResponseStatus.NOT_SEND,
// }
// return failure
throw err
}
}
private mapResponseStatus(
status: NamaProviderResponseStatus,
): TspProviderResponseStatus {
switch (status.toUpperCase()) {
case NamaProviderResponseStatus.SUCCESS:
case NamaProviderResponseStatus.POSTED:
return TspProviderResponseStatus.SUCCESS
case NamaProviderResponseStatus.PENDING:
case NamaProviderResponseStatus.IN_PROGRESS:
return TspProviderResponseStatus.QUEUED
case NamaProviderResponseStatus.FAILED:
return TspProviderResponseStatus.FAILURE
default:
return TspProviderResponseStatus.QUEUED
}
}
private mapToNamaRequestDto(
payload: TspProviderSendPayloadDto,
): NamaProviderRequestDto {
return {
uuid: payload.invoice_id,
economic_code: payload.economic_code,
fiscal_id: payload.fiscal_id,
payment: this.mapPayments(payload.payments),
header: {
ins: this.mapTspProviderRequestType(payload.type),
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',
})),
}
}
private mapTspProviderRequestType(type: TspProviderRequestType) {
switch (type) {
case TspProviderRequestType.MAIN:
return '1'
case TspProviderRequestType.UPDATE:
return '2'
case TspProviderRequestType.REVOKE:
return '3'
case TspProviderRequestType.REMOVE:
return '4'
}
}
private mapInvoiceTemplate(template: InvoiceTemplateType) {
switch (template) {
case InvoiceTemplateType.SALE:
return '1'
case InvoiceTemplateType.FX_SALE:
return '2'
case InvoiceTemplateType.GOLD_JEWELRY:
return '3'
case InvoiceTemplateType.CONTRACT:
return '4'
case InvoiceTemplateType.UTILITY:
return '5'
case InvoiceTemplateType.AIR_TICKET:
return '6'
case InvoiceTemplateType.EXPORT:
return '7'
case InvoiceTemplateType.BILL_OF_LADING:
return '8'
case InvoiceTemplateType.PETROCHEMICAL:
return '9'
case InvoiceTemplateType.COMMODITY_EXCHANGE:
return '11'
case InvoiceTemplateType.INSURANCE:
return '13'
}
}
private mapTspProviderCustomerType(type?: TspProviderCustomerType) {
switch (type) {
case TspProviderCustomerType.Unknown:
return '1'
case TspProviderCustomerType.Known:
return '2'
default:
return '3'
}
}
private mapCustomerType(type?: CustomerType) {
switch (type) {
case CustomerType.INDIVIDUAL:
return '1'
case CustomerType.LEGAL:
return '2'
default:
return '5'
}
}
private mapCustomerInfo(customer?: CustomerInfoDto) {
const info = {} as any
info.tob = this.mapCustomerType(customer?.type)
if (customer?.type === CustomerType.LEGAL && customer.legal_info) {
info.name = customer.legal_info.name
info.bid = customer.legal_info.economic_code
info.address = ''
} else if (customer?.type === CustomerType.INDIVIDUAL && customer.individual_info) {
info.name = `${customer.individual_info?.first_name || ''} ${
customer.individual_info?.last_name || ''
}`.trim()
info.bid = customer.individual_info.national_id
info.mobile = customer.individual_info.mobile_number
info.address = ''
}
return info
}
private mapPaymentMethod(method: PaymentMethodType): number {
switch (method) {
case PaymentMethodType.CHEQUE:
return 1
case PaymentMethodType.SET_OFF:
return 2
case PaymentMethodType.CASH:
return 3
case PaymentMethodType.TERMINAL:
return 4
case PaymentMethodType.PAYMENT_GATEWAY:
return 5
case PaymentMethodType.CARD:
return 6
case PaymentMethodType.BANK:
return 7
case PaymentMethodType.OTHER:
return 8
}
}
private mapPayments(payments: PaymentInfoDto[]): NamaProviderPaymentInfoDto[] {
return payments.map(payment => ({
pmt: this.mapPaymentMethod(payment.payment_method),
pv: payment.amount,
trn: payment.tracking_code,
pcn: payment.card_number,
pdt: payment.paid_at ? String(payment.paid_at.getTime()) : undefined,
}))
}
}
@@ -0,0 +1,261 @@
import { TspProviderResponseStatus } from '@/generated/prisma/enums'
import { ApiProperty } from '@nestjs/swagger'
import { Type } from 'class-transformer'
import {
IsArray,
IsEnum,
IsNumber,
IsOptional,
IsString,
Min,
ValidateNested,
} from 'class-validator'
export enum NamaProviderResponseStatus {
POSTED = 'SUCCESS',
PENDING = 'PENDING',
IN_PROGRESS = 'IN_PROGRESS',
SUCCESS = 'SUCCESS',
FAILED = 'FAILED',
}
export class NamaProviderPaymentInfoDto {
@ApiProperty({ required: true, description: 'روش پرداخت' })
@IsNumber()
pmt: number
@ApiProperty({ required: true, description: 'مبلغ پرداختی' })
@IsNumber()
@Min(10_000)
pv: number
@ApiProperty({ required: false, description: 'شماره‌ی پیگیری' })
@IsOptional()
@IsString()
trn?: string
@ApiProperty({ required: false, description: 'شماره‌ی کارت پرداخت کننده‌ی صورت‌حساب' })
@IsOptional()
@IsString()
pcn?: string
@ApiProperty({ required: false, description: 'تاریخ و زمان پرداخت صورت‌حساب unix' })
@IsOptional()
@IsNumber()
pdt?: string
}
export class NamaProviderBodyItemDto {
@ApiProperty()
@IsString()
sstid: string
@ApiProperty()
@IsString()
vra: string
// @ApiProperty()
// @IsString()
// sstt: string
@ApiProperty()
@IsString()
fee: string
@ApiProperty()
@IsString()
dis: string
@ApiProperty()
@IsString()
mu: string
@ApiProperty()
@IsString()
am: string
@ApiProperty()
@IsString()
consfee: string
@ApiProperty()
@IsString()
bros: string
@ApiProperty()
@IsString()
spro: string
}
export class NamaProviderHeaderDto {
@ApiProperty({ required: true })
@IsString()
ins: string
@ApiProperty()
@IsString()
inp: string
@ApiProperty({ required: true })
@IsString()
inty: string
// @ApiProperty({required: true})
// @IsString()
// unique_tax_code: string
@ApiProperty({ required: true })
@IsString()
inno: string
@ApiProperty({ required: true })
@IsString()
tins: string
@ApiProperty({ required: true })
@IsString()
indatim: string
@ApiProperty({ required: true })
@IsString()
name: string
@ApiProperty({ required: true })
@IsString()
tob: string
@ApiProperty()
@IsOptional()
@IsString()
address?: string
@ApiProperty()
@IsOptional()
@IsString()
mobile?: string
@ApiProperty()
@IsString()
bid: string
@ApiProperty({ required: true })
@IsString()
setm: string
}
export class NamaProviderRequestDto {
@ApiProperty({ type: [NamaProviderBodyItemDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => NamaProviderBodyItemDto)
body: NamaProviderBodyItemDto[]
@ApiProperty({ type: [NamaProviderPaymentInfoDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => NamaProviderPaymentInfoDto)
payment: NamaProviderPaymentInfoDto[]
@ApiProperty({ type: NamaProviderHeaderDto })
@ValidateNested()
@Type(() => NamaProviderHeaderDto)
header: NamaProviderHeaderDto
@ApiProperty()
@IsString()
uuid: string
@ApiProperty()
@IsString()
economic_code: string
@ApiProperty()
@IsString()
fiscal_id: string
}
export class NamaProviderApiErrorItemDto {
@ApiProperty()
@IsString()
code: string
@ApiProperty()
@IsString()
message: string
}
export class NamaProviderApiErrorResponseDto {
@ApiProperty({ type: [NamaProviderApiErrorItemDto], required: false })
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => NamaProviderApiErrorItemDto)
error?: NamaProviderApiErrorItemDto
}
export class NamaProviderSendItemResponseDto {
@ApiProperty()
@IsString()
uuid: string
@ApiProperty()
@IsString()
message: string
@ApiProperty()
@IsString()
status: NamaProviderResponseStatus
@ApiProperty()
@IsString()
tax_id: string
@ApiProperty()
@IsString()
inno: string
@ApiProperty({ required: true })
@IsString()
reference_number: string
@ApiProperty({ type: () => NamaProviderApiErrorResponseDto, required: false })
@IsOptional()
@ValidateNested()
@Type(() => NamaProviderApiErrorResponseDto)
tax_api_response?: NamaProviderApiErrorResponseDto
@ApiProperty({ required: false })
@IsOptional()
@IsString()
tsp_update_time: string
}
export class NamaProviderGetResponseDto {
@ApiProperty()
@IsString()
uuid: string
@ApiProperty()
@IsString()
message: string
@ApiProperty({ enum: TspProviderResponseStatus })
@IsEnum(TspProviderResponseStatus)
status: TspProviderResponseStatus
@ApiProperty()
@IsString()
tax_id: string
@ApiProperty()
@IsString()
inno: string
@ApiProperty()
@IsString()
reference_number: string
@ApiProperty()
@IsString()
tsp_update_time: string
}