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:
@@ -1,10 +1,17 @@
|
||||
import { IsOptional, IsString } from 'class-validator'
|
||||
import { InvoiceTemplateType } from '@/generated/prisma/enums'
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { IsEnum, IsString } from 'class-validator'
|
||||
|
||||
export class CreateGuildDto {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
name: string
|
||||
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
code?: string
|
||||
code: string
|
||||
|
||||
@ApiProperty({ required: true, enum: InvoiceTemplateType })
|
||||
@IsEnum(InvoiceTemplateType)
|
||||
invoice_template: InvoiceTemplateType
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartnerFiscalSwitchType, PartnerStatus } from '@/generated/prisma/enums'
|
||||
import { PartnerStatus, TspProviderType } from '@/generated/prisma/enums'
|
||||
import { ApiProperty, PartialType } from '@nestjs/swagger'
|
||||
import { IsEnum, IsNumber, IsOptional, IsString } from 'class-validator'
|
||||
|
||||
@@ -11,9 +11,9 @@ export class CreatePartnerDto {
|
||||
@ApiProperty({ required: true })
|
||||
code: string
|
||||
|
||||
@IsEnum(PartnerFiscalSwitchType)
|
||||
@ApiProperty({ required: true })
|
||||
fiscal_switch_type: PartnerFiscalSwitchType
|
||||
@IsEnum(TspProviderType)
|
||||
@ApiProperty({ required: true, enum: TspProviderType })
|
||||
tsp_provider: TspProviderType
|
||||
|
||||
// @IsOptional()
|
||||
// @IsNumber()
|
||||
|
||||
@@ -27,7 +27,7 @@ export class PartnersService {
|
||||
code: true,
|
||||
status: true,
|
||||
logo_url: true,
|
||||
fiscal_switch_type: true,
|
||||
tsp_provider: true,
|
||||
created_at: true,
|
||||
license_charge_transactions: {
|
||||
select: {
|
||||
|
||||
@@ -12,6 +12,9 @@ export class BusinessActivitiesService {
|
||||
name: true,
|
||||
economic_code: true,
|
||||
created_at: true,
|
||||
partner_token: true,
|
||||
fiscal_id: true,
|
||||
invoice_number_sequence: true,
|
||||
guild: {
|
||||
select: {
|
||||
id: true,
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { ApiProperty, PartialType } from '@nestjs/swagger'
|
||||
import { IsString } from 'class-validator'
|
||||
import { IsNumber, IsString, Max, Min } from 'class-validator'
|
||||
|
||||
export class CreateBusinessActivityDto {
|
||||
@IsString()
|
||||
@ApiProperty({ required: true })
|
||||
name: string
|
||||
|
||||
@ApiProperty({ required: false, default: '1' })
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(1_000_000_000)
|
||||
invoice_number_sequence: number
|
||||
}
|
||||
|
||||
export class UpdateBusinessActivityDto extends PartialType(CreateBusinessActivityDto) {}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
TaxSwitchBulkSendResultDto as FiscalSwitchBulkSendResultDto,
|
||||
TaxSwitchSendItemResultDto as FiscalSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto as FiscalSwitchSendPayloadDto,
|
||||
TaxSwitchGetResultDto,
|
||||
} from './dto/tax-switch.dto'
|
||||
import { NamaTaxSwitchAdapter } from './switch/nama/nama-fiscal-switch.adapter'
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceFiscalSwitchService {
|
||||
constructor(private readonly namaAdapter: NamaTaxSwitchAdapter) {}
|
||||
|
||||
private resolveSwitch(providerCode?: string | null) {
|
||||
const normalizedCode = providerCode?.trim().toUpperCase() || ''
|
||||
|
||||
switch (normalizedCode) {
|
||||
case 'NAMA':
|
||||
default:
|
||||
return this.namaAdapter
|
||||
}
|
||||
}
|
||||
|
||||
async send(
|
||||
payload: FiscalSwitchSendPayloadDto,
|
||||
): Promise<FiscalSwitchSendItemResultDto[]> {
|
||||
const adapter = this.resolveSwitch(payload.provider_code)
|
||||
return adapter.send(payload)
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: FiscalSwitchSendPayloadDto[],
|
||||
): Promise<FiscalSwitchBulkSendResultDto[]> {
|
||||
const groupedByProvider = new Map<string, FiscalSwitchSendPayloadDto[]>()
|
||||
|
||||
for (const payload of payloads) {
|
||||
const key = payload.provider_code?.trim().toUpperCase() || 'NAMA'
|
||||
const currentGroup = groupedByProvider.get(key) || []
|
||||
currentGroup.push(payload)
|
||||
groupedByProvider.set(key, currentGroup)
|
||||
}
|
||||
|
||||
const result: FiscalSwitchBulkSendResultDto[] = []
|
||||
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 | null | undefined,
|
||||
taxId: string,
|
||||
): Promise<TaxSwitchGetResultDto> {
|
||||
const adapter = this.resolveSwitch(providerCode)
|
||||
return adapter.get(taxId)
|
||||
}
|
||||
}
|
||||
@@ -1,372 +0,0 @@
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { Injectable, NotFoundException } from '@nestjs/common'
|
||||
import {
|
||||
FiscalInvoiceCustomerType,
|
||||
FiscalRequestType,
|
||||
Prisma,
|
||||
} from 'generated/prisma/client'
|
||||
import {
|
||||
TaxSendStatus,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from './dto/tax-switch.dto'
|
||||
import { SalesInvoiceFiscalSwitchService } from './sales-invoice-fiscal-switch.service'
|
||||
|
||||
type TaxRow = {
|
||||
id: string
|
||||
retry_count: number
|
||||
}
|
||||
|
||||
type ItemTaxProviderRow = {
|
||||
provider_code: string | null
|
||||
tax_id: string | null
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceFiscalService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly taxSwitchService: SalesInvoiceFiscalSwitchService,
|
||||
) {}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string): Promise<void> {
|
||||
const posId = await this.getPosId(consumer_id, invoice_id)
|
||||
const payload = await this.buildPayload(invoice_id, posId)
|
||||
|
||||
const itemResults = await this.trySend(payload)
|
||||
await this.persistAttemptResults(itemResults)
|
||||
}
|
||||
|
||||
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
|
||||
if (!invoice_ids.length) return
|
||||
|
||||
const payloads: TaxSwitchSendPayloadDto[] = []
|
||||
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.taxSwitchService.sendBulk(payloads)
|
||||
const allItemResults = bulkResult.flatMap(result => result.items)
|
||||
await this.persistAttemptResults(allItemResults)
|
||||
}
|
||||
|
||||
async get(invoiceItemId: string, posId: string): Promise<TaxSwitchGetResultDto> {
|
||||
const rows = await this.prisma.$queryRaw<ItemTaxProviderRow[]>(Prisma.sql`
|
||||
SELECT p.code AS provider_code, t.tax_id AS tax_id
|
||||
FROM sales_invoice_item_taxes t
|
||||
INNER JOIN sales_invoice_items si ON si.id = t.invoice_item_id
|
||||
INNER JOIN sales_invoices s ON s.id = si.invoice_id
|
||||
INNER JOIN poses pz ON pz.id = s.pos_id
|
||||
LEFT JOIN providers p ON p.id = pz.provider_id
|
||||
WHERE t.invoice_item_id = ${invoiceItemId} AND s.pos_id = ${posId}
|
||||
LIMIT 1
|
||||
`)
|
||||
|
||||
if (!rows.length || !rows[0].tax_id) {
|
||||
throw new NotFoundException('Tax id for this invoice item was not found.')
|
||||
}
|
||||
|
||||
return this.taxSwitchService.get(rows[0].provider_code, rows[0].tax_id)
|
||||
}
|
||||
|
||||
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<TaxSwitchSendPayloadDto> {
|
||||
const invoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoiceId,
|
||||
pos_id: posId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
total_amount: true,
|
||||
invoice_date: 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,
|
||||
consumer: {
|
||||
select: {
|
||||
legal: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
fiscal_switch_type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
individual: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
fiscal_switch_type: 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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_code: invoice.code,
|
||||
invoice_date: invoice.invoice_date,
|
||||
total_amount: Number(invoice.total_amount),
|
||||
// provider_code: invoice.pos.provider?.code || null,
|
||||
type: FiscalRequestType.MAIN,
|
||||
provider_code: partner.fiscal_switch_type!,
|
||||
customer_type: invoice.customer?.type
|
||||
? FiscalInvoiceCustomerType.Known
|
||||
: FiscalInvoiceCustomerType.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: TaxSwitchSendPayloadDto,
|
||||
): Promise<TaxSwitchSendItemResultDto[]> {
|
||||
try {
|
||||
return await this.taxSwitchService.send(payload)
|
||||
} catch (error: any) {
|
||||
const message = error?.message || 'Unexpected tax switch error.'
|
||||
const now = new Date()
|
||||
return payload.items.map(item => ({
|
||||
invoice_item_id: item.invoice_item_id,
|
||||
status: TaxSendStatus.FAILED,
|
||||
error_message: message,
|
||||
sent_at: now.toISOString(),
|
||||
received_at: now.toISOString(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
private async persistAttemptResults(
|
||||
itemResults: TaxSwitchSendItemResultDto[],
|
||||
): Promise<void> {
|
||||
if (!itemResults.length) return
|
||||
|
||||
await this.prisma.$transaction(async $tx => {
|
||||
for (const itemResult of itemResults) {
|
||||
await $tx.$executeRaw(Prisma.sql`
|
||||
INSERT INTO sales_invoice_item_taxes (
|
||||
id,
|
||||
tax_id,
|
||||
status,
|
||||
retry_count,
|
||||
last_attempt_at,
|
||||
created_at,
|
||||
updated_at,
|
||||
invoice_item_id
|
||||
) VALUES (
|
||||
UUID(),
|
||||
${itemResult.tax_id || null},
|
||||
${itemResult.status},
|
||||
0,
|
||||
${itemResult.sent_at || new Date()},
|
||||
NOW(),
|
||||
NOW(),
|
||||
${itemResult.invoice_item_id}
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
updated_at = NOW()
|
||||
`)
|
||||
|
||||
const rows = await $tx.$queryRaw<TaxRow[]>(Prisma.sql`
|
||||
SELECT id, retry_count
|
||||
FROM sales_invoice_item_taxes
|
||||
WHERE invoice_item_id = ${itemResult.invoice_item_id}
|
||||
LIMIT 1
|
||||
`)
|
||||
|
||||
if (!rows.length) continue
|
||||
|
||||
const itemTaxRow = rows[0]
|
||||
const attemptNo = Number(itemTaxRow.retry_count || 0) + 1
|
||||
|
||||
await $tx.$executeRaw(Prisma.sql`
|
||||
INSERT INTO sales_invoice_item_tax_attempts (
|
||||
id,
|
||||
attempt_no,
|
||||
status,
|
||||
tax_id,
|
||||
request_payload,
|
||||
response_payload,
|
||||
error_message,
|
||||
sent_at,
|
||||
received_at,
|
||||
created_at,
|
||||
item_tax_id
|
||||
) VALUES (
|
||||
UUID(),
|
||||
${attemptNo},
|
||||
${itemResult.status},
|
||||
${itemResult.tax_id || null},
|
||||
${JSON.stringify(itemResult.request_payload ?? null)},
|
||||
${JSON.stringify(itemResult.response_payload ?? null)},
|
||||
${itemResult.error_message || null},
|
||||
${itemResult.sent_at ? new Date(itemResult.sent_at) : new Date()},
|
||||
${itemResult.received_at ? new Date(itemResult.received_at) : new Date()},
|
||||
NOW(),
|
||||
${itemTaxRow.id}
|
||||
)
|
||||
`)
|
||||
|
||||
await $tx.$executeRaw(Prisma.sql`
|
||||
UPDATE sales_invoice_item_taxes
|
||||
SET
|
||||
tax_id = COALESCE(${itemResult.tax_id || null}, tax_id),
|
||||
status = ${itemResult.status},
|
||||
retry_count = ${attemptNo},
|
||||
last_attempt_at = ${itemResult.sent_at ? new Date(itemResult.sent_at) : new Date()},
|
||||
updated_at = NOW()
|
||||
WHERE id = ${itemTaxRow.id}
|
||||
`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
import {
|
||||
CustomerType,
|
||||
FiscalInvoiceCustomerType,
|
||||
FiscalRequestType,
|
||||
} from '@/generated/prisma/enums'
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
ITaxSwitchAdapter,
|
||||
TaxSendStatus,
|
||||
TaxSwitchBulkSendResultDto,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from '../../dto/tax-switch.dto'
|
||||
import {
|
||||
NamaTaxGetResponseDto,
|
||||
NamaTaxRequestDto,
|
||||
NamaTaxSendItemResponseDto,
|
||||
} from './nama-fiscal-switch.dto'
|
||||
|
||||
@Injectable()
|
||||
export class NamaTaxSwitchAdapter implements ITaxSwitchAdapter {
|
||||
readonly code = 'NAMA'
|
||||
private readonly sandboxBaseUrl =
|
||||
process.env.NAMA_FISCAL_SANDBOX_URL || 'https://sandbox-api.nama.ir'
|
||||
private readonly productionBaseUrl =
|
||||
process.env.NAMA_FISCAL_PRODUCTION_URL || 'https://api.nama.ir'
|
||||
|
||||
private readonly sendPath = '/api/v1/fiscal/invoices/single-send'
|
||||
private readonly sendBulkPath = '/api/v1/invoices'
|
||||
private readonly checkStatus = '/api/v1/invoices/check-by-uuids'
|
||||
private readonly checkBulkStatus = '/api/v1/invoices/check-by-uuids'
|
||||
private readonly getPath = '/api/v1/fiscal/invoices/'
|
||||
|
||||
private get baseUrl() {
|
||||
return process.env.NODE_ENV === 'production'
|
||||
? this.productionBaseUrl
|
||||
: this.sandboxBaseUrl
|
||||
}
|
||||
|
||||
private buildSendUrl() {
|
||||
return `${this.baseUrl}${this.sendPath}`
|
||||
}
|
||||
|
||||
private buildGetUrl(taxId: string) {
|
||||
return `${this.baseUrl}${this.getPath}/${taxId}`
|
||||
}
|
||||
|
||||
async send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]> {
|
||||
const mappedRequest = this.mapToNamaRequestDto(payload)
|
||||
|
||||
return payload.items.map((item, index) => {
|
||||
const sentAt = new Date()
|
||||
const receivedAt = new Date(sentAt.getTime() + 50)
|
||||
|
||||
const providerResponse: NamaTaxSendItemResponseDto = {
|
||||
invoice_item_id: item.invoice_item_id,
|
||||
status: TaxSendStatus.SENT,
|
||||
tax_id: `TAX-${payload.invoice_code}-${index + 1}`,
|
||||
request_payload: {
|
||||
url: this.buildSendUrl(),
|
||||
body: mappedRequest,
|
||||
},
|
||||
response_payload: {
|
||||
provider: this.code,
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
endpoint: this.buildSendUrl(),
|
||||
status: 'ACCEPTED',
|
||||
},
|
||||
sent_at: sentAt.toISOString(),
|
||||
received_at: receivedAt.toISOString(),
|
||||
}
|
||||
|
||||
return {
|
||||
invoice_item_id: providerResponse.invoice_item_id,
|
||||
status: providerResponse.status,
|
||||
tax_id: providerResponse.tax_id,
|
||||
request_payload: providerResponse.request_payload,
|
||||
response_payload: providerResponse.response_payload,
|
||||
error_message: providerResponse.error_message,
|
||||
sent_at: providerResponse.sent_at,
|
||||
received_at: providerResponse.received_at,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TaxSwitchSendPayloadDto[],
|
||||
): Promise<TaxSwitchBulkSendResultDto[]> {
|
||||
const result: TaxSwitchBulkSendResultDto[] = []
|
||||
for (const payload of payloads) {
|
||||
const itemResults = await this.send(payload)
|
||||
result.push({
|
||||
invoice_id: payload.invoice_id,
|
||||
items: itemResults,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async get(taxId: string): Promise<TaxSwitchGetResultDto> {
|
||||
const providerResponse: NamaTaxGetResponseDto = {
|
||||
tax_id: taxId,
|
||||
status: TaxSendStatus.SENT,
|
||||
response_payload: {
|
||||
provider: this.code,
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
endpoint: this.buildGetUrl(taxId),
|
||||
status: 'CONFIRMED',
|
||||
tracking_code: taxId,
|
||||
},
|
||||
received_at: new Date().toISOString(),
|
||||
}
|
||||
|
||||
return {
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: providerResponse.status,
|
||||
response_payload: providerResponse.response_payload,
|
||||
received_at: providerResponse.received_at,
|
||||
}
|
||||
}
|
||||
|
||||
private mapToNamaRequestDto(payload: TaxSwitchSendPayloadDto): NamaTaxRequestDto {
|
||||
return {
|
||||
uuid: payload.invoice_id,
|
||||
economic_code: '',
|
||||
fiscal_id: '',
|
||||
payment: [],
|
||||
header: {
|
||||
ins: this.mapFiscalRequestType(payload.type),
|
||||
inp: '2',
|
||||
inty: this.mapFiscalInvoiceCustomerType(payload.customer_type),
|
||||
// unique_tax_code: payload.invoice_code,
|
||||
inno: payload.invoice_code,
|
||||
tins: '',
|
||||
indatim: payload.invoice_date.getTime() + '',
|
||||
name:
|
||||
`${payload.customer?.individual_info?.first_name} ${payload.customer?.individual_info?.last_name}` ||
|
||||
payload.customer?.legal_info?.name ||
|
||||
'',
|
||||
tob: this.mapCustomerType(payload.customer?.type),
|
||||
address: '',
|
||||
mobile: payload.customer?.individual_info?.mobile_number || '',
|
||||
bid:
|
||||
payload.customer?.individual_info?.national_id ||
|
||||
payload.customer?.legal_info?.economic_code ||
|
||||
'',
|
||||
},
|
||||
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 mapFiscalRequestType(type: FiscalRequestType) {
|
||||
switch (type) {
|
||||
case FiscalRequestType.MAIN:
|
||||
return '1'
|
||||
case FiscalRequestType.UPDATE:
|
||||
return '2'
|
||||
case FiscalRequestType.REVOKE:
|
||||
return '3'
|
||||
case FiscalRequestType.REMOVE:
|
||||
return '4'
|
||||
}
|
||||
}
|
||||
|
||||
private mapFiscalInvoiceCustomerType(type?: FiscalInvoiceCustomerType) {
|
||||
switch (type) {
|
||||
case FiscalInvoiceCustomerType.Unknown:
|
||||
return '1'
|
||||
case FiscalInvoiceCustomerType.Known:
|
||||
return '2'
|
||||
default:
|
||||
return '3'
|
||||
}
|
||||
}
|
||||
|
||||
private mapCustomerType(type?: CustomerType) {
|
||||
switch (type) {
|
||||
case CustomerType.INDIVIDUAL:
|
||||
return '1'
|
||||
case CustomerType.LEGAL:
|
||||
return '2'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
import { TaxSendStatus } from '../../dto/tax-switch.dto'
|
||||
|
||||
export class NamaTaxBodyItemDto {
|
||||
@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 NamaTaxHeaderDto {
|
||||
@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
|
||||
}
|
||||
|
||||
export class NamaTaxRequestDto {
|
||||
@ApiProperty({ type: [NamaTaxBodyItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NamaTaxBodyItemDto)
|
||||
body: NamaTaxBodyItemDto[]
|
||||
|
||||
@ApiProperty({ type: [Object] })
|
||||
@IsArray()
|
||||
payment: unknown[]
|
||||
|
||||
@ApiProperty({ type: NamaTaxHeaderDto })
|
||||
@ValidateNested()
|
||||
@Type(() => NamaTaxHeaderDto)
|
||||
header: NamaTaxHeaderDto
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
uuid: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
economic_code: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
fiscal_id: string
|
||||
}
|
||||
|
||||
export class NamaTaxSendItemResponseDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_item_id: string
|
||||
|
||||
@ApiProperty({ enum: TaxSendStatus })
|
||||
@IsEnum(TaxSendStatus)
|
||||
status: TaxSendStatus
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tax_id?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
request_payload?: unknown
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
response_payload?: unknown
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
error_message?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sent_at?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
received_at?: string | null
|
||||
}
|
||||
|
||||
export class NamaTaxGetResponseDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
tax_id: string
|
||||
|
||||
@ApiProperty({ enum: TaxSendStatus })
|
||||
@IsEnum(TaxSendStatus)
|
||||
status: TaxSendStatus
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
response_payload?: unknown
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
received_at?: string | null
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { PrismaModule } from '@/prisma/prisma.module'
|
||||
import { Module } from '@nestjs/common'
|
||||
import { SalesInvoiceFiscalSwitchService } from './fiscal/sales-invoice-fiscal-switch.service'
|
||||
import { SalesInvoiceFiscalService } from './fiscal/sales-invoice-fiscal.service'
|
||||
import { NamaTaxSwitchAdapter } from './fiscal/switch/nama/nama-fiscal-switch.adapter'
|
||||
import { HttpClientUtil } from '../../../common/utils/http-client.util'
|
||||
import { SalesInvoiceTspSwitchService } from '../../tspProviders/sales-invoice-tsp-switch.service'
|
||||
import { SalesInvoiceTspService } from '../../tspProviders/sales-invoice-tsp.service'
|
||||
import { NamaProviderSwitchAdapter } from '../../tspProviders/switch/nama/nama-provider.adapter'
|
||||
import { StatisticsController } from './saleInvoices.controller'
|
||||
import { SaleInvoicesService } from './saleInvoices.service'
|
||||
|
||||
@@ -11,9 +12,10 @@ import { SaleInvoicesService } from './saleInvoices.service'
|
||||
controllers: [StatisticsController],
|
||||
providers: [
|
||||
SaleInvoicesService,
|
||||
SalesInvoiceFiscalService,
|
||||
SalesInvoiceFiscalSwitchService,
|
||||
NamaTaxSwitchAdapter,
|
||||
HttpClientUtil,
|
||||
SalesInvoiceTspService,
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
],
|
||||
exports: [SaleInvoicesService],
|
||||
})
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { translateEnumValue } from '@/common/utils'
|
||||
import { TspProviderResponseStatus } from '@/generated/prisma/enums'
|
||||
import {
|
||||
SalesInvoiceSelect,
|
||||
SalesInvoiceWhereInput,
|
||||
SalesInvoiceWhereUniqueInput,
|
||||
} from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
|
||||
import { ResponseMapper } from 'common/response/response-mapper'
|
||||
import { SalesInvoiceFiscalService } from './fiscal/sales-invoice-fiscal.service'
|
||||
import { SalesInvoiceTspService } from '../../tspProviders/sales-invoice-tsp.service'
|
||||
|
||||
@Injectable()
|
||||
export class SaleInvoicesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private salesInvoiceTaxService: SalesInvoiceFiscalService,
|
||||
private salesInvoiceTaxService: SalesInvoiceTspService,
|
||||
) {}
|
||||
|
||||
private readonly defaultSelect: SalesInvoiceSelect = {
|
||||
@@ -49,23 +51,31 @@ export class SaleInvoicesService {
|
||||
},
|
||||
},
|
||||
},
|
||||
fiscal: {
|
||||
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
created_at: 'asc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
attempts: {
|
||||
orderBy: {
|
||||
created_at: 'asc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
private readonly invoiceMapper = (invoice: any) => {
|
||||
const { tsp_attempts, ...rest } = invoice || {}
|
||||
|
||||
return {
|
||||
...rest,
|
||||
status: translateEnumValue(
|
||||
'TspProviderResponseStatus',
|
||||
invoice.tsp_attempts?.[0]?.status || TspProviderResponseStatus.NOT_SEND,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async findAll(consumer_id: string, page = 1, perPage = 10) {
|
||||
const invoicesWhere: SalesInvoiceWhereInput = {
|
||||
consumer_account: {
|
||||
@@ -81,7 +91,9 @@ export class SaleInvoicesService {
|
||||
}),
|
||||
await tx.salesInvoice.count({ where: invoicesWhere }),
|
||||
])
|
||||
return ResponseMapper.paginate(invoices, { page, perPage, total })
|
||||
|
||||
const mappedInvoices = invoices.map(this.invoiceMapper)
|
||||
return ResponseMapper.paginate(mappedInvoices, { page, perPage, total })
|
||||
}
|
||||
|
||||
async findOne(consumer_id: string, id: string) {
|
||||
@@ -161,15 +173,21 @@ export class SaleInvoicesService {
|
||||
unknown_customer: true,
|
||||
},
|
||||
})
|
||||
return ResponseMapper.single(invoice)
|
||||
|
||||
if (invoice) {
|
||||
return ResponseMapper.single(this.invoiceMapper(invoice))
|
||||
}
|
||||
throw new NotFoundException('فاکتور مورد نظر شما یافت نشد.')
|
||||
}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string) {
|
||||
await this.salesInvoiceTaxService.send(consumer_id, invoice_id)
|
||||
const tspProviderResult = await this.salesInvoiceTaxService.send(
|
||||
consumer_id,
|
||||
invoice_id,
|
||||
)
|
||||
|
||||
return ResponseMapper.single({
|
||||
invoice_id,
|
||||
sent_to_tax: true,
|
||||
...tspProviderResult,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -109,9 +109,9 @@ export class EnumsController {
|
||||
return this.enumsService.getEnumValues('ConsumerRole')
|
||||
}
|
||||
|
||||
@Get('fiscal_response_status')
|
||||
@Get('tsp_provider_response_status')
|
||||
@PublicWithToken()
|
||||
async getFiscalResponseStatus(): Promise<EnumsServiceGetEnumValuesResponseDto> {
|
||||
return this.enumsService.getEnumValues('FiscalResponseStatus')
|
||||
async getTspProviderResponseStatus(): Promise<EnumsServiceGetEnumValuesResponseDto> {
|
||||
return this.enumsService.getEnumValues('TspProviderResponseStatus')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,13 +13,9 @@ import {
|
||||
ConsumerStatus,
|
||||
ConsumerType,
|
||||
CustomerType,
|
||||
FiscalInvoiceCustomerType,
|
||||
FiscalRequestType,
|
||||
FiscalResponseStatus,
|
||||
GoodPricingModel,
|
||||
LicenseStatus,
|
||||
LicenseType,
|
||||
PartnerFiscalSwitchType,
|
||||
PartnerRole,
|
||||
PartnerStatus,
|
||||
PaymentMethodType,
|
||||
@@ -30,6 +26,10 @@ import {
|
||||
ProviderStatus,
|
||||
SKUGuildType,
|
||||
TokenType,
|
||||
TspProviderCustomerType,
|
||||
TspProviderRequestType,
|
||||
TspProviderResponseStatus,
|
||||
TspProviderType,
|
||||
UnitType,
|
||||
UserStatus,
|
||||
UserType,
|
||||
@@ -79,10 +79,7 @@ export class EnumsService {
|
||||
ConsumerStatus: this.prepareData(ConsumerStatus, 'ConsumerStatus'),
|
||||
ConsumerType: this.prepareData(ConsumerType, 'ConsumerType'),
|
||||
PartnerStatus: this.prepareData(PartnerStatus, 'PartnerStatus'),
|
||||
PartnerFiscalSwitchType: this.prepareData(
|
||||
PartnerFiscalSwitchType,
|
||||
'PartnerFiscalSwitchType',
|
||||
),
|
||||
TspProviderType: this.prepareData(TspProviderType, 'TspProviderType'),
|
||||
ApplicationPlatform: this.prepareData(ApplicationPlatform, 'ApplicationPlatform'),
|
||||
ApplicationReleaseType: this.prepareData(
|
||||
ApplicationReleaseType,
|
||||
@@ -93,14 +90,17 @@ export class EnumsService {
|
||||
'ApplicationPublisher',
|
||||
),
|
||||
CustomerType: this.prepareData(CustomerType, 'CustomerType'),
|
||||
FiscalResponseStatus: this.prepareData(
|
||||
FiscalResponseStatus,
|
||||
'FiscalResponseStatus',
|
||||
TspProviderResponseStatus: this.prepareData(
|
||||
TspProviderResponseStatus,
|
||||
'TspProviderResponseStatus',
|
||||
),
|
||||
FiscalRequestType: this.prepareData(FiscalRequestType, 'FiscalRequestType'),
|
||||
FiscalInvoiceCustomerType: this.prepareData(
|
||||
FiscalInvoiceCustomerType,
|
||||
'FiscalInvoiceCustomerType',
|
||||
TspProviderRequestType: this.prepareData(
|
||||
TspProviderRequestType,
|
||||
'TspProviderRequestType',
|
||||
),
|
||||
TspProviderCustomerType: this.prepareData(
|
||||
TspProviderCustomerType,
|
||||
'TspProviderCustomerType',
|
||||
),
|
||||
SKUGuildType: this.prepareData(SKUGuildType, 'SKUGuildType'),
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ export class CreateSalesInvoiceDto {
|
||||
@ApiProperty({ required: false, default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
send_to_tax?: boolean
|
||||
send_to_tsp?: boolean
|
||||
|
||||
@ApiProperty({ required: true, default: CustomerType.UNKNOWN })
|
||||
@IsEnum(CustomerType)
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
IsString,
|
||||
Min,
|
||||
} from 'class-validator'
|
||||
import { FiscalResponseStatus } from 'generated/prisma/enums'
|
||||
import { TspProviderResponseStatus } from 'generated/prisma/enums'
|
||||
|
||||
export class SalesInvoicesFilterDto {
|
||||
@ApiPropertyOptional({ default: 1 })
|
||||
@@ -70,10 +70,10 @@ export class SalesInvoicesFilterDto {
|
||||
@IsString()
|
||||
customer_economic_code?: string
|
||||
|
||||
@ApiPropertyOptional({ enum: FiscalResponseStatus })
|
||||
@ApiPropertyOptional({ enum: TspProviderResponseStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(FiscalResponseStatus)
|
||||
status?: FiscalResponseStatus
|
||||
@IsEnum(TspProviderResponseStatus)
|
||||
status?: TspProviderResponseStatus
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { PosInfo } from '@/common/decorators/posInfo.decorator'
|
||||
import type { IPosPayload } from '@/common/models/posPayload.model'
|
||||
import { Controller, Get, Param, Post } from '@nestjs/common'
|
||||
import { PosSalesInvoiceFiscalService } from './sales-invoice-fiscal.service'
|
||||
|
||||
@Controller('pos/sales_invoices/:invoiceId/fiscal')
|
||||
export class PosSalesInvoiceFiscalController {
|
||||
constructor(private readonly service: PosSalesInvoiceFiscalService) {}
|
||||
|
||||
@Post('send')
|
||||
async send(@PosInfo() posInfo: IPosPayload, @Param('invoiceId') invoiceId: string) {
|
||||
return this.service.send(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
@Post('retry')
|
||||
async retry(@PosInfo() posInfo: IPosPayload, @Param('invoiceId') invoiceId: string) {
|
||||
return this.service.retry(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
@Get('status')
|
||||
async getStatus(
|
||||
@PosInfo() posInfo: IPosPayload,
|
||||
@Param('invoiceId') invoiceId: string,
|
||||
) {
|
||||
return this.service.getStatus(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
@Post('status/refresh')
|
||||
async refreshStatus(
|
||||
@PosInfo() posInfo: IPosPayload,
|
||||
@Param('invoiceId') invoiceId: string,
|
||||
) {
|
||||
return this.service.refreshStatus(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
@Get('attempts')
|
||||
async getAttempts(
|
||||
@PosInfo() posInfo: IPosPayload,
|
||||
@Param('invoiceId') invoiceId: string,
|
||||
) {
|
||||
return this.service.getAttempts(invoiceId, posInfo)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { SalesInvoiceFiscalSwitchService } from '../../../consumer/saleInvoices/fiscal/sales-invoice-fiscal-switch.service'
|
||||
import { NamaTaxSwitchAdapter } from '../../../consumer/saleInvoices/fiscal/switch/nama/nama-fiscal-switch.adapter'
|
||||
import { PosSalesInvoiceFiscalController } from './sales-invoice-fiscal.controller'
|
||||
import { PosSalesInvoiceFiscalService } from './sales-invoice-fiscal.service'
|
||||
|
||||
@Module({
|
||||
controllers: [PosSalesInvoiceFiscalController],
|
||||
providers: [PosSalesInvoiceFiscalService, SalesInvoiceFiscalSwitchService, NamaTaxSwitchAdapter],
|
||||
exports: [PosSalesInvoiceFiscalService],
|
||||
})
|
||||
export class PosSalesInvoiceFiscalModule {}
|
||||
@@ -1,411 +0,0 @@
|
||||
import { IPosPayload } from '@/common/models/posPayload.model'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { Injectable, NotFoundException } from '@nestjs/common'
|
||||
import {
|
||||
FiscalInvoiceCustomerType,
|
||||
FiscalRequestType,
|
||||
FiscalResponseStatus,
|
||||
} from 'generated/prisma/enums'
|
||||
import {
|
||||
TaxSendStatus,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from '../../../consumer/saleInvoices/fiscal/dto/tax-switch.dto'
|
||||
import { SalesInvoiceFiscalSwitchService } from '../../../consumer/saleInvoices/fiscal/sales-invoice-fiscal-switch.service'
|
||||
|
||||
@Injectable()
|
||||
export class PosSalesInvoiceFiscalService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly fiscalSwitchService: SalesInvoiceFiscalSwitchService,
|
||||
) {}
|
||||
|
||||
async send(invoiceId: string, posInfo: IPosPayload) {
|
||||
const payload = await this.buildPayload(invoiceId, posInfo)
|
||||
const itemResults = await this.safeSend(payload)
|
||||
const attempt = await this.persistAttempt(invoiceId, itemResults)
|
||||
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
fiscal_id: attempt.fiscal_id,
|
||||
status: attempt.status,
|
||||
attempt_no: attempt.attempt_no,
|
||||
}
|
||||
}
|
||||
|
||||
async retry(invoiceId: string, posInfo: IPosPayload) {
|
||||
return this.send(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
async getStatus(invoiceId: string, posInfo: IPosPayload) {
|
||||
const invoice = await this.getInvoiceForBusiness(invoiceId, posInfo.business_id)
|
||||
if (!invoice.fiscal) {
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
status: FiscalResponseStatus.NOT_SEND,
|
||||
fiscal: null,
|
||||
}
|
||||
}
|
||||
|
||||
const latestAttempt = invoice.fiscal.attempts[0] || null
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
status: latestAttempt?.status || FiscalResponseStatus.NOT_SEND,
|
||||
fiscal: {
|
||||
id: invoice.fiscal.id,
|
||||
retry_count: invoice.fiscal.retry_count,
|
||||
last_attempt_at: invoice.fiscal.last_attempt_at,
|
||||
},
|
||||
latest_attempt: latestAttempt,
|
||||
}
|
||||
}
|
||||
|
||||
async refreshStatus(invoiceId: string, posInfo: IPosPayload) {
|
||||
const invoice = await this.getInvoiceForBusiness(invoiceId, posInfo.business_id)
|
||||
const latestAttempt = invoice.fiscal?.attempts?.[0]
|
||||
|
||||
if (!invoice.fiscal || !latestAttempt?.tax_id) {
|
||||
return this.getStatus(invoiceId, posInfo)
|
||||
}
|
||||
|
||||
const providerCode = invoice.pos.provider?.code
|
||||
const switchResult = await this.fiscalSwitchService.get(
|
||||
providerCode,
|
||||
latestAttempt.tax_id,
|
||||
)
|
||||
const mappedStatus = this.mapSwitchGetStatus(switchResult.status)
|
||||
|
||||
const refreshedAttempt = await this.prisma.$transaction(async tx => {
|
||||
const nextNo = (latestAttempt.attempt_no || 0) + 1
|
||||
const createdAttempt = await tx.saleInvoiceFiscalAttempts.create({
|
||||
data: {
|
||||
fiscal_id: invoice.fiscal!.id,
|
||||
attempt_no: nextNo,
|
||||
status: mappedStatus,
|
||||
tax_id: switchResult.tax_id,
|
||||
response_payload: switchResult.response_payload
|
||||
? JSON.parse(JSON.stringify(switchResult.response_payload))
|
||||
: undefined,
|
||||
received_at: switchResult.received_at
|
||||
? new Date(switchResult.received_at)
|
||||
: null,
|
||||
type: FiscalRequestType.MAIN,
|
||||
},
|
||||
})
|
||||
|
||||
await tx.saleInvoiceFiscals.update({
|
||||
where: { id: invoice.fiscal!.id },
|
||||
data: {
|
||||
retry_count: nextNo,
|
||||
last_attempt_at: createdAttempt.created_at,
|
||||
},
|
||||
})
|
||||
|
||||
return createdAttempt
|
||||
})
|
||||
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
status: refreshedAttempt.status,
|
||||
latest_attempt: refreshedAttempt,
|
||||
}
|
||||
}
|
||||
|
||||
async getAttempts(invoiceId: string, posInfo: IPosPayload) {
|
||||
const invoice = await this.getInvoiceForBusiness(invoiceId, posInfo.business_id)
|
||||
if (!invoice.fiscal) {
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
fiscal_id: null,
|
||||
attempts: [],
|
||||
}
|
||||
}
|
||||
|
||||
const attempts = await this.prisma.saleInvoiceFiscalAttempts.findMany({
|
||||
where: {
|
||||
fiscal_id: invoice.fiscal.id,
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
invoice_id: invoiceId,
|
||||
fiscal_id: invoice.fiscal.id,
|
||||
attempts,
|
||||
}
|
||||
}
|
||||
|
||||
private async buildPayload(invoiceId: string, posInfo: IPosPayload) {
|
||||
const invoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoiceId,
|
||||
pos: {
|
||||
id: posInfo.pos_id,
|
||||
complex: {
|
||||
business_activity_id: posInfo.business_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
invoice_date: true,
|
||||
total_amount: true,
|
||||
items: {
|
||||
select: {
|
||||
id: true,
|
||||
quantity: true,
|
||||
unit_price: true,
|
||||
total_amount: true,
|
||||
measure_unit_text: true,
|
||||
sku_code: true,
|
||||
sku_vat: true,
|
||||
measure_unit_code: true,
|
||||
good_id: true,
|
||||
service_id: true,
|
||||
payload: true,
|
||||
good_snapshot: true,
|
||||
},
|
||||
},
|
||||
customer: {
|
||||
select: {
|
||||
type: true,
|
||||
individual: true,
|
||||
legal: true,
|
||||
},
|
||||
},
|
||||
|
||||
pos: {
|
||||
select: {
|
||||
complex: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
fiscal_id: true,
|
||||
economic_code: true,
|
||||
consumer: {
|
||||
select: {
|
||||
legal: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
fiscal_switch_type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
individual: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
fiscal_switch_type: 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_code: invoice.code,
|
||||
invoice_date: invoice.invoice_date,
|
||||
total_amount: Number(invoice.total_amount),
|
||||
customer_type: invoice.customer
|
||||
? FiscalInvoiceCustomerType.Known
|
||||
: FiscalInvoiceCustomerType.Unknown,
|
||||
type: FiscalRequestType.MAIN,
|
||||
provider_code: partner.fiscal_switch_type,
|
||||
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),
|
||||
good_id: item.good_id,
|
||||
service_id: item.service_id,
|
||||
payload: item.payload,
|
||||
good_snapshot: item.good_snapshot,
|
||||
discount: String((item.payload as Record<string, any>)?.discount || '0'),
|
||||
sku: item.sku_code,
|
||||
sku_vat: String(item.sku_vat),
|
||||
measure_unit: item.measure_unit_code,
|
||||
// sku: item.
|
||||
})),
|
||||
} satisfies TaxSwitchSendPayloadDto
|
||||
}
|
||||
|
||||
private async safeSend(payload: TaxSwitchSendPayloadDto) {
|
||||
try {
|
||||
return await this.fiscalSwitchService.send(payload)
|
||||
} catch (error: any) {
|
||||
const now = new Date().toISOString()
|
||||
return payload.items.map(item => ({
|
||||
invoice_item_id: item.invoice_item_id,
|
||||
status: TaxSendStatus.FAILED,
|
||||
error_message: error?.message || 'Unexpected fiscal switch error.',
|
||||
sent_at: now,
|
||||
received_at: now,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
private async persistAttempt(
|
||||
invoiceId: string,
|
||||
itemResults: TaxSwitchSendItemResultDto[],
|
||||
) {
|
||||
return this.prisma.$transaction(async tx => {
|
||||
const fiscal = await tx.saleInvoiceFiscals.upsert({
|
||||
where: { invoice_id: invoiceId },
|
||||
update: {},
|
||||
create: {
|
||||
invoice_id: invoiceId,
|
||||
},
|
||||
})
|
||||
|
||||
const latest = await tx.saleInvoiceFiscalAttempts.findFirst({
|
||||
where: { fiscal_id: fiscal.id },
|
||||
orderBy: { attempt_no: 'desc' },
|
||||
select: { attempt_no: true },
|
||||
})
|
||||
const nextAttemptNo = (latest?.attempt_no || 0) + 1
|
||||
|
||||
const finalStatus = this.mapItemResultsStatus(itemResults)
|
||||
const firstTaxId = itemResults.find(item => item.tax_id)?.tax_id || null
|
||||
const sentAt = itemResults.map(item => item.sent_at).find(Boolean)
|
||||
const receivedAt = itemResults.map(item => item.received_at).find(Boolean)
|
||||
const errors = itemResults.map(item => item.error_message).filter(Boolean)
|
||||
const errorMessage = errors.length ? Array.from(new Set(errors)).join(' | ') : null
|
||||
|
||||
const attempt = await tx.saleInvoiceFiscalAttempts.create({
|
||||
data: {
|
||||
fiscal_id: fiscal.id,
|
||||
attempt_no: nextAttemptNo,
|
||||
status: finalStatus,
|
||||
tax_id: firstTaxId,
|
||||
type: FiscalRequestType.MAIN,
|
||||
request_payload: JSON.parse(
|
||||
JSON.stringify(itemResults.map(item => item.request_payload)),
|
||||
),
|
||||
response_payload: JSON.parse(
|
||||
JSON.stringify(itemResults.map(item => item.response_payload)),
|
||||
),
|
||||
error_message: errorMessage,
|
||||
sent_at: sentAt ? new Date(sentAt) : null,
|
||||
received_at: receivedAt ? new Date(receivedAt) : null,
|
||||
},
|
||||
})
|
||||
|
||||
await tx.saleInvoiceFiscals.update({
|
||||
where: { id: fiscal.id },
|
||||
data: {
|
||||
retry_count: nextAttemptNo,
|
||||
last_attempt_at: attempt.sent_at || attempt.created_at,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
fiscal_id: fiscal.id,
|
||||
status: attempt.status,
|
||||
attempt_no: attempt.attempt_no,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private mapItemResultsStatus(itemResults: TaxSwitchSendItemResultDto[]) {
|
||||
if (!itemResults.length) {
|
||||
return FiscalResponseStatus.NOT_SEND
|
||||
}
|
||||
const hasFailure = itemResults.some(item => item.status === TaxSendStatus.FAILED)
|
||||
if (hasFailure) {
|
||||
return FiscalResponseStatus.FAILURE
|
||||
}
|
||||
const hasSent = itemResults.some(item => item.status === TaxSendStatus.SENT)
|
||||
if (hasSent) {
|
||||
return FiscalResponseStatus.SUCCESS
|
||||
}
|
||||
return FiscalResponseStatus.NOT_SEND
|
||||
}
|
||||
|
||||
private mapSwitchGetStatus(status: TaxSwitchGetResultDto['status']) {
|
||||
switch (status) {
|
||||
case TaxSendStatus.SENT:
|
||||
return FiscalResponseStatus.SUCCESS
|
||||
case TaxSendStatus.FAILED:
|
||||
return FiscalResponseStatus.FAILURE
|
||||
default:
|
||||
return FiscalResponseStatus.NOT_SEND
|
||||
}
|
||||
}
|
||||
|
||||
private async getInvoiceForBusiness(invoiceId: string, businessId: string) {
|
||||
const invoice = await this.prisma.salesInvoice.findFirst({
|
||||
where: {
|
||||
id: invoiceId,
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity_id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
pos: {
|
||||
select: {
|
||||
provider: {
|
||||
select: {
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
fiscal: {
|
||||
select: {
|
||||
id: true,
|
||||
retry_count: true,
|
||||
last_attempt_at: true,
|
||||
attempts: {
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
attempt_no: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
sent_at: true,
|
||||
received_at: true,
|
||||
error_message: true,
|
||||
created_at: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!invoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
|
||||
return invoice
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -1,7 +1,6 @@
|
||||
import { ApiProperty, PartialType } from '@nestjs/swagger'
|
||||
import { IsEnum, IsNumber, IsObject, IsOptional, IsString } from 'class-validator'
|
||||
import { IsNumber, IsObject, IsOptional, IsString } from 'class-validator'
|
||||
import type { SaleInvoiceType } from 'common/interfaces/sale-invoice-payload'
|
||||
import { UnitType } from 'generated/prisma/enums'
|
||||
|
||||
export class CreateSalesInvoiceItemDto {
|
||||
@IsNumber()
|
||||
@@ -24,10 +23,6 @@ export class CreateSalesInvoiceItemDto {
|
||||
@ApiProperty({ required: true })
|
||||
invoice_id: string
|
||||
|
||||
@IsEnum(UnitType)
|
||||
@ApiProperty({ enum: Object.values(UnitType) })
|
||||
unit_type: UnitType
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
|
||||
@@ -20,15 +20,24 @@ export class SalesInvoicesController {
|
||||
return this.salesInvoicesService.findOne(posInfo, id)
|
||||
}
|
||||
|
||||
@Get(':id/inquiry')
|
||||
inquiry(@PosInfo() posInfo: IPosPayload, @Param('id') id: string) {
|
||||
return this.salesInvoicesService.inquiry(
|
||||
posInfo.consumer_account_id,
|
||||
posInfo.pos_id,
|
||||
id,
|
||||
)
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() data: CreateSalesInvoiceDto, @PosInfo() posInfo: IPosPayload) {
|
||||
return this.salesInvoicesService.create(data, posInfo)
|
||||
}
|
||||
|
||||
// @Post(':id/send')
|
||||
// send(@Param('id') id: string, @PosInfo() posInfo: IPosPayload) {
|
||||
// return this.salesInvoicesService.send(id, posInfo)
|
||||
// }
|
||||
@Post(':id/send')
|
||||
send(@Param('id') id: string, @PosInfo() posInfo: IPosPayload) {
|
||||
return this.salesInvoicesService.send(id, posInfo)
|
||||
}
|
||||
|
||||
// @Post('send/bulk')
|
||||
// sendBulk(@Body() data: SendBulkSalesInvoicesDto, @PosInfo() posInfo: IPosPayload) {
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { SalesInvoiceFiscalSwitchService } from '../../consumer/saleInvoices/fiscal/sales-invoice-fiscal-switch.service'
|
||||
import { SalesInvoiceFiscalService } from '../../consumer/saleInvoices/fiscal/sales-invoice-fiscal.service'
|
||||
import { NamaTaxSwitchAdapter } from '../../consumer/saleInvoices/fiscal/switch/nama/nama-fiscal-switch.adapter'
|
||||
import { PosSalesInvoiceFiscalModule } from './fiscal/sales-invoice-fiscal.module'
|
||||
import { HttpClientUtil } from '../../../common/utils/http-client.util'
|
||||
import { SalesInvoiceTspSwitchService } from '../../tspProviders/sales-invoice-tsp-switch.service'
|
||||
import { SalesInvoiceTspService } from '../../tspProviders/sales-invoice-tsp.service'
|
||||
import { NamaProviderSwitchAdapter } from '../../tspProviders/switch/nama/nama-provider.adapter'
|
||||
import { SalesInvoicesController } from './sales-invoices.controller'
|
||||
import { SalesInvoicesService } from './sales-invoices.service'
|
||||
|
||||
@Module({
|
||||
imports: [PosSalesInvoiceFiscalModule],
|
||||
controllers: [SalesInvoicesController],
|
||||
providers: [
|
||||
SalesInvoicesService,
|
||||
SalesInvoiceFiscalService,
|
||||
SalesInvoiceFiscalSwitchService,
|
||||
NamaTaxSwitchAdapter,
|
||||
HttpClientUtil,
|
||||
SalesInvoiceTspService,
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
],
|
||||
})
|
||||
export class PosSalesInvoicesModule {}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { IPosPayload } from '@/common/models/posPayload.model'
|
||||
import { translateEnumValue } from '@/common/utils'
|
||||
import { SalesInvoiceCreateInput } from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
|
||||
import { ResponseMapper } from 'common/response/response-mapper'
|
||||
import type { CustomerIndividual, CustomerLegal } from 'generated/prisma/client'
|
||||
import { Prisma } from 'generated/prisma/client'
|
||||
import {
|
||||
ConsumerRole,
|
||||
CustomerType,
|
||||
FiscalResponseStatus,
|
||||
PaymentMethodType,
|
||||
TspProviderRequestType,
|
||||
TspProviderResponseStatus,
|
||||
} from 'generated/prisma/enums'
|
||||
import { SalesInvoiceFiscalService } from '../../consumer/saleInvoices/fiscal/sales-invoice-fiscal.service'
|
||||
import { SalesInvoiceTspService } from '../../tspProviders/sales-invoice-tsp.service'
|
||||
import { CreateSalesInvoiceDto } from './dto/create-sales-invoice.dto'
|
||||
import { SalesInvoicesFilterDto } from './dto/sales-invoices-filter.dto'
|
||||
|
||||
@@ -53,7 +56,7 @@ export class SalesInvoicesService {
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private salesInvoiceTaxService: SalesInvoiceFiscalService,
|
||||
private salesInvoiceTaxService: SalesInvoiceTspService,
|
||||
) {}
|
||||
|
||||
async findAll(posInfo: IPosPayload, query: SalesInvoicesFilterDto = {}) {
|
||||
@@ -96,17 +99,13 @@ export class SalesInvoicesService {
|
||||
},
|
||||
},
|
||||
},
|
||||
fiscal: {
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
attempts: {
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -117,8 +116,8 @@ export class SalesInvoicesService {
|
||||
const summaryItems = items.map(invoice => ({
|
||||
...invoice,
|
||||
status: translateEnumValue(
|
||||
'FiscalResponseStatus',
|
||||
invoice.fiscal?.attempts?.[0]?.status || FiscalResponseStatus.NOT_SEND,
|
||||
'TspProviderResponseStatus',
|
||||
invoice.tsp_attempts?.[0]?.status || TspProviderResponseStatus.NOT_SEND,
|
||||
),
|
||||
}))
|
||||
|
||||
@@ -126,10 +125,11 @@ export class SalesInvoicesService {
|
||||
}
|
||||
|
||||
async findOne(posInfo: IPosPayload, id: string) {
|
||||
const invoice = await this.prisma.salesInvoice.findFirstOrThrow({
|
||||
const invoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id,
|
||||
pos: {
|
||||
id: posInfo.pos_id,
|
||||
complex: {
|
||||
business_activity_id: posInfo.business_id,
|
||||
},
|
||||
@@ -234,45 +234,50 @@ export class SalesInvoicesService {
|
||||
},
|
||||
},
|
||||
},
|
||||
fiscal: {
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
retry_count: true,
|
||||
last_attempt_at: true,
|
||||
attempts: {
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
attempt_no: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
error_message: true,
|
||||
sent_at: true,
|
||||
received_at: true,
|
||||
created_at: true,
|
||||
},
|
||||
},
|
||||
attempt_no: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
error_message: true,
|
||||
sent_at: true,
|
||||
received_at: true,
|
||||
created_at: true,
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return ResponseMapper.single({
|
||||
...invoice,
|
||||
status: invoice.fiscal?.attempts?.[0]?.status || FiscalResponseStatus.NOT_SEND,
|
||||
})
|
||||
if (invoice) {
|
||||
const { tsp_attempts, ...rest } = invoice || {}
|
||||
|
||||
return ResponseMapper.single({
|
||||
...rest,
|
||||
status: tsp_attempts?.[0]?.status || TspProviderResponseStatus.NOT_SEND,
|
||||
})
|
||||
} else throw new NotFoundException('فاکتور مورد نظر شما یافت نشد.')
|
||||
}
|
||||
|
||||
// async send(invoiceId: string, posInfo: IPosPayload) {
|
||||
// await this.salesInvoiceTaxService.send(invoiceId, posInfo.pos_id)
|
||||
async send(invoiceId: string, posInfo: IPosPayload) {
|
||||
const consumer_id = await this.checkAccessToInvoice(
|
||||
posInfo.consumer_account_id,
|
||||
posInfo.pos_id,
|
||||
)
|
||||
const invoice = await this.salesInvoiceTaxService.send(consumer_id, invoiceId)
|
||||
|
||||
// return ResponseMapper.single({
|
||||
// invoice_id: invoiceId,
|
||||
// sent_to_tax: true,
|
||||
// })
|
||||
// }
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
|
||||
async inquiry(consumer_account_id: string, pos_id: string, invoiceId: string) {
|
||||
const consumer_id = await this.checkAccessToInvoice(consumer_account_id, pos_id)
|
||||
const invoice = await this.salesInvoiceTaxService.get(invoiceId, pos_id, consumer_id)
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
|
||||
// async sendBulk(invoiceIds: string[], posInfo: IPosPayload) {
|
||||
// if (!invoiceIds.length) {
|
||||
@@ -325,13 +330,13 @@ export class SalesInvoicesService {
|
||||
normalizedInvoiceDate,
|
||||
)
|
||||
|
||||
if (data.send_to_tsp) {
|
||||
await this.salesInvoiceTaxService.send(salesInvoice.id, pos_id)
|
||||
}
|
||||
|
||||
return salesInvoice
|
||||
})
|
||||
|
||||
if (data.send_to_tax) {
|
||||
await this.salesInvoiceTaxService.send(salesInvoice.id, pos_id)
|
||||
}
|
||||
|
||||
return ResponseMapper.create(salesInvoice)
|
||||
} catch (error) {
|
||||
if (
|
||||
@@ -500,16 +505,12 @@ export class SalesInvoicesService {
|
||||
}
|
||||
|
||||
if (query.status) {
|
||||
if (query.status === FiscalResponseStatus.NOT_SEND) {
|
||||
where.fiscal = null
|
||||
if (query.status === TspProviderResponseStatus.NOT_SEND) {
|
||||
where.tsp_attempts = undefined
|
||||
} else {
|
||||
where.fiscal = {
|
||||
is: {
|
||||
attempts: {
|
||||
some: {
|
||||
status: query.status,
|
||||
},
|
||||
},
|
||||
where.tsp_attempts = {
|
||||
some: {
|
||||
status: query.status,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -530,8 +531,9 @@ export class SalesInvoicesService {
|
||||
cash: PaymentMethodType.CASH,
|
||||
set_off: PaymentMethodType.SET_OFF,
|
||||
card: PaymentMethodType.CARD,
|
||||
payment_gateway: PaymentMethodType.PAYMENT_GATEWAY,
|
||||
bank: PaymentMethodType.BANK,
|
||||
check: PaymentMethodType.CHECK,
|
||||
check: PaymentMethodType.CHEQUE,
|
||||
other: PaymentMethodType.OTHER,
|
||||
terminal: PaymentMethodType.TERMINAL,
|
||||
}
|
||||
@@ -705,6 +707,8 @@ export class SalesInvoicesService {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
VAT: true,
|
||||
},
|
||||
},
|
||||
local_sku: true,
|
||||
@@ -714,6 +718,7 @@ export class SalesInvoicesService {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
base_sale_price: true,
|
||||
@@ -755,7 +760,7 @@ export class SalesInvoicesService {
|
||||
} = params
|
||||
const { customer_id, customer_type, customer, payments, ...invoiceData } = data
|
||||
|
||||
const salesInvoiceData: any = {
|
||||
const salesInvoiceData: SalesInvoiceCreateInput = {
|
||||
...invoiceData,
|
||||
invoice_date: normalizedInvoiceDate,
|
||||
invoice_number: invoiceNumber,
|
||||
@@ -764,11 +769,14 @@ export class SalesInvoicesService {
|
||||
items: {
|
||||
createMany: {
|
||||
data: data.items.map(item => ({
|
||||
good_id: item.good_id,
|
||||
good_id: item.good_id!,
|
||||
quantity: item.quantity,
|
||||
unit_price: item.unit_price,
|
||||
total_amount: item.total_amount,
|
||||
measure_unit_text: item.unit_type,
|
||||
measure_unit_text: goodsById.get(item.good_id!)?.measure_unit.name || null,
|
||||
measure_unit_code: goodsById.get(item.good_id!)?.measure_unit.code || null,
|
||||
sku_code: goodsById.get(item.good_id!)?.sku.code || null,
|
||||
sku_vat: goodsById.get(item.good_id!)?.sku.VAT || null,
|
||||
payload: item.payload ? JSON.parse(JSON.stringify(item.payload)) : undefined,
|
||||
good_snapshot: item.good_id
|
||||
? JSON.parse(
|
||||
@@ -777,7 +785,6 @@ export class SalesInvoicesService {
|
||||
}),
|
||||
)
|
||||
: undefined,
|
||||
unit_type: item.unit_type,
|
||||
})),
|
||||
},
|
||||
},
|
||||
@@ -794,6 +801,16 @@ export class SalesInvoicesService {
|
||||
},
|
||||
}
|
||||
|
||||
if (data.send_to_tsp) {
|
||||
salesInvoiceData.tsp_attempts = {
|
||||
create: {
|
||||
attempt_no: 1,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (customerId) {
|
||||
salesInvoiceData.customer = {
|
||||
connect: {
|
||||
@@ -819,10 +836,29 @@ export class SalesInvoicesService {
|
||||
},
|
||||
select: {
|
||||
invoice_number: true,
|
||||
pos: {
|
||||
select: {
|
||||
complex: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
invoice_number_sequence: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return (latestInvoice?.invoice_number || 0) + 1
|
||||
const latestSequence =
|
||||
latestInvoice?.pos?.complex?.business_activity?.invoice_number_sequence.toNumber() ||
|
||||
0
|
||||
|
||||
console.log(latestSequence)
|
||||
|
||||
return Math.max(latestInvoice?.invoice_number || 0, latestSequence) + 1
|
||||
}
|
||||
|
||||
private async createPayments(
|
||||
@@ -852,7 +888,7 @@ export class SalesInvoicesService {
|
||||
terminal_id: terminalInfo.terminalId,
|
||||
stan: terminalInfo.stan,
|
||||
rrn: terminalInfo.rrn,
|
||||
transaction_date_time: new Date(terminalInfo.transactionDateTime),
|
||||
transaction_date_time: new Date(terminalInfo.transactionDateTime || ''),
|
||||
customer_card_no: terminalInfo.customerCardNO || null,
|
||||
description: terminalInfo.description || null,
|
||||
},
|
||||
@@ -867,6 +903,35 @@ export class SalesInvoicesService {
|
||||
pos_id: string,
|
||||
invoice_number: number,
|
||||
) {
|
||||
return `${business_id.substring(0, 2)}-${complex_id.substring(0, 2)}-${pos_id.substring(0, 2)}-${invoice_number.toString()}`
|
||||
return `${business_id.substring(business_id.length - 2, business_id.length)}-${complex_id.substring(complex_id.length - 2, complex_id.length)}-${pos_id.substring(pos_id.length - 2, pos_id.length)}-${invoice_number.toString()}`
|
||||
}
|
||||
|
||||
private async checkAccessToInvoice(
|
||||
consumer_account_id: string,
|
||||
pos_id: string,
|
||||
): Promise<string> {
|
||||
const consumer = await this.prisma.consumerAccount.findUnique({
|
||||
where: {
|
||||
id: consumer_account_id,
|
||||
OR: [
|
||||
{
|
||||
pos: {
|
||||
id: pos_id,
|
||||
},
|
||||
},
|
||||
{
|
||||
role: ConsumerRole.OWNER,
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
consumer_id: true,
|
||||
},
|
||||
})
|
||||
if (!consumer) {
|
||||
throw new BadRequestException('شما دسترسی لازم برای ارسال فاکتور را ندارید.')
|
||||
}
|
||||
|
||||
return consumer.consumer_id
|
||||
}
|
||||
}
|
||||
|
||||
+117
-55
@@ -1,28 +1,27 @@
|
||||
import {
|
||||
CustomerType,
|
||||
FiscalInvoiceCustomerType,
|
||||
FiscalRequestType,
|
||||
PartnerFiscalSwitchType,
|
||||
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 enum TaxSendStatus {
|
||||
SENT = 'SENT',
|
||||
FAILED = 'FAILED',
|
||||
PENDING = 'PENDING',
|
||||
}
|
||||
|
||||
export class CustomerLegalInfoDto {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
@@ -66,7 +65,34 @@ export class CustomerInfoDto {
|
||||
@ValidateNested({ each: true })
|
||||
individual_info?: CustomerIndividualInfoDto
|
||||
}
|
||||
export class TaxSwitchSendItemPayloadDto {
|
||||
|
||||
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
|
||||
@@ -116,20 +142,20 @@ export class TaxSwitchSendItemPayloadDto {
|
||||
payload?: unknown
|
||||
}
|
||||
|
||||
export class TaxSwitchSendPayloadDto {
|
||||
@ApiProperty({ required: true, enum: FiscalRequestType })
|
||||
@IsEnum(FiscalRequestType)
|
||||
type: FiscalRequestType
|
||||
export class TspProviderSendPayloadDto {
|
||||
@ApiProperty({ required: true, enum: TspProviderRequestType })
|
||||
@IsEnum(TspProviderRequestType)
|
||||
type: TspProviderRequestType
|
||||
|
||||
@ApiProperty({ required: true, enum: FiscalInvoiceCustomerType })
|
||||
@IsEnum(FiscalInvoiceCustomerType)
|
||||
customer_type: FiscalInvoiceCustomerType
|
||||
@ApiProperty({ required: true, enum: TspProviderCustomerType })
|
||||
@IsEnum(TspProviderCustomerType)
|
||||
customer_type: TspProviderCustomerType
|
||||
|
||||
@ApiProperty({ type: [TaxSwitchSendItemPayloadDto] })
|
||||
@ApiProperty({ type: [TspProviderSendItemPayloadDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TaxSwitchSendItemPayloadDto)
|
||||
items: TaxSwitchSendItemPayloadDto[]
|
||||
@Type(() => TspProviderSendItemPayloadDto)
|
||||
items: TspProviderSendItemPayloadDto[]
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@Type(() => CustomerInfoDto)
|
||||
@@ -137,11 +163,10 @@ export class TaxSwitchSendPayloadDto {
|
||||
customer?: CustomerInfoDto
|
||||
|
||||
@ApiProperty({ required: true, nullable: true })
|
||||
@IsString()
|
||||
invoice_code: string
|
||||
@IsNumber()
|
||||
invoice_number: number
|
||||
|
||||
@ApiProperty({ required: true, nullable: true })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
invoice_date: Date
|
||||
|
||||
@@ -153,86 +178,123 @@ export class TaxSwitchSendPayloadDto {
|
||||
@IsNumber()
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: true, enum: PartnerFiscalSwitchType })
|
||||
@IsEnum(PartnerFiscalSwitchType)
|
||||
provider_code: PartnerFiscalSwitchType
|
||||
@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 TaxSwitchSendItemResultDto {
|
||||
export class TspProviderSendItemResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_item_id: string
|
||||
invoice_id: string
|
||||
|
||||
@ApiProperty({ enum: TaxSendStatus })
|
||||
@IsEnum(TaxSendStatus)
|
||||
status: TaxSendStatus
|
||||
@ApiProperty({ enum: TspProviderResponseStatus })
|
||||
@IsEnum(TspProviderResponseStatus)
|
||||
status: TspProviderResponseStatus
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tax_id?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@ApiProperty({ required: true, nullable: true, type: TspProviderSendPayloadDto })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
request_payload?: unknown
|
||||
@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()
|
||||
error_message?: string | null
|
||||
message?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
sent_at?: string | null
|
||||
sent_at: string
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
received_at?: string | null
|
||||
received_at: string
|
||||
}
|
||||
|
||||
export class TaxSwitchBulkSendResultDto {
|
||||
export class TspProviderBulkSendResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_id: string
|
||||
|
||||
@ApiProperty({ type: [TaxSwitchSendItemResultDto] })
|
||||
@ApiProperty({ type: [TspProviderSendItemResultDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TaxSwitchSendItemResultDto)
|
||||
items: TaxSwitchSendItemResultDto[]
|
||||
@Type(() => TspProviderSendItemResultDto)
|
||||
items: TspProviderSendItemResultDto[]
|
||||
}
|
||||
|
||||
export class TaxSwitchGetResultDto {
|
||||
export class TspProviderGetResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
tax_id: string
|
||||
|
||||
@ApiProperty({ enum: TaxSendStatus })
|
||||
@IsEnum(TaxSendStatus)
|
||||
status: TaxSendStatus
|
||||
@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: false, nullable: true })
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
received_at?: string | null
|
||||
sent_at: string
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString()
|
||||
received_at: string
|
||||
}
|
||||
|
||||
export interface ITaxSwitchAdapter {
|
||||
export interface IProviderSwitchAdapter {
|
||||
readonly code: string
|
||||
send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]>
|
||||
sendBulk(payloads: TaxSwitchSendPayloadDto[]): Promise<TaxSwitchBulkSendResultDto[]>
|
||||
get(taxId: string): Promise<TaxSwitchGetResultDto>
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user