feat(partners): add utility functions for partner business activity allocation limits and remaining licenses

- Implemented `getPartnerBusinessActivityAllocationLimits` to retrieve allocation limits for a partner's business activity.
- Added `ensurePartnerBusinessActivityHasRemainingAllocation` to validate remaining allocation credits.
- Created `getPartnerRemainingLicenses` to count remaining licenses for a partner.
- Developed `getPartnerFirstRemainingLicense` to fetch the first unused license for a partner.
- Introduced `ensurePartnerHasRemainingLicense` to ensure a partner has at least one unused license.
This commit is contained in:
2026-04-24 23:02:05 +03:30
parent 9b652a3603
commit 12506de863
43 changed files with 4645 additions and 2196 deletions
@@ -24,8 +24,13 @@ export class PartnerActivatedLicensesService {
id: true,
starts_at: true,
expires_at: true,
license_id: true,
created_at: true,
account_allocations: {
select: {
id: true,
account_id: true,
},
},
business_activity: {
select: {
id: true,
@@ -46,7 +51,25 @@ export class PartnerActivatedLicensesService {
}),
])
return ResponseMapper.paginate(licenses, {
const mappedLicenses = licenses.map(license => {
const { account_allocations, business_activity, ...rest } = license
return {
...rest,
license: {
accounts_limit: account_allocations.length,
allocated_account_count: account_allocations.filter(
allocation => allocation.account_id !== null,
).length,
},
business_activity: {
...business_activity,
consumer_name: `${business_activity.consumer.first_name} ${business_activity.consumer.last_name}`,
},
}
})
return ResponseMapper.paginate(mappedLicenses, {
page,
pageSize,
count,
@@ -1,4 +1,4 @@
import { PartnerAccountQuotaAllocationWhereInput } from '@/generated/prisma/models'
import { PartnerAccountQuotaCreditWhereInput } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
@@ -8,14 +8,14 @@ export class PartnerAllocatedAccountsService {
constructor(private readonly prisma: PrismaService) {}
async findAll(partner_id: string, page = 1, pageSize = 10) {
const defaultWhere: PartnerAccountQuotaAllocationWhereInput = {
const defaultWhere: PartnerAccountQuotaCreditWhereInput = {
charge_transaction: {
partner_id,
},
}
const [allocations, count] = await this.prisma.$transaction(async tx => [
await tx.partnerAccountQuotaAllocation.findMany({
await tx.partnerAccountQuotaCredit.findMany({
where: defaultWhere,
skip: (page - 1) * pageSize,
take: pageSize,
@@ -24,7 +24,6 @@ export class PartnerAllocatedAccountsService {
created_at: true,
updated_at: true,
charge_transaction_id: true,
license_id: true,
charge_transaction: {
select: {
id: true,
@@ -33,21 +32,22 @@ export class PartnerAllocatedAccountsService {
created_at: true,
},
},
license: {
allocation: {
select: {
id: true,
accounts_limit: true,
activation: {
account: {
select: {
id: true,
business_activity_id: true,
pos: {
select: {
id: true,
},
},
},
},
},
},
},
}),
await tx.partnerAccountQuotaAllocation.count({
await tx.partnerAccountQuotaCredit.count({
where: defaultWhere,
}),
])
@@ -3,9 +3,9 @@ import {
isTrackingCodeUniqueViolation,
} from '@/common/utils/tracking-code-generator.util'
import {
PartnerAccountQuotaAllocationCreateInput,
PartnerAccountQuotaChargeTransactionSelect,
PartnerAccountQuotaChargeTransactionWhereInput,
PartnerAccountQuotaCreditCreateInput,
} from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
@@ -40,10 +40,10 @@ export class PartnerAccountChargeTransactionService {
purchased_count: true,
_count: {
select: {
allocations: {
credits: {
where: {
license_id: {
not: null,
allocation: {
isNot: null,
},
},
},
@@ -120,9 +120,9 @@ export class PartnerAccountChargeTransactionService {
throw new BadRequestException('متاسفانه مشکلی پیش آمده است.')
}
const accountCreationPromises: any[] = []
const creditCreationPromises: any[] = []
for (let i = 0; i < data.quantity; i++) {
const account: PartnerAccountQuotaAllocationCreateInput = {
const credit: PartnerAccountQuotaCreditCreateInput = {
charge_transaction: {
connect: {
id: transaction.id,
@@ -130,20 +130,16 @@ export class PartnerAccountChargeTransactionService {
},
}
accountCreationPromises.push(
tx.partnerAccountQuotaAllocation.create({ data: account }),
creditCreationPromises.push(
tx.partnerAccountQuotaCredit.create({ data: credit }),
)
}
const createdAllocations = await Promise.all(accountCreationPromises)
const createdCredits = await Promise.all(creditCreationPromises)
if (
createdAllocations.some(
createdAllocation => createdAllocation.activation_id === null,
)
) {
if (createdCredits.some(createdCredit => createdCredit.activation_id === null)) {
throw new BadRequestException('متاسفانه مشکلی پیش آمده است. ')
}
return { transaction, createdAllocations }
return { transaction, createdCredits }
})
} catch (error) {
throw error
@@ -2,7 +2,6 @@ import { PrismaModule } from '@/prisma/prisma.module'
import { Module } from '@nestjs/common'
import { AdminPartnerActivatedLicensesModule } from './activatedLicenses/activatedLicenses.module'
import { AdminPartnerAllocatedAccountsModule } from './allocatedAccounts/allocatedAccounts.module'
import { PartnerAccountChargeTransactionModule } from './chargeAccountQoutaTransactions/chargeAccountQuotaTransactions.module'
import { AdminPartnerLicenseChargeTransactionModule } from './chargedLicenseTransactions/chargedLicenseTransactions.module'
import { AdminPartnerAccountsModule } from './partnerAccounts/accounts.module'
@@ -14,7 +13,7 @@ import { PartnersService } from './partners.service'
PrismaModule,
AdminPartnerLicenseChargeTransactionModule,
AdminPartnerActivatedLicensesModule,
AdminPartnerAllocatedAccountsModule,
// AdminPartnerAllocatedAccountsModule,
PartnerAccountChargeTransactionModule,
AdminPartnerAccountsModule,
],
+100 -103
View File
@@ -1,5 +1,4 @@
import { PasswordUtil } from '@/common/utils/password.util'
import { LicenseChargeTransaction } from '@/generated/prisma/client'
import {
AccountStatus,
AccountType,
@@ -14,6 +13,7 @@ import { CreatePartnerDto, UpdatePartnerDto } from './dto/partner.dto'
@Injectable()
export class PartnersService {
private now = new Date().getTime()
constructor(private readonly prisma: PrismaService) {}
private readonly defaultSelect: PartnerSelect = {
@@ -22,40 +22,107 @@ export class PartnersService {
code: true,
status: true,
created_at: true,
license_charge_transactions: {
select: {
activation_expires_at: true,
purchased_count: true,
_count: {
select: {
licenses: {
where: {
activation: {
isNot: null,
},
},
},
},
},
},
},
license_renew_charge_transactions: {
select: {
activation_expires_at: true,
purchased_count: true,
_count: {
select: {
license_renews: {
where: {
activation: {
isNot: undefined,
},
},
},
},
},
},
},
account_quota_charge_transactions: {
select: {
activation_expires_at: true,
purchased_count: true,
_count: {
select: {
credits: {
where: {
allocation_id: {
not: null,
},
},
},
},
},
},
},
}
private readonly separateLicenseCount = (
transactions: LicenseChargeTransaction[] | null,
) => {
function toDateOnlyString(date) {
return date.toISOString().slice(0, 10)
}
private readonly mapPartner = (partner: any) => {
const {
license_charge_transactions,
account_quota_charge_transactions,
license_renew_charge_transactions,
...rest
} = partner
const startOfTodayDate = toDateOnlyString(new Date())
const account_quota_status = { total: 0, used: 0, expired: 0 }
account_quota_charge_transactions.forEach((account_quota_charge_transaction: any) => {
const total = account_quota_charge_transaction.purchased_count
const used = account_quota_charge_transaction._count.credits
account_quota_status.total += total
account_quota_status.used += used
account_quota_status.expired +=
account_quota_charge_transaction.activation_expires_at.getTime() <= this.now
? total - used
: 0
})
const used = transactions?.reduce((sum, cur) => {
const license = cur as any
return sum + license.licenses.filter(license => license.activation).length || 0
}, 0)
const total = transactions?.reduce((sum, cur) => {
const license = cur as any
return sum + license.licenses.length || 0
}, 0)
const expired = transactions?.reduce((sum, cur) => {
const license = cur as any
const activationExpiresDate = toDateOnlyString(license.activation_expires_at)
if (startOfTodayDate > activationExpiresDate)
return sum + license.licenses.filter(license => !license.activation).length || 0
return sum
}, 0)
const licenses_status = { total: 0, used: 0, expired: 0 }
license_charge_transactions.forEach((license_charge_transaction: any) => {
const total = license_charge_transaction.purchased_count
const used = license_charge_transaction._count.licenses
licenses_status.total += total
licenses_status.used += used
licenses_status.expired +=
license_charge_transaction.activation_expires_at.getTime() <= this.now
? total - used
: 0
})
const license_renew_status = { total: 0, used: 0, expired: 0 }
license_renew_charge_transactions.forEach((license_renew_charge_transaction: any) => {
const total = license_renew_charge_transaction.purchased_count
const used = license_renew_charge_transaction._count.license_renews
license_renew_status.total += total
license_renew_status.used += used
license_renew_status.expired +=
license_renew_charge_transaction.activation_expires_at.getTime() <= this.now
? total - used
: 0
})
return {
total,
used,
expired,
...rest,
licenses_status,
license_renew_status,
account_quota_status,
}
}
@@ -64,88 +131,18 @@ export class PartnersService {
select: this.defaultSelect,
})
// const mappedPartners = partners.map(partner => {
// const { license_charge_transactions, account_quota_charge_transactions, ...rest } = partner
// const a = { total: 0, used: 0, expired: 0 }
const mappedPartners = partners.map(this.mapPartner)
// account_quota_charge_transactions.forEach(account_quota_charge_transaction => {
// a.total += account_quota_charge_transaction.
// })
// return {
// ...rest,
// licenses_status: this.separateLicenseCount(license_charge_transactions),
// }
// })
return ResponseMapper.list(partners)
return ResponseMapper.list(mappedPartners)
}
async findOne(id: string) {
const partner = await this.prisma.partner.findUniqueOrThrow({
where: { id },
select: {
...this.defaultSelect,
license_charge_transactions: {
select: {
purchased_count: true,
_count: {
select: {
licenses: {
where: {
activation: {
isNot: null,
},
},
},
},
},
},
},
account_quota_charge_transactions: {
select: {
purchased_count: true,
_count: {
select: {
allocations: {
where: {
license_id: null,
},
},
},
},
},
},
},
select: this.defaultSelect,
})
const { license_charge_transactions, account_quota_charge_transactions, ...rest } =
partner
const account_quota_status = { total: 0, used: 0, expired: 0 }
account_quota_charge_transactions.forEach(account_quota_charge_transaction => {
account_quota_status.total += account_quota_charge_transaction.purchased_count
account_quota_status.used += account_quota_charge_transaction._count.allocations
account_quota_status.expired +=
account_quota_charge_transaction.purchased_count -
account_quota_charge_transaction._count.allocations
})
const licenses_status = { total: 0, used: 0, expired: 0 }
license_charge_transactions.forEach(license_charge_transaction => {
licenses_status.total += license_charge_transaction.purchased_count
licenses_status.used += license_charge_transaction._count.licenses
licenses_status.expired +=
license_charge_transaction.purchased_count -
license_charge_transaction._count.licenses
})
const mappedPartner = {
...rest,
licenses_status,
account_quota_status,
}
return ResponseMapper.single(mappedPartner)
return ResponseMapper.single(this.mapPartner(partner))
}
async create(data: CreatePartnerDto) {