=== BEGIN ARTIFACT FEATURE-LoadCsvReader.md === # FEATURE: Load CSV Reader | Field | Value | |-------|-------| | Version | 20261027 V1 | | Description | Shared reader that opens a CSV file named on the command line, checks its header, and returns numbered rows. | | Depends On | ARCHITECTURE.md, FEATURE-CliEntry.md | | Provides | ledger_core.csvio | | Consumes | ledger, cli.registry | ## Questions - None. ## Purpose The three `ledger load ` commands share one reader so that file handling, header checking, and the exit codes for unreadable files and malformed rows are identical. The reader only reads: it never touches the database and never writes. ## Interface `ledger_core.csvio.read_rows(path, header)` - `path` is the file path named on the command line; `header` is the sequence of column names the table requires, in order. - Returns a list of `(line_number, fields)` tuples, one per data row, in file order. `line_number` is the 1-based line of the file (the header is line 1, so the first data row is line 2). `fields` is a list of strings exactly as parsed by the `csv` module. - A file that is missing or cannot be read or decoded raises `Operational` (exit 1). - A header that differs from `header` in names or order, an empty file, or a data row whose field count differs from `len(header)` raises `Rejected` (exit 3), with a diagnostic naming the line. - A file with a valid header and no data rows returns an empty list. - Blank lines are not data rows and are skipped. ## Database Interface - None — persistence is owned by DATABASE.md. ## Programmatic Acceptance === AC csvio-reads-numbered-rows === Intent: read_rows returns every data row in file order with 1-based file line numbers and the parsed fields, for a file whose header matches. Requires: executable=python3; scope=test import csv import os import tempfile from ledger_core.csvio import read_rows header = ["account", "name"] rows = [["ZZR1", "First Row"], ["ZZR2", "Second Row"], ["ZZR3", "Third Row"]] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "in.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(header) w.writerows(rows) got = read_rows(path, header) assert len(got) == len(rows) for i, (line_no, fields) in enumerate(got): assert line_no == i + 2 assert list(fields) == rows[i] === END AC csvio-reads-numbered-rows === === AC csvio-header-only-is-empty === Intent: a file with a matching header and no data rows yields an empty list rather than an error. Requires: executable=python3; scope=test import csv import os import tempfile from ledger_core.csvio import read_rows header = ["category", "description"] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "in.csv") with open(path, "w", newline="") as fh: csv.writer(fh, lineterminator="\n").writerow(header) assert list(read_rows(path, header)) == [] === END AC csvio-header-only-is-empty === === AC csvio-missing-file-operational === Intent: an unreadable path raises the Operational error, which the CLI maps to exit 1. Requires: executable=python3; scope=test import os import tempfile from ledger_core.csvio import read_rows with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "does-not-exist.csv") try: read_rows(path, ["account", "name"]) except Exception as exc: assert type(exc).__name__ == "Operational" else: raise AssertionError("expected Operational") === END AC csvio-missing-file-operational === === AC csvio-bad-header-rejected === Intent: a header with the wrong names, the wrong order, or no content raises Rejected, which the CLI maps to exit 3. Requires: executable=python3; scope=test import csv import os import tempfile from ledger_core.csvio import read_rows header = ["account", "name"] bad_headers = [["name", "account"], ["account"], ["account", "name", "extra"], ["code", "name"]] with tempfile.TemporaryDirectory() as d: for i, bad in enumerate(bad_headers): path = os.path.join(d, f"bad{i}.csv") with open(path, "w", newline="") as fh: csv.writer(fh, lineterminator="\n").writerow(bad) try: read_rows(path, header) except Exception as exc: assert type(exc).__name__ == "Rejected" else: raise AssertionError("expected Rejected for header %r" % (bad,)) empty = os.path.join(d, "empty.csv") open(empty, "w").close() try: read_rows(empty, header) except Exception as exc: assert type(exc).__name__ == "Rejected" else: raise AssertionError("expected Rejected for an empty file") === END AC csvio-bad-header-rejected === === AC csvio-wrong-field-count-rejected === Intent: a data row with too few or too many fields raises Rejected even when the header is valid. Requires: executable=python3; scope=test import os import tempfile from ledger_core.csvio import read_rows header = ["account", "name"] bodies = ["ZZR1\n", "ZZR1,Name,Extra\n"] with tempfile.TemporaryDirectory() as d: for i, body in enumerate(bodies): path = os.path.join(d, f"row{i}.csv") with open(path, "w", newline="") as fh: fh.write(",".join(header) + "\n" + body) try: read_rows(path, header) except Exception as exc: assert type(exc).__name__ == "Rejected" else: raise AssertionError("expected Rejected for body %r" % body) === END AC csvio-wrong-field-count-rejected === === AC csvio-load-missing-file-exit-1 === Intent: through the CLI, a load naming an unreadable file exits 1, writes nothing to stdout, and stores nothing. Requires: executable=python3; scope=test import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "missing.csv") with db_session() as db: before = len(db.accounts.list()) code, out, err = cli_runner("load", "accounts", path) assert code == 1 assert out == "" assert len(db.accounts.list()) == before === END AC csvio-load-missing-file-exit-1 === ## User Acceptance - None. ## Guardrails - The reader never writes to the database or to any file. - The reader never opens a database driver. - Diagnostics go to standard error only; nothing is written to standard output. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-LoadAccounts.md === # FEATURE: Load Accounts | Field | Value | |-------|-------| | Version | 20261027 V1 | | Description | Implements `ledger load accounts ` as an all-or-nothing bulk load. | | Depends On | FEATURE-LoadCsvReader.md, FEATURE-Validation.md, DATABASE.md | | Provides | ledger load accounts | | Consumes | ledger_core.csvio, ledger_core.validation, cli.registry | ## Questions - None. ## Purpose Load accounts from a CSV file whose header is `account,name`. Every row is validated before the first write; the rows are then written together or not at all. ## Behavior 1. `ledger load accounts ` takes exactly one file argument; other counts exit 2. 2. Read the file with `ledger_core.csvio.read_rows(path, ("account", "name"))`. An unreadable file exits 1; a wrong header or wrong field count exits 3. 3. Validate every row before any write: the code is 1 to 12 characters of `A-Z0-9`, the name is 1 to 40 characters with no comma or newline, the code does not repeat within the file, and the code is not already stored. 4. Insert every row in one atomic unit. A failure at any row leaves every earlier row unstored. 5. Print `table,loaded` then `accounts,`, where `` is the number of rows inserted. 6. Any rejection exits 3 with nothing on standard output and one diagnostic line on standard error. A header-only file loads zero rows and prints `accounts,0`. ## Database Interface - `FEATURE-ACCOUNT-005` — read: list stored accounts to detect duplicate keys - supplies: — - returns: `account`, `name` - `FEATURE-ACCOUNT-001` — write: create an account - supplies: `account`, `name` - returns: `account`, `name` ## Programmatic Acceptance === AC load-accounts-success === Intent: a valid accounts file loads every row, prints the declared two CSV rows with the loaded count, and the rows are readable afterward. Requires: executable=python3; scope=test import csv import io import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session rows = [["ZZLAA1", "Load One"], ["ZZLAA2", "Load Two"], ["ZZLAA3", "Load Three"]] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "accounts.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["account", "name"]) w.writerows(rows) with db_session() as db: code, out, err = cli_runner("load", "accounts", path) print(out, err) assert code == 0 parsed = list(csv.reader(io.StringIO(out))) assert parsed == [["table", "loaded"], ["accounts", str(len(rows))]] for acct, name in rows: row = db.accounts.get(account=acct) assert row is not None got = row["name"] if isinstance(row, dict) else row.name assert got == name === END AC load-accounts-success === === AC load-accounts-rejected-row-stores-nothing === Intent: when the last row is invalid, exit 3 is returned, stdout is empty, and none of the earlier valid rows is stored. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session good = [["ZZLB%d" % i, "Good %d" % i] for i in range(1, 11)] bad = ["zzlbbad", "Lowercase Code"] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "accounts.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["account", "name"]) w.writerows(good) w.writerow(bad) with db_session() as db: before = len(db.accounts.list()) code, out, err = cli_runner("load", "accounts", path) assert code == 3 assert out == "" assert len(db.accounts.list()) == before for acct, _ in good: assert db.accounts.get(account=acct) is None === END AC load-accounts-rejected-row-stores-nothing === === AC load-accounts-invalid-fields === Intent: each invalid code or name (too long, empty, bad characters, comma in name) rejects the whole file with exit 3 and stores neither it nor the valid row before it. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session first = ["ZZLCOK", "Valid First"] bad_rows = [ ["ABCDEFGHIJKLM", "Code Too Long"], ["ZZLC-1", "Bad Char Code"], ["", "Empty Code"], ["ZZLC2", ""], ["ZZLC3", "x" * 41], ["ZZLC4", "has,comma"], ] with tempfile.TemporaryDirectory() as d: with db_session() as db: for i, bad in enumerate(bad_rows): path = os.path.join(d, "a%d.csv" % i) with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["account", "name"]) w.writerow(first) w.writerow(bad) code, out, err = cli_runner("load", "accounts", path) assert code == 3, bad assert out == "" assert db.accounts.get(account=first[0]) is None === END AC load-accounts-invalid-fields === === AC load-accounts-duplicates-rejected === Intent: a code repeated inside the file, and a code already stored, each reject the whole file with exit 3 and leave the other rows unstored. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session def write(path, rows): with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["account", "name"]) w.writerows(rows) with tempfile.TemporaryDirectory() as d: with db_session() as db: p1 = os.path.join(d, "dup_in_file.csv") write(p1, [["ZZLD1", "One"], ["ZZLD2", "Two"], ["ZZLD1", "One Again"]]) code, out, err = cli_runner("load", "accounts", p1) assert code == 3 assert out == "" assert db.accounts.get(account="ZZLD1") is None assert db.accounts.get(account="ZZLD2") is None stored = "ZZLD3" stored_name = "Already Stored" db.accounts.create(account=stored, name=stored_name) p2 = os.path.join(d, "dup_stored.csv") write(p2, [["ZZLD4", "Fresh"], [stored, "Replacement"]]) code, out, err = cli_runner("load", "accounts", p2) assert code == 3 assert out == "" assert db.accounts.get(account="ZZLD4") is None row = db.accounts.get(account=stored) got = row["name"] if isinstance(row, dict) else row.name assert got == stored_name === END AC load-accounts-duplicates-rejected === === AC load-accounts-header-and-usage === Intent: a wrong header exits 3 with nothing stored, and a missing file argument is a usage error with exit 2. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "wrong_header.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["code", "name"]) w.writerow(["ZZLE1", "Wrong Header"]) with db_session() as db: code, out, err = cli_runner("load", "accounts", path) assert code == 3 assert out == "" assert db.accounts.get(account="ZZLE1") is None code, out, err = cli_runner("load", "accounts") assert code == 2 assert out == "" === END AC load-accounts-header-and-usage === ## User Acceptance - None. ## Guardrails - No row is written until every row in the file has been validated. - Seed files are never read by application code; the file path comes only from the command line. - A failing command writes nothing to standard output. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-LoadCategories.md === # FEATURE: Load Categories | Field | Value | |-------|-------| | Version | 20261027 V1 | | Description | Implements `ledger load categories ` as an all-or-nothing bulk load. | | Depends On | FEATURE-LoadCsvReader.md, FEATURE-Validation.md, DATABASE.md | | Provides | ledger load categories | | Consumes | ledger_core.csvio, ledger_core.validation, cli.registry | ## Questions - None. ## Purpose Load categories from a CSV file whose header is `category,description`, applying the same validate-everything-then-write rule as the accounts load. ## Behavior 1. `ledger load categories ` takes exactly one file argument; other counts exit 2. 2. Read the file with `ledger_core.csvio.read_rows(path, ("category", "description"))`. An unreadable file exits 1; a wrong header or wrong field count exits 3. 3. Validate every row before any write: the code is 1 to 12 characters of `A-Z0-9`, the description is 1 to 40 characters with no comma or newline, the code does not repeat within the file, and the code is not already stored. 4. Insert every row in one atomic unit; a rejection stores none of them. 5. Print `table,loaded` then `categories,`. 6. Any rejection exits 3 with nothing on standard output and one diagnostic line on standard error. ## Database Interface - `FEATURE-CATEGORY-005` — read: list stored categories to detect duplicate keys - supplies: — - returns: `category`, `description` - `FEATURE-CATEGORY-001` — write: create a category - supplies: `category`, `description` - returns: `category`, `description` ## Programmatic Acceptance === AC load-categories-success === Intent: a valid categories file loads every row, prints the declared two CSV rows with the loaded count, and the rows are readable afterward. Requires: executable=python3; scope=test import csv import io import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session rows = [["ZZKA1", "Cat One"], ["ZZKA2", "Cat Two"], ["ZZKA3", "Cat Three"]] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "categories.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["category", "description"]) w.writerows(rows) with db_session() as db: code, out, err = cli_runner("load", "categories", path) print(out, err) assert code == 0 parsed = list(csv.reader(io.StringIO(out))) assert parsed == [["table", "loaded"], ["categories", str(len(rows))]] for cat, text in rows: row = db.categories.get(category=cat) assert row is not None got = row["description"] if isinstance(row, dict) else row.description assert got == text === END AC load-categories-success === === AC load-categories-rejected-row-stores-nothing === Intent: when a later row is invalid, exit 3 is returned, stdout is empty, and none of the earlier valid rows is stored. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session good = [["ZZKB%d" % i, "Good %d" % i] for i in range(1, 6)] bad = ["ZZKBBAD", "x" * 41] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "categories.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["category", "description"]) w.writerows(good) w.writerow(bad) with db_session() as db: before = len(db.categories.list()) code, out, err = cli_runner("load", "categories", path) assert code == 3 assert out == "" assert len(db.categories.list()) == before for cat, _ in good: assert db.categories.get(category=cat) is None === END AC load-categories-rejected-row-stores-nothing === === AC load-categories-invalid-fields === Intent: each invalid code or description (bad characters, empty, over length, comma) rejects the whole file with exit 3 and stores no row. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session first = ["ZZKCOK", "Valid First"] bad_rows = [ ["zzkc1", "Lowercase"], ["ABCDEFGHIJKLM", "Too Long Code"], ["", "Empty Code"], ["ZZKC2", ""], ["ZZKC3", "has,comma"], ] with tempfile.TemporaryDirectory() as d: with db_session() as db: for i, bad in enumerate(bad_rows): path = os.path.join(d, "c%d.csv" % i) with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["category", "description"]) w.writerow(first) w.writerow(bad) code, out, err = cli_runner("load", "categories", path) assert code == 3, bad assert out == "" assert db.categories.get(category=first[0]) is None === END AC load-categories-invalid-fields === === AC load-categories-duplicates-rejected === Intent: a code repeated inside the file, and a code already stored, each reject the whole file with exit 3 and leave the stored row unchanged. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session def write(path, rows): with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["category", "description"]) w.writerows(rows) with tempfile.TemporaryDirectory() as d: with db_session() as db: p1 = os.path.join(d, "dup_in_file.csv") write(p1, [["ZZKD1", "One"], ["ZZKD1", "One Again"]]) code, out, err = cli_runner("load", "categories", p1) assert code == 3 assert out == "" assert db.categories.get(category="ZZKD1") is None stored = "ZZKD2" stored_text = "Already Stored" db.categories.create(category=stored, description=stored_text) p2 = os.path.join(d, "dup_stored.csv") write(p2, [["ZZKD3", "Fresh"], [stored, "Replacement"]]) code, out, err = cli_runner("load", "categories", p2) assert code == 3 assert out == "" assert db.categories.get(category="ZZKD3") is None row = db.categories.get(category=stored) got = row["description"] if isinstance(row, dict) else row.description assert got == stored_text === END AC load-categories-duplicates-rejected === === AC load-categories-header-and-usage === Intent: a wrong header exits 3 with nothing stored, and a missing file argument is a usage error with exit 2. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "wrong_header.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["category", "name"]) w.writerow(["ZZKE1", "Wrong Header"]) with db_session() as db: code, out, err = cli_runner("load", "categories", path) assert code == 3 assert out == "" assert db.categories.get(category="ZZKE1") is None code, out, err = cli_runner("load", "categories") assert code == 2 assert out == "" === END AC load-categories-header-and-usage === ## User Acceptance - None. ## Guardrails - No row is written until every row in the file has been validated. - Seed files are never read by application code; the file path comes only from the command line. - A failing command writes nothing to standard output. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-LoadTransactions.md === # FEATURE: Load Transactions | Field | Value | |-------|-------| | Version | 20261027 V1 | | Description | Implements `ledger load transactions ` with full validation and the balance rule checked before any write. | | Depends On | FEATURE-LoadCsvReader.md, FEATURE-Validation.md, FEATURE-BalanceRule.md, FEATURE-LoadAccounts.md, FEATURE-LoadCategories.md, DATABASE.md | | Provides | ledger load transactions | | Consumes | ledger_core.csvio, ledger_core.validation, ledger_core.balances, cli.registry | ## Questions - None. ## Purpose Load transactions from a CSV file whose header is `txn_id,date,account,category,amount,memo`. Each row keeps the `txn_id` from the file. The file is accepted entirely or not at all. ## Behavior 1. `ledger load transactions ` takes exactly one file argument; other counts exit 2. 2. Read the file with `ledger_core.csvio.read_rows(path, ("txn_id", "date", "account", "category", "amount", "memo"))`. An unreadable file exits 1; a wrong header or wrong field count exits 3. 3. Validate every row before any write: `txn_id` is an integer, not repeated in the file and not already stored; the date is a real calendar date `YYYY-MM-DD`; the account and category exist in the store; the amount matches `-?DIGITS[.D[D]]`, has at most two decimals, and is not zero; the memo is 0 to 60 characters with no comma or newline. Amounts are converted to integer cents without floating point. 4. Apply `ledger_core.balances.check_no_negative` to all rows together as inserts. The effect of the whole file is considered at once, so a withdrawal that precedes its funding deposit in the file is accepted when the final balance is not below zero. A resulting negative balance for any account rejects the file. 5. Insert every row in one atomic unit, then print `table,loaded` and `transactions,`. 6. Any rejection exits 3, writes nothing to standard output, and stores none of the rows. ## Database Interface - `FEATURE-ACCOUNT-002` — read: confirm each referenced account exists - supplies: `account` - returns: `account` - `FEATURE-CATEGORY-002` — read: confirm each referenced category exists - supplies: `category` - returns: `category` - `FEATURE-TXN-002` — read: detect an already stored txn_id - supplies: `txn_id` - returns: `txn_id` - `FEATURE-TXN-001` — write: create a transaction - supplies: `txn_id`, `date`, `account`, `category`, `amount`, `memo` - returns: `txn_id`, `date`, `account`, `category`, `amount`, `memo` ## Programmatic Acceptance === AC load-transactions-success === Intent: a valid file loads every row keeping its txn_id, prints the declared two CSV rows, and each stored row reads back with the cents derived from the input text. Requires: executable=python3; scope=test import csv import io import os import tempfile from decimal import Decimal from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMA1", "ZZMC1" rows = [ ["920000001", "2026-01-02", acct, cat, "100.50", "deposit"], ["920000002", "2026-01-03", acct, cat, "-20.25", "withdrawal"], ["920000003", "2026-01-04", acct, cat, "7", ""], ] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "txns.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["txn_id", "date", "account", "category", "amount", "memo"]) w.writerows(rows) with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") code, out, err = cli_runner("load", "transactions", path) print(out, err) assert code == 0 parsed = list(csv.reader(io.StringIO(out))) assert parsed == [["table", "loaded"], ["transactions", str(len(rows))]] for tid, day, a, c, amt, memo in rows: row = db.transactions.get(txn_id=int(tid)) assert row is not None g = (lambda n: row[n]) if isinstance(row, dict) else (lambda n: getattr(row, n)) assert g("date") == day assert g("account") == a assert g("category") == c assert g("amount") == int(Decimal(amt) * 100) assert g("memo") == memo === END AC load-transactions-success === === AC load-transactions-unknown-reference-stores-nothing === Intent: a final row naming an unknown account rejects the whole file with exit 3, and none of the ten valid rows before it is stored. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMB1", "ZZMC2" base = 920000100 good = [[str(base + i), "2026-04-01", acct, cat, "10.00", "bad batch %d" % i] for i in range(1, 11)] bad = [str(base + 11), "2026-04-01", "ZZNOSUCH", cat, "10.00", "unknown account"] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "txns.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["txn_id", "date", "account", "category", "amount", "memo"]) w.writerows(good) w.writerow(bad) with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") code, out, err = cli_runner("load", "transactions", path) assert code == 3 assert out == "" for r in good: assert db.transactions.get(txn_id=int(r[0])) is None assert db.transactions.get(txn_id=int(bad[0])) is None unknown_cat = [[str(base + 20), "2026-04-01", acct, "ZZNOCAT", "10.00", ""]] path2 = os.path.join(d, "txns2.csv") with open(path2, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["txn_id", "date", "account", "category", "amount", "memo"]) w.writerows(unknown_cat) code, out, err = cli_runner("load", "transactions", path2) assert code == 3 assert out == "" assert db.transactions.get(txn_id=base + 20) is None === END AC load-transactions-unknown-reference-stores-nothing === === AC load-transactions-invalid-fields === Intent: each invalid date, amount, memo, or txn_id rejects the file with exit 3 and stores neither the bad row nor the valid row before it. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMC1", "ZZMC3" first_id = 920000200 first = [str(first_id), "2026-05-01", acct, cat, "10.00", "ok"] bad_rows = [ ["920000201", "2026-02-30", acct, cat, "10.00", "impossible date"], ["920000202", "2026-5-1", acct, cat, "10.00", "short date"], ["920000203", "2026-05-01", acct, cat, "1.234", "three decimals"], ["920000204", "2026-05-01", acct, cat, "0.00", "zero amount"], ["920000205", "2026-05-01", acct, cat, "abc", "not a number"], ["920000206", "2026-05-01", acct, cat, "10.00", "m" * 61], ["notanumber", "2026-05-01", acct, cat, "10.00", "bad id"], ] with tempfile.TemporaryDirectory() as d: with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") for i, bad in enumerate(bad_rows): path = os.path.join(d, "t%d.csv" % i) with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["txn_id", "date", "account", "category", "amount", "memo"]) w.writerow(first) w.writerow(bad) code, out, err = cli_runner("load", "transactions", path) assert code == 3, bad assert out == "" assert db.transactions.get(txn_id=first_id) is None === END AC load-transactions-invalid-fields === === AC load-transactions-duplicate-ids-rejected === Intent: a txn_id repeated inside the file, or already stored, rejects the whole file with exit 3 and leaves the stored row unchanged. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMD1", "ZZMC4" head = ["txn_id", "date", "account", "category", "amount", "memo"] def write(path, rows): with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(head) w.writerows(rows) with tempfile.TemporaryDirectory() as d: with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") p1 = os.path.join(d, "dup_in_file.csv") write(p1, [["920000300", "2026-06-01", acct, cat, "5.00", ""], ["920000300", "2026-06-02", acct, cat, "6.00", ""]]) code, out, err = cli_runner("load", "transactions", p1) assert code == 3 assert out == "" assert db.transactions.get(txn_id=920000300) is None stored_id = 920000310 stored_cents = 4321 db.transactions.create(txn_id=stored_id, date="2026-06-03", account=acct, category=cat, amount=stored_cents, memo="stored") p2 = os.path.join(d, "dup_stored.csv") write(p2, [["920000311", "2026-06-04", acct, cat, "1.00", ""], [str(stored_id), "2026-06-05", acct, cat, "9.99", "replacement"]]) code, out, err = cli_runner("load", "transactions", p2) assert code == 3 assert out == "" assert db.transactions.get(txn_id=920000311) is None row = db.transactions.get(txn_id=stored_id) got = row["amount"] if isinstance(row, dict) else row.amount assert got == stored_cents === END AC load-transactions-duplicate-ids-rejected === === AC load-transactions-negative-balance-rejected === Intent: a file whose combined effect leaves an account below zero is rejected with exit 3 and stores no row, even though each row is individually well formed. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZME1", "ZZMC5" head = ["txn_id", "date", "account", "category", "amount", "memo"] rows = [ ["920000400", "2026-07-01", acct, cat, "1.00", "deposit"], ["920000401", "2026-07-02", acct, cat, "-2.00", "overdraw"], ] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "txns.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(head) w.writerows(rows) with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") code, out, err = cli_runner("load", "transactions", path) assert code == 3 assert out == "" for r in rows: assert db.transactions.get(txn_id=int(r[0])) is None assert db.transactions.list(account=acct) == [] === END AC load-transactions-negative-balance-rejected === === AC load-transactions-balance-considers-whole-file === Intent: a withdrawal listed before the deposit that funds it is accepted because the balance rule uses the combined effect of all rows, and both rows are stored. Requires: executable=python3; scope=test import csv import os import tempfile from decimal import Decimal from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMF1", "ZZMC6" head = ["txn_id", "date", "account", "category", "amount", "memo"] rows = [ ["920000500", "2026-08-01", acct, cat, "-3.00", "withdraw first"], ["920000501", "2026-08-02", acct, cat, "5.00", "deposit second"], ] with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "txns.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(head) w.writerows(rows) with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") code, out, err = cli_runner("load", "transactions", path) print(out, err) assert code == 0 stored = db.transactions.list(account=acct) total = sum((r["amount"] if isinstance(r, dict) else r.amount) for r in stored) assert total == sum(int(Decimal(r[4]) * 100) for r in rows) assert len(stored) == len(rows) === END AC load-transactions-balance-considers-whole-file === === AC load-transactions-header-and-usage === Intent: a wrong header exits 3 with nothing stored, an unreadable file exits 1, and a missing file argument exits 2. Requires: executable=python3; scope=test import csv import os import tempfile from cli.testing import cli_runner from persistence.testing import db_session acct, cat = "ZZMG1", "ZZMC7" with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "wrong_header.csv") with open(path, "w", newline="") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["id", "date", "account", "category", "amount", "memo"]) w.writerow(["920000600", "2026-09-01", acct, cat, "1.00", ""]) with db_session() as db: db.accounts.create(account=acct, name="Load Txn Account") db.categories.create(category=cat, description="Load Txn Category") code, out, err = cli_runner("load", "transactions", path) assert code == 3 assert out == "" assert db.transactions.get(txn_id=920000600) is None code, out, err = cli_runner("load", "transactions", os.path.join(d, "missing.csv")) assert code == 1 assert out == "" code, out, err = cli_runner("load", "transactions") assert code == 2 assert out == "" === END AC load-transactions-header-and-usage === ## User Acceptance - None. ## Guardrails - No row is written until every row has passed validation and the balance rule. - Amounts are integer cents; floating point is never used for money. - The file's `txn_id` values are kept; none is renumbered. - A failing command writes nothing to standard output. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-AccountAdd.md === # FEATURE: Account Add | Field | Value | |-------|-------| | Version | 20261027 V1 | | Description | Implements `ledger account add ` and the shared `account_row` helper. | | Depends On | FEATURE-CliEntry.md, FEATURE-Validation.md, DATABASE.md | | Provides | ledger account add, ledger_core.accounts | | Consumes | ledger_core.validation, ledger_core.money, cli.registry | ## Questions - None. ## Purpose Create one account and print its row. The module `ledger_core.accounts` also exports the helper the other account commands use to build an account row from live data. ## Behavior 1. `ledger account add ` takes exactly two arguments; other counts exit 2. 2. Validate the code (1 to 12 characters of `A-Z0-9`) and the name (1 to 40 characters, no comma or newline). A violation exits 3. 3. A code that is already stored exits 3 and leaves the stored account unchanged. 4. Insert the account, then print CSV: the header `account,name,transactions,balance` and one row with the new account, its name, `0` transactions, and balance `0.00`. 5. A failing command writes nothing to standard output. ## Interface `ledger_core.accounts.account_row(db, code)` returns `None` when the account is absent, otherwise the tuple `(account, name, transactions, balance_cents)` where `transactions` is the number of that account's stored transactions and `balance_cents` is the integer sum of their amounts. Both are computed from the database on every call. Formatting the balance as text is done by `ledger_core.money.format_cents` in the command, not in the helper. ## Database Interface - `FEATURE-ACCOUNT-002` — read: get an account by code - supplies: `account` - returns: `account`, `name` - `FEATURE-ACCOUNT-001` — write: create an account - supplies: `account`, `name` - returns: `account`, `name` - `FEATURE-TXN-005` — read: list an account's transactions to count and sum them - supplies: `account` - returns: `amount` ## Programmatic Acceptance === AC account-add-success === Intent: adding a new account exits 0, prints the header and one row with zero transactions and a zero balance, and the account reads back from the store. Requires: executable=python3; scope=test import csv import io from cli.testing import cli_runner from persistence.testing import db_session acct = "ZZNA1" name = "Add Probe" with db_session() as db: code, out, err = cli_runner("account", "add", acct, name) print(out, err) assert code == 0 parsed = list(csv.reader(io.StringIO(out))) assert parsed[0] == ["account", "name", "transactions", "balance"] assert parsed[1] == [acct, name, "0", "0.00"] assert len(parsed) == 2 row = db.accounts.get(account=acct) assert row is not None got = row["name"] if isinstance(row, dict) else row.name assert got == name === END AC account-add-success === === AC account-add-duplicate-rejected === Intent: adding a code that already exists exits 3, prints nothing, and leaves the stored name unchanged. Requires: executable=python3; scope=test from cli.testing import cli_runner from persistence.testing import db_session acct = "ZZNB1" original = "Original Name" with db_session() as db: code, out, err = cli_runner("account", "add", acct, original) assert code == 0 code, out, err = cli_runner("account", "add", acct, "Different Name") assert code == 3 assert out == "" row = db.accounts.get(account=acct) got = row["name"] if isinstance(row, dict) else row.name assert got == original === END AC account-add-duplicate-rejected === === AC account-add-invalid-code === Intent: lowercase letters, a code longer than 12 characters, a bad character, and an empty code each exit 3 with no output and store no account. Requires: executable=python3; scope=test from cli.testing import cli_runner from persistence.testing import db_session bad_codes = ["zznc1", "ABCDEFGHIJKLM", "ZZ-NC", "ZZ NC", ""] with db_session() as db: before = len(db.accounts.list()) for bad in bad_codes: code, out, err = cli_runner("account", "add", bad, "Valid Name") assert code == 3, bad assert out == "" assert len(db.accounts.list()) == before === END AC account-add-invalid-code === === AC account-add-invalid-name === Intent: an empty name, a name over 40 characters, and a name containing a comma each exit 3 with no output and store no account. Requires: executable=python3; scope=test from cli.testing import cli_runner from persistence.testing import db_session acct = "ZZND1" bad_names = ["", "n" * 41, "has,comma"] with db_session() as db: for bad in bad_names: code, out, err = cli_runner("account", "add", acct, bad) assert code == 3, bad assert out == "" assert db.accounts.get(account=acct) is None === END AC account-add-invalid-name === === AC account-add-boundary-lengths === Intent: a 12-character code and a 40-character name are the largest accepted values and are stored whole. Requires: executable=python3; scope=test from cli.testing import cli_runner from persistence.testing import db_session acct = "Z" * 12 name = "n" * 40 with db_session() as db: code, out, err = cli_runner("account", "add", acct, name) assert code == 0 row = db.accounts.get(account=acct) assert row is not None got = row["name"] if isinstance(row, dict) else row.name assert got == name === END AC account-add-boundary-lengths === === AC account-add-usage-errors === Intent: the wrong number of arguments is a usage error with exit 2 and no output. Requires: executable=python3; scope=test from cli.testing import cli_runner for args in (("account", "add"), ("account", "add", "ZZNE1"), ("account", "add", "ZZNE1", "Name", "Extra")): code, out, err = cli_runner(*args) assert code == 2, args assert out == "" === END AC account-add-usage-errors === === AC account-row-helper === Intent: account_row reports the live transaction count and the integer-cent balance computed from stored transactions, and None for an absent account. Requires: executable=python3; scope=test from persistence.testing import db_session from ledger_core.accounts import account_row acct, cat = "ZZNF1", "ZZNFC" name = "Helper Probe" amounts = [10000, -2550, 1] with db_session() as db: db.accounts.create(account=acct, name=name) db.categories.create(category=cat, description="Helper Category") for i, cents in enumerate(amounts): db.transactions.create(txn_id=930000000 + i, date="2026-03-01", account=acct, category=cat, amount=cents, memo="") row = account_row(db, acct) assert row is not None assert tuple(row) == (acct, name, len(amounts), sum(amounts)) assert account_row(db, "ZZNFNONE") is None === END AC account-row-helper === ## User Acceptance - None. ## Guardrails - Validation completes before the insert; a rejected add changes nothing. - The balance is integer cents in the helper and is formatted only for output. - A failing command writes nothing to standard output. === END ARTIFACT ===