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_wallet_books.py · 13.7 KB · 329 lines
| 1 | """Wallet money reaching the books, and proving it still adds up. |
| 2 | |
| 3 | The gap: wallet_entries recorded every movement of customer money and |
| 4 | none of it reached fin_journals. app-payments' system_books composed |
| 5 | journals for payments/refunds/invoices; nothing did the same for the |
| 6 | prepaid wallet, so a server charging real money for template runs showed |
| 7 | zero revenue on the P&L and neither the cash nor the customer liability |
| 8 | on the balance sheet. |
| 9 | |
| 10 | The assertion that carries the most weight in this file is that **a |
| 11 | top-up is not revenue**. It is the flattering mistake -- book top-ups as |
| 12 | income and every unspent dollar in a customer wallet inflates profit |
| 13 | while the debt owed for it goes unrecorded. The policy tests below pin |
| 14 | the deferral explicitly, because a future refactor that "simplifies" |
| 15 | top-up straight to revenue would pass every balance check and every |
| 16 | idempotency test while making the books lie. |
| 17 | """ |
| 18 | |
| 19 | import pathlib |
| 20 | |
| 21 | import pytest |
| 22 | from conftest import schema_header, stage_collection |
| 23 | |
| 24 | import object_billing |
| 25 | import object_execution |
| 26 | import object_finance |
| 27 | import object_records |
| 28 | import python_object_runtime |
| 29 | |
| 30 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 31 | BILLING_OBJECTS = REPO_ROOT / "packages" / "app-billing" / "objects" |
| 32 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 33 | |
| 34 | CASH, FUNDS, REVENUE, PROMO, ADJUST = ( |
| 35 | "acct-cash", "acct-customer-funds", "acct-revenue", |
| 36 | "acct-promo", "acct-adjust", |
| 37 | ) |
| 38 | ALL_ACCOUNTS = { |
| 39 | "cash": CASH, "customer_funds": FUNDS, "revenue": REVENUE, |
| 40 | "promo_expense": PROMO, "adjustment": ADJUST, |
| 41 | } |
| 42 | |
| 43 | |
| 44 | # --- the accounting policy (pure) ----------------------------------------------- |
| 45 | |
| 46 | def test_a_topup_is_a_liability_not_revenue(): |
| 47 | """THE assertion. Cash arrives and service is owed; nothing is earned |
| 48 | until the work is done. Booking this to revenue overstates income by |
| 49 | every unspent cent and understates what is owed by the same amount.""" |
| 50 | posting = object_billing.wallet_posting("topup", 5000, ALL_ACCOUNTS) |
| 51 | assert posting == {"debit": CASH, "credit": FUNDS, "amount_minor": 5000} |
| 52 | assert REVENUE not in posting.values() |
| 53 | |
| 54 | |
| 55 | def test_a_debit_is_where_revenue_is_finally_earned(): |
| 56 | posting = object_billing.wallet_posting("debit", -25, ALL_ACCOUNTS) |
| 57 | assert posting == {"debit": FUNDS, "credit": REVENUE, "amount_minor": 25} |
| 58 | |
| 59 | |
| 60 | def test_a_refund_un_earns_revenue_without_moving_cash(): |
| 61 | """Credit returned to a wallet reverses the earning, but the money |
| 62 | never left the wallet, so cash must not appear.""" |
| 63 | posting = object_billing.wallet_posting("refund", 25, ALL_ACCOUNTS) |
| 64 | assert posting == {"debit": REVENUE, "credit": FUNDS, "amount_minor": 25} |
| 65 | assert CASH not in posting.values() |
| 66 | |
| 67 | |
| 68 | def test_promo_credit_costs_us_something(): |
| 69 | posting = object_billing.wallet_posting("promo", 500, ALL_ACCOUNTS) |
| 70 | assert posting == {"debit": PROMO, "credit": FUNDS, "amount_minor": 500} |
| 71 | |
| 72 | |
| 73 | def test_an_adjustment_gets_its_own_account_not_revenue(): |
| 74 | """Burying corrections in revenue is how a P&L stops being auditable.""" |
| 75 | posting = object_billing.wallet_posting("adjustment", -100, ALL_ACCOUNTS) |
| 76 | assert posting == {"debit": FUNDS, "credit": ADJUST, "amount_minor": 100} |
| 77 | |
| 78 | |
| 79 | @pytest.mark.parametrize("kind", ["hold", "release"]) |
| 80 | def test_holds_compose_nothing_and_say_why(kind): |
| 81 | """Doctrine, not an omission: ring-fencing funds inside the same |
| 82 | liability is not an economic event.""" |
| 83 | posting = object_billing.wallet_posting(kind, -25, ALL_ACCOUNTS) |
| 84 | assert "skip" in posting |
| 85 | assert "never spent" in posting["skip"] |
| 86 | |
| 87 | |
| 88 | def test_a_negative_amount_never_reaches_a_journal_line(): |
| 89 | """Direction is carried by WHICH account, never by a sign -- a |
| 90 | negative debit_cents is rejected by the composer, so a policy that |
| 91 | leaked one would fail at post time instead of here.""" |
| 92 | for kind, amount in [("topup", 5000), ("debit", -25), ("refund", 25), |
| 93 | ("promo", 500), ("adjustment", -100), ("topup", -300)]: |
| 94 | posting = object_billing.wallet_posting(kind, amount, ALL_ACCOUNTS) |
| 95 | assert posting["amount_minor"] > 0, (kind, amount) |
| 96 | |
| 97 | |
| 98 | def test_an_unconfigured_account_skips_and_names_the_setting(): |
| 99 | """Never guess an account. Posting real money somewhere plausible is |
| 100 | worse than not posting, and the operator needs the key to fix.""" |
| 101 | posting = object_billing.wallet_posting("topup", 5000, {"cash": CASH}) |
| 102 | assert "skip" in posting |
| 103 | assert "billing.journal.customer_funds_account" in posting["skip"] |
| 104 | |
| 105 | |
| 106 | def test_an_unknown_kind_refuses_rather_than_inventing_a_policy(): |
| 107 | posting = object_billing.wallet_posting("mystery", 100, ALL_ACCOUNTS) |
| 108 | assert "no accounting policy" in posting["skip"] |
| 109 | |
| 110 | |
| 111 | def test_a_wrong_signed_movement_is_refused(): |
| 112 | assert "skip" in object_billing.wallet_posting("debit", 25, ALL_ACCOUNTS) |
| 113 | assert "skip" in object_billing.wallet_posting("refund", -25, ALL_ACCOUNTS) |
| 114 | |
| 115 | |
| 116 | # --- the reconciliation invariant ----------------------------------------------- |
| 117 | |
| 118 | def test_reconciliation_balances_when_the_books_match(): |
| 119 | result = object_billing.customer_funds_reconciliation([3000, 1750], 250, 5000) |
| 120 | assert result["owed_to_customers_minor"] == 4750 |
| 121 | assert result["booked_liability_minor"] == 4750 |
| 122 | assert result["balanced"] is True |
| 123 | |
| 124 | |
| 125 | def test_an_in_flight_hold_does_not_look_like_a_discrepancy(): |
| 126 | """THE false-alarm test. A wallet with an open hold reports a balance |
| 127 | below what its owner is owed -- the money is still theirs -- while |
| 128 | the books correctly composed nothing for the hold. A reconciliation |
| 129 | that ignores holds reports a difference every time a template run is |
| 130 | in progress, and a report that cries wolf is one nobody reads.""" |
| 131 | entries = [ |
| 132 | {"kind": "topup", "amount_minor": "5000"}, |
| 133 | {"kind": "hold", "amount_minor": "-25"}, # in flight, unreleased |
| 134 | ] |
| 135 | holds = object_billing.outstanding_holds_minor(entries) |
| 136 | assert holds == 25 |
| 137 | |
| 138 | balanced = object_billing.customer_funds_reconciliation( |
| 139 | [4975], 0, 5000, outstanding_holds=holds) |
| 140 | assert balanced["balanced"] is True, balanced |
| 141 | |
| 142 | naive = object_billing.customer_funds_reconciliation([4975], 0, 5000) |
| 143 | assert naive["balanced"] is False # what the wrong version would report |
| 144 | |
| 145 | |
| 146 | def test_a_settled_hold_cancels_itself(): |
| 147 | entries = [ |
| 148 | {"kind": "hold", "amount_minor": "-25"}, |
| 149 | {"kind": "release", "amount_minor": "25"}, |
| 150 | ] |
| 151 | assert object_billing.outstanding_holds_minor(entries) == 0 |
| 152 | |
| 153 | |
| 154 | def test_a_real_shortfall_is_still_caught(): |
| 155 | """The report must not be so forgiving it can never fail.""" |
| 156 | result = object_billing.customer_funds_reconciliation([5000], 0, 4000) |
| 157 | assert result["balanced"] is False |
| 158 | assert result["difference_minor"] == 1000 |
| 159 | |
| 160 | |
| 161 | # --- the composer, end to end --------------------------------------------------- |
| 162 | |
| 163 | def setup_books(tmp_path, monkeypatch, *, books=True, configured=True): |
| 164 | data_dir = tmp_path / "data" |
| 165 | for pkg, name in (("app-billing", "wallets"), ("app-billing", "wallet_entries")): |
| 166 | stage_collection(data_dir, pkg, name) |
| 167 | |
| 168 | settings = "" |
| 169 | if configured: |
| 170 | settings = (f"s1\tbilling.journal.cash_account\t{CASH}\t\n" |
| 171 | f"s2\tbilling.journal.customer_funds_account\t{FUNDS}\t\n" |
| 172 | f"s3\tbilling.journal.revenue_account\t{REVENUE}\t\n") |
| 173 | stage_collection(data_dir, "app-settings", "app_settings", rows=settings) |
| 174 | |
| 175 | if books: |
| 176 | # Field-order pinned against the real schema, like test_books_spine: |
| 177 | # a later schema edit must not silently shift values into the wrong |
| 178 | # columns. |
| 179 | fields = schema_header("app-finance", "fin_accounts").strip("\n").split("\t") |
| 180 | |
| 181 | def account_row(account_id, name, account_type): |
| 182 | values = {"id": account_id, "name": name, |
| 183 | "account_type": account_type, "owner_id": "dan"} |
| 184 | return "\t".join(values.get(f, "") for f in fields) + "\n" |
| 185 | |
| 186 | stage_collection(data_dir, "app-finance", "fin_accounts", |
| 187 | rows=(account_row(CASH, "Cash", "asset") |
| 188 | + account_row(FUNDS, "Customer Funds", "liability") |
| 189 | + account_row(REVENUE, "Revenue", "income"))) |
| 190 | stage_collection(data_dir, "app-finance", "fin_journals") |
| 191 | stage_collection(data_dir, "app-finance", "fin_journal_lines") |
| 192 | |
| 193 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 194 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects-unused")) |
| 195 | object_records.create_collection_record( |
| 196 | "wallets", {"id": "w1", "owner_id": "dan", "is_active": "true"}, |
| 197 | base_dir=data_dir) |
| 198 | return data_dir |
| 199 | |
| 200 | |
| 201 | def stage_entry(data_dir, entry_id, amount, kind): |
| 202 | return object_records.create_collection_record( |
| 203 | "wallet_entries", |
| 204 | {"id": entry_id, "wallet_id": "w1", "amount_minor": str(amount), |
| 205 | "kind": kind, "description": f"{kind} {entry_id}", "owner_id": "dan"}, |
| 206 | base_dir=data_dir) |
| 207 | |
| 208 | |
| 209 | def fire(entry_id, action="created"): |
| 210 | # Mirror the REAL dispatcher payload: the event name uses the |
| 211 | # participle, the action field carries the raw verb. |
| 212 | raw = {"created": "create", "updated": "update", "deleted": "delete"}[action] |
| 213 | return object_execution.execute_object( |
| 214 | RUNTIME, |
| 215 | object_execution.ObjectExecutionRequest( |
| 216 | "system_wallet_books", method="EVENT", |
| 217 | payload={"event": f"wallet_entries.record.{action}", |
| 218 | "collection": "wallet_entries", "record_id": entry_id, |
| 219 | "action": raw}, |
| 220 | ), |
| 221 | roots=[BILLING_OBJECTS], |
| 222 | ).result |
| 223 | |
| 224 | |
| 225 | def posted_lines(data_dir): |
| 226 | return {row["account_id"]: (int(row["debit_cents"]), int(row["credit_cents"])) |
| 227 | for row in object_records.read_collection_records( |
| 228 | "fin_journal_lines", base_dir=data_dir)} |
| 229 | |
| 230 | |
| 231 | def test_a_topup_lands_in_the_books_as_cash_and_a_liability(tmp_path, monkeypatch): |
| 232 | data_dir = setup_books(tmp_path, monkeypatch) |
| 233 | stage_entry(data_dir, "e1", 5000, "topup") |
| 234 | result = fire("e1") |
| 235 | assert result.get("ok") and result.get("journal_id"), result |
| 236 | |
| 237 | lines = posted_lines(data_dir) |
| 238 | assert lines[CASH] == (5000, 0) |
| 239 | assert lines[FUNDS] == (0, 5000) |
| 240 | assert REVENUE not in lines # nothing earned yet |
| 241 | |
| 242 | |
| 243 | def test_a_run_charge_moves_the_liability_into_revenue(tmp_path, monkeypatch): |
| 244 | data_dir = setup_books(tmp_path, monkeypatch) |
| 245 | stage_entry(data_dir, "e2", -25, "debit") |
| 246 | assert fire("e2").get("journal_id") |
| 247 | |
| 248 | lines = posted_lines(data_dir) |
| 249 | assert lines[FUNDS] == (25, 0) |
| 250 | assert lines[REVENUE] == (0, 25) |
| 251 | |
| 252 | |
| 253 | def test_a_replayed_event_composes_nothing(tmp_path, monkeypatch): |
| 254 | """Provenance idempotency, the house rule -- events get redelivered.""" |
| 255 | data_dir = setup_books(tmp_path, monkeypatch) |
| 256 | stage_entry(data_dir, "e3", 5000, "topup") |
| 257 | first = fire("e3") |
| 258 | second = fire("e3") |
| 259 | assert second.get("skipped") |
| 260 | assert second.get("journal_id") == first.get("journal_id") |
| 261 | assert len(object_records.read_collection_records( |
| 262 | "fin_journals", base_dir=data_dir)) == 1 |
| 263 | |
| 264 | |
| 265 | def test_a_hold_leaves_the_books_untouched(tmp_path, monkeypatch): |
| 266 | data_dir = setup_books(tmp_path, monkeypatch) |
| 267 | stage_entry(data_dir, "e4", -25, "hold") |
| 268 | result = fire("e4") |
| 269 | assert "never spent" in result.get("skipped", "") |
| 270 | assert object_records.read_collection_records( |
| 271 | "fin_journals", base_dir=data_dir) == [] |
| 272 | |
| 273 | |
| 274 | def test_billing_works_with_no_books_installed(tmp_path, monkeypatch): |
| 275 | """Soft dependency: the books simply learn nothing.""" |
| 276 | data_dir = setup_books(tmp_path, monkeypatch, books=False) |
| 277 | stage_entry(data_dir, "e5", 5000, "topup") |
| 278 | result = fire("e5") |
| 279 | assert result.get("ok") is True |
| 280 | assert "books not installed" in result.get("skipped", "") |
| 281 | |
| 282 | |
| 283 | def test_unconfigured_accounts_skip_and_name_the_setting(tmp_path, monkeypatch): |
| 284 | data_dir = setup_books(tmp_path, monkeypatch, configured=False) |
| 285 | stage_entry(data_dir, "e7", 5000, "topup") |
| 286 | result = fire("e7") |
| 287 | assert "billing.journal.cash_account" in result.get("skipped", "") |
| 288 | assert object_records.read_collection_records( |
| 289 | "fin_journals", base_dir=data_dir) == [] |
| 290 | |
| 291 | |
| 292 | def test_an_edit_to_an_entry_never_double_books(tmp_path, monkeypatch): |
| 293 | data_dir = setup_books(tmp_path, monkeypatch) |
| 294 | stage_entry(data_dir, "e6", 5000, "topup") |
| 295 | fire("e6") |
| 296 | updated = fire("e6", action="updated") |
| 297 | assert updated.get("skipped") == "only new entries compose" |
| 298 | assert len(object_records.read_collection_records( |
| 299 | "fin_journals", base_dir=data_dir)) == 1 |
| 300 | |
| 301 | |
| 302 | def test_the_full_cycle_reconciles(tmp_path, monkeypatch): |
| 303 | """Top up, hold, release, charge -- then the books and the wallet must |
| 304 | agree about what is still owed, WITH a hold left in flight so the |
| 305 | holds term is exercised end to end rather than only in the unit.""" |
| 306 | data_dir = setup_books(tmp_path, monkeypatch) |
| 307 | for entry_id, amount, kind in [ |
| 308 | ("c1", 5000, "topup"), ("c2", -25, "hold"), ("c3", 25, "release"), |
| 309 | ("c4", -25, "debit"), ("c5", -25, "hold"), # c5 still in flight |
| 310 | ]: |
| 311 | stage_entry(data_dir, entry_id, amount, kind) |
| 312 | fire(entry_id) |
| 313 | |
| 314 | wallet = object_records.get_collection_record("wallets", "w1", base_dir=data_dir) |
| 315 | balance = int(wallet["balance_minor"]) |
| 316 | assert balance == 4950 # 5000 - 25 charged - 25 held |
| 317 | |
| 318 | entries = object_records.read_collection_records("wallet_entries", base_dir=data_dir) |
| 319 | totals = {row["account_id"]: row for row in |
| 320 | object_finance.trial_balance(base_dir=data_dir)} |
| 321 | funds = totals[FUNDS] |
| 322 | result = object_billing.customer_funds_reconciliation( |
| 323 | [balance], |
| 324 | int(funds["debit_total_cents"]), int(funds["credit_total_cents"]), |
| 325 | outstanding_holds=object_billing.outstanding_holds_minor(entries)) |
| 326 | |
| 327 | assert result["outstanding_holds_minor"] == 25 |
| 328 | assert result["balanced"] is True, result |
| 329 | assert int(totals[REVENUE]["credit_total_cents"]) == 25 |