askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_financial_statements.py · 13.9 KB · 320 lines
| 1 | """Tests for object_finance.profit_and_loss() / .balance_sheet() and the |
| 2 | site_statements page object (packages/app-finance/objects/site/ |
| 3 | statements.py) -- the two financial statements plan/accounting-coverage- |
| 4 | and-usability.md's M1 calls the highest-value missing piece. |
| 5 | |
| 6 | Fixture style follows tests/test_books_spine.py's setup_env(): a bare |
| 7 | data_dir built from this package's own schemas plus hand-written TSV |
| 8 | collection headers, with fin_accounts/fin_journals/fin_journal_lines |
| 9 | records created through object_records.create_collection_record() (never |
| 10 | hand-typed TSV rows) so every write goes through the same schema |
| 11 | validation and defaulting a real request would. Journals are posted the |
| 12 | same way tests/test_books_spine.py's make_posted_journal() does: create |
| 13 | draft, add lines, then update status -> posted directly -- this is |
| 14 | exactly the "posting is a bare status flip, balance NOT enforced" |
| 15 | behavior fin_journals.json's own status field documents, and it is |
| 16 | deliberately used here (rather than object_finance.compose_posted_journal, |
| 17 | which verifies balance before posting) to construct the one test case |
| 18 | that needs an actually-unbalanced posted journal on the books. |
| 19 | """ |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import pathlib |
| 23 | |
| 24 | import object_execution |
| 25 | import object_finance |
| 26 | import object_records |
| 27 | import python_object_runtime |
| 28 | from conftest import stage_collection |
| 29 | |
| 30 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 31 | PACKAGES = REPO_ROOT / "packages" |
| 32 | FINANCE_OBJECTS = PACKAGES / "app-finance" / "objects" |
| 33 | |
| 34 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 35 | |
| 36 | # A small chart of accounts reused across tests. |
| 37 | CASH, AR, LOAN, EQUITY, REV, EXP = ( |
| 38 | "acct-cash", "acct-ar", "acct-loan", "acct-equity", "acct-rev", "acct-exp", |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | def setup_env(tmp_path, monkeypatch): |
| 43 | data_dir = tmp_path / "data" |
| 44 | for name in ("fin_accounts", "fin_journals", "fin_journal_lines"): |
| 45 | stage_collection(data_dir, "app-finance", name) |
| 46 | |
| 47 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 48 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects-unused")) |
| 49 | return data_dir |
| 50 | |
| 51 | |
| 52 | def make_account(data_dir, account_id, name, account_type, owner="dan", code=""): |
| 53 | object_records.create_collection_record( |
| 54 | "fin_accounts", |
| 55 | {"id": account_id, "name": name, "code": code, "account_type": account_type, |
| 56 | "owner_id": owner}, |
| 57 | base_dir=data_dir, |
| 58 | ) |
| 59 | |
| 60 | |
| 61 | def make_default_chart(data_dir, owner="dan", prefix=""): |
| 62 | # Account ids are globally unique across all owners (fin_accounts has |
| 63 | # no per-owner namespacing), so a second owner's chart needs distinct |
| 64 | # ids -- prefix disambiguates when a test builds more than one owner's |
| 65 | # books in the same data_dir. |
| 66 | make_account(data_dir, prefix + CASH, "Cash", "asset", owner=owner, code="1000") |
| 67 | make_account(data_dir, prefix + AR, "Accounts Receivable", "asset", owner=owner, code="1100") |
| 68 | make_account(data_dir, prefix + LOAN, "Loan Payable", "liability", owner=owner, code="2000") |
| 69 | make_account(data_dir, prefix + EQUITY, "Owner Equity", "equity", owner=owner, code="3000") |
| 70 | make_account(data_dir, prefix + REV, "Revenue", "income", owner=owner, code="4000") |
| 71 | make_account(data_dir, prefix + EXP, "Expenses", "expense", owner=owner, code="5000") |
| 72 | |
| 73 | |
| 74 | def make_journal(data_dir, jid, *, date, lines, status="posted", owner="dan"): |
| 75 | """Create a journal with the given (account_id, debit_cents, credit_cents) |
| 76 | line specs and flip it to `status` directly (a bare field update, same |
| 77 | as tests/test_books_spine.py's make_posted_journal) -- no balance check |
| 78 | happens here, which is the point for the unbalanced-ledger test below. |
| 79 | """ |
| 80 | object_records.create_collection_record( |
| 81 | "fin_journals", |
| 82 | {"id": jid, "date": date, "description": f"journal {jid}", |
| 83 | "status": "draft", "kind": "standard", "owner_id": owner}, |
| 84 | base_dir=data_dir, |
| 85 | ) |
| 86 | for i, (account_id, debit_cents, credit_cents) in enumerate(lines): |
| 87 | object_records.create_collection_record( |
| 88 | "fin_journal_lines", |
| 89 | {"id": f"{jid}-l{i}", "journal_id": jid, "account_id": account_id, |
| 90 | "debit_cents": str(debit_cents), "credit_cents": str(credit_cents), |
| 91 | "owner_id": owner}, |
| 92 | base_dir=data_dir, |
| 93 | ) |
| 94 | if status != "draft": |
| 95 | object_records.update_collection_record( |
| 96 | "fin_journals", jid, {"status": status}, base_dir=data_dir) |
| 97 | |
| 98 | |
| 99 | def call_statements(payload): |
| 100 | return object_execution.execute_object( |
| 101 | RUNTIME, |
| 102 | object_execution.ObjectExecutionRequest( |
| 103 | "site_statements", method="GET", payload=payload), |
| 104 | roots=[FINANCE_OBJECTS], |
| 105 | ) |
| 106 | |
| 107 | |
| 108 | # --------------------------------------------------------------------------- |
| 109 | # profit_and_loss() |
| 110 | # --------------------------------------------------------------------------- |
| 111 | |
| 112 | def test_pl_sign_conventions_and_net_income(tmp_path, monkeypatch): |
| 113 | data_dir = setup_env(tmp_path, monkeypatch) |
| 114 | make_default_chart(data_dir) |
| 115 | # A sale: debit cash, credit revenue -- revenue is credit-normal, so |
| 116 | # its P&L amount should be positive (credit - debit = 1000 - 0). |
| 117 | # An expense paid in cash: debit expense, credit cash -- expense is |
| 118 | # debit-normal, so its amount should also be positive (1000 - 0 = 400... ) |
| 119 | make_journal(data_dir, "j1", date="2026-07-10", |
| 120 | lines=[(CASH, 1000, 0), (REV, 0, 1000)]) |
| 121 | make_journal(data_dir, "j2", date="2026-07-11", |
| 122 | lines=[(EXP, 400, 0), (CASH, 0, 400)]) |
| 123 | |
| 124 | pl = object_finance.profit_and_loss(base_dir=data_dir, owner="dan") |
| 125 | income_by_id = {r["account_id"]: r["amount_cents"] for r in pl["income"]} |
| 126 | expense_by_id = {r["account_id"]: r["amount_cents"] for r in pl["expenses"]} |
| 127 | |
| 128 | assert income_by_id[REV] == 1000 # credit-normal: reported positive |
| 129 | assert expense_by_id[EXP] == 400 # debit-normal: reported positive |
| 130 | assert pl["total_income_cents"] == 1000 |
| 131 | assert pl["total_expenses_cents"] == 400 |
| 132 | assert pl["net_income_cents"] == 600 # income - expenses |
| 133 | # asset/liability/equity accounts never appear on a P&L |
| 134 | assert all(r["account_id"] != CASH for r in pl["income"] + pl["expenses"]) |
| 135 | |
| 136 | |
| 137 | def test_pl_date_filtering_excludes_out_of_period(tmp_path, monkeypatch): |
| 138 | data_dir = setup_env(tmp_path, monkeypatch) |
| 139 | make_default_chart(data_dir) |
| 140 | make_journal(data_dir, "jan", date="2026-01-15", |
| 141 | lines=[(CASH, 100, 0), (REV, 0, 100)]) |
| 142 | make_journal(data_dir, "jul", date="2026-07-15", |
| 143 | lines=[(CASH, 200, 0), (REV, 0, 200)]) |
| 144 | |
| 145 | pl = object_finance.profit_and_loss( |
| 146 | base_dir=data_dir, owner="dan", start="2026-07-01", end="2026-07-31") |
| 147 | assert pl["total_income_cents"] == 200 # only the July journal counts |
| 148 | |
| 149 | pl_all = object_finance.profit_and_loss(base_dir=data_dir, owner="dan") |
| 150 | assert pl_all["total_income_cents"] == 300 # blank bounds = unbounded |
| 151 | |
| 152 | |
| 153 | def test_pl_excludes_draft_journals(tmp_path, monkeypatch): |
| 154 | data_dir = setup_env(tmp_path, monkeypatch) |
| 155 | make_default_chart(data_dir) |
| 156 | make_journal(data_dir, "draft1", date="2026-07-10", |
| 157 | lines=[(CASH, 500, 0), (REV, 0, 500)], status="draft") |
| 158 | pl = object_finance.profit_and_loss(base_dir=data_dir, owner="dan") |
| 159 | assert pl["income"] == [] |
| 160 | assert pl["total_income_cents"] == 0 |
| 161 | assert pl["net_income_cents"] == 0 |
| 162 | |
| 163 | |
| 164 | def test_pl_owner_scoping(tmp_path, monkeypatch): |
| 165 | data_dir = setup_env(tmp_path, monkeypatch) |
| 166 | make_default_chart(data_dir, owner="dan") |
| 167 | make_default_chart(data_dir, owner="mallory", prefix="m-") |
| 168 | make_journal(data_dir, "j-dan", date="2026-07-10", |
| 169 | lines=[(CASH, 1000, 0), (REV, 0, 1000)], owner="dan") |
| 170 | make_journal(data_dir, "j-mallory", date="2026-07-10", |
| 171 | lines=[("m-" + CASH, 9999, 0), ("m-" + REV, 0, 9999)], owner="mallory") |
| 172 | |
| 173 | pl = object_finance.profit_and_loss(base_dir=data_dir, owner="dan") |
| 174 | assert pl["total_income_cents"] == 1000 # mallory's journal never appears |
| 175 | |
| 176 | |
| 177 | def test_pl_empty_ledger_returns_zeros(tmp_path, monkeypatch): |
| 178 | data_dir = setup_env(tmp_path, monkeypatch) |
| 179 | pl = object_finance.profit_and_loss(base_dir=data_dir, owner="dan") |
| 180 | assert pl == { |
| 181 | "period": {"start": "", "end": ""}, |
| 182 | "income": [], |
| 183 | "expenses": [], |
| 184 | "total_income_cents": 0, |
| 185 | "total_expenses_cents": 0, |
| 186 | "net_income_cents": 0, |
| 187 | } |
| 188 | |
| 189 | |
| 190 | # --------------------------------------------------------------------------- |
| 191 | # balance_sheet() |
| 192 | # --------------------------------------------------------------------------- |
| 193 | |
| 194 | def test_balance_sheet_balances_when_net_income_included(tmp_path, monkeypatch): |
| 195 | data_dir = setup_env(tmp_path, monkeypatch) |
| 196 | make_default_chart(data_dir) |
| 197 | # Owner contributes cash (equity), then a cash sale (asset up, income |
| 198 | # up). Assets: cash 1500. Liabilities: 0. Equity: owner equity 500 + |
| 199 | # current period earnings (net income) 1000 = 1500. Balances. |
| 200 | make_journal(data_dir, "j1", date="2026-07-01", |
| 201 | lines=[(CASH, 500, 0), (EQUITY, 0, 500)]) |
| 202 | make_journal(data_dir, "j2", date="2026-07-10", |
| 203 | lines=[(CASH, 1000, 0), (REV, 0, 1000)]) |
| 204 | |
| 205 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan") |
| 206 | assert bs["total_assets_cents"] == 1500 |
| 207 | assert bs["total_liabilities_cents"] == 0 |
| 208 | assert bs["total_equity_cents"] == 1500 # 500 stored + 1000 derived earnings |
| 209 | assert bs["balances"] is True |
| 210 | assert bs["difference_cents"] == 0 |
| 211 | |
| 212 | earnings_rows = [r for r in bs["equity"] if r["account_name"] == "Current period earnings"] |
| 213 | assert len(earnings_rows) == 1 |
| 214 | assert earnings_rows[0]["account_id"] == "" |
| 215 | assert earnings_rows[0]["amount_cents"] == 1000 |
| 216 | |
| 217 | |
| 218 | def test_balance_sheet_reports_unbalanced_ledger_loudly(tmp_path, monkeypatch): |
| 219 | data_dir = setup_env(tmp_path, monkeypatch) |
| 220 | make_default_chart(data_dir) |
| 221 | # A lopsided posted journal: debit cash 700, credit nothing. This can |
| 222 | # only happen because posting is a bare status flip that never checks |
| 223 | # is_balanced (fin_journals.json's own documented gap) -- exactly the |
| 224 | # scenario balance_sheet()'s difference_cents exists to surface. |
| 225 | make_journal(data_dir, "bad", date="2026-07-05", lines=[(CASH, 700, 0)]) |
| 226 | |
| 227 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan") |
| 228 | assert bs["balances"] is False |
| 229 | assert bs["difference_cents"] == 700 # assets 700, liabilities+equity 0 |
| 230 | assert bs["total_assets_cents"] == 700 |
| 231 | |
| 232 | |
| 233 | def test_balance_sheet_excludes_draft_journals(tmp_path, monkeypatch): |
| 234 | data_dir = setup_env(tmp_path, monkeypatch) |
| 235 | make_default_chart(data_dir) |
| 236 | make_journal(data_dir, "draft1", date="2026-07-05", |
| 237 | lines=[(CASH, 700, 0), (EQUITY, 0, 700)], status="draft") |
| 238 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan") |
| 239 | assert bs["total_assets_cents"] == 0 |
| 240 | assert bs["balances"] is True |
| 241 | assert bs["difference_cents"] == 0 |
| 242 | |
| 243 | |
| 244 | def test_balance_sheet_owner_scoping(tmp_path, monkeypatch): |
| 245 | data_dir = setup_env(tmp_path, monkeypatch) |
| 246 | make_default_chart(data_dir, owner="dan") |
| 247 | make_default_chart(data_dir, owner="mallory", prefix="m-") |
| 248 | make_journal(data_dir, "j-dan", date="2026-07-01", |
| 249 | lines=[(CASH, 100, 0), (EQUITY, 0, 100)], owner="dan") |
| 250 | make_journal(data_dir, "j-mallory", date="2026-07-01", |
| 251 | lines=[("m-" + CASH, 5000, 0), ("m-" + EQUITY, 0, 5000)], owner="mallory") |
| 252 | |
| 253 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan") |
| 254 | assert bs["total_assets_cents"] == 100 # mallory's books never appear |
| 255 | assert bs["balances"] is True |
| 256 | |
| 257 | |
| 258 | def test_balance_sheet_empty_ledger_returns_zeros(tmp_path, monkeypatch): |
| 259 | data_dir = setup_env(tmp_path, monkeypatch) |
| 260 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan") |
| 261 | assert bs["total_assets_cents"] == 0 |
| 262 | assert bs["total_liabilities_cents"] == 0 |
| 263 | assert bs["total_equity_cents"] == 0 |
| 264 | assert bs["balances"] is True |
| 265 | assert bs["difference_cents"] == 0 |
| 266 | # The synthetic earnings line is still present, just zero. |
| 267 | assert bs["equity"][-1]["account_name"] == "Current period earnings" |
| 268 | assert bs["equity"][-1]["amount_cents"] == 0 |
| 269 | |
| 270 | |
| 271 | def test_balance_sheet_as_of_filters_later_activity(tmp_path, monkeypatch): |
| 272 | data_dir = setup_env(tmp_path, monkeypatch) |
| 273 | make_default_chart(data_dir) |
| 274 | make_journal(data_dir, "early", date="2026-01-01", |
| 275 | lines=[(CASH, 100, 0), (EQUITY, 0, 100)]) |
| 276 | make_journal(data_dir, "later", date="2026-12-01", |
| 277 | lines=[(CASH, 200, 0), (EQUITY, 0, 200)]) |
| 278 | |
| 279 | bs = object_finance.balance_sheet(base_dir=data_dir, owner="dan", as_of="2026-06-30") |
| 280 | assert bs["total_assets_cents"] == 100 |
| 281 | assert bs["balances"] is True |
| 282 | |
| 283 | |
| 284 | # --------------------------------------------------------------------------- |
| 285 | # site_statements page |
| 286 | # --------------------------------------------------------------------------- |
| 287 | |
| 288 | def test_page_renders_statements_for_signed_in_user(tmp_path, monkeypatch): |
| 289 | data_dir = setup_env(tmp_path, monkeypatch) |
| 290 | make_default_chart(data_dir) |
| 291 | make_journal(data_dir, "j1", date="2026-07-10", |
| 292 | lines=[(CASH, 1000, 0), (REV, 0, 1000)]) |
| 293 | |
| 294 | result = call_statements({"_identity": {"user_id": "dan"}}) |
| 295 | assert result.ok, result.error |
| 296 | body = result.result["body"] |
| 297 | assert "Profit & Loss" in body |
| 298 | assert "Balance Sheet" in body |
| 299 | assert "Revenue" in body |
| 300 | assert "USD 10.00" in body # 1000 cents formatted |
| 301 | |
| 302 | |
| 303 | def test_page_shows_signin_prompt_for_anonymous(tmp_path, monkeypatch): |
| 304 | setup_env(tmp_path, monkeypatch) |
| 305 | result = call_statements({}) |
| 306 | assert result.ok, result.error |
| 307 | body = result.result["body"] |
| 308 | assert "Sign in" in body |
| 309 | assert "Profit" not in body |
| 310 | |
| 311 | |
| 312 | def test_page_shows_unbalanced_warning(tmp_path, monkeypatch): |
| 313 | data_dir = setup_env(tmp_path, monkeypatch) |
| 314 | make_default_chart(data_dir) |
| 315 | make_journal(data_dir, "bad", date="2026-07-05", lines=[(CASH, 700, 0)]) |
| 316 | |
| 317 | result = call_statements({"_identity": {"user_id": "dan"}}) |
| 318 | assert result.ok, result.error |
| 319 | body = result.result["body"] |
| 320 | assert "does NOT balance" in body or "does not balance" in body.lower() |