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_audit_year_end.py · 16.0 KB · 301 lines
| 1 | """A year of expenses, run end to end and checked by hand, the way an accountant would. |
| 2 | |
| 3 | docs/expense-substantiation.md ends with a year-end checklist. This is that |
| 4 | checklist, run against a made-up 2025 through the real ASGI app with |
| 5 | enforcement on, event handlers on and the change-log replay on -- the |
| 6 | deployment the docs describe. Two employees, ann and bob, spend on client |
| 7 | meals, travel, supplies and entertainment, drive their own cars on business, |
| 8 | and one of bob's claims sits unapproved for months. mia (role:manager) |
| 9 | approves; fin (role:finance) keeps the rates and the fringe register and |
| 10 | runs the reports. |
| 11 | |
| 12 | Every expected number below is worked out in the comments beside it, from |
| 13 | the amounts and the operator's data (the seeded categories, a test mileage |
| 14 | rate of 70.00 cents a mile -- test data, not a statement of the IRS rate), |
| 15 | not read back from the code under test. The test then checks the three |
| 16 | things an audit asks: the deductible report adds up, the mileage |
| 17 | reimbursement adds up, and every expense on the books traces to a receipt |
| 18 | (or a mileage log), a purpose and an approval by somebody else -- and the |
| 19 | books (the journals) say the same total. |
| 20 | """ |
| 21 | |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import csv |
| 25 | import io |
| 26 | |
| 27 | import pytest |
| 28 | |
| 29 | import object_change_dispatch |
| 30 | import object_handlers |
| 31 | from scripts.try_package import Sandbox |
| 32 | |
| 33 | YEAR_FROM, YEAR_TO = "2025-01-01", "2025-12-31" |
| 34 | RATE = 7000 # hundredths of a cent per mile: 70.00 cents |
| 35 | |
| 36 | MEAL = "expcat_meals_clients" |
| 37 | LODGING = "expcat_travel_lodging" |
| 38 | TRANSPORT = "expcat_travel_transport" |
| 39 | TRAVEL_MEAL = "expcat_travel_meals" |
| 40 | SUPPLIES = "expcat_office_supplies" |
| 41 | FUN = "expcat_entertainment" |
| 42 | MILEAGE = "expcat_mileage" |
| 43 | |
| 44 | PURPOSE = "Contract renewal with Acme" |
| 45 | GUESTS = "Jo Park, CFO, Acme (client)" |
| 46 | |
| 47 | # (who, day, category, cents, paid_by, receipt?, with purpose/attendees?) |
| 48 | SPENDING = [ |
| 49 | ("ann", "2025-01-14", MEAL, 18640, "company", True), |
| 50 | ("ann", "2025-04-22", MEAL, 9575, "company", True), |
| 51 | ("ann", "2025-09-09", MEAL, 6230, "company", False), # under $75: no receipt needed |
| 52 | ("ann", "2025-03-03", LODGING, 41200, "company", True), |
| 53 | ("ann", "2025-03-03", TRANSPORT, 38950, "company", True), |
| 54 | ("ann", "2025-03-04", TRAVEL_MEAL, 5420, "company", False), |
| 55 | ("ann", "2025-02-10", SUPPLIES, 12999, "company", True), |
| 56 | ("ann", "2025-06-18", SUPPLIES, 4310, "company", False), |
| 57 | ("ann", "2025-11-07", FUN, 24000, "company", True), |
| 58 | ("bob", "2025-07-15", MEAL, 11111, "company", True), |
| 59 | ("bob", "2025-10-02", SUPPLIES, 8800, "personal", True), |
| 60 | ] |
| 61 | LATE_CLAIM = ("bob", "2025-08-01", TRANSPORT, 15600, "personal", True) |
| 62 | |
| 63 | # (who, vehicle, day, start, end, miles-if-no-odometer) |
| 64 | TRIPS = [ |
| 65 | ("ann", "car", "2025-02-03", 12000, 12046, None), # 46 mi x 70.00 = 3,220 |
| 66 | ("ann", "car", "2025-05-12", 12046, 12187, None), # 141 mi x 70.00 = 9,870 |
| 67 | ("ann", "car", "2025-08-20", 15000, 15333, None), # 333 mi x 70.00 = 23,310 |
| 68 | ("bob", "car", "2025-03-09", 30500, 30587, None), # 87 mi x 70.00 = 6,090 |
| 69 | ("bob", "car", "2025-10-30", None, None, 64), # 64 mi x 70.00 = 4,480 |
| 70 | ] |
| 71 | # ann 520 mi = 36,400; bob 151 mi = 10,570; together 671 mi = 46,970 cents. |
| 72 | MILEAGE_TOTAL = 46970 |
| 73 | |
| 74 | # The deductible report, by hand (seeded categories; half-up once per expense): |
| 75 | # client meals 18,640 -> 9,320 9,575 -> 4,787.5 -> 4,788 6,230 -> 3,115 |
| 76 | # 11,111 -> 5,555.5 -> 5,556 |
| 77 | # amount 45,556 deductible 22,779 non-deductible 22,777 |
| 78 | # lodging 41,200 -> 41,200 (100%) |
| 79 | # transport 38,950 + 15,600 (bob's late claim) = 54,550, all deductible |
| 80 | # travel meals 5,420 -> 2,710 / 2,710 |
| 81 | # supplies 12,999 + 4,310 + 8,800 = 26,109, all deductible |
| 82 | # entertainment 24,000 -> 0 / 24,000 |
| 83 | # mileage 46,970, all deductible (5 expenses) |
| 84 | EXPECTED = { |
| 85 | MEAL: (4, 45556, 22779, 22777), |
| 86 | LODGING: (1, 41200, 41200, 0), |
| 87 | TRANSPORT: (2, 54550, 54550, 0), |
| 88 | TRAVEL_MEAL: (1, 5420, 2710, 2710), |
| 89 | SUPPLIES: (3, 26109, 26109, 0), |
| 90 | FUN: (1, 24000, 0, 24000), |
| 91 | MILEAGE: (5, 46970, 46970, 0), |
| 92 | } |
| 93 | # 45,556 + 41,200 + 54,550 + 5,420 + 26,109 + 24,000 + 46,970 = 243,805 |
| 94 | # deductible 22,779 + 41,200 + 54,550 + 2,710 + 26,109 + 0 + 46,970 = 194,318 |
| 95 | # non-deductible 22,777 + 2,710 + 24,000 = 49,487; 194,318 + 49,487 = 243,805 |
| 96 | TOTAL, DEDUCTIBLE, NONDEDUCTIBLE = 243805, 194318, 49487 |
| 97 | # Owed back to staff (paid_by personal): mileage 46,970 + bob's supplies 8,800 |
| 98 | # + bob's late claim 15,600 = 71,370; the company card carries the other 172,435. |
| 99 | OWED_TO_STAFF, ON_THE_CARD = 71370, 172435 |
| 100 | |
| 101 | |
| 102 | def ok(answer, status=(200, 201)): |
| 103 | code, body = answer |
| 104 | assert code in (status if isinstance(status, tuple) else (status,)), body |
| 105 | return body |
| 106 | |
| 107 | |
| 108 | def replay(box): |
| 109 | for _ in range(10): |
| 110 | outcome = object_change_dispatch.dispatch_pending(base_dir=box.data_dir, roots=[box.objects_dir]) |
| 111 | assert outcome["errors"] == 0, outcome["results"] |
| 112 | if not outcome["processed"]: |
| 113 | return |
| 114 | raise AssertionError("change dispatch never went quiet") |
| 115 | |
| 116 | |
| 117 | @pytest.fixture |
| 118 | def year(monkeypatch): |
| 119 | monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true") |
| 120 | monkeypatch.setenv(object_change_dispatch.ENABLE_ENV, "true") |
| 121 | object_handlers.invalidate() |
| 122 | with Sandbox(["app-nav", "app-settings", "app-intake", "app-finance"]) as box: |
| 123 | for name in ("ann", "bob"): |
| 124 | box.add_user(name) |
| 125 | box.add_user("mia", roles=["manager"]) |
| 126 | box.add_user("fin", roles=["finance"]) |
| 127 | assert object_change_dispatch.dispatch_pending( |
| 128 | base_dir=box.data_dir, roots=[box.objects_dir])["processed"] == 0 |
| 129 | for account_id, kind in (("acct-expense", "expense"), ("acct-card", "liability"), |
| 130 | ("acct-owed", "liability")): |
| 131 | ok(box.call("admin", "POST", "/collections/fin_accounts/records", |
| 132 | {"id": account_id, "name": account_id, "account_type": kind})) |
| 133 | for key, value in (("expenses.journal.expense_account", "acct-expense"), |
| 134 | ("expenses.journal.paid_account", "acct-card"), |
| 135 | ("expenses.journal.reimbursable_account", "acct-owed")): |
| 136 | ok(box.call("admin", "POST", "/collections/app_settings/records", {"key": key, "value": value})) |
| 137 | ok(box.call("fin", "POST", "/collections/mileage_rates/records", { |
| 138 | "year": 2025, "rate_hundredths_cent": RATE, "owner_id": "fin", |
| 139 | "source_url": "https://www.irs.gov/tax-professionals/standard-mileage-rates", |
| 140 | "source_date": "2024-12-19", "notes": "test data"})) |
| 141 | yield box |
| 142 | object_handlers.invalidate() |
| 143 | |
| 144 | |
| 145 | def file_expense(box, who, day, category, cents, paid_by, receipt): |
| 146 | body = {"description": f"{category} {day}", "incurred_on": day, "amount_cents": cents, |
| 147 | "category_id": category, "paid_by": paid_by, "billable": False, |
| 148 | "business_purpose": PURPOSE, "attendees": GUESTS, "location": "Austin", |
| 149 | "owner_id": who} |
| 150 | if receipt: |
| 151 | body["receipt_scan_id"] = ok(box.call(who, "POST", "/collections/scans/records", { |
| 152 | "filename": f"{day}-{cents}.jpg", "status": "extracted", "owner_id": who}))["record"]["id"] |
| 153 | record = ok(box.call(who, "POST", "/collections/expenses/records", body))["record"] |
| 154 | ok(box.call(who, "PUT", f"/collections/expenses/records/{record['id']}", {"status": "submitted"})) |
| 155 | return record["id"] |
| 156 | |
| 157 | |
| 158 | def approve(box, expense_id): |
| 159 | return ok(box.call("mia", "PUT", f"/collections/expenses/records/{expense_id}", |
| 160 | {"status": "approved"}))["record"] |
| 161 | |
| 162 | |
| 163 | def test_a_year_of_expenses_adds_up_and_every_one_traces_to_its_evidence(year): |
| 164 | box = year |
| 165 | |
| 166 | # --- the year's spending, each submitted by its spender, approved by mia |
| 167 | for entry in SPENDING: |
| 168 | approve(box, file_expense(box, *entry)) |
| 169 | late = file_expense(box, *LATE_CLAIM) |
| 170 | |
| 171 | # Noise that must not reach the books: a draft, and a rejected claim. |
| 172 | draft = file_expense(box, "ann", "2025-12-20", SUPPLIES, 999, "company", False) |
| 173 | ok(box.call("mia", "PUT", f"/collections/expenses/records/{draft}", {"status": "rejected"})) |
| 174 | ok(box.call("ann", "POST", "/collections/expenses/records", { |
| 175 | "description": "never submitted", "incurred_on": "2025-12-30", "amount_cents": 777, |
| 176 | "category_id": SUPPLIES, "owner_id": "ann"})) |
| 177 | |
| 178 | # --- bob's claim, months old and still not approved, is on the queue |
| 179 | queue = {row["id"]: row for row in ok(box.call("mia", "GET", "/objects/action_nav_entries"))["attention"]} |
| 180 | late_queue = queue["expenses_past_accountable_window"] |
| 181 | # bob's 15,600 submitted claim, plus ann's 777 draft from December 2025 -- |
| 182 | # both spent more than 60 days before today. |
| 183 | assert late_queue["count"] == 2 |
| 184 | assert late_queue["detail"].startswith("163.77 spent and still not approved") |
| 185 | assert "accountant" in late_queue["detail"] |
| 186 | approve(box, late) |
| 187 | |
| 188 | # --- mileage: two personal cars, five trips, one mistake of each kind refused |
| 189 | cars = {} |
| 190 | for who in ("ann", "bob"): |
| 191 | cars[who] = ok(box.call(who, "POST", "/collections/vehicles/records", { |
| 192 | "name": f"{who}'s car", "ownership": "personal", "owner_id": who}))["record"]["id"] |
| 193 | trip_ids = [] |
| 194 | for who, _car, day, start, end, miles in TRIPS: |
| 195 | body = {"vehicle_id": cars[who], "trip_date": day, "from_place": "Office", |
| 196 | "to_place": "Client site", "business_purpose": f"Site visit {day}", "owner_id": who} |
| 197 | if start is None: |
| 198 | body["miles"] = miles |
| 199 | else: |
| 200 | body.update(start_odometer=start, end_odometer=end) |
| 201 | log = ok(box.call(who, "POST", "/collections/mileage_logs/records", body))["record"] |
| 202 | ok(box.call(who, "PUT", f"/collections/mileage_logs/records/{log['id']}", {"status": "submitted"})) |
| 203 | ok(box.call("mia", "PUT", f"/collections/mileage_logs/records/{log['id']}", {"status": "approved"})) |
| 204 | trip_ids.append(log["id"]) |
| 205 | overlap = box.call("ann", "POST", "/collections/mileage_logs/records", { |
| 206 | "vehicle_id": cars["ann"], "trip_date": "2025-06-01", "start_odometer": 12100, |
| 207 | "end_odometer": 12200, "from_place": "Office", "to_place": "X", |
| 208 | "business_purpose": "Double-counted", "owner_id": "ann"}) |
| 209 | assert overlap[0] == 409 and "overlaps" in overlap[1]["error"] |
| 210 | backwards = box.call("bob", "POST", "/collections/mileage_logs/records", { |
| 211 | "vehicle_id": cars["bob"], "trip_date": "2025-06-01", "start_odometer": 31000, |
| 212 | "end_odometer": 30990, "from_place": "Office", "to_place": "X", |
| 213 | "business_purpose": "Typo", "owner_id": "bob"}) |
| 214 | assert backwards[0] == 400 |
| 215 | |
| 216 | replay(box) # storage-level writes (the mileage expenses) reach their handlers |
| 217 | |
| 218 | # --- the mileage reimbursement adds up by hand |
| 219 | logs = ok(box.call("fin", "GET", "/collections/mileage_logs/records?limit=100"))["records"] |
| 220 | assert sum(int(log["miles"]) for log in logs) == 671 |
| 221 | assert sum(int(log["reimbursement_cents"]) for log in logs) == MILEAGE_TOTAL |
| 222 | expenses = ok(box.call("fin", "GET", "/collections/expenses/records?limit=500"))["records"] |
| 223 | mileage = [e for e in expenses if e["generated_from"].startswith("mileage_logs/")] |
| 224 | assert len(mileage) == 5 and sum(int(e["amount_cents"]) for e in mileage) == MILEAGE_TOTAL |
| 225 | assert {e["owner_id"] for e in mileage} == {"ann", "bob"} |
| 226 | assert sum(int(e["amount_cents"]) for e in mileage if e["owner_id"] == "ann") == 36400 |
| 227 | assert sum(int(e["amount_cents"]) for e in mileage if e["owner_id"] == "bob") == 10570 |
| 228 | |
| 229 | # --- the deductible report adds up by hand |
| 230 | report = ok(box.call("fin", "GET", |
| 231 | f"/objects/action_expense_report?from={YEAR_FROM}&to={YEAR_TO}&period=year")) |
| 232 | by_category = {row["category_id"]: row for row in report["by_category"]} |
| 233 | assert set(by_category) == set(EXPECTED) |
| 234 | for category, (count, amount, deductible, nondeductible) in EXPECTED.items(): |
| 235 | row = by_category[category] |
| 236 | assert (row["count"], row["amount_cents"], row["deductible_cents"], |
| 237 | row["nondeductible_cents"], row["unclassified_cents"]) == ( |
| 238 | count, amount, deductible, nondeductible, 0), category |
| 239 | assert report["totals"] == {"count": 17, "amount_cents": TOTAL, "deductible_cents": DEDUCTIBLE, |
| 240 | "nondeductible_cents": NONDEDUCTIBLE, "unclassified_cents": 0} |
| 241 | assert report["gaps"] == [] |
| 242 | quarterly = ok(box.call("fin", "GET", |
| 243 | f"/objects/action_expense_report?from={YEAR_FROM}&to={YEAR_TO}&period=quarter")) |
| 244 | assert sum(row["amount_cents"] for row in quarterly["by_period"]) == TOTAL |
| 245 | assert [row["period"] for row in quarterly["by_period"]] == ["2025-Q1", "2025-Q2", "2025-Q3", "2025-Q4"] |
| 246 | code, text = box.call("fin", "GET", |
| 247 | f"/objects/action_expense_report?from={YEAR_FROM}&to={YEAR_TO}&period=month&format=csv") |
| 248 | assert code == 200 |
| 249 | rows = list(csv.DictReader(io.StringIO(text))) |
| 250 | assert sum(int(r["deductible_cents"]) for r in rows) == DEDUCTIBLE |
| 251 | assert sum(int(r["nondeductible_cents"]) for r in rows) == NONDEDUCTIBLE |
| 252 | |
| 253 | # --- every expense on the books traces to its evidence, purpose and approval |
| 254 | on_books = [e for e in expenses if e["status"] in ("approved", "billed")] |
| 255 | assert len(on_books) == 17 |
| 256 | logs_by_id = {log["id"]: log for log in logs} |
| 257 | for expense in on_books: |
| 258 | assert expense["approved_by"] and expense["approved_by"] != expense["owner_id"], expense["id"] |
| 259 | assert expense["business_purpose"], expense["id"] |
| 260 | if expense["attendees_required"] == "true": |
| 261 | assert expense["attendees"], expense["id"] |
| 262 | if expense["generated_from"].startswith("mileage_logs/"): |
| 263 | log = logs_by_id[expense["generated_from"].split("/", 1)[1]] |
| 264 | assert log["status"] == "approved" and log["approved_by"] == expense["approved_by"] |
| 265 | assert log["reimbursement_cents"] == expense["amount_cents"] |
| 266 | assert log["owner_id"] == expense["owner_id"] |
| 267 | continue |
| 268 | if expense["receipt_required"] == "true": |
| 269 | receipt = ok(box.call("fin", "GET", f"/collections/scans/records/{expense['receipt_scan_id']}"))["record"] |
| 270 | assert receipt["owner_id"] == expense["owner_id"] |
| 271 | else: |
| 272 | assert int(expense["amount_cents"]) <= 7499, expense["id"] # the seeded threshold |
| 273 | |
| 274 | # --- the books say the same: one live journal per expense, by who paid |
| 275 | journals = ok(box.call("admin", "GET", "/collections/fin_journals/records?limit=500"))["records"] |
| 276 | booked = {j["generated_from"] for j in journals if j["generated_from"].startswith("expenses/")} |
| 277 | assert booked == {f"expenses/{e['id']}" for e in on_books} |
| 278 | assert not [j for j in journals if j["generated_from"].startswith("reversal:")] |
| 279 | lines = ok(box.call("admin", "GET", "/collections/fin_journal_lines/records?limit=1000"))["records"] |
| 280 | debit = {} |
| 281 | credit = {} |
| 282 | for line in lines: |
| 283 | debit[line["account_id"]] = debit.get(line["account_id"], 0) + int(line["debit_cents"] or 0) |
| 284 | credit[line["account_id"]] = credit.get(line["account_id"], 0) + int(line["credit_cents"] or 0) |
| 285 | assert debit.get("acct-expense") == TOTAL |
| 286 | assert credit.get("acct-owed") == OWED_TO_STAFF |
| 287 | assert credit.get("acct-card") == ON_THE_CARD |
| 288 | assert OWED_TO_STAFF + ON_THE_CARD == TOTAL |
| 289 | |
| 290 | # --- the queue is clear once the late claim is approved; the draft remains |
| 291 | queue = {row["id"]: row for row in ok(box.call("mia", "GET", "/objects/action_nav_entries"))["attention"]} |
| 292 | assert queue["expenses_past_accountable_window"]["count"] == 1 # ann's never-submitted draft |
| 293 | |
| 294 | # --- and the fringe benefit goes to payroll as recorded |
| 295 | ok(box.call("fin", "POST", "/collections/fringe_benefits/records", { |
| 296 | "employee_id": "E-2", "employee_name": "Bob", "benefit_type": "gift_card_or_cash_equivalent", |
| 297 | "period_start": "2025-12-19", "period_end": "2025-12-19", "value_cents": 10000, |
| 298 | "taxable": "yes", "valuation_method": "face value", "source": "holiday gift card receipt", |
| 299 | "owner_id": "fin"})) |
| 300 | export = ok(box.call("fin", "GET", f"/objects/action_fringe_export?from={YEAR_FROM}&to={YEAR_TO}")) |
| 301 | assert (export["count"], export["total_value_cents"], export["taxable_value_cents"]) == (1, 10000, 10000) |