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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
statements.py · 12.0 KB · 268 lines
1"""site_statements -- the profit & loss (income statement) and balance
2sheet: the two financial statements plan/accounting-coverage-and-
3usability.md's M1 calls the highest-value missing piece, and the two
4reports object_finance.py's own module docstring (and dbbasic-
5package.json's Deferred list) named as the natural next step after
6trial_balance(). Both are FOLDS over posted journals -- the exact same
7data trial_balance() already reads, re-bucketed by account-type sign
8convention -- not a new engine, matching the "pick simpler, report
9which" precedent every report page in this package has followed so far.
10
11Identity posture, copied from packages/app-finance/objects/site/
12trial_balance.py and packages/app-banking/objects/site/reconcile.py
13exactly: this object is public execute, and every byte of financial
14data is gated on a signed-in identity inside. An anonymous visitor gets
15a sign-in prompt and object_finance is never even imported for that
16request -- there is no anonymous or cross-owner path here at all.
17
18Trust boundary, stated explicitly (same as trial_balance.py's own
19docstring): object_finance.profit_and_loss() and .balance_sheet() read
20fin_journals/fin_journal_lines/fin_accounts directly via object_records,
21which is NOT subject to permissions/rules.json's row_filter
22owner_id=$user_id the way the HTTP /collections/* API is. This handler
23passes owner=user_id explicitly on every call, which is what keeps both
24statements scoped to the signed-in visitor's own books -- removing that
25argument would leak every owner's ledger into one report.
26
27Query params: ?start=&end= bound the profit & loss period (either blank
28= unbounded on that side); ?as_of= bounds the balance sheet (blank = every
29posted journal, no upper bound). All three default to blank, i.e. "the
30whole ledger" -- the same "blank means unfiltered" convention
31object_finance.py documents for these functions.
32
33The balance sheet's "balances" / "difference_cents" fields exist to catch
34a broken ledger, and a broken ledger is not a subtle problem: when
35difference_cents != 0, this page renders an unmissable warning banner
36above the statement rather than a balance sheet that quietly fails to
37foot. Money is formatted for display only (whole currency units, 2dp);
38the stored and computed values stay integer cents everywhere else.
39"""
40from __future__ import annotations
41
42import html
43import os
44
45DATA_DIR_ENV = "DBBASIC_DATA_DIR"
46
47_STYLE = """
48table.stmt { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
49table.stmt th, table.stmt td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
50table.stmt th.num, table.stmt td.num { text-align: right; }
51table.stmt tr.subtotal td { font-weight: 700; border-top: 1px solid var(--line, #38384a); }
52table.stmt tr.total td { font-weight: 700; border-top: 2px solid var(--line, #38384a); }
53table.stmt tr.derived td { font-style: italic; }
54.tiles { display: flex; gap: 0.75rem; flex-wrap: wrap; margin: 1rem 0; }
55.tile { background: var(--panel, #1a1a22); border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.6rem 1rem; min-width: 160px; }
56.tile .n { font-size: 1.2rem; font-weight: 600; }
57.tile .l { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }
58h2 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); margin: 1.5rem 0 0.5rem; }
59.hint { color: var(--muted, #999); font-size: 0.85rem; }
60form.filters { display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; margin: 1rem 0; }
61form.filters label { display: flex; flex-direction: column; font-size: 0.75rem; color: var(--muted, #999); gap: 0.25rem; }
62.warnbox { border: 2px solid var(--danger, #ff6b6b); color: var(--danger, #ff6b6b); border-radius: 8px; padding: 0.75rem 1rem; margin: 1rem 0; font-weight: 600; }
63"""
64
65
66def _base_dir() -> str:
67 # Same standalone pattern as trial_balance.py's own _data_dir():
68 # object_finance is a plain library import, not a registered DBBASIC
69 # object, so there is no request payload to read a base_dir override
70 # from -- read the env var directly.
71 import object_records
72 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
73
74
75def _esc(value) -> str:
76 return html.escape(str(value or ""))
77
78
79def _money(cents_value, currency: str = "USD") -> str:
80 """Whole-currency-unit display, 2dp. The stored/computed value stays
81 integer cents everywhere else in object_finance.py and this module.
82 """
83 cents = int(cents_value or 0)
84 sign = "-" if cents < 0 else ""
85 amount = abs(cents)
86 return f"{sign}{currency} {amount // 100:,}.{amount % 100:02d}"
87
88
89def _row_html(row: dict, *, derived: bool = False) -> str:
90 label = row["account_name"] or row["account_id"] or "(unlabeled)"
91 code = f" ({_esc(row['account_code'])})" if row.get("account_code") else ""
92 cls = ' class="derived"' if derived else ""
93 return (
94 f"<tr{cls}>"
95 f"<td>{_esc(label)}{code}</td>"
96 f"<td class=\"num\">{_money(row['amount_cents'])}</td>"
97 "</tr>"
98 )
99
100
101def _section_html(title: str, rows: list[dict], total_cents: int, *, empty_hint: str) -> str:
102 if rows:
103 # The synthetic "Current period earnings" line (empty account_id,
104 # appended last by object_finance.balance_sheet) renders in
105 # italics via the "derived" row class so a reader can tell at a
106 # glance that it is not a stored account -- see that function's
107 # docstring for why the line exists at all.
108 body_rows = "".join(
109 _row_html(row, derived=not row.get("account_id"))
110 for row in rows
111 )
112 else:
113 body_rows = f'<tr><td colspan="2" class="hint">{_esc(empty_hint)}</td></tr>'
114 return f"""
115<table class="stmt">
116<thead><tr><th>{_esc(title)}</th><th class="num">Amount</th></tr></thead>
117<tbody>
118{body_rows}
119<tr class="total"><td>Total {_esc(title.lower())}</td><td class="num">{_money(total_cents)}</td></tr>
120</tbody>
121</table>"""
122
123
124def _profit_and_loss_html(pl: dict) -> str:
125 period = pl["period"]
126 period_label = (
127 f"{_esc(period['start'])} &ndash; {_esc(period['end'])}"
128 if (period["start"] or period["end"])
129 else "all posted journals"
130 )
131 net = pl["net_income_cents"]
132 net_label = "Net income" if net >= 0 else "Net loss"
133 tiles = f"""
134<div class="tiles">
135<div class="tile"><div class="n">{_money(pl['total_income_cents'])}</div><div class="l">Total income</div></div>
136<div class="tile"><div class="n">{_money(pl['total_expenses_cents'])}</div><div class="l">Total expenses</div></div>
137<div class="tile"><div class="n">{_money(net)}</div><div class="l">{_esc(net_label)}</div></div>
138</div>"""
139 return f"""
140<div class="pagehead"><h1>Profit &amp; Loss</h1>
141<p class="hint">Period: {period_label} &middot; posted journals only -- draft journals are excluded.</p></div>
142{tiles}
143{_section_html("Income", pl["income"], pl["total_income_cents"], empty_hint="No posted income this period.")}
144{_section_html("Expenses", pl["expenses"], pl["total_expenses_cents"], empty_hint="No posted expenses this period.")}
145<table class="stmt">
146<tbody>
147<tr class="total"><td>{_esc(net_label)}</td><td class="num">{_money(net)}</td></tr>
148</tbody>
149</table>
150"""
151
152
153def _balance_warning_html(bs: dict) -> str:
154 """Render an unmissable warning when the balance sheet does not
155 balance -- see object_finance.balance_sheet's docstring: this is not
156 a cosmetic imbalance, it means the posted ledger itself is broken
157 (a partial write, a bypass of the balanced-by-construction posting
158 gate), and this page must say so loudly rather than render the
159 statement as if everything is fine.
160 """
161 if bs["balances"]:
162 return ""
163 diff = bs["difference_cents"]
164 direction = "more assets than liabilities + equity" if diff > 0 else "fewer assets than liabilities + equity"
165 return (
166 '<div class="warnbox">'
167 "&#9888; This balance sheet does NOT balance. "
168 f"Assets minus (liabilities + equity) = {_money(diff)} ({_esc(direction)}). "
169 "This indicates the posted journals are unbalanced -- a broken ledger, "
170 "not a rounding artifact -- and should be investigated before this "
171 "statement is relied on."
172 "</div>"
173 )
174
175
176def _balance_sheet_html(bs: dict) -> str:
177 as_of_label = _esc(bs["as_of"]) if bs["as_of"] else "all posted journals (no end date)"
178 status_badge = (
179 '<span class="hint">Assets = Liabilities + Equity &#10003;</span>'
180 if bs["balances"]
181 else '<span class="warnbox" style="display:inline-block;padding:0.2rem 0.6rem;margin:0">Does not balance</span>'
182 )
183 tiles = f"""
184<div class="tiles">
185<div class="tile"><div class="n">{_money(bs['total_assets_cents'])}</div><div class="l">Total assets</div></div>
186<div class="tile"><div class="n">{_money(bs['total_liabilities_cents'])}</div><div class="l">Total liabilities</div></div>
187<div class="tile"><div class="n">{_money(bs['total_equity_cents'])}</div><div class="l">Total equity</div></div>
188<div class="tile"><div class="n">{_money(bs['difference_cents'])}</div><div class="l">Difference</div></div>
189</div>"""
190 return f"""
191<div class="pagehead"><h1>Balance Sheet</h1>
192<p class="hint">As of: {as_of_label} &middot; {status_badge}</p></div>
193{_balance_warning_html(bs)}
194{tiles}
195{_section_html("Assets", bs["assets"], bs["total_assets_cents"], empty_hint="No posted assets.")}
196{_section_html("Liabilities", bs["liabilities"], bs["total_liabilities_cents"], empty_hint="No posted liabilities.")}
197{_section_html("Equity", bs["equity"], bs["total_equity_cents"], empty_hint="No posted equity.")}
198<p class="hint">"Current period earnings" (in Equity) is a DERIVED line -- income minus
199expenses over every posted journal up to the as-of date -- not a stored account. A
200real year-end close would move it into retained earnings; that close (fin_journals
201kind=closing) is reserved but not yet built, so this line is how the equation stays
202honest in the meantime.</p>
203"""
204
205
206def _filters_html(start: str, end: str, as_of: str) -> str:
207 return f"""
208<form class="filters" method="get" action="/statements">
209<label>P&amp;L start<input type="date" name="start" value="{_esc(start)}"></label>
210<label>P&amp;L end<input type="date" name="end" value="{_esc(end)}"></label>
211<label>Balance sheet as of<input type="date" name="as_of" value="{_esc(as_of)}"></label>
212<label>&nbsp;<button type="submit">Apply</button></label>
213</form>"""
214
215
216def GET(request):
217 identity = request.get("_identity") or {}
218 user_id = identity.get("user_id")
219 _logger.info("site_statements served", user_id=user_id or "anonymous")
220
221 if not user_id:
222 body = ('<p class="hint"><a href="/login?next=/statements">Sign in</a> to see '
223 "your profit &amp; loss and balance sheet.</p>")
224 return _page(body)
225
226 import object_finance
227
228 start = str(request.get("start") or "").strip()
229 end = str(request.get("end") or "").strip()
230 as_of = str(request.get("as_of") or "").strip()
231 base = _base_dir()
232
233 pl = object_finance.profit_and_loss(base_dir=base, owner=user_id, start=start, end=end)
234 bs = object_finance.balance_sheet(base_dir=base, owner=user_id, as_of=as_of)
235
236 body = (
237 '<div class="breadcrumb"><a href="/">Home</a> / Statements</div>'
238 + _filters_html(start, end, as_of)
239 + _profit_and_loss_html(pl)
240 + _balance_sheet_html(bs)
241 )
242 return _page(body, user_id=user_id)
243
244
245def _page(body: str, *, user_id: str | None = None) -> dict:
246 who = (
247 f"signed in as <strong>{_esc(user_id)}</strong>"
248 if user_id
249 else '<a href="/login?next=/statements">sign in</a>'
250 )
251 html_out = f"""<!doctype html>
252<html lang="en">
253<head>
254<meta charset="utf-8">
255<meta name="viewport" content="width=device-width, initial-scale=1">
256<title>Financial Statements</title>
257<link rel="stylesheet" href="/style">
258<style>{_STYLE}</style>
259</head>
260<body>
261<div class="wrap">
262<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
263{body}
264</div>
265<script src="/nav"></script>
266</body>
267</html>"""
268 return {"content_type": "text/html; charset=utf-8", "body": html_out}