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
record_count.py · 17.8 KB · 385 lines
1"""action_record_count -- reconcile the accounts nobody sends a statement for.
2
3POST {value_account_id, counted_minor, counted_on?, witnessed_by?, notes?}
4
5A till, a petty-cash box, a safe: real money, and no third party will ever
6send you a statement about it. The only evidence available is that someone
7counted it. That makes this the weakest reconciliation in the system and
8the one most worth doing honestly, because a drawer is where a slow leak
9hides best.
10
11Three things follow from that, and they are the whole object:
12
131. **The count is evidence, so it is a record** -- who counted, who
14 witnessed, what the books said at that moment (stamped, #1), and the
15 variance. Append-only: a count is an observation, not a figure to
16 revise (#8).
172. **A witness can be required.** value_accounts.requires_second_attestor
18 refuses a self-certified count outright, because the person counting the
19 till is usually the person who could take from it. This is the oldest
20 control in retail and it is one field.
213. **A variance composes a real journal.** Cash over/short is an expense a
22 business genuinely incurs; booking it keeps the ledger equal to reality
23 and makes the leak visible as a number that accumulates. Pretending the
24 drawer always balances is how years go by.
25
26The count row is written FIRST, the variance journal second, and the link
27between them last. Until 2026-11-28 the journal came first: when the count
28write then failed, a posted cash-over/short journal stood in the books with
29no count to explain it, and a retry saw variance 0 and never linked it
30(bug-reports/2026-11-28-06-14-50-CST-record-count-orphan-journal). Now:
31
32- count write fails -> nothing was written; the error says so.
33- journal fails -> the count (a real observation) stays, journal_id blank,
34 and the error says the variance was NOT booked. The books still say what
35 they said, so the next count sees the same variance and books it once.
36- link write fails -> the journal is posted and its generated_from
37 (value_account_counts/{count_id}) names the count, so nothing is orphaned;
38 the answer carries a warning.
39
40Two counts against the same books book one variance. A double click, or
41two people counting one drawer at once, used to read the same book balance
42and BOTH post the shortage, so a 2.50 short till lost 5.00 in the books.
43A count that books a variance now stamps `book_basis` -- a fingerprint of
44the posted lines its book balance was folded from -- and
45value_account_counts declares it unique per account, inside the write
46lock. The second count against the same books is refused (409) before it
47books anything; once the first journal posts, the books have moved and a
48recount gets a new basis. A count whose journal then fails clears its
49basis, so the recount that books it is not refused.
50
51A named witness is a claim until the witness confirms it (2026-12-02).
52`witnessed_by` used to be any text: a closer could pocket cash, type a
53colleague's name, and the books showed a witnessed shortage that wrongly
54implicated the colleague. Now:
55
56- `witnessed_by` is the user id of another ACTIVE user (object_identity,
57 the same users the sign-in reads; ids only -- a display name or email is
58 not looked up). An unknown, inactive or same-person witness (the counter's
59 own id, display name or email), or one from another identity account
60 than the counter's, gets ONE refusal that does not say which it was, and
61 nothing is recorded.
62- The count is still recorded and its variance still booked at once: the
63 platform records and warns, it does not hold up the books. But the row
64 says `witness_status: named`, the answer rates it as self-certified
65 ("weak"), and an account that requires a second attestor reports that
66 requirement UNMET -- until the named user, signed in as themselves,
67 states the same figure through action_confirm_count.
68- Accounts that do not require a witness, counted without one, behave as
69 before.
70
71Structurally this is the same verb as action_apply_count in app-catalog:
72count the thing, compare to the derived book figure, write ONE compensating
73record for the difference. Inventory shrinkage and cash shortage are the
74same event in different denominations, and they book the same way.
75"""
76
77import hashlib
78import os
79from datetime import date
80
81import object_finance
82import object_access
83import object_identity
84import object_ids
85import object_money
86import object_records
87
88ACTOR = "action_record_count"
89
90COUNTABLE_KINDS = ("cash_box", "metal", "gift_card", "other")
91
92
93def _base_dir():
94 return os.environ.get("DBBASIC_DATA_DIR", "data")
95
96
97def _setting(base, key, default=""):
98 try:
99 # access: box configuration
100 for row in object_records.read_collection_records("app_settings", base_dir=base):
101 if row.get("key") == key and str(row.get("value") or "").strip():
102 return row["value"].strip()
103 except Exception:
104 pass
105 return default
106
107
108def _book_balance_minor(base, fin_account_id, as_of):
109 """What the ledger says this account holds, over POSTED journals only.
110
111 Same fold and same posted-only rule the trial balance and the bank
112 reconciliation use -- an asset account, so debits increase it.
113 """
114 return _book_state(base, fin_account_id, as_of)[0]
115
116
117def _book_state(base, fin_account_id, as_of):
118 """(balance, basis): the balance, and a fingerprint of exactly which
119 posted lines it was folded from -- the claim key that stops two counts
120 against the same books from both booking the variance."""
121 if not fin_account_id:
122 return None, ""
123 # access: folds the book account of the value account read through Access above
124 posted = {j.get("id") for j in
125 object_records.read_collection_records("fin_journals", base_dir=base)
126 if j.get("status") == "posted"
127 and (not as_of or (j.get("date") or "") <= as_of)}
128 debits = credits = 0
129 folded = []
130 # access: folds the book account of the value account read through Access above
131 for line in object_records.read_collection_records("fin_journal_lines", base_dir=base):
132 if line.get("journal_id") not in posted or line.get("account_id") != fin_account_id:
133 continue
134 debits += int(line.get("debit_cents") or 0)
135 credits += int(line.get("credit_cents") or 0)
136 folded.append(str(line.get("id") or ""))
137 basis = hashlib.sha256(
138 f"{fin_account_id}|{as_of}|{','.join(sorted(folded))}".encode()).hexdigest()
139 return debits - credits, basis
140
141
142def _release_basis(base, count_id):
143 """A count whose variance was NOT booked gives up its claim on the
144 books, so the recount that books it is not refused as a duplicate."""
145 try:
146 # access: system write for the account read through Access above
147 object_records.update_collection_record(
148 "value_account_counts", count_id, {"book_basis": ""},
149 base_dir=base, actor=ACTOR, preserve_read_only=True)
150 except Exception:
151 pass
152
153
154WITNESS_REFUSED = ("witnessed_by must be the user id of another active user "
155 "who signs in to this server, not the person counting. "
156 "Nothing was recorded.")
157
158
159def _requires_witness(account):
160 return str(account.get("requires_second_attestor") or "").lower() in ("true", "1", "yes")
161
162
163def _witness_refusal(base, identity, witnessed_by):
164 """None when `witnessed_by` names another active user, else (status, error).
165
166 Matched by user id only, exactly. Every reason a name is refused --
167 nobody by that id, a disabled or pending user, the counter by id or by
168 their own display name or email, a user in another identity account --
169 gets the same answer, so the refusal says nothing about who exists
170 beyond what a signed-in user can already find out.
171 """
172 caller = str(identity.get("user_id") or "")
173 if witnessed_by.casefold() == caller.casefold():
174 return 409, WITNESS_REFUSED
175 try:
176 witness = object_identity.get_user(witnessed_by, base_dir=base)
177 except (LookupError, ValueError):
178 return 409, WITNESS_REFUSED
179 except OSError:
180 return 503, ("The user list could not be read, so the witness cannot be "
181 "checked. Nothing was recorded; try again.")
182 if witness.get("status") != object_identity.ACTIVE_STATUS:
183 return 409, WITNESS_REFUSED
184 if str(witness.get("user_id") or "") == caller:
185 return 409, WITNESS_REFUSED
186 try:
187 me = object_identity.get_user(caller, base_dir=base)
188 except (LookupError, ValueError, OSError):
189 me = {}
190 # The counter's own name in the witness box: refused even when it
191 # happens to be somebody else's user id.
192 mine = {str(me.get(k) or "").strip().casefold() for k in ("display_name", "email")}
193 if witnessed_by.casefold() in mine - {""}:
194 return 409, WITNESS_REFUSED
195 caller_account = str(identity.get("account_id") or me.get("account_id") or "")
196 if caller_account and str(witness.get("account_id") or "") != caller_account:
197 return 409, WITNESS_REFUSED
198 return None
199
200
201def witness_summary(account, row):
202 """What the count's witness evidence is worth now: the assurance and,
203 for an account that requires a second attestor, whether that is met."""
204 status = str(row.get("witness_status") or "")
205 confirmed = status == "confirmed"
206 required = _requires_witness(account)
207 assurance = object_money.assurance_for("physical_count", witnessed=confirmed)
208 if not row.get("witnessed_by"):
209 return {"assurance": assurance} # self-certified, as it always was
210 return {
211 "assurance": assurance,
212 "witness": {
213 "user_id": str(row.get("witnessed_by") or ""),
214 "status": status or "none",
215 "second_attestor_required": required,
216 "second_attestor_met": confirmed if required else None,
217 },
218 }
219
220
221def POST(request):
222 identity = request.get("_identity") or {}
223 user_id = identity.get("user_id") or ""
224 if not user_id:
225 return {"status": 403, "error": "Sign in to record a count."}
226
227 account_id = str(request.get("value_account_id") or "").strip()
228 if not account_id:
229 return {"status": 400, "error": "value_account_id is required."}
230 try:
231 counted = int(request.get("counted_minor"))
232 except (TypeError, ValueError):
233 return {"status": 400,
234 "error": "counted_minor is required, as a whole number of the "
235 "denomination's smallest unit."}
236 if counted < 0:
237 return {"status": 400, "error": "A count cannot be negative."}
238
239 base = _base_dir()
240 # The account is the unit of access: asked of the permission engine (the
241 # same answer the value_accounts API gives), not "has an owner who is not
242 # me", which let anybody act on an account that had no owner. A refused
243 # account reads exactly like a missing one.
244 account = object_access.Access(identity, base_dir=base).get(
245 "value_accounts", account_id, action=object_access.UPDATE)
246 if account is None:
247 return {"status": 404, "error": f"Value account not found: {account_id}"}
248
249 if (account.get("verification") or "") != "physical_count":
250 return {"status": 409,
251 "error": (f"This account is verified by "
252 f"{account.get('verification') or 'nothing'}, not by counting. "
253 "Import its statement instead, or change how the account is "
254 "verified if it really is counted by hand.")}
255
256 witnessed_by = str(request.get("witnessed_by") or "").strip()
257 if _requires_witness(account) and not witnessed_by:
258 return {"status": 409,
259 "error": ("This account requires a witness: a count of it is only "
260 "evidence if a second person attests. Pass witnessed_by, "
261 "the user id of the second person; they then confirm the "
262 "figure from their own sign-in.")}
263 if witnessed_by:
264 refused = _witness_refusal(base, identity, witnessed_by)
265 if refused:
266 return {"status": refused[0], "error": refused[1]}
267
268 counted_on = str(request.get("counted_on") or "").strip() or date.today().isoformat()
269 fin_account_id = account.get("fin_account_id") or ""
270 book_balance, book_basis = _book_state(base, fin_account_id, counted_on)
271 variance = None if book_balance is None else counted - book_balance
272
273 over_short = ""
274 if variance:
275 over_short = _setting(base, "reconcile.journal.cash_over_short_account")
276 if not over_short:
277 return {"status": 409,
278 "error": ("A variance needs somewhere to go: set app_settings "
279 "reconcile.journal.cash_over_short_account first. "
280 "Cash over/short is a real expense and must not be "
281 "silently dropped.")}
282
283 count_id = object_ids.new_uuid4()
284 record = {
285 "id": count_id,
286 "value_account_id": account_id,
287 "counted_on": counted_on,
288 "counted_minor": str(counted),
289 "book_balance_minor": "" if book_balance is None else str(book_balance),
290 "variance_minor": "" if variance is None else str(variance),
291 "counted_by": user_id,
292 "witnessed_by": witnessed_by,
293 # Named is not witnessed: only the named user's own confirmation
294 # (action_confirm_count) lifts the count out of self-certification.
295 "witness_status": "named" if witnessed_by else "",
296 "journal_id": "",
297 # Only a count that books something claims the books it read.
298 "book_basis": book_basis if variance else "",
299 "notes": str(request.get("notes") or "").strip(),
300 "owner_id": account.get("owner_id") or user_id,
301 }
302 if account.get("entity_id"):
303 record["entity_id"] = account["entity_id"]
304 # The evidence first: if this write fails, nothing has been booked.
305 try:
306 # access: system write for the account read through Access above
307 object_records.create_collection_record(
308 "value_account_counts", record, base_dir=base, actor=ACTOR,
309 preserve_read_only=True)
310 except object_records.UniqueConstraintError as exc:
311 return {"status": 409, "count_id": exc.existing_id,
312 "error": ("Another count of this account was just recorded "
313 f"against the same books ({exc.existing_id}) and is "
314 f"booking the same variance of {variance}. Nothing "
315 "was booked for this one; count again if the drawer "
316 "still disagrees.")}
317
318 journal = None
319 journal_id = ""
320 warning = None
321 if variance:
322 amount = abs(variance)
323 shortage = variance < 0
324 try:
325 journal = object_finance.compose_posted_journal(
326 base,
327 generated_from=f"value_account_counts/{count_id}",
328 date=counted_on,
329 description=(f"Cash {'shortage' if shortage else 'overage'} on "
330 f"{account.get('name') or account_id} ({counted_on})"),
331 lines=[
332 {"account_id": over_short if shortage else fin_account_id,
333 "debit_cents": amount, "credit_cents": 0},
334 {"account_id": fin_account_id if shortage else over_short,
335 "debit_cents": 0, "credit_cents": amount},
336 ],
337 owner_id=account.get("owner_id") or user_id,
338 entity_id=account.get("entity_id", ""),
339 actor=ACTOR,
340 )
341 except Exception as exc:
342 _release_basis(base, count_id)
343 return {"status": 500, "count_id": count_id,
344 "error": (f"The count was recorded ({count_id}) but its "
345 f"variance of {variance} was NOT booked: "
346 f"{str(exc)[:200]}. The books are unchanged, so "
347 "the next count will show the same variance and "
348 "book it.")}
349 journal_id = journal.get("journal_id", "") if journal.get("ok") else ""
350 if not journal_id:
351 # compose refused (unusable amounts) or skipped (books unreadable):
352 # the variance is not in the books, and a 200 would say it was.
353 _release_basis(base, count_id)
354 return {"status": 409, "count_id": count_id, "journal": journal,
355 "error": (f"The count was recorded ({count_id}) but its "
356 f"variance of {variance} was NOT booked: "
357 f"{journal.get('error') or journal.get('skipped')}.")}
358 if journal_id:
359 try:
360 # access: system write for the account read through Access above
361 object_records.update_collection_record(
362 "value_account_counts", count_id, {"journal_id": journal_id},
363 base_dir=base, actor=ACTOR)
364 except Exception as exc:
365 warning = (f"journal {journal_id} was booked, but linking it to "
366 f"the count failed ({str(exc)[:120]}); the journal's "
367 f"generated_from still names this count")
368
369 return {
370 "status": 200,
371 "count_id": count_id,
372 "counted_minor": counted,
373 "book_balance_minor": book_balance,
374 "variance_minor": variance,
375 "journal": journal,
376 **witness_summary(account, record),
377 **({"witness_note": (f"{witnessed_by} is named as witness but has not "
378 "confirmed: until they sign in and confirm the same "
379 "figure (action_confirm_count), this count is "
380 "self-certified.")} if witnessed_by else {}),
381 "note": ("counted balance agrees with the books" if variance == 0 else
382 "no book account set, so no variance could be computed"
383 if variance is None else None),
384 **({"warning": warning} if warning else {}),
385 }