import type { BillingSubscription, Prisma } from '@generated/prisma/client'; import type { AdminAccountListItem, AdminAccountQuery, Plan } from '@gruperly/shared'; import { countryCodeSchema } from '@gruperly/shared'; import { proSubscriptionWhere, resolvePlan } from '@/modules/billing/lib'; export type AccountRecord = { id: string; name: string; email: string; country: string | null; createdAt: Date; onboardingCompleted: boolean; planSelectedAt: Date | null; subscription: BillingSubscription | null; }; export type AccountUsage = { groupsCount: number; attendeesCount: number }; export type PlanContext = { now: Date; graceDays: number }; /** Pro by its subscription; otherwise Free once chosen, `null` while not chosen. */ export function accountPlan( account: Pick, { now, graceDays }: PlanContext, ): { plan: Plan | null; graceUntil: Date | null } { const resolution = resolvePlan(account.subscription, now, graceDays); if (resolution.plan === 'PRO') return resolution; return { plan: account.planSelectedAt ? 'FREE' : null, graceUntil: null }; } export function toAccountListItem( account: AccountRecord, usage: AccountUsage, context: PlanContext, ): AdminAccountListItem { const country = countryCodeSchema.safeParse(account.country); const subscription = account.subscription; return { id: account.id, name: account.name, email: account.email, country: country.success ? country.data : null, createdAt: account.createdAt.toISOString(), onboardingCompleted: account.onboardingCompleted, plan: accountPlan(account, context).plan, subscription: subscription ? { provider: subscription.provider, status: subscription.status, amount: Number(subscription.amount.toString()), currency: subscription.currency, paidThrough: subscription.paidThrough?.toISOString() ?? null, nextPaymentDate: subscription.status === 'AUTHORIZED' ? (subscription.nextPaymentDate?.toISOString() ?? null) : null, } : null, ...usage, }; } /** The list filters as a `user` query. The plan follows `accountPlan`. */ export function buildAccountWhere( query: Pick, { now, graceDays }: PlanContext, ): Prisma.UserWhereInput { const and: Prisma.UserWhereInput[] = []; if (query.search) { and.push({ OR: [ { name: { contains: query.search, mode: 'insensitive' } }, { email: { contains: query.search, mode: 'insensitive' } }, ], }); } if (query.country) and.push({ country: query.country }); if (query.subscriptionStatus === 'NONE') { and.push({ subscription: { is: null } }); } else if (query.subscriptionStatus) { and.push({ subscription: { is: { status: query.subscriptionStatus } } }); } if (query.plan) { const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } }; if (query.plan === 'PRO') and.push(isPro); if (query.plan === 'FREE') and.push({ planSelectedAt: { not: null }, NOT: isPro }); if (query.plan === 'NOT_SELECTED') and.push({ planSelectedAt: null, NOT: isPro }); } return and.length > 0 ? { AND: and } : {}; }