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

0 downloads

dbbasic-object-server/tests/test_expenses.py
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
test_expenses.py · 16.8 KB · 396 lines
1"""Expenses: the materials half of time and materials.
2
3An expense is an accounting fact first and a billable item second, and
4almost every property here follows from that ordering. Unbillable
5spending still posts. Who paid decides which account is credited, not a
6note on a report. And approval -- by somebody other than the spender --
7is the single event that both composes the journal and fixes the price
8the client will see.
9"""
10
11import pathlib
12
13from conftest import stage_collection
14
15import object_execution
16import object_rates
17import object_records
18import python_object_runtime
19
20REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
21PACKAGES = REPO_ROOT / "packages"
22FINANCE_OBJECTS = PACKAGES / "app-finance" / "objects"
23INVOICE_OBJECTS = PACKAGES / "app-invoices" / "objects"
24RUNTIME = python_object_runtime.PythonObjectRuntime()
25
26ACCOUNTS = (
27 ("acct-travel", "Travel", "expense"),
28 ("acct-card", "Company Card Clearing", "liability"),
29 ("acct-owed", "Owed To Staff", "liability"),
30)
31
32SETTINGS = (
33 ("expenses.journal.expense_account", "acct-travel"),
34 ("expenses.journal.paid_account", "acct-card"),
35 ("expenses.journal.reimbursable_account", "acct-owed"),
36)
37
38
39def setup_env(tmp_path, monkeypatch, *, settings=SETTINGS):
40 data_dir = tmp_path / "data"
41 for pkg, name in (("app-finance", "expenses"), ("app-finance", "fin_accounts"),
42 ("app-finance", "fin_journals"), ("app-finance", "fin_journal_lines"),
43 ("app-projects", "projects"),
44 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
45 ("app-timers", "time_logs"), ("app-timers", "rate_cards")):
46 stage_collection(data_dir, pkg, name)
47 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
48 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
49 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
50
51 object_records.create_collection_record(
52 "projects", {"id": "proj-acme", "name": "Acme Rebuild", "owner_id": "boss"},
53 base_dir=data_dir)
54 for account_id, name, kind in ACCOUNTS:
55 object_records.create_collection_record(
56 "fin_accounts",
57 {"id": account_id, "name": name, "account_type": kind,
58 "code": account_id[-4:], "is_active": "true", "owner_id": "boss"},
59 base_dir=data_dir)
60 return data_dir
61
62
63def spend(data_dir, expense_id, cents=25000, **fields):
64 record = {"id": expense_id, "description": "Flight to Chicago",
65 "incurred_on": "2026-06-15", "amount_cents": str(cents),
66 "currency": "USD", "project_id": "proj-acme", "paid_by": "company",
67 "billable": "true", "markup_bps": "0", "status": "draft",
68 "owner_id": "dana"}
69 record.update({k: str(v) for k, v in fields.items()})
70 return object_records.create_collection_record(
71 "expenses", record, base_dir=data_dir)
72
73
74def hook(record, *, existing=None, changes=None, actor="boss", action="update"):
75 return object_execution.execute_object(
76 RUNTIME,
77 object_execution.ObjectExecutionRequest(
78 "hook_expenses", method="BEFORE_WRITE",
79 payload={"action": action, "collection": "expenses",
80 "record": record, "existing": existing,
81 "changes": changes if changes is not None else dict(record),
82 "subject": {"user_id": actor, "roles": ["manager"]}}),
83 roots=[FINANCE_OBJECTS]).result
84
85
86def approve(data_dir, expense_id, *, actor="boss"):
87 existing = object_records.get_collection_record("expenses", expense_id,
88 base_dir=data_dir)
89 outcome = hook({"status": "approved"}, existing=existing,
90 changes={"status": "approved"}, actor=actor)
91 if outcome and outcome.get("error"):
92 return outcome
93 patch = (outcome or {}).get("record") or {"status": "approved"}
94 object_records.update_collection_record("expenses", expense_id, patch,
95 base_dir=data_dir, actor=actor)
96 return {"ok": True}
97
98
99def post_books(data_dir, expense_id):
100 expense = object_records.get_collection_record("expenses", expense_id,
101 base_dir=data_dir)
102 return object_execution.execute_object(
103 RUNTIME,
104 object_execution.ObjectExecutionRequest(
105 "system_expense_books", method="POST",
106 payload={"collection": "expenses", "record": expense}),
107 roots=[FINANCE_OBJECTS]).result
108
109
110def generate(payload=None):
111 return object_execution.execute_object(
112 RUNTIME,
113 object_execution.ObjectExecutionRequest(
114 "action_generate_tm_invoice", method="POST", payload=payload or {}),
115 roots=[INVOICE_OBJECTS]).result
116
117
118def expense(data_dir, expense_id):
119 return object_records.get_collection_record("expenses", expense_id,
120 base_dir=data_dir)
121
122
123def journal_lines(data_dir):
124 return object_records.read_collection_records("fin_journal_lines",
125 base_dir=data_dir)
126
127
128def lines(data_dir):
129 return object_records.read_collection_records("invoice_lines", base_dir=data_dir)
130
131
132# --- markup ------------------------------------------------------------------
133
134def test_markup_is_basis_points_rounded_once():
135 assert object_rates.with_markup(10000, 0) == 10000 # at cost
136 assert object_rates.with_markup(10000, 1500) == 11500 # 15%
137 # 3333 at 15% is 3832.95 -> 3833, rounded once on the whole amount.
138 assert object_rates.with_markup(3333, 1500) == 3833
139
140
141# --- the gate ----------------------------------------------------------------
142
143def test_nobody_approves_their_own_spending(tmp_path, monkeypatch):
144 data_dir = setup_env(tmp_path, monkeypatch)
145 spend(data_dir, "e1", status="submitted")
146 outcome = approve(data_dir, "e1", actor="dana")
147 assert outcome["status"] == 403 and "not an approval" in outcome["error"]
148
149
150def test_unbillable_spending_is_still_approved(tmp_path, monkeypatch):
151 """It still left the bank account. Refusing to approve it would leave
152 real money unrecorded -- a worse failure than an unbilled hour."""
153 data_dir = setup_env(tmp_path, monkeypatch)
154 spend(data_dir, "e1", status="submitted", billable="false")
155 assert approve(data_dir, "e1")["ok"]
156
157 row = expense(data_dir, "e1")
158 assert row["status"] == "approved"
159 assert row["billable_amount_cents"] == "0" # approved, never billable
160
161
162def test_approval_stamps_the_markup_that_applied_then(tmp_path, monkeypatch):
163 data_dir = setup_env(tmp_path, monkeypatch)
164 spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted")
165 approve(data_dir, "e1")
166
167 row = expense(data_dir, "e1")
168 assert row["markup_bps"] == "1500"
169 assert row["billable_amount_cents"] == "11500"
170 assert row["approved_by"] == "boss" and row["approved_at"]
171
172
173def test_the_default_markup_comes_from_settings(tmp_path, monkeypatch):
174 data_dir = setup_env(tmp_path, monkeypatch,
175 settings=SETTINGS + (("billing.expense_markup_bps", "1000"),))
176 spend(data_dir, "e1", cents=10000, markup_bps="", status="submitted")
177 approve(data_dir, "e1")
178 assert expense(data_dir, "e1")["billable_amount_cents"] == "11000"
179
180
181def test_an_expense_needs_an_amount(tmp_path, monkeypatch):
182 setup_env(tmp_path, monkeypatch)
183 outcome = hook({"description": "Nothing", "amount_cents": "0",
184 "owner_id": "dana"}, action="create")
185 assert outcome["status"] == 400 and "negative spend" in outcome["error"]
186
187
188def test_submitting_needs_the_date_the_money_was_spent(tmp_path, monkeypatch):
189 """Schema `required` already blocks this on the public write path;
190 the gate matters for rows a trusted server-side writer put there,
191 which skip validation by design."""
192 setup_env(tmp_path, monkeypatch)
193 outcome = hook({"status": "submitted"},
194 existing={"id": "e1", "amount_cents": "25000",
195 "incurred_on": "", "owner_id": "dana",
196 "status": "draft"},
197 changes={"status": "submitted"}, actor="dana")
198 assert outcome["status"] == 400
199 assert "period its journal belongs to" in outcome["error"]
200
201
202def test_an_explicit_zero_markup_beats_the_house_policy(tmp_path, monkeypatch):
203 """Blank means 'whatever the house does'; 0 means 'this one at cost'.
204 A schema default would have collapsed the two."""
205 data_dir = setup_env(tmp_path, monkeypatch,
206 settings=SETTINGS + (("billing.expense_markup_bps", "1000"),))
207 spend(data_dir, "e1", cents=10000, markup_bps=0, status="submitted")
208 approve(data_dir, "e1")
209 assert expense(data_dir, "e1")["billable_amount_cents"] == "10000"
210
211
212def test_approved_spending_is_frozen(tmp_path, monkeypatch):
213 data_dir = setup_env(tmp_path, monkeypatch)
214 spend(data_dir, "e1", status="submitted")
215 approve(data_dir, "e1")
216
217 existing = expense(data_dir, "e1")
218 outcome = hook({"amount_cents": "99999"}, existing=existing,
219 changes={"amount_cents": "99999"})
220 assert outcome["status"] == 409 and "settled" in outcome["error"]
221
222
223# --- the books ----------------------------------------------------------------
224
225def test_a_company_paid_expense_credits_the_card(tmp_path, monkeypatch):
226 data_dir = setup_env(tmp_path, monkeypatch)
227 spend(data_dir, "e1", status="submitted")
228 approve(data_dir, "e1")
229
230 result = post_books(data_dir, "e1")
231 assert result.get("journal_id") and result.get("posted")
232
233 rows = {r["account_id"]: r for r in journal_lines(data_dir)}
234 assert rows["acct-travel"]["debit_cents"] == "25000"
235 assert rows["acct-card"]["credit_cents"] == "25000"
236
237
238def test_a_personally_paid_expense_credits_what_the_business_owes(
239 tmp_path, monkeypatch):
240 """Booking somebody's own card against company cash claims money left
241 an account it never left, and leaves them chasing a reimbursement the
242 ledger has no record of."""
243 data_dir = setup_env(tmp_path, monkeypatch)
244 spend(data_dir, "e1", status="submitted", paid_by="personal")
245 approve(data_dir, "e1")
246 post_books(data_dir, "e1")
247
248 rows = {r["account_id"]: r for r in journal_lines(data_dir)}
249 assert rows["acct-travel"]["debit_cents"] == "25000"
250 assert rows["acct-owed"]["credit_cents"] == "25000"
251 assert "acct-card" not in rows
252 assert "reimbursable to dana" in rows["acct-owed"]["memo"]
253
254
255def test_an_unapproved_expense_posts_nothing(tmp_path, monkeypatch):
256 data_dir = setup_env(tmp_path, monkeypatch)
257 spend(data_dir, "e1", status="submitted")
258 assert post_books(data_dir, "e1")["skipped"] == "not approved"
259 assert journal_lines(data_dir) == []
260
261
262def test_posting_twice_composes_one_journal(tmp_path, monkeypatch):
263 data_dir = setup_env(tmp_path, monkeypatch)
264 spend(data_dir, "e1", status="submitted")
265 approve(data_dir, "e1")
266 post_books(data_dir, "e1")
267 again = post_books(data_dir, "e1")
268 assert "already composed" in again["skipped"]
269 assert len(journal_lines(data_dir)) == 2 # the one balanced pair
270
271
272def test_unconfigured_books_skip_rather_than_block_the_expense(
273 tmp_path, monkeypatch):
274 """Recording that you bought a plane ticket must not require somebody
275 to have built a chart of accounts first."""
276 data_dir = setup_env(tmp_path, monkeypatch, settings=())
277 spend(data_dir, "e1", status="submitted")
278 assert approve(data_dir, "e1")["ok"] # the expense stands
279 result = post_books(data_dir, "e1")
280 assert result["skipped"] == "accounts unconfigured"
281 assert result["needs"]
282
283
284def test_an_expense_naming_its_own_account_overrides_the_default(
285 tmp_path, monkeypatch):
286 data_dir = setup_env(tmp_path, monkeypatch)
287 object_records.create_collection_record(
288 "fin_accounts", {"id": "acct-meals", "name": "Meals",
289 "account_type": "expense", "code": "6100",
290 "is_active": "true", "owner_id": "boss"},
291 base_dir=data_dir)
292 spend(data_dir, "e1", status="submitted", account_id="acct-meals")
293 approve(data_dir, "e1")
294 post_books(data_dir, "e1")
295
296 rows = {r["account_id"]: r for r in journal_lines(data_dir)}
297 assert rows["acct-meals"]["debit_cents"] == "25000"
298
299
300# --- reaching the invoice -------------------------------------------------------
301
302def test_costs_and_hours_land_on_one_invoice(tmp_path, monkeypatch):
303 """A client engaged one firm for one project and gets one bill."""
304 data_dir = setup_env(tmp_path, monkeypatch)
305 object_records.create_collection_record(
306 "rate_cards", {"id": "house", "label": "House", "hourly_rate_cents": "15000",
307 "valid_from": "2026-01-01", "is_active": "true",
308 "owner_id": "boss"}, base_dir=data_dir)
309 object_records.create_collection_record(
310 "time_logs", {"id": "t1", "project_id": "proj-acme",
311 "started_at": "2026-06-15T09:00:00Z",
312 "ended_at": "2026-06-15T10:00:00Z", "is_running": "false",
313 "billable": "true", "status": "approved",
314 "duration_seconds": "3600", "hourly_rate_cents": "15000",
315 "amount_cents": "15000", "owner_id": "dana"},
316 base_dir=data_dir)
317 spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted")
318 approve(data_dir, "e1")
319
320 result = generate({"project_id": "proj-acme"})
321 assert result["entries_billed"] == 1 and result["expenses_billed"] == 1
322 assert result["time_cents"] == 15000 and result["expense_cents"] == 11500
323 assert result["total_cents"] == 26500
324
325 invoice = object_records.read_collection_records("invoices", base_dir=data_dir)[0]
326 assert invoice["total_cents"] == "26500"
327 assert expense(data_dir, "e1")["status"] == "billed"
328
329
330def test_the_line_says_when_a_cost_was_marked_up(tmp_path, monkeypatch):
331 """A pass-through cost quietly grossed up is what clients discover
332 later and remember."""
333 data_dir = setup_env(tmp_path, monkeypatch)
334 spend(data_dir, "e1", cents=10000, markup_bps=1500, status="submitted")
335 spend(data_dir, "e2", cents=5000, markup_bps=0, status="submitted",
336 description="Taxi", incurred_on="2026-06-16")
337 approve(data_dir, "e1")
338 approve(data_dir, "e2")
339 generate({"project_id": "proj-acme"})
340
341 rows = sorted(lines(data_dir), key=lambda r: r["description"])
342 assert "cost plus 15%" in rows[0]["description"]
343 assert "(at cost)" in rows[1]["description"]
344
345
346def test_unbillable_costs_never_reach_the_invoice(tmp_path, monkeypatch):
347 data_dir = setup_env(tmp_path, monkeypatch)
348 spend(data_dir, "e1", status="submitted", billable="false")
349 approve(data_dir, "e1")
350 assert generate({"project_id": "proj-acme"})["invoiced"] == 0
351
352
353def test_billing_twice_bills_no_cost_twice(tmp_path, monkeypatch):
354 data_dir = setup_env(tmp_path, monkeypatch)
355 spend(data_dir, "e1", status="submitted")
356 approve(data_dir, "e1")
357 generate({"project_id": "proj-acme"})
358 assert generate({"project_id": "proj-acme"})["invoiced"] == 0
359 assert len(lines(data_dir)) == 1
360
361
362def test_expenses_are_never_collapsed_into_one_line(tmp_path, monkeypatch):
363 """One receipt, one line: grouping would hide exactly what a client
364 wants itemised."""
365 data_dir = setup_env(tmp_path, monkeypatch)
366 spend(data_dir, "e1", status="submitted")
367 spend(data_dir, "e2", status="submitted", description="Hotel",
368 incurred_on="2026-06-16")
369 approve(data_dir, "e1")
370 approve(data_dir, "e2")
371 generate({"project_id": "proj-acme", "grouping": "by_person"})
372 assert len(lines(data_dir)) == 2
373
374
375def test_expenses_absent_leaves_time_billing_working(tmp_path, monkeypatch):
376 """app-finance is a soft dependency: time still bills without it."""
377 data_dir = tmp_path / "data"
378 for pkg, name in (("app-timers", "time_logs"), ("app-timers", "rate_cards"),
379 ("app-projects", "projects"),
380 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
381 ("app-settings", "app_settings")):
382 stage_collection(data_dir, pkg, name)
383 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
384 object_records.create_collection_record(
385 "projects", {"id": "proj-acme", "name": "Acme", "owner_id": "boss"},
386 base_dir=data_dir)
387 object_records.create_collection_record(
388 "time_logs", {"id": "t1", "project_id": "proj-acme",
389 "started_at": "2026-06-15T09:00:00Z",
390 "ended_at": "2026-06-15T10:00:00Z", "is_running": "false",
391 "billable": "true", "status": "approved",
392 "duration_seconds": "3600", "hourly_rate_cents": "15000",
393 "amount_cents": "15000", "owner_id": "dana"},
394 base_dir=data_dir)
395 result = generate({"project_id": "proj-acme"})
396 assert result["invoiced"] == 1 and result["expenses_billed"] == 0