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