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,6 +24,12 @@ export class PartnerLicensesService {
},
},
},
account_allocations: {
select: {
id: true,
account_id: true,
},
},
license: {
select: {
id: true,
@@ -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) {
@@ -19,15 +19,7 @@ export class BusinessActivitiesService {
name: true,
},
},
complexes: {
select: {
_count: {
select: {
pos_list: true,
},
},
},
},
license_activation: {
select: {
id: true,
@@ -35,10 +27,14 @@ export class BusinessActivitiesService {
expires_at: true,
license: {
select: {
accounts_limit: true,
_count: {
activation: {
select: {
account_allocations: true,
account_allocations: {
select: {
id: true,
account_id: true,
},
},
},
},
},
@@ -50,17 +46,16 @@ export class BusinessActivitiesService {
private readonly prepareBusinessActivityResponse = (businessActivity: any) => {
const { license_activation, complexes, ...rest } = businessActivity
const { license, ...license_activation_rest } = license_activation
const { accounts_limit, _count } = license
const { account_allocations } = license.activation
return {
...rest,
license_info: {
...license_activation_rest,
accounts_limit: accounts_limit + _count.account_allocations,
allocated_account_count: complexes.reduce(
(acc: number, complex: any) => acc + complex._count.pos_list,
0,
),
accounts_limit: account_allocations.length,
allocated_account_count: account_allocations.filter(
allocation => allocation.account_id,
).length,
},
}
}
@@ -6,7 +6,6 @@ import {
POSStatus,
} from '@/generated/prisma/enums'
import { PosCreateInput, PosSelect, PosWhereInput } from '@/generated/prisma/models'
import { getBusinessActivityRemainingAccounts } from '@/modules/consumer/utils/getBusinessActivityRemainingAccounts.util'
import { PrismaService } from '@/prisma/prisma.service'
import { BadRequestException, Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
@@ -24,6 +23,15 @@ export class ComplexPosesService {
status: true,
created_at: true,
pos_type: true,
account: {
select: {
account: {
select: {
username: true,
},
},
},
},
provider: {
select: {
@@ -74,6 +82,7 @@ export class ComplexPosesService {
defaultInsert = async (
consumer_id: string,
complex_id: string,
account_allocation_id: string,
data: CreatePosDto,
): Promise<PosCreateInput> => {
const { device_id, provider_id, username, password, ...rest } = data
@@ -88,6 +97,11 @@ export class ComplexPosesService {
account: {
create: {
role: ConsumerRole.OPERATOR,
account_allocation: {
connect: {
id: account_allocation_id,
},
},
account: {
create: {
username,
@@ -120,13 +134,25 @@ export class ComplexPosesService {
}
}
private readonly mapPos = (pos: any) => {
const { account, ...rest } = pos
const { account: accountInfo } = account
return {
...rest,
account: {
username: accountInfo.username,
},
}
}
async findAll(consumer_id: string, business_activity_id: string, complex_id: string) {
const poses = await this.prisma.pos.findMany({
where: this.defaultWhere(consumer_id, business_activity_id, complex_id),
select: this.defaultSelect,
})
return ResponseMapper.list(poses)
return ResponseMapper.list(poses.map(this.mapPos))
}
async findOne(
@@ -142,7 +168,7 @@ export class ComplexPosesService {
},
select: this.defaultSelect,
})
return ResponseMapper.single(pos)
return ResponseMapper.single(this.mapPos(pos))
}
async create(
@@ -151,13 +177,41 @@ export class ComplexPosesService {
complex_id: string,
data: CreatePosDto,
) {
const now = new Date()
const pos = await this.prisma.$transaction(async tx => {
const quota = await getBusinessActivityRemainingAccounts(tx, {
consumer_id,
business_activity_id,
const account_allocation = await tx.licenseAccountAllocation.findFirst({
where: {
account_id: null,
license_activation: {
business_activity_id,
business_activity: {
consumer_id,
},
OR: [
{
expires_at: {
gte: now,
},
},
{
license_renews: {
some: {
expires_at: {
gte: now,
},
},
},
},
],
},
},
select: {
id: true,
},
})
if (quota.remaining_accounts <= 0) {
if (!account_allocation) {
throw new BadRequestException(
`تعداد کاربرهای تخصیص داده شده برای این فعالیت تجاری به پایان رسیده است.`,
)
@@ -165,7 +219,12 @@ export class ComplexPosesService {
return await tx.pos.create({
data: {
...(await this.defaultInsert(consumer_id, complex_id, data)),
...(await this.defaultInsert(
consumer_id,
complex_id,
account_allocation.id,
data,
)),
status: POSStatus.ACTIVE,
},
})
@@ -1,7 +1,8 @@
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common'
import { PartnerInfo } from '@/common/decorators/partnerInfo.decorator'
import { Body, Controller, Get, Param, Patch } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { AccountsService } from './accounts.service'
import { CreateConsumerAccountDto, UpdateAccountDto } from './dto/account.dto'
import { UpdateAccountDto } from './dto/account.dto'
@ApiTags('PartnerConsumerAccounts')
@Controller('partner/consumers/:consumerId/accounts')
@@ -9,26 +10,39 @@ export class AccountsController {
constructor(private readonly accountsService: AccountsService) {}
@Get()
async findAll(@Param('consumerId') consumerId: string) {
return this.accountsService.findAll(consumerId)
async findAll(
@PartnerInfo('id') partnerId: string,
@Param('consumerId') consumerId: string,
) {
return this.accountsService.findAll(partnerId, consumerId)
}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.accountsService.findOne(id)
async findOne(
@PartnerInfo('id') partnerId: string,
@Param('consumerId') consumerId: string,
@Param('id') id: string,
) {
return this.accountsService.findOne(partnerId, consumerId, id)
}
@Post()
async create(
@Param('consumerId') consumerId: string,
@Body() data: CreateConsumerAccountDto,
) {
return this.accountsService.create(consumerId, data)
}
// @Post()
// async create(
// @PartnerInfo('id') partnerId: string,
// @Param('consumerId') consumerId: string,
// @Body() data: CreateConsumerAccountDto,
// ) {
// return this.accountsService.create(partnerId, consumerId, data)
// }
@Patch(':id')
async update(@Param('id') id: string, @Body() data: UpdateAccountDto) {
return this.accountsService.update(id, data)
async update(
@PartnerInfo('id') partnerId: string,
@Param('consumerId') consumerId: string,
@Param('id') id: string,
@Body() data: UpdateAccountDto,
) {
return this.accountsService.update(partnerId, consumerId, id, data)
}
// @Delete(':id')
@@ -1,82 +1,113 @@
import { PasswordUtil } from '@/common/utils/password.util'
import { AccountStatus, AccountType } from '@/generated/prisma/enums'
import { ConsumerAccountSelect } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { ResponseMapper } from 'common/response/response-mapper'
import { CreateConsumerAccountDto, UpdateAccountDto } from './dto/account.dto'
import { UpdateAccountDto } from './dto/account.dto'
@Injectable()
export class AccountsService {
constructor(private readonly prisma: PrismaService) {}
async findAll(consumer_id: string) {
const accounts = await this.prisma.consumerAccount.findMany({
where: { consumer_id },
private readonly default_select: ConsumerAccountSelect = {
id: true,
role: true,
created_at: true,
pos: {
select: {
id: true,
role: true,
created_at: true,
account: {
name: true,
complex: {
select: {
username: true,
status: true,
id: true,
name: true,
branch_code: true,
business_activity: {
select: {
id: true,
name: true,
},
},
},
},
},
},
account: {
select: {
username: true,
status: true,
},
},
}
private readonly defaultWhere = (partner_id, consumer_id) => ({
consumer_id,
consumer: {
partner_id,
},
})
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,
})
return ResponseMapper.list(accounts)
}
async findOne(id: string) {
async findOne(partner_id: string, consumer_id: string, id: string) {
const account = await this.prisma.consumerAccount.findMany({
where: { id },
select: {
id: true,
role: true,
created_at: true,
account: {
select: {
username: true,
status: true,
},
},
where: {
...this.defaultWhere(partner_id, consumer_id),
id,
},
select: this.default_select,
})
return ResponseMapper.single(account)
}
async create(consumerId: string, data: CreateConsumerAccountDto) {
const account = await this.prisma.consumerAccount.create({
data: {
role: data.role,
account: {
create: {
password: await PasswordUtil.hash(data.password),
status: AccountStatus.ACTIVE,
type: AccountType.CONSUMER,
username: data.username,
},
},
consumer: {
connect: {
id: consumerId,
},
},
permission: {
create: {},
},
},
})
return ResponseMapper.create(account)
}
// async create(partner_id: string, consumer_id: string, data: CreateConsumerAccountDto) {
// const account = await this.prisma.consumerAccount.create({
// data: {
// role: data.role,
// account: {
// create: {
// password: await PasswordUtil.hash(data.password),
// status: AccountStatus.ACTIVE,
// type: AccountType.CONSUMER,
// username: data.username,
// },
// },
// consumer: {
// connect: {
// id: consumer_id,
// },
// },
// permission: {
// create: {},
// },
// },
// })
// return ResponseMapper.create(account)
// }
async update(id: string, data: UpdateAccountDto) {
const account = await this.prisma.account.update({ where: { id }, data })
async update(
partner_id: string,
consumer_id: string,
id: string,
data: UpdateAccountDto,
) {
const account = await this.prisma.account.update({
where: {
...this.defaultWhere(partner_id, consumer_id),
id,
},
data,
})
return ResponseMapper.update(account)
}
async delete(id: string) {
await this.prisma.account.delete({ where: { id } })
return ResponseMapper.delete()
}
// async delete(partner_id: string, id: string) {
// await this.prisma.account.delete({ where: { id } })
// return ResponseMapper.delete()
// }
}
@@ -31,10 +31,11 @@ export class BusinessActivitiesController {
@Post()
async create(
@PartnerInfo('id') partnerId: string,
@Param('consumerId') consumerId: string,
@Body() data: CreateBusinessActivitiesDto,
) {
return this.businessActivitiesService.create(consumerId, data)
return this.businessActivitiesService.create(partnerId, consumerId, data)
}
@Put(':id')
@@ -1,6 +1,7 @@
import { BusinessActivitySelect } from '@/generated/prisma/models'
import { getPartnerFirstRemainingLicense } from '@/modules/partners/utils/getPartnerRemainingLicenses.util'
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 { CreateBusinessActivitiesDto } from './dto/create-business-activities.dto'
@@ -8,6 +9,12 @@ import { CreateBusinessActivitiesDto } from './dto/create-business-activities.dt
export class BusinessActivitiesService {
constructor(private readonly prisma: PrismaService) {}
private readonly setExpireDate = (starts_at: Date) => {
return new Date(
new Date(starts_at).setFullYear(new Date(starts_at).getFullYear() + 1),
).toISOString()
}
defaultSelect: BusinessActivitySelect = {
id: true,
name: true,
@@ -27,10 +34,13 @@ export class BusinessActivitiesService {
expires_at: true,
license: {
select: {
accounts_limit: true,
_count: {
activation: {
select: {
account_allocations: true,
_count: {
select: {
account_allocations: true,
},
},
},
},
},
@@ -42,13 +52,13 @@ export class BusinessActivitiesService {
private readonly prepareBusinessActivityResponse = (businessActivity: any) => {
const { license_activation, ...rest } = businessActivity
const { license, ...license_activation_rest } = license_activation
const { accounts_limit, _count } = license
const { _count } = license.activation
return {
...rest,
license_info: {
...license_activation_rest,
accounts_limit: accounts_limit + _count.account_allocations,
accounts_limit: _count.account_allocations,
},
}
}
@@ -82,24 +92,80 @@ export class BusinessActivitiesService {
return ResponseMapper.single(this.prepareBusinessActivityResponse(businessActivity))
}
async create(consumer_id: string, data: CreateBusinessActivitiesDto) {
const { guild_id, ...rest } = data
const businessActivity = await this.prisma.businessActivity.create({
data: {
...rest,
guild: {
connect: {
id: data.guild_id,
async create(
partner_id: string,
consumer_id: string,
data: CreateBusinessActivitiesDto,
) {
const businessActivity = await this.prisma.$transaction(async tx => {
const license = await getPartnerFirstRemainingLicense(tx, { partner_id })
const { guild_id, license_starts_at, expires_at, ...rest } = data
const createdBusinessActivity = await tx.businessActivity.create({
data: {
...rest,
guild: {
connect: {
id: guild_id,
},
},
consumer: {
connect: {
id: consumer_id,
},
},
license_activation: {
create: {
starts_at: license_starts_at ?? new Date(),
expires_at:
expires_at ?? this.setExpireDate(new Date(license_starts_at || '')),
license: {
connect: {
id: license.id,
},
},
},
},
},
consumer: {
connect: {
id: consumer_id,
select: {
id: true,
license_activation: {
select: {
id: true,
},
},
},
},
select: this.defaultSelect,
})
const activationId = createdBusinessActivity.license_activation?.id
if (!activationId) {
throw new BadRequestException('لایسنس برای این فعالیت تجاری ایجاد نشد.')
}
const licenseAllocationCreation = Array.from({
length: license.accounts_limit,
}).map(() =>
tx.licenseAccountAllocation.create({
data: {
license_activation: {
connect: {
id: activationId,
},
},
},
}),
)
await Promise.all(licenseAllocationCreation)
return tx.businessActivity.findUniqueOrThrow({
where: {
id: createdBusinessActivity.id,
},
select: this.defaultSelect,
})
})
return ResponseMapper.create(businessActivity)
}
@@ -36,7 +36,7 @@ export class BusinessActivityComplexesController {
@Param('businessActivityId') businessActivityId: string,
@Body() data: CreateComplexDto,
) {
return this.service.create(businessActivityId, data)
return this.service.create(partnerId, businessActivityId, data)
}
@Patch(':id')
@@ -31,11 +31,11 @@ export class BusinessActivityComplexesService {
})
async findAll(partner_id: string, consumer_id: string, business_activity_id: string) {
const accounts = await this.prisma.complex.findMany({
const complexes = await this.prisma.complex.findMany({
where: this.defaultWhere(partner_id, consumer_id, business_activity_id),
select: this.defaultSelect,
})
return ResponseMapper.list(accounts)
return ResponseMapper.list(complexes)
}
async findOne(
@@ -44,18 +44,18 @@ export class BusinessActivityComplexesService {
business_activity_id: string,
id: string,
) {
const account = await this.prisma.complex.findUnique({
const complex = await this.prisma.complex.findUnique({
where: {
...this.defaultWhere(partner_id, consumer_id, business_activity_id),
id,
},
select: this.defaultSelect,
})
return ResponseMapper.single(account)
return ResponseMapper.single(complex)
}
async create(business_id: string, data: CreateComplexDto) {
const account = await this.prisma.complex.create({
async create(partner_id: string, business_id: string, data: CreateComplexDto) {
const complex = await this.prisma.complex.create({
data: {
...data,
business_activity: {
@@ -65,7 +65,7 @@ export class BusinessActivityComplexesService {
},
},
})
return ResponseMapper.create(account)
return ResponseMapper.create(complex)
}
async update(
@@ -75,11 +75,11 @@ export class BusinessActivityComplexesService {
id: string,
data: UpdateComplexDto,
) {
const account = await this.prisma.complex.update({
const complex = await this.prisma.complex.update({
where: { ...this.defaultWhere(partner_id, consumer_id, business_activity_id), id },
data,
})
return ResponseMapper.update(account)
return ResponseMapper.update(complex)
}
// async delete(id: string) {
@@ -1,8 +1,9 @@
import { POSStatus, POSType } from '@/generated/prisma/enums'
import { ApiProperty, PartialType } from '@nestjs/swagger'
import { CreateConsumerAccountDto } from '@/modules/partners/consumers/accounts/dto/account.dto'
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger'
import { IsEnum, IsOptional, IsString } from 'class-validator'
export class CreatePosDto {
export class CreatePosDto extends OmitType(CreateConsumerAccountDto, ['role']) {
@IsString()
@ApiProperty({})
name: string
@@ -31,10 +31,11 @@ export class ComplexPosesController {
@Post()
async create(
@PartnerInfo('id') partnerId: string,
@Param('businessActivityId') businessActivityId: string,
@Param('complexId') complexId: string,
@Body() data: CreatePosDto,
) {
return this.service.create(complexId, data)
return this.service.create(partnerId, businessActivityId, complexId, data)
}
@Patch(':id')
@@ -1,7 +1,13 @@
import { POSStatus } from '@/generated/prisma/enums'
import { PasswordUtil } from '@/common/utils/password.util'
import {
AccountStatus,
AccountType,
ConsumerRole,
POSStatus,
} from '@/generated/prisma/enums'
import { PosCreateInput, PosSelect } 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 { CreatePosDto, UpdatePosDto } from './dto/pos.dto'
@@ -18,6 +24,16 @@ export class ComplexPosesService {
created_at: true,
pos_type: true,
account: {
select: {
account: {
select: {
username: true,
},
},
},
},
provider: {
select: {
id: true,
@@ -67,10 +83,22 @@ export class ComplexPosesService {
},
})
private readonly mapPos = (pos: any) => {
const { account, ...rest } = pos
const { account: accountInfo } = account
return {
...rest,
account: {
username: accountInfo.username,
},
}
}
private readonly defaultInsert = (data: CreatePosDto, complex_id: string) => {
const { device_id, provider_id, ...rest } = data
return {
const dataToCreate: PosCreateInput = {
...rest,
complex: {
connect: {
@@ -91,15 +119,20 @@ export class ComplexPosesService {
},
}
: undefined,
} as PosCreateInput
}
return dataToCreate
}
async findAll(partner_id: string, business_activity_id: string, complex_id: string) {
const accounts = await this.prisma.pos.findMany({
const poses = await this.prisma.pos.findMany({
where: this.defaultWhere(partner_id, complex_id, business_activity_id),
select: this.defaultSelect,
})
return ResponseMapper.list(accounts)
const mappedPoses = poses.map(this.mapPos)
return ResponseMapper.list(mappedPoses)
}
async findOne(
@@ -108,21 +141,102 @@ export class ComplexPosesService {
complex_id: string,
id: string,
) {
const account = await this.prisma.pos.findUniqueOrThrow({
const pos = await this.prisma.pos.findUniqueOrThrow({
where: { ...this.defaultWhere(partner_id, complex_id, business_activity_id), id },
select: this.defaultSelect,
})
return ResponseMapper.single(account)
return ResponseMapper.single(this.mapPos(pos))
}
async create(complex_id: string, data: CreatePosDto) {
const account = await this.prisma.pos.create({
data: {
...this.defaultInsert(data, complex_id),
status: POSStatus.ACTIVE,
},
async create(
partner_id: string,
business_activity_id: string,
complex_id: string,
data: CreatePosDto,
) {
const pos = this.prisma.$transaction(async tx => {
const ba = await tx.businessActivity.findUniqueOrThrow({
where: {
id: business_activity_id,
consumer: {
partner_id,
},
},
select: {
consumer_id: true,
license_activation: {
select: {
_count: {
select: {
account_allocations: {
where: {
account_id: {
not: undefined,
},
},
},
},
},
},
},
},
})
if (!ba.license_activation?._count.account_allocations) {
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: ba.consumer_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,
},
})
})
return ResponseMapper.create(account)
return ResponseMapper.create(pos)
}
async update(
@@ -133,7 +247,7 @@ export class ComplexPosesService {
data: UpdatePosDto,
) {
const { device_id, provider_id, ...rest } = data
const account = await this.prisma.pos.update({
const pos = await this.prisma.pos.update({
where: { ...this.defaultWhere(partner_id, complex_id, business_activity_id), id },
data: {
complex: {
@@ -158,7 +272,7 @@ export class ComplexPosesService {
...rest,
},
})
return ResponseMapper.update(account)
return ResponseMapper.update(pos)
}
// async delete(id: string) {
@@ -1,5 +1,5 @@
import { ApiProperty, PartialType } from '@nestjs/swagger'
import { IsString } from 'class-validator'
import { IsDateString, IsOptional, IsString } from 'class-validator'
export class CreateBusinessActivitiesDto {
@IsString()
@@ -11,8 +11,18 @@ export class CreateBusinessActivitiesDto {
economic_code: string
@IsString()
@ApiProperty({})
@ApiProperty({ required: true })
guild_id: string
@IsDateString()
@IsOptional()
@ApiProperty({ required: false })
license_starts_at: string
@IsDateString()
@IsOptional()
@ApiProperty({ required: false })
expires_at: string
}
export class UpdateBusinessActivityDto extends PartialType(CreateBusinessActivitiesDto) {}
+6 -1
View File
@@ -10,7 +10,12 @@ export class PartnerController {
constructor(private service: PartnerService) {}
@Get('')
async findOne(@PartnerInfo('id') partnerId: string) {
async me(@PartnerInfo('id') partnerId: string) {
return this.service.me(partnerId)
}
@Get('info')
async getInfo(@PartnerInfo('id') partnerId: string) {
return this.service.getInfo(partnerId)
}
+169 -15
View File
@@ -1,5 +1,5 @@
import { ResponseMapper } from '@/common/response/response-mapper'
import { PartnerSelect } from '@/generated/prisma/models'
import { PartnerAccountSelect } from '@/generated/prisma/models'
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { UpdatePartnerProfileDto } from './dto/partner.dto'
@@ -8,23 +8,31 @@ import { UpdatePartnerProfileDto } from './dto/partner.dto'
export class PartnerService {
constructor(private readonly prisma: PrismaService) {}
private readonly defaultSelect: PartnerSelect = {
id: true,
name: true,
status: true,
account_quota_charge_transactions: {
private readonly defaultSelect: PartnerAccountSelect = {}
async me(partner_id: string) {
const partner = await this.prisma.partnerAccount.findUniqueOrThrow({
where: {
partner_id,
},
select: {
_count: {
id: true,
role: true,
account: {
select: {
allocations: {
where: {
license_id: undefined,
},
},
username: true,
},
},
partner: {
select: {
id: true,
name: true,
},
},
},
},
})
return ResponseMapper.single(partner)
}
async getInfo(partner_id: string) {
@@ -32,10 +40,156 @@ export class PartnerService {
where: {
id: partner_id,
},
select: this.defaultSelect,
select: {
id: true,
name: true,
code: true,
created_at: true,
license_charge_transactions: {
select: {
purchased_count: true,
activation_expires_at: true,
_count: {
select: {
licenses: {
where: {
activation: {
isNot: null,
},
},
},
},
},
},
},
account_quota_charge_transactions: {
select: {
purchased_count: true,
activation_expires_at: true,
_count: {
select: {
credits: {
where: {
charge_transaction: {
isNot: null,
},
allocation: {
isNot: null,
},
},
},
},
},
},
},
license_renew_charge_transactions: {
select: {
purchased_count: true,
activation_expires_at: true,
_count: {
select: {
license_renews: {
where: {
activation: {
isNot: undefined,
},
},
},
},
},
},
},
},
})
return ResponseMapper.single(partner)
const {
license_charge_transactions,
account_quota_charge_transactions,
license_renew_charge_transactions,
...partnerInfo
} = partner
const licenses_status = {
total_purchased: 0,
total_activated: 0,
total_expired: 0,
}
const account_quotas_status = {
total_purchased: 0,
total_activated: 0,
total_expired: 0,
}
const license_renews_status = {
total_purchased: 0,
total_activated: 0,
total_expired: 0,
}
const now = new Date()
const checkExpired = (expires_at: Date) => expires_at < now
const prepareData = (
items_count: number,
activation_expires_at: Date,
purchased_count: number,
) => {
let totalActivated = 0
let totalExpired = 0
if (!checkExpired(activation_expires_at)) {
totalActivated = items_count
} else {
totalExpired = items_count
}
return {
total_purchased: purchased_count,
total_activated: totalActivated,
total_expired: totalExpired,
}
}
license_charge_transactions.forEach(
({ _count, activation_expires_at, purchased_count }) => {
const status = prepareData(
_count.licenses,
activation_expires_at,
purchased_count,
)
licenses_status.total_purchased += status.total_purchased
licenses_status.total_activated += status.total_activated
licenses_status.total_expired += status.total_expired
},
)
account_quota_charge_transactions.forEach(
({ _count, activation_expires_at, purchased_count }) => {
const status = prepareData(_count.credits, activation_expires_at, purchased_count)
account_quotas_status.total_purchased += status.total_purchased
account_quotas_status.total_activated += status.total_activated
account_quotas_status.total_expired += status.total_expired
},
)
license_renew_charge_transactions.forEach(
({ _count, activation_expires_at, purchased_count }) => {
const status = prepareData(
_count.license_renews,
activation_expires_at,
purchased_count,
)
license_renews_status.total_purchased += status.total_purchased
license_renews_status.total_activated += status.total_activated
license_renews_status.total_expired += status.total_expired
},
)
return ResponseMapper.single({
licenses_status,
license_renews_status,
account_quotas_status,
...partnerInfo,
})
}
async updateInfo(partner_id: string, data: UpdatePartnerProfileDto) {
@@ -0,0 +1,97 @@
import { BadRequestException } from '@nestjs/common'
type PartnerBusinessActivityAllocationClient = {
licenseActivation: {
findFirst: (args: any) => Promise<any>
}
}
type GetPartnerBusinessActivityAllocationLimitsParams = {
partner_id: string
business_activity_id: string
referenceDate?: Date
}
export type PartnerBusinessActivityAllocationLimits = {
activation_id: string
total_credits: number
allocated_credits: number
remaining_credits: number
}
export const getPartnerBusinessActivityAllocationLimits = async (
prisma: PartnerBusinessActivityAllocationClient,
params: GetPartnerBusinessActivityAllocationLimitsParams,
): Promise<PartnerBusinessActivityAllocationLimits> => {
const { partner_id, business_activity_id, referenceDate = new Date() } = params
const startOfDay = new Date(referenceDate)
startOfDay.setHours(0, 0, 0, 0)
const activation = await prisma.licenseActivation.findFirst({
where: {
business_activity_id,
business_activity: {
consumer: {
partner_id,
},
},
OR: [
{
expires_at: {
gte: startOfDay,
},
},
{
license_renews: {
some: {
expires_at: {
gte: startOfDay,
},
},
},
},
],
},
select: {
id: true,
account_allocations: {
select: {
id: true,
account_id: true,
},
},
},
})
if (!activation) {
throw new BadRequestException('لایسنس فعال برای این فعالیت تجاری یافت نشد.')
}
const totalCredits = activation.account_allocations.length
const allocatedCredits = activation.account_allocations.filter(
account_allocation => account_allocation.account_id,
).length
return {
activation_id: activation.id,
total_credits: totalCredits,
allocated_credits: allocatedCredits,
remaining_credits: totalCredits - allocatedCredits,
}
}
export const ensurePartnerBusinessActivityHasRemainingAllocation = async (
prisma: PartnerBusinessActivityAllocationClient,
params: GetPartnerBusinessActivityAllocationLimitsParams,
) => {
const quota = await getPartnerBusinessActivityAllocationLimits(prisma, params)
if (quota.remaining_credits <= 0) {
throw new BadRequestException(
'محدودیت تخصیص حساب برای این فعالیت تجاری به پایان رسیده است.',
)
}
return quota
}
@@ -0,0 +1,94 @@
import { BadRequestException } from '@nestjs/common'
type PartnerRemainingLicensesClient = {
license: {
count: (args: any) => Promise<number>
findFirst: (args: any) => Promise<any>
}
}
type GetPartnerRemainingLicensesParams = {
partner_id: string
referenceDate?: Date
}
export const getPartnerRemainingLicenses = async (
prisma: PartnerRemainingLicensesClient,
params: GetPartnerRemainingLicensesParams,
) => {
const { partner_id, referenceDate = new Date() } = params
const startOfDay = new Date(referenceDate)
startOfDay.setHours(0, 0, 0, 0)
const remaining_count = await prisma.license.count({
where: {
activation: null,
charge_transaction: {
partner_id,
activation_expires_at: {
gte: startOfDay,
},
},
},
})
return {
remaining_count,
}
}
export const getPartnerFirstRemainingLicense = async (
prisma: PartnerRemainingLicensesClient,
params: GetPartnerRemainingLicensesParams,
) => {
const { partner_id, referenceDate = new Date() } = params
const startOfDay = new Date(referenceDate)
startOfDay.setHours(0, 0, 0, 0)
const license = await prisma.license.findFirst({
where: {
activation: null,
charge_transaction: {
partner_id,
activation_expires_at: {
gte: startOfDay,
},
},
},
orderBy: {
charge_transaction: {
activation_expires_at: 'asc',
},
},
select: {
id: true,
charge_transaction_id: true,
accounts_limit: true,
},
})
if (!license) {
throw new BadRequestException(
'لایسنس فعال و استفاده نشده برای این شریک تجاری وجود ندارد.',
)
}
return license
}
export const ensurePartnerHasRemainingLicense = async (
prisma: PartnerRemainingLicensesClient,
params: GetPartnerRemainingLicensesParams,
) => {
const quota = await getPartnerRemainingLicenses(prisma, params)
if (quota.remaining_count <= 0) {
throw new BadRequestException(
'لایسنس فعال و استفاده نشده برای این شریک تجاری وجود ندارد.',
)
}
return quota
}