Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(api): stop refunded invoices restoring cancelled premium (#3671)

Hampus94ab5cb3834a
diff --git a/fluxer_api/src/api/stripe/StripeSubscriptionPeriod.ts b/fluxer_api/src/api/stripe/StripeSubscriptionPeriod.ts
index 798e7f7dc..f2946c065 100644
--- a/fluxer_api/src/api/stripe/StripeSubscriptionPeriod.ts
+++ b/fluxer_api/src/api/stripe/StripeSubscriptionPeriod.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {extractId} from '@app/api/stripe/StripeUtils';
import type Stripe from 'stripe';
type StripePaymentIntentWithExpandedLatestCharge = Stripe.PaymentIntent & {
@@ -7,8 +8,13 @@ type StripePaymentIntentWithExpandedLatestCharge = Stripe.PaymentIntent & {
};
type StripeInvoicePaymentEntry = {
payment?: {
+ charge?: string | Stripe.Charge | null;
payment_intent?: string | StripePaymentIntentWithExpandedLatestCharge | null;
} | null;
+ status?: string | null;
+ status_transitions?: {
+ paid_at?: number | null;
+ } | null;
};
type StripeInvoiceWithPayments = Stripe.Invoice & {
payments?: {
@@ -140,6 +146,32 @@ export function getFirstInvoicePaymentIntentId(invoice: Stripe.Invoice | null):
return paymentIntent.id ?? null;
}
+export function getInvoicePaymentRef(invoice: Stripe.Invoice): {
+ chargeId: string | null;
+ paymentIntentId: string | null;
+ paidAt: Date | null;
+} | null {
+ const candidates = (invoice as StripeInvoiceWithPayments).payments?.data ?? [];
+ const preferred =
+ candidates.find((c) => c.status === 'paid' && (c.payment?.payment_intent || c.payment?.charge)) ??
+ candidates.find((c) => c.payment?.payment_intent || c.payment?.charge) ??
+ null;
+ if (!preferred) {
+ return null;
+ }
+ const paymentIntentId = extractId(preferred.payment?.payment_intent);
+ let chargeId = extractId(preferred.payment?.charge);
+ if (!chargeId && preferred.payment?.payment_intent && typeof preferred.payment.payment_intent !== 'string') {
+ chargeId = extractId(preferred.payment.payment_intent.latest_charge);
+ }
+ const paidAtSec = preferred.status_transitions?.paid_at ?? null;
+ return {
+ chargeId,
+ paymentIntentId,
+ paidAt: paidAtSec ? new Date(paidAtSec * 1000) : null,
+ };
+}
+
export function getSubscriptionBillingCycle(subscription: Stripe.Subscription): 'monthly' | 'yearly' | null {
const item = getPrimarySubscriptionItem(subscription);
const interval = item?.price?.recurring?.interval;
diff --git a/fluxer_api/src/api/stripe/services/StripeRefundService.ts b/fluxer_api/src/api/stripe/services/StripeRefundService.ts
index 58960f3d2..aaf24363f 100644
--- a/fluxer_api/src/api/stripe/services/StripeRefundService.ts
+++ b/fluxer_api/src/api/stripe/services/StripeRefundService.ts
@@ -11,6 +11,7 @@ import {
} from '@app/api/store_billing/GooglePlayRefundTarget';
import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';
import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';
+import {getInvoicePaymentRef} from '@app/api/stripe/StripeSubscriptionPeriod';
import {extractId} from '@app/api/stripe/StripeUtils';
import {
buildRefundEligibility,
@@ -59,52 +60,10 @@ type GooglePlayLatestTarget = RefundEligibilityTarget & {
type LatestRefundTarget = RefundTarget | GooglePlayLatestTarget;
-type StripeInvoiceWithPayments = Stripe.Invoice & {
- customer?: string | Stripe.Customer | null;
- payments?: {
- data?: Array<{
- payment?: {
- charge?: string | Stripe.Charge | null;
- payment_intent?: string | Stripe.PaymentIntent | null;
- } | null;
- status?: string | null;
- status_transitions?: {
- paid_at?: number | null;
- } | null;
- }>;
- } | null;
-};
-
function resolveInvoiceSubscriptionId(invoice: Stripe.Invoice): string | null {
return extractId(invoice.parent?.subscription_details?.subscription ?? null);
}
-function getInvoicePaymentRef(invoice: Stripe.Invoice): {
- chargeId: string | null;
- paymentIntentId: string | null;
- paidAt: Date | null;
-} | null {
- const candidates = (invoice as StripeInvoiceWithPayments).payments?.data ?? [];
- const preferred =
- candidates.find((c) => c.status === 'paid' && (c.payment?.payment_intent || c.payment?.charge)) ??
- candidates.find((c) => c.payment?.payment_intent || c.payment?.charge) ??
- null;
- if (!preferred) {
- return null;
- }
- const paymentIntentId = extractId(preferred.payment?.payment_intent);
- let chargeId = extractId(preferred.payment?.charge);
- if (!chargeId && preferred.payment?.payment_intent && typeof preferred.payment.payment_intent !== 'string') {
- chargeId = extractId(preferred.payment.payment_intent.latest_charge);
- }
- const paidAtSec = preferred.status_transitions?.paid_at ?? null;
- return {
- chargeId,
- paymentIntentId,
- paidAt: paidAtSec ? new Date(paidAtSec * 1000) : null,
- };
-}
-
export class StripeRefundService {
constructor(
private readonly stripe: Stripe | null,
diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookSubscription.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookSubscription.test.ts
index a7902cb5d..f41d84fc9 100644
--- a/fluxer_api/src/api/stripe/tests/StripeWebhookSubscription.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookSubscription.test.ts
@@ -3,6 +3,7 @@
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createUserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
+import {createTestStoreEntitlementService} from '@app/api/store_billing/tests/StoreBillingTestUtils';
import {ProductType} from '@app/api/stripe/ProductRegistry';
import {
sendStripeWebhook,
@@ -11,16 +12,20 @@ import {
} from '@app/api/stripe/tests/StripeWebhookTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {
+ createPaymentIntentInvoicePayments,
createStripeApiHandlers,
createSubscriptionDeletedEvent,
createSubscriptionUpdatedEvent,
type StripeApiHandlers,
} from '@app/api/test/msw/handlers/StripeApiHandlers';
import {server} from '@app/api/test/msw/server';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {PaymentRepository} from '@app/api/user/repositories/PaymentRepository';
import {UserRepository} from '@app/api/user/repositories/UserRepository';
import {getPremiumPaymentRecoveryGraceMs, PREMIUM_GRACE_PERIOD_MS} from '@app/api/user/UserHelpers';
+import processPremiumStateReconciliationQueue from '@app/api/worker/tasks/ProcessPremiumStateReconciliationQueue';
+import {getWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
import {HttpResponse, http} from 'msw';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
@@ -553,6 +558,60 @@ describe('Stripe Webhook Subscription Lifecycle', () => {
const {checkHasActivePaidPremium} = await import('@app/api/user/UserHelpers');
expect(checkHasActivePaidPremium(afterUser!)).toBe(false);
});
+ test('keeps premium cut off after reconciliation when the cancelled subscription was refunded and disputed', async () => {
+ const account = await createTestAccount(harness);
+ const userId = createUserID(BigInt(account.userId));
+ const subscriptionId = 'sub_test_refunded_yearly';
+ const invoiceId = 'in_test_refunded_yearly';
+ const day = 24 * 60 * 60;
+ const endedAt = Math.floor(Date.now() / 1000) - 60;
+ const paidPeriodEnd = endedAt + 222 * day;
+ const paymentIntentId = `pi_${invoiceId}`;
+ const stripeApi = createStripeApiHandlers({
+ subscriptions: {
+ [subscriptionId]: {
+ status: 'canceled',
+ interval: 'year',
+ ended_at: endedAt,
+ current_period_start: paidPeriodEnd - 365 * day,
+ current_period_end: paidPeriodEnd,
+ },
+ },
+ invoices: {
+ [invoiceId]: {
+ subscriptionId,
+ lines: {data: [{period: {start: paidPeriodEnd - 365 * day, end: paidPeriodEnd}}]},
+ payments: createPaymentIntentInvoicePayments(invoiceId, paymentIntentId, endedAt),
+ },
+ },
+ charges: {
+ [`ch_${paymentIntentId}`]: {refunded: true, amount_refunded: 2500, disputed: true},
+ },
+ });
+ server.use(...stripeApi.handlers);
+ await userRepository.patchUpsert(
+ userId,
+ {
+ premium_type: UserPremiumTypes.SUBSCRIPTION,
+ stripe_subscription_id: subscriptionId,
+ stripe_customer_id: 'cus_test_1',
+ premium_since: new Date(),
+ premium_until: new Date(paidPeriodEnd * 1000),
+ },
+ (await userRepository.findUnique(userId))!.toRow(),
+ );
+ const result = await sendStripeWebhook(harness, createSubscriptionDeletedEvent({subscriptionId, endedAt}));
+ expect(result.received).toBe(true);
+ setWorkerDependenciesForTest({
+ ...getWorkerDependencies(),
+ storeEntitlementService: createTestStoreEntitlementService(),
+ });
+ await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
+ const afterUser = await userRepository.findUnique(userId);
+ expect(afterUser?.premiumType).toBeNull();
+ expect(afterUser?.premiumUntil).toBeNull();
+ expect(stripeApi.spies.retrievedPaymentIntents).toContain(paymentIntentId);
+ });
test('ends premium without grace when the subscription is cancelled at the end of its paid period', async () => {
const account = await createTestAccount(harness);
const userId = createUserID(BigInt(account.userId));
diff --git a/fluxer_api/src/api/test/msw/handlers/StripeApiHandlers.ts b/fluxer_api/src/api/test/msw/handlers/StripeApiHandlers.ts
index 7f64585eb..d469474c6 100644
--- a/fluxer_api/src/api/test/msw/handlers/StripeApiHandlers.ts
+++ b/fluxer_api/src/api/test/msw/handlers/StripeApiHandlers.ts
@@ -289,6 +289,9 @@ interface MockStripeInvoice {
hosted_invoice_url: string | null;
invoice_pdf: string | null;
number: string | null;
+ lines: {
+ data: Array<{period: {start: number; end: number}}>;
+ };
payments: {
object: 'list';
data: Array<MockStripeInvoicePayment>;
@@ -322,6 +325,7 @@ interface MockStripeSubscriptionState {
current_period_end: number;
cancel_at: number | null;
cancel_at_period_end: boolean;
+ ended_at: number | null;
default_payment_method: string | null;
latest_invoice: string | null;
status: 'active' | 'canceled' | 'incomplete' | 'past_due' | 'trialing';
@@ -725,6 +729,7 @@ export function createStripeApiHandlers(config: StripeApiMockConfig = {}): Strip
hosted_invoice_url: `https://invoice.stripe.com/i/${id}`,
invoice_pdf: `https://pay.stripe.com/invoice/${id}/pdf`,
number: null,
+ lines: {data: []},
payments: {
object: 'list',
data: [createDefaultInvoicePayment(`inpay_${id}`, id, paymentIntentId, chargeId)],
@@ -795,6 +800,7 @@ export function createStripeApiHandlers(config: StripeApiMockConfig = {}): Strip
current_period_end: currentPeriodStart + 30 * 24 * 60 * 60,
cancel_at: null,
cancel_at_period_end: false,
+ ended_at: null,
default_payment_method: 'pm_test_1',
latest_invoice: null,
status: 'active',
@@ -858,6 +864,7 @@ export function createStripeApiHandlers(config: StripeApiMockConfig = {}): Strip
cancel_at: subState.cancel_at,
cancel_at_period_end: subState.cancel_at_period_end,
canceled_at: subState.status === 'canceled' ? Math.floor(Date.now() / 1000) : null,
+ ended_at: subState.ended_at,
collection_method: 'charge_automatically',
created: Math.floor(Date.now() / 1000) - 90 * 24 * 60 * 60,
default_payment_method: subState.default_payment_method
@@ -1502,11 +1509,9 @@ export function createStripeApiHandlers(config: StripeApiMockConfig = {}): Strip
const subState = getOrCreateSubscriptionState(subscriptionId);
subState.status = 'canceled';
subState.cancel_at_period_end = false;
+ subState.ended_at = Math.floor(Date.now() / 1000);
subscriptionStore.set(subscriptionId, subState);
- return HttpResponse.json({
- ...mapSubscriptionStateToStripeSubscription(subscriptionId, subState),
- ended_at: Math.floor(Date.now() / 1000),
- });
+ return HttpResponse.json(mapSubscriptionStateToStripeSubscription(subscriptionId, subState));
}),
http.get(`${STRIPE_API_BASE}/v1/subscriptions`, ({request}) => {
if (config.subscriptionsListEmpty) {
@@ -1844,6 +1849,34 @@ export interface StripeWebhookEventData {
let mockWebhookEventCounter = 0;
+export function createPaymentIntentInvoicePayments(
+ invoiceId: string,
+ paymentIntentId: string,
+ paidAt: number,
+): MockStripeInvoice['payments'] {
+ return {
+ object: 'list',
+ data: [
+ {
+ id: `inpay_${invoiceId}`,
+ object: 'invoice_payment',
+ amount_paid: 2500,
+ amount_requested: 2500,
+ created: paidAt,
+ currency: 'usd',
+ invoice: invoiceId,
+ is_default: true,
+ livemode: false,
+ payment: {charge: null, payment_intent: paymentIntentId, type: 'payment_intent'},
+ status: 'paid',
+ status_transitions: {canceled_at: null, paid_at: paidAt},
+ },
+ ],
+ has_more: false,
+ url: `/v1/invoices/${invoiceId}/payments`,
+ };
+}
+
export function createMockWebhookPayload(eventData: StripeWebhookEventData): {
payload: string;
timestamp: number;
diff --git a/fluxer_api/src/api/worker/tasks/ProcessPremiumStateReconciliationQueue.ts b/fluxer_api/src/api/worker/tasks/ProcessPremiumStateReconciliationQueue.ts
index d09156e98..248003b62 100644
--- a/fluxer_api/src/api/worker/tasks/ProcessPremiumStateReconciliationQueue.ts
+++ b/fluxer_api/src/api/worker/tasks/ProcessPremiumStateReconciliationQueue.ts
@@ -10,6 +10,7 @@ import {isBillingActive} from '@app/api/stripe/BillingConfigCache';
import {canProvisionPremiumFromSubscriptionStatus} from '@app/api/stripe/StripeSubscriptionAccessPolicy';
import {
getInvoiceLatestLinePeriodEnd,
+ getInvoicePaymentRef,
getSubscriptionBillingCycle,
getSubscriptionCurrentPeriodStart,
getSubscriptionPremiumPeriodEnd,
@@ -162,6 +163,7 @@ async function getPaidThroughFromSubscriptionInvoices(
subscription: subscription.id,
status: 'paid',
limit: PAID_INVOICE_LOOKUP_LIMIT,
+ expand: ['data.payments'],
});
} catch (error) {
Logger.warn(
@@ -173,13 +175,47 @@ async function getPaidThroughFromSubscriptionInvoices(
let paidThrough: Date | null = null;
for (const invoice of invoices.data) {
const periodEnd = getInvoiceLatestLinePeriodEnd(invoice);
- if (periodEnd && (paidThrough === null || periodEnd.getTime() > paidThrough.getTime())) {
+ if (
+ periodEnd &&
+ (paidThrough === null || periodEnd.getTime() > paidThrough.getTime()) &&
+ !(await wasInvoicePaymentReturned(stripe, invoice))
+ ) {
paidThrough = periodEnd;
}
}
return paidThrough;
}
+async function wasInvoicePaymentReturned(stripe: Stripe, invoice: Stripe.Invoice): Promise<boolean> {
+ if (invoice.post_payment_credit_notes_amount > 0) {
+ return true;
+ }
+ const charge = await retrieveInvoiceCharge(stripe, invoice);
+ if (!charge) {
+ return false;
+ }
+ if (charge.refunded || charge.amount_refunded > 0) {
+ return true;
+ }
+ if (!charge.disputed) {
+ return false;
+ }
+ const disputes = await stripe.disputes.list({charge: charge.id});
+ return disputes.data.some((dispute) => dispute.status === 'lost');
+}
+
+async function retrieveInvoiceCharge(stripe: Stripe, invoice: Stripe.Invoice): Promise<Stripe.Charge | null> {
+ const paymentRef = getInvoicePaymentRef(invoice);
+ if (paymentRef?.chargeId) {
+ return stripe.charges.retrieve(paymentRef.chargeId);
+ }
+ if (!paymentRef?.paymentIntentId) {
+ return null;
+ }
+ const paymentIntent = await stripe.paymentIntents.retrieve(paymentRef.paymentIntentId, {expand: ['latest_charge']});
+ return typeof paymentIntent.latest_charge === 'object' ? paymentIntent.latest_charge : null;
+}
+
async function getEffectiveActiveStripeSubscription(
stripe: Stripe,
user: User,