The minimalistic document archiving platform.
feat(entitlements): add subscription discount coupon support (#1363)
Corentin Thomassetb3a625e079ed
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.tsindex 8d9d41cc..6b157cb7 100644--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts@@ -5,6 +5,7 @@ export type PlanEntitlementDriver = {verifyEligibility: (params: { user: { id: string; email: string } }) => Promise<boolean>;getIsEnabledForNewClaims: () => Promise<boolean>;planId: PlanId;+ subscriptionDiscountCouponId?: string;claimValidityDuration: Temporal.DurationLike;ineligibilityGraceDuration: Temporal.DurationLike;};diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.tsindex fa8c00f6..a65f3d40 100644--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';import { createTestClock } from '../shared/clock/clock.test-utils';import { createUsersRepository } from '../users/users.repository';import { createPlanEntitlementsRepository } from './plan-entitlements.repository';@@ -11,6 +12,7 @@ import {import {claimUserPlanEntitlement,grantUserPlanEntitlement,+ resolveOrganizationEntitlementCouponId,reverifyUserClaimedPlanEntitlements,} from './plan-entitlements.usecases';@@ -564,4 +566,123 @@ describe('plan-entitlements usecases', () => {expect(user2Entitlements[0]?.expiresAt).to.eql(new Date('2026-06-11T12:00:00Z'));});});++ describe('resolveOrganizationEntitlementCouponId', () => {+ test('when the organization owner has an active entitlement whose driver defines a subscription discount coupon, the coupon id is resolved', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'usr_1', email: '[email protected]' }],+ organizations: [{ id: 'org_1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'org_1', userId: 'usr_1', role: ORGANIZATION_ROLES.OWNER },+ ],+ planEntitlements: [+ {+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',+ userId: 'usr_1',+ type: 'selfhst-premium',+ source: 'user-claim',+ grantedAt: new Date('2026-01-01'),+ },+ ],+ });++ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({+ driver: createTestPlanEntitlementDriver({ subscriptionDiscountCouponId: 'coupon-1' }),+ });++ const { couponId } = await resolveOrganizationEntitlementCouponId({+ organizationId: 'org_1',+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ });++ expect(couponId).to.eql('coupon-1');+ });++ test('when the entitlement driver does not define a subscription discount coupon, no coupon id is resolved', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'usr_1', email: '[email protected]' }],+ organizations: [{ id: 'org_1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'org_1', userId: 'usr_1', role: ORGANIZATION_ROLES.OWNER },+ ],+ planEntitlements: [+ {+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',+ userId: 'usr_1',+ type: 'selfhst-premium',+ source: 'user-claim',+ grantedAt: new Date('2026-01-01'),+ },+ ],+ });++ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({+ driver: createTestPlanEntitlementDriver({ subscriptionDiscountCouponId: undefined }),+ });++ const { couponId } = await resolveOrganizationEntitlementCouponId({+ organizationId: 'org_1',+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ });++ expect(couponId).to.eql(undefined);+ });++ test('when the organization has no active entitlement, no coupon id is resolved', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'usr_1', email: '[email protected]' }],+ organizations: [{ id: 'org_1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'org_1', userId: 'usr_1', role: ORGANIZATION_ROLES.OWNER },+ ],+ });++ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({+ driver: createTestPlanEntitlementDriver({ subscriptionDiscountCouponId: 'coupon-1' }),+ });++ const { couponId } = await resolveOrganizationEntitlementCouponId({+ organizationId: 'org_1',+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ });++ expect(couponId).to.eql(undefined);+ });++ test('when no driver exists for the entitlement type, no coupon id is resolved', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'usr_1', email: '[email protected]' }],+ organizations: [{ id: 'org_1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'org_1', userId: 'usr_1', role: ORGANIZATION_ROLES.OWNER },+ ],+ planEntitlements: [+ {+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',+ userId: 'usr_1',+ type: 'selfhst-premium',+ source: 'user-claim',+ grantedAt: new Date('2026-01-01'),+ },+ ],+ });++ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });+ const planEntitlementDefinitionRegistry = createEmptyTestPlanEntitlementRegistry();++ const { couponId } = await resolveOrganizationEntitlementCouponId({+ organizationId: 'org_1',+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ });++ expect(couponId).to.eql(undefined);+ });+ });});diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.tsindex 17042b6f..78432d9c 100644--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts@@ -248,6 +248,40 @@ async function reverifyUserClaimedPlanEntitlement({});}+export async function resolveOrganizationEntitlementCouponId({+ organizationId,+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ logger = createLogger({ namespace: 'resolveOrganizationEntitlementCouponId' }),+}: {+ organizationId: string;+ planEntitlementsRepository: PlanEntitlementsRepository;+ planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;+ logger?: Logger;+}): Promise<{ couponId: string | undefined }> {+ const { planEntitlement } = await planEntitlementsRepository.getActiveEntitlementForOrganization({+ organizationId,+ });++ if (!planEntitlement) {+ return { couponId: undefined };+ }++ const { type } = planEntitlement;++ const { planEntitlementDriver } = planEntitlementDefinitionRegistry.getPlanEntitlementDriver({+ type,+ });++ if (isNil(planEntitlementDriver)) {+ logger.error({ type }, 'No plan entitlement driver found for type');++ return { couponId: undefined };+ }++ return { couponId: planEntitlementDriver.subscriptionDiscountCouponId };+}+export async function resolveOrganizationPlanEntitlements({organizationId,planEntitlementsRepository,diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.tsindex c94e5ec5..c32f35a5 100644--- a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts@@ -10,6 +10,13 @@ export const selfhstEntitlementsConfig = {env: 'SELFHST_ENTITLEMENTS_IS_ENABLED_FOR_NEW_CLAIMS',showInDocumentation: false,},+ subscriptionDiscountCouponId: {+ doc: 'The Stripe coupon ID applied at checkout for users holding a selfhst entitlement.',+ schema: v.optional(v.string()),+ default: undefined,+ env: 'SELFHST_ENTITLEMENTS_SUBSCRIPTION_DISCOUNT_COUPON_ID',+ showInDocumentation: false,+ },entitlementVerification: {endpoint: {doc: 'The endpoint to verify the selfhst entitlement.',diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.tsindex 033835cb..a2206e19 100644--- a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts@@ -25,6 +25,7 @@ export const selfhstPlanEntitlementsFactory: PlanEntitlementDriverFactory = ({ creturn isValid;},planId: PLAN_IDS.FREE_EXTENDED,+ subscriptionDiscountCouponId: selfhstConfig.subscriptionDiscountCouponId,claimValidityDuration: SELFHST_ENTITLEMENT_CLAIM_VALIDITY_DURATION,ineligibilityGraceDuration: SELFHST_ENTITLEMENT_INELIGIBILITY_GRACE_DURATION,};diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.tsindex ae560d5b..71c222c1 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts@@ -15,6 +15,7 @@ import {import { FREE_PLANS_IDS, PLAN_IDS } from '../plans/plans.constants';import { getPriceIdForBillingInterval } from '../plans/plans.models';import { createPlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';+import { resolveOrganizationEntitlementCouponId } from '../plan-entitlements/plan-entitlements.usecases';import { createPlansRepository } from '../plans/plans.repository';import { getOrganizationPlan } from '../plans/plans.usecases';import { getHeader } from '../shared/headers/headers.models';@@ -150,6 +151,12 @@ function setupCreateCheckoutSessionRoute({organizationsRepository,});+ const { couponId: entitlementCouponId } = await resolveOrganizationEntitlementCouponId({+ organizationId,+ planEntitlementsRepository,+ planEntitlementDefinitionRegistry,+ });+// Step 1: Expire any active checkout sessions before creating a new one// This allows subscriptions to be canceled (can't cancel while checkout is active)await subscriptionsServices.expireActiveCheckoutSessions({ customerId });@@ -180,6 +187,7 @@ function setupCreateCheckoutSessionRoute({customerId,priceId,organizationId,+ entitlementCouponId,});return context.json({ checkoutUrl });diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.services.test.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.services.test.tsnew file mode 100644index 00000000..3dd11312--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.services.test.ts@@ -0,0 +1,98 @@+import type Stripe from 'stripe';+import { describe, expect, test } from 'vitest';+import { resolveCheckoutDiscount } from './subscriptions.services';++function createStripeClientStub({+ coupons = {},+}: { coupons?: Record<string, { valid: boolean }> } = {}) {+ return {+ coupons: {+ retrieve: async (couponId: string) => {+ const coupon = coupons[couponId];++ if (!coupon) {+ throw new Error(`No such coupon: ${couponId}`);+ }++ return { id: couponId, valid: coupon.valid };+ },+ },+ } as unknown as Stripe;+}++describe('subscriptions services', () => {+ describe('resolveCheckoutDiscount', () => {+ test('the entitlement coupon takes precedence over the global coupon', async () => {+ const stripeClient = createStripeClientStub({+ coupons: {+ 'entitlement-coupon': { valid: true },+ 'global-coupon': { valid: true },+ },+ });++ const { discountDetails } = await resolveCheckoutDiscount({+ stripeClient,+ entitlementCouponId: 'entitlement-coupon',+ globalCouponId: 'global-coupon',+ });++ expect(discountDetails).to.eql({ discounts: [{ coupon: 'entitlement-coupon' }] });+ });++ test('when the entitlement coupon is invalid, the global coupon is applied', async () => {+ const stripeClient = createStripeClientStub({+ coupons: {+ 'entitlement-coupon': { valid: false },+ 'global-coupon': { valid: true },+ },+ });++ const { discountDetails } = await resolveCheckoutDiscount({+ stripeClient,+ entitlementCouponId: 'entitlement-coupon',+ globalCouponId: 'global-coupon',+ });++ expect(discountDetails).to.eql({ discounts: [{ coupon: 'global-coupon' }] });+ });++ test('when no entitlement coupon is provided, the global coupon is applied', async () => {+ const stripeClient = createStripeClientStub({+ coupons: {+ 'global-coupon': { valid: true },+ },+ });++ const { discountDetails } = await resolveCheckoutDiscount({+ stripeClient,+ globalCouponId: 'global-coupon',+ });++ expect(discountDetails).to.eql({ discounts: [{ coupon: 'global-coupon' }] });+ });++ test('when no coupon is valid, promotion codes are allowed instead of a discount', async () => {+ const stripeClient = createStripeClientStub({+ coupons: {+ 'entitlement-coupon': { valid: false },+ },+ });++ const { discountDetails } = await resolveCheckoutDiscount({+ stripeClient,+ entitlementCouponId: 'entitlement-coupon',+ globalCouponId: 'global-coupon',+ });++ expect(discountDetails).to.eql({ allow_promotion_codes: true });+ });++ test('when no coupon is configured, promotion codes are allowed', async () => {+ const stripeClient = createStripeClientStub();++ const { discountDetails } = await resolveCheckoutDiscount({ stripeClient });++ expect(discountDetails).to.eql({ allow_promotion_codes: true });+ });+ });+});diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.services.tsindex 651b81fb..09f969ed 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts@@ -52,17 +52,41 @@ async function createCustomer({return { customerId };}+export async function resolveCheckoutDiscount({+ stripeClient,+ entitlementCouponId,+ globalCouponId,+}: {+ stripeClient: Stripe;+ entitlementCouponId?: string;+ globalCouponId?: string;+}) {+ // Checkout sessions accept a single coupon, mutually exclusive with promotion+ // codes, so the first valid coupon wins: entitlement, then global, then none+ for (const couponId of [entitlementCouponId, globalCouponId]) {+ const { coupon } = await getCoupon({ stripeClient, couponId });++ if (!isNil(coupon)) {+ return { discountDetails: { discounts: [{ coupon: coupon.id }] } };+ }+ }++ return { discountDetails: { allow_promotion_codes: true } };+}+export async function createCheckoutUrl({stripeClient,customerId,priceId,organizationId,+ entitlementCouponId,config,}: {stripeClient: Stripe;customerId: string;priceId: string;organizationId: string;+ entitlementCouponId?: string;config: Config;}) {const { clientBaseUrl } = getClientBaseUrl({ config });@@ -75,13 +99,11 @@ export async function createCheckoutUrl({const { globalCouponId } = config.subscriptions;- const { coupon } = await getCoupon({ stripeClient, couponId: globalCouponId });-- // If there's no coupon or if the coupon is invalid (expired), we just don't apply any discount but allow promotion codes- // to be used at checkout, can't do both at the same time- const discountDetails = isNil(coupon)- ? { allow_promotion_codes: true }- : { discounts: [{ coupon: coupon.id }] };+ const { discountDetails } = await resolveCheckoutDiscount({+ stripeClient,+ entitlementCouponId,+ globalCouponId,+ });const session = await stripeClient.checkout.sessions.create({customer: customerId,