A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(billing): add distribution channel pricing (#3858)
Hampus7a74a43b9a58
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex 109d1cdd1..afe69d17d 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -18364,6 +18364,7 @@"additionalProperties": false},"billing": {"$ref": "#/components/schemas/InstanceBillingResponse"},+ "distribution_pricing": {"$ref": "#/components/schemas/DistributionPricingConfigResponse"},"notice": {"nullable": true,"description": "Notice shown to everyone on the instance, or null",@@ -18394,6 +18395,7 @@"integrations","media","billing",+ "distribution_pricing","notice","warnings"],@@ -18912,6 +18914,10 @@}},"billing": {"nullable": true, "allOf": [{"$ref": "#/components/schemas/InstanceBillingUpdateRequest"}]},+ "distribution_pricing": {+ "nullable": true,+ "allOf": [{"$ref": "#/components/schemas/DistributionPricingUpdateRequest"}]+ },"notice": {"description": "Notice shown to everyone on the instance, such as planned maintenance","nullable": true,@@ -24198,6 +24204,45 @@"x-enumNames": ["INCOMING", "CHANNEL_FOLLOWER"],"x-enumDescriptions": ["Incoming webhook", "Channel follower webhook"]},+ "DistributionPricingUpdateRequest": {+ "type": "object",+ "properties": {+ "rules": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9_]{1,32}$",+ "description": "Distribution id sent by clients built for that distribution, for example ios_marketplace"+ },+ "active": {+ "type": "boolean",+ "description": "Whether checkouts and quotes for this distribution use the channel price"+ },+ "rate_bps": {+ "type": "integer",+ "minimum": 1,+ "maximum": 3000,+ "description": "Share of the channel price that goes to the distribution, in basis points. 500 means 5%"+ },+ "products": {+ "minItems": 1,+ "maxItems": 2,+ "type": "array",+ "items": {"$ref": "#/components/schemas/DistributionProductSchema"},+ "description": "Products that get the channel price"+ }+ },+ "required": ["id", "active", "rate_bps", "products"]+ },+ "description": "Full list of distribution rules. A left-out rule that already has channel prices stays stored as inactive so its subscriptions keep renewing"+ }+ },+ "required": ["rules"]+ },"InstanceBillingUpdateRequest": {"type": "object","properties": {@@ -24563,6 +24608,7 @@},"PremiumCurrency": {"type": "string", "pattern": "^[A-Z]{3}$"},"StripePriceIdSchema": {"type": "string", "maxLength": 255, "pattern": "^price_[A-Za-z0-9]+$"},+ "DistributionProductSchema": {"type": "string", "enum": ["plutonium_subscription", "plutonium_gift"]},"EmailType": {"type": "string"},"PendingRegistrationResponse": {"type": "object",@@ -24622,6 +24668,19 @@"additionalProperties": false,"description": "Notice from the instance administrator shown to everyone, such as planned maintenance"},+ "DistributionPricingConfigResponse": {+ "type": "object",+ "properties": {+ "rules": {+ "default": [],+ "maxItems": 32,+ "type": "array",+ "items": {"$ref": "#/components/schemas/DistributionRuleSchema"}+ }+ },+ "required": ["rules"],+ "additionalProperties": false+ },"InstanceBillingResponse": {"type": "object","properties": {@@ -25053,6 +25112,78 @@"required": ["monthly", "yearly", "gift_1_month", "gift_1_year"],"additionalProperties": false},+ "DistributionRuleSchema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9_]{1,32}$",+ "description": "Distribution id sent by clients built for that distribution, for example ios_marketplace"+ },+ "active": {+ "type": "boolean",+ "description": "Whether checkouts and quotes for this distribution use the channel price"+ },+ "rate_bps": {+ "type": "integer",+ "minimum": 1,+ "maximum": 3000,+ "description": "Share of the channel price that goes to the distribution, in basis points. 500 means 5%"+ },+ "products": {+ "minItems": 1,+ "maxItems": 2,+ "type": "array",+ "items": {"$ref": "#/components/schemas/DistributionProductSchema"},+ "description": "Products that get the channel price"+ },+ "rule_version": {+ "type": "integer",+ "minimum": 1,+ "maximum": 9007199254740991,+ "description": "Bumped by the server whenever rate_bps changes. Prices made under a version keep it"+ },+ "prices": {+ "default": {},+ "description": "Channel Stripe prices keyed by \"<rule_version>:<base price ID>\". Managed by the server and never removed",+ "type": "object",+ "additionalProperties": {"$ref": "#/components/schemas/DistributionChannelPriceSchema"}+ }+ },+ "required": ["id", "active", "rate_bps", "products", "rule_version", "prices"],+ "additionalProperties": false+ },+ "DistributionChannelPriceSchema": {+ "type": "object",+ "properties": {+ "price_id": {+ "type": "string",+ "minLength": 1,+ "maxLength": 255,+ "description": "Stripe price ID charged through the distribution"+ },+ "rate_bps": {+ "type": "integer",+ "minimum": 1,+ "maximum": 3000,+ "description": "Share of the channel price that goes to the distribution, in basis points. 500 means 5%"+ },+ "base_unit_amount": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991,+ "description": "Unit amount of the base price, in minor units"+ },+ "unit_amount": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991,+ "description": "Unit amount of the channel price, in minor units"+ }+ },+ "required": ["price_id", "rate_bps", "base_unit_amount", "unit_amount"],+ "additionalProperties": false+ },"JobLedgerEntrySchema": {"type": "object","properties": {diff --git a/fluxer_admin/src/api/types/instance_billing.rs b/fluxer_admin/src/api/types/instance_billing.rsindex 605d97442..172331c17 100644--- a/fluxer_admin/src/api/types/instance_billing.rs+++ b/fluxer_admin/src/api/types/instance_billing.rs@@ -235,3 +235,14 @@ fn favicon_url(favicon_url: Option<&str>, icon_url: Option<&str>) -> Option<Stri.or_else(|| non_blank(icon_url)).map(str::to_owned)}++pub use crate::api::generated::types::{+ DistributionPricingConfigResponse as DistributionPricingResponse,+ DistributionPricingUpdateRequest,+ DistributionPricingUpdateRequestRulesItem as DistributionRuleUpdate,+ DistributionProductSchema as DistributionProduct,+ DistributionRuleSchema as DistributionRuleResponse,+};++pub const DISTRIBUTION_RATE_BPS_MAX: u64 = 3000;+pub const DISTRIBUTION_PRODUCTS_ALL: &str = "all";diff --git a/fluxer_admin/src/api/types/instance_config.rs b/fluxer_admin/src/api/types/instance_config.rsindex fca921073..451f7ee2a 100644--- a/fluxer_admin/src/api/types/instance_config.rs+++ b/fluxer_admin/src/api/types/instance_config.rs@@ -2,7 +2,10 @@use serde::{Deserialize, Serialize};-use super::{InstanceBillingResponse, InstanceBillingUpdateRequest};+use super::{+ DistributionPricingResponse, DistributionPricingUpdateRequest, InstanceBillingResponse,+ InstanceBillingUpdateRequest,+};use crate::api::generated::types as generated_types;pub use generated_types::{@@ -50,6 +53,7 @@ pub struct InstanceConfigResponse {pub experiment_delivery: ExperimentDeliveryConfigResponse,#[serde(default)]pub billing: InstanceBillingResponse,+ pub distribution_pricing: DistributionPricingResponse,pub auth: AuthConfigResponse,pub accounts: AccountsConfigResponse,#[serde(default)]@@ -1027,6 +1031,8 @@ pub struct InstanceConfigUpdateRequest {#[serde(skip_serializing_if = "Option::is_none")]pub billing: Option<InstanceBillingUpdateRequest>,#[serde(skip_serializing_if = "Option::is_none")]+ pub distribution_pricing: Option<DistributionPricingUpdateRequest>,+ #[serde(skip_serializing_if = "Option::is_none")]pub auth: Option<AuthConfigUpdateRequest>,#[serde(skip_serializing_if = "Option::is_none")]pub accounts: Option<AccountsConfigUpdateRequest>,diff --git a/fluxer_admin/src/routes/billing_actions.rs b/fluxer_admin/src/routes/billing_actions.rsindex a4cae43f0..1e8d25871 100644--- a/fluxer_admin/src/routes/billing_actions.rs+++ b/fluxer_admin/src/routes/billing_actions.rs@@ -7,14 +7,16 @@ use crate::{AppBrandingConfigUpdateRequest, AppPublicConfigUpdateRequest,BILLING_MAX_COUNTRY_CURRENCIES, BILLING_MAX_CURRENCIES,BILLING_MAX_LEGACY_PRICES_PER_SLOT, BILLING_MAX_LEGACY_SLOTS, BILLING_PRICE_SLOTS,- BillingPriceSet, InstanceBillingUpdateRequest, InstanceConfigUpdateRequest,+ BillingPriceSet, DISTRIBUTION_PRODUCTS_ALL, DISTRIBUTION_RATE_BPS_MAX,+ DistributionPricingUpdateRequest, DistributionProduct, DistributionRuleUpdate,+ InstanceBillingUpdateRequest, InstanceConfigUpdateRequest,PREMIUM_PRODUCT_NAME_MAX_CHARS, TRI_STATE_DEFAULT, TRI_STATE_OFF, TRI_STATE_ON,},},middleware::flash::FlashData,utils::forms::MultiValueForm,};-use std::collections::BTreeMap;+use std::{collections::BTreeMap, num::NonZeroU64};const PRICE_ID_MAX_CHARS: usize = 255;const INFO_URL_MAX_CHARS: usize = 2048;@@ -333,3 +335,94 @@ fn parse_legacy_prices(value: &str) -> Result<Option<BTreeMap<String, Vec<String}Ok((!legacy.is_empty()).then_some(legacy))}++pub(super) fn build_distribution_pricing_update(+ form: &MultiValueForm,+) -> Result<InstanceConfigUpdateRequest, String> {+ let ids = form.values("distribution_id");+ let column = |key: &str, index: usize| {+ form.values(key)+ .get(index)+ .map(|value| value.trim())+ .unwrap_or("")+ };+ let mut rules: Vec<DistributionRuleUpdate> = Vec::new();+ for (index, id) in ids.iter().enumerate() {+ let id = id.trim();+ if id.is_empty() {+ continue;+ }+ let parsed = id.parse().map_err(|_| {+ format!(+ "\"{id}\" is not a valid distribution id. Use 1 to 32 lowercase letters, digits or underscores"+ )+ })?;+ if rules.iter().any(|rule| rule.id == parsed) {+ return Err(format!("{id} appears more than once"));+ }+ rules.push(DistributionRuleUpdate {+ rate_bps: parse_distribution_rate(column("distribution_rate", index), id)?,+ products: parse_distribution_products(column("distribution_products", index), id)?,+ active: column("distribution_active", index) == TRI_STATE_ON,+ id: parsed,+ });+ }+ Ok(InstanceConfigUpdateRequest {+ distribution_pricing: Some(DistributionPricingUpdateRequest { rules }),+ ..Default::default()+ })+}++fn parse_distribution_rate(value: &str, id: &str) -> Result<NonZeroU64, String> {+ let invalid =+ || format!("Rate for {id} must be a percentage between 0.01 and 30, like 5 or 2.5");+ let (whole, fraction) = value.split_once('.').unwrap_or((value, ""));+ if whole.is_empty()+ || fraction.len() > 2+ || !whole.bytes().all(|byte| byte.is_ascii_digit())+ || !fraction.bytes().all(|byte| byte.is_ascii_digit())+ {+ return Err(invalid());+ }+ let whole: u64 = whole.parse().map_err(|_| invalid())?;+ let fraction: u64 = format!("{fraction:0<2}").parse().map_err(|_| invalid())?;+ let bps = whole+ .checked_mul(100)+ .and_then(|bps| bps.checked_add(fraction))+ .filter(|bps| *bps <= DISTRIBUTION_RATE_BPS_MAX)+ .and_then(NonZeroU64::new)+ .ok_or_else(invalid)?;+ Ok(bps)+}++fn parse_distribution_products(value: &str, id: &str) -> Result<Vec<DistributionProduct>, String> {+ if value == DISTRIBUTION_PRODUCTS_ALL {+ return Ok(vec![+ DistributionProduct::PlutoniumSubscription,+ DistributionProduct::PlutoniumGift,+ ]);+ }+ value+ .parse()+ .map(|product| vec![product])+ .map_err(|_| format!("Invalid products choice \"{value}\" for {id}"))+}++#[cfg(test)]+mod tests {+ use super::parse_distribution_rate;+ use std::num::NonZeroU64;++ #[test]+ fn distribution_rate_reads_percent_into_basis_points() {+ let bps = |value| parse_distribution_rate(value, "x").map(NonZeroU64::get);+ assert_eq!(bps("5"), Ok(500));+ assert_eq!(bps("2.5"), Ok(250));+ assert_eq!(bps("0.01"), Ok(1));+ assert_eq!(bps("30"), Ok(3000));+ assert!(parse_distribution_rate("0", "x").is_err());+ assert!(parse_distribution_rate("30.01", "x").is_err());+ assert!(parse_distribution_rate("1.234", "x").is_err());+ assert!(parse_distribution_rate("-5", "x").is_err());+ }+}diff --git a/fluxer_admin/src/routes/system_actions.rs b/fluxer_admin/src/routes/system_actions.rsindex b3ec5d19f..d2096ae10 100644--- a/fluxer_admin/src/routes/system_actions.rs+++ b/fluxer_admin/src/routes/system_actions.rs@@ -217,6 +217,10 @@ pub async fn instance_config_post("update_billing" => {super::billing_actions::build_billing_update(&form).map_err(FlashData::error)}+ "update_distribution_pricing" => {+ super::billing_actions::build_distribution_pricing_update(&form)+ .map_err(FlashData::error)+ }"update_push_relay" => Ok(build_push_relay_update(&form)),"update_domain_migration" => {experiments::build_domain_migration_update(&form).map_err(FlashData::error)diff --git a/fluxer_admin/src/templates/pages/instance_billing.rs b/fluxer_admin/src/templates/pages/instance_billing.rsindex d775670fa..7fd140239 100644--- a/fluxer_admin/src/templates/pages/instance_billing.rs+++ b/fluxer_admin/src/templates/pages/instance_billing.rs@@ -3,8 +3,9 @@use crate::templates::pages::instance_config::ConfigForm;use crate::{api::types::{- AppBrandingConfigResponse, BillingCatalogMode, BillingPriceSet, InstanceBillingResponse,- PremiumMode, TRI_STATE_DEFAULT, TRI_STATE_OFF, TRI_STATE_ON,+ AppBrandingConfigResponse, BillingCatalogMode, BillingPriceSet, DISTRIBUTION_PRODUCTS_ALL,+ DistributionPricingResponse, DistributionProduct, DistributionRuleResponse,+ InstanceBillingResponse, PremiumMode, TRI_STATE_DEFAULT, TRI_STATE_OFF, TRI_STATE_ON,},templates::components::{badge::{BadgeVariant, badge},@@ -490,3 +491,140 @@ pub(crate) fn premium_billing_section(},)}++fn distribution_select(+ name: &str,+ label: &str,+ options: &[(&str, &str)],+ selected: &str,+) -> Markup {+ html! {+ td class="px-2 py-2" {+ div class="relative" {+ select name=(name) aria-label=(label) class=(FORM_SELECT_CLASS) {+ @for (value, display) in options {+ option value=(value) selected[*value == selected] { (display) }+ }+ }+ (select_chevron())+ }+ }+ }+}++fn distribution_rate_text(rate_bps: u64) -> String {+ format!("{}.{:02}", rate_bps / 100, rate_bps % 100)+ .trim_end_matches('0')+ .trim_end_matches('.')+ .to_owned()+}++fn distribution_products_value(products: &[DistributionProduct]) -> String {+ match products {+ [only] => only.to_string(),+ _ => DISTRIBUTION_PRODUCTS_ALL.to_owned(),+ }+}++fn distribution_row(rule: Option<&DistributionRuleResponse>) -> Markup {+ let rate = rule+ .map(|rule| distribution_rate_text(rule.rate_bps.get()))+ .unwrap_or_default();+ let products = rule.map_or_else(+ || DISTRIBUTION_PRODUCTS_ALL.to_owned(),+ |rule| distribution_products_value(&rule.products),+ );+ let active = if rule.is_none_or(|rule| rule.active) {+ TRI_STATE_ON+ } else {+ TRI_STATE_OFF+ };+ html! {+ tr {+ td class="px-2 py-2" {+ input type="text" name="distribution_id" value=(rule.map_or("", |rule| rule.id.as_str()))+ placeholder="ios_marketplace" maxlength="32" aria-label="Distribution id"+ autocomplete="off" spellcheck="false"+ class={(FORM_INPUT_CLASS) " w-48"};+ }+ td class="px-2 py-2" {+ input type="text" name="distribution_rate" value=(rate)+ placeholder="5" inputmode="decimal" aria-label="Rate in percent"+ autocomplete="off" class={(FORM_INPUT_CLASS) " w-20"};+ }+ (distribution_select(+ "distribution_products",+ "Products",+ &[+ (DISTRIBUTION_PRODUCTS_ALL, "Subscriptions and gifts"),+ ("plutonium_subscription", "Subscriptions"),+ ("plutonium_gift", "Gifts"),+ ],+ &products,+ ))+ (distribution_select(+ "distribution_active",+ "Active",+ &[(TRI_STATE_ON, "On"), (TRI_STATE_OFF, "Off")],+ active,+ ))+ td class="px-2 py-2 text-xs text-neutral-500 whitespace-nowrap" {+ @if let Some(rule) = rule {+ "Version " (rule.rule_version) ", " (rule.prices.len())+ @if rule.prices.len() == 1 { " channel price" } @else { " channel prices" }+ }+ }+ }+ }+}++pub(crate) fn distribution_pricing_section(+ base: &str,+ config_form: ConfigForm<'_>,+ pricing: &DistributionPricingResponse,+) -> Markup {+ section_card_with_description(+ "Distribution pricing",+ "App builds sold through a store that keeps a share of each sale send their distribution id with price \+ and checkout requests. A matching rule charges the price divided by one minus the rate, rounded up, \+ so the amount left after the store's share is at least the standard price. Every other request pays the \+ standard price.",+ html! {+ form method="post" action={(base) "/instance-config?action=update_distribution_pricing"}+ data-admin-result-form="true" {+ (config_form.fields())+ div class="space-y-4" {+ div class="overflow-x-auto" {+ table class="min-w-full text-sm" {+ thead {+ tr class="text-left text-xs text-neutral-500" {+ th class="px-2 py-1 font-medium" { "Distribution id" }+ th class="px-2 py-1 font-medium" { "Rate (%)" }+ th class="px-2 py-1 font-medium" { "Products" }+ th class="px-2 py-1 font-medium" { "Active" }+ th class="px-2 py-1 font-medium" {}+ }+ }+ tbody {+ @for rule in &pricing.rules {+ (distribution_row(Some(rule)))+ }+ (distribution_row(None))+ }+ }+ }+ p class="text-xs text-neutral-500" {+ "Changing a rate starts a new version. New checkouts and plan changes use \+ it, and existing subscriptions keep the price they signed up at. The API creates the \+ Stripe price for each channel the first time someone checks out. Clear a distribution id \+ to remove its rule. A rule that already has channel prices stays stored as inactive so \+ those subscriptions keep renewing."+ }+ (form_actions(html! {+ (submit_button("Save distribution pricing"))+ }))+ }+ }+ },+ )+}diff --git a/fluxer_admin/src/templates/pages/instance_config.rs b/fluxer_admin/src/templates/pages/instance_config.rsindex 7704c6a89..aea0319fa 100644--- a/fluxer_admin/src/templates/pages/instance_config.rs+++ b/fluxer_admin/src/templates/pages/instance_config.rs@@ -25,7 +25,8 @@ use crate::{},layout::admin_layout,pages::{- instance_billing::premium_billing_section, instance_branding::branding_section,+ instance_billing::{distribution_pricing_section, premium_billing_section},+ instance_branding::branding_section,instance_registration::registration_config_section,},},@@ -234,6 +235,11 @@ pub fn instance_config_page(),))}+ (config_group(+ "Distribution pricing",+ "Channel prices for app builds sold through a store that takes a share of each sale.",+ distribution_pricing_section(base, config_form, &instance_config.distribution_pricing),+ ))(config_group("Runtime integrations","Credentials and provider choices that override environment variables at runtime.",diff --git a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.tsindex e9662fce7..5e0dd927b 100644--- a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts@@ -46,6 +46,7 @@ import {} from '@app/api/middleware/ServiceSingletons';import type {User} from '@app/api/models/User';import {RateLimitConfigs} from '@app/api/RateLimitConfig';+import {mergeDistributionRules} from '@app/api/stripe/DistributionPricing';import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';import {scheduleSystemDeletion} from '@app/api/user/AccountCleanup';import {noticeEmailAddress} from '@app/api/user/services/SystemDmMessage';@@ -258,6 +259,7 @@ async function buildInstanceConfigResponse(warnings: Array<string> = []): PromisaccountIdentityLockReason,instantAccountAvailability,notice,+ distributionPricing,] = await Promise.all([instanceConfigRepository.getAppPublicConfig(),instanceConfigRepository.getInstancePolicyConfig(),@@ -269,6 +271,7 @@ async function buildInstanceConfigResponse(warnings: Array<string> = []): PromisinstanceConfigRepository.getAccountIdentityLockReason(),instanceConfigRepository.getInstantAccountAvailability(),instanceConfigRepository.getInstanceNotice(),+ instanceConfigRepository.getDistributionPricingConfig(),]);return {sso: {@@ -336,6 +339,7 @@ async function buildInstanceConfigResponse(warnings: Array<string> = []): Promisintegrations,media,billing,+ distribution_pricing: distributionPricing,notice,warnings,};@@ -667,6 +671,14 @@ const INSTANCE_CONFIG_SECTION_APPLIERS = {);},),+ distribution_pricing: createInstanceConfigSectionApplier(+ ({data}) => data.distribution_pricing,+ async (update, {instanceConfigRepository}) => {+ await instanceConfigRepository.updateDistributionPricingConfig((current) =>+ mergeDistributionRules(current, update.rules),+ );+ },+ ),voice_p2p: createInstanceConfigSectionApplier(({data}) => nonEmptyPatch(data.voice_p2p),async (patch, {instanceConfigRepository}) => {diff --git a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts b/fluxer_api/src/api/admin/services/AdminUserDeletionService.tsindex 2fd3efd10..fea9d6bdb 100644--- a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts+++ b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts@@ -32,6 +32,7 @@ import {type IARSubmission, ReportStatus} from '@app/api/report/ReportModels';import type {ReportService} from '@app/api/report/ReportService';import {getReportSearchService} from '@app/api/SearchFactory';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';+import {distributionRefundMetadata} from '@app/api/stripe/DistributionStripeMetadata';import {isEnforcementDeletionReason} from '@app/api/user/ProfileVisibility';import {type PartialUserChangePropagationDeps,@@ -429,6 +430,7 @@ export class AdminUserDeletionService {admin_user_id: String(adminUserId),target_user_id: String(userId),reason: 'pending_deletion',+ ...(await distributionRefundMetadata(stripe, refundTarget)),},});try {diff --git a/fluxer_api/src/api/database/types/PaymentTypes.ts b/fluxer_api/src/api/database/types/PaymentTypes.tsindex b8f811d72..0fad15916 100644--- a/fluxer_api/src/api/database/types/PaymentTypes.ts+++ b/fluxer_api/src/api/database/types/PaymentTypes.ts@@ -41,6 +41,13 @@ export interface PaymentRow {eu_withdrawal_waiver_accepted: boolean;eu_withdrawal_waiver_accepted_at: Date | null;eu_withdrawal_waiver_text_version: string | null;+ distribution?: string | null;+ distribution_rate_bps?: number | null;+ distribution_rule_version?: number | null;+ distribution_base_amount_minor?: number | null;+ distribution_purchase_ref?: string | null;+ tax_amount_minor?: number | null;+ tax_country?: string | null;created_at: Date;completed_at: Date | null;version: number;@@ -79,6 +86,13 @@ export const PAYMENT_COLUMNS = ['eu_withdrawal_waiver_accepted','eu_withdrawal_waiver_accepted_at','eu_withdrawal_waiver_text_version',+ 'distribution',+ 'distribution_rate_bps',+ 'distribution_rule_version',+ 'distribution_base_amount_minor',+ 'distribution_purchase_ref',+ 'tax_amount_minor',+ 'tax_country','created_at','completed_at','version',diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.tsindex d7af6b6fe..f2608be8b 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.ts@@ -61,6 +61,7 @@ import {isStripeServiceable,setStoredBillingConfig,} from '@app/api/stripe/BillingConfigCache';+import {defaultDistributionPricingConfig, setDistributionPricingConfig} from '@app/api/stripe/DistributionPricing';import {AdminAuditLogs, InstanceConfiguration, Users} from '@app/api/Tables';import {DEFAULT_DECAY_CONSTANTS, DEFAULT_RENEWAL_CONSTANTS} from '@app/api/utils/AttachmentDecay';import {isJsonRecord} from '@app/api/utils/JsonBoundaryUtils';@@ -153,6 +154,10 @@ import {type StoredBillingConfig,StoredBillingConfigSchema,} from '@fluxer/schema/src/domains/admin/InstanceBillingSchemas';+import {+ type DistributionPricingConfig,+ DistributionPricingConfigSchema,+} from '@fluxer/schema/src/domains/admin/InstanceDistributionPricingSchemas';import {type LegacyPushServiceDeliveryWire,type PushRelayConfig,@@ -184,6 +189,7 @@ const GATEWAY_ROLLOUT_CONFIG_KEY = 'gateway_rollout_config';const PUSH_RELAY_CONFIG_KEY = 'push_service_delivery_config';const DOMAIN_MIGRATION_CONFIG_KEY = 'domain_migration_config';const VOICE_P2P_CONFIG_KEY = 'voice_p2p_config';+const DISTRIBUTION_PRICING_CONFIG_KEY = 'distribution_pricing_config';const CAPTCHA_CONFIG_KEY = 'captcha_config';const AUTH_CONFIG_KEY = 'auth_config';const ACCOUNTS_CONFIG_KEY = 'accounts_config';@@ -572,6 +578,7 @@ type StoredConfigSection =| 'push relay'| 'domain migration'| 'voice p2p'+ | 'distribution pricing'| 'captcha'| 'auth'| 'accounts'@@ -804,6 +811,15 @@ function parseStoredVoiceP2pConfig(raw: string | null): VoiceP2pConfig {return parseStoredConfigOrDefault(VoiceP2pConfigSchema, raw, 'voice p2p');}+function parseStoredDistributionPricingConfig(raw: string | null): DistributionPricingConfig {+ if (raw === null) return defaultDistributionPricingConfig();+ return salvageStoredConfig(+ DistributionPricingConfigSchema,+ readStoredConfigValue(raw, 'distribution pricing'),+ 'distribution pricing',+ );+}+function migrateStoredCaptchaConfig(value: unknown): unknown {if (!isJsonRecord(value) || Object.hasOwn(value, 'provider') || typeof value.enabled !== 'boolean') return value;const {enabled, ...rest} = value;@@ -1841,6 +1857,9 @@ export class InstanceConfigRepository {parseStoredPushRelayConfig(snapshot.get(PUSH_RELAY_CONFIG_KEY) ?? null);parseStoredDomainMigrationConfig(snapshot.get(DOMAIN_MIGRATION_CONFIG_KEY) ?? null);parseStoredVoiceP2pConfig(snapshot.get(VOICE_P2P_CONFIG_KEY) ?? null);+ setDistributionPricingConfig(+ parseStoredDistributionPricingConfig(snapshot.get(DISTRIBUTION_PRICING_CONFIG_KEY) ?? null),+ );parseStoredCaptchaConfig(snapshot.get(CAPTCHA_CONFIG_KEY) ?? null);parseStoredAuthConfig(snapshot.get(AUTH_CONFIG_KEY) ?? null);setCachedAccountsConfig(@@ -2222,6 +2241,26 @@ export class InstanceConfigRepository {);}+ async getDistributionPricingConfig(): Promise<DistributionPricingConfig> {+ const config = parseStoredDistributionPricingConfig(await this.getConfig(DISTRIBUTION_PRICING_CONFIG_KEY));+ setDistributionPricingConfig(config);+ return config;+ }++ async updateDistributionPricingConfig(+ update: (current: DistributionPricingConfig) => DistributionPricingConfig,+ ): Promise<DistributionPricingConfig> {+ const next = await this.updateStoredConfig(DISTRIBUTION_PRICING_CONFIG_KEY, (raw) =>+ validateStoredConfig(+ DistributionPricingConfigSchema,+ update(parseStoredDistributionPricingConfig(raw)),+ 'distribution pricing',+ ),+ );+ setDistributionPricingConfig(next);+ return next;+ }+private async getStoredCustomBadges(): Promise<StoredCustomBadges> {const raw = await this.getConfig(CUSTOM_BADGES_CONFIG_KEY);if (this.parsedCustomBadges?.raw !== raw) {diff --git a/fluxer_api/src/api/models/Payment.ts b/fluxer_api/src/api/models/Payment.tsindex 2e638274a..524dacea4 100644--- a/fluxer_api/src/api/models/Payment.ts+++ b/fluxer_api/src/api/models/Payment.ts@@ -23,6 +23,13 @@ export class Payment {readonly euWithdrawalWaiverAccepted: boolean;readonly euWithdrawalWaiverAcceptedAt: Date | null;readonly euWithdrawalWaiverTextVersion: string | null;+ readonly distribution: string | null;+ readonly distributionRateBps: number | null;+ readonly distributionRuleVersion: number | null;+ readonly distributionBaseAmountMinor: number | null;+ readonly distributionPurchaseRef: string | null;+ readonly taxAmountMinor: number | null;+ readonly taxCountry: string | null;readonly createdAt: Date;readonly completedAt: Date | null;readonly version: number;@@ -47,6 +54,13 @@ export class Payment {this.euWithdrawalWaiverAccepted = row.eu_withdrawal_waiver_accepted ?? false;this.euWithdrawalWaiverAcceptedAt = row.eu_withdrawal_waiver_accepted_at ?? null;this.euWithdrawalWaiverTextVersion = row.eu_withdrawal_waiver_text_version ?? null;+ this.distribution = row.distribution ?? null;+ this.distributionRateBps = row.distribution_rate_bps ?? null;+ this.distributionRuleVersion = row.distribution_rule_version ?? null;+ this.distributionBaseAmountMinor = row.distribution_base_amount_minor ?? null;+ this.distributionPurchaseRef = row.distribution_purchase_ref ?? null;+ this.taxAmountMinor = row.tax_amount_minor ?? null;+ this.taxCountry = row.tax_country ?? null;this.createdAt = row.created_at;this.completedAt = row.completed_at ?? null;this.version = row.version;@@ -73,6 +87,13 @@ export class Payment {eu_withdrawal_waiver_accepted: this.euWithdrawalWaiverAccepted,eu_withdrawal_waiver_accepted_at: this.euWithdrawalWaiverAcceptedAt,eu_withdrawal_waiver_text_version: this.euWithdrawalWaiverTextVersion,+ distribution: this.distribution,+ distribution_rate_bps: this.distributionRateBps,+ distribution_rule_version: this.distributionRuleVersion,+ distribution_base_amount_minor: this.distributionBaseAmountMinor,+ distribution_purchase_ref: this.distributionPurchaseRef,+ tax_amount_minor: this.taxAmountMinor,+ tax_country: this.taxCountry,created_at: this.createdAt,completed_at: this.completedAt,version: this.version,diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.jsonindex 7e7f73476..84741ff7e 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -15376,6 +15376,13 @@"type": "string"},"description": "Two-letter country code for regional pricing. Only used when the server cannot geolocate the request; otherwise the request GeoIP country wins."+ },+ {+ "name": "distribution",+ "in": "query",+ "required": false,+ "schema": {"$ref": "#/components/schemas/DistributionQueryParam"},+ "description": "Distribution the client build was sold through. Unknown or inactive values fall back to the standard price"}]}@@ -15599,6 +15606,13 @@"type": "string"},"description": "Two-letter country code for regional pricing. Only used when the server cannot geolocate the request; otherwise the request GeoIP country wins."+ },+ {+ "name": "distribution",+ "in": "query",+ "required": false,+ "schema": {"$ref": "#/components/schemas/DistributionQueryParam"},+ "description": "Distribution the client build was sold through. Unknown or inactive values fall back to the standard price"}]}@@ -32209,7 +32223,9 @@"description": "Whether the purchase is for a business. When true, Stripe Checkout requires a billing address for the invoice. When false or omitted, billing address collection is left to Stripe (auto).","type": "boolean"},- "cnpj": {"$ref": "#/components/schemas/CnpjSchema"}+ "cnpj": {"$ref": "#/components/schemas/CnpjSchema"},+ "distribution": {"$ref": "#/components/schemas/DistributionQueryParam"},+ "distribution_token": {"$ref": "#/components/schemas/DistributionTokenParam"}},"required": ["price_id"]},@@ -32987,6 +33003,11 @@"required": ["app_account_token", "app_store", "google_play", "purchase_blocked_reason", "blocking_provider"],"additionalProperties": false},+ "DistributionQueryParam": {+ "description": "Distribution the client build was sold through. Unknown or inactive values fall back to the standard price",+ "type": "string",+ "maxLength": 64+ },"PremiumStateResponse": {"type": "object","properties": {@@ -33257,9 +33278,13 @@"gift_currency": {"anyOf": [{"$ref": "#/components/schemas/PremiumCurrency"}, {"type": "null"}],"description": "Currency for gift prices, null when no gift prices are configured"+ },+ "distribution": {+ "anyOf": [{"$ref": "#/components/schemas/PriceDistributionResponse"}, {"type": "null"}],+ "description": "Distribution whose channel price the amounts include, or null for the standard price"}},- "required": ["currency", "gift_currency"],+ "required": ["currency", "gift_currency", "distribution"],"additionalProperties": false},"UpdatePremiumPerksDisabledRequest": {@@ -44086,6 +44111,16 @@"additionalProperties": false},"PremiumCurrency": {"type": "string", "pattern": "^[A-Z]{3}$"},+ "PriceDistributionResponse": {+ "type": "object",+ "properties": {+ "id": {"type": "string", "pattern": "^[a-z0-9_]{1,32}$"},+ "rate_bps": {"type": "integer", "minimum": 1, "maximum": 3000},+ "rule_version": {"type": "integer", "minimum": 1, "maximum": 9007199254740991}+ },+ "required": ["id", "rate_bps", "rule_version"],+ "additionalProperties": false+ },"SelfServeRefundProvider": {"type": "string", "enum": ["stripe", "google_play"]},"SelfServeRefundIneligibilityReason": {"type": "string",@@ -45377,6 +45412,11 @@"enum": ["user", "bot", "webhook"],"type": "string"},+ "DistributionTokenParam": {+ "description": "Opaque purchase token from the distribution, kept for reporting",+ "type": "string",+ "maxLength": 4096+ },"CheckoutPaymentMethodEnum": {"type": "string", "enum": ["card", "pix", "upi"]},"GifCategoryTagResponse": {"type": "object",diff --git a/fluxer_api/src/api/premium/PremiumController.ts b/fluxer_api/src/api/premium/PremiumController.tsindex 38c014d08..384f2b704 100644--- a/fluxer_api/src/api/premium/PremiumController.ts+++ b/fluxer_api/src/api/premium/PremiumController.ts@@ -32,9 +32,11 @@ export function PremiumController(app: HonoApp) {}),async (ctx) => {const userId = ctx.get('user').id;- const {country_code} = ctx.req.valid('query');+ const {country_code, distribution} = ctx.req.valid('query');const geoip = await lookupGeoip(ctx.req.raw);- const state = await ctx.get('stripeService').premiumState.getState(userId, geoip.countryCode ?? country_code);+ const state = await ctx+ .get('stripeService')+ .premiumState.getState(userId, geoip.countryCode ?? country_code, distribution);return ctx.json(state);},);diff --git a/fluxer_api/src/api/stripe/DistributionPriceSync.ts b/fluxer_api/src/api/stripe/DistributionPriceSync.tsnew file mode 100644index 000000000..95b6391b3--- /dev/null+++ b/fluxer_api/src/api/stripe/DistributionPriceSync.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Logger} from '@app/api/Logger';+import {+ channelPriceKey,+ channelPriceLookupKey,+ channelUnitAmount,+ lookupChannelPrice,+} from '@app/api/stripe/DistributionPricing';+import {extractId} from '@app/api/stripe/StripeUtils';+import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';+import type {+ DistributionChannelPrice,+ DistributionPricingConfig,+ DistributionRule,+} from '@fluxer/schema/src/domains/admin/InstanceDistributionPricingSchemas';+import type Stripe from 'stripe';++export interface DistributionPricingStore {+ updateDistributionPricingConfig(+ update: (current: DistributionPricingConfig) => DistributionPricingConfig,+ ): Promise<DistributionPricingConfig>;+}++function channelPriceParams(+ rule: DistributionRule,+ base: Stripe.Price,+ unitAmount: number,+ lookupKey: string,+): Stripe.PriceCreateParams {+ const product = extractId(base.product);+ if (!product) throw new StripeError('Base price has no product');+ return {+ currency: base.currency,+ product,+ unit_amount: unitAmount,+ ...(base.recurring+ ? {recurring: {interval: base.recurring.interval, interval_count: base.recurring.interval_count}}+ : {}),+ ...(base.tax_behavior ? {tax_behavior: base.tax_behavior} : {}),+ ...(base.nickname ? {nickname: base.nickname} : {}),+ lookup_key: lookupKey,+ metadata: {+ distribution: rule.id,+ distribution_rule_version: String(rule.rule_version),+ distribution_rate_bps: String(rule.rate_bps),+ distribution_base_price: base.id,+ },+ };+}++export class DistributionPriceSync {+ constructor(+ private readonly stripe: Stripe,+ private readonly store: DistributionPricingStore,+ ) {}++ async ensureChannelPrice(rule: DistributionRule, basePriceId: string): Promise<DistributionChannelPrice> {+ const known = lookupChannelPrice(rule, basePriceId);+ if (known) return known;+ const base = await this.stripe.prices.retrieve(basePriceId);+ if (base.unit_amount == null || base.billing_scheme === 'tiered') {+ throw new StripeError('Base price has no fixed unit amount');+ }+ const unitAmount = channelUnitAmount(base.unit_amount, base.currency, rule);+ const lookupKey = channelPriceLookupKey(rule, basePriceId);+ const price = await this.findOrCreatePrice(rule, base, unitAmount, lookupKey);+ const entry: DistributionChannelPrice = {+ price_id: price.id,+ rate_bps: rule.rate_bps,+ base_unit_amount: base.unit_amount,+ unit_amount: price.unit_amount ?? unitAmount,+ };+ const key = channelPriceKey(rule.rule_version, basePriceId);+ const stored = await this.store.updateDistributionPricingConfig((current) => ({+ rules: current.rules.map((candidate) =>+ candidate.id === rule.id && !candidate.prices[key]+ ? {...candidate, prices: {...candidate.prices, [key]: entry}}+ : candidate,+ ),+ }));+ const storedEntry = stored.rules.find((candidate) => candidate.id === rule.id)?.prices[key];+ Logger.info(+ {distribution: rule.id, ruleVersion: rule.rule_version, basePriceId, priceId: price.id, unitAmount},+ 'Registered distribution channel price',+ );+ return storedEntry ?? entry;+ }++ private async findOrCreatePrice(+ rule: DistributionRule,+ base: Stripe.Price,+ unitAmount: number,+ lookupKey: string,+ ): Promise<Stripe.Price> {+ const existing = await this.stripe.prices.list({lookup_keys: [lookupKey], limit: 1});+ const match = existing.data[0];+ if (match) {+ const matches =+ match.active &&+ match.unit_amount === unitAmount &&+ match.currency === base.currency &&+ extractId(match.product) === extractId(base.product);+ if (!matches) throw new StripeError(`Stripe price ${match.id} with lookup key ${lookupKey} does not match`);+ return match;+ }+ return this.stripe.prices.create(channelPriceParams(rule, base, unitAmount, lookupKey), {+ idempotencyKey: lookupKey,+ });+ }+}diff --git a/fluxer_api/src/api/stripe/DistributionPricing.ts b/fluxer_api/src/api/stripe/DistributionPricing.tsnew file mode 100644index 000000000..825bce25e--- /dev/null+++ b/fluxer_api/src/api/stripe/DistributionPricing.ts@@ -0,0 +1,323 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Config} from '@app/api/Config';+import {stripeCurrencyExponent} from '@fluxer/number_utils/src/PriceFormatting';+import {+ DEFAULT_HOSTED_DISTRIBUTION_PRICING_CONFIG,+ type DistributionChannelPrice,+ type DistributionPricingConfig,+ type DistributionProduct,+ type DistributionRule,+} from '@fluxer/schema/src/domains/admin/InstanceDistributionPricingSchemas';+import {DISTRIBUTION_ID_PATTERN} from '@fluxer/schema/src/domains/premium/DistributionSchemas';+import type {PriceIdsResponse} from '@fluxer/schema/src/domains/premium/PremiumSchemas';++interface DistributionPrice {+ id: string;+ rateBps: number;+ ruleVersion: number;+ baseUnitAmount: number;+ unitAmount: number;+}++export interface ProductDistribution extends DistributionPrice {+ basePriceId: string;+}++export interface DistributionSale extends DistributionPrice {+ purchaseRef: string | null;+}++const DISTRIBUTION_METADATA_KEYS = [+ 'distribution',+ 'distribution_rate_bps',+ 'distribution_rule_version',+ 'distribution_base_unit_amount',+ 'distribution_unit_amount',+ 'distribution_extra_unit_amount',+ 'distribution_purchase_ref',+] as const;++const MULTIPLE_OF_100_CURRENCIES = new Set(['HUF', 'ISK', 'TWD', 'UGX']);+const PURCHASE_REF_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;+const BPS_SCALE = 10000;++let storedConfig: DistributionPricingConfig | null = null;+let reverseIndex: {config: DistributionPricingConfig; byPriceId: Map<string, ProductDistributionRef>} | null = null;++interface ProductDistributionRef {+ id: string;+ ruleVersion: number;+ basePriceId: string;+ entry: DistributionChannelPrice;+}++export function defaultDistributionPricingConfig(): DistributionPricingConfig {+ return Config.instance.selfHosted ? {rules: []} : structuredClone(DEFAULT_HOSTED_DISTRIBUTION_PRICING_CONFIG);+}++export function setDistributionPricingConfig(config: DistributionPricingConfig | null): void {+ storedConfig = config;+}++export function getDistributionPricingConfig(): DistributionPricingConfig {+ storedConfig ??= defaultDistributionPricingConfig();+ return storedConfig;+}++export function parseDistributionId(value: string | null | undefined): string | null {+ return typeof value === 'string' && DISTRIBUTION_ID_PATTERN.test(value) ? value : null;+}++export function distributionProductOf(info: {isGift: boolean}): DistributionProduct {+ return info.isGift ? 'plutonium_gift' : 'plutonium_subscription';+}++function findDistributionRule(+ id: string | null,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): DistributionRule | null {+ if (id === null) return null;+ return config.rules.find((rule) => rule.id === id) ?? null;+}++export function resolveDistributionRule(+ id: string | null,+ product: DistributionProduct,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): DistributionRule | null {+ const rule = findDistributionRule(id, config);+ return rule?.active && rule.products.includes(product) ? rule : null;+}++function roundingStep(currency: string): number {+ const code = currency.toUpperCase();+ if (MULTIPLE_OF_100_CURRENCIES.has(code)) return 100;+ return stripeCurrencyExponent(code) === 3 ? 10 : 1;+}++export function channelUnitAmount(+ baseMinor: number,+ currency: string,+ rule: Pick<DistributionRule, 'rate_bps'>,+): number {+ const divisor = BPS_SCALE - rule.rate_bps;+ const raw = Math.floor((baseMinor * BPS_SCALE + divisor - 1) / divisor);+ const step = roundingStep(currency);+ return Math.max(baseMinor, Math.ceil(raw / step) * step);+}++export function channelPriceKey(ruleVersion: number, basePriceId: string): string {+ return `${ruleVersion}:${basePriceId}`;+}++export function channelPriceLookupKey(+ rule: Pick<DistributionRule, 'id' | 'rule_version' | 'rate_bps'>,+ basePriceId: string,+): string {+ return `dist_${rule.id}_${rule.rule_version}_${rule.rate_bps}_${basePriceId}`;+}++export function lookupChannelPrice(rule: DistributionRule, basePriceId: string): DistributionChannelPrice | null {+ return rule.prices[channelPriceKey(rule.rule_version, basePriceId)] ?? null;+}++function buildReverseIndex(config: DistributionPricingConfig): Map<string, ProductDistributionRef> {+ const byPriceId = new Map<string, ProductDistributionRef>();+ for (const rule of config.rules) {+ for (const [key, entry] of Object.entries(rule.prices)) {+ const separator = key.indexOf(':');+ byPriceId.set(entry.price_id, {+ id: rule.id,+ ruleVersion: Number(key.slice(0, separator)),+ basePriceId: key.slice(separator + 1),+ entry,+ });+ }+ }+ return byPriceId;+}++export function findChannelPrice(+ priceId: string,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): ProductDistribution | null {+ if (reverseIndex?.config !== config) {+ reverseIndex = {config, byPriceId: buildReverseIndex(config)};+ }+ const ref = reverseIndex.byPriceId.get(priceId);+ if (!ref) return null;+ return {+ id: ref.id,+ ruleVersion: ref.ruleVersion,+ rateBps: ref.entry.rate_bps,+ basePriceId: ref.basePriceId,+ baseUnitAmount: ref.entry.base_unit_amount,+ unitAmount: ref.entry.unit_amount,+ };+}++export function distributionSaleFromEntry(+ rule: Pick<DistributionRule, 'id' | 'rule_version'>,+ entry: DistributionChannelPrice,+ purchaseRef: string | null,+): DistributionSale {+ return {+ id: rule.id,+ rateBps: entry.rate_bps,+ ruleVersion: rule.rule_version,+ baseUnitAmount: entry.base_unit_amount,+ unitAmount: entry.unit_amount,+ purchaseRef,+ };+}++export function distributionMetadata(sale: DistributionPrice & {purchaseRef?: string | null}): Record<string, string> {+ return {+ distribution: sale.id,+ distribution_rate_bps: String(sale.rateBps),+ distribution_rule_version: String(sale.ruleVersion),+ distribution_base_unit_amount: String(sale.baseUnitAmount),+ distribution_unit_amount: String(sale.unitAmount),+ distribution_extra_unit_amount: String(sale.unitAmount - sale.baseUnitAmount),+ ...(sale.purchaseRef ? {distribution_purchase_ref: sale.purchaseRef} : {}),+ };+}++export function pickDistributionMetadata(+ metadata: Readonly<Record<string, string>> | null | undefined,+): Record<string, string> {+ if (!metadata?.['distribution']) return {};+ const picked: Record<string, string> = {};+ for (const key of DISTRIBUTION_METADATA_KEYS) {+ const value = metadata[key];+ if (value) picked[key] = value;+ }+ return picked;+}++function metadataInt(value: string | undefined): number | null {+ return value && /^\d{1,10}$/.test(value) ? Number(value) : null;+}++export function distributionSaleFromMetadata(+ metadata: Readonly<Record<string, string>> | null | undefined,+): DistributionSale | null {+ const id = parseDistributionId(metadata?.['distribution']);+ const rateBps = metadataInt(metadata?.['distribution_rate_bps']);+ const ruleVersion = metadataInt(metadata?.['distribution_rule_version']);+ const baseUnitAmount = metadataInt(metadata?.['distribution_base_unit_amount']);+ const unitAmount = metadataInt(metadata?.['distribution_unit_amount']);+ if (!id || rateBps === null || ruleVersion === null || baseUnitAmount === null || unitAmount === null) return null;+ return {+ id,+ rateBps,+ ruleVersion,+ baseUnitAmount,+ unitAmount,+ purchaseRef: metadata?.['distribution_purchase_ref'] || null,+ };+}++export function distributionPaymentFields(sale: DistributionSale | null): {+ distribution: string | null;+ distribution_rate_bps: number | null;+ distribution_rule_version: number | null;+ distribution_base_amount_minor: number | null;+ distribution_purchase_ref: string | null;+} {+ return {+ distribution: sale?.id ?? null,+ distribution_rate_bps: sale?.rateBps ?? null,+ distribution_rule_version: sale?.ruleVersion ?? null,+ distribution_base_amount_minor: sale?.baseUnitAmount ?? null,+ distribution_purchase_ref: sale?.purchaseRef ?? null,+ };+}++export function decodeDistributionPurchaseRef(token: string | null | undefined): string | null {+ if (!token) return null;+ try {+ const payload = token.includes('.') ? (token.split('.')[1] ?? '') : token;+ const decoded: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (typeof decoded !== 'object' || decoded === null) return null;+ const ref = (decoded as Record<string, unknown>)['externalPurchaseId'];+ return typeof ref === 'string' && PURCHASE_REF_PATTERN.test(ref) ? ref : null;+ } catch {+ return null;+ }+}++type QuoteSlot = 'monthly' | 'yearly' | 'gift_1_month' | 'gift_1_year';++const QUOTE_SLOTS: ReadonlyArray<{slot: QuoteSlot; amount: `${QuoteSlot}_amount_minor`; product: DistributionProduct}> =+ [+ {slot: 'monthly', amount: 'monthly_amount_minor', product: 'plutonium_subscription'},+ {slot: 'yearly', amount: 'yearly_amount_minor', product: 'plutonium_subscription'},+ {slot: 'gift_1_month', amount: 'gift_1_month_amount_minor', product: 'plutonium_gift'},+ {slot: 'gift_1_year', amount: 'gift_1_year_amount_minor', product: 'plutonium_gift'},+ ];++export function applyDistributionToQuote(+ quote: PriceIdsResponse,+ distribution: string | null | undefined,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): PriceIdsResponse {+ const id = parseDistributionId(distribution);+ const next: PriceIdsResponse = {...quote, distribution: null};+ for (const {slot, amount, product} of QUOTE_SLOTS) {+ const rule = resolveDistributionRule(id, product, config);+ const basePriceId = quote[slot];+ if (!rule || !basePriceId) continue;+ const currency = product === 'plutonium_gift' ? quote.gift_currency : quote.currency;+ const baseAmount = quote[amount];+ next[slot] = lookupChannelPrice(rule, basePriceId)?.price_id ?? basePriceId;+ next[amount] = baseAmount == null || !currency ? null : channelUnitAmount(baseAmount, currency, rule);+ next.distribution = {id: rule.id, rate_bps: rule.rate_bps, rule_version: rule.rule_version};+ }+ return next;+}++export function mergeDistributionRules(+ current: DistributionPricingConfig,+ updates: ReadonlyArray<Omit<DistributionRule, 'rule_version' | 'prices'>>,+): DistributionPricingConfig {+ const existingById = new Map(current.rules.map((rule) => [rule.id, rule]));+ const updatedIds = new Set(updates.map((rule) => rule.id));+ const rules: Array<DistributionRule> = updates.map((next) => {+ const existing = existingById.get(next.id);+ if (!existing) return {...next, rule_version: 1, prices: {}};+ return {+ ...next,+ rule_version: existing.rate_bps !== next.rate_bps ? existing.rule_version + 1 : existing.rule_version,+ prices: existing.prices,+ };+ });+ const retired = current.rules+ .filter((rule) => !updatedIds.has(rule.id) && Object.keys(rule.prices).length > 0)+ .map((rule) => ({...rule, active: false}));+ return {rules: [...rules, ...retired]};+}++export function resolveListPriceId(+ currentPriceId: string | null,+ baseListPriceId: string | null,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): string | null {+ const current = currentPriceId ? findChannelPrice(currentPriceId, config) : null;+ if (!current || !currentPriceId) return baseListPriceId;+ if (!baseListPriceId) return null;+ const rule = resolveDistributionRule(current.id, 'plutonium_subscription', config);+ const entry = rule ? lookupChannelPrice(rule, baseListPriceId) : null;+ if (entry) return entry.price_id;+ return current.basePriceId === baseListPriceId ? currentPriceId : null;+}++export function subscriptionDistributionMetadata(+ priceId: string,+ config: DistributionPricingConfig = getDistributionPricingConfig(),+): Record<string, string> {+ const distribution = findChannelPrice(priceId, config);+ if (distribution) return distributionMetadata(distribution);+ return Object.fromEntries(DISTRIBUTION_METADATA_KEYS.map((key) => [key, '']));+}diff --git a/fluxer_api/src/api/stripe/DistributionStripeMetadata.ts b/fluxer_api/src/api/stripe/DistributionStripeMetadata.tsnew file mode 100644index 000000000..17074611f--- /dev/null+++ b/fluxer_api/src/api/stripe/DistributionStripeMetadata.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Logger} from '@app/api/Logger';+import {+ distributionMetadata,+ findChannelPrice,+ getDistributionPricingConfig,+ type ProductDistribution,+ pickDistributionMetadata,+} from '@app/api/stripe/DistributionPricing';+import {extractId} from '@app/api/stripe/StripeUtils';+import type Stripe from 'stripe';++function hasChannelPrices(): boolean {+ return getDistributionPricingConfig().rules.some((rule) => Object.keys(rule.prices).length > 0);+}++function invoiceDistribution(invoice: Stripe.Invoice): ProductDistribution | null {+ for (const line of invoice.lines?.data ?? []) {+ if (line.amount <= 0) continue;+ const priceId = extractId(line.pricing?.price_details?.price ?? null);+ const distribution = priceId ? findChannelPrice(priceId) : null;+ if (distribution) return distribution;+ }+ return null;+}++function invoiceDistributionMetadata(+ invoice: Stripe.Invoice,+ distribution: ProductDistribution,+): Record<string, string> {+ const subscriptionMetadata = invoice.parent?.subscription_details?.metadata ?? null;+ const purchaseRef =+ invoice.billing_reason === 'subscription_create' ? subscriptionMetadata?.['distribution_purchase_ref'] : undefined;+ return {+ ...distributionMetadata(distribution),+ ...(purchaseRef ? {distribution_purchase_ref: purchaseRef} : {}),+ };+}++export async function tagInvoiceDistribution(stripe: Stripe, invoice: Stripe.Invoice): Promise<void> {+ const distribution = invoiceDistribution(invoice);+ if (!distribution || !invoice.id) return;+ const metadata = invoiceDistributionMetadata(invoice, distribution);+ const payments = await stripe.invoicePayments.list({invoice: invoice.id, limit: 10});+ for (const payment of payments.data) {+ const paymentIntentId = extractId(payment.payment?.payment_intent ?? null);+ const chargeId = extractId(payment.payment?.charge ?? null);+ if (paymentIntentId) {+ const paymentIntent = await stripe.paymentIntents.update(paymentIntentId, {metadata});+ const latestChargeId = extractId(paymentIntent.latest_charge);+ if (latestChargeId) await stripe.charges.update(latestChargeId, {metadata});+ } else if (chargeId) {+ await stripe.charges.update(chargeId, {metadata});+ }+ }+}++export async function tagChargeDistribution(stripe: Stripe, charge: Stripe.Charge): Promise<void> {+ if (charge.metadata?.['distribution'] || !hasChannelPrices()) return;+ const paymentIntentId = extractId(charge.payment_intent);+ if (!paymentIntentId) return;+ const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);+ const metadata = pickDistributionMetadata(paymentIntent.metadata);+ if (Object.keys(metadata).length > 0) {+ await stripe.charges.update(charge.id, {metadata});+ }+}++export async function distributionRefundMetadata(+ stripe: Stripe,+ target: {payment_intent?: string | null; charge?: string | null},+): Promise<Record<string, string>> {+ if (!hasChannelPrices()) return {};+ try {+ if (target.payment_intent) {+ const paymentIntent = await stripe.paymentIntents.retrieve(target.payment_intent);+ return pickDistributionMetadata(paymentIntent.metadata);+ }+ if (!target.charge) return {};+ const charge = await stripe.charges.retrieve(target.charge);+ const fromCharge = pickDistributionMetadata(charge.metadata);+ if (Object.keys(fromCharge).length > 0) return fromCharge;+ const paymentIntentId = extractId(charge.payment_intent);+ if (!paymentIntentId) return {};+ const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);+ return pickDistributionMetadata(paymentIntent.metadata);+ } catch (error) {+ Logger.warn({error, target}, 'Failed to read distribution metadata for refund');+ return {};+ }+}diff --git a/fluxer_api/src/api/stripe/ProductRegistry.ts b/fluxer_api/src/api/stripe/ProductRegistry.tsindex 72ba970de..4d192939d 100644--- a/fluxer_api/src/api/stripe/ProductRegistry.ts+++ b/fluxer_api/src/api/stripe/ProductRegistry.ts@@ -7,6 +7,7 @@ import {type EffectiveBillingConfig,getEffectiveBillingConfig,} from '@app/api/stripe/BillingConfigCache';+import {findChannelPrice, type ProductDistribution} from '@app/api/stripe/DistributionPricing';import {type Currency, getCurrencyPreferences, getGiftCurrencyPreferences} from '@app/api/utils/CurrencyUtils';export enum ProductType {@@ -24,6 +25,7 @@ export interface ProductInfo {isGift: boolean;currency: Currency;billingCycle?: RecurringBillingCycle;+ distribution?: ProductDistribution;}const LEGACY_SLOT_SHAPES: Record<string, Omit<ProductInfo, 'currency'> | undefined> = {@@ -148,7 +150,17 @@ export class ProductRegistry {}getProduct(priceId: string): ProductInfo | null {- return this.products.get(priceId) || null;+ return this.products.get(priceId) ?? this.getChannelProduct(priceId);+ }++ private getChannelProduct(priceId: string): ProductInfo | null {+ const distribution = findChannelPrice(priceId);+ const base = distribution ? this.products.get(distribution.basePriceId) : undefined;+ return distribution && base ? {...base, distribution} : null;+ }++ getBasePriceId(priceId: string): string {+ return findChannelPrice(priceId)?.basePriceId ?? priceId;}isRecurringSubscription(info: ProductInfo): boolean {diff --git a/fluxer_api/src/api/stripe/StripeController.ts b/fluxer_api/src/api/stripe/StripeController.tsindex 8407a7bd1..3574562f8 100644--- a/fluxer_api/src/api/stripe/StripeController.ts+++ b/fluxer_api/src/api/stripe/StripeController.ts@@ -116,6 +116,8 @@ export function StripeController(app: HonoApp) {payment_method,is_business,cnpj,+ distribution,+ distribution_token,} = ctx.req.valid('json');const userId = ctx.get('user').id;const checkoutUrl = await ctx.get('stripeService').createCheckoutSession({@@ -129,6 +131,8 @@ export function StripeController(app: HonoApp) {paymentMethod: payment_method,isBusiness: is_business,cnpj,+ distribution,+ distributionToken: distribution_token,});return ctx.json({url: checkoutUrl});},@@ -150,8 +154,16 @@ export function StripeController(app: HonoApp) {}),Validator('json', CreateCheckoutSessionRequest),async (ctx) => {- const {price_id, country_code, client_geoip_country_code, eu_withdrawal_waiver_accepted, is_business, cnpj} =- ctx.req.valid('json');+ const {+ price_id,+ country_code,+ client_geoip_country_code,+ eu_withdrawal_waiver_accepted,+ is_business,+ cnpj,+ distribution,+ distribution_token,+ } = ctx.req.valid('json');const userId = ctx.get('user').id;const checkoutUrl = await ctx.get('stripeService').createCheckoutSession({userId,@@ -163,6 +175,8 @@ export function StripeController(app: HonoApp) {euWithdrawalWaiverAccepted: eu_withdrawal_waiver_accepted,isBusiness: is_business,cnpj,+ distribution,+ distributionToken: distribution_token,});return ctx.json({url: checkoutUrl});},@@ -263,9 +277,11 @@ export function StripeController(app: HonoApp) {tags: 'Premium',}),async (ctx) => {- const {country_code} = ctx.req.valid('query');+ const {country_code, distribution} = ctx.req.valid('query');const geoipCountryCode = await getPurchaseGeoipCountryCode(ctx.req.raw);- const priceIds = await ctx.get('stripeService').checkout.getPriceIds(geoipCountryCode ?? country_code);+ const priceIds = await ctx+ .get('stripeService')+ .checkout.getPriceIds(geoipCountryCode ?? country_code, distribution);return ctx.json(priceIds);},);diff --git a/fluxer_api/src/api/stripe/StripeService.ts b/fluxer_api/src/api/stripe/StripeService.tsindex 3d2fe7863..de5982329 100644--- a/fluxer_api/src/api/stripe/StripeService.ts+++ b/fluxer_api/src/api/stripe/StripeService.ts@@ -6,13 +6,14 @@ import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository'import type {GuildService} from '@app/api/guild/services/GuildService';import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';import type {OperatorPassServices} from '@app/api/middleware/OperatorPassServiceFactory';-import {getEmailService} from '@app/api/middleware/ServiceSingletons';+import {getEmailService, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';import {createOperatorPassFulfilmentService,type OperatorPassFulfilmentService,} from '@app/api/operator_pass/OperatorPassFulfilmentService';import type {StoreBillingRepository} from '@app/api/store_billing/StoreBillingRepository';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';+import {DistributionPriceSync} from '@app/api/stripe/DistributionPriceSync';import {getProductRegistry, type ProductRegistry} from '@app/api/stripe/ProductRegistry';import {getStripeClient} from '@app/api/stripe/StripeClient';import {PremiumStateService} from '@app/api/stripe/services/PremiumStateService';@@ -30,6 +31,7 @@ import type Stripe from 'stripe';export class StripeService {private stripe: Stripe | null;private productRegistry: ProductRegistry;+ private readonly distributionPriceSync: DistributionPriceSync | null;readonly checkout: StripeCheckoutService;readonly subscriptions: StripeSubscriptionService;readonly gifts: StripeGiftService;@@ -65,12 +67,16 @@ export class StripeService {this.cacheService,this.storeBillingRepository,);+ this.distributionPriceSync = this.stripe+ ? new DistributionPriceSync(this.stripe, getInstanceConfigRepository())+ : null;this.checkout = new StripeCheckoutService(this.stripe,this.userRepository,this.productRegistry,this.cacheService,this.storeEntitlementService,+ this.distributionPriceSync,);this.subscriptions = new StripeSubscriptionService(this.stripe,@@ -79,6 +85,7 @@ export class StripeService {this.cacheService,this.gatewayService,this.storeEntitlementService,+ this.distributionPriceSync,);this.operatorPassFulfilment = createOperatorPassFulfilmentService({stripe: this.stripe,diff --git a/fluxer_api/src/api/stripe/services/PremiumStateService.ts b/fluxer_api/src/api/stripe/services/PremiumStateService.tsindex 973132b4e..a8549f0e6 100644--- a/fluxer_api/src/api/stripe/services/PremiumStateService.ts+++ b/fluxer_api/src/api/stripe/services/PremiumStateService.ts@@ -29,6 +29,7 @@ import {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';@@ -202,12 +203,12 @@ export class PremiumStateService {private readonly storeBillingRepository: StoreBillingRepository | null = null,) {}- async getState(userId: UserID, countryCode?: string): Promise<PremiumStateResponse> {+ 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);+ return this.buildState(user, countryCode, distribution);}async setPerksDisabled(userId: UserID, disabled: boolean): Promise<PremiumStateResponse> {@@ -228,7 +229,7 @@ export class PremiumStateService {return this.buildState(updatedUser);}- private async buildState(user: User, countryCode?: string): Promise<PremiumStateResponse> {+ private async buildState(user: User, countryCode?: string, distribution?: string): Promise<PremiumStateResponse> {const [customerIds, subscription, paymentDisputeOpen] = await Promise.all([this.resolveCustomerIds(user),this.resolvePrimarySubscription(user),@@ -240,7 +241,7 @@ export class PremiumStateService {this.resolvePaymentMethods(customerIds),this.resolveSubscriptionPrice(subscription, user),this.resolvePendingSubscriptionChange(user),- this.resolvePricing(countryCode),+ this.resolvePricing(countryCode, distribution),]);const storeRow = await this.resolveActiveStoreSubscription(user);const store = storeRow ? mapPremiumStoreSubscriptionState(storeRow) : null;@@ -513,7 +514,9 @@ export class PremiumStateService {return null;}const currency = (price?.currency ?? subscription.currency ?? 'usd').toUpperCase();- const listPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);+ 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);@@ -745,16 +748,22 @@ export class PremiumStateService {return total;}- private async resolvePricing(countryCode: string | null | undefined): Promise<PremiumPricingState> {+ private async resolvePricing(+ countryCode: string | null | undefined,+ distribution: string | undefined,+ ): Promise<PremiumPricingState> {const normalizedCountryCode = normalizeCountryCode(countryCode);- const localized = await this.resolvePriceIds(normalizedCountryCode);+ const localized = await this.resolvePriceIds(normalizedCountryCode, distribution);return {country_code: normalizedCountryCode,localized,};}- private async resolvePriceIds(countryCode: string | null): Promise<PriceIdsResponse | null> {+ private async resolvePriceIds(+ countryCode: string | null,+ distribution: string | undefined,+ ): Promise<PriceIdsResponse | null> {const resolved = this.productRegistry.resolveLocalizedPriceIds(countryCode);if (!resolved) {return null;@@ -765,13 +774,17 @@ export class PremiumStateService {this.resolvePriceAmountMinor(resolved.gift_1_month),this.resolvePriceAmountMinor(resolved.gift_1_year),]);- return {- ...resolved,- monthly_amount_minor: monthlyAmount,- yearly_amount_minor: yearlyAmount,- gift_1_month_amount_minor: gift1MonthAmount,- gift_1_year_amount_minor: gift1YearAmount,- };+ 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> {diff --git a/fluxer_api/src/api/stripe/services/StripeCheckoutService.ts b/fluxer_api/src/api/stripe/services/StripeCheckoutService.tsindex a837ca249..add611c9d 100644--- a/fluxer_api/src/api/stripe/services/StripeCheckoutService.ts+++ b/fluxer_api/src/api/stripe/services/StripeCheckoutService.ts@@ -11,6 +11,18 @@ import {assertNoOpenPaymentDispute} from '@app/api/payment_disputes/PaymentDispuimport type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';import {getBillingBranding} from '@app/api/stripe/BillingBranding';import {getEffectiveBillingConfig, isCurrentCatalogPriceId} from '@app/api/stripe/BillingConfigCache';+import type {DistributionPriceSync} from '@app/api/stripe/DistributionPriceSync';+import {+ applyDistributionToQuote,+ type DistributionSale,+ decodeDistributionPurchaseRef,+ distributionMetadata,+ distributionPaymentFields,+ distributionProductOf,+ distributionSaleFromEntry,+ parseDistributionId,+ resolveDistributionRule,+} from '@app/api/stripe/DistributionPricing';import type {ProductInfo, ProductRegistry} from '@app/api/stripe/ProductRegistry';import {ensureStripeCustomer, isStripeResourceMissingError} from '@app/api/stripe/StripeCustomer';import {getPortalConfigurationId} from '@app/api/stripe/StripePortalConfiguration';@@ -90,6 +102,8 @@ export interface CreateCheckoutSessionParams {paymentMethod?: CheckoutPaymentMethod;isBusiness?: boolean;cnpj?: string;+ distribution?: string;+ distributionToken?: string;}const PIX_UPI_MANDATE_HEADROOM_MULTIPLIER = 1.25;@@ -191,11 +205,12 @@ export class StripeCheckoutService {private productRegistry: ProductRegistry,private cacheService: ICacheService,private storeEntitlementService: StoreEntitlementService | null = null,+ private distributionPriceSync: DistributionPriceSync | null = null,) {}async createCheckoutSession({userId,- priceId,+ priceId: requestedPriceId,isGift = false,countryCode,clientGeoipCountryCode,@@ -204,14 +219,24 @@ export class StripeCheckoutService {paymentMethod = 'card',isBusiness = false,cnpj,+ distribution,+ distributionToken,}: CreateCheckoutSessionParams): Promise<string> {+ const basePriceId = this.productRegistry.getBasePriceId(requestedPriceId);const {customerId, productInfo, user} = await this.prepareCheckoutContext({userId,- priceId,+ priceId: basePriceId,isGift,countryCode,purchaseGeoipCountryCode,});+ const distributionSale = await this.resolveDistributionSale({+ productInfo,+ basePriceId,+ distribution,+ distributionToken,+ });+ const priceId = distributionSale?.priceId ?? basePriceId;const isRecurringSubscription = this.productRegistry.isRecurringSubscription(productInfo);const checkoutMode: CheckoutSessionMode = isRecurringSubscription ? 'subscription' : 'payment';const effectivePaymentMethod =@@ -259,6 +284,7 @@ export class StripeCheckoutService {...(brazilBusiness ? {cnpj} : {}),...(billing.termsConsentRequired && !brazil && waiverContext.required ? {withdrawal_pro_rata: 'true'} : {}),payment_method: effectivePaymentMethod,+ ...(distributionSale ? distributionMetadata(distributionSale.sale) : {}),};const checkoutParams: CheckoutSessionCreateParams = {customer: customerId,@@ -319,9 +345,32 @@ export class StripeCheckoutService {clientGeoipCountryCode,purchaseGeoipCountryCode,waiverContext,+ distributionSale: distributionSale?.sale ?? null,});}+ private async resolveDistributionSale({+ productInfo,+ basePriceId,+ distribution,+ distributionToken,+ }: {+ productInfo: ProductInfo;+ basePriceId: string;+ distribution: string | undefined;+ distributionToken: string | undefined;+ }): Promise<{priceId: string; sale: DistributionSale} | null> {+ const rule = resolveDistributionRule(parseDistributionId(distribution), distributionProductOf(productInfo));+ if (!rule || !this.distributionPriceSync) {+ return null;+ }+ const entry = await this.distributionPriceSync.ensureChannelPrice(rule, basePriceId);+ return {+ priceId: entry.price_id,+ sale: distributionSaleFromEntry(rule, entry, decodeDistributionPurchaseRef(distributionToken)),+ };+ }+private async prepareCheckoutContext({userId,priceId,@@ -404,6 +453,7 @@ export class StripeCheckoutService {clientGeoipCountryCode,purchaseGeoipCountryCode,waiverContext,+ distributionSale,}: {checkoutParams: CheckoutSessionCreateParams;productInfo: ProductInfo;@@ -413,6 +463,7 @@ export class StripeCheckoutService {clientGeoipCountryCode?: string | null;purchaseGeoipCountryCode?: string | null;waiverContext: EuWithdrawalWaiverContext;+ distributionSale: DistributionSale | null;}): Promise<string> {if (!this.stripe) {throw new StripePaymentNotAvailableError();@@ -437,6 +488,7 @@ export class StripeCheckoutService {eu_withdrawal_waiver_accepted: waiverContext.accepted,eu_withdrawal_waiver_accepted_at: waiverContext.acceptedAt,eu_withdrawal_waiver_text_version: waiverContext.required ? EU_WITHDRAWAL_WAIVER_TEXT_VERSION : null,+ ...distributionPaymentFields(distributionSale),});Logger.debug({userId, sessionId: session.id, productType: productInfo.type}, 'Checkout session created');return session.url;@@ -676,7 +728,7 @@ export class StripeCheckoutService {}}- async getPriceIds(countryCode?: string): Promise<PriceIdsResponse> {+ async getPriceIds(countryCode?: string, distribution?: string): Promise<PriceIdsResponse> {const resolvedPrices = this.productRegistry.resolveLocalizedPriceIds(countryCode);if (!resolvedPrices) throw new StripeError('Stripe price ids missing for supported currencies');const [monthlyPrice, yearlyPrice, gift1MonthPrice, gift1YearPrice] = await Promise.all([@@ -685,13 +737,17 @@ export class StripeCheckoutService {this.getStripePriceSummary(resolvedPrices.gift_1_month),this.getStripePriceSummary(resolvedPrices.gift_1_year),]);- return {- ...resolvedPrices,- monthly_amount_minor: monthlyPrice?.unitAmountMinor ?? null,- yearly_amount_minor: yearlyPrice?.unitAmountMinor ?? null,- gift_1_month_amount_minor: gift1MonthPrice?.unitAmountMinor ?? null,- gift_1_year_amount_minor: gift1YearPrice?.unitAmountMinor ?? null,- };+ return applyDistributionToQuote(+ {+ ...resolvedPrices,+ monthly_amount_minor: monthlyPrice?.unitAmountMinor ?? null,+ yearly_amount_minor: yearlyPrice?.unitAmountMinor ?? null,+ gift_1_month_amount_minor: gift1MonthPrice?.unitAmountMinor ?? null,+ gift_1_year_amount_minor: gift1YearPrice?.unitAmountMinor ?? null,+ distribution: null,+ },+ distribution,+ );}private async getStripePriceSummary(priceId: string | null): Promise<StripePriceSummary | null> {diff --git a/fluxer_api/src/api/stripe/services/StripeCheckoutWebhookHandler.ts b/fluxer_api/src/api/stripe/services/StripeCheckoutWebhookHandler.tsindex 0c1300d90..b1f64155a 100644--- a/fluxer_api/src/api/stripe/services/StripeCheckoutWebhookHandler.ts+++ b/fluxer_api/src/api/stripe/services/StripeCheckoutWebhookHandler.ts@@ -15,6 +15,8 @@ import {type OperatorPassFulfilmentService,} from '@app/api/operator_pass/OperatorPassFulfilmentService';import {flagPurchaseDuringDispute} from '@app/api/payment_disputes/PaymentDisputeReviews';+import {distributionPaymentFields, distributionSaleFromMetadata} from '@app/api/stripe/DistributionPricing';+import {distributionRefundMetadata} from '@app/api/stripe/DistributionStripeMetadata';import type {ProductInfo, ProductRegistry} from '@app/api/stripe/ProductRegistry';import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';import {@@ -274,6 +276,8 @@ export class StripeCheckoutWebhookHandler {payment.euWithdrawalWaiverTextVersion ??session.metadata?.eu_withdrawal_waiver_text_version ??EU_WITHDRAWAL_WAIVER_TEXT_VERSION,+ tax_amount_minor: session.total_details?.amount_tax ?? null,+ tax_country: session.customer_details?.address?.country ?? null,});Logger.debug({@@ -587,6 +591,7 @@ export class StripeCheckoutWebhookHandler {metadata: {checkout_session_id: checkoutSessionId,rejection_reason: 'duplicate_active_subscription',+ ...(await distributionRefundMetadata(this.stripe, {charge: chargeId})),},},{idempotencyKey: `duplicate-sub-refund:${checkoutSessionId}`},@@ -751,6 +756,7 @@ export class StripeCheckoutWebhookHandler {eu_withdrawal_waiver_accepted_at: waiverAcceptedAt,eu_withdrawal_waiver_text_version:session.metadata?.eu_withdrawal_waiver_text_version ?? EU_WITHDRAWAL_WAIVER_TEXT_VERSION,+ ...distributionPaymentFields(distributionSaleFromMetadata(session.metadata)),});Logger.warn({sessionId: session.id, userId: userId.toString(), priceId, productType},diff --git a/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts b/fluxer_api/src/api/stripe/services/StripePaymentFraudService.tsindex e13fe1c17..0c0d15e84 100644--- a/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts+++ b/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts@@ -8,6 +8,7 @@ import {decisionAuditMetadata, type EnforcementDecisionService} from '@app/api/eimport {Logger} from '@app/api/Logger';import {getBillingRepository} from '@app/api/middleware/ServiceRegistry';import type {OperatorPassFulfilmentService} from '@app/api/operator_pass/OperatorPassFulfilmentService';+import {distributionRefundMetadata} from '@app/api/stripe/DistributionStripeMetadata';import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';import {extractId, isMissingOrCancelledSubscriptionError} from '@app/api/stripe/StripeUtils';import type {UserRepository} from '@app/api/user/repositories/UserRepository';@@ -335,6 +336,7 @@ export class StripePaymentFraudService {rejection_reason: 'stripe_early_fraud_warning',source: 'stripe_early_fraud_warning',warning_id: warningId,+ ...(await distributionRefundMetadata(stripe, {charge: charge.id})),},reason: 'fraudulent',},diff --git a/fluxer_api/src/api/stripe/services/StripeRefundService.ts b/fluxer_api/src/api/stripe/services/StripeRefundService.tsindex 6aaf4826e..9e1496c67 100644--- a/fluxer_api/src/api/stripe/services/StripeRefundService.ts+++ b/fluxer_api/src/api/stripe/services/StripeRefundService.ts@@ -11,6 +11,7 @@ import {isGooglePlaySelfServiceRefundEnabled,} from '@app/api/store_billing/GooglePlayRefundTarget';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';+import {distributionRefundMetadata} from '@app/api/stripe/DistributionStripeMetadata';import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';import {getInvoicePaymentRef} from '@app/api/stripe/StripeSubscriptionPeriod';import {extractId} from '@app/api/stripe/StripeUtils';@@ -881,6 +882,10 @@ export class StripeRefundService {? {withdrawal_received_at: withdrawalReceivedAt.toISOString()}: {refund_window_days: String(SELF_SERVE_REFUND_WINDOW_DAYS)}),...(target.subscriptionId ? {subscription_id: target.subscriptionId} : {}),+ ...(await distributionRefundMetadata(stripe, {+ payment_intent: target.paymentIntentId,+ charge: target.chargeId,+ })),},},{idempotencyKey},diff --git a/fluxer_api/src/api/stripe/services/StripeSubscriptionService.ts b/fluxer_api/src/api/stripe/services/StripeSubscriptionService.tsindex 8d6e97917..203d743d9 100644--- a/fluxer_api/src/api/stripe/services/StripeSubscriptionService.ts+++ b/fluxer_api/src/api/stripe/services/StripeSubscriptionService.ts@@ -11,6 +11,13 @@ import {addGiftCodeDuration} from '@app/api/models/GiftCode';import type {User} from '@app/api/models/User';import {assertNoOpenPaymentDispute} from '@app/api/payment_disputes/PaymentDisputeReviews';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';+import type {DistributionPriceSync} from '@app/api/stripe/DistributionPriceSync';+import {+ findChannelPrice,+ resolveDistributionRule,+ resolveListPriceId,+ subscriptionDistributionMetadata,+} from '@app/api/stripe/DistributionPricing';import type {ProductInfo, RecurringBillingCycle} from '@app/api/stripe/ProductRegistry';import {buildGiftTrialMetadata,@@ -136,8 +143,30 @@ export class StripeSubscriptionService {private cacheService: ICacheService,private gatewayService: IGatewayService,private storeEntitlementService: StoreEntitlementService | null = null,+ private distributionPriceSync: DistributionPriceSync | null = null,) {}+ private distributionMetadataForPriceChange(+ currentPriceId: string,+ targetPriceId: string,+ ): Record<string, string> | null {+ return findChannelPrice(currentPriceId) || findChannelPrice(targetPriceId)+ ? subscriptionDistributionMetadata(targetPriceId)+ : null;+ }++ private async resolveCycleChangeTargetPriceId(currentPriceId: string, baseTargetPriceId: string): Promise<string> {+ const current = findChannelPrice(currentPriceId);+ if (!current || !this.distributionPriceSync) {+ return baseTargetPriceId;+ }+ const rule = resolveDistributionRule(current.id, 'plutonium_subscription');+ if (!rule) {+ return baseTargetPriceId;+ }+ return (await this.distributionPriceSync.ensureChannelPrice(rule, baseTargetPriceId)).price_id;+ }+async cancelSubscriptionAtPeriodEnd(userId: UserID, source: BillingCancelSource): Promise<void> {if (!this.stripe) {throw new StripePaymentNotAvailableError();@@ -483,10 +512,11 @@ export class StripeSubscriptionService {);return;}- const targetPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, item.price.currency);- if (!targetPriceId) {+ const baseTargetPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, item.price.currency);+ if (!baseTargetPriceId) {throw new StripeInvalidProductConfigurationError();}+ const targetPriceId = await this.resolveCycleChangeTargetPriceId(item.price.id, baseTargetPriceId);const scheduledChange = await loadSubscriptionSchedule(this.stripe, subscription.schedule);if (scheduledChange && this.subscriptionScheduleHasFutureTargetPrice(scheduledChange, targetPriceId)) {const patch: Record<string, unknown> = {@@ -526,8 +556,11 @@ export class StripeSubscriptionService {return;}const clearCancellationParams = this.getClearCancellationUpdateParams(subscription) ?? {};+ const distributionMetadata = this.distributionMetadataForPriceChange(item.price.id, targetPriceId);+ const distributionMetadataPatch = distributionMetadata ? {metadata: distributionMetadata} : {};const updatedSubscription = await this.stripe.subscriptions.update(user.stripeSubscriptionId, {...clearCancellationParams,+ ...distributionMetadataPatch,items: [{id: item.id,@@ -628,7 +661,8 @@ export class StripeSubscriptionService {return {status: 'ineligible', reason: 'unsupported_subscription'};}const currency = item.price.currency.toUpperCase() as Currency;- const targetPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);+ const baseListPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);+ const targetPriceId = resolveListPriceId(item.price.id, baseListPriceId);if (!targetPriceId) {return {status: 'ineligible', reason: 'no_list_price'};}@@ -794,6 +828,10 @@ export class StripeSubscriptionService {first_invoice_credit_source: 'current_period_payment',};}+ const distributionMetadata = this.distributionMetadataForPriceChange(item.price.id, targetPriceId);+ if (distributionMetadata) {+ targetPhase.metadata = {...targetPhase.metadata, ...distributionMetadata};+ }await this.stripe.subscriptionSchedules.update(schedule.id, {end_behavior: clearCancellation ? 'release' : schedule.end_behavior,proration_behavior: 'none',@@ -1212,7 +1250,8 @@ export class StripeSubscriptionService {return null;}const currency = price.currency.toUpperCase() as Currency;- const listPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);+ const baseListPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);+ const listPriceId = resolveListPriceId(price.id, baseListPriceId);const listAmountMinor = listPriceId ? await this.getListPriceAmountMinor(listPriceId) : null;const isGrandfathered = listPriceId != null && listPriceId !== price.id;return {diff --git a/fluxer_api/src/api/stripe/services/StripeWebhookService.ts b/fluxer_api/src/api/stripe/services/StripeWebhookService.tsindex 058756ae0..2b903fe4e 100644--- a/fluxer_api/src/api/stripe/services/StripeWebhookService.ts+++ b/fluxer_api/src/api/stripe/services/StripeWebhookService.ts@@ -20,6 +20,7 @@ import {PaymentDisputeRepository} from '@app/api/payment_disputes/PaymentDisputeimport {PaymentDisputeReviewService} from '@app/api/payment_disputes/PaymentDisputeReviews';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';import {getAcceptedWebhookSecrets} from '@app/api/stripe/BillingConfigCache';+import {tagChargeDistribution, tagInvoiceDistribution} from '@app/api/stripe/DistributionStripeMetadata';import type {ProductRegistry} from '@app/api/stripe/ProductRegistry';import {mirrorBestEffort} from '@app/api/stripe/StripeMirror';import {extractId} from '@app/api/stripe/StripeUtils';@@ -223,6 +224,7 @@ export class StripeWebhookService {await this.mirrorInvoice(event, inv);await this.subscriptionHandler.handleInvoicePaymentSucceeded(event.id, inv);await this.queueBillingEmail(inv.id ? {kind: 'invoice_paid', id: inv.id} : null);+ if (event.type === 'invoice.paid' && this.stripe) await tagInvoiceDistribution(this.stripe, inv);break;}case 'invoice.payment_failed': {@@ -369,6 +371,7 @@ export class StripeWebhookService {case 'charge.captured': {const c = event.data.object as Stripe.Charge;await this.safeMirrorUpsert(event, () => this.billingRepository.charges.upsertFromStripe(c));+ if (event.type === 'charge.succeeded' && this.stripe) await tagChargeDistribution(this.stripe, c);break;}case 'refund.created':diff --git a/fluxer_api/src/api/stripe/tests/DistributionPricing.test.ts b/fluxer_api/src/api/stripe/tests/DistributionPricing.test.tsnew file mode 100644index 000000000..661a8d733--- /dev/null+++ b/fluxer_api/src/api/stripe/tests/DistributionPricing.test.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ applyDistributionToQuote,+ channelUnitAmount,+ decodeDistributionPurchaseRef,+ mergeDistributionRules,+ resolveListPriceId,+} from '@app/api/stripe/DistributionPricing';+import type {+ DistributionPricingConfig,+ DistributionRule,+} from '@fluxer/schema/src/domains/admin/InstanceDistributionPricingSchemas';+import type {PriceIdsResponse} from '@fluxer/schema/src/domains/premium/PremiumSchemas';+import {describe, expect, test} from 'vitest';++const RULE: DistributionRule = {+ id: 'ios_marketplace',+ active: true,+ rate_bps: 500,+ products: ['plutonium_subscription', 'plutonium_gift'],+ rule_version: 1,+ prices: {},+};++const QUOTE: PriceIdsResponse = {+ monthly: 'price_monthly_eur',+ yearly: 'price_yearly_eur',+ gift_1_month: 'price_gift_month_eur',+ gift_1_year: 'price_gift_year_eur',+ monthly_amount_minor: 499,+ yearly_amount_minor: 4999,+ gift_1_month_amount_minor: 499,+ gift_1_year_amount_minor: 4999,+ currency: 'EUR',+ gift_currency: 'EUR',+ distribution: null,+};++describe('channelUnitAmount', () => {+ test('leaves the standard price after a 5% share, rounded up', () => {+ expect(channelUnitAmount(499, 'EUR', RULE)).toBe(526);+ expect(channelUnitAmount(4999, 'EUR', RULE)).toBe(5263);+ });++ test('rounds currencies Stripe charges in hundreds up to a multiple of 100', () => {+ expect(channelUnitAmount(79900, 'ISK', RULE)).toBe(84200);+ expect(channelUnitAmount(199900, 'HUF', RULE) % 100).toBe(0);+ });++ test('never goes below the base amount', () => {+ expect(channelUnitAmount(0, 'EUR', RULE)).toBe(0);+ expect(channelUnitAmount(1, 'EUR', {...RULE, rate_bps: 1})).toBe(2);+ });+});++describe('applyDistributionToQuote', () => {+ const config: DistributionPricingConfig = {rules: [RULE]};++ test('quotes the channel amount and reports the rule for a known distribution', () => {+ const quote = applyDistributionToQuote(QUOTE, 'ios_marketplace', config);+ expect(quote.monthly_amount_minor).toBe(526);+ expect(quote.gift_1_year_amount_minor).toBe(5263);+ expect(quote.monthly).toBe('price_monthly_eur');+ expect(quote.distribution).toEqual({id: 'ios_marketplace', rate_bps: 500, rule_version: 1});+ });++ test('falls back to the standard price for malformed, unknown or inactive values', () => {+ for (const value of [undefined, '', 'IOS_MARKETPLACE', 'ios marketplace', 'web', 'x'.repeat(40)]) {+ expect(applyDistributionToQuote(QUOTE, value, config)).toEqual(QUOTE);+ }+ expect(applyDistributionToQuote(QUOTE, 'ios_marketplace', {rules: [{...RULE, active: false}]})).toEqual(QUOTE);+ });++ test('only raises the products the rule lists and returns registered channel price IDs', () => {+ const withPrice: DistributionRule = {+ ...RULE,+ products: ['plutonium_subscription'],+ prices: {'1:price_monthly_eur': {price_id: 'price_ch', rate_bps: 500, base_unit_amount: 499, unit_amount: 526}},+ };+ const quote = applyDistributionToQuote(QUOTE, 'ios_marketplace', {rules: [withPrice]});+ expect(quote.monthly).toBe('price_ch');+ expect(quote.yearly).toBe('price_yearly_eur');+ expect(quote.yearly_amount_minor).toBe(5263);+ expect(quote.gift_1_month).toBe('price_gift_month_eur');+ expect(quote.gift_1_month_amount_minor).toBe(499);+ });+});++describe('mergeDistributionRules', () => {+ const priced: DistributionRule = {+ ...RULE,+ prices: {'1:price_monthly_eur': {price_id: 'price_ch', rate_bps: 500, base_unit_amount: 499, unit_amount: 526}},+ };++ test('starts a new version when the rate changes and keeps the prices', () => {+ const {prices: _prices, rule_version: _version, ...editable} = priced;+ const same = mergeDistributionRules({rules: [priced]}, [{...editable, active: false}]);+ expect(same.rules[0]).toMatchObject({rule_version: 1, active: false, prices: priced.prices});+ const raised = mergeDistributionRules({rules: [priced]}, [{...editable, rate_bps: 600}]);+ expect(raised.rules[0]).toMatchObject({rule_version: 2, rate_bps: 600, prices: priced.prices});+ });++ test('keeps a removed rule with channel prices as inactive and drops one without', () => {+ const merged = mergeDistributionRules({rules: [priced, {...RULE, id: 'other'}]}, []);+ expect(merged.rules).toEqual([{...priced, active: false}]);+ });+});++describe('resolveListPriceId', () => {+ const config: DistributionPricingConfig = {+ rules: [+ {+ ...RULE,+ rule_version: 2,+ prices: {+ '1:price_monthly_old': {price_id: 'price_ch_old', rate_bps: 500, base_unit_amount: 399, unit_amount: 421},+ '2:price_monthly_eur': {price_id: 'price_ch_new', rate_bps: 500, base_unit_amount: 499, unit_amount: 526},+ },+ },+ ],+ };++ test('keeps the list price inside the distribution', () => {+ expect(resolveListPriceId('price_ch_old', 'price_monthly_eur', config)).toBe('price_ch_new');+ expect(resolveListPriceId('price_ch_new', 'price_monthly_eur', config)).toBe('price_ch_new');+ expect(resolveListPriceId('price_monthly_old', 'price_monthly_eur', config)).toBe('price_monthly_eur');+ expect(resolveListPriceId(null, 'price_monthly_eur', config)).toBe('price_monthly_eur');+ });++ test('offers no list price once the rule is off, so the channel price is never dropped', () => {+ const off = {rules: config.rules.map((rule) => ({...rule, active: false}))};+ expect(resolveListPriceId('price_ch_old', 'price_monthly_eur', off)).toBeNull();+ });+});++describe('decodeDistributionPurchaseRef', () => {+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');++ test('keeps only the external purchase id', () => {+ expect(decodeDistributionPurchaseRef(encode({externalPurchaseId: 'abc-123', bundleId: 'x'}))).toBe('abc-123');+ });++ test('ignores tokens it cannot read', () => {+ expect(decodeDistributionPurchaseRef('not base64 json')).toBeNull();+ expect(decodeDistributionPurchaseRef(encode({externalPurchaseId: 'bad value with spaces'}))).toBeNull();+ expect(decodeDistributionPurchaseRef(encode(['abc']))).toBeNull();+ expect(decodeDistributionPurchaseRef(undefined)).toBeNull();+ });+});diff --git a/fluxer_api/src/api/stripe/tests/DistributionStripeMetadata.test.ts b/fluxer_api/src/api/stripe/tests/DistributionStripeMetadata.test.tsnew file mode 100644index 000000000..2c62771ee--- /dev/null+++ b/fluxer_api/src/api/stripe/tests/DistributionStripeMetadata.test.ts@@ -0,0 +1,128 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {setDistributionPricingConfig} from '@app/api/stripe/DistributionPricing';+import {distributionRefundMetadata, tagInvoiceDistribution} from '@app/api/stripe/DistributionStripeMetadata';+import type Stripe from 'stripe';+import {afterEach, beforeEach, expect, test} from 'vitest';++const CHANNEL_KEYS = {+ distribution: 'ios_marketplace',+ distribution_rate_bps: '500',+ distribution_rule_version: '1',+ distribution_base_unit_amount: '499',+ distribution_unit_amount: '526',+ distribution_extra_unit_amount: '27',+};++beforeEach(() => {+ setDistributionPricingConfig({+ rules: [+ {+ id: 'ios_marketplace',+ active: true,+ rate_bps: 500,+ products: ['plutonium_subscription'],+ rule_version: 1,+ prices: {'1:price_base': {price_id: 'price_ch', rate_bps: 500, base_unit_amount: 499, unit_amount: 526}},+ },+ ],+ });+});++afterEach(() => {+ setDistributionPricingConfig(null);+});++test('refunds carry the distribution keys of the payment they reverse', async () => {+ const stripe = {+ paymentIntents: {retrieve: async () => ({metadata: {user_id: '1', ...CHANNEL_KEYS}})},+ charges: {retrieve: async () => ({metadata: {}, payment_intent: 'pi_1'})},+ } as unknown as Stripe;+ expect(await distributionRefundMetadata(stripe, {payment_intent: 'pi_1'})).toEqual(CHANNEL_KEYS);+ expect(await distributionRefundMetadata(stripe, {charge: 'ch_1'})).toEqual(CHANNEL_KEYS);+});++test('a refund still goes through when the payment cannot be read', async () => {+ const stripe = {+ paymentIntents: {+ retrieve: async () => {+ throw new Error('unavailable');+ },+ },+ } as unknown as Stripe;+ expect(await distributionRefundMetadata(stripe, {payment_intent: 'pi_1'})).toEqual({});+});++test('a renewal invoice on a channel price tags its payment intent and charge', async () => {+ const updates: Array<[string, Record<string, string>]> = [];+ const stripe = {+ invoicePayments: {list: async () => ({data: [{payment: {payment_intent: 'pi_renew'}}]})},+ paymentIntents: {+ update: async (id: string, params: {metadata: Record<string, string>}) => {+ updates.push([id, params.metadata]);+ return {latest_charge: 'ch_renew'};+ },+ },+ charges: {+ update: async (id: string, params: {metadata: Record<string, string>}) => {+ updates.push([id, params.metadata]);+ return {};+ },+ },+ } as unknown as Stripe;+ const invoice = {+ id: 'in_renew',+ billing_reason: 'subscription_cycle',+ lines: {data: [{amount: 526, pricing: {price_details: {price: 'price_ch'}}}]},+ } as unknown as Stripe.Invoice;+ await tagInvoiceDistribution(stripe, invoice);+ expect(updates).toEqual([+ ['pi_renew', CHANNEL_KEYS],+ ['ch_renew', CHANNEL_KEYS],+ ]);+ updates.length = 0;+ const standard = {...invoice, lines: {data: [{amount: 499, pricing: {price_details: {price: 'price_base'}}}]}};+ await tagInvoiceDistribution(stripe, standard as unknown as Stripe.Invoice);+ expect(updates).toEqual([]);+});++test('a plan change off the channel price is not tagged from the credit for unused time', async () => {+ const updates: Array<string> = [];+ const stripe = {+ invoicePayments: {list: async () => ({data: [{payment: {payment_intent: 'pi_change'}}]})},+ paymentIntents: {+ update: async (id: string) => {+ updates.push(id);+ return {latest_charge: null};+ },+ },+ } as unknown as Stripe;+ const invoice = {+ id: 'in_change',+ billing_reason: 'subscription_update',+ lines: {+ data: [+ {amount: -300, pricing: {price_details: {price: 'price_ch'}}},+ {amount: 4999, pricing: {price_details: {price: 'price_base_yearly'}}},+ ],+ },+ } as unknown as Stripe.Invoice;+ await tagInvoiceDistribution(stripe, invoice);+ expect(updates).toEqual([]);+});++test('a failed tag fails the webhook so Stripe sends it again', async () => {+ const stripe = {+ invoicePayments: {+ list: async () => {+ throw new Error('unavailable');+ },+ },+ } as unknown as Stripe;+ const invoice = {+ id: 'in_renew',+ billing_reason: 'subscription_cycle',+ lines: {data: [{amount: 526, pricing: {price_details: {price: 'price_ch'}}}]},+ } as unknown as Stripe.Invoice;+ await expect(tagInvoiceDistribution(stripe, invoice)).rejects.toThrow('unavailable');+});diff --git a/fluxer_api/src/api/stripe/tests/StripeCheckoutDistribution.test.ts b/fluxer_api/src/api/stripe/tests/StripeCheckoutDistribution.test.tsnew file mode 100644index 000000000..1c48e7103--- /dev/null+++ b/fluxer_api/src/api/stripe/tests/StripeCheckoutDistribution.test.ts@@ -0,0 +1,183 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {createUserID} from '@app/api/BrandedTypes';+import {Config} from '@app/api/Config';+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';+import {server} from '@app/api/test/msw/server';+import {HTTP_STATUS} from '@app/api/test/TestConstants';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {PaymentRepository} from '@app/api/user/repositories/PaymentRepository';+import type {PriceIdsResponse} from '@fluxer/schema/src/domains/premium/PremiumSchemas';+import {HttpResponse, http} from 'msw';+import {afterAll, beforeAll, beforeEach, expect, test} from 'vitest';++const STRIPE_API_BASE = 'https://api.stripe.com';+const MOCK_PRICES = {+ monthlyEur: 'price_dist_monthly_eur',+ yearlyEur: 'price_dist_yearly_eur',+ gift1MonthEur: 'price_dist_gift_1_month_eur',+ gift1YearEur: 'price_dist_gift_1_year_eur',+ monthlyUsd: 'price_dist_monthly_usd',+ yearlyUsd: 'price_dist_yearly_usd',+ gift1MonthUsd: 'price_dist_gift_1_month_usd',+ gift1YearUsd: 'price_dist_gift_1_year_usd',+};++let harness: ApiTestHarness;+let stripeHandlers: StripeApiHandlers;+let originalPrices: typeof Config.stripe.prices | undefined;+let createdPrices: Array<Record<string, string>>;++function priceHandlers() {+ return [+ http.get(`${STRIPE_API_BASE}/v1/prices`, () =>+ HttpResponse.json({object: 'list', data: [], has_more: false, url: '/v1/prices'}),+ ),+ http.post(`${STRIPE_API_BASE}/v1/prices`, async ({request}) => {+ const params = Object.fromEntries(new URLSearchParams(await request.text()));+ createdPrices.push(params);+ return HttpResponse.json({+ id: `price_channel_${createdPrices.length}`,+ object: 'price',+ currency: params['currency'],+ unit_amount: Number(params['unit_amount']),+ product: params['product'],+ });+ }),+ ];+}++beforeAll(async () => {+ originalPrices = Config.stripe.prices;+ harness = await createApiTestHarness();+});++afterAll(async () => {+ await harness.shutdown();+ Config.stripe.prices = originalPrices;+});++beforeEach(async () => {+ await harness.reset();+ Config.stripe.prices = MOCK_PRICES;+ createdPrices = [];+ stripeHandlers = createStripeApiHandlers({+ prices: {+ [MOCK_PRICES.monthlyEur]: {unit_amount: 499, currency: 'eur', interval: 'month'},+ [MOCK_PRICES.monthlyUsd]: {unit_amount: 499, currency: 'usd', interval: 'month'},+ },+ subscriptionsListEmpty: true,+ });+ server.use(...stripeHandlers.handlers, ...priceHandlers());+ await getInstanceConfigRepository().updateDistributionPricingConfig(() => ({+ rules: [+ {+ id: 'ios_marketplace',+ active: true,+ rate_bps: 500,+ products: ['plutonium_subscription', 'plutonium_gift'],+ rule_version: 1,+ prices: {},+ },+ ],+ }));+});++async function verifiedAccount() {+ const account = await createTestAccount(harness);+ await createBuilderWithoutAuth(harness)+ .post(`/test/users/${account.userId}/security-flags`)+ .body({email_verified: true})+ .expect(HTTP_STATUS.OK)+ .execute();+ return account;+}++async function checkout(token: string, body: Record<string, unknown>) {+ await createBuilder(harness, token)+ .post('/stripe/checkout/subscription')+ .body({price_id: MOCK_PRICES.monthlyUsd, ...body})+ .expect(HTTP_STATUS.OK)+ .execute();+ return stripeHandlers.spies.createdCheckoutSessions.at(-1) as unknown as {+ id?: string;+ metadata: Record<string, string>;+ line_items: Array<{price: string}>;+ subscription_data: {metadata: Record<string, string>};+ };+}++test('a marketplace checkout charges the channel price once and tags every record', async () => {+ const account = await verifiedAccount();+ const token = Buffer.from(JSON.stringify({externalPurchaseId: 'ext-42'})).toString('base64url');+ const session = await checkout(account.token, {distribution: 'ios_marketplace', distribution_token: token});++ expect(createdPrices).toHaveLength(1);+ expect(createdPrices[0]).toMatchObject({+ unit_amount: '526',+ currency: 'usd',+ 'recurring[interval]': 'month',+ lookup_key: `dist_ios_marketplace_1_500_${MOCK_PRICES.monthlyUsd}`,+ 'metadata[distribution]': 'ios_marketplace',+ });+ expect(session.line_items[0]?.price).toBe('price_channel_1');+ const expected = {+ distribution: 'ios_marketplace',+ distribution_rate_bps: '500',+ distribution_rule_version: '1',+ distribution_base_unit_amount: '499',+ distribution_unit_amount: '526',+ distribution_extra_unit_amount: '27',+ distribution_purchase_ref: 'ext-42',+ };+ expect(session.metadata).toMatchObject(expected);+ expect(session.subscription_data.metadata).toMatchObject(expected);++ const [payment] = await new PaymentRepository().findPaymentsByUserId(createUserID(BigInt(account.userId)));+ expect(payment).toMatchObject({+ priceId: 'price_channel_1',+ distribution: 'ios_marketplace',+ distributionRateBps: 500,+ distributionRuleVersion: 1,+ distributionBaseAmountMinor: 499,+ distributionPurchaseRef: 'ext-42',+ });++ const quote = await createBuilder<PriceIdsResponse>(harness, account.token)+ .get('/premium/price-ids?country_code=US&distribution=ios_marketplace')+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(quote.monthly).toBe('price_channel_1');+ expect(quote.monthly_amount_minor).toBe(526);+ expect(quote.distribution).toEqual({id: 'ios_marketplace', rate_bps: 500, rule_version: 1});++ const second = await verifiedAccount();+ const reused = await checkout(second.token, {price_id: 'price_channel_1', distribution: 'ios_marketplace'});+ expect(createdPrices).toHaveLength(1);+ expect(reused.line_items[0]?.price).toBe('price_channel_1');+});++test('an unknown distribution or a channel price without one pays the standard price', async () => {+ const account = await verifiedAccount();+ const unknown = await checkout(account.token, {distribution: 'not_a_channel'});+ expect(unknown.line_items[0]?.price).toBe(MOCK_PRICES.monthlyUsd);+ expect(unknown.metadata['distribution']).toBeUndefined();+ expect(createdPrices).toHaveLength(0);++ const quote = await createBuilder<PriceIdsResponse>(harness, account.token)+ .get('/premium/price-ids?country_code=US&distribution=NOT%20VALID')+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(quote.monthly_amount_minor).toBe(499);+ expect(quote.distribution).toBeNull();++ await checkout(account.token, {distribution: 'ios_marketplace'});+ expect(createdPrices).toHaveLength(1);+ const second = await verifiedAccount();+ const stripped = await checkout(second.token, {price_id: 'price_channel_1'});+ expect(stripped.line_items[0]?.price).toBe(MOCK_PRICES.monthlyUsd);+ expect(stripped.metadata['distribution']).toBeUndefined();+});diff --git a/fluxer_api/src/api/user/repositories/PaymentRepository.ts b/fluxer_api/src/api/user/repositories/PaymentRepository.tsindex e43206767..f783fdf24 100644--- a/fluxer_api/src/api/user/repositories/PaymentRepository.ts+++ b/fluxer_api/src/api/user/repositories/PaymentRepository.ts@@ -42,6 +42,11 @@ export class PaymentRepository {eu_withdrawal_waiver_accepted?: boolean;eu_withdrawal_waiver_accepted_at?: Date | null;eu_withdrawal_waiver_text_version?: string | null;+ distribution?: string | null;+ distribution_rate_bps?: number | null;+ distribution_rule_version?: number | null;+ distribution_base_amount_minor?: number | null;+ distribution_purchase_ref?: string | null;}): Promise<void> {const batch = new BatchBuilder();const paymentRow: PaymentRow = {@@ -65,6 +70,11 @@ export class PaymentRepository {eu_withdrawal_waiver_accepted: data.eu_withdrawal_waiver_accepted ?? false,eu_withdrawal_waiver_accepted_at: data.eu_withdrawal_waiver_accepted_at ?? null,eu_withdrawal_waiver_text_version: data.eu_withdrawal_waiver_text_version ?? null,+ distribution: data.distribution ?? null,+ distribution_rate_bps: data.distribution_rate_bps ?? null,+ distribution_rule_version: data.distribution_rule_version ?? null,+ distribution_base_amount_minor: data.distribution_base_amount_minor ?? null,+ distribution_purchase_ref: data.distribution_purchase_ref ?? null,completed_at: null,version: 1,};@@ -118,6 +128,13 @@ export class PaymentRepository {addField('eu_withdrawal_waiver_accepted');addField('eu_withdrawal_waiver_accepted_at');addField('eu_withdrawal_waiver_text_version');+ addField('distribution');+ addField('distribution_rate_bps');+ addField('distribution_rule_version');+ addField('distribution_base_amount_minor');+ addField('distribution_purchase_ref');+ addField('tax_amount_minor');+ addField('tax_country');addField('completed_at');return {pk: {checkout_session_id: checkoutSessionId},diff --git a/fluxer_docs/src/content/docs/admin-api/instance.mdx b/fluxer_docs/src/content/docs/admin-api/instance.mdxindex 5561eb5cd..f5f310353 100644--- a/fluxer_docs/src/content/docs/admin-api/instance.mdx+++ b/fluxer_docs/src/content/docs/admin-api/instance.mdx@@ -32,6 +32,7 @@ The full runtime configuration. A setting that was never saved uses the default| integrations | [instance integrations](#instance-integrations-object) object | Third-party provider settings || media | [instance media](#instance-media-object) object | Attachment retention settings || billing | [instance billing](#instance-billing-object) object | Premium billing settings |+| distribution_pricing | [distribution pricing](#distribution-pricing-object) object | Channel prices for app builds sold through a store || auth | [auth configuration](#auth-configuration-object) object | Email-first sign-in and instant accounts || accounts | [accounts configuration](#accounts-configuration-object) object | Date of birth step, account tiers and cleanup || guild_visits | [guild visits configuration](#guild-visits-configuration-object) object | Rollout of visiting communities before joining |@@ -496,6 +497,40 @@ The Stripe price IDs for one currency.| gift_1_month | ?string | Price ID of the one-month gift || gift_1_year | ?string | Price ID of the one-year gift |+## Distribution pricing object++The rules behind [distributions](/http-api/premium/#distributions). On fluxer.com it holds one rule for `ios_marketplace` until an admin saves it. Self-hosted instances start with none.++### Structure++| Field | Type | Description |+| --- | --- | --- |+| rules | array[[distribution rule](#distribution-rule-object) object] | Up to 32 rules with unique ids |++## Distribution rule object++### Structure++| Field | Type | Description |+| --- | --- | --- |+| id | string | Distribution id clients send (1-32 lowercase letters, digits or underscores) |+| active | boolean | Whether quotes and checkouts use the channel price |+| rate_bps | integer | The store's share in basis points (1-3000) |+| products | array[string] | `plutonium_subscription`, `plutonium_gift` or both |+| rule_version | integer | Starts at 1 and goes up when `rate_bps` changes |+| prices | map[string, [channel price](#distribution-channel-price-object) object] | Channel prices keyed by `<rule_version>:<standard price ID>`, added at first checkout and never removed |++## Distribution channel price object++### Structure++| Field | Type | Description |+| --- | --- | --- |+| price_id | string | The Stripe price ID charged |+| rate_bps | integer | The rate the price was made with |+| base_unit_amount | integer | The standard price amount, in minor units |+| unit_amount | integer | The channel price amount, in minor units |+## Instance media objectAttachment retention overrides and the values in use.@@ -658,6 +693,7 @@ Merges the body into the saved configuration and returns the [instance configura| media? | object | `attachment_decay` overrides, null to restore a default || policy? | [instance policy update](#instance-policy-update-structure) object | Community, direct message, premium and gating policy || billing?<sup>4</sup> | object | [Instance billing](#instance-billing-object) fields, plus `stripe_secret_key` and `stripe_webhook_secret` |+| distribution_pricing?<sup>6</sup> | object | `rules`, each with `id`, `active`, `rate_bps` and `products` from the [distribution rule](#distribution-rule-object) || auth? | object | `identifier_first` and any `instant_accounts` fields from the [auth configuration](#auth-configuration-object) || accounts? | object | Any [accounts configuration](#accounts-configuration-object) fields || guild_visits? | object | Any [guild visits configuration](#guild-visits-configuration-object) fields |@@ -673,6 +709,8 @@ Merges the body into the saved configuration and returns the [instance configura<sup>5</sup> `message` is up to 1000 characters, and null or an empty string removes the notice. A request replaces the whole notice+<sup>6</sup> `rules` replaces the saved list. Fluxer keeps `rule_version` and `prices` for ids it already has, and raises `rule_version` when `rate_bps` changes. A rule left out that already has channel prices stays saved with `active` false, so its subscriptions keep renewing+Fluxer checks the merged settings before it writes anything, and refuses these combinations with 400 `INVALID_FORM_BODY`.- `INSTANT_ACCOUNTS_REQUIRE_CAPTCHA` when instant accounts are turned on while the captcha provider is `none`diff --git a/fluxer_docs/src/content/docs/http-api/billing.mdx b/fluxer_docs/src/content/docs/http-api/billing.mdxindex 771e3ea40..a6cc85b0c 100644--- a/fluxer_docs/src/content/docs/http-api/billing.mdx+++ b/fluxer_docs/src/content/docs/http-api/billing.mdx@@ -75,11 +75,15 @@ If the account already has an `active` or `trialing` subscription and `price_id`| eu_withdrawal_waiver_accepted? | boolean | Whether the user accepted the EU withdrawal waiver for digital content || payment_method?<sup>2</sup> | string | Either `card`, `pix` or `upi` (default `card`) || is_business? | boolean | Whether to require a billing address for tax invoicing (default false) |+| distribution?<sup>3</sup> | string | [Distribution](/http-api/premium/#distributions) the app build was sold through, such as `ios_marketplace` (up to 64 characters) |+| distribution_token? | string | Purchase token from that distribution, kept for reporting (up to 4096 characters) |<sup>1</sup> Fluxer uses this only when it can't find the request's country. With prices set in environment config, a price in a currency other than USD or EUR needs it.<sup>2</sup> With prices set in environment config, `pix` needs a BRL price and `upi` needs an INR price. Prices saved in the instance billing settings accept only `card`.+<sup>3</sup> With an active rule for the distribution, checkout charges its channel price, and `price_id` can be the standard price or the channel price from [get price IDs](/http-api/premium/#get-price-ids). Any other value pays the standard price.+### Response| Status | Body | Condition |@@ -120,9 +124,13 @@ Creates a one-time premium gift checkout session and returns a [redirect URL](#r| eu_withdrawal_waiver_accepted? | boolean | Whether the user accepted the EU withdrawal waiver for digital content || is_business? | boolean | Whether to require a billing address for tax invoicing (default false) || payment_method? | string | Ignored by this route (`card`, `pix` or `upi`) |+| distribution?<sup>2</sup> | string | [Distribution](/http-api/premium/#distributions) the app build was sold through, such as `ios_marketplace` (up to 64 characters) |+| distribution_token? | string | Purchase token from that distribution, kept for reporting (up to 4096 characters) |<sup>1</sup> Fluxer uses this only when it can't find the request's country. With prices set in environment config, a price in a currency other than USD or EUR needs it.+<sup>2</sup> With an active rule for the distribution, checkout charges its channel price, and `price_id` can be the standard price or the channel price from [get price IDs](/http-api/premium/#get-price-ids). Any other value pays the standard price.+### Response| Status | Body | Condition |diff --git a/fluxer_docs/src/content/docs/http-api/premium.mdx b/fluxer_docs/src/content/docs/http-api/premium.mdxindex a731d4544..dac74452d 100644--- a/fluxer_docs/src/content/docs/http-api/premium.mdx+++ b/fluxer_docs/src/content/docs/http-api/premium.mdx@@ -47,9 +47,24 @@ The recurring and gift checkout prices for one country.| gift_1_year_amount_minor? | ?integer | The one-year gift amount, in the minor unit of `gift_currency` || currency | string | [Display currency](#display-currencies) of the recurring prices || gift_currency<sup>1</sup> | ?string | [Display currency](#display-currencies) of the gift prices |+| distribution | ?[price distribution](#price-distribution-object) object | The distribution whose channel prices these are, or null for the standard prices |<sup>1</sup> Null when no currency has both gift prices set up, and gift checkout is unavailable then.+## Distributions++An app build sold through a store that keeps a share of each sale sends its distribution id, such as `ios_marketplace`, with [get price IDs](#get-price-ids), [get premium state](#get-premium-state) and the [checkout routes](/http-api/billing/#create-subscription-checkout). When the instance has an active rule for that id, the amounts and checkout use its channel price. The channel price is the standard price divided by one minus the rule's rate, rounded up to an amount Stripe accepts in that currency, so the amount left after the store's share is at least the standard price. An unknown, malformed or inactive id gets the standard price and never an error. Self-hosted instances have no rules until an admin adds one.++## Price distribution object++### Structure++| Field | Type | Description |+| --- | --- | --- |+| id | string | The distribution id |+| rate_bps | integer | The store's share in basis points, where 500 is 5% |+| rule_version | integer | The version of the rule the prices come from |+## Current subscription price objectThe price the account is billed against, and the current list price for the same billing cycle and currency.@@ -237,6 +252,7 @@ Returns the [price IDs](#price-ids-object) object for the request's country.| Field | Type | Description || --- | --- | --- || country_code? | string | A two-letter country code, used when Fluxer can't locate the request |+| distribution? | string | The [distribution](#distributions) the app build was sold through (up to 64 characters) |### Response@@ -258,6 +274,7 @@ Returns the [premium state](#premium-state-object) object for the current accoun| Field | Type | Description || --- | --- | --- || country_code? | string | A two-letter country code for `pricing`, used when Fluxer can't locate the request |+| distribution? | string | The [distribution](#distributions) for `pricing` (up to 64 characters) |### Responsediff --git a/packages/schema/src/domains/admin/AdminSchemas.ts b/packages/schema/src/domains/admin/AdminSchemas.tsindex b0a9f271f..777f0aa0c 100644--- a/packages/schema/src/domains/admin/AdminSchemas.ts+++ b/packages/schema/src/domains/admin/AdminSchemas.ts@@ -47,6 +47,10 @@ import {InstanceBillingResponse,InstanceBillingUpdateRequest,} from '@fluxer/schema/src/domains/admin/InstanceBillingSchemas';+import {+ DistributionPricingConfigResponse,+ DistributionPricingUpdateRequest,+} from '@fluxer/schema/src/domains/admin/InstanceDistributionPricingSchemas';import {PushRelayConfigResponse, PushRelayConfigUpdateRequest} from '@fluxer/schema/src/domains/admin/PushRelaySchemas';import {VoiceP2pConfigResponse, VoiceP2pConfigUpdateRequest} from '@fluxer/schema/src/domains/admin/VoiceP2pSchemas';import {@@ -839,6 +843,7 @@ export const InstanceConfigResponse = z.object({integrations: InstanceIntegrationsResponse,media: InstanceMediaResponse,billing: InstanceBillingResponse,+ distribution_pricing: DistributionPricingConfigResponse,notice: InstanceNoticeSchema.nullable().describe('Notice shown to everyone on the instance, or null'),warnings: z.array(z.string())@@ -1014,6 +1019,7 @@ export const InstanceConfigUpdateRequest = z.object({.nullish(),policy: InstancePolicyUpdateSchema.nullish(),billing: InstanceBillingUpdateRequest.nullish(),+ distribution_pricing: DistributionPricingUpdateRequest.nullish(),notice: z.object({message: zdiff --git a/packages/schema/src/domains/admin/InstanceDistributionPricingSchemas.ts b/packages/schema/src/domains/admin/InstanceDistributionPricingSchemas.tsnew file mode 100644index 000000000..ace536ec3--- /dev/null+++ b/packages/schema/src/domains/admin/InstanceDistributionPricingSchemas.ts@@ -0,0 +1,105 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ DISTRIBUTION_ID_PATTERN,+ DISTRIBUTION_RATE_BPS_MAX,+} from '@fluxer/schema/src/domains/premium/DistributionSchemas';+import {z} from 'zod';++const DISTRIBUTION_RULES_MAX = 32;+const DISTRIBUTION_PRICE_KEY_PATTERN = /^[1-9]\d{0,8}:[A-Za-z0-9_]{1,255}$/;++export const DistributionProductSchema = z.enum(['plutonium_subscription', 'plutonium_gift']);++export type DistributionProduct = z.infer<typeof DistributionProductSchema>;++const DistributionIdSchema = z+ .string()+ .regex(DISTRIBUTION_ID_PATTERN)+ .describe('Distribution id sent by clients built for that distribution, for example ios_marketplace');++const distributionRuleFields = {+ id: DistributionIdSchema,+ active: z.boolean().describe('Whether checkouts and quotes for this distribution use the channel price'),+ rate_bps: z+ .number()+ .int()+ .min(1)+ .max(DISTRIBUTION_RATE_BPS_MAX)+ .describe('Share of the channel price that goes to the distribution, in basis points. 500 means 5%'),+ products: z+ .array(DistributionProductSchema)+ .min(1)+ .max(DistributionProductSchema.options.length)+ .refine((products) => new Set(products).size === products.length, 'Products must be unique')+ .describe('Products that get the channel price'),+};++export const DistributionChannelPriceSchema = z.object({+ price_id: z.string().min(1).max(255).describe('Stripe price ID charged through the distribution'),+ rate_bps: distributionRuleFields.rate_bps,+ base_unit_amount: z.number().int().min(0).describe('Unit amount of the base price, in minor units'),+ unit_amount: z.number().int().min(0).describe('Unit amount of the channel price, in minor units'),+});++export type DistributionChannelPrice = z.infer<typeof DistributionChannelPriceSchema>;++export const DistributionRuleSchema = z.object({+ ...distributionRuleFields,+ rule_version: z+ .number()+ .int()+ .min(1)+ .describe('Bumped by the server whenever rate_bps changes. Prices made under a version keep it'),+ prices: z+ .record(z.string().regex(DISTRIBUTION_PRICE_KEY_PATTERN), DistributionChannelPriceSchema)+ .default({})+ .describe(+ 'Channel Stripe prices keyed by "<rule_version>:<base price ID>". Managed by the server and never removed',+ ),+});++export type DistributionRule = z.infer<typeof DistributionRuleSchema>;++function uniqueRuleIds(rules: ReadonlyArray<{id: string}>): boolean {+ return new Set(rules.map((rule) => rule.id)).size === rules.length;+}++export const DistributionPricingConfigSchema = z.object({+ rules: z+ .array(DistributionRuleSchema)+ .max(DISTRIBUTION_RULES_MAX)+ .refine(uniqueRuleIds, 'Distribution ids must be unique')+ .default([]),+});++export type DistributionPricingConfig = z.infer<typeof DistributionPricingConfigSchema>;++export const DEFAULT_HOSTED_DISTRIBUTION_PRICING_CONFIG: DistributionPricingConfig = {+ rules: [+ {+ id: 'ios_marketplace',+ active: true,+ rate_bps: 500,+ products: ['plutonium_subscription', 'plutonium_gift'],+ rule_version: 1,+ prices: {},+ },+ ],+};++export const DistributionPricingConfigResponse = DistributionPricingConfigSchema;++export type DistributionPricingConfigResponse = z.infer<typeof DistributionPricingConfigResponse>;++export const DistributionPricingUpdateRequest = z.object({+ rules: z+ .array(z.object(distributionRuleFields))+ .max(DISTRIBUTION_RULES_MAX)+ .refine(uniqueRuleIds, 'Distribution ids must be unique')+ .describe(+ 'Full list of distribution rules. A left-out rule that already has channel prices stays stored as inactive so its subscriptions keep renewing',+ ),+});++export type DistributionPricingUpdateRequest = z.infer<typeof DistributionPricingUpdateRequest>;diff --git a/packages/schema/src/domains/premium/DistributionSchemas.ts b/packages/schema/src/domains/premium/DistributionSchemas.tsnew file mode 100644index 000000000..6c7fcdbb5--- /dev/null+++ b/packages/schema/src/domains/premium/DistributionSchemas.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {z} from 'zod';++export const DISTRIBUTION_ID_PATTERN = /^[a-z0-9_]{1,32}$/;+export const DISTRIBUTION_RATE_BPS_MAX = 3000;++export const DistributionQueryParam = z+ .string()+ .max(64)+ .optional()+ .describe(+ 'Distribution the client build was sold through. Unknown or inactive values fall back to the standard price',+ );++export const DistributionTokenParam = z+ .string()+ .max(4096)+ .optional()+ .describe('Opaque purchase token from the distribution, kept for reporting');++export const PriceDistributionResponse = z.object({+ id: z.string().regex(DISTRIBUTION_ID_PATTERN),+ rate_bps: z.number().int().min(1).max(DISTRIBUTION_RATE_BPS_MAX),+ rule_version: z.number().int().min(1),+});++export type PriceDistributionResponse = z.infer<typeof PriceDistributionResponse>;diff --git a/packages/schema/src/domains/premium/GiftCodeSchemas.ts b/packages/schema/src/domains/premium/GiftCodeSchemas.tsindex 26bb55020..0d3f3db73 100644--- a/packages/schema/src/domains/premium/GiftCodeSchemas.ts+++ b/packages/schema/src/domains/premium/GiftCodeSchemas.ts@@ -2,6 +2,7 @@import {GIFT_CODE_DURATION_TYPE_DEFINITIONS} from '@fluxer/constants/src/GiftCodeConstants';import {CnpjSchema} from '@fluxer/schema/src/domains/premium/Cnpj';+import {DistributionQueryParam, DistributionTokenParam} from '@fluxer/schema/src/domains/premium/DistributionSchemas';import {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';import {createNamedStringLiteralUnion, createStringType} from '@fluxer/schema/src/primitives/SchemaPrimitives';import {z} from 'zod';@@ -34,6 +35,8 @@ export const CreateCheckoutSessionRequest = z.object({'Whether the purchase is for a business. When true, Stripe Checkout requires a billing address for the invoice. When false or omitted, billing address collection is left to Stripe (auto).',),cnpj: CnpjSchema.optional(),+ distribution: DistributionQueryParam,+ distribution_token: DistributionTokenParam,});export type CreateCheckoutSessionRequest = z.infer<typeof CreateCheckoutSessionRequest>;diff --git a/packages/schema/src/domains/premium/PremiumSchemas.ts b/packages/schema/src/domains/premium/PremiumSchemas.tsindex 5835b68e6..17dd07f08 100644--- a/packages/schema/src/domains/premium/PremiumSchemas.ts+++ b/packages/schema/src/domains/premium/PremiumSchemas.ts@@ -1,6 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {BillingDocumentResponse} from '@fluxer/schema/src/domains/billing_documents/BillingDocumentSchemas';+import {+ DistributionQueryParam,+ PriceDistributionResponse,+} from '@fluxer/schema/src/domains/premium/DistributionSchemas';import {PremiumStoreSubscriptionState} from '@fluxer/schema/src/domains/premium/StoreBillingSchemas';import {createStringType, withOpenApiType} from '@fluxer/schema/src/primitives/SchemaPrimitives';import {UserPremiumTypesSchema} from '@fluxer/schema/src/primitives/UserSettingsValidators';@@ -41,6 +45,9 @@ export const PriceIdsResponse = z.object({gift_currency: PremiumCurrency.nullable().describe('Currency for gift prices, null when no gift prices are configured',),+ distribution: PriceDistributionResponse.nullable().describe(+ 'Distribution whose channel price the amounts include, or null for the standard price',+ ),});export type PriceIdsResponse = z.infer<typeof PriceIdsResponse>;@@ -51,6 +58,7 @@ export const PriceIdsQueryRequest = z.object({.describe('Two-letter country code for regional pricing. Only used when the server cannot geolocate the request; otherwise the request GeoIP country wins.',),+ distribution: DistributionQueryParam,});export type PriceIdsQueryRequest = z.infer<typeof PriceIdsQueryRequest>;diff --git a/tools/dev/cassandra_target_schema.json b/tools/dev/cassandra_target_schema.jsonindex 22efbec7f..9f2459c2b 100644--- a/tools/dev/cassandra_target_schema.json+++ b/tools/dev/cassandra_target_schema.json@@ -8679,6 +8679,34 @@{"name": "eu_withdrawal_waiver_text_version","type": "text"+ },+ {+ "name": "distribution",+ "type": "text"+ },+ {+ "name": "distribution_rate_bps",+ "type": "int"+ },+ {+ "name": "distribution_rule_version",+ "type": "int"+ },+ {+ "name": "distribution_base_amount_minor",+ "type": "int"+ },+ {+ "name": "distribution_purchase_ref",+ "type": "text"+ },+ {+ "name": "tax_amount_minor",+ "type": "int"+ },+ {+ "name": "tax_country",+ "type": "text"}],"primary_key": "((checkout_session_id))",