📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Preserve coupon when changing plans; don't include imported events into billable usage
Blue Mousee9a89c7c5a9d
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.tsindex 9e1f32eda..917cf3403 100644--- a/backend/apps/cloud/src/common/constants.ts+++ b/backend/apps/cloud/src/common/constants.ts@@ -37,8 +37,8 @@ const isValidPID = (pid: string) => PID_REGEX.test(pid)// redis keysconst getRedisProjectKey = (pid: string) => `pid_${pid}`-const getRedisUserCountKey = (uid: string) => `user_c_${uid}`-const getRedisUserUsageInfoKey = (uid: string) => `user_ui_${uid}`+const getRedisUserCountKey = (uid: string) => `user_c_billable_${uid}`+const getRedisUserUsageInfoKey = (uid: string) => `user_ui_billable_${uid}`const getRedisCaptchaKey = (token: string) => `captcha_${hash(token)}`const REDIS_USERS_COUNT_KEY = 'stats:users_count'diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex c37397cb2..8fa50b6dd 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -909,6 +909,7 @@ export class ProjectService {WHERE created BETWEEN {monthStart:String} AND {monthEnd:String}AND pid IN ({pids:Array(FixedString(12))})AND type IN ('pageview', 'custom_event', 'captcha', 'error')+ AND importID IS NULL`const { data: counts } = await clickhouse@@ -1006,6 +1007,7 @@ export class ProjectService {WHERE pid IN ({pids:Array(FixedString(12))})AND created BETWEEN {periodStart:String} AND {periodEnd:String}AND type IN ('pageview', 'custom_event', 'captcha', 'error')+ AND importID IS NULL`const { data: counts } = await clickhousediff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex b2aab1f5d..3e0f93de1 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -250,6 +250,7 @@ const generatePlanUsageQueryForUser = (): string => {FROM eventsWHERE pid IN ({pids:Array(FixedString(12))})AND type IN ('pageview', 'custom_event', 'error', 'captcha')+ AND importID IS NULLAND created BETWEEN {from:String} AND {to:String}`}diff --git a/backend/apps/cloud/src/user/paddle-subscription-discount.spec.ts b/backend/apps/cloud/src/user/paddle-subscription-discount.spec.tsnew file mode 100644index 000000000..278e49901--- /dev/null+++ b/backend/apps/cloud/src/user/paddle-subscription-discount.spec.ts@@ -0,0 +1,181 @@+import { getPaddleSubscriptionDiscount } from './paddle-subscription-discount'++describe('Paddle subscription discounts', () => {+ const credentials = { vendorId: '1', apiKey: 'test-key' }+ let fetchMock: jest.SpyInstance++ const reply = (data: unknown, status = 200) =>+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify(data), { status }),+ )++ const checkout = (couponCode = 'SAVE30', subscriptionId = 123) => {+ reply({+ success: true,+ response: [+ {+ checkout_id: 'checkout-123',+ is_one_off: false,+ subscription: { subscription_id: 123 },+ },+ ],+ })+ reply({+ state: 'processed',+ order: { subscription_id: subscriptionId, coupon_code: couponCode },+ })+ }++ const coupon = (overrides = {}) => {+ reply({+ success: true,+ response: [+ {+ coupon: 'SAVE30',+ is_recurring: true,+ discount_type: 'percentage',+ discount_amount: 30,+ discount_currency: 'USD',+ ...overrides,+ },+ ],+ })+ }++ const plan = (id = 456, price = '100.00') =>+ reply({+ success: true,+ response: [{ id, recurring_price: { USD: price } }],+ })++ beforeEach(() => {+ fetchMock = jest.spyOn(global, 'fetch')+ })++ afterEach(() => jest.restoreAllMocks())++ it.each([+ [456, '100.00', 70],+ [789, '49.00', 34.3],+ [101, '199.99', 139.99],+ ])(+ 'recalculates 30%% off destination plan %s',+ async (id, price, expected) => {+ checkout()+ coupon()+ plan(id, price)++ await expect(+ getPaddleSubscriptionDiscount('123', id, 'USD', credentials),+ ).resolves.toEqual({ recurring_price: expected })++ const couponRequest = fetchMock.mock.calls[2][1].body as URLSearchParams+ expect(couponRequest.get('product_id')).toBe(String(id))+ expect(couponRequest.get('coupon')).toBe('SAVE30')+ expect(couponRequest.has('is_valid')).toBe(false)+ },+ )++ it('retains a recurring discount after its checkout redemption limit or expiry', async () => {+ checkout()+ coupon({ allowed_uses: 1, times_used: 1, expires: '2020-01-01 00:00:00' })+ plan()++ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({ recurring_price: 70 })+ })++ it('uses normal pricing without a coupon', async () => {+ checkout('')+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({})+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('does not apply a coupon outside its product scope', async () => {+ checkout()+ reply({ success: true, response: [] })+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({})+ expect(fetchMock).toHaveBeenCalledTimes(3)+ })++ it('does not turn a one-time coupon into a recurring discount', async () => {+ checkout()+ coupon({ is_recurring: false })+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({})+ })++ it('preserves a flat discount in the matching currency', async () => {+ checkout()+ coupon({ discount_type: 'flat', discount_amount: 10 })+ plan(456, '29.00')+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({ recurring_price: 19 })+ })++ it('does not apply a flat discount in a different currency', async () => {+ checkout()+ coupon({ discount_type: 'flat', discount_currency: 'EUR' })+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({})+ })++ it('caps a discount at the price of the plan', async () => {+ checkout()+ coupon({ discount_type: 'flat', discount_amount: 100 })+ plan(456, '29.00')+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({ recurring_price: 0 })+ })++ it('rejects checkout details belonging to a different subscription', async () => {+ checkout('SAVE30', 999)+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).rejects.toThrow('Unable to verify the Paddle subscription checkout')+ })++ it('fails instead of silently dropping discounts when Paddle fails', async () => {+ checkout()+ reply({ success: false }, 503)+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).rejects.toThrow('Unable to verify Paddle subscription discount')+ })++ it('rejects missing destination currency pricing', async () => {+ checkout()+ coupon()+ plan()+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'GBP', credentials),+ ).rejects.toThrow('Invalid Paddle subscription discount pricing')+ })++ it('skips one-off charges when finding the original subscription checkout', async () => {+ reply({+ success: true,+ response: Array.from({ length: 100 }, () => ({+ checkout_id: 'addon-checkout',+ is_one_off: true,+ subscription: { subscription_id: 123 },+ })),+ })+ checkout()+ coupon()+ plan()+ await expect(+ getPaddleSubscriptionDiscount('123', 456, 'USD', credentials),+ ).resolves.toEqual({ recurring_price: 70 })+ expect(fetchMock.mock.calls[1][1].body.get('page')).toBe('2')+ })+})diff --git a/backend/apps/cloud/src/user/paddle-subscription-discount.ts b/backend/apps/cloud/src/user/paddle-subscription-discount.tsnew file mode 100644index 000000000..db6890381--- /dev/null+++ b/backend/apps/cloud/src/user/paddle-subscription-discount.ts@@ -0,0 +1,141 @@+interface PaddleCredentials {+ vendorId: string+ apiKey: string+}++interface PaddleTransaction {+ checkout_id: string+ is_one_off: boolean+ subscription: { subscription_id: number }+}++interface PaddleCoupon {+ coupon: string+ is_recurring: boolean+ discount_type: 'percentage' | 'flat'+ discount_amount: number+ discount_currency: string+}++const TIMEOUT_MS = 10000++export async function getPaddleSubscriptionDiscount(+ subscriptionId: string,+ planId: number,+ currency: string,+ credentials: PaddleCredentials,+): Promise<{ recurring_price?: number }> {+ if (!/^\d+$/.test(subscriptionId)) {+ throw new Error('Invalid Paddle subscription ID')+ }++ async function post<T>(endpoint: string, params: Record<string, string>) {+ const response = await fetch(+ `https://vendors.paddle.com/api/2.0/${endpoint}`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ vendor_id: credentials.vendorId,+ vendor_auth_code: credentials.apiKey,+ ...params,+ }),+ signal: AbortSignal.timeout(TIMEOUT_MS),+ },+ )+ const data = await response.json()++ if (+ !response.ok ||+ data.success !== true ||+ !Array.isArray(data.response)+ ) {+ throw new Error('Unable to verify Paddle subscription discount')+ }++ return data.response as T[]+ }++ let checkoutId: string | undefined+ for (let page = 1; ; page++) {+ const transactions = await post<PaddleTransaction>(+ `subscription/${subscriptionId}/transactions`,+ { page: String(page), results_per_page: '100' },+ )+ checkoutId = transactions.find(+ (transaction) =>+ !transaction.is_one_off &&+ String(transaction.subscription?.subscription_id) === subscriptionId &&+ transaction.checkout_id,+ )?.checkout_id++ if (checkoutId || transactions.length < 100) break+ }++ if (!checkoutId) {+ throw new Error('Unable to find the Paddle subscription checkout')+ }++ const orderResponse = await fetch(+ `https://checkout.paddle.com/api/1.0/order?${new URLSearchParams({ checkout_id: checkoutId })}`,+ { signal: AbortSignal.timeout(TIMEOUT_MS) },+ )+ const orderData = await orderResponse.json()+ const order = orderData.order++ if (+ !orderResponse.ok ||+ orderData.state !== 'processed' ||+ String(order?.subscription_id) !== subscriptionId+ ) {+ throw new Error('Unable to verify the Paddle subscription checkout')+ }++ if (!order.coupon_code) return {}++ const coupons = await post<PaddleCoupon>('product/list_coupons', {+ product_id: String(planId),+ coupon: order.coupon_code,+ })+ const coupon = coupons.find(+ (candidate) => candidate.coupon === order.coupon_code,+ )++ if (!coupon || !coupon.is_recurring) return {}+ if (+ coupon.discount_type === 'flat' &&+ coupon.discount_currency !== currency+ ) {+ return {}+ }++ const plans = await post<{+ id: number+ recurring_price: Record<string, string>+ }>('subscription/plans', { plan: String(planId) })+ const price = plans.find((plan) => Number(plan.id) === planId)+ ?.recurring_price[currency]+ const amount = Number(price)+ const discount = Number(coupon.discount_amount)++ if (+ price == null ||+ !Number.isFinite(amount) ||+ amount < 0 ||+ !Number.isFinite(discount) ||+ discount < 0 ||+ (coupon.discount_type === 'percentage' && discount > 100) ||+ !['percentage', 'flat'].includes(coupon.discount_type)+ ) {+ throw new Error('Invalid Paddle subscription discount pricing')+ }++ const discountedAmount =+ coupon.discount_type === 'percentage'+ ? amount * (1 - discount / 100)+ : amount - discount++ return {+ recurring_price: Math.max(0, Math.round(discountedAmount * 100) / 100),+ }+}diff --git a/backend/apps/cloud/src/user/user-subscription.spec.ts b/backend/apps/cloud/src/user/user-subscription.spec.tsnew file mode 100644index 000000000..e15e8cc02--- /dev/null+++ b/backend/apps/cloud/src/user/user-subscription.spec.ts@@ -0,0 +1,101 @@+jest.mock('../common/constants', () => ({ redis: {} }))+jest.mock('../organisation/organisation.service', () => ({+ OrganisationService: class {},+}))+jest.mock('./paddle-subscription-discount')++import { UserService } from './user.service'+import { BillingFrequency, PlanCode, PlanType } from './entities/user.entity'+import { getPaddleSubscriptionDiscount } from './paddle-subscription-discount'++describe('subscription plan changes', () => {+ const discountMock = jest.mocked(getPaddleSubscriptionDiscount)+ let service: UserService+ let fetchMock: jest.SpyInstance++ beforeEach(() => {+ service = Object.create(UserService.prototype)+ service.findOne = jest.fn().mockResolvedValue({+ id: 'user-1',+ subID: '123',+ tierCurrency: 'USD',+ planCode: PlanCode['100k'],+ planType: PlanType.standard,+ billingFrequency: BillingFrequency.Monthly,+ })+ service.update = jest.fn()+ service.recordUserSubscription = jest.fn()+ service.refreshWebsiteAddonEntitlements = jest.fn()+ service.refreshSessionReplayAddonEntitlements = jest.fn()+ discountMock.mockResolvedValue({ recurring_price: 70 })+ fetchMock = jest.spyOn(global, 'fetch').mockImplementation(+ async () =>+ new Response(+ JSON.stringify({+ success: true,+ response: {+ subscription_id: '123',+ immediate_payment: { amount: 15, currency: 'USD' },+ next_payment: { amount: 70, currency: 'USD', date: '2026-10-01' },+ },+ }),+ ),+ )+ })++ afterEach(() => {+ jest.restoreAllMocks()+ jest.clearAllMocks()+ })++ it.each([+ [PlanType.standard, PlanType.plus, 925536],+ [PlanType.plus, PlanType.standard, 916455],+ [PlanType.standard, PlanType.standard, 854654],+ [PlanType.standard, PlanType.plus, 925537],+ ])(+ 'preserves preview/update pricing from %s to %s (%s)',+ async (from, to, planId) => {+ jest.mocked(service.findOne).mockResolvedValue({+ id: 'user-1',+ subID: '123',+ tierCurrency: 'USD',+ planCode: PlanCode['100k'],+ planType: from,+ billingFrequency: BillingFrequency.Monthly,+ } as Awaited<ReturnType<UserService['findOne']>>)+ const preview = await service.previewSubscription('user-1', planId, to)+ await service.updateSubscription('user-1', planId, to)++ expect(preview.nextPayment.amount).toBe(70)+ expect(discountMock).toHaveBeenCalledTimes(2)+ expect(discountMock).toHaveBeenCalledWith(+ '123',+ planId,+ 'USD',+ expect.any(Object),+ )+ for (const [, request] of fetchMock.mock.calls) {+ expect(JSON.parse(request.body)).toMatchObject({+ subscription_id: 123,+ plan_id: planId,+ recurring_price: 70,+ keep_modifiers: true,+ prorate: true,+ bill_immediately: true,+ })+ }+ },+ )++ it('does not update Paddle or local entitlements if discount verification fails', async () => {+ jest.spyOn(console, 'error').mockImplementation(() => {})+ discountMock.mockRejectedValue(new Error('Paddle unavailable'))++ await expect(+ service.updateSubscription('user-1', 925536, 'plus'),+ ).rejects.toThrow()+ expect(fetchMock).not.toHaveBeenCalled()+ expect(service.update).not.toHaveBeenCalled()+ })+})diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.tsindex f45d39e5e..f53aac651 100644--- a/backend/apps/cloud/src/user/user.service.ts+++ b/backend/apps/cloud/src/user/user.service.ts@@ -62,6 +62,7 @@ import {SubscriptionDunningStatus,} from './entities/subscription-dunning.entity'import { UserSubscription } from './entities/user-subscription.entity'+import { getPaddleSubscriptionDiscount } from './paddle-subscription-discount'import { UserGoogleDTO } from './dto/user-google.dto'import { UserGithubDTO } from './dto/user-github.dto'import { EMAIL_ACTION_ENCRYPTION_KEY, redis } from '../common/constants'@@ -2692,6 +2693,12 @@ export class UserService {let preview: any = {}try {+ const discount = await getPaddleSubscriptionDiscount(+ String(user.subID),+ planID,+ user.tierCurrency,+ { vendorId: PADDLE_VENDOR_ID, apiKey: PADDLE_API_KEY },+ )const res = await fetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -2703,7 +2710,8 @@ export class UserService {prorate: true,bill_immediately: true,currency: user.tierCurrency,- keep_modifiers: false,+ keep_modifiers: true,+ ...discount,}),})preview = { data: await res.json() }@@ -2824,6 +2832,12 @@ export class UserService {let result: any = {}try {+ const discount = await getPaddleSubscriptionDiscount(+ String(user.subID),+ planID,+ user.tierCurrency,+ { vendorId: PADDLE_VENDOR_ID, apiKey: PADDLE_API_KEY },+ )const res = await fetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -2835,7 +2849,8 @@ export class UserService {prorate: true,bill_immediately: true,currency: user.tierCurrency,- keep_modifiers: false,+ keep_modifiers: true,+ ...discount,passthrough: JSON.stringify({uid: id,planType,