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
send_document.py · 13.0 KB · 325 lines
| 1 | """action_send_document -- render a document, freeze what it said, mint the |
| 2 | link, and QUEUE the mail. POST {kind, source, to}. |
| 3 | |
| 4 | Four facts get created here and they are deliberately in this order: |
| 5 | |
| 6 | 1. the render model (object_documents, pure) |
| 7 | 2. the sent_documents row (the snapshot + the token: the evidence) |
| 8 | 3. the outbox row (the message) |
| 9 | 4. the link, returned to caller (so a human can paste it anywhere) |
| 10 | |
| 11 | The row before the message, always. If the mail write fails after the row |
| 12 | exists, the operator has a working link they can send by hand; if the message |
| 13 | went first and the row write failed, the customer would have a link to nothing. |
| 14 | One of those is recoverable and the other is a support ticket. |
| 15 | |
| 16 | **It queues; it never sends.** enqueue() is a plain local write of one `queued` |
| 17 | row and the daemon owns delivery, retries and backoff -- the same posture |
| 18 | system_order_email argues at length. Nothing here opens a socket, so a slow |
| 19 | SMTP server cannot add its timeout to the click that sent a quote. |
| 20 | |
| 21 | **Idempotent per (source, recipient), the way system_order_email is.** Two |
| 22 | levels, because there are two facts: |
| 23 | |
| 24 | * the DOCUMENT is keyed on (source, sent_to) in sent_documents. Sending the |
| 25 | same quote to the same person twice is one document, one snapshot, one |
| 26 | token, one opened_at -- not two links racing to be the one they clicked. |
| 27 | Sending it to their accounts department as well is genuinely a second |
| 28 | delivery, so the recipient is in the key. |
| 29 | * the MESSAGE is keyed on a marker in the outbox row's source_object_id: |
| 30 | |
| 31 | action_send_document:{source}:{recipient} |
| 32 | |
| 33 | scanned before composing, exactly as system_order_email does, and for the |
| 34 | identical reason: the outbox row IS the message, so the claim "this message |
| 35 | exists" belongs on it rather than on a stamped flag somewhere else that can |
| 36 | disagree with it. |
| 37 | |
| 38 | Split that way, a retry after a half-finished send finishes the job instead of |
| 39 | duplicating it: the row is found and reused, the marker is missing, so the mail |
| 40 | is composed once. |
| 41 | |
| 42 | **A nameless business is refused here, and only here (409).** object_documents |
| 43 | raises NamelessBusinessError when `business.name` is unset. The printable pages |
| 44 | swallow it -- an operator standing at a printer gets their paperwork, unbranded |
| 45 | but honest -- because refusing there costs somebody a parcel. Refusing HERE |
| 46 | costs one settings row and nobody is waiting, and an anonymous document in a |
| 47 | stranger's inbox cannot be paid, queried or filed. |
| 48 | |
| 49 | **portal.base_url is also a 409, not a degrade.** system_order_email sends its |
| 50 | mail without links when no origin is configured, and that is right for a |
| 51 | confirmation whose body is worth reading on its own. This message's entire |
| 52 | payload IS the link. Sending it without one would be posting an empty envelope, |
| 53 | so the refusal names the setting instead. |
| 54 | |
| 55 | What is deliberately NOT here: attaching a PDF. Print -> Save as PDF already |
| 56 | produces a good PDF and costs nothing, and server-side PDF is a capability with |
| 57 | an honest absent state (action_render_pdf). A send that silently produced no |
| 58 | attachment because no engine was installed would be the worst of both. |
| 59 | """ |
| 60 | |
| 61 | import os |
| 62 | import secrets |
| 63 | from datetime import datetime, timezone |
| 64 | |
| 65 | import object_documents |
| 66 | import object_email |
| 67 | import object_money |
| 68 | import object_records |
| 69 | |
| 70 | ACTOR = "action_send_document" |
| 71 | COLLECTION = "sent_documents" |
| 72 | |
| 73 | |
| 74 | def _base_dir(): |
| 75 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 76 | |
| 77 | |
| 78 | def _text(value): |
| 79 | return str(value if value is not None else "").strip() |
| 80 | |
| 81 | |
| 82 | def _now(): |
| 83 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 84 | |
| 85 | |
| 86 | def _settings(base): |
| 87 | """Every app_settings row as one dict. |
| 88 | |
| 89 | Read whole rather than key by key: object_documents wants a mapping, the |
| 90 | collection is tiny, and one scan beats six. Duplicated on purpose like |
| 91 | every other package that reads app_settings (docs/logic-decisions.md #4). |
| 92 | """ |
| 93 | values = {} |
| 94 | try: |
| 95 | for row in object_records.read_collection_records("app_settings", |
| 96 | base_dir=base): |
| 97 | key, value = _text(row.get("key")), _text(row.get("value")) |
| 98 | if key and value: |
| 99 | values[key] = value |
| 100 | except Exception: |
| 101 | pass |
| 102 | return values |
| 103 | |
| 104 | |
| 105 | def _split_source(source): |
| 106 | """'orders/9f3...' -> ('orders', '9f3...'), or (None, None).""" |
| 107 | source = _text(source) |
| 108 | if source.count("/") != 1: |
| 109 | return None, None |
| 110 | collection, _, record_id = source.partition("/") |
| 111 | collection, record_id = _text(collection), _text(record_id) |
| 112 | if not collection or not record_id: |
| 113 | return None, None |
| 114 | return collection, record_id |
| 115 | |
| 116 | |
| 117 | def _lines_for(base, spec, record_id): |
| 118 | """The document's line rows, or none at all. |
| 119 | |
| 120 | Wrapped whole: the lines collection belongs to another package, and a |
| 121 | server that never installed line-item detail must still be able to send a |
| 122 | document -- one without lines, honestly, rather than a traceback. |
| 123 | """ |
| 124 | collection = spec.get("lines_collection") |
| 125 | if not collection: |
| 126 | return [] |
| 127 | try: |
| 128 | rows = object_records.read_collection_records(collection, base_dir=base) |
| 129 | except Exception: |
| 130 | return [] |
| 131 | key = spec.get("lines_fk") |
| 132 | lines = [row for row in rows if _text(row.get(key)) == record_id] |
| 133 | lines.sort(key=lambda row: _text(row.get("description"))) |
| 134 | return lines |
| 135 | |
| 136 | |
| 137 | def _existing_document(base, source, to): |
| 138 | """The document already sent for this (source, recipient), or None.""" |
| 139 | try: |
| 140 | rows = object_records.read_collection_records(COLLECTION, base_dir=base) |
| 141 | except Exception: |
| 142 | return None |
| 143 | for row in rows: |
| 144 | if _text(row.get("source")) == source and _text(row.get("sent_to")) == to: |
| 145 | return row |
| 146 | return None |
| 147 | |
| 148 | |
| 149 | def _marker(source, to): |
| 150 | return f"{ACTOR}:{source}:{to}" |
| 151 | |
| 152 | |
| 153 | def _already_queued(base, marker): |
| 154 | """Whether this exact message is already in the outbox, or None when the |
| 155 | outbox cannot be read at all. |
| 156 | |
| 157 | None is a REFUSAL, not a False -- system_order_email's argument holds |
| 158 | here word for word: a message skipped now can be composed by a retry, and |
| 159 | a message sent twice is already in somebody's inbox. |
| 160 | """ |
| 161 | try: |
| 162 | rows = object_records.read_collection_records( |
| 163 | object_email.OUTBOX_COLLECTION, base_dir=base) |
| 164 | except Exception: |
| 165 | return None |
| 166 | return any(_text(row.get("source_object_id")) == marker for row in rows) |
| 167 | |
| 168 | |
| 169 | def _email_body(model, link, settings): |
| 170 | name = "" |
| 171 | for party in model.get("parties") or []: |
| 172 | if party.get("role") != "from": |
| 173 | name = _text(party.get("name")) |
| 174 | label = _text(model.get("kind_label")) or "document" |
| 175 | number = _text(model.get("number")) |
| 176 | business = _text((model.get("business") or {}).get("name")) |
| 177 | lines = [f"Hello {name or 'there'},", "", |
| 178 | f"Your {label.lower()}{(' ' + number) if number else ''} " |
| 179 | f"from {business} is ready to read:", "", link, ""] |
| 180 | terms = _text(model.get("terms")) |
| 181 | if terms: |
| 182 | lines += [terms, ""] |
| 183 | lines += ["This link shows the document exactly as it was sent to you. " |
| 184 | "You can print it, or print it and choose Save as PDF.", ""] |
| 185 | return "\n".join(lines) |
| 186 | |
| 187 | |
| 188 | def POST(request): |
| 189 | identity = request.get("_identity") or {} |
| 190 | user_id = _text(identity.get("user_id")) |
| 191 | if not user_id: |
| 192 | return {"status": 403, "error": "Sign in to send a document."} |
| 193 | |
| 194 | kind = _text(request.get("kind")) |
| 195 | source = _text(request.get("source")) |
| 196 | to = _text(request.get("to")) |
| 197 | if not kind or not source or not to: |
| 198 | return {"status": 400, |
| 199 | "error": "kind, source and to are all required", |
| 200 | "example": {"kind": "quote", "source": "orders/{id}", |
| 201 | "to": "buyer@example.test"}} |
| 202 | |
| 203 | try: |
| 204 | spec = object_documents.source_spec(kind) |
| 205 | except object_documents.UnknownKindError as exc: |
| 206 | return {"status": 400, "error": str(exc)} |
| 207 | if spec is None: |
| 208 | # Printable but not sendable: the kind has no source record to render |
| 209 | # from yet. An honest state, said out loud, rather than a document |
| 210 | # built out of guesses. |
| 211 | return {"status": 409, |
| 212 | "error": f"'{kind}' documents can be printed but not yet sent: " |
| 213 | "the layer has no source mapping for them.", |
| 214 | "kind": kind} |
| 215 | |
| 216 | collection, record_id = _split_source(source) |
| 217 | if collection is None: |
| 218 | return {"status": 400, |
| 219 | "error": f"source must look like 'collection/{{id}}', not {source!r}"} |
| 220 | if collection != spec["collection"]: |
| 221 | # A packing slip built from an invoice would print the wrong address on |
| 222 | # the box. Caught here rather than discovered on a doorstep. |
| 223 | return {"status": 400, |
| 224 | "error": (f"a '{kind}' is rendered from {spec['collection']}, " |
| 225 | f"but source names {collection}")} |
| 226 | |
| 227 | base = _base_dir() |
| 228 | try: |
| 229 | record = object_records.get_collection_record(collection, record_id, |
| 230 | base_dir=base) |
| 231 | except Exception: |
| 232 | record = None |
| 233 | if not record: |
| 234 | return {"status": 404, "error": f"No such record: {source}"} |
| 235 | |
| 236 | if _text(record.get("owner_id")) and _text(record.get("owner_id")) != user_id: |
| 237 | is_admin = "admin" in (identity.get("roles") or []) |
| 238 | if not is_admin: |
| 239 | return {"status": 403, |
| 240 | "error": "Only the owner (or an admin) may send this document."} |
| 241 | |
| 242 | settings = _settings(base) |
| 243 | origin = _text(settings.get("portal.base_url")).rstrip("/") |
| 244 | if not origin: |
| 245 | return {"status": 409, |
| 246 | "error": ("portal.base_url is not set, so there is no address " |
| 247 | "to put in the email. This message is nothing but a " |
| 248 | "link -- set portal.base_url in Settings first."), |
| 249 | "setting": "portal.base_url"} |
| 250 | |
| 251 | currency = _text(record.get("currency")) or "USD" |
| 252 | |
| 253 | def money(cents): |
| 254 | try: |
| 255 | return object_money.format_amount(cents or 0, currency, base_dir=base) |
| 256 | except Exception: |
| 257 | return f"{cents or 0} (minor units)" |
| 258 | |
| 259 | facts = object_documents.facts_from_records( |
| 260 | kind, record, _lines_for(base, spec, record_id), money=money) |
| 261 | try: |
| 262 | model = object_documents.build_model(kind, facts, settings) |
| 263 | except object_documents.NamelessBusinessError as exc: |
| 264 | return {"status": 409, "error": str(exc), "setting": "business.name"} |
| 265 | except object_documents.DocumentError as exc: |
| 266 | return {"status": 400, "error": str(exc)} |
| 267 | |
| 268 | marker = _marker(source, to) |
| 269 | queued_already = _already_queued(base, marker) |
| 270 | if queued_already is None: |
| 271 | return {"status": 409, |
| 272 | "error": "The email outbox could not be read, so nothing was " |
| 273 | "sent -- app-email may not be installed."} |
| 274 | |
| 275 | existing = _existing_document(base, source, to) |
| 276 | if existing is not None: |
| 277 | token = _text(existing.get("token")) |
| 278 | row_id = _text(existing.get("id")) |
| 279 | else: |
| 280 | token = secrets.token_urlsafe(32) |
| 281 | try: |
| 282 | created = object_records.create_collection_record( |
| 283 | COLLECTION, |
| 284 | {"kind": kind, "source": source, "token": token, |
| 285 | "sent_to": to, "sent_at": _now(), "opened_at": "", |
| 286 | "content_hash": object_documents.content_hash(model), |
| 287 | "source_rev": object_records.compute_record_rev(record), |
| 288 | "snapshot": object_documents.snapshot_json(model), |
| 289 | "owner_id": user_id}, |
| 290 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 291 | except Exception as exc: |
| 292 | return {"status": 500, |
| 293 | "error": f"Could not record the sent document: {exc}"} |
| 294 | row_id = created["id"] |
| 295 | |
| 296 | link = f"{origin}/d/{token}" |
| 297 | |
| 298 | if queued_already: |
| 299 | return {"status": "ok", "document_id": row_id, "link": link, |
| 300 | "queued": False, |
| 301 | "note": (f"already sent to {to}; this is the same link, and " |
| 302 | "the same document they were sent")} |
| 303 | |
| 304 | number = _text(model.get("number")) |
| 305 | subject = (f"{model.get('kind_label')}" |
| 306 | + (f" {number}" if number else "") |
| 307 | + f" from {(model.get('business') or {}).get('name', '')}").strip() |
| 308 | try: |
| 309 | object_email.enqueue(to, subject, _email_body(model, link, settings), |
| 310 | base_dir=base, source_object_id=marker) |
| 311 | except Exception as exc: |
| 312 | # The document exists and the link works; only the mail failed. Say |
| 313 | # which, so an operator sends it by hand instead of assuming silence. |
| 314 | return {"status": "ok", "document_id": row_id, "link": link, |
| 315 | "queued": False, "error": f"could not queue the email: {exc}"} |
| 316 | |
| 317 | return {"status": "ok", "document_id": row_id, "link": link, |
| 318 | "queued": True, "sent_to": to, "kind": kind, "source": source} |
| 319 | |
| 320 | |
| 321 | # Kept for symmetry with the rest of the house: an operator poking an action by |
| 322 | # hand over HTTP uses POST, and nothing else calls this. |
| 323 | def GET(request): |
| 324 | return {"status": 405, |
| 325 | "error": "POST {kind, source, to} to send a document."} |