feat: implement correction and original send functionality for Nama provider
- Added new DTOs for correction requests and responses in `nama-provider.dto.ts`. - Updated `nama-provider.adapter.ts` to include `originalSend` and `correctionSend` methods. - Enhanced `nama-provider.util.ts` with mapping functions for correction requests. - Created operational guidelines for agents in `AGENT.md`. - Updated Prisma migrations to support new invoice types and relationships. - Introduced new service and DTO for creating sales invoices in `sale-invoice-create.service.ts` and `sale-invoice-create.dto.ts`. - Added utility for handling Prisma errors in `prisma-error.util.ts`.
This commit is contained in:
@@ -143,8 +143,8 @@ export default {
|
||||
[TspProviderResponseStatus.QUEUED]: 'در صف ارسال',
|
||||
},
|
||||
TspProviderRequestType: {
|
||||
MAIN: 'اصلی',
|
||||
UPDATE: 'اصلاح',
|
||||
ORIGINAL: 'اصلی',
|
||||
CORRECTION: 'اصلاح',
|
||||
REVOKE: 'ابطال',
|
||||
REMOVE: 'حذف',
|
||||
},
|
||||
|
||||
@@ -5,8 +5,8 @@ export enum GoldKarat {
|
||||
}
|
||||
|
||||
export enum TspProviderRequestType {
|
||||
MAIN = 'MAIN',
|
||||
UPDATE = 'UPDATE',
|
||||
ORIGINAL = 'ORIGINAL',
|
||||
CORRECTION = 'CORRECTION',
|
||||
REVOKE = 'REVOKE',
|
||||
REMOVE = 'REMOVE',
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ export const infoSelect: ConsumerSelect = {
|
||||
first_name: true,
|
||||
last_name: true,
|
||||
mobile_number: true,
|
||||
national_code: true,
|
||||
partner: {
|
||||
select: {
|
||||
id: true,
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import type { SaleInvoiceType } from '@/common/interfaces/sale-invoice-payload'
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsBoolean,
|
||||
IsDate,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
import type { CustomerIndividual, CustomerLegal } from 'generated/prisma/client'
|
||||
import { CustomerType } from 'generated/prisma/enums'
|
||||
|
||||
export class SharedCreateSalesInvoiceItemDto {
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true })
|
||||
unit_price: number
|
||||
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true, default: 1 })
|
||||
quantity: number
|
||||
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true })
|
||||
total_amount: number
|
||||
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true })
|
||||
discount_amount: number
|
||||
|
||||
@IsString()
|
||||
@ApiProperty({ required: true })
|
||||
invoice_id: string
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
good_id?: string
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
service_id?: string
|
||||
|
||||
// @IsEnum(SalesInvoiceItemPricingModel)
|
||||
// @ApiProperty({ enum: Object.values(SalesInvoiceItemPricingModel) })
|
||||
// @IsOptional()
|
||||
// pricingModel: SalesInvoiceItemPricingModel
|
||||
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
@ApiProperty({ required: false, default: {} })
|
||||
payload: SaleInvoiceType
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false, default: '' })
|
||||
notes: string
|
||||
}
|
||||
|
||||
export class SharedCreateTerminalPayment {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
amount?: number
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
terminalId: string
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
stan: string
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
rrn: string
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
response_code?: string
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
customer_card_no?: string
|
||||
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
@ApiProperty({ required: true })
|
||||
transaction_date_time: Date
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
description?: string
|
||||
}
|
||||
|
||||
export class SharedCreateSalesInvoicePaymentsDto {
|
||||
@IsOptional()
|
||||
@ValidateNested()
|
||||
@Type(() => SharedCreateTerminalPayment)
|
||||
@ApiProperty({ required: false, type: () => SharedCreateTerminalPayment })
|
||||
terminals?: SharedCreateTerminalPayment
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
cash?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
set_off?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
card?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
bank?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
check?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
other?: number
|
||||
}
|
||||
|
||||
export class SharedCreateSalesInvoiceDto {
|
||||
// @TODO: totalAmount must calculated instead of get from api
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true, default: 0 })
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString(
|
||||
{ strict: true },
|
||||
{ message: 'invoice_date must be a valid ISO-8601 string' },
|
||||
)
|
||||
invoice_date: Date
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsObject()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SharedCreateSalesInvoicePaymentsDto)
|
||||
payments: SharedCreateSalesInvoicePaymentsDto
|
||||
|
||||
@ApiProperty()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
items: SharedCreateSalesInvoiceItemDto[]
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string
|
||||
|
||||
@ApiProperty({ required: false, default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
send_to_tsp?: boolean
|
||||
|
||||
@ApiProperty({ required: true, default: CustomerType.UNKNOWN })
|
||||
@IsEnum(CustomerType)
|
||||
customer_type: CustomerType
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
customer_id?: string
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
customer?: {
|
||||
customer_individual?: Omit<CustomerIndividual, 'business_activity_id' | 'customer_id'>
|
||||
customer_legal?: Omit<CustomerLegal, 'business_activity_id' | 'customer_id'>
|
||||
customer_unknown?: {
|
||||
first_name: string
|
||||
last_name: string
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
import { SalesInvoiceCreateInput } from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'
|
||||
import { Prisma } from 'generated/prisma/client'
|
||||
import {
|
||||
CustomerType,
|
||||
PaymentMethodType,
|
||||
TspProviderRequestType,
|
||||
} from 'generated/prisma/enums'
|
||||
import { SharedCreateSalesInvoiceDto } from './sale-invoice-create.dto'
|
||||
|
||||
interface TerminalPaymentInfo {
|
||||
terminalId: string
|
||||
stan: string
|
||||
rrn: string
|
||||
transactionDateTime: string | Date
|
||||
customerCardNO?: string
|
||||
description?: string
|
||||
amount?: number
|
||||
}
|
||||
|
||||
interface NormalizedPayment {
|
||||
method: PaymentMethodType
|
||||
amount: number
|
||||
}
|
||||
|
||||
interface CreateSharedSaleInvoiceInput {
|
||||
tx?: Prisma.TransactionClient
|
||||
data: SharedCreateSalesInvoiceDto
|
||||
businessId: string
|
||||
complexId: string
|
||||
posId: string
|
||||
consumerAccountId: string
|
||||
type: TspProviderRequestType
|
||||
main_invoice_id?: string
|
||||
ref_invoice_id?: string
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SharedSaleInvoiceCreateService {
|
||||
private readonly createInvoiceRetries = 3
|
||||
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async create(input: CreateSharedSaleInvoiceInput) {
|
||||
const {
|
||||
tx = this.prisma,
|
||||
data,
|
||||
businessId,
|
||||
complexId,
|
||||
posId,
|
||||
consumerAccountId,
|
||||
type,
|
||||
main_invoice_id,
|
||||
ref_invoice_id,
|
||||
} = input
|
||||
|
||||
const normalizedInvoiceDate = this.normalizeInvoiceDate(data.invoice_date)
|
||||
const { payments, terminalInfo } = this.buildPaymentsData(
|
||||
data.payments,
|
||||
data.total_amount,
|
||||
)
|
||||
|
||||
for (let attempt = 1; attempt <= this.createInvoiceRetries; attempt++) {
|
||||
try {
|
||||
return await tx.$transaction(async $tx => {
|
||||
const invoiceNumber = await this.getNextInvoiceNumber($tx, businessId)
|
||||
const customerId = await this.resolveCustomerId($tx, data, businessId)
|
||||
const goodsById = await this.getGoodsById($tx, data)
|
||||
const salesInvoiceData = this.buildSalesInvoiceData({
|
||||
data,
|
||||
normalizedInvoiceDate,
|
||||
invoiceNumber,
|
||||
consumerAccountId,
|
||||
businessId,
|
||||
complexId,
|
||||
posId,
|
||||
goodsById,
|
||||
customerId,
|
||||
type,
|
||||
main_invoice_id,
|
||||
ref_invoice_id,
|
||||
})
|
||||
|
||||
const salesInvoice = await $tx.salesInvoice.create({
|
||||
data: salesInvoiceData,
|
||||
})
|
||||
|
||||
await this.createPayments(
|
||||
$tx,
|
||||
salesInvoice.id,
|
||||
payments,
|
||||
terminalInfo,
|
||||
normalizedInvoiceDate,
|
||||
)
|
||||
|
||||
return salesInvoice
|
||||
})
|
||||
} catch (error) {
|
||||
if (
|
||||
this.isRetryableInvoiceConflict(error) &&
|
||||
attempt < this.createInvoiceRetries
|
||||
) {
|
||||
continue
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
throw new BadRequestException('ایجاد فاکتور با خطا مواجه شد.')
|
||||
}
|
||||
|
||||
private isRetryableInvoiceConflict(error: unknown) {
|
||||
if (!(error instanceof Prisma.PrismaClientKnownRequestError)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (error.code !== 'P2002') {
|
||||
return false
|
||||
}
|
||||
|
||||
const target = (error.meta?.target as string[]) || []
|
||||
return (
|
||||
target.includes('invoice_number') ||
|
||||
target.includes('sales_invoices_invoice_number_pos_id_key')
|
||||
)
|
||||
}
|
||||
|
||||
private normalizeInvoiceDate(invoiceDate: Date | string) {
|
||||
return new Date(invoiceDate).toISOString() as any
|
||||
}
|
||||
|
||||
private buildPaymentsData(
|
||||
paymentsData: SharedCreateSalesInvoiceDto['payments'],
|
||||
totalAmount: number,
|
||||
) {
|
||||
const paymentMethodMap: Record<string, PaymentMethodType> = {
|
||||
cash: PaymentMethodType.CASH,
|
||||
set_off: PaymentMethodType.SET_OFF,
|
||||
card: PaymentMethodType.CARD,
|
||||
payment_gateway: PaymentMethodType.PAYMENT_GATEWAY,
|
||||
bank: PaymentMethodType.BANK,
|
||||
check: PaymentMethodType.CHEQUE,
|
||||
other: PaymentMethodType.OTHER,
|
||||
terminal: PaymentMethodType.TERMINAL,
|
||||
}
|
||||
|
||||
const rawPayments = (paymentsData || {}) as Record<string, unknown>
|
||||
const terminalInfo = rawPayments.terminals as TerminalPaymentInfo | undefined
|
||||
|
||||
const payments: NormalizedPayment[] = Object.entries(rawPayments)
|
||||
.filter(([key]) => key !== 'terminals')
|
||||
.map(([key, value]) => ({
|
||||
method: paymentMethodMap[key.toLowerCase()],
|
||||
amount: typeof value === 'number' ? value : Number(value || 0),
|
||||
}))
|
||||
.filter(payment => payment.method && payment.amount > 0) as NormalizedPayment[]
|
||||
|
||||
const hasTerminalPayment = payments.some(
|
||||
payment => payment.method === PaymentMethodType.TERMINAL,
|
||||
)
|
||||
const nonTerminalTotal = payments
|
||||
.filter(payment => payment.method !== PaymentMethodType.TERMINAL)
|
||||
.reduce((sum, payment) => sum + payment.amount, 0)
|
||||
|
||||
if (!hasTerminalPayment && terminalInfo) {
|
||||
const terminalAmount =
|
||||
typeof terminalInfo.amount === 'number'
|
||||
? terminalInfo.amount
|
||||
: Math.max(0, Number(totalAmount) - nonTerminalTotal)
|
||||
|
||||
if (terminalAmount > 0) {
|
||||
payments.push({
|
||||
method: PaymentMethodType.TERMINAL,
|
||||
amount: terminalAmount,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
this.validatePayments(payments, totalAmount, terminalInfo)
|
||||
|
||||
return {
|
||||
payments,
|
||||
terminalInfo,
|
||||
}
|
||||
}
|
||||
|
||||
private validatePayments(
|
||||
payments: NormalizedPayment[],
|
||||
totalAmount: number,
|
||||
terminalInfo?: TerminalPaymentInfo,
|
||||
) {
|
||||
const totalPayments = payments.reduce((sum, payment) => sum + payment.amount, 0)
|
||||
const roundedTotalPayments = Number(totalPayments.toFixed(2))
|
||||
const roundedTotalAmount = Number(Number(totalAmount).toFixed(2))
|
||||
|
||||
if (roundedTotalPayments !== roundedTotalAmount) {
|
||||
throw new BadRequestException('مبلغ پرداختی باید برابر با مبلغ کل فاکتور باشد.')
|
||||
}
|
||||
|
||||
const terminalPayments = payments.filter(
|
||||
payment => payment.method === PaymentMethodType.TERMINAL,
|
||||
)
|
||||
|
||||
if (terminalPayments.length > 0 && !terminalInfo) {
|
||||
throw new BadRequestException('برای پرداخت ترمینال اطلاعات ترمینال الزامی است.')
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCustomerId(
|
||||
tx: Prisma.TransactionClient,
|
||||
data: SharedCreateSalesInvoiceDto,
|
||||
businessId: string,
|
||||
) {
|
||||
if (data.customer_id) {
|
||||
return data.customer_id
|
||||
}
|
||||
|
||||
if (
|
||||
data.customer_type === CustomerType.INDIVIDUAL &&
|
||||
data.customer?.customer_individual
|
||||
) {
|
||||
const { national_id, mobile_number, ...rest } = data.customer.customer_individual
|
||||
|
||||
const customerIndividual = await tx.customerIndividual.upsert({
|
||||
where: {
|
||||
business_activity_id_national_id: {
|
||||
business_activity_id: businessId,
|
||||
national_id: data.customer.customer_individual.national_id,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
...data.customer.customer_individual,
|
||||
customer: {
|
||||
create: {
|
||||
type: CustomerType.INDIVIDUAL,
|
||||
},
|
||||
},
|
||||
business_activity: {
|
||||
connect: {
|
||||
id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
update: { ...rest },
|
||||
select: {
|
||||
customer_id: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!customerIndividual) {
|
||||
throw new BadRequestException('متاسفانه مشکلی در اطلاعات مشتری وجود دارد.')
|
||||
}
|
||||
|
||||
return customerIndividual.customer_id
|
||||
}
|
||||
|
||||
if (data.customer_type === CustomerType.LEGAL && data.customer?.customer_legal) {
|
||||
const { registration_number, ...rest } = data.customer.customer_legal
|
||||
const customerLegal = await tx.customerLegal.upsert({
|
||||
where: {
|
||||
business_activity_id_economic_code: {
|
||||
business_activity_id: businessId,
|
||||
economic_code: data.customer.customer_legal.economic_code,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
...data.customer.customer_legal,
|
||||
customer: {
|
||||
create: {
|
||||
type: CustomerType.LEGAL,
|
||||
},
|
||||
},
|
||||
business_activity: {
|
||||
connect: {
|
||||
id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
update: {
|
||||
...rest,
|
||||
},
|
||||
select: {
|
||||
customer_id: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!customerLegal) {
|
||||
throw new BadRequestException('متاسفانه مشکلی در اطلاعات مشتری وجود دارد.')
|
||||
}
|
||||
|
||||
return customerLegal.customer_id
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private async getGoodsById(
|
||||
tx: Prisma.TransactionClient,
|
||||
data: SharedCreateSalesInvoiceDto,
|
||||
) {
|
||||
const itemGoodIds = data.items
|
||||
.map(item => item.good_id)
|
||||
.filter((goodId): goodId is string => Boolean(goodId))
|
||||
|
||||
const goods = itemGoodIds.length
|
||||
? await tx.good.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: itemGoodIds,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
sku: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
VAT: true,
|
||||
},
|
||||
},
|
||||
local_sku: true,
|
||||
barcode: true,
|
||||
pricing_model: true,
|
||||
measure_unit: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
base_sale_price: true,
|
||||
image_url: true,
|
||||
category: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: []
|
||||
|
||||
return new Map(goods.map(good => [good.id, good]))
|
||||
}
|
||||
|
||||
private buildSalesInvoiceData(params: {
|
||||
data: SharedCreateSalesInvoiceDto
|
||||
normalizedInvoiceDate: Date
|
||||
invoiceNumber: number
|
||||
consumerAccountId: string
|
||||
businessId: string
|
||||
complexId: string
|
||||
posId: string
|
||||
goodsById: Map<string, any>
|
||||
customerId: string | null
|
||||
type: TspProviderRequestType
|
||||
main_invoice_id?: string
|
||||
ref_invoice_id?: string
|
||||
}) {
|
||||
const {
|
||||
data,
|
||||
normalizedInvoiceDate,
|
||||
invoiceNumber,
|
||||
consumerAccountId,
|
||||
posId,
|
||||
goodsById,
|
||||
customerId,
|
||||
businessId,
|
||||
complexId,
|
||||
type,
|
||||
main_invoice_id,
|
||||
ref_invoice_id,
|
||||
} = params
|
||||
const { customer_id, customer_type, customer, payments, ...invoiceData } = data
|
||||
|
||||
if (
|
||||
type !== TspProviderRequestType.ORIGINAL &&
|
||||
!(main_invoice_id || ref_invoice_id)
|
||||
) {
|
||||
throw new BadRequestException('متاسفانه مشکلی در اطلاعات فاکتور وجود دارد.')
|
||||
}
|
||||
|
||||
const salesInvoiceData: SalesInvoiceCreateInput = {
|
||||
...invoiceData,
|
||||
invoice_date: normalizedInvoiceDate,
|
||||
invoice_number: invoiceNumber,
|
||||
total_amount: data.total_amount,
|
||||
code: this.generateInvoiceCode(businessId, complexId, posId, invoiceNumber),
|
||||
type,
|
||||
items: {
|
||||
createMany: {
|
||||
data: data.items.map(item => ({
|
||||
good_id: item.good_id!,
|
||||
quantity: item.quantity,
|
||||
unit_price: item.unit_price,
|
||||
total_amount: item.total_amount,
|
||||
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(
|
||||
JSON.stringify({
|
||||
good: goodsById.get(item.good_id) || null,
|
||||
}),
|
||||
)
|
||||
: undefined,
|
||||
})),
|
||||
},
|
||||
},
|
||||
unknown_customer: {},
|
||||
consumer_account: {
|
||||
connect: {
|
||||
id: consumerAccountId,
|
||||
},
|
||||
},
|
||||
pos: {
|
||||
connect: {
|
||||
id: posId,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if (customerId) {
|
||||
salesInvoiceData.customer = {
|
||||
connect: {
|
||||
id: customerId,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (type !== TspProviderRequestType.ORIGINAL) {
|
||||
salesInvoiceData.main_id = main_invoice_id
|
||||
salesInvoiceData.reference_invoice = {
|
||||
connect: {
|
||||
id: ref_invoice_id,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return salesInvoiceData
|
||||
}
|
||||
|
||||
private async getNextInvoiceNumber(tx: Prisma.TransactionClient, businessId: string) {
|
||||
const latestInvoice = await tx.salesInvoice.findFirst({
|
||||
where: {
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity_id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
invoice_number: 'desc',
|
||||
},
|
||||
select: {
|
||||
invoice_number: true,
|
||||
pos: {
|
||||
select: {
|
||||
complex: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
invoice_number_sequence: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const latestSequence =
|
||||
latestInvoice?.pos?.complex?.business_activity?.invoice_number_sequence.toNumber() ||
|
||||
0
|
||||
|
||||
return Math.max(latestInvoice?.invoice_number || 0, latestSequence) + 1
|
||||
}
|
||||
|
||||
private async createPayments(
|
||||
tx: Prisma.TransactionClient,
|
||||
invoiceId: string,
|
||||
payments: NormalizedPayment[],
|
||||
terminalInfo: TerminalPaymentInfo | undefined,
|
||||
paidAt: Date,
|
||||
) {
|
||||
for (const payment of payments) {
|
||||
if (payment.amount <= 0) {
|
||||
continue
|
||||
}
|
||||
const createdPayment = await tx.salesInvoicePayment.create({
|
||||
data: {
|
||||
invoice_id: invoiceId,
|
||||
amount: payment.amount,
|
||||
payment_method: payment.method,
|
||||
paid_at: paidAt,
|
||||
},
|
||||
})
|
||||
|
||||
if (payment.method === PaymentMethodType.TERMINAL && terminalInfo) {
|
||||
await tx.salesInvoicePaymentTerminalInfo.create({
|
||||
data: {
|
||||
payment_id: createdPayment.id,
|
||||
terminal_id: terminalInfo.terminalId,
|
||||
stan: terminalInfo.stan,
|
||||
rrn: terminalInfo.rrn,
|
||||
transaction_date_time: new Date(terminalInfo.transactionDateTime || ''),
|
||||
customer_card_no: terminalInfo.customerCardNO || null,
|
||||
description: terminalInfo.description || null,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private generateInvoiceCode(
|
||||
businessId: string,
|
||||
complexId: string,
|
||||
posId: string,
|
||||
invoiceNumber: number,
|
||||
) {
|
||||
return `${businessId.substring(businessId.length - 2, businessId.length)}-${complexId.substring(complexId.length - 2, complexId.length)}-${posId.substring(posId.length - 2, posId.length)}-${invoiceNumber.toString()}`
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ export default (consumer: any) => {
|
||||
status: translateEnumValue('ConsumerStatus', consumer.status),
|
||||
legal: legal ? { ...legal } : null,
|
||||
individual: individual
|
||||
? { ...individual, fullname: `${rest?.first_name} ${rest?.last_name}` }
|
||||
? { ...individual, fullname: `${individual?.first_name} ${individual?.last_name}` }
|
||||
: null,
|
||||
name: legal ? legal.name : `${individual?.first_name} ${individual?.last_name}`,
|
||||
business_counts,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { BadRequestException, ConflictException } from '@nestjs/common'
|
||||
import { Prisma } from 'generated/prisma/client'
|
||||
|
||||
type UniqueMessageMap = Record<string, string>
|
||||
|
||||
export class PrismaErrorUtil {
|
||||
static isKnownError(error: unknown): error is Prisma.PrismaClientKnownRequestError {
|
||||
return error instanceof Prisma.PrismaClientKnownRequestError
|
||||
}
|
||||
|
||||
static isCode(error: unknown, code: string): boolean {
|
||||
return this.isKnownError(error) && error.code === code
|
||||
}
|
||||
|
||||
static hasTarget(error: unknown, targetKey: string): boolean {
|
||||
if (!this.isKnownError(error)) {
|
||||
return false
|
||||
}
|
||||
const target = error.meta?.target as string[] | string | undefined
|
||||
if (Array.isArray(target)) {
|
||||
return target.includes(targetKey)
|
||||
}
|
||||
if (typeof target === 'string') {
|
||||
return target.includes(targetKey)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
static throwIfKnown(error: unknown, uniqueMap: UniqueMessageMap = {}) {
|
||||
if (!(error instanceof Prisma.PrismaClientKnownRequestError)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
if (error.code === 'P2002') {
|
||||
const target = (error.meta?.target as string[]) || []
|
||||
for (const key of Object.keys(uniqueMap)) {
|
||||
if (target.includes(key)) {
|
||||
throw new BadRequestException(uniqueMap[key])
|
||||
}
|
||||
}
|
||||
throw new ConflictException('رکورد تکراری است.')
|
||||
}
|
||||
|
||||
if (error.code === 'P2003') {
|
||||
throw new BadRequestException('ارتباط دادهای نامعتبر است.')
|
||||
}
|
||||
|
||||
if (error.code === 'P2025') {
|
||||
throw new BadRequestException('رکورد مورد نظر یافت نشد.')
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { randomBytes } from 'crypto'
|
||||
import { PrismaErrorUtil } from './prisma-error.util'
|
||||
|
||||
export function generateTrackingCode(prefix: string, suffixLength: number) {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
||||
@@ -13,23 +14,8 @@ export function generateTrackingCode(prefix: string, suffixLength: number) {
|
||||
}
|
||||
|
||||
export function isTrackingCodeUniqueViolation(error: unknown) {
|
||||
const prismaError = error as {
|
||||
code?: string
|
||||
meta?: { target?: string[] | string }
|
||||
}
|
||||
|
||||
if (prismaError?.code !== 'P2002') {
|
||||
if (!PrismaErrorUtil.isCode(error, 'P2002')) {
|
||||
return false
|
||||
}
|
||||
|
||||
const target = prismaError.meta?.target
|
||||
if (Array.isArray(target)) {
|
||||
return target.includes('tracking_code')
|
||||
}
|
||||
|
||||
if (typeof target === 'string') {
|
||||
return target.includes('tracking_code')
|
||||
}
|
||||
|
||||
return true
|
||||
return PrismaErrorUtil.hasTarget(error, 'tracking_code')
|
||||
}
|
||||
|
||||
@@ -650,6 +650,23 @@ export type EnumInvoiceTemplateTypeWithAggregatesFilter<$PrismaModel = never> =
|
||||
_max?: Prisma.NestedEnumInvoiceTemplateTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumTspProviderRequestTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
}
|
||||
|
||||
export type EnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type JsonFilter<$PrismaModel = never> =
|
||||
| Prisma.PatchUndefined<
|
||||
Prisma.Either<Required<JsonFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||
@@ -708,13 +725,6 @@ export type EnumTspProviderResponseStatusFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumTspProviderResponseStatusFilter<$PrismaModel> | $Enums.TspProviderResponseStatus
|
||||
}
|
||||
|
||||
export type EnumTspProviderRequestTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
}
|
||||
|
||||
export type EnumTspProviderResponseStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderResponseStatus | Prisma.EnumTspProviderResponseStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderResponseStatus[]
|
||||
@@ -725,16 +735,6 @@ export type EnumTspProviderResponseStatusWithAggregatesFilter<$PrismaModel = nev
|
||||
_max?: Prisma.NestedEnumTspProviderResponseStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumPaymentMethodTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.PaymentMethodType | Prisma.EnumPaymentMethodTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.PaymentMethodType[]
|
||||
@@ -1378,6 +1378,23 @@ export type NestedEnumInvoiceTemplateTypeWithAggregatesFilter<$PrismaModel = nev
|
||||
_max?: Prisma.NestedEnumInvoiceTemplateTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumTspProviderRequestTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
}
|
||||
|
||||
export type NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedJsonFilter<$PrismaModel = never> =
|
||||
| Prisma.PatchUndefined<
|
||||
Prisma.Either<Required<NestedJsonFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||
@@ -1409,13 +1426,6 @@ export type NestedEnumTspProviderResponseStatusFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumTspProviderResponseStatusFilter<$PrismaModel> | $Enums.TspProviderResponseStatus
|
||||
}
|
||||
|
||||
export type NestedEnumTspProviderRequestTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
}
|
||||
|
||||
export type NestedEnumTspProviderResponseStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderResponseStatus | Prisma.EnumTspProviderResponseStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderResponseStatus[]
|
||||
@@ -1426,16 +1436,6 @@ export type NestedEnumTspProviderResponseStatusWithAggregatesFilter<$PrismaModel
|
||||
_max?: Prisma.NestedEnumTspProviderResponseStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TspProviderRequestType | Prisma.EnumTspProviderRequestTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.TspProviderRequestType[]
|
||||
notIn?: $Enums.TspProviderRequestType[]
|
||||
not?: Prisma.NestedEnumTspProviderRequestTypeWithAggregatesFilter<$PrismaModel> | $Enums.TspProviderRequestType
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumTspProviderRequestTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumPaymentMethodTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.PaymentMethodType | Prisma.EnumPaymentMethodTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.PaymentMethodType[]
|
||||
|
||||
@@ -261,16 +261,15 @@ export const TspProviderResponseStatus = {
|
||||
SUCCESS: 'SUCCESS',
|
||||
FAILURE: 'FAILURE',
|
||||
NOT_SEND: 'NOT_SEND',
|
||||
QUEUED: 'QUEUED',
|
||||
REVOKED: 'REVOKED'
|
||||
QUEUED: 'QUEUED'
|
||||
} as const
|
||||
|
||||
export type TspProviderResponseStatus = (typeof TspProviderResponseStatus)[keyof typeof TspProviderResponseStatus]
|
||||
|
||||
|
||||
export const TspProviderRequestType = {
|
||||
MAIN: 'MAIN',
|
||||
UPDATE: 'UPDATE',
|
||||
ORIGINAL: 'ORIGINAL',
|
||||
CORRECTION: 'CORRECTION',
|
||||
REVOKE: 'REVOKE',
|
||||
RETURN: 'RETURN'
|
||||
} as const
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4031,10 +4031,14 @@ export const SalesInvoiceScalarFieldEnum = {
|
||||
total_amount: 'total_amount',
|
||||
invoice_number: 'invoice_number',
|
||||
invoice_date: 'invoice_date',
|
||||
type: 'type',
|
||||
tax_id: 'tax_id',
|
||||
notes: 'notes',
|
||||
unknown_customer: 'unknown_customer',
|
||||
created_at: 'created_at',
|
||||
updated_at: 'updated_at',
|
||||
main_id: 'main_id',
|
||||
ref_id: 'ref_id',
|
||||
customer_id: 'customer_id',
|
||||
consumer_account_id: 'consumer_account_id',
|
||||
pos_id: 'pos_id'
|
||||
@@ -4069,11 +4073,9 @@ export const SaleInvoiceTspAttemptsScalarFieldEnum = {
|
||||
id: 'id',
|
||||
attempt_no: 'attempt_no',
|
||||
status: 'status',
|
||||
tax_id: 'tax_id',
|
||||
type: 'type',
|
||||
request_payload: 'request_payload',
|
||||
response_payload: 'response_payload',
|
||||
error_message: 'error_message',
|
||||
message: 'message',
|
||||
sent_at: 'sent_at',
|
||||
received_at: 'received_at',
|
||||
created_at: 'created_at',
|
||||
@@ -4586,7 +4588,10 @@ export type GuildOrderByRelevanceFieldEnum = (typeof GuildOrderByRelevanceFieldE
|
||||
export const SalesInvoiceOrderByRelevanceFieldEnum = {
|
||||
id: 'id',
|
||||
code: 'code',
|
||||
tax_id: 'tax_id',
|
||||
notes: 'notes',
|
||||
main_id: 'main_id',
|
||||
ref_id: 'ref_id',
|
||||
customer_id: 'customer_id',
|
||||
consumer_account_id: 'consumer_account_id',
|
||||
pos_id: 'pos_id'
|
||||
@@ -4611,8 +4616,7 @@ export type SalesInvoiceItemOrderByRelevanceFieldEnum = (typeof SalesInvoiceItem
|
||||
|
||||
export const SaleInvoiceTspAttemptsOrderByRelevanceFieldEnum = {
|
||||
id: 'id',
|
||||
tax_id: 'tax_id',
|
||||
error_message: 'error_message',
|
||||
message: 'message',
|
||||
invoice_id: 'invoice_id'
|
||||
} as const
|
||||
|
||||
@@ -4870,16 +4874,16 @@ export type EnumInvoiceTemplateTypeFieldRefInput<$PrismaModel> = FieldRefInputTy
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TspProviderResponseStatus'
|
||||
* Reference to a field of type 'TspProviderRequestType'
|
||||
*/
|
||||
export type EnumTspProviderResponseStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TspProviderResponseStatus'>
|
||||
export type EnumTspProviderRequestTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TspProviderRequestType'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TspProviderRequestType'
|
||||
* Reference to a field of type 'TspProviderResponseStatus'
|
||||
*/
|
||||
export type EnumTspProviderRequestTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TspProviderRequestType'>
|
||||
export type EnumTspProviderResponseStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TspProviderResponseStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -622,10 +622,14 @@ export const SalesInvoiceScalarFieldEnum = {
|
||||
total_amount: 'total_amount',
|
||||
invoice_number: 'invoice_number',
|
||||
invoice_date: 'invoice_date',
|
||||
type: 'type',
|
||||
tax_id: 'tax_id',
|
||||
notes: 'notes',
|
||||
unknown_customer: 'unknown_customer',
|
||||
created_at: 'created_at',
|
||||
updated_at: 'updated_at',
|
||||
main_id: 'main_id',
|
||||
ref_id: 'ref_id',
|
||||
customer_id: 'customer_id',
|
||||
consumer_account_id: 'consumer_account_id',
|
||||
pos_id: 'pos_id'
|
||||
@@ -660,11 +664,9 @@ export const SaleInvoiceTspAttemptsScalarFieldEnum = {
|
||||
id: 'id',
|
||||
attempt_no: 'attempt_no',
|
||||
status: 'status',
|
||||
tax_id: 'tax_id',
|
||||
type: 'type',
|
||||
request_payload: 'request_payload',
|
||||
response_payload: 'response_payload',
|
||||
error_message: 'error_message',
|
||||
message: 'message',
|
||||
sent_at: 'sent_at',
|
||||
received_at: 'received_at',
|
||||
created_at: 'created_at',
|
||||
@@ -1177,7 +1179,10 @@ export type GuildOrderByRelevanceFieldEnum = (typeof GuildOrderByRelevanceFieldE
|
||||
export const SalesInvoiceOrderByRelevanceFieldEnum = {
|
||||
id: 'id',
|
||||
code: 'code',
|
||||
tax_id: 'tax_id',
|
||||
notes: 'notes',
|
||||
main_id: 'main_id',
|
||||
ref_id: 'ref_id',
|
||||
customer_id: 'customer_id',
|
||||
consumer_account_id: 'consumer_account_id',
|
||||
pos_id: 'pos_id'
|
||||
@@ -1202,8 +1207,7 @@ export type SalesInvoiceItemOrderByRelevanceFieldEnum = (typeof SalesInvoiceItem
|
||||
|
||||
export const SaleInvoiceTspAttemptsOrderByRelevanceFieldEnum = {
|
||||
id: 'id',
|
||||
tax_id: 'tax_id',
|
||||
error_message: 'error_message',
|
||||
message: 'message',
|
||||
invoice_id: 'invoice_id'
|
||||
} as const
|
||||
|
||||
|
||||
@@ -38,9 +38,7 @@ export type SaleInvoiceTspAttemptsMinAggregateOutputType = {
|
||||
id: string | null
|
||||
attempt_no: number | null
|
||||
status: $Enums.TspProviderResponseStatus | null
|
||||
tax_id: string | null
|
||||
type: $Enums.TspProviderRequestType | null
|
||||
error_message: string | null
|
||||
message: string | null
|
||||
sent_at: Date | null
|
||||
received_at: Date | null
|
||||
created_at: Date | null
|
||||
@@ -51,9 +49,7 @@ export type SaleInvoiceTspAttemptsMaxAggregateOutputType = {
|
||||
id: string | null
|
||||
attempt_no: number | null
|
||||
status: $Enums.TspProviderResponseStatus | null
|
||||
tax_id: string | null
|
||||
type: $Enums.TspProviderRequestType | null
|
||||
error_message: string | null
|
||||
message: string | null
|
||||
sent_at: Date | null
|
||||
received_at: Date | null
|
||||
created_at: Date | null
|
||||
@@ -64,11 +60,9 @@ export type SaleInvoiceTspAttemptsCountAggregateOutputType = {
|
||||
id: number
|
||||
attempt_no: number
|
||||
status: number
|
||||
tax_id: number
|
||||
type: number
|
||||
request_payload: number
|
||||
response_payload: number
|
||||
error_message: number
|
||||
message: number
|
||||
sent_at: number
|
||||
received_at: number
|
||||
created_at: number
|
||||
@@ -89,9 +83,7 @@ export type SaleInvoiceTspAttemptsMinAggregateInputType = {
|
||||
id?: true
|
||||
attempt_no?: true
|
||||
status?: true
|
||||
tax_id?: true
|
||||
type?: true
|
||||
error_message?: true
|
||||
message?: true
|
||||
sent_at?: true
|
||||
received_at?: true
|
||||
created_at?: true
|
||||
@@ -102,9 +94,7 @@ export type SaleInvoiceTspAttemptsMaxAggregateInputType = {
|
||||
id?: true
|
||||
attempt_no?: true
|
||||
status?: true
|
||||
tax_id?: true
|
||||
type?: true
|
||||
error_message?: true
|
||||
message?: true
|
||||
sent_at?: true
|
||||
received_at?: true
|
||||
created_at?: true
|
||||
@@ -115,11 +105,9 @@ export type SaleInvoiceTspAttemptsCountAggregateInputType = {
|
||||
id?: true
|
||||
attempt_no?: true
|
||||
status?: true
|
||||
tax_id?: true
|
||||
type?: true
|
||||
request_payload?: true
|
||||
response_payload?: true
|
||||
error_message?: true
|
||||
message?: true
|
||||
sent_at?: true
|
||||
received_at?: true
|
||||
created_at?: true
|
||||
@@ -217,11 +205,9 @@ export type SaleInvoiceTspAttemptsGroupByOutputType = {
|
||||
id: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload: runtime.JsonValue | null
|
||||
response_payload: runtime.JsonValue | null
|
||||
error_message: string | null
|
||||
message: string
|
||||
sent_at: Date | null
|
||||
received_at: Date | null
|
||||
created_at: Date
|
||||
@@ -255,11 +241,9 @@ export type SaleInvoiceTspAttemptsWhereInput = {
|
||||
id?: Prisma.StringFilter<"SaleInvoiceTspAttempts"> | string
|
||||
attempt_no?: Prisma.IntFilter<"SaleInvoiceTspAttempts"> | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.StringNullableFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
response_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
error_message?: Prisma.StringNullableFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
message?: Prisma.StringFilter<"SaleInvoiceTspAttempts"> | string
|
||||
sent_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
received_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
created_at?: Prisma.DateTimeFilter<"SaleInvoiceTspAttempts"> | Date | string
|
||||
@@ -271,11 +255,9 @@ export type SaleInvoiceTspAttemptsOrderByWithRelationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
attempt_no?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
tax_id?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
request_payload?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
response_payload?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
error_message?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
message?: Prisma.SortOrder
|
||||
sent_at?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
received_at?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
created_at?: Prisma.SortOrder
|
||||
@@ -286,7 +268,6 @@ export type SaleInvoiceTspAttemptsOrderByWithRelationInput = {
|
||||
|
||||
export type SaleInvoiceTspAttemptsWhereUniqueInput = Prisma.AtLeast<{
|
||||
id?: string
|
||||
tax_id?: string
|
||||
invoice_id?: string
|
||||
invoice_id_attempt_no?: Prisma.SaleInvoiceTspAttemptsInvoice_idAttempt_noCompoundUniqueInput
|
||||
AND?: Prisma.SaleInvoiceTspAttemptsWhereInput | Prisma.SaleInvoiceTspAttemptsWhereInput[]
|
||||
@@ -294,25 +275,22 @@ export type SaleInvoiceTspAttemptsWhereUniqueInput = Prisma.AtLeast<{
|
||||
NOT?: Prisma.SaleInvoiceTspAttemptsWhereInput | Prisma.SaleInvoiceTspAttemptsWhereInput[]
|
||||
attempt_no?: Prisma.IntFilter<"SaleInvoiceTspAttempts"> | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderResponseStatus
|
||||
type?: Prisma.EnumTspProviderRequestTypeFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
response_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
error_message?: Prisma.StringNullableFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
message?: Prisma.StringFilter<"SaleInvoiceTspAttempts"> | string
|
||||
sent_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
received_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
created_at?: Prisma.DateTimeFilter<"SaleInvoiceTspAttempts"> | Date | string
|
||||
invoice?: Prisma.XOR<Prisma.SalesInvoiceScalarRelationFilter, Prisma.SalesInvoiceWhereInput>
|
||||
}, "id" | "tax_id" | "invoice_id" | "invoice_id_attempt_no">
|
||||
}, "id" | "invoice_id" | "invoice_id_attempt_no">
|
||||
|
||||
export type SaleInvoiceTspAttemptsOrderByWithAggregationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
attempt_no?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
tax_id?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
request_payload?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
response_payload?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
error_message?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
message?: Prisma.SortOrder
|
||||
sent_at?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
received_at?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
created_at?: Prisma.SortOrder
|
||||
@@ -331,11 +309,9 @@ export type SaleInvoiceTspAttemptsScalarWhereWithAggregatesInput = {
|
||||
id?: Prisma.StringWithAggregatesFilter<"SaleInvoiceTspAttempts"> | string
|
||||
attempt_no?: Prisma.IntWithAggregatesFilter<"SaleInvoiceTspAttempts"> | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusWithAggregatesFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.StringNullableWithAggregatesFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeWithAggregatesFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.JsonNullableWithAggregatesFilter<"SaleInvoiceTspAttempts">
|
||||
response_payload?: Prisma.JsonNullableWithAggregatesFilter<"SaleInvoiceTspAttempts">
|
||||
error_message?: Prisma.StringNullableWithAggregatesFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
message?: Prisma.StringWithAggregatesFilter<"SaleInvoiceTspAttempts"> | string
|
||||
sent_at?: Prisma.DateTimeNullableWithAggregatesFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
received_at?: Prisma.DateTimeNullableWithAggregatesFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
created_at?: Prisma.DateTimeWithAggregatesFilter<"SaleInvoiceTspAttempts"> | Date | string
|
||||
@@ -346,11 +322,9 @@ export type SaleInvoiceTspAttemptsCreateInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -361,11 +335,9 @@ export type SaleInvoiceTspAttemptsUncheckedCreateInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -376,11 +348,9 @@ export type SaleInvoiceTspAttemptsUpdateInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -391,11 +361,9 @@ export type SaleInvoiceTspAttemptsUncheckedUpdateInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -406,11 +374,9 @@ export type SaleInvoiceTspAttemptsCreateManyInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -421,11 +387,9 @@ export type SaleInvoiceTspAttemptsUpdateManyMutationInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -435,11 +399,9 @@ export type SaleInvoiceTspAttemptsUncheckedUpdateManyInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -471,11 +433,9 @@ export type SaleInvoiceTspAttemptsCountOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
attempt_no?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
tax_id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
request_payload?: Prisma.SortOrder
|
||||
response_payload?: Prisma.SortOrder
|
||||
error_message?: Prisma.SortOrder
|
||||
message?: Prisma.SortOrder
|
||||
sent_at?: Prisma.SortOrder
|
||||
received_at?: Prisma.SortOrder
|
||||
created_at?: Prisma.SortOrder
|
||||
@@ -490,9 +450,7 @@ export type SaleInvoiceTspAttemptsMaxOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
attempt_no?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
tax_id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
error_message?: Prisma.SortOrder
|
||||
message?: Prisma.SortOrder
|
||||
sent_at?: Prisma.SortOrder
|
||||
received_at?: Prisma.SortOrder
|
||||
created_at?: Prisma.SortOrder
|
||||
@@ -503,9 +461,7 @@ export type SaleInvoiceTspAttemptsMinOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
attempt_no?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
tax_id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
error_message?: Prisma.SortOrder
|
||||
message?: Prisma.SortOrder
|
||||
sent_at?: Prisma.SortOrder
|
||||
received_at?: Prisma.SortOrder
|
||||
created_at?: Prisma.SortOrder
|
||||
@@ -562,19 +518,13 @@ export type EnumTspProviderResponseStatusFieldUpdateOperationsInput = {
|
||||
set?: $Enums.TspProviderResponseStatus
|
||||
}
|
||||
|
||||
export type EnumTspProviderRequestTypeFieldUpdateOperationsInput = {
|
||||
set?: $Enums.TspProviderRequestType
|
||||
}
|
||||
|
||||
export type SaleInvoiceTspAttemptsCreateWithoutInvoiceInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -584,11 +534,9 @@ export type SaleInvoiceTspAttemptsUncheckedCreateWithoutInvoiceInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -627,11 +575,9 @@ export type SaleInvoiceTspAttemptsScalarWhereInput = {
|
||||
id?: Prisma.StringFilter<"SaleInvoiceTspAttempts"> | string
|
||||
attempt_no?: Prisma.IntFilter<"SaleInvoiceTspAttempts"> | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.StringNullableFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFilter<"SaleInvoiceTspAttempts"> | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
response_payload?: Prisma.JsonNullableFilter<"SaleInvoiceTspAttempts">
|
||||
error_message?: Prisma.StringNullableFilter<"SaleInvoiceTspAttempts"> | string | null
|
||||
message?: Prisma.StringFilter<"SaleInvoiceTspAttempts"> | string
|
||||
sent_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
received_at?: Prisma.DateTimeNullableFilter<"SaleInvoiceTspAttempts"> | Date | string | null
|
||||
created_at?: Prisma.DateTimeFilter<"SaleInvoiceTspAttempts"> | Date | string
|
||||
@@ -642,11 +588,9 @@ export type SaleInvoiceTspAttemptsCreateManyInvoiceInput = {
|
||||
id?: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id?: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: string | null
|
||||
message: string
|
||||
sent_at?: Date | string | null
|
||||
received_at?: Date | string | null
|
||||
created_at?: Date | string
|
||||
@@ -656,11 +600,9 @@ export type SaleInvoiceTspAttemptsUpdateWithoutInvoiceInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -670,11 +612,9 @@ export type SaleInvoiceTspAttemptsUncheckedUpdateWithoutInvoiceInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -684,11 +624,9 @@ export type SaleInvoiceTspAttemptsUncheckedUpdateManyWithoutInvoiceInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
attempt_no?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
status?: Prisma.EnumTspProviderResponseStatusFieldUpdateOperationsInput | $Enums.TspProviderResponseStatus
|
||||
tax_id?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
type?: Prisma.EnumTspProviderRequestTypeFieldUpdateOperationsInput | $Enums.TspProviderRequestType
|
||||
request_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
response_payload?: Prisma.NullableJsonNullValueInput | runtime.InputJsonValue
|
||||
error_message?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
message?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
sent_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
received_at?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
|
||||
created_at?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -700,11 +638,9 @@ export type SaleInvoiceTspAttemptsSelect<ExtArgs extends runtime.Types.Extension
|
||||
id?: boolean
|
||||
attempt_no?: boolean
|
||||
status?: boolean
|
||||
tax_id?: boolean
|
||||
type?: boolean
|
||||
request_payload?: boolean
|
||||
response_payload?: boolean
|
||||
error_message?: boolean
|
||||
message?: boolean
|
||||
sent_at?: boolean
|
||||
received_at?: boolean
|
||||
created_at?: boolean
|
||||
@@ -718,18 +654,16 @@ export type SaleInvoiceTspAttemptsSelectScalar = {
|
||||
id?: boolean
|
||||
attempt_no?: boolean
|
||||
status?: boolean
|
||||
tax_id?: boolean
|
||||
type?: boolean
|
||||
request_payload?: boolean
|
||||
response_payload?: boolean
|
||||
error_message?: boolean
|
||||
message?: boolean
|
||||
sent_at?: boolean
|
||||
received_at?: boolean
|
||||
created_at?: boolean
|
||||
invoice_id?: boolean
|
||||
}
|
||||
|
||||
export type SaleInvoiceTspAttemptsOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "attempt_no" | "status" | "tax_id" | "type" | "request_payload" | "response_payload" | "error_message" | "sent_at" | "received_at" | "created_at" | "invoice_id", ExtArgs["result"]["saleInvoiceTspAttempts"]>
|
||||
export type SaleInvoiceTspAttemptsOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "attempt_no" | "status" | "request_payload" | "response_payload" | "message" | "sent_at" | "received_at" | "created_at" | "invoice_id", ExtArgs["result"]["saleInvoiceTspAttempts"]>
|
||||
export type SaleInvoiceTspAttemptsInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
invoice?: boolean | Prisma.SalesInvoiceDefaultArgs<ExtArgs>
|
||||
}
|
||||
@@ -743,11 +677,9 @@ export type $SaleInvoiceTspAttemptsPayload<ExtArgs extends runtime.Types.Extensi
|
||||
id: string
|
||||
attempt_no: number
|
||||
status: $Enums.TspProviderResponseStatus
|
||||
tax_id: string | null
|
||||
type: $Enums.TspProviderRequestType
|
||||
request_payload: runtime.JsonValue | null
|
||||
response_payload: runtime.JsonValue | null
|
||||
error_message: string | null
|
||||
message: string
|
||||
sent_at: Date | null
|
||||
received_at: Date | null
|
||||
created_at: Date
|
||||
@@ -1125,11 +1057,9 @@ export interface SaleInvoiceTspAttemptsFieldRefs {
|
||||
readonly id: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'String'>
|
||||
readonly attempt_no: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'Int'>
|
||||
readonly status: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'TspProviderResponseStatus'>
|
||||
readonly tax_id: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'String'>
|
||||
readonly type: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'TspProviderRequestType'>
|
||||
readonly request_payload: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'Json'>
|
||||
readonly response_payload: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'Json'>
|
||||
readonly error_message: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'String'>
|
||||
readonly message: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'String'>
|
||||
readonly sent_at: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'DateTime'>
|
||||
readonly received_at: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'DateTime'>
|
||||
readonly created_at: Prisma.FieldRef<"SaleInvoiceTspAttempts", 'DateTime'>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -181,7 +181,7 @@ export class SaleInvoicesService {
|
||||
}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string) {
|
||||
const tspProviderResult = await this.salesInvoiceTaxService.send(
|
||||
const tspProviderResult = await this.salesInvoiceTaxService.originalSend(
|
||||
consumer_id,
|
||||
invoice_id,
|
||||
)
|
||||
|
||||
@@ -9,22 +9,28 @@ import { CreatePartnerAccountDto, UpdateAccountDto } from './dto/account.dto'
|
||||
export class AccountsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async findAll(partner_id: string) {
|
||||
const accounts = await this.prisma.partnerAccount.findMany({
|
||||
where: { partner_id },
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
created_at: true,
|
||||
account: {
|
||||
select: {
|
||||
username: true,
|
||||
status: true,
|
||||
async findAll(partner_id: string, page = 1, perPage = 10) {
|
||||
const where = { partner_id }
|
||||
const [accounts, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.partnerAccount.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
created_at: true,
|
||||
account: {
|
||||
select: {
|
||||
username: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return ResponseMapper.list(accounts)
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.partnerAccount.count({ where }),
|
||||
])
|
||||
return ResponseMapper.paginate(accounts, { total, page, perPage })
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
|
||||
@@ -58,11 +58,17 @@ export class AccountsService {
|
||||
},
|
||||
})
|
||||
|
||||
async findAll(partner_id: string, consumer_id: string) {
|
||||
const accounts = await this.prisma.consumerAccount.findMany({
|
||||
where: this.defaultWhere(partner_id, consumer_id),
|
||||
select: this.default_select,
|
||||
})
|
||||
async findAll(partner_id: string, consumer_id: string, page = 1, perPage = 10) {
|
||||
const where = this.defaultWhere(partner_id, consumer_id)
|
||||
const [accounts, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.consumerAccount.findMany({
|
||||
where,
|
||||
select: this.default_select,
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.consumerAccount.count({ where }),
|
||||
])
|
||||
|
||||
const mappedAccounts = accounts.map(account => {
|
||||
const { account: mainAccount, role, ...rest } = account
|
||||
@@ -77,7 +83,7 @@ export class AccountsService {
|
||||
}
|
||||
})
|
||||
|
||||
return ResponseMapper.list(mappedAccounts)
|
||||
return ResponseMapper.paginate(mappedAccounts, { total, page, perPage })
|
||||
}
|
||||
|
||||
async findOne(partner_id: string, consumer_id: string, id: string) {
|
||||
|
||||
+8
-3
@@ -1,5 +1,5 @@
|
||||
import { PartnerInfo } from '@/common/decorators/partnerInfo.decorator'
|
||||
import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common'
|
||||
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common'
|
||||
import { ApiTags } from '@nestjs/swagger'
|
||||
import { BusinessActivitiesService } from './business-activities.service'
|
||||
import {
|
||||
@@ -38,7 +38,7 @@ export class BusinessActivitiesController {
|
||||
return this.businessActivitiesService.create(partnerId, consumerId, data)
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@Patch(':id')
|
||||
async update(
|
||||
@PartnerInfo('id') partnerId: string,
|
||||
@Param('consumerId') consumerId: string,
|
||||
@@ -54,4 +54,9 @@ export class BusinessActivitiesController {
|
||||
// }
|
||||
}
|
||||
|
||||
import type { BusinessActivitiesServiceCreateResponseDto, BusinessActivitiesServiceFindAllResponseDto, BusinessActivitiesServiceFindOneResponseDto, BusinessActivitiesServiceUpdateResponseDto } from './dto/business-activities-response.dto'
|
||||
import type {
|
||||
BusinessActivitiesServiceCreateResponseDto,
|
||||
BusinessActivitiesServiceFindAllResponseDto,
|
||||
BusinessActivitiesServiceFindOneResponseDto,
|
||||
BusinessActivitiesServiceUpdateResponseDto,
|
||||
} from './dto/business-activities-response.dto'
|
||||
|
||||
@@ -20,6 +20,9 @@ export class BusinessActivitiesService {
|
||||
name: true,
|
||||
economic_code: true,
|
||||
created_at: true,
|
||||
fiscal_id: true,
|
||||
invoice_number_sequence: true,
|
||||
partner_token: true,
|
||||
guild: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -81,13 +84,20 @@ export class BusinessActivitiesService {
|
||||
}
|
||||
}
|
||||
|
||||
async findAll(partner_id: string, consumer_id: string) {
|
||||
const businessActivities = await this.prisma.businessActivity.findMany({
|
||||
where: this.defaultWhere(partner_id, consumer_id),
|
||||
select: this.defaultSelect,
|
||||
})
|
||||
return ResponseMapper.list(
|
||||
async findAll(partner_id: string, consumer_id: string, page = 1, perPage = 10) {
|
||||
const where = this.defaultWhere(partner_id, consumer_id)
|
||||
const [businessActivities, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.businessActivity.findMany({
|
||||
where,
|
||||
select: this.defaultSelect,
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.businessActivity.count({ where }),
|
||||
])
|
||||
return ResponseMapper.paginate(
|
||||
businessActivities.map(this.prepareBusinessActivityResponse),
|
||||
{ total, page, perPage },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -42,18 +42,30 @@ export class BusinessActivityComplexesService {
|
||||
},
|
||||
})
|
||||
|
||||
async findAll(partner_id: string, consumer_id: string, business_activity_id: string) {
|
||||
const complexes = await this.prisma.complex.findMany({
|
||||
where: this.defaultWhere(partner_id, consumer_id, business_activity_id),
|
||||
select: {
|
||||
...this.defaultSelect,
|
||||
_count: {
|
||||
select: {
|
||||
pos_list: true,
|
||||
async findAll(
|
||||
partner_id: string,
|
||||
consumer_id: string,
|
||||
business_activity_id: string,
|
||||
page = 1,
|
||||
perPage = 10,
|
||||
) {
|
||||
const where = this.defaultWhere(partner_id, consumer_id, business_activity_id)
|
||||
const [complexes, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.complex.findMany({
|
||||
where,
|
||||
select: {
|
||||
...this.defaultSelect,
|
||||
_count: {
|
||||
select: {
|
||||
pos_list: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.complex.count({ where }),
|
||||
])
|
||||
|
||||
const mappedComplexes = complexes.map(complex => {
|
||||
const { _count, ...rest } = complex
|
||||
@@ -62,7 +74,7 @@ export class BusinessActivityComplexesService {
|
||||
pos_count: _count.pos_list,
|
||||
}
|
||||
})
|
||||
return ResponseMapper.list(mappedComplexes)
|
||||
return ResponseMapper.paginate(mappedComplexes, { total, page, perPage })
|
||||
}
|
||||
|
||||
async findOne(
|
||||
|
||||
+114
-90
@@ -1,5 +1,6 @@
|
||||
import { QUERY_CONSTANTS } from '@/common/queryConstants'
|
||||
import { consumerRelatedPartner } from '@/common/queryConstants/consumer'
|
||||
import { PrismaErrorUtil } from '@/common/utils/prisma-error.util'
|
||||
import { PasswordUtil } from '@/common/utils/password.util'
|
||||
import {
|
||||
AccountStatus,
|
||||
@@ -97,17 +98,32 @@ export class ComplexPosesService {
|
||||
}
|
||||
}
|
||||
|
||||
async findAll(partner_id: string, business_activity_id: string, complex_id: string) {
|
||||
const poses = await this.prisma.pos.findMany({
|
||||
where: {
|
||||
...this.defaultWhere(partner_id, complex_id, business_activity_id),
|
||||
},
|
||||
select: this.defaultSelect,
|
||||
})
|
||||
async findAll(
|
||||
partner_id: string,
|
||||
business_activity_id: string,
|
||||
complex_id: string,
|
||||
page = 1,
|
||||
perPage = 10,
|
||||
) {
|
||||
const [poses, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.pos.findMany({
|
||||
where: {
|
||||
...this.defaultWhere(partner_id, complex_id, business_activity_id),
|
||||
},
|
||||
select: this.defaultSelect,
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.pos.count({
|
||||
where: {
|
||||
...this.defaultWhere(partner_id, complex_id, business_activity_id),
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
const mappedPoses = poses.map(this.mapPos)
|
||||
|
||||
return ResponseMapper.list(mappedPoses)
|
||||
return ResponseMapper.paginate(mappedPoses, { total, page, perPage })
|
||||
}
|
||||
|
||||
async findOne(
|
||||
@@ -129,94 +145,102 @@ export class ComplexPosesService {
|
||||
complex_id: string,
|
||||
data: CreatePosDto,
|
||||
) {
|
||||
const pos = this.prisma.$transaction(async tx => {
|
||||
const activeAccountAllocation = await tx.licenseAccountAllocation.findFirst({
|
||||
where: {
|
||||
account_id: null,
|
||||
license_activation: {
|
||||
business_activity_id,
|
||||
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
|
||||
license: {
|
||||
charge_transaction: {
|
||||
partner_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
license_activation: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
consumer_id: true,
|
||||
let pos
|
||||
try {
|
||||
pos = await this.prisma.$transaction(async tx => {
|
||||
const activeAccountAllocation = await tx.licenseAccountAllocation.findFirst({
|
||||
where: {
|
||||
account_id: null,
|
||||
license_activation: {
|
||||
business_activity_id,
|
||||
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
|
||||
license: {
|
||||
charge_transaction: {
|
||||
partner_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
license_activation: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
consumer_id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!activeAccountAllocation) {
|
||||
throw new BadRequestException(
|
||||
`محدودیت تعریف تعداد کاربران این فعالیت تجاری به پایان رسیده است.`,
|
||||
)
|
||||
}
|
||||
|
||||
const { device_id, provider_id, username, password, ...rest } = data
|
||||
|
||||
return await tx.pos.create({
|
||||
data: {
|
||||
...rest,
|
||||
status: POSStatus.ACTIVE,
|
||||
|
||||
account: {
|
||||
create: {
|
||||
role: ConsumerRole.OPERATOR,
|
||||
|
||||
consumer: {
|
||||
connect: {
|
||||
id: activeAccountAllocation.license_activation!.business_activity
|
||||
.consumer_id,
|
||||
},
|
||||
},
|
||||
account_allocation: {
|
||||
connect: {
|
||||
id: activeAccountAllocation.id,
|
||||
},
|
||||
},
|
||||
account: {
|
||||
create: {
|
||||
username,
|
||||
password: await PasswordUtil.hash(password),
|
||||
type: AccountType.CONSUMER,
|
||||
status: AccountStatus.ACTIVE,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
complex: {
|
||||
connect: {
|
||||
id: complex_id,
|
||||
},
|
||||
},
|
||||
device: device_id
|
||||
? {
|
||||
connect: {
|
||||
id: device_id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
provider: provider_id
|
||||
? {
|
||||
connect: {
|
||||
id: provider_id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (!activeAccountAllocation) {
|
||||
throw new BadRequestException(
|
||||
`محدودیت تعریف تعداد کاربران این فعالیت تجاری به پایان رسیده است.`,
|
||||
)
|
||||
}
|
||||
|
||||
const { device_id, provider_id, username, password, ...rest } = data
|
||||
|
||||
return await tx.pos.create({
|
||||
data: {
|
||||
...rest,
|
||||
status: POSStatus.ACTIVE,
|
||||
|
||||
account: {
|
||||
create: {
|
||||
role: ConsumerRole.OPERATOR,
|
||||
|
||||
consumer: {
|
||||
connect: {
|
||||
id: activeAccountAllocation.license_activation!.business_activity
|
||||
.consumer_id,
|
||||
},
|
||||
},
|
||||
account_allocation: {
|
||||
connect: {
|
||||
id: activeAccountAllocation.id,
|
||||
},
|
||||
},
|
||||
account: {
|
||||
create: {
|
||||
username,
|
||||
password: await PasswordUtil.hash(password),
|
||||
type: AccountType.CONSUMER,
|
||||
status: AccountStatus.ACTIVE,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
complex: {
|
||||
connect: {
|
||||
id: complex_id,
|
||||
},
|
||||
},
|
||||
device: device_id
|
||||
? {
|
||||
connect: {
|
||||
id: device_id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
provider: provider_id
|
||||
? {
|
||||
connect: {
|
||||
id: provider_id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
} catch (error) {
|
||||
PrismaErrorUtil.throwIfKnown(error, {
|
||||
username: 'نام کاربری تکراری است',
|
||||
accounts_username_key: 'نام کاربری تکراری است',
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return ResponseMapper.create(pos)
|
||||
}
|
||||
|
||||
@@ -16,42 +16,48 @@ export class LicensesService {
|
||||
).toISOString()
|
||||
}
|
||||
|
||||
async findAll(partner_id: string, consumer_id: string) {
|
||||
const licenses = await this.prisma.licenseActivation.findMany({
|
||||
where: {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
},
|
||||
license: {
|
||||
charge_transaction: {
|
||||
partner_id,
|
||||
},
|
||||
async findAll(partner_id: string, consumer_id: string, page = 1, perPage = 10) {
|
||||
const where = {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
},
|
||||
license: {
|
||||
charge_transaction: {
|
||||
partner_id,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
starts_at: true,
|
||||
expires_at: true,
|
||||
created_at: true,
|
||||
license: {
|
||||
select: {
|
||||
id: true,
|
||||
charge_transaction: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
}
|
||||
const [licenses, total] = await this.prisma.$transaction(async tx => [
|
||||
await tx.licenseActivation.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
starts_at: true,
|
||||
expires_at: true,
|
||||
created_at: true,
|
||||
license: {
|
||||
select: {
|
||||
id: true,
|
||||
charge_transaction: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
await tx.licenseActivation.count({ where }),
|
||||
])
|
||||
|
||||
return ResponseMapper.list(licenses)
|
||||
return ResponseMapper.paginate(licenses, { total, page, perPage })
|
||||
}
|
||||
|
||||
// async create(consumerId: string, data: CreateLicenseDto) {
|
||||
|
||||
@@ -66,16 +66,23 @@ export const getPartnerFirstRemainingLicense = async (
|
||||
id: true,
|
||||
charge_transaction_id: true,
|
||||
accounts_limit: true,
|
||||
parent: {
|
||||
charge_transaction: {
|
||||
select: {
|
||||
name: true,
|
||||
partner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!license) {
|
||||
throw new BadRequestException(`لایسنس فعالی برای ${license.parent.name} وجود ندارد.`)
|
||||
throw new BadRequestException(
|
||||
`لایسنس فعالی برای ${license.charge_transaction.parent.name} وجود ندارد.`,
|
||||
)
|
||||
}
|
||||
|
||||
return license
|
||||
|
||||
@@ -1,163 +1,6 @@
|
||||
import { ApiProperty, PartialType } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsBoolean,
|
||||
IsDate,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
import type { CustomerIndividual, CustomerLegal } from 'generated/prisma/client'
|
||||
import { CustomerType } from 'generated/prisma/enums'
|
||||
import { CreateSalesInvoiceItemDto } from '../sales-invoice-items/dto/create-sales-invoice-item.dto'
|
||||
import { SharedCreateSalesInvoiceDto } from '@/common/services/saleInvoices/sale-invoice-create.dto'
|
||||
import { PartialType } from '@nestjs/swagger'
|
||||
|
||||
export class CreateTerminalPayment {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
amount?: number
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
terminalId: string
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
stan: string
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({ required: true })
|
||||
rrn: string
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
response_code?: string
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiProperty({ required: true })
|
||||
customer_card_no?: string
|
||||
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
@ApiProperty({ required: true })
|
||||
transaction_date_time: Date
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
description?: string
|
||||
}
|
||||
|
||||
export class CreateSalesInvoicePaymentsDto {
|
||||
@IsOptional()
|
||||
@ValidateNested()
|
||||
@Type(() => CreateTerminalPayment)
|
||||
@ApiProperty({ required: false, type: () => CreateTerminalPayment })
|
||||
terminals?: CreateTerminalPayment
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
cash?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
set_off?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
card?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
bank?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
check?: number
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@ApiProperty({ required: false, default: 0 })
|
||||
other?: number
|
||||
}
|
||||
|
||||
export class CreateSalesInvoiceDto {
|
||||
// @TODO: totalAmount must calculated instead of get from api
|
||||
@IsNumber()
|
||||
@ApiProperty({ required: true, default: 0 })
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsDateString(
|
||||
{ strict: true },
|
||||
{ message: 'invoice_date must be a valid ISO-8601 string' },
|
||||
)
|
||||
invoice_date: Date
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsObject()
|
||||
@ValidateNested()
|
||||
@Type(() => CreateSalesInvoicePaymentsDto)
|
||||
payments: CreateSalesInvoicePaymentsDto
|
||||
|
||||
@ApiProperty()
|
||||
@ArrayMinSize(1)
|
||||
items: CreateSalesInvoiceItemDto[]
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string
|
||||
|
||||
@ApiProperty({ required: false, default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
send_to_tsp?: boolean
|
||||
|
||||
@ApiProperty({ required: true, default: CustomerType.UNKNOWN })
|
||||
@IsEnum(CustomerType)
|
||||
customer_type: CustomerType
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiProperty({ required: false })
|
||||
customer_id?: string
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
customer?: {
|
||||
customer_individual?: Omit<CustomerIndividual, 'business_activity_id' | 'customer_id'>
|
||||
customer_legal?: Omit<CustomerLegal, 'business_activity_id' | 'customer_id'>
|
||||
customer_unknown?: {
|
||||
first_name: string
|
||||
last_name: string
|
||||
}
|
||||
}
|
||||
}
|
||||
export class CreateSalesInvoiceDto extends SharedCreateSalesInvoiceDto {}
|
||||
|
||||
export class UpdateSalesInvoiceDto extends PartialType(CreateSalesInvoiceDto) {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { SaleInvoiceTspModule } from '@/modules/tspProviders/sales-invoice-tsp.module'
|
||||
import { Module } from '@nestjs/common'
|
||||
import { SalesInvoicesController } from './sales-invoices.controller'
|
||||
@@ -6,6 +7,6 @@ import { SalesInvoicesService } from './sales-invoices.service'
|
||||
@Module({
|
||||
imports: [SaleInvoiceTspModule],
|
||||
controllers: [SalesInvoicesController],
|
||||
providers: [SalesInvoicesService],
|
||||
providers: [SalesInvoicesService, SharedSaleInvoiceCreateService],
|
||||
})
|
||||
export class PosSalesInvoicesModule {}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { IPosPayload } from '@/common/models/posPayload.model'
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { translateEnumValue } from '@/common/utils'
|
||||
import { SalesInvoiceCreateInput } from '@/generated/prisma/models'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
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,
|
||||
PaymentMethodType,
|
||||
TspProviderRequestType,
|
||||
TspProviderResponseStatus,
|
||||
} from 'generated/prisma/enums'
|
||||
@@ -17,46 +14,12 @@ import { SalesInvoiceTspService } from '../../tspProviders/sales-invoice-tsp.ser
|
||||
import { CreateSalesInvoiceDto } from './dto/create-sales-invoice.dto'
|
||||
import { SalesInvoicesFilterDto } from './dto/sales-invoices-filter.dto'
|
||||
|
||||
// Define type guard for CustomerIndividual
|
||||
function isCustomerIndividual(customer: any): customer is CustomerIndividual {
|
||||
return (
|
||||
customer &&
|
||||
typeof customer.first_name === 'string' &&
|
||||
typeof customer.last_name === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
// Define type guard for CustomerLegal
|
||||
function isCustomerLegal(customer: any): customer is CustomerLegal {
|
||||
return (
|
||||
customer &&
|
||||
typeof customer.company_name === 'string' &&
|
||||
typeof customer.registration_number === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
interface TerminalPaymentInfo {
|
||||
terminalId: string
|
||||
stan: string
|
||||
rrn: string
|
||||
transactionDateTime: string | Date
|
||||
customerCardNO?: string
|
||||
description?: string
|
||||
amount?: number
|
||||
}
|
||||
|
||||
interface NormalizedPayment {
|
||||
method: PaymentMethodType
|
||||
amount: number
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoicesService {
|
||||
private readonly createInvoiceRetries = 3
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private salesInvoiceTaxService: SalesInvoiceTspService,
|
||||
private sharedSaleInvoiceCreateService: SharedSaleInvoiceCreateService,
|
||||
) {}
|
||||
|
||||
async findAll(posInfo: IPosPayload, query: SalesInvoicesFilterDto = {}) {
|
||||
@@ -145,6 +108,7 @@ export class SalesInvoicesService {
|
||||
notes: true,
|
||||
total_amount: true,
|
||||
unknown_customer: true,
|
||||
tax_id: true,
|
||||
customer: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -242,8 +206,7 @@ export class SalesInvoicesService {
|
||||
id: true,
|
||||
attempt_no: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
error_message: true,
|
||||
message: true,
|
||||
sent_at: true,
|
||||
received_at: true,
|
||||
created_at: true,
|
||||
@@ -267,71 +230,27 @@ export class SalesInvoicesService {
|
||||
}
|
||||
|
||||
async create(data: CreateSalesInvoiceDto, posInfo: IPosPayload) {
|
||||
const { business_id, pos_id, consumer_account_id, complex_id } = posInfo
|
||||
const normalizedInvoiceDate = this.normalizeInvoiceDate(data.invoice_date)
|
||||
const { payments, terminalInfo } = this.buildPaymentsData(
|
||||
data.payments,
|
||||
data.total_amount,
|
||||
)
|
||||
const salesInvoice = await this.sharedSaleInvoiceCreateService.create({
|
||||
data,
|
||||
businessId: posInfo.business_id,
|
||||
complexId: posInfo.complex_id,
|
||||
posId: posInfo.pos_id,
|
||||
consumerAccountId: posInfo.consumer_account_id,
|
||||
type: TspProviderRequestType.ORIGINAL,
|
||||
})
|
||||
|
||||
for (let attempt = 1; attempt <= this.createInvoiceRetries; attempt++) {
|
||||
try {
|
||||
const salesInvoice = await this.prisma.$transaction(async $tx => {
|
||||
const invoiceNumber = await this.getNextInvoiceNumber($tx, business_id)
|
||||
const newCustomerId = await this.resolveCustomerId($tx, data, business_id)
|
||||
const goodsById = await this.getGoodsById($tx, data)
|
||||
const salesInvoiceData = this.buildSalesInvoiceData({
|
||||
data,
|
||||
normalizedInvoiceDate,
|
||||
invoiceNumber,
|
||||
consumer_account_id,
|
||||
businessId: business_id,
|
||||
complexId: complex_id,
|
||||
pos_id,
|
||||
goodsById,
|
||||
customerId: newCustomerId,
|
||||
})
|
||||
|
||||
const salesInvoice = await $tx.salesInvoice.create({
|
||||
data: salesInvoiceData,
|
||||
})
|
||||
|
||||
await this.createPayments(
|
||||
$tx,
|
||||
salesInvoice.id,
|
||||
payments,
|
||||
terminalInfo,
|
||||
normalizedInvoiceDate,
|
||||
)
|
||||
|
||||
if (data.send_to_tsp) {
|
||||
await this.salesInvoiceTaxService.send(salesInvoice.id, pos_id)
|
||||
}
|
||||
|
||||
return salesInvoice
|
||||
})
|
||||
|
||||
return ResponseMapper.create(salesInvoice)
|
||||
} catch (error) {
|
||||
if (
|
||||
this.isRetryableInvoiceConflict(error) &&
|
||||
attempt < this.createInvoiceRetries
|
||||
) {
|
||||
continue
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (data.send_to_tsp) {
|
||||
await this.salesInvoiceTaxService.originalSend(salesInvoice.id, posInfo.pos_id)
|
||||
}
|
||||
|
||||
throw new BadRequestException('ایجاد فاکتور با خطا مواجه شد.')
|
||||
return ResponseMapper.create(salesInvoice)
|
||||
}
|
||||
|
||||
async send(invoiceId: string, posInfo: IPosPayload) {
|
||||
const consumer_id = await this.checkAccessToInvoice(
|
||||
posInfo.consumer_account_id,
|
||||
const invoice = await this.salesInvoiceTaxService.originalSend(
|
||||
posInfo.pos_id,
|
||||
invoiceId,
|
||||
)
|
||||
const invoice = await this.salesInvoiceTaxService.send(consumer_id, invoiceId)
|
||||
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
@@ -339,7 +258,15 @@ export class SalesInvoicesService {
|
||||
async revoke(invoiceId: string, posInfo: IPosPayload) {
|
||||
await this.checkAccessToInvoice(posInfo.consumer_account_id, posInfo.pos_id)
|
||||
|
||||
const invoice = await this.salesInvoiceTaxService.revoke(posInfo.pos_id, invoiceId)
|
||||
const { consumer_account_id, pos_id, business_id, complex_id } = posInfo
|
||||
|
||||
const invoice = await this.salesInvoiceTaxService.revoke(
|
||||
consumer_account_id,
|
||||
pos_id,
|
||||
complex_id,
|
||||
business_id,
|
||||
invoiceId,
|
||||
)
|
||||
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
@@ -350,38 +277,10 @@ export class SalesInvoicesService {
|
||||
return ResponseMapper.single(invoice)
|
||||
}
|
||||
|
||||
// async sendBulk(invoiceIds: string[], posInfo: IPosPayload) {
|
||||
// if (!invoiceIds.length) {
|
||||
// throw new BadRequestException('invoice_ids is required and cannot be empty.')
|
||||
// }
|
||||
|
||||
// await this.salesInvoiceTaxService.sendBulk(invoiceIds, posInfo.pos_id)
|
||||
|
||||
// return ResponseMapper.single({
|
||||
// invoice_ids: invoiceIds,
|
||||
// sent_to_tax: true,
|
||||
// })
|
||||
// }
|
||||
|
||||
private isRetryableInvoiceConflict(error: unknown) {
|
||||
if (!(error instanceof Prisma.PrismaClientKnownRequestError)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (error.code !== 'P2002') {
|
||||
return false
|
||||
}
|
||||
|
||||
const target = (error.meta?.target as string[]) || []
|
||||
return (
|
||||
target.includes('invoice_number') ||
|
||||
target.includes('sales_invoices_invoice_number_pos_id_key')
|
||||
)
|
||||
}
|
||||
|
||||
private buildFindAllWhere(posInfo: IPosPayload, query: SalesInvoicesFilterDto) {
|
||||
const where: Prisma.SalesInvoiceWhereInput = {
|
||||
pos: {
|
||||
id: posInfo.pos_id,
|
||||
complex: {
|
||||
business_activity_id: posInfo.business_id,
|
||||
},
|
||||
@@ -530,393 +429,6 @@ export class SalesInvoicesService {
|
||||
return where
|
||||
}
|
||||
|
||||
private normalizeInvoiceDate(invoiceDate: Date | string) {
|
||||
return new Date(invoiceDate).toISOString() as any
|
||||
}
|
||||
|
||||
private buildPaymentsData(
|
||||
paymentsData: CreateSalesInvoiceDto['payments'],
|
||||
totalAmount: number,
|
||||
) {
|
||||
const paymentMethodMap: Record<string, PaymentMethodType> = {
|
||||
cash: PaymentMethodType.CASH,
|
||||
set_off: PaymentMethodType.SET_OFF,
|
||||
card: PaymentMethodType.CARD,
|
||||
payment_gateway: PaymentMethodType.PAYMENT_GATEWAY,
|
||||
bank: PaymentMethodType.BANK,
|
||||
check: PaymentMethodType.CHEQUE,
|
||||
other: PaymentMethodType.OTHER,
|
||||
terminal: PaymentMethodType.TERMINAL,
|
||||
}
|
||||
|
||||
const rawPayments = (paymentsData || {}) as Record<string, unknown>
|
||||
const terminalInfo = rawPayments.terminals as TerminalPaymentInfo | undefined
|
||||
|
||||
const payments: NormalizedPayment[] = Object.entries(rawPayments)
|
||||
.filter(([key]) => key !== 'terminals')
|
||||
.map(([key, value]) => ({
|
||||
method: paymentMethodMap[key.toLowerCase()],
|
||||
amount: typeof value === 'number' ? value : Number(value || 0),
|
||||
}))
|
||||
.filter(payment => payment.method && payment.amount > 0) as NormalizedPayment[]
|
||||
|
||||
const hasTerminalPayment = payments.some(
|
||||
payment => payment.method === PaymentMethodType.TERMINAL,
|
||||
)
|
||||
const nonTerminalTotal = payments
|
||||
.filter(payment => payment.method !== PaymentMethodType.TERMINAL)
|
||||
.reduce((sum, payment) => sum + payment.amount, 0)
|
||||
|
||||
if (!hasTerminalPayment && terminalInfo) {
|
||||
const terminalAmount =
|
||||
typeof terminalInfo.amount === 'number'
|
||||
? terminalInfo.amount
|
||||
: Math.max(0, Number(totalAmount) - nonTerminalTotal)
|
||||
|
||||
if (terminalAmount > 0) {
|
||||
payments.push({
|
||||
method: PaymentMethodType.TERMINAL,
|
||||
amount: terminalAmount,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
this.validatePayments(payments, totalAmount, terminalInfo)
|
||||
|
||||
return {
|
||||
payments,
|
||||
terminalInfo,
|
||||
}
|
||||
}
|
||||
|
||||
private validatePayments(
|
||||
payments: NormalizedPayment[],
|
||||
totalAmount: number,
|
||||
terminalInfo?: TerminalPaymentInfo,
|
||||
) {
|
||||
const totalPayments = payments.reduce((sum, payment) => sum + payment.amount, 0)
|
||||
const roundedTotalPayments = Number(totalPayments.toFixed(2))
|
||||
const roundedTotalAmount = Number(Number(totalAmount).toFixed(2))
|
||||
|
||||
if (roundedTotalPayments !== roundedTotalAmount) {
|
||||
throw new BadRequestException('مبلغ پرداختی باید برابر با مبلغ کل فاکتور باشد.')
|
||||
}
|
||||
|
||||
const terminalPayments = payments.filter(
|
||||
payment => payment.method === PaymentMethodType.TERMINAL,
|
||||
)
|
||||
|
||||
if (terminalPayments.length > 0 && !terminalInfo) {
|
||||
throw new BadRequestException('برای پرداخت ترمینال اطلاعات ترمینال الزامی است.')
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCustomerId(
|
||||
tx: Prisma.TransactionClient,
|
||||
data: CreateSalesInvoiceDto,
|
||||
businessId: string,
|
||||
) {
|
||||
if (data.customer_id) {
|
||||
return data.customer_id
|
||||
}
|
||||
|
||||
if (
|
||||
data.customer_type === CustomerType.INDIVIDUAL &&
|
||||
data.customer?.customer_individual
|
||||
) {
|
||||
const { national_id, mobile_number, ...rest } = data.customer.customer_individual
|
||||
|
||||
const customerIndividual = await tx.customerIndividual.upsert({
|
||||
where: {
|
||||
business_activity_id_national_id: {
|
||||
business_activity_id: businessId,
|
||||
national_id: data.customer.customer_individual.national_id,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
...data.customer.customer_individual,
|
||||
customer: {
|
||||
create: {
|
||||
type: CustomerType.INDIVIDUAL,
|
||||
},
|
||||
},
|
||||
business_activity: {
|
||||
connect: {
|
||||
id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
update: { ...rest },
|
||||
select: {
|
||||
customer_id: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!customerIndividual) {
|
||||
throw new BadRequestException('متاسفانه مشکلی در اطلاعات مشتری وجود دارد.')
|
||||
}
|
||||
|
||||
return customerIndividual.customer_id
|
||||
}
|
||||
|
||||
if (data.customer_type === CustomerType.LEGAL && data.customer?.customer_legal) {
|
||||
const { registration_number, ...rest } = data.customer.customer_legal
|
||||
const customerLegal = await tx.customerLegal.upsert({
|
||||
where: {
|
||||
business_activity_id_economic_code: {
|
||||
business_activity_id: businessId,
|
||||
economic_code: data.customer.customer_legal.economic_code,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
...data.customer.customer_legal,
|
||||
customer: {
|
||||
create: {
|
||||
type: CustomerType.LEGAL,
|
||||
},
|
||||
},
|
||||
business_activity: {
|
||||
connect: {
|
||||
id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
update: {
|
||||
...rest,
|
||||
},
|
||||
select: {
|
||||
customer_id: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!customerLegal) {
|
||||
throw new BadRequestException('متاسفانه مشکلی در اطلاعات مشتری وجود دارد.')
|
||||
}
|
||||
|
||||
return customerLegal.customer_id
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private async getGoodsById(tx: Prisma.TransactionClient, data: CreateSalesInvoiceDto) {
|
||||
const itemGoodIds = data.items
|
||||
.map(item => item.good_id)
|
||||
.filter((goodId): goodId is string => Boolean(goodId))
|
||||
|
||||
const goods = itemGoodIds.length
|
||||
? await tx.good.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: itemGoodIds,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
sku: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
VAT: true,
|
||||
},
|
||||
},
|
||||
local_sku: true,
|
||||
barcode: true,
|
||||
pricing_model: true,
|
||||
measure_unit: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
base_sale_price: true,
|
||||
image_url: true,
|
||||
category: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: []
|
||||
|
||||
return new Map(goods.map(good => [good.id, good]))
|
||||
}
|
||||
|
||||
private buildSalesInvoiceData(params: {
|
||||
data: CreateSalesInvoiceDto
|
||||
normalizedInvoiceDate: Date
|
||||
invoiceNumber: number
|
||||
consumer_account_id: string
|
||||
businessId: string
|
||||
complexId: string
|
||||
pos_id: string
|
||||
goodsById: Map<string, any>
|
||||
customerId: string | null
|
||||
}) {
|
||||
const {
|
||||
data,
|
||||
normalizedInvoiceDate,
|
||||
invoiceNumber,
|
||||
consumer_account_id,
|
||||
pos_id,
|
||||
goodsById,
|
||||
customerId,
|
||||
businessId,
|
||||
complexId,
|
||||
} = params
|
||||
const { customer_id, customer_type, customer, payments, ...invoiceData } = data
|
||||
|
||||
const salesInvoiceData: SalesInvoiceCreateInput = {
|
||||
...invoiceData,
|
||||
invoice_date: normalizedInvoiceDate,
|
||||
invoice_number: invoiceNumber,
|
||||
total_amount: data.total_amount,
|
||||
code: this.generateInvoiceCode(businessId, complexId, pos_id, invoiceNumber),
|
||||
items: {
|
||||
createMany: {
|
||||
data: data.items.map(item => ({
|
||||
good_id: item.good_id!,
|
||||
quantity: item.quantity,
|
||||
unit_price: item.unit_price,
|
||||
total_amount: item.total_amount,
|
||||
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(
|
||||
JSON.stringify({
|
||||
good: goodsById.get(item.good_id) || null,
|
||||
}),
|
||||
)
|
||||
: undefined,
|
||||
})),
|
||||
},
|
||||
},
|
||||
unknown_customer: {},
|
||||
consumer_account: {
|
||||
connect: {
|
||||
id: consumer_account_id,
|
||||
},
|
||||
},
|
||||
pos: {
|
||||
connect: {
|
||||
id: pos_id,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if (data.send_to_tsp) {
|
||||
salesInvoiceData.tsp_attempts = {
|
||||
create: {
|
||||
attempt_no: 1,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (customerId) {
|
||||
salesInvoiceData.customer = {
|
||||
connect: {
|
||||
id: customerId,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return salesInvoiceData
|
||||
}
|
||||
|
||||
private async getNextInvoiceNumber(tx: Prisma.TransactionClient, businessId: string) {
|
||||
const latestInvoice = await tx.salesInvoice.findFirst({
|
||||
where: {
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity_id: businessId,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
invoice_number: 'desc',
|
||||
},
|
||||
select: {
|
||||
invoice_number: true,
|
||||
pos: {
|
||||
select: {
|
||||
complex: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
invoice_number_sequence: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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(
|
||||
tx: Prisma.TransactionClient,
|
||||
invoiceId: string,
|
||||
payments: NormalizedPayment[],
|
||||
terminalInfo: TerminalPaymentInfo | undefined,
|
||||
paidAt: Date,
|
||||
) {
|
||||
for (const payment of payments) {
|
||||
if (payment.amount <= 0) {
|
||||
continue
|
||||
}
|
||||
const createdPayment = await tx.salesInvoicePayment.create({
|
||||
data: {
|
||||
invoice_id: invoiceId,
|
||||
amount: payment.amount,
|
||||
payment_method: payment.method,
|
||||
paid_at: paidAt,
|
||||
},
|
||||
})
|
||||
|
||||
if (payment.method === PaymentMethodType.TERMINAL && terminalInfo) {
|
||||
await tx.salesInvoicePaymentTerminalInfo.create({
|
||||
data: {
|
||||
payment_id: createdPayment.id,
|
||||
terminal_id: terminalInfo.terminalId,
|
||||
stan: terminalInfo.stan,
|
||||
rrn: terminalInfo.rrn,
|
||||
transaction_date_time: new Date(terminalInfo.transactionDateTime || ''),
|
||||
customer_card_no: terminalInfo.customerCardNO || null,
|
||||
description: terminalInfo.description || null,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private generateInvoiceCode(
|
||||
business_id: string,
|
||||
complex_id: string,
|
||||
pos_id: string,
|
||||
invoice_number: number,
|
||||
) {
|
||||
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,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
SharedCreateSalesInvoiceItemDto,
|
||||
SharedCreateSalesInvoicePaymentsDto,
|
||||
} from '@/common/services/saleInvoices/sale-invoice-create.dto'
|
||||
import {
|
||||
CustomerType,
|
||||
InvoiceTemplateType,
|
||||
@@ -10,6 +14,7 @@ import {
|
||||
import { ApiProperty } from '@nestjs/swagger'
|
||||
import { Type } from 'class-transformer'
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
@@ -142,7 +147,7 @@ export class TspProviderSendItemPayloadDto {
|
||||
payload?: unknown
|
||||
}
|
||||
|
||||
export class TspProviderSendPayloadDto {
|
||||
export class TspProviderOriginalSendPayloadDto {
|
||||
@ApiProperty({ required: true, enum: TspProviderRequestType })
|
||||
@IsEnum(TspProviderRequestType)
|
||||
type: TspProviderRequestType
|
||||
@@ -219,11 +224,14 @@ export class TspProviderSendItemResultDto {
|
||||
@IsString()
|
||||
tax_id?: string | null
|
||||
|
||||
@ApiProperty({ required: true, nullable: true, type: TspProviderSendPayloadDto })
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
nullable: true,
|
||||
type: TspProviderOriginalSendPayloadDto,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
@Type(() => TspProviderSendPayloadDto)
|
||||
request_payload: TspProviderSendPayloadDto
|
||||
request_payload: Object
|
||||
|
||||
@ApiProperty({ required: false, nullable: true, type: Object })
|
||||
@IsOptional()
|
||||
@@ -260,6 +268,8 @@ export class TspProviderBulkSendResultDto {
|
||||
items: TspProviderSendItemResultDto[]
|
||||
}
|
||||
|
||||
///////////// GET RELATED DTOs /////////////
|
||||
|
||||
export class TspProviderGetResultDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@@ -292,6 +302,8 @@ export class TspProviderGetResultDto {
|
||||
received_at: string
|
||||
}
|
||||
|
||||
///////////// REVOKE RELATED DTOs /////////////
|
||||
|
||||
export class TspProviderRevokePayloadDto {
|
||||
@ApiProperty({ required: true, nullable: true })
|
||||
@IsNumber()
|
||||
@@ -319,7 +331,7 @@ export class TspProviderRevokePayloadDto {
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
last_attempt_tax_id: string
|
||||
last_tax_id: string
|
||||
}
|
||||
|
||||
export class TspProviderRevokeResponseDto {
|
||||
@@ -363,10 +375,55 @@ export class TspProviderRevokeResponseDto {
|
||||
received_at: string
|
||||
}
|
||||
|
||||
///////////// CORRECTION RELATED DTOs /////////////
|
||||
export class TspProviderCorrectionInvoicePayloadDto {
|
||||
@ApiProperty({ type: [SharedCreateSalesInvoiceItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SharedCreateSalesInvoiceItemDto)
|
||||
@ArrayMinSize(1)
|
||||
items: SharedCreateSalesInvoiceItemDto[]
|
||||
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
total_amount: number
|
||||
|
||||
@ApiProperty({ required: true, type: SharedCreateSalesInvoicePaymentsDto })
|
||||
@IsObject()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => SharedCreateSalesInvoicePaymentsDto)
|
||||
payments: SharedCreateSalesInvoicePaymentsDto
|
||||
}
|
||||
export class TspProviderCorrectionSendPayloadDto extends TspProviderOriginalSendPayloadDto {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
last_tax_id: string
|
||||
}
|
||||
|
||||
export class TspProviderCorrectionSendResponseDto {}
|
||||
|
||||
export class TspProviderActionResponseDto {
|
||||
@IsObject()
|
||||
invoice: object
|
||||
|
||||
@IsString()
|
||||
message: string
|
||||
|
||||
@IsEnum(TspProviderResponseStatus)
|
||||
status: TspProviderResponseStatus
|
||||
}
|
||||
|
||||
export interface IProviderSwitchAdapter {
|
||||
readonly code: string
|
||||
send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto>
|
||||
sendBulk(payloads: TspProviderSendPayloadDto[]): Promise<TspProviderBulkSendResultDto[]>
|
||||
originalSend(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto>
|
||||
sendBulk(
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]>
|
||||
correctionSend(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto>
|
||||
get(invoiceId: string, tsp_token: string): Promise<TspProviderGetResultDto>
|
||||
revoke(payload: TspProviderRevokePayloadDto): Promise<TspProviderRevokeResponseDto>
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
TspProviderBulkSendResultDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderGetResultDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from './dto/provider-switch.dto'
|
||||
import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
|
||||
@@ -23,15 +25,24 @@ export class SalesInvoiceTspSwitchService {
|
||||
}
|
||||
}
|
||||
|
||||
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
|
||||
async send(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
return adapter.send(payload)
|
||||
return adapter.originalSend(payload)
|
||||
}
|
||||
|
||||
async correction(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto> {
|
||||
const adapter = this.resolveSwitch(payload.tsp_provider)
|
||||
return adapter.correctionSend(payload)
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TspProviderSendPayloadDto[],
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]> {
|
||||
const groupedByProvider = new Map<string, TspProviderSendPayloadDto[]>()
|
||||
const groupedByProvider = new Map<string, TspProviderOriginalSendPayloadDto[]>()
|
||||
|
||||
for (const payload of payloads) {
|
||||
const key = payload.tsp_provider?.trim().toUpperCase() || 'NAMA'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { HttpClientUtil } from '@/common/utils'
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { NamaProviderUtils } from '@/modules/tspProviders/switch/nama/nama-provider.util'
|
||||
import { PrismaModule } from '@/prisma/prisma.module'
|
||||
import { Module } from '@nestjs/common'
|
||||
@@ -14,6 +15,7 @@ import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
NamaProviderUtils,
|
||||
SharedSaleInvoiceCreateService,
|
||||
],
|
||||
exports: [
|
||||
HttpClientUtil,
|
||||
@@ -21,6 +23,7 @@ import { NamaProviderSwitchAdapter } from './switch/nama/nama-provider.adapter'
|
||||
SalesInvoiceTspSwitchService,
|
||||
NamaProviderSwitchAdapter,
|
||||
NamaProviderUtils,
|
||||
SharedSaleInvoiceCreateService,
|
||||
],
|
||||
})
|
||||
export class SaleInvoiceTspModule {}
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { SharedSaleInvoiceCreateService } from '@/common/services/saleInvoices/sale-invoice-create.service'
|
||||
import { PrismaService } from '@/prisma/prisma.service'
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
|
||||
import {
|
||||
CustomerType,
|
||||
Prisma,
|
||||
TspProviderCustomerType,
|
||||
TspProviderRequestType,
|
||||
TspProviderResponseStatus,
|
||||
} from 'generated/prisma/client'
|
||||
import { CreateSalesInvoiceDto } from '../pos/sales-invoices/dto/create-sales-invoice.dto'
|
||||
import {
|
||||
TspProviderActionResponseDto,
|
||||
TspProviderCorrectionInvoicePayloadDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from './dto/provider-switch.dto'
|
||||
import { SalesInvoiceTspSwitchService } from './sales-invoice-tsp-switch.service'
|
||||
|
||||
@@ -19,81 +24,51 @@ type ItemTspRow = {
|
||||
tax_id: string | null
|
||||
}
|
||||
|
||||
type IAttempt = any
|
||||
|
||||
@Injectable()
|
||||
export class SalesInvoiceTspService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly tspSwitchService: SalesInvoiceTspSwitchService,
|
||||
private sharedSaleInvoiceCreateService: SharedSaleInvoiceCreateService,
|
||||
) {}
|
||||
|
||||
async send(consumer_id: string, invoice_id: string): Promise<IAttempt> {
|
||||
const posId = await this.getPosId(consumer_id, invoice_id)
|
||||
async originalSend(
|
||||
posId: string,
|
||||
invoice_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
const payload = await this.buildPayload(invoice_id, posId)
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: 1,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
},
|
||||
})
|
||||
|
||||
const sendResult = await this.trySend(payload)
|
||||
const result = await this.trySend(payload)
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(sendResult)
|
||||
|
||||
if (sendResult) {
|
||||
if (sendResult.hasError) {
|
||||
throw new Error(sendResult.message || '')
|
||||
}
|
||||
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: attempt.id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(sendResult)),
|
||||
status: sendResult.status,
|
||||
tax_id: sendResult.tax_id,
|
||||
sent_at: sendResult.sent_at,
|
||||
received_at: sendResult.received_at,
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
return await this.onCreateCorrectionResult(result, attempt.id)
|
||||
}
|
||||
|
||||
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
|
||||
if (!invoice_ids.length) return
|
||||
|
||||
const payloads: TspProviderSendPayloadDto[] = []
|
||||
for (const invoiceId of invoice_ids) {
|
||||
const posId = await this.getPosId(consumer_id, invoiceId)
|
||||
payloads.push(await this.buildPayload(invoiceId, posId))
|
||||
}
|
||||
|
||||
const bulkResult = await this.tspSwitchService.sendBulk(payloads)
|
||||
const allItemResults = bulkResult.flatMap(result => result.items)
|
||||
await this.persistAttemptResults(allItemResults)
|
||||
// if (!invoice_ids.length) return
|
||||
// const payloads: TspProviderOriginalSendPayloadDto[] = []
|
||||
// for (const invoiceId of invoice_ids) {
|
||||
// const posId = await this.getPosId(consumer_id, invoiceId)
|
||||
// payloads.push(await this.buildPayload(invoiceId, posId))
|
||||
// }
|
||||
// const bulkResult = await this.tspSwitchService.sendBulk(payloads)
|
||||
// const allItemResults = bulkResult.flatMap(result => result.items)
|
||||
// await this.persistAttemptResults(allItemResults)
|
||||
}
|
||||
|
||||
async get(invoice_id: string, pos_id: string, consumer_id: string): Promise<IAttempt> {
|
||||
async get(
|
||||
invoice_id: string,
|
||||
pos_id: string,
|
||||
consumer_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
const [attempt, pos] = await this.prisma.$transaction(async tx => [
|
||||
await tx.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
@@ -190,206 +165,307 @@ export class SalesInvoiceTspService {
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
message: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
}
|
||||
|
||||
async update(
|
||||
consumer_id: string,
|
||||
invoice_id: string,
|
||||
dataToUpdate: CreateSalesInvoiceDto,
|
||||
): Promise<IAttempt> {
|
||||
const posId = await this.getPosId(consumer_id, invoice_id)
|
||||
const payload = await this.buildPayload(invoice_id, posId)
|
||||
|
||||
const lastAttempt = await this.prisma.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
invoice_id,
|
||||
invoice: {
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
async correctionSend(
|
||||
consumerAccountId: string,
|
||||
posId: string,
|
||||
complexId: string,
|
||||
businessId: string,
|
||||
ref_invoice_id: string,
|
||||
dataToUpdate: TspProviderCorrectionInvoicePayloadDto,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
const [newInvoice, attempt, correctionPayload] = await this.prisma.$transaction(
|
||||
async tx => {
|
||||
const relatedInvoice = await tx.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: ref_invoice_id,
|
||||
},
|
||||
include: {
|
||||
customer: {
|
||||
select: {
|
||||
type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
include: {
|
||||
invoice: {
|
||||
include: {
|
||||
items: {
|
||||
include: {
|
||||
good: true,
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!relatedInvoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
|
||||
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
if (!relatedInvoice.tax_id) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
const newInvoice = await this.sharedSaleInvoiceCreateService.create({
|
||||
data: {
|
||||
customer_type: relatedInvoice.customer?.type || CustomerType.UNKNOWN,
|
||||
invoice_date: new Date(),
|
||||
payments: dataToUpdate.payments,
|
||||
items: dataToUpdate.items,
|
||||
total_amount: dataToUpdate.total_amount,
|
||||
customer_id: relatedInvoice.customer_id || undefined,
|
||||
},
|
||||
businessId,
|
||||
complexId,
|
||||
posId,
|
||||
consumerAccountId,
|
||||
main_invoice_id: relatedInvoice.main_id || relatedInvoice.id,
|
||||
ref_invoice_id: relatedInvoice.id,
|
||||
type: TspProviderRequestType.CORRECTION,
|
||||
})
|
||||
|
||||
const correctionPayload = await this.buildCorrectionPayload(tx, newInvoice.id)
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: 1,
|
||||
invoice_id: newInvoice.id,
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
request_payload: JSON.parse(JSON.stringify(correctionPayload)),
|
||||
},
|
||||
})
|
||||
|
||||
return [newInvoice, attempt, correctionPayload]
|
||||
},
|
||||
)
|
||||
|
||||
const result = await this.trySend(correctionPayload)
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(result)
|
||||
return this.onCreateCorrectionResult(result, attempt.id)
|
||||
|
||||
// const countByGoodId = (goodIds: string[]): Map<string, number> => {
|
||||
// const counts = new Map<string, number>()
|
||||
// for (const goodId of goodIds) {
|
||||
// counts.set(goodId, (counts.get(goodId) ?? 0) + 1)
|
||||
// }
|
||||
// return counts
|
||||
// }
|
||||
|
||||
// const updatedGoodIds = dataToUpdate.items.map(item => item.good_id!)
|
||||
// const previousGoodIds = lastAttempt.invoice.items.map(item => item.good_id)
|
||||
|
||||
// const updatedCounts = countByGoodId(updatedGoodIds)
|
||||
// const previousCounts = countByGoodId(previousGoodIds)
|
||||
|
||||
// let isBackFromSale = false
|
||||
// if (updatedCounts.size !== previousCounts.size) {
|
||||
// isBackFromSale = true
|
||||
// } else {
|
||||
// for (const [goodId, count] of updatedCounts) {
|
||||
// if (previousCounts.get(goodId) !== count) {
|
||||
// isBackFromSale = true
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
async revoke(
|
||||
consumerAccountId: string,
|
||||
posId: string,
|
||||
complexId: string,
|
||||
businessId: string,
|
||||
ref_invoice_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
const [newInvoice, attempt, revokePayload] = await this.prisma.$transaction(
|
||||
async tx => {
|
||||
const relatedInvoice = await tx.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: ref_invoice_id,
|
||||
},
|
||||
include: {
|
||||
customer: {
|
||||
select: {
|
||||
type: true,
|
||||
},
|
||||
},
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
payments: {
|
||||
include: {
|
||||
terminal_info: true,
|
||||
},
|
||||
},
|
||||
items: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (!lastAttempt) {
|
||||
throw new NotFoundException('صورتحساب ارسالی فاکتور شما به سامانه یافت نشد.')
|
||||
}
|
||||
|
||||
if (lastAttempt.status === TspProviderResponseStatus.QUEUED) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور هنوز به سامانه مالیاتی ارسال نشده است یا در صف ارسال قرار دارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
const countByGoodId = (goodIds: string[]): Map<string, number> => {
|
||||
const counts = new Map<string, number>()
|
||||
for (const goodId of goodIds) {
|
||||
counts.set(goodId, (counts.get(goodId) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
const updatedGoodIds = dataToUpdate.items.map(item => item.good_id!)
|
||||
const previousGoodIds = lastAttempt.invoice.items.map(item => item.good_id)
|
||||
|
||||
const updatedCounts = countByGoodId(updatedGoodIds)
|
||||
const previousCounts = countByGoodId(previousGoodIds)
|
||||
|
||||
let isBackFromSale = false
|
||||
if (updatedCounts.size !== previousCounts.size) {
|
||||
isBackFromSale = true
|
||||
} else {
|
||||
for (const [goodId, count] of updatedCounts) {
|
||||
if (previousCounts.get(goodId) !== count) {
|
||||
isBackFromSale = true
|
||||
break
|
||||
if (!relatedInvoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: 1,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
type: TspProviderRequestType.MAIN,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
},
|
||||
})
|
||||
if (relatedInvoice.type === TspProviderRequestType.REVOKE) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور ارسالی قبلا ابطال شده است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
const sendResult = await this.trySend(payload)
|
||||
if (!relatedInvoice.tax_id) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور قبلی همچنان در حال بررسی است و امکان ویرایش آن وجود ندارد.',
|
||||
)
|
||||
}
|
||||
|
||||
console.log('sendResult')
|
||||
console.log(sendResult)
|
||||
|
||||
if (sendResult) {
|
||||
if (sendResult.hasError) {
|
||||
throw new Error(sendResult.message || '')
|
||||
}
|
||||
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: attempt.id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(sendResult)),
|
||||
status: sendResult.status,
|
||||
tax_id: sendResult.tax_id,
|
||||
sent_at: sendResult.sent_at,
|
||||
received_at: sendResult.received_at,
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
...updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async revoke(
|
||||
pos_id: string,
|
||||
invoice_id: string,
|
||||
): Promise<TspProviderRevokeResponseDto> {
|
||||
const attempt = await this.prisma.saleInvoiceTspAttempts.findFirst({
|
||||
where: {
|
||||
invoice_id,
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
select: {
|
||||
tax_id: true,
|
||||
status: true,
|
||||
attempt_no: true,
|
||||
invoice: {
|
||||
select: {
|
||||
invoice_number: true,
|
||||
const payments = relatedInvoice.payments.reduce(
|
||||
(acc, payment) => {
|
||||
const amount = Number(payment.amount)
|
||||
switch (payment.payment_method) {
|
||||
case 'CASH':
|
||||
acc.cash = (acc.cash || 0) + amount
|
||||
break
|
||||
case 'SET_OFF':
|
||||
acc.set_off = (acc.set_off || 0) + amount
|
||||
break
|
||||
case 'CARD':
|
||||
acc.card = (acc.card || 0) + amount
|
||||
break
|
||||
case 'BANK':
|
||||
acc.bank = (acc.bank || 0) + amount
|
||||
break
|
||||
case 'CHEQUE':
|
||||
acc.check = (acc.check || 0) + amount
|
||||
break
|
||||
case 'OTHER':
|
||||
acc.other = (acc.other || 0) + amount
|
||||
break
|
||||
case 'TERMINAL':
|
||||
acc.terminals = payment.terminal_info
|
||||
? {
|
||||
amount,
|
||||
terminalId: payment.terminal_info.terminal_id,
|
||||
stan: payment.terminal_info.stan,
|
||||
rrn: payment.terminal_info.rrn,
|
||||
customer_card_no:
|
||||
payment.terminal_info.customer_card_no || undefined,
|
||||
transaction_date_time: payment.terminal_info.transaction_date_time,
|
||||
description: payment.terminal_info.description || undefined,
|
||||
}
|
||||
: acc.terminals
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
return acc
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
{} as {
|
||||
terminals?: {
|
||||
amount?: number
|
||||
terminalId: string
|
||||
stan: string
|
||||
rrn: string
|
||||
customer_card_no?: string
|
||||
transaction_date_time: Date
|
||||
description?: string
|
||||
}
|
||||
cash?: number
|
||||
set_off?: number
|
||||
card?: number
|
||||
bank?: number
|
||||
check?: number
|
||||
other?: number
|
||||
},
|
||||
)
|
||||
|
||||
if (!attempt) {
|
||||
throw new NotFoundException('صورتحساب ارسالی فاکتور شما به سامانه یافت نشد.')
|
||||
}
|
||||
if (attempt.status === TspProviderResponseStatus.QUEUED) {
|
||||
throw new BadRequestException(
|
||||
'فاکتور هنوز به سامانه مالیاتی ارسال نشده است یا در صف ارسال قرار دارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
const payload = await this.buildRevokePayload(invoice_id, pos_id)
|
||||
|
||||
const result = await this.tspSwitchService.revoke(payload)
|
||||
|
||||
if (result) {
|
||||
await this.prisma.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: attempt.attempt_no + 1,
|
||||
invoice_id,
|
||||
status: TspProviderResponseStatus.REVOKED,
|
||||
const newInvoice = await this.sharedSaleInvoiceCreateService.create({
|
||||
data: {
|
||||
customer_type: relatedInvoice.customer?.type || CustomerType.UNKNOWN,
|
||||
invoice_date: new Date(),
|
||||
payments,
|
||||
items: relatedInvoice.items.map(item => ({
|
||||
unit_price: Number(item.unit_price),
|
||||
quantity: Number(item.quantity),
|
||||
total_amount: Number(item.total_amount),
|
||||
discount_amount: Number(item.discount || 0),
|
||||
invoice_id: '',
|
||||
good_id: item.good_id,
|
||||
service_id: item.service_id || undefined,
|
||||
payload: item.payload as any,
|
||||
notes: item.notes || '',
|
||||
})),
|
||||
total_amount: Number(relatedInvoice.total_amount),
|
||||
customer_id: relatedInvoice.customer_id || undefined,
|
||||
},
|
||||
businessId,
|
||||
complexId,
|
||||
posId,
|
||||
consumerAccountId,
|
||||
main_invoice_id: relatedInvoice.main_id || relatedInvoice.id,
|
||||
ref_invoice_id: relatedInvoice.id,
|
||||
type: TspProviderRequestType.REVOKE,
|
||||
received_at: new Date(),
|
||||
request_payload: JSON.parse(JSON.stringify(result.request_payload)),
|
||||
sent_at: result.sent_at ? new Date(result.sent_at) : new Date(),
|
||||
response_payload: JSON.parse(JSON.stringify(result)),
|
||||
tax_id: result.tax_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
const payload = await this.buildRevokePayload(newInvoice.id, posId)
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.create({
|
||||
data: {
|
||||
attempt_no: 1,
|
||||
invoice_id: newInvoice.id,
|
||||
message: 'در حال ارسال به سامانه مالیاتی...',
|
||||
status: TspProviderResponseStatus.QUEUED,
|
||||
request_payload: JSON.parse(JSON.stringify(payload)),
|
||||
},
|
||||
})
|
||||
|
||||
return [newInvoice, attempt, payload]
|
||||
},
|
||||
)
|
||||
|
||||
const result = await this.tspSwitchService.revoke(revokePayload)
|
||||
|
||||
return await this.onCreateCorrectionResult(result, attempt.id)
|
||||
}
|
||||
|
||||
private async getPosId(consumer_id: string, invoice_id: string): Promise<string> {
|
||||
private async getPosId(
|
||||
consumer_account_id: string,
|
||||
invoice_id: string,
|
||||
): Promise<string> {
|
||||
const now = new Date()
|
||||
console.log(consumer_account_id, invoice_id)
|
||||
const saleInvoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoice_id,
|
||||
pos: {
|
||||
complex: {
|
||||
business_activity: {
|
||||
consumer_id,
|
||||
consumer: {
|
||||
accounts: {
|
||||
some: {
|
||||
id: consumer_account_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -462,6 +538,7 @@ export class SalesInvoiceTspService {
|
||||
total_amount: true,
|
||||
invoice_date: true,
|
||||
invoice_number: true,
|
||||
tax_id: true,
|
||||
tsp_attempts: {
|
||||
orderBy: {
|
||||
created_at: 'asc',
|
||||
@@ -470,7 +547,6 @@ export class SalesInvoiceTspService {
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
tax_id: true,
|
||||
},
|
||||
},
|
||||
pos: {
|
||||
@@ -532,14 +608,147 @@ export class SalesInvoiceTspService {
|
||||
fiscal_id: invoice.pos.complex.business_activity.fiscal_id,
|
||||
tsp_token: invoice.pos.complex.business_activity.partner_token,
|
||||
tsp_provider: partner.tsp_provider!,
|
||||
last_attempt_tax_id: invoice.tsp_attempts[0].tax_id!,
|
||||
last_tax_id: invoice.tax_id!,
|
||||
}
|
||||
}
|
||||
|
||||
private async buildCorrectionPayload(
|
||||
tx: Prisma.TransactionClient,
|
||||
invoice_id: string,
|
||||
): Promise<TspProviderCorrectionSendPayloadDto> {
|
||||
const invoice = await tx.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoice_id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
total_amount: true,
|
||||
invoice_date: true,
|
||||
invoice_number: true,
|
||||
items: true,
|
||||
pos: {
|
||||
select: {
|
||||
complex: {
|
||||
select: {
|
||||
business_activity: {
|
||||
select: {
|
||||
fiscal_id: true,
|
||||
economic_code: true,
|
||||
partner_token: true,
|
||||
guild: {
|
||||
select: {
|
||||
invoice_template: true,
|
||||
},
|
||||
},
|
||||
consumer: {
|
||||
select: {
|
||||
legal: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
tsp_provider: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
individual: {
|
||||
select: {
|
||||
partner: {
|
||||
select: {
|
||||
tsp_provider: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
customer: {
|
||||
select: {
|
||||
type: true,
|
||||
individual: true,
|
||||
legal: true,
|
||||
},
|
||||
},
|
||||
|
||||
reference_invoice: {
|
||||
select: {
|
||||
tax_id: true,
|
||||
},
|
||||
},
|
||||
payments: {
|
||||
include: {
|
||||
terminal_info: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!invoice) {
|
||||
throw Error()
|
||||
}
|
||||
|
||||
const { partner } = (invoice.pos.complex.business_activity.consumer.legal ||
|
||||
invoice.pos.complex.business_activity.consumer.individual)!
|
||||
|
||||
const returnData: TspProviderCorrectionSendPayloadDto = {
|
||||
items: invoice.items.map(item => ({
|
||||
invoice_item_id: item.id,
|
||||
quantity: Number(item.quantity),
|
||||
unit_price: Number(item.unit_price),
|
||||
total_amount: Number(item.total_amount),
|
||||
measure_unit: item.measure_unit_code,
|
||||
sku: item.sku_code,
|
||||
sku_vat: String(item.sku_vat),
|
||||
discount: String((item.payload as Record<string, any>)?.discount || '0'),
|
||||
good_id: item.good_id,
|
||||
service_id: item.service_id,
|
||||
payload: item.payload,
|
||||
good_snapshot: item.good_snapshot,
|
||||
})),
|
||||
payments: invoice.payments.map(payment => ({
|
||||
amount: Number(payment.amount),
|
||||
payment_method: payment.payment_method,
|
||||
paid_at: payment.paid_at,
|
||||
card_number: payment.terminal_info ? payment.terminal_info.stan : undefined,
|
||||
tracking_code: payment.terminal_info ? payment.terminal_info.rrn : undefined,
|
||||
})),
|
||||
total_amount: Number(invoice.total_amount),
|
||||
last_tax_id: invoice.reference_invoice!.tax_id!,
|
||||
invoice_number: invoice.invoice_number,
|
||||
invoice_id: invoice.id,
|
||||
economic_code: invoice.pos.complex.business_activity.economic_code,
|
||||
fiscal_id: invoice.pos.complex.business_activity.fiscal_id,
|
||||
tsp_token: invoice.pos.complex.business_activity.partner_token,
|
||||
type: TspProviderRequestType.CORRECTION,
|
||||
tsp_provider: partner.tsp_provider!,
|
||||
invoice_template: invoice.pos.complex.business_activity.guild.invoice_template,
|
||||
invoice_date: new Date(),
|
||||
|
||||
customer_type: invoice.customer?.type
|
||||
? TspProviderCustomerType.Known
|
||||
: TspProviderCustomerType.Unknown,
|
||||
customer: invoice.customer?.type
|
||||
? {
|
||||
type: invoice.customer.type,
|
||||
legal_info: invoice.customer.legal ?? undefined,
|
||||
individual_info: invoice.customer.individual ?? undefined,
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
return returnData
|
||||
}
|
||||
|
||||
private async buildPayload(
|
||||
invoiceId: string,
|
||||
posId: string,
|
||||
): Promise<TspProviderSendPayloadDto> {
|
||||
): Promise<TspProviderOriginalSendPayloadDto> {
|
||||
const invoice = await this.prisma.salesInvoice.findUnique({
|
||||
where: {
|
||||
id: invoiceId,
|
||||
@@ -644,6 +853,8 @@ export class SalesInvoiceTspService {
|
||||
},
|
||||
})
|
||||
|
||||
console.log(invoiceId, posId)
|
||||
|
||||
if (!invoice) {
|
||||
throw new NotFoundException('فاکتور مورد نظر یافت نشد.')
|
||||
}
|
||||
@@ -667,7 +878,7 @@ export class SalesInvoiceTspService {
|
||||
card_number: payment.terminal_info ? payment.terminal_info.stan : undefined,
|
||||
tracking_code: payment.terminal_info ? payment.terminal_info.rrn : undefined,
|
||||
})),
|
||||
type: TspProviderRequestType.MAIN,
|
||||
type: TspProviderRequestType.ORIGINAL,
|
||||
tsp_provider: partner.tsp_provider!,
|
||||
customer_type: invoice.customer?.type
|
||||
? TspProviderCustomerType.Known
|
||||
@@ -696,62 +907,79 @@ export class SalesInvoiceTspService {
|
||||
}
|
||||
}
|
||||
|
||||
private async tryCorrection(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto | null> {
|
||||
const taxResult = await this.tspSwitchService.correction(payload)
|
||||
|
||||
return taxResult || null
|
||||
}
|
||||
|
||||
private async trySend(
|
||||
payload: TspProviderSendPayloadDto,
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto | null> {
|
||||
const taxResult = await this.tspSwitchService.send(payload)
|
||||
|
||||
return taxResult || null
|
||||
}
|
||||
|
||||
private async persistAttemptResults(
|
||||
itemResults: TspProviderSendItemResultDto[],
|
||||
): Promise<any> {
|
||||
if (!itemResults.length) return
|
||||
|
||||
const attemptsResult = [] as any[]
|
||||
console.log('persistAttemptResults')
|
||||
|
||||
for (const itemResult of itemResults) {
|
||||
const attempt = await this.prisma.$transaction(async tx => {
|
||||
const lastAttempt = await tx.saleInvoiceTspAttempts.findFirst({
|
||||
private async onCreateCorrectionResult(
|
||||
result: any,
|
||||
attempt_id: string,
|
||||
): Promise<TspProviderActionResponseDto> {
|
||||
if (result) {
|
||||
if (result.hasError) {
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
invoice_id: itemResult.invoice_id,
|
||||
},
|
||||
orderBy: {
|
||||
attempt_no: 'desc',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
})
|
||||
|
||||
const attempt = await tx.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: lastAttempt!.id,
|
||||
id: attempt_id,
|
||||
},
|
||||
data: {
|
||||
status: itemResult.status,
|
||||
tax_id: itemResult.tax_id,
|
||||
request_payload: JSON.parse(JSON.stringify(itemResult.request_payload)),
|
||||
response_payload: JSON.parse(JSON.stringify(itemResult.response_payload)),
|
||||
error_message: itemResult.message,
|
||||
sent_at: itemResult.sent_at ? new Date(itemResult.sent_at) : new Date(),
|
||||
received_at: itemResult.received_at
|
||||
? new Date(itemResult.received_at)
|
||||
: new Date(),
|
||||
response_payload: JSON.parse(JSON.stringify(result)),
|
||||
status: result.status,
|
||||
message: result.message?.toString() || 'وجود مشکل در ارسال به سامانه مالیاتی',
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
message: true,
|
||||
},
|
||||
})
|
||||
return {
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
}
|
||||
|
||||
return attempt
|
||||
const updatedAttempt = await this.prisma.saleInvoiceTspAttempts.update({
|
||||
where: {
|
||||
id: attempt_id,
|
||||
},
|
||||
data: {
|
||||
response_payload: JSON.parse(JSON.stringify(result)),
|
||||
status: result.status,
|
||||
sent_at: result.sent_at,
|
||||
received_at: result.received_at,
|
||||
message: 'ارسال با موفقیت انجام شد.',
|
||||
},
|
||||
select: {
|
||||
status: true,
|
||||
invoice: true,
|
||||
message: true,
|
||||
},
|
||||
})
|
||||
attemptsResult.push(attempt)
|
||||
|
||||
return {
|
||||
invoice: updatedAttempt.invoice,
|
||||
status: updatedAttempt.status,
|
||||
message: updatedAttempt.message,
|
||||
}
|
||||
} else {
|
||||
throw new NotFoundException(
|
||||
'متاسفانه امکان ارسال فاکتور به سیستم مالیاتی در حال حاضر وجود ندارد. لطفا بعدا تلاش کنید.',
|
||||
)
|
||||
}
|
||||
|
||||
console.log(attemptsResult)
|
||||
|
||||
return attemptsResult
|
||||
}
|
||||
}
|
||||
|
||||
// {"type": "MAIN", "items": [{"sku": "2720000044726", "good_id": "01KQHY48M299C9BG2D06DMWK4E", "payload": {"karat": "18", "wages": 40000000, "profit": 48000000, "commission": 40000000}, "sku_vat": "0", "discount": "0", "quantity": 2, "service_id": null, "unit_price": 200000000, "measure_unit": "63", "total_amount": 540800000, "good_snapshot": {"good": {"id": "01KQHY48M299C9BG2D06DMWK4E", "sku": {"id": "01KQHXE2D4XEFSDK4DSV2J6GT2", "VAT": "0", "code": "2720000044726", "name": "گوشواره طلا زیورالات ساخته شده از طلا"}, "name": "گوشواره", "barcode": null, "category": {"id": "01KQHY48CF6X2TK2AG09MKDVKQ", "name": "زیورآلات"}, "image_url": null, "local_sku": null, "measure_unit": {"id": "01KQHY489HE02787SE8TWDE18S", "code": "63", "name": "گرم"}, "pricing_model": "GOLD", "base_sale_price": "0"}}, "invoice_item_id": "01KQMZTMDC4M4T7VE9GFZJEW4E"}], "payments": [{"amount": 540800000, "paid_at": "2026-05-02T18:39:46.000Z", "payment_method": "CASH"}], "fiscal_id": "A296T3", "tsp_token": "pfFE6QxOJxUIhzkpUCPWYMR5", "invoice_id": "98c3377d-4e42-4703-97f0-38c3b3c8e87f", "invoice_date": "2026-05-02T18:39:46.000Z", "total_amount": 540800000, "tsp_provider": "NAMA", "customer_type": "Unknown", "economic_code": "14003579468", "invoice_number": 13, "invoice_template": "GOLD_JEWELRY"}
|
||||
// {"type": "ORIGINAL", "items": [{"sku": "2720000044726", "good_id": "01KQHY48M299C9BG2D06DMWK4E", "payload": {"karat": "18", "wages": 40000000, "profit": 48000000, "commission": 40000000}, "sku_vat": "0", "discount": "0", "quantity": 2, "service_id": null, "unit_price": 200000000, "measure_unit": "63", "total_amount": 540800000, "good_snapshot": {"good": {"id": "01KQHY48M299C9BG2D06DMWK4E", "sku": {"id": "01KQHXE2D4XEFSDK4DSV2J6GT2", "VAT": "0", "code": "2720000044726", "name": "گوشواره طلا زیورالات ساخته شده از طلا"}, "name": "گوشواره", "barcode": null, "category": {"id": "01KQHY48CF6X2TK2AG09MKDVKQ", "name": "زیورآلات"}, "image_url": null, "local_sku": null, "measure_unit": {"id": "01KQHY489HE02787SE8TWDE18S", "code": "63", "name": "گرم"}, "pricing_model": "GOLD", "base_sale_price": "0"}}, "invoice_item_id": "01KQMZTMDC4M4T7VE9GFZJEW4E"}], "payments": [{"amount": 540800000, "paid_at": "2026-05-02T18:39:46.000Z", "payment_method": "CASH"}], "fiscal_id": "A296T3", "tsp_token": "pfFE6QxOJxUIhzkpUCPWYMR5", "invoice_id": "98c3377d-4e42-4703-97f0-38c3b3c8e87f", "invoice_date": "2026-05-02T18:39:46.000Z", "total_amount": 540800000, "tsp_provider": "NAMA", "customer_type": "Unknown", "economic_code": "14003579468", "invoice_number": 13, "invoice_template": "GOLD_JEWELRY"}
|
||||
|
||||
@@ -9,11 +9,13 @@ import { Injectable, Logger } from '@nestjs/common'
|
||||
import {
|
||||
IProviderSwitchAdapter,
|
||||
TspProviderBulkSendResultDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderCorrectionSendResponseDto,
|
||||
TspProviderGetResultDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderRevokeResponseDto,
|
||||
TspProviderSendItemResultDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from '../../dto/provider-switch.dto'
|
||||
import {
|
||||
NamaProviderGetResponseDto,
|
||||
@@ -73,7 +75,9 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
]
|
||||
}
|
||||
|
||||
async send(payload: TspProviderSendPayloadDto): Promise<TspProviderSendItemResultDto> {
|
||||
async originalSend(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): Promise<TspProviderSendItemResultDto> {
|
||||
const mappedRequest = this.namaProviderUtils.mapToNamaRequestDto(payload)
|
||||
try {
|
||||
console.log(mappedRequest)
|
||||
@@ -120,12 +124,60 @@ export class NamaProviderSwitchAdapter implements IProviderSwitchAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
async correctionSend(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): Promise<TspProviderCorrectionSendResponseDto> {
|
||||
const mappedRequest = this.namaProviderUtils.mapToNamaRequestDto(payload)
|
||||
|
||||
try {
|
||||
const response = await this.httpClient.request(
|
||||
this.buildSendUrl(),
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(mappedRequest),
|
||||
},
|
||||
this.createRequestInterceptors(payload.tsp_token),
|
||||
)
|
||||
const providerResponse: NamaProviderSendItemResponseDto = await response.json()
|
||||
this.logger.debug('NAMA provider response', providerResponse)
|
||||
|
||||
const result: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
hasError: !response.ok,
|
||||
message: providerResponse.message,
|
||||
sent_at: new Date().toISOString(),
|
||||
response_payload: providerResponse,
|
||||
received_at: providerResponse.tsp_update_time,
|
||||
tax_id: providerResponse.tax_id,
|
||||
status: this.namaProviderUtils.mapResponseStatus(
|
||||
providerResponse.status as NamaProviderResponseStatus,
|
||||
),
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (err) {
|
||||
this.logger.error('NAMA send failed', err)
|
||||
const failure: TspProviderSendItemResultDto = {
|
||||
invoice_id: payload.invoice_id,
|
||||
request_payload: mappedRequest,
|
||||
hasError: true,
|
||||
message: (err as Error).message,
|
||||
sent_at: new Date().toISOString(),
|
||||
received_at: new Date().toISOString(),
|
||||
tax_id: null,
|
||||
status: TspProviderResponseStatus.NOT_SEND,
|
||||
}
|
||||
return failure
|
||||
}
|
||||
}
|
||||
|
||||
async sendBulk(
|
||||
payloads: TspProviderSendPayloadDto[],
|
||||
payloads: TspProviderOriginalSendPayloadDto[],
|
||||
): Promise<TspProviderBulkSendResultDto[]> {
|
||||
const result: TspProviderBulkSendResultDto[] = []
|
||||
for (const payload of payloads) {
|
||||
const itemResults = await this.send(payload)
|
||||
const itemResults = await this.originalSend(payload)
|
||||
result.push({
|
||||
invoice_id: payload.invoice_id,
|
||||
items: [itemResults],
|
||||
|
||||
@@ -383,3 +383,163 @@ export class NamaProviderRevokeResponseDto {
|
||||
@IsString()
|
||||
tsp_update_time: string
|
||||
}
|
||||
|
||||
/////////////// Correction DTOs ///////////////
|
||||
export class NamaProviderCorrectionBodyItemDto {
|
||||
@ApiProperty({ required: true, description: 'شناسه کالا / خدمت' })
|
||||
@IsString()
|
||||
sstid: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: `نرخ مالیات بر ارزش افزوده`,
|
||||
})
|
||||
@IsString()
|
||||
vra: string
|
||||
|
||||
// @ApiProperty()
|
||||
// @IsString()
|
||||
// sstt: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'مبلغ واحد',
|
||||
})
|
||||
@IsString()
|
||||
fee: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'مبلغ تخفیف',
|
||||
})
|
||||
@IsString()
|
||||
dis: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'واحد اندازه گیری',
|
||||
})
|
||||
@IsString()
|
||||
mu: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'تعداد / مقدار',
|
||||
})
|
||||
@IsString()
|
||||
am: string
|
||||
|
||||
@ApiProperty({
|
||||
description: ' اجرت ساخت (طلا)',
|
||||
})
|
||||
@IsString()
|
||||
consfee: string
|
||||
|
||||
@ApiProperty({
|
||||
description: 'حق العمل',
|
||||
})
|
||||
@IsString()
|
||||
bros: string
|
||||
|
||||
@ApiProperty({
|
||||
description: 'سود فروشنده',
|
||||
})
|
||||
@IsString()
|
||||
spro: string
|
||||
}
|
||||
|
||||
export class NamaProviderCorrectionHeaderDto {
|
||||
@ApiProperty({ required: true, description: 'موضوع صورتحساب' })
|
||||
@IsString()
|
||||
ins: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'الگوی صورتحساب' })
|
||||
@IsString()
|
||||
inp: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'نوع صورتحساب' })
|
||||
@IsString()
|
||||
inty: string
|
||||
|
||||
// @ApiProperty({required: true})
|
||||
// @IsString()
|
||||
// unique_tax_code: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'سریال صورتحساب داخلی حافظه مالیاتی' })
|
||||
@IsString()
|
||||
inno: string
|
||||
|
||||
// @ApiProperty({ required: true })
|
||||
// @IsString()
|
||||
// tins: string
|
||||
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
description: 'تاریخ و زمان صدور صورتحساب به صورت timestamp',
|
||||
})
|
||||
@IsString()
|
||||
indatim: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'نام مشتری' })
|
||||
@IsString()
|
||||
name: string
|
||||
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description:
|
||||
'نوع شخصیت خریدار (در صورتیکه خریدار نوع ۲ باشه باید ۱ یا ۲ گذاشته بشه)',
|
||||
})
|
||||
@IsString()
|
||||
tob: string
|
||||
|
||||
@ApiProperty({ description: 'آدرس' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
address?: string
|
||||
|
||||
@ApiProperty({ description: 'شماره موبایل' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mobile?: string
|
||||
|
||||
@ApiProperty({
|
||||
description: `شماره ملی / شناسه ملی / شناسه مشارکت مدنی / کد فراگیر خریدار`,
|
||||
})
|
||||
@IsString()
|
||||
bid: string
|
||||
|
||||
@ApiProperty({ required: true, description: 'روش تسویه' })
|
||||
@IsString()
|
||||
setm: string
|
||||
}
|
||||
|
||||
export class NamaProviderCorrectionRequestDto {
|
||||
@ApiProperty({ type: [NamaProviderCorrectionBodyItemDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NamaProviderCorrectionBodyItemDto)
|
||||
body: NamaProviderCorrectionBodyItemDto[]
|
||||
|
||||
@ApiProperty({ type: [NamaProviderPaymentInfoDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NamaProviderPaymentInfoDto)
|
||||
payment: NamaProviderPaymentInfoDto[]
|
||||
|
||||
@ApiProperty({ type: NamaProviderCorrectionHeaderDto })
|
||||
@ValidateNested()
|
||||
@Type(() => NamaProviderCorrectionHeaderDto)
|
||||
header: NamaProviderCorrectionHeaderDto
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
uuid: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
economic_code: string
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
fiscal_id: string
|
||||
}
|
||||
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
import {
|
||||
CustomerInfoDto,
|
||||
PaymentInfoDto,
|
||||
TspProviderCorrectionSendPayloadDto,
|
||||
TspProviderOriginalSendPayloadDto,
|
||||
TspProviderRevokePayloadDto,
|
||||
TspProviderSendPayloadDto,
|
||||
} from '../../dto/provider-switch.dto'
|
||||
import {
|
||||
NamaProviderCorrectionRequestDto,
|
||||
NamaProviderPaymentInfoDto,
|
||||
NamaProviderRequestDto,
|
||||
NamaProviderResponseStatus,
|
||||
@@ -35,7 +37,9 @@ export class NamaProviderUtils {
|
||||
}
|
||||
}
|
||||
|
||||
mapToNamaRequestDto(payload: TspProviderSendPayloadDto): NamaProviderRequestDto {
|
||||
mapToNamaRequestDto(
|
||||
payload: TspProviderOriginalSendPayloadDto,
|
||||
): NamaProviderRequestDto {
|
||||
return {
|
||||
uuid: payload.invoice_id,
|
||||
economic_code: payload.economic_code,
|
||||
@@ -66,6 +70,39 @@ export class NamaProviderUtils {
|
||||
}
|
||||
}
|
||||
|
||||
mapToNamaCorrectionDto(
|
||||
payload: TspProviderCorrectionSendPayloadDto,
|
||||
): NamaProviderCorrectionRequestDto {
|
||||
return {
|
||||
uuid: payload.invoice_id,
|
||||
economic_code: payload.economic_code,
|
||||
fiscal_id: payload.fiscal_id,
|
||||
payment: this.mapPayments(payload.payments),
|
||||
header: {
|
||||
ins: this.mapTspProviderRequestType(TspProviderRequestType.CORRECTION),
|
||||
inp: this.mapInvoiceTemplate(payload.invoice_template),
|
||||
inty: this.mapTspProviderCustomerType(payload.customer_type),
|
||||
inno: payload.invoice_number.toString(),
|
||||
tins: '',
|
||||
indatim: payload.invoice_date.getTime() + '',
|
||||
setm: '1',
|
||||
...this.mapCustomerInfo(payload.customer),
|
||||
},
|
||||
body: payload.items.map(item => ({
|
||||
sstid: item.sku,
|
||||
vra: item.sku_vat,
|
||||
// sstt: item.unit_type,
|
||||
fee: String(item.unit_price),
|
||||
dis: String(item.discount),
|
||||
mu: item.measure_unit,
|
||||
am: String(item.quantity),
|
||||
consfee: '0',
|
||||
bros: '0',
|
||||
spro: '0',
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
mapRevokeToNamaRequestDto(
|
||||
payload: TspProviderRevokePayloadDto,
|
||||
): NamaProviderRevokeRequestDto {
|
||||
@@ -76,7 +113,7 @@ export class NamaProviderUtils {
|
||||
header: {
|
||||
inno: payload.invoice_number.toString(),
|
||||
ins: this.mapTspProviderRequestType(TspProviderRequestType.REVOKE),
|
||||
irtaxid: payload.last_attempt_tax_id,
|
||||
irtaxid: payload.last_tax_id,
|
||||
indatim: new Date().getTime() + '',
|
||||
},
|
||||
}
|
||||
@@ -84,9 +121,9 @@ export class NamaProviderUtils {
|
||||
|
||||
private mapTspProviderRequestType(type: TspProviderRequestType) {
|
||||
switch (type) {
|
||||
case TspProviderRequestType.MAIN:
|
||||
case TspProviderRequestType.ORIGINAL:
|
||||
return '1'
|
||||
case TspProviderRequestType.UPDATE:
|
||||
case TspProviderRequestType.CORRECTION:
|
||||
return '2'
|
||||
case TspProviderRequestType.REVOKE:
|
||||
return '3'
|
||||
|
||||
Reference in New Issue
Block a user