174 lines
6.1 KiB
TypeScript
174 lines
6.1 KiB
TypeScript
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
|
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
|
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
|
import {
|
|
planFeatureRequiredProblem,
|
|
planLimitReachedProblem,
|
|
planReadOnlyProblem,
|
|
} from '@/http/problem-builders';
|
|
import prisma from '@/lib/prisma';
|
|
import { getGraceDays, isBillingEnforced } from './config';
|
|
|
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
|
export type SubscriptionSnapshot = {
|
|
status: SubscriptionStatus;
|
|
authorizedAt: Date | null;
|
|
paidThrough: Date | null;
|
|
};
|
|
|
|
export type PlanResolution = {
|
|
plan: Plan;
|
|
/** Set while Pro survives a lapse (failed renewal or cancellation) on grace. */
|
|
graceUntil: Date | null;
|
|
};
|
|
|
|
/**
|
|
* Pro lasts while a charge covers today, plus the grace period after the last
|
|
* paid day. That one rule covers a cancelled subscription (Pro until the end of
|
|
* what was paid) and a failed renewal (Mercado Pago keeps retrying meanwhile).
|
|
*
|
|
* An AUTHORIZED subscription with no approved charge yet is Pro too, for the
|
|
* grace period after the authorization: the first charge is in flight.
|
|
*/
|
|
export function resolvePlan(
|
|
subscription: SubscriptionSnapshot | null,
|
|
now: Date,
|
|
graceDays: number,
|
|
): PlanResolution {
|
|
if (!subscription) return { plan: 'FREE', graceUntil: null };
|
|
const graceMs = graceDays * DAY_MS;
|
|
|
|
if (subscription.paidThrough) {
|
|
if (subscription.paidThrough > now) return { plan: 'PRO', graceUntil: null };
|
|
const graceUntil = new Date(subscription.paidThrough.getTime() + graceMs);
|
|
return graceUntil > now ? { plan: 'PRO', graceUntil } : { plan: 'FREE', graceUntil: null };
|
|
}
|
|
|
|
if (subscription.status === 'AUTHORIZED' && subscription.authorizedAt) {
|
|
const graceUntil = new Date(subscription.authorizedAt.getTime() + graceMs);
|
|
if (graceUntil > now) return { plan: 'PRO', graceUntil: null };
|
|
}
|
|
|
|
return { plan: 'FREE', graceUntil: null };
|
|
}
|
|
|
|
/**
|
|
* `resolvePlan` written as a query, for listing accounts by plan: a
|
|
* subscription is Pro when its paid period (or, before the first charge, its
|
|
* authorization) is younger than the grace period. Keep both in step.
|
|
*/
|
|
export function proSubscriptionWhere(now: Date, graceDays: number): Prisma.BillingSubscriptionWhereInput {
|
|
const cutoff = new Date(now.getTime() - graceDays * DAY_MS);
|
|
return {
|
|
OR: [
|
|
{ paidThrough: { gt: cutoff } },
|
|
{ paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } },
|
|
],
|
|
};
|
|
}
|
|
|
|
export type PlanUsage = { groups: number; attendees: number };
|
|
|
|
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
|
|
return (
|
|
(limits.maxGroups !== null && usage.groups > limits.maxGroups)
|
|
|| (limits.maxAttendees !== null && usage.attendees > limits.maxAttendees)
|
|
);
|
|
}
|
|
|
|
export type Entitlements = PlanResolution & {
|
|
limits: PlanLimits;
|
|
usage: PlanUsage;
|
|
/** Free with more usage than its limits. Always false when not enforced. */
|
|
readOnly: boolean;
|
|
enforced: boolean;
|
|
};
|
|
|
|
type PlanGuardDeps = {
|
|
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
|
|
enforced?: boolean;
|
|
graceDays?: number;
|
|
now?: () => Date;
|
|
};
|
|
|
|
/**
|
|
* What a professor's plan allows. Every check is about the **owner** of the
|
|
* group (`group.createdById`): an ADMIN acting on someone else's group spends
|
|
* the owner's plan, not their own.
|
|
*
|
|
* With enforcement off the checks pass without touching the database.
|
|
*/
|
|
export class PlanGuard {
|
|
constructor(private readonly deps: PlanGuardDeps = {}) {}
|
|
|
|
private get enforced(): boolean {
|
|
return this.deps.enforced ?? isBillingEnforced();
|
|
}
|
|
|
|
async getEntitlements(ownerId: string): Promise<Entitlements> {
|
|
const db = this.deps.db ?? prisma;
|
|
const now = this.deps.now?.() ?? new Date();
|
|
|
|
const [subscription, groups, attendees] = await Promise.all([
|
|
db.billingSubscription.findUnique({
|
|
where: { userId: ownerId },
|
|
select: { status: true, authorizedAt: true, paidThrough: true },
|
|
}),
|
|
db.group.count({ where: { createdById: ownerId } }),
|
|
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
|
|
]);
|
|
|
|
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
|
const limits = PLAN_LIMITS[resolution.plan];
|
|
const usage = { groups, attendees };
|
|
const enforced = this.enforced;
|
|
|
|
return {
|
|
...resolution,
|
|
limits,
|
|
usage,
|
|
readOnly: enforced && exceedsLimits(limits, usage),
|
|
enforced,
|
|
};
|
|
}
|
|
|
|
async requireWritable(ownerId: string): Promise<Result<void, ProblemDetails>> {
|
|
if (!this.enforced) return ok(undefined);
|
|
const entitlements = await this.getEntitlements(ownerId);
|
|
return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
|
|
}
|
|
|
|
async canCreateGroup(ownerId: string): Promise<Result<void, ProblemDetails>> {
|
|
if (!this.enforced) return ok(undefined);
|
|
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
|
|
if (readOnly) return err(planReadOnlyProblem());
|
|
if (limits.maxGroups !== null && usage.groups + 1 > limits.maxGroups) {
|
|
return err(planLimitReachedProblem('groups', limits.maxGroups));
|
|
}
|
|
return ok(undefined);
|
|
}
|
|
|
|
async canAddAttendees(ownerId: string, count = 1): Promise<Result<void, ProblemDetails>> {
|
|
if (!this.enforced || count <= 0) return ok(undefined);
|
|
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
|
|
if (readOnly) return err(planReadOnlyProblem());
|
|
if (limits.maxAttendees !== null && usage.attendees + count > limits.maxAttendees) {
|
|
return err(planLimitReachedProblem('attendees', limits.maxAttendees));
|
|
}
|
|
return ok(undefined);
|
|
}
|
|
|
|
async requireFeature(ownerId: string, feature: PlanFeature): Promise<Result<void, ProblemDetails>> {
|
|
return (await this.hasFeature(ownerId, feature))
|
|
? ok(undefined)
|
|
: err(planFeatureRequiredProblem(feature));
|
|
}
|
|
|
|
async hasFeature(ownerId: string, feature: PlanFeature): Promise<boolean> {
|
|
if (!this.enforced) return true;
|
|
const { limits } = await this.getEntitlements(ownerId);
|
|
return limits[feature];
|
|
}
|
|
}
|