Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_expense_substantiation.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_expense_substantiation.py · 26.0 KB · 491 lines
1"""Expenses that hold up in an audit: categories, stamps, receipts, the report.
2
3An expense an auditor can accept says what it was for, who was there when
4that matters, links the receipt when the amount calls for one, names who
5approved it, and says how much of it the books treat as deductible. Each of
6those is per KIND of spending, and the kinds and their numbers are the
7operator's data (expense_categories), never a constant: the rules change and
8a hard-coded 50% is wrong the year it changes.
9
10Every flow here goes through the real ASGI app with enforcement on
11(scripts/try_package.Sandbox), as the people it is about: ann spends, mia
12(role:manager) approves, fin (role:finance) reports, bob is somebody else.
13The writers below the hook (confirm_scan, a storage-level create) are
14driven too, because a rule the hook alone enforced would be a rule any
15writer below it could skip.
16
17Not tax advice; the seeded percentages are a starting point the docs page
18(docs/expense-substantiation.md) tells the operator to check.
19"""
20
21from __future__ import annotations
22
23import json
24from datetime import date, timedelta
25from pathlib import Path
26
27import pytest
28
29import object_expense_rules as rules
30import object_handlers
31import object_records
32from scripts.try_package import Sandbox
33
34ROOT = Path(__file__).resolve().parents[1]
35FINANCE = ROOT / "packages" / "app-finance"
36RECORDS = "/collections/expenses/records"
37MEAL = "expcat_meals_clients"
38SUPPLIES = "expcat_office_supplies"
39LODGING = "expcat_travel_lodging"
40FUN = "expcat_entertainment"
41
42
43@pytest.fixture
44def box(monkeypatch):
45 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
46 object_handlers.invalidate()
47 with Sandbox(["app-nav", "app-settings", "app-intake", "app-finance"]) as sandbox:
48 sandbox.add_user("ann")
49 sandbox.add_user("bob")
50 sandbox.add_user("mia", roles=["manager"])
51 sandbox.add_user("fin", roles=["finance"])
52 for account_id, name, kind in (("acct-meals", "Meals", "expense"),
53 ("acct-general", "General expense", "expense"),
54 ("acct-card", "Card clearing", "liability"),
55 ("acct-owed", "Owed to staff", "liability")):
56 # finance keeps the chart of accounts, so it may point a
57 # category at one (expense_categories.account_id requires update)
58 ok(sandbox.call("admin", "POST", "/collections/fin_accounts/records",
59 {"id": account_id, "name": name, "account_type": kind,
60 "owner_id": "fin"}))
61 for key, value in (("expenses.journal.expense_account", "acct-general"),
62 ("expenses.journal.paid_account", "acct-card"),
63 ("expenses.journal.reimbursable_account", "acct-owed")):
64 ok(sandbox.call("admin", "POST", "/collections/app_settings/records",
65 {"key": key, "value": value}))
66 yield sandbox
67 object_handlers.invalidate()
68
69
70def days_ago(n):
71 return (date.today() - timedelta(days=n)).isoformat()
72
73
74def ok(answer, status=(200, 201)):
75 code, body = answer
76 assert code in (status if isinstance(status, tuple) else (status,)), body
77 return body
78
79
80def refused(answer, status):
81 code, body = answer
82 assert code == status, body
83 return body.get("error") if isinstance(body, dict) else body
84
85
86def scan(box, owner="ann", name="receipt.jpg"):
87 return ok(box.call(owner, "POST", "/collections/scans/records",
88 {"filename": name, "status": "extracted", "owner_id": owner}))["record"]["id"]
89
90
91def spend(box, who="ann", **fields):
92 body = {"description": "Lunch with Jo Park", "incurred_on": "2025-03-04",
93 "amount_cents": 12000, "owner_id": who, **fields}
94 return ok(box.call(who, "POST", RECORDS, body))["record"]
95
96
97def put(box, who, expense_id, changes):
98 return box.call(who, "PUT", f"{RECORDS}/{expense_id}", changes)
99
100
101def full_meal(box, who="ann", amount=12000, **extra):
102 return spend(box, who, category_id=MEAL, amount_cents=amount,
103 business_purpose="Renewal terms for the Acme contract",
104 attendees="Jo Park, CFO, Acme (client)", location="Bistro, Austin",
105 receipt_scan_id=scan(box, who), **extra)
106
107
108def approved_meal(box, **extra):
109 record = full_meal(box, **extra)
110 ok(put(box, "ann", record["id"], {"status": "submitted"}))
111 return ok(put(box, "mia", record["id"], {"status": "approved"}))["record"]
112
113
114# --- the categories are data with sources ------------------------------------
115
116def test_every_seeded_category_names_its_source_and_its_numbers_are_whole():
117 """The numbers are operator data; the source beside each is what makes a
118 number reviewable rather than folklore."""
119 lines = (FINANCE / "seed" / "expense_categories.tsv").read_text().splitlines()
120 header = lines[0].split("\t")
121 rows = [dict(zip(header, line.split("\t"))) for line in lines[1:]]
122 assert {row["id"] for row in rows} >= {MEAL, LODGING, SUPPLIES, FUN, "expcat_mileage"}
123 for row in rows:
124 assert "accountant" in row["notes"], row["id"]
125 assert any(cite in row["notes"] for cite in ("IRC", "Publication", "Reg.")), row["id"]
126 assert 0 <= int(row["deductible_bps"]) <= 10000
127 assert row["receipt_required_over_cents"] == "" or int(row["receipt_required_over_cents"]) >= 0
128 by_id = {row["id"]: row for row in rows}
129 assert by_id[MEAL]["deductible_bps"] == "5000"
130 assert (by_id[MEAL]["requires_business_purpose"], by_id[MEAL]["requires_attendees"]) == ("true", "true")
131 assert by_id[SUPPLIES]["deductible_bps"] == "10000"
132 assert by_id[FUN]["deductible_bps"] == "0"
133
134
135def test_no_rate_or_threshold_is_a_constant_in_code():
136 """A literal 5000, 7499 or a mileage rate in the rules module would be a
137 policy hidden from the operator. The only numbers it may hold are
138 arithmetic: date slicing, quarters, cents per dollar, basis points per
139 whole."""
140 import ast
141 tree = ast.parse((ROOT / "object_expense_rules.py").read_text())
142 numbers = {node.value for node in ast.walk(tree)
143 if isinstance(node, ast.Constant) and type(node.value) is int}
144 assert numbers <= {0, 1, 2, 3, 4, 5, 7, 10, 100, 10_000}, numbers
145
146
147def test_a_claimant_reads_the_categories_and_cannot_change_them(box):
148 assert ok(box.call("ann", "GET", "/collections/expense_categories/records"))["total"] >= 7
149 refused(box.call("ann", "PUT", f"/collections/expense_categories/records/{MEAL}",
150 {"deductible_bps": 10000}), 403)
151 refused(box.call("ann", "POST", "/collections/expense_categories/records",
152 {"name": "Mine", "deductible_bps": 10000, "owner_id": "ann"}), 403)
153 refused(box.call("mia", "PUT", f"/collections/expense_categories/records/{MEAL}",
154 {"deductible_bps": 10000}), 403)
155
156
157def test_finance_edits_the_policy_and_nobody_deletes_it_but_an_admin(box):
158 ok(box.call("fin", "PUT", f"/collections/expense_categories/records/{SUPPLIES}",
159 {"notes": "Checked with our CPA 2026-11-30."}))
160 created = ok(box.call("fin", "POST", "/collections/expense_categories/records",
161 {"name": "Conference fees", "deductible_bps": 10000, "owner_id": "fin"}))
162 refused(box.call("fin", "DELETE",
163 f"/collections/expense_categories/records/{created['record']['id']}"), 403)
164 ok(box.call("admin", "DELETE",
165 f"/collections/expense_categories/records/{created['record']['id']}"))
166
167
168# --- stamping and the requirements --------------------------------------------
169
170def test_a_categorised_expense_is_stamped_with_what_its_category_requires(box):
171 record = spend(box, category_id=MEAL)
172 assert rules.stamps_of(record) == {
173 "receipt_required": "true", "purpose_required": "true", "attendees_required": "true",
174 "deductible_bps": "5000", "deductible_cents": "6000"}
175 supplies = spend(box, category_id=SUPPLIES, amount_cents=2999)
176 assert rules.stamps_of(supplies) == {
177 "receipt_required": "false", "purpose_required": "false", "attendees_required": "false",
178 "deductible_bps": "10000", "deductible_cents": "2999"}
179
180
181def test_a_client_meal_cannot_be_submitted_without_purpose_attendees_and_receipt(box):
182 record = spend(box, category_id=MEAL)
183 assert "business_purpose" in refused(put(box, "ann", record["id"], {"status": "submitted"}), 400)
184 ok(put(box, "ann", record["id"], {"business_purpose": "Renewal terms"}))
185 assert "attendees" in refused(put(box, "ann", record["id"], {"status": "submitted"}), 400)
186 ok(put(box, "ann", record["id"], {"attendees": "Jo Park, CFO, Acme"}))
187 assert "receipt_scan_id" in refused(put(box, "ann", record["id"], {"status": "submitted"}), 400)
188 ok(put(box, "ann", record["id"], {"receipt_scan_id": scan(box)}))
189 assert ok(put(box, "ann", record["id"], {"status": "submitted"}))["record"]["status"] == "submitted"
190
191
192def test_the_receipt_threshold_is_strictly_over_the_operators_number(box):
193 """7499 in the category: $74.99 needs no receipt, $75.00 does."""
194 at = spend(box, category_id=SUPPLIES, amount_cents=7499)
195 over = spend(box, category_id=SUPPLIES, amount_cents=7500)
196 assert (at["receipt_required"], over["receipt_required"]) == ("false", "true")
197 ok(put(box, "ann", at["id"], {"status": "submitted"}))
198 refused(put(box, "ann", over["id"], {"status": "submitted"}), 400)
199 lodging = spend(box, category_id=LODGING, amount_cents=1, business_purpose="Austin trip")
200 assert lodging["receipt_required"] == "true" # threshold 0: every amount
201
202
203def test_blanking_the_purpose_of_a_submitted_expense_is_refused(box):
204 record = full_meal(box)
205 ok(put(box, "ann", record["id"], {"status": "submitted"}))
206 refused(put(box, "ann", record["id"], {"business_purpose": ""}), 400)
207
208
209def test_raising_the_amount_restamps_and_can_make_a_receipt_required(box):
210 record = spend(box, category_id=SUPPLIES, amount_cents=1000)
211 assert record["receipt_required"] == "false"
212 changed = ok(put(box, "ann", record["id"], {"amount_cents": 20000}))["record"]
213 assert (changed["receipt_required"], changed["deductible_cents"]) == ("true", "20000")
214
215
216def test_a_client_cannot_stamp_its_own_deductible_share(box):
217 """Sent through the API, a forged stamp is overwritten by the hook."""
218 record = spend(box, category_id=FUN, deductible_bps=10000, deductible_cents=12000)
219 assert (record["deductible_bps"], record["deductible_cents"]) == ("0", "0")
220
221
222def test_an_inactive_category_cannot_be_chosen(box):
223 ok(box.call("fin", "PUT", f"/collections/expense_categories/records/{FUN}", {"active": False}))
224 assert "no longer in use" in refused(
225 box.call("ann", "POST", RECORDS, {"description": "Game", "incurred_on": "2025-05-01",
226 "amount_cents": 5000, "category_id": FUN,
227 "owner_id": "ann"}), 409)
228
229
230def test_the_approval_restamps_from_the_category_as_it_stands_then(box):
231 """Policy tightened between submit and approve: the approval is judged by
232 the policy at approval, and refused until the expense meets it."""
233 record = spend(box, category_id=SUPPLIES, amount_cents=3000)
234 ok(put(box, "ann", record["id"], {"status": "submitted"}))
235 ok(box.call("fin", "PUT", f"/collections/expense_categories/records/{SUPPLIES}",
236 {"requires_business_purpose": True, "deductible_bps": 9000}))
237 assert "business_purpose" in refused(put(box, "mia", record["id"], {"status": "approved"}), 400)
238
239
240def test_editing_a_category_restates_nothing_already_approved(box):
241 record = approved_meal(box)
242 assert (record["deductible_bps"], record["deductible_cents"]) == ("5000", "6000")
243 ok(box.call("fin", "PUT", f"/collections/expense_categories/records/{MEAL}",
244 {"deductible_bps": 10000, "requires_attendees": False}))
245 again = ok(box.call("ann", "GET", f"{RECORDS}/{record['id']}"))["record"]
246 assert (again["deductible_bps"], again["deductible_cents"]) == ("5000", "6000")
247 # ...and the later edit does not block what happens to it next.
248 ok(put(box, "mia", record["id"], {"status": "rejected"}))
249
250
251def test_nobody_approves_their_own_meal_and_approval_freezes_the_substantiation(box):
252 record = full_meal(box)
253 ok(put(box, "ann", record["id"], {"status": "submitted"}))
254 refused(put(box, "ann", record["id"], {"status": "approved"}), 403)
255 approved = ok(put(box, "mia", record["id"], {"status": "approved"}))["record"]
256 assert approved["approved_by"] == "mia"
257 body = box.call("mia", "PUT", f"{RECORDS}/{record['id']}", {"attendees": "Somebody else"})
258 assert body[0] == 409 and body[1]["code"] == "record_locked"
259
260
261def test_approval_posts_the_journal_to_the_categorys_account(box):
262 ok(box.call("fin", "PUT", f"/collections/expense_categories/records/{MEAL}",
263 {"account_id": "acct-meals"}))
264 record = approved_meal(box, paid_by="personal")
265 journals = ok(box.call("admin", "GET",
266 f"/collections/fin_journals/records?generated_from=expenses/{record['id']}"))
267 assert journals["total"] == 1
268 lines = ok(box.call("admin", "GET",
269 f"/collections/fin_journal_lines/records?journal_id={journals['records'][0]['id']}"))
270 shape = sorted((l["account_id"], l["debit_cents"], l["credit_cents"]) for l in lines["records"])
271 assert shape == [("acct-meals", "12000", "0"), ("acct-owed", "0", "12000")]
272
273
274# --- the receipt link ---------------------------------------------------------
275
276def test_a_receipt_is_a_scan_its_citer_may_act_on_and_substantiates_one_claim(box):
277 annes = scan(box, "ann")
278 # bob cannot cite ann's receipt (he may not even see it: answered as missing)
279 assert "missing" in refused(box.call("bob", "POST", RECORDS, {
280 "description": "x", "incurred_on": "2025-01-02", "amount_cents": 100,
281 "receipt_scan_id": annes, "owner_id": "bob"}), 400)
282 spend(box, amount_cents=100, receipt_scan_id=annes)
283 code, body = box.call("ann", "POST", RECORDS, {
284 "description": "again", "incurred_on": "2025-01-02", "amount_cents": 100,
285 "receipt_scan_id": annes, "owner_id": "ann"})
286 assert code == 409 and body["code"] == "unique_violation"
287
288
289def test_the_approver_can_read_the_receipt_the_expense_cites(box):
290 record = full_meal(box)
291 ok(box.call("mia", "GET", f"/collections/scans/records/{record['receipt_scan_id']}"))
292 ok(box.call("fin", "GET", f"/collections/scans/records/{record['receipt_scan_id']}"))
293 assert box.call("bob", "GET", f"/collections/scans/records/{record['receipt_scan_id']}")[0] in (403, 404)
294
295
296def test_confirming_a_scan_links_it_and_stamps_the_category(box):
297 scan_id = ok(box.call("ann", "POST", "/collections/scans/records", {
298 "filename": "bistro.jpg", "status": "extracted", "owner_id": "ann",
299 "extracted": json.dumps({"vendor": "Bistro", "total_cents": 8800, "date": "2025-06-01"})}))["record"]["id"]
300 result = ok(box.call("ann", "POST", "/objects/action_confirm_scan", {
301 "scan_id": scan_id, "category_id": MEAL, "business_purpose": "Pipeline review",
302 "attendees": "Sam Lee, Beta Co (prospect)", "location": "Bistro"}))
303 expense = ok(box.call("ann", "GET", f"{RECORDS}/{result['expense_id']}"))["record"]
304 assert expense["receipt_scan_id"] == scan_id and expense["receipt_ref"] == f"scans/{scan_id}"
305 assert (expense["deductible_cents"], expense["attendees_required"]) == ("4400", "true")
306 ok(put(box, "ann", expense["id"], {"status": "submitted"}))
307
308
309def test_a_writer_below_the_hook_cannot_skip_the_category_rules(box):
310 """The locked check, for every writer: an unstamped or mis-stamped
311 categorised expense is refused inside the write lock."""
312 base = box.data_dir
313 roots = [box.objects_dir]
314 row = {"description": "dinner", "incurred_on": "2025-02-02", "amount_cents": "9000",
315 "category_id": MEAL, "status": "draft", "owner_id": "ann"}
316 with pytest.raises(object_records.CheckRefusedError, match="stamps do not match"):
317 object_records.create_collection_record("expenses", dict(row), base_dir=base, roots=roots)
318 forged = {**row, **rules.category_stamps({"deductible_bps": "10000"}, "9000")}
319 with pytest.raises(object_records.CheckRefusedError, match="do not match"):
320 object_records.create_collection_record("expenses", forged, base_dir=base, roots=roots)
321 category = object_records.get_collection_record("expense_categories", MEAL, base_dir=base)
322 honest = {**row, **rules.category_stamps(category, "9000")}
323 created = object_records.create_collection_record("expenses", honest, base_dir=base, roots=roots)
324 assert created["deductible_cents"] == "4500"
325 # and submitting it without the purpose the stamp requires is refused declaratively
326 with pytest.raises(object_records.InvalidRecordPayloadError, match="business_purpose"):
327 object_records.update_collection_record("expenses", created["id"], {"status": "submitted"},
328 base_dir=base, roots=roots)
329
330
331def test_an_expense_with_no_category_is_unaffected(box):
332 """Rows from before 0.19.0, and anybody who does not categorise: no
333 stamps, no new requirement, the old approval flow untouched."""
334 record = spend(box)
335 assert rules.stamps_of(record) == rules.blank_stamps() or not any(rules.stamps_of(record).values())
336 ok(put(box, "ann", record["id"], {"status": "submitted"}))
337 ok(put(box, "mia", record["id"], {"status": "approved"}))
338
339
340# --- the report ---------------------------------------------------------------
341
342def test_the_report_splits_deductible_by_period_and_category_checked_by_hand(box):
343 approved_meal(box, amount=12000) # Q1, 50%: 6000 / 6000
344 approved_meal(box, amount=8001, incurred_on="2025-03-30") # Q1, 50%: 4001 / 4000 (half-up)
345 supplies = spend(box, category_id=SUPPLIES, amount_cents=4550, incurred_on="2025-04-10")
346 ok(put(box, "ann", supplies["id"], {"status": "submitted"}))
347 ok(put(box, "mia", supplies["id"], {"status": "approved"})) # Q2, 100%
348 game = spend(box, category_id=FUN, amount_cents=6000, incurred_on="2025-05-20",
349 business_purpose="Client hospitality", attendees="Jo Park, Acme")
350 ok(put(box, "ann", game["id"], {"status": "submitted"}))
351 ok(put(box, "mia", game["id"], {"status": "approved"})) # Q2, 0%
352 plain = spend(box, amount_cents=1234, incurred_on="2025-05-21")
353 ok(put(box, "ann", plain["id"], {"status": "submitted"}))
354 ok(put(box, "mia", plain["id"], {"status": "approved"})) # Q2, unclassified
355 spend(box, category_id=SUPPLIES, amount_cents=999, incurred_on="2025-05-22") # draft: not on the books
356
357 report = ok(box.call("fin", "GET", "/objects/action_expense_report?from=2025-01-01&to=2025-12-31&period=quarter"))
358 rows = {(r["period"], r["category_id"]): r for r in report["rows"]}
359 assert rows[("2025-Q1", MEAL)] == {**rows[("2025-Q1", MEAL)], "count": 2, "amount_cents": 20001,
360 "deductible_cents": 10001, "nondeductible_cents": 10000,
361 "unclassified_cents": 0}
362 assert (rows[("2025-Q2", SUPPLIES)]["deductible_cents"], rows[("2025-Q2", SUPPLIES)]["nondeductible_cents"]) == (4550, 0)
363 assert (rows[("2025-Q2", FUN)]["deductible_cents"], rows[("2025-Q2", FUN)]["nondeductible_cents"]) == (0, 6000)
364 assert rows[("2025-Q2", "")]["unclassified_cents"] == 1234
365 assert report["totals"] == {"count": 5, "amount_cents": 20001 + 4550 + 6000 + 1234,
366 "deductible_cents": 10001 + 4550, "nondeductible_cents": 10000 + 6000,
367 "unclassified_cents": 1234}
368 assert [g["missing"] for g in report["gaps"]] == [["category"]]
369 assert "accountant" in report["note"]
370 csv_code, csv_body = box.call("fin", "GET", "/objects/action_expense_report?from=2025-01-01&period=year&format=csv")
371 assert csv_code == 200 and csv_body.splitlines()[0].startswith("period,category_id")
372
373
374def test_the_report_shows_each_person_only_what_they_may_read(box):
375 approved_meal(box)
376 bobs = spend(box, "bob", amount_cents=500, incurred_on="2025-03-05")
377 ok(put(box, "bob", bobs["id"], {"status": "submitted"}))
378 ok(put(box, "mia", bobs["id"], {"status": "approved"}))
379 url = "/objects/action_expense_report?period=year"
380 assert ok(box.call("ann", "GET", url))["totals"]["amount_cents"] == 12000
381 assert ok(box.call("bob", "GET", url))["totals"]["amount_cents"] == 500
382 assert ok(box.call("fin", "GET", url))["totals"]["amount_cents"] == 12500
383 assert ok(box.call("mia", "GET", url))["totals"]["amount_cents"] == 12500
384 assert box.call("anon", "GET", url)[0] in (401, 403)
385 refused(box.call("ann", "GET", url + "&period=fortnight"), 400)
386
387
388# --- what needs somebody ------------------------------------------------------
389
390def _attention(box, who):
391 body = ok(box.call(who, "GET", "/objects/action_nav_entries"))
392 return {row["id"]: row for row in body.get("attention", [])}
393
394
395def test_drafts_missing_receipt_or_purpose_and_stale_claims_are_counted_for_their_owner(box):
396 spend(box, category_id=MEAL, incurred_on=days_ago(3)) # missing both, recent
397 old = full_meal(box, incurred_on="2025-01-15")
398 ok(put(box, "ann", old["id"], {"status": "submitted"})) # complete, but 60+ days old
399 mine = _attention(box, "ann")
400 assert mine["expenses_missing_receipt"]["count"] == 1
401 assert mine["expenses_missing_purpose"]["count"] == 1
402 assert mine["expenses_past_accountable_window"]["count"] == 1
403 assert "accountant" in mine["expenses_past_accountable_window"]["detail"]
404 assert _attention(box, "mia")["expenses_past_accountable_window"]["count"] == 1
405 assert "expenses_missing_receipt" not in _attention(box, "bob")
406
407
408def test_the_accountable_plan_window_is_a_setting(box):
409 full = full_meal(box, incurred_on=days_ago(41))
410 ok(put(box, "ann", full["id"], {"status": "submitted"}))
411 assert "expenses_past_accountable_window" not in _attention(box, "ann")
412 ok(box.call("admin", "POST", "/collections/app_settings/records",
413 {"key": "expenses.accountable_plan_days", "value": "30"}))
414 assert _attention(box, "ann")["expenses_past_accountable_window"]["count"] == 1
415
416
417# --- the upgrade --------------------------------------------------------------
418
419BEFORE = "9f84876" # app-finance 0.18.1 / app-intake 0.5.2, the last release before categories
420
421
422def _drop_dead_keys(packages: Path) -> None:
423 """Take out of an old package tree the two keys that never did anything
424 (denominations.json's field `maxlength`, unit_prices.json's root `label`).
425 The installer now refuses a key DRON does not define, and they were taken
426 out of the shipped files for that reason; removing them changes nothing
427 the old version did, because the loader dropped both."""
428 for path in packages.glob("*/schemas/*.json"):
429 schema = json.loads(path.read_text(encoding="utf-8"))
430 changed = schema.pop("label", None) is not None
431 for field in schema.get("fields", []):
432 changed = field.pop("maxlength", None) is not None or changed
433 if changed:
434 path.write_text(json.dumps(schema), encoding="utf-8")
435
436
437def test_an_upgrade_leaves_expenses_written_before_it_working(tmp_path, monkeypatch):
438 """Install the packages as they shipped before 0.19.0, write expenses the
439 old way (a submitted one, an approved one, a draft from a confirmed
440 scan), upgrade over the same data, and carry each on: the submitted one
441 is approved, the approved one rejected, and the old draft categorised
442 and submitted under the new rules. Nothing written before the upgrade is
443 refused for lacking what did not exist when it was written."""
444 import subprocess
445 import tarfile
446
447 archive = subprocess.run(
448 ["git", "archive", BEFORE, "packages"], cwd=ROOT, capture_output=True)
449 if archive.returncode != 0:
450 pytest.skip(f"{BEFORE} is not in this checkout")
451 old = tmp_path / "old"
452 old.mkdir()
453 import io
454 with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar:
455 tar.extractall(old, filter="data")
456 _drop_dead_keys(old / "packages")
457 names = ("app-nav", "app-settings", "app-views", "app-entities", "app-intake", "app-finance")
458 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
459 object_handlers.invalidate()
460 with Sandbox(["app-nav", "app-settings", "app-intake", "app-finance"],
461 packages_dir=old / "packages") as box:
462 box.add_user("ann")
463 box.add_user("mia", roles=["manager"])
464 legacy = {}
465 for key in ("submitted", "approved", "draft"):
466 record = ok(box.call("ann", "POST", RECORDS, {
467 "description": f"old {key}", "incurred_on": "2025-02-02", "amount_cents": 15000,
468 "receipt_ref": "shoebox #4", "owner_id": "ann"}))["record"]
469 if key != "draft":
470 ok(put(box, "ann", record["id"], {"status": "submitted"}))
471 if key == "approved":
472 ok(put(box, "mia", record["id"], {"status": "approved"}))
473 legacy[key] = record["id"]
474
475 box.packages_dir = ROOT / "packages"
476 for name in names:
477 box.reinstall(name)
478 object_handlers.invalidate()
479
480 ok(put(box, "mia", legacy["submitted"], {"status": "approved"}))
481 ok(put(box, "mia", legacy["approved"], {"status": "rejected"}))
482 assert ok(box.call("ann", "GET", f"{RECORDS}/{legacy['approved']}"))["record"]["receipt_ref"] == "shoebox #4"
483 # The old draft, categorised now, meets the new rules like any other.
484 ok(put(box, "ann", legacy["draft"], {"category_id": SUPPLIES}))
485 assert "receipt_scan_id" in refused(put(box, "ann", legacy["draft"], {"status": "submitted"}), 400)
486 ok(put(box, "ann", legacy["draft"], {"receipt_scan_id": scan(box)}))
487 ok(put(box, "ann", legacy["draft"], {"status": "submitted"}))
488 report = ok(box.call("ann", "GET", "/objects/action_expense_report?period=year"))
489 assert report["totals"]["unclassified_cents"] == 15000 # the one approved after the upgrade
490 assert [gap["missing"] for gap in report["gaps"]] == [["category"]]
491 object_handlers.invalidate()