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_bank_csv.py · 9.5 KB · 198 lines
| 1 | """action_import_bank_csv -- read a bank's CSV export through a saved profile. |
| 2 | |
| 3 | POST {bank_account_id, profile_id, content, opening_balance_cents?, |
| 4 | closing_balance_cents?, period_start?, period_end?} |
| 5 | |
| 6 | The evidence-handling posture (plan/bank-import-reconciliation-spec.md): |
| 7 | |
| 8 | 1. **File-level idempotency** -- the same file re-imported is a no-op, |
| 9 | reported as already_imported with the original import's id. Operators |
| 10 | re-upload by accident constantly; that must be boring, not destructive. |
| 11 | An import that stopped part-way (a crash after the import row, before |
| 12 | its last line) is RESUMED by re-importing the file: the missing lines |
| 13 | land under the original import, nothing is doubled |
| 14 | (object_banking.land_import; until 2026-11-28 the half-loaded file was |
| 15 | "already imported" forever). |
| 16 | 2. **Deterministic parsing** -- the profile's column_map decides how to |
| 17 | read the file. AI helps AUTHOR a profile once; it never re-reads |
| 18 | statements, because a fraud control cannot be nondeterministic. |
| 19 | 3. **The statement checks itself** -- tie-out (opening + lines == closing) |
| 20 | and continuity (this opening == the previous statement's closing) run |
| 21 | here, and their verdict SETS the import's status. Flagged imports still |
| 22 | store their lines: evidence is evidence, and hiding a truncated |
| 23 | statement is exactly the failure this control exists to catch. |
| 24 | 4. **Line-level dedup** -- lines already on file for this account (by the |
| 25 | bank's transaction id, else a content hash) are skipped and counted, |
| 26 | so overlapping date ranges between statements are safe. This action |
| 27 | writes at the storage level (never through the HTTP hook), so it |
| 28 | performs the same check hook_bank_lines enforces for direct writers. |
| 29 | |
| 30 | Nothing here posts to the books. Imported lines are the OTHER party's |
| 31 | record; journals only ever come from resolving a line deliberately. |
| 32 | """ |
| 33 | |
| 34 | import json |
| 35 | import os |
| 36 | |
| 37 | import object_access |
| 38 | import object_banking |
| 39 | import object_records |
| 40 | |
| 41 | ACTOR = "action_import_bank_csv" |
| 42 | |
| 43 | |
| 44 | def _base_dir(): |
| 45 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 46 | |
| 47 | |
| 48 | def POST(request): |
| 49 | identity = request.get("_identity") or {} |
| 50 | user_id = identity.get("user_id") or "" |
| 51 | if not user_id: |
| 52 | return {"status": 403, "error": "Sign in to import a statement."} |
| 53 | |
| 54 | bank_account_id = str(request.get("bank_account_id") or "").strip() |
| 55 | profile_id = str(request.get("profile_id") or "").strip() |
| 56 | content = request.get("content") |
| 57 | if not bank_account_id or not isinstance(content, str) or not content.strip(): |
| 58 | return {"status": 400, "error": "bank_account_id and content are required."} |
| 59 | |
| 60 | base = _base_dir() |
| 61 | # The account is the unit of access: asked of the permission engine (the |
| 62 | # same answer the value_accounts API gives), not "has an owner who is not |
| 63 | # me", which let anybody act on an account that had no owner. A refused |
| 64 | # account reads exactly like a missing one. |
| 65 | access = object_access.Access(identity, base_dir=base) |
| 66 | account = access.get("value_accounts", bank_account_id, action=object_access.UPDATE) |
| 67 | if account is None: |
| 68 | return {"status": 404, "error": f"Bank account not found: {bank_account_id}"} |
| 69 | |
| 70 | column_map = {} |
| 71 | profile = None |
| 72 | if profile_id: |
| 73 | # A profile is its owner's: reading another person's column map by id |
| 74 | # is refused like a missing one. |
| 75 | profile = access.get("bank_import_profiles", profile_id) |
| 76 | if profile is None: |
| 77 | return {"status": 404, "error": f"Import profile not found: {profile_id}"} |
| 78 | try: |
| 79 | column_map = json.loads(profile.get("column_map") or "{}") |
| 80 | except (ValueError, TypeError): |
| 81 | return {"status": 409, |
| 82 | "error": f"Profile {profile_id} has an unparseable column_map."} |
| 83 | if not column_map: |
| 84 | column_map = request.get("column_map") or {} |
| 85 | if not isinstance(column_map, dict) or not column_map: |
| 86 | return {"status": 400, |
| 87 | "error": "No column_map: pass profile_id (preferred) or an inline column_map."} |
| 88 | |
| 89 | digest = object_banking.file_hash(content) |
| 90 | try: |
| 91 | prior = object_banking.find_import_by_file_hash( |
| 92 | bank_account_id, digest, base_dir=base, strict=True) |
| 93 | except Exception as exc: |
| 94 | return {"status": 409, |
| 95 | "error": ("Could not read this account's existing statements " |
| 96 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 97 | "imported: an unreadable history would let the " |
| 98 | "same lines go on file twice.")} |
| 99 | |
| 100 | try: |
| 101 | parsed = object_banking.parse_statement_csv(content, column_map) |
| 102 | except object_banking.ImportError_ as exc: |
| 103 | return {"status": 422, "error": f"Could not read the statement: {exc}"} |
| 104 | if not parsed: |
| 105 | return {"status": 422, "error": "The statement had no data rows."} |
| 106 | lines = object_banking.assign_line_hashes(parsed) |
| 107 | |
| 108 | try: |
| 109 | known = object_banking.existing_line_keys( |
| 110 | bank_account_id, base_dir=base, strict=True) |
| 111 | except Exception as exc: |
| 112 | return {"status": 409, |
| 113 | "error": ("Could not read this account's existing statements " |
| 114 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 115 | "imported: an unreadable history would let the " |
| 116 | "same lines go on file twice.")} |
| 117 | |
| 118 | if prior is not None: |
| 119 | # Already imported -- but a crash may have stopped it part-way, so |
| 120 | # land whatever of this file is not on file yet, under the import |
| 121 | # it belongs to. A complete import lands nothing: a no-op. |
| 122 | landed = object_banking.land_lines( |
| 123 | prior.get("id"), bank_account_id, lines, account=account, |
| 124 | user_id=user_id, base_dir=base, actor=ACTOR, known=known) |
| 125 | if landed["imported"]: |
| 126 | return {"status": 200, "already_imported": True, "resumed": True, |
| 127 | "import_id": prior.get("id"), "imported": landed["imported"], |
| 128 | "duplicates": landed["duplicates"], |
| 129 | "note": (f"This file's import had stopped part-way; the " |
| 130 | f"{landed['imported']} missing line(s) were added " |
| 131 | "to it. Its checks are the ones recorded when it " |
| 132 | "was first imported.")} |
| 133 | return {"status": 200, "already_imported": True, "import_id": prior.get("id"), |
| 134 | "imported": 0, "duplicates": 0, |
| 135 | "note": "This exact file was already imported; nothing changed."} |
| 136 | |
| 137 | dates = sorted(l["posted_on"] for l in lines if l.get("posted_on")) |
| 138 | period_start = str(request.get("period_start") or "").strip() or (dates[0] if dates else "") |
| 139 | period_end = str(request.get("period_end") or "").strip() or (dates[-1] if dates else "") |
| 140 | |
| 141 | try: |
| 142 | gates = object_banking.run_gates( |
| 143 | lines, bank_account_id=bank_account_id, |
| 144 | opening_balance_cents=request.get("opening_balance_cents"), |
| 145 | closing_balance_cents=request.get("closing_balance_cents"), |
| 146 | period_start=period_start, base_dir=base, strict=True) |
| 147 | except Exception as exc: |
| 148 | return {"status": 409, |
| 149 | "error": ("Could not read this account's existing statements " |
| 150 | f"and lines ({str(exc)[:160]}), so nothing was " |
| 151 | "imported: an unreadable history would let the " |
| 152 | "same lines go on file twice.")} |
| 153 | |
| 154 | # Deterministic, so two overlapping first imports of one file converge |
| 155 | # on one import row (object_banking.land_import). |
| 156 | import_id = object_banking.import_id_for(bank_account_id, digest) |
| 157 | import_row = { |
| 158 | "id": import_id, |
| 159 | "bank_account_id": bank_account_id, |
| 160 | "profile_id": profile_id, |
| 161 | "source_format": (profile or {}).get("source_format", "csv") or "csv", |
| 162 | "file_hash": digest, |
| 163 | "period_start": period_start, |
| 164 | "period_end": period_end, |
| 165 | # is_present, not `or ""`: a zero balance is a real balance. |
| 166 | "opening_balance_cents": (str(request.get("opening_balance_cents")).strip() |
| 167 | if object_banking.is_present(request.get("opening_balance_cents")) else ""), |
| 168 | "closing_balance_cents": (str(request.get("closing_balance_cents")).strip() |
| 169 | if object_banking.is_present(request.get("closing_balance_cents")) else ""), |
| 170 | "line_count": str(len(lines)), |
| 171 | "status": gates["status"], |
| 172 | "flags": object_banking.flags_json(gates), |
| 173 | "owner_id": user_id, |
| 174 | } |
| 175 | if account.get("entity_id"): |
| 176 | import_row["entity_id"] = account["entity_id"] |
| 177 | # The row, then the lines (bank_lines.import_id is a relation to it). A |
| 178 | # failure after the row raises; re-importing the file resumes it (above). |
| 179 | landed = object_banking.land_import( |
| 180 | import_row, lines, account=account, user_id=user_id, base_dir=base, |
| 181 | actor=ACTOR, known=known) |
| 182 | if landed is None: |
| 183 | return {"status": 200, "already_imported": True, "import_id": import_id, |
| 184 | "imported": 0, "duplicates": 0, |
| 185 | "note": ("This exact file is being imported by another request " |
| 186 | "right now; nothing more changed here.")} |
| 187 | imported, duplicates = landed["imported"], landed["duplicates"] |
| 188 | |
| 189 | return { |
| 190 | "status": 200, |
| 191 | "import_id": import_id, |
| 192 | "imported": imported, |
| 193 | "duplicates": duplicates, |
| 194 | "import_status": gates["status"], |
| 195 | "failed_checks": gates["failed"], |
| 196 | "checks": gates["checks"], |
| 197 | "period": {"start": period_start, "end": period_end}, |
| 198 | } |