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_app_finance_package.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_app_finance_package.py · 23.9 KB · 514 lines
1"""Structural tests for packages/app-finance (double-entry accounting v1).
2
3Mirrors the package/schema/permission testing conventions used for
4packages/app-invoices in tests/test_app_invoices_package.py. Behavior
5tests for the computed helpers (journal_totals/trial_balance) live in
6tests/test_object_finance.py -- there is no HANDLES totals handler in
7this package to test here (deliberate; see object_finance.py's module
8docstring and dbbasic-package.json's description).
9"""
10
11import json
12import re
13from pathlib import Path
14
15import object_packages
16import object_permissions
17import object_schemas
18from package_pins import assert_includes_in_order
19
20PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
21APP_FINANCE_DIR = PACKAGES_ROOT / "app-finance"
22
23# Field types that store money as a float/decimal rather than integer cents
24# -- the doctrine this package must never violate (00-doctrine-and-contract.md).
25_FLOAT_MONEY_TYPES = {"float", "number", "currency"}
26
27# 0.4.0 added `denominations`: what a unit of value is and how finely it
28# divides (object_money.py). Amounts are integers of the smallest unit, so
29# this is the collection that says where the decimal point goes.
30_SCHEMA_NAMES = ("denominations", "rates", "fin_accounts", "fin_journals",
31 "fin_journal_lines", "fin_recurring",
32 # 0.7.0: settled books stay settled -- the closed-period
33 # gate the predecessor modeled and this system lacked.
34 "fin_closed_periods",
35 # 0.9.0: the materials half of time and materials. An
36 # expense is an accounting fact first and a billable item
37 # second, which is why it lives with the books.
38 "expenses")
39
40# Collections that are shared REFERENCE data rather than per-owner business
41# records: a denomination is the same fact in every set of books (gold is
42# gold), so unlike the rest of finance it carries no entity_id scoping FK
43# and it ships seeded rows instead of a bare header. `rates` is shared in the
44# same way (an observed price is not owned by one set of books) but ships
45# header-only, since rates are fetched rather than seeded.
46_REFERENCE_COLLECTIONS = ("denominations", "rates")
47_SEEDED_REFERENCE = ("denominations",)
48
49
50def _schema(name):
51 return json.loads((APP_FINANCE_DIR / "schemas" / f"{name}.json").read_text())
52
53
54def test_get_package_normalizes_app_finance_manifest():
55 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
56
57 assert package["id"] == "app-finance"
58 assert package["name"] == "Finance"
59 assert {schema["collection"] for schema in package["schemas"]} >= set(_SCHEMA_NAMES)
60 # site_setup_accounts (65 slice 4) added the Setup Accounts action object.
61 # site_journal_view was retrofitted away (stage-6): the journal detail
62 # page is now a seeded 59 view (site_view_render), not a bespoke object.
63 # hook_fin_journals: the balance-enforcement pre-write hook (internal --
64 # no public execute rule; the write path runs it, never HTTP).
65 # 0.7.0 deletes the bespoke /accounts and /journals list page objects
66 # too: both held no business logic and are now seeded VIEW records over
67 # the generic `list` block.
68 assert {obj["id"] for obj in package["objects"]} >= {
69 "site_trial_balance",
70 "site_setup_accounts", "hook_fin_journals",
71 # 0.7.0: the line-side closed-period gate -- a journal's amounts
72 # live in its lines, so freezing the journal alone froze nothing.
73 "hook_fin_journal_lines",
74 "action_reverse_journal", "system_fin_recurring_runner",
75 # 0.6.0: the P&L + balance sheet page, the two statements this
76 # package listed as deferred from v1 (object_finance.py's docstring).
77 "site_statements",
78 # 0.9.0: expenses -- the approval gate and the journal it composes.
79 "hook_expenses", "system_expense_books",
80 # 0.10.0 shipped system_expense_attention for expenses at
81 # `submitted`; 0.17.0 declares that count in the manifest instead.
82 }
83 assert {"path": "permissions/rules.json"} in package["permissions"]
84 # + a site_routes seed for /finance/setup-accounts and /journals/{id},
85 # + a views seed for the retrofitted journal detail view.
86 assert {entry["collection"] for entry in package["seed"]} >= set(_SCHEMA_NAMES) | {"views", "site_routes"}
87
88
89def test_dry_run_app_finance_package_is_safe(tmp_path):
90 object_root = tmp_path / "objects"
91 object_root.mkdir()
92
93 plan = object_packages.dry_run_package(
94 "app-finance",
95 root=PACKAGES_ROOT,
96 base_dir=tmp_path / "data",
97 object_roots=[object_root],
98 )
99
100 assert plan["safe_to_install"] is True
101 assert plan["warnings"] == []
102 assert {schema["collection"] for schema in plan["schemas"]} >= set(_SCHEMA_NAMES)
103
104
105def test_install_app_finance_package_loads_schemas(tmp_path):
106 data_dir = tmp_path / "data"
107 object_root = tmp_path / "objects"
108 object_root.mkdir()
109
110 object_packages.install_package(
111 "app-finance", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root],
112 )
113
114 for name in _SCHEMA_NAMES:
115 schema = object_schemas.get_schema(name, base_dir=data_dir)
116 assert schema["name"] == name
117
118 assert (object_root / "site" / "trial_balance.py").is_file()
119 # journal_view.py was deleted (stage-6 retrofit): the journal detail
120 # page is now a seeded 59 view, not an installed object file.
121 assert not (object_root / "site" / "journal_view.py").exists()
122 # accounts.py/journals.py were deleted (0.7.0): the /accounts and
123 # /journals list pages are now seeded VIEW records too.
124 assert not (object_root / "site" / "accounts.py").exists()
125 assert not (object_root / "site" / "journals.py").exists()
126
127
128def test_schema_json_files_are_valid_and_versioned():
129 # Every finance collection gained an entity_id scoping FK (65 multi-entity)
130 # -- an additive relation field -- so each version bumped by one from its
131 # prior value: fin_accounts 2->3, fin_journals 2->3, the rest 1->2.
132 for name in _SCHEMA_NAMES:
133 payload = _schema(name)
134 assert payload["name"] == name
135 if name in _REFERENCE_COLLECTIONS:
136 continue
137 # entity_id is present on every finance collection, a relation into
138 # the entities collection (scoping FK, not composition).
139 by_name = {f["name"]: f for f in payload["fields"]}
140 assert by_name["entity_id"]["relation"]["collection"] == "entities", name
141 if name == "fin_accounts":
142 # hierarchy tree view (60) + generated_from (61) history, now + entity_id
143 assert payload["version"] >= 3
144 assert payload["views"]["list_mode"] == "tree"
145 elif name == "fin_journals":
146 # generated_from (61) + entity_id (65) + hooks.before_write (v4)
147 # + totals rollups (v5) + kind standard|adjusting|reversing|closing
148 # (v6, the books spine) + capabilities.comments/attachments
149 # (v7 -- "what is this journal FOR" is the commonest question a
150 # set of books has to answer, and the supporting document and
151 # the reasoning both attach WITHOUT mutating the posted entry)
152 # + unique generated_from (v8 -- one journal per provenance
153 # marker; tests/test_finance_action_claims.py)
154 # + locked_when on posted (v9 -- posted is final for every
155 # writer; until then nothing froze a posted journal at all)
156 # + the unique message reworded for the person refused (v10)
157 assert payload["version"] >= 10
158 assert [rule["when"] for rule in payload["locked_when"]] == [{"status": ["posted"]}]
159 assert_includes_in_order(payload["views"]["filter_fields"], ["status", "kind"])
160 assert payload["hooks"] == {"before_write": "hook_fin_journals"}
161 assert payload["views"]["list_mode"] == "table"
162 else:
163 # fin_journal_lines: 2 -> 3 (hooks.before_write, closed periods);
164 # fin_recurring stays at 2 (entity_id).
165 if payload["name"] == "fin_journal_lines":
166 assert payload["version"] >= 3
167 assert payload["hooks"] == {"before_write": "hook_fin_journal_lines"}
168 elif payload["name"] == "expenses":
169 # 1 -> 2: generated_from, unique, so one scan books one
170 # expense (confirm_scan retries and double clicks)
171 # 2 -> 3: locked_when on approved/billed and validation.min 1
172 # on amount_cents, which replaced the hook's copies of both
173 assert payload["version"] >= 3
174 # 4 -> 5 (0.19.0): one receipt substantiates one expense.
175 assert payload["unique"] == [
176 {"fields": ["generated_from"],
177 "message": "That scan has already been confirmed into an expense."},
178 {"fields": ["receipt_scan_id"],
179 "message": "That receipt already substantiates another expense. "
180 "One receipt, one claim."}]
181 elif payload["name"] == "fin_closed_periods":
182 assert payload["version"] >= 1 # new in 0.7.0
183 else:
184 assert payload["version"] >= 2
185 assert payload["views"]["list_mode"] == "table"
186
187
188def test_no_money_field_uses_a_float_or_currency_type():
189 for name in _SCHEMA_NAMES:
190 for field in _schema(name)["fields"]:
191 field_name = field["name"]
192 field_type = field.get("type")
193 if "_cents" in field_name:
194 # A derived money field (rollup sum of integer-cents inputs)
195 # is `computed`; every stored/writable money field stays
196 # integer. Both keep money out of float-shaped types.
197 assert field_type in ("integer", "computed"), (
198 f"{name}.{field_name} must be integer (or computed over "
199 f"integers), got {field_type!r}"
200 )
201 if field_type == "computed":
202 rollup = field.get("rollup") or {}
203 assert rollup.get("field", "").endswith("_cents"), (
204 f"{name}.{field_name} computed money must derive from "
205 f"a _cents field"
206 )
207 assert field_type not in _FLOAT_MONEY_TYPES, (
208 f"{name}.{field_name} uses a float-shaped type {field_type!r}"
209 )
210
211
212def test_fin_accounts_has_the_five_real_account_types():
213 by_name = {f["name"]: f for f in _schema("fin_accounts")["fields"]}
214 account_type = by_name["account_type"]
215 assert account_type["type"] == "enum"
216 assert_includes_in_order(account_type["enum"], ["asset", "liability", "equity", "income", "expense"])
217 assert account_type["required"] is True
218
219
220def test_fin_accounts_parent_id_is_a_self_relation():
221 by_name = {f["name"]: f for f in _schema("fin_accounts")["fields"]}
222 parent = by_name["parent_id"]
223 assert parent["relation"]["collection"] == "fin_accounts"
224 assert "required" not in parent or not parent["required"]
225
226
227def test_fin_accounts_search_fields_match_the_brief():
228 schema = _schema("fin_accounts")
229 assert_includes_in_order(schema["search"]["fields"], ["name", "code"])
230
231
232def test_fin_journals_status_transition_is_draft_to_posted_owner_gated_only():
233 """No balance check anywhere in this guard -- posting is a bare status
234 flip, matching the source's own gap exactly (see dbbasic-package.json).
235 """
236 by_name = {f["name"]: f for f in _schema("fin_journals")["fields"]}
237 status = by_name["status"]
238 assert status["type"] == "enum"
239 assert_includes_in_order(status["enum"], ["draft", "posted"])
240 assert status["default"] == "draft"
241
242 transitions = status["transitions"]
243 assert transitions == {
244 "draft": [{"to": "posted", "when": {"owner_id": "$user_id"}}],
245 }
246 # posted is terminal: no entry in the transitions map at all.
247 assert "posted" not in transitions
248
249
250def test_fin_journals_status_help_documents_no_balance_enforcement():
251 by_name = {f["name"]: f for f in _schema("fin_journals")["fields"]}
252 help_text = by_name["status"]["help"].lower()
253 assert "not enforced" in help_text or "does not check" in help_text or "does not enforce" in help_text \
254 or "does not" in help_text
255
256
257def test_fin_journal_lines_uses_append_storage():
258 schema = _schema("fin_journal_lines")
259 assert schema["storage"] == "append"
260
261
262def test_fin_journal_lines_debit_and_credit_are_integer_cents():
263 by_name = {f["name"]: f for f in _schema("fin_journal_lines")["fields"]}
264 for name in ("debit_cents", "credit_cents"):
265 assert by_name[name]["type"] == "integer"
266 assert by_name[name]["default"] == "0"
267
268
269def test_fin_journal_lines_has_no_search_config():
270 schema = _schema("fin_journal_lines")
271 assert "search" not in schema
272
273
274def test_fin_journal_lines_relations_point_at_journals_and_accounts():
275 by_name = {f["name"]: f for f in _schema("fin_journal_lines")["fields"]}
276 assert by_name["journal_id"]["relation"]["collection"] == "fin_journals"
277 assert by_name["journal_id"]["required"] is True
278 assert by_name["account_id"]["relation"]["collection"] == "fin_accounts"
279 assert by_name["account_id"]["required"] is True
280
281
282def test_fin_recurring_fields_match_the_brief():
283 schema = _schema("fin_recurring")
284 by_name = {f["name"]: f for f in schema["fields"]}
285 assert_includes_in_order(by_name["frequency"]["enum"], ["daily", "weekly", "monthly", "quarterly", "yearly"])
286 assert by_name["frequency"]["default"] == "monthly"
287 assert by_name["auto_post"]["type"] == "boolean"
288 assert by_name["auto_post"]["default"] == "false"
289 assert by_name["is_active"]["type"] == "boolean"
290 assert by_name["is_active"]["default"] == "true"
291 assert by_name["template_lines"]["type"] == "textarea"
292 assert "next_run" in by_name
293 assert "last_run" in by_name
294
295
296def test_every_schema_has_created_at_read_only_and_owner_id():
297 for name in _SCHEMA_NAMES:
298 by_name = {f["name"]: f for f in _schema(name)["fields"]}
299 assert by_name["created_at"]["read_only"] is True
300 assert by_name["owner_id"]["type"] == "text"
301
302
303def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order():
304 """Header-only seeds, matching the established precedent (app-invoices,
305 app-orders, app-catalog, app-tasks, app-notes, app-contacts all ship
306 header-only seeds).
307 """
308 for name in _SCHEMA_NAMES:
309 schema = _schema(name)
310 path = APP_FINANCE_DIR / "seed" / f"{name}.tsv"
311 lines = path.read_text().splitlines()
312 if name in _SEEDED_REFERENCE:
313 # Reference data, not user data: an install that did not know
314 # USD divides into two places and BTC into eight could not render
315 # an amount at all, so these rows ship. Still schema-ordered, and
316 # every row is_system so operator-defined units stay separable.
317 assert len(lines) > 1, f"{name}.tsv is reference data and should ship rows"
318 assert all(row.split("\t")[6] == "true" for row in lines[1:])
319 else:
320 assert len(lines) == 1, f"{name}.tsv should be header-only"
321 header = lines[0].split("\t")
322 assert header == [f["name"] for f in schema["fields"]]
323
324
325def _app_finance_policy():
326 payload = json.loads((APP_FINANCE_DIR / "permissions" / "rules.json").read_text())
327 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
328
329
330def test_the_bookkeeper_and_the_owner_keep_the_books_and_a_customer_does_not():
331 """Decision 5 (owner, 2026-11-30): the chart of accounts and the
332 journals are the business's books, kept by role:finance (the bookkeeper)
333 and role:owner. They used to be every signed-in user's own rows -- a
334 customer could keep a chart, post journals, and read the journals the
335 books composed for their own payments."""
336 policy = _app_finance_policy()
337 customer = object_permissions.PermissionSubject(user_id="7")
338 for collection in ("fin_accounts", "fin_journals", "fin_journal_lines", "fin_recurring",
339 "fin_closed_periods"):
340 for action in (object_permissions.CREATE, object_permissions.READ):
341 decision = object_permissions.check_permission(
342 customer, action, policy=policy, collection=collection,
343 record={"owner_id": "7"} if action != object_permissions.CREATE else None)
344 assert decision.allowed is False, f"{collection}/{action} for a customer"
345 for role in ("finance", "owner"):
346 subject = object_permissions.PermissionSubject(user_id="7", roles=(role,))
347 _keeper_can_crud(policy, subject)
348
349
350def _keeper_can_crud(policy, subject):
351 records = {
352 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
353 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
354 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
355 "fin_recurring": {"owner_id": "7", "name": "Rent"},
356 }
357 for collection, record in records.items():
358 for action in (
359 object_permissions.CREATE, object_permissions.READ,
360 object_permissions.UPDATE, object_permissions.DELETE,
361 ):
362 decision = object_permissions.check_permission(
363 subject, action, policy=policy, collection=collection, record=record,
364 )
365 assert decision.allowed is True, f"{collection}/{action} should be allowed for {subject.roles}"
366
367
368def test_others_cannot_touch_someone_elses_records():
369 policy = _app_finance_policy()
370 subject = object_permissions.PermissionSubject(user_id="8")
371 records = {
372 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
373 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
374 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
375 "fin_recurring": {"owner_id": "7", "name": "Rent"},
376 }
377 for collection, record in records.items():
378 for action in (
379 object_permissions.READ, object_permissions.UPDATE, object_permissions.DELETE,
380 ):
381 decision = object_permissions.check_permission(
382 subject, action, policy=policy, collection=collection, record=record,
383 )
384 assert decision.allowed is False, f"{collection}/{action} should be denied for a non-owner"
385
386
387def test_anonymous_cannot_read_any_collection():
388 policy = _app_finance_policy()
389 records = {
390 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
391 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
392 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
393 "fin_recurring": {"owner_id": "7", "name": "Rent"},
394 }
395 for collection, record in records.items():
396 decision = object_permissions.check_permission(
397 None, object_permissions.READ, policy=policy, collection=collection, record=record,
398 )
399 assert decision.allowed is False
400
401
402def test_site_pages_are_publicly_executable():
403 """Public execute on the *page objects* (they show a sign-in prompt to
404 visitors), never public read on a collection -- same split app-invoices
405 and app-catalog use. Only on page objects this package SHIPS:
406 site_accounts and site_journals are seeded views now, and a grant for an
407 id nothing ships makes whatever is later created under that id public
408 (bug-reports/2026-11-28-06-14-43).
409 """
410 # site_journal_view is gone (stage-6 retrofit): the journal detail page
411 # is now site_view_render, granted public execute by app-views itself,
412 # not by a per-package rule here (see packages/app-views/permissions).
413 policy = _app_finance_policy()
414 for object_id, expected in (("site_trial_balance", True),
415 ("site_accounts", False), ("site_journals", False)):
416 decision = object_permissions.check_permission(
417 None, object_permissions.EXECUTE, policy=policy, object_id=object_id,
418 )
419 assert decision.allowed is expected, object_id
420
421
422def test_no_disallowed_org_names_leak_into_the_package():
423 """Public repo hygiene: no internal org/codename references anywhere
424 in this package's source.
425 """
426 # Built from fragments so this guard file itself stays clean of the very
427 # internal names it forbids (otherwise the test would flag its own source).
428 banned = re.compile(
429 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
430 re.IGNORECASE,
431 )
432 for path in APP_FINANCE_DIR.rglob("*"):
433 if "__pycache__" in path.parts:
434 continue # compiled bytes can match a name by chance
435 if path.is_dir():
436 continue
437 text = path.read_text(encoding="utf-8", errors="ignore")
438 assert not banned.search(text), f"disallowed reference found in {path}"
439
440
441def test_object_finance_module_has_no_disallowed_org_names():
442 """object_finance.py lives at the repo root, not inside packages/
443 app-finance/ (see dbbasic-package.json's description), so the repo-
444 hygiene sweep above never walks it -- covered here explicitly instead.
445 """
446 banned = re.compile(
447 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
448 re.IGNORECASE,
449 )
450 path = Path(__file__).resolve().parents[1] / "object_finance.py"
451 text = path.read_text(encoding="utf-8", errors="ignore")
452 assert not banned.search(text), f"disallowed reference found in {path}"
453
454
455# --- 0.11.0: the expenses index the attention count had been assuming --------
456#
457# 0.10.0 shipped a provider counting expenses at `submitted` and pointed it
458# at /expenses?status=submitted. `expenses` had a schema, a hook, a books
459# poster and a badge on the home page, and no route on the box served
460# /expenses -- so the queue was a number on a poster. Same fix as /accounts
461# and /journals got in 0.7.0: a views record, a route, a door.
462
463
464def _finance_seed_rows(name):
465 import csv
466
467 with open(APP_FINANCE_DIR / "seed" / f"{name}.tsv", newline="") as handle:
468 return list(csv.DictReader(handle, delimiter="\t"))
469
470
471def test_the_expenses_index_is_a_seeded_view_over_the_list_block():
472 rows = [row for row in _finance_seed_rows("views") if row["id"] == "view_expenses"]
473 assert len(rows) == 1
474 view = rows[0]
475 assert view["route"] == "/expenses"
476 blocks = json.loads(view["blocks"])
477 assert len(blocks) == 1
478 block = blocks[0]
479 assert block["kind"] == "list"
480 assert block["collection"] == "expenses"
481 assert block["add"] is True # claiming an expense is form work
482 assert block["link"] is False # /expenses/{id} is not seeded here
483
484
485def test_the_expenses_route_points_at_the_generic_renderer():
486 rows = [row for row in _finance_seed_rows("site_routes")
487 if row["id"] == "route_expenses_index"]
488 assert len(rows) == 1
489 assert rows[0]["pattern"] == "/expenses"
490 assert rows[0]["object_id"] == "site_view_render"
491
492
493def test_expenses_gets_a_money_door_beside_the_ledger_pages():
494 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
495 entry = next(row for row in package["nav"] if row["id"] == "expenses")
496
497 assert entry["path"] == "/expenses"
498 assert entry["group"] == "Money"
499 assert entry["surface"] == "member"
500
501
502def test_the_expenses_count_opens_the_index_and_claims_no_filter():
503 """The status filter comes from the schema's own filter_fields, drawn
504 as a bar on the page. Nothing reads it out of the URL, so the path
505 that ships is the honest index rather than a link that would land on
506 every expense while the badge beside it said four."""
507 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
508 source = next(row for row in package["attention"]
509 if row["id"] == "expenses_to_approve")
510
511 assert source["path"] == "/expenses"
512 assert "?" not in source["path"]
513 assert source["nav_id"] == "expenses"
514 assert "status" in _schema("expenses")["views"]["filter_fields"]