feat(api): add customer accounts with live summary and append-only ledger

One balance row per (user, kind, currency): available and frozen carry the
platform base currency, points carries none. Monetary and points rows use
separate partial unique indexes because a plain UNIQUE lets NULL repeat.

Balance changes go through transactional primitives that debits guard with a
conditional update, credits add atomically, and freeze/release move both sides
in one transaction after locking rows by primary key. Every change appends an
immutable entry holding its resulting balance. Registration and a migration
backfill create the zero rows; GET /api/me/stats is the only public surface and
no endpoint mutates a balance.

The mall buyer center and points page drop the USER_STATS fixture for the
shared contract; the fixture stays exported so the fixed-data adapter can still
serve the account domain as a rollback path.

Implements openspec change add-customer-accounts.
This commit is contained in:
2026-09-18 11:54:53 +00:00
parent bcd97ab48f
commit 7a2745fb16
19 changed files with 818 additions and 21 deletions
+44
View File
@@ -242,6 +242,50 @@ pub struct Invoice {
pub created_at: DateTime<Utc>,
}
/// Balance bucket. `available`/`frozen` are monetary and carry a currency;
/// `points` is an integer loyalty balance with no currency.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[sqlx(type_name = "customer_account_kind", rename_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum AccountKind {
Available,
Frozen,
Points,
}
impl AccountKind {
pub fn is_monetary(self) -> bool {
!matches!(self, AccountKind::Points)
}
}
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct CustomerAccount {
pub id: Uuid,
pub user_id: Uuid,
pub kind: AccountKind,
pub currency: Option<String>,
pub balance_minor: i64,
}
pub const CUSTOMER_ACCOUNT_COLUMNS: &str = "id, user_id, kind, currency, balance_minor";
/// One immutable balance movement. Written in the same transaction as the
/// guarded account update it describes.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct CustomerAccountEntry {
pub id: Uuid,
pub account_id: Uuid,
pub delta_minor: i64,
pub balance_minor: i64,
pub reason: String,
pub reference_type: Option<String>,
pub reference_id: Option<Uuid>,
pub created_at: DateTime<Utc>,
}
pub const CUSTOMER_ACCOUNT_ENTRY_COLUMNS: &str = "id, account_id, delta_minor, balance_minor, reason, reference_type, reference_id, created_at";
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct AddressBookEntry {
pub id: Uuid,