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_app_invoices_package.py · 17.9 KB · 404 lines
| 1 | """Structural tests for packages/app-invoices (invoices, quotes, credit notes). |
| 2 | |
| 3 | Mirrors the package/schema/permission testing conventions used for |
| 4 | packages/app-notes and packages/app-tasks in tests/test_app_settings_package.py |
| 5 | and tests/test_app_views_package.py. Behavior tests for the invoice_totals |
| 6 | HANDLES handler live in tests/test_app_invoices_totals.py. |
| 7 | """ |
| 8 | |
| 9 | import json |
| 10 | import re |
| 11 | from pathlib import Path |
| 12 | |
| 13 | import object_packages |
| 14 | import object_permissions |
| 15 | import object_schemas |
| 16 | from package_pins import assert_includes_in_order |
| 17 | |
| 18 | PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages" |
| 19 | APP_INVOICES_DIR = PACKAGES_ROOT / "app-invoices" |
| 20 | |
| 21 | # Field types that store money as a float/decimal rather than integer cents |
| 22 | # -- the doctrine this package must never violate (00-doctrine-and-contract.md, |
| 23 | # plan/vocabulary/20-invoice-spec.md's "Money, stated as a hard rule" section). |
| 24 | _FLOAT_MONEY_TYPES = {"float", "number", "currency"} |
| 25 | |
| 26 | # quantity is the one deliberate exception: a count/measure (e.g. 2.5 |
| 27 | # hours), not currency. |
| 28 | _ALLOWED_FLOAT_FIELDS = {"quantity"} |
| 29 | |
| 30 | |
| 31 | def _invoices_schema(): |
| 32 | return json.loads((APP_INVOICES_DIR / "schemas" / "invoices.json").read_text()) |
| 33 | |
| 34 | |
| 35 | def _invoice_lines_schema(): |
| 36 | return json.loads((APP_INVOICES_DIR / "schemas" / "invoice_lines.json").read_text()) |
| 37 | |
| 38 | |
| 39 | def test_get_package_normalizes_app_invoices_manifest(): |
| 40 | package = object_packages.get_package("app-invoices", root=PACKAGES_ROOT) |
| 41 | |
| 42 | assert package["id"] == "app-invoices" |
| 43 | assert package["name"] == "Invoices" |
| 44 | assert {schema["collection"] for schema in package["schemas"]} >= { |
| 45 | "invoices", |
| 46 | "invoice_lines", |
| 47 | } |
| 48 | # 0.6.0 deletes the bespoke /invoices list page object: it held no |
| 49 | # business logic and is now a seeded VIEW record over the generic |
| 50 | # `list` block. |
| 51 | assert {obj["id"] for obj in package["objects"]} >= { |
| 52 | "system_invoice_totals", |
| 53 | "system_invoice_aging", # aging + dunning runner (payments slice 2) |
| 54 | # 0.5.0 portal: the page a dunning email can finally point at, the |
| 55 | # regenerate verb for a leaked link, and the handler that mints a |
| 56 | # token the moment an invoice leaves draft. |
| 57 | "site_invoice_portal", |
| 58 | "action_regenerate_portal_link", |
| 59 | "system_invoice_portal_link", |
| 60 | # 0.8.0 time and materials: approved hours become one invoice, the |
| 61 | # last mile of the consulting billing mode. |
| 62 | "action_generate_tm_invoice", |
| 63 | # 0.9.0 shipped system_invoice_attention for invoices past their |
| 64 | # due date; 0.14.0 declares that count in the manifest instead. |
| 65 | } |
| 66 | assert {"path": "permissions/rules.json"} in package["permissions"] |
| 67 | assert {entry["collection"] for entry in package["seed"]} >= { |
| 68 | "invoices", |
| 69 | "invoice_lines", |
| 70 | "views", |
| 71 | "site_routes", |
| 72 | "notify_rules", |
| 73 | } |
| 74 | |
| 75 | |
| 76 | def test_dry_run_app_invoices_package_is_safe(tmp_path): |
| 77 | object_root = tmp_path / "objects" |
| 78 | object_root.mkdir() |
| 79 | |
| 80 | plan = object_packages.dry_run_package( |
| 81 | "app-invoices", |
| 82 | root=PACKAGES_ROOT, |
| 83 | base_dir=tmp_path / "data", |
| 84 | object_roots=[object_root], |
| 85 | ) |
| 86 | |
| 87 | assert plan["safe_to_install"] is True |
| 88 | assert plan["warnings"] == [] |
| 89 | assert {schema["collection"] for schema in plan["schemas"]} >= { |
| 90 | "invoices", |
| 91 | "invoice_lines", |
| 92 | } |
| 93 | |
| 94 | |
| 95 | def test_install_app_invoices_package_loads_schemas(tmp_path): |
| 96 | data_dir = tmp_path / "data" |
| 97 | object_root = tmp_path / "objects" |
| 98 | object_root.mkdir() |
| 99 | |
| 100 | object_packages.install_package( |
| 101 | "app-invoices", |
| 102 | root=PACKAGES_ROOT, |
| 103 | base_dir=data_dir, |
| 104 | object_roots=[object_root], |
| 105 | ) |
| 106 | |
| 107 | invoices_schema = object_schemas.get_schema("invoices", base_dir=data_dir) |
| 108 | lines_schema = object_schemas.get_schema("invoice_lines", base_dir=data_dir) |
| 109 | |
| 110 | assert invoices_schema["name"] == "invoices" |
| 111 | assert lines_schema["name"] == "invoice_lines" |
| 112 | # invoices.py was deleted (0.6.0): the /invoices list page is now a |
| 113 | # seeded VIEW record over the generic `list` block. |
| 114 | assert not (object_root / "site" / "invoices.py").exists() |
| 115 | assert (object_root / "system" / "invoice_totals.py").is_file() |
| 116 | |
| 117 | |
| 118 | def test_schema_json_files_are_valid_and_versioned(): |
| 119 | for name in ("invoices", "invoice_lines"): |
| 120 | payload = json.loads((APP_INVOICES_DIR / "schemas" / f"{name}.json").read_text()) |
| 121 | assert payload["name"] == name |
| 122 | # invoices v2: paid/balance became derived (app-payments rollups/ |
| 123 | # formulas). v3: dunning fields + lifecycle arcs. v4: the portal |
| 124 | # capability URL (portal_token, read_only) plus view counters, which |
| 125 | # tell "viewed three times, still unpaid" apart from "never opened". |
| 126 | # v6: generated_from (read_only), the biller's provenance stamp, which |
| 127 | # used to live in the editable notes field. v7: number_key |
| 128 | # (read_only, unique), the claim that keeps two generated invoices |
| 129 | # from sharing a number. |
| 130 | assert payload["version"] >= (7 if name == "invoices" else 1) |
| 131 | if name == "invoices": |
| 132 | assert payload["unique"] == [ |
| 133 | {"fields": ["number_key"], |
| 134 | "message": "That invoice number has already been issued."}] |
| 135 | assert payload["views"]["list_mode"] == "table" |
| 136 | |
| 137 | |
| 138 | def test_no_money_field_uses_a_float_or_currency_type(): |
| 139 | """00-doctrine-and-contract.md's hard rule: money is *_cents integers, |
| 140 | never object_records.py's _FLOAT_TYPES = {"float", "number", "currency"}. |
| 141 | quantity is the one documented, deliberate exception -- it is a count, |
| 142 | not currency. |
| 143 | """ |
| 144 | for schema in (_invoices_schema(), _invoice_lines_schema()): |
| 145 | for field in schema["fields"]: |
| 146 | name = field["name"] |
| 147 | field_type = field.get("type") |
| 148 | if name in _ALLOWED_FLOAT_FIELDS: |
| 149 | continue |
| 150 | if "_cents" in name or name in {"balance_due_cents"}: |
| 151 | assert field_type in ("integer", "computed"), f"{schema['name']}.{name} must be integer or computed-over-cents, got {field_type!r}" |
| 152 | assert field_type not in _FLOAT_MONEY_TYPES, ( |
| 153 | f"{schema['name']}.{name} uses a float-shaped type {field_type!r}" |
| 154 | ) |
| 155 | |
| 156 | |
| 157 | def test_every_cents_field_is_present_and_integer(): |
| 158 | invoices_by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 159 | for name in ( |
| 160 | "subtotal_cents", "tax_cents", "total_cents", |
| 161 | "amount_paid_cents", "balance_due_cents", |
| 162 | ): |
| 163 | expected = "computed" if name in ("amount_paid_cents", "balance_due_cents", "payments_received_cents", "refunded_cents") else "integer" |
| 164 | assert invoices_by_name[name]["type"] == expected |
| 165 | if expected == "integer": |
| 166 | assert invoices_by_name[name]["default"] == "0" |
| 167 | |
| 168 | lines_by_name = {f["name"]: f for f in _invoice_lines_schema()["fields"]} |
| 169 | for name in ("unit_price_cents", "line_total_cents", "line_tax_cents"): |
| 170 | assert lines_by_name[name]["type"] == "integer" |
| 171 | |
| 172 | |
| 173 | def test_stamped_totals_fields_are_not_schema_read_only(): |
| 174 | """Deliberate deviation from the task brief, documented in |
| 175 | dbbasic-package.json and objects/system/invoice_totals.py's module |
| 176 | docstring: update_collection_record has no read_only write exception, |
| 177 | so a genuinely read_only field could never be re-stamped by the |
| 178 | totals handler after the first write. These fields stay ordinary |
| 179 | owner-writable fields and are protected by omission from |
| 180 | forms.default instead (UI-only, matches |
| 181 | plan/vocabulary/20-invoice-spec.md's own already-reasoned posture). |
| 182 | """ |
| 183 | invoices_by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 184 | for name in ("subtotal_cents", "tax_cents", "total_cents", "balance_due_cents"): |
| 185 | assert not invoices_by_name[name].get("read_only") |
| 186 | assert name not in _invoices_schema()["forms"]["default"]["fields"] |
| 187 | |
| 188 | lines_by_name = {f["name"]: f for f in _invoice_lines_schema()["fields"]} |
| 189 | for name in ("line_total_cents", "line_tax_cents"): |
| 190 | assert not lines_by_name[name].get("read_only") |
| 191 | assert name not in _invoice_lines_schema()["forms"]["default"]["fields"] |
| 192 | |
| 193 | # invoice_lines.invoice_id: required at creation, so it also cannot be |
| 194 | # schema read_only (the server rejects any client submission of a |
| 195 | # read_only field, including the first one) -- see the field's own |
| 196 | # "help" text and the schema test below. |
| 197 | assert lines_by_name["invoice_id"]["required"] is True |
| 198 | assert not lines_by_name["invoice_id"].get("read_only") |
| 199 | |
| 200 | # created_at is the one field that IS read_only in both schemas: it is |
| 201 | # special-cased server-side (_apply_auto_created_at), unlike every |
| 202 | # other read_only field. |
| 203 | assert invoices_by_name["created_at"]["read_only"] is True |
| 204 | assert lines_by_name["created_at"]["read_only"] is True |
| 205 | |
| 206 | |
| 207 | def test_invoices_status_transitions_match_the_brief(): |
| 208 | """The map of moves is the brief's. Who may make them is not on the map |
| 209 | since app-invoices 0.15.0: the owner_id guards are gone, because the |
| 210 | owner of a machine-raised invoice is the customer it bills, and the |
| 211 | status field's permissions (staff edit, everyone else read) say who.""" |
| 212 | status_field = next(f for f in _invoices_schema()["fields"] if f["name"] == "status") |
| 213 | assert_includes_in_order(status_field["enum"], ["draft", "sent", "paid", "partial", "overdue", "void"]) |
| 214 | assert status_field["default"] == "draft" |
| 215 | |
| 216 | transitions = status_field["transitions"] |
| 217 | assert set(transitions["draft"]) == {"sent", "void"} |
| 218 | # v13 (decision 1, 2026-11-30): status follows the money, and money can |
| 219 | # move back -- a bounced, deleted or refunded payment reopens a paid |
| 220 | # invoice, a credit note settles one -- so any money state may follow |
| 221 | # any other. void stays reachable only from an unpaid state, and is |
| 222 | # terminal. |
| 223 | money = {"sent", "partial", "overdue", "paid", "credit_owed", "refunded", "credited"} |
| 224 | assert money <= set(status_field["enum"]) |
| 225 | for state in money: |
| 226 | unpaid = state in ("sent", "partial", "overdue") |
| 227 | assert set(transitions[state]) == (money - {state}) | ({"void"} if unpaid else set()), state |
| 228 | assert "void" not in transitions |
| 229 | assert status_field["permissions"] == {"edit": ["role:manager", "role:admin"], |
| 230 | "default": "read"} |
| 231 | |
| 232 | |
| 233 | def test_customer_snapshot_fields_present_alongside_optional_relation(): |
| 234 | """plan/vocabulary/20-invoice-spec.md's 'standalone-with-optional- |
| 235 | relation, not a hard app-contacts coupling' decision: customer_id is |
| 236 | an optional cross-reference; the snapshot fields are what renders. |
| 237 | """ |
| 238 | by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 239 | assert by_name["customer_id"]["relation"]["collection"] == "contacts" |
| 240 | assert "required" not in by_name["customer_id"] or not by_name["customer_id"]["required"] |
| 241 | assert by_name["customer_name"]["required"] is True |
| 242 | |
| 243 | |
| 244 | def _app_invoices_policy(): |
| 245 | payload = json.loads((APP_INVOICES_DIR / "permissions" / "rules.json").read_text()) |
| 246 | return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]}) |
| 247 | |
| 248 | |
| 249 | def test_owner_can_create_read_update_but_not_delete_own_invoice(): |
| 250 | """No delete since 0.15.0: an issued invoice is voided, and the owner of |
| 251 | a machine-raised one is the customer it bills.""" |
| 252 | policy = _app_invoices_policy() |
| 253 | subject = object_permissions.PermissionSubject(user_id="7") |
| 254 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 255 | |
| 256 | for action in ( |
| 257 | object_permissions.CREATE, |
| 258 | object_permissions.READ, |
| 259 | object_permissions.UPDATE, |
| 260 | ): |
| 261 | decision = object_permissions.check_permission( |
| 262 | subject, action, policy=policy, collection="invoices", record=record |
| 263 | ) |
| 264 | assert decision.allowed is True |
| 265 | assert not object_permissions.check_permission( |
| 266 | subject, object_permissions.DELETE, policy=policy, collection="invoices", |
| 267 | record=record).allowed |
| 268 | |
| 269 | |
| 270 | def test_others_cannot_touch_someone_elses_invoice(): |
| 271 | policy = _app_invoices_policy() |
| 272 | subject = object_permissions.PermissionSubject(user_id="8") |
| 273 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 274 | |
| 275 | for action in ( |
| 276 | object_permissions.READ, |
| 277 | object_permissions.UPDATE, |
| 278 | object_permissions.DELETE, |
| 279 | ): |
| 280 | decision = object_permissions.check_permission( |
| 281 | subject, action, policy=policy, collection="invoices", record=record |
| 282 | ) |
| 283 | assert decision.allowed is False |
| 284 | |
| 285 | |
| 286 | def test_anonymous_cannot_read_any_invoice(): |
| 287 | """No public read rule is granted on the invoices collection at all -- |
| 288 | the tokenized public view is a later slice (see dbbasic-package.json). |
| 289 | """ |
| 290 | policy = _app_invoices_policy() |
| 291 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 292 | |
| 293 | decision = object_permissions.check_permission( |
| 294 | None, object_permissions.READ, policy=policy, collection="invoices", record=record |
| 295 | ) |
| 296 | assert decision.allowed is False |
| 297 | |
| 298 | |
| 299 | def test_owner_can_create_read_update_but_not_delete_own_invoice_lines(): |
| 300 | policy = _app_invoices_policy() |
| 301 | subject = object_permissions.PermissionSubject(user_id="7") |
| 302 | record = {"owner_id": "7", "invoice_id": "inv_1", "description": "Consulting"} |
| 303 | |
| 304 | for action in ( |
| 305 | object_permissions.CREATE, |
| 306 | object_permissions.READ, |
| 307 | object_permissions.UPDATE, |
| 308 | ): |
| 309 | decision = object_permissions.check_permission( |
| 310 | subject, action, policy=policy, collection="invoice_lines", record=record |
| 311 | ) |
| 312 | assert decision.allowed is True |
| 313 | assert not object_permissions.check_permission( |
| 314 | subject, object_permissions.DELETE, policy=policy, collection="invoice_lines", |
| 315 | record=record).allowed |
| 316 | |
| 317 | |
| 318 | def test_others_cannot_touch_someone_elses_invoice_lines(): |
| 319 | policy = _app_invoices_policy() |
| 320 | subject = object_permissions.PermissionSubject(user_id="8") |
| 321 | record = {"owner_id": "7", "invoice_id": "inv_1", "description": "Consulting"} |
| 322 | |
| 323 | for action in ( |
| 324 | object_permissions.READ, |
| 325 | object_permissions.UPDATE, |
| 326 | object_permissions.DELETE, |
| 327 | ): |
| 328 | decision = object_permissions.check_permission( |
| 329 | subject, action, policy=policy, collection="invoice_lines", record=record |
| 330 | ) |
| 331 | assert decision.allowed is False |
| 332 | |
| 333 | |
| 334 | def test_the_deleted_invoices_page_keeps_no_public_execute_grant(): |
| 335 | """The site_invoices object was deleted in 0.6.0 (the /invoices list |
| 336 | page is a seeded VIEW record, the detail permalink a 59 view rendered by |
| 337 | site_view_render -- see tests/test_app_invoices_detail_retrofit.py), and |
| 338 | so is its public-execute rule: a grant for an id nothing ships made |
| 339 | whatever was later created under that id public without anybody |
| 340 | deciding so (bug-reports/2026-11-28-06-14-43).""" |
| 341 | policy = _app_invoices_policy() |
| 342 | |
| 343 | decision = object_permissions.check_permission( |
| 344 | None, object_permissions.EXECUTE, policy=policy, object_id="site_invoices" |
| 345 | ) |
| 346 | assert decision.allowed is False |
| 347 | |
| 348 | |
| 349 | def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order(): |
| 350 | """Both seed files ship header-only (no starter data), matching the |
| 351 | established precedent (app-tasks, app-notes, app-contacts all ship |
| 352 | header-only seeds; only app-settings/ai_prices.tsv, live operational |
| 353 | config, ships rows). The header order matches the schema's own field |
| 354 | order for readability. |
| 355 | """ |
| 356 | for name, schema in (("invoices", _invoices_schema()), ("invoice_lines", _invoice_lines_schema())): |
| 357 | path = APP_INVOICES_DIR / "seed" / f"{name}.tsv" |
| 358 | lines = path.read_text().splitlines() |
| 359 | assert len(lines) == 1, f"{name}.tsv should be header-only" |
| 360 | header = lines[0].split("\t") |
| 361 | assert header == [f["name"] for f in schema["fields"]] |
| 362 | |
| 363 | |
| 364 | def test_no_disallowed_org_names_leak_into_the_package(): |
| 365 | """Public repo hygiene: no internal org/codename references anywhere |
| 366 | in this package's source. |
| 367 | """ |
| 368 | # Built from fragments so this guard file itself stays clean of the very |
| 369 | # internal names it forbids (otherwise the test would flag its own source). |
| 370 | banned = re.compile( |
| 371 | "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]), |
| 372 | re.IGNORECASE, |
| 373 | ) |
| 374 | for path in APP_INVOICES_DIR.rglob("*"): |
| 375 | if "__pycache__" in path.parts: |
| 376 | continue # compiled bytes can match a name by chance |
| 377 | if path.is_dir(): |
| 378 | continue |
| 379 | text = path.read_text(encoding="utf-8", errors="ignore") |
| 380 | assert not banned.search(text), f"disallowed reference found in {path}" |
| 381 | |
| 382 | |
| 383 | def test_the_overdue_count_names_every_unsettled_status(): |
| 384 | """The declared overdue count says which statuses are still owed as a |
| 385 | list, because a list is what the index can read; the provider it |
| 386 | replaced said which were SETTLED (paid, void, draft -- a draft was never |
| 387 | sent, so it cannot be late). The two are the same only while the list |
| 388 | plus the settled three is the whole enum plus blank. A status added to |
| 389 | the enum later fails here rather than silently never being overdue.""" |
| 390 | manifest = json.loads((APP_INVOICES_DIR / "dbbasic-package.json").read_text()) |
| 391 | [entry] = [e for e in manifest["attention"] if e["id"] == "invoices_overdue"] |
| 392 | owed = set(entry["where"]["status"]["value"]) |
| 393 | schema = json.loads((APP_INVOICES_DIR / "schemas" / "invoices.json").read_text()) |
| 394 | [status] = [f for f in schema["fields"] if f["name"] == "status"] |
| 395 | [doc_type] = [f for f in schema["fields"] if f["name"] == "doc_type"] |
| 396 | assert entry["where"]["status"]["op"] == "in" |
| 397 | # Settled: nothing is owed to the shop. credit_owed is the shop owing |
| 398 | # the customer, which is not late payment either. |
| 399 | settled = {"paid", "void", "draft", "refunded", "credited", "credit_owed"} |
| 400 | assert owed | settled == set(status["enum"]) | {""} |
| 401 | assert not owed & {"paid", "void", "draft"} |
| 402 | # Blank means invoice, as it did in the provider; the default is invoice. |
| 403 | assert entry["where"]["doc_type"] == {"op": "in", "value": ["invoice", ""]} |
| 404 | assert doc_type["default"] == "invoice" |