import type { Subscription } from '../base.js'; import { getPlan, hasPlan, type Plan, proPlan, scalePlan } from '../plans.js'; import type { IApp } from '../toDesktop.js'; export const PRO_CHILD_APP_LIMIT = 2; export const SCALE_CHILD_APP_LIMIT = 10; export interface AppEntitlementContext { app: IApp; apps: IApp[]; childAppLimit: number; childApps: IApp[]; effectiveApp: IApp; effectivePlan: null | Plan; effectiveSubscription?: Subscription; isChildApp: boolean; leaderApp: IApp; remainingChildAppCapacity: number; } export function getChildAppLimit(subscription?: Subscription): number { if (!subscription) { return 0; } if (hasPlan(scalePlan, subscription)) { return SCALE_CHILD_APP_LIMIT; } if (hasPlan(proPlan, subscription)) { return PRO_CHILD_APP_LIMIT; } return 0; } export function getRequiredPlanForAdditionalChildApp( childAppCount: number, ): Plan { return childAppCount >= PRO_CHILD_APP_LIMIT ? scalePlan : proPlan; } export function getLeaderApp(app: IApp, apps: IApp[] = []): IApp { const parentId = app.parent?.id; if (!parentId) { return app; } return apps.find(({ id }) => id === parentId) || app; } export function getEntitlementContext( app: IApp, apps: IApp[] = [], ): AppEntitlementContext { const leaderApp = getLeaderApp(app, apps); const childApps = apps.filter(({ parent }) => parent?.id === leaderApp.id); const effectiveSubscription = leaderApp.subscription; const childAppLimit = getChildAppLimit(effectiveSubscription); return { app, apps, childAppLimit, childApps, effectiveApp: leaderApp, effectivePlan: getPlan(effectiveSubscription), effectiveSubscription, isChildApp: Boolean(app.parent?.id), leaderApp, remainingChildAppCapacity: Math.max(0, childAppLimit - childApps.length), }; }