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