feat: add DTOs and services for tax switch integration

- Created SendBulkSaleInvoicesDto for handling bulk sale invoice requests.
- Implemented TaxSwitchSendPayloadDto and related DTOs for tax switch item payloads and results.
- Developed SalesInvoiceTaxSwitchService to manage tax switch operations, including sending and retrieving tax information.
- Added SalesInvoiceTaxService for handling sales invoice tax logic, including bulk sending and persistence of results.
- Introduced NamaTaxSwitchAdapter to interact with the tax switch service, simulating external API responses.
- Created SendBulkSalesInvoicesDto for POS module to handle bulk sales invoice requests.
This commit is contained in:
2026-04-27 22:11:05 +03:30
parent dee96b6e91
commit 58a7c359d8
68 changed files with 7896 additions and 3534 deletions
@@ -9,41 +9,13 @@ import { ResponseMapper } from 'common/response/response-mapper'
export class AdminConsumersService {
constructor(private readonly prisma: PrismaService) {}
private readonly now = new Date()
private readonly defaultSelect: ConsumerSelect = {
id: true,
type: true,
...QUERY_CONSTANTS.CONSUMER.infoSelect,
...QUERY_CONSTANTS.CONSUMER.activeBusinessCount,
status: true,
created_at: true,
_count: {
select: {
business_activities: {
where: {
license_activation: {
OR: [
{
expires_at: {
gt: this.now,
},
},
{
license_renews: {
some: {
expires_at: {
gt: this.now,
},
},
},
},
],
},
},
},
},
},
}
async findAll() {
@@ -1,3 +1,4 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { ComplexSelect } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
@@ -53,8 +54,6 @@ export class BusinessActivityComplexesService {
data: CreateConsumerComplexDto,
) {
const complex = await this.prisma.$transaction(async tx => {
const now = new Date()
const relatedLicense = await tx.licenseAccountAllocation.findFirst({
where: {
license_activation: {
@@ -62,22 +61,7 @@ export class BusinessActivityComplexesService {
id: business_activity_id,
consumer_id,
},
OR: [
{
expires_at: {
gte: now,
},
},
{
license_renews: {
some: {
expires_at: {
gte: now,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
},
account_id: null,
},
@@ -1,3 +1,4 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { PasswordUtil } from '@/common/utils/password.util'
import {
AccountStatus,
@@ -189,22 +190,7 @@ export class ComplexPosesService {
business_activity: {
consumer_id,
},
OR: [
{
expires_at: {
gte: now,
},
},
{
license_renews: {
some: {
expires_at: {
gte: now,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
},
},
select: {
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger'
import { ArrayMinSize, IsArray, IsString } from 'class-validator'
export class SendBulkSaleInvoicesDto {
@ApiProperty({ type: [String], minItems: 1 })
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
invoice_ids: string[]
}
@@ -1,8 +1,12 @@
import { TokenAccount } from '@/common/decorators/tokenInfo.decorator'
import { Controller, Get, Param } from '@nestjs/common'
import { Body, Controller, Get, Param, Post } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import type {
SaleInvoicesServiceFindAllResponseDto,
SaleInvoicesServiceFindOneResponseDto,
} from './dto/saleInvoices-response.dto'
import { SendBulkSaleInvoicesDto } from './dto/send-saleInvoices.dto'
import { SaleInvoicesService } from './saleInvoices.service'
import type { SaleInvoicesServiceFindAllResponseDto, SaleInvoicesServiceFindOneResponseDto } from './dto/saleInvoices-response.dto'
@ApiTags('ConsumerSaleInvoices')
@Controller('consumer/sale-invoices')
@@ -10,12 +14,30 @@ export class StatisticsController {
constructor(private readonly service: SaleInvoicesService) {}
@Get('')
async findAll(@TokenAccount('userId') consumerId: string): Promise<SaleInvoicesServiceFindAllResponseDto> {
async findAll(
@TokenAccount('userId') consumerId: string,
): Promise<SaleInvoicesServiceFindAllResponseDto> {
return this.service.findAll(consumerId)
}
@Get(':id')
async findOne(@TokenAccount('userId') consumerId: string, @Param('id') id: string): Promise<SaleInvoicesServiceFindOneResponseDto> {
async findOne(
@TokenAccount('userId') consumerId: string,
@Param('id') id: string,
): Promise<SaleInvoicesServiceFindOneResponseDto> {
return this.service.findOne(consumerId, id)
}
@Post(':id/send_tax')
async send(@TokenAccount('userId') consumerId: string, @Param('id') id: string) {
return this.service.send(consumerId, id)
}
@Post('send_tax_bulk')
async sendBulk(
@TokenAccount('userId') consumerId: string,
@Body() data: SendBulkSaleInvoicesDto,
) {
return this.service.sendBulk(consumerId, data.invoice_ids)
}
}
@@ -2,11 +2,19 @@ import { PrismaModule } from '@/prisma/prisma.module'
import { Module } from '@nestjs/common'
import { StatisticsController } from './saleInvoices.controller'
import { SaleInvoicesService } from './saleInvoices.service'
import { SalesInvoiceTaxSwitchService } from './tax/sales-invoice-tax-switch.service'
import { SalesInvoiceTaxService } from './tax/sales-invoice-tax.service'
import { NamaTaxSwitchAdapter } from './tax/switch/nama-tax-switch.adapter'
@Module({
imports: [PrismaModule],
controllers: [StatisticsController],
providers: [SaleInvoicesService],
providers: [
SaleInvoicesService,
SalesInvoiceTaxService,
SalesInvoiceTaxSwitchService,
NamaTaxSwitchAdapter,
],
exports: [SaleInvoicesService],
})
export class ConsumerSaleInvoicesModule {}
@@ -4,12 +4,16 @@ import {
SalesInvoiceWhereUniqueInput,
} from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { BadRequestException, Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
import { SalesInvoiceTaxService } from './tax/sales-invoice-tax.service'
@Injectable()
export class SaleInvoicesService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private salesInvoiceTaxService: SalesInvoiceTaxService,
) {}
private readonly defaultSelect: SalesInvoiceSelect = {
id: true,
@@ -45,6 +49,21 @@ export class SaleInvoicesService {
},
},
},
fiscal: {
select: {
id: true,
attempts: {
orderBy: {
created_at: 'asc',
},
take: 1,
select: {
id: true,
status: true,
},
},
},
},
}
async findAll(consumer_id: string, page = 1, perPage = 10) {
@@ -139,4 +158,26 @@ export class SaleInvoicesService {
})
return ResponseMapper.single(invoice)
}
async send(consumer_id: string, invoice_id: string) {
await this.salesInvoiceTaxService.send(consumer_id, invoice_id)
return ResponseMapper.single({
invoice_id,
sent_to_tax: true,
})
}
async sendBulk(consumer_id: string, invoiceIds: string[]) {
if (!invoiceIds.length) {
throw new BadRequestException('لیست شناسه فاکتورها نمی‌تواند خالی باشد.')
}
await this.salesInvoiceTaxService.sendBulk(consumer_id, invoiceIds)
return ResponseMapper.single({
invoice_ids: invoiceIds,
sent_to_tax: true,
})
}
}
@@ -0,0 +1,169 @@
import { ApiProperty } from '@nestjs/swagger'
import { Type } from 'class-transformer'
import {
IsArray,
IsDateString,
IsEnum,
IsNumber,
IsObject,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator'
export enum TaxSendStatus {
SENT = 'SENT',
FAILED = 'FAILED',
PENDING = 'PENDING',
}
export class TaxSwitchSendItemPayloadDto {
@ApiProperty()
@IsString()
invoice_item_id: string
@ApiProperty()
@IsNumber()
quantity: number
@ApiProperty()
@IsNumber()
unit_price: number
@ApiProperty()
@IsNumber()
total_amount: number
@ApiProperty()
@IsString()
unit_type: string
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
good_id?: string | null
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
service_id?: string | null
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
payload?: unknown
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
good_snapshot?: unknown
}
export class TaxSwitchSendPayloadDto {
@ApiProperty()
@IsString()
invoice_id: string
@ApiProperty()
@IsString()
invoice_code: string
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsDateString()
invoice_date: string | null
@ApiProperty()
@IsNumber()
total_amount: number
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
provider_code?: string | null
@ApiProperty({ type: [TaxSwitchSendItemPayloadDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => TaxSwitchSendItemPayloadDto)
items: TaxSwitchSendItemPayloadDto[]
}
export class TaxSwitchSendItemResultDto {
@ApiProperty()
@IsString()
invoice_item_id: string
@ApiProperty({ enum: TaxSendStatus })
@IsEnum(TaxSendStatus)
status: TaxSendStatus
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
tax_id?: string | null
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
request_payload?: unknown
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
response_payload?: unknown
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
error_message?: string | null
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsDateString()
sent_at?: string | null
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsDateString()
received_at?: string | null
}
export class TaxSwitchBulkSendResultDto {
@ApiProperty()
@IsString()
invoice_id: string
@ApiProperty({ type: [TaxSwitchSendItemResultDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => TaxSwitchSendItemResultDto)
items: TaxSwitchSendItemResultDto[]
}
export class TaxSwitchGetResultDto {
@ApiProperty()
@IsString()
tax_id: string
@ApiProperty({ enum: TaxSendStatus })
@IsEnum(TaxSendStatus)
status: TaxSendStatus
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
response_payload?: unknown
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsDateString()
received_at?: string | null
}
export interface ITaxSwitchAdapter {
readonly code: string
send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]>
sendBulk(payloads: TaxSwitchSendPayloadDto[]): Promise<TaxSwitchBulkSendResultDto[]>
get(taxId: string): Promise<TaxSwitchGetResultDto>
}
@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common'
import {
TaxSwitchBulkSendResultDto,
TaxSwitchGetResultDto,
TaxSwitchSendItemResultDto,
TaxSwitchSendPayloadDto,
} from './dto/tax-switch.dto'
import { NamaTaxSwitchAdapter } from './switch/nama-tax-switch.adapter'
@Injectable()
export class SalesInvoiceTaxSwitchService {
constructor(private readonly namaAdapter: NamaTaxSwitchAdapter) {}
private resolveSwitch(providerCode?: string | null) {
const normalizedCode = providerCode?.trim().toUpperCase() || ''
switch (normalizedCode) {
case 'NAMA':
default:
return this.namaAdapter
}
}
async send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]> {
const adapter = this.resolveSwitch(payload.provider_code)
return adapter.send(payload)
}
async sendBulk(
payloads: TaxSwitchSendPayloadDto[],
): Promise<TaxSwitchBulkSendResultDto[]> {
const groupedByProvider = new Map<string, TaxSwitchSendPayloadDto[]>()
for (const payload of payloads) {
const key = payload.provider_code?.trim().toUpperCase() || 'NAMA'
const currentGroup = groupedByProvider.get(key) || []
currentGroup.push(payload)
groupedByProvider.set(key, currentGroup)
}
const result: TaxSwitchBulkSendResultDto[] = []
for (const [providerCode, groupedPayloads] of groupedByProvider.entries()) {
const adapter = this.resolveSwitch(providerCode)
const providerResult = await adapter.sendBulk(groupedPayloads)
result.push(...providerResult)
}
return result
}
async get(
providerCode: string | null | undefined,
taxId: string,
): Promise<TaxSwitchGetResultDto> {
const adapter = this.resolveSwitch(providerCode)
return adapter.get(taxId)
}
}
@@ -0,0 +1,301 @@
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable, NotFoundException } from '@nestjs/common'
import { Prisma } from 'generated/prisma/client'
import {
TaxSendStatus,
TaxSwitchGetResultDto,
TaxSwitchSendItemResultDto,
TaxSwitchSendPayloadDto,
} from './dto/tax-switch.dto'
import { SalesInvoiceTaxSwitchService } from './sales-invoice-tax-switch.service'
type TaxRow = {
id: string
retry_count: number
}
type ItemTaxProviderRow = {
provider_code: string | null
tax_id: string | null
}
@Injectable()
export class SalesInvoiceTaxService {
constructor(
private readonly prisma: PrismaService,
private readonly taxSwitchService: SalesInvoiceTaxSwitchService,
) {}
async send(consumer_id: string, invoice_id: string): Promise<void> {
const posId = await this.getPosId(consumer_id, invoice_id)
const payload = await this.buildPayload(invoice_id, posId)
const itemResults = await this.trySend(payload)
await this.persistAttemptResults(itemResults)
}
async sendBulk(consumer_id: string, invoice_ids: string[]): Promise<void> {
if (!invoice_ids.length) return
const payloads: TaxSwitchSendPayloadDto[] = []
for (const invoiceId of invoice_ids) {
const posId = await this.getPosId(consumer_id, invoiceId)
payloads.push(await this.buildPayload(invoiceId, posId))
}
const bulkResult = await this.taxSwitchService.sendBulk(payloads)
const allItemResults = bulkResult.flatMap(result => result.items)
await this.persistAttemptResults(allItemResults)
}
async get(invoiceItemId: string, posId: string): Promise<TaxSwitchGetResultDto> {
const rows = await this.prisma.$queryRaw<ItemTaxProviderRow[]>(Prisma.sql`
SELECT p.code AS provider_code, t.tax_id AS tax_id
FROM sales_invoice_item_taxes t
INNER JOIN sales_invoice_items si ON si.id = t.invoice_item_id
INNER JOIN sales_invoices s ON s.id = si.invoice_id
INNER JOIN poses pz ON pz.id = s.pos_id
LEFT JOIN providers p ON p.id = pz.provider_id
WHERE t.invoice_item_id = ${invoiceItemId} AND s.pos_id = ${posId}
LIMIT 1
`)
if (!rows.length || !rows[0].tax_id) {
throw new NotFoundException('Tax id for this invoice item was not found.')
}
return this.taxSwitchService.get(rows[0].provider_code, rows[0].tax_id)
}
private async getPosId(consumer_id: string, invoice_id: string): Promise<string> {
const now = new Date()
const saleInvoice = await this.prisma.salesInvoice.findUnique({
where: {
id: invoice_id,
pos: {
complex: {
business_activity: {
consumer_id,
},
},
},
},
select: {
pos: {
select: {
id: true,
complex: {
select: {
business_activity: {
select: {
name: true,
license_activation: {
select: {
expires_at: true,
license_renews: {
select: {
expires_at: true,
},
},
},
},
},
},
},
},
},
},
},
})
if (!saleInvoice) {
throw new NotFoundException('متاسفانه فاکتور مورد نظر یافت نشد.')
}
const { license_activation, name: businessName } =
saleInvoice.pos.complex.business_activity
let expired = !license_activation || false
if (license_activation) {
const { expires_at, license_renews } = license_activation
if (expires_at < now) {
for (const renew of license_renews) {
if (renew.expires_at > now) {
expired = false
break
}
}
}
}
if (expired) {
throw new NotFoundException(`متاسفانه مجوز ${businessName} منقضی شده است.`)
}
return saleInvoice.pos.id
}
private async buildPayload(
invoiceId: string,
posId: string,
): Promise<TaxSwitchSendPayloadDto> {
const invoice = await this.prisma.salesInvoice.findFirst({
where: {
id: invoiceId,
pos_id: posId,
},
select: {
id: true,
code: true,
total_amount: true,
invoice_date: true,
items: {
select: {
id: true,
quantity: true,
unit_price: true,
total_amount: true,
unit_type: true,
good_id: true,
service_id: true,
payload: true,
good_snapshot: true,
},
},
pos: {
select: {
provider: {
select: {
code: true,
},
},
},
},
},
})
if (!invoice) {
throw new NotFoundException('Sales invoice was not found.')
}
return {
invoice_id: invoice.id,
invoice_code: invoice.code,
invoice_date: invoice.invoice_date ? invoice.invoice_date.toISOString() : null,
total_amount: Number(invoice.total_amount),
provider_code: invoice.pos.provider?.code || null,
items: invoice.items.map(item => ({
invoice_item_id: item.id,
quantity: Number(item.quantity),
unit_price: Number(item.unit_price),
total_amount: Number(item.total_amount),
unit_type: item.unit_type,
good_id: item.good_id,
service_id: item.service_id,
payload: item.payload,
good_snapshot: item.good_snapshot,
})),
}
}
private async trySend(
payload: TaxSwitchSendPayloadDto,
): Promise<TaxSwitchSendItemResultDto[]> {
try {
return await this.taxSwitchService.send(payload)
} catch (error: any) {
const message = error?.message || 'Unexpected tax switch error.'
const now = new Date()
return payload.items.map(item => ({
invoice_item_id: item.invoice_item_id,
status: TaxSendStatus.FAILED,
error_message: message,
sent_at: now.toISOString(),
received_at: now.toISOString(),
}))
}
}
private async persistAttemptResults(
itemResults: TaxSwitchSendItemResultDto[],
): Promise<void> {
if (!itemResults.length) return
await this.prisma.$transaction(async $tx => {
for (const itemResult of itemResults) {
await $tx.$executeRaw(Prisma.sql`
INSERT INTO sales_invoice_item_taxes (
id,
tax_id,
status,
retry_count,
last_attempt_at,
created_at,
updated_at,
invoice_item_id
) VALUES (
UUID(),
${itemResult.tax_id || null},
${itemResult.status},
0,
${itemResult.sent_at || new Date()},
NOW(),
NOW(),
${itemResult.invoice_item_id}
)
ON DUPLICATE KEY UPDATE
updated_at = NOW()
`)
const rows = await $tx.$queryRaw<TaxRow[]>(Prisma.sql`
SELECT id, retry_count
FROM sales_invoice_item_taxes
WHERE invoice_item_id = ${itemResult.invoice_item_id}
LIMIT 1
`)
if (!rows.length) continue
const itemTaxRow = rows[0]
const attemptNo = Number(itemTaxRow.retry_count || 0) + 1
await $tx.$executeRaw(Prisma.sql`
INSERT INTO sales_invoice_item_tax_attempts (
id,
attempt_no,
status,
tax_id,
request_payload,
response_payload,
error_message,
sent_at,
received_at,
created_at,
item_tax_id
) VALUES (
UUID(),
${attemptNo},
${itemResult.status},
${itemResult.tax_id || null},
${JSON.stringify(itemResult.request_payload ?? null)},
${JSON.stringify(itemResult.response_payload ?? null)},
${itemResult.error_message || null},
${itemResult.sent_at ? new Date(itemResult.sent_at) : new Date()},
${itemResult.received_at ? new Date(itemResult.received_at) : new Date()},
NOW(),
${itemTaxRow.id}
)
`)
await $tx.$executeRaw(Prisma.sql`
UPDATE sales_invoice_item_taxes
SET
tax_id = COALESCE(${itemResult.tax_id || null}, tax_id),
status = ${itemResult.status},
retry_count = ${attemptNo},
last_attempt_at = ${itemResult.sent_at ? new Date(itemResult.sent_at) : new Date()},
updated_at = NOW()
WHERE id = ${itemTaxRow.id}
`)
}
})
}
}
@@ -0,0 +1,69 @@
import { Injectable } from '@nestjs/common'
import {
ITaxSwitchAdapter,
TaxSendStatus,
TaxSwitchBulkSendResultDto,
TaxSwitchGetResultDto,
TaxSwitchSendItemResultDto,
TaxSwitchSendPayloadDto,
} from '../dto/tax-switch.dto'
@Injectable()
export class NamaTaxSwitchAdapter implements ITaxSwitchAdapter {
readonly code = 'NAMA'
async send(payload: TaxSwitchSendPayloadDto): Promise<TaxSwitchSendItemResultDto[]> {
return payload.items.map((item, index) => {
const sentAt = new Date()
const receivedAt = new Date(sentAt.getTime() + 50)
const externalRequest = {
invoiceCode: payload.invoice_code,
itemId: item.invoice_item_id,
quantity: item.quantity,
unitPrice: item.unit_price,
totalAmount: item.total_amount,
}
const externalResponse = {
status: 'ACCEPTED',
trackingCode: `TAX-${payload.invoice_code}-${index + 1}`,
}
return {
invoice_item_id: item.invoice_item_id,
status: TaxSendStatus.SENT,
tax_id: externalResponse.trackingCode,
request_payload: externalRequest,
response_payload: externalResponse,
sent_at: sentAt.toISOString(),
received_at: receivedAt.toISOString(),
}
})
}
async sendBulk(
payloads: TaxSwitchSendPayloadDto[],
): Promise<TaxSwitchBulkSendResultDto[]> {
const result: TaxSwitchBulkSendResultDto[] = []
for (const payload of payloads) {
const itemResults = await this.send(payload)
result.push({
invoice_id: payload.invoice_id,
items: itemResults,
})
}
return result
}
async get(taxId: string): Promise<TaxSwitchGetResultDto> {
return {
tax_id: taxId,
status: TaxSendStatus.SENT,
response_payload: {
status: 'CONFIRMED',
trackingCode: taxId,
},
received_at: new Date().toISOString(),
}
}
}
@@ -1,3 +1,4 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { BadRequestException } from '@nestjs/common'
type BusinessActivityAccountQuotaClient = {
@@ -27,31 +28,13 @@ export const getBusinessActivityRemainingAccounts = async (
): Promise<BusinessActivityRemainingAccounts> => {
const { consumer_id, business_activity_id, referenceDate = new Date() } = params
const startOfDay = new Date(referenceDate)
startOfDay.setHours(0, 0, 0, 0)
const relatedLicense = await prisma.licenseActivation.findFirst({
where: {
business_activity_id,
business_activity: {
consumer_id,
},
OR: [
{
expires_at: {
gte: startOfDay,
},
},
{
license_renews: {
some: {
expires_at: {
gte: startOfDay,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
},
select: {
license: {
@@ -1,3 +1,4 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
@@ -40,22 +41,7 @@ export class PartnerBusinessActivityAccountsChargeService {
],
},
},
OR: [
{
expires_at: {
gte: startOfDay,
},
},
{
license_renews: {
some: {
expires_at: {
gte: startOfDay,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
},
select: {
id: true,
@@ -1,3 +1,4 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { ComplexSelect, ComplexWhereInput } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
@@ -44,9 +45,24 @@ 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,
select: {
...this.defaultSelect,
_count: {
select: {
pos_list: true,
},
},
},
})
return ResponseMapper.list(complexes)
const mappedComplexes = complexes.map(complex => {
const { _count, ...rest } = complex
return {
...rest,
pos_count: _count.pos_list,
}
})
return ResponseMapper.list(mappedComplexes)
}
async findOne(
@@ -67,8 +83,6 @@ export class BusinessActivityComplexesService {
async create(partner_id: string, business_id: string, data: CreateComplexDto) {
const complex = this.prisma.$transaction(async tx => {
const now = new Date()
const relatedLicense = await tx.licenseAccountAllocation.findFirst({
where: {
license_activation: {
@@ -80,22 +94,7 @@ export class BusinessActivityComplexesService {
business_activity: {
id: business_id,
},
OR: [
{
expires_at: {
gte: now,
},
},
{
license_renews: {
some: {
expires_at: {
gte: now,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
},
account_id: null,
},
@@ -1,3 +1,5 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { consumerRelatedPartner } from '@/common/queryConstants/consumer'
import { PasswordUtil } from '@/common/utils/password.util'
import {
AccountStatus,
@@ -77,7 +79,7 @@ export class ComplexPosesService {
business_activity: {
id: business_activity_id,
consumer: {
partner_id,
...consumerRelatedPartner(partner_id),
},
},
},
@@ -97,7 +99,9 @@ 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),
where: {
...this.defaultWhere(partner_id, complex_id, business_activity_id),
},
select: this.defaultSelect,
})
@@ -126,29 +130,12 @@ export class ComplexPosesService {
data: CreatePosDto,
) {
const pos = this.prisma.$transaction(async tx => {
const now = new Date()
const activeAccountAllocation = await tx.licenseAccountAllocation.findFirst({
where: {
account_id: null,
license_activation: {
business_activity_id,
OR: [
{
expires_at: {
gte: now,
},
},
{
license_renews: {
some: {
expires_at: {
gte: now,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(),
license: {
charge_transaction: {
partner_id,
@@ -10,6 +10,14 @@ export class CreateBusinessActivitiesDto {
@ApiProperty({ required: true })
economic_code: string
@IsString()
@ApiProperty({ required: true })
fiscal_id: string
@IsString()
@ApiProperty({ required: true })
partner_token: string
@IsString()
@ApiProperty({ required: true })
guild_id: string
@@ -31,9 +31,10 @@ export class PartnerConsumersService {
defaultSelect: ConsumerSelect = {
id: true,
...QUERY_CONSTANTS.CONSUMER.infoSelect,
status: true,
created_at: true,
...QUERY_CONSTANTS.CONSUMER.infoSelect,
...QUERY_CONSTANTS.CONSUMER.activeBusinessCount,
}
private defaultWhere = (partner_id: string): ConsumerWhereInput => ({
@@ -119,8 +120,7 @@ export class PartnerConsumersService {
throw new BadRequestException(`تعداد لایسنس‌های فعلی شما به پایان رسیده است.`)
}
const { username, password, customer, ...rest } = data
const { individual, legal } = customer
const { username, password, individual, legal, ...rest } = data
const createConsumerData: ConsumerCreateInput = {
...rest,
@@ -228,7 +228,15 @@ export class PartnerConsumersService {
...(this.defaultWhere(partner_id) as any),
id,
},
data,
data: {
status: data.status,
legal: {
update: data.legal,
},
individual: {
update: data.individual,
},
},
})
}
}
@@ -16,12 +16,13 @@ export class CreateConsumerDto {
@ApiProperty({ required: true })
password: string
@ApiProperty({ required: true })
@ApiProperty({ required: false })
@IsObject()
customer: {
individual?: Omit<ConsumerIndividual, 'partner_id' | 'consumer_id'>
legal?: Omit<ConsumerLegal, 'partner_id' | 'consumer_id'>
}
individual?: Omit<ConsumerIndividual, 'partner_id' | 'consumer_id'>
@ApiProperty({ required: false })
@IsObject()
legal?: Omit<ConsumerLegal, 'partner_id' | 'consumer_id'>
}
export class UpdateConsumerDto extends OmitType(PartialType(CreateConsumerDto), [
'password',
@@ -26,8 +26,6 @@ export interface PartnerLicenseActivationChargeTransactionResponseDto {
export interface PartnerLicenseActivationLicenseResponseDto {
id: string
accounts_limit: number
charge_transaction: PartnerLicenseActivationChargeTransactionResponseDto
}
export interface PartnerLicenseActivationCountResponseDto {
@@ -42,7 +40,7 @@ export interface PartnerLicenseActivationResponseDto {
updated_at: Date
business_activity: PartnerLicenseActivationBusinessActivityResponseDto
license: PartnerLicenseActivationLicenseResponseDto
_count: PartnerLicenseActivationCountResponseDto
account_allocation_count: Number
}
export type PartnerLicensesServiceFindAllResponseDto = Awaited<
@@ -1,6 +1,5 @@
import {
PartnerLicenseActivationBusinessActivityResponseDto,
PartnerLicenseActivationChargeTransactionResponseDto,
PartnerLicenseActivationConsumerResponseDto,
PartnerLicenseActivationCountResponseDto,
PartnerLicenseActivationLicenseResponseDto,
@@ -35,8 +34,6 @@ type PartnerLicenseActivationChargeTransactionQueryResult = {
type PartnerLicenseActivationLicenseQueryResult = {
id: string
accounts_limit: number
charge_transaction: PartnerLicenseActivationChargeTransactionQueryResult
}
type PartnerLicenseActivationQueryResult = {
@@ -62,7 +59,9 @@ export const mapPartnerLicenseActivationConsumer = (
first_name: individual?.first_name ?? null,
last_name: individual?.last_name ?? null,
mobile_number: individual?.mobile_number ?? null,
name: legal?.name ?? null,
name: individual
? `${individual?.first_name} ${individual?.last_name}`
: (legal?.name ?? null),
registration_code: legal?.registration_code ?? null,
}
}
@@ -78,17 +77,8 @@ export const mapPartnerLicenseActivation = (
),
}
const chargeTransaction: PartnerLicenseActivationChargeTransactionResponseDto = {
id: licenseActivation.license.charge_transaction.id,
tracking_code: licenseActivation.license.charge_transaction.tracking_code,
activation_expires_at:
licenseActivation.license.charge_transaction.activation_expires_at,
}
const license: PartnerLicenseActivationLicenseResponseDto = {
id: licenseActivation.license.id,
accounts_limit: licenseActivation.license.accounts_limit,
charge_transaction: chargeTransaction,
}
return {
@@ -99,6 +89,6 @@ export const mapPartnerLicenseActivation = (
updated_at: licenseActivation.updated_at,
business_activity: businessActivity,
license,
_count: licenseActivation._count,
account_allocation_count: licenseActivation._count.account_allocations,
}
}
@@ -11,10 +11,7 @@ export class PartnerLicensesService {
constructor(private readonly prisma: PrismaService) {}
async findAll(
partner_id: string,
params: PartnerLicensesFilterDto = {},
) {
async findAll(partner_id: string, params: PartnerLicensesFilterDto = {}) {
const { perPage, page, consumer_name, consumer_mobile, expires_from, expires_to } =
params
@@ -137,14 +134,6 @@ export class PartnerLicensesService {
license: {
select: {
id: true,
accounts_limit: true,
charge_transaction: {
select: {
id: true,
tracking_code: true,
activation_expires_at: true,
},
},
},
},
_count: {
@@ -1,3 +1,5 @@
import { QUERY_CONSTANTS } from '@/common/queryConstants'
import { consumerRelatedPartner } from '@/common/queryConstants/consumer'
import { BadRequestException } from '@nestjs/common'
type PartnerBusinessActivityAllocationClient = {
@@ -36,26 +38,9 @@ const getPartnerBusinessActivityActiveActivation = async (
where: {
business_activity_id,
business_activity: {
consumer: {
partner_id,
},
...consumerRelatedPartner(partner_id),
},
OR: [
{
expires_at: {
gte: startOfDay,
},
},
{
license_renews: {
some: {
expires_at: {
gte: startOfDay,
},
},
},
},
],
...QUERY_CONSTANTS.LICENSE_ACTIVATION.activeOnDate(startOfDay),
},
select: includeAccountAllocations
? {
@@ -1,6 +1,7 @@
import { ApiProperty, PartialType } from '@nestjs/swagger'
import {
ArrayMinSize,
IsBoolean,
IsDateString,
IsEnum,
IsNumber,
@@ -42,6 +43,11 @@ export class CreateSalesInvoiceDto {
@IsString()
notes?: string
@ApiProperty({ required: false, default: false })
@IsOptional()
@IsBoolean()
send_to_tax?: boolean
@ApiProperty({ required: true, default: CustomerType.UNKNOWN })
@IsEnum(CustomerType)
customer_type: CustomerType
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger'
import { ArrayMinSize, IsArray, IsString } from 'class-validator'
export class SendBulkSalesInvoicesDto {
@ApiProperty({ type: [String], minItems: 1 })
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
invoice_ids: string[]
}
@@ -1,9 +1,9 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common'
import { PosInfo } from '@/common/decorators/posInfo.decorator'
import type { IPosPayload } from '@/common/models/posPayload.model'
import { CreateSalesInvoiceDto } from './dto/create-sales-invoice.dto'
import { SalesInvoicesService } from './sales-invoices.service'
import type { IPosPayload } from '@/common/models/posPayload.model'
@Controller('pos/sales_invoices')
export class SalesInvoicesController {
@@ -23,4 +23,14 @@ export class SalesInvoicesController {
create(@Body() data: CreateSalesInvoiceDto, @PosInfo() posInfo: IPosPayload) {
return this.salesInvoicesService.create(data, posInfo)
}
// @Post(':id/send')
// send(@Param('id') id: string, @PosInfo() posInfo: IPosPayload) {
// return this.salesInvoicesService.send(id, posInfo)
// }
// @Post('send/bulk')
// sendBulk(@Body() data: SendBulkSalesInvoicesDto, @PosInfo() posInfo: IPosPayload) {
// return this.salesInvoicesService.sendBulk(data.invoice_ids, posInfo)
// }
}
@@ -1,9 +1,17 @@
import { Module } from '@nestjs/common'
import { SalesInvoiceTaxSwitchService } from '../../consumer/saleInvoices/tax/sales-invoice-tax-switch.service'
import { SalesInvoiceTaxService } from '../../consumer/saleInvoices/tax/sales-invoice-tax.service'
import { NamaTaxSwitchAdapter } from '../../consumer/saleInvoices/tax/switch/nama-tax-switch.adapter'
import { SalesInvoicesController } from './sales-invoices.controller'
import { SalesInvoicesService } from './sales-invoices.service'
@Module({
controllers: [SalesInvoicesController],
providers: [SalesInvoicesService],
providers: [
SalesInvoicesService,
SalesInvoiceTaxService,
SalesInvoiceTaxSwitchService,
NamaTaxSwitchAdapter,
],
})
export class PosSalesInvoicesModule {}
@@ -1,10 +1,10 @@
import { IPosPayload } from '@/common/models/posPayload.model'
import { SalesInvoiceCreateInput } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
import type { CustomerIndividual, CustomerLegal } from 'generated/prisma/client'
import { CustomerType, PaymentMethodType } from 'generated/prisma/enums'
import { SalesInvoiceTaxService } from '../../consumer/saleInvoices/tax/sales-invoice-tax.service'
import { CreateSalesInvoiceDto } from './dto/create-sales-invoice.dto'
// Define type guard for CustomerIndividual
@@ -27,7 +27,10 @@ function isCustomerLegal(customer: any): customer is CustomerLegal {
@Injectable()
export class SalesInvoicesService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private salesInvoiceTaxService: SalesInvoiceTaxService,
) {}
findAll() {
// TODO: Implement fetching all sales invoices
@@ -39,6 +42,28 @@ export class SalesInvoicesService {
return {}
}
// async send(invoiceId: string, posInfo: IPosPayload) {
// await this.salesInvoiceTaxService.send(invoiceId, posInfo.pos_id)
// return ResponseMapper.single({
// invoice_id: invoiceId,
// sent_to_tax: true,
// })
// }
// 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,
// })
// }
async create(data: CreateSalesInvoiceDto, posInfo: IPosPayload) {
data.invoice_date = new Date(data.invoice_date).toISOString() as any
@@ -135,7 +160,40 @@ export class SalesInvoicesService {
} else if (data.customer_type === CustomerType.UNKNOWN) {
}
const salesInvoiceData: SalesInvoiceCreateInput = {
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: true,
local_sku: true,
barcode: true,
pricing_model: true,
unit_type: true,
base_sale_price: true,
image_url: true,
category: {
select: {
id: true,
name: true,
},
},
},
})
: []
const goodsById = new Map(goods.map(good => [good.id, good]))
const salesInvoiceData: any = {
...invoiceData,
total_amount: data.total_amount,
code: 'INV-' + Date.now(),
@@ -150,6 +208,13 @@ export class SalesInvoicesService {
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,
unit_type: item.unit_type,
// pricing_model: item.pricingModel,
})),
@@ -192,6 +257,10 @@ export class SalesInvoicesService {
return salesInvoice
})
if (data.send_to_tax) {
await this.salesInvoiceTaxService.send(salesInvoice.id, pos_id)
}
return ResponseMapper.create(salesInvoice)
}
}