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
resolve_bank_line.py · 10.1 KB · 203 lines
| 1 | """action_resolve_bank_line -- book the lines that have no book counterpart. |
| 2 | |
| 3 | POST {line_id, kind, ...} where kind is one of: |
| 4 | |
| 5 | fee a bank charge -> DR bank fees / CR this bank's cash |
| 6 | interest interest earned -> DR this bank's cash / CR interest income |
| 7 | transfer own-account move -> DR/CR between two of your own cash accounts |
| 8 | (payload counterpart_bank_account_id) |
| 9 | nsf a payment bounced -> flips the payment (payload payment_id) and |
| 10 | reverses its journal |
| 11 | timing in transit -> no journal; carried as a reconciling item |
| 12 | other out of scope -> no journal; explained in the memo |
| 13 | |
| 14 | This is where the unmatched tail stops being a mystery. Fees and interest |
| 15 | are entries most small books simply never record, which is exactly why |
| 16 | their cash balance drifts from the bank's until someone gives up on |
| 17 | reconciling at all. Every journal goes through the shared composer |
| 18 | (object_finance.compose_posted_journal) stamped generated_from |
| 19 | "bank_lines/{id}", so resolving twice composes once. |
| 20 | |
| 21 | Accounts come from where they belong: the CASH side is the bank account's |
| 22 | own fin_account_id (per-account, not a global setting), the expense/income |
| 23 | side from app_settings: |
| 24 | reconcile.journal.fees_account |
| 25 | reconcile.journal.interest_account |
| 26 | |
| 27 | NSF note (and a repeat worth counting): event handlers dispatch on the HTTP |
| 28 | write path only, so a storage-level write from an object never reaches |
| 29 | system_books. This verb therefore composes the bounce reversal itself -- |
| 30 | not by duplicating that logic but by calling the same shared composer with |
| 31 | the SAME provenance marker system_books uses ("payments/{id}:bounced"), so |
| 32 | whichever path runs first wins and the other is a no-op. action_apply_count |
| 33 | needed the same treatment; a third instance should buy a daemon pass that |
| 34 | dispatches handlers from the change log rather than a third workaround |
| 35 | (docs/logic-decisions.md #4). |
| 36 | """ |
| 37 | |
| 38 | import os |
| 39 | |
| 40 | import object_finance |
| 41 | import object_records |
| 42 | |
| 43 | ACTOR = "action_resolve_bank_line" |
| 44 | |
| 45 | JOURNAL_KINDS = ("fee", "interest", "transfer", "nsf") |
| 46 | NOTE_KINDS = ("timing", "other") |
| 47 | |
| 48 | |
| 49 | def _base_dir(): |
| 50 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 51 | |
| 52 | |
| 53 | def _setting(base, key, default=""): |
| 54 | try: |
| 55 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 56 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 57 | return row["value"].strip() |
| 58 | except Exception: |
| 59 | pass |
| 60 | return default |
| 61 | |
| 62 | |
| 63 | def _get(base, collection, record_id): |
| 64 | try: |
| 65 | return object_records.get_collection_record(collection, record_id, base_dir=base) |
| 66 | except Exception: |
| 67 | return None |
| 68 | |
| 69 | |
| 70 | def _compose(base, *, marker, date, description, debit, credit, amount, owner_id, |
| 71 | entity_id="", kind="standard"): |
| 72 | return object_finance.compose_posted_journal( |
| 73 | base, generated_from=marker, date=date, description=description, |
| 74 | lines=[{"account_id": debit, "debit_cents": amount, "credit_cents": 0}, |
| 75 | {"account_id": credit, "debit_cents": 0, "credit_cents": amount}], |
| 76 | owner_id=owner_id, entity_id=entity_id, kind=kind, actor=ACTOR) |
| 77 | |
| 78 | |
| 79 | def POST(request): |
| 80 | identity = request.get("_identity") or {} |
| 81 | user_id = identity.get("user_id") or "" |
| 82 | is_admin = "admin" in (identity.get("roles") or []) |
| 83 | if not user_id: |
| 84 | return {"status": 403, "error": "Sign in to resolve a bank line."} |
| 85 | |
| 86 | line_id = str(request.get("line_id") or "").strip() |
| 87 | kind = str(request.get("kind") or "").strip().lower() |
| 88 | if not line_id or kind not in JOURNAL_KINDS + NOTE_KINDS: |
| 89 | return {"status": 400, |
| 90 | "error": f"line_id and kind are required; kind must be one of " |
| 91 | f"{', '.join(JOURNAL_KINDS + NOTE_KINDS)}."} |
| 92 | |
| 93 | base = _base_dir() |
| 94 | line = _get(base, "bank_lines", line_id) |
| 95 | if line is None: |
| 96 | return {"status": 404, "error": f"Bank line not found: {line_id}"} |
| 97 | if line.get("owner_id") and line["owner_id"] != user_id and not is_admin: |
| 98 | return {"status": 403, "error": "That bank line belongs to someone else."} |
| 99 | if line.get("match_status") == "resolved": |
| 100 | return {"status": 409, |
| 101 | "error": f"This line is already resolved as {line.get('resolved_as') or 'other'}."} |
| 102 | |
| 103 | amount = abs(int(line.get("amount_cents") or 0)) |
| 104 | date = str(line.get("posted_on") or "")[:10] |
| 105 | memo = str(request.get("memo") or "").strip() |
| 106 | changes = {"match_status": "resolved", "resolved_as": kind} |
| 107 | journal = None |
| 108 | |
| 109 | if kind in JOURNAL_KINDS: |
| 110 | account = _get(base, "value_accounts", line.get("bank_account_id", "")) or {} |
| 111 | cash = account.get("fin_account_id") or "" |
| 112 | entity_id = line.get("entity_id") or account.get("entity_id") or "" |
| 113 | if not cash: |
| 114 | return {"status": 409, |
| 115 | "error": ("This bank account has no book account set (fin_account_id), " |
| 116 | "so there is nothing to post against. Set it on the bank " |
| 117 | "account first.")} |
| 118 | if amount <= 0: |
| 119 | return {"status": 409, "error": "This line has no amount to book."} |
| 120 | |
| 121 | if kind == "fee": |
| 122 | fees = _setting(base, "reconcile.journal.fees_account") |
| 123 | if not fees: |
| 124 | return {"status": 409, |
| 125 | "error": "Set app_settings reconcile.journal.fees_account first."} |
| 126 | journal = _compose(base, marker=f"bank_lines/{line_id}", date=date, |
| 127 | description=f"Bank fee: {line.get('description') or line_id}" |
| 128 | + (f" ({memo})" if memo else ""), |
| 129 | debit=fees, credit=cash, amount=amount, |
| 130 | owner_id=line.get("owner_id"), entity_id=entity_id) |
| 131 | |
| 132 | elif kind == "interest": |
| 133 | income = _setting(base, "reconcile.journal.interest_account") |
| 134 | if not income: |
| 135 | return {"status": 409, |
| 136 | "error": "Set app_settings reconcile.journal.interest_account first."} |
| 137 | journal = _compose(base, marker=f"bank_lines/{line_id}", date=date, |
| 138 | description=f"Interest earned: {line.get('description') or line_id}", |
| 139 | debit=cash, credit=income, amount=amount, |
| 140 | owner_id=line.get("owner_id"), entity_id=entity_id) |
| 141 | |
| 142 | elif kind == "transfer": |
| 143 | other_id = str(request.get("counterpart_bank_account_id") or "").strip() |
| 144 | counterpart = _get(base, "value_accounts", other_id) if other_id else None |
| 145 | if counterpart is None or not counterpart.get("fin_account_id"): |
| 146 | return {"status": 400, |
| 147 | "error": ("transfer needs counterpart_bank_account_id naming another " |
| 148 | "of your bank accounts that has a book account set.")} |
| 149 | if counterpart.get("owner_id") and counterpart["owner_id"] != user_id and not is_admin: |
| 150 | return {"status": 403, "error": "That counterpart account belongs to someone else."} |
| 151 | other_cash = counterpart["fin_account_id"] |
| 152 | incoming = int(line.get("amount_cents") or 0) > 0 |
| 153 | journal = _compose( |
| 154 | base, marker=f"bank_lines/{line_id}", date=date, |
| 155 | description=f"Transfer between own accounts: {line.get('description') or line_id}", |
| 156 | debit=cash if incoming else other_cash, |
| 157 | credit=other_cash if incoming else cash, |
| 158 | amount=amount, owner_id=line.get("owner_id"), entity_id=entity_id) |
| 159 | |
| 160 | else: # nsf |
| 161 | payment_id = str(request.get("payment_id") |
| 162 | or (line.get("matched_to") or "").split("/")[-1] or "").strip() |
| 163 | payment = _get(base, "payments", payment_id) if payment_id else None |
| 164 | if payment is None: |
| 165 | return {"status": 400, |
| 166 | "error": ("nsf needs payment_id (or a line already matched to a " |
| 167 | "payment) so the right payment can be bounced.")} |
| 168 | if payment.get("status") != "bounced": |
| 169 | try: |
| 170 | object_records.update_collection_record( |
| 171 | "payments", payment_id, {"status": "bounced"}, |
| 172 | base_dir=base, actor=ACTOR) |
| 173 | except Exception as exc: |
| 174 | return {"status": 409, |
| 175 | "error": f"Could not bounce payment {payment_id}: {str(exc)[:160]}"} |
| 176 | basis = _setting(base, "payments.accounting_basis", "cash") |
| 177 | counter = _setting(base, "payments.journal.receivable_account") if basis == "accrual" \ |
| 178 | else _setting(base, "payments.journal.revenue_account") |
| 179 | book_cash = _setting(base, "payments.journal.cash_account") or cash |
| 180 | if not counter: |
| 181 | journal = {"ok": True, "skipped": "payment accounts unconfigured"} |
| 182 | else: |
| 183 | # Same marker system_books stamps, so whichever path composes |
| 184 | # the reversal first, the other is a no-op. |
| 185 | journal = _compose( |
| 186 | base, marker=f"payments/{payment_id}:bounced", date=date, |
| 187 | description=f"Bounce reversal of payment {payment_id} (bank NSF)", |
| 188 | debit=counter, credit=book_cash, amount=abs(int(payment.get("amount_cents") or 0)), |
| 189 | owner_id=payment.get("owner_id"), entity_id=entity_id, kind="reversing") |
| 190 | changes["matched_to"] = f"payments/{payment_id}" |
| 191 | |
| 192 | # memo rides into the journal description (above); the line itself keeps |
| 193 | # the matcher's suggestions block untouched -- what was proposed and why |
| 194 | # stays readable after a human decided otherwise. |
| 195 | try: |
| 196 | object_records.update_collection_record( |
| 197 | "bank_lines", line_id, changes, base_dir=base, actor=ACTOR) |
| 198 | except Exception as exc: |
| 199 | return {"status": 409, "error": f"Could not update the line: {str(exc)[:160]}"} |
| 200 | |
| 201 | return {"status": 200, "line_id": line_id, "resolved_as": kind, |
| 202 | "journal": journal, |
| 203 | "note": ("recorded as a reconciling item; no journal" if kind in NOTE_KINDS else None)} |