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
render_pdf.py · 8.8 KB · 220 lines
| 1 | """action_render_pdf -- a CAPABILITY, absent by default. POST {token} or |
| 2 | {source, kind}. |
| 3 | |
| 4 | **Browser print-to-PDF already produces a good PDF and costs nothing.** That is |
| 5 | the default answer, it is said out loud on every document page rendered by this |
| 6 | layer, and it is the reason this object is allowed to be absent: nobody is |
| 7 | blocked by it. |
| 8 | |
| 9 | Server-side PDF is a real dependency decision and does not belong in the core: |
| 10 | |
| 11 | WeasyPrint pango/cairo system libs -- heavy on a 1GB box |
| 12 | Chrome heavier still: a whole browser to render a page we already |
| 13 | rendered |
| 14 | wkhtmltopdf an unmaintained binary |
| 15 | ReportLab pure Python, but you rebuild the layout by hand, which is two |
| 16 | renderers again -- the exact failure this layer exists to end |
| 17 | |
| 18 | So this follows the pattern already used for OCR engines |
| 19 | (docs/capability-objects.md) and carrier labels (app-shipping's action_buy_label |
| 20 | and connectors/manual.py): the capability is named in a SETTING, |
| 21 | `documents.pdf_engine`, defaulting to `none`, and an unconfigured server gets a |
| 22 | 409 that NAMES WHAT TO INSTALL rather than a traceback, a silent nothing, or a |
| 23 | stub PDF with a watermark on it. |
| 24 | |
| 25 | **No surface offers a PDF button when it would 409.** object_documents. |
| 26 | pdf_engine_status is the single pure answer to "is there an engine?", every |
| 27 | document page consults it before drawing the button, and render_page(pdf=...) |
| 28 | is the only way a button gets drawn at all. A button that 409s tells the person |
| 29 | pressing it that something is broken on YOUR end -- the same reason |
| 30 | site_invoice_portal only draws "Pay by card" when Stripe is actually |
| 31 | configured. |
| 32 | |
| 33 | **There is deliberately no WeasyPrint or Chrome adapter in this file.** Nothing |
| 34 | in this repo can test one; an untested integration against a heavyweight |
| 35 | dependency is the worst kind of confident wrong answer; and the honest boundary |
| 36 | is more useful than a guess at the far side of it. What an engine must provide |
| 37 | when one is installed is exactly this: take `html` -- the SAME HTML the print |
| 38 | view renders, from object_documents.render_page, never a second template -- and |
| 39 | return PDF bytes. That is the whole contract, and it is why this object still |
| 40 | builds the HTML and returns it in the refusal: the boundary is demonstrably the |
| 41 | same document, not a promise that it would be. |
| 42 | """ |
| 43 | |
| 44 | import hmac |
| 45 | import os |
| 46 | |
| 47 | import object_documents |
| 48 | import object_money |
| 49 | import object_records |
| 50 | |
| 51 | ACTOR = "action_render_pdf" |
| 52 | COLLECTION = "sent_documents" |
| 53 | |
| 54 | |
| 55 | def _base_dir(): |
| 56 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 57 | |
| 58 | |
| 59 | def _text(value): |
| 60 | return str(value if value is not None else "").strip() |
| 61 | |
| 62 | |
| 63 | def _settings(base): |
| 64 | values = {} |
| 65 | try: |
| 66 | for row in object_records.read_collection_records("app_settings", |
| 67 | base_dir=base): |
| 68 | key, value = _text(row.get("key")), _text(row.get("value")) |
| 69 | if key and value: |
| 70 | values[key] = value |
| 71 | except Exception: |
| 72 | pass |
| 73 | return values |
| 74 | |
| 75 | |
| 76 | def _document_by_token(base, token): |
| 77 | token = _text(token) |
| 78 | if not token: |
| 79 | return None |
| 80 | try: |
| 81 | rows = object_records.read_collection_records(COLLECTION, base_dir=base) |
| 82 | except Exception: |
| 83 | return None |
| 84 | for row in rows: |
| 85 | candidate = _text(row.get("token")) |
| 86 | if candidate and hmac.compare_digest(candidate, token): |
| 87 | return row |
| 88 | return None |
| 89 | |
| 90 | |
| 91 | def _model_from_source(base, kind, source, settings): |
| 92 | """Render a document straight from its source record -- the operator path, |
| 93 | for a document that has not been sent to anybody yet.""" |
| 94 | try: |
| 95 | spec = object_documents.source_spec(kind) |
| 96 | except object_documents.UnknownKindError as exc: |
| 97 | return None, {"status": 400, "error": str(exc)} |
| 98 | if spec is None: |
| 99 | return None, {"status": 409, |
| 100 | "error": f"'{kind}' documents have no source mapping yet."} |
| 101 | if source.count("/") != 1: |
| 102 | return None, {"status": 400, |
| 103 | "error": "source must look like 'collection/{id}'"} |
| 104 | collection, _, record_id = source.partition("/") |
| 105 | collection, record_id = _text(collection), _text(record_id) |
| 106 | if collection != spec["collection"]: |
| 107 | return None, {"status": 400, |
| 108 | "error": (f"a '{kind}' is rendered from " |
| 109 | f"{spec['collection']}, not {collection}")} |
| 110 | try: |
| 111 | record = object_records.get_collection_record(collection, record_id, |
| 112 | base_dir=base) |
| 113 | except Exception: |
| 114 | record = None |
| 115 | if not record: |
| 116 | return None, {"status": 404, "error": f"No such record: {source}"} |
| 117 | |
| 118 | lines = [] |
| 119 | if spec.get("lines_collection"): |
| 120 | try: |
| 121 | rows = object_records.read_collection_records( |
| 122 | spec["lines_collection"], base_dir=base) |
| 123 | lines = [row for row in rows |
| 124 | if _text(row.get(spec["lines_fk"])) == record_id] |
| 125 | lines.sort(key=lambda row: _text(row.get("description"))) |
| 126 | except Exception: |
| 127 | lines = [] |
| 128 | |
| 129 | currency = _text(record.get("currency")) or "USD" |
| 130 | |
| 131 | def money(cents): |
| 132 | try: |
| 133 | return object_money.format_amount(cents or 0, currency, base_dir=base) |
| 134 | except Exception: |
| 135 | return f"{cents or 0} (minor units)" |
| 136 | |
| 137 | facts = object_documents.facts_from_records(kind, record, lines, money=money) |
| 138 | try: |
| 139 | model = object_documents.build_model(kind, facts, settings, |
| 140 | require_business=False) |
| 141 | except object_documents.DocumentError as exc: |
| 142 | return None, {"status": 400, "error": str(exc)} |
| 143 | return model, None |
| 144 | |
| 145 | |
| 146 | def POST(request): |
| 147 | identity = request.get("_identity") or {} |
| 148 | if not _text(identity.get("user_id")): |
| 149 | return {"status": 403, "error": "Sign in to render a PDF."} |
| 150 | |
| 151 | base = _base_dir() |
| 152 | settings = _settings(base) |
| 153 | engine = object_documents.pdf_engine_status( |
| 154 | settings.get(object_documents.PDF_ENGINE_SETTING)) |
| 155 | |
| 156 | token = _text(request.get("token")) |
| 157 | source = _text(request.get("source")) |
| 158 | kind = _text(request.get("kind")) |
| 159 | if not token and not source: |
| 160 | return {"status": 400, |
| 161 | "error": "pass either {token} for a sent document, or " |
| 162 | "{kind, source} for one that has not been sent"} |
| 163 | |
| 164 | if token: |
| 165 | row = _document_by_token(base, token) |
| 166 | if row is None: |
| 167 | return {"status": 404, "error": "No such document."} |
| 168 | try: |
| 169 | model = object_documents.model_from_snapshot(row.get("snapshot")) |
| 170 | except object_documents.DocumentError as exc: |
| 171 | return {"status": 409, "error": str(exc)} |
| 172 | # A sent document's PDF is a PDF of what was SENT -- the snapshot, the |
| 173 | # same thing the link shows. A PDF built from the live record would be |
| 174 | # a second version of a document somebody already has. |
| 175 | else: |
| 176 | model, refusal = _model_from_source(base, kind, source, settings) |
| 177 | if refusal is not None: |
| 178 | return refusal |
| 179 | |
| 180 | page = object_documents.render_page( |
| 181 | model, chrome=False, |
| 182 | size=settings.get(object_documents.PAGE_SIZE_SETTING)) |
| 183 | html_body = page["body"] |
| 184 | |
| 185 | if not engine["available"]: |
| 186 | # The honest absent state. It names the setting, it names what to |
| 187 | # install and what each option costs, and it names the thing that |
| 188 | # already works -- so an operator gets a decision rather than an error. |
| 189 | return { |
| 190 | "status": 409, |
| 191 | "error": engine["reason"], |
| 192 | "setting": object_documents.PDF_ENGINE_SETTING, |
| 193 | "engine": engine["engine"], |
| 194 | "install": engine["install"], |
| 195 | "alternative": ("Print this document and choose Save as PDF. It " |
| 196 | "needs no dependency and produces the same page."), |
| 197 | # The boundary, demonstrated rather than described: this is the |
| 198 | # exact HTML an engine would be handed, byte for byte the page the |
| 199 | # print view serves. |
| 200 | "html": html_body, |
| 201 | } |
| 202 | |
| 203 | # Unreachable today: pdf_engine_status never returns available=True, |
| 204 | # because no engine module ships with this server. The line is here so the |
| 205 | # contract is unambiguous for whoever installs one -- take `html_body`, |
| 206 | # return bytes, and never render a second template. |
| 207 | return {"status": 501, |
| 208 | "error": (f"'{engine['engine']}' reports as available but no " |
| 209 | "adapter is wired up in this build."), |
| 210 | "html": html_body} |
| 211 | |
| 212 | |
| 213 | def GET(request): |
| 214 | """The capability, asked about rather than invoked -- so a surface can |
| 215 | check before it draws a button, without side effects.""" |
| 216 | settings = _settings(_base_dir()) |
| 217 | status = object_documents.pdf_engine_status( |
| 218 | settings.get(object_documents.PDF_ENGINE_SETTING)) |
| 219 | return {"status": "ok", "pdf": status, |
| 220 | "alternative": "Print -> Save as PDF works today and costs nothing."} |