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.
test_expenses.py · 17.3 KB · 402 lines
| 1 | """Expenses: the materials half of time and materials. |
| 2 | |
| 3 | An expense is an accounting fact first and a billable item second, and |
| 4 | almost every property here follows from that ordering. Unbillable |
| 5 | spending still posts. Who paid decides which account is credited, not a |
| 6 | note on a report. And approval -- by somebody other than the spender -- |
| 7 | is the single event that both composes the journal and fixes the price |
| 8 | the client will see. |
| 9 | """ |
| 10 | |
| 11 | import pathlib |
| 12 | |
| 13 | import pytest |
| 14 | |
| 15 | from conftest import stage_collection |
| 16 | |
| 17 | import object_execution |
| 18 | import object_rates |
| 19 | import object_records |
| 20 | import python_object_runtime |
| 21 | |
| 22 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 23 | PACKAGES = REPO_ROOT / "packages" |
| 24 | FINANCE_OBJECTS = PACKAGES / "app-finance" / "objects" |
| 25 | INVOICE_OBJECTS = PACKAGES / "app-invoices" / "objects" |
| 26 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 27 | |
| 28 | ACCOUNTS = ( |
| 29 | ("acct-travel", "Travel", "expense"), |
| 30 | ("acct-card", "Company Card Clearing", "liability"), |
| 31 | ("acct-owed", "Owed To Staff", "liability"), |
| 32 | ) |
| 33 | |
| 34 | SETTINGS = ( |
| 35 | ("expenses.journal.expense_account", "acct-travel"), |
| 36 | ("expenses.journal.paid_account", "acct-card"), |
| 37 | ("expenses.journal.reimbursable_account", "acct-owed"), |
| 38 | ) |
| 39 | |
| 40 | |
| 41 | def setup_env(tmp_path, monkeypatch, *, settings=SETTINGS): |
| 42 | data_dir = tmp_path / "data" |
| 43 | for pkg, name in (("app-finance", "expenses"), ("app-finance", "fin_accounts"), |
| 44 | ("app-finance", "fin_journals"), ("app-finance", "fin_journal_lines"), |
| 45 | ("app-projects", "projects"), |
| 46 | ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"), |
| 47 | ("app-timers", "time_logs"), ("app-timers", "rate_cards")): |
| 48 | stage_collection(data_dir, pkg, name) |
| 49 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 50 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 51 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 52 | |
| 53 | object_records.create_collection_record( |
| 54 | "projects", {"id": "proj-acme", "name": "Acme Rebuild", "owner_id": "boss"}, |
| 55 | base_dir=data_dir) |
| 56 | for account_id, name, kind in ACCOUNTS: |
| 57 | object_records.create_collection_record( |
| 58 | "fin_accounts", |
| 59 | {"id": account_id, "name": name, "account_type": kind, |
| 60 | "code": account_id[-4:], "is_active": "true", "owner_id": "boss"}, |
| 61 | base_dir=data_dir) |
| 62 | return data_dir |
| 63 | |
| 64 | |
| 65 | def spend(data_dir, expense_id, cents=25000, **fields): |
| 66 | record = {"id": expense_id, "description": "Flight to Chicago", |
| 67 | "incurred_on": "2026-06-15", "amount_cents": str(cents), |
| 68 | "currency": "USD", "project_id": "proj-acme", "paid_by": "company", |
| 69 | "billable": "true", "markup_bps": "0", "status": "draft", |
| 70 | "owner_id": "dana"} |
| 71 | record.update({k: str(v) for k, v in fields.items()}) |
| 72 | return object_records.create_collection_record( |
| 73 | "expenses", record, base_dir=data_dir) |
| 74 | |
| 75 | |
| 76 | def hook(record, *, existing=None, changes=None, actor="boss", action="update"): |
| 77 | return object_execution.execute_object( |
| 78 | RUNTIME, |
| 79 | object_execution.ObjectExecutionRequest( |
| 80 | "hook_expenses", method="BEFORE_WRITE", |
| 81 | payload={"action": action, "collection": "expenses", |
| 82 | "record": record, "existing": existing, |
| 83 | "changes": changes if changes is not None else dict(record), |
| 84 | "subject": {"user_id": actor, "roles": ["manager"]}}), |
| 85 | roots=[FINANCE_OBJECTS]).result |
| 86 | |
| 87 | |
| 88 | def approve(data_dir, expense_id, *, actor="boss"): |
| 89 | existing = object_records.get_collection_record("expenses", expense_id, |
| 90 | base_dir=data_dir) |
| 91 | outcome = hook({"status": "approved"}, existing=existing, |
| 92 | changes={"status": "approved"}, actor=actor) |
| 93 | if outcome and outcome.get("error"): |
| 94 | return outcome |
| 95 | patch = (outcome or {}).get("record") or {"status": "approved"} |
| 96 | object_records.update_collection_record("expenses", expense_id, patch, |
| 97 | base_dir=data_dir, actor=actor) |
| 98 | return {"ok": True} |
| 99 | |
| 100 | |
| 101 | def post_books(data_dir, expense_id): |
| 102 | expense = object_records.get_collection_record("expenses", expense_id, |
| 103 | base_dir=data_dir) |
| 104 | return object_execution.execute_object( |
| 105 | RUNTIME, |
| 106 | object_execution.ObjectExecutionRequest( |
| 107 | "system_expense_books", method="POST", |
| 108 | payload={"collection": "expenses", "record": expense}), |
| 109 | roots=[FINANCE_OBJECTS]).result |
| 110 | |
| 111 | |
| 112 | def generate(payload=None): |
| 113 | return object_execution.execute_object( |
| 114 | RUNTIME, |
| 115 | object_execution.ObjectExecutionRequest( |
| 116 | "action_generate_tm_invoice", method="POST", payload=payload or {}), |
| 117 | roots=[INVOICE_OBJECTS]).result |
| 118 | |
| 119 | |
| 120 | def expense(data_dir, expense_id): |
| 121 | return object_records.get_collection_record("expenses", expense_id, |
| 122 | base_dir=data_dir) |
| 123 | |
| 124 | |
| 125 | def journal_lines(data_dir): |
| 126 | return object_records.read_collection_records("fin_journal_lines", |
| 127 | base_dir=data_dir) |
| 128 | |
| 129 | |
| 130 | def lines(data_dir): |
| 131 | return object_records.read_collection_records("invoice_lines", base_dir=data_dir) |
| 132 | |
| 133 | |
| 134 | # --- markup ------------------------------------------------------------------ |
| 135 | |
| 136 | def test_markup_is_basis_points_rounded_once(): |
| 137 | assert object_rates.with_markup(10000, 0) == 10000 # at cost |
| 138 | assert object_rates.with_markup(10000, 1500) == 11500 # 15% |
| 139 | # 3333 at 15% is 3832.95 -> 3833, rounded once on the whole amount. |
| 140 | assert object_rates.with_markup(3333, 1500) == 3833 |
| 141 | |
| 142 | |
| 143 | # --- the gate ---------------------------------------------------------------- |
| 144 | |
| 145 | def test_nobody_approves_their_own_spending(tmp_path, monkeypatch): |
| 146 | data_dir = setup_env(tmp_path, monkeypatch) |
| 147 | spend(data_dir, "e1", status="submitted") |
| 148 | outcome = approve(data_dir, "e1", actor="dana") |
| 149 | assert outcome["status"] == 403 and "not an approval" in outcome["error"] |
| 150 | |
| 151 | |
| 152 | def test_unbillable_spending_is_still_approved(tmp_path, monkeypatch): |
| 153 | """It still left the bank account. Refusing to approve it would leave |
| 154 | real money unrecorded -- a worse failure than an unbilled hour.""" |
| 155 | data_dir = setup_env(tmp_path, monkeypatch) |
| 156 | spend(data_dir, "e1", status="submitted", billable="false") |
| 157 | assert approve(data_dir, "e1")["ok"] |
| 158 | |
| 159 | row = expense(data_dir, "e1") |
| 160 | assert row["status"] == "approved" |
| 161 | assert row["billable_amount_cents"] == "0" # approved, never billable |
| 162 | |
| 163 | |
| 164 | def test_approval_stamps_the_markup_that_applied_then(tmp_path, monkeypatch): |
| 165 | data_dir = setup_env(tmp_path, monkeypatch) |
| 166 | spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted") |
| 167 | approve(data_dir, "e1") |
| 168 | |
| 169 | row = expense(data_dir, "e1") |
| 170 | assert row["markup_bps"] == "1500" |
| 171 | assert row["billable_amount_cents"] == "11500" |
| 172 | assert row["approved_by"] == "boss" and row["approved_at"] |
| 173 | |
| 174 | |
| 175 | def test_the_default_markup_comes_from_settings(tmp_path, monkeypatch): |
| 176 | data_dir = setup_env(tmp_path, monkeypatch, |
| 177 | settings=SETTINGS + (("billing.expense_markup_bps", "1000"),)) |
| 178 | spend(data_dir, "e1", cents=10000, markup_bps="", status="submitted") |
| 179 | approve(data_dir, "e1") |
| 180 | assert expense(data_dir, "e1")["billable_amount_cents"] == "11000" |
| 181 | |
| 182 | |
| 183 | def test_an_expense_needs_an_amount(tmp_path, monkeypatch): |
| 184 | """`validation.min` 1 on amount_cents (the hook's copy of it is gone), so |
| 185 | it holds for the storage-level writers the hook never saw.""" |
| 186 | data_dir = setup_env(tmp_path, monkeypatch) |
| 187 | with pytest.raises(object_records.InvalidRecordPayloadError, match="below min"): |
| 188 | object_records.create_collection_record( |
| 189 | "expenses", {"id": "e0", "description": "Nothing", "incurred_on": "2026-06-01", |
| 190 | "amount_cents": "0", "owner_id": "dana"}, base_dir=data_dir) |
| 191 | |
| 192 | |
| 193 | def test_an_expense_needs_the_date_the_money_was_spent(tmp_path, monkeypatch): |
| 194 | """`required` on incurred_on: that is the period its journal belongs to, |
| 195 | and the hook's own submit-time copy of the rule was dead code.""" |
| 196 | data_dir = setup_env(tmp_path, monkeypatch) |
| 197 | with pytest.raises(object_records.InvalidRecordPayloadError, match="incurred_on"): |
| 198 | object_records.create_collection_record( |
| 199 | "expenses", {"id": "e0", "description": "Nothing", "incurred_on": "", |
| 200 | "amount_cents": "100", "owner_id": "dana"}, base_dir=data_dir) |
| 201 | |
| 202 | |
| 203 | def test_an_explicit_zero_markup_beats_the_house_policy(tmp_path, monkeypatch): |
| 204 | """Blank means 'whatever the house does'; 0 means 'this one at cost'. |
| 205 | A schema default would have collapsed the two.""" |
| 206 | data_dir = setup_env(tmp_path, monkeypatch, |
| 207 | settings=SETTINGS + (("billing.expense_markup_bps", "1000"),)) |
| 208 | spend(data_dir, "e1", cents=10000, markup_bps=0, status="submitted") |
| 209 | approve(data_dir, "e1") |
| 210 | assert expense(data_dir, "e1")["billable_amount_cents"] == "10000" |
| 211 | |
| 212 | |
| 213 | def test_approved_spending_is_frozen(tmp_path, monkeypatch): |
| 214 | data_dir = setup_env(tmp_path, monkeypatch) |
| 215 | spend(data_dir, "e1", status="submitted") |
| 216 | approve(data_dir, "e1") |
| 217 | |
| 218 | # `locked_when` on approved/billed, inside the write lock, for every |
| 219 | # writer and for delete. |
| 220 | with pytest.raises(object_records.RecordLockedError, match="settled"): |
| 221 | object_records.update_collection_record( |
| 222 | "expenses", "e1", {"amount_cents": "99999"}, base_dir=data_dir) |
| 223 | with pytest.raises(object_records.RecordLockedError): |
| 224 | object_records.delete_collection_record("expenses", "e1", base_dir=data_dir) |
| 225 | object_records.update_collection_record( |
| 226 | "expenses", "e1", {"notes": "receipt found"}, base_dir=data_dir) |
| 227 | |
| 228 | |
| 229 | # --- the books ---------------------------------------------------------------- |
| 230 | |
| 231 | def test_a_company_paid_expense_credits_the_card(tmp_path, monkeypatch): |
| 232 | data_dir = setup_env(tmp_path, monkeypatch) |
| 233 | spend(data_dir, "e1", status="submitted") |
| 234 | approve(data_dir, "e1") |
| 235 | |
| 236 | result = post_books(data_dir, "e1") |
| 237 | assert result.get("journal_id") and result.get("posted") |
| 238 | |
| 239 | rows = {r["account_id"]: r for r in journal_lines(data_dir)} |
| 240 | assert rows["acct-travel"]["debit_cents"] == "25000" |
| 241 | assert rows["acct-card"]["credit_cents"] == "25000" |
| 242 | |
| 243 | |
| 244 | def test_a_personally_paid_expense_credits_what_the_business_owes( |
| 245 | tmp_path, monkeypatch): |
| 246 | """Booking somebody's own card against company cash claims money left |
| 247 | an account it never left, and leaves them chasing a reimbursement the |
| 248 | ledger has no record of.""" |
| 249 | data_dir = setup_env(tmp_path, monkeypatch) |
| 250 | spend(data_dir, "e1", status="submitted", paid_by="personal") |
| 251 | approve(data_dir, "e1") |
| 252 | post_books(data_dir, "e1") |
| 253 | |
| 254 | rows = {r["account_id"]: r for r in journal_lines(data_dir)} |
| 255 | assert rows["acct-travel"]["debit_cents"] == "25000" |
| 256 | assert rows["acct-owed"]["credit_cents"] == "25000" |
| 257 | assert "acct-card" not in rows |
| 258 | assert "reimbursable to dana" in rows["acct-owed"]["memo"] |
| 259 | |
| 260 | |
| 261 | def test_an_unapproved_expense_posts_nothing(tmp_path, monkeypatch): |
| 262 | data_dir = setup_env(tmp_path, monkeypatch) |
| 263 | spend(data_dir, "e1", status="submitted") |
| 264 | assert post_books(data_dir, "e1")["skipped"] == "not approved" |
| 265 | assert journal_lines(data_dir) == [] |
| 266 | |
| 267 | |
| 268 | def test_posting_twice_composes_one_journal(tmp_path, monkeypatch): |
| 269 | data_dir = setup_env(tmp_path, monkeypatch) |
| 270 | spend(data_dir, "e1", status="submitted") |
| 271 | approve(data_dir, "e1") |
| 272 | post_books(data_dir, "e1") |
| 273 | again = post_books(data_dir, "e1") |
| 274 | assert "already composed" in again["skipped"] |
| 275 | assert len(journal_lines(data_dir)) == 2 # the one balanced pair |
| 276 | |
| 277 | |
| 278 | def test_unconfigured_books_skip_rather_than_block_the_expense( |
| 279 | tmp_path, monkeypatch): |
| 280 | """Recording that you bought a plane ticket must not require somebody |
| 281 | to have built a chart of accounts first.""" |
| 282 | data_dir = setup_env(tmp_path, monkeypatch, settings=()) |
| 283 | spend(data_dir, "e1", status="submitted") |
| 284 | assert approve(data_dir, "e1")["ok"] # the expense stands |
| 285 | result = post_books(data_dir, "e1") |
| 286 | assert result["skipped"] == "accounts unconfigured" |
| 287 | assert result["needs"] |
| 288 | |
| 289 | |
| 290 | def test_an_expense_naming_its_own_account_overrides_the_default( |
| 291 | tmp_path, monkeypatch): |
| 292 | data_dir = setup_env(tmp_path, monkeypatch) |
| 293 | object_records.create_collection_record( |
| 294 | "fin_accounts", {"id": "acct-meals", "name": "Meals", |
| 295 | "account_type": "expense", "code": "6100", |
| 296 | "is_active": "true", "owner_id": "boss"}, |
| 297 | base_dir=data_dir) |
| 298 | spend(data_dir, "e1", status="submitted", account_id="acct-meals") |
| 299 | approve(data_dir, "e1") |
| 300 | post_books(data_dir, "e1") |
| 301 | |
| 302 | rows = {r["account_id"]: r for r in journal_lines(data_dir)} |
| 303 | assert rows["acct-meals"]["debit_cents"] == "25000" |
| 304 | |
| 305 | |
| 306 | # --- reaching the invoice ------------------------------------------------------- |
| 307 | |
| 308 | def test_costs_and_hours_land_on_one_invoice(tmp_path, monkeypatch): |
| 309 | """A client engaged one firm for one project and gets one bill.""" |
| 310 | data_dir = setup_env(tmp_path, monkeypatch) |
| 311 | object_records.create_collection_record( |
| 312 | "rate_cards", {"id": "house", "label": "House", "hourly_rate_cents": "15000", |
| 313 | "valid_from": "2026-01-01", "is_active": "true", |
| 314 | "owner_id": "boss"}, base_dir=data_dir) |
| 315 | object_records.create_collection_record( |
| 316 | "time_logs", {"id": "t1", "project_id": "proj-acme", |
| 317 | "started_at": "2026-06-15T09:00:00Z", |
| 318 | "ended_at": "2026-06-15T10:00:00Z", "is_running": "false", |
| 319 | "billable": "true", "status": "approved", |
| 320 | "duration_seconds": "3600", "hourly_rate_cents": "15000", |
| 321 | "amount_cents": "15000", "owner_id": "dana"}, |
| 322 | base_dir=data_dir) |
| 323 | spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted") |
| 324 | approve(data_dir, "e1") |
| 325 | |
| 326 | result = generate({"project_id": "proj-acme"}) |
| 327 | assert result["entries_billed"] == 1 and result["expenses_billed"] == 1 |
| 328 | assert result["time_cents"] == 15000 and result["expense_cents"] == 11500 |
| 329 | assert result["total_cents"] == 26500 |
| 330 | |
| 331 | invoice = object_records.read_collection_records("invoices", base_dir=data_dir)[0] |
| 332 | assert invoice["total_cents"] == "26500" |
| 333 | assert expense(data_dir, "e1")["status"] == "billed" |
| 334 | |
| 335 | |
| 336 | def test_the_line_says_when_a_cost_was_marked_up(tmp_path, monkeypatch): |
| 337 | """A pass-through cost quietly grossed up is what clients discover |
| 338 | later and remember.""" |
| 339 | data_dir = setup_env(tmp_path, monkeypatch) |
| 340 | spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted") |
| 341 | spend(data_dir, "e2", cents=5000, markup_bps=0, status="submitted", |
| 342 | description="Taxi", incurred_on="2026-06-16") |
| 343 | approve(data_dir, "e1") |
| 344 | approve(data_dir, "e2") |
| 345 | generate({"project_id": "proj-acme"}) |
| 346 | |
| 347 | rows = sorted(lines(data_dir), key=lambda r: r["description"]) |
| 348 | assert "cost plus 15%" in rows[0]["description"] |
| 349 | assert "(at cost)" in rows[1]["description"] |
| 350 | |
| 351 | |
| 352 | def test_unbillable_costs_never_reach_the_invoice(tmp_path, monkeypatch): |
| 353 | data_dir = setup_env(tmp_path, monkeypatch) |
| 354 | spend(data_dir, "e1", status="submitted", billable="false") |
| 355 | approve(data_dir, "e1") |
| 356 | assert generate({"project_id": "proj-acme"})["invoiced"] == 0 |
| 357 | |
| 358 | |
| 359 | def test_billing_twice_bills_no_cost_twice(tmp_path, monkeypatch): |
| 360 | data_dir = setup_env(tmp_path, monkeypatch) |
| 361 | spend(data_dir, "e1", status="submitted") |
| 362 | approve(data_dir, "e1") |
| 363 | generate({"project_id": "proj-acme"}) |
| 364 | assert generate({"project_id": "proj-acme"})["invoiced"] == 0 |
| 365 | assert len(lines(data_dir)) == 1 |
| 366 | |
| 367 | |
| 368 | def test_expenses_are_never_collapsed_into_one_line(tmp_path, monkeypatch): |
| 369 | """One receipt, one line: grouping would hide exactly what a client |
| 370 | wants itemised.""" |
| 371 | data_dir = setup_env(tmp_path, monkeypatch) |
| 372 | spend(data_dir, "e1", status="submitted") |
| 373 | spend(data_dir, "e2", status="submitted", description="Hotel", |
| 374 | incurred_on="2026-06-16") |
| 375 | approve(data_dir, "e1") |
| 376 | approve(data_dir, "e2") |
| 377 | generate({"project_id": "proj-acme", "grouping": "by_person"}) |
| 378 | assert len(lines(data_dir)) == 2 |
| 379 | |
| 380 | |
| 381 | def test_expenses_absent_leaves_time_billing_working(tmp_path, monkeypatch): |
| 382 | """app-finance is a soft dependency: time still bills without it.""" |
| 383 | data_dir = tmp_path / "data" |
| 384 | for pkg, name in (("app-timers", "time_logs"), ("app-timers", "rate_cards"), |
| 385 | ("app-projects", "projects"), |
| 386 | ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"), |
| 387 | ("app-settings", "app_settings")): |
| 388 | stage_collection(data_dir, pkg, name) |
| 389 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 390 | object_records.create_collection_record( |
| 391 | "projects", {"id": "proj-acme", "name": "Acme", "owner_id": "boss"}, |
| 392 | base_dir=data_dir) |
| 393 | object_records.create_collection_record( |
| 394 | "time_logs", {"id": "t1", "project_id": "proj-acme", |
| 395 | "started_at": "2026-06-15T09:00:00Z", |
| 396 | "ended_at": "2026-06-15T10:00:00Z", "is_running": "false", |
| 397 | "billable": "true", "status": "approved", |
| 398 | "duration_seconds": "3600", "hourly_rate_cents": "15000", |
| 399 | "amount_cents": "15000", "owner_id": "dana"}, |
| 400 | base_dir=data_dir) |
| 401 | result = generate({"project_id": "proj-acme"}) |
| 402 | assert result["invoiced"] == 1 and result["expenses_billed"] == 0 |