Bar item 1: money arithmetic lives in kernel/ and nowhere else. scripts/raw-decimal-arith.sh listed 210 places in ledger-core that did not: raw +, -, * and unary minus (which panic past Decimal's range), and checked_add / checked_sub / checked_mul / checked_div calls that resolved to rust_decimal's inherent methods (which round silently past 28 digits) and not to the kernel's Amount. 199 of them now call the kernel: Amount's methods by their full path, total / total_of for the hand-rolled sums, normal_balance, and money.rs's sign and in-range helpers. The rewrite was done by a script from the compiler's own line and column for each site, so no site was copied by hand; the few that needed a decision are explicit: - a balance sheet that cannot add liabilities and equity is not balanced (it panicked); - a template's shares, a party's percents, a reconciliation's book and cleared balances and a reversal's document movements refuse with TooLargeToCompute or their own message where they panicked; - tax_capital's split refuses where a product by the sign could not be taken, and collects its remainders as Options. No figure moves: every site computes what it computed, by the same operations in the same order. Left, each for a named reason (the detector prints these 11): money.rs 139 and 150 and periods.rs 149 and 202 (K-U10a rewrites them), audit.rs 355 and 511 (V-D3 is in them), ledger.rs 4048 (a share times the closed total: checked_mul_rounded, with K-U10a), and four rescale calls (money.rs 302, reports.rs 637, schedules.rs 370 and 377) that need a kernel function of their own. Co-Authored-By: Claude <noreply@anthropic.com>
228 lines
7.6 KiB
Rust
228 lines
7.6 KiB
Rust
//! Payouts: a platform deposit grossed up into what really happened.
|
||
//!
|
||
//! App stores, payment processors, and marketplaces collect revenue, keep
|
||
//! their fees, and deposit the difference. Booking only the deposit as
|
||
//! revenue understates income and hides the fees; the correct entry grosses
|
||
//! it up:
|
||
//!
|
||
//! ```text
|
||
//! Dr bank net deposit
|
||
//! Dr platform fees fees withheld
|
||
//! Dr/Cr adjustments refunds, chargebacks, reserves, tax withheld, ...
|
||
//! Cr revenue gross sales (one line per product or class)
|
||
//! ```
|
||
//!
|
||
//! [`payout_plan`] builds those lines and refuses unless gross − fees ±
|
||
//! adjustments equals the deposit exactly, naming the difference. It knows
|
||
//! no platform: callers (or a format-specific parser) supply the numbers
|
||
//! from the payout statement, which is the entry's receipt.
|
||
|
||
use crate::money::{add_exact, neg, on_side, sub_exact, sum_exact_of};
|
||
use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side};
|
||
use rust_decimal::Decimal;
|
||
|
||
/// A revenue or fee line of a payout.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct PayoutLine {
|
||
/// The account.
|
||
pub account: AccountId,
|
||
/// Positive amount.
|
||
pub amount: Decimal,
|
||
/// Optional class (product line, app, store).
|
||
pub class: Option<ClassId>,
|
||
}
|
||
|
||
/// Anything else on the statement: refunds, chargebacks, reserves held or
|
||
/// released, taxes withheld, currency conversion. A debit reduces the
|
||
/// deposit; a credit increases it.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct PayoutAdjustment {
|
||
/// The account.
|
||
pub account: AccountId,
|
||
/// Debit (reduces the deposit) or credit (increases it).
|
||
pub side: Side,
|
||
/// Positive amount.
|
||
pub amount: Decimal,
|
||
/// Optional class.
|
||
pub class: Option<ClassId>,
|
||
}
|
||
|
||
/// A payout to gross up.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct Payout {
|
||
/// Where the money landed.
|
||
pub deposit_account: AccountId,
|
||
/// The net deposit. Negative when the platform debited the account
|
||
/// (fees and refunds exceeded sales).
|
||
pub deposit: Decimal,
|
||
/// Gross revenue, credited.
|
||
pub revenue: Vec<PayoutLine>,
|
||
/// Fees withheld, debited.
|
||
pub fees: Vec<PayoutLine>,
|
||
/// Everything else.
|
||
pub adjustments: Vec<PayoutAdjustment>,
|
||
}
|
||
|
||
/// The payout's totals.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub struct PayoutTotals {
|
||
/// Sum of revenue lines.
|
||
pub gross: Decimal,
|
||
/// Sum of fee lines.
|
||
pub fees: Decimal,
|
||
/// Net effect of adjustments on the deposit (credits − debits).
|
||
pub adjustments: Decimal,
|
||
/// The deposit.
|
||
pub deposit: Decimal,
|
||
}
|
||
|
||
/// One planned line: account, side, amount, class.
|
||
pub type PayoutPlanLine = (AccountId, Side, Decimal, Option<ClassId>);
|
||
|
||
/// Validate a payout and build its entry's lines: the deposit first, then
|
||
/// fees, adjustments, and revenue. Errors unless every amount is positive,
|
||
/// every account is postable and fits its role (revenue lines credit
|
||
/// revenue or liability accounts, e.g. deferred revenue or sales tax
|
||
/// collected; fees debit expense accounts), and the payout reconciles to
|
||
/// the cent.
|
||
/// A zero deposit (fees and adjustments ate the sales exactly) has no
|
||
/// deposit line: every planned line is positive (BS-entry-2).
|
||
pub fn payout_plan(
|
||
payout: &Payout,
|
||
chart: &ChartOfAccounts,
|
||
) -> Result<(Vec<PayoutPlanLine>, PayoutTotals), LedgerError> {
|
||
let bad = |m: String| Err(LedgerError::InvalidPayout(m));
|
||
if payout.revenue.is_empty() {
|
||
return bad("a payout needs at least one revenue line".into());
|
||
}
|
||
let check = |account: AccountId,
|
||
amount: Decimal,
|
||
role: &str,
|
||
allowed: &[AccountType]|
|
||
-> Result<(), LedgerError> {
|
||
let a = chart
|
||
.get(account)
|
||
.ok_or(LedgerError::UnknownAccount(account))?;
|
||
if a.placeholder {
|
||
return Err(LedgerError::InvalidPayout(format!(
|
||
"{role} account {} is a placeholder",
|
||
a.code
|
||
)));
|
||
}
|
||
if !allowed.is_empty() && !allowed.contains(&a.account_type) {
|
||
return Err(LedgerError::InvalidPayout(format!(
|
||
"{role} account {} is {:?}; expected {}",
|
||
a.code,
|
||
a.account_type,
|
||
allowed
|
||
.iter()
|
||
.map(|t| format!("{t:?}"))
|
||
.collect::<Vec<_>>()
|
||
.join(" or ")
|
||
)));
|
||
}
|
||
if amount <= Decimal::ZERO {
|
||
return Err(LedgerError::InvalidPayout(format!(
|
||
"{role} amounts must be positive, got {amount} on {}",
|
||
a.code
|
||
)));
|
||
}
|
||
// No larger than a journal line may be: the payout's totals are
|
||
// sums of them (P0 review round 3, S1).
|
||
if !crate::kernel::Amount::in_line_range(amount) {
|
||
return Err(LedgerError::ValueOutOfRange(format!(
|
||
"{role} amount {amount} on {}",
|
||
a.code
|
||
)));
|
||
}
|
||
Ok(())
|
||
};
|
||
if !crate::kernel::Amount::in_line_range(payout.deposit) {
|
||
return Err(LedgerError::ValueOutOfRange(format!(
|
||
"deposit {}",
|
||
payout.deposit
|
||
)));
|
||
}
|
||
let deposit_account = chart
|
||
.get(payout.deposit_account)
|
||
.ok_or(LedgerError::UnknownAccount(payout.deposit_account))?;
|
||
if deposit_account.placeholder || deposit_account.account_type != AccountType::Asset {
|
||
return bad(format!(
|
||
"deposit account {} must be a postable asset account",
|
||
deposit_account.code
|
||
));
|
||
}
|
||
for l in &payout.revenue {
|
||
check(
|
||
l.account,
|
||
l.amount,
|
||
"revenue",
|
||
&[AccountType::Revenue, AccountType::Liability],
|
||
)?;
|
||
}
|
||
for l in &payout.fees {
|
||
check(l.account, l.amount, "fee", &[AccountType::Expense])?;
|
||
}
|
||
for a in &payout.adjustments {
|
||
check(a.account, a.amount, "adjustment", &[])?;
|
||
}
|
||
let gross = sum_exact_of(&payout.revenue, |l| l.amount, "the payout's revenue")?;
|
||
let fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?;
|
||
let adjustments = sum_exact_of(
|
||
&payout.adjustments,
|
||
|a| on_side(Side::Credit, a.side, a.amount),
|
||
"the payout's adjustments",
|
||
)?;
|
||
let expected = add_exact(
|
||
sub_exact(gross, fees, "the payout's total")?,
|
||
adjustments,
|
||
"the payout's total",
|
||
)?;
|
||
if expected != payout.deposit {
|
||
return bad(format!(
|
||
"payout doesn't reconcile: gross {gross} − fees {fees} + adjustments \
|
||
{adjustments} = {expected}, but the deposit is {} (off by {})",
|
||
payout.deposit,
|
||
sub_exact(payout.deposit, expected, "the payout's difference")?
|
||
));
|
||
}
|
||
let mut plan = Vec::new();
|
||
if payout.deposit > Decimal::ZERO {
|
||
plan.push((payout.deposit_account, Side::Debit, payout.deposit, None));
|
||
} else if payout.deposit < Decimal::ZERO {
|
||
plan.push((
|
||
payout.deposit_account,
|
||
Side::Credit,
|
||
neg(payout.deposit),
|
||
None,
|
||
));
|
||
}
|
||
plan.extend(
|
||
payout
|
||
.fees
|
||
.iter()
|
||
.map(|l| (l.account, Side::Debit, l.amount, l.class)),
|
||
);
|
||
plan.extend(
|
||
payout
|
||
.adjustments
|
||
.iter()
|
||
.map(|a| (a.account, a.side, a.amount, a.class)),
|
||
);
|
||
plan.extend(
|
||
payout
|
||
.revenue
|
||
.iter()
|
||
.map(|l| (l.account, Side::Credit, l.amount, l.class)),
|
||
);
|
||
Ok((
|
||
plan,
|
||
PayoutTotals {
|
||
gross,
|
||
fees,
|
||
adjustments,
|
||
deposit: payout.deposit,
|
||
},
|
||
))
|
||
}
|