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.
send_document.py · 13.8 KB · 335 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_access |
| 66 | import object_documents |
| 67 | import object_email |
| 68 | import object_money |
| 69 | import object_records |
| 70 | |
| 71 | ACTOR = "action_send_document" |
| 72 | COLLECTION = "sent_documents" |
| 73 | |
| 74 | |
| 75 | def _base_dir(): |
| 76 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 77 | |
| 78 | |
| 79 | def _text(value): |
| 80 | return str(value if value is not None else "").strip() |
| 81 | |
| 82 | |
| 83 | def _now(): |
| 84 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 85 | |
| 86 | |
| 87 | def _settings(base): |
| 88 | """Every app_settings row as one dict. |
| 89 | |
| 90 | Read whole rather than key by key: object_documents wants a mapping, the |
| 91 | collection is tiny, and one scan beats six. Duplicated on purpose like |
| 92 | every other package that reads app_settings (docs/logic-decisions.md #4). |
| 93 | """ |
| 94 | values = {} |
| 95 | try: |
| 96 | # access: box configuration |
| 97 | for row in object_records.read_collection_records("app_settings", |
| 98 | base_dir=base): |
| 99 | key, value = _text(row.get("key")), _text(row.get("value")) |
| 100 | if key and value: |
| 101 | values[key] = value |
| 102 | except Exception: |
| 103 | pass |
| 104 | return values |
| 105 | |
| 106 | |
| 107 | def _split_source(source): |
| 108 | """'orders/9f3...' -> ('orders', '9f3...'), or (None, None).""" |
| 109 | source = _text(source) |
| 110 | if source.count("/") != 1: |
| 111 | return None, None |
| 112 | collection, _, record_id = source.partition("/") |
| 113 | collection, record_id = _text(collection), _text(record_id) |
| 114 | if not collection or not record_id: |
| 115 | return None, None |
| 116 | return collection, record_id |
| 117 | |
| 118 | |
| 119 | def _lines_for(base, spec, record_id): |
| 120 | """The document's line rows, or none at all. |
| 121 | |
| 122 | Wrapped whole: the lines collection belongs to another package, and a |
| 123 | server that never installed line-item detail must still be able to send a |
| 124 | document -- one without lines, honestly, rather than a traceback. |
| 125 | """ |
| 126 | collection = spec.get("lines_collection") |
| 127 | if not collection: |
| 128 | return [] |
| 129 | try: |
| 130 | rows = object_records.read_collection_records(collection, base_dir=base) |
| 131 | except Exception: |
| 132 | return [] |
| 133 | key = spec.get("lines_fk") |
| 134 | lines = [row for row in rows if _text(row.get(key)) == record_id] |
| 135 | lines.sort(key=lambda row: _text(row.get("description"))) |
| 136 | return lines |
| 137 | |
| 138 | |
| 139 | def _existing_document(base, source, to): |
| 140 | """The document already sent for this (source, recipient), or None.""" |
| 141 | try: |
| 142 | # access: lines and sent-document rows of the record read through Access above |
| 143 | rows = object_records.read_collection_records(COLLECTION, base_dir=base) |
| 144 | except Exception: |
| 145 | return None |
| 146 | for row in rows: |
| 147 | if _text(row.get("source")) == source and _text(row.get("sent_to")) == to: |
| 148 | return row |
| 149 | return None |
| 150 | |
| 151 | |
| 152 | def _marker(source, to): |
| 153 | return f"{ACTOR}:{source}:{to}" |
| 154 | |
| 155 | |
| 156 | def _already_queued(base, marker): |
| 157 | """Whether this exact message is already in the outbox, or None when the |
| 158 | outbox cannot be read at all. |
| 159 | |
| 160 | None is a REFUSAL, not a False -- system_order_email's argument holds |
| 161 | here word for word: a message skipped now can be composed by a retry, and |
| 162 | a message sent twice is already in somebody's inbox. |
| 163 | """ |
| 164 | try: |
| 165 | # access: checks whether this document's email is already queued; the rows are never shown |
| 166 | rows = object_records.read_collection_records( |
| 167 | object_email.OUTBOX_COLLECTION, base_dir=base) |
| 168 | except Exception: |
| 169 | return None |
| 170 | return any(_text(row.get("source_object_id")) == marker for row in rows) |
| 171 | |
| 172 | |
| 173 | def _email_body(model, link, settings): |
| 174 | name = "" |
| 175 | for party in model.get("parties") or []: |
| 176 | if party.get("role") != "from": |
| 177 | name = _text(party.get("name")) |
| 178 | label = _text(model.get("kind_label")) or "document" |
| 179 | number = _text(model.get("number")) |
| 180 | business = _text((model.get("business") or {}).get("name")) |
| 181 | lines = [f"Hello {name or 'there'},", "", |
| 182 | f"Your {label.lower()}{(' ' + number) if number else ''} " |
| 183 | f"from {business} is ready to read:", "", link, ""] |
| 184 | terms = _text(model.get("terms")) |
| 185 | if terms: |
| 186 | lines += [terms, ""] |
| 187 | lines += ["This link shows the document exactly as it was sent to you. " |
| 188 | "You can print it, or print it and choose Save as PDF.", ""] |
| 189 | return "\n".join(lines) |
| 190 | |
| 191 | |
| 192 | def POST(request): |
| 193 | identity = request.get("_identity") or {} |
| 194 | user_id = _text(identity.get("user_id")) |
| 195 | if not user_id: |
| 196 | return {"status": 403, "error": "Sign in to send a document."} |
| 197 | |
| 198 | kind = _text(request.get("kind")) |
| 199 | source = _text(request.get("source")) |
| 200 | to = _text(request.get("to")) |
| 201 | if not kind or not source or not to: |
| 202 | return {"status": 400, |
| 203 | "error": "kind, source and to are all required", |
| 204 | "example": {"kind": "quote", "source": "orders/{id}", |
| 205 | "to": "buyer@example.test"}} |
| 206 | |
| 207 | try: |
| 208 | spec = object_documents.source_spec(kind) |
| 209 | except object_documents.UnknownKindError as exc: |
| 210 | return {"status": 400, "error": str(exc)} |
| 211 | if spec is None: |
| 212 | # Printable but not sendable: the kind has no source record to render |
| 213 | # from yet. An honest state, said out loud, rather than a document |
| 214 | # built out of guesses. |
| 215 | return {"status": 409, |
| 216 | "error": f"'{kind}' documents can be printed but not yet sent: " |
| 217 | "the layer has no source mapping for them.", |
| 218 | "kind": kind} |
| 219 | |
| 220 | collection, record_id = _split_source(source) |
| 221 | if collection is None: |
| 222 | return {"status": 400, |
| 223 | "error": f"source must look like 'collection/{{id}}', not {source!r}"} |
| 224 | if collection != spec["collection"]: |
| 225 | # A packing slip built from an invoice would print the wrong address on |
| 226 | # the box. Caught here rather than discovered on a doorstep. |
| 227 | return {"status": 400, |
| 228 | "error": (f"a '{kind}' is rendered from {spec['collection']}, " |
| 229 | f"but source names {collection}")} |
| 230 | |
| 231 | base = _base_dir() |
| 232 | # Sending mails a copy of the record (and its lines) to an address the |
| 233 | # caller chooses, so the caller must be someone the permission engine |
| 234 | # lets READ it: the same answer the collection API gives, an admin |
| 235 | # included, a role the policy grants included. The hand-written test |
| 236 | # that stood here ("has an owner who is not me, and I am not an admin") |
| 237 | # let anybody send any record that had no owner. A refused record reads |
| 238 | # exactly like a missing one, so a guessed id learns nothing. |
| 239 | access = object_access.Access(identity, base_dir=base) |
| 240 | try: |
| 241 | record = access.get(collection, record_id) |
| 242 | except Exception: |
| 243 | record = None |
| 244 | if not record: |
| 245 | return {"status": 404, "error": f"No such record: {source}"} |
| 246 | |
| 247 | settings = _settings(base) |
| 248 | origin = _text(settings.get("portal.base_url")).rstrip("/") |
| 249 | if not origin: |
| 250 | return {"status": 409, |
| 251 | "error": ("portal.base_url is not set, so there is no address " |
| 252 | "to put in the email. This message is nothing but a " |
| 253 | "link -- set portal.base_url in Settings first."), |
| 254 | "setting": "portal.base_url"} |
| 255 | |
| 256 | currency = _text(record.get("currency")) or "USD" |
| 257 | |
| 258 | def money(cents): |
| 259 | try: |
| 260 | return object_money.format_amount(cents or 0, currency, base_dir=base) |
| 261 | except Exception: |
| 262 | return f"{cents or 0} (minor units)" |
| 263 | |
| 264 | facts = object_documents.facts_from_records( |
| 265 | kind, record, _lines_for(base, spec, record_id), money=money) |
| 266 | try: |
| 267 | model = object_documents.build_model(kind, facts, settings) |
| 268 | except object_documents.NamelessBusinessError as exc: |
| 269 | return {"status": 409, "error": str(exc), "setting": "business.name"} |
| 270 | except object_documents.DocumentError as exc: |
| 271 | return {"status": 400, "error": str(exc)} |
| 272 | |
| 273 | marker = _marker(source, to) |
| 274 | queued_already = _already_queued(base, marker) |
| 275 | if queued_already is None: |
| 276 | return {"status": 409, |
| 277 | "error": "The email outbox could not be read, so nothing was " |
| 278 | "sent -- app-email may not be installed."} |
| 279 | |
| 280 | existing = _existing_document(base, source, to) |
| 281 | if existing is not None: |
| 282 | token = _text(existing.get("token")) |
| 283 | row_id = _text(existing.get("id")) |
| 284 | else: |
| 285 | token = secrets.token_urlsafe(32) |
| 286 | try: |
| 287 | # access: lines and sent-document rows of the record read through Access above |
| 288 | created = object_records.create_collection_record( |
| 289 | COLLECTION, |
| 290 | {"kind": kind, "source": source, "token": token, |
| 291 | "sent_to": to, "sent_at": _now(), "opened_at": "", |
| 292 | "content_hash": object_documents.content_hash(model), |
| 293 | # Keyed (client_record_rev), never the unkeyed fingerprint: |
| 294 | # the sender reads this row, and an unkeyed hash of the |
| 295 | # source would let them test guesses of its hidden fields. |
| 296 | "source_rev": object_records.client_record_rev( |
| 297 | collection, record, base_dir=base), |
| 298 | "snapshot": object_documents.snapshot_json(model), |
| 299 | "owner_id": user_id}, |
| 300 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 301 | except Exception as exc: |
| 302 | return {"status": 500, |
| 303 | "error": f"Could not record the sent document: {exc}"} |
| 304 | row_id = created["id"] |
| 305 | |
| 306 | link = f"{origin}/d/{token}" |
| 307 | |
| 308 | if queued_already: |
| 309 | return {"status": "ok", "document_id": row_id, "link": link, |
| 310 | "queued": False, |
| 311 | "note": (f"already sent to {to}; this is the same link, and " |
| 312 | "the same document they were sent")} |
| 313 | |
| 314 | number = _text(model.get("number")) |
| 315 | subject = (f"{model.get('kind_label')}" |
| 316 | + (f" {number}" if number else "") |
| 317 | + f" from {(model.get('business') or {}).get('name', '')}").strip() |
| 318 | try: |
| 319 | object_email.enqueue(to, subject, _email_body(model, link, settings), |
| 320 | base_dir=base, source_object_id=marker) |
| 321 | except Exception as exc: |
| 322 | # The document exists and the link works; only the mail failed. Say |
| 323 | # which, so an operator sends it by hand instead of assuming silence. |
| 324 | return {"status": "ok", "document_id": row_id, "link": link, |
| 325 | "queued": False, "error": f"could not queue the email: {exc}"} |
| 326 | |
| 327 | return {"status": "ok", "document_id": row_id, "link": link, |
| 328 | "queued": True, "sent_to": to, "kind": kind, "source": source} |
| 329 | |
| 330 | |
| 331 | # Kept for symmetry with the rest of the house: an operator poking an action by |
| 332 | # hand over HTTP uses POST, and nothing else calls this. |
| 333 | def GET(request): |
| 334 | return {"status": 405, |
| 335 | "error": "POST {kind, source, to} to send a document."} |