A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {UserID} from '@app/api/BrandedTypes';
import type {BillingRepository} from '@app/api/billing/repositories/BillingRepository';
import {mapBillingDocument} from '@app/api/billing_documents/BillingDocumentMappers';
import {BillingDocumentRepository} from '@app/api/billing_documents/BillingDocumentRepository';
import {Config} from '@app/api/Config';
import type {
BillingInvoiceRow,
BillingPaymentMethodRow,
BillingRefundRow,
BillingSubscriptionRow,
} from '@app/api/database/types/BillingTypes';
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,
} from '@app/api/store_billing/StoreBillingMappers';
import type {StoreBillingRepository} from '@app/api/store_billing/StoreBillingRepository';
import {isStripeSubscriptionActive} from '@app/api/store_billing/StoreEntitlementWriter';
import {isBillingActive} from '@app/api/stripe/BillingConfigCache';
import {applyDistributionToQuote, resolveListPriceId} from '@app/api/stripe/DistributionPricing';
import {getProductRegistry, type RecurringBillingCycle} from '@app/api/stripe/ProductRegistry';
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,
combinedRefundTarget,
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,
ListPriceSwitchState,
PendingSubscriptionChangeKind,
PendingSubscriptionChangeResponse,
PremiumBillingPaymentMethodResponse,
PremiumBillingSubscriptionResponse,
PremiumPricingState,
PremiumStateResponse,
PremiumSubscriptionProvider,
PriceIdsResponse,
SelfServeRefundEligibilityResponse,
} from '@fluxer/schema/src/domains/premium/PremiumSchemas';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import type Stripe from 'stripe';
const INVOICE_LIMIT = 12;
const DOCUMENT_LIST_LIMIT = 50;
const ACTIVE_SUBSCRIPTION_STATUSES = new Set(['active', 'trialing']);
const RELEVANT_SUBSCRIPTION_STATUSES = new Set(['past_due', 'unpaid', 'incomplete']);
const REFUND_BLOCKING_STATUSES = new Set(['pending', 'succeeded', 'requires_action']);
interface InvoiceResult {
rows: Array<BillingInvoiceRow>;
allRows: Array<BillingInvoiceRow>;
hasMore: boolean;
}
interface StripePriceDetails {
priceId: string | null;
amountMinor: number | null;
currency: Currency | null;
billingCycle: RecurringBillingCycle | null;
}
function toNumber(value: bigint | number | null | undefined): number {
if (value == null) {
return 0;
}
return Number(value);
}
function nullableNumber(value: bigint | number | null | undefined): number | null {
if (value == null) {
return null;
}
return Number(value);
}
function positiveIntegerFromMetadata(value: string | null | undefined): number | null {
if (value == null) {
return null;
}
const parsed = Number(value);
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;
}
return null;
}
function billingCycleFromInterval(value: string | null | undefined): RecurringBillingCycle | null {
if (value === 'month') {
return 'monthly';
}
if (value === 'year') {
return 'yearly';
}
return null;
}
function normalizeCurrency(value: string | null | undefined): Currency | null {
return normalizeCatalogCurrency(value);
}
function compareNullableDatesDesc(left: Date | null | undefined, right: Date | null | undefined): number {
return (right?.getTime() ?? 0) - (left?.getTime() ?? 0);
}
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;
}
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;
}
return compareNullableDatesDesc(left.current_period_end, right.current_period_end);
});
}
function normalizeCountryCode(countryCode: string | null | undefined): string | null {
const normalized = countryCode?.trim().toUpperCase();
return normalized && normalized.length === 2 ? normalized : null;
}
function resolveSubscriptionProvider(
user: User,
stripeSubscription: BillingSubscriptionRow | null,
storeRow: StorePurchaseRow | null,
now: Date,
): PremiumSubscriptionProvider | 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;
const storeEnd = storeRow ? resolveStoreAccessEnd(storeRow) : null;
if (storeRow && storeEnd && (!stripeEnd || storeEnd.getTime() >= stripeEnd.getTime())) {
return storeRow.provider;
}
return stripeEnd ? 'stripe' : null;
}
function mapPaymentMethod(row: BillingPaymentMethodRow): PremiumBillingPaymentMethodResponse {
return {
id: row.provider_id,
type: row.type ?? null,
card_brand: row.card_brand ?? null,
card_last4: row.card_last4 ?? null,
card_exp_month: row.card_exp_month ?? null,
card_exp_year: row.card_exp_year ?? null,
is_default: row.is_default ?? false,
};
}
export class PremiumStateService {
private readonly productRegistry = getProductRegistry();
constructor(
private readonly userRepository: UserRepository,
private readonly gatewayService: IGatewayService,
private readonly billingRepository: BillingRepository,
private readonly stripe: Stripe | null = null,
private readonly cacheService: ICacheService | null = null,
private readonly storeBillingRepository: StoreBillingRepository | null = null,
) {}
async getState(userId: UserID, countryCode?: string, distribution?: string): Promise<PremiumStateResponse> {
const user = await this.userRepository.findUnique(userId);
if (!user) {
throw new UnknownUserError();
}
return this.buildState(user, countryCode, distribution);
}
async setPerksDisabled(userId: UserID, disabled: boolean): Promise<PremiumStateResponse> {
const user = await this.userRepository.findUnique(userId);
if (!user) {
throw new UnknownUserError();
}
const nextFlags = disabled
? user.premiumFlags | PremiumFlags.PERKS_DISABLED
: user.premiumFlags & ~PremiumFlags.PERKS_DISABLED;
const updatedUser =
nextFlags === user.premiumFlags
? user
: await this.userRepository.patchUpsert(user.id, {premium_flags: nextFlags}, user.toRow());
if (updatedUser !== user) {
await dispatchUserUpdate(this.gatewayService, updatedUser);
}
return this.buildState(updatedUser);
}
private async buildState(user: User, countryCode?: string, distribution?: string): Promise<PremiumStateResponse> {
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([
this.resolveInvoices(customerIds),
this.resolvePaymentMethods(customerIds),
this.resolveSubscriptionPrice(subscription, user),
this.resolvePendingSubscriptionChange(user),
this.resolvePricing(countryCode, distribution),
]);
const storeRow = await this.resolveActiveStoreSubscription(user);
const store = storeRow ? mapPremiumStoreSubscriptionState(storeRow) : null;
const refundEligibilityState = await this.resolveRefundEligibility(user, invoices.allRows);
const listPriceSwitch = this.resolveListPriceSwitch(subscription, subscriptionPrice, pendingSubscriptionChange);
const pendingBillingCycleChange =
pendingSubscriptionChange?.change_kind === 'billing_cycle' ? pendingSubscriptionChange : null;
const activePaidPremium = checkHasActivePaidPremium(user);
const isEffectivePremium = user.isPremium();
const actualPremiumEndAt = user.effectivePremiumUntil;
return {
actual: {
premium_type: user.premiumType ?? UserPremiumTypes.NONE,
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: toIsoOrNull(user.premiumGraceEndsAt),
has_active_paid_premium: activePaidPremium,
is_visionary: user.premiumType === UserPremiumTypes.LIFETIME,
has_ever_purchased: user.hasEverPurchased,
},
effective: {
is_premium: isEffectivePremium,
premium_type: isEffectivePremium ? (user.premiumType ?? UserPremiumTypes.NONE) : UserPremiumTypes.NONE,
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: 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,
},
billing: {
stripe_customer_id: customerIds[0] ?? user.stripeCustomerId ?? null,
current_subscription_price: subscriptionPrice,
pending_subscription_change: pendingBillingCycleChange,
list_price_switch: listPriceSwitch,
subscription: subscription ? await this.mapSubscription(subscription) : null,
documents: Config.instance.selfHosted
? []
: (await new BillingDocumentRepository().listUserDocuments(user.id, null, DOCUMENT_LIST_LIMIT)).map(
mapBillingDocument,
),
payment_methods: paymentMethods.map(mapPaymentMethod),
refund_eligibility: refundEligibilityState,
},
pricing,
store,
subscription_provider: resolveSubscriptionProvider(user, subscription, store ? storeRow : null, new Date()),
};
}
private async resolveActiveStoreSubscription(user: User): Promise<StorePurchaseRow | null> {
if (!this.storeBillingRepository || Config.instance.selfHosted) {
return null;
}
const rows = await this.storeBillingRepository.listPurchasesForUser(user.id);
return selectActiveStoreSubscription(rows, new Date());
}
private async resolveCustomerIds(user: User): Promise<Array<string>> {
const ids = new Set<string>();
if (user.stripeCustomerId) {
ids.add(user.stripeCustomerId);
}
const rows = await this.billingRepository.customers.findByUserId(user.id);
for (const row of rows) {
if (!row.deleted) {
ids.add(row.provider_id);
}
}
return [...ids];
}
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 (user.stripeSubscriptionId) {
add(await this.billingRepository.subscriptions.findById(user.stripeSubscriptionId));
}
for (const row of await this.billingRepository.subscriptions.listByUser(user.id)) {
add(row);
}
const customerIds = await this.resolveCustomerIds(user);
const customerSubscriptions = await Promise.all(
customerIds.map((customerId) => this.billingRepository.subscriptions.listByCustomer(customerId)),
);
for (const rows of customerSubscriptions) {
for (const row of rows) {
add(row);
}
}
return sortSubscriptionsByRelevance([...byId.values()])[0] ?? null;
}
private async resolveInvoices(customerIds: Array<string>): Promise<InvoiceResult> {
const byId = new Map<string, BillingInvoiceRow>();
let hasMore = false;
const customerInvoices = await Promise.all(
customerIds.map((customerId) => this.billingRepository.invoices.listByCustomer(customerId, {pageSize: 100})),
);
for (const result of customerInvoices) {
for (const row of result.rows) {
byId.set(row.provider_id, row);
}
if (result.pageState) {
hasMore = true;
}
}
const rows = [...byId.values()].sort((left, right) =>
compareNullableDatesDesc(left.stripe_created_at, right.stripe_created_at),
);
return {rows: rows.slice(0, INVOICE_LIMIT), allRows: rows, hasMore: hasMore || rows.length > INVOICE_LIMIT};
}
private async resolvePaymentMethods(customerIds: Array<string>): Promise<Array<BillingPaymentMethodRow>> {
const byId = new Map<string, BillingPaymentMethodRow>();
const customerPaymentMethods = await Promise.all(
customerIds.map((customerId) => this.billingRepository.paymentMethods.listByCustomer(customerId)),
);
for (const rows of customerPaymentMethods) {
for (const row of rows) {
byId.set(row.provider_id, row);
}
}
return [...byId.values()].sort((left, right) => {
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);
});
}
private async repairPaymentMethodsFromStripe(
user: User,
customerIds: Array<string>,
subscription: BillingSubscriptionRow | null,
): Promise<void> {
if (!this.stripe || customerIds.length === 0) {
return;
}
await Promise.all(
customerIds.map(async (customerId) => {
try {
await this.repairCustomerPaymentMethodsFromStripe(user, customerId, subscription);
} catch (error) {
Logger.warn(
{error, userId: user.id.toString(), customerId},
'Failed to lazily repair Stripe billing payment methods',
);
}
}),
);
}
private async repairCustomerPaymentMethodsFromStripe(
user: User,
customerId: string,
mirroredSubscription: BillingSubscriptionRow | null,
): Promise<void> {
if (!this.stripe) {
return;
}
let customer = await this.stripe.customers.retrieve(customerId, {
expand: ['invoice_settings.default_payment_method'],
});
await this.billingRepository.customers.upsertFromStripe(customer, {knownUserId: user.id});
if ('deleted' in customer && customer.deleted) {
return;
}
let subscription = await this.resolveStripeSubscriptionForPaymentMethodRepair(
user,
customerId,
mirroredSubscription,
);
const customerDefaultPaymentMethodId = extractId(customer.invoice_settings?.default_payment_method);
const subscriptionDefaultPaymentMethodId = extractId(subscription?.default_payment_method);
let defaultPaymentMethodId = customerDefaultPaymentMethodId ?? subscriptionDefaultPaymentMethodId;
if (
subscription &&
customerDefaultPaymentMethodId &&
customerDefaultPaymentMethodId !== subscriptionDefaultPaymentMethodId
) {
subscription = await this.stripe.subscriptions.update(subscription.id, {
default_payment_method: customerDefaultPaymentMethodId,
expand: ['default_payment_method'],
});
defaultPaymentMethodId = customerDefaultPaymentMethodId;
} else if (!customerDefaultPaymentMethodId && subscriptionDefaultPaymentMethodId) {
customer = await this.stripe.customers.update(customerId, {
invoice_settings: {default_payment_method: subscriptionDefaultPaymentMethodId},
expand: ['invoice_settings.default_payment_method'],
});
defaultPaymentMethodId = subscriptionDefaultPaymentMethodId;
}
await this.billingRepository.customers.upsertFromStripe(customer, {knownUserId: user.id});
if (subscription) {
await this.billingRepository.subscriptions.upsertFromStripe(subscription, {
knownUserId: user.id,
snapshotCapturedAt: new Date(),
});
}
const listedPaymentMethodIds = new Set<string>();
const paymentMethods = await this.stripe.customers.listPaymentMethods(customerId, {limit: 100});
for (const paymentMethod of paymentMethods.data) {
listedPaymentMethodIds.add(paymentMethod.id);
await this.billingRepository.paymentMethods.upsertFromStripe(paymentMethod, {
isDefault: paymentMethod.id === defaultPaymentMethodId,
});
}
if (defaultPaymentMethodId && !listedPaymentMethodIds.has(defaultPaymentMethodId)) {
const paymentMethod = await this.stripe.customers.retrievePaymentMethod(customerId, defaultPaymentMethodId);
await this.billingRepository.paymentMethods.upsertFromStripe(paymentMethod, {isDefault: true});
}
}
private async resolveStripeSubscriptionForPaymentMethodRepair(
user: User,
customerId: string,
mirroredSubscription: BillingSubscriptionRow | null,
): Promise<Stripe.Subscription | null> {
if (!this.stripe) {
return null;
}
const subscriptions = await this.stripe.subscriptions.list({
customer: customerId,
status: 'all',
limit: 100,
expand: ['data.default_payment_method'],
});
const activeSubscriptions = subscriptions.data.filter((subscription) =>
ACTIVE_SUBSCRIPTION_STATUSES.has(subscription.status),
);
return (
activeSubscriptions.find((subscription) => subscription.id === user.stripeSubscriptionId) ??
activeSubscriptions.find((subscription) => subscription.id === mirroredSubscription?.provider_id) ??
activeSubscriptions.sort((left, right) => {
const leftEnd = getPrimarySubscriptionItem(left)?.current_period_end ?? left.created;
const rightEnd = getPrimarySubscriptionItem(right)?.current_period_end ?? right.created;
return rightEnd - leftEnd;
})[0] ??
null
);
}
private async resolveSubscriptionPrice(
subscription: BillingSubscriptionRow | null,
user: User,
): Promise<CurrentSubscriptionPriceResponse> {
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;
}
const currency = (price?.currency ?? subscription.currency ?? 'usd').toUpperCase();
const baseListPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);
const currentPriceId = price?.provider_id ?? subscription.primary_price_id;
const listPriceId = resolveListPriceId(currentPriceId ?? null, baseListPriceId);
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;
}
return {
price_id: price?.provider_id ?? subscription.primary_price_id ?? '',
amount_minor: amountMinor,
currency: currency as Currency,
billing_cycle: billingCycle,
is_grandfathered: listPriceId != null && listPriceId !== (price?.provider_id ?? subscription.primary_price_id),
list_price_id: listPriceId,
list_amount_minor: nullableNumber(listPrice?.unit_amount),
};
}
private async mapSubscription(row: BillingSubscriptionRow): Promise<PremiumBillingSubscriptionResponse> {
const price = row.primary_price_id ? await this.billingRepository.prices.findById(row.primary_price_id) : null;
return {
id: row.provider_id,
status: row.status ?? null,
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: 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,
default_payment_method_id: row.default_payment_method ?? null,
};
}
private async resolvePendingSubscriptionChange(user: User): Promise<PendingSubscriptionChangeResponse> {
if (!this.stripe || !user.stripeSubscriptionId) {
return null;
}
try {
const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
expand: ['items.data.price', 'schedule'],
});
const schedule = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
if (!schedule || (schedule.status !== 'active' && schedule.status !== 'not_started')) {
return null;
}
return this.mapPendingSubscriptionChange(subscription, schedule, normalizeBillingCycle(user.premiumBillingCycle));
} catch (error) {
Logger.warn(
{error, userId: user.id, subscriptionId: user.stripeSubscriptionId},
'Failed to resolve pending Stripe subscription schedule change',
);
return null;
}
}
private async mapPendingSubscriptionChange(
subscription: Stripe.Subscription,
schedule: Stripe.SubscriptionSchedule,
fallbackCurrentBillingCycle: RecurringBillingCycle | null,
): Promise<PendingSubscriptionChangeResponse> {
const now = Math.floor(Date.now() / 1000);
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;
}
const currentItem = getPrimarySubscriptionItem(subscription);
const currentPriceDetails = await this.resolveStripePriceDetails(currentItem?.price ?? null);
const currentBillingCycle = currentPriceDetails.billingCycle ?? fallbackCurrentBillingCycle;
const targetItem = futurePhase.items[0] ?? null;
const targetPriceDetails = await this.resolveStripePriceDetails(targetItem?.price ?? null);
const metadataTargetBillingCycle = normalizeBillingCycle(schedule.metadata?.pending_billing_cycle);
const targetBillingCycle = targetPriceDetails.billingCycle ?? metadataTargetBillingCycle ?? currentBillingCycle;
if (!targetBillingCycle) {
return null;
}
const changeKind: PendingSubscriptionChangeKind =
targetBillingCycle === currentBillingCycle ? 'price' : 'billing_cycle';
if (
changeKind === 'price' &&
(targetPriceDetails.priceId == null || targetPriceDetails.priceId === currentPriceDetails.priceId)
) {
return null;
}
const quantity = targetItem?.quantity ?? currentItem?.quantity ?? 1;
const recurringAmountMinor =
targetPriceDetails.amountMinor == null ? null : targetPriceDetails.amountMinor * quantity;
const addInvoiceItemsTotal = await this.sumPhaseAddInvoiceItems(futurePhase);
const metadataCreditAmountMinor = positiveIntegerFromMetadata(
futurePhase.metadata?.first_invoice_credit_amount_minor,
);
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;
return {
schedule_id: schedule.id,
change_kind: changeKind,
current_billing_cycle: currentBillingCycle,
target_billing_cycle: targetBillingCycle,
effective_at: new Date(futurePhase.start_date * 1000).toISOString(),
current_price_id: currentPriceDetails.priceId,
target_price_id: targetPriceDetails.priceId,
target_amount_minor: targetPriceDetails.amountMinor,
currency: targetPriceDetails.currency,
initial_amount_minor: initialAmountMinor,
recurring_amount_minor: recurringAmountMinor,
credit_amount_minor: creditAmountMinor,
};
}
private resolveListPriceSwitch(
subscription: BillingSubscriptionRow | null,
subscriptionPrice: CurrentSubscriptionPriceResponse,
pendingChange: PendingSubscriptionChangeResponse,
): ListPriceSwitchState {
const base = {
pending: false,
current_price_id: subscriptionPrice?.price_id ?? null,
current_amount_minor: subscriptionPrice?.amount_minor ?? null,
list_price_id: subscriptionPrice?.list_price_id ?? null,
list_amount_minor: subscriptionPrice?.list_amount_minor ?? null,
currency: subscriptionPrice?.currency ?? null,
billing_cycle: subscriptionPrice?.billing_cycle ?? null,
effective_at: toIsoOrNull(subscription?.current_period_end),
};
if (Config.instance.selfHosted || !isBillingActive()) {
return {...base, available: false, reason: 'feature_unavailable'};
}
if (!subscription) {
return {...base, available: false, reason: 'no_active_subscription'};
}
if (!subscriptionPrice) {
return {...base, available: false, reason: 'unsupported_subscription'};
}
if (!subscription.status || !ACTIVE_SUBSCRIPTION_STATUSES.has(subscription.status)) {
return {...base, available: false, reason: 'subscription_not_chargeable'};
}
if (subscription.cancel_at != null || subscription.cancel_at_period_end === true) {
return {...base, available: false, reason: 'subscription_cancelling'};
}
if (pendingChange) {
const targetsListPrice =
subscriptionPrice.list_price_id != null && pendingChange.target_price_id === subscriptionPrice.list_price_id;
return {
...base,
available: false,
reason: targetsListPrice ? null : 'conflicting_pending_change',
pending: targetsListPrice,
effective_at: pendingChange.effective_at,
};
}
if (subscriptionPrice.list_price_id == null || subscriptionPrice.list_amount_minor == null) {
return {...base, available: false, reason: 'no_list_price'};
}
if (subscriptionPrice.list_price_id === subscriptionPrice.price_id) {
return {...base, available: false, reason: 'already_on_list_price'};
}
if (subscriptionPrice.list_amount_minor >= subscriptionPrice.amount_minor) {
return {...base, available: false, reason: 'not_a_price_decrease'};
}
if (base.effective_at == null) {
return {...base, available: false, reason: 'missing_period_end'};
}
return {...base, available: true, reason: null};
}
private async resolveStripePriceDetails(
priceRef: Stripe.Price | Stripe.DeletedPrice | string | null | undefined,
): Promise<StripePriceDetails> {
const priceId = extractId(priceRef);
let amountMinor: number | null =
typeof priceRef === 'object' && priceRef && 'unit_amount' in priceRef ? (priceRef.unit_amount ?? null) : null;
let currency: Currency | null =
typeof priceRef === 'object' && priceRef && 'currency' in priceRef ? normalizeCurrency(priceRef.currency) : null;
let billingCycle: RecurringBillingCycle | null =
typeof priceRef === 'object' && priceRef && 'recurring' in priceRef
? billingCycleFromInterval(priceRef.recurring?.interval)
: null;
if (priceId && (amountMinor == null || currency == null || billingCycle == null)) {
const mirroredPrice = await this.billingRepository.prices.findById(priceId);
amountMinor ??= nullableNumber(mirroredPrice?.unit_amount);
currency ??= normalizeCurrency(mirroredPrice?.currency);
billingCycle ??= billingCycleFromInterval(mirroredPrice?.interval);
}
if (this.stripe && priceId && (amountMinor == null || currency == null || billingCycle == null)) {
const livePrice = await this.stripe.prices.retrieve(priceId);
amountMinor ??= livePrice.unit_amount ?? null;
currency ??= normalizeCurrency(livePrice.currency);
billingCycle ??= billingCycleFromInterval(livePrice.recurring?.interval);
}
return {priceId, amountMinor, currency, billingCycle};
}
private async sumPhaseAddInvoiceItems(phase: Stripe.SubscriptionSchedule.Phase): Promise<number> {
let total = 0;
for (const item of phase.add_invoice_items ?? []) {
const invoiceItem = item as {
price?: Stripe.Price | Stripe.DeletedPrice | string | null;
price_data?: {
unit_amount?: number | null;
};
quantity?: number | null;
};
const unitAmount =
typeof invoiceItem.price_data?.unit_amount === 'number' ? invoiceItem.price_data.unit_amount : null;
const quantity = invoiceItem.quantity ?? 1;
if (unitAmount != null) {
total += unitAmount * quantity;
continue;
}
try {
const priceDetails = await this.resolveStripePriceDetails(invoiceItem.price);
if (priceDetails.amountMinor != null) {
total += priceDetails.amountMinor * quantity;
}
} catch (error) {
Logger.warn(
{error, priceId: extractId(invoiceItem.price)},
'Failed to resolve pending subscription schedule invoice item price',
);
}
}
return total;
}
private async resolvePricing(
countryCode: string | null | undefined,
distribution: string | undefined,
): Promise<PremiumPricingState> {
const normalizedCountryCode = normalizeCountryCode(countryCode);
const localized = await this.resolvePriceIds(normalizedCountryCode, distribution);
return {
country_code: normalizedCountryCode,
localized,
};
}
private async resolvePriceIds(
countryCode: string | null,
distribution: string | undefined,
): Promise<PriceIdsResponse | null> {
const resolved = this.productRegistry.resolveLocalizedPriceIds(countryCode);
if (!resolved) {
return null;
}
const [monthlyAmount, yearlyAmount, gift1MonthAmount, gift1YearAmount] = await Promise.all([
this.resolvePriceAmountMinor(resolved.monthly),
this.resolvePriceAmountMinor(resolved.yearly),
this.resolvePriceAmountMinor(resolved.gift_1_month),
this.resolvePriceAmountMinor(resolved.gift_1_year),
]);
return applyDistributionToQuote(
{
...resolved,
monthly_amount_minor: monthlyAmount,
yearly_amount_minor: yearlyAmount,
gift_1_month_amount_minor: gift1MonthAmount,
gift_1_year_amount_minor: gift1YearAmount,
distribution: null,
},
distribution,
);
}
private async resolvePriceAmountMinor(priceId: string | null): Promise<number | null> {
if (!priceId) {
return null;
}
const mirrored = await this.billingRepository.prices.findById(priceId);
if (mirrored) {
return nullableNumber(mirrored.unit_amount);
}
if (!Config.instance.selfHosted || !this.cacheService) {
return null;
}
const summary = await getCachedStripePriceSummary({
stripe: this.stripe,
cacheService: this.cacheService,
priceId,
mirror: this.billingRepository,
});
return summary?.unitAmountMinor ?? null;
}
private async invoiceHasBlockingRefund(invoice: BillingInvoiceRow): Promise<boolean> {
const refunds = await this.billingRepository.refunds.listByInvoice(invoice.provider_id);
return refunds.some(
(refund: BillingRefundRow) => refund.status == null || REFUND_BLOCKING_STATUSES.has(refund.status),
);
}
private async resolveRefundEligibility(
user: User,
invoices: Array<BillingInvoiceRow>,
): Promise<SelfServeRefundEligibilityResponse> {
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 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);
const targets: Array<RefundEligibilityTarget> = [];
for (const invoice of paidInvoices) {
if (await this.invoiceHasBlockingRefund(invoice)) {
continue;
}
const paidAt = invoice.paid_at ?? invoice.stripe_created_at;
if (!paidAt) {
continue;
}
targets.push({
provider: 'stripe',
invoiceId: invoice.provider_id,
amountPaidCents: nullableNumber(invoice.amount_paid),
currency: invoice.currency,
paidAt,
subscriptionId: invoice.subscription_id,
});
}
const latest = latestRefundTarget(...targets);
return latest ? combinedRefundTarget(latest, targets) : 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;
}
}