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
customer_funds.py · 8.0 KB · 195 lines
1"""Customer funds reconciliation: does what we owe match what we booked?
2
3The report that makes prepaid balances honest. Wallet balances are a
4LIABILITY -- money customers handed over before the service was
5rendered -- and this page answers the one question that liability has to
6survive: does the sum of every wallet equal the credit balance of the
7customer-funds account in the books?
8
9Two facts about the arithmetic, both of which a naive version gets wrong:
10
11**Outstanding holds are added back.** A wallet with a hold in flight
12reports a balance BELOW what its owner is actually owed; the money is
13still theirs until the run settles, and system_wallet_books deliberately
14composes nothing for a hold (a hold is money that was never spent, not a
15debit that got undone). Without adding holds back, this report would
16show a discrepancy every time a template run was in progress -- a
17reconciliation that cries wolf is one nobody reads.
18
19**A liability's natural balance is a CREDIT.** Booked liability is
20credits minus debits, not the trial balance's raw column totals.
21
22Computed server-side, like app-finance's trial_balance page and for the
23same reason: it is a fold across every wallet and every posted journal,
24not one record's detail, so there is no natural collection endpoint for
25the browser to call.
26
27Trust boundary: this is an OPERATOR report. Unlike trial_balance, which
28scopes to the signed-in user's own books, reconciling customer funds is
29inherently cross-owner -- the question is whether OUR books match ALL
30customers' balances. It therefore requires an admin identity and says so
31rather than quietly showing a signed-in customer a fold over everyone's
32money.
33"""
34from __future__ import annotations
35
36import os
37
38_STYLE = """
39table.cf { width: 100%; border-collapse: collapse; margin: 1rem 0; max-width: 40rem; }
40table.cf th, table.cf td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
41table.cf td.num { text-align: right; font-variant-numeric: tabular-nums; }
42table.cf tr.total td { font-weight: 700; border-top: 2px solid var(--line, #38384a); }
43.verdict { padding: 0.6rem 0.9rem; border-radius: 6px; margin: 1rem 0; max-width: 40rem; }
44.verdict.ok { border: 1px solid #2f7d4f; }
45.verdict.off { border: 1px solid #b5493a; }
46"""
47
48DATA_DIR_ENV = "DBBASIC_DATA_DIR"
49
50
51def _data_dir() -> str:
52 import object_records
53 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
54
55
56def _money(minor, currency: str = "USD") -> str:
57 value = int(minor or 0)
58 sign = "-" if value < 0 else ""
59 amount = abs(value)
60 return f"{sign}{currency} {amount // 100}.{amount % 100:02d}"
61
62
63def _esc(value) -> str:
64 return (
65 str(value or "")
66 .replace("&", "&amp;")
67 .replace("<", "&lt;")
68 .replace(">", "&gt;")
69 .replace('"', "&quot;")
70 .replace("'", "&#39;")
71 )
72
73
74def _report(base):
75 import object_billing
76 import object_finance
77 import object_records
78
79 # access: admin-only object (execute is granted to role:admin only)
80 wallets = object_records.read_collection_records("wallets", base_dir=base)
81 # access: admin-only object (execute is granted to role:admin only)
82 entries = object_records.read_collection_records("wallet_entries", base_dir=base)
83
84 balances = []
85 for wallet in wallets:
86 try:
87 balances.append(int(wallet.get("balance_minor") or 0))
88 except (TypeError, ValueError):
89 continue
90
91 funds_account = ""
92 # access: admin-only object (execute is granted to role:admin only)
93 for row in object_records.read_collection_records("app_settings", base_dir=base):
94 if row.get("key") == "billing.journal.customer_funds_account":
95 funds_account = str(row.get("value") or "").strip()
96 break
97
98 debit = credit = 0
99 if funds_account:
100 for row in object_finance.trial_balance(base_dir=base):
101 if row["account_id"] == funds_account:
102 debit = int(row["debit_total_cents"] or 0)
103 credit = int(row["credit_total_cents"] or 0)
104 break
105
106 result = object_billing.customer_funds_reconciliation(
107 balances, debit, credit,
108 outstanding_holds=object_billing.outstanding_holds_minor(entries),
109 )
110 result["wallet_count"] = len(balances)
111 result["funds_account"] = funds_account
112 return result
113
114
115def GET(request):
116 identity = request.get("_identity", {}) or {}
117 user_id = identity.get("user_id")
118 is_admin = bool(identity.get("is_admin")) or "admin" in (identity.get("roles") or [])
119
120 if not user_id:
121 body = ('<p class="hint"><a href="/login?next=/customer-funds">Sign in</a>'
122 " to see this report.</p>")
123 elif not is_admin:
124 body = ('<p class="hint">Customer funds reconciliation is an operator '
125 "report: it folds every customer's balance against the books, "
126 "so it is deliberately not scoped to one signed-in account. "
127 "An admin identity is required.</p>")
128 else:
129 try:
130 result = _report(_data_dir())
131 except Exception as exc:
132 result = None
133 body = ('<p class="hint">Could not compute: '
134 f"{_esc(str(exc)[:200])}</p>")
135 if result is not None:
136 if not result["funds_account"]:
137 verdict = ('<div class="verdict off"><strong>Not configured.</strong> '
138 "Set <code>billing.journal.customer_funds_account</code> in "
139 "app_settings so wallet money reaches the books. Until then "
140 "nothing is booked and there is nothing to reconcile "
141 "against.</div>")
142 elif result["balanced"]:
143 verdict = ('<div class="verdict ok"><strong>Balanced.</strong> '
144 "Every cent owed to a customer is on the books as a "
145 "liability.</div>")
146 else:
147 verdict = ('<div class="verdict off"><strong>Off by '
148 f"{_esc(_money(result['difference_minor']))}.</strong> "
149 "What customers are owed does not match the booked "
150 "liability. Entries created before "
151 "system_wallet_books was installed compose nothing "
152 "retroactively -- that is the usual cause, and it is a "
153 "backfill, not a bug.</div>")
154 body = f"""
155<div class="breadcrumb"><a href="/">Home</a> / Customer Funds</div>
156<div class="pagehead"><h1>Customer Funds Reconciliation</h1></div>
157<p class="hint">Prepaid balances are money owed, not money earned. This
158compares what customers are owed against what the books say we owe.</p>
159{verdict}
160<table class="cf">
161<tbody>
162<tr><td>Wallet balances ({result['wallet_count']} wallets)</td>
163 <td class="num">{_esc(_money(result['wallet_balances_minor']))}</td></tr>
164<tr><td>Outstanding holds (ring-fenced, still the customer's)</td>
165 <td class="num">{_esc(_money(result['outstanding_holds_minor']))}</td></tr>
166<tr class="total"><td>Owed to customers</td>
167 <td class="num">{_esc(_money(result['owed_to_customers_minor']))}</td></tr>
168<tr><td>Booked liability (credits &minus; debits)</td>
169 <td class="num">{_esc(_money(result['booked_liability_minor']))}</td></tr>
170<tr class="total"><td>Difference</td>
171 <td class="num">{_esc(_money(result['difference_minor']))}</td></tr>
172</tbody>
173</table>
174"""
175
176 who = (f"signed in as <strong>{_esc(user_id)}</strong>" if user_id
177 else '<a href="/login?next=/customer-funds">sign in</a>')
178 html = f"""<!doctype html>
179<html lang="en">
180<head>
181<meta charset="utf-8">
182<meta name="viewport" content="width=device-width, initial-scale=1">
183<title>Customer Funds</title>
184<link rel="stylesheet" href="/style">
185<style>{_STYLE}</style>
186</head>
187<body>
188<div class="wrap">
189<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
190{body}
191</div>
192<script src="/nav"></script>
193</body>
194</html>"""
195 return {"content_type": "text/html; charset=utf-8", "body": html}