Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

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, 49 minutes ago History
invoice_portal.py · 19.5 KB · 443 lines
1"""site_invoice_portal -- the door a dunning email currently has no way to
2point at (plan/customer-payment-portal-spec.md). GET /pay/{token}.
3
4The core posture: the customer is NOT a user of this system. Invoices
5carry customer_email, not an identity, so there is no account to sign
6into and no signup wall to put between a willing payer and their money.
7Access is instead a CAPABILITY URL -- an unguessable bearer token
8(secrets.token_urlsafe(32), minted by action_regenerate_portal_link or
9lazily by system_invoice_aging) that grants exactly "view this one
10invoice and see how to pay it." No session, no identity, no other record
11ever reachable from here.
12
13Looked up BY TOKEN ONLY -- never by id. Record ids are already UUIDv4
14(docs/runtime-contract.md) and appear in record_changes, in the
15owner-scoped /collections/invoices/records/{id} path, and in correlation
16ids threaded through logs -- surfaces an operator reasonably expects to
17stay internal, not something a stranger's browser history holds. Keeping
18portal_token a *separate* field (rather than treating the id itself as
19the secret) means there is no enumeration path from a guessed id to an
20invoice, and a leaked link is revoked (action_regenerate_portal_link)
21without touching the invoice's identity or its own audit trail.
22
23secrets.compare_digest is used for the match (constant-time: a plain `==`
24on attacker-controlled input leaks how many leading characters matched,
25via how long the comparison took, which is exactly the kind of side
26channel a bearer-token scheme exists to close). A blank or unknown token
27renders the SAME "not found" page, at 404, as an invoice that never
28existed -- never 403 -- because a 403 would confirm the token namespace
29itself is a thing worth attacking; "not found" makes a guess and a typo
30indistinguishable.
31
32No nav, no global search, no site chrome beyond the base stylesheet: this
33page is not "in" the app. A customer following an emailed link should
34never be one click from someone else's invoices or the sign-in wall of a
35system they have no account on.
36
37**THE DOCUMENT HALF NOW COMES FROM THE SHARED LAYER** (object_documents,
38one of the two pages migrated as proof in app-documents 0.1.0). The
39business header, the document identity, the bill-to party, the lines
40table, the totals and every print rule are the same code every other
41document on this server uses -- so an invoice and a quote cannot slowly
42stop looking like they came from the same business, and the print CSS
43gets the one rule seven hand-rolled `@media print` blocks all missed
44(`thead { display: table-header-group }`, which repeats the column
45headings when a long invoice runs onto a second page).
46
47What stays local is what is genuinely PORTAL rather than DOCUMENT: the
48status bucket the customer sees, the tiles, the payment instructions, and
49the pay button. Those are about paying, not about the invoice.
50
51**bill_to, not ship_to.** The layer decides that from the kind
52(KINDS["invoice"]["to_role"]), which is the same mechanism that keeps the
53packing slip's ship-to off an invoice and prices off a packing slip.
54
55Print -> Save as PDF is stated on the page, because it already works and
56costs nothing. A PDF *button* appears only if a PDF engine is actually
57configured -- the same rule as the Pay button below, and for the same
58reason.
59"""
60from __future__ import annotations
61
62import html
63import os
64import secrets
65from datetime import datetime, timezone
66
67import object_documents
68import object_money
69import object_stripe
70import object_records
71
72DATA_DIR_ENV = "DBBASIC_DATA_DIR"
73ACTOR = "site_invoice_portal"
74KIND = "invoice"
75
76# Buckets shown to the customer. The schema's real status enum is finer
77# (draft/sent/paid/partial/overdue/void) than the four states this spec
78# calls for -- draft/sent/overdue all read as "money is owed" from a
79# payer's point of view, so they share the "unpaid" rendering. void is the
80# one status that refuses the door outright regardless of what the token
81# validates against (see _render_void).
82STATUS_PAID = "paid"
83STATUS_PARTIAL = "partial"
84STATUS_VOID = "void"
85
86
87def _base_dir() -> str:
88 return os.environ.get(DATA_DIR_ENV, "data")
89
90
91def _esc(value) -> str:
92 return html.escape(str(value if value is not None else ""))
93
94
95def _esc_multiline(value) -> str:
96 return _esc(value).replace("\n", "<br>")
97
98
99def _settings(base) -> dict:
100 """Every app_settings row as one mapping.
101
102 Read whole rather than key by key: object_documents wants a mapping of
103 business.*, the collection is tiny, and one scan beats five. Duplicated,
104 on purpose, from every other package that reads app_settings -- there is
105 still no shared object_settings module in this codebase
106 (docs/logic-decisions.md #4).
107 """
108 values: dict[str, str] = {}
109 try:
110 # access: box configuration
111 for row in object_records.read_collection_records("app_settings", base_dir=base):
112 key = str(row.get("key") or "").strip()
113 value = str(row.get("value") or "").strip()
114 if key and value:
115 values[key] = value
116 except Exception:
117 pass
118 return values
119
120
121def _find_invoice_by_token(base, token: str) -> dict | None:
122 """The only lookup this page performs: a full scan matched with a
123 constant-time comparison, never a keyed/indexed lookup by id. A blank
124 token matches nothing -- without this guard, an invoice that has never
125 had a portal_token minted (stored as "") would otherwise "match" a
126 blank incoming token, which would turn "no link generated yet" into an
127 accidental open door.
128 """
129 token = str(token or "").strip()
130 if not token:
131 return None
132 try:
133 # access: capability link: the invoice is found by its secret portal_token, compared in constant time
134 rows = object_records.read_collection_records("invoices", base_dir=base)
135 except Exception:
136 return None
137 for row in rows:
138 candidate = str(row.get("portal_token") or "")
139 if not candidate:
140 continue
141 if secrets.compare_digest(candidate, token):
142 return row
143 return None
144
145
146def _invoice_lines_for(base, invoice_id: str) -> list[dict]:
147 """Line items, skipped gracefully when app-invoices' invoice_lines
148 collection/schema is not installed -- this page must render a usable
149 invoice even on a deployment that never adopted line-item detail.
150 """
151 try:
152 # access: capability link: the invoice is found by its secret portal_token, compared in constant time
153 rows = object_records.read_collection_records("invoice_lines", base_dir=base)
154 except Exception:
155 return []
156 return [r for r in rows if r.get("invoice_id") == invoice_id]
157
158
159def _stamp_view(base, invoice: dict) -> None:
160 """Best-effort view counter. Dunning intelligence downstream ("viewed
161 3x, still unpaid" is a different follow-up than "never opened") depends
162 on this, but no counter is worth breaking the page a customer is
163 actively trying to read -- any failure here is swallowed.
164
165 Called from POST (the page's beacon), never from GET: a mail scanner
166 or link prefetcher GETs every link on delivery, so a GET-side counter
167 said "viewed" for invoices nobody had opened, and each bump changed
168 the invoice's record rev under an owner's expected_rev edit
169 (bug-reports/2026-11-28-06-14-54).
170 """
171 try:
172 views = int(str(invoice.get("portal_views") or "0").strip() or "0")
173 except ValueError:
174 views = 0
175 now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
176 try:
177 # access: capability link: the invoice is found by its secret portal_token, compared in constant time
178 object_records.update_collection_record(
179 "invoices",
180 invoice["id"],
181 {"portal_views": str(views + 1), "last_viewed_at": now},
182 base_dir=base,
183 actor=ACTOR,
184 )
185 except Exception:
186 pass
187
188
189# What is left of this page's own CSS after the migration: the portal's
190# paying-a-bill furniture (tiles, status badges, the instructions panel) and
191# nothing else. Every rule about how a DOCUMENT looks, on screen or on paper,
192# now comes from object_documents.document_css, inlined by render_page.
193_STYLE = """
194.tiles { display: flex; gap: 0.75rem; flex-wrap: wrap; margin: 1.25rem 0; }
195.tile { background: var(--panel, #1a1a22); border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.6rem 1rem; min-width: 160px; }
196.tile .n { font-size: 1.3rem; font-weight: 700; }
197.tile .l { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }
198.badge { display: inline-block; padding: 0.15rem 0.6rem; border-radius: 999px; font-size: 0.8rem; font-weight: 600; }
199.badge.ok { background: rgba(82,210,115,0.15); color: var(--positive, #52d273); }
200.badge.warn { background: rgba(241,183,71,0.15); color: var(--warning, #f1b747); }
201.badge.bad { background: rgba(255,107,107,0.15); color: var(--danger, #ff6b6b); }
202.badge.muted { background: rgba(153,153,153,0.15); color: var(--muted, #999); }
203.instructions { border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.9rem 1.1rem; margin: 1rem 0; white-space: pre-wrap; }
204.notfound { text-align: center; padding: 3rem 1rem; }
205"""
206
207
208def _not_found() -> dict:
209 """Deliberately not rendered through the document layer: there is no
210 document. Bare, 404, and identical for a mistyped token and a token that
211 never existed."""
212 return {
213 "status": 404,
214 "content_type": "text/html; charset=utf-8",
215 "body": f"""<!doctype html>
216<html lang="en">
217<head>
218<meta charset="utf-8">
219<meta name="viewport" content="width=device-width, initial-scale=1">
220<meta name="referrer" content="no-referrer">
221<title>Not found</title>
222<link rel="stylesheet" href="/style">
223<style>{_STYLE}</style>
224</head>
225<body>
226<div class="notfound"><h1>Not found</h1>
227<p>This payment link is not valid. It may have been mistyped, or the invoice
228owner may have generated a newer link. Contact the business that sent it for a
229fresh one.</p></div>
230</body>
231</html>""",
232 }
233
234
235def _payment_instructions_html(settings) -> str:
236 text = str(settings.get("portal.payment_instructions") or "").strip()
237 if not text:
238 return (
239 '<div class="instructions hint">This business has not published '
240 "payment instructions yet. Contact them directly to arrange "
241 "payment.</div>"
242 )
243 return f'<div class="instructions">{_esc_multiline(text)}</div>'
244
245
246def _model_for(invoice, lines, settings, base, *, with_lines=True):
247 """The invoice as a document, folded by the shared layer.
248
249 require_business=False keeps the promise site_invoice_portal has always
250 made: an unbranded invoice is honest, a fake one is not. A customer is
251 never shown a nudge to configure somebody else's business (render_page
252 only draws that for an operator -- see setup_nudge).
253 """
254 currency = str(invoice.get("currency") or "USD").strip() or "USD"
255
256 def money(cents):
257 try:
258 return object_money.format_amount(cents or 0, currency, base_dir=base)
259 except Exception:
260 return f"{cents or 0} (minor units)"
261
262 due = str(invoice.get("due_date") or "").strip()
263 facts = object_documents.facts_from_records(
264 KIND, invoice, lines if with_lines else (), money=money,
265 extra={"to": {"name": str(invoice.get("customer_name") or ""),
266 "address": str(invoice.get("customer_address") or ""),
267 "email": str(invoice.get("customer_email") or "")},
268 "terms": f"Due {due}" if due else "Due on receipt"})
269 if not with_lines:
270 # A cancelled invoice shows no financial content at all -- no lines,
271 # no totals, no balance, and no due date either: a payment term on a
272 # bill that no longer exists is an instruction to pay it.
273 facts["totals"] = []
274 facts["terms"] = ""
275 return object_documents.build_model(KIND, facts, settings,
276 require_business=False)
277
278
279def _page(model, *, title, before="", after="", settings=None):
280 settings = settings or {}
281 pdf = object_documents.pdf_engine_status(
282 settings.get(object_documents.PDF_ENGINE_SETTING))
283 page = object_documents.render_page(
284 model, title=title, before=before, after=after,
285 # chrome=False is the posture this page has always had: handed to a
286 # stranger's inbox, so never one click from anything but this invoice.
287 chrome=False, pdf=pdf["available"],
288 size=settings.get(object_documents.PAGE_SIZE_SETTING),
289 # The view counter is the page POSTing back once a browser has it
290 # open (POST below), never a write during the GET.
291 beacon=True)
292 # The portal's own furniture rides in the same <head>, after the shared
293 # document CSS so a tile can override a document rule and never the other
294 # way round.
295 page["body"] = page["body"].replace("</head>", f"<style>{_STYLE}</style></head>", 1)
296 return page
297
298
299def _tiles(*pairs) -> str:
300 cells = "".join(f'<div class="tile"><div class="n">{value}</div>'
301 f'<div class="l">{label}</div></div>'
302 for label, value in pairs)
303 return f'<div class="tiles">{cells}</div>'
304
305
306def _render_void(invoice, settings, base) -> dict:
307 """Void refuses the portal outright: no balance, no line items, no
308 payment instructions -- showing any of that on a cancelled document
309 would invite paying a bill that no longer exists. The status check
310 happens here, in the page, rather than only via a token that gets
311 scrubbed on void (that hook lives outside this file's edit boundary),
312 so the customer-facing outcome holds regardless of whether the token
313 itself was ever cleared -- and it is a terminal status in the schema's
314 own transition table (no move ever leaves void), so this is permanent.
315 """
316 model = _model_for(invoice, (), settings, base, with_lines=False)
317 return _page(
318 model, settings=settings,
319 title=f"Invoice {invoice.get('number') or ''} -- cancelled",
320 after='<p><span class="badge muted">Cancelled</span></p>'
321 '<p class="doc-hint">This invoice was cancelled. If you believe '
322 "this is a mistake, contact the business that sent it.</p>")
323
324
325def _render_paid(invoice, currency, base, lines, settings) -> dict:
326 total = object_money.format_amount(invoice.get("total_cents") or 0, currency, base_dir=base)
327 paid = object_money.format_amount(invoice.get("amount_paid_cents") or 0, currency, base_dir=base)
328 paid_at = invoice.get("paid_at") or ""
329 model = _model_for(invoice, lines, settings, base)
330 before = (f'<p><span class="badge ok">Paid in full</span>'
331 + (f' <span class="doc-hint">on <time datetime="{_esc(paid_at)}">'
332 f'{_esc(paid_at)}</time></span>' if paid_at else "")
333 + "</p>"
334 + _tiles(("Total", total), ("Paid", paid)))
335 return _page(model, settings=settings, before=before,
336 after='<p class="doc-hint">This is your receipt. No further '
337 "payment is due on this invoice.</p>",
338 title=f"Invoice {invoice.get('number') or ''} -- paid")
339
340
341def _render_partial(invoice, currency, base, lines, settings) -> dict:
342 total = object_money.format_amount(invoice.get("total_cents") or 0, currency, base_dir=base)
343 paid = object_money.format_amount(invoice.get("amount_paid_cents") or 0, currency, base_dir=base)
344 balance = object_money.format_amount(invoice.get("balance_due_cents") or 0, currency, base_dir=base)
345 model = _model_for(invoice, lines, settings, base)
346 before = ('<p><span class="badge warn">Partially paid</span></p>'
347 + _tiles(("Total", total), ("Received so far", paid),
348 ("Still due", balance)))
349 return _page(model, settings=settings, before=before,
350 after="<h2>How to pay the remaining balance</h2>"
351 + _payment_instructions_html(settings),
352 title=f"Invoice {invoice.get('number') or ''} -- partially paid")
353
354
355_PAY_SCRIPT = """
356const btn = document.getElementById("paybtn");
357btn.addEventListener("click", async () => {
358 btn.disabled = true;
359 btn.textContent = "Starting secure checkout…";
360 const token = location.pathname.split("/").pop();
361 let data = {};
362 try {
363 const resp = await fetch("/objects/action_stripe_checkout", {
364 method: "POST",
365 headers: {"Content-Type": "application/json"},
366 body: JSON.stringify({token: token}),
367 });
368 data = await resp.json();
369 } catch (err) { data = {}; }
370 if (data && data.url) { location.href = data.url; return; }
371 // Never strand the payer: fall back to the instructions already on the
372 // page rather than leaving a dead button.
373 btn.disabled = false;
374 btn.textContent = "Pay by card";
375 document.getElementById("payerror").textContent =
376 (data && data.error) || "Card payment is unavailable right now -- the payment "
377 + "instructions below still work.";
378});
379"""
380
381
382def _pay_button_html() -> str:
383 """Rendered only when Stripe is configured -- see _render_unpaid.
384
385 The same rule the PDF button obeys, one layer up: a control exists
386 because the action behind it can actually succeed.
387 """
388 if not object_stripe.stripe_config_from_env().configured:
389 return ""
390 return ('<p class="noprint" style="margin:1rem 0"><button id="paybtn" class="btn primary">'
391 "Pay by card</button> "
392 '<span id="payerror" class="warn" style="margin-left:0.5rem"></span></p>'
393 f"<script>{_PAY_SCRIPT}</script>")
394
395
396def _render_unpaid(invoice, currency, base, lines, settings) -> dict:
397 total = object_money.format_amount(invoice.get("total_cents") or 0, currency, base_dir=base)
398 balance = object_money.format_amount(invoice.get("balance_due_cents") or 0, currency, base_dir=base)
399 model = _model_for(invoice, lines, settings, base)
400 before = ('<p><span class="badge bad">Payment due</span></p>'
401 + _tiles(("Amount due", balance), ("Invoice total", total)))
402 # The Pay button appears ONLY when card payment can actually succeed.
403 # A button that posts nowhere tells a customer trying to pay you that
404 # something is broken on YOUR end, so an unconfigured server shows the
405 # payment instructions alone rather than a lie with a shadow on it.
406 after = (_pay_button_html()
407 + "<h2>How to pay</h2>"
408 + _payment_instructions_html(settings))
409 return _page(model, settings=settings, before=before, after=after,
410 title=f"Invoice {invoice.get('number') or ''} -- payment due")
411
412
413def GET(request):
414 token = request.get("token")
415 base = _base_dir()
416 invoice = _find_invoice_by_token(base, token)
417 if invoice is None:
418 return _not_found()
419
420 settings = _settings(base)
421 currency = str(invoice.get("currency") or "USD").strip() or "USD"
422 status = str(invoice.get("status") or "")
423 lines = _invoice_lines_for(base, invoice["id"])
424
425 if status == STATUS_VOID:
426 return _render_void(invoice, settings, base)
427 if status == STATUS_PAID:
428 return _render_paid(invoice, currency, base, lines, settings)
429 if status == STATUS_PARTIAL:
430 return _render_partial(invoice, currency, base, lines, settings)
431 return _render_unpaid(invoice, currency, base, lines, settings)
432
433
434def POST(request):
435 """The page's view beacon (object_documents.VIEW_BEACON): count one
436 view and nothing else. Same token lookup and the same 404 as the GET."""
437 base = _base_dir()
438 invoice = _find_invoice_by_token(base, request.get("token"))
439 if invoice is None:
440 return _not_found()
441 _stamp_view(base, invoice)
442 return {"status": 200, "content_type": "application/json",
443 "body": '{"ok": true}'}