feat: add DTOs and services for tax switch integration
- Created SendBulkSaleInvoicesDto for handling bulk sale invoice requests. - Implemented TaxSwitchSendPayloadDto and related DTOs for tax switch item payloads and results. - Developed SalesInvoiceTaxSwitchService to manage tax switch operations, including sending and retrieving tax information. - Added SalesInvoiceTaxService for handling sales invoice tax logic, including bulk sending and persistence of results. - Introduced NamaTaxSwitchAdapter to interact with the tax switch service, simulating external API responses. - Created SendBulkSalesInvoicesDto for POS module to handle bulk sales invoice requests.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { QUERY_CONSTANTS } from '@/common/queryConstants'
|
||||
import { ComplexSelect } from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
@@ -53,8 +54,6 @@ export class BusinessActivityComplexesService {
|
||||
data: CreateConsumerComplexDto,
|
||||
) {
|
||||
const complex = await this.prisma.$transaction(async tx => {
|
||||
const now = new Date()
|
||||
|
||||
const relatedLicense = await tx.licenseAccountAllocation.findFirst({
|
||||
where: {
|
||||
license_activation: {
|
||||
@@ -62,22 +61,7 @@ export class BusinessActivityComplexesService {
|
||||
id: business_activity_id,
|
||||
consumer_id,
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
expires_at: {
|
||||
gte: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
license_renews: {
|
||||
some: {
|
||||
expires_at: {
|
||||
gte: now,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
|
||||
},
|
||||
account_id: null,
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QUERY_CONSTANTS } from '@/common/queryConstants'
|
||||
import { PasswordUtil } from '@/common/utils/password.util'
|
||||
import {
|
||||
AccountStatus,
|
||||
@@ -189,22 +190,7 @@ export class ComplexPosesService {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
expires_at: {
|
||||
gte: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
license_renews: {
|
||||
some: {
|
||||
expires_at: {
|
||||
gte: now,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { ArrayMinSize, IsArray, IsString } from 'class-validator'
|
||||
|
||||
export class SendBulkSaleInvoicesDto {
|
||||
@ApiProperty({ type: [String], minItems: 1 })
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsString({ each: true })
|
||||
invoice_ids: string[]
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import { TokenAccount } from '@/common/decorators/tokenInfo.decorator'
|
||||
import { Controller, Get, Param } from '@nestjs/common'
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common'
|
||||
import { ApiTags } from '@nestjs/swagger'
|
||||
import type {
|
||||
SaleInvoicesServiceFindAllResponseDto,
|
||||
SaleInvoicesServiceFindOneResponseDto,
|
||||
} from './dto/saleInvoices-response.dto'
|
||||
import { SendBulkSaleInvoicesDto } from './dto/send-saleInvoices.dto'
|
||||
import { SaleInvoicesService } from './saleInvoices.service'
|
||||
import type { SaleInvoicesServiceFindAllResponseDto, SaleInvoicesServiceFindOneResponseDto } from './dto/saleInvoices-response.dto'
|
||||
|
||||
@ApiTags('ConsumerSaleInvoices')
|
||||
@Controller('consumer/sale-invoices')
|
||||
@@ -10,12 +14,30 @@ export class StatisticsController {
|
||||
constructor(private readonly service: SaleInvoicesService) {}
|
||||
|
||||
@Get('')
|
||||
async findAll(@TokenAccount('userId') consumerId: string): Promise<SaleInvoicesServiceFindAllResponseDto> {
|
||||
async findAll(
|
||||
@TokenAccount('userId') consumerId: string,
|
||||
): Promise<SaleInvoicesServiceFindAllResponseDto> {
|
||||
return this.service.findAll(consumerId)
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async findOne(@TokenAccount('userId') consumerId: string, @Param('id') id: string): Promise<SaleInvoicesServiceFindOneResponseDto> {
|
||||
async findOne(
|
||||
@TokenAccount('userId') consumerId: string,
|
||||
@Param('id') id: string,
|
||||
): Promise<SaleInvoicesServiceFindOneResponseDto> {
|
||||
return this.service.findOne(consumerId, id)
|
||||
}
|
||||
|
||||
@Post(':id/send_tax')
|
||||
async send(@TokenAccount('userId') consumerId: string, @Param('id') id: string) {
|
||||
return this.service.send(consumerId, id)
|
||||
}
|
||||
|
||||
@Post('send_tax_bulk')
|
||||
async sendBulk(
|
||||
@TokenAccount('userId') consumerId: string,
|
||||
@Body() data: SendBulkSaleInvoicesDto,
|
||||
) {
|
||||
return this.service.sendBulk(consumerId, data.invoice_ids)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,19 @@ import { PrismaModule } from '@/prisma/prisma.module'
|
||||
import { Module } from '@nestjs/common'
|
||||
import { StatisticsController } from './saleInvoices.controller'
|
||||
import { SaleInvoicesService } from './saleInvoices.service'
|
||||
import { SalesInvoiceTaxSwitchService } from './tax/sales-invoice-tax-switch.service'
|
||||
import { SalesInvoiceTaxService } from './tax/sales-invoice-tax.service'
|
||||
import { NamaTaxSwitchAdapter } from './tax/switch/nama-tax-switch.adapter'
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [StatisticsController],
|
||||
providers: [SaleInvoicesService],
|
||||
providers: [
|
||||
SaleInvoicesService,
|
||||
SalesInvoiceTaxService,
|
||||
SalesInvoiceTaxSwitchService,
|
||||
NamaTaxSwitchAdapter,
|
||||
],
|
||||
exports: [SaleInvoicesService],
|
||||
})
|
||||
export class ConsumerSaleInvoicesModule {}
|
||||
|
||||
@@ -4,12 +4,16 @@ import {
|
||||
SalesInvoiceWhereUniqueInput,
|
||||
} from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
import { ResponseMapper } from 'common/response/response-mapper'
|
||||
import { SalesInvoiceTaxService } from './tax/sales-invoice-tax.service'
|
||||
|
||||
@Injectable()
|
||||
export class SaleInvoicesService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private salesInvoiceTaxService: SalesInvoiceTaxService,
|
||||
) {}
|
||||
|
||||
private readonly defaultSelect: SalesInvoiceSelect = {
|
||||
id: true,
|
||||
@@ -45,6 +49,21 @@ export class SaleInvoicesService {
|
||||
},
|
||||
},
|
||||
},
|
||||
fiscal: {
|
||||
select: {
|
||||
id: true,
|
||||
attempts: {
|
||||
orderBy: {
|
||||
created_at: 'asc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
async findAll(consumer_id: string, page = 1, perPage = 10) {
|
||||
@@ -139,4 +158,26 @@ export class SaleInvoicesService {
|
||||
})
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string) {
|
||||
await this.salesInvoiceTaxService.send(consumer_id, invoice_id)
|
||||
|
||||
return ResponseMapper.single({
|
||||
invoice_id,
|
||||
sent_to_tax: true,
|
||||
})
|
||||
}
|
||||
|
||||
async sendBulk(consumer_id: string, invoiceIds: string[]) {
|
||||
if (!invoiceIds.length) {
|
||||
throw new BadRequestException('لیست شناسه فاکتورها نمیتواند خالی باشد.')
|
||||
}
|
||||
|
||||
await this.salesInvoiceTaxService.sendBulk(consumer_id, invoiceIds)
|
||||
|
||||
return ResponseMapper.single({
|
||||
invoice_ids: invoiceIds,
|
||||
sent_to_tax: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
IsArray,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
|
||||
export enum TaxSendStatus {
|
||||
SENT = 'SENT',
|
||||
FAILED = 'FAILED',
|
||||
PENDING = 'PENDING',
|
||||
}
|
||||
|
||||
export class TaxSwitchSendItemPayloadDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_item_id: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
quantity: number
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
unit_price: number
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
unit_type: string
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
good_id?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
service_id?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
payload?: unknown
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
good_snapshot?: unknown
|
||||
}
|
||||
|
||||
export class TaxSwitchSendPayloadDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_id: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_code: string
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
invoice_date: string | null
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
provider_code?: string | null
|
||||
|
||||
@ApiProperty({ type: [TaxSwitchSendItemPayloadDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TaxSwitchSendItemPayloadDto)
|
||||
items: TaxSwitchSendItemPayloadDto[]
|
||||
}
|
||||
|
||||
export class TaxSwitchSendItemResultDto {
|
||||
@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()
|
||||
@IsDateString()
|
||||
sent_at?: string | null
|
||||
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
received_at?: string | null
|
||||
}
|
||||
|
||||
export class TaxSwitchBulkSendResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
invoice_id: string
|
||||
|
||||
@ApiProperty({ type: [TaxSwitchSendItemResultDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TaxSwitchSendItemResultDto)
|
||||
items: TaxSwitchSendItemResultDto[]
|
||||
}
|
||||
|
||||
export class TaxSwitchGetResultDto {
|
||||
@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()
|
||||
@IsDateString()
|
||||
received_at?: string | null
|
||||
}
|
||||
|
||||
export interface ITaxSwitchAdapter {
|
||||
readonly code: string
|
||||
send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]>
|
||||
sendBulk(payloads: TaxSwitchSendPayloadDto[]): Promise<TaxSwitchBulkSendResultDto[]>
|
||||
get(taxId: string): Promise<TaxSwitchGetResultDto>
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
TaxSwitchBulkSendResultDto,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from './dto/tax-switch.dto'
|
||||
import { NamaTaxSwitchAdapter } from './switch/nama-tax-switch.adapter'
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceTaxSwitchService {
|
||||
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: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]> {
|
||||
const adapter = this.resolveSwitch(payload.provider_code)
|
||||
return adapter.send(payload)
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TaxSwitchSendPayloadDto[],
|
||||
): Promise<TaxSwitchBulkSendResultDto[]> {
|
||||
const groupedByProvider = new Map<string, TaxSwitchSendPayloadDto[]>()
|
||||
|
||||
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: TaxSwitchBulkSendResultDto[] = []
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { Injectable, NotFoundException } from '@nestjs/common'
|
||||
import { Prisma } from 'generated/prisma/client'
|
||||
import {
|
||||
TaxSendStatus,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from './dto/tax-switch.dto'
|
||||
import { SalesInvoiceTaxSwitchService } from './sales-invoice-tax-switch.service'
|
||||
|
||||
type TaxRow = {
|
||||
id: string
|
||||
retry_count: number
|
||||
}
|
||||
|
||||
type ItemTaxProviderRow = {
|
||||
provider_code: string | null
|
||||
tax_id: string | null
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceTaxService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly taxSwitchService: SalesInvoiceTaxSwitchService,
|
||||
) {}
|
||||
|
||||
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.findFirst({
|
||||
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,
|
||||
unit_type: true,
|
||||
good_id: true,
|
||||
service_id: true,
|
||||
payload: true,
|
||||
good_snapshot: true,
|
||||
},
|
||||
},
|
||||
pos: {
|
||||
select: {
|
||||
provider: {
|
||||
select: {
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!invoice) {
|
||||
throw new NotFoundException('Sales invoice was not found.')
|
||||
}
|
||||
|
||||
return {
|
||||
invoice_id: invoice.id,
|
||||
invoice_code: invoice.code,
|
||||
invoice_date: invoice.invoice_date ? invoice.invoice_date.toISOString() : null,
|
||||
total_amount: Number(invoice.total_amount),
|
||||
provider_code: invoice.pos.provider?.code || null,
|
||||
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),
|
||||
unit_type: item.unit_type,
|
||||
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}
|
||||
`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
ITaxSwitchAdapter,
|
||||
TaxSendStatus,
|
||||
TaxSwitchBulkSendResultDto,
|
||||
TaxSwitchGetResultDto,
|
||||
TaxSwitchSendItemResultDto,
|
||||
TaxSwitchSendPayloadDto,
|
||||
} from '../dto/tax-switch.dto'
|
||||
|
||||
@Injectable()
|
||||
export class NamaTaxSwitchAdapter implements ITaxSwitchAdapter {
|
||||
readonly code = 'NAMA'
|
||||
|
||||
async send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]> {
|
||||
return payload.items.map((item, index) => {
|
||||
const sentAt = new Date()
|
||||
const receivedAt = new Date(sentAt.getTime() + 50)
|
||||
const externalRequest = {
|
||||
invoiceCode: payload.invoice_code,
|
||||
itemId: item.invoice_item_id,
|
||||
quantity: item.quantity,
|
||||
unitPrice: item.unit_price,
|
||||
totalAmount: item.total_amount,
|
||||
}
|
||||
|
||||
const externalResponse = {
|
||||
status: 'ACCEPTED',
|
||||
trackingCode: `TAX-${payload.invoice_code}-${index + 1}`,
|
||||
}
|
||||
|
||||
return {
|
||||
invoice_item_id: item.invoice_item_id,
|
||||
status: TaxSendStatus.SENT,
|
||||
tax_id: externalResponse.trackingCode,
|
||||
request_payload: externalRequest,
|
||||
response_payload: externalResponse,
|
||||
sent_at: sentAt.toISOString(),
|
||||
received_at: receivedAt.toISOString(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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> {
|
||||
return {
|
||||
tax_id: taxId,
|
||||
status: TaxSendStatus.SENT,
|
||||
response_payload: {
|
||||
status: 'CONFIRMED',
|
||||
trackingCode: taxId,
|
||||
},
|
||||
received_at: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QUERY_CONSTANTS } from '@/common/queryConstants'
|
||||
import { BadRequestException } from '@nestjs/common'
|
||||
|
||||
type BusinessActivityAccountQuotaClient = {
|
||||
@@ -27,31 +28,13 @@ export const getBusinessActivityRemainingAccounts = async (
|
||||
): Promise<BusinessActivityRemainingAccounts> => {
|
||||
const { consumer_id, business_activity_id, referenceDate = new Date() } = params
|
||||
|
||||
const startOfDay = new Date(referenceDate)
|
||||
startOfDay.setHours(0, 0, 0, 0)
|
||||
|
||||
const relatedLicense = await prisma.licenseActivation.findFirst({
|
||||
where: {
|
||||
business_activity_id,
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
expires_at: {
|
||||
gte: startOfDay,
|
||||
},
|
||||
},
|
||||
{
|
||||
license_renews: {
|
||||
some: {
|
||||
expires_at: {
|
||||
gte: startOfDay,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
|
||||
},
|
||||
select: {
|
||||
license: {
|
||||
|
||||
Reference in New Issue
Block a user