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_documents.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_documents.py · 32.6 KB · 773 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_an_unchanged_source_shows_no_banner_at_all(tmp_path, monkeypatch):
435 """A banner on an unchanged document would teach people to ignore it."""
436 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
437 make_order(data_dir)
438 token = send(objects_root)["link"].rsplit("/", 1)[1]
439
440 body = open_link(objects_root, token)["body"]
441 assert '<div class="doc-banner">' not in body
442 assert "was changed" not in body
443 assert "36.00 USD" in body
444
445
446def test_opened_at_stamps_once_and_is_idempotent(tmp_path, monkeypatch):
447 """'Did they read it?' is the first thing anyone asks after sending a
448 quote. The fact worth keeping is that they opened it, not how many times,
449 so it is written only while the field is empty."""
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 assert sent_rows(data_dir)[0]["opened_at"] == ""
454
455 open_link(objects_root, token)
456 first = sent_rows(data_dir)[0]["opened_at"]
457 assert first
458
459 open_link(objects_root, token)
460 open_link(objects_root, token, v="current")
461 assert sent_rows(data_dir)[0]["opened_at"] == first
462
463
464def test_an_unknown_or_blank_token_is_the_same_404_as_one_that_never_existed(
465 tmp_path, monkeypatch):
466 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
467 make_order(data_dir)
468 send(objects_root) # a real token exists, just not these
469
470 for token in ("totally-made-up", "", None):
471 result = open_link(objects_root, token)
472 assert result["status"] == 404
473 assert "not valid" in result["body"]
474 assert "403" not in str(result)
475 assert "Traceback" not in result["body"]
476
477
478def test_sending_refuses_a_nameless_business_and_a_missing_origin(
479 tmp_path, monkeypatch):
480 """Both refusals land where refusing costs one settings row and nobody is
481 waiting -- unlike the printer, where a parcel is."""
482 data_dir = tmp_path / "data"
483 for package_id, collection in (("app-documents", "sent_documents"),
484 ("app-orders", "orders"),
485 ("app-orders", "order_lines"),
486 ("app-email", "email_outbox")):
487 stage_collection(data_dir, package_id, collection)
488 stage_collection(data_dir, "app-settings", "app_settings", rows="")
489 objects_root = tmp_path / "objects"
490 shutil.copytree(PACKAGES / "app-documents" / "objects", objects_root,
491 dirs_exist_ok=True)
492 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
493 make_order(data_dir)
494
495 # No portal.base_url: this message is nothing but a link.
496 refusal = send(objects_root)
497 assert refusal["status"] == 409
498 assert refusal["setting"] == "portal.base_url"
499
500 object_records.create_collection_record(
501 "app_settings", {"id": "s9", "key": "portal.base_url",
502 "value": BASE_URL}, base_dir=data_dir)
503 nameless = send(objects_root)
504 assert nameless["status"] == 409
505 assert nameless["setting"] == "business.name"
506 assert sent_rows(data_dir) == []
507 assert outbox(data_dir) == []
508
509
510def test_a_packing_slip_cannot_be_rendered_from_an_invoice(tmp_path, monkeypatch):
511 """The kind decides which address the document carries, so the kind and
512 the source have to agree -- a packing slip built from an invoice would
513 print the wrong address on a box."""
514 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
515 make_order(data_dir)
516 refused = send(objects_root, kind="packing_slip", source="orders/ord-1")
517 assert refused["status"] == 400
518 assert "shipments" in refused["error"]
519
520
521def test_sending_requires_sign_in_and_refuses_somebody_elses_record(
522 tmp_path, monkeypatch):
523 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
524 make_order(data_dir)
525
526 assert send(objects_root, user_id=None)["status"] == 403
527 assert send(objects_root, user_id="mallory")["status"] == 403
528 assert send(objects_root, user_id="ops")["status"] == 403
529 assert sent_rows(data_dir) == []
530
531
532# --- delivery 2: PDF as a capability, absent by default -------------------------
533
534def test_render_pdf_with_no_engine_names_exactly_what_to_install(
535 tmp_path, monkeypatch):
536 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
537 make_order(data_dir)
538 token = send(objects_root)["link"].rsplit("/", 1)[1]
539
540 result = run(objects_root, "action_render_pdf", "POST",
541 {"token": token, "_identity": {"user_id": OWNER}})
542
543 assert result["status"] == 409
544 assert result["setting"] == "documents.pdf_engine"
545 assert result["engine"] == "none"
546 assert set(result["install"]) == {"weasyprint", "chrome", "wkhtmltopdf"}
547 assert "pango/cairo" in result["install"]["weasyprint"]
548 # The free answer is named, because it already works.
549 assert "Save as PDF" in result["alternative"]
550 # And the boundary is demonstrated rather than described: the HTML in the
551 # refusal is the SAME page the print view serves, never a second template.
552 assert "table-header-group" in result["html"]
553 assert "36.00 USD" in result["html"]
554
555
556def test_a_named_engine_with_nothing_behind_it_is_reported_not_swallowed(
557 tmp_path, monkeypatch):
558 """An operator who pasted an engine name in and heard nothing would
559 reasonably conclude PDFs were being generated."""
560 data_dir, objects_root = setup_env(
561 tmp_path, monkeypatch,
562 extra_settings=(("documents.pdf_engine", "weasyprint"),))
563 make_order(data_dir)
564 token = send(objects_root)["link"].rsplit("/", 1)[1]
565
566 result = run(objects_root, "action_render_pdf", "POST",
567 {"token": token, "_identity": {"user_id": OWNER}})
568 assert result["status"] == 409
569 assert result["engine"] == "weasyprint"
570 assert "no PDF engine module is installed" in result["error"]
571 assert set(result["install"]) == {"weasyprint"}
572
573
574@pytest.mark.parametrize("engine", ["", "none", "weasyprint", "chrome",
575 "typo-engine"])
576def test_no_surface_offers_a_pdf_button_when_it_would_409(
577 tmp_path, monkeypatch, engine):
578 """The property, swept over every document surface this layer serves.
579
580 A button that 409s tells the person pressing it that something is broken
581 on YOUR end -- the same reason site_invoice_portal only draws "Pay by
582 card" when Stripe is actually configured.
583 """
584 extra = (("documents.pdf_engine", engine),) if engine else ()
585 data_dir, objects_root = setup_env(tmp_path, monkeypatch,
586 extra_settings=extra)
587 make_order(data_dir)
588 make_invoice(data_dir)
589 shipment(data_dir)
590 token = send(objects_root)["link"].rsplit("/", 1)[1]
591
592 assert object_documents.pdf_engine_status(engine)["available"] is False
593
594 pages = {
595 "sent document": open_link(objects_root, token)["body"],
596 "packing slip": run(objects_root, "site_packing_slip", "GET",
597 {"shipment_id": "ship-1"})["body"],
598 "invoice portal": run(objects_root, "site_invoice_portal", "GET",
599 {"token": "invoice-token-1"})["body"],
600 }
601 for name, body in pages.items():
602 assert "Download PDF" not in body, name
603 assert "action_render_pdf" not in body, name
604 # ...and every one of them says the thing that DOES work.
605 assert "Save as PDF" in body, name
606 assert "Ctrl/Cmd+P" in body, name
607
608
609# --- the two migrated pages ------------------------------------------------------
610
611def make_invoice(data_dir, invoice_id="inv-1"):
612 object_records.create_collection_record(
613 "invoices",
614 {"id": invoice_id, "number": "INV-9", "customer_name": "Grace Hopper",
615 "customer_email": "grace@acme.test", "currency": "USD",
616 "status": "sent", "issue_date": "2026-06-10", "due_date": "2026-07-10",
617 "total_cents": "3600",
618 "portal_token": "invoice-token-1", "owner_id": OWNER},
619 base_dir=data_dir, preserve_read_only=True)
620 object_records.create_collection_record(
621 "invoice_lines",
622 {"id": "il-1", "invoice_id": invoice_id, "description": "Enamel Mug",
623 "quantity": "3", "unit_price_cents": "1200",
624 "line_total_cents": "3600", "owner_id": OWNER},
625 base_dir=data_dir)
626
627
628def shipment(data_dir, shipment_id="ship-1"):
629 object_records.create_collection_record(
630 "shipments",
631 {"id": shipment_id, "order_id": "ord-1", "direction": "outbound",
632 "status": "shipped", "ship_to_name": "Grace Hopper",
633 "ship_to_address": "9 Navy Yard", "shipped_on": "2026-07-02",
634 "owner_id": OWNER},
635 base_dir=data_dir)
636 object_records.create_collection_record(
637 "shipment_lines",
638 {"id": "sl-1", "shipment_id": shipment_id, "order_line_id": "line-1",
639 "description": "Enamel Mug", "quantity": "3",
640 "owner_id": OWNER},
641 base_dir=data_dir)
642
643
644def test_the_packing_slip_still_shows_no_prices_after_migrating(
645 tmp_path, monkeypatch):
646 """THE regression that matters. Everything else about this page could
647 change and be fixed later; a price on a packing slip is the amount paid
648 stapled to a birthday present, and it is already in the post."""
649 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
650 make_order(data_dir)
651 shipment(data_dir)
652
653 body = run(objects_root, "site_packing_slip", "GET",
654 {"shipment_id": "ship-1"})["body"]
655
656 for forbidden in ("$", "36.00", "12.00", "3600", "1200", "USD",
657 "Unit price", "unit_price", "_cents", "Total"):
658 assert forbidden not in body, forbidden
659
660 # It is still a usable packing slip: goods, quantity, order, ship-to.
661 assert "Enamel Mug" in body
662 assert ">3<" in body
663 assert "Q-1001" in body
664 assert "Grace Hopper" in body
665 assert "Ship to" in body and "Bill to" not in body
666 # ...printed through the shared layer, with the rule the old page lacked.
667 assert "table-header-group" in body
668 assert "@media print" in body
669
670
671def test_the_invoice_portal_still_shows_prices_status_and_the_pay_button(
672 tmp_path, monkeypatch):
673 """The other half of the proof: migrating must not cost the portal
674 anything it had. Prices, the status bucket, the payment instructions and
675 the card button all survive."""
676 data_dir, objects_root = setup_env(
677 tmp_path, monkeypatch,
678 extra_settings=(("portal.payment_instructions", "Wire to Acme Bank"),))
679 make_invoice(data_dir)
680 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_x")
681 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_x")
682
683 result = run(objects_root, "site_invoice_portal", "GET",
684 {"token": "invoice-token-1"})
685 body = result["body"]
686 assert result.get("status", 200) == 200
687
688 assert "Payment due" in body # the status bucket
689 assert "Amount due" in body # the tile
690 assert "36.00 USD" in body # the money, in whole units
691 assert "12.00 USD" in body # the line's unit price
692 assert "3600" not in body.replace("36.00 USD", "") # never raw minor units
693 assert "Enamel Mug" in body # the lines table
694 assert "Wire to Acme Bank" in body # payment instructions
695 assert 'id="paybtn"' in body # the card button, configured
696 assert "Bill to" in body and "Ship to" not in body
697 assert "Acme Supplies Ltd" in body # the business header
698 # No app chrome on a page handed to a stranger's inbox.
699 assert "/nav" not in body
700 # ...and the shared print rules came with it.
701 assert "table-header-group" in body
702
703
704def test_the_portal_never_nags_a_customer_about_an_unconfigured_business(
705 tmp_path, monkeypatch):
706 """An unbranded invoice is honest. Telling the CUSTOMER to go and set
707 business.name is the sender's software talking over the sender, about
708 something the reader cannot fix."""
709 data_dir = tmp_path / "data"
710 for package_id, collection in (("app-invoices", "invoices"),
711 ("app-invoices", "invoice_lines")):
712 stage_collection(data_dir, package_id, collection)
713 stage_collection(data_dir, "app-settings", "app_settings", rows="")
714 objects_root = tmp_path / "objects"
715 shutil.copytree(PACKAGES / "app-invoices" / "objects", objects_root,
716 dirs_exist_ok=True)
717 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
718 make_invoice(data_dir)
719
720 body = run(objects_root, "site_invoice_portal", "GET",
721 {"token": "invoice-token-1"})["body"]
722 assert "business.name" not in body
723 assert "36.00 USD" in body
724
725
726def test_the_operators_own_printable_is_told_quietly_and_off_the_paper(
727 tmp_path, monkeypatch):
728 """The other side of the same rule: the person who CAN set business.name
729 is the operator, so the nudge goes on their page -- and it is .noprint, so
730 it never reaches the parcel."""
731 data_dir = tmp_path / "data"
732 for package_id, collection in (("app-orders", "orders"),
733 ("app-orders", "order_lines"),
734 ("app-shipping", "shipments"),
735 ("app-shipping", "shipment_lines")):
736 stage_collection(data_dir, package_id, collection)
737 stage_collection(data_dir, "app-settings", "app_settings", rows="")
738 objects_root = tmp_path / "objects"
739 shutil.copytree(PACKAGES / "app-shipping" / "objects", objects_root,
740 dirs_exist_ok=True)
741 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
742 make_order(data_dir)
743 shipment(data_dir)
744
745 body = run(objects_root, "site_packing_slip", "GET",
746 {"shipment_id": "ship-1"})["body"]
747 assert "business.name" in body
748 assert 'class="doc-setup noprint"' in body
749 assert "$" not in body
750
751
752# --- the package declares itself the way every other package must ---------------
753
754def test_the_package_manifest_declares_its_door_routes_and_permissions():
755 manifest = json.loads(
756 (PACKAGES / "app-documents" / "dbbasic-package.json").read_text())
757 assert manifest["version"] == "0.1.0"
758 assert [entry["id"] for entry in manifest["nav"]] == ["documents"]
759 assert manifest["nav"][0]["group"] == "Work"
760
761 rules = json.loads(
762 (PACKAGES / "app-documents" / "permissions" / "rules.json").read_text())
763 by_object = {rule.get("object_id"): rule for rule in rules["rules"]}
764 # The public door is the tokened page and nothing else.
765 assert by_object["site_document"]["principal"] == "public"
766 assert by_object["action_send_document"]["principal"] == "registered"
767 assert by_object["action_render_pdf"]["principal"] == "registered"
768
769 collection_rule = [rule for rule in rules["rules"]
770 if rule.get("collection") == "sent_documents"][0]
771 # A document that was sent cannot be made not to have been sent.
772 assert "delete" not in collection_rule["actions"]
773 assert collection_rule["row_filter"] == {"owner_id": "$user_id"}