feat: add payment gateway and billing plans

This commit is contained in:
Entropy.Xu
2026-05-13 01:18:38 +08:00
parent 0fa97595bf
commit 10285c5eb9
97 changed files with 14797 additions and 404 deletions
@@ -4,7 +4,9 @@ use sqlx::{PgPool, Row};
use super::{
AdminBillingCollectorRecord, AdminBillingCollectorWriteInput, AdminBillingMutationOutcome,
AdminBillingPresetApplyResult, AdminBillingRuleRecord, AdminBillingRuleWriteInput,
BillingReadRepository, StoredBillingModelContext,
BillingPlanRecord, BillingPlanWriteInput, BillingReadRepository, PaymentGatewayConfigRecord,
PaymentGatewayConfigWriteInput, StoredBillingModelContext, UserDailyQuotaAvailabilityRecord,
UserPlanEntitlementRecord,
};
use crate::{error::SqlxResultExt, DataLayerError};
@@ -687,8 +689,422 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW(), NOW())
},
))
}
async fn find_payment_gateway_config(
&self,
provider: &str,
) -> Result<Option<PaymentGatewayConfigRecord>, DataLayerError> {
let row = sqlx::query(
r#"
SELECT
provider, enabled, endpoint_url, callback_base_url, merchant_id,
merchant_key_encrypted, pay_currency,
CAST(usd_exchange_rate AS DOUBLE PRECISION) AS usd_exchange_rate,
CAST(min_recharge_usd AS DOUBLE PRECISION) AS min_recharge_usd,
channels_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
FROM payment_gateway_configs
WHERE provider = $1
LIMIT 1
"#,
)
.bind(provider.trim().to_ascii_lowercase())
.fetch_optional(&self.pool)
.await
.map_postgres_err()?;
row.as_ref().map(map_payment_gateway_config_row).transpose()
}
async fn upsert_payment_gateway_config(
&self,
input: &PaymentGatewayConfigWriteInput,
) -> Result<AdminBillingMutationOutcome<PaymentGatewayConfigRecord>, DataLayerError> {
let provider = input.provider.trim().to_ascii_lowercase();
let row = sqlx::query(
r#"
INSERT INTO payment_gateway_configs (
provider, enabled, endpoint_url, callback_base_url, merchant_id,
merchant_key_encrypted, pay_currency, usd_exchange_rate, min_recharge_usd,
channels_json, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW())
ON CONFLICT (provider)
DO UPDATE SET
enabled = EXCLUDED.enabled,
endpoint_url = EXCLUDED.endpoint_url,
callback_base_url = EXCLUDED.callback_base_url,
merchant_id = EXCLUDED.merchant_id,
merchant_key_encrypted = CASE
WHEN $11::BOOL THEN payment_gateway_configs.merchant_key_encrypted
ELSE EXCLUDED.merchant_key_encrypted
END,
pay_currency = EXCLUDED.pay_currency,
usd_exchange_rate = EXCLUDED.usd_exchange_rate,
min_recharge_usd = EXCLUDED.min_recharge_usd,
channels_json = EXCLUDED.channels_json,
updated_at = NOW()
RETURNING
provider, enabled, endpoint_url, callback_base_url, merchant_id,
merchant_key_encrypted, pay_currency,
CAST(usd_exchange_rate AS DOUBLE PRECISION) AS usd_exchange_rate,
CAST(min_recharge_usd AS DOUBLE PRECISION) AS min_recharge_usd,
channels_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
"#,
)
.bind(&provider)
.bind(input.enabled)
.bind(&input.endpoint_url)
.bind(input.callback_base_url.as_deref())
.bind(&input.merchant_id)
.bind(input.merchant_key_encrypted.as_deref())
.bind(&input.pay_currency)
.bind(input.usd_exchange_rate)
.bind(input.min_recharge_usd)
.bind(&input.channels_json)
.bind(input.preserve_existing_secret)
.fetch_one(&self.pool)
.await
.map_postgres_err()?;
Ok(AdminBillingMutationOutcome::Applied(
map_payment_gateway_config_row(&row)?,
))
}
async fn list_billing_plans(
&self,
include_disabled: bool,
) -> Result<Option<Vec<BillingPlanRecord>>, DataLayerError> {
let rows = sqlx::query(
r#"
SELECT
id, title, description,
CAST(price_amount AS DOUBLE PRECISION) AS price_amount,
price_currency, duration_unit, duration_value, enabled, sort_order,
max_active_per_user, purchase_limit_scope, entitlements_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
FROM billing_plans
WHERE ($1::BOOL = TRUE OR enabled = TRUE)
ORDER BY sort_order ASC, price_amount ASC, id ASC
"#,
)
.bind(include_disabled)
.fetch_all(&self.pool)
.await
.map_postgres_err()?;
Ok(Some(
rows.iter()
.map(map_billing_plan_row)
.collect::<Result<Vec<_>, _>>()?,
))
}
async fn find_billing_plan(
&self,
plan_id: &str,
) -> Result<Option<BillingPlanRecord>, DataLayerError> {
let row = sqlx::query(
r#"
SELECT
id, title, description,
CAST(price_amount AS DOUBLE PRECISION) AS price_amount,
price_currency, duration_unit, duration_value, enabled, sort_order,
max_active_per_user, purchase_limit_scope, entitlements_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
FROM billing_plans
WHERE id = $1
LIMIT 1
"#,
)
.bind(plan_id)
.fetch_optional(&self.pool)
.await
.map_postgres_err()?;
row.as_ref().map(map_billing_plan_row).transpose()
}
async fn create_billing_plan(
&self,
input: &BillingPlanWriteInput,
) -> Result<AdminBillingMutationOutcome<BillingPlanRecord>, DataLayerError> {
let id = uuid::Uuid::new_v4().to_string();
let row = sqlx::query(BILLING_PLAN_INSERT_RETURNING_SQL)
.bind(&id)
.bind(&input.title)
.bind(input.description.as_deref())
.bind(input.price_amount)
.bind(&input.price_currency)
.bind(&input.duration_unit)
.bind(input.duration_value)
.bind(input.enabled)
.bind(input.sort_order)
.bind(input.max_active_per_user)
.bind(&input.purchase_limit_scope)
.bind(&input.entitlements_json)
.fetch_one(&self.pool)
.await
.map_postgres_err()?;
Ok(AdminBillingMutationOutcome::Applied(map_billing_plan_row(
&row,
)?))
}
async fn update_billing_plan(
&self,
plan_id: &str,
input: &BillingPlanWriteInput,
) -> Result<AdminBillingMutationOutcome<BillingPlanRecord>, DataLayerError> {
let row = sqlx::query(BILLING_PLAN_UPDATE_RETURNING_SQL)
.bind(plan_id)
.bind(&input.title)
.bind(input.description.as_deref())
.bind(input.price_amount)
.bind(&input.price_currency)
.bind(&input.duration_unit)
.bind(input.duration_value)
.bind(input.enabled)
.bind(input.sort_order)
.bind(input.max_active_per_user)
.bind(&input.purchase_limit_scope)
.bind(&input.entitlements_json)
.fetch_optional(&self.pool)
.await
.map_postgres_err()?;
match row {
Some(row) => Ok(AdminBillingMutationOutcome::Applied(map_billing_plan_row(
&row,
)?)),
None => Ok(AdminBillingMutationOutcome::NotFound),
}
}
async fn set_billing_plan_enabled(
&self,
plan_id: &str,
enabled: bool,
) -> Result<AdminBillingMutationOutcome<BillingPlanRecord>, DataLayerError> {
let row = sqlx::query(
r#"
UPDATE billing_plans
SET enabled = $2, updated_at = NOW()
WHERE id = $1
RETURNING
id, title, description,
CAST(price_amount AS DOUBLE PRECISION) AS price_amount,
price_currency, duration_unit, duration_value, enabled, sort_order,
max_active_per_user, purchase_limit_scope, entitlements_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
"#,
)
.bind(plan_id)
.bind(enabled)
.fetch_optional(&self.pool)
.await
.map_postgres_err()?;
match row {
Some(row) => Ok(AdminBillingMutationOutcome::Applied(map_billing_plan_row(
&row,
)?)),
None => Ok(AdminBillingMutationOutcome::NotFound),
}
}
async fn delete_billing_plan(
&self,
plan_id: &str,
) -> Result<AdminBillingMutationOutcome<()>, DataLayerError> {
let exists = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*)::bigint FROM billing_plans WHERE id = $1",
)
.bind(plan_id)
.fetch_one(&self.pool)
.await
.map_postgres_err()?;
if exists == 0 {
return Ok(AdminBillingMutationOutcome::NotFound);
}
let order_count = sqlx::query_scalar::<_, i64>(
r#"
SELECT COUNT(*)::bigint
FROM payment_orders
WHERE product_id = $1
AND order_kind = 'plan_purchase'
"#,
)
.bind(plan_id)
.fetch_one(&self.pool)
.await
.map_postgres_err()?;
let entitlement_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*)::bigint FROM user_plan_entitlements WHERE plan_id = $1",
)
.bind(plan_id)
.fetch_one(&self.pool)
.await
.map_postgres_err()?;
if order_count > 0 || entitlement_count > 0 {
return Ok(AdminBillingMutationOutcome::Invalid(
"套餐已有订单或权益,不能删除,请停用该套餐".to_string(),
));
}
let result = sqlx::query("DELETE FROM billing_plans WHERE id = $1")
.bind(plan_id)
.execute(&self.pool)
.await
.map_postgres_err()?;
if result.rows_affected() == 0 {
Ok(AdminBillingMutationOutcome::NotFound)
} else {
Ok(AdminBillingMutationOutcome::Applied(()))
}
}
async fn list_user_plan_entitlements(
&self,
user_id: &str,
) -> Result<Option<Vec<UserPlanEntitlementRecord>>, DataLayerError> {
let rows = sqlx::query(
r#"
SELECT
id, user_id, plan_id, payment_order_id, status,
CAST(EXTRACT(EPOCH FROM starts_at) AS BIGINT) AS starts_at_unix_secs,
CAST(EXTRACT(EPOCH FROM expires_at) AS BIGINT) AS expires_at_unix_secs,
entitlements_snapshot,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
FROM user_plan_entitlements
WHERE user_id = $1
AND status = 'active'
AND expires_at > NOW()
ORDER BY expires_at ASC, created_at ASC
"#,
)
.bind(user_id)
.fetch_all(&self.pool)
.await
.map_postgres_err()?;
Ok(Some(
rows.iter()
.map(map_user_plan_entitlement_row)
.collect::<Result<Vec<_>, _>>()?,
))
}
async fn find_user_daily_quota_availability(
&self,
user_id: &str,
) -> Result<Option<UserDailyQuotaAvailabilityRecord>, DataLayerError> {
let rows = sqlx::query(
r#"
SELECT id, entitlements_snapshot
FROM user_plan_entitlements
WHERE user_id = $1
AND status = 'active'
AND starts_at <= NOW()
AND expires_at > NOW()
ORDER BY expires_at ASC, created_at ASC, id ASC
"#,
)
.bind(user_id)
.fetch_all(&self.pool)
.await
.map_postgres_err()?;
let now = chrono::Utc::now();
let mut grants = Vec::new();
for row in rows {
let entitlement_id: String = row.try_get("id").map_postgres_err()?;
let entitlements: serde_json::Value =
row.try_get("entitlements_snapshot").map_postgres_err()?;
grants.extend(daily_quota_grants_from_entitlement(
&entitlement_id,
&entitlements,
now,
)?);
}
let mut total_quota_usd = 0.0;
let mut used_usd = 0.0;
let mut remaining_usd = 0.0;
let mut allow_wallet_overage = true;
for grant in &grants {
allow_wallet_overage &= grant.allow_wallet_overage;
let used = sqlx::query_scalar::<_, Option<f64>>(
r#"
SELECT CAST(COALESCE(SUM(amount_usd), 0) AS DOUBLE PRECISION)
FROM entitlement_usage_ledgers
WHERE user_entitlement_id = $1
AND usage_date = $2
"#,
)
.bind(&grant.entitlement_id)
.bind(&grant.usage_date)
.fetch_one(&self.pool)
.await
.map_postgres_err()?
.unwrap_or(0.0);
total_quota_usd += grant.daily_quota_usd;
used_usd += used.min(grant.daily_quota_usd).max(0.0);
remaining_usd += (grant.daily_quota_usd - used).max(0.0);
}
let has_active_daily_quota = !grants.is_empty();
Ok(Some(UserDailyQuotaAvailabilityRecord {
has_active_daily_quota,
total_quota_usd,
used_usd,
remaining_usd,
allow_wallet_overage: has_active_daily_quota && allow_wallet_overage,
}))
}
}
const BILLING_PLAN_INSERT_RETURNING_SQL: &str = r#"
INSERT INTO billing_plans (
id, title, description, price_amount, price_currency, duration_unit,
duration_value, enabled, sort_order, max_active_per_user, purchase_limit_scope,
entitlements_json, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NOW(), NOW())
RETURNING
id, title, description,
CAST(price_amount AS DOUBLE PRECISION) AS price_amount,
price_currency, duration_unit, duration_value, enabled, sort_order,
max_active_per_user, purchase_limit_scope, entitlements_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
"#;
const BILLING_PLAN_UPDATE_RETURNING_SQL: &str = r#"
UPDATE billing_plans
SET
title = $2,
description = $3,
price_amount = $4,
price_currency = $5,
duration_unit = $6,
duration_value = $7,
enabled = $8,
sort_order = $9,
max_active_per_user = $10,
purchase_limit_scope = $11,
entitlements_json = $12,
updated_at = NOW()
WHERE id = $1
RETURNING
id, title, description,
CAST(price_amount AS DOUBLE PRECISION) AS price_amount,
price_currency, duration_unit, duration_value, enabled, sort_order,
max_active_per_user, purchase_limit_scope, entitlements_json,
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs
"#;
fn map_row(row: &sqlx::postgres::PgRow) -> Result<StoredBillingModelContext, DataLayerError> {
StoredBillingModelContext::new(
row.try_get("provider_id").map_postgres_err()?,
@@ -718,6 +1134,146 @@ fn read_count(row: sqlx::postgres::PgRow) -> Result<u64, DataLayerError> {
Ok(row.try_get::<i64, _>("total").map_postgres_err()?.max(0) as u64)
}
#[derive(Debug)]
struct DailyQuotaGrant {
entitlement_id: String,
daily_quota_usd: f64,
usage_date: String,
allow_wallet_overage: bool,
}
fn daily_quota_usage_date(
reset_timezone: Option<&str>,
now: chrono::DateTime<chrono::Utc>,
) -> Result<String, DataLayerError> {
let timezone = reset_timezone
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("Asia/Shanghai")
.parse::<chrono_tz::Tz>()
.map_err(|err| DataLayerError::InvalidInput(format!("invalid reset_timezone: {err}")))?;
Ok(now.with_timezone(&timezone).date_naive().to_string())
}
fn daily_quota_grants_from_entitlement(
entitlement_id: &str,
entitlements: &serde_json::Value,
now: chrono::DateTime<chrono::Utc>,
) -> Result<Vec<DailyQuotaGrant>, DataLayerError> {
let mut grants = Vec::new();
let Some(items) = entitlements.as_array() else {
return Ok(grants);
};
for item in items {
if item.get("type").and_then(serde_json::Value::as_str) != Some("daily_quota") {
continue;
}
let daily_quota_usd = item
.get("daily_quota_usd")
.and_then(serde_json::Value::as_f64)
.unwrap_or(0.0);
if !daily_quota_usd.is_finite() || daily_quota_usd <= 0.0 {
continue;
}
grants.push(DailyQuotaGrant {
entitlement_id: entitlement_id.to_string(),
daily_quota_usd,
usage_date: daily_quota_usage_date(
item.get("reset_timezone")
.and_then(serde_json::Value::as_str),
now,
)?,
allow_wallet_overage: item
.get("allow_wallet_overage")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false),
});
}
Ok(grants)
}
fn map_payment_gateway_config_row(
row: &sqlx::postgres::PgRow,
) -> Result<PaymentGatewayConfigRecord, DataLayerError> {
Ok(PaymentGatewayConfigRecord {
provider: row.try_get("provider").map_postgres_err()?,
enabled: row.try_get("enabled").map_postgres_err()?,
endpoint_url: row.try_get("endpoint_url").map_postgres_err()?,
callback_base_url: row.try_get("callback_base_url").map_postgres_err()?,
merchant_id: row.try_get("merchant_id").map_postgres_err()?,
merchant_key_encrypted: row.try_get("merchant_key_encrypted").map_postgres_err()?,
pay_currency: row.try_get("pay_currency").map_postgres_err()?,
usd_exchange_rate: row.try_get("usd_exchange_rate").map_postgres_err()?,
min_recharge_usd: row.try_get("min_recharge_usd").map_postgres_err()?,
channels_json: row
.try_get::<Option<serde_json::Value>, _>("channels_json")
.map_postgres_err()?
.unwrap_or_else(|| serde_json::json!([])),
created_at_unix_secs: row
.try_get::<i64, _>("created_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
updated_at_unix_secs: row
.try_get::<i64, _>("updated_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
})
}
fn map_billing_plan_row(row: &sqlx::postgres::PgRow) -> Result<BillingPlanRecord, DataLayerError> {
Ok(BillingPlanRecord {
id: row.try_get("id").map_postgres_err()?,
title: row.try_get("title").map_postgres_err()?,
description: row.try_get("description").map_postgres_err()?,
price_amount: row.try_get("price_amount").map_postgres_err()?,
price_currency: row.try_get("price_currency").map_postgres_err()?,
duration_unit: row.try_get("duration_unit").map_postgres_err()?,
duration_value: row.try_get("duration_value").map_postgres_err()?,
enabled: row.try_get("enabled").map_postgres_err()?,
sort_order: row.try_get("sort_order").map_postgres_err()?,
max_active_per_user: row.try_get("max_active_per_user").map_postgres_err()?,
purchase_limit_scope: row.try_get("purchase_limit_scope").map_postgres_err()?,
entitlements_json: row.try_get("entitlements_json").map_postgres_err()?,
created_at_unix_secs: row
.try_get::<i64, _>("created_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
updated_at_unix_secs: row
.try_get::<i64, _>("updated_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
})
}
fn map_user_plan_entitlement_row(
row: &sqlx::postgres::PgRow,
) -> Result<UserPlanEntitlementRecord, DataLayerError> {
Ok(UserPlanEntitlementRecord {
id: row.try_get("id").map_postgres_err()?,
user_id: row.try_get("user_id").map_postgres_err()?,
plan_id: row.try_get("plan_id").map_postgres_err()?,
payment_order_id: row.try_get("payment_order_id").map_postgres_err()?,
status: row.try_get("status").map_postgres_err()?,
starts_at_unix_secs: row
.try_get::<i64, _>("starts_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
expires_at_unix_secs: row
.try_get::<i64, _>("expires_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
entitlements_snapshot: row.try_get("entitlements_snapshot").map_postgres_err()?,
created_at_unix_secs: row
.try_get::<i64, _>("created_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
updated_at_unix_secs: row
.try_get::<i64, _>("updated_at_unix_secs")
.map_postgres_err()?
.max(0) as u64,
})
}
fn map_admin_billing_rule_row(
row: &sqlx::postgres::PgRow,
) -> Result<AdminBillingRuleRecord, DataLayerError> {