- The 13K-character instructions (clients cut them short) become a
connect text of at most 1,400 characters whose first 512 stand alone,
plus books.handbook and books://handbook/{section}: the old guidance by
section, with no helper commands, home paths, pull requests or
file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
roots (the downloads folder by default, or --import-root), never the
data dir, books dir, vault or the key's folder, no symlink escapes or
hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.
Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
panic, so after a panic mid-mutation the server kept serving a Store
behind its journal. A panic (the task, or while holding the store)
now stops the shared store; every later request on every session is
refused with a plain message; a restart re-verifies the journal. The
join error goes through redact_refusal and never carries the panic's
text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
vault key was stored and get_w9 wrote it out): it now goes through the
import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
leads, both folders, and the default key folder whatever the settings
say. Refusals check the roots first, so outside them every path gets
one message (no probing what exists); inside, other books-dir files say
to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
can't hang a thread) and must match the checked file's device and
inode. New dependency: libc (unix only), for those two open flags,
which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
TINs) are never written into an import root, and the server refuses to
import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
annotations_complete pins the key tools' hints. The read-only hint is
checked in behaviour on every spec_mcp call (journal and data-dir files
unchanged).
- Text: the connect text names the settings file as the one local file
to edit, says every entry balances on real accounts and names its
party, says invoice/bill/payment/payroll tools post unchecked, rewords
the exemptions, and shows the company name as one plain line; the
handbook takes section "all", lists its ids in the schema and says to
read contract first; books.settings drops the config.json path and no
error names the data dir or the key file. tool_text_lint covers the
whole tool JSON and resources and bans git/commit/FL-0001; tool
descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
day of a month.
Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
became one registry beside the vault (vault/tin-files.sha256, hashes
only), shared by every session and every later server. It holds the
W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
with TINs, CPA packages with TINs and each file in one that holds a
TIN; a file is recorded before it is written, and a failure refuses.
import_local_file, attach_receipt and file_document (base64 was never
checked) refuse a recorded file, and a text file (by type, name, or
UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
exports are filed for reconciliation, and has_full_tin's "nine digits
however separated" refused their routing numbers, long references and
dates run into amounts). Text is refused when it holds (a) a TIN the
vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
on the server against the decrypted vault and never returned or
logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
hyphen or dot followed by a digit, beside it. Full-width digits and
Unicode hyphens and spaces read as ASCII. has_full_tin still guards
refusals and results (redact_refusal). Known limit, for P7: a refusal
under (a) tells the agent a text it chose holds a vault TIN.
New dependency: zeroize in ledger-mcp (already in the workspace
through ledger-vault, same major version), so the vault's TINs decoded
for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
each law a survivor broke (handbook titles, a dropped default root, a
.jpg W-9, the waker, the walk's folder flags against a link and a
pipe, the 40-link limit, save paths refused as such, the package
marking only its TIN files, a registry that can't be read, text types,
the short receipt rule's counts and a 12-character code). Simpler
code where only a race could tell: inspect places an existing path by
canonicalize itself (no second comparison), read_checked's read limit
is its one size check, openat fails on -1 as specified. The 25 MiB
upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
asks the agent to find the figure from the rule's official authority,
confirm it with the human, pass it explicitly, and tell the human so it
can be reported upstream (as the handbook says); a lib test pins it and
bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
made $HOME (or /) the root. No root may be /, the home folder or hold
it, or hold the books, data dir, vault or a key: a named one stops the
server at startup, a default one is dropped; the default falls back to
~/Downloads only if that is a real folder other than $HOME; with no
root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
folder swapped for a link after the check fails; no step may land on a
protected inode (one renamed into a root); dev/ino and nlink stay. No
/proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
follows every link, dangling ones too, so a link's target existing or
not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
their folders only when not $HOME, not a root, not holding a root; and
~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
address) and says to tell the human, never a repo path, PR or GitHub;
the digest's stale_rules drop the repo catalog and path for it; vault,
outside-books, STOPPED and local-file refusals name no git, path or
flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
--import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
request, and also lints every error template (scanned from source),
built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
exact threshold in the base currency (no "$", no rounding), required
and exempt accounts, reversals exempt; the connect text fits 1,400
characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
everywhere. shown_name drops Unicode format characters (bidi, zero
width).
- read_only_tools_change_nothing compares file contents, the database
by every row, the vault and the settings file (raw database bytes did
not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
the digest's journal repair says when the tail was set aside, not the
journal's file name; "version-history messages" back in the TIN rule;
openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
gains `authority` (the statute or publication with its address) and
RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
error"; ledger-config's ReceiptPolicy::rule takes the base currency.
New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
same version and features as ledger-store), to read the database's
rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
holding more than two TIN-shaped numbers (any rendering rule (a)
reads) that end in a known TIN's last four (the books' TIN and W-9
facts, via known_tin_last4, before the vault is opened; then the
vault's own) is refused with TIN_PROBE, the same words whether or not
one is the vault's TIN; only one or two candidates are compared
against the vault. Tests: unit
text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
one_or_two_candidates_are_compared_against_the_vault; over HTTP
text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.
Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.
Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.
Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
do); replay_register_asset/correct_asset (chrono overflow only),
replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
(check_shares_journaled), replay_register_recurring
(validate_recurring_journaled), replay_register_schedule (months 1 to
600), replay_create_period (order only), replay_dispose_asset, and no
line, date, payment or payroll range checks in replay_invoice/bill,
their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
DateOutOfRange), never panic: amortization plans, depreciation into
chrono's last month (and the true-up for lives past 9999), intervals,
document totals and aging, net pay and payroll plans, money flows and
share resolution, the asset register, receipt-policy debits; the MCP
tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
more edges, written by main's Store API with main's figures
(expected.json); every one opens in the writer and the viewer to those
figures, every derived figure computes or refuses, every MCP tool and
GUI page answers; hostile_args restarts the server after each
property; each bound has a command/replay test pair.
Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
364 lines
15 KiB
Rust
364 lines
15 KiB
Rust
//! Party shares: an entry with more than one party, each with their part of
|
||
//! what it moved.
|
||
//!
|
||
//! An entry names its counterparties as a list of [`PartyShare`]s. Most
|
||
//! name one party, who had all of it. A joint transaction names several:
|
||
//! the two members of a partnership reimbursed together, a payment split
|
||
//! between two contractors, a contribution from both members' joint funds.
|
||
//! Each share is an exact amount, a percentage, or derived from the entry
|
||
//! itself ([`Share::Derived`]).
|
||
//!
|
||
//! ```text
|
||
//! GOAL: "what did we pay each of them?" right when one entry was with
|
||
//! several parties, with apportioning the human controls exactly.
|
||
//! SOURCE: DECISION (owner, 2026-10-15): no "joint" party; a joint
|
||
//! transaction is with both members, each with their share, and
|
||
//! shares can be apportioned explicitly ("do you allow for
|
||
//! controlled apportioning?" Yes). docs/parties-and-attachments.md
|
||
//! "Shares".
|
||
//! DEFINITIONS:
|
||
//! flow: crate::parties::entry_flow(entry, money).
|
||
//! target: flow.net when it is not zero, else the entry's total debits
|
||
//! (a member contributing property moves no money but is still all
|
||
//! theirs). magnitude = |target|; sign = the sign of target (positive
|
||
//! when net is zero).
|
||
//! A member: a PartyMember (party, income share, capital account,
|
||
//! distributions account), passed in by the caller from the company's
|
||
//! settings ([[company.members]]); core doesn't read the settings.
|
||
//! INVARIANTS (of an entry's shares, checked by check_shares, journaled):
|
||
//! 1. No party appears twice; every party is in the directory.
|
||
//! 2. All shares are one kind: all Amount, all Percent, or all Derived.
|
||
//! 3. An Amount is positive with at most two decimal places (cents).
|
||
//! 4. A Percent is positive, at most 100, and the percents sum to exactly
|
||
//! 100.
|
||
//! 5. At most one party has a vendor record: a 1099 counts a payment
|
||
//! toward a single vendor.
|
||
//! INVARIANTS (of resolve, against the entry's lines and the members):
|
||
//! 6. Resolved amounts sum to target exactly, and each has target's sign.
|
||
//! 7. Amount: each party gets sign × its amount; refused unless the
|
||
//! amounts sum to magnitude.
|
||
//! 8. Percent: each party gets magnitude × percent / 100 rounded toward
|
||
//! zero to the cent; the cents left over (fewer than one per party)
|
||
//! go to the first party in order. Then the sign.
|
||
//! 9. Derived, one party: it gets target.
|
||
//! 10. Derived, several parties: every one must be a member (else
|
||
//! refused: give amounts or percents). If the entry has a line on any
|
||
//! named member's capital or distributions account, each member gets
|
||
//! |credits − debits| on their own two accounts, and those must sum
|
||
//! to magnitude (else refused). Otherwise each gets their income share
|
||
//! of magnitude, the shares rescaled to the members named, rounded as
|
||
//! in 8 (remainder to the first).
|
||
//! SCENARIOS:
|
||
//! 1. Reimbursing both members $100.00 (Dr 2100 / Cr 1000), both named,
|
||
//! derived, 50/50: $50.00 each.
|
||
//! 2. A joint contribution (Dr 1000 300 / Cr 3000 200 / Cr 3001 100):
|
||
//! derived from the capital lines, Tobin −200.00, Morgan −100.00
|
||
//! (received).
|
||
//! 3. A property contribution (Dr Equipment 1000 / Cr 3000 500 / Cr 3001
|
||
//! 500): net is zero; target is the total, 500.00 each.
|
||
//! 4. $100.00 split 1/3 each three ways by percent 33.33, 33.33, 33.34:
|
||
//! 33.33, 33.33, 33.34. By 33.333/33.333/33.334: 33.34, 33.33, 33.33
|
||
//! (the leftover cent to the first).
|
||
//! 5. Amounts of $60.00 and $30.00 on a $100.00 payment: refused.
|
||
//! ```
|
||
|
||
use crate::{AccountId, JournalEntry, PartyId, Side};
|
||
use rust_decimal::Decimal;
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
/// What part of an entry one party had.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum Share {
|
||
/// Exactly this much of what the entry moved (a positive amount, in
|
||
/// cents; the sign follows the entry).
|
||
Amount(Decimal),
|
||
/// This percent of what the entry moved (0 < p ≤ 100).
|
||
Percent(Decimal),
|
||
/// From the entry itself: all of it for a sole party; for members,
|
||
/// their capital lines or their income share (see the module's
|
||
/// INVARIANT 10).
|
||
Derived,
|
||
}
|
||
|
||
/// One party named on an entry, with their share.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||
pub struct PartyShare {
|
||
/// The party.
|
||
#[serde(rename = "party_id")]
|
||
pub party: PartyId,
|
||
/// Their share.
|
||
pub share: Share,
|
||
}
|
||
|
||
impl PartyShare {
|
||
/// The sole party, with all of it.
|
||
pub fn whole(party: PartyId) -> Self {
|
||
PartyShare {
|
||
party,
|
||
share: Share::Derived,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A member of the company as shares see them: their party, their share of
|
||
/// income (a fraction, e.g. 0.50), and their capital and distributions
|
||
/// accounts. Built by the caller from the settings' members.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub struct PartyMember {
|
||
/// The member's party in the directory.
|
||
pub party: PartyId,
|
||
/// Their share of income, as a fraction (the members' sum to 1).
|
||
pub share: Decimal,
|
||
/// Their capital account.
|
||
pub capital: AccountId,
|
||
/// Their distributions account, if they have one.
|
||
pub distributions: Option<AccountId>,
|
||
}
|
||
|
||
/// The structural checks on an entry's shares (the module's INVARIANTS 1–4;
|
||
/// 5 needs the directory and is [`crate::Ledger::check_set_entry_parties`]'s).
|
||
/// `known` says whether a party is in the directory. Returns why not.
|
||
///
|
||
/// For new shares: [`check_shares_journaled`], and no amount larger than a
|
||
/// line may be (kernel::MAX_LINE_AMOUNT; P0 review round 3, S1). Replay
|
||
/// checks only [`check_shares_journaled`] (rules.md B-28).
|
||
pub fn check_shares(shares: &[PartyShare], known: impl Fn(PartyId) -> bool) -> Result<(), String> {
|
||
check_shares_journaled(shares, known)?;
|
||
for s in shares {
|
||
if let Share::Amount(a) = s.share
|
||
&& a > crate::kernel::MAX_LINE_AMOUNT
|
||
{
|
||
return Err(format!(
|
||
"party {}'s amount {a} is larger than any entry may move (at most 1000000000000000)",
|
||
s.party
|
||
));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// The checks every journaled `entry.parties_set` passed when it was
|
||
/// written (the rule through 2026-10-16): [`check_shares`] without the
|
||
/// amount's upper bound. Replay applies exactly these, so books an earlier
|
||
/// version wrote always open (rules.md B-28).
|
||
pub fn check_shares_journaled(
|
||
shares: &[PartyShare],
|
||
known: impl Fn(PartyId) -> bool,
|
||
) -> Result<(), String> {
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
for s in shares {
|
||
if !known(s.party) {
|
||
return Err(format!("unknown party {}", s.party));
|
||
}
|
||
if !seen.insert(s.party) {
|
||
return Err(format!("party {} is named twice", s.party));
|
||
}
|
||
}
|
||
let kind = |s: &Share| match s {
|
||
Share::Amount(_) => 0,
|
||
Share::Percent(_) => 1,
|
||
Share::Derived => 2,
|
||
};
|
||
if let Some(first) = shares.first()
|
||
&& shares.iter().any(|s| kind(&s.share) != kind(&first.share))
|
||
{
|
||
return Err(
|
||
"give every party the same kind of share: all amounts, all percents, or none (derived)"
|
||
.into(),
|
||
);
|
||
}
|
||
let mut percent = Decimal::ZERO;
|
||
let mut any_percent = false;
|
||
for s in shares {
|
||
match s.share {
|
||
Share::Amount(a) => {
|
||
if a <= Decimal::ZERO {
|
||
return Err(format!("party {}'s amount must be positive", s.party));
|
||
}
|
||
if a.normalize().scale() > 2 {
|
||
return Err(format!(
|
||
"party {}'s amount {a} is finer than a cent",
|
||
s.party
|
||
));
|
||
}
|
||
}
|
||
Share::Percent(p) => {
|
||
if p <= Decimal::ZERO || p > Decimal::ONE_HUNDRED {
|
||
return Err(format!(
|
||
"party {}'s percent must be more than 0 and at most 100",
|
||
s.party
|
||
));
|
||
}
|
||
any_percent = true;
|
||
percent += p;
|
||
}
|
||
Share::Derived => {}
|
||
}
|
||
}
|
||
if any_percent && percent != Decimal::ONE_HUNDRED {
|
||
return Err(format!("the percents sum to {percent}, not 100"));
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// What the shares are split over: the entry's flow net, else its total
|
||
/// debits (the module's DEFINITIONS).
|
||
/// Refused (TooLargeToCompute), never a panic, when a sum is past exact
|
||
/// arithmetic: a draft's lines and an entry's shares are as journaled, of
|
||
/// any size (rules.md B-28).
|
||
pub fn share_target(
|
||
entry: &JournalEntry,
|
||
money: &crate::parties::MoneyAccounts,
|
||
) -> Result<Decimal, crate::LedgerError> {
|
||
let net = crate::parties::entry_flow(entry, money)?.net;
|
||
if net.is_zero() {
|
||
entry
|
||
.lines()
|
||
.iter()
|
||
.filter(|l| l.side == Side::Debit)
|
||
.try_fold(Decimal::ZERO, |s, l| s.checked_add(l.amount.amount))
|
||
.ok_or_else(|| too_large(format!("entry {}'s debits", entry.id())))
|
||
} else {
|
||
Ok(net)
|
||
}
|
||
}
|
||
|
||
/// The refusal of a sum past exact arithmetic.
|
||
fn too_large(what: String) -> crate::LedgerError {
|
||
crate::LedgerError::TooLargeToCompute(what)
|
||
}
|
||
|
||
/// The sum of `values`, or None past exact arithmetic.
|
||
fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
|
||
values
|
||
.into_iter()
|
||
.try_fold(Decimal::ZERO, |s, v| s.checked_add(v))
|
||
}
|
||
|
||
/// Split `magnitude` (non-negative) by `weights` (positive, any sum): each
|
||
/// part rounded toward zero to the cent, the cents left over to the first.
|
||
/// None when a product or sum is past exact arithmetic.
|
||
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
|
||
use rust_decimal::RoundingStrategy::ToZero;
|
||
let total = checked_sum(weights.iter().copied())?;
|
||
if weights.is_empty() || total.is_zero() {
|
||
return Some(vec![Decimal::ZERO; weights.len()]);
|
||
}
|
||
let mut parts: Vec<Decimal> = weights
|
||
.iter()
|
||
.map(|w| {
|
||
magnitude
|
||
.checked_mul(*w)
|
||
.and_then(|x| x.checked_div(total))
|
||
.map(|x| x.round_dp_with_strategy(2, ToZero))
|
||
})
|
||
.collect::<Option<_>>()?;
|
||
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
|
||
parts[0] = parts[0].checked_add(left)?;
|
||
Some(parts)
|
||
}
|
||
|
||
/// Each party's exact part of what `entry` moved (the module's INVARIANTS
|
||
/// 6–10), in the shares' order. Refused, with why, when the shares can't
|
||
/// resolve against these lines and members.
|
||
pub fn resolve(
|
||
entry: &JournalEntry,
|
||
shares: &[PartyShare],
|
||
money: &crate::parties::MoneyAccounts,
|
||
members: &[PartyMember],
|
||
) -> Result<Vec<(PartyId, Decimal)>, String> {
|
||
let target = share_target(entry, money).map_err(|e| e.to_string())?;
|
||
let past_exact = || too_large(format!("entry {}'s shares", entry.id())).to_string();
|
||
let magnitude = target.abs();
|
||
let signed = |v: Decimal| if target.is_sign_negative() { -v } else { v };
|
||
let Some(first) = shares.first() else {
|
||
return Ok(Vec::new());
|
||
};
|
||
let parts: Vec<Decimal> = match first.share {
|
||
Share::Amount(_) => {
|
||
let amounts: Vec<Decimal> = shares
|
||
.iter()
|
||
.map(|s| match s.share {
|
||
Share::Amount(a) => a,
|
||
_ => Decimal::ZERO,
|
||
})
|
||
.collect();
|
||
let sum = checked_sum(amounts.iter().copied()).ok_or_else(past_exact)?;
|
||
if sum != magnitude {
|
||
return Err(format!(
|
||
"the parties' amounts sum to {sum}, but entry {} moved {magnitude}",
|
||
entry.id()
|
||
));
|
||
}
|
||
amounts
|
||
}
|
||
Share::Percent(_) => {
|
||
let weights: Vec<Decimal> = shares
|
||
.iter()
|
||
.map(|s| match s.share {
|
||
Share::Percent(p) => p,
|
||
_ => Decimal::ZERO,
|
||
})
|
||
.collect();
|
||
split_first(magnitude, &weights).ok_or_else(past_exact)?
|
||
}
|
||
Share::Derived if shares.len() == 1 => vec![magnitude],
|
||
Share::Derived => {
|
||
let named: Vec<&PartyMember> = shares
|
||
.iter()
|
||
.map(|s| {
|
||
members.iter().find(|m| m.party == s.party).ok_or_else(|| {
|
||
format!(
|
||
"party {} isn't a member, so its share can't be derived: give each party an amount or a percent",
|
||
s.party
|
||
)
|
||
})
|
||
})
|
||
.collect::<Result<_, _>>()?;
|
||
let on = |m: &PartyMember, a: AccountId| a == m.capital || Some(a) == m.distributions;
|
||
let touches = entry
|
||
.lines()
|
||
.iter()
|
||
.any(|l| named.iter().any(|m| on(m, l.account)));
|
||
if touches {
|
||
let parts: Vec<Decimal> = named
|
||
.iter()
|
||
.map(|m| {
|
||
checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| {
|
||
match l.side {
|
||
Side::Credit => l.amount.amount,
|
||
Side::Debit => -l.amount.amount,
|
||
}
|
||
}))
|
||
.map(|s| s.abs())
|
||
})
|
||
.collect::<Option<_>>()
|
||
.ok_or_else(past_exact)?;
|
||
let sum = checked_sum(parts.iter().copied()).ok_or_else(past_exact)?;
|
||
if sum != magnitude {
|
||
return Err(format!(
|
||
"the members' capital lines on entry {} come to {sum}, but it moved {magnitude}: give each member an amount",
|
||
entry.id()
|
||
));
|
||
}
|
||
parts
|
||
} else {
|
||
let weights: Vec<Decimal> = named.iter().map(|m| m.share).collect();
|
||
if weights.iter().any(|w| *w <= Decimal::ZERO) {
|
||
return Err(
|
||
"a member named has no income share: give each party an amount or a percent"
|
||
.into(),
|
||
);
|
||
}
|
||
split_first(magnitude, &weights).ok_or_else(past_exact)?
|
||
}
|
||
}
|
||
};
|
||
Ok(shares
|
||
.iter()
|
||
.zip(parts)
|
||
.map(|(s, v)| (s.party, signed(v)))
|
||
.collect())
|
||
}
|