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
object_documents.py · 39.3 KB · 998 lines
| 1 | """The document layer: ONE renderer for every business document. |
| 2 | |
| 3 | Seven printable pages already shipped before this module existed -- packing |
| 4 | slip, pick list, manifest, kitchen ticket, kitchen queue, receiving sheet, |
| 5 | return form -- plus the invoice portal and the order tracking page. Each one |
| 6 | invented its own header, its own `@media print` block, and its own answer to |
| 7 | "does this show money?". None of them shares a line with any other, and the |
| 8 | seven blocks between them contain zero occurrences of the one print rule that |
| 9 | actually matters: |
| 10 | |
| 11 | thead { display: table-header-group; } |
| 12 | |
| 13 | Without it a three-page pick list comes out of the printer with column headings |
| 14 | on page one and two anonymous columns of numbers on pages two and three. Nobody |
| 15 | notices in review, because nobody reviews on paper. That single rule is most of |
| 16 | the argument for a shared layer. |
| 17 | |
| 18 | WHAT IS HERE AND WHY IT IS PURE |
| 19 | ------------------------------- |
| 20 | This module is a FOLD: facts in, render model out, HTML out, hash out. No file |
| 21 | reads, no settings lookups, no clock, no currency formatting (that needs a data |
| 22 | dir -- see object_money). Every decision a document makes lives here; every |
| 23 | piece of I/O a document needs lives in the calling object. That split is what |
| 24 | lets app-invoices and app-shipping share one renderer at all: package objects |
| 25 | cannot import each other, and the ONLY code two packages can both reach is a |
| 26 | root ``object_*`` module. So the renderer had to be here or be copied. |
| 27 | |
| 28 | THE MONEY RULE IS A PARAMETER, NOT AN ARGUMENT |
| 29 | ---------------------------------------------- |
| 30 | ``KINDS[kind]["show_money"]`` decides, once, for every document of that kind, |
| 31 | and there is deliberately no per-call override. The packing slip's no-prices |
| 32 | rule (see site_packing_slip: pricelessness by construction is what makes every |
| 33 | parcel gift-safe without a flag somebody has to remember to tick) is now a |
| 34 | table entry rather than a paragraph re-argued in each new printable. A caller |
| 35 | that could pass ``show_money=True`` to a packing slip would be a caller that |
| 36 | can staple the amount paid to a birthday present, so that argument is not |
| 37 | offered. |
| 38 | |
| 39 | When ``show_money`` is false the money is not hidden -- it is NEVER PUT IN THE |
| 40 | MODEL. Line unit prices, line amounts, totals and the currency are dropped by |
| 41 | ``build_model`` itself, so a snapshot of a packing slip contains no prices |
| 42 | either, and no future renderer, template, PDF engine or debug dump can leak |
| 43 | what was never carried. |
| 44 | |
| 45 | THE ADDRESS RULE IS ALSO A PARAMETER |
| 46 | ------------------------------------ |
| 47 | A packing slip's ship-to is not an invoice's bill-to. ``KINDS[kind]["to_role"]`` |
| 48 | names which one the document's "to" party is, and the renderer labels it from |
| 49 | that -- so a document cannot accidentally print the accounts department's |
| 50 | address on the box. |
| 51 | |
| 52 | PRINT CSS: WHERE IT LIVES, AND WHY NOT IN /style |
| 53 | ------------------------------------------------ |
| 54 | ``site_style`` (app-theme, served at ``/style``) is the SCREEN design system: |
| 55 | semantic tokens, chrome, and a theme an operator can swap live. Paper geometry |
| 56 | is a different thing wearing the same word "CSS": |
| 57 | |
| 58 | * it is not themeable -- installing the `terminal` theme must not change the |
| 59 | margins of an invoice somebody is about to post; |
| 60 | * it depends on a setting app-theme has no business knowing |
| 61 | (``documents.page_size``: A4 or Letter is a fact about the operator's |
| 62 | printer tray, not about their brand); |
| 63 | * it must survive leaving the server. A document saved to disk, attached to |
| 64 | a mail, or handed to a PDF engine still has to print correctly, and a page |
| 65 | whose print rules live behind ``<link href="/style">`` prints wrong the |
| 66 | moment it is read anywhere but this origin. |
| 67 | |
| 68 | So the print CSS is defined ONCE, here, in ``document_css()``, and INLINED by |
| 69 | ``render_page`` into every document page after the ``/style`` link. That keeps |
| 70 | the design-system property that matters (nothing downstream owns a copy -- |
| 71 | change this function and every document on the box changes) while keeping the |
| 72 | property ``/style`` cannot give (the page is self-contained on paper). Pages |
| 73 | still link ``/style`` for tokens and chrome; the two do not overlap. |
| 74 | |
| 75 | |
| 76 | --- |
| 77 | Browser Print -> Save as PDF already produces a good PDF and costs nothing, so |
| 78 | every page rendered here SAYS SO (``_print_hint_html``) rather than leaving it |
| 79 | to be discovered. Server-side PDF is a capability with an honest absent state |
| 80 | (docs/capability-objects.md) -- ``pdf_engine_status`` is the pure half of that |
| 81 | decision, and ``render_page(pdf=...)`` is why no surface offers a button that |
| 82 | would 409: the button is not drawn unless an engine is actually there. |
| 83 | """ |
| 84 | |
| 85 | from __future__ import annotations |
| 86 | |
| 87 | import hashlib |
| 88 | import html |
| 89 | import json |
| 90 | from typing import Any, Callable, Iterable, Mapping, Sequence |
| 91 | |
| 92 | __all__ = [ |
| 93 | "DocumentError", |
| 94 | "NamelessBusinessError", |
| 95 | "UnknownKindError", |
| 96 | "KINDS", |
| 97 | "PAGE_SIZES", |
| 98 | "DEFAULT_PAGE_SIZE", |
| 99 | "PDF_ENGINE_SETTING", |
| 100 | "PAGE_SIZE_SETTING", |
| 101 | "kind_spec", |
| 102 | "source_spec", |
| 103 | "shows_money", |
| 104 | "business_header", |
| 105 | "build_model", |
| 106 | "facts_from_records", |
| 107 | "content_hash", |
| 108 | "snapshot_json", |
| 109 | "model_from_snapshot", |
| 110 | "document_css", |
| 111 | "render_html", |
| 112 | "render_page", |
| 113 | "pdf_engine_status", |
| 114 | ] |
| 115 | |
| 116 | |
| 117 | class DocumentError(ValueError): |
| 118 | """A document that could not honestly be built.""" |
| 119 | |
| 120 | |
| 121 | class NamelessBusinessError(DocumentError): |
| 122 | """No ``business.name`` configured. |
| 123 | |
| 124 | A document is a statement by a business. One with no name on it cannot be |
| 125 | paid (there is nobody to pay), cannot be queried (there is nobody to ring) |
| 126 | and cannot be filed. Fabricating a default -- "My Company", the server's |
| 127 | hostname, the owner's user id -- would be worse than refusing, because it |
| 128 | would be a plausible-looking lie printed on paperwork somebody keeps. |
| 129 | |
| 130 | Raised by ``business_header`` and, by default, ``build_model``. Callers |
| 131 | that must render for an operator standing at a printer pass |
| 132 | ``require_business=False`` and get an unbranded (but honest) document; the |
| 133 | refusal belongs at SEND time, where nobody is waiting and the cost of |
| 134 | stopping is one settings row. |
| 135 | """ |
| 136 | |
| 137 | |
| 138 | class UnknownKindError(DocumentError): |
| 139 | """A document kind this layer has never heard of.""" |
| 140 | |
| 141 | |
| 142 | # --- the kind registry ------------------------------------------------------- |
| 143 | # |
| 144 | # Everything a document kind decides differently from every other kind, in one |
| 145 | # table. Adding a printable is adding a row here; it is not adding a file with |
| 146 | # its own opinions about money and addresses. |
| 147 | # |
| 148 | # label what the document calls itself at the top of the page |
| 149 | # show_money the no-prices rule as a parameter (see the module docstring) |
| 150 | # to_role which address the counterparty block carries |
| 151 | # from_label / to_label the two headings over the parties block |
| 152 | # sendable whether `source` can resolve facts for it today. A kind with |
| 153 | # no `source` is printable but not yet sendable, which is an |
| 154 | # honest state rather than a missing feature: the five |
| 155 | # unmigrated printables are declared here so that migrating |
| 156 | # them later is a data edit rather than a fresh argument. |
| 157 | |
| 158 | _TO_LABELS = { |
| 159 | "bill_to": "Bill to", |
| 160 | "ship_to": "Ship to", |
| 161 | "deliver_to": "Deliver to", |
| 162 | "supplier": "Supplier", |
| 163 | "customer": "Customer", |
| 164 | } |
| 165 | |
| 166 | KINDS: dict[str, dict[str, Any]] = { |
| 167 | # --- sendable: a source record resolves into facts --------------------- |
| 168 | "invoice": { |
| 169 | "label": "Invoice", |
| 170 | "show_money": True, |
| 171 | "to_role": "bill_to", |
| 172 | "from_label": "From", |
| 173 | "source": {"collection": "invoices", |
| 174 | "lines_collection": "invoice_lines", |
| 175 | "lines_fk": "invoice_id"}, |
| 176 | }, |
| 177 | "quote": { |
| 178 | "label": "Quote", |
| 179 | "show_money": True, |
| 180 | "to_role": "bill_to", |
| 181 | "from_label": "From", |
| 182 | # A quote is an ORDER with doc_type=quote (plan/documents-print-pdf-spec |
| 183 | # .md): same row, same history, before anybody committed. It resolves |
| 184 | # against `orders` for exactly that reason -- a quote with its own |
| 185 | # collection would be a quote nobody can find after the sale. |
| 186 | "source": {"collection": "orders", |
| 187 | "lines_collection": "order_lines", |
| 188 | "lines_fk": "order_id"}, |
| 189 | }, |
| 190 | "order": { |
| 191 | "label": "Order confirmation", |
| 192 | "show_money": True, |
| 193 | "to_role": "bill_to", |
| 194 | "from_label": "From", |
| 195 | "source": {"collection": "orders", |
| 196 | "lines_collection": "order_lines", |
| 197 | "lines_fk": "order_id"}, |
| 198 | }, |
| 199 | "purchase_order": { |
| 200 | "label": "Purchase order", |
| 201 | "show_money": True, |
| 202 | "to_role": "supplier", |
| 203 | "from_label": "Ordered by", |
| 204 | "source": {"collection": "orders", |
| 205 | "lines_collection": "order_lines", |
| 206 | "lines_fk": "order_id"}, |
| 207 | }, |
| 208 | "packing_slip": { |
| 209 | "label": "Packing slip", |
| 210 | # NO PRICES. Not "hidden behind a gift flag", not "unless the buyer |
| 211 | # ticked something": none, ever. See site_packing_slip's docstring -- |
| 212 | # the money conversation already happened with somebody who may not be |
| 213 | # the person holding the box. |
| 214 | "show_money": False, |
| 215 | "to_role": "ship_to", |
| 216 | "from_label": "From", |
| 217 | "source": {"collection": "shipments", |
| 218 | "lines_collection": "shipment_lines", |
| 219 | "lines_fk": "shipment_id"}, |
| 220 | }, |
| 221 | |
| 222 | # --- printable, not yet sendable --------------------------------------- |
| 223 | "pick_list": { |
| 224 | "label": "Pick list", "show_money": False, "to_role": "ship_to", |
| 225 | "from_label": "From", |
| 226 | }, |
| 227 | "manifest": { |
| 228 | "label": "Carrier manifest", "show_money": False, "to_role": "ship_to", |
| 229 | "from_label": "From", |
| 230 | }, |
| 231 | "receiving_sheet": { |
| 232 | "label": "Receiving sheet", "show_money": False, "to_role": "supplier", |
| 233 | "from_label": "Received by", |
| 234 | }, |
| 235 | "return_form": { |
| 236 | "label": "Return form", "show_money": False, "to_role": "customer", |
| 237 | "from_label": "Return to", |
| 238 | }, |
| 239 | "kitchen_ticket": { |
| 240 | "label": "Kitchen ticket", "show_money": False, "to_role": "customer", |
| 241 | "from_label": "From", |
| 242 | }, |
| 243 | "statement": { |
| 244 | "label": "Statement", "show_money": True, "to_role": "bill_to", |
| 245 | "from_label": "From", |
| 246 | }, |
| 247 | } |
| 248 | |
| 249 | PAGE_SIZE_SETTING = "documents.page_size" |
| 250 | PDF_ENGINE_SETTING = "documents.pdf_engine" |
| 251 | |
| 252 | # `size` values CSS actually understands. An operator who types something else |
| 253 | # gets A4 rather than a stylesheet with a syntax error in it, because a broken |
| 254 | # @page rule fails silently and prints at whatever the browser felt like. |
| 255 | PAGE_SIZES = {"a4": "A4", "letter": "Letter", "legal": "Legal", |
| 256 | "a5": "A5"} |
| 257 | DEFAULT_PAGE_SIZE = "A4" |
| 258 | |
| 259 | # The engines a server-side PDF could plausibly use, and what installing each |
| 260 | # one actually costs. Named in the refusal so an operator gets a decision |
| 261 | # rather than an error (see docs/capability-objects.md, and app-shipping's |
| 262 | # carrier connector for the same absent-by-default posture). |
| 263 | PDF_ENGINES = { |
| 264 | "weasyprint": "pip install weasyprint, plus the pango/cairo system " |
| 265 | "libraries (heavy on a 1GB box)", |
| 266 | "chrome": "a headless Chrome/Chromium binary on PATH (heavier still: a " |
| 267 | "whole browser to render a page this server already rendered)", |
| 268 | "wkhtmltopdf": "the wkhtmltopdf binary (unmaintained upstream)", |
| 269 | } |
| 270 | |
| 271 | |
| 272 | def kind_spec(kind: str) -> dict[str, Any]: |
| 273 | """The one row of the registry that decides everything about `kind`.""" |
| 274 | spec = KINDS.get(str(kind or "").strip()) |
| 275 | if spec is None: |
| 276 | raise UnknownKindError( |
| 277 | f"Unknown document kind {kind!r}. Known kinds: " |
| 278 | + ", ".join(sorted(KINDS))) |
| 279 | return spec |
| 280 | |
| 281 | |
| 282 | def source_spec(kind: str) -> dict[str, str] | None: |
| 283 | """Which collection a kind's facts come from, or None when the kind is |
| 284 | printable but not yet sendable. Data, so the sending action and the public |
| 285 | document page read the same collections without either owning the |
| 286 | knowledge.""" |
| 287 | spec = kind_spec(kind).get("source") |
| 288 | return dict(spec) if spec else None |
| 289 | |
| 290 | |
| 291 | def shows_money(kind: str) -> bool: |
| 292 | """The no-prices rule, asked as a question instead of re-argued.""" |
| 293 | return bool(kind_spec(kind)["show_money"]) |
| 294 | |
| 295 | |
| 296 | # --- the header -------------------------------------------------------------- |
| 297 | |
| 298 | _BUSINESS_FIELDS = ( |
| 299 | ("name", "business.name"), |
| 300 | ("address", "business.address"), |
| 301 | ("email", "business.email"), |
| 302 | ("phone", "business.phone"), |
| 303 | ("website", "business.website"), |
| 304 | ("tax_id", "business.tax_id"), |
| 305 | ) |
| 306 | |
| 307 | |
| 308 | def business_header(settings: Mapping[str, Any]) -> dict[str, str]: |
| 309 | """The business's own identity, from ``business.*``. |
| 310 | |
| 311 | Refuses a nameless business: see NamelessBusinessError. Every other field |
| 312 | is optional and simply absent when unset -- an operator who has not typed |
| 313 | a VAT number has a document without one, not a document with a blank |
| 314 | labelled row. |
| 315 | """ |
| 316 | values = {key: _text(settings.get(setting_key)) |
| 317 | for key, setting_key in _BUSINESS_FIELDS} |
| 318 | if not values["name"]: |
| 319 | raise NamelessBusinessError( |
| 320 | "business.name is not set: a document with no business on it " |
| 321 | "cannot be paid, queried or filed. Set business.name in Settings.") |
| 322 | return {key: value for key, value in values.items() if value} |
| 323 | |
| 324 | |
| 325 | # --- the fold ---------------------------------------------------------------- |
| 326 | |
| 327 | def build_model( |
| 328 | kind: str, |
| 329 | facts: Mapping[str, Any], |
| 330 | settings: Mapping[str, Any], |
| 331 | *, |
| 332 | require_business: bool = True, |
| 333 | ) -> dict[str, Any]: |
| 334 | """Fold one document's facts into the render model every surface uses. |
| 335 | |
| 336 | `facts` is a plain dict of already-resolved, already-formatted values -- |
| 337 | money arrives as strings a human can read ("$24.00"), never as minor units, |
| 338 | because formatting currency needs a data dir and this module does no I/O. |
| 339 | ``facts_from_records`` builds one from a stored record for the sendable |
| 340 | kinds; a hand-written page can build one itself. |
| 341 | |
| 342 | Recognised keys: number, date, state, reference, currency, to, from, |
| 343 | lines, totals, terms, notes, footer. |
| 344 | |
| 345 | The model is JSON-safe by construction: it is what gets hashed |
| 346 | (``content_hash``) and snapshotted (``snapshot_json``) when a document is |
| 347 | sent, and a snapshot that cannot round-trip through JSON is not evidence |
| 348 | of anything. |
| 349 | """ |
| 350 | spec = kind_spec(kind) |
| 351 | money = bool(spec["show_money"]) |
| 352 | |
| 353 | try: |
| 354 | business = business_header(settings) |
| 355 | except NamelessBusinessError: |
| 356 | if require_business: |
| 357 | raise |
| 358 | # An operator standing at a printer gets their paperwork. The document |
| 359 | # is honest about being unbranded rather than inventing a name, and |
| 360 | # the page shows a no-print nudge (see render_page) so the missing |
| 361 | # setting is visible to the one person who can fix it. |
| 362 | business = {} |
| 363 | |
| 364 | model: dict[str, Any] = { |
| 365 | "kind": str(kind).strip(), |
| 366 | "kind_label": spec["label"], |
| 367 | "show_money": money, |
| 368 | "business": business, |
| 369 | "number": _text(facts.get("number")), |
| 370 | "date": _text(facts.get("date")), |
| 371 | "state": _text(facts.get("state")), |
| 372 | "reference": _text(facts.get("reference")), |
| 373 | "parties": _parties(spec, facts, business), |
| 374 | "lines": _lines(facts.get("lines") or (), money), |
| 375 | "totals": _totals(facts.get("totals") or (), money), |
| 376 | "terms": _text(facts.get("terms")), |
| 377 | "notes": _notes(facts.get("notes") or ()), |
| 378 | "footer": _text(facts.get("footer")), |
| 379 | } |
| 380 | if money: |
| 381 | currency = _text(facts.get("currency")) |
| 382 | if currency: |
| 383 | model["currency"] = currency |
| 384 | return model |
| 385 | |
| 386 | |
| 387 | def _parties(spec, facts, business) -> list[dict[str, str]]: |
| 388 | """From/to, with the address the KIND says this document carries. |
| 389 | |
| 390 | The "from" party defaults to the business header rather than being typed |
| 391 | again: a document whose letterhead and whose "from" block can disagree is |
| 392 | a document that will eventually disagree. |
| 393 | """ |
| 394 | parties = [] |
| 395 | origin = facts.get("from") |
| 396 | if origin: |
| 397 | parties.append(_party("from", spec.get("from_label", "From"), origin)) |
| 398 | elif business: |
| 399 | parties.append(_party("from", spec.get("from_label", "From"), { |
| 400 | "name": business.get("name", ""), |
| 401 | "address": business.get("address", ""), |
| 402 | "email": business.get("email", ""), |
| 403 | })) |
| 404 | recipient = facts.get("to") |
| 405 | if recipient: |
| 406 | role = spec["to_role"] |
| 407 | parties.append(_party(role, _TO_LABELS.get(role, "To"), recipient)) |
| 408 | return parties |
| 409 | |
| 410 | |
| 411 | def _party(role: str, label: str, values: Mapping[str, Any]) -> dict[str, str]: |
| 412 | party = {"role": role, "label": label} |
| 413 | for key in ("name", "address", "email", "phone"): |
| 414 | value = _text(values.get(key)) |
| 415 | if value: |
| 416 | party[key] = value |
| 417 | return party |
| 418 | |
| 419 | |
| 420 | # Line keys that carry money. Dropped -- not blanked, not hidden -- on a |
| 421 | # document whose kind says no prices. |
| 422 | _MONEY_LINE_KEYS = ("unit_price", "amount", "tax", "discount") |
| 423 | _PLAIN_LINE_KEYS = ("description", "sku", "quantity", "unit", "note") |
| 424 | |
| 425 | |
| 426 | def _lines(raw: Iterable[Mapping[str, Any]], money: bool) -> list[dict[str, str]]: |
| 427 | lines = [] |
| 428 | for entry in raw: |
| 429 | line = {} |
| 430 | for key in _PLAIN_LINE_KEYS: |
| 431 | value = _text(entry.get(key)) |
| 432 | if value: |
| 433 | line[key] = value |
| 434 | if money: |
| 435 | for key in _MONEY_LINE_KEYS: |
| 436 | value = _text(entry.get(key)) |
| 437 | if value: |
| 438 | line[key] = value |
| 439 | if line: |
| 440 | lines.append(line) |
| 441 | return lines |
| 442 | |
| 443 | |
| 444 | def _totals(raw: Iterable[Mapping[str, Any]], money: bool) -> list[dict[str, Any]]: |
| 445 | """Empty on a no-prices document, always. A totals block is money by |
| 446 | definition; there is no such thing as a priceless total.""" |
| 447 | if not money: |
| 448 | return [] |
| 449 | totals = [] |
| 450 | for entry in raw: |
| 451 | label = _text(entry.get("label")) |
| 452 | value = _text(entry.get("value")) |
| 453 | if not label and not value: |
| 454 | continue |
| 455 | total = {"label": label, "value": value} |
| 456 | if entry.get("emphasis"): |
| 457 | total["emphasis"] = True |
| 458 | totals.append(total) |
| 459 | return totals |
| 460 | |
| 461 | |
| 462 | def _notes(raw: Iterable[Mapping[str, Any]]) -> list[dict[str, str]]: |
| 463 | notes = [] |
| 464 | for entry in raw: |
| 465 | body = _text(entry.get("body")) |
| 466 | if not body: |
| 467 | continue |
| 468 | notes.append({"title": _text(entry.get("title")), "body": body}) |
| 469 | return notes |
| 470 | |
| 471 | |
| 472 | def _text(value: Any) -> str: |
| 473 | return str(value if value is not None else "").strip() |
| 474 | |
| 475 | |
| 476 | # --- records -> facts (still pure: the caller does the reading) -------------- |
| 477 | |
| 478 | # How each sendable kind's source record spells the things every document |
| 479 | # needs. Tried in order; the first field present on the record wins, so one |
| 480 | # mapping serves collections that named the same fact differently. |
| 481 | _FIELD_ALIASES = { |
| 482 | "number": ("number", "reference", "id"), |
| 483 | "date": ("issue_date", "order_date", "shipped_on", "created_at"), |
| 484 | "state": ("status",), |
| 485 | "currency": ("currency",), |
| 486 | "to_name": ("ship_to_name", "customer_name", "supplier_name", "contact_name"), |
| 487 | "to_address": ("ship_to_address", "customer_address", "billing_address", |
| 488 | "address"), |
| 489 | "to_email": ("customer_email", "supplier_email", "email"), |
| 490 | } |
| 491 | |
| 492 | # Per-kind overrides where the generic order would pick the wrong fact. A |
| 493 | # packing slip must prefer ship_to_*; an invoice must prefer the billing |
| 494 | # address even on a record that also carries a shipping one. |
| 495 | _KIND_ALIASES = { |
| 496 | "packing_slip": {"to_name": ("ship_to_name", "customer_name"), |
| 497 | "to_address": ("ship_to_address",), |
| 498 | "date": ("shipped_on", "created_at")}, |
| 499 | "invoice": {"to_name": ("customer_name",), |
| 500 | "to_address": ("customer_address", "billing_address", "address"), |
| 501 | "date": ("issue_date", "created_at")}, |
| 502 | } |
| 503 | |
| 504 | |
| 505 | def facts_from_records( |
| 506 | kind: str, |
| 507 | record: Mapping[str, Any], |
| 508 | lines: Sequence[Mapping[str, Any]] = (), |
| 509 | *, |
| 510 | money: Callable[[Any], str] | None = None, |
| 511 | extra: Mapping[str, Any] | None = None, |
| 512 | ) -> dict[str, Any]: |
| 513 | """Map a stored record + its line rows onto the facts ``build_model`` wants. |
| 514 | |
| 515 | Pure: the caller reads the rows and passes a `money` callable (cents -> |
| 516 | display string, usually a closure over object_money.format_amount and a |
| 517 | base_dir). On a no-prices kind `money` is never called at all, so a |
| 518 | packing slip cannot be made to format a price by accident. |
| 519 | |
| 520 | `extra` overlays anything the caller knows that the record does not -- |
| 521 | a gift message read off a joined order, a state the page derived, the |
| 522 | reference of the shipment a slip belongs to. |
| 523 | """ |
| 524 | spec = kind_spec(kind) |
| 525 | show_money = bool(spec["show_money"]) |
| 526 | aliases = dict(_FIELD_ALIASES) |
| 527 | aliases.update(_KIND_ALIASES.get(kind, {})) |
| 528 | |
| 529 | def pick(name: str) -> str: |
| 530 | for field in aliases.get(name, ()): # first present wins |
| 531 | value = _text(record.get(field)) |
| 532 | if value: |
| 533 | return value |
| 534 | return "" |
| 535 | |
| 536 | facts: dict[str, Any] = { |
| 537 | "number": pick("number"), |
| 538 | "date": pick("date")[:10], |
| 539 | "state": pick("state"), |
| 540 | "currency": pick("currency") if show_money else "", |
| 541 | "to": {"name": pick("to_name"), "address": pick("to_address"), |
| 542 | "email": pick("to_email")}, |
| 543 | "lines": [_line_from_record(row, show_money, money) for row in lines], |
| 544 | } |
| 545 | if show_money: |
| 546 | facts["totals"] = _totals_from_record(record, money) |
| 547 | for key, value in (extra or {}).items(): |
| 548 | facts[key] = value |
| 549 | return facts |
| 550 | |
| 551 | |
| 552 | def _line_from_record(row, show_money, money): |
| 553 | line = { |
| 554 | "description": (_text(row.get("description")) |
| 555 | or _text(row.get("name")) |
| 556 | or _text(row.get("product_id"))), |
| 557 | "sku": _text(row.get("sku")), |
| 558 | "quantity": _text(row.get("quantity")) or "1", |
| 559 | } |
| 560 | if show_money and money is not None: |
| 561 | if _text(row.get("unit_price_cents")): |
| 562 | line["unit_price"] = money(row.get("unit_price_cents")) |
| 563 | if _text(row.get("line_total_cents")): |
| 564 | line["amount"] = money(row.get("line_total_cents")) |
| 565 | return line |
| 566 | |
| 567 | |
| 568 | _TOTAL_FIELDS = ( |
| 569 | ("subtotal_cents", "Subtotal", False), |
| 570 | ("tax_cents", "Tax", False), |
| 571 | ("shipping_cents", "Shipping", False), |
| 572 | ("total_cents", "Total", True), |
| 573 | ("amount_paid_cents", "Paid", False), |
| 574 | ("balance_due_cents", "Balance due", True), |
| 575 | ) |
| 576 | |
| 577 | |
| 578 | def _totals_from_record(record, money): |
| 579 | if money is None: |
| 580 | return [] |
| 581 | totals = [] |
| 582 | for field, label, emphasis in _TOTAL_FIELDS: |
| 583 | if not _text(record.get(field)): |
| 584 | continue |
| 585 | entry = {"label": label, "value": money(record.get(field))} |
| 586 | if emphasis: |
| 587 | entry["emphasis"] = True |
| 588 | totals.append(entry) |
| 589 | return totals |
| 590 | |
| 591 | |
| 592 | # --- the snapshot rule's arithmetic ------------------------------------------ |
| 593 | |
| 594 | def content_hash(model: Mapping[str, Any]) -> str: |
| 595 | """A stable fingerprint of what a document SAYS. |
| 596 | |
| 597 | Canonical JSON (sorted keys, no incidental whitespace) so two renders of |
| 598 | the same facts hash the same on any machine, in any Python, in any order |
| 599 | the dict happened to be built. Stored on the sent document beside the |
| 600 | snapshot: the snapshot is the evidence and this is the seal on it. |
| 601 | """ |
| 602 | payload = json.dumps(model, sort_keys=True, separators=(",", ":"), |
| 603 | ensure_ascii=False, default=str) |
| 604 | return hashlib.sha256(payload.encode("utf-8")).hexdigest() |
| 605 | |
| 606 | |
| 607 | def snapshot_json(model: Mapping[str, Any]) -> str: |
| 608 | """The model as one storable line. Compact and escaped, so it is safe in a |
| 609 | TSV cell (json.dumps escapes tabs and newlines by construction).""" |
| 610 | return json.dumps(model, sort_keys=True, separators=(",", ":"), |
| 611 | ensure_ascii=False, default=str) |
| 612 | |
| 613 | |
| 614 | def model_from_snapshot(text: str) -> dict[str, Any]: |
| 615 | """Read a stored snapshot back, or raise DocumentError. |
| 616 | |
| 617 | Refuses rather than repairs: a document page that silently rendered a |
| 618 | half-parsed snapshot would be showing something nobody ever sent, which is |
| 619 | the exact failure this whole mechanism exists to prevent. |
| 620 | """ |
| 621 | try: |
| 622 | model = json.loads(text or "") |
| 623 | except (TypeError, ValueError) as exc: |
| 624 | raise DocumentError(f"Unreadable document snapshot: {exc}") from exc |
| 625 | if not isinstance(model, dict): |
| 626 | raise DocumentError("Document snapshot is not an object") |
| 627 | return model |
| 628 | |
| 629 | |
| 630 | # --- PDF: the capability boundary -------------------------------------------- |
| 631 | |
| 632 | def pdf_engine_status(setting_value: Any) -> dict[str, Any]: |
| 633 | """What ``documents.pdf_engine`` means today, as a plain answer. |
| 634 | |
| 635 | Absent by default and absent in practice: no PDF engine module ships with |
| 636 | this server, exactly as no carrier adapter ships with app-shipping. The |
| 637 | honest states are |
| 638 | |
| 639 | available=False, engine="none" nothing configured -- Print -> Save |
| 640 | as PDF is the answer, and it works |
| 641 | available=False, engine="weasyprint" a name with nothing behind it on |
| 642 | this box |
| 643 | |
| 644 | and the second one is reported rather than swallowed, because an operator |
| 645 | who pasted an engine name in and heard nothing would reasonably conclude |
| 646 | PDFs were being generated. |
| 647 | |
| 648 | ``available`` is what every surface consults before drawing a PDF button. |
| 649 | A button that 409s tells the person pressing it that something is broken |
| 650 | on your end, which is the same reason site_invoice_portal only draws "Pay |
| 651 | by card" when Stripe is actually configured. |
| 652 | """ |
| 653 | engine = _text(setting_value).lower() or "none" |
| 654 | if engine in ("none", "off", "disabled"): |
| 655 | return { |
| 656 | "available": False, "engine": "none", |
| 657 | "reason": (f"No PDF engine is configured ({PDF_ENGINE_SETTING} is " |
| 658 | "'none'). Print this page and choose Save as PDF -- " |
| 659 | "that already produces a good PDF and costs nothing."), |
| 660 | "install": dict(PDF_ENGINES), |
| 661 | } |
| 662 | if engine in PDF_ENGINES: |
| 663 | return { |
| 664 | "available": False, "engine": engine, |
| 665 | "reason": (f"{PDF_ENGINE_SETTING} names '{engine}', but no PDF " |
| 666 | "engine module is installed on this server. Install " |
| 667 | f"it: {PDF_ENGINES[engine]}."), |
| 668 | "install": {engine: PDF_ENGINES[engine]}, |
| 669 | } |
| 670 | return { |
| 671 | "available": False, "engine": engine, |
| 672 | "reason": (f"{PDF_ENGINE_SETTING} names '{engine}', which is not a " |
| 673 | "PDF engine this server knows. Set it to one of " |
| 674 | + ", ".join(sorted(PDF_ENGINES)) |
| 675 | + ", or to 'none' and use Print -> Save as PDF."), |
| 676 | "install": dict(PDF_ENGINES), |
| 677 | } |
| 678 | |
| 679 | |
| 680 | # --- print CSS, defined once -------------------------------------------------- |
| 681 | |
| 682 | def page_size(setting_value: Any) -> str: |
| 683 | """The `@page size` value, from ``documents.page_size``. Unknown values |
| 684 | fall back to A4 rather than emitting CSS the browser will discard.""" |
| 685 | return PAGE_SIZES.get(_text(setting_value).lower(), DEFAULT_PAGE_SIZE) |
| 686 | |
| 687 | |
| 688 | def document_css(size: Any = DEFAULT_PAGE_SIZE) -> str: |
| 689 | """Every print rule this server has, in one string. |
| 690 | |
| 691 | The rule that justifies the module: ``thead { display: table-header-group }`` |
| 692 | tells the printer to repeat the heading row at the top of every page a |
| 693 | table spills onto. Seven hand-rolled print blocks shipped without it, and |
| 694 | a three-page pick list printed its column headings once. |
| 695 | """ |
| 696 | size = page_size(size) |
| 697 | return """ |
| 698 | .doc { max-width: 46rem; margin: 0 auto; padding: 2rem 1.25rem; } |
| 699 | .doc-head { display: flex; justify-content: space-between; gap: 1.5rem; |
| 700 | flex-wrap: wrap; align-items: flex-start; margin-bottom: 1.5rem; } |
| 701 | .doc-business { font-size: 0.9rem; line-height: 1.45; } |
| 702 | .doc-business .name { font-size: 1.05rem; font-weight: 700; display: block; } |
| 703 | .doc-identity { text-align: right; } |
| 704 | .doc-identity h1 { margin: 0 0 0.2rem; font-size: 1.5rem; } |
| 705 | .doc-identity .meta { color: var(--muted, #999); font-size: 0.9rem; |
| 706 | line-height: 1.5; } |
| 707 | .doc-state { display: inline-block; padding: 0.1rem 0.55rem; border-radius: 999px; |
| 708 | border: 1px solid var(--line, #444); font-size: 0.75rem; text-transform: uppercase; |
| 709 | letter-spacing: 0.05em; } |
| 710 | .doc-parties { display: flex; gap: 1rem; flex-wrap: wrap; margin: 0 0 1.25rem; } |
| 711 | .doc-party { border: 1px solid var(--line, #333); border-radius: 8px; |
| 712 | padding: 0.7rem 0.95rem; min-width: 15rem; flex: 1 1 15rem; line-height: 1.45; } |
| 713 | .doc-party .role { font-size: 0.7rem; text-transform: uppercase; |
| 714 | letter-spacing: 0.05em; color: var(--muted, #999); display: block; |
| 715 | margin-bottom: 0.2rem; } |
| 716 | table.doc-lines { width: 100%; border-collapse: collapse; margin: 0 0 1.25rem; } |
| 717 | table.doc-lines th, table.doc-lines td { text-align: left; padding: 0.4rem 0.6rem; |
| 718 | border-bottom: 1px solid var(--line, #38384a); vertical-align: top; } |
| 719 | table.doc-lines th { font-size: 0.75rem; text-transform: uppercase; |
| 720 | letter-spacing: 0.05em; color: var(--muted, #999); } |
| 721 | table.doc-lines td.num, table.doc-lines th.num { text-align: right; |
| 722 | white-space: nowrap; } |
| 723 | .doc-totals { width: auto; margin: 0 0 1.25rem auto; border-collapse: collapse; } |
| 724 | .doc-totals td { padding: 0.25rem 0.6rem; text-align: right; } |
| 725 | .doc-totals tr.emphasis td { font-weight: 700; border-top: 1px solid var(--line, #444); } |
| 726 | .doc-note { border: 1px solid var(--line, #333); border-radius: 8px; |
| 727 | padding: 0.7rem 0.95rem; margin: 0 0 1rem; white-space: pre-wrap; } |
| 728 | .doc-terms { color: var(--muted, #999); font-size: 0.9rem; margin: 0 0 1rem; |
| 729 | white-space: pre-wrap; } |
| 730 | .doc-footer { color: var(--muted, #999); font-size: 0.85rem; |
| 731 | border-top: 1px solid var(--line, #333); padding-top: 0.75rem; margin-top: 1.5rem; } |
| 732 | .doc-banner { border: 1px solid var(--warning, #f1b747); border-radius: 8px; |
| 733 | padding: 0.7rem 0.95rem; margin: 0 0 1.25rem; line-height: 1.5; } |
| 734 | .doc-banner strong { display: block; } |
| 735 | .doc-hint { color: var(--muted, #999); font-size: 0.85rem; margin: 1rem 0 0; } |
| 736 | .doc-setup { border: 1px dashed var(--warning, #f1b747); border-radius: 8px; |
| 737 | padding: 0.6rem 0.9rem; margin: 0 0 1.25rem; font-size: 0.9rem; } |
| 738 | |
| 739 | @page { size: __SIZE__; margin: 14mm; } |
| 740 | |
| 741 | @media print { |
| 742 | /* Chrome is not part of the document. */ |
| 743 | nav, header.app, .noprint, .btn, button, form { display: none !important; } |
| 744 | html, body { background: #fff !important; color: #000 !important; } |
| 745 | .doc { max-width: none; padding: 0; } |
| 746 | a { color: #000; text-decoration: none; } |
| 747 | |
| 748 | /* THE RULE. A table that spills onto page two repeats its heading row |
| 749 | there. Every hand-rolled print stylesheet in this repo forgot it, and |
| 750 | nobody notices until a three-page pick list prints headerless. */ |
| 751 | thead { display: table-header-group; } |
| 752 | tfoot { display: table-footer-group; } |
| 753 | tr, img { page-break-inside: avoid; break-inside: avoid; } |
| 754 | |
| 755 | /* Keep blocks whole across a break, and never orphan a heading. */ |
| 756 | .doc-party, .doc-note, .doc-totals, .doc-banner { |
| 757 | page-break-inside: avoid; break-inside: avoid; } |
| 758 | h1, h2, h3 { page-break-after: avoid; break-after: avoid; } |
| 759 | p { orphans: 3; widows: 3; } |
| 760 | |
| 761 | /* Borders that survive a printer with no colour and no background |
| 762 | graphics -- the default in every browser's print dialog. */ |
| 763 | .doc-party, .doc-note, .doc-banner, table.doc-lines th, |
| 764 | table.doc-lines td, .doc-totals tr.emphasis td, .doc-footer, |
| 765 | .doc-state { border-color: #999 !important; } |
| 766 | .doc-identity .meta, .doc-party .role, .doc-terms, .doc-footer, |
| 767 | table.doc-lines th { color: #333 !important; } |
| 768 | } |
| 769 | """.replace("__SIZE__", size) |
| 770 | |
| 771 | |
| 772 | # --- rendering ---------------------------------------------------------------- |
| 773 | |
| 774 | def _esc(value: Any) -> str: |
| 775 | return html.escape(_text(value)) |
| 776 | |
| 777 | |
| 778 | def _esc_multiline(value: Any) -> str: |
| 779 | return _esc(value).replace("\n", "<br>") |
| 780 | |
| 781 | |
| 782 | def _business_html(model) -> str: |
| 783 | business = model.get("business") or {} |
| 784 | if not business: |
| 785 | return '<div class="doc-business"></div>' |
| 786 | parts = [f'<span class="name">{_esc(business["name"])}</span>'] |
| 787 | if business.get("address"): |
| 788 | parts.append(f'<div>{_esc_multiline(business["address"])}</div>') |
| 789 | contact = " · ".join( |
| 790 | _esc(business[key]) for key in ("email", "phone", "website") |
| 791 | if business.get(key)) |
| 792 | if contact: |
| 793 | parts.append(f"<div>{contact}</div>") |
| 794 | if business.get("tax_id"): |
| 795 | parts.append(f'<div>{_esc(business["tax_id"])}</div>') |
| 796 | return f'<div class="doc-business">{"".join(parts)}</div>' |
| 797 | |
| 798 | |
| 799 | def _identity_html(model) -> str: |
| 800 | meta = [] |
| 801 | if model.get("number"): |
| 802 | meta.append(f'No. {_esc(model["number"])}') |
| 803 | if model.get("date"): |
| 804 | meta.append(_esc(model["date"])) |
| 805 | if model.get("reference"): |
| 806 | meta.append(_esc(model["reference"])) |
| 807 | state = (f'<div><span class="doc-state">{_esc(model["state"])}</span></div>' |
| 808 | if model.get("state") else "") |
| 809 | return (f'<div class="doc-identity"><h1>{_esc(model.get("kind_label"))}</h1>' |
| 810 | f'<div class="meta">{" · ".join(meta)}</div>{state}</div>') |
| 811 | |
| 812 | |
| 813 | def _parties_html(model) -> str: |
| 814 | parties = model.get("parties") or [] |
| 815 | if not parties: |
| 816 | return "" |
| 817 | blocks = [] |
| 818 | for party in parties: |
| 819 | rows = [f'<span class="role">{_esc(party.get("label"))}</span>'] |
| 820 | if party.get("name"): |
| 821 | rows.append(f'<strong>{_esc(party["name"])}</strong>') |
| 822 | for key in ("address", "email", "phone"): |
| 823 | if party.get(key): |
| 824 | rows.append(f'<div>{_esc_multiline(party[key])}</div>') |
| 825 | blocks.append(f'<div class="doc-party">{"".join(rows)}</div>') |
| 826 | return f'<div class="doc-parties">{"".join(blocks)}</div>' |
| 827 | |
| 828 | |
| 829 | def _lines_html(model) -> str: |
| 830 | lines = model.get("lines") or [] |
| 831 | if not lines: |
| 832 | # Nothing at all, not an empty table and not a stock apology. What a |
| 833 | # document with no lines should SAY depends entirely on which document |
| 834 | # it is ("nothing has been picked into this shipment" is useful; "no |
| 835 | # lines" on a cancelled invoice is noise), so the page says it. |
| 836 | return "" |
| 837 | money = bool(model.get("show_money")) |
| 838 | has_sku = any(line.get("sku") for line in lines) |
| 839 | |
| 840 | head = ["<th>Item</th>"] |
| 841 | if has_sku: |
| 842 | head.append("<th>Code</th>") |
| 843 | head.append('<th class="num">Qty</th>') |
| 844 | if money: |
| 845 | head.append('<th class="num">Unit price</th>') |
| 846 | head.append('<th class="num">Amount</th>') |
| 847 | |
| 848 | rows = [] |
| 849 | for line in lines: |
| 850 | cells = [f'<td>{_esc(line.get("description"))}' |
| 851 | + (f'<div class="doc-hint">{_esc(line["note"])}</div>' |
| 852 | if line.get("note") else "") |
| 853 | + "</td>"] |
| 854 | if has_sku: |
| 855 | cells.append(f'<td>{_esc(line.get("sku"))}</td>') |
| 856 | quantity = _esc(line.get("quantity")) |
| 857 | unit = _esc(line.get("unit")) |
| 858 | cells.append(f'<td class="num">{quantity}{(" " + unit) if unit else ""}</td>') |
| 859 | if money: |
| 860 | cells.append(f'<td class="num">{_esc(line.get("unit_price"))}</td>') |
| 861 | cells.append(f'<td class="num">{_esc(line.get("amount"))}</td>') |
| 862 | rows.append(f"<tr>{''.join(cells)}</tr>") |
| 863 | |
| 864 | # <thead> is not decoration here: document_css's table-header-group rule |
| 865 | # has nothing to repeat without it. |
| 866 | return (f'<table class="doc-lines"><thead><tr>{"".join(head)}</tr></thead>' |
| 867 | f'<tbody>{"".join(rows)}</tbody></table>') |
| 868 | |
| 869 | |
| 870 | def _totals_html(model) -> str: |
| 871 | totals = model.get("totals") or [] |
| 872 | if not totals: |
| 873 | return "" |
| 874 | rows = "".join( |
| 875 | f'<tr class="emphasis"><td>{_esc(t.get("label"))}</td>' |
| 876 | f'<td>{_esc(t.get("value"))}</td></tr>' if t.get("emphasis") else |
| 877 | f'<tr><td>{_esc(t.get("label"))}</td><td>{_esc(t.get("value"))}</td></tr>' |
| 878 | for t in totals) |
| 879 | return f'<table class="doc-totals"><tbody>{rows}</tbody></table>' |
| 880 | |
| 881 | |
| 882 | def _notes_html(model) -> str: |
| 883 | blocks = [] |
| 884 | for note in model.get("notes") or []: |
| 885 | title = (f'<strong>{_esc(note["title"])}</strong><br>' |
| 886 | if note.get("title") else "") |
| 887 | blocks.append(f'<div class="doc-note">{title}' |
| 888 | f'{_esc_multiline(note.get("body"))}</div>') |
| 889 | return "".join(blocks) |
| 890 | |
| 891 | |
| 892 | def render_html(model: Mapping[str, Any]) -> str: |
| 893 | """The document itself: header, identity, parties, lines, totals, terms, |
| 894 | notes, footer. One template, used by the print view, by anything that |
| 895 | emails a document, and by a PDF engine if one is ever installed -- so a |
| 896 | PDF cannot say something the link does not.""" |
| 897 | parts = [ |
| 898 | '<div class="doc-head">', |
| 899 | _business_html(model), |
| 900 | _identity_html(model), |
| 901 | "</div>", |
| 902 | _parties_html(model), |
| 903 | _lines_html(model), |
| 904 | _totals_html(model), |
| 905 | _notes_html(model), |
| 906 | ] |
| 907 | if model.get("terms"): |
| 908 | parts.append(f'<div class="doc-terms">{_esc_multiline(model["terms"])}</div>') |
| 909 | if model.get("footer"): |
| 910 | parts.append(f'<div class="doc-footer">{_esc_multiline(model["footer"])}</div>') |
| 911 | return "".join(part for part in parts if part) |
| 912 | |
| 913 | |
| 914 | def _print_hint_html(pdf: bool) -> str: |
| 915 | """Print -> Save as PDF already works, so say so. |
| 916 | |
| 917 | It costs nothing, it needs no dependency, and leaving it to be discovered |
| 918 | is how somebody ends up asking for a PDF feature they already have. |
| 919 | """ |
| 920 | hint = ('<p class="doc-hint noprint">Print this page (Ctrl/Cmd+P) and ' |
| 921 | 'choose <strong>Save as PDF</strong> to get a PDF file — no ' |
| 922 | 'setup needed.</p>') |
| 923 | if not pdf: |
| 924 | return hint |
| 925 | return hint + ('<p class="noprint"><button class="btn" id="docpdf">' |
| 926 | "Download PDF</button></p>") |
| 927 | |
| 928 | |
| 929 | _SETUP_NUDGE = ( |
| 930 | '<div class="doc-setup noprint">This document has no business identity on ' |
| 931 | "it. Set <strong>business.name</strong> (and address) in Settings so your " |
| 932 | "paperwork says who sent it.</div>") |
| 933 | |
| 934 | |
| 935 | def render_page( |
| 936 | model: Mapping[str, Any], |
| 937 | *, |
| 938 | title: str = "", |
| 939 | banner: str = "", |
| 940 | before: str = "", |
| 941 | after: str = "", |
| 942 | chrome: bool = True, |
| 943 | pdf: bool = False, |
| 944 | setup_nudge: bool | None = None, |
| 945 | size: Any = DEFAULT_PAGE_SIZE, |
| 946 | status: int = 200, |
| 947 | ) -> dict[str, Any]: |
| 948 | """One whole HTML page around one document, as an object response. |
| 949 | |
| 950 | `chrome=False` drops the ``/nav`` script -- the posture site_invoice_portal |
| 951 | established for a page handed to a stranger's inbox: never one click from |
| 952 | somebody else's records or from a sign-in wall for a system they have no |
| 953 | account on. |
| 954 | |
| 955 | `pdf` draws the download button, and it must only ever be true when |
| 956 | ``pdf_engine_status(...)["available"]`` is. A button that 409s is a lie |
| 957 | with a shadow on it. |
| 958 | |
| 959 | `setup_nudge` defaults to "whenever an OPERATOR is looking at an unbranded |
| 960 | document" -- which is what ``chrome`` means. A customer who followed an |
| 961 | emailed link must never be told to go and configure the business that sent |
| 962 | it: they cannot, and it would read as the sender's software talking over |
| 963 | the sender. |
| 964 | """ |
| 965 | document_title = title or " ".join( |
| 966 | part for part in (model.get("kind_label"), model.get("number")) if part) |
| 967 | if setup_nudge is None: |
| 968 | setup_nudge = chrome and not (model.get("business") or {}) |
| 969 | nudge = _SETUP_NUDGE if setup_nudge else "" |
| 970 | body = "".join([ |
| 971 | banner, nudge, before, |
| 972 | render_html(model), |
| 973 | after, |
| 974 | _print_hint_html(pdf), |
| 975 | ]) |
| 976 | page = { |
| 977 | "content_type": "text/html; charset=utf-8", |
| 978 | "body": f"""<!doctype html> |
| 979 | <html lang="en"> |
| 980 | <head> |
| 981 | <meta charset="utf-8"> |
| 982 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 983 | {'<meta name="referrer" content="no-referrer">' if not chrome else ''} |
| 984 | <title>{_esc(document_title)}</title> |
| 985 | <link rel="stylesheet" href="/style"> |
| 986 | <style>{document_css(size)}</style> |
| 987 | </head> |
| 988 | <body> |
| 989 | <div class="doc"> |
| 990 | {body} |
| 991 | </div> |
| 992 | {'<script src="/nav"></script>' if chrome else ''} |
| 993 | </body> |
| 994 | </html>""", |
| 995 | } |
| 996 | if status != 200: |
| 997 | page["status"] = status |
| 998 | return page |