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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_app_invoices_package.py · 18.1 KB · 428 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 | |
| 17 | PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages" |
| 18 | APP_INVOICES_DIR = PACKAGES_ROOT / "app-invoices" |
| 19 | |
| 20 | # Field types that store money as a float/decimal rather than integer cents |
| 21 | # -- the doctrine this package must never violate (00-doctrine-and-contract.md, |
| 22 | # plan/vocabulary/20-invoice-spec.md's "Money, stated as a hard rule" section). |
| 23 | _FLOAT_MONEY_TYPES = {"float", "number", "currency"} |
| 24 | |
| 25 | # quantity is the one deliberate exception: a count/measure (e.g. 2.5 |
| 26 | # hours), not currency. |
| 27 | _ALLOWED_FLOAT_FIELDS = {"quantity"} |
| 28 | |
| 29 | |
| 30 | def _invoices_schema(): |
| 31 | return json.loads((APP_INVOICES_DIR / "schemas" / "invoices.json").read_text()) |
| 32 | |
| 33 | |
| 34 | def _invoice_lines_schema(): |
| 35 | return json.loads((APP_INVOICES_DIR / "schemas" / "invoice_lines.json").read_text()) |
| 36 | |
| 37 | |
| 38 | def test_get_package_normalizes_app_invoices_manifest(): |
| 39 | package = object_packages.get_package("app-invoices", root=PACKAGES_ROOT) |
| 40 | |
| 41 | assert package["id"] == "app-invoices" |
| 42 | assert package["name"] == "Invoices" |
| 43 | assert {schema["collection"] for schema in package["schemas"]} == { |
| 44 | "invoices", |
| 45 | "invoice_lines", |
| 46 | } |
| 47 | # 0.6.0 deletes the bespoke /invoices list page object: it held no |
| 48 | # business logic and is now a seeded VIEW record over the generic |
| 49 | # `list` block. |
| 50 | assert {obj["id"] for obj in package["objects"]} == { |
| 51 | "system_invoice_totals", |
| 52 | "system_invoice_aging", # aging + dunning runner (payments slice 2) |
| 53 | # 0.5.0 portal: the page a dunning email can finally point at, the |
| 54 | # regenerate verb for a leaked link, and the handler that mints a |
| 55 | # token the moment an invoice leaves draft. |
| 56 | "site_invoice_portal", |
| 57 | "action_regenerate_portal_link", |
| 58 | "system_invoice_portal_link", |
| 59 | # 0.8.0 time and materials: approved hours become one invoice, the |
| 60 | # last mile of the consulting billing mode. |
| 61 | "action_generate_tm_invoice", |
| 62 | # 0.9.0: invoices past their due date, counted for the home |
| 63 | # page's attention band -- a queue the calendar creates with |
| 64 | # no write happening, so nothing else announces it. |
| 65 | "system_invoice_attention", |
| 66 | } |
| 67 | assert package["permissions"] == [{"path": "permissions/rules.json"}] |
| 68 | assert {entry["collection"] for entry in package["seed"]} == { |
| 69 | "invoices", |
| 70 | "invoice_lines", |
| 71 | "views", |
| 72 | "site_routes", |
| 73 | "notify_rules", |
| 74 | } |
| 75 | |
| 76 | |
| 77 | def test_dry_run_app_invoices_package_is_safe(tmp_path): |
| 78 | object_root = tmp_path / "objects" |
| 79 | object_root.mkdir() |
| 80 | |
| 81 | plan = object_packages.dry_run_package( |
| 82 | "app-invoices", |
| 83 | root=PACKAGES_ROOT, |
| 84 | base_dir=tmp_path / "data", |
| 85 | object_roots=[object_root], |
| 86 | ) |
| 87 | |
| 88 | assert plan["safe_to_install"] is True |
| 89 | assert plan["warnings"] == [] |
| 90 | assert {schema["collection"] for schema in plan["schemas"]} == { |
| 91 | "invoices", |
| 92 | "invoice_lines", |
| 93 | } |
| 94 | |
| 95 | |
| 96 | def test_install_app_invoices_package_loads_schemas(tmp_path): |
| 97 | data_dir = tmp_path / "data" |
| 98 | object_root = tmp_path / "objects" |
| 99 | object_root.mkdir() |
| 100 | |
| 101 | object_packages.install_package( |
| 102 | "app-invoices", |
| 103 | root=PACKAGES_ROOT, |
| 104 | base_dir=data_dir, |
| 105 | object_roots=[object_root], |
| 106 | ) |
| 107 | |
| 108 | invoices_schema = object_schemas.get_schema("invoices", base_dir=data_dir) |
| 109 | lines_schema = object_schemas.get_schema("invoice_lines", base_dir=data_dir) |
| 110 | |
| 111 | assert invoices_schema["name"] == "invoices" |
| 112 | assert lines_schema["name"] == "invoice_lines" |
| 113 | # invoices.py was deleted (0.6.0): the /invoices list page is now a |
| 114 | # seeded VIEW record over the generic `list` block. |
| 115 | assert not (object_root / "site" / "invoices.py").exists() |
| 116 | assert (object_root / "system" / "invoice_totals.py").is_file() |
| 117 | |
| 118 | |
| 119 | def test_schema_json_files_are_valid_and_versioned(): |
| 120 | for name in ("invoices", "invoice_lines"): |
| 121 | payload = json.loads((APP_INVOICES_DIR / "schemas" / f"{name}.json").read_text()) |
| 122 | assert payload["name"] == name |
| 123 | # invoices v2: paid/balance became derived (app-payments rollups/ |
| 124 | # formulas). v3: dunning fields + lifecycle arcs. v4: the portal |
| 125 | # capability URL (portal_token, read_only) plus view counters, which |
| 126 | # tell "viewed three times, still unpaid" apart from "never opened". |
| 127 | assert payload["version"] == (5 if name == "invoices" else 1) |
| 128 | assert payload["views"]["list_mode"] == "table" |
| 129 | |
| 130 | |
| 131 | def test_no_money_field_uses_a_float_or_currency_type(): |
| 132 | """00-doctrine-and-contract.md's hard rule: money is *_cents integers, |
| 133 | never object_records.py's _FLOAT_TYPES = {"float", "number", "currency"}. |
| 134 | quantity is the one documented, deliberate exception -- it is a count, |
| 135 | not currency. |
| 136 | """ |
| 137 | for schema in (_invoices_schema(), _invoice_lines_schema()): |
| 138 | for field in schema["fields"]: |
| 139 | name = field["name"] |
| 140 | field_type = field.get("type") |
| 141 | if name in _ALLOWED_FLOAT_FIELDS: |
| 142 | continue |
| 143 | if "_cents" in name or name in {"balance_due_cents"}: |
| 144 | assert field_type in ("integer", "computed"), f"{schema['name']}.{name} must be integer or computed-over-cents, got {field_type!r}" |
| 145 | assert field_type not in _FLOAT_MONEY_TYPES, ( |
| 146 | f"{schema['name']}.{name} uses a float-shaped type {field_type!r}" |
| 147 | ) |
| 148 | |
| 149 | |
| 150 | def test_every_cents_field_is_present_and_integer(): |
| 151 | invoices_by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 152 | for name in ( |
| 153 | "subtotal_cents", "tax_cents", "total_cents", |
| 154 | "amount_paid_cents", "balance_due_cents", |
| 155 | ): |
| 156 | expected = "computed" if name in ("amount_paid_cents", "balance_due_cents", "payments_received_cents", "refunded_cents") else "integer" |
| 157 | assert invoices_by_name[name]["type"] == expected |
| 158 | if expected == "integer": |
| 159 | assert invoices_by_name[name]["default"] == "0" |
| 160 | |
| 161 | lines_by_name = {f["name"]: f for f in _invoice_lines_schema()["fields"]} |
| 162 | for name in ("unit_price_cents", "line_total_cents", "line_tax_cents"): |
| 163 | assert lines_by_name[name]["type"] == "integer" |
| 164 | |
| 165 | |
| 166 | def test_stamped_totals_fields_are_not_schema_read_only(): |
| 167 | """Deliberate deviation from the task brief, documented in |
| 168 | dbbasic-package.json and objects/system/invoice_totals.py's module |
| 169 | docstring: update_collection_record has no read_only write exception, |
| 170 | so a genuinely read_only field could never be re-stamped by the |
| 171 | totals handler after the first write. These fields stay ordinary |
| 172 | owner-writable fields and are protected by omission from |
| 173 | forms.default instead (UI-only, matches |
| 174 | plan/vocabulary/20-invoice-spec.md's own already-reasoned posture). |
| 175 | """ |
| 176 | invoices_by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 177 | for name in ("subtotal_cents", "tax_cents", "total_cents", "balance_due_cents"): |
| 178 | assert not invoices_by_name[name].get("read_only") |
| 179 | assert name not in _invoices_schema()["forms"]["default"]["fields"] |
| 180 | |
| 181 | lines_by_name = {f["name"]: f for f in _invoice_lines_schema()["fields"]} |
| 182 | for name in ("line_total_cents", "line_tax_cents"): |
| 183 | assert not lines_by_name[name].get("read_only") |
| 184 | assert name not in _invoice_lines_schema()["forms"]["default"]["fields"] |
| 185 | |
| 186 | # invoice_lines.invoice_id: required at creation, so it also cannot be |
| 187 | # schema read_only (the server rejects any client submission of a |
| 188 | # read_only field, including the first one) -- see the field's own |
| 189 | # "help" text and the schema test below. |
| 190 | assert lines_by_name["invoice_id"]["required"] is True |
| 191 | assert not lines_by_name["invoice_id"].get("read_only") |
| 192 | |
| 193 | # created_at is the one field that IS read_only in both schemas: it is |
| 194 | # special-cased server-side (_apply_auto_created_at), unlike every |
| 195 | # other read_only field. |
| 196 | assert invoices_by_name["created_at"]["read_only"] is True |
| 197 | assert lines_by_name["created_at"]["read_only"] is True |
| 198 | |
| 199 | |
| 200 | def test_invoices_guarded_status_transitions_match_the_brief(): |
| 201 | status_field = next(f for f in _invoices_schema()["fields"] if f["name"] == "status") |
| 202 | assert status_field["enum"] == ["draft", "sent", "paid", "partial", "overdue", "void"] |
| 203 | assert status_field["default"] == "draft" |
| 204 | |
| 205 | transitions = status_field["transitions"] |
| 206 | owner_guard = {"owner_id": "$user_id"} |
| 207 | |
| 208 | draft_targets = {entry["to"]: entry["when"] for entry in transitions["draft"]} |
| 209 | assert draft_targets == {"sent": owner_guard, "void": owner_guard} |
| 210 | |
| 211 | sent_targets = {entry["to"]: entry["when"] for entry in transitions["sent"]} |
| 212 | assert sent_targets == { |
| 213 | "paid": owner_guard, "partial": owner_guard, |
| 214 | "overdue": owner_guard, "void": owner_guard, |
| 215 | } |
| 216 | |
| 217 | partial_targets = {entry["to"]: entry["when"] for entry in transitions["partial"]} |
| 218 | # + overdue (v3): a partially-paid invoice can age past due (slice 2) |
| 219 | assert partial_targets == {"paid": owner_guard, "void": owner_guard, |
| 220 | "overdue": owner_guard} |
| 221 | # v3: overdue is no longer terminal (clears to paid/partial, voidable), |
| 222 | # and a refund can reopen a paid invoice -- the lifecycle arcs the |
| 223 | # aging/status machines revealed. |
| 224 | overdue_targets = {entry["to"]: entry["when"] for entry in transitions["overdue"]} |
| 225 | assert overdue_targets == {"paid": owner_guard, "partial": owner_guard, |
| 226 | "void": owner_guard} |
| 227 | paid_targets = {entry["to"]: entry["when"] for entry in transitions["paid"]} |
| 228 | assert paid_targets == {"partial": owner_guard} |
| 229 | |
| 230 | # void is terminal; paid can reopen to partial when a refund lands |
| 231 | # (v3 -- the arc the refund machinery revealed). |
| 232 | assert "void" not in transitions |
| 233 | |
| 234 | |
| 235 | def test_invoices_forms_and_views_match_the_brief(): |
| 236 | schema = _invoices_schema() |
| 237 | assert schema["forms"]["default"]["fields"] == [ |
| 238 | "doc_type", "number", "customer_id", "customer_name", "customer_email", |
| 239 | "customer_address", "currency", "issue_date", "due_date", "status", |
| 240 | "notes", "payment_link", |
| 241 | ] |
| 242 | assert schema["views"]["list_fields"] == [ |
| 243 | "number", "customer_name", "status", "total_cents", "due_date", |
| 244 | ] |
| 245 | assert schema["search"]["fields"] == ["number", "customer_name"] |
| 246 | |
| 247 | |
| 248 | def test_invoices_parity_fields_present(): |
| 249 | """Parity fields carried over from the predecessor system's invoice |
| 250 | model, not present in the first-principles 20-invoice-spec.md: doc_type |
| 251 | (invoice/credit_note/quote share one schema + numbering scheme there) |
| 252 | and source_order_id (order -> invoice conversion provenance). Neither is |
| 253 | fully built here (no counter, no orders package) but both fields exist |
| 254 | so no future migration has to backfill. |
| 255 | """ |
| 256 | by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 257 | assert by_name["doc_type"]["type"] == "enum" |
| 258 | assert by_name["doc_type"]["enum"] == ["invoice", "credit_note", "quote"] |
| 259 | assert by_name["doc_type"]["default"] == "invoice" |
| 260 | assert "source_order_id" in by_name |
| 261 | |
| 262 | |
| 263 | def test_invoice_lines_schema_matches_the_brief(): |
| 264 | schema = _invoice_lines_schema() |
| 265 | field_names = [f["name"] for f in schema["fields"]] |
| 266 | # discount_bps sits with the price it reduces -- the rate somebody |
| 267 | # negotiated is a fact about the sale, not part of the arithmetic -- |
| 268 | # and line_discount_cents joins the computed block beside the total |
| 269 | # it produced, so an invoice can print what was taken off rather than |
| 270 | # only what is left. |
| 271 | assert field_names == [ |
| 272 | "id", "invoice_id", "description", "quantity", "unit_price_cents", |
| 273 | "discount_bps", "line_discount_cents", |
| 274 | "line_total_cents", "tax_rate_bps", "line_tax_cents", "owner_id", "created_at", |
| 275 | ] |
| 276 | by_name = {f["name"]: f for f in schema["fields"]} |
| 277 | assert by_name["invoice_id"]["relation"]["collection"] == "invoices" |
| 278 | assert by_name["description"]["required"] is True |
| 279 | assert by_name["quantity"]["type"] == "number" |
| 280 | assert by_name["quantity"]["default"] == "1" |
| 281 | assert by_name["unit_price_cents"]["required"] is True |
| 282 | |
| 283 | |
| 284 | def test_customer_snapshot_fields_present_alongside_optional_relation(): |
| 285 | """plan/vocabulary/20-invoice-spec.md's 'standalone-with-optional- |
| 286 | relation, not a hard app-contacts coupling' decision: customer_id is |
| 287 | an optional cross-reference; the snapshot fields are what renders. |
| 288 | """ |
| 289 | by_name = {f["name"]: f for f in _invoices_schema()["fields"]} |
| 290 | assert by_name["customer_id"]["relation"]["collection"] == "contacts" |
| 291 | assert "required" not in by_name["customer_id"] or not by_name["customer_id"]["required"] |
| 292 | assert by_name["customer_name"]["required"] is True |
| 293 | |
| 294 | |
| 295 | def _app_invoices_policy(): |
| 296 | payload = json.loads((APP_INVOICES_DIR / "permissions" / "rules.json").read_text()) |
| 297 | return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]}) |
| 298 | |
| 299 | |
| 300 | def test_owner_can_crud_own_invoice(): |
| 301 | policy = _app_invoices_policy() |
| 302 | subject = object_permissions.PermissionSubject(user_id="7") |
| 303 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 304 | |
| 305 | for action in ( |
| 306 | object_permissions.CREATE, |
| 307 | object_permissions.READ, |
| 308 | object_permissions.UPDATE, |
| 309 | object_permissions.DELETE, |
| 310 | ): |
| 311 | decision = object_permissions.check_permission( |
| 312 | subject, action, policy=policy, collection="invoices", record=record |
| 313 | ) |
| 314 | assert decision.allowed is True |
| 315 | |
| 316 | |
| 317 | def test_others_cannot_touch_someone_elses_invoice(): |
| 318 | policy = _app_invoices_policy() |
| 319 | subject = object_permissions.PermissionSubject(user_id="8") |
| 320 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 321 | |
| 322 | for action in ( |
| 323 | object_permissions.READ, |
| 324 | object_permissions.UPDATE, |
| 325 | object_permissions.DELETE, |
| 326 | ): |
| 327 | decision = object_permissions.check_permission( |
| 328 | subject, action, policy=policy, collection="invoices", record=record |
| 329 | ) |
| 330 | assert decision.allowed is False |
| 331 | |
| 332 | |
| 333 | def test_anonymous_cannot_read_any_invoice(): |
| 334 | """No public read rule is granted on the invoices collection at all -- |
| 335 | the tokenized public view is a later slice (see dbbasic-package.json). |
| 336 | """ |
| 337 | policy = _app_invoices_policy() |
| 338 | record = {"owner_id": "7", "number": "INV-0001", "customer_name": "Example Co", "status": "draft"} |
| 339 | |
| 340 | decision = object_permissions.check_permission( |
| 341 | None, object_permissions.READ, policy=policy, collection="invoices", record=record |
| 342 | ) |
| 343 | assert decision.allowed is False |
| 344 | |
| 345 | |
| 346 | def test_owner_can_crud_own_invoice_lines(): |
| 347 | policy = _app_invoices_policy() |
| 348 | subject = object_permissions.PermissionSubject(user_id="7") |
| 349 | record = {"owner_id": "7", "invoice_id": "inv_1", "description": "Consulting"} |
| 350 | |
| 351 | for action in ( |
| 352 | object_permissions.CREATE, |
| 353 | object_permissions.READ, |
| 354 | object_permissions.UPDATE, |
| 355 | object_permissions.DELETE, |
| 356 | ): |
| 357 | decision = object_permissions.check_permission( |
| 358 | subject, action, policy=policy, collection="invoice_lines", record=record |
| 359 | ) |
| 360 | assert decision.allowed is True |
| 361 | |
| 362 | |
| 363 | def test_others_cannot_touch_someone_elses_invoice_lines(): |
| 364 | policy = _app_invoices_policy() |
| 365 | subject = object_permissions.PermissionSubject(user_id="8") |
| 366 | record = {"owner_id": "7", "invoice_id": "inv_1", "description": "Consulting"} |
| 367 | |
| 368 | for action in ( |
| 369 | object_permissions.READ, |
| 370 | object_permissions.UPDATE, |
| 371 | object_permissions.DELETE, |
| 372 | ): |
| 373 | decision = object_permissions.check_permission( |
| 374 | subject, action, policy=policy, collection="invoice_lines", record=record |
| 375 | ) |
| 376 | assert decision.allowed is False |
| 377 | |
| 378 | |
| 379 | def test_invoices_page_is_publicly_executable(): |
| 380 | """Public execute on the *page object* (it shows a sign-in prompt to |
| 381 | visitors), never public read on the *collection* -- same split |
| 382 | app-notes uses for site_notes. The invoice detail permalink is now a |
| 383 | seeded 59 view rendered by site_view_render (app-views' own package), |
| 384 | not a per-package object, so it has no rule here anymore -- see |
| 385 | tests/test_app_invoices_detail_retrofit.py. |
| 386 | |
| 387 | site_invoices' own public-execute rule is left in place even though the |
| 388 | object was deleted in 0.6.0 (the /invoices list page is now a seeded |
| 389 | VIEW record) -- same precedent as app-notes' site_notes rule. |
| 390 | """ |
| 391 | policy = _app_invoices_policy() |
| 392 | |
| 393 | decision = object_permissions.check_permission( |
| 394 | None, object_permissions.EXECUTE, policy=policy, object_id="site_invoices" |
| 395 | ) |
| 396 | assert decision.allowed is True |
| 397 | |
| 398 | |
| 399 | def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order(): |
| 400 | """Both seed files ship header-only (no starter data), matching the |
| 401 | established precedent (app-tasks, app-notes, app-contacts all ship |
| 402 | header-only seeds; only app-settings/ai_prices.tsv, live operational |
| 403 | config, ships rows). The header order matches the schema's own field |
| 404 | order for readability. |
| 405 | """ |
| 406 | for name, schema in (("invoices", _invoices_schema()), ("invoice_lines", _invoice_lines_schema())): |
| 407 | path = APP_INVOICES_DIR / "seed" / f"{name}.tsv" |
| 408 | lines = path.read_text().splitlines() |
| 409 | assert len(lines) == 1, f"{name}.tsv should be header-only" |
| 410 | header = lines[0].split("\t") |
| 411 | assert header == [f["name"] for f in schema["fields"]] |
| 412 | |
| 413 | |
| 414 | def test_no_disallowed_org_names_leak_into_the_package(): |
| 415 | """Public repo hygiene: no internal org/codename references anywhere |
| 416 | in this package's source. |
| 417 | """ |
| 418 | # Built from fragments so this guard file itself stays clean of the very |
| 419 | # internal names it forbids (otherwise the test would flag its own source). |
| 420 | banned = re.compile( |
| 421 | "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]), |
| 422 | re.IGNORECASE, |
| 423 | ) |
| 424 | for path in APP_INVOICES_DIR.rglob("*"): |
| 425 | if path.is_dir(): |
| 426 | continue |
| 427 | text = path.read_text(encoding="utf-8", errors="ignore") |
| 428 | assert not banned.search(text), f"disallowed reference found in {path}" |