A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(billing): play refunds, cooldown from last, no refund block
Hampusff3acb899c49
diff --git a/fluxer_api/src/api/store_billing/GooglePlayRefundTarget.ts b/fluxer_api/src/api/store_billing/GooglePlayRefundTarget.tsnew file mode 100644index 000000000..67314a676--- /dev/null+++ b/fluxer_api/src/api/store_billing/GooglePlayRefundTarget.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Config} from '@app/api/Config';+import type {StorePurchaseRow} from '@app/api/database/types/StoreBillingTypes';+import type {GiftCode} from '@app/api/models/GiftCode';+import {+ isGooglePlayConfigured,+ isGooglePlayPackageConfigured,+ STORE_PRODUCT_SLOTS,+} from '@app/api/store_billing/StoreBillingConfig';+import {PAID_SUBSCRIPTION_STATES} from '@app/api/store_billing/StoreBillingTypes';++export interface GooglePlayRefundTarget {+ row: StorePurchaseRow;+ orderId: string;+ paidAt: Date;+}++type FindGiftCode = (code: string) => Promise<GiftCode | null>;++export function isGooglePlaySelfServiceRefundEnabled(): boolean {+ return Config.googlePlay.selfServiceRefunds && isGooglePlayConfigured();+}++function lastChargedAt(row: StorePurchaseRow, now: Date): Date | null {+ const startedAt = row.started_at ?? row.purchased_at;+ if (row.kind === 'gift' || !row.expires_at) {+ return startedAt;+ }+ const periodStart = new Date(row.expires_at);+ periodStart.setUTCMonth(periodStart.getUTCMonth() - STORE_PRODUCT_SLOTS[row.slot].durationMonths);+ const chargedAt = Math.max(periodStart.getTime(), startedAt?.getTime() ?? Number.NEGATIVE_INFINITY);+ return new Date(Math.min(chargedAt, now.getTime()));+}++async function isRefundable(row: StorePurchaseRow, findGiftCode: FindGiftCode): Promise<boolean> {+ if (+ row.provider !== 'google_play' ||+ row.revoked_at !== null ||+ !row.latest_transaction_id ||+ !isGooglePlayPackageConfigured(row.app_id)+ ) {+ return false;+ }+ if (row.kind === 'subscription') {+ return row.entitled && PAID_SUBSCRIPTION_STATES.has(row.state);+ }+ if (row.state !== 'purchased' && row.state !== 'fulfilled') {+ return false;+ }+ if (!row.gift_code) {+ return true;+ }+ const gift = await findGiftCode(row.gift_code);+ return gift === null || (gift.redeemedByUserId === null && gift.revokedAt === null);+}++export async function findGooglePlayRefundTarget(+ rows: ReadonlyArray<StorePurchaseRow>,+ findGiftCode: FindGiftCode,+ now = new Date(),+): Promise<GooglePlayRefundTarget | null> {+ if (!isGooglePlaySelfServiceRefundEnabled()) {+ return null;+ }+ let latest: GooglePlayRefundTarget | null = null;+ for (const row of rows) {+ const paidAt = lastChargedAt(row, now);+ if (!paidAt || (latest && latest.paidAt.getTime() >= paidAt.getTime())) {+ continue;+ }+ if (await isRefundable(row, findGiftCode)) {+ latest = {row, orderId: row.latest_transaction_id!, paidAt};+ }+ }+ return latest;+}diff --git a/fluxer_api/src/api/store_billing/StoreEntitlementService.ts b/fluxer_api/src/api/store_billing/StoreEntitlementService.tsindex 3b904099b..1f3a11e3d 100644--- a/fluxer_api/src/api/store_billing/StoreEntitlementService.ts+++ b/fluxer_api/src/api/store_billing/StoreEntitlementService.ts@@ -9,6 +9,8 @@ import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';import {Logger} from '@app/api/Logger';+import type {PaymentDisputeRepository} from '@app/api/payment_disputes/PaymentDisputeRepository';+import {flagPurchaseDuringDispute} from '@app/api/payment_disputes/PaymentDisputeReviews';import {AppStoreJwsVerificationError,toStoreEnvironment,@@ -20,9 +22,17 @@ import {AppStoreServerApiError,isAppStoreTransactionNotFound,} from '@app/api/store_billing/app_store/AppStoreServerApiClient';+import {+ findGooglePlayRefundTarget,+ type GooglePlayRefundTarget,+ isGooglePlaySelfServiceRefundEnabled,+} from '@app/api/store_billing/GooglePlayRefundTarget';import {GooglePlaySettlement} from '@app/api/store_billing/GooglePlaySettlement';import {isGooglePlayApiError} from '@app/api/store_billing/google_play/GooglePlayApiError';-import type {GooglePlayDeveloperApiClient} from '@app/api/store_billing/google_play/GooglePlayDeveloperApiClient';+import type {+ GooglePlayCancellationType,+ GooglePlayDeveloperApiClient,+} from '@app/api/store_billing/google_play/GooglePlayDeveloperApiClient';import {buildGooglePlayProductSnapshot,buildGooglePlaySubscriptionSnapshot,@@ -88,6 +98,7 @@ interface StoreEntitlementServiceDeps {appStoreClient: AppStoreServerApiClient;googlePlayClient: GooglePlayDeveloperApiClient;giftReversalHandler: StripeGiftReversalHandler;+ paymentDisputeRepository: PaymentDisputeRepository;}interface ActiveStoreEntitlement {@@ -219,7 +230,7 @@ export class StoreEntitlementService {};}- async hasStorePurchases(userId: UserID): Promise<boolean> {+ private async hasStorePurchases(userId: UserID): Promise<boolean> {if (Config.instance.selfHosted) {return false;}@@ -372,9 +383,14 @@ export class StoreEntitlementService {}const storeKey = buildGooglePlayStoreKey(params.purchaseToken);const known = await this.deps.repository.findPurchase(storeKey);- const kind =- known?.kind ??- (params.productType === 'subscription' ? 'subscription' : params.productType === 'one_time' ? 'gift' : null);+ let kind = known?.kind ?? null;+ if (kind === null) {+ if (params.productType === 'subscription') {+ kind = 'subscription';+ } else if (params.productType === 'one_time') {+ kind = 'gift';+ }+ }try {if (kind === 'subscription') {await this.syncGooglePlaySubscription({packageName: params.packageName, purchaseToken: params.purchaseToken});@@ -457,25 +473,64 @@ export class StoreEntitlementService {}}+ async findGooglePlayRefundTarget(userId: UserID): Promise<GooglePlayRefundTarget | null> {+ if (!isGooglePlaySelfServiceRefundEnabled()) {+ return null;+ }+ const rows = await this.deps.repository.listPurchasesForUser(userId);+ return findGooglePlayRefundTarget(rows, (code) => this.deps.userRepository.findGiftCode(code));+ }++ async refundGooglePlayPurchase(userId: UserID, target: GooglePlayRefundTarget): Promise<boolean> {+ const storeKey = target.row.store_key;+ return this.withPurchaseLock(storeKey, async () => {+ const current = await this.deps.repository.findPurchase(storeKey);+ if (!current || current.user_id !== userId) {+ return false;+ }+ const confirmed = await findGooglePlayRefundTarget([current], (code) =>+ this.deps.userRepository.findGiftCode(code),+ );+ if (!confirmed || confirmed.orderId !== target.orderId) {+ return false;+ }+ await this.deps.googlePlayClient.refundOrder(current.app_id, confirmed.orderId);+ Logger.info(+ {userId: userId.toString(), storeKey: redactStoreKey(storeKey), kind: current.kind},+ 'Refunded a Google Play purchase at its owner request',+ );+ await this.markGooglePlayVoided(storeKey, confirmed.orderId, new Date());+ return true;+ });+ }+async stopBillingForDeletedUser(userId: UserID): Promise<void> {+ await this.cancelGooglePlaySubscriptions(userId, 'DEVELOPER_REQUESTED_STOP_PAYMENTS', 'a deleted user');+ }++ async stopGooglePlayRenewals(userId: UserID): Promise<void> {+ await this.cancelGooglePlaySubscriptions(userId, 'USER_REQUESTED_STOP_RENEWALS', 'a long gift');+ }++ private async cancelGooglePlaySubscriptions(+ userId: UserID,+ cancellationType: GooglePlayCancellationType,+ reason: string,+ ): Promise<void> {try {const rows = await this.listGooglePlaySubscriptionsToStop(userId);for (const row of rows) {try {- await this.deps.googlePlayClient.cancelSubscription(- row.app_id,- row.store_reference,- 'DEVELOPER_REQUESTED_STOP_PAYMENTS',- );+ await this.deps.googlePlayClient.cancelSubscription(row.app_id, row.store_reference, cancellationType);} catch (error) {Logger.warn({error, userId: userId.toString(), storeKey: redactStoreKey(row.store_key)},- 'Failed to stop Google Play billing for a deleted user',+ `Failed to stop Google Play billing for ${reason}`,);}}} catch (error) {- Logger.warn({error, userId: userId.toString()}, 'Failed to stop store billing for a deleted user');+ Logger.warn({error, userId: userId.toString()}, `Failed to stop store billing for ${reason}`);}}@@ -745,6 +800,9 @@ export class StoreEntitlementService {if (context.claimerId !== null && row.user_id === context.claimerId && row.provider === 'app_store') {row = await this.ensureAppStoreAccountToken(row, snapshot);}+ if (row.user_id !== null && previous?.user_id !== row.user_id) {+ await flagPurchaseDuringDispute(this.deps.paymentDisputeRepository, row.user_id, row.store_key);+ }const owner = row.user_id !== null ? await this.deps.userRepository.findUnique(row.user_id) : null;if (row.kind === 'gift') {row = await this.giftFulfilment.settleGift(row);@@ -764,7 +822,10 @@ export class StoreEntitlementService {const ownerId = await this.resolveOwner(existing, snapshot, context);const now = new Date();const fields = this.buildRowFields(snapshot, existing, ownerId, context, now);- const boundAt = ownerId === null ? null : ownerId === existing?.user_id ? existing.bound_at : now;+ let boundAt: Date | null = null;+ if (ownerId !== null) {+ boundAt = ownerId === existing?.user_id ? existing.bound_at : now;+ }const releasedAt = ownerId === null ? (existing?.released_at ?? null) : null;if (!existing) {const row: StorePurchaseRow = {diff --git a/fluxer_api/src/api/stripe/services/PremiumStateService.ts b/fluxer_api/src/api/stripe/services/PremiumStateService.tsindex 6ed423795..9df8f09c6 100644--- a/fluxer_api/src/api/stripe/services/PremiumStateService.ts+++ b/fluxer_api/src/api/stripe/services/PremiumStateService.ts@@ -12,12 +12,17 @@ import type {import type {StorePurchaseRow} from '@app/api/database/types/StoreBillingTypes';import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';import {Logger} from '@app/api/Logger';+import {getPaymentDisputeRepository} from '@app/api/middleware/ServiceSingletons';import type {User} from '@app/api/models/User';+import {hasOpenPaymentDispute} from '@app/api/payment_disputes/PaymentDisputeReviews';+import {+ findGooglePlayRefundTarget,+ isGooglePlaySelfServiceRefundEnabled,+} from '@app/api/store_billing/GooglePlayRefundTarget';import {mapPremiumStoreSubscriptionState,resolveStoreAccessEnd,selectActiveStoreSubscription,- toIso,} from '@app/api/store_billing/StoreBillingMappers';import type {StoreBillingRepository} from '@app/api/store_billing/StoreBillingRepository';import {isStripeSubscriptionActive} from '@app/api/store_billing/StoreEntitlementWriter';@@ -27,12 +32,19 @@ import {getStripeClient} from '@app/api/stripe/StripeClient';import {getCachedStripePriceSummary} from '@app/api/stripe/StripePriceSummaryCache';import {getPrimarySubscriptionItem, loadSubscriptionSchedule} from '@app/api/stripe/StripeSubscriptionPeriod';import {extractId} from '@app/api/stripe/StripeUtils';-import {buildRefundEligibility, refundCooldownExpiresAt} from '@app/api/stripe/services/RefundAllowance';+import {+ buildRefundEligibility,+ googlePlayRefundEligibilityTarget,+ latestRefundTarget,+ type RefundEligibilityTarget,+ refundCooldownExpiresAt,+} from '@app/api/stripe/services/RefundAllowance';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {checkHasActivePaidPremium} from '@app/api/user/UserHelpers';import {dispatchUserUpdate} from '@app/api/user/UserMappers';import {type Currency, normalizeCatalogCurrency} from '@app/api/utils/CurrencyUtils';import {PremiumFlags, UserPremiumTypes} from '@fluxer/constants/src/UserConstants';+import {toIsoOrNull} from '@fluxer/date_utils/src/DateSerialization';import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';import type {CurrentSubscriptionPriceResponse,@@ -70,30 +82,44 @@ interface StripePriceDetails {}function toNumber(value: bigint | number | null | undefined): number {- if (value == null) return 0;+ if (value == null) {+ return 0;+ }return Number(value);}function nullableNumber(value: bigint | number | null | undefined): number | null {- if (value == null) return null;+ if (value == null) {+ return null;+ }return Number(value);}function positiveIntegerFromMetadata(value: string | null | undefined): number | null {- if (value == null) return null;+ if (value == null) {+ return null;+ }const parsed = Number(value);- if (!Number.isSafeInteger(parsed) || parsed <= 0) return null;+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {+ return null;+ }return parsed;}function normalizeBillingCycle(value: string | null | undefined): RecurringBillingCycle | null {- if (value === 'monthly' || value === 'yearly') return value;+ if (value === 'monthly' || value === 'yearly') {+ return value;+ }return null;}function billingCycleFromInterval(value: string | null | undefined): RecurringBillingCycle | null {- if (value === 'month') return 'monthly';- if (value === 'year') return 'yearly';+ if (value === 'month') {+ return 'monthly';+ }+ if (value === 'year') {+ return 'yearly';+ }return null;}@@ -106,15 +132,21 @@ function compareNullableDatesDesc(left: Date | null | undefined, right: Date | n}function subscriptionRank(row: BillingSubscriptionRow): number {- if (row.status && ACTIVE_SUBSCRIPTION_STATUSES.has(row.status)) return 0;- if (row.status && RELEVANT_SUBSCRIPTION_STATUSES.has(row.status)) return 1;+ if (row.status && ACTIVE_SUBSCRIPTION_STATUSES.has(row.status)) {+ return 0;+ }+ if (row.status && RELEVANT_SUBSCRIPTION_STATUSES.has(row.status)) {+ return 1;+ }return 2;}function sortSubscriptionsByRelevance(rows: Array<BillingSubscriptionRow>): Array<BillingSubscriptionRow> {return rows.sort((left, right) => {const rankDiff = subscriptionRank(left) - subscriptionRank(right);- if (rankDiff !== 0) return rankDiff;+ if (rankDiff !== 0) {+ return rankDiff;+ }return compareNullableDatesDesc(left.current_period_end, right.current_period_end);});}@@ -130,7 +162,9 @@ function resolveSubscriptionProvider(storeRow: StorePurchaseRow | null,now: Date,): PremiumSubscriptionProvider | null {- if (user.premiumType === UserPremiumTypes.LIFETIME) return null;+ if (user.premiumType === UserPremiumTypes.LIFETIME) {+ return null;+ }const stripePeriodEnd =stripeSubscription?.provider_id === user.stripeSubscriptionId ? stripeSubscription?.current_period_end : null;const stripeEnd = isStripeSubscriptionActive(user, now) ? (stripePeriodEnd ?? user.premiumUntil) : null;@@ -149,8 +183,8 @@ function mapInvoice(row: BillingInvoiceRow): PremiumBillingInvoiceResponse {amount_paid: toNumber(row.amount_paid),currency: row.currency ?? 'usd',status: row.status ?? null,- created_at: toIso(row.stripe_created_at),- paid_at: toIso(row.paid_at),+ created_at: toIsoOrNull(row.stripe_created_at),+ paid_at: toIsoOrNull(row.paid_at),billing_reason: row.billing_reason ?? null,subscription_id: row.subscription_id ?? null,hosted_invoice_url: row.hosted_invoice_url ?? null,@@ -209,9 +243,10 @@ export class PremiumStateService {}private async buildState(user: User, countryCode?: string): Promise<PremiumStateResponse> {- const [customerIds, subscription] = await Promise.all([+ const [customerIds, subscription, paymentDisputeOpen] = await Promise.all([this.resolveCustomerIds(user),this.resolvePrimarySubscription(user),+ hasOpenPaymentDispute(getPaymentDisputeRepository(), user.id),]);await this.repairPaymentMethodsFromStripe(user, customerIds, subscription);const [invoices, paymentMethods, subscriptionPrice, pendingSubscriptionChange, pricing] = await Promise.all([@@ -233,12 +268,12 @@ export class PremiumStateService {return {actual: {premium_type: user.premiumType ?? UserPremiumTypes.NONE,- premium_since: toIso(user.premiumSince),- premium_until: toIso(actualPremiumEndAt),+ premium_since: toIsoOrNull(user.premiumSince),+ premium_until: toIsoOrNull(actualPremiumEndAt),premium_will_cancel: user.premiumWillCancel,premium_billing_cycle: normalizeBillingCycle(user.premiumBillingCycle),premium_lifetime_sequence: user.premiumLifetimeSequence,- premium_grace_ends_at: toIso(user.premiumGraceEndsAt),+ premium_grace_ends_at: toIsoOrNull(user.premiumGraceEndsAt),has_active_paid_premium: activePaidPremium,is_visionary: user.premiumType === UserPremiumTypes.LIFETIME,has_ever_purchased: user.hasEverPurchased,@@ -246,14 +281,15 @@ export class PremiumStateService {effective: {is_premium: isEffectivePremium,premium_type: isEffectivePremium ? (user.premiumType ?? UserPremiumTypes.NONE) : UserPremiumTypes.NONE,- premium_since: isEffectivePremium ? toIso(user.premiumSince) : null,- premium_until: toIso(actualPremiumEndAt),+ premium_since: isEffectivePremium ? toIsoOrNull(user.premiumSince) : null,+ premium_until: toIsoOrNull(actualPremiumEndAt),premium_will_cancel: user.premiumWillCancel,premium_billing_cycle: normalizeBillingCycle(user.premiumBillingCycle),premium_lifetime_sequence: user.premiumLifetimeSequence,- premium_grace_ends_at: toIso(user.premiumGraceEndsAt),+ premium_grace_ends_at: toIsoOrNull(user.premiumGraceEndsAt),premium_enabled_override: (user.premiumFlags & PremiumFlags.ENABLED_OVERRIDE) !== 0,premium_purchase_disabled: (user.premiumFlags & PremiumFlags.PURCHASE_DISABLED) !== 0 || !isBillingActive(),+ payment_dispute_open: paymentDisputeOpen,premium_perks_disabled: (user.premiumFlags & PremiumFlags.PERKS_DISABLED) !== 0,self_hosted: Config.instance.selfHosted,bot: user.isBot,@@ -290,7 +326,9 @@ export class PremiumStateService {}const rows = await this.billingRepository.customers.findByUserId(user.id);for (const row of rows) {- if (!row.deleted) ids.add(row.provider_id);+ if (!row.deleted) {+ ids.add(row.provider_id);+ }}return [...ids];}@@ -298,7 +336,9 @@ export class PremiumStateService {private async resolvePrimarySubscription(user: User): Promise<BillingSubscriptionRow | null> {const byId = new Map<string, BillingSubscriptionRow>();const add = (row: BillingSubscriptionRow | null) => {- if (row) byId.set(row.provider_id, row);+ if (row) {+ byId.set(row.provider_id, row);+ }};if (user.stripeSubscriptionId) {add(await this.billingRepository.subscriptions.findById(user.stripeSubscriptionId));@@ -349,7 +389,9 @@ export class PremiumStateService {}}return [...byId.values()].sort((left, right) => {- if ((left.is_default ?? false) !== (right.is_default ?? false)) return left.is_default ? -1 : 1;+ if ((left.is_default ?? false) !== (right.is_default ?? false)) {+ return left.is_default ? -1 : 1;+ }return compareNullableDatesDesc(left.stripe_created_at, right.stripe_created_at);});}@@ -359,7 +401,9 @@ export class PremiumStateService {customerIds: Array<string>,subscription: BillingSubscriptionRow | null,): Promise<void> {- if (!this.stripe || customerIds.length === 0) return;+ if (!this.stripe || customerIds.length === 0) {+ return;+ }await Promise.all(customerIds.map(async (customerId) => {try {@@ -379,7 +423,9 @@ export class PremiumStateService {customerId: string,mirroredSubscription: BillingSubscriptionRow | null,): Promise<void> {- if (!this.stripe) return;+ if (!this.stripe) {+ return;+ }let customer = await this.stripe.customers.retrieve(customerId, {expand: ['invoice_settings.default_payment_method'],});@@ -438,7 +484,9 @@ export class PremiumStateService {customerId: string,mirroredSubscription: BillingSubscriptionRow | null,): Promise<Stripe.Subscription | null> {- if (!this.stripe) return null;+ if (!this.stripe) {+ return null;+ }const subscriptions = await this.stripe.subscriptions.list({customer: customerId,status: 'all',@@ -464,19 +512,25 @@ export class PremiumStateService {subscription: BillingSubscriptionRow | null,user: User,): Promise<CurrentSubscriptionPriceResponse> {- if (!subscription) return null;+ if (!subscription) {+ return null;+ }const price = subscription.primary_price_id? await this.billingRepository.prices.findById(subscription.primary_price_id): null;const billingCycle =billingCycleFromInterval(price?.interval) ?? normalizeBillingCycle(user.premiumBillingCycle) ?? null;- if (!billingCycle) return null;+ if (!billingCycle) {+ return null;+ }const currency = (price?.currency ?? subscription.currency ?? 'usd').toUpperCase();const listPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);const listPrice = listPriceId ? await this.billingRepository.prices.findById(listPriceId) : null;const itemAmount = subscription.items?.[0]?.[3] ?? null;const amountMinor = nullableNumber(price?.unit_amount ?? itemAmount);- if (amountMinor == null) return null;+ if (amountMinor == null) {+ return null;+ }return {price_id: price?.provider_id ?? subscription.primary_price_id ?? '',amount_minor: amountMinor,@@ -493,11 +547,11 @@ export class PremiumStateService {return {id: row.provider_id,status: row.status ?? null,- current_period_start: toIso(row.current_period_start),- current_period_end: toIso(row.current_period_end),+ current_period_start: toIsoOrNull(row.current_period_start),+ current_period_end: toIsoOrNull(row.current_period_end),cancel_at_period_end: row.cancel_at_period_end ?? false,- cancel_at: toIso(row.cancel_at),- canceled_at: toIso(row.canceled_at),+ cancel_at: toIsoOrNull(row.cancel_at),+ canceled_at: toIsoOrNull(row.canceled_at),plan_interval: price?.interval ?? null,plan_amount_minor: nullableNumber(price?.unit_amount ?? row.items?.[0]?.[3] ?? null),plan_currency: price?.currency ?? row.currency ?? null,@@ -506,7 +560,9 @@ export class PremiumStateService {}private async resolvePendingSubscriptionChange(user: User): Promise<PendingSubscriptionChangeResponse> {- if (!this.stripe || !user.stripeSubscriptionId) return null;+ if (!this.stripe || !user.stripeSubscriptionId) {+ return null;+ }try {const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {expand: ['items.data.price', 'schedule'],@@ -534,7 +590,9 @@ export class PremiumStateService {const futurePhase = schedule.phases.filter((phase) => typeof phase.start_date === 'number' && phase.start_date > now).sort((left, right) => left.start_date - right.start_date)[0];- if (!futurePhase) return null;+ if (!futurePhase) {+ return null;+ }const currentItem = getPrimarySubscriptionItem(subscription);const currentPriceDetails = await this.resolveStripePriceDetails(currentItem?.price ?? null);const currentBillingCycle = currentPriceDetails.billingCycle ?? fallbackCurrentBillingCycle;@@ -560,12 +618,10 @@ export class PremiumStateService {const metadataCreditAmountMinor = positiveIntegerFromMetadata(futurePhase.metadata?.first_invoice_credit_amount_minor,);- const firstInvoiceAdjustmentTotal =- addInvoiceItemsTotal !== 0- ? addInvoiceItemsTotal- : metadataCreditAmountMinor == null- ? 0- : -metadataCreditAmountMinor;+ let firstInvoiceAdjustmentTotal = addInvoiceItemsTotal;+ if (firstInvoiceAdjustmentTotal === 0) {+ firstInvoiceAdjustmentTotal = metadataCreditAmountMinor == null ? 0 : -metadataCreditAmountMinor;+ }const initialAmountMinor =recurringAmountMinor == null ? null : Math.max(0, recurringAmountMinor + firstInvoiceAdjustmentTotal);const creditAmountMinor = firstInvoiceAdjustmentTotal < 0 ? -firstInvoiceAdjustmentTotal : null;@@ -598,7 +654,7 @@ export class PremiumStateService {list_amount_minor: subscriptionPrice?.list_amount_minor ?? null,currency: subscriptionPrice?.currency ?? null,billing_cycle: subscriptionPrice?.billing_cycle ?? null,- effective_at: toIso(subscription?.current_period_end),+ effective_at: toIsoOrNull(subscription?.current_period_end),};if (Config.instance.selfHosted || !isBillingActive()) {return {...base, available: false, reason: 'feature_unavailable'};@@ -711,7 +767,9 @@ export class PremiumStateService {private async resolvePriceIds(countryCode: string | null): Promise<PriceIdsResponse | null> {const resolved = this.productRegistry.resolveLocalizedPriceIds(countryCode);- if (!resolved) return null;+ if (!resolved) {+ return null;+ }const [monthlyAmount, yearlyAmount, gift1MonthAmount, gift1YearAmount] = await Promise.all([this.resolvePriceAmountMinor(resolved.monthly),this.resolvePriceAmountMinor(resolved.yearly),@@ -758,25 +816,47 @@ export class PremiumStateService {user: User,invoices: Array<BillingInvoiceRow>,): Promise<SelfServeRefundEligibilityResponse> {- if (Config.instance.selfHosted || !getStripeClient())+ const stripeAvailable = getStripeClient() !== null;+ const storeBillingRepository = this.storeBillingRepository;+ const googlePlayAvailable = storeBillingRepository !== null && isGooglePlaySelfServiceRefundEnabled();+ if (Config.instance.selfHosted || (!stripeAvailable && !googlePlayAvailable)) {return buildRefundEligibility({reason: 'feature_unavailable'});- const cooldownExpiresAt = refundCooldownExpiresAt(user);+ }+ const target = latestRefundTarget(+ stripeAvailable ? await this.resolveStripeRefundTarget(invoices) : null,+ googlePlayAvailable ? await this.resolveGooglePlayRefundTarget(user, storeBillingRepository) : null,+ );+ return buildRefundEligibility({target, cooldownExpiresAt: refundCooldownExpiresAt(user)});+ }++ private async resolveStripeRefundTarget(invoices: Array<BillingInvoiceRow>): Promise<RefundEligibilityTarget | null> {const paidInvoices = invoices.filter((invoice) => invoice.status === 'paid' && toNumber(invoice.amount_paid) > 0);for (const invoice of paidInvoices) {- if (await this.invoiceHasBlockingRefund(invoice)) continue;+ if (await this.invoiceHasBlockingRefund(invoice)) {+ continue;+ }const paidAt = invoice.paid_at ?? invoice.stripe_created_at;- if (!paidAt) continue;- return buildRefundEligibility({- target: {- invoiceId: invoice.provider_id,- amountPaidCents: nullableNumber(invoice.amount_paid),- currency: invoice.currency,- paidAt,- subscriptionId: invoice.subscription_id,- },- cooldownExpiresAt,- });+ if (!paidAt) {+ continue;+ }+ return {+ provider: 'stripe',+ invoiceId: invoice.provider_id,+ amountPaidCents: nullableNumber(invoice.amount_paid),+ currency: invoice.currency,+ paidAt,+ subscriptionId: invoice.subscription_id,+ };}- return buildRefundEligibility({reason: 'no_refundable_purchase', cooldownExpiresAt});+ return null;+ }++ private async resolveGooglePlayRefundTarget(+ user: User,+ storeBillingRepository: StoreBillingRepository,+ ): Promise<RefundEligibilityTarget | null> {+ const rows = await storeBillingRepository.listPurchasesForUser(user.id);+ const target = await findGooglePlayRefundTarget(rows, (code) => this.userRepository.findGiftCode(code));+ return target ? googlePlayRefundEligibilityTarget(target) : null;}}diff --git a/fluxer_api/src/api/stripe/services/RefundAllowance.ts b/fluxer_api/src/api/stripe/services/RefundAllowance.tsindex 3f7d7dc4c..7c17c7cf5 100644--- a/fluxer_api/src/api/stripe/services/RefundAllowance.ts+++ b/fluxer_api/src/api/stripe/services/RefundAllowance.ts@@ -1,92 +1,84 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {BillingRefundRow} from '@app/api/database/types/BillingTypes';-import {getBillingRepository} from '@app/api/middleware/ServiceRegistry';import type {User} from '@app/api/models/User';-import type {UserRepository} from '@app/api/user/repositories/UserRepository';+import type {GooglePlayRefundTarget} from '@app/api/store_billing/GooglePlayRefundTarget';+import {MS_PER_DAY} from '@fluxer/date_utils/src/DateConstants';import type {SelfServeRefundEligibilityResponse,SelfServeRefundIneligibilityReason,+ SelfServeRefundProvider,} from '@fluxer/schema/src/domains/premium/PremiumSchemas';-const REFUND_ALLOWANCE_BLOCK_THRESHOLD = 2;--function isCountedAgainstAllowance(refund: BillingRefundRow): boolean {- if (refund.status !== 'succeeded') {- return false;- }- return (refund.metadata?.get('rejection_reason') ?? null) === null;-}--async function listCountedRefundIds(user: User, userRepository: UserRepository): Promise<Array<string>> {- const payments = await userRepository.findPaymentsByUserId(user.id);- const paymentIntentIds = [- ...new Set(payments.map((payment) => payment.paymentIntentId).filter((id): id is string => id !== null)),- ];- const counted = new Set<string>();- for (const paymentIntentId of paymentIntentIds) {- for (const refund of await getBillingRepository().refunds.listByPaymentIntent(paymentIntentId)) {- if (isCountedAgainstAllowance(refund)) {- counted.add(refund.provider_id);- }- }- }- return [...counted].sort();-}--export async function shouldBlockFurtherPurchases(- user: User,- userRepository: UserRepository,-): Promise<{blocked: boolean; countedRefundIds: Array<string>}> {- const countedRefundIds = await listCountedRefundIds(user, userRepository);- return {blocked: countedRefundIds.length >= REFUND_ALLOWANCE_BLOCK_THRESHOLD, countedRefundIds};-}--const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;export const SELF_SERVE_REFUND_WINDOW_DAYS = 3;const SELF_SERVE_REFUND_COOLDOWN_DAYS = 30;-export function refundCooldownExpiresAt(user: Pick<User, 'firstRefundAt'>): Date | null {- if (!user.firstRefundAt) return null;- const expiresAt = new Date(user.firstRefundAt.getTime() + SELF_SERVE_REFUND_COOLDOWN_DAYS * MILLISECONDS_PER_DAY);+export function refundCooldownExpiresAt(user: Pick<User, 'lastRefundAt'>): Date | null {+ if (!user.lastRefundAt) {+ return null;+ }+ const expiresAt = new Date(user.lastRefundAt.getTime() + SELF_SERVE_REFUND_COOLDOWN_DAYS * MS_PER_DAY);return expiresAt.getTime() > Date.now() ? expiresAt : null;}export function refundWindowExpiresAt(paidAt: Date): Date {- return new Date(paidAt.getTime() + SELF_SERVE_REFUND_WINDOW_DAYS * MILLISECONDS_PER_DAY);+ return new Date(paidAt.getTime() + SELF_SERVE_REFUND_WINDOW_DAYS * MS_PER_DAY);}-export function refundIneligibilityReason(+function refundIneligibilityReason(windowExpiresAt: Date | null,cooldownExpiresAt: Date | null | undefined,): SelfServeRefundIneligibilityReason | null {- if (windowExpiresAt && windowExpiresAt.getTime() <= Date.now()) return 'outside_refund_window';+ if (windowExpiresAt && windowExpiresAt.getTime() <= Date.now()) {+ return 'outside_refund_window';+ }return cooldownExpiresAt ? 'cooldown_active' : null;}+export interface RefundEligibilityTarget {+ provider: SelfServeRefundProvider;+ invoiceId: string;+ amountPaidCents: number | null;+ currency: string | null;+ paidAt: Date | null;+ subscriptionId: string | null;+}++export function googlePlayRefundEligibilityTarget(target: GooglePlayRefundTarget): RefundEligibilityTarget {+ return {+ provider: 'google_play',+ invoiceId: target.orderId,+ amountPaidCents: null,+ currency: null,+ paidAt: target.paidAt,+ subscriptionId: target.row.kind === 'subscription' ? target.row.id.toString() : null,+ };+}++export function latestRefundTarget<T extends {paidAt: Date | null}>(...targets: Array<T | null>): T | null {+ let latest: T | null = null;+ for (const target of targets) {+ if (target && (!latest || (target.paidAt?.getTime() ?? 0) > (latest.paidAt?.getTime() ?? 0))) {+ latest = target;+ }+ }+ return latest;+}+export function buildRefundEligibility({reason,target,cooldownExpiresAt,}: {reason?: SelfServeRefundIneligibilityReason | null;- target?: {- invoiceId: string;- amountPaidCents: number | null;- currency: string | null;- paidAt: Date | null;- subscriptionId: string | null;- } | null;+ target?: RefundEligibilityTarget | null;cooldownExpiresAt?: Date | null;}): SelfServeRefundEligibilityResponse {const paidAt = target?.paidAt ?? null;const windowExpiresAt = paidAt ? refundWindowExpiresAt(paidAt) : null;- const resolvedReason =- reason === undefined- ? target- ? refundIneligibilityReason(windowExpiresAt, cooldownExpiresAt)- : 'no_refundable_purchase'- : reason;+ let resolvedReason = reason;+ if (resolvedReason === undefined) {+ resolvedReason = target ? refundIneligibilityReason(windowExpiresAt, cooldownExpiresAt) : 'no_refundable_purchase';+ }return {eligible: resolvedReason === null && target != null,reason: resolvedReason,@@ -97,5 +89,6 @@ export function buildRefundEligibility({refund_window_expires_at: windowExpiresAt?.toISOString() ?? null,cooldown_expires_at: cooldownExpiresAt?.toISOString() ?? null,cancels_subscription: target?.subscriptionId != null,+ provider: target?.provider ?? null,};}diff --git a/fluxer_api/src/api/stripe/services/StripeRefundService.ts b/fluxer_api/src/api/stripe/services/StripeRefundService.tsindex c7724babf..58960f3d2 100644--- a/fluxer_api/src/api/stripe/services/StripeRefundService.ts+++ b/fluxer_api/src/api/stripe/services/StripeRefundService.ts@@ -2,24 +2,29 @@import {createUserID, type UserID} from '@app/api/BrandedTypes';import {Config} from '@app/api/Config';-import type {UserRow} from '@app/api/database/types/UserTypes';import {Logger} from '@app/api/Logger';import {getBillingRepository} from '@app/api/middleware/ServiceRegistry';import type {User} from '@app/api/models/User';+import {+ type GooglePlayRefundTarget,+ isGooglePlaySelfServiceRefundEnabled,+} from '@app/api/store_billing/GooglePlayRefundTarget';+import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';import {extractId} from '@app/api/stripe/StripeUtils';import {buildRefundEligibility,+ googlePlayRefundEligibilityTarget,+ latestRefundTarget,+ type RefundEligibilityTarget,refundCooldownExpiresAt,refundWindowExpiresAt,SELF_SERVE_REFUND_WINDOW_DAYS,- shouldBlockFurtherPurchases,} from '@app/api/stripe/services/RefundAllowance';-import {REFUND_ALLOWANCE_CLAIM_PREFIX} from '@app/api/stripe/services/StripeDisputeWebhookHandler';import type {StripeSubscriptionService} from '@app/api/stripe/services/StripeSubscriptionService';import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import {PremiumFlags} from '@fluxer/constants/src/UserConstants';import {FeatureNotAvailableSelfHostedError} from '@fluxer/errors/src/domains/core/FeatureNotAvailableSelfHostedError';+import {StoreBillingUnavailableError} from '@fluxer/errors/src/domains/payment/StoreBillingUnavailableError';import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';import {StripeNoPurchaseHistoryError} from '@fluxer/errors/src/domains/payment/StripeNoPurchaseHistoryError';import {StripePaymentNotAvailableError} from '@fluxer/errors/src/domains/payment/StripePaymentNotAvailableError';@@ -35,6 +40,7 @@ import type Stripe from 'stripe';const PIX_EXACT_AMOUNT_REFUND_SHORTFALL_CENTS = 1;interface RefundTarget {+ provider: 'stripe';invoice: Stripe.Invoice;invoiceId: string;amountPaidCents: number;@@ -45,6 +51,14 @@ interface RefundTarget {subscriptionId: string | null;}+type GooglePlayLatestTarget = RefundEligibilityTarget & {+ provider: 'google_play';+ paidAt: Date;+ googlePlay: GooglePlayRefundTarget;+};++type LatestRefundTarget = RefundTarget | GooglePlayLatestTarget;+type StripeInvoiceWithPayments = Stripe.Invoice & {customer?: string | Stripe.Customer | null;payments?: {@@ -96,16 +110,24 @@ export class StripeRefundService {private readonly stripe: Stripe | null,private readonly userRepository: UserRepository,private readonly subscriptionService: StripeSubscriptionService,+ private readonly storeEntitlementService: StoreEntitlementService | null,) {}- private ensureStripe(): Stripe {+ private isAvailable(): boolean {+ return !Config.instance.selfHosted && (this.stripe !== null || this.isGooglePlayAvailable());+ }++ private isGooglePlayAvailable(): boolean {+ return this.storeEntitlementService !== null && isGooglePlaySelfServiceRefundEnabled();+ }++ private ensureAvailable(): void {if (Config.instance.selfHosted) {throw new FeatureNotAvailableSelfHostedError();}- if (!this.stripe) {+ if (!this.isAvailable()) {throw new StripePaymentNotAvailableError();}- return this.stripe;}private async getRequiredUser(userId: UserID): Promise<User> {@@ -116,7 +138,30 @@ export class StripeRefundService {return user;}- private async resolveLatestRefundTarget(user: User): Promise<RefundTarget | null> {+ private async resolveLatestRefundTarget(user: User): Promise<LatestRefundTarget | null> {+ const [stripeTarget, googlePlayTarget] = await Promise.all([+ this.resolveLatestStripeTarget(user),+ this.resolveLatestGooglePlayTarget(user),+ ]);+ return latestRefundTarget<LatestRefundTarget>(stripeTarget, googlePlayTarget);+ }++ private async resolveLatestGooglePlayTarget(user: User): Promise<GooglePlayLatestTarget | null> {+ if (!this.storeEntitlementService || !this.isGooglePlayAvailable()) {+ return null;+ }+ const target = await this.storeEntitlementService.findGooglePlayRefundTarget(user.id);+ return target+ ? {+ ...googlePlayRefundEligibilityTarget(target),+ provider: 'google_play',+ paidAt: target.paidAt,+ googlePlay: target,+ }+ : null;+ }++ private async resolveLatestStripeTarget(user: User): Promise<RefundTarget | null> {if (!this.stripe || !user.stripeCustomerId) {return null;}@@ -136,6 +181,7 @@ export class StripeRefundService {}const paidAt = ref.paidAt ?? new Date(invoice.created * 1000);return {+ provider: 'stripe',invoice,invoiceId: invoice.id,amountPaidCents: invoice.amount_paid,@@ -153,7 +199,7 @@ export class StripeRefundService {}async getEligibility(userId: UserID): Promise<SelfServeRefundEligibilityResponse> {- if (Config.instance.selfHosted || !this.stripe) return buildRefundEligibility({reason: 'feature_unavailable'});+ if (!this.isAvailable()) return buildRefundEligibility({reason: 'feature_unavailable'});const user = await this.getRequiredUser(userId);const target = await this.resolveLatestRefundTarget(user);return buildRefundEligibility({target, cooldownExpiresAt: refundCooldownExpiresAt(user)});@@ -218,50 +264,54 @@ export class StripeRefundService {);}}- const claimKey = `${REFUND_ALLOWANCE_CLAIM_PREFIX}:${refund.id}`;- const claim = await getBillingRepository().webhookEvents.tryClaim(claimKey);- if (claim === 'in_flight') {- Logger.debug(- {userId: user.id.toString(), refundId: refund.id, claim},- 'Self-serve refund allowance is being counted by another delivery',- );+ if (!(await this.startRefundCooldown(user, new Date(refund.created * 1000)))) {return;}- const isFirstRefund = !user.firstRefundAt;- let patch: Partial<UserRow>;- let countedRefundIds: Array<string> = [];- if (isFirstRefund) {- patch = {first_refund_at: new Date()};- } else {- const outcome = await shouldBlockFurtherPurchases(user, this.userRepository);- countedRefundIds = outcome.countedRefundIds;- if (!outcome.blocked) {- await getBillingRepository().webhookEvents.markProcessed(claimKey);- Logger.info(- {userId: user.id.toString(), refundId: refund.id, countedRefundIds},- 'Self-serve refund redelivered after the allowance claim expired; not counting it twice',- );- return;- }- patch = {premium_flags: user.premiumFlags | PremiumFlags.PURCHASE_DISABLED};+ Logger.info(+ {userId: user.id.toString(), refundId: refund.id, subscriptionId: subscriptionId || null},+ 'Self-serve refund confirmed succeeded; refund cooldown started',+ );+ }++ private async startRefundCooldown(user: User, refundedAt: Date): Promise<boolean> {+ if (user.lastRefundAt && user.lastRefundAt.getTime() >= refundedAt.getTime()) {+ return false;}+ await this.userRepository.patchUpsert(user.id, {first_refund_at: refundedAt}, user.toRow());+ return true;+ }++ private async refundGooglePlayPurchase(user: User, target: GooglePlayLatestTarget): Promise<SelfServeRefundResponse> {+ let refunded: boolean;try {- await this.userRepository.patchUpsert(user.id, patch, user.toRow());+ refunded = await this.storeEntitlementService!.refundGooglePlayPurchase(user.id, target.googlePlay);} catch (error) {- await getBillingRepository().webhookEvents.releaseClaim(claimKey);- throw error;+ Logger.warn(+ {error, userId: user.id.toString(), orderId: target.invoiceId},+ 'Self-serve refund failed at Google Play',+ );+ throw new StoreBillingUnavailableError();+ }+ if (!refunded) {+ throw new StripeNoPurchaseHistoryError();}- await getBillingRepository().webhookEvents.markProcessed(claimKey);+ await this.startRefundCooldown(await this.getRequiredUser(user.id), new Date());Logger.info(- {- userId: user.id.toString(),- refundId: refund.id,- subscriptionId: subscriptionId || null,- isFirstRefund,- countedRefundIds,- },- 'Self-serve refund confirmed succeeded; refund allowance and cancellation finalized',+ {userId: user.id.toString(), orderId: target.invoiceId, subscriptionId: target.subscriptionId},+ 'Self-serve refund issued through Google Play',);+ return {+ invoice_id: target.invoiceId,+ payment_intent_id: null,+ charge_id: null,+ refund_id: null,+ refunded_amount_cents: null,+ invoice_amount_paid_cents: null,+ currency: null,+ subscription_id: target.subscriptionId,+ status: 'succeeded',+ provider: 'google_play',+ };}async handleRefundWebhookEvent(refund: Stripe.Refund): Promise<void> {@@ -269,7 +319,7 @@ export class StripeRefundService {}async refundLatestPurchase(userId: UserID): Promise<SelfServeRefundResponse> {- const stripe = this.ensureStripe();+ this.ensureAvailable();const user = await this.getRequiredUser(userId);const target = await this.resolveLatestRefundTarget(user);if (!target) {@@ -282,6 +332,10 @@ export class StripeRefundService {if (refundCooldownExpiresAt(user)) {throw new StripeRefundCooldownActiveError();}+ if (target.provider === 'google_play') {+ return this.refundGooglePlayPurchase(user, target);+ }+ const stripe = this.stripe!;const priorFailures = await this.countPriorTerminalFailures(target.invoiceId);const idempotencyKey = ['self-serve-refund',@@ -353,6 +407,7 @@ export class StripeRefundService {currency: target.currency,subscription_id: succeeded ? target.subscriptionId : null,status: refund.status ?? 'pending',+ provider: 'stripe',};}}