askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_finance_action_claims.py · 25.9 KB · 582 lines
| 1 | """Finance and inventory actions that claim before they write. |
| 2 | |
| 3 | Companion to tests/test_findings_actions.py, whose strict-xfail findings |
| 4 | these fixes turned green. Those reproduce each bug in one deterministic |
| 5 | interleaving; the tests here pin the fix from the other sides -- a real |
| 6 | race between threads (AGENTS.md: "verify by reproduction"), a retry after |
| 7 | a crash at each step, and the refusals a fix adds. |
| 8 | |
| 9 | Races are forced, not hoped for: each racing thread waits on a barrier at |
| 10 | a point AFTER it has read the state it decides on and BEFORE it writes, |
| 11 | so every thread has made its decision before any of them writes. If the |
| 12 | code serialised them anyway (a lock taken earlier), the barrier times |
| 13 | out and the threads proceed one at a time -- the test still passes for |
| 14 | the right reason, it just stops proving the overlap. Nothing here touches |
| 15 | the network. |
| 16 | """ |
| 17 | |
| 18 | import pathlib |
| 19 | import threading |
| 20 | |
| 21 | import pytest |
| 22 | |
| 23 | import object_execution |
| 24 | import object_intake |
| 25 | import object_records |
| 26 | import python_object_runtime |
| 27 | |
| 28 | import test_document_intake as tdi |
| 29 | import test_period_locking as tpl |
| 30 | |
| 31 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 32 | PACKAGES = REPO_ROOT / "packages" |
| 33 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 34 | |
| 35 | |
| 36 | def execute(root, object_id, payload, method="POST"): |
| 37 | return object_execution.execute_object( |
| 38 | RUNTIME, |
| 39 | object_execution.ObjectExecutionRequest( |
| 40 | object_id, method=method, payload=payload), |
| 41 | roots=[root]) |
| 42 | |
| 43 | |
| 44 | def race(n, target, gate_module, gate_name): |
| 45 | """Run target(i) in n threads; each blocks inside gate_module.gate_name |
| 46 | until all n have reached it. Returns the results in thread order.""" |
| 47 | barrier = threading.Barrier(n, timeout=5) |
| 48 | real = getattr(gate_module, gate_name) |
| 49 | passed = threading.local() |
| 50 | |
| 51 | def gated(*args, **kwargs): |
| 52 | if not getattr(passed, "done", False): |
| 53 | passed.done = True |
| 54 | try: |
| 55 | barrier.wait() |
| 56 | except threading.BrokenBarrierError: |
| 57 | pass |
| 58 | return real(*args, **kwargs) |
| 59 | |
| 60 | results = [None] * n |
| 61 | errors = [] |
| 62 | |
| 63 | def worker(i): |
| 64 | try: |
| 65 | results[i] = target(i) |
| 66 | except BaseException as exc: # pragma: no cover - reported |
| 67 | errors.append(exc) |
| 68 | |
| 69 | setattr(gate_module, gate_name, gated) |
| 70 | try: |
| 71 | threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)] |
| 72 | for t in threads: |
| 73 | t.start() |
| 74 | for t in threads: |
| 75 | t.join(30) |
| 76 | finally: |
| 77 | setattr(gate_module, gate_name, real) |
| 78 | assert not errors, errors |
| 79 | return results |
| 80 | |
| 81 | |
| 82 | # ============================================================================= |
| 83 | # confirm_scan: one scan, one expense |
| 84 | # ============================================================================= |
| 85 | |
| 86 | def extracted_scan(tmp_path, monkeypatch): |
| 87 | data_dir = tdi.setup_env(tmp_path, monkeypatch) |
| 88 | scan_id = tdi.ingest()["scan_id"] |
| 89 | tdi.run("system_scan_processor") |
| 90 | assert tdi.scan(data_dir, scan_id)["status"] == "extracted" |
| 91 | return data_dir, scan_id |
| 92 | |
| 93 | |
| 94 | def test_racing_confirmations_of_one_scan_book_one_expense(tmp_path, monkeypatch): |
| 95 | """Four clicks land together. Every one of them has read the scan as |
| 96 | unconfirmed (the barrier sits after that read) before any writes; the |
| 97 | unique key on expenses.generated_from lets exactly one expense in, and |
| 98 | every answer names that one.""" |
| 99 | data_dir, scan_id = extracted_scan(tmp_path, monkeypatch) |
| 100 | |
| 101 | results = race(4, lambda i: tdi.confirm({"scan_id": scan_id}), |
| 102 | object_intake, "normalize_extraction") |
| 103 | |
| 104 | rows = tdi.expenses(data_dir) |
| 105 | assert len(rows) == 1, f"{len(rows)} expenses for one scan" |
| 106 | assert all(r and r.get("ok") for r in results), results |
| 107 | assert {r["expense_id"] for r in results} == {rows[0]["id"]} |
| 108 | assert rows[0]["generated_from"] == f"scans/{scan_id}" |
| 109 | assert tdi.scan(data_dir, scan_id)["confirmed_record"] == f"expenses/{rows[0]['id']}" |
| 110 | |
| 111 | |
| 112 | def test_a_confirmation_that_failed_after_the_expense_links_it_on_retry( |
| 113 | tmp_path, monkeypatch): |
| 114 | """The expense was written and the scan stamp then failed (a crash, a |
| 115 | full disk). The retry must not book a second expense; it links the |
| 116 | first and finishes the job.""" |
| 117 | data_dir, scan_id = extracted_scan(tmp_path, monkeypatch) |
| 118 | real = object_records.update_collection_record |
| 119 | |
| 120 | def failing(collection, *a, **k): |
| 121 | if collection == "scans": |
| 122 | raise OSError("disk full while stamping the scan") |
| 123 | return real(collection, *a, **k) |
| 124 | |
| 125 | monkeypatch.setattr(object_records, "update_collection_record", failing) |
| 126 | first = tdi.confirm({"scan_id": scan_id}) |
| 127 | monkeypatch.setattr(object_records, "update_collection_record", real) |
| 128 | assert first["status"] == 409 and "disk full" in first["error"] |
| 129 | assert len(tdi.expenses(data_dir)) == 1 |
| 130 | |
| 131 | retry = tdi.confirm({"scan_id": scan_id}) |
| 132 | rows = tdi.expenses(data_dir) |
| 133 | assert len(rows) == 1 |
| 134 | assert retry["ok"] and retry["duplicate"] is True |
| 135 | assert retry["expense_id"] == first["expense_id"] == rows[0]["id"] |
| 136 | assert tdi.scan(data_dir, scan_id)["status"] == "confirmed" |
| 137 | |
| 138 | |
| 139 | def test_an_unread_scan_is_refused_before_anything_is_written( |
| 140 | tmp_path, monkeypatch): |
| 141 | data_dir = tdi.setup_env(tmp_path, monkeypatch) |
| 142 | scan_id = tdi.ingest()["scan_id"] # not processed: pending |
| 143 | result = tdi.confirm({"scan_id": scan_id, "amount_cents": "899"}) |
| 144 | assert result["status"] == 409 |
| 145 | assert "cannot move from 'pending' to 'confirmed'" in result["error"] |
| 146 | assert tdi.expenses(data_dir) == [] |
| 147 | |
| 148 | |
| 149 | def test_no_client_write_can_set_an_expense_generated_from(tmp_path, monkeypatch): |
| 150 | """The key is read_only: an ordinary write cannot plant scans/{id} on a |
| 151 | hand-made expense and so block that scan's real confirmation.""" |
| 152 | data_dir = tdi.setup_env(tmp_path, monkeypatch) |
| 153 | with pytest.raises(ValueError): |
| 154 | object_records.create_collection_record( |
| 155 | "expenses", |
| 156 | {"id": "e-squat", "description": "x", "incurred_on": "2026-06-15", |
| 157 | "amount_cents": "1", "generated_from": "scans/abc"}, |
| 158 | base_dir=data_dir) |
| 159 | |
| 160 | |
| 161 | # ============================================================================= |
| 162 | # reverse_journal: the period lock |
| 163 | # ============================================================================= |
| 164 | |
| 165 | FINANCE_OBJECTS = PACKAGES / "app-finance" / "objects" |
| 166 | DAN = {"user_id": "dan", "roles": []} |
| 167 | |
| 168 | |
| 169 | def q1_journal(tmp_path, monkeypatch): |
| 170 | import test_findings_actions as tfa |
| 171 | data_dir = tpl.setup_env(tmp_path, monkeypatch) |
| 172 | tfa.posted_journal_in_q1(data_dir) |
| 173 | return data_dir |
| 174 | |
| 175 | |
| 176 | def mirrors(data_dir): |
| 177 | return [j for j in object_records.read_collection_records( |
| 178 | "fin_journals", base_dir=data_dir) |
| 179 | if j.get("generated_from") == "reversal:j-q1"] |
| 180 | |
| 181 | |
| 182 | def test_a_reversal_of_a_closed_period_journal_names_the_period( |
| 183 | tmp_path, monkeypatch): |
| 184 | data_dir = q1_journal(tmp_path, monkeypatch) |
| 185 | result = execute(FINANCE_OBJECTS, "action_reverse_journal", |
| 186 | {"journal_id": "j-q1", "_identity": DAN}).result |
| 187 | assert result["status"] == 409 |
| 188 | assert "2026-01-01 to 2026-03-31" in result["error"] |
| 189 | assert mirrors(data_dir) == [] |
| 190 | |
| 191 | |
| 192 | def test_a_reversal_dated_in_an_open_period_posts_there(tmp_path, monkeypatch): |
| 193 | data_dir = q1_journal(tmp_path, monkeypatch) |
| 194 | result = execute(FINANCE_OBJECTS, "action_reverse_journal", |
| 195 | {"journal_id": "j-q1", "date": "2026-04-01", |
| 196 | "_identity": DAN}).result |
| 197 | assert result["status"] == 200 and result["posted"] is True, result |
| 198 | [mirror] = mirrors(data_dir) |
| 199 | assert mirror["date"] == "2026-04-01" and mirror["status"] == "posted" |
| 200 | |
| 201 | |
| 202 | def test_a_reversal_cannot_be_dated_into_a_closed_period_either( |
| 203 | tmp_path, monkeypatch): |
| 204 | data_dir = q1_journal(tmp_path, monkeypatch) |
| 205 | result = execute(FINANCE_OBJECTS, "action_reverse_journal", |
| 206 | {"journal_id": "j-q1", "date": "2026-03-31", |
| 207 | "_identity": DAN}).result |
| 208 | assert result["status"] == 409 and mirrors(data_dir) == [] |
| 209 | bad = execute(FINANCE_OBJECTS, "action_reverse_journal", |
| 210 | {"journal_id": "j-q1", "date": "next tuesday", |
| 211 | "_identity": DAN}).result |
| 212 | assert bad["status"] == 400 and mirrors(data_dir) == [] |
| 213 | |
| 214 | |
| 215 | def test_unreadable_closed_periods_refuse_the_reversal(tmp_path, monkeypatch): |
| 216 | """An unreadable lock is not an open one.""" |
| 217 | data_dir = q1_journal(tmp_path, monkeypatch) |
| 218 | real = object_records.read_collection_records |
| 219 | |
| 220 | def failing(collection, *a, **k): |
| 221 | if collection == "fin_closed_periods": |
| 222 | raise OSError("closed periods unreadable") |
| 223 | return real(collection, *a, **k) |
| 224 | |
| 225 | monkeypatch.setattr(object_records, "read_collection_records", failing) |
| 226 | result = execute(FINANCE_OBJECTS, "action_reverse_journal", |
| 227 | {"journal_id": "j-q1", "date": "2026-04-01", |
| 228 | "_identity": DAN}).result |
| 229 | monkeypatch.setattr(object_records, "read_collection_records", real) |
| 230 | assert result["status"] == 409 and "closed periods" in result["error"] |
| 231 | assert mirrors(data_dir) == [] |
| 232 | |
| 233 | |
| 234 | # ============================================================================= |
| 235 | # record_count: the evidence before the journal |
| 236 | # ============================================================================= |
| 237 | |
| 238 | import test_cash_counts as tcc # noqa: E402 |
| 239 | |
| 240 | |
| 241 | def till_balance(data_dir): |
| 242 | return sum(int(l["debit_cents"]) - int(l["credit_cents"]) |
| 243 | for l in object_records.read_collection_records( |
| 244 | "fin_journal_lines", base_dir=data_dir) |
| 245 | if l["account_id"] == tcc.CASH |
| 246 | and l["journal_id"] in {j["id"] for j in object_records.read_collection_records( |
| 247 | "fin_journals", base_dir=data_dir) if j["status"] == "posted"}) |
| 248 | |
| 249 | |
| 250 | def test_a_count_whose_journal_fails_keeps_the_count_and_says_nothing_was_booked( |
| 251 | tmp_path, monkeypatch): |
| 252 | import object_finance |
| 253 | data_dir = tcc.setup_env(tmp_path, monkeypatch) |
| 254 | tcc.make_till(data_dir) |
| 255 | tcc.book_cash(data_dir, 20000) |
| 256 | |
| 257 | def broken(*a, **k): |
| 258 | raise OSError("ledger write failed") |
| 259 | |
| 260 | real = object_finance.compose_posted_journal |
| 261 | monkeypatch.setattr(object_finance, "compose_posted_journal", broken) |
| 262 | result = tcc.count({"value_account_id": tcc.TILL, "counted_minor": 19750, |
| 263 | "counted_on": "2026-07-31"}) |
| 264 | monkeypatch.setattr(object_finance, "compose_posted_journal", real) |
| 265 | assert result["status"] == 500 and "NOT booked" in result["error"] |
| 266 | [row] = tcc.counts(data_dir) |
| 267 | assert row["variance_minor"] == "-250" and row["journal_id"] == "" |
| 268 | assert till_balance(data_dir) == 20000 |
| 269 | |
| 270 | # The books still say 20000, so the next count books the shortage once. |
| 271 | again = tcc.count({"value_account_id": tcc.TILL, "counted_minor": 19750, |
| 272 | "counted_on": "2026-07-31"}) |
| 273 | assert again["status"] == 200 and again["journal"]["posted"] is True |
| 274 | assert till_balance(data_dir) == 19750 |
| 275 | |
| 276 | |
| 277 | def test_racing_counts_of_one_till_book_the_shortage_once(tmp_path, monkeypatch): |
| 278 | """A double click, or two people at one drawer: both counts read the |
| 279 | same 20000 book balance before either writes (the barrier sits at the |
| 280 | first write). Found while fixing the orphan journal: the books lost |
| 281 | 500 for a 250 shortage. Now one count books it and the other is |
| 282 | refused against the same books.""" |
| 283 | data_dir = tcc.setup_env(tmp_path, monkeypatch) |
| 284 | tcc.make_till(data_dir) |
| 285 | tcc.book_cash(data_dir, 20000) |
| 286 | |
| 287 | results = race(3, lambda i: tcc.count({"value_account_id": tcc.TILL, |
| 288 | "counted_minor": 19750, |
| 289 | "counted_on": "2026-07-31"}), |
| 290 | object_records, "create_collection_record") |
| 291 | |
| 292 | assert till_balance(data_dir) == 19750, results |
| 293 | assert sorted(r["status"] for r in results) == [200, 409, 409], results |
| 294 | booked = [c for c in tcc.counts(data_dir) if c["journal_id"]] |
| 295 | assert len(booked) == 1 and len(tcc.counts(data_dir)) == 1 |
| 296 | |
| 297 | # The books moved, so a later recount is an ordinary count again. |
| 298 | later = tcc.count({"value_account_id": tcc.TILL, "counted_minor": 19750, |
| 299 | "counted_on": "2026-07-31"}) |
| 300 | assert later["status"] == 200 and later["variance_minor"] == 0 |
| 301 | |
| 302 | |
| 303 | def test_a_count_whose_link_fails_still_names_the_count_from_the_journal( |
| 304 | tmp_path, monkeypatch): |
| 305 | data_dir = tcc.setup_env(tmp_path, monkeypatch) |
| 306 | tcc.make_till(data_dir) |
| 307 | tcc.book_cash(data_dir, 20000) |
| 308 | real = object_records.update_collection_record |
| 309 | |
| 310 | def failing(collection, *a, **k): |
| 311 | if collection == "value_account_counts": |
| 312 | raise OSError("disk full while linking") |
| 313 | return real(collection, *a, **k) |
| 314 | |
| 315 | monkeypatch.setattr(object_records, "update_collection_record", failing) |
| 316 | result = tcc.count({"value_account_id": tcc.TILL, "counted_minor": 19750, |
| 317 | "counted_on": "2026-07-31"}) |
| 318 | monkeypatch.setattr(object_records, "update_collection_record", real) |
| 319 | assert result["status"] == 200 and "linking it to the count failed" in result["warning"] |
| 320 | [row] = tcc.counts(data_dir) |
| 321 | journal = object_records.get_collection_record( |
| 322 | "fin_journals", result["journal"]["journal_id"], base_dir=data_dir) |
| 323 | assert journal["generated_from"] == f"value_account_counts/{row['id']}" |
| 324 | |
| 325 | |
| 326 | # ============================================================================= |
| 327 | # generate_tm_invoice: claimed numbers, claimed hours |
| 328 | # ============================================================================= |
| 329 | |
| 330 | import test_tm_billing as ttm # noqa: E402 |
| 331 | |
| 332 | |
| 333 | def approved_hours(data_dir, *ids, project="proj-acme"): |
| 334 | for log_id in ids: |
| 335 | ttm.log_time(data_dir, log_id, status="submitted", project_id=project) |
| 336 | assert ttm.approve(data_dir, log_id)["ok"] |
| 337 | |
| 338 | |
| 339 | def test_racing_invoice_runs_bill_each_hour_once(tmp_path, monkeypatch): |
| 340 | """Four runs start together, every one after reading the same three |
| 341 | approved hours as unbilled (the barrier sits at the first write). The |
| 342 | hours are billed once in total, every invoice that exists has lines and |
| 343 | a total, and no two invoices share a number.""" |
| 344 | data_dir = ttm.setup_env(tmp_path, monkeypatch) |
| 345 | ttm.rate_card(data_dir, "house", 15000) |
| 346 | approved_hours(data_dir, "t1", "t2", "t3") |
| 347 | |
| 348 | results = race(4, lambda i: ttm.generate({"project_id": "proj-acme", |
| 349 | "through_date": "2026-06-30"}), |
| 350 | object_records, "create_collection_record") |
| 351 | |
| 352 | invoices = ttm.invoices(data_dir) |
| 353 | billed = sum(int(i["total_cents"]) for i in invoices) |
| 354 | assert billed == 3 * 15000, (billed, results) |
| 355 | assert sum(r["entries_billed"] for r in results if r.get("invoiced")) == 3 |
| 356 | assert all(int(i["total_cents"]) > 0 for i in invoices), invoices |
| 357 | numbers = [i["number"] for i in invoices] |
| 358 | assert len(numbers) == len(set(numbers)), numbers |
| 359 | per_invoice = {} |
| 360 | for log_id in ("t1", "t2", "t3"): |
| 361 | row = ttm.entry(data_dir, log_id) |
| 362 | assert row["status"] == "billed" |
| 363 | per_invoice[row["invoice_id"]] = per_invoice.get(row["invoice_id"], 0) + 1 |
| 364 | lines = ttm.lines(data_dir) |
| 365 | for invoice in invoices: |
| 366 | on_it = [l for l in lines if l["invoice_id"] == invoice["id"]] |
| 367 | assert sum(int(l["line_total_cents"]) for l in on_it) == int(invoice["total_cents"]) |
| 368 | assert per_invoice.get(invoice["id"], 0) * 15000 == int(invoice["total_cents"]) |
| 369 | |
| 370 | |
| 371 | def test_projects_sharing_a_prefix_get_different_numbers(tmp_path, monkeypatch): |
| 372 | data_dir = ttm.setup_env(tmp_path, monkeypatch) |
| 373 | ttm.rate_card(data_dir, "house", 15000) |
| 374 | object_records.create_collection_record( |
| 375 | "projects", {"id": "proj-acme-2", "name": "Acme Two", "owner_id": "boss"}, |
| 376 | base_dir=data_dir) |
| 377 | approved_hours(data_dir, "t1") |
| 378 | approved_hours(data_dir, "t2", project="proj-acme-2") |
| 379 | ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"}) |
| 380 | ttm.generate({"project_id": "proj-acme-2", "through_date": "2026-06-30"}) |
| 381 | numbers = sorted(i["number"] for i in ttm.invoices(data_dir)) |
| 382 | assert numbers == ["TM-proj-acm-2026-06-30", "TM-proj-acm-2026-06-30-2"] |
| 383 | |
| 384 | |
| 385 | def test_a_number_already_typed_on_an_invoice_is_not_reissued(tmp_path, monkeypatch): |
| 386 | data_dir = ttm.setup_env(tmp_path, monkeypatch) |
| 387 | ttm.rate_card(data_dir, "house", 15000) |
| 388 | object_records.create_collection_record( |
| 389 | "invoices", {"id": "inv-typed", "number": "TM-proj-acm-2026-06-30", |
| 390 | "customer_name": "x", "status": "draft", "owner_id": "boss"}, |
| 391 | base_dir=data_dir) |
| 392 | approved_hours(data_dir, "t1") |
| 393 | result = ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"}) |
| 394 | assert result["number"] == "TM-proj-acm-2026-06-30-2" |
| 395 | |
| 396 | |
| 397 | def test_a_run_that_loses_every_entry_leaves_no_empty_invoice(tmp_path, monkeypatch): |
| 398 | """An edit lands between the read and the claim, so the compare fails: |
| 399 | nothing is billed, the empty header is deleted (releasing its number), |
| 400 | and the next run bills the hour under the first number.""" |
| 401 | data_dir = ttm.setup_env(tmp_path, monkeypatch) |
| 402 | ttm.rate_card(data_dir, "house", 15000) |
| 403 | approved_hours(data_dir, "t1") |
| 404 | real = object_records.update_collection_record |
| 405 | |
| 406 | def someone_else_first(collection, record_id, patch, **kwargs): |
| 407 | if collection == "time_logs" and kwargs.get("expected_rev"): |
| 408 | real(collection, record_id, {"notes": "edited meanwhile"}, |
| 409 | base_dir=kwargs["base_dir"]) |
| 410 | return real(collection, record_id, patch, **kwargs) |
| 411 | |
| 412 | monkeypatch.setattr(object_records, "update_collection_record", someone_else_first) |
| 413 | result = ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"}) |
| 414 | monkeypatch.setattr(object_records, "update_collection_record", real) |
| 415 | assert result["invoiced"] == 0 |
| 416 | assert ttm.invoices(data_dir) == [] |
| 417 | assert ttm.entry(data_dir, "t1")["status"] == "approved" |
| 418 | again = ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"}) |
| 419 | assert again["invoiced"] == 1 and again["number"] == "TM-proj-acm-2026-06-30" |
| 420 | |
| 421 | |
| 422 | # ============================================================================= |
| 423 | # bank statement imports: resume, refuse, converge |
| 424 | # ============================================================================= |
| 425 | |
| 426 | import test_bank_import as tbi # noqa: E402 |
| 427 | import test_bank_import_ofx as tbo # noqa: E402 |
| 428 | |
| 429 | |
| 430 | def bank_rows(data_dir, collection): |
| 431 | return object_records.read_collection_records(collection, base_dir=data_dir) |
| 432 | |
| 433 | |
| 434 | def test_a_resumed_import_puts_every_line_under_the_original_import( |
| 435 | tmp_path, monkeypatch): |
| 436 | import test_findings_actions as tfa |
| 437 | data_dir = tbi.setup_env(tmp_path, monkeypatch) |
| 438 | restore = tfa.fail_nth_write(monkeypatch, "bank_lines", 2) |
| 439 | crashed = execute(tbi.BANKING_OBJECTS, "action_import_bank_csv", { |
| 440 | "_identity": {"user_id": "dan"}, "bank_account_id": tbi.ACCOUNT, |
| 441 | "profile_id": tbi.PROFILE, "content": tbi.STATEMENT, |
| 442 | "opening_balance_cents": 0, "closing_balance_cents": 133265}) |
| 443 | restore() |
| 444 | assert not crashed.ok |
| 445 | [import_row] = bank_rows(data_dir, "bank_statement_imports") |
| 446 | |
| 447 | retry = tbi.import_statement() |
| 448 | assert retry["already_imported"] and retry["resumed"] and retry["imported"] == 2 |
| 449 | assert retry["import_id"] == import_row["id"] |
| 450 | assert {l["import_id"] for l in bank_rows(data_dir, "bank_lines")} == {import_row["id"]} |
| 451 | assert len(bank_rows(data_dir, "bank_statement_imports")) == 1 |
| 452 | |
| 453 | again = tbi.import_statement() # now complete: a no-op |
| 454 | assert again["already_imported"] and again["imported"] == 0 |
| 455 | assert "resumed" not in again |
| 456 | assert len(bank_rows(data_dir, "bank_lines")) == 3 |
| 457 | |
| 458 | |
| 459 | @pytest.mark.parametrize("collection", ["bank_statement_imports", "bank_lines"]) |
| 460 | def test_an_unreadable_history_refuses_the_import_and_writes_nothing( |
| 461 | tmp_path, monkeypatch, collection): |
| 462 | """The gate reads are strict now: an unreadable history is a 409, not |
| 463 | "never imported" / "no lines on file" (which put lines on file twice).""" |
| 464 | data_dir = tbi.setup_env(tmp_path, monkeypatch) |
| 465 | real = object_records.read_collection_records |
| 466 | |
| 467 | def failing(name, *a, **k): |
| 468 | if name == collection: |
| 469 | raise OSError(f"{name} unreadable") |
| 470 | return real(name, *a, **k) |
| 471 | |
| 472 | monkeypatch.setattr(object_records, "read_collection_records", failing) |
| 473 | outcome = execute(tbi.BANKING_OBJECTS, "action_import_bank_csv", { |
| 474 | "_identity": {"user_id": "dan"}, "bank_account_id": tbi.ACCOUNT, |
| 475 | "profile_id": tbi.PROFILE, "content": tbi.STATEMENT, |
| 476 | "opening_balance_cents": 0, "closing_balance_cents": 133265}) |
| 477 | monkeypatch.setattr(object_records, "read_collection_records", real) |
| 478 | assert outcome.ok and outcome.result["status"] == 409, outcome.result |
| 479 | assert f"{collection} unreadable" in outcome.result["error"] |
| 480 | assert bank_rows(data_dir, "bank_statement_imports") == [] |
| 481 | assert bank_rows(data_dir, "bank_lines") == [] |
| 482 | assert tbi.import_statement()["imported"] == 3 # readable again: normal |
| 483 | |
| 484 | |
| 485 | def test_racing_imports_of_one_file_land_one_import_and_no_doubled_lines( |
| 486 | tmp_path, monkeypatch): |
| 487 | """Three uploads of the same OFX file at once, every one past the |
| 488 | "already imported?" read before any writes. The derived import id lets |
| 489 | one import row in; the others are told it is already being imported.""" |
| 490 | data_dir = tbo.setup_env(tmp_path, monkeypatch) |
| 491 | results = race(3, lambda i: tbo.run({"bank_account_id": tbo.ACCOUNT, |
| 492 | "content": tbo.JULY}), |
| 493 | object_records, "create_collection_record") |
| 494 | assert len(bank_rows(data_dir, "bank_statement_imports")) == 1 |
| 495 | assert len(bank_rows(data_dir, "bank_lines")) == 2 |
| 496 | assert sum(r.get("imported", 0) for r in results) == 2 |
| 497 | assert sum(1 for r in results if r.get("already_imported")) == 2 |
| 498 | |
| 499 | |
| 500 | # ============================================================================= |
| 501 | # apply_count: one adjustment per stock state |
| 502 | # ============================================================================= |
| 503 | |
| 504 | def test_racing_counts_of_one_shelf_adjust_the_stock_once(tmp_path, monkeypatch): |
| 505 | """apply_count, the inventory twin: a shelf booked at 10 and counted at |
| 506 | 7, submitted three times at once. Before the fix it ended at 4 with the |
| 507 | shrinkage booked twice; now one adjustment lands and the others are |
| 508 | refused against the same stock.""" |
| 509 | import object_stock |
| 510 | import test_inventory_adjustments as tia |
| 511 | data_dir = tia.setup_env(tmp_path, monkeypatch) |
| 512 | tia.make_product(data_dir, cost="250") |
| 513 | tia.make_location(data_dir) |
| 514 | tia.make_move(data_dir, "mv-in", reason="purchase", qty="10", to_loc="loc1") |
| 515 | |
| 516 | results = race(3, lambda i: tia.apply_count({"product_id": "prod1", |
| 517 | "location_id": "loc1", |
| 518 | "counted_qty": "7"}), |
| 519 | object_records, "create_collection_record") |
| 520 | |
| 521 | assert object_stock.quantity_at_location("prod1", "loc1", base_dir=data_dir) == 7 |
| 522 | assert sorted(r["status"] for r in results) == [200, 409, 409], results |
| 523 | journals = object_records.read_collection_records("fin_journals", base_dir=data_dir) |
| 524 | assert len(journals) == 1, journals |
| 525 | again = tia.apply_count({"product_id": "prod1", "location_id": "loc1", |
| 526 | "counted_qty": "6"}) |
| 527 | assert again["status"] == 200 and again["variance"] == "-1" |
| 528 | |
| 529 | |
| 530 | # ============================================================================= |
| 531 | # compose_posted_journal: one journal per provenance marker |
| 532 | # ============================================================================= |
| 533 | |
| 534 | def test_racing_reversals_of_one_journal_post_one_mirror(tmp_path, monkeypatch): |
| 535 | """Four clicks on Reverse, every one past the "already reversed?" read |
| 536 | before any writes (the barrier sits at the first write). Before the |
| 537 | unique key, all four mirrors posted and the books reversed a 500 sale |
| 538 | four times. Now one lands; the others are told it is already reversed.""" |
| 539 | import object_finance |
| 540 | data_dir = q1_journal(tmp_path, monkeypatch) |
| 541 | |
| 542 | results = race(4, lambda i: execute( |
| 543 | FINANCE_OBJECTS, "action_reverse_journal", |
| 544 | {"journal_id": "j-q1", "date": "2026-04-01", "_identity": DAN}).result, |
| 545 | object_records, "create_collection_record") |
| 546 | |
| 547 | [mirror] = mirrors(data_dir) |
| 548 | assert mirror["status"] == "posted" |
| 549 | assert sorted(r["status"] for r in results) == [200, 409, 409, 409], results |
| 550 | assert object_finance.journal_totals(mirror["id"], base_dir=data_dir)[ |
| 551 | "total_debits_cents"] == 500 |
| 552 | stray = [l for l in object_records.read_collection_records( |
| 553 | "fin_journal_lines", base_dir=data_dir) |
| 554 | if l["journal_id"] not in {"j-q1", mirror["id"]}] |
| 555 | assert stray == [], "a losing reversal left lines behind" |
| 556 | |
| 557 | |
| 558 | def test_a_journal_already_composed_under_a_marker_is_answered_not_repeated( |
| 559 | tmp_path, monkeypatch): |
| 560 | """The storage-level answer, for every caller of compose_posted_journal |
| 561 | (payments, refunds, stock losses, wallet books, recurring journals): |
| 562 | a write that loses the marker to another is "already composed", with |
| 563 | the journal that holds it, and writes no lines.""" |
| 564 | import object_finance |
| 565 | data_dir = tpl.setup_env(tmp_path, monkeypatch) |
| 566 | spec = dict(generated_from="payments/p-1", date="2026-05-01", |
| 567 | description="Payment", owner_id="dan", |
| 568 | lines=[{"account_id": "acct-cash", "debit_cents": 700}, |
| 569 | {"account_id": "acct-cash", "credit_cents": 700}]) |
| 570 | # The second call is made as if its provenance scan had found nothing, |
| 571 | # which is exactly what a call that overlapped the first one saw. |
| 572 | first = object_finance.compose_posted_journal(data_dir, **spec) |
| 573 | monkeypatch.setattr(object_finance, "_scan_provenance", lambda *a, **k: None) |
| 574 | second = object_finance.compose_posted_journal(data_dir, **spec) |
| 575 | |
| 576 | assert first["posted"] is True |
| 577 | assert second["ok"] is True and second["journal_id"] == first["journal_id"] |
| 578 | assert "already composed" in second["skipped"] |
| 579 | assert len(object_records.read_collection_records( |
| 580 | "fin_journals", base_dir=data_dir)) == 1 |
| 581 | assert len(object_records.read_collection_records( |
| 582 | "fin_journal_lines", base_dir=data_dir)) == 2 |