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
trial_balance.py · 6.3 KB · 167 lines
1"""Trial balance report page: the one report v1 of this package ships
2(reconciled against a private predecessor-system audit, not part of this
3repo, whose own reports "filter posted lines" -- profit & loss, balance
4sheet, and cash flow are the same fold shape and are DEFERRED, see
5dbbasic-package.json's description).
6
7Unlike every other page in this package, this page computes its data
8SERVER-SIDE by calling object_finance.trial_balance() directly in
9GET(request), rather than having the browser fetch /collections/*
10records and fold them in JS. That is a deliberate choice ("pick simpler,
11report which" -- this is simpler): a trial balance is a fold over every
12posted journal's lines across the whole owner, not a single record's
13detail, so there is no natural single collection endpoint for the
14browser to call the way invoice_view.py fetches one invoice and its
15lines. Computing it here, once, and rendering plain HTML rows avoids
16needing a bespoke API object (a fifth object in this package) just to
17re-expose the same fold object_finance.py already provides.
18
19Trust boundary, stated explicitly: object_finance.trial_balance() reads
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 (see
23object_finance.trial_balance's own docstring). This handler passes
24owner=user_id explicitly on every call, which is what keeps this report
25scoped to the signed-in visitor's own books -- removing that argument
26would leak every owner's journals into one report. There is no
27anonymous or cross-owner path here at all: an anonymous visitor gets a
28sign-in prompt and object_finance is never even imported for that
29request.
30
31Money is formatted for display only; the stored value stays an integer
32number of cents everywhere else.
33"""
34from __future__ import annotations
35
36import os
37
38_STYLE = """
39table.tb { width: 100%; border-collapse: collapse; margin: 1rem 0; }
40table.tb th, table.tb td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
41table.tb th { font-weight: 600; }
42table.tb td.num, table.tb th.num { text-align: right; }
43table.tb tr.totals td { font-weight: 700; border-top: 2px solid var(--line, #38384a); }
44"""
45
46DATA_DIR_ENV = "DBBASIC_DATA_DIR"
47
48
49def _data_dir() -> str:
50 # Same pattern as packages/app-invoices/objects/system/invoice_totals.py's
51 # own _data_dir(): standalone, reads os.environ directly rather than
52 # depending on object_server for a base_dir. object_finance is a plain
53 # library import (like object_records itself), not a registered
54 # DBBASIC object, so there is no request payload to read a base_dir
55 # override from.
56 import object_records
57 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
58
59
60def _money(cents_value, currency: str = "USD") -> str:
61 cents = int(cents_value or 0)
62 sign = "-" if cents < 0 else ""
63 amount = abs(cents)
64 return f"{sign}{currency} {amount // 100}.{amount % 100:02d}"
65
66
67def _row_html(row: dict) -> str:
68 label = row["account_name"] or row["account_id"]
69 code = f" ({row['account_code']})" if row["account_code"] else ""
70 return (
71 "<tr>"
72 f"<td>{_esc(label)}{_esc(code)}</td>"
73 f"<td>{_esc(row['account_type'])}</td>"
74 f"<td class=\"num\">{_money(row['debit_total_cents'])}</td>"
75 f"<td class=\"num\">{_money(row['credit_total_cents'])}</td>"
76 "</tr>"
77 )
78
79
80def _esc(value) -> str:
81 return (
82 str(value or "")
83 .replace("&", "&amp;")
84 .replace("<", "&lt;")
85 .replace(">", "&gt;")
86 .replace('"', "&quot;")
87 .replace("'", "&#39;")
88 )
89
90
91_KEEPERS = ("admin", "finance", "owner")
92
93
94def _books_owner(identity, user_id):
95 """Whose journals the report folds: the whole business's for the
96 people who keep its books (role:finance, role:owner, admins -- decision
97 5, 2026-11-30), the signed-in user's own otherwise."""
98 roles = {str(r).split(":", 1)[-1] for r in (identity.get("roles") or [])}
99 return None if roles & set(_KEEPERS) else user_id
100
101
102def GET(request):
103 identity = request.get("_identity", {})
104 user_id = identity.get("user_id")
105 _logger.info("site_trial_balance served", user_id=user_id or "anonymous")
106
107 if not user_id:
108 body = '<p class="hint"><a href="/login?next=/trial-balance">Sign in</a> to see your trial balance.</p>'
109 else:
110 import object_finance
111
112 rows = object_finance.trial_balance(base_dir=_data_dir(),
113 owner=_books_owner(identity, user_id))
114 total_debits_cents = sum(row["debit_total_cents"] for row in rows)
115 total_credits_cents = sum(row["credit_total_cents"] for row in rows)
116
117 if rows:
118 rows_html = "".join(_row_html(row) for row in rows)
119 else:
120 rows_html = '<tr><td colspan="4" class="hint">No posted journals yet.</td></tr>'
121
122 totals_html = (
123 '<tr class="totals">'
124 "<td colspan=\"2\">Total</td>"
125 f"<td class=\"num\">{_money(total_debits_cents)}</td>"
126 f"<td class=\"num\">{_money(total_credits_cents)}</td>"
127 "</tr>"
128 )
129
130 body = f"""
131<div class="breadcrumb"><a href="/">Home</a> / Trial Balance</div>
132<div class="pagehead"><h1>Trial Balance</h1></div>
133<p class="hint">Posted journals only -- draft journals are excluded, matching
134the predecessor system's own report semantics (a private predecessor-system
135audit, not part of this repo).</p>
136<table class="tb">
137<thead><tr><th>Account</th><th>Type</th><th class="num">Debit</th><th class="num">Credit</th></tr></thead>
138<tbody>
139{rows_html}
140{totals_html}
141</tbody>
142</table>
143"""
144
145 who = (
146 f"signed in as <strong>{user_id}</strong>"
147 if user_id
148 else '<a href="/login?next=/trial-balance">sign in</a>'
149 )
150 html = f"""<!doctype html>
151<html lang="en">
152<head>
153<meta charset="utf-8">
154<meta name="viewport" content="width=device-width, initial-scale=1">
155<title>Trial Balance</title>
156<link rel="stylesheet" href="/style">
157<style>{_STYLE}</style>
158</head>
159<body>
160<div class="wrap">
161<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
162{body}
163</div>
164<script src="/nav"></script>
165</body>
166</html>"""
167 return {"content_type": "text/html; charset=utf-8", "body": html}