A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(billing): rework refund webhook tests for no purchase block
Hampus4a8fe1b82899
diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookRefund.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookRefund.test.tsindex 2faaaefbf..60c756131 100644--- a/fluxer_api/src/api/stripe/tests/StripeWebhookRefund.test.ts+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookRefund.test.ts@@ -43,47 +43,6 @@ describe('Stripe Webhook Refund', () => {);}describe('charge.refunded', () => {- test('revokes premium and records first refund', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_first_123';- const checkoutSessionId = 'cs_test_refund_first_123';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- useRefundListHandler('ch_test_refund_123');- await sendStripeWebhook(harness, {- type: 'charge.refunded',- data: {- object: {- id: 'ch_test_refund_123',- payment_intent: paymentIntentId,- amount_refunded: 2500,- },- },- });- const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser).not.toBeNull();- expect(updatedUser!.firstRefundAt).not.toBeNull();- const updatedPayment = await userRepository.getPaymentByPaymentIntent(paymentIntentId);- expect(updatedPayment).not.toBeNull();- expect(updatedPayment!.status).toBe('refunded');- });async function seedRefundedPayment(userId: ReturnType<typeof createUserID>,suffix: string,@@ -108,478 +67,65 @@ describe('Stripe Webhook Refund', () => {});return {paymentIntentId, chargeId: `ch_test_refund_${suffix}`};}- test('applies permanent purchase block when a second distinct refund exists', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const userRepository = new UserRepository();- const firstRefundDate = new Date('2024-01-01');- await userRepository.patchUpsert(- userId,- {first_refund_at: firstRefundDate},- (await userRepository.findUnique(userId))!.toRow(),- );- const {paymentIntentId, chargeId} = await seedRefundedPayment(userId, 'second_456');- const nowSeconds = Math.floor(Date.now() / 1000);- const earlier = {- id: 're_test_refund_second_456_1',+ function customerRefund(id: string, chargeId: string, paymentIntentId: string, created: number) {+ return {+ id,object: 'refund',charge: chargeId,payment_intent: paymentIntentId,amount: 1200,currency: 'usd',status: 'succeeded',- created: nowSeconds - 600,- metadata: {},- };- const latest = {...earlier, id: 're_test_refund_second_456_2', amount: 1300, created: nowSeconds};- await sendStripeWebhook(harness, {- type: 'charge.refunded',- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- refunds: {object: 'list', has_more: false, url: `/v1/charges/${chargeId}/refunds`, data: [earlier, latest]},- },- },- });- const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser).not.toBeNull();- expect(updatedUser!.firstRefundAt).toEqual(firstRefundDate);- expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(PremiumFlags.PURCHASE_DISABLED);- const updatedPayment = await userRepository.getPaymentByPaymentIntent(paymentIntentId);- expect(updatedPayment).not.toBeNull();- expect(updatedPayment!.status).toBe('refunded');- });- test('does not block purchases when one refund is redelivered after the allowance claim expired', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const userRepository = new UserRepository();- const firstRefundDate = new Date('2024-01-01');- await userRepository.patchUpsert(- userId,- {first_refund_at: firstRefundDate},- (await userRepository.findUnique(userId))!.toRow(),- );- const {paymentIntentId, chargeId} = await seedRefundedPayment(userId, 'replay_789');- const onlyRefund = {- id: 're_test_refund_replay_789',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 2500,- currency: 'usd',- status: 'succeeded',- created: Math.floor(Date.now() / 1000),+ created,metadata: {},};- await sendStripeWebhook(harness, {- type: 'charge.refunded',- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- refunds: {object: 'list', has_more: false, url: `/v1/charges/${chargeId}/refunds`, data: [onlyRefund]},- },- },- });- const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser).not.toBeNull();- expect(updatedUser!.firstRefundAt).toEqual(firstRefundDate);- expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- });- test('counts a refund once when the same charge.refunded event is redelivered', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_retry_123';- const checkoutSessionId = 'cs_test_refund_retry_123';- const chargeId = 'ch_test_refund_retry_123';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- useRefundListHandler(chargeId, [- {- id: 're_test_refund_retry_123',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 2500,- currency: 'brl',- status: 'succeeded',- created: Math.floor(Date.now() / 1000),- metadata: {},- },- ]);- const chargeEvent = {- type: 'charge.refunded' as const,- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- },- },- };- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_retry_1'});- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_retry_2'});- const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).not.toBeNull();- expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- });- test('counts a refund once when charge.refunded lands before the refund record exists', async () => {+ }+ test('marks the payment refunded without starting the self-serve refund cooldown', async () => {const account = await createTestAccount(harness);const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_late_record';- const checkoutSessionId = 'cs_test_refund_late_record';- const chargeId = 'ch_test_refund_late_record';- const refundId = 're_test_refund_late_record';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- const refund = {- id: refundId,- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 2500,- currency: 'brl',- status: 'succeeded',- created: Math.floor(Date.now() / 1000),- metadata: {},- };- const chargeEvent = {- type: 'charge.refunded' as const,- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- },- },- };+ const {paymentIntentId, chargeId} = await seedRefundedPayment(userId, 'support_123');useRefundListHandler(chargeId);- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_late_record_1'});- const afterFallback = await userRepository.findUnique(userId);- expect(afterFallback!.firstRefundAt).not.toBeNull();- expect(afterFallback!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- await sendStripeWebhook(harness, {- id: 'evt_test_refund_late_record_2',- type: 'refund.created',- data: {object: refund},- });- useRefundListHandler(chargeId, [refund]);- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_late_record_3'});- const afterRecord = await userRepository.findUnique(userId);- expect(afterRecord!.firstRefundAt!.getTime()).toBe(afterFallback!.firstRefundAt!.getTime());- expect(afterRecord!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- });- test('does not count a refund Fluxer issued itself against the refund allowance', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_system_123';- const checkoutSessionId = 'cs_test_refund_system_123';- const chargeId = 'ch_test_refund_system_123';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- useRefundListHandler(chargeId, [- {- id: 're_test_refund_system_123',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 2500,- currency: 'brl',- status: 'succeeded',- created: Math.floor(Date.now() / 1000),- metadata: {rejection_reason: 'duplicate_active_subscription'},- },- ]);- await sendStripeWebhook(harness, {- type: 'charge.refunded',- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- },- },- });- const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).toBeNull();- expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- });- test('does not count a refund Fluxer issued for a localized card country mismatch', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_card_mismatch';- const checkoutSessionId = 'cs_test_refund_card_mismatch';- const chargeId = 'ch_test_refund_card_mismatch';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- useRefundListHandler(chargeId, [- {- id: 're_test_refund_card_mismatch',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 2500,- currency: 'brl',- status: 'succeeded',- created: Math.floor(Date.now() / 1000),- metadata: {rejection_reason: 'localized_card_country_mismatch'},- },- ]);await sendStripeWebhook(harness, {type: 'charge.refunded',- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- },- },+ data: {object: {id: chargeId, payment_intent: paymentIntentId, amount_refunded: 2500}},});const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).toBeNull();+ expect(updatedUser!.lastRefundAt).toBeNull();expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);const updatedPayment = await userRepository.getPaymentByPaymentIntent(paymentIntentId);expect(updatedPayment!.status).toBe('refunded');});- test('counts only the customer refund when Fluxer issued a later system refund on the same charge', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_mixed';- const checkoutSessionId = 'cs_test_refund_mixed';- const chargeId = 'ch_test_refund_mixed';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- const nowSeconds = Math.floor(Date.now() / 1000);- const chargeEvent = {- type: 'charge.refunded' as const,- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- refunds: {- object: 'list',- has_more: false,- url: `/v1/charges/${chargeId}/refunds`,- data: [- {- id: 're_test_refund_mixed_customer',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 1500,- currency: 'brl',- status: 'succeeded',- created: nowSeconds - 600,- metadata: {},- },- {- id: 're_test_refund_mixed_system',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 1000,- currency: 'brl',- status: 'succeeded',- created: nowSeconds,- metadata: {rejection_reason: 'duplicate_active_subscription'},- },- ],- },- },- },- };- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_mixed_1'});- const afterFirst = await userRepository.findUnique(userId);- expect(afterFirst!.firstRefundAt).not.toBeNull();- expect(afterFirst!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_test_refund_mixed_2'});- const afterRetry = await userRepository.findUnique(userId);- expect(afterRetry!.firstRefundAt!.getTime()).toBe(afterFirst!.firstRefundAt!.getTime());- expect(afterRetry!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- });- test('counts a second, distinct refund against the allowance after the first one was already counted', async () => {- const account = await createTestAccount(harness);- const userId = createUserID(BigInt(account.userId));- const {PaymentRepository} = await import('@app/api/user/repositories/PaymentRepository');- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');- const paymentRepository = new PaymentRepository();- const userRepository = new UserRepository();- const paymentIntentId = 'pi_test_refund_ladder';- const checkoutSessionId = 'cs_test_refund_ladder';- const chargeId = 'ch_test_refund_ladder';- await paymentRepository.createPayment({- checkout_session_id: checkoutSessionId,- user_id: userId,- price_id: 'price_test_monthly',- product_type: 'monthly_subscription',- status: 'completed',- is_gift: false,- created_at: new Date(),- });- await paymentRepository.updatePayment({- checkout_session_id: checkoutSessionId,- payment_intent_id: paymentIntentId,- completed_at: new Date(),- });- const nowSeconds = Math.floor(Date.now() / 1000);- function chargeEventWithRefunds(refunds: Array<Record<string, unknown>>) {- return {- type: 'charge.refunded' as const,- data: {- object: {- id: chargeId,- payment_intent: paymentIntentId,- amount_refunded: 2500,- refunds: {- object: 'list',- has_more: false,- url: `/v1/charges/${chargeId}/refunds`,- data: refunds,- },- },- },- };- }- const firstRefund = {- id: 're_test_refund_ladder_1',- object: 'refund',- charge: chargeId,- payment_intent: paymentIntentId,- amount: 1200,- currency: 'brl',- status: 'succeeded',- created: nowSeconds - 600,- metadata: {},- };- const secondRefund = {- ...firstRefund,- id: 're_test_refund_ladder_2',- amount: 1300,- created: nowSeconds,- };- await sendStripeWebhook(harness, {...chargeEventWithRefunds([firstRefund]), id: 'evt_test_refund_ladder_1'});- const afterFirst = await userRepository.findUnique(userId);- expect(afterFirst!.firstRefundAt).not.toBeNull();- expect(afterFirst!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);- await sendStripeWebhook(harness, {- ...chargeEventWithRefunds([firstRefund, secondRefund]),- id: 'evt_test_refund_ladder_2',- });- const afterSecond = await userRepository.findUnique(userId);- expect(afterSecond!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(PremiumFlags.PURCHASE_DISABLED);- });- test('falls back to customer ID when payment intent is not indexed (subscription mode)', async () => {+ test('never blocks purchases however many refunds a user has had', async () => {const account = await createTestAccount(harness);const userId = createUserID(BigInt(account.userId));- const {UserRepository} = await import('@app/api/user/repositories/UserRepository');const userRepository = new UserRepository();- const stripeCustomerId = 'cus_test_subscription_fallback';+ const earlierRefundAt = new Date('2024-01-01');await userRepository.patchUpsert(userId,- {stripe_customer_id: stripeCustomerId},+ {first_refund_at: earlierRefundAt},(await userRepository.findUnique(userId))!.toRow(),);- useRefundListHandler('ch_test_refund_sub_789');+ const {paymentIntentId, chargeId} = await seedRefundedPayment(userId, 'many_456');+ const nowSeconds = Math.floor(Date.now() / 1000);+ const refunds = [+ customerRefund('re_test_refund_many_456_1', chargeId, paymentIntentId, nowSeconds - 600),+ customerRefund('re_test_refund_many_456_2', chargeId, paymentIntentId, nowSeconds),+ ];await sendStripeWebhook(harness, {type: 'charge.refunded',data: {object: {- id: 'ch_test_refund_sub_789',- payment_intent: 'pi_test_not_indexed_789',- customer: stripeCustomerId,- amount_refunded: 4999,+ id: chargeId,+ payment_intent: paymentIntentId,+ amount_refunded: 2400,+ refunds: {object: 'list', has_more: false, url: `/v1/charges/${chargeId}/refunds`, data: refunds},},},});const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser).not.toBeNull();- expect(updatedUser!.firstRefundAt).not.toBeNull();+ expect(updatedUser!.lastRefundAt).toEqual(earlierRefundAt);+ expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);});test('skips premium action for donation customer refund', async () => {const donationCustomerId = 'cus_test_donation_refund';@@ -710,6 +256,7 @@ describe('Stripe Webhook Refund', () => {const userId = createUserID(BigInt(account.userId));const userRepository = new UserRepository();const subscriptionId = 'sub_test_webhook_finalize';+ const refundCreated = Math.floor(Date.now() / 1000) - 120;await userRepository.patchUpsert(userId,{stripe_subscription_id: subscriptionId},@@ -726,6 +273,7 @@ describe('Stripe Webhook Refund', () => {object: {id: 'pyr_test_webhook_finalize',status: 'succeeded',+ created: refundCreated,amount: 2499,currency: 'brl',metadata: {@@ -738,7 +286,7 @@ describe('Stripe Webhook Refund', () => {},});const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).not.toBeNull();+ expect(updatedUser!.lastRefundAt!.getTime()).toBe(refundCreated * 1000);});test('does not finalize cooldown while the refund is still pending', async () => {const account = await createTestAccount(harness);@@ -761,7 +309,7 @@ describe('Stripe Webhook Refund', () => {},});const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).toBeNull();+ expect(updatedUser!.lastRefundAt).toBeNull();});});describe('refund.failed', () => {@@ -787,7 +335,7 @@ describe('Stripe Webhook Refund', () => {},});const updatedUser = await userRepository.findUnique(userId);- expect(updatedUser!.firstRefundAt).toBeNull();+ expect(updatedUser!.lastRefundAt).toBeNull();});});});