Skip to content

金额、汇率与产品值

1. 业务背景

订阅市场需要记录订单金额、币种、汇率和入账金额。金额不是单纯的数字:它至少要带币种;汇率会随时间变化;已入账的金额不能因为今天的汇率变化而被改写。

市场例子已经使用 Money 产品值和当前汇率;本文聚焦历史入账汇率这个更窄的问题。

这个例子演示三件事:

  • Money 是产品值,不是 entity,也不是拆开的两个 relation。
  • 汇率是带时间的事实,不是 Money 的字段。
  • 入账时保存实际使用的汇率和折算金额;历史报表不重算。

2. 领域模型

entity Customer

entity Order

// 结算币种。
value Currency = { USD, CNY, EUR }

// 金额 + 币种。产品值没有身份,按字段比较。
value Money = {
  amount: Decimal,
  currency: Currency
} where amount >= 0

订单金额

/**
 * @gloss {order} 的订单金额是 {value}
 * @example 订单 o1 的 CNY 金额是 100.00:order_money(o1, Money { amount: 100.00, currency: CNY })
 */
state relation order_money(order: Order, value: Money) {
  key total (order)
}

金额和币种总是一起出现,所以它们属于一个产品值,不拆成两个关系。

汇率与入账事实

/**
 * @gloss {currency} 在 {at} 的汇率是 {rate}
 * @example 2024-01-01 的 CNY 汇率是 0.25 USD:exchange_rate(CNY, 2024-01-01T00:00:00Z, 0.25)
 */
state relation exchange_rate(currency: Currency, at: Timestamp, rate: Decimal) {
  key partial (currency, at)
}

/**
 * @gloss {order} 在 {at} 使用汇率 {rate} 入账
 * @example o1 在 2024-01-01 按 0.25 入账:applied_rate(o1, 0.25, 2024-01-01T00:00:00Z)
 */
state relation applied_rate(order: Order, rate: Decimal, at: Timestamp) {
  key partial (order)
}

/**
 * @gloss {order} 的基准币金额是 {value}
 * @example 100 CNY 按 0.25 折算后入账 25.00:base_amount(o1, 25.00)
 */
state relation base_amount(order: Order, value: Decimal) {
  key partial (order)
}

汇率是带 at 的事实;applied_rate 是入账时保存的事实;base_amount 是折算结果。它们都不属于 Money 值本身。

业务计算

define amount_of(money: Money) -> Decimal {
  money.amount
}

define currency_of(money: Money) -> Currency {
  money.currency
}

define convert(money: Money, rate: Decimal, to: Currency) -> Money {
  Money {
    amount: money.amount * rate,
    currency: to
  }
}

define base_amount_of(order: Order, rate: Decimal) -> Decimal {
  amount_of(order_money(order)) * rate
}

字段读取是纯投影;转换是顶层 define,不是 Money 的方法。

业务动作

transition post(order: Order, rate: Decimal, at: Timestamp) {
  require exchange_rate(currency_of(order_money(order)), at, rate)
  applied_rate(order, rate, at)
  base_amount(order, base_amount_of(order, rate))
}

入账时检查汇率存在,并把实际使用的汇率和折算金额写成事实。

视角与场景

view finance = { order_money, applied_rate, base_amount }

state s0 {
  time 2024-01-01T00:00:00Z
  o1: Order
  order_money(o1, Money { amount: 100.00, currency: CNY })
  exchange_rate(CNY, 2024-01-01T00:00:00Z, 0.25)
  exchange_rate(USD, 2024-01-01T00:00:00Z, 1.00)
}

init s0

scenario post_flow {
  start s0
  do post(o1, 0.25, 2024-01-01T00:00:00Z)
}

3. 为什么这样组合

概念 构造 原因
Money value 产品值 无身份、字段总是一起出现
Order entity 有身份和生命周期
订单金额 state relation 事实,key 是订单
汇率 带 at 的 state relation 外部事实,随时间变化
入账汇率 state relation 支付时保存的事实
换算 define 纯计算,不存储

简单场景可以只用 Amount = Decimal where self >= 0;需要币种时升级到 Money;需要历史时增加带 at 的事实;Money 本身不变。

4. 边界

  • 未建模手续费、税、买卖价差和舍入策略。
  • 汇率历史只保留示例数据;完整 as-of 查询需要时间区间或查询层。
  • 入账汇率由调用方提供;业务上应由支付事件或汇率快照决定。
  • 货币不是静态 unit;不要把 Currency 做成 unit。

输入关键词开始搜索…

↑↓ 选择↵ 打开Esc 关闭