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
confirm_scan.py · 5.5 KB · 147 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 | |
| 6 | The one write in this whole pipeline that matters. Everything upstream -- |
| 7 | OCR, extraction, confidence -- produced a suggestion; this creates the |
| 8 | real record, as a DRAFT, stamped with where it came from and with a |
| 9 | human's name on it. |
| 10 | |
| 11 | Overrides are first-class rather than an escape hatch. Any field passed in |
| 12 | beats what the machine read, because the point of confirmation is that |
| 13 | somebody is looking at the image while they do it. A total the extractor |
| 14 | missed is typed in here, and that is a success of the design rather than |
| 15 | a failure of it: thirty seconds of typing is the cost of never posting a |
| 16 | confident wrong number. |
| 17 | |
| 18 | `preview: true` returns the draft without writing, so the same mapping |
| 19 | that would be committed can be shown on screen first. |
| 20 | |
| 21 | Idempotency: one scan, one record, however many times anyone clicks. The |
| 22 | scan carries confirmed_record once it is done, and that stamp -- not a |
| 23 | status flag alone -- is what a second call checks. |
| 24 | |
| 25 | The expense it creates then rides every gate that already exists: the |
| 26 | approval gate (somebody OTHER than the person who spent it), the markup |
| 27 | stamp, the books composer, the T&M invoice generator. Intake is a new |
| 28 | front door onto machinery that was already there, which is the reason it |
| 29 | is a small object. |
| 30 | """ |
| 31 | |
| 32 | import json |
| 33 | import os |
| 34 | |
| 35 | import object_ids |
| 36 | import object_intake |
| 37 | import object_records |
| 38 | |
| 39 | ACTOR = "action_confirm_scan" |
| 40 | |
| 41 | |
| 42 | def _base_dir(): |
| 43 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 44 | |
| 45 | |
| 46 | def _text(value): |
| 47 | return str(value if value is not None else "").strip() |
| 48 | |
| 49 | |
| 50 | def _truthy(value): |
| 51 | return _text(value).lower() in ("true", "1", "yes", "on") |
| 52 | |
| 53 | |
| 54 | def _int(value, default=0): |
| 55 | try: |
| 56 | return int(_text(value) or default) |
| 57 | except (TypeError, ValueError): |
| 58 | return default |
| 59 | |
| 60 | |
| 61 | def POST(request): |
| 62 | base = _base_dir() |
| 63 | scan_id = _text(request.get("scan_id")) |
| 64 | if not scan_id: |
| 65 | return {"status": 400, "error": "scan_id is required"} |
| 66 | |
| 67 | try: |
| 68 | scan = object_records.get_collection_record("scans", scan_id, base_dir=base) |
| 69 | except Exception: |
| 70 | return {"status": 404, "error": f"No such scan: {scan_id}"} |
| 71 | if not scan: |
| 72 | return {"status": 404, "error": f"No such scan: {scan_id}"} |
| 73 | |
| 74 | already = _text(scan.get("confirmed_record")) |
| 75 | if already: |
| 76 | return {"ok": True, "scan_id": scan_id, "record": already, |
| 77 | "duplicate": True, |
| 78 | "note": "this scan was already confirmed; one scan, one record"} |
| 79 | |
| 80 | try: |
| 81 | extraction = json.loads(_text(scan.get("extracted")) or "{}") |
| 82 | except (TypeError, ValueError): |
| 83 | extraction = {} |
| 84 | extraction = object_intake.normalize_extraction( |
| 85 | extraction, engine=_text(scan.get("ocr_engine"))) |
| 86 | |
| 87 | draft = object_intake.expense_draft_from(scan, extraction) |
| 88 | # Anything the person typed beats anything the machine read. They have |
| 89 | # the image in front of them; the extractor had a guess. |
| 90 | for field in ("description", "incurred_on", "currency", "notes"): |
| 91 | if _text(request.get(field)): |
| 92 | draft[field] = _text(request.get(field)) |
| 93 | if _text(request.get("amount_cents")): |
| 94 | draft["amount_cents"] = _int(request.get("amount_cents")) |
| 95 | |
| 96 | identity = request.get("_identity") or {} |
| 97 | owner = (_text(request.get("owner_id")) |
| 98 | or _text(scan.get("owner_id")) |
| 99 | or _text(identity.get("user_id"))) |
| 100 | |
| 101 | expense = { |
| 102 | "id": object_ids.new_uuid4(), |
| 103 | "description": draft["description"], |
| 104 | "incurred_on": draft["incurred_on"], |
| 105 | "amount_cents": str(draft["amount_cents"]), |
| 106 | "currency": draft["currency"], |
| 107 | "project_id": _text(request.get("project_id")), |
| 108 | "paid_by": _text(request.get("paid_by")) or "company", |
| 109 | "billable": "true" if _truthy(request.get("billable", "true")) else "false", |
| 110 | "receipt_ref": draft["receipt_ref"], |
| 111 | "status": "draft", |
| 112 | "notes": draft.get("notes", ""), |
| 113 | "owner_id": owner, |
| 114 | "entity_id": _text(scan.get("entity_id")), |
| 115 | } |
| 116 | if _text(request.get("markup_bps")): |
| 117 | expense["markup_bps"] = str(_int(request.get("markup_bps"))) |
| 118 | |
| 119 | if _truthy(request.get("preview")): |
| 120 | return {"ok": True, "preview": True, "scan_id": scan_id, |
| 121 | "would_create": {"collection": "expenses", **expense}, |
| 122 | "extraction": extraction} |
| 123 | |
| 124 | if expense["amount_cents"] in ("", "0"): |
| 125 | return {"status": 400, |
| 126 | "error": ("This document has no amount yet. The extractor did " |
| 127 | "not read one, so type it in from the image -- an " |
| 128 | "expense with no amount would post nothing and hide " |
| 129 | "a real cost.")} |
| 130 | |
| 131 | try: |
| 132 | object_records.create_collection_record( |
| 133 | "expenses", expense, base_dir=base, actor=ACTOR) |
| 134 | except Exception as exc: |
| 135 | return {"status": 400, |
| 136 | "error": f"Could not create the expense: {str(exc)[:200]}"} |
| 137 | |
| 138 | reference = f"expenses/{expense['id']}" |
| 139 | object_records.update_collection_record( |
| 140 | "scans", scan_id, |
| 141 | {"status": "confirmed", "confirmed_record": reference}, |
| 142 | base_dir=base, actor=ACTOR) |
| 143 | |
| 144 | return {"ok": True, "scan_id": scan_id, "record": reference, |
| 145 | "expense_id": expense["id"], "status_of_expense": "draft", |
| 146 | "note": "created as a draft; it still needs submitting and " |
| 147 | "approving by somebody else"} |