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
record_count.py · 8.1 KB · 191 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
26Structurally this is the same verb as action_apply_count in app-catalog:
27count the thing, compare to the derived book figure, write ONE compensating
28record for the difference. Inventory shrinkage and cash shortage are the
29same event in different denominations, and they book the same way.
30"""
31
32import os
33from datetime import date
34
35import object_finance
36import object_ids
37import object_money
38import object_records
39
40ACTOR = "action_record_count"
41
42COUNTABLE_KINDS = ("cash_box", "metal", "gift_card", "other")
43
44
45def _base_dir():
46 return os.environ.get("DBBASIC_DATA_DIR", "data")
47
48
49def _setting(base, key, default=""):
50 try:
51 for row in object_records.read_collection_records("app_settings", base_dir=base):
52 if row.get("key") == key and str(row.get("value") or "").strip():
53 return row["value"].strip()
54 except Exception:
55 pass
56 return default
57
58
59def _book_balance_minor(base, fin_account_id, as_of):
60 """What the ledger says this account holds, over POSTED journals only.
61
62 Same fold and same posted-only rule the trial balance and the bank
63 reconciliation use -- an asset account, so debits increase it.
64 """
65 if not fin_account_id:
66 return None
67 posted = {j.get("id") for j in
68 object_records.read_collection_records("fin_journals", base_dir=base)
69 if j.get("status") == "posted"
70 and (not as_of or (j.get("date") or "") <= as_of)}
71 debits = credits = 0
72 for line in object_records.read_collection_records("fin_journal_lines", base_dir=base):
73 if line.get("journal_id") not in posted or line.get("account_id") != fin_account_id:
74 continue
75 debits += int(line.get("debit_cents") or 0)
76 credits += int(line.get("credit_cents") or 0)
77 return debits - credits
78
79
80def POST(request):
81 identity = request.get("_identity") or {}
82 user_id = identity.get("user_id") or ""
83 is_admin = "admin" in (identity.get("roles") or [])
84 if not user_id:
85 return {"status": 403, "error": "Sign in to record a count."}
86
87 account_id = str(request.get("value_account_id") or "").strip()
88 if not account_id:
89 return {"status": 400, "error": "value_account_id is required."}
90 try:
91 counted = int(request.get("counted_minor"))
92 except (TypeError, ValueError):
93 return {"status": 400,
94 "error": "counted_minor is required, as a whole number of the "
95 "denomination's smallest unit."}
96 if counted < 0:
97 return {"status": 400, "error": "A count cannot be negative."}
98
99 base = _base_dir()
100 try:
101 account = object_records.get_collection_record(
102 "value_accounts", account_id, base_dir=base)
103 except Exception:
104 return {"status": 404, "error": f"Value account not found: {account_id}"}
105 if account.get("owner_id") and account["owner_id"] != user_id and not is_admin:
106 return {"status": 403, "error": "That account belongs to someone else."}
107
108 if (account.get("verification") or "") != "physical_count":
109 return {"status": 409,
110 "error": (f"This account is verified by "
111 f"{account.get('verification') or 'nothing'}, not by counting. "
112 "Import its statement instead, or change how the account is "
113 "verified if it really is counted by hand.")}
114
115 witnessed_by = str(request.get("witnessed_by") or "").strip()
116 if str(account.get("requires_second_attestor") or "").lower() in ("true", "1", "yes") \
117 and not witnessed_by:
118 return {"status": 409,
119 "error": ("This account requires a witness: a count of it is only "
120 "evidence if a second person attests. Pass witnessed_by.")}
121 if witnessed_by and witnessed_by == user_id:
122 return {"status": 409,
123 "error": "The witness must be someone other than the person counting."}
124
125 counted_on = str(request.get("counted_on") or "").strip() or date.today().isoformat()
126 fin_account_id = account.get("fin_account_id") or ""
127 book_balance = _book_balance_minor(base, fin_account_id, counted_on)
128 variance = None if book_balance is None else counted - book_balance
129
130 count_id = object_ids.new_uuid4()
131 journal = None
132 journal_id = ""
133 if variance:
134 over_short = _setting(base, "reconcile.journal.cash_over_short_account")
135 if not over_short:
136 return {"status": 409,
137 "error": ("A variance needs somewhere to go: set app_settings "
138 "reconcile.journal.cash_over_short_account first. "
139 "Cash over/short is a real expense and must not be "
140 "silently dropped.")}
141 amount = abs(variance)
142 shortage = variance < 0
143 journal = object_finance.compose_posted_journal(
144 base,
145 generated_from=f"value_account_counts/{count_id}",
146 date=counted_on,
147 description=(f"Cash {'shortage' if shortage else 'overage'} on "
148 f"{account.get('name') or account_id} ({counted_on})"),
149 lines=[
150 {"account_id": over_short if shortage else fin_account_id,
151 "debit_cents": amount, "credit_cents": 0},
152 {"account_id": fin_account_id if shortage else over_short,
153 "debit_cents": 0, "credit_cents": amount},
154 ],
155 owner_id=account.get("owner_id") or user_id,
156 entity_id=account.get("entity_id", ""),
157 actor=ACTOR,
158 )
159 journal_id = journal.get("journal_id", "") if journal.get("ok") else ""
160
161 record = {
162 "id": count_id,
163 "value_account_id": account_id,
164 "counted_on": counted_on,
165 "counted_minor": str(counted),
166 "book_balance_minor": "" if book_balance is None else str(book_balance),
167 "variance_minor": "" if variance is None else str(variance),
168 "counted_by": user_id,
169 "witnessed_by": witnessed_by,
170 "journal_id": journal_id,
171 "notes": str(request.get("notes") or "").strip(),
172 "owner_id": account.get("owner_id") or user_id,
173 }
174 if account.get("entity_id"):
175 record["entity_id"] = account["entity_id"]
176 object_records.create_collection_record(
177 "value_account_counts", record, base_dir=base, actor=ACTOR)
178
179 return {
180 "status": 200,
181 "count_id": count_id,
182 "counted_minor": counted,
183 "book_balance_minor": book_balance,
184 "variance_minor": variance,
185 "journal": journal,
186 "assurance": object_money.assurance_for("physical_count",
187 witnessed=bool(witnessed_by)),
188 "note": ("counted balance agrees with the books" if variance == 0 else
189 "no book account set, so no variance could be computed"
190 if variance is None else None),
191 }