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_invoice_portal.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, 19 minutes ago History
test_invoice_portal.py · 18.9 KB · 463 lines
1"""Customer payment portal (plan/customer-payment-portal-spec.md): the door
2a dunning email currently has no way to point at.
3
4Fixture style mirrors tests/test_payments_slice2.py -- direct
5object_execution.execute_object calls against the real package objects,
6schemas copied straight from packages/app-invoices/schemas/*.json (so a
7future schema edit can't silently drift out of sync with what this test
8exercises), and app-payments' own system_invoice_status object reused
9(read-only, never edited here) to produce a realistic partial/paid state
10the same way a live deployment would, rather than hand-faking the
11computed amount_paid_cents/balance_due_cents fields.
12
13Security posture under test, per the spec's own sketch: portal_token
14never surfaces in a list/search response for a non-owner (guaranteed by
15the pre-existing row_filter on the invoices collection, unrelated to
16anything this feature adds -- proven directly against
17packages/app-invoices/permissions/rules.json); the portal page 404s on a
18bad or blank token, never 403 (never confirm the token space exists);
19void invoices refuse the portal's financial content; and regenerating a
20link invalidates whatever token was live before.
21"""
22
23import json
24import pathlib
25
26import object_documents
27import object_execution
28import object_permissions
29import object_records
30import python_object_runtime
31from conftest import stage_collection
32
33REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
34PACKAGES = REPO_ROOT / "packages"
35APP_INVOICES = PACKAGES / "app-invoices"
36RUNTIME = python_object_runtime.PythonObjectRuntime()
37
38
39def setup_env(tmp_path, monkeypatch, *, settings=(), with_invoice_lines=False):
40 data_dir = tmp_path / "data"
41
42 # invoices: header is the real seed file's own header line -- kept in
43 # sync with the schema by construction (the seed IS real invoice data),
44 # rather than a second hand-typed field list that could drift. Not
45 # schema_header(): deliberately verbatim, per this module's docstring.
46 schema_dir = data_dir / "schemas"
47 schema_dir.mkdir(parents=True, exist_ok=True)
48 (schema_dir / "invoices.json").write_text(
49 (APP_INVOICES / "schemas" / "invoices.json").read_text())
50 invoices_header = (APP_INVOICES / "seed" / "invoices.tsv").read_text().splitlines()[0] + "\n"
51 invoices_coll = data_dir / "collections" / "invoices"
52 invoices_coll.mkdir(parents=True, exist_ok=True)
53 (invoices_coll / "records.tsv").write_text(invoices_header)
54
55 stage_collection(data_dir, "app-payments", "payments")
56 stage_collection(data_dir, "app-payments", "refunds")
57 stage_collection(data_dir, "app-invoices", "invoice_credits")
58 stage_collection(data_dir, "app-email", "email_outbox")
59 if with_invoice_lines:
60 stage_collection(data_dir, "app-invoices", "invoice_lines")
61
62 rows = ""
63 for i, (k, v) in enumerate(settings):
64 rows += f"s{i}\t{k}\t{v}\t\n"
65 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
66 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
67 return data_dir
68
69
70def make_invoice(data_dir, iid="inv1", status="sent", total="10000",
71 due="2026-07-10", email="grace@acme.test", owner="dan", **extra):
72 rec = {"id": iid, "number": f"N-{iid}", "customer_name": "Grace Hopper",
73 "customer_email": email, "status": status, "due_date": due,
74 "issue_date": "2026-06-10", "total_cents": total, "owner_id": owner}
75 rec.update(extra)
76 return object_records.create_collection_record("invoices", rec, base_dir=data_dir)
77
78
79def pay(data_dir, pid, invoice_id, cents, status="received"):
80 return object_records.create_collection_record(
81 "payments",
82 {"id": pid, "invoice_id": invoice_id, "amount_cents": cents,
83 "method": "card", "received_on": "2026-07-09", "status": status,
84 "owner_id": "dan"},
85 base_dir=data_dir)
86
87
88def fire_status(collection, record_id, action_raw):
89 """Reuses app-payments' own system_invoice_status object (read-only
90 import, not edited by this task) to produce realistic partial/paid
91 invoice state -- amount_paid_cents/balance_due_cents/status all
92 genuinely computed, not hand-faked."""
93 return object_execution.execute_object(
94 RUNTIME,
95 object_execution.ObjectExecutionRequest(
96 "system_invoice_status", method="EVENT",
97 payload={"event": f"{collection}.record.{action_raw}d",
98 "collection": collection, "record_id": record_id,
99 "action": action_raw}),
100 roots=[PACKAGES / "app-payments" / "objects"])
101
102
103def run_aging(today):
104 return object_execution.execute_object(
105 RUNTIME,
106 object_execution.ObjectExecutionRequest(
107 "system_invoice_aging", method="POST", payload={"today": today}),
108 roots=[APP_INVOICES / "objects"])
109
110
111def portal_get(token, query_extra=None):
112 payload = {"token": token}
113 if query_extra:
114 payload.update(query_extra)
115 return object_execution.execute_object(
116 RUNTIME,
117 object_execution.ObjectExecutionRequest(
118 "site_invoice_portal", method="GET", payload=payload),
119 roots=[APP_INVOICES / "objects"])
120
121
122def regenerate(invoice_id, user_id="dan", roles=None):
123 identity = {"user_id": user_id, "roles": roles or []} if user_id else {}
124 payload = {"invoice_id": invoice_id}
125 if identity:
126 payload["_identity"] = identity
127 return object_execution.execute_object(
128 RUNTIME,
129 object_execution.ObjectExecutionRequest(
130 "action_regenerate_portal_link", method="POST", payload=payload),
131 roots=[APP_INVOICES / "objects"])
132
133
134def invoice(data_dir, iid="inv1"):
135 return object_records.get_collection_record("invoices", iid, base_dir=data_dir)
136
137
138def outbox(data_dir):
139 return object_records.read_collection_records("email_outbox", base_dir=data_dir)
140
141
142def token_for(data_dir, iid="inv1", owner="dan"):
143 """Mint a portal link the way an owner would, and return the bare token."""
144 result = regenerate(iid, user_id=owner)
145 assert result.ok, result.error
146 path = result.result["path"]
147 assert path.startswith("/pay/")
148 return path[len("/pay/"):]
149
150
151# --- states -----------------------------------------------------------------
152
153def test_unpaid_state_shows_amount_due_and_instructions_with_no_pay_button(tmp_path, monkeypatch):
154 data_dir = setup_env(tmp_path, monkeypatch,
155 settings=(("portal.payment_instructions",
156 "Wire to Acme Bank, account 000123"),))
157 make_invoice(data_dir, total="10000")
158 token = token_for(data_dir)
159
160 result = portal_get(token)
161 assert result.ok, result.error
162 body = result.result["body"]
163 assert result.result.get("status", 200) == 200
164 assert "Payment due" in body
165 assert "100.00 USD" in body # balance_due_cents=10000
166 assert "Wire to Acme Bank, account 000123" in body
167 # No fake Pay button: there is no card-processing rail wired up yet, and
168 # a button that posts nowhere is worse than no button at all.
169 assert "Pay now" not in body and "<button" not in body and "<form" not in body
170
171
172def test_unpaid_state_without_instructions_says_so_plainly(tmp_path, monkeypatch):
173 data_dir = setup_env(tmp_path, monkeypatch) # no portal.payment_instructions set
174 make_invoice(data_dir, total="5000")
175 token = token_for(data_dir)
176
177 body = portal_get(token).result["body"]
178 assert "has not published payment instructions" in body
179 # Never an empty box standing in for the missing setting.
180 assert '<div class="instructions"></div>' not in body
181
182
183def test_partial_state_shows_received_and_remaining(tmp_path, monkeypatch):
184 data_dir = setup_env(tmp_path, monkeypatch)
185 make_invoice(data_dir, total="10000")
186 pay(data_dir, "p1", "inv1", "4000")
187 fire_status("payments", "p1", "create")
188 assert invoice(data_dir)["status"] == "partial"
189 token = token_for(data_dir)
190
191 body = portal_get(token).result["body"]
192 assert "Partially paid" in body
193 assert "40.00 USD" in body # received so far
194 assert "60.00 USD" in body # still due
195 assert "How to pay" in body
196
197
198def test_paid_state_renders_receipt_with_no_payment_instructions(tmp_path, monkeypatch):
199 data_dir = setup_env(tmp_path, monkeypatch,
200 settings=(("portal.payment_instructions", "Wire details here"),))
201 make_invoice(data_dir, total="10000")
202 pay(data_dir, "p1", "inv1", "10000")
203 fire_status("payments", "p1", "create")
204 assert invoice(data_dir)["status"] == "paid"
205 token = token_for(data_dir)
206
207 body = portal_get(token).result["body"]
208 assert "Paid in full" in body
209 assert "100.00 USD" in body
210 assert "No further payment is due" in body
211 assert "Wire details here" not in body # receipt view, not a pay ask
212
213
214def test_void_invoice_refuses_the_portal(tmp_path, monkeypatch):
215 data_dir = setup_env(tmp_path, monkeypatch,
216 settings=(("portal.payment_instructions", "Wire details here"),))
217 make_invoice(data_dir, status="void", total="10000")
218 token = token_for(data_dir)
219
220 result = portal_get(token)
221 body = result.result["body"]
222 assert result.result.get("status", 200) == 200 # a real page, not a 404 -- it IS found
223 assert "cancelled" in body.lower()
224 # Refuses the financial content entirely: no balance, no instructions,
225 # no line items -- showing any of that on a cancelled document would
226 # invite paying a bill that no longer exists.
227 assert "Amount due" not in body
228 assert "Wire details here" not in body
229
230
231# --- token lookup security ----------------------------------------------
232
233def test_unknown_token_is_404_not_403(tmp_path, monkeypatch):
234 data_dir = setup_env(tmp_path, monkeypatch)
235 make_invoice(data_dir)
236 token_for(data_dir) # a real token exists in the system, just not this one
237
238 result = portal_get("totally-made-up-token-value")
239 assert result.result["status"] == 404
240 assert "not found" in result.result["body"].lower()
241 assert "403" not in str(result.result)
242
243
244def test_blank_token_is_404_even_when_no_invoice_has_minted_one(tmp_path, monkeypatch):
245 """A blank submitted token must never match a blank stored portal_token
246 (an invoice that has never had a link generated) -- otherwise "no link
247 yet" would accidentally be an open door."""
248 data_dir = setup_env(tmp_path, monkeypatch)
249 make_invoice(data_dir) # portal_token left at its default: blank
250
251 result = portal_get("")
252 assert result.result["status"] == 404
253
254
255# --- view counters ------------------------------------------------------
256
257def portal_beacon(token):
258 """What the rendered page's VIEW_BEACON sends once a browser has it open."""
259 return object_execution.execute_object(
260 RUNTIME,
261 object_execution.ObjectExecutionRequest(
262 "site_invoice_portal", method="POST", payload={"token": token}),
263 roots=[APP_INVOICES / "objects"])
264
265
266def test_portal_view_stamps_counter_and_timestamp_on_every_view(tmp_path, monkeypatch):
267 """A view is counted by the page's beacon POST, once per page a browser
268 actually rendered."""
269 data_dir = setup_env(tmp_path, monkeypatch)
270 make_invoice(data_dir)
271 token = token_for(data_dir)
272
273 assert invoice(data_dir)["portal_views"] in ("0", "", None)
274 assert object_documents.VIEW_BEACON in portal_get(token).result["body"]
275 portal_beacon(token)
276 row = invoice(data_dir)
277 assert row["portal_views"] == "1"
278 assert row["last_viewed_at"]
279
280 portal_beacon(token)
281 assert invoice(data_dir)["portal_views"] == "2"
282
283
284def test_the_get_itself_writes_nothing(tmp_path, monkeypatch):
285 """A mail scanner or link prefetcher GETs every link in a message on
286 delivery. Counting that as a view said "viewed" about an invoice nobody
287 had opened, and each bump changed the invoice's record rev under the
288 owner's own expected_rev edit."""
289 data_dir = setup_env(tmp_path, monkeypatch)
290 make_invoice(data_dir)
291 token = token_for(data_dir)
292 rev = object_records.compute_record_rev(invoice(data_dir))
293
294 portal_get(token)
295 portal_get(token)
296 assert invoice(data_dir)["portal_views"] in ("0", "", None)
297 assert object_records.compute_record_rev(invoice(data_dir)) == rev
298
299
300def test_a_beacon_with_a_wrong_token_writes_nothing(tmp_path, monkeypatch):
301 data_dir = setup_env(tmp_path, monkeypatch)
302 make_invoice(data_dir)
303 token_for(data_dir)
304 assert portal_beacon("not-the-token").result["status"] == 404
305 assert portal_beacon("").result["status"] == 404
306 assert invoice(data_dir)["portal_views"] in ("0", "", None)
307
308
309# --- line items -----------------------------------------------------------
310
311def test_line_items_render_when_invoice_lines_is_installed(tmp_path, monkeypatch):
312 data_dir = setup_env(tmp_path, monkeypatch, with_invoice_lines=True)
313 make_invoice(data_dir, total="10000")
314 object_records.create_collection_record(
315 "invoice_lines",
316 {"id": "l1", "invoice_id": "inv1", "description": "Consulting hours",
317 "quantity": "2", "unit_price_cents": "5000", "line_total_cents": "10000",
318 "owner_id": "dan"},
319 base_dir=data_dir)
320 token = token_for(data_dir)
321
322 body = portal_get(token).result["body"]
323 assert "Consulting hours" in body
324 assert "50.00 USD" in body # unit price
325
326
327def test_line_items_skip_gracefully_when_invoice_lines_not_installed(tmp_path, monkeypatch):
328 data_dir = setup_env(tmp_path, monkeypatch, with_invoice_lines=False)
329 make_invoice(data_dir, total="10000")
330 token = token_for(data_dir)
331
332 result = portal_get(token)
333 assert result.ok, result.error # must not crash just because the collection is absent
334 body = result.result["body"]
335 assert result.result.get("status", 200) == 200
336 assert '<table class="lines">' not in body
337
338
339# --- regeneration ---------------------------------------------------------
340
341def test_regenerate_invalidates_the_old_token(tmp_path, monkeypatch):
342 data_dir = setup_env(tmp_path, monkeypatch)
343 make_invoice(data_dir)
344 old_token = token_for(data_dir)
345 assert portal_get(old_token).result.get("status", 200) == 200
346
347 new_result = regenerate("inv1", user_id="dan")
348 new_token = new_result.result["path"][len("/pay/"):]
349 assert new_token != old_token
350
351 assert portal_get(old_token).result["status"] == 404
352 assert portal_get(new_token).result.get("status", 200) == 200
353
354
355def test_regenerate_requires_owner_or_admin(tmp_path, monkeypatch):
356 data_dir = setup_env(tmp_path, monkeypatch)
357 make_invoice(data_dir, owner="dan")
358
359 stranger = regenerate("inv1", user_id="mallory")
360 assert stranger.result["status"] == 403
361
362 anonymous = regenerate("inv1", user_id=None)
363 assert anonymous.result["status"] == 403
364
365 owner = regenerate("inv1", user_id="dan")
366 assert owner.result["status"] == 200
367
368 admin = regenerate("inv1", user_id="ops", roles=["admin"])
369 assert admin.result["status"] == 200
370
371
372def test_regenerate_missing_or_unknown_invoice(tmp_path, monkeypatch):
373 setup_env(tmp_path, monkeypatch)
374 assert regenerate("", user_id="dan").result["status"] == 400
375 assert regenerate("does-not-exist", user_id="dan").result["status"] == 404
376
377
378# --- dunning email carries the door ----------------------------------------
379
380def test_dunning_email_contains_the_pay_link_when_base_url_configured(tmp_path, monkeypatch):
381 data_dir = setup_env(tmp_path, monkeypatch,
382 settings=(("portal.base_url", "https://pay.example.test"),))
383 make_invoice(data_dir) # due 2026-07-10, unpaid, no portal_token minted yet
384
385 run_aging("2026-07-11")
386 mails = outbox(data_dir)
387 assert len(mails) == 1
388 body = mails[0]["text_body"]
389 assert "https://pay.example.test/pay/" in body
390
391 # The link must actually resolve -- proves aging minted a real token,
392 # not a placeholder.
393 token = body.split("https://pay.example.test/pay/", 1)[1].split()[0].strip()
394 assert invoice(data_dir)["portal_token"] == token
395 assert portal_get(token).result.get("status", 200) == 200
396
397
398def test_dunning_email_omits_link_cleanly_when_base_url_unset(tmp_path, monkeypatch):
399 data_dir = setup_env(tmp_path, monkeypatch) # portal.base_url never set
400 make_invoice(data_dir)
401
402 run_aging("2026-07-11")
403 mails = outbox(data_dir)
404 assert len(mails) == 1
405 body = mails[0]["text_body"]
406 assert "/pay/" not in body
407 assert "http" not in body
408 # No link was ever built, so no token needed to be minted to build one.
409 assert invoice(data_dir)["portal_token"] in ("", None)
410
411
412# --- amounts in whole currency units ---------------------------------------
413
414def test_amounts_render_via_format_amount_in_whole_units_never_raw_cents(tmp_path, monkeypatch):
415 import object_money
416 data_dir = setup_env(tmp_path, monkeypatch)
417 make_invoice(data_dir, total="123456") # $1,234.56
418 token = token_for(data_dir)
419
420 body = portal_get(token).result["body"]
421 expected = object_money.format_amount("123456", "USD", base_dir=data_dir)
422 assert expected in body
423 assert "123456 cents" not in body
424 assert "123456" not in body.replace(expected, "") # raw minor units never leak elsewhere
425
426
427# --- security: token cannot surface for a non-owner ------------------------
428
429def _app_invoices_policy():
430 payload = json.loads((APP_INVOICES / "permissions" / "rules.json").read_text())
431 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
432
433
434def test_portal_token_never_reaches_a_non_owner_via_list_or_search():
435 """portal_token is not itself access-controlled field-by-field -- it
436 relies entirely on the invoices collection's existing row_filter
437 ({"owner_id": "$user_id"}), unmodified by this feature. Proving that
438 filter still denies READ to a non-owner is exactly proving the token
439 can never appear in a list/search response for anyone but the owner:
440 a row nobody may read is a row whose fields, portal_token included,
441 never leave the server for that caller."""
442 policy = _app_invoices_policy()
443 stranger = object_permissions.PermissionSubject(user_id="mallory")
444 record = {"owner_id": "dan", "number": "N-inv1", "customer_name": "Grace Hopper",
445 "status": "sent", "portal_token": "super-secret-capability-token"}
446
447 decision = object_permissions.check_permission(
448 stranger, object_permissions.READ, policy=policy, collection="invoices", record=record)
449 assert decision.allowed is False
450
451 owner = object_permissions.PermissionSubject(user_id="dan")
452 decision = object_permissions.check_permission(
453 owner, object_permissions.READ, policy=policy, collection="invoices", record=record)
454 assert decision.allowed is True
455
456
457def test_portal_token_excluded_from_generic_form_list_and_search_surfaces():
458 schema = json.loads((APP_INVOICES / "schemas" / "invoices.json").read_text())
459 assert "portal_token" not in schema["forms"]["default"]["fields"]
460 assert "portal_token" not in schema["views"]["list_fields"]
461 assert "portal_token" not in schema["search"]["fields"]
462 by_name = {f["name"]: f for f in schema["fields"]}
463 assert by_name["portal_token"]["read_only"] is True