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_orders_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, 18 minutes ago History
test_app_orders_package.py · 22.6 KB · 499 lines
1"""Structural tests for packages/app-orders (sales and purchase orders).
2
3Mirrors the package/schema/permission testing conventions used for
4packages/app-invoices in tests/test_app_invoices_package.py. Behavior
5tests for the order_totals HANDLES handler live in
6tests/test_app_orders_totals.py.
7"""
8
9import json
10import re
11from pathlib import Path
12
13import object_packages
14import object_permissions
15import object_schemas
16from package_pins import assert_includes_in_order
17
18PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
19APP_ORDERS_DIR = PACKAGES_ROOT / "app-orders"
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_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
30def _orders_schema():
31 return json.loads((APP_ORDERS_DIR / "schemas" / "orders.json").read_text())
32
33
34def _order_lines_schema():
35 return json.loads((APP_ORDERS_DIR / "schemas" / "order_lines.json").read_text())
36
37
38def test_get_package_normalizes_app_orders_manifest():
39 package = object_packages.get_package("app-orders", root=PACKAGES_ROOT)
40
41 assert package["id"] == "app-orders"
42 assert package["name"] == "Orders"
43 assert {schema["collection"] for schema in package["schemas"]} >= {
44 "orders",
45 "order_lines",
46 }
47 # 0.3.0 deletes the bespoke /orders 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_order_totals",
52 # 0.4.0: committed orders with goods still owed -- the pick
53 # queue, counted for the home page's attention band.
54 "system_order_attention",
55 # 0.5.0, the store-voice slice: the customer's own door and the
56 # shop's own voice. Behavior lives in tests/test_store_voice.py.
57 "system_order_portal_link",
58 "system_order_email",
59 "site_order_status",
60 # 0.6.0, the drop-ship slice: the action that raises the vendor's
61 # purchase order from a sale order, and the two-row read that
62 # proves margin needed no stored field. Behavior lives in
63 # tests/test_dropship.py.
64 "action_dropship_order",
65 "site_dropship_margin",
66 }
67 assert {"path": "permissions/rules.json"} in package["permissions"]
68 assert {entry["collection"] for entry in package["seed"]} >= {
69 "orders",
70 "order_lines",
71 "views",
72 "site_routes",
73 }
74 assert "app-views" in {dep["id"] for dep in package["dependencies"]}
75
76
77def test_dry_run_app_orders_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-orders",
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 "orders",
92 "order_lines",
93 }
94
95
96def test_install_app_orders_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-orders", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
103 )
104
105 orders_schema = object_schemas.get_schema("orders", base_dir=data_dir)
106 lines_schema = object_schemas.get_schema("order_lines", base_dir=data_dir)
107
108 assert orders_schema["name"] == "orders"
109 assert lines_schema["name"] == "order_lines"
110 # orders.py was deleted (0.3.0): the /orders list page is now a seeded
111 # VIEW record over the generic `list` block.
112 assert not (object_root / "site" / "orders.py").exists()
113 assert (object_root / "system" / "order_totals.py").is_file()
114
115
116def test_schema_json_files_are_valid_and_versioned():
117 # orders is at v3: the fulfillment slice added the machine-derived
118 # `partial` status and the receiving slice added `received`, the
119 # purchase side's terminal state (see the transitions test below).
120 # orders v4: customer_note + gift_message, so the packing slip prints
121 # what the shopper typed at checkout (v3 added `received` for the PO
122 # side, v2 added `partial`).
123 # orders v5: portal_token, the customer's capability URL. A guest
124 # checkout leaves no account to sign into, so without it a buyer could
125 # neither track an order nor start a return.
126 # orders v6: drop-shipping -- fulfillment_source, linked_order_id,
127 # vendor_id and the ship_to pair. No new collection, because the v1
128 # shared SO/PO schema had already modelled "the vendor ships straight
129 # to my customer" as two rows pointing at each other; see
130 # tests/test_dropship.py.
131 # orders v7: TIME -- fulfillment_method plus the four datetimes
132 # (requested_at/promised_at/ready_at/collected_at) and the pickup half
133 # of the status ladder. Five fields and three enum values rather than a
134 # new collection, because everything about the money was already here
135 # and only the time was missing; see tests/test_pickup_slots.py.
136 # order_lines v3: `backordered`, so the shipment builder can tell a
137 # line the shop agreed to owe from one it can actually pack.
138 # v2 added line_note and modifier_cents, the per-line half of
139 # the same slice -- "no onions" is an instruction on one line of one
140 # order and has no SKU, and "oat milk +60c" is that instruction with a
141 # price delta, which is why the delta lives on the line rather than in
142 # the price book. See tests/test_pickup_service.py.
143 # orders v10: action_claim, the compare-and-set claim the shipment,
144 # receipt, drop-ship and return actions hold while they write; see
145 # tests/test_fulfilment_action_races.py.
146 expected_versions = {"orders": 10, "order_lines": 3}
147 for name in ("orders", "order_lines"):
148 payload = json.loads((APP_ORDERS_DIR / "schemas" / f"{name}.json").read_text())
149 assert payload["name"] == name
150 assert payload["version"] >= expected_versions[name]
151 assert payload["views"]["list_mode"] == "table"
152
153
154def test_no_money_field_uses_a_float_or_currency_type():
155 """00-doctrine-and-contract.md's hard rule: money is *_cents integers,
156 never object_records.py's _FLOAT_TYPES = {"float", "number", "currency"}.
157 quantity is the one documented, deliberate exception -- it is a count,
158 not currency.
159 """
160 for schema in (_orders_schema(), _order_lines_schema()):
161 for field in schema["fields"]:
162 name = field["name"]
163 field_type = field.get("type")
164 if name in _ALLOWED_FLOAT_FIELDS:
165 continue
166 if "_cents" in name:
167 assert field_type == "integer", f"{schema['name']}.{name} must be type integer, got {field_type!r}"
168 assert field_type not in _FLOAT_MONEY_TYPES, (
169 f"{schema['name']}.{name} uses a float-shaped type {field_type!r}"
170 )
171
172
173def test_every_cents_field_is_present_and_integer():
174 orders_by_name = {f["name"]: f for f in _orders_schema()["fields"]}
175 for name in ("subtotal_cents", "tax_cents", "total_cents"):
176 assert orders_by_name[name]["type"] == "integer"
177 assert orders_by_name[name]["default"] == "0"
178
179 lines_by_name = {f["name"]: f for f in _order_lines_schema()["fields"]}
180 for name in ("unit_price_cents", "line_total_cents", "line_tax_cents"):
181 assert lines_by_name[name]["type"] == "integer"
182
183
184def test_stamped_totals_fields_are_not_schema_read_only():
185 """Deliberate deviation from the task brief, documented in
186 dbbasic-package.json and objects/system/order_totals.py's module
187 docstring: update_collection_record has no read_only write exception,
188 so a genuinely read_only field could never be re-stamped by the
189 totals handler after the first write. These fields stay ordinary
190 owner-writable fields and are protected by omission from
191 forms.default instead (same posture as app-invoices).
192 """
193 orders_by_name = {f["name"]: f for f in _orders_schema()["fields"]}
194 for name in ("subtotal_cents", "tax_cents", "total_cents"):
195 assert not orders_by_name[name].get("read_only")
196 assert name not in _orders_schema()["forms"]["default"]["fields"]
197
198 lines_by_name = {f["name"]: f for f in _order_lines_schema()["fields"]}
199 for name in ("line_total_cents", "line_tax_cents"):
200 assert not lines_by_name[name].get("read_only")
201 assert name not in _order_lines_schema()["forms"]["default"]["fields"]
202
203 # order_lines.order_id: required at creation, so it also cannot be
204 # schema read_only (the server rejects any client submission of a
205 # read_only field, including the first one) -- see the field's own
206 # "help" text and the schema test below.
207 assert lines_by_name["order_id"]["required"] is True
208 assert not lines_by_name["order_id"].get("read_only")
209
210 # created_at is the one field that IS read_only in both schemas: it is
211 # special-cased server-side (_apply_auto_created_at), unlike every
212 # other read_only field.
213 assert orders_by_name["created_at"]["read_only"] is True
214 assert lines_by_name["created_at"]["read_only"] is True
215
216
217def test_orders_guarded_status_transitions_match_the_real_lifecycle():
218 status_field = next(f for f in _orders_schema()["fields"] if f["name"] == "status")
219 assert_includes_in_order(status_field["enum"], [
220 "draft", "confirmed", "processing", "partial", "shipped", "delivered",
221 "received", "preparing", "ready", "collected", "cancelled",
222 ])
223 assert status_field["default"] == "draft"
224
225 transitions = status_field["transitions"]
226 owner_guard = {"owner_id": "$user_id"}
227
228 draft_targets = {entry["to"]: entry["when"] for entry in transitions["draft"]}
229 assert draft_targets == {"confirmed": owner_guard, "cancelled": owner_guard}
230
231 # partial/shipped are reachable straight from confirmed because they are
232 # DERIVED by system_order_fulfillment from shipment lines, and the
233 # zero-touch shop (app-shop's auto_fulfill) ships a paid order without
234 # ever passing through processing.
235 # `received` is reachable from the same three states for the mirror
236 # reason on the PURCHASE side: system_receipt_posting derives it from
237 # receipt lines, and a PO that was received in one delivery never passed
238 # through partial.
239 # v7: `preparing` and `ready` join the same list, and `ready` is
240 # reachable straight from confirmed for the third time the same
241 # argument has been made here -- a counter that makes the coffee while
242 # the customer stands there never passes through a `preparing` anybody
243 # observed, and a forced bookkeeping hop nobody performed is fake
244 # precision, exactly as it was for the zero-touch shop's shipped.
245 confirmed_targets = {entry["to"]: entry["when"] for entry in transitions["confirmed"]}
246 assert confirmed_targets == {"processing": owner_guard, "partial": owner_guard,
247 "shipped": owner_guard, "received": owner_guard,
248 "preparing": owner_guard, "ready": owner_guard,
249 "cancelled": owner_guard}
250
251 processing_targets = {entry["to"]: entry["when"] for entry in transitions["processing"]}
252 assert processing_targets == {"partial": owner_guard, "shipped": owner_guard,
253 "received": owner_guard, "cancelled": owner_guard}
254
255 # v9: a lost or returned parcel sends the derived status BACK --
256 # shipped -> partial when some of the goods never arrived, and
257 # shipped/partial -> processing when none did -- so the order returns
258 # to the pick queue instead of sitting at `shipped` with goods owed.
259 partial_targets = {entry["to"]: entry["when"] for entry in transitions["partial"]}
260 assert partial_targets == {"shipped": owner_guard, "processing": owner_guard,
261 "received": owner_guard, "cancelled": owner_guard}
262
263 shipped_targets = {entry["to"]: entry["when"] for entry in transitions["shipped"]}
264 assert shipped_targets == {"delivered": owner_guard, "partial": owner_guard,
265 "processing": owner_guard}
266
267 # The PICKUP ladder (v7): confirmed -> preparing -> ready -> collected.
268 # cancelled hangs off both middle rungs, for the customer who calls
269 # back while it is being made and the one who never turns up.
270 preparing_targets = {entry["to"]: entry["when"] for entry in transitions["preparing"]}
271 assert preparing_targets == {"ready": owner_guard, "cancelled": owner_guard}
272
273 ready_targets = {entry["to"]: entry["when"] for entry in transitions["ready"]}
274 assert ready_targets == {"collected": owner_guard, "cancelled": owner_guard}
275
276 # delivered, received, collected and cancelled are terminal: no entries
277 # in the transitions map at all. received is terminal for the same
278 # reason delivered is -- goods that arrived cannot un-arrive, and a
279 # miscount is an adjustment move, never an edit. `collected` is
280 # terminal for the third version of that sentence.
281 assert "delivered" not in transitions
282 assert "received" not in transitions
283 assert "collected" not in transitions
284 assert "cancelled" not in transitions
285
286
287def test_orders_forms_and_views_match_the_brief():
288 schema = _orders_schema()
289 # fulfillment_method is IN the default form (v7): it is the field every
290 # downstream behaviour keys off, and one only action_checkout could set
291 # would leave an operator raising a counter or pickup order by hand with
292 # no way to say so.
293 assert_includes_in_order(schema["forms"]["default"]["fields"], [
294 "doc_type", "number", "customer_id", "customer_name", "customer_email",
295 "currency", "order_date", "expected_date", "status", "fulfillment_method",
296 "notes",
297 ])
298 assert_includes_in_order(schema["views"]["list_fields"], [
299 "number", "customer_name", "status", "total_cents", "expected_date",
300 ])
301 assert_includes_in_order(schema["search"]["fields"], ["number", "customer_name"])
302
303
304def test_orders_parity_fields_present():
305 """Parity fields carried over from the predecessor system's Order model
306 (reconciled against a private predecessor-system audit, not part of
307 this repo: "Order+Lines (SO/PO; convert_to_invoice)"): doc_type is the real SO/PO split, and
308 invoice_id is the order-to-invoice conversion provenance. Neither is
309 fully built here (no counter, no convert action) but both fields
310 exist so no future migration has to backfill.
311 """
312 by_name = {f["name"]: f for f in _orders_schema()["fields"]}
313 assert by_name["doc_type"]["type"] == "enum"
314 assert_includes_in_order(by_name["doc_type"]["enum"], ["sale", "purchase"])
315 assert by_name["doc_type"]["default"] == "sale"
316 assert "invoice_id" in by_name
317
318
319def test_order_lines_schema_matches_the_brief():
320 schema = _order_lines_schema()
321 field_names = [f["name"] for f in schema["fields"]]
322 # v2 puts line_note and modifier_cents next to the unit price they
323 # qualify, and before the line total they are folded into -- reading
324 # order is the argument: the note and the delta belong to the thing
325 # being sold, not to the arithmetic underneath it. v3 adds
326 # `backordered` last among the facts about the sale and still ahead of
327 # the arithmetic, for the same reason. v4 adds discount_bps in the
328 # same spirit: the rate somebody negotiated is a fact about the sale,
329 # so it sits with the price it reduces, and line_discount_cents joins
330 # the computed block beside the total it produced.
331 assert_includes_in_order(field_names, [
332 "id", "order_id", "product_id", "description", "quantity", "unit_price_cents",
333 "line_note", "modifier_cents", "backordered",
334 "discount_bps", "line_discount_cents",
335 "line_total_cents", "tax_rate_bps", "line_tax_cents", "owner_id", "created_at",
336 ])
337 by_name = {f["name"]: f for f in schema["fields"]}
338 assert by_name["order_id"]["relation"]["collection"] == "orders"
339 assert by_name["description"]["required"] is True
340 assert by_name["quantity"]["type"] == "number"
341 assert by_name["quantity"]["default"] == "1"
342 assert by_name["unit_price_cents"]["required"] is True
343
344
345def test_product_id_relation_present_and_optional():
346 """Order lines relate to app-catalog's products collection, but the
347 relation is optional -- a line may be free-text (task brief), and
348 this package declares no dependency on app-catalog. It does depend on
349 app-views now (the retrofit's seeded view_order_detail needs
350 site_view_render), same as every other Stage-6-retrofitted package.
351 """
352 by_name = {f["name"]: f for f in _order_lines_schema()["fields"]}
353 assert by_name["product_id"]["relation"]["collection"] == "products"
354 assert "required" not in by_name["product_id"] or not by_name["product_id"]["required"]
355
356 manifest = json.loads((APP_ORDERS_DIR / "dbbasic-package.json").read_text())
357 assert "app-catalog" not in manifest.get("dependencies", [])
358 assert "app-views" in manifest.get("dependencies", [])
359
360
361def test_customer_snapshot_fields_present_alongside_optional_relation():
362 """Same 'standalone-with-optional-relation, not a hard app-contacts
363 coupling' decision app-invoices makes: customer_id is an optional
364 cross-reference; the snapshot fields are what renders.
365 """
366 by_name = {f["name"]: f for f in _orders_schema()["fields"]}
367 assert by_name["customer_id"]["relation"]["collection"] == "contacts"
368 assert "required" not in by_name["customer_id"] or not by_name["customer_id"]["required"]
369 assert by_name["customer_name"]["required"] is True
370
371
372def _app_orders_policy():
373 payload = json.loads((APP_ORDERS_DIR / "permissions" / "rules.json").read_text())
374 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
375
376
377def test_owner_can_crud_own_order():
378 policy = _app_orders_policy()
379 subject = object_permissions.PermissionSubject(user_id="7")
380 record = {"owner_id": "7", "number": "SO-0001", "customer_name": "Example Co", "status": "draft"}
381
382 for action in (
383 object_permissions.CREATE,
384 object_permissions.READ,
385 object_permissions.UPDATE,
386 object_permissions.DELETE,
387 ):
388 decision = object_permissions.check_permission(
389 subject, action, policy=policy, collection="orders", record=record
390 )
391 assert decision.allowed is True
392
393
394def test_others_cannot_touch_someone_elses_order():
395 policy = _app_orders_policy()
396 subject = object_permissions.PermissionSubject(user_id="8")
397 record = {"owner_id": "7", "number": "SO-0001", "customer_name": "Example Co", "status": "draft"}
398
399 for action in (
400 object_permissions.READ,
401 object_permissions.UPDATE,
402 object_permissions.DELETE,
403 ):
404 decision = object_permissions.check_permission(
405 subject, action, policy=policy, collection="orders", record=record
406 )
407 assert decision.allowed is False
408
409
410def test_anonymous_cannot_read_any_order():
411 """No public read rule is granted on the orders collection at all."""
412 policy = _app_orders_policy()
413 record = {"owner_id": "7", "number": "SO-0001", "customer_name": "Example Co", "status": "draft"}
414
415 decision = object_permissions.check_permission(
416 None, object_permissions.READ, policy=policy, collection="orders", record=record
417 )
418 assert decision.allowed is False
419
420
421def test_owner_can_crud_own_order_lines():
422 policy = _app_orders_policy()
423 subject = object_permissions.PermissionSubject(user_id="7")
424 record = {"owner_id": "7", "order_id": "ord_1", "description": "Widget"}
425
426 for action in (
427 object_permissions.CREATE,
428 object_permissions.READ,
429 object_permissions.UPDATE,
430 object_permissions.DELETE,
431 ):
432 decision = object_permissions.check_permission(
433 subject, action, policy=policy, collection="order_lines", record=record
434 )
435 assert decision.allowed is True
436
437
438def test_others_cannot_touch_someone_elses_order_lines():
439 policy = _app_orders_policy()
440 subject = object_permissions.PermissionSubject(user_id="8")
441 record = {"owner_id": "7", "order_id": "ord_1", "description": "Widget"}
442
443 for action in (
444 object_permissions.READ,
445 object_permissions.UPDATE,
446 object_permissions.DELETE,
447 ):
448 decision = object_permissions.check_permission(
449 subject, action, policy=policy, collection="order_lines", record=record
450 )
451 assert decision.allowed is False
452
453
454def test_the_deleted_orders_page_keeps_no_public_execute_grant():
455 """The site_orders object was deleted in 0.3.0 (the /orders list page is
456 now a seeded VIEW record rendered by site_view_render), and so is its
457 public-execute rule: a grant for an id nothing ships made whatever was
458 later created under that id public without anybody deciding so
459 (bug-reports/2026-11-28-06-14-43). Never public read on the collection
460 either way."""
461 policy = _app_orders_policy()
462
463 decision = object_permissions.check_permission(
464 None, object_permissions.EXECUTE, policy=policy, object_id="site_orders"
465 )
466 assert decision.allowed is False
467
468
469def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order():
470 """Both seed files ship header-only (no starter data), matching the
471 established precedent (app-tasks, app-notes, app-contacts, app-invoices
472 all ship header-only seeds). The header order matches the schema's own
473 field order for readability.
474 """
475 for name, schema in (("orders", _orders_schema()), ("order_lines", _order_lines_schema())):
476 path = APP_ORDERS_DIR / "seed" / f"{name}.tsv"
477 lines = path.read_text().splitlines()
478 assert len(lines) == 1, f"{name}.tsv should be header-only"
479 header = lines[0].split("\t")
480 assert header == [f["name"] for f in schema["fields"]]
481
482
483def test_no_disallowed_org_names_leak_into_the_package():
484 """Public repo hygiene: no internal org/codename references anywhere
485 in this package's source.
486 """
487 # Built from fragments so this guard file itself stays clean of the very
488 # internal names it forbids (otherwise the test would flag its own source).
489 banned = re.compile(
490 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
491 re.IGNORECASE,
492 )
493 for path in APP_ORDERS_DIR.rglob("*"):
494 if "__pycache__" in path.parts:
495 continue # compiled bytes can match a name by chance
496 if path.is_dir():
497 continue
498 text = path.read_text(encoding="utf-8", errors="ignore")
499 assert not banned.search(text), f"disallowed reference found in {path}"