Files
wanderbooks/crates/ledger-core/src/payroll.rs
T
swaitsandClaude Opus 5.5 8693d5a3f5 MCP: short connect text, a handbook, tool annotations, safe local imports
- 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
2026-10-17 09:25:00 -06:00

470 lines
18 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Payroll: accounting-only payroll runs (no tax tables).
//!
//! A payroll run posts one balanced entry: gross wages hit Salary & Wage
//! Expense, the employer share of FICA hits Payroll Tax Expense, employee
//! withholdings and deductions accumulate in the 2110–2150 payable accounts,
//! and net pay leaves cash. A later [`crate::Ledger::remit_payroll_taxes`]
//! clears the payables when the tax payments go out.
//!
//! There is no tax law here: every withholding number is supplied by the
//! caller. All amounts are exact [`rust_decimal::Decimal`], never floats.
use crate::{AccountId, Currency, EntryId, LedgerError, Money, Side};
use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
/// Opaque payroll run handle. Created by [`crate::Ledger`]; never forged.
pub type PayrollRunId = u64;
/// One employee's payroll line: gross pay and every withholding and
/// deduction. All amounts must be non-negative; the engine rejects
/// negatives, and rejects the line when withholdings exceed gross.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayrollLine {
/// Employee name, for the run record.
pub employee_name: String,
/// The employee's party, if named (new runs should; runs from before
/// the party directory carry the name only).
#[serde(default)]
pub employee: Option<crate::PartyId>,
/// Gross pay for the period.
pub gross_pay: Decimal,
/// Federal income tax withheld.
pub federal_withholding: Decimal,
/// State income tax withheld.
pub state_withholding: Decimal,
/// Employee share of Social Security tax.
pub ss_employee: Decimal,
/// Employee share of Medicare tax.
pub medicare_employee: Decimal,
/// Employer share of Social Security tax.
pub ss_employer: Decimal,
/// Employer share of Medicare tax.
pub medicare_employer: Decimal,
/// Other deductions (retirement, insurance, garnishments, ...).
pub other_deductions: Decimal,
}
impl PayrollLine {
/// Gross minus all employee withholdings and deductions. Must be >= 0:
/// you cannot withhold more than the employee earned. Refused
/// (TooLargeToCompute), never a panic, past exact arithmetic: a run is
/// restored as journaled (rules.md B-28).
pub fn net_pay(&self) -> Result<Decimal, LedgerError> {
[
self.federal_withholding,
self.state_withholding,
self.ss_employee,
self.medicare_employee,
self.other_deductions,
]
.into_iter()
.try_fold(self.gross_pay, Decimal::checked_sub)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s net pay", self.employee_name)))
}
}
/// A posted payroll run: the inputs plus the journal entry it posted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayrollRun {
/// Run id (the allocator's).
pub id: PayrollRunId,
/// Pay date: the date of the posted entry.
pub date: NaiveDate,
/// One line per employee.
pub lines: Vec<PayrollLine>,
/// The posted journal entry.
pub entry_id: EntryId,
}
/// The chart accounts a payroll run posts to, resolved by code.
#[derive(Clone, Copy, Debug)]
pub struct PayrollAccounts {
/// `6100` Salary & Wage Expense.
pub salary_expense: AccountId,
/// `6110` Payroll Tax Expense.
pub payroll_tax_expense: AccountId,
/// `2110` Federal Withholding Payable.
pub federal_payable: AccountId,
/// `2120` State Withholding Payable.
pub state_payable: AccountId,
/// `2130` SS Tax Payable.
pub ss_payable: AccountId,
/// `2140` Medicare Tax Payable.
pub medicare_payable: AccountId,
/// `2150` Other Deductions Payable.
pub other_payable: AccountId,
}
/// Validate a payroll run's lines without mutating: non-empty, no negative
/// amounts, no negative net pay. Journaling stores run this before writing
/// anything, so a doomed run never leaves journal lines behind.
pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError> {
// No wages at all is no payroll: refused before anything changes
// (found by the spec-blind tests, 2026-10-13: an all-zero run passed
// validation, then failed at post after creating accounts).
if lines.is_empty() || lines.iter().all(|l| l.gross_pay.is_zero()) {
return Err(LedgerError::EmptyPayroll);
}
for line in lines {
for amount in [
line.gross_pay,
line.federal_withholding,
line.state_withholding,
line.ss_employee,
line.medicare_employee,
line.ss_employer,
line.medicare_employer,
line.other_deductions,
] {
if amount < Decimal::ZERO {
return Err(LedgerError::NegativePayrollAmount(amount));
}
}
check_payroll_ranges(std::slice::from_ref(line))?;
if line.net_pay()? < Decimal::ZERO {
return Err(LedgerError::NegativeNetPay(line.employee_name.clone()));
}
}
Ok(())
}
/// Every amount of every line no larger than a journal line may be
/// (kernel::MAX_LINE_AMOUNT, ten decimal places), so net pay and the run's
/// totals are exact (P0 review round 3, S1). For new runs only: replay
/// restores a run as journaled (rules.md B-28).
pub fn check_payroll_ranges(lines: &[PayrollLine]) -> Result<(), LedgerError> {
for line in lines {
for amount in [
line.gross_pay,
line.federal_withholding,
line.state_withholding,
line.ss_employee,
line.medicare_employee,
line.ss_employer,
line.medicare_employer,
line.other_deductions,
] {
if !crate::kernel::Amount::in_line_range(amount) {
return Err(LedgerError::ValueOutOfRange(format!(
"payroll amount {amount}"
)));
}
}
}
Ok(())
}
/// The auto-posted payroll entry's lines, in posting order: Dr 6100 gross,
/// Dr 6110 the employer FICA share, Cr 2110–2150 the payables, Cr cash net
/// pay. Zero totals are skipped — the engine rejects zero-amount lines.
///
/// Shared by [`crate::Ledger::run_payroll`] and the journaling store, so the
/// journaled entry and the posted entry are built from the same math. The
/// plan always balances: debits are gross + employer FICA, credits are the
/// payables + net, and net is defined as gross minus employee withholdings.
/// Refused (TooLargeToCompute) when a total is past exact arithmetic.
pub fn payroll_entry_plan(
lines: &[PayrollLine],
accounts: PayrollAccounts,
cash_account: AccountId,
base: Currency,
) -> Result<Vec<(AccountId, Side, Money)>, LedgerError> {
let too_large = || LedgerError::TooLargeToCompute("the payroll run's totals".into());
let sum = |f: &dyn Fn(&PayrollLine) -> Option<Decimal>| {
lines
.iter()
.try_fold(Decimal::ZERO, |t, l| t.checked_add(f(l)?))
.ok_or_else(too_large)
};
let gross = sum(&|l| Some(l.gross_pay))?;
let employer = sum(&|l| l.ss_employer.checked_add(l.medicare_employer))?;
let federal = sum(&|l| Some(l.federal_withholding))?;
let state = sum(&|l| Some(l.state_withholding))?;
let ss = sum(&|l| l.ss_employee.checked_add(l.ss_employer))?;
let medicare = sum(&|l| l.medicare_employee.checked_add(l.medicare_employer))?;
let other = sum(&|l| Some(l.other_deductions))?;
let net = sum(&|l| l.net_pay().ok())?;
let mut plan = Vec::new();
let mut push = |account: AccountId, side: Side, amount: Decimal| {
if !amount.is_zero() {
plan.push((account, side, Money::new(amount, base)));
}
};
push(accounts.salary_expense, Side::Debit, gross);
push(accounts.payroll_tax_expense, Side::Debit, employer);
push(accounts.federal_payable, Side::Credit, federal);
push(accounts.state_payable, Side::Credit, state);
push(accounts.ss_payable, Side::Credit, ss);
push(accounts.medicare_payable, Side::Credit, medicare);
push(accounts.other_payable, Side::Credit, other);
push(cash_account, Side::Credit, net);
Ok(plan)
}
/// The remittance entry's lines: Dr each payable with a non-zero balance,
/// Cr cash for the total. Balances are normal-side (positive = owed), so
/// the plan balances by construction.
pub fn payroll_remit_plan(
payables: &[(AccountId, Decimal)],
cash_account: AccountId,
base: Currency,
) -> Vec<(AccountId, Side, Money)> {
let mut plan = Vec::new();
let mut total = Decimal::ZERO;
for (account, balance) in payables {
if balance.is_zero() {
continue;
}
plan.push((*account, Side::Debit, Money::new(*balance, base)));
total += *balance;
}
if !total.is_zero() {
plan.push((cash_account, Side::Credit, Money::new(total, base)));
}
plan
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AccountType, Ledger};
fn d(cents: i64) -> Decimal {
Decimal::new(cents, 2)
}
fn line(name: &str) -> PayrollLine {
PayrollLine {
employee_name: name.to_string(),
employee: None,
gross_pay: d(500_000), // 5000.00
federal_withholding: d(75_000), // 750.00
state_withholding: d(25_000), // 250.00
ss_employee: d(31_000), // 310.00
medicare_employee: d(7_250), // 72.50
ss_employer: d(31_000),
medicare_employer: d(7_250),
other_deductions: d(10_000), // 100.00
}
}
fn ledger_with_cash() -> (Ledger, AccountId) {
let mut ledger = Ledger::new(Currency::USD);
let cash = ledger
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
(ledger, cash)
}
#[test]
fn net_pay_math() {
let l = line("Ada");
// 5000 - 750 - 250 - 310 - 72.50 - 100 = 3517.50
assert_eq!(l.net_pay().unwrap(), d(351_750));
}
#[test]
fn validation_rejects_empty_negative_and_overwithheld() {
assert_eq!(validate_payroll_lines(&[]), Err(LedgerError::EmptyPayroll));
let mut bad = line("Bob");
bad.ss_employee = d(-1);
assert_eq!(
validate_payroll_lines(std::slice::from_ref(&bad)),
Err(LedgerError::NegativePayrollAmount(d(-1)))
);
let mut over = line("Cat");
over.other_deductions = d(99_999_999);
assert!(over.net_pay().unwrap() < Decimal::ZERO);
assert_eq!(
validate_payroll_lines(std::slice::from_ref(&over)),
Err(LedgerError::NegativeNetPay("Cat".to_string()))
);
assert!(validate_payroll_lines(&[line("Ada")]).is_ok());
}
#[test]
fn entry_plan_balances_and_skips_zeros() {
let cash = ledger_with_cash().1;
let accounts = PayrollAccounts {
salary_expense: 101,
payroll_tax_expense: 102,
federal_payable: 103,
state_payable: 104,
ss_payable: 105,
medicare_payable: 106,
other_payable: 107,
};
// No state withholding and no other deductions: those credits vanish.
let mut l = line("Ada");
l.state_withholding = Decimal::ZERO;
l.other_deductions = Decimal::ZERO;
let plan = payroll_entry_plan(&[l], accounts, cash, Currency::USD).unwrap();
assert_eq!(plan.len(), 6); // gross, employer tax, fed, ss, medicare, cash
let mut debits = Decimal::ZERO;
let mut credits = Decimal::ZERO;
for (_, side, amount) in &plan {
match side {
Side::Debit => debits += amount.amount,
Side::Credit => credits += amount.amount,
}
}
assert_eq!(debits, credits);
assert!(debits > Decimal::ZERO);
for (_, _, amount) in &plan {
assert!(!amount.amount.is_zero());
}
}
#[test]
fn run_payroll_posts_balanced_entry_and_records_run() {
let (mut ledger, cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap();
let id = ledger
.run_payroll(date, vec![line("Ada"), line("Bob")], cash)
.unwrap();
assert_eq!(id, 1);
assert_eq!(ledger.next_payroll_run_id(), 2);
let run = ledger.get_payroll_run(id).unwrap();
assert_eq!(run.date, date);
assert_eq!(run.lines.len(), 2);
let entry = ledger.get_entry(run.entry_id).unwrap();
assert_eq!(entry.status(), crate::EntryStatus::Posted);
// Debits equal credits, exactly.
let mut debits = Decimal::ZERO;
let mut credits = Decimal::ZERO;
for l in entry.lines() {
match l.side {
Side::Debit => debits += l.amount.amount,
Side::Credit => credits += l.amount.amount,
}
}
assert_eq!(debits, credits);
// Gross x2 = 10000 hits Salary & Wage Expense (debit-normal).
let salary = ledger.chart().find_by_code("6100").unwrap().id;
assert_eq!(ledger.account_balance(salary).unwrap(), d(1_000_000));
// Net x2 = 7035 leaves cash (debit-normal): -7035.
assert_eq!(ledger.account_balance(cash).unwrap(), -d(703_500));
// The seven payroll accounts were auto-created.
for code in ["6100", "6110", "2110", "2120", "2130", "2140", "2150"] {
assert!(
ledger.chart().find_by_code(code).is_some(),
"missing {code}"
);
}
// Runs list in id order.
let id2 = ledger.run_payroll(date, vec![line("Cat")], cash).unwrap();
let ids: Vec<_> = ledger.list_payroll_runs().iter().map(|r| r.id).collect();
assert_eq!(ids, vec![id, id2]);
}
#[test]
fn run_payroll_rejects_closed_period() {
let (mut ledger, cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 9, 30).unwrap();
let pid = ledger
.create_period("Sep", NaiveDate::from_ymd_opt(2026, 9, 1).unwrap(), date)
.unwrap();
ledger.close_period(pid).unwrap();
let err = ledger.run_payroll(date, vec![line("Ada")], cash);
assert_eq!(err, Err(LedgerError::ClosedPeriod(pid, date.to_string())));
}
#[test]
fn run_payroll_rejects_bad_inputs() {
let (mut ledger, cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap();
assert_eq!(
ledger.run_payroll(date, vec![], cash),
Err(LedgerError::EmptyPayroll)
);
let mut bad = line("Ada");
bad.gross_pay = d(-100);
assert_eq!(
ledger.run_payroll(date, vec![bad], cash),
Err(LedgerError::NegativePayrollAmount(d(-100)))
);
assert_eq!(
ledger.run_payroll(date, vec![line("Ada")], 999),
Err(LedgerError::UnknownAccount(999))
);
}
#[test]
fn remit_clears_payables() {
let (mut ledger, cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap();
ledger.run_payroll(date, vec![line("Ada")], cash).unwrap();
// Withholdings owed: 750 + 250 + (310+310) + (72.50+72.50) + 100 = 1865.
let fed = ledger.chart().find_by_code("2110").unwrap().id;
assert_eq!(ledger.account_balance(fed).unwrap(), d(75_000));
// Nothing owed before any payroll: fresh ledger remits nothing.
let (mut fresh, fresh_cash) = ledger_with_cash();
assert_eq!(
fresh.remit_payroll_taxes(date, fresh_cash),
Err(LedgerError::NothingToRemit)
);
// Remit: payables go to zero, cash drops by the total.
let cash_before = ledger.account_balance(cash).unwrap();
let entry = ledger.remit_payroll_taxes(date, cash).unwrap();
let posted = ledger.get_entry(entry).unwrap();
assert_eq!(posted.status(), crate::EntryStatus::Posted);
for code in ["2110", "2120", "2130", "2140", "2150"] {
let id = ledger.chart().find_by_code(code).unwrap().id;
assert_eq!(
ledger.account_balance(id).unwrap(),
Decimal::ZERO,
"payable {code} not cleared"
);
}
assert_eq!(
ledger.account_balance(cash).unwrap(),
cash_before - d(186_500)
);
// Second remit finds nothing left.
assert_eq!(
ledger.remit_payroll_taxes(date, cash),
Err(LedgerError::NothingToRemit)
);
}
#[test]
fn remit_rejects_closed_period() {
let (mut ledger, cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 9, 30).unwrap();
ledger
.run_payroll(
NaiveDate::from_ymd_opt(2026, 9, 15).unwrap(),
vec![line("Ada")],
cash,
)
.unwrap();
let pid = ledger
.create_period("Sep", NaiveDate::from_ymd_opt(2026, 9, 1).unwrap(), date)
.unwrap();
ledger.close_period(pid).unwrap();
assert_eq!(
ledger.remit_payroll_taxes(date, cash),
Err(LedgerError::ClosedPeriod(pid, date.to_string()))
);
}
#[test]
fn replay_payroll_run_checks_id() {
let (mut ledger, _cash) = ledger_with_cash();
let date = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap();
let entry = ledger.create_entry(date, "x");
let err = ledger.replay_payroll_run(7, date, vec![line("Ada")], entry);
assert_eq!(err, Err(LedgerError::ReplayIdMismatch(7, 1)));
// The allocator did not move on failure.
assert_eq!(ledger.next_payroll_run_id(), 1);
ledger
.replay_payroll_run(1, date, vec![line("Ada")], entry)
.unwrap();
assert_eq!(ledger.next_payroll_run_id(), 2);
assert!(ledger.get_payroll_run(1).is_some());
assert!(ledger.get_payroll_run(2).is_none());
}
}