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

0 downloads

dbbasic-object-server/tests/test_app_finance_package.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_app_finance_package.py · 21.0 KB · 471 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
18
19PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
20APP_FINANCE_DIR = PACKAGES_ROOT / "app-finance"
21
22# Field types that store money as a float/decimal rather than integer cents
23# -- the doctrine this package must never violate (00-doctrine-and-contract.md).
24_FLOAT_MONEY_TYPES = {"float", "number", "currency"}
25
26# 0.4.0 added `denominations`: what a unit of value is and how finely it
27# divides (object_money.py). Amounts are integers of the smallest unit, so
28# this is the collection that says where the decimal point goes.
29_SCHEMA_NAMES = ("denominations", "rates", "fin_accounts", "fin_journals",
30 "fin_journal_lines", "fin_recurring",
31 # 0.7.0: settled books stay settled -- the closed-period
32 # gate the predecessor modeled and this system lacked.
33 "fin_closed_periods",
34 # 0.9.0: the materials half of time and materials. An
35 # expense is an accounting fact first and a billable item
36 # second, which is why it lives with the books.
37 "expenses")
38
39# Collections that are shared REFERENCE data rather than per-owner business
40# records: a denomination is the same fact in every set of books (gold is
41# gold), so unlike the rest of finance it carries no entity_id scoping FK
42# and it ships seeded rows instead of a bare header. `rates` is shared in the
43# same way (an observed price is not owned by one set of books) but ships
44# header-only, since rates are fetched rather than seeded.
45_REFERENCE_COLLECTIONS = ("denominations", "rates")
46_SEEDED_REFERENCE = ("denominations",)
47
48
49def _schema(name):
50 return json.loads((APP_FINANCE_DIR / "schemas" / f"{name}.json").read_text())
51
52
53def test_get_package_normalizes_app_finance_manifest():
54 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
55
56 assert package["id"] == "app-finance"
57 assert package["name"] == "Finance"
58 assert {schema["collection"] for schema in package["schemas"]} == set(_SCHEMA_NAMES)
59 # site_setup_accounts (65 slice 4) added the Setup Accounts action object.
60 # site_journal_view was retrofitted away (stage-6): the journal detail
61 # page is now a seeded 59 view (site_view_render), not a bespoke object.
62 # hook_fin_journals: the balance-enforcement pre-write hook (internal --
63 # no public execute rule; the write path runs it, never HTTP).
64 # 0.7.0 deletes the bespoke /accounts and /journals list page objects
65 # too: both held no business logic and are now seeded VIEW records over
66 # the generic `list` block.
67 assert {obj["id"] for obj in package["objects"]} == {
68 "site_trial_balance",
69 "site_setup_accounts", "hook_fin_journals",
70 # 0.7.0: the line-side closed-period gate -- a journal's amounts
71 # live in its lines, so freezing the journal alone froze nothing.
72 "hook_fin_journal_lines",
73 "action_reverse_journal", "system_fin_recurring_runner",
74 # 0.6.0: the P&L + balance sheet page, the two statements this
75 # package listed as deferred from v1 (object_finance.py's docstring).
76 "site_statements",
77 # 0.9.0: expenses -- the approval gate and the journal it composes.
78 "hook_expenses", "system_expense_books",
79 # 0.10.0: what "needs a human" means here -- expenses at
80 # `submitted`, counted for the home page's attention band.
81 "system_expense_attention",
82 }
83 assert package["permissions"] == [{"path": "permissions/rules.json"}]
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 assert payload["version"] == 7
153 assert payload["views"]["filter_fields"] == ["status", "kind"]
154 assert payload["hooks"] == {"before_write": "hook_fin_journals"}
155 assert payload["views"]["list_mode"] == "table"
156 else:
157 # fin_journal_lines: 2 -> 3 (hooks.before_write, closed periods);
158 # fin_recurring stays at 2 (entity_id).
159 if payload["name"] == "fin_journal_lines":
160 assert payload["version"] == 3
161 assert payload["hooks"] == {"before_write": "hook_fin_journal_lines"}
162 elif payload["name"] in ("fin_closed_periods", "expenses"):
163 assert payload["version"] == 1 # new in 0.7.0 / 0.9.0
164 else:
165 assert payload["version"] == 2
166 assert payload["views"]["list_mode"] == "table"
167
168
169def test_no_money_field_uses_a_float_or_currency_type():
170 for name in _SCHEMA_NAMES:
171 for field in _schema(name)["fields"]:
172 field_name = field["name"]
173 field_type = field.get("type")
174 if "_cents" in field_name:
175 # A derived money field (rollup sum of integer-cents inputs)
176 # is `computed`; every stored/writable money field stays
177 # integer. Both keep money out of float-shaped types.
178 assert field_type in ("integer", "computed"), (
179 f"{name}.{field_name} must be integer (or computed over "
180 f"integers), got {field_type!r}"
181 )
182 if field_type == "computed":
183 rollup = field.get("rollup") or {}
184 assert rollup.get("field", "").endswith("_cents"), (
185 f"{name}.{field_name} computed money must derive from "
186 f"a _cents field"
187 )
188 assert field_type not in _FLOAT_MONEY_TYPES, (
189 f"{name}.{field_name} uses a float-shaped type {field_type!r}"
190 )
191
192
193def test_fin_accounts_has_the_five_real_account_types():
194 by_name = {f["name"]: f for f in _schema("fin_accounts")["fields"]}
195 account_type = by_name["account_type"]
196 assert account_type["type"] == "enum"
197 assert account_type["enum"] == ["asset", "liability", "equity", "income", "expense"]
198 assert account_type["required"] is True
199
200
201def test_fin_accounts_parent_id_is_a_self_relation():
202 by_name = {f["name"]: f for f in _schema("fin_accounts")["fields"]}
203 parent = by_name["parent_id"]
204 assert parent["relation"]["collection"] == "fin_accounts"
205 assert "required" not in parent or not parent["required"]
206
207
208def test_fin_accounts_search_fields_match_the_brief():
209 schema = _schema("fin_accounts")
210 assert schema["search"]["fields"] == ["name", "code"]
211
212
213def test_fin_journals_status_transition_is_draft_to_posted_owner_gated_only():
214 """No balance check anywhere in this guard -- posting is a bare status
215 flip, matching the source's own gap exactly (see dbbasic-package.json).
216 """
217 by_name = {f["name"]: f for f in _schema("fin_journals")["fields"]}
218 status = by_name["status"]
219 assert status["type"] == "enum"
220 assert status["enum"] == ["draft", "posted"]
221 assert status["default"] == "draft"
222
223 transitions = status["transitions"]
224 assert transitions == {
225 "draft": [{"to": "posted", "when": {"owner_id": "$user_id"}}],
226 }
227 # posted is terminal: no entry in the transitions map at all.
228 assert "posted" not in transitions
229
230
231def test_fin_journals_status_help_documents_no_balance_enforcement():
232 by_name = {f["name"]: f for f in _schema("fin_journals")["fields"]}
233 help_text = by_name["status"]["help"].lower()
234 assert "not enforced" in help_text or "does not check" in help_text or "does not enforce" in help_text \
235 or "does not" in help_text
236
237
238def test_fin_journal_lines_uses_append_storage():
239 schema = _schema("fin_journal_lines")
240 assert schema["storage"] == "append"
241
242
243def test_fin_journal_lines_debit_and_credit_are_integer_cents():
244 by_name = {f["name"]: f for f in _schema("fin_journal_lines")["fields"]}
245 for name in ("debit_cents", "credit_cents"):
246 assert by_name[name]["type"] == "integer"
247 assert by_name[name]["default"] == "0"
248
249
250def test_fin_journal_lines_has_no_search_config():
251 schema = _schema("fin_journal_lines")
252 assert "search" not in schema
253
254
255def test_fin_journal_lines_relations_point_at_journals_and_accounts():
256 by_name = {f["name"]: f for f in _schema("fin_journal_lines")["fields"]}
257 assert by_name["journal_id"]["relation"]["collection"] == "fin_journals"
258 assert by_name["journal_id"]["required"] is True
259 assert by_name["account_id"]["relation"]["collection"] == "fin_accounts"
260 assert by_name["account_id"]["required"] is True
261
262
263def test_fin_recurring_fields_match_the_brief():
264 schema = _schema("fin_recurring")
265 by_name = {f["name"]: f for f in schema["fields"]}
266 assert by_name["frequency"]["enum"] == ["daily", "weekly", "monthly", "quarterly", "yearly"]
267 assert by_name["frequency"]["default"] == "monthly"
268 assert by_name["auto_post"]["type"] == "boolean"
269 assert by_name["auto_post"]["default"] == "false"
270 assert by_name["is_active"]["type"] == "boolean"
271 assert by_name["is_active"]["default"] == "true"
272 assert by_name["template_lines"]["type"] == "textarea"
273 assert "next_run" in by_name
274 assert "last_run" in by_name
275
276
277def test_every_schema_has_created_at_read_only_and_owner_id():
278 for name in _SCHEMA_NAMES:
279 by_name = {f["name"]: f for f in _schema(name)["fields"]}
280 assert by_name["created_at"]["read_only"] is True
281 assert by_name["owner_id"]["type"] == "text"
282
283
284def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order():
285 """Header-only seeds, matching the established precedent (app-invoices,
286 app-orders, app-catalog, app-tasks, app-notes, app-contacts all ship
287 header-only seeds).
288 """
289 for name in _SCHEMA_NAMES:
290 schema = _schema(name)
291 path = APP_FINANCE_DIR / "seed" / f"{name}.tsv"
292 lines = path.read_text().splitlines()
293 if name in _SEEDED_REFERENCE:
294 # Reference data, not user data: an install that did not know
295 # USD divides into two places and BTC into eight could not render
296 # an amount at all, so these rows ship. Still schema-ordered, and
297 # every row is_system so operator-defined units stay separable.
298 assert len(lines) > 1, f"{name}.tsv is reference data and should ship rows"
299 assert all(row.split("\t")[6] == "true" for row in lines[1:])
300 else:
301 assert len(lines) == 1, f"{name}.tsv should be header-only"
302 header = lines[0].split("\t")
303 assert header == [f["name"] for f in schema["fields"]]
304
305
306def _app_finance_policy():
307 payload = json.loads((APP_FINANCE_DIR / "permissions" / "rules.json").read_text())
308 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
309
310
311def test_owner_can_crud_own_records_in_every_collection():
312 policy = _app_finance_policy()
313 subject = object_permissions.PermissionSubject(user_id="7")
314 records = {
315 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
316 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
317 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
318 "fin_recurring": {"owner_id": "7", "name": "Rent"},
319 }
320 for collection, record in records.items():
321 for action in (
322 object_permissions.CREATE, object_permissions.READ,
323 object_permissions.UPDATE, object_permissions.DELETE,
324 ):
325 decision = object_permissions.check_permission(
326 subject, action, policy=policy, collection=collection, record=record,
327 )
328 assert decision.allowed is True, f"{collection}/{action} should be allowed for the owner"
329
330
331def test_others_cannot_touch_someone_elses_records():
332 policy = _app_finance_policy()
333 subject = object_permissions.PermissionSubject(user_id="8")
334 records = {
335 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
336 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
337 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
338 "fin_recurring": {"owner_id": "7", "name": "Rent"},
339 }
340 for collection, record in records.items():
341 for action in (
342 object_permissions.READ, object_permissions.UPDATE, object_permissions.DELETE,
343 ):
344 decision = object_permissions.check_permission(
345 subject, action, policy=policy, collection=collection, record=record,
346 )
347 assert decision.allowed is False, f"{collection}/{action} should be denied for a non-owner"
348
349
350def test_anonymous_cannot_read_any_collection():
351 policy = _app_finance_policy()
352 records = {
353 "fin_accounts": {"owner_id": "7", "name": "Cash", "account_type": "asset"},
354 "fin_journals": {"owner_id": "7", "date": "2026-07-01", "status": "draft"},
355 "fin_journal_lines": {"owner_id": "7", "journal_id": "j_1", "account_id": "a_1"},
356 "fin_recurring": {"owner_id": "7", "name": "Rent"},
357 }
358 for collection, record in records.items():
359 decision = object_permissions.check_permission(
360 None, object_permissions.READ, policy=policy, collection=collection, record=record,
361 )
362 assert decision.allowed is False
363
364
365def test_site_pages_are_publicly_executable():
366 """Public execute on the *page objects* (they show a sign-in prompt to
367 visitors), never public read on a collection -- same split app-invoices
368 and app-catalog use.
369 """
370 # site_journal_view is gone (stage-6 retrofit): the journal detail page
371 # is now site_view_render, granted public execute by app-views itself,
372 # not by a per-package rule here (see packages/app-views/permissions).
373 policy = _app_finance_policy()
374 for object_id in ("site_accounts", "site_journals", "site_trial_balance"):
375 decision = object_permissions.check_permission(
376 None, object_permissions.EXECUTE, policy=policy, object_id=object_id,
377 )
378 assert decision.allowed is True
379
380
381def test_no_disallowed_org_names_leak_into_the_package():
382 """Public repo hygiene: no internal org/codename references anywhere
383 in this package's source.
384 """
385 # Built from fragments so this guard file itself stays clean of the very
386 # internal names it forbids (otherwise the test would flag its own source).
387 banned = re.compile(
388 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
389 re.IGNORECASE,
390 )
391 for path in APP_FINANCE_DIR.rglob("*"):
392 if path.is_dir():
393 continue
394 text = path.read_text(encoding="utf-8", errors="ignore")
395 assert not banned.search(text), f"disallowed reference found in {path}"
396
397
398def test_object_finance_module_has_no_disallowed_org_names():
399 """object_finance.py lives at the repo root, not inside packages/
400 app-finance/ (see dbbasic-package.json's description), so the repo-
401 hygiene sweep above never walks it -- covered here explicitly instead.
402 """
403 banned = re.compile(
404 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
405 re.IGNORECASE,
406 )
407 path = Path(__file__).resolve().parents[1] / "object_finance.py"
408 text = path.read_text(encoding="utf-8", errors="ignore")
409 assert not banned.search(text), f"disallowed reference found in {path}"
410
411
412# --- 0.11.0: the expenses index the attention count had been assuming --------
413#
414# 0.10.0 shipped a provider counting expenses at `submitted` and pointed it
415# at /expenses?status=submitted. `expenses` had a schema, a hook, a books
416# poster and a badge on the home page, and no route on the box served
417# /expenses -- so the queue was a number on a poster. Same fix as /accounts
418# and /journals got in 0.7.0: a views record, a route, a door.
419
420
421def _finance_seed_rows(name):
422 import csv
423
424 with open(APP_FINANCE_DIR / "seed" / f"{name}.tsv", newline="") as handle:
425 return list(csv.DictReader(handle, delimiter="\t"))
426
427
428def test_the_expenses_index_is_a_seeded_view_over_the_list_block():
429 rows = [row for row in _finance_seed_rows("views") if row["id"] == "view_expenses"]
430 assert len(rows) == 1
431 view = rows[0]
432 assert view["route"] == "/expenses"
433 blocks = json.loads(view["blocks"])
434 assert len(blocks) == 1
435 block = blocks[0]
436 assert block["kind"] == "list"
437 assert block["collection"] == "expenses"
438 assert block["add"] is True # claiming an expense is form work
439 assert block["link"] is False # /expenses/{id} is not seeded here
440
441
442def test_the_expenses_route_points_at_the_generic_renderer():
443 rows = [row for row in _finance_seed_rows("site_routes")
444 if row["id"] == "route_expenses_index"]
445 assert len(rows) == 1
446 assert rows[0]["pattern"] == "/expenses"
447 assert rows[0]["object_id"] == "site_view_render"
448
449
450def test_expenses_gets_a_money_door_beside_the_ledger_pages():
451 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
452 entry = next(row for row in package["nav"] if row["id"] == "expenses")
453
454 assert entry["path"] == "/expenses"
455 assert entry["group"] == "Money"
456 assert entry["surface"] == "member"
457
458
459def test_the_expenses_count_opens_the_index_and_claims_no_filter():
460 """The status filter comes from the schema's own filter_fields, drawn
461 as a bar on the page. Nothing reads it out of the URL, so the path
462 that ships is the honest index rather than a link that would land on
463 every expense while the badge beside it said four."""
464 package = object_packages.get_package("app-finance", root=PACKAGES_ROOT)
465 source = next(row for row in package["attention"]
466 if row["id"] == "expenses_to_approve")
467
468 assert source["path"] == "/expenses"
469 assert "?" not in source["path"]
470 assert source["nav_id"] == "expenses"
471 assert "status" in _schema("expenses")["views"]["filter_fields"]