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

9 downloads

dbbasic-object-server/tests/test_tm_billing.py
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, 18 minutes ago History
test_tm_billing.py · 15.3 KB · 364 lines
1"""Time and materials: hours -> approved -> invoiced.
2
3Consulting hours are a usage metric with an approval gate, so most of
4this spine is already proven elsewhere. What is genuinely new -- and
5therefore what is tested hardest here -- is the gate itself: nobody
6approves their own hours, nothing is submitted while the clock is still
7running, the rate is fixed at the moment a human said yes, and the same
8hour is never billed twice.
9"""
10
11import pathlib
12
13import pytest
14
15from conftest import stage_collection
16
17import object_execution
18import object_rates
19import object_records
20import python_object_runtime
21
22REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
23PACKAGES = REPO_ROOT / "packages"
24TIMER_OBJECTS = PACKAGES / "app-timers" / "objects"
25INVOICE_OBJECTS = PACKAGES / "app-invoices" / "objects"
26RUNTIME = python_object_runtime.PythonObjectRuntime()
27
28HOUR = 3600
29
30
31def setup_env(tmp_path, monkeypatch):
32 data_dir = tmp_path / "data"
33 for pkg, name in (("app-timers", "time_logs"), ("app-timers", "rate_cards"),
34 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
35 ("app-tasks", "tasks"), ("app-projects", "projects"),
36 ("app-settings", "app_settings")):
37 stage_collection(data_dir, pkg, name)
38 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
39 object_records.create_collection_record(
40 "projects", {"id": "proj-acme", "name": "Acme Rebuild", "owner_id": "boss"},
41 base_dir=data_dir)
42 object_records.create_collection_record(
43 "tasks", {"id": "task-1", "title": "Data migration", "owner_id": "dana"},
44 base_dir=data_dir)
45 return data_dir
46
47
48def rate_card(data_dir, card_id, cents, **fields):
49 record = {"id": card_id, "label": card_id, "hourly_rate_cents": str(cents),
50 "currency": "USD", "valid_from": "2026-01-01", "is_active": "true",
51 "owner_id": "boss"}
52 record.update({k: str(v) for k, v in fields.items()})
53 return object_records.create_collection_record(
54 "rate_cards", record, base_dir=data_dir)
55
56
57def log_time(data_dir, log_id, *, seconds=HOUR, owner="dana", **fields):
58 record = {"id": log_id, "task_id": "task-1", "project_id": "proj-acme",
59 "started_at": "2026-06-15T09:00:00Z", "ended_at": "2026-06-15T10:00:00Z",
60 "is_running": "false", "billable": "true", "status": "draft",
61 "duration_seconds": str(seconds), "owner_id": owner,
62 "notes": "Migration work"}
63 record.update({k: str(v) for k, v in fields.items()})
64 return object_records.create_collection_record(
65 "time_logs", record, base_dir=data_dir)
66
67
68def hook(data_dir, record, *, existing=None, changes=None, actor="boss",
69 action="update"):
70 return object_execution.execute_object(
71 RUNTIME,
72 object_execution.ObjectExecutionRequest(
73 "hook_time_logs", method="BEFORE_WRITE",
74 payload={"action": action, "collection": "time_logs",
75 "record": record, "existing": existing,
76 "changes": changes if changes is not None else dict(record),
77 "subject": {"user_id": actor, "roles": ["manager"]}}),
78 roots=[TIMER_OBJECTS]).result
79
80
81def approve(data_dir, log_id, *, actor="boss"):
82 """Move an entry through the gate the way the write path would."""
83 existing = object_records.get_collection_record("time_logs", log_id,
84 base_dir=data_dir)
85 outcome = hook(data_dir, {"status": "approved"}, existing=existing,
86 changes={"status": "approved"}, actor=actor)
87 if outcome and outcome.get("error"):
88 return outcome
89 patch = (outcome or {}).get("record") or {"status": "approved"}
90 object_records.update_collection_record("time_logs", log_id, patch,
91 base_dir=data_dir, actor=actor)
92 return {"ok": True}
93
94
95def generate(payload=None):
96 return object_execution.execute_object(
97 RUNTIME,
98 object_execution.ObjectExecutionRequest(
99 "action_generate_tm_invoice", method="POST", payload=payload or {}),
100 roots=[INVOICE_OBJECTS]).result
101
102
103def entry(data_dir, log_id):
104 return object_records.get_collection_record("time_logs", log_id, base_dir=data_dir)
105
106
107def invoices(data_dir):
108 return object_records.read_collection_records("invoices", base_dir=data_dir)
109
110
111def lines(data_dir):
112 return object_records.read_collection_records("invoice_lines", base_dir=data_dir)
113
114
115# --- resolving the rate -----------------------------------------------------
116
117def test_the_most_specific_card_wins():
118 """The reason anyone writes a rate for one person on one project is
119 that it must beat both the project rate and their standard rate."""
120 cards = [
121 {"id": "house", "hourly_rate_cents": "10000", "valid_from": "2026-01-01"},
122 {"id": "dana", "person_id": "dana", "hourly_rate_cents": "12000",
123 "valid_from": "2026-01-01"},
124 {"id": "acme", "project_id": "proj-acme", "hourly_rate_cents": "15000",
125 "valid_from": "2026-01-01"},
126 {"id": "dana_acme", "person_id": "dana", "project_id": "proj-acme",
127 "hourly_rate_cents": "18000", "valid_from": "2026-01-01"},
128 ]
129 pick = lambda **kw: object_rates.find_rate(cards, on_date="2026-06-15", **kw)["id"]
130 assert pick(person_id="dana", project_id="proj-acme") == "dana_acme"
131 assert pick(person_id="sam", project_id="proj-acme") == "acme"
132 assert pick(person_id="dana", project_id="proj-other") == "dana"
133 assert pick(person_id="sam", project_id="proj-other") == "house"
134
135
136def test_a_rate_never_looks_forward():
137 """Next quarter's rate must not price last quarter's unbilled hours."""
138 cards = [{"id": "old", "hourly_rate_cents": "10000", "valid_from": "2026-01-01"},
139 {"id": "new", "hourly_rate_cents": "13000", "valid_from": "2026-07-01"}]
140 assert object_rates.find_rate(cards, on_date="2026-06-15")["id"] == "old"
141 assert object_rates.find_rate(cards, on_date="2026-07-02")["id"] == "new"
142
143
144def test_a_retired_card_stops_applying_to_new_work():
145 cards = [{"id": "old", "hourly_rate_cents": "10000", "valid_from": "2026-01-01",
146 "is_active": "false"}]
147 assert object_rates.find_rate(cards, on_date="2026-06-15") is None
148
149
150def test_the_increment_rounds_up_because_that_is_what_an_increment_is():
151 # 61 minutes at a 15-minute increment bills 75 minutes.
152 assert object_rates.billable_seconds(61 * 60, 15) == 75 * 60
153 assert object_rates.billable_seconds(HOUR, 15) == HOUR # exact stays exact
154 assert object_rates.billable_seconds(HOUR, 0) == HOUR # 0 bills what happened
155
156
157def test_the_amount_rounds_once_for_the_entry():
158 # 20 minutes at $150/hr is exactly 5000; 25 minutes is 6250.
159 assert object_rates.amount_cents(20 * 60, 15000) == 5000
160 assert object_rates.amount_cents(25 * 60, 15000) == 6250
161 # 1 second at $150/hr rounds half-up to 4 cents, not away to nothing.
162 assert object_rates.amount_cents(1, 15000) == 4
163
164
165def test_time_with_no_applicable_card_is_reported_not_priced_at_zero():
166 """Hours nobody wrote a rate for must not look like unbillable hours."""
167 rated = object_rates.rate_entry(
168 {"owner_id": "dana", "project_id": "proj-acme", "duration_seconds": HOUR},
169 [])
170 assert rated["amount_cents"] == 0
171 assert "no rate card applies" in rated["unrated_reason"]
172
173
174# --- the gate ---------------------------------------------------------------
175
176def test_nobody_approves_their_own_hours(tmp_path, monkeypatch):
177 """An approval you can grant yourself is not an approval."""
178 data_dir = setup_env(tmp_path, monkeypatch)
179 rate_card(data_dir, "house", 15000)
180 log_time(data_dir, "t1", status="submitted")
181 outcome = approve(data_dir, "t1", actor="dana") # dana logged it
182 assert outcome["status"] == 403
183 assert "not an approval" in outcome["error"]
184 assert entry(data_dir, "t1")["status"] == "submitted"
185
186
187def test_a_running_timer_cannot_be_submitted(tmp_path, monkeypatch):
188 """Billing a duration that is still growing means the number invoiced
189 was never the number approved."""
190 data_dir = setup_env(tmp_path, monkeypatch)
191 log_time(data_dir, "t1", is_running="true", ended_at="", duration_seconds=0)
192 existing = entry(data_dir, "t1")
193 outcome = hook(data_dir, {"status": "submitted"}, existing=existing,
194 changes={"status": "submitted"}, actor="dana")
195 assert outcome["status"] == 400 and "Stop the timer" in outcome["error"]
196
197
198def test_unbillable_time_is_not_approved_for_billing(tmp_path, monkeypatch):
199 data_dir = setup_env(tmp_path, monkeypatch)
200 rate_card(data_dir, "house", 15000)
201 log_time(data_dir, "t1", status="submitted", billable="false")
202 outcome = approve(data_dir, "t1")
203 assert outcome["status"] == 400 and "billable" in outcome["error"]
204
205
206def test_approving_without_a_rate_is_refused_rather_than_approved_at_nothing(
207 tmp_path, monkeypatch):
208 data_dir = setup_env(tmp_path, monkeypatch)
209 log_time(data_dir, "t1", status="submitted")
210 outcome = approve(data_dir, "t1")
211 assert outcome["status"] == 409 and "No rate applies" in outcome["error"]
212
213
214def test_approval_stamps_the_rate_that_applied_when_the_work_happened(
215 tmp_path, monkeypatch):
216 data_dir = setup_env(tmp_path, monkeypatch)
217 rate_card(data_dir, "house", 15000)
218 log_time(data_dir, "t1", status="submitted", seconds=90 * 60)
219 assert approve(data_dir, "t1")["ok"]
220
221 row = entry(data_dir, "t1")
222 assert row["status"] == "approved"
223 assert row["hourly_rate_cents"] == "15000"
224 assert row["amount_cents"] == "22500" # 1.5h at $150
225 assert row["rate_card_id"] == "house"
226 assert row["approved_by"] == "boss"
227 assert row["approved_at"]
228
229
230def test_a_later_rate_change_never_reprices_approved_work(tmp_path, monkeypatch):
231 """The stamp is the whole point of stamping."""
232 data_dir = setup_env(tmp_path, monkeypatch)
233 rate_card(data_dir, "house", 15000)
234 log_time(data_dir, "t1", status="submitted")
235 approve(data_dir, "t1")
236
237 rate_card(data_dir, "house_2027", 25000, valid_from="2026-07-01")
238 generate({"project_id": "proj-acme", "through_date": "2026-12-31"})
239 assert lines(data_dir)[0]["line_total_cents"] == "15000"
240
241
242def test_approved_time_is_frozen(tmp_path, monkeypatch):
243 """Correcting settled evidence is a compensating entry, not an edit."""
244 data_dir = setup_env(tmp_path, monkeypatch)
245 rate_card(data_dir, "house", 15000)
246 log_time(data_dir, "t1", status="submitted")
247 approve(data_dir, "t1")
248
249 # The schema's `locked_when` (approved/billed), not the hook: inside the
250 # write lock, for every writer, and for delete.
251 with pytest.raises(object_records.RecordLockedError, match="settled"):
252 object_records.update_collection_record(
253 "time_logs", "t1", {"duration_seconds": "72000"}, base_dir=data_dir)
254 with pytest.raises(object_records.RecordLockedError):
255 object_records.delete_collection_record("time_logs", "t1", base_dir=data_dir)
256
257
258def test_billed_time_cannot_be_reopened(tmp_path, monkeypatch):
259 data_dir = setup_env(tmp_path, monkeypatch)
260 rate_card(data_dir, "house", 15000)
261 log_time(data_dir, "t1", status="submitted")
262 approve(data_dir, "t1")
263 generate({"project_id": "proj-acme"})
264
265 # `transitions: billed -> []`, not the hook: terminal for every writer.
266 with pytest.raises(object_records.InvalidRecordPayloadError, match="cannot move from 'billed'"):
267 object_records.update_collection_record(
268 "time_logs", "t1", {"status": "draft"}, base_dir=data_dir)
269 assert entry(data_dir, "t1")["status"] == "billed"
270
271
272# --- generating the invoice --------------------------------------------------
273
274def test_approved_hours_become_an_invoice_a_client_can_check(tmp_path, monkeypatch):
275 data_dir = setup_env(tmp_path, monkeypatch)
276 rate_card(data_dir, "house", 15000)
277 log_time(data_dir, "t1", status="submitted", seconds=2 * HOUR)
278 log_time(data_dir, "t2", status="submitted", seconds=HOUR)
279 approve(data_dir, "t1")
280 approve(data_dir, "t2")
281
282 result = generate({"project_id": "proj-acme"})
283 assert result["invoiced"] == 1 and result["entries_billed"] == 2
284
285 invoice = invoices(data_dir)[0]
286 assert invoice["total_cents"] == "45000"
287 assert invoice["customer_name"] == "Acme Rebuild"
288 assert invoice["status"] == "draft" # a human sends it
289
290 rows = lines(data_dir)
291 assert len(rows) == 2
292 assert "2.00 hours" in rows[0]["description"]
293 assert "at 150.00/hr" in rows[0]["description"]
294
295
296def test_running_the_generator_twice_bills_nothing_twice(tmp_path, monkeypatch):
297 """The failure a consultancy does not get to explain twice."""
298 data_dir = setup_env(tmp_path, monkeypatch)
299 rate_card(data_dir, "house", 15000)
300 log_time(data_dir, "t1", status="submitted")
301 approve(data_dir, "t1")
302
303 generate({"project_id": "proj-acme"})
304 again = generate({"project_id": "proj-acme"})
305 assert again["invoiced"] == 0
306 assert len(invoices(data_dir)) == 1
307 assert entry(data_dir, "t1")["status"] == "billed"
308
309
310def test_only_approved_time_is_billed(tmp_path, monkeypatch):
311 data_dir = setup_env(tmp_path, monkeypatch)
312 rate_card(data_dir, "house", 15000)
313 log_time(data_dir, "t1", status="submitted") # never approved
314 log_time(data_dir, "t2", status="draft")
315 assert generate({"project_id": "proj-acme"})["invoiced"] == 0
316
317
318def test_a_through_date_leaves_later_work_for_the_next_invoice(tmp_path, monkeypatch):
319 data_dir = setup_env(tmp_path, monkeypatch)
320 rate_card(data_dir, "house", 15000)
321 log_time(data_dir, "t1", status="submitted")
322 log_time(data_dir, "t2", status="submitted",
323 started_at="2026-07-20T09:00:00Z", ended_at="2026-07-20T10:00:00Z")
324 approve(data_dir, "t1")
325 approve(data_dir, "t2")
326
327 result = generate({"project_id": "proj-acme", "through_date": "2026-06-30"})
328 assert result["entries_billed"] == 1
329 assert entry(data_dir, "t2")["status"] == "approved" # still waiting
330
331
332def test_grouping_by_person_collapses_the_lines(tmp_path, monkeypatch):
333 data_dir = setup_env(tmp_path, monkeypatch)
334 rate_card(data_dir, "house", 15000)
335 log_time(data_dir, "t1", status="submitted", owner="dana")
336 log_time(data_dir, "t2", status="submitted", owner="dana")
337 log_time(data_dir, "t3", status="submitted", owner="sam")
338 for log_id in ("t1", "t2", "t3"):
339 approve(data_dir, log_id)
340
341 generate({"project_id": "proj-acme", "grouping": "by_person"})
342 rows = sorted(lines(data_dir), key=lambda r: r["description"])
343 assert len(rows) == 2
344 assert rows[0]["description"].startswith("dana: 2.00 hours")
345 assert rows[0]["line_total_cents"] == "30000"
346
347
348def test_a_dry_run_says_what_it_would_bill_and_writes_nothing(tmp_path, monkeypatch):
349 data_dir = setup_env(tmp_path, monkeypatch)
350 rate_card(data_dir, "house", 15000)
351 log_time(data_dir, "t1", status="submitted")
352 approve(data_dir, "t1")
353
354 result = generate({"project_id": "proj-acme", "dry_run": "true"})
355 assert result["would_invoice"] == 1 and result["total_cents"] == 15000
356 assert invoices(data_dir) == []
357 assert entry(data_dir, "t1")["status"] == "approved"
358
359
360def test_time_tracking_absent_is_a_graceful_skip(tmp_path, monkeypatch):
361 data_dir = tmp_path / "data"
362 data_dir.mkdir()
363 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
364 assert generate()["skipped"].startswith("time tracking not installed")