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.
import_ofx.py · 9.4 KB · 202 lines
| 1 | """action_import_ofx -- import an OFX/QFX download. |
| 2 | |
| 3 | POST {bank_account_id, content, opening_balance_cents?, profile_id?} |
| 4 | |
| 5 | OFX is the format worth supporting after CSV, because it carries the two |
| 6 | things a CSV usually cannot: a stable per-transaction id (FITID), which |
| 7 | makes deduplication exact instead of heuristic, and a stated closing |
| 8 | balance (LEDGERBAL), which lets the statement check its own arithmetic. |
| 9 | Parsing lives in object_ofx.py; this action is the same landing path |
| 10 | action_import_bank_csv uses, so everything downstream -- gates, dedup, |
| 11 | matching, resolution, reconciliation -- is unchanged. One canonical shape, |
| 12 | thin importers (plan/bank-import-reconciliation-spec.md section 3). The |
| 13 | landing itself -- import row, lines, resuming an import that stopped |
| 14 | part-way -- is object_banking.land_import / land_lines, shared with the |
| 15 | CSV importer so the two cannot drift again. |
| 16 | |
| 17 | **Chained openings.** OFX states a closing balance but has no standard |
| 18 | opening-balance tag at all, so a lone file cannot tie out. It can once |
| 19 | there is a prior statement: last month's closing IS this month's opening. |
| 20 | When the caller does not supply one, this action derives the opening from |
| 21 | the account's previous import and records in the import's flags that the |
| 22 | figure was DERIVED rather than stated. That distinction matters -- a |
| 23 | derived opening makes continuity true by construction, so the check that |
| 24 | actually earns its keep is tie-out: do this statement's transactions |
| 25 | explain the movement from the last statement's end to this one's? Claiming |
| 26 | both checks passed when one was tautological would be exactly the |
| 27 | comfortable lie the flags exist to prevent. |
| 28 | """ |
| 29 | |
| 30 | import json |
| 31 | import os |
| 32 | |
| 33 | import object_access |
| 34 | import object_banking |
| 35 | import object_ofx |
| 36 | import object_records |
| 37 | |
| 38 | ACTOR = "action_import_ofx" |
| 39 | |
| 40 | |
| 41 | def _base_dir(): |
| 42 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 43 | |
| 44 | |
| 45 | def POST(request): |
| 46 | identity = request.get("_identity") or {} |
| 47 | user_id = identity.get("user_id") or "" |
| 48 | if not user_id: |
| 49 | return {"status": 403, "error": "Sign in to import a statement."} |
| 50 | |
| 51 | bank_account_id = str(request.get("bank_account_id") or "").strip() |
| 52 | content = request.get("content") |
| 53 | if not bank_account_id or not isinstance(content, str) or not content.strip(): |
| 54 | return {"status": 400, "error": "bank_account_id and content are required."} |
| 55 | |
| 56 | base = _base_dir() |
| 57 | # The account is the unit of access: asked of the permission engine (the |
| 58 | # same answer the value_accounts API gives), not "has an owner who is not |
| 59 | # me", which let anybody act on an account that had no owner. A refused |
| 60 | # account reads exactly like a missing one. |
| 61 | access = object_access.Access(identity, base_dir=base) |
| 62 | account = access.get("value_accounts", bank_account_id, action=object_access.UPDATE) |
| 63 | if account is None: |
| 64 | return {"status": 404, "error": f"Bank account not found: {bank_account_id}"} |
| 65 | |
| 66 | digest = object_banking.file_hash(content) |
| 67 | try: |
| 68 | prior = object_banking.find_import_by_file_hash( |
| 69 | bank_account_id, digest, base_dir=base, strict=True) |
| 70 | except Exception as exc: |
| 71 | return {"status": 409, |
| 72 | "error": ("Could not read this account's existing statements " |
| 73 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 74 | "imported: an unreadable history would let the " |
| 75 | "same lines go on file twice.")} |
| 76 | |
| 77 | try: |
| 78 | parsed = object_ofx.parse_ofx(content) |
| 79 | except object_ofx.OfxError as exc: |
| 80 | return {"status": 422, "error": f"Could not read the statement: {exc}"} |
| 81 | lines = object_banking.assign_line_hashes(parsed["lines"]) |
| 82 | if not lines: |
| 83 | return {"status": 422, "error": "The statement had no transactions."} |
| 84 | |
| 85 | try: |
| 86 | known = object_banking.existing_line_keys( |
| 87 | bank_account_id, base_dir=base, strict=True) |
| 88 | except Exception as exc: |
| 89 | return {"status": 409, |
| 90 | "error": ("Could not read this account's existing statements " |
| 91 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 92 | "imported: an unreadable history would let the " |
| 93 | "same lines go on file twice.")} |
| 94 | |
| 95 | if prior is not None: |
| 96 | # Already imported -- but a crash may have stopped it part-way, so |
| 97 | # land whatever of this file is not on file yet, under the import |
| 98 | # it belongs to. A complete import lands nothing: a no-op. |
| 99 | landed = object_banking.land_lines( |
| 100 | prior.get("id"), bank_account_id, lines, account=account, |
| 101 | user_id=user_id, base_dir=base, actor=ACTOR, known=known) |
| 102 | if landed["imported"]: |
| 103 | return {"status": 200, "already_imported": True, "resumed": True, |
| 104 | "import_id": prior.get("id"), "imported": landed["imported"], |
| 105 | "duplicates": landed["duplicates"], |
| 106 | "note": (f"This file's import had stopped part-way; the " |
| 107 | f"{landed['imported']} missing line(s) were added " |
| 108 | "to it. Its checks are the ones recorded when it " |
| 109 | "was first imported.")} |
| 110 | return {"status": 200, "already_imported": True, "import_id": prior.get("id"), |
| 111 | "imported": 0, "duplicates": 0, |
| 112 | "note": "This exact file was already imported; nothing changed."} |
| 113 | |
| 114 | period_start = parsed["period"].get("start") or "" |
| 115 | period_end = parsed["period"].get("end") or "" |
| 116 | closing = parsed["balances"].get("closing_balance_cents") |
| 117 | |
| 118 | opening = request.get("opening_balance_cents") |
| 119 | opening_derived = False |
| 120 | if not object_banking.is_present(opening): |
| 121 | try: |
| 122 | previous = object_banking.previous_import( |
| 123 | bank_account_id, base_dir=base, before=period_start, strict=True) |
| 124 | except Exception as exc: |
| 125 | return {"status": 409, |
| 126 | "error": ("Could not read this account's existing statements " |
| 127 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 128 | "imported: an unreadable history would let the " |
| 129 | "same lines go on file twice.")} |
| 130 | if previous is not None and str(previous.get("closing_balance_cents") or "").strip(): |
| 131 | opening = int(previous["closing_balance_cents"]) |
| 132 | opening_derived = True |
| 133 | |
| 134 | try: |
| 135 | gates = object_banking.run_gates( |
| 136 | lines, bank_account_id=bank_account_id, |
| 137 | opening_balance_cents=opening, closing_balance_cents=closing, |
| 138 | period_start=period_start, base_dir=base, strict=True) |
| 139 | except Exception as exc: |
| 140 | return {"status": 409, |
| 141 | "error": ("Could not read this account's existing statements " |
| 142 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 143 | "imported: an unreadable history would let the " |
| 144 | "same lines go on file twice.")} |
| 145 | checks = dict(gates["checks"]) |
| 146 | if opening_derived: |
| 147 | # Say plainly that continuity could not fail here: it compared the |
| 148 | # previous closing balance against itself. |
| 149 | checks["opening_balance"] = { |
| 150 | "ran": True, "derived": True, |
| 151 | "detail": ("OFX states no opening balance; used the previous statement's " |
| 152 | "closing balance, so continuity is true by construction and " |
| 153 | "tie-out is the check that carries weight here"), |
| 154 | } |
| 155 | if isinstance(checks.get("continuity"), dict): |
| 156 | checks["continuity"]["tautological"] = True |
| 157 | gates = {**gates, "checks": checks} |
| 158 | |
| 159 | # Deterministic, so two overlapping first imports of one file converge |
| 160 | # on one import row (object_banking.land_import). |
| 161 | import_id = object_banking.import_id_for(bank_account_id, digest) |
| 162 | import_row = { |
| 163 | "id": import_id, |
| 164 | "bank_account_id": bank_account_id, |
| 165 | "profile_id": str(request.get("profile_id") or "").strip(), |
| 166 | "source_format": "ofx", |
| 167 | "file_hash": digest, |
| 168 | "period_start": period_start, |
| 169 | "period_end": period_end, |
| 170 | "opening_balance_cents": str(opening) if object_banking.is_present(opening) else "", |
| 171 | "closing_balance_cents": str(closing) if closing is not None else "", |
| 172 | "line_count": str(len(lines)), |
| 173 | "status": gates["status"], |
| 174 | "flags": json.dumps(checks, sort_keys=True), |
| 175 | "owner_id": user_id, |
| 176 | } |
| 177 | if account.get("entity_id"): |
| 178 | import_row["entity_id"] = account["entity_id"] |
| 179 | # The row, then the lines (bank_lines.import_id is a relation to it). A |
| 180 | # failure after the row raises; re-importing the file resumes it (above). |
| 181 | landed = object_banking.land_import( |
| 182 | import_row, lines, account=account, user_id=user_id, base_dir=base, |
| 183 | actor=ACTOR, known=known) |
| 184 | if landed is None: |
| 185 | return {"status": 200, "already_imported": True, "import_id": import_id, |
| 186 | "imported": 0, "duplicates": 0, |
| 187 | "note": ("This exact file is being imported by another request " |
| 188 | "right now; nothing more changed here.")} |
| 189 | imported, duplicates = landed["imported"], landed["duplicates"] |
| 190 | |
| 191 | return { |
| 192 | "status": 200, |
| 193 | "import_id": import_id, |
| 194 | "imported": imported, |
| 195 | "duplicates": duplicates, |
| 196 | "import_status": gates["status"], |
| 197 | "failed_checks": gates["failed"], |
| 198 | "checks": checks, |
| 199 | "opening_derived": opening_derived, |
| 200 | "period": {"start": period_start, "end": period_end}, |
| 201 | "account": parsed.get("account", {}), |
| 202 | } |