Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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