The minimalistic document archiving platform.
feat(plans): harden subscription resolution (#1405)
Corentin Thomasset18bde86c9c7d
diff --git a/apps/papra-server/src/modules/plans/plans.models.test.ts b/apps/papra-server/src/modules/plans/plans.models.test.tsnew file mode 100644index 00000000..5621d9d5--- /dev/null+++ b/apps/papra-server/src/modules/plans/plans.models.test.ts@@ -0,0 +1,110 @@+import { describe, expect, test } from 'vitest';+import { overrideConfig } from '../config/config.test-utils';+import { PLAN_IDS } from './plans.constants';+import { resolveOrganizationPlanFromPriceIds } from './plans.models';+import { getOrganizationPlansRecords } from './plans.repository';++function createOrganizationPlans() {+ const config = overrideConfig({+ organizationPlans: {+ plusPlanMonthlyPriceId: 'price_plus_monthly',+ plusPlanAnnualPriceId: 'price_plus_annual',+ proPlanMonthlyPriceId: 'price_pro_monthly',+ proPlanAnnualPriceId: 'price_pro_annual',+ },+ });++ const { organizationPlans } = getOrganizationPlansRecords({ config });++ return organizationPlans;+}++describe('plans models', () => {+ describe('resolveOrganizationPlanFromPriceIds', () => {+ const organizationPlans = createOrganizationPlans();++ test('the plan is resolved regardless of the position of its price id among the subscription items', () => {+ const { organizationPlan } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_some_addon', 'price_pro_monthly'],+ organizationPlans,+ });++ expect(organizationPlan?.id).to.equal(PLAN_IDS.PRO);+ });++ test('a plan is matched by its annual price id as well as its monthly one', () => {+ expect(+ resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_plus_annual'],+ organizationPlans,+ }).organizationPlan?.id,+ ).to.equal(PLAN_IDS.PLUS);++ expect(+ resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_plus_monthly'],+ organizationPlans,+ }).organizationPlan?.id,+ ).to.equal(PLAN_IDS.PLUS);+ });++ test('price ids matching no plan are reported to the caller instead of being an error, as an unknown price should not prevent the subscription from being synced', () => {+ const { organizationPlan, unknownPriceIds } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_storage_pack', 'price_pro_monthly', 'price_whatever'],+ organizationPlans,+ });++ expect(organizationPlan?.id).to.equal(PLAN_IDS.PRO);+ expect(unknownPriceIds).to.eql(['price_storage_pack', 'price_whatever']);+ });++ test('the monthly and annual prices of a same plan are not considered ambiguous', () => {+ const { organizationPlan } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_pro_monthly', 'price_pro_annual'],+ organizationPlans,+ });++ expect(organizationPlan?.id).to.equal(PLAN_IDS.PRO);+ });++ test('when no price id matches a plan, or when there is no item at all, the plan is undefined', () => {+ expect(+ resolveOrganizationPlanFromPriceIds({ priceIds: ['price_unknown'], organizationPlans })+ .organizationPlan,+ ).to.eql(undefined);++ expect(+ resolveOrganizationPlanFromPriceIds({ priceIds: [], organizationPlans }).organizationPlan,+ ).to.eql(undefined);+ });++ test('a subscription holding the prices of two different plans keeps the most generous one and reports the others, as blocking the sync would leave the subscription stale', () => {+ const { organizationPlan, discardedPlanIds } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_plus_monthly', 'price_pro_monthly'],+ organizationPlans,+ });++ expect(organizationPlan?.id).to.equal(PLAN_IDS.PRO);+ expect(discardedPlanIds).to.eql([PLAN_IDS.PLUS]);+ });++ test('the most generous plan is kept regardless of the order of the subscription items', () => {+ const { organizationPlan, discardedPlanIds } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_pro_annual', 'price_plus_annual'],+ organizationPlans,+ });++ expect(organizationPlan?.id).to.equal(PLAN_IDS.PRO);+ expect(discardedPlanIds).to.eql([PLAN_IDS.PLUS]);+ });++ test('a subscription matching a single plan reports no discarded plan', () => {+ const { discardedPlanIds } = resolveOrganizationPlanFromPriceIds({+ priceIds: ['price_pro_monthly', 'price_pro_annual'],+ organizationPlans,+ });++ expect(discardedPlanIds).to.eql([]);+ });+ });+});diff --git a/apps/papra-server/src/modules/plans/plans.models.ts b/apps/papra-server/src/modules/plans/plans.models.tsindex 48c48f13..2615b7f8 100644--- a/apps/papra-server/src/modules/plans/plans.models.ts+++ b/apps/papra-server/src/modules/plans/plans.models.ts@@ -1,6 +1,7 @@-import { isNil } from '../shared/utils';+import { isNil, uniqBy } from '../shared/utils';import { PLAN_PRIORITY } from './plans.constants';import type { PlanId } from './plans.constants';+import type { OrganizationPlanRecord } from './plans.types';import { createOrganizationPlanPriceIdNotSetError } from './plans.errors';export function getPriceIdForBillingInterval({@@ -21,6 +22,45 @@ export function getPriceIdForBillingInterval({return { priceId };}+export function resolveOrganizationPlanFromPriceIds({+ priceIds,+ organizationPlans,+}: {+ priceIds: string[];+ organizationPlans: Record<string, OrganizationPlanRecord>;+}) {+ const plans = Object.values(organizationPlans);+ const matchedPlans: OrganizationPlanRecord[] = [];+ const unknownPriceIds: string[] = [];++ for (const priceId of priceIds) {+ const matchedPlan = plans.find(+ (plan) => plan.monthlyPriceId === priceId || plan.annualPriceId === priceId,+ );++ if (isNil(matchedPlan)) {+ unknownPriceIds.push(priceId);+ continue;+ }++ matchedPlans.push(matchedPlan);+ }++ const [organizationPlan, ...discardedPlans] = uniqBy(matchedPlans, (plan) => plan.id).sort(+ (planA, planB) => getPlanPriority({ planId: planB.id }) - getPlanPriority({ planId: planA.id }),+ );++ return {+ organizationPlan,+ unknownPriceIds,+ discardedPlanIds: discardedPlans.map((plan) => plan.id),+ };+}++function getPlanPriority({ planId }: { planId: string }) {+ return PLAN_PRIORITY[planId as PlanId] ?? 0;+}+export function getApplyablePlanId({basePlanId,entitlementPlanId,diff --git a/apps/papra-server/src/modules/plans/plans.repository.ts b/apps/papra-server/src/modules/plans/plans.repository.tsindex 5247d1a5..d4ad90a9 100644--- a/apps/papra-server/src/modules/plans/plans.repository.ts+++ b/apps/papra-server/src/modules/plans/plans.repository.ts@@ -5,6 +5,7 @@ import { isDocumentSizeLimitEnabled } from '../documents/documents.models';import { IN_BYTES } from '../shared/units';import { PLAN_IDS } from './plans.constants';import { createPlanNotFoundError } from './plans.errors';+import { resolveOrganizationPlanFromPriceIds } from './plans.models';export type PlansRepository = ReturnType<typeof createPlansRepository>;@@ -14,7 +15,7 @@ export function createPlansRepository({ config }: { config: Config }) {return injectArguments({getOrganizationPlanById,- getOrganizationPlanByPriceId,+ getOrganizationPlanByPriceIds,},{organizationPlans,@@ -101,20 +102,12 @@ async function getOrganizationPlanById({return { organizationPlan };}-async function getOrganizationPlanByPriceId({- priceId,+async function getOrganizationPlanByPriceIds({+ priceIds,organizationPlans,}: {- priceId: string;+ priceIds: string[];organizationPlans: Record<string, OrganizationPlanRecord>;}) {- const organizationPlan = Object.values(organizationPlans).find(- (plan) => plan.monthlyPriceId === priceId || plan.annualPriceId === priceId,- );-- if (!organizationPlan) {- throw createPlanNotFoundError();- }-- return { organizationPlan };+ return resolveOrganizationPlanFromPriceIds({ priceIds, organizationPlans });}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.tsindex 2ef82537..41b7a2cd 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts@@ -7,6 +7,7 @@ import { createOrganizationNotFoundError } from '../organizations/organizations.import { createLogger } from '../shared/logger/logger';import { isNil } from '../shared/utils';import { coerceStripeTimestampToDate } from './subscriptions.models';+import { createPlanNotFoundError } from '../plans/plans.errors';export async function handleStripeWebhookEvent({event,@@ -63,12 +64,6 @@ export async function handleStripeWebhookEvent({}// Extract data from current Stripe state- const subscriptionItem = stripeSubscription.items.data[0];-- if (!subscriptionItem) {- throw new Error(`Subscription ${subscriptionId} has no items`);- }-const customerId =typeof stripeSubscription.customer === 'string'? stripeSubscription.customer@@ -79,9 +74,33 @@ export async function handleStripeWebhookEvent({const status = stripeSubscription.status;// Look up the plan - this might fail if price ID is misconfigured- const { organizationPlan } = await plansRepository.getOrganizationPlanByPriceId({- priceId: subscriptionItem.price.id,- });+ const priceIds = stripeSubscription.items.data.map(({ price }) => price.id);++ const { organizationPlan, unknownPriceIds, discardedPlanIds } =+ await plansRepository.getOrganizationPlanByPriceIds({ priceIds });++ if (unknownPriceIds.length > 0) {+ logger.warn(+ { subscriptionId, unknownPriceIds },+ 'Subscription contains price IDs matching no plan, they have been ignored',+ );+ }++ if (discardedPlanIds.length > 0) {+ logger.warn(+ { subscriptionId, discardedPlanIds },+ 'Subscription contains the price IDs of several plans, only the most generous one has been applied',+ );+ }++ if (isNil(organizationPlan)) {+ logger.warn(+ { subscriptionId, priceIds },+ 'Subscription contains no price ID matching a plan, it has been ignored',+ );++ throw createPlanNotFoundError();+ }// Upsert subscription with current state from Stripeawait subscriptionsRepository.upsertSubscription({