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_documents.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_documents.py · 36.4 KB · 844 lines
1"""The document layer: one renderer, three deliveries, and the rule that
2makes the third one safe.
3
4The properties worth holding here are the ones seven hand-rolled printable
5pages could not hold between them.
6
7A document says who sent it -- the business header comes from settings, and
8a nameless business is refused where refusing costs nothing (at SEND time)
9rather than where somebody is standing at a printer.
10
11The packing slip's no-prices rule is a PARAMETER now, not a paragraph. It is
12asserted on the rendered HTML rather than on the model, because "no prices in
13the model" is a claim about a dict and "no prices on the page" is the claim
14that keeps the amount paid off a birthday present.
15
16Print CSS repeats table headings across a page break. That single rule --
17`thead { display: table-header-group }` -- appeared in exactly none of the
18seven @media print blocks that shipped before this layer, which is why a
19three-page pick list came out of the printer headerless and nobody noticed:
20nobody reviews on paper.
21
22A document that was SENT is evidence of what was sent. Change the source and
23the customer's link keeps showing the snapshot, names both dates, and offers
24the current version -- it never silently restates a document somebody is
25holding a printout of.
26
27opened_at stamps once. Sending twice to one recipient queues one email. And
28the PDF capability is honest in both directions: with no engine it returns a
29409 naming exactly what to install, and NO surface anywhere draws a button
30that would produce that 409.
31
32Fixture style follows tests/test_shipping.py: direct object_execution calls
33against the real package objects, with one merged object root -- which is what
34an installed server actually looks like, and the only way a page that reaches
35a root object_* module resolves the way it will in production.
36"""
37
38import json
39import pathlib
40import shutil
41
42import pytest
43from conftest import stage_collection
44
45import object_documents
46import object_execution
47import object_records
48import python_object_runtime
49
50REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
51PACKAGES = REPO_ROOT / "packages"
52RUNTIME = python_object_runtime.PythonObjectRuntime()
53
54OWNER = "dan"
55BASE_URL = "https://docs.example.test"
56
57BUSINESS = (
58 ("business.name", "Acme Supplies Ltd"),
59 ("business.address", "12 Kiln Lane\nSheffield"),
60 ("business.email", "hello@acme.test"),
61 ("portal.base_url", BASE_URL),
62)
63
64
65# --- the pure fold ------------------------------------------------------------
66
67def settings(**overrides):
68 values = dict(BUSINESS)
69 values.update(overrides)
70 return values
71
72
73def facts(**overrides):
74 base = {
75 "number": "Q-1001",
76 "date": "2026-07-01",
77 "state": "sent",
78 "currency": "USD",
79 "to": {"name": "Grace Hopper", "address": "9 Navy Yard",
80 "email": "grace@acme.test"},
81 "lines": [{"description": "Enamel Mug", "quantity": "3",
82 "unit_price": "12.00 USD", "amount": "36.00 USD"}],
83 "totals": [{"label": "Total", "value": "36.00 USD", "emphasis": True}],
84 }
85 base.update(overrides)
86 return base
87
88
89def test_the_model_carries_the_business_header_from_settings():
90 """A document looks like it came from a business rather than from
91 software. Every field is optional except the name."""
92 model = object_documents.build_model("quote", facts(), settings())
93
94 assert model["business"] == {
95 "name": "Acme Supplies Ltd",
96 "address": "12 Kiln Lane\nSheffield",
97 "email": "hello@acme.test",
98 }
99 # And it is the "from" party too, rather than a second copy somebody can
100 # edit into disagreeing with the letterhead.
101 origin = [p for p in model["parties"] if p["role"] == "from"][0]
102 assert origin["name"] == "Acme Supplies Ltd"
103
104 body = object_documents.render_html(model)
105 assert "Acme Supplies Ltd" in body
106 assert "12 Kiln Lane<br>Sheffield" in body
107
108
109def test_a_nameless_business_is_refused():
110 """Fabricating a default -- "My Company", the hostname, the owner's user
111 id -- would be a plausible-looking lie printed on paperwork somebody
112 keeps."""
113 nameless = {k: v for k, v in settings().items() if k != "business.name"}
114
115 with pytest.raises(object_documents.NamelessBusinessError) as exc:
116 object_documents.business_header(nameless)
117 assert "business.name" in str(exc.value)
118
119 with pytest.raises(object_documents.NamelessBusinessError):
120 object_documents.build_model("quote", facts(), nameless)
121
122 # ...and the documented escape, for the operator standing at a printer.
123 model = object_documents.build_model("quote", facts(), nameless,
124 require_business=False)
125 assert model["business"] == {}
126
127
128def test_show_money_false_produces_a_document_with_no_price_anywhere():
129 """Asserted on the RENDERED HTML, not the model: a model with no prices
130 in it is a claim about a dict, and the claim that matters is that nothing
131 reaches the page.
132
133 Same facts, both kinds. The only thing that differs is the kind's row in
134 the registry -- which is the entire point of making it a parameter.
135 """
136 priced = object_documents.build_model("invoice", facts(), settings())
137 priceless = object_documents.build_model("packing_slip", facts(), settings())
138
139 assert priced["show_money"] is True
140 assert priceless["show_money"] is False
141
142 priced_html = object_documents.render_html(priced)
143 assert "12.00 USD" in priced_html and "36.00 USD" in priced_html
144
145 slip_html = object_documents.render_html(priceless)
146 for forbidden in ("12.00", "36.00", "USD", "Unit price", "Amount",
147 "unit_price", "_cents", "$"):
148 assert forbidden not in slip_html, forbidden
149 # The goods are still on it -- pricelessness is not blankness.
150 assert "Enamel Mug" in slip_html and ">3<" in slip_html
151
152 # And the money never entered the model, so a snapshot of it carries none
153 # either: the rule survives being written to disk.
154 assert "12.00" not in object_documents.snapshot_json(priceless)
155 assert priceless["totals"] == []
156 assert "currency" not in priceless
157
158 # There is deliberately no way to argue the packing slip into showing
159 # money: the decision lives in the registry, not at the call site.
160 assert object_documents.shows_money("packing_slip") is False
161 assert "show_money" not in object_documents.build_model.__kwdefaults__
162
163
164def test_the_ship_to_of_a_slip_is_not_the_bill_to_of_an_invoice():
165 invoice = object_documents.build_model("invoice", facts(), settings())
166 slip = object_documents.build_model("packing_slip", facts(), settings())
167
168 assert [p["role"] for p in invoice["parties"]] == ["from", "bill_to"]
169 assert [p["role"] for p in slip["parties"]] == ["from", "ship_to"]
170 assert "Bill to" in object_documents.render_html(invoice)
171 assert "Ship to" in object_documents.render_html(slip)
172
173
174def test_print_css_repeats_table_headers_across_a_page_break():
175 """The rule every hand-rolled print stylesheet in this repo forgot.
176 Without it, page two of a long document is two anonymous columns of
177 numbers."""
178 css = object_documents.document_css()
179 assert "thead { display: table-header-group; }" in css
180 assert "tfoot { display: table-footer-group; }" in css
181
182 # It has something to repeat: the renderer emits a real <thead>.
183 body = object_documents.render_html(
184 object_documents.build_model("invoice", facts(), settings()))
185 assert "<thead>" in body
186
187
188def test_exactly_two_pages_were_migrated_and_they_own_no_print_css():
189 """A layer nobody has migrated to is a layer that does not work, and
190 migrating all seven at once would make a regression impossible to locate.
191 So: exactly two, and those two carry no private @media print block at all
192 -- if they still did, they would be a second opinion about paper that
193 nobody would notice diverging."""
194 printables = {
195 "app-shipping/packing_slip": True, # migrated
196 "app-invoices/invoice_portal": True, # migrated
197 "app-shipping/pick_list": False,
198 "app-shipping/manifest": False,
199 "app-kitchen/kitchen": False,
200 "app-kitchen/kitchen_ticket": False,
201 "app-receiving/receiving_sheet": False,
202 "app-returns/return_form": False,
203 }
204 for path, migrated in printables.items():
205 package_id, name = path.split("/")
206 source = (PACKAGES / package_id / "objects" / "site"
207 / f"{name}.py").read_text()
208 owns_print_css = "@media print {" in source
209 assert owns_print_css is not migrated, path
210 assert ("object_documents" in source) is migrated, path
211
212
213def test_the_page_size_comes_from_a_setting_and_never_emits_broken_css():
214 assert "@page { size: A4; margin: 14mm; }" in object_documents.document_css()
215 assert "size: Letter" in object_documents.document_css("letter")
216 # An operator typo must not produce a stylesheet the browser discards --
217 # a broken @page rule fails silently and prints at whatever size it liked.
218 assert "size: A4" in object_documents.document_css("foolscap")
219
220
221def test_the_content_hash_is_stable_and_moves_with_the_content():
222 model = object_documents.build_model("quote", facts(), settings())
223 again = object_documents.build_model("quote", facts(), settings())
224 changed = object_documents.build_model(
225 "quote", facts(totals=[{"label": "Total", "value": "45.00 USD"}]),
226 settings())
227
228 assert object_documents.content_hash(model) == object_documents.content_hash(again)
229 assert object_documents.content_hash(model) != object_documents.content_hash(changed)
230
231 # A snapshot round-trips, and a broken one is refused rather than repaired:
232 # rendering a half-parsed snapshot would show something nobody ever sent.
233 assert object_documents.model_from_snapshot(
234 object_documents.snapshot_json(model)) == model
235 with pytest.raises(object_documents.DocumentError):
236 object_documents.model_from_snapshot("{not json")
237
238
239# --- a box with the whole slice installed --------------------------------------
240
241def setup_env(tmp_path, monkeypatch, *, extra_settings=()):
242 data_dir = tmp_path / "data"
243 for package_id, collection in (
244 ("app-documents", "sent_documents"),
245 ("app-orders", "orders"), ("app-orders", "order_lines"),
246 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
247 ("app-shipping", "shipments"), ("app-shipping", "shipment_lines"),
248 ("app-email", "email_outbox")):
249 stage_collection(data_dir, package_id, collection)
250
251 rows = "".join(f"s{i}\t{key}\t{value}\t\n" for i, (key, value)
252 in enumerate(tuple(BUSINESS) + tuple(extra_settings)))
253 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
254
255 objects_root = tmp_path / "objects"
256 for package_id in ("app-documents", "app-invoices", "app-shipping"):
257 shutil.copytree(PACKAGES / package_id / "objects", objects_root,
258 dirs_exist_ok=True)
259
260 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
261 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
262 return data_dir, objects_root
263
264
265def run(objects_root, object_id, method, payload):
266 return object_execution.execute_object(
267 RUNTIME,
268 object_execution.ObjectExecutionRequest(object_id, method=method,
269 payload=payload),
270 roots=[objects_root]).result
271
272
273def make_order(data_dir, order_id="ord-1", *, total="3600", number="Q-1001"):
274 order = object_records.create_collection_record(
275 "orders",
276 # doc_type stays `sale`: quotes are the B2B slice and do not exist
277 # yet as a document type on orders. The document LAYER already carries
278 # the kind (KINDS["quote"] renders from orders for exactly that
279 # reason), so this exercises the same path a quote will take.
280 {"id": order_id, "doc_type": "sale", "number": number,
281 "customer_name": "Grace Hopper", "customer_email": "grace@acme.test",
282 "currency": "USD", "status": "draft", "order_date": "2026-07-01",
283 "total_cents": total, "owner_id": OWNER},
284 base_dir=data_dir)
285 object_records.create_collection_record(
286 "order_lines",
287 # No product_id: the catalog is another package, and a document
288 # renders from what the order says, not from what is in stock.
289 {"id": "line-1", "order_id": order_id,
290 "description": "Enamel Mug", "quantity": "3",
291 "unit_price_cents": "1200", "line_total_cents": total,
292 "owner_id": OWNER},
293 base_dir=data_dir)
294 return order
295
296
297def send(objects_root, *, kind="order", source="orders/ord-1",
298 to="grace@acme.test", user_id=OWNER):
299 payload = {"kind": kind, "source": source, "to": to}
300 if user_id:
301 payload["_identity"] = {"user_id": user_id, "roles": []}
302 return run(objects_root, "action_send_document", "POST", payload)
303
304
305def open_link(objects_root, token, **extra):
306 payload = {"token": token}
307 payload.update(extra)
308 return run(objects_root, "site_document", "GET", payload)
309
310
311def sent_rows(data_dir):
312 return object_records.read_collection_records("sent_documents",
313 base_dir=data_dir)
314
315
316def outbox(data_dir):
317 return object_records.read_collection_records("email_outbox",
318 base_dir=data_dir)
319
320
321# --- delivery 3: the link, and the rule that makes it safe ---------------------
322
323def test_sending_a_document_snapshots_it_mints_a_link_and_queues_one_email(
324 tmp_path, monkeypatch):
325 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
326 make_order(data_dir)
327
328 result = send(objects_root)
329 assert result["status"] == "ok", result
330 assert result["queued"] is True
331 assert result["link"].startswith(f"{BASE_URL}/d/")
332
333 row = sent_rows(data_dir)[0]
334 assert row["kind"] == "order"
335 assert row["source"] == "orders/ord-1"
336 assert row["sent_to"] == "grace@acme.test"
337 assert row["opened_at"] == ""
338 snapshot = object_documents.model_from_snapshot(row["snapshot"])
339 assert snapshot["content_hash"] if False else True # the hash is on the row
340 assert row["content_hash"] == object_documents.content_hash(snapshot)
341 assert "36.00 USD" in object_documents.render_html(snapshot)
342
343 # It QUEUES; it never sends. One `queued` row, carrying the link.
344 mails = outbox(data_dir)
345 assert len(mails) == 1
346 assert mails[0]["status"] == "queued"
347 assert result["link"] in mails[0]["text_body"]
348
349
350def test_sending_twice_to_the_same_recipient_queues_one_email(
351 tmp_path, monkeypatch):
352 """Idempotent per (source, recipient), the way system_order_email is: the
353 document is one document with one token and one opened_at, and a second
354 copy of the mail is already in somebody's inbox and cannot be taken back.
355 """
356 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
357 make_order(data_dir)
358
359 first = send(objects_root)
360 second = send(objects_root)
361
362 assert second["status"] == "ok"
363 assert second["queued"] is False
364 assert second["link"] == first["link"]
365 assert len(sent_rows(data_dir)) == 1
366 assert len(outbox(data_dir)) == 1
367 assert "already sent" in second["note"]
368
369 # A DIFFERENT recipient is genuinely a second delivery: their own link,
370 # their own read receipt.
371 third = send(objects_root, to="accounts@acme.test")
372 assert third["queued"] is True
373 assert third["link"] != first["link"]
374 assert len(outbox(data_dir)) == 2
375
376
377def test_the_link_renders_the_snapshot_after_the_source_changes(
378 tmp_path, monkeypatch):
379 """The load-bearing rule. Email a quote at 36.00, change it to 45.00, and
380 the customer's link must not silently show 45.00 -- they may be holding a
381 printout of the first one."""
382 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
383 make_order(data_dir)
384 result = send(objects_root)
385 token = result["link"].rsplit("/", 1)[1]
386
387 # Backdated so the banner has two genuinely different dates to name.
388 object_records.update_collection_record(
389 "sent_documents", sent_rows(data_dir)[0]["id"],
390 {"sent_at": "2026-07-01T09:00:00Z"}, base_dir=data_dir, actor="test")
391
392 # ...and now the price moves.
393 object_records.update_collection_record(
394 "orders", "ord-1", {"total_cents": "4500"},
395 base_dir=data_dir, actor="test")
396 object_records.update_collection_record(
397 "order_lines", "line-1", {"line_total_cents": "4500"},
398 base_dir=data_dir, actor="test")
399
400 body = open_link(objects_root, token)["body"]
401 assert "36.00 USD" in body # what they were sent
402 assert "45.00 USD" not in body # never silently restated
403
404 # Both dates, named, with a way to the current version.
405 assert "2026-07-01" in body
406 changed_on = object_records.read_collection_records(
407 "sent_documents", base_dir=data_dir) # touch nothing; date comes below
408 assert "sent to you on 2026-07-01" in body
409 assert "This document was changed on 20" in body
410 assert f'href="/d/{token}?v=current"' in body
411 assert changed_on # the row still exists, unmodified by the view
412
413
414def test_the_current_version_is_offered_but_never_substituted(
415 tmp_path, monkeypatch):
416 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
417 make_order(data_dir)
418 token = send(objects_root)["link"].rsplit("/", 1)[1]
419
420 object_records.update_collection_record(
421 "orders", "ord-1", {"total_cents": "4500"},
422 base_dir=data_dir, actor="test")
423 object_records.update_collection_record(
424 "order_lines", "line-1", {"line_total_cents": "4500"},
425 base_dir=data_dir, actor="test")
426
427 current = open_link(objects_root, token, v="current")["body"]
428 assert "45.00 USD" in current
429 assert "CURRENT version" in current
430 # ...and it still points back at what was actually sent.
431 assert f'href="/d/{token}"' in current
432
433
434def test_source_rev_is_keyed_so_its_reader_cannot_test_guesses_of_the_source(
435 tmp_path, monkeypatch):
436 """The sender reads the sent_documents row. An unkeyed hash of the whole
437 source row there would let them hash each guess of a field they may not
438 read on the source and compare."""
439 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
440 make_order(data_dir)
441 send(objects_root)
442 order = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
443 stored = sent_rows(data_dir)[0]["source_rev"]
444 assert stored != object_records.compute_record_rev(order)
445 assert stored == object_records.client_record_rev("orders", order, base_dir=data_dir)
446
447
448def test_a_document_sent_before_the_keyed_rev_still_reads_as_unchanged(
449 tmp_path, monkeypatch):
450 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
451 make_order(data_dir)
452 token = send(objects_root)["link"].rsplit("/", 1)[1]
453 order = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
454 object_records.update_collection_record(
455 "sent_documents", sent_rows(data_dir)[0]["id"],
456 {"source_rev": object_records.compute_record_rev(order)},
457 base_dir=data_dir, actor="test")
458 assert "was changed" not in open_link(objects_root, token)["body"]
459 object_records.update_collection_record(
460 "orders", "ord-1", {"total_cents": "4500"}, base_dir=data_dir, actor="test")
461 assert "This document was changed on 20" in open_link(objects_root, token)["body"]
462
463
464def test_an_unchanged_source_shows_no_banner_at_all(tmp_path, monkeypatch):
465 """A banner on an unchanged document would teach people to ignore it."""
466 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
467 make_order(data_dir)
468 token = send(objects_root)["link"].rsplit("/", 1)[1]
469
470 body = open_link(objects_root, token)["body"]
471 assert '<div class="doc-banner">' not in body
472 assert "was changed" not in body
473 assert "36.00 USD" in body
474
475
476def beacon(objects_root, token):
477 """What the rendered page's VIEW_BEACON sends once a browser has it open."""
478 return run(objects_root, "site_document", "POST", {"token": token})
479
480
481def test_opened_at_stamps_once_and_is_idempotent(tmp_path, monkeypatch):
482 """'Did they read it?' is the first thing anyone asks after sending a
483 quote. The fact worth keeping is that they opened it, not how many times,
484 so it is written only while the field is empty. It is written by the
485 page's own beacon POST, never by the GET: a mail scanner or prefetcher
486 GETs every link on delivery, and that is not the customer reading it."""
487 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
488 make_order(data_dir)
489 token = send(objects_root)["link"].rsplit("/", 1)[1]
490 assert sent_rows(data_dir)[0]["opened_at"] == ""
491
492 page = open_link(objects_root, token)
493 assert object_documents.VIEW_BEACON in page["body"]
494 assert sent_rows(data_dir)[0]["opened_at"] == "" # the GET wrote nothing
495
496 beacon(objects_root, token)
497 first = sent_rows(data_dir)[0]["opened_at"]
498 assert first
499
500 beacon(objects_root, token)
501 open_link(objects_root, token, v="current")
502 assert sent_rows(data_dir)[0]["opened_at"] == first
503 assert beacon(objects_root, "not-a-token")["status"] == 404
504
505
506def test_an_unknown_or_blank_token_is_the_same_404_as_one_that_never_existed(
507 tmp_path, monkeypatch):
508 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
509 make_order(data_dir)
510 send(objects_root) # a real token exists, just not these
511
512 for token in ("totally-made-up", "", None):
513 result = open_link(objects_root, token)
514 assert result["status"] == 404
515 assert "not valid" in result["body"]
516 assert "403" not in str(result)
517 assert "Traceback" not in result["body"]
518
519
520def test_sending_refuses_a_nameless_business_and_a_missing_origin(
521 tmp_path, monkeypatch):
522 """Both refusals land where refusing costs one settings row and nobody is
523 waiting -- unlike the printer, where a parcel is."""
524 data_dir = tmp_path / "data"
525 for package_id, collection in (("app-documents", "sent_documents"),
526 ("app-orders", "orders"),
527 ("app-orders", "order_lines"),
528 ("app-email", "email_outbox")):
529 stage_collection(data_dir, package_id, collection)
530 stage_collection(data_dir, "app-settings", "app_settings", rows="")
531 objects_root = tmp_path / "objects"
532 shutil.copytree(PACKAGES / "app-documents" / "objects", objects_root,
533 dirs_exist_ok=True)
534 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
535 make_order(data_dir)
536
537 # No portal.base_url: this message is nothing but a link.
538 refusal = send(objects_root)
539 assert refusal["status"] == 409
540 assert refusal["setting"] == "portal.base_url"
541
542 object_records.create_collection_record(
543 "app_settings", {"id": "s9", "key": "portal.base_url",
544 "value": BASE_URL}, base_dir=data_dir)
545 nameless = send(objects_root)
546 assert nameless["status"] == 409
547 assert nameless["setting"] == "business.name"
548 assert sent_rows(data_dir) == []
549 assert outbox(data_dir) == []
550
551
552def test_a_packing_slip_cannot_be_rendered_from_an_invoice(tmp_path, monkeypatch):
553 """The kind decides which address the document carries, so the kind and
554 the source have to agree -- a packing slip built from an invoice would
555 print the wrong address on a box."""
556 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
557 make_order(data_dir)
558 refused = send(objects_root, kind="packing_slip", source="orders/ord-1")
559 assert refused["status"] == 400
560 assert "shipments" in refused["error"]
561
562
563def test_sending_requires_sign_in_and_refuses_somebody_elses_record(
564 tmp_path, monkeypatch):
565 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
566 make_order(data_dir)
567
568 assert send(objects_root, user_id=None)["status"] == 403
569 # Refused reads exactly like missing, so a guessed id learns nothing.
570 missing = send(objects_root, source="orders/no-such", user_id="mallory")
571 assert missing["status"] == 404
572 for stranger in ("mallory", "ops"):
573 refused = send(objects_root, user_id=stranger)
574 assert refused["status"] == 404
575 assert refused["error"].replace("orders/ord-1", "orders/no-such") == missing["error"]
576 assert sent_rows(data_dir) == []
577 assert outbox(data_dir) == []
578
579
580def test_sending_a_record_nobody_owns_is_for_an_admin_only(tmp_path, monkeypatch):
581 """The check used to be "has an owner who is not me", so a record with
582 NO owner could be mailed, with its lines, by any signed-in account. The
583 collection API shows it to nobody but an admin, and so does this."""
584 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
585 make_order(data_dir)
586 object_records.update_collection_record(
587 "orders", "ord-1", {"owner_id": ""}, base_dir=data_dir, actor="test")
588
589 assert send(objects_root, user_id="mallory")["status"] == 404
590 assert sent_rows(data_dir) == []
591 admin = run(objects_root, "action_send_document", "POST",
592 {"kind": "order", "source": "orders/ord-1", "to": "grace@acme.test",
593 "_identity": {"user_id": "ops", "roles": ["admin"]}})
594 assert admin.get("status") == "ok", admin
595
596
597# --- delivery 2: PDF as a capability, absent by default -------------------------
598
599def test_render_pdf_with_no_engine_names_exactly_what_to_install(
600 tmp_path, monkeypatch):
601 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
602 make_order(data_dir)
603 token = send(objects_root)["link"].rsplit("/", 1)[1]
604
605 result = run(objects_root, "action_render_pdf", "POST",
606 {"token": token, "_identity": {"user_id": OWNER}})
607
608 assert result["status"] == 409
609 assert result["setting"] == "documents.pdf_engine"
610 assert result["engine"] == "none"
611 assert set(result["install"]) == {"weasyprint", "chrome", "wkhtmltopdf"}
612 assert "pango/cairo" in result["install"]["weasyprint"]
613 # The free answer is named, because it already works.
614 assert "Save as PDF" in result["alternative"]
615 # And the boundary is demonstrated rather than described: the HTML in the
616 # refusal is the SAME page the print view serves, never a second template.
617 assert "table-header-group" in result["html"]
618 assert "36.00 USD" in result["html"]
619
620
621def test_a_named_engine_with_nothing_behind_it_is_reported_not_swallowed(
622 tmp_path, monkeypatch):
623 """An operator who pasted an engine name in and heard nothing would
624 reasonably conclude PDFs were being generated."""
625 data_dir, objects_root = setup_env(
626 tmp_path, monkeypatch,
627 extra_settings=(("documents.pdf_engine", "weasyprint"),))
628 make_order(data_dir)
629 token = send(objects_root)["link"].rsplit("/", 1)[1]
630
631 result = run(objects_root, "action_render_pdf", "POST",
632 {"token": token, "_identity": {"user_id": OWNER}})
633 assert result["status"] == 409
634 assert result["engine"] == "weasyprint"
635 assert "no PDF engine module is installed" in result["error"]
636 assert set(result["install"]) == {"weasyprint"}
637
638
639@pytest.mark.parametrize("engine", ["", "none", "weasyprint", "chrome",
640 "typo-engine"])
641def test_no_surface_offers_a_pdf_button_when_it_would_409(
642 tmp_path, monkeypatch, engine):
643 """The property, swept over every document surface this layer serves.
644
645 A button that 409s tells the person pressing it that something is broken
646 on YOUR end -- the same reason site_invoice_portal only draws "Pay by
647 card" when Stripe is actually configured.
648 """
649 extra = (("documents.pdf_engine", engine),) if engine else ()
650 data_dir, objects_root = setup_env(tmp_path, monkeypatch,
651 extra_settings=extra)
652 make_order(data_dir)
653 make_invoice(data_dir)
654 shipment(data_dir)
655 token = send(objects_root)["link"].rsplit("/", 1)[1]
656
657 assert object_documents.pdf_engine_status(engine)["available"] is False
658
659 pages = {
660 "sent document": open_link(objects_root, token)["body"],
661 "packing slip": run(objects_root, "site_packing_slip", "GET",
662 {"shipment_id": "ship-1", "_identity": {"user_id": OWNER}})["body"],
663 "invoice portal": run(objects_root, "site_invoice_portal", "GET",
664 {"token": "invoice-token-1"})["body"],
665 }
666 for name, body in pages.items():
667 assert "Download PDF" not in body, name
668 assert "action_render_pdf" not in body, name
669 # ...and every one of them says the thing that DOES work.
670 assert "Save as PDF" in body, name
671 assert "Ctrl/Cmd+P" in body, name
672
673
674# --- the two migrated pages ------------------------------------------------------
675
676def make_invoice(data_dir, invoice_id="inv-1"):
677 object_records.create_collection_record(
678 "invoices",
679 {"id": invoice_id, "number": "INV-9", "customer_name": "Grace Hopper",
680 "customer_email": "grace@acme.test", "currency": "USD",
681 "status": "sent", "issue_date": "2026-06-10", "due_date": "2026-07-10",
682 "total_cents": "3600",
683 "portal_token": "invoice-token-1", "owner_id": OWNER},
684 base_dir=data_dir, preserve_read_only=True)
685 object_records.create_collection_record(
686 "invoice_lines",
687 {"id": "il-1", "invoice_id": invoice_id, "description": "Enamel Mug",
688 "quantity": "3", "unit_price_cents": "1200",
689 "line_total_cents": "3600", "owner_id": OWNER},
690 base_dir=data_dir)
691
692
693def shipment(data_dir, shipment_id="ship-1"):
694 object_records.create_collection_record(
695 "shipments",
696 {"id": shipment_id, "order_id": "ord-1", "direction": "outbound",
697 "status": "shipped", "ship_to_name": "Grace Hopper",
698 "ship_to_address": "9 Navy Yard", "shipped_on": "2026-07-02",
699 "owner_id": OWNER},
700 base_dir=data_dir)
701 object_records.create_collection_record(
702 "shipment_lines",
703 {"id": "sl-1", "shipment_id": shipment_id, "order_line_id": "line-1",
704 "description": "Enamel Mug", "quantity": "3",
705 "owner_id": OWNER},
706 base_dir=data_dir)
707
708
709def test_the_packing_slip_still_shows_no_prices_after_migrating(
710 tmp_path, monkeypatch):
711 """THE regression that matters. Everything else about this page could
712 change and be fixed later; a price on a packing slip is the amount paid
713 stapled to a birthday present, and it is already in the post."""
714 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
715 make_order(data_dir)
716 shipment(data_dir)
717
718 body = run(objects_root, "site_packing_slip", "GET",
719 {"shipment_id": "ship-1", "_identity": {"user_id": OWNER}})["body"]
720
721 for forbidden in ("$", "36.00", "12.00", "3600", "1200", "USD",
722 "Unit price", "unit_price", "_cents", "Total"):
723 assert forbidden not in body, forbidden
724
725 # It is still a usable packing slip: goods, quantity, order, ship-to.
726 assert "Enamel Mug" in body
727 assert ">3<" in body
728 assert "Q-1001" in body
729 assert "Grace Hopper" in body
730 assert "Ship to" in body and "Bill to" not in body
731 # ...printed through the shared layer, with the rule the old page lacked.
732 assert "table-header-group" in body
733 assert "@media print" in body
734
735
736def test_the_invoice_portal_still_shows_prices_status_and_the_pay_button(
737 tmp_path, monkeypatch):
738 """The other half of the proof: migrating must not cost the portal
739 anything it had. Prices, the status bucket, the payment instructions and
740 the card button all survive."""
741 data_dir, objects_root = setup_env(
742 tmp_path, monkeypatch,
743 extra_settings=(("portal.payment_instructions", "Wire to Acme Bank"),))
744 make_invoice(data_dir)
745 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_x")
746 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_x")
747
748 result = run(objects_root, "site_invoice_portal", "GET",
749 {"token": "invoice-token-1"})
750 body = result["body"]
751 assert result.get("status", 200) == 200
752
753 assert "Payment due" in body # the status bucket
754 assert "Amount due" in body # the tile
755 assert "36.00 USD" in body # the money, in whole units
756 assert "12.00 USD" in body # the line's unit price
757 assert "3600" not in body.replace("36.00 USD", "") # never raw minor units
758 assert "Enamel Mug" in body # the lines table
759 assert "Wire to Acme Bank" in body # payment instructions
760 assert 'id="paybtn"' in body # the card button, configured
761 assert "Bill to" in body and "Ship to" not in body
762 assert "Acme Supplies Ltd" in body # the business header
763 # No app chrome on a page handed to a stranger's inbox.
764 assert "/nav" not in body
765 # ...and the shared print rules came with it.
766 assert "table-header-group" in body
767
768
769def test_the_portal_never_nags_a_customer_about_an_unconfigured_business(
770 tmp_path, monkeypatch):
771 """An unbranded invoice is honest. Telling the CUSTOMER to go and set
772 business.name is the sender's software talking over the sender, about
773 something the reader cannot fix."""
774 data_dir = tmp_path / "data"
775 for package_id, collection in (("app-invoices", "invoices"),
776 ("app-invoices", "invoice_lines")):
777 stage_collection(data_dir, package_id, collection)
778 stage_collection(data_dir, "app-settings", "app_settings", rows="")
779 objects_root = tmp_path / "objects"
780 shutil.copytree(PACKAGES / "app-invoices" / "objects", objects_root,
781 dirs_exist_ok=True)
782 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
783 make_invoice(data_dir)
784
785 body = run(objects_root, "site_invoice_portal", "GET",
786 {"token": "invoice-token-1"})["body"]
787 assert "business.name" not in body
788 assert "36.00 USD" in body
789
790
791def test_the_operators_own_printable_is_told_quietly_and_off_the_paper(
792 tmp_path, monkeypatch):
793 """The other side of the same rule: the person who CAN set business.name
794 is the operator, so the nudge goes on their page -- and it is .noprint, so
795 it never reaches the parcel."""
796 data_dir = tmp_path / "data"
797 for package_id, collection in (("app-orders", "orders"),
798 ("app-orders", "order_lines"),
799 ("app-shipping", "shipments"),
800 ("app-shipping", "shipment_lines")):
801 stage_collection(data_dir, package_id, collection)
802 stage_collection(data_dir, "app-settings", "app_settings", rows="")
803 objects_root = tmp_path / "objects"
804 shutil.copytree(PACKAGES / "app-shipping" / "objects", objects_root,
805 dirs_exist_ok=True)
806 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
807 make_order(data_dir)
808 shipment(data_dir)
809
810 body = run(objects_root, "site_packing_slip", "GET",
811 {"shipment_id": "ship-1", "_identity": {"user_id": OWNER}})["body"]
812 assert "business.name" in body
813 assert 'class="doc-setup noprint"' in body
814 assert "$" not in body
815
816
817# --- the package declares itself the way every other package must ---------------
818
819def test_the_package_manifest_declares_its_door_routes_and_permissions():
820 manifest = json.loads(
821 (PACKAGES / "app-documents" / "dbbasic-package.json").read_text())
822 assert manifest["version"] == "0.1.3" # 0.1.3: source_rev is the keyed client rev
823 assert [entry["id"] for entry in manifest["nav"]] == ["documents"]
824 assert manifest["nav"][0]["group"] == "Work"
825
826 rules = json.loads(
827 (PACKAGES / "app-documents" / "permissions" / "rules.json").read_text())
828 by_object = {rule.get("object_id"): rule for rule in rules["rules"]}
829 # The public door is the tokened page and nothing else.
830 assert by_object["site_document"]["principal"] == "public"
831 assert by_object["action_send_document"]["principal"] == "registered"
832 assert by_object["action_render_pdf"]["principal"] == "registered"
833
834 collection_rule = [rule for rule in rules["rules"]
835 if rule.get("collection") == "sent_documents"
836 and rule["effect"] == "allow"][0]
837 # A document that was sent cannot be made not to have been sent.
838 assert "delete" not in collection_rule["actions"]
839 assert collection_rule["row_filter"] == {"owner_id": "$user_id"}
840 # Leaving delete out of the grant is not enough on its own: the engine's
841 # owner fallback would still give it to the document's owner.
842 assert [rule["actions"] for rule in rules["rules"]
843 if rule.get("collection") == "sent_documents"
844 and rule["principal"] == "owner_fallback"] == [["delete"]]