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
reconcile.py · 14.0 KB · 324 lines
1"""site_reconcile -- the bank reconciliation statement (plan/bank-import-
2reconciliation-spec.md section 6): "bank closing balance (last accepted
3import) vs. book cash balance (fin account), reconciled by: matched total,
4outstanding timing items, unresolved tail. The classic rec statement -- a
5generative view over stored state, no new engine."
6
7Identity posture, same as packages/system-dashboard/objects/system/
8scheduler.py: this object is public execute, and everything is gated on a
9signed-in identity inside. Unlike the scheduler board (admin-only), any
10registered user may see this page -- but ONLY their own accounts and lines.
11The scoping happens twice, deliberately: once here (every read below is
12filtered to owner_id == the caller before it is ever displayed), and again
13in object_banking.reconciliation() itself, which requires the caller to
14name a bank_account_id it has already verified belongs to them -- the same
15trust-boundary posture packages/app-finance/objects/site/trial_balance.py
16documents for object_finance.trial_balance(): these library functions read
17collections directly via object_records, which is NOT subject to
18permissions/rules.json's row_filter the way the HTTP /collections/* API
19is, so the caller (this page) is the only thing standing between one
20owner's ledger and another's.
21
22The account list and the one-account statement are the same page (?account=
23<id> selects one of the caller's own accounts) rather than two objects,
24matching trial_balance.py's "pick simpler, report which" posture -- there
25is no natural second collection endpoint here either; the statement is a
26fold across three collections, not a single record's detail.
27"""
28from __future__ import annotations
29
30import html
31import json
32import os
33
34import object_banking
35import object_books_status
36import object_records
37
38DATA_DIR_ENV = "DBBASIC_DATA_DIR"
39
40
41def _base_dir() -> str:
42 return os.environ.get(DATA_DIR_ENV, "data")
43
44
45def _esc(value) -> str:
46 return html.escape(str(value or ""))
47
48
49def _money(cents_value, currency: str = "USD") -> str:
50 """Whole-currency-unit display, 2dp -- the stored value stays integer
51 cents everywhere else (object_banking.py, bank_lines.amount_cents).
52 None means "unknown" (no import yet, no book account set), which is a
53 materially different thing from a real zero balance and must not
54 print as one.
55 """
56 if cents_value is None:
57 return "—" # em dash: genuinely unknown, not zero
58 cents = int(cents_value)
59 sign = "-" if cents < 0 else ""
60 amount = abs(cents)
61 return f"{sign}{currency} {amount // 100:,}.{amount % 100:02d}"
62
63
64ASSURANCE_LABEL = {
65 "verified": ("Verified", "ok"),
66 "unverified": ("Unverified", "warn"),
67 "flagged": ("Flagged", "bad"),
68}
69
70
71def _assurance_badge(assurance) -> str:
72 if not assurance:
73 return '<span class="badge muted">No imports yet</span>'
74 label, tone = ASSURANCE_LABEL.get(assurance, (assurance, "muted"))
75 return f'<span class="badge {tone}">{_esc(label)}</span>'
76
77
78def _currency_for(base, account):
79 """The denomination code an account is kept in.
80
81 value_accounts names a denomination record rather than carrying a
82 currency string, because the unit decides how an amount is even
83 rendered -- eight places for bitcoin, none for yen (object_money.py).
84 Falls back to USD so a half-configured account still displays.
85 """
86 denomination_id = str(account.get("denomination_id") or "").strip()
87 if not denomination_id:
88 return "USD"
89 try:
90 # access: the currency code of the caller's own account, never shown as a record
91 row = object_records.get_collection_record(
92 "denominations", denomination_id, base_dir=base)
93 except Exception:
94 return "USD"
95 return str(row.get("code") or "USD")
96
97
98def _my_accounts(base, user_id):
99 # access: own rows only: kept to owner_id == the caller's user_id in this expression
100 return [a for a in object_records.read_collection_records("value_accounts", base_dir=base)
101 if a.get("owner_id") == user_id]
102
103
104def _my_lines(base, user_id, bank_account_id):
105 # access: own rows only: kept to owner_id == the caller's user_id in this expression
106 return [l for l in object_records.read_collection_records("bank_lines", base_dir=base)
107 if l.get("bank_account_id") == bank_account_id and l.get("owner_id") == user_id]
108
109
110def _suggestion_summary(row) -> str:
111 raw = row.get("suggestions") or ""
112 if not raw:
113 return ""
114 try:
115 proposals = json.loads(raw)
116 except (ValueError, TypeError):
117 return ""
118 if not proposals:
119 return ""
120 best = proposals[0]
121 return (f"tier {_esc(best.get('tier'))}: {_esc(', '.join(best.get('refs') or []))}"
122 f" &mdash; {_esc(best.get('why'))}")
123
124
125def _line_row_html(row, currency):
126 status = row.get("match_status") or "unmatched"
127 tone = "warn" if status == "suggested" else ""
128 return (
129 "<tr>"
130 f"<td>{_esc(row.get('posted_on'))}</td>"
131 f"<td>{_esc(row.get('description'))}</td>"
132 f"<td class=\"num\">{_money(row.get('amount_cents'), currency)}</td>"
133 f"<td class=\"{tone}\">{_esc(status)}</td>"
134 f"<td>{_suggestion_summary(row)}</td>"
135 "</tr>"
136 )
137
138
139def _timing_row_html(row, currency):
140 return (
141 "<tr>"
142 f"<td>{_esc(row.get('posted_on'))}</td>"
143 f"<td>{_esc(row.get('description'))}</td>"
144 f"<td class=\"num\">{_money(row.get('amount_cents'), currency)}</td>"
145 "</tr>"
146 )
147
148
149def _account_list_html(accounts, selected_id):
150 if not accounts:
151 return '<p class="hint">No bank accounts yet.</p>'
152 items = []
153 for account in accounts:
154 current = " class=\"current\"" if account.get("id") == selected_id else ""
155 items.append(
156 f'<li{current}><a href="/reconcile?account={_esc(account["id"])}">'
157 f'{_esc(account.get("name") or account["id"])}</a>'
158 f' <span class="hint">{_esc(account.get("custodian"))}</span></li>'
159 )
160 return "<ul class=\"accountlist\">" + "".join(items) + "</ul>"
161
162
163def _statement_html(account, result, open_lines, timing_lines, currency="USD"):
164 tiles = f"""
165<div class="tiles">
166<div class="tile"><div class="n">{_money(result['bank_closing_cents'], currency)}</div><div class="l">Bank closing balance</div></div>
167<div class="tile"><div class="n">{_money(result['book_balance_cents'], currency)}</div><div class="l">Book balance</div></div>
168<div class="tile"><div class="n">{_money(result['difference_cents'], currency)}</div><div class="l">Difference</div></div>
169<div class="tile"><div class="n">{_money(result['timing_cents'], currency)}</div><div class="l">Outstanding timing items</div></div>
170</div>"""
171
172 rec_rows = "".join(_line_row_html(row, currency) for row in open_lines) or \
173 '<tr><td colspan="5" class="hint">Nothing open -- every line is matched or resolved.</td></tr>'
174 timing_rows = "".join(_timing_row_html(row, currency) for row in timing_lines) or \
175 '<tr><td colspan="3" class="hint">No outstanding timing items.</td></tr>'
176
177 status_badge = ('<span class="badge ok">&#10003; Reconciled</span>' if result["reconciled"]
178 else '<span class="badge warn">Not yet reconciled</span>')
179
180 statement_date = result.get("bank_statement_date") or "—"
181
182 return f"""
183<div class="pagehead"><h1>{_esc(account.get('name') or account['id'])}</h1>
184<p class="hint">{_esc(account.get('custodian'))} &middot; statement as of {_esc(statement_date)}
185&middot; {_assurance_badge(result['assurance'])}</p></div>
186{tiles}
187<h2>The tie</h2>
188<table class="rec">
189<tbody>
190<tr><td>Bank statement closing balance</td><td class="num">{_money(result['bank_closing_cents'], currency)}</td></tr>
191<tr><td>Book balance (your ledger)</td><td class="num">{_money(result['book_balance_cents'], currency)}</td></tr>
192<tr class="totals"><td>Difference</td><td class="num">{_money(result['difference_cents'], currency)}</td></tr>
193<tr><td>Outstanding timing items (on the statement, not yet booked)</td><td class="num">{_money(result['timing_cents'], currency)}</td></tr>
194<tr class="totals"><td>{status_badge}</td><td class="num">{result['unmatched_count']} unmatched
195&middot; {result['suggested_count']} suggested</td></tr>
196</tbody>
197</table>
198<p class="hint">Reconciled means the difference between the bank and the books is
199fully EXPLAINED by outstanding timing items -- not merely that the numbers
200happen to match. Any unmatched or suggested line below is unexplained slack.</p>
201<h2>Open lines (unmatched &amp; suggested)</h2>
202<table class="rec">
203<thead><tr><th>Posted</th><th>Description</th><th class="num">Amount</th><th>Status</th><th>Suggestion</th></tr></thead>
204<tbody>{rec_rows}</tbody>
205</table>
206<h2>Resolved timing items</h2>
207<table class="rec">
208<thead><tr><th>Posted</th><th>Description</th><th class="num">Amount</th></tr></thead>
209<tbody>{timing_rows}</tbody>
210</table>
211"""
212
213
214_STYLE = """
215.wrap { max-width: 1100px; margin: 0 auto; padding: 1.25rem; }
216table.rec { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
217table.rec th, table.rec td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); vertical-align: top; }
218table.rec td.num, table.rec th.num { text-align: right; }
219table.rec tr.totals td { font-weight: 700; border-top: 2px solid var(--line, #38384a); }
220.tiles { display: flex; gap: 0.75rem; flex-wrap: wrap; margin: 1rem 0; }
221.tile { background: var(--panel, #1a1a22); border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.6rem 1rem; min-width: 160px; }
222.tile .n { font-size: 1.2rem; font-weight: 600; }
223.tile .l { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }
224h2 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); margin: 1.5rem 0 0.5rem; }
225.hint { color: var(--muted, #999); font-size: 0.85rem; }
226.badge { display: inline-block; padding: 0.1rem 0.5rem; border-radius: 999px; font-size: 0.75rem; }
227.badge.ok { background: rgba(82,210,115,0.15); color: var(--positive, #52d273); }
228.badge.warn { background: rgba(241,183,71,0.15); color: var(--warning, #f1b747); }
229.badge.bad { background: rgba(255,107,107,0.15); color: var(--danger, #ff6b6b); }
230.badge.muted { background: rgba(153,153,153,0.15); color: var(--muted, #999); }
231.warn { color: var(--warning, #f1b747); }
232ul.accountlist { list-style: none; padding: 0; margin: 0.5rem 0 1.5rem; }
233ul.accountlist li { padding: 0.4rem 0; border-bottom: 1px solid var(--line, #333); }
234ul.accountlist li.current a { font-weight: 700; }
235"""
236
237
238def _page(body, *, title="Reconcile"):
239 return {
240 "content_type": "text/html; charset=utf-8",
241 "body": f"""<!doctype html>
242<html lang="en">
243<head>
244<meta charset="utf-8">
245<meta name="viewport" content="width=device-width, initial-scale=1">
246<title>{_esc(title)}</title>
247<link rel="stylesheet" href="/style">
248<style>{_STYLE}</style>
249</head>
250<body>
251<script src="/nav"></script>
252<div class="wrap">
253<h1>Reconcile</h1>
254{body}
255</div>
256</body>
257</html>""",
258 }
259
260
261def _books_banner_html(base):
262 """Warn, here of all places, when the ledger side cannot post.
263
264 This page's whole claim is that two independent records agree. If the
265 composers are skipping because their accounts are unmapped, the book
266 side is not a second opinion at all -- it is an empty column, and a
267 difference shown against it means nothing. Better to say so where
268 someone is actively reading the comparison than to leave the reason in
269 a return value nobody sees.
270 """
271 try:
272 status = object_books_status.books_status(base_dir=base)
273 except Exception:
274 return ""
275 if status.get("ready"):
276 return ""
277 items = "".join(
278 f"<li><code>{_esc(p.get('id'))}</code> &mdash; {_esc(p.get('impact'))}</li>"
279 for p in status.get("problems", [])[:6])
280 return (
281 '<div class="warn" style="border:1px solid currentColor;border-radius:8px;'
282 'padding:0.75rem 1rem;margin:0 0 1rem">'
283 f"<strong>The books cannot post yet.</strong> {_esc(status.get('summary'))}"
284 + (f"<ul style='margin:0.5rem 0 0'>{items}</ul>" if items else "")
285 + "<p style='margin:0.5rem 0 0;font-size:0.85rem'>Any difference shown below "
286 "is measured against a ledger that is not receiving entries, so it reflects "
287 "configuration rather than a real discrepancy.</p></div>")
288
289
290def GET(request):
291 identity = request.get("_identity") or {}
292 user_id = identity.get("user_id")
293 if not user_id:
294 return _page('<p class="hint"><a href="/login?next=/reconcile">Sign in</a> to see '
295 "your bank accounts and their reconciliation statements.</p>")
296
297 base = _base_dir()
298 accounts = _my_accounts(base, user_id)
299 requested_id = str(request.get("account") or "").strip()
300 # Owner scoping happens right here: an id the caller does not own is
301 # simply not in `accounts`, so it is silently treated as no selection
302 # rather than looked up directly -- there is no code path from a
303 # guessed/borrowed id to another owner's statement.
304 selected = next((a for a in accounts if a.get("id") == requested_id), None)
305
306 body = _books_banner_html(base) + \
307 f'<h2>Your bank accounts</h2>{_account_list_html(accounts, requested_id)}'
308 if selected is not None:
309 as_of = str(request.get("as_of") or "").strip()
310 result = object_banking.reconciliation(selected["id"], base_dir=base, as_of=as_of)
311 lines = _my_lines(base, user_id, selected["id"])
312 open_lines = sorted(
313 (l for l in lines if (l.get("match_status") or "unmatched") in ("unmatched", "suggested")),
314 key=lambda l: l.get("posted_on") or "")
315 timing_lines = sorted(
316 (l for l in lines if l.get("match_status") == "resolved"
317 and (l.get("resolved_as") or "") == "timing"),
318 key=lambda l: l.get("posted_on") or "")
319 body += _statement_html(selected, result, open_lines, timing_lines,
320 _currency_for(base, selected))
321 elif requested_id:
322 body += '<p class="hint">That account was not found among yours.</p>'
323
324 return _page(body)