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