import { BadRequestException } from '@nestjs/common' type PartnerRemainingLicensesClient = { license: { count: (args: any) => Promise findFirst: (args: any) => Promise } } 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, parent: { select: { name: true, }, }, }, }) if (!license) { throw new BadRequestException(`لایسنس فعالی برای ${license.parent.name} وجود ندارد.`) } 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 }