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.
confirm_scan.py · 13.2 KB · 294 lines
| 1 | """action_confirm_scan -- a person says yes, and the record is theirs. |
| 2 | |
| 3 | POST {scan_id, project_id?, billable?, paid_by?, markup_bps?, |
| 4 | description?, incurred_on?, amount_cents?, currency?, preview?, |
| 5 | category_id?, business_purpose?, attendees?, location?} |
| 6 | |
| 7 | The expense links this scan as its receipt (`receipt_scan_id`, app-finance |
| 8 | 0.19.0) as well as naming it in `receipt_ref`, and stamps its category's |
| 9 | requirements itself when a category is given -- this writes below the |
| 10 | expenses hook, so it does what the hook would (object_expense_rules). |
| 11 | |
| 12 | The one write in this whole pipeline that matters. Everything upstream -- |
| 13 | OCR, extraction, confidence -- produced a suggestion; this creates the |
| 14 | real record, as a DRAFT, stamped with where it came from and with a |
| 15 | human's name on it. |
| 16 | |
| 17 | Overrides are first-class rather than an escape hatch. Any field passed in |
| 18 | beats what the machine read, because the point of confirmation is that |
| 19 | somebody is looking at the image while they do it. A total the extractor |
| 20 | missed is typed in here, and that is a success of the design rather than |
| 21 | a failure of it: thirty seconds of typing is the cost of never posting a |
| 22 | confident wrong number. |
| 23 | |
| 24 | `preview: true` returns the draft without writing, so the same mapping |
| 25 | that would be committed can be shown on screen first. |
| 26 | |
| 27 | Idempotency: one scan, one record, however many times anyone clicks. The |
| 28 | scan carries confirmed_record once it is done, and that stamp -- not a |
| 29 | status flag alone -- is what a second call checks. |
| 30 | |
| 31 | That stamp is written AFTER the expense, so on its own it only guards a |
| 32 | call that starts after another one finished. Until 2026-11-28 an attempt |
| 33 | that wrote the expense and then failed the scan transition (a `pending` |
| 34 | scan with the amount typed in: pending -> confirmed is not a legal move) |
| 35 | left the expense behind, and each retry booked another |
| 36 | (bug-reports/2026-11-28-06-14-33-CST-confirm-scan-retry-duplicate-expenses); |
| 37 | two overlapping clicks did the same. So the expense now carries the claim |
| 38 | itself: `generated_from = scans/{id}`, which expenses.json declares |
| 39 | `unique` (checked inside the write lock, for every writer) and read_only |
| 40 | (no form or API client can squat a scan's key). The order is: |
| 41 | |
| 42 | 1. refuse up front when the scan's status cannot move to `confirmed` |
| 43 | (the schema's own transitions), so the common failure writes nothing; |
| 44 | 2. create the expense; a UniqueConstraintError means an earlier or |
| 45 | concurrent attempt already created it, and THAT expense is the one -- |
| 46 | it is linked, not duplicated; |
| 47 | 3. stamp the scan. If this fails, the draft expense stays and the answer |
| 48 | says so; the next attempt lands on step 2's "already there" and links it. |
| 49 | |
| 50 | What was rejected: claiming the scan first (status confirmed with |
| 51 | expected_rev, then the expense). `confirmed` is terminal, so an expense |
| 52 | write that then failed would leave a scan that says confirmed pointing at |
| 53 | nothing, with no legal move back. |
| 54 | |
| 55 | The expense it creates then rides every gate that already exists: the |
| 56 | approval gate (somebody OTHER than the person who spent it), the markup |
| 57 | stamp, the books composer, the T&M invoice generator. Intake is a new |
| 58 | front door onto machinery that was already there, which is the reason it |
| 59 | is a small object. |
| 60 | """ |
| 61 | |
| 62 | import json |
| 63 | import os |
| 64 | |
| 65 | import object_access |
| 66 | import object_collections |
| 67 | import object_expense_rules |
| 68 | import object_ids |
| 69 | import object_intake |
| 70 | import object_records |
| 71 | import object_schemas |
| 72 | |
| 73 | ACTOR = "action_confirm_scan" |
| 74 | |
| 75 | |
| 76 | def _base_dir(): |
| 77 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 78 | |
| 79 | |
| 80 | def _text(value): |
| 81 | return str(value if value is not None else "").strip() |
| 82 | |
| 83 | |
| 84 | def _truthy(value): |
| 85 | return _text(value).lower() in ("true", "1", "yes", "on") |
| 86 | |
| 87 | |
| 88 | def _int(value, default=0): |
| 89 | try: |
| 90 | return int(_text(value) or default) |
| 91 | except (TypeError, ValueError): |
| 92 | return default |
| 93 | |
| 94 | |
| 95 | def _status_cannot_confirm(scan, base): |
| 96 | """The reason this scan's status may not move to `confirmed`, or "" |
| 97 | when it may (or the schema cannot say: the update itself still enforces |
| 98 | the transition, and the unique key keeps a failure at one expense).""" |
| 99 | current = _text(scan.get("status")) |
| 100 | if not current or current == "confirmed": |
| 101 | return "" |
| 102 | try: |
| 103 | schema = object_schemas.get_schema("scans", base_dir=base) |
| 104 | except Exception: |
| 105 | return "" |
| 106 | for field in schema.get("fields") or []: |
| 107 | if not isinstance(field, dict) or field.get("name") != "status": |
| 108 | continue |
| 109 | transitions = field.get("transitions") |
| 110 | if not isinstance(transitions, dict): |
| 111 | return "" |
| 112 | targets = [entry if isinstance(entry, str) else |
| 113 | _text(entry.get("to")) if isinstance(entry, dict) else "" |
| 114 | for entry in transitions.get(current) or []] |
| 115 | if "confirmed" in targets: |
| 116 | return "" |
| 117 | return (f"This scan cannot move from '{current}' to 'confirmed'. " |
| 118 | + ("It has not been read yet; run the reader (or wait for it) " |
| 119 | "and confirm it once it is 'extracted'." |
| 120 | if current in ("pending", "processing") else |
| 121 | "Only an 'extracted' scan can be confirmed.")) |
| 122 | return "" |
| 123 | |
| 124 | |
| 125 | def POST(request): |
| 126 | base = _base_dir() |
| 127 | scan_id = _text(request.get("scan_id")) |
| 128 | if not scan_id: |
| 129 | return {"status": 400, "error": "scan_id is required"} |
| 130 | |
| 131 | # Only someone the scans API would let UPDATE this scan may confirm it, |
| 132 | # preview it included: the preview is the scan's extraction. Asked of |
| 133 | # the permission engine because this object writes server-side and is |
| 134 | # the only gate (bug-reports/2026-11-28-06-14-25). Refused and missing |
| 135 | # are one answer, so the action is not an existence oracle for scan ids. |
| 136 | identity = request.get("_identity") or {} |
| 137 | access = object_access.Access(identity, base_dir=base) |
| 138 | try: |
| 139 | scan = access.get("scans", scan_id, action="update") |
| 140 | except Exception: |
| 141 | return {"status": 404, "error": f"No such scan: {scan_id}"} |
| 142 | if not scan: |
| 143 | return {"status": 404, "error": f"No such scan: {scan_id}"} |
| 144 | |
| 145 | already = _text(scan.get("confirmed_record")) |
| 146 | if already: |
| 147 | return {"ok": True, "scan_id": scan_id, "record": already, |
| 148 | "duplicate": True, |
| 149 | "note": "this scan was already confirmed; one scan, one record"} |
| 150 | |
| 151 | try: |
| 152 | extraction = json.loads(_text(scan.get("extracted")) or "{}") |
| 153 | except (TypeError, ValueError): |
| 154 | extraction = {} |
| 155 | extraction = object_intake.normalize_extraction( |
| 156 | extraction, engine=_text(scan.get("ocr_engine"))) |
| 157 | |
| 158 | draft = object_intake.expense_draft_from(scan, extraction) |
| 159 | # Anything the person typed beats anything the machine read. They have |
| 160 | # the image in front of them; the extractor had a guess. |
| 161 | for field in ("description", "incurred_on", "currency", "notes"): |
| 162 | if _text(request.get(field)): |
| 163 | draft[field] = _text(request.get(field)) |
| 164 | if _text(request.get("amount_cents")): |
| 165 | draft["amount_cents"] = _int(request.get("amount_cents")) |
| 166 | |
| 167 | # The expense lands in the books of whoever owns the scan -- never of |
| 168 | # an owner_id named in the request body, which let a caller plant an |
| 169 | # expense in anybody's books. |
| 170 | owner = _text(scan.get("owner_id")) or access.user_id |
| 171 | |
| 172 | expense = { |
| 173 | "id": object_ids.new_uuid4(), |
| 174 | "description": draft["description"], |
| 175 | "incurred_on": draft["incurred_on"], |
| 176 | "amount_cents": str(draft["amount_cents"]), |
| 177 | "currency": draft["currency"], |
| 178 | "project_id": _text(request.get("project_id")), |
| 179 | "paid_by": _text(request.get("paid_by")) or "company", |
| 180 | "billable": "true" if _truthy(request.get("billable", "true")) else "false", |
| 181 | "receipt_ref": draft["receipt_ref"], |
| 182 | "status": "draft", |
| 183 | "notes": draft.get("notes", ""), |
| 184 | "owner_id": owner, |
| 185 | "entity_id": _text(scan.get("entity_id")), |
| 186 | } |
| 187 | if _text(request.get("markup_bps")): |
| 188 | expense["markup_bps"] = str(_int(request.get("markup_bps"))) |
| 189 | |
| 190 | # The scan IS the receipt (app-finance 0.19.0): linked as a relation, |
| 191 | # not only named in receipt_ref, so the receipt requirement and the |
| 192 | # audit trail can follow it. What an auditor also asks for -- category, |
| 193 | # purpose, attendees, place -- is typed in here by the person holding |
| 194 | # the receipt, who is the one who knows. |
| 195 | expense["receipt_scan_id"] = scan_id |
| 196 | for field in ("category_id", "business_purpose", "attendees", "location"): |
| 197 | if _text(request.get(field)): |
| 198 | expense[field] = _text(request.get(field)) |
| 199 | if expense.get("category_id"): |
| 200 | # A storage-level writer stamps the category's requirements itself |
| 201 | # (expenses' LOCKED_CHECK refuses an unstamped categorised expense |
| 202 | # for every writer), with the same function the hook uses. |
| 203 | try: |
| 204 | # access: categories are policy every signed-in user reads; read only to stamp its requirements |
| 205 | category = object_records.get_collection_record( |
| 206 | "expense_categories", expense["category_id"], base_dir=base) |
| 207 | except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError): |
| 208 | return {"status": 400, "error": f"No expense category {expense['category_id']}."} |
| 209 | except Exception: |
| 210 | return {"status": 503, "error": "Expense categories are unreadable; try again."} |
| 211 | try: |
| 212 | expense.update(object_expense_rules.category_stamps(category, expense["amount_cents"])) |
| 213 | except ValueError: |
| 214 | pass # no amount yet: refused below, before anything is written |
| 215 | # An app-finance older than 0.19.0 has none of those fields; sending |
| 216 | # them would refuse the whole expense. Keep only what it declares. |
| 217 | try: |
| 218 | declared = {field.get("name") for field in |
| 219 | (object_schemas.get_schema("expenses", base_dir=base).get("fields") or []) |
| 220 | if isinstance(field, dict)} |
| 221 | except Exception: |
| 222 | declared = set() |
| 223 | if declared: |
| 224 | expense = {key: value for key, value in expense.items() if key in declared} |
| 225 | |
| 226 | # Every pointer on the expense is asked the record API's |
| 227 | # relation.requires question for this caller, preview included and |
| 228 | # before anything is written: project_id comes from the request, and |
| 229 | # entity_id from a scan that may predate ingest's own check (or was |
| 230 | # written below the record API). A record the caller may not act on |
| 231 | # and a missing one get the record API's one answer. |
| 232 | refusal = access.relation_refusal("expenses", expense) |
| 233 | if refusal is not None: |
| 234 | status, body = refusal |
| 235 | return {**body, "status": status} |
| 236 | |
| 237 | if _truthy(request.get("preview")): |
| 238 | return {"ok": True, "preview": True, "scan_id": scan_id, |
| 239 | "would_create": {"collection": "expenses", **expense}, |
| 240 | "extraction": extraction} |
| 241 | |
| 242 | if expense["amount_cents"] in ("", "0"): |
| 243 | return {"status": 400, |
| 244 | "error": ("This document has no amount yet. The extractor did " |
| 245 | "not read one, so type it in from the image -- an " |
| 246 | "expense with no amount would post nothing and hide " |
| 247 | "a real cost.")} |
| 248 | |
| 249 | refusal = _status_cannot_confirm(scan, base) |
| 250 | if refusal: |
| 251 | return {"status": 409, "error": refusal} |
| 252 | |
| 253 | # The claim: one expense per scan, enforced by expenses.json's unique |
| 254 | # key on generated_from inside the write lock. |
| 255 | expense["generated_from"] = f"scans/{scan_id}" |
| 256 | linked_existing = False |
| 257 | try: |
| 258 | # access: system write after the access check above (the scan was read for update through Access; the expense's pointers passed relation_refusal) |
| 259 | object_records.create_collection_record( |
| 260 | "expenses", expense, base_dir=base, actor=ACTOR, |
| 261 | preserve_read_only=True) |
| 262 | except object_records.UniqueConstraintError as exc: |
| 263 | # An earlier attempt (or one running right now) created it. That |
| 264 | # expense is this scan's record; booking ours too is the bug. |
| 265 | expense["id"] = exc.existing_id |
| 266 | linked_existing = True |
| 267 | except Exception as exc: |
| 268 | return {"status": 400, |
| 269 | "error": f"Could not create the expense: {str(exc)[:200]}"} |
| 270 | |
| 271 | reference = f"expenses/{expense['id']}" |
| 272 | try: |
| 273 | object_records.update_collection_record( |
| 274 | "scans", scan_id, |
| 275 | {"status": "confirmed", "confirmed_record": reference}, |
| 276 | base_dir=base, actor=ACTOR) |
| 277 | except Exception as exc: |
| 278 | return {"status": 409, |
| 279 | "error": (f"The draft expense {expense['id']} exists, but the " |
| 280 | f"scan could not be marked confirmed: {str(exc)[:200]}. " |
| 281 | "Confirming again links that expense; it does not " |
| 282 | "create another."), |
| 283 | "expense_id": expense["id"]} |
| 284 | |
| 285 | result = {"ok": True, "scan_id": scan_id, "record": reference, |
| 286 | "expense_id": expense["id"], "status_of_expense": "draft", |
| 287 | "note": "created as a draft; it still needs submitting and " |
| 288 | "approving by somebody else"} |
| 289 | if linked_existing: |
| 290 | result["duplicate"] = True |
| 291 | result["note"] = ("an expense for this scan already existed (an earlier " |
| 292 | "or simultaneous confirmation); it was linked, not " |
| 293 | "created again") |
| 294 | return result |