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_assets_and_losses.py · 49.7 KB · 789 lines
| 1 | """Fixed assets, depreciation, disposals, improvements vs repairs, loss |
| 2 | events and decimal stock -- every flow through the real ASGI app. |
| 3 | |
| 4 | Each test builds a throwaway box (scripts/try_package.Sandbox: app-assets |
| 5 | and its dependencies installed, permission enforcement on) and acts as a |
| 6 | person would: through /collections/* and /objects/*. Reads that check the |
| 7 | books afterwards go through object_finance (the same fold the trial-balance |
| 8 | page uses), scoped to the owner. |
| 9 | |
| 10 | The money in these tests is checked against numbers worked out by hand in |
| 11 | the comments beside them, not against the code's own output: a test that |
| 12 | asserts whatever the function returned proves only that it returned it. |
| 13 | """ |
| 14 | |
| 15 | from __future__ import annotations |
| 16 | |
| 17 | import json |
| 18 | from pathlib import Path |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | import object_assets |
| 23 | import object_execution |
| 24 | import object_finance |
| 25 | import object_records |
| 26 | import python_object_runtime |
| 27 | from scripts.try_package import Sandbox |
| 28 | |
| 29 | ROOT = Path(__file__).resolve().parents[1] |
| 30 | PACKAGE = ROOT / "packages" / "app-assets" |
| 31 | |
| 32 | ACCOUNTS = [ |
| 33 | ("Cash", "asset", "1000"), ("Equipment", "asset", "1500"), |
| 34 | ("Accumulated depreciation", "asset", "1590"), ("Inventory", "asset", "1300"), |
| 35 | ("Insurance receivable", "asset", "1200"), ("Owner equity", "equity", "3000"), |
| 36 | ("Gain on disposal", "income", "4900"), ("Insurance recoveries", "income", "4910"), |
| 37 | ("Depreciation expense", "expense", "6100"), ("Repairs", "expense", "6200"), |
| 38 | ("Loss on disposal", "expense", "6900"), ("Shrinkage", "expense", "5100"), |
| 39 | ("Spoilage", "expense", "5110"), ("Evaporation", "expense", "5120"), |
| 40 | ("Theft losses", "expense", "6910"), |
| 41 | ] |
| 42 | SETTINGS = { |
| 43 | "assets.journal.cost_account": "Equipment", |
| 44 | "assets.journal.accumulated_account": "Accumulated depreciation", |
| 45 | "assets.journal.depreciation_account": "Depreciation expense", |
| 46 | "assets.journal.funding_account": "Cash", |
| 47 | "assets.journal.proceeds_account": "Cash", |
| 48 | "assets.journal.gain_account": "Gain on disposal", |
| 49 | "assets.journal.loss_account": "Loss on disposal", |
| 50 | "assets.journal.repair_account": "Repairs", |
| 51 | "assets.journal.insurance_receivable_account": "Insurance receivable", |
| 52 | "losses.journal.loss_account": "Theft losses", |
| 53 | "losses.journal.recovery_account": "Insurance recoveries", |
| 54 | "inventory.journal.inventory_account": "Inventory", |
| 55 | "inventory.journal.shrinkage_account": "Shrinkage", |
| 56 | "inventory.journal.waste_account": "Spoilage", |
| 57 | "inventory.journal.evaporation_account": "Evaporation", |
| 58 | } |
| 59 | |
| 60 | |
| 61 | class Books: |
| 62 | """A box with dan's chart of accounts and the account settings.""" |
| 63 | |
| 64 | def __init__(self, box, owner="dan"): |
| 65 | self.box = box |
| 66 | self.owner = owner |
| 67 | self.acct = {} |
| 68 | for name, kind, code in ACCOUNTS: |
| 69 | self.acct[name] = self.create("fin_accounts", {"name": name, "account_type": kind, "code": code}) |
| 70 | for key, name in SETTINGS.items(): |
| 71 | status, body = box.call("admin", "POST", "/collections/app_settings/records", |
| 72 | {"key": key, "value": self.acct[name]}) |
| 73 | assert status == 201, body |
| 74 | |
| 75 | def call(self, method, path, body=None, who=None): |
| 76 | return self.box.call(who or self.owner, method, path, body) |
| 77 | |
| 78 | def create(self, collection, record, who=None, expect=201): |
| 79 | who = who or self.owner |
| 80 | status, body = self.box.call(who, "POST", f"/collections/{collection}/records", |
| 81 | {"owner_id": who, **record}) |
| 82 | assert status == expect, (collection, status, body) |
| 83 | return body["record"]["id"] if status == 201 else body |
| 84 | |
| 85 | def put(self, collection, record_id, changes, who=None): |
| 86 | return self.box.call(who or self.owner, "PUT", f"/collections/{collection}/records/{record_id}", changes) |
| 87 | |
| 88 | def get(self, collection, record_id, who=None): |
| 89 | status, body = self.box.call(who or self.owner, "GET", f"/collections/{collection}/records/{record_id}") |
| 90 | assert status == 200, body |
| 91 | return body["record"] |
| 92 | |
| 93 | def run(self, as_of, who=None, **target): |
| 94 | status, body = self.box.call(who or self.owner, "POST", "/objects/action_asset_books", |
| 95 | {"as_of": as_of, **target}) |
| 96 | assert status == 200, body |
| 97 | return body |
| 98 | |
| 99 | def asset(self, name, cost, in_service, life, salvage=0, **extra): |
| 100 | return self.create("fixed_assets", { |
| 101 | "name": name, "cost_cents": cost, "placed_in_service_on": in_service, |
| 102 | "status": "in_service", "book_life_months": life, "book_salvage_cents": salvage, **extra}) |
| 103 | |
| 104 | def journals(self): |
| 105 | return [j for j in object_records.read_collection_records("fin_journals", base_dir=self.box.data_dir) |
| 106 | if j.get("owner_id") == self.owner] |
| 107 | |
| 108 | def journal(self, marker): |
| 109 | found = [j for j in self.journals() if j.get("generated_from") == marker] |
| 110 | assert len(found) == 1, (marker, found) |
| 111 | return found[0] |
| 112 | |
| 113 | def lines(self, journal_id): |
| 114 | return {(self.name_of(l["account_id"]), int(l["debit_cents"] or 0), int(l["credit_cents"] or 0)) |
| 115 | for l in object_records.read_collection_records("fin_journal_lines", base_dir=self.box.data_dir) |
| 116 | if l["journal_id"] == journal_id} |
| 117 | |
| 118 | def name_of(self, account_id): |
| 119 | return next(name for name, acct in self.acct.items() if acct == account_id) |
| 120 | |
| 121 | def balances(self): |
| 122 | """{account name: debit minus credit} over posted journals.""" |
| 123 | rows = object_finance.trial_balance(base_dir=self.box.data_dir, owner=self.owner) |
| 124 | return {self.name_of(r["account_id"]): r["debit_total_cents"] - r["credit_total_cents"] for r in rows} |
| 125 | |
| 126 | def hand_journal(self, date, description, debit, credit, amount, reference): |
| 127 | jid = self.create("fin_journals", {"date": date, "description": description, "reference": reference}) |
| 128 | self.create("fin_journal_lines", {"journal_id": jid, "account_id": self.acct[debit], "debit_cents": amount, |
| 129 | "credit_cents": 0}) |
| 130 | self.create("fin_journal_lines", {"journal_id": jid, "account_id": self.acct[credit], "debit_cents": 0, |
| 131 | "credit_cents": amount}) |
| 132 | status, body = self.put("fin_journals", jid, {"status": "posted"}) |
| 133 | assert status == 200, body |
| 134 | return jid |
| 135 | |
| 136 | |
| 137 | @pytest.fixture |
| 138 | def books(): |
| 139 | with Sandbox(["app-assets"]) as box: |
| 140 | box.add_user("dan", roles=["owner"]) # the owner keeps the books (decision 5) |
| 141 | box.add_user("mgr", roles=["manager"]) |
| 142 | box.add_user("eve") |
| 143 | yield Books(box) |
| 144 | |
| 145 | |
| 146 | def react(box, handler_id, payload): |
| 147 | """Run a HANDLES handler exactly as object_change_dispatch does: method |
| 148 | EVENT, the change's payload, the installed objects.""" |
| 149 | runtime = python_object_runtime.PythonObjectRuntime(base_dir=box.data_dir) |
| 150 | result = object_execution.execute_object( |
| 151 | runtime, object_execution.ObjectExecutionRequest(handler_id, method="EVENT", payload=payload), |
| 152 | roots=[box.objects_dir]) |
| 153 | assert result.ok, result.error |
| 154 | return result.result |
| 155 | |
| 156 | |
| 157 | def depreciation_markers(books, asset_id): |
| 158 | prefix = f"fixed_assets/{asset_id}/depreciation/" |
| 159 | return sorted(j["generated_from"][len(prefix):] for j in books.journals() |
| 160 | if str(j.get("generated_from") or "").startswith(prefix)) |
| 161 | |
| 162 | |
| 163 | # --- the package is wired -------------------------------------------------- |
| 164 | |
| 165 | def test_the_schemas_name_the_hooks_and_checks_the_manifest_ships(): |
| 166 | """A hook or check is wired by the schema and found by object id; a name |
| 167 | that matches nothing installs cleanly and refuses every write (503).""" |
| 168 | manifest = json.loads((PACKAGE / "dbbasic-package.json").read_text()) |
| 169 | objects = {o["id"] for o in manifest["objects"]} |
| 170 | for path in (PACKAGE / "schemas").glob("*.json"): |
| 171 | schema = json.loads(path.read_text()) |
| 172 | for check in schema.get("locked_checks", []): |
| 173 | assert check["object"] in objects, (path.name, check) |
| 174 | hook = schema.get("hooks", {}).get("before_write") |
| 175 | if hook: |
| 176 | assert hook in objects |
| 177 | loss = json.loads((PACKAGE / "schemas" / "loss_events.json").read_text()) |
| 178 | assert loss["hooks"] == {"before_write": "hook_loss_events"} |
| 179 | assert {s["object_id"] for s in manifest["schedules"]} == {"system_asset_books"} |
| 180 | source = (PACKAGE / "objects" / "system" / "asset_books.py").read_text() |
| 181 | assert "POST = EVENT" in source, "the scheduler calls POST, the dispatcher EVENT" |
| 182 | |
| 183 | |
| 184 | # --- the arithmetic, by hand ------------------------------------------------ |
| 185 | |
| 186 | def test_straight_line_puts_the_odd_cents_where_the_running_total_crosses_them(): |
| 187 | # 1000 over 3 months: floor(1000*1/3)=333, floor(1000*2/3)=666, 1000. |
| 188 | assert object_assets.component_amounts(1000, 0, 3, "straight_line") == [333, 333, 334] |
| 189 | # 30000.00 cost, 6000.00 salvage, 60 months: 2,400,000 / 60 = 40,000 a month. |
| 190 | amounts = object_assets.component_amounts(3_000_000, 600_000, 60, "straight_line") |
| 191 | assert set(amounts) == {40_000} and sum(amounts) == 2_400_000 |
| 192 | |
| 193 | |
| 194 | def test_declining_balance_switches_to_straight_line_and_stops_at_salvage(): |
| 195 | # cost 10000, salvage 1000, 4 months, double declining (2/4 = 50% a month): |
| 196 | # m1 10000*.5=5000 (SL 9000/4=2250); m2 5000*.5=2500 (SL 4000/3=1333); |
| 197 | # m3 2500*.5=1250 (SL 1500/2=750); m4 the rest above salvage: 1250-1000=250. |
| 198 | assert object_assets.component_amounts(10_000, 1_000, 4, "declining", 20_000) == [5000, 2500, 1250, 250] |
| 199 | # 150% over 10 months on 100000, salvage 10000: never below salvage, exactly to it. |
| 200 | amounts = object_assets.component_amounts(100_000, 10_000, 10, "declining", 15_000) |
| 201 | assert sum(amounts) == 90_000 and all(a >= 0 for a in amounts) |
| 202 | assert object_assets.component_amounts(5000, 0, 12, "none") == [] |
| 203 | |
| 204 | |
| 205 | def test_disposal_gain_and_loss_by_hand(): |
| 206 | # cost 12,000.00, 18 months of 250.00 = 4,500.00 accumulated, NBV 7,500.00. |
| 207 | sold_low = object_assets.disposal_result(1_200_000, 450_000, 700_000, 0) |
| 208 | assert sold_low["net_book_value_cents"] == 750_000 |
| 209 | assert sold_low["gain_loss_cents"] == -50_000 # 7,000 - 7,500 |
| 210 | sold_high = object_assets.disposal_result(1_200_000, 450_000, 800_000, 0) |
| 211 | assert sold_high["gain_loss_cents"] == 50_000 # 8,000 - 7,500 |
| 212 | accounts = {k: k for k in ("cost", "accumulated", "proceeds", "insurance", "gain", "loss")} |
| 213 | lines = object_assets.disposal_lines(sold_low, accounts) |
| 214 | assert sum(l["debit_cents"] for l in lines) == sum(l["credit_cents"] for l in lines) == 1_200_000 |
| 215 | |
| 216 | |
| 217 | # --- depreciation through HTTP ---------------------------------------------- |
| 218 | |
| 219 | def test_monthly_depreciation_posts_once_per_asset_month_and_replays_post_nothing(books): |
| 220 | van = books.asset("Van", 3_000_000, "2025-01-10", 60, salvage=600_000) |
| 221 | first = books.run("2025-06-30", asset_id=van) |
| 222 | assert first["ok"] and first["posted"] == 7 # capitalization + Jan..Jun |
| 223 | assert depreciation_markers(books, van) == [f"2025-0{m}" for m in range(1, 7)] |
| 224 | june = books.journal(f"fixed_assets/{van}/depreciation/2025-06") |
| 225 | assert june["date"] == "2025-06-30" and june["status"] == "posted" |
| 226 | assert books.lines(june["id"]) == {("Depreciation expense", 40_000, 0), |
| 227 | ("Accumulated depreciation", 0, 40_000)} |
| 228 | count = len(books.journals()) |
| 229 | # The same run again, the whole-register run, and the scheduled pass's |
| 230 | # reaction for this asset: nothing new. |
| 231 | assert books.run("2025-06-30", asset_id=van)["posted"] == 0 |
| 232 | assert books.run("2025-06-30")["posted"] == 0 |
| 233 | status, body = books.box.call("admin", "POST", "/objects/system_asset_books", |
| 234 | {"collection": "fixed_assets", "record_id": van}) |
| 235 | assert status == 200 and body["ok"] |
| 236 | # (the reaction runs as of today, so it books the months since June -- |
| 237 | # still once each, and never June again) |
| 238 | markers = depreciation_markers(books, van) |
| 239 | assert len(markers) == len(set(markers)) |
| 240 | assert books.run("2025-06-30", asset_id=van)["posted"] == 0 |
| 241 | assert len(books.journals()) == count + len(markers) - 6 |
| 242 | balances = books.balances() |
| 243 | assert sum(balances.values()) == 0 |
| 244 | |
| 245 | |
| 246 | def test_a_month_is_booked_after_it_ends_and_never_ahead_of_time(books): |
| 247 | van = books.asset("Van", 3_000_000, "2025-01-10", 60, salvage=600_000) |
| 248 | books.run("2025-04-29", asset_id=van) |
| 249 | assert depreciation_markers(books, van) == ["2025-01", "2025-02", "2025-03"] |
| 250 | status, body = books.call("POST", "/objects/action_asset_books", {"as_of": "2999-01-31", "asset_id": van}) |
| 251 | assert status == 400 and "ahead of time" in body["error"] |
| 252 | |
| 253 | |
| 254 | def test_depreciation_stops_at_end_of_life_on_salvage(books): |
| 255 | # 1,000.00 over 3 months, salvage 100.00: 300, 300, 300; nothing after. |
| 256 | tool = books.asset("Drill", 100_000, "2025-01-20", 3, salvage=10_000) |
| 257 | books.run("2025-12-31", asset_id=tool) |
| 258 | assert depreciation_markers(books, tool) == ["2025-01", "2025-02", "2025-03"] |
| 259 | balances = books.balances() |
| 260 | assert balances["Accumulated depreciation"] == -90_000 # NBV 100.00 = salvage |
| 261 | |
| 262 | |
| 263 | def test_a_closed_period_books_on_the_first_open_day_flagged_for_review(books): |
| 264 | books.create("fin_closed_periods", {"start_date": "2025-01-01", "end_date": "2025-03-31", |
| 265 | "reason": "Q1 filed"}) |
| 266 | van = books.asset("Van", 3_000_000, "2025-01-10", 60, salvage=600_000) |
| 267 | books.run("2025-04-30", asset_id=van) |
| 268 | for month in ("2025-01", "2025-02", "2025-03"): |
| 269 | journal = books.journal(f"fixed_assets/{van}/depreciation/{month}") |
| 270 | assert journal["date"] == "2025-04-01" |
| 271 | assert journal["occurred_on"] == object_assets.month_end(month) |
| 272 | assert journal["period_review"] == "pending" and journal["status"] == "posted" |
| 273 | capital = books.journal(f"fixed_assets/{van}/capitalization") |
| 274 | assert capital["date"] == "2025-04-01" and capital["occurred_on"] == "2025-01-10" |
| 275 | april = books.journal(f"fixed_assets/{van}/depreciation/2025-04") |
| 276 | assert april["date"] == "2025-04-30" and not april.get("period_review") |
| 277 | # Nothing landed inside the closed quarter. |
| 278 | assert not [j for j in books.journals() if "2025-01-01" <= j["date"] <= "2025-03-31"] |
| 279 | assert books.run("2025-04-30", asset_id=van)["posted"] == 0 |
| 280 | |
| 281 | |
| 282 | def test_an_unconfigured_account_waits_and_books_nothing(books): |
| 283 | status, rows = books.box.call("admin", "GET", "/collections/app_settings/records?key=assets.journal.funding_account") |
| 284 | setting = rows["records"][0]["id"] |
| 285 | assert books.box.call("admin", "DELETE", f"/collections/app_settings/records/{setting}")[0] in (200, 204) |
| 286 | van = books.asset("Van", 3_000_000, "2025-01-10", 60) |
| 287 | report = books.run("2025-06-30", asset_id=van) |
| 288 | waiting = report["assets"][0]["waiting"] |
| 289 | assert waiting[0]["step"] == "capitalization" and "funding" in waiting[0]["needs"][0] |
| 290 | assert report["posted"] == 0 and not books.journals() |
| 291 | # Booked elsewhere: depreciation goes ahead without a capitalization. |
| 292 | other = books.asset("Oven", 1_200_000, "2025-01-10", 48, capitalization="booked_elsewhere") |
| 293 | assert books.run("2025-02-28", asset_id=other)["posted"] == 2 |
| 294 | |
| 295 | |
| 296 | def test_an_in_service_asset_is_frozen_and_only_a_posted_disposal_disposes_it(books): |
| 297 | van = books.asset("Van", 3_000_000, "2025-01-10", 60) |
| 298 | status, body = books.put("fixed_assets", van, {"cost_cents": 1}) |
| 299 | assert status == 409 and body["code"] == "record_locked" |
| 300 | assert books.put("fixed_assets", van, {"location": "Depot 2", "custodian": "Sam"})[0] == 200 |
| 301 | status, body = books.put("fixed_assets", van, {"status": "disposed"}) |
| 302 | assert status == 409 and body["code"] == "check_refused" |
| 303 | assert books.box.call("dan", "DELETE", f"/collections/fixed_assets/records/{van}")[0] == 409 |
| 304 | refused = books.create("fixed_assets", {"name": "x", "cost_cents": 5, "status": "disposed", |
| 305 | "placed_in_service_on": "2025-01-01", "book_life_months": 12}, |
| 306 | expect=409) |
| 307 | assert refused["code"] == "check_refused" |
| 308 | |
| 309 | |
| 310 | # --- disposals -------------------------------------------------------------- |
| 311 | |
| 312 | def test_a_sale_below_book_value_books_the_loss_worked_by_hand(books): |
| 313 | # Cost 12,000.00 in service Jan 2024, 48 months, no salvage: 250.00 a |
| 314 | # month. Sold 2025-07-15: Jan 2024..Jun 2025 is 18 months = 4,500.00 |
| 315 | # accumulated (July, the month of sale, is not depreciated). NBV |
| 316 | # 7,500.00; sold for 7,000.00: a loss of 500.00. |
| 317 | press = books.asset("Press", 1_200_000, "2024-01-05", 48) |
| 318 | books.run("2025-05-31", asset_id=press) |
| 319 | sale = books.create("asset_disposals", {"asset_id": press, "disposed_on": "2025-07-15", "kind": "sale", |
| 320 | "proceeds_cents": 700_000, "counterparty": "A. Buyer", |
| 321 | "evidence_refs": "bill of sale BS-77"}) |
| 322 | books.run("2025-12-31", asset_id=press) |
| 323 | stamped = books.get("asset_disposals", sale) |
| 324 | assert stamped["status"] == "posted" |
| 325 | assert (stamped["cost_basis_cents"], stamped["accumulated_depreciation_cents"], |
| 326 | stamped["net_book_value_cents"], stamped["gain_loss_cents"]) == ("1200000", "450000", "750000", "-50000") |
| 327 | journal = books.journal(f"asset_disposals/{sale}") |
| 328 | assert journal["date"] == "2025-07-15" and stamped["journal_id"] == journal["id"] |
| 329 | assert books.lines(journal["id"]) == {("Accumulated depreciation", 450_000, 0), ("Cash", 700_000, 0), |
| 330 | ("Loss on disposal", 50_000, 0), ("Equipment", 0, 1_200_000)} |
| 331 | assert depreciation_markers(books, press)[-1] == "2025-06" # nothing after disposal |
| 332 | assert books.get("fixed_assets", press)["status"] == "disposed" |
| 333 | assert books.put("fixed_assets", press, {"location": "gone"})[0] == 409 |
| 334 | assert books.put("asset_disposals", sale, {"proceeds_cents": 1})[0] == 409 |
| 335 | balances = books.balances() |
| 336 | assert balances.get("Equipment", 0) == 0 and balances.get("Accumulated depreciation", 0) == 0 |
| 337 | assert balances["Loss on disposal"] == 50_000 and sum(balances.values()) == 0 |
| 338 | assert books.run("2025-12-31", asset_id=press)["posted"] == 0 |
| 339 | |
| 340 | |
| 341 | def test_a_sale_above_book_value_books_the_gain(books): |
| 342 | press = books.asset("Press", 1_200_000, "2024-01-05", 48) |
| 343 | sale = books.create("asset_disposals", {"asset_id": press, "disposed_on": "2025-07-15", "kind": "sale", |
| 344 | "proceeds_cents": 800_000, "evidence_refs": "BS-78"}) |
| 345 | books.run("2025-12-31", asset_id=press) |
| 346 | journal = books.journal(f"asset_disposals/{sale}") |
| 347 | assert books.lines(journal["id"]) == {("Accumulated depreciation", 450_000, 0), ("Cash", 800_000, 0), |
| 348 | ("Equipment", 0, 1_200_000), ("Gain on disposal", 0, 50_000)} |
| 349 | |
| 350 | |
| 351 | def test_a_theft_is_booked_only_once_somebody_else_approves_its_loss_event(books): |
| 352 | # Laptop 2,400.00, 24 months, in service Feb 2025: 100.00 a month. |
| 353 | # Stolen 2025-09-14: Feb..Aug = 7 months, 700.00. NBV 1,700.00, loss 1,700.00. |
| 354 | laptop = books.asset("Laptop", 240_000, "2025-02-03", 24) |
| 355 | event = books.create("loss_events", {"occurred_on": "2025-09-14", "discovered_on": "2025-09-15", |
| 356 | "kind": "theft", "subject": "equipment", "asset_id": laptop, |
| 357 | "what": "Laptop taken from the van", |
| 358 | "how_discovered": "Van found unlocked on Monday morning", |
| 359 | "estimated_amount_cents": 170_000}) |
| 360 | disposal = books.create("asset_disposals", {"asset_id": laptop, "disposed_on": "2025-09-14", "kind": "theft", |
| 361 | "evidence_refs": "police report 25-11873", |
| 362 | "loss_event_id": event}) |
| 363 | report = books.run("2025-12-31", asset_id=laptop) |
| 364 | assert "approved" in report["assets"][0]["waiting"][0]["reason"] |
| 365 | assert books.get("asset_disposals", disposal).get("status", "") == "" |
| 366 | # The reporter cannot approve it; approving needs evidence and a final amount. |
| 367 | status, body = books.put("loss_events", event, {"status": "approved"}, who="mgr") |
| 368 | assert status == 400 and "required" in body["error"] |
| 369 | status, body = books.put("loss_events", event, {"status": "approved", "final_amount_cents": 170_000, |
| 370 | "evidence_refs": "police report 25-11873"}) |
| 371 | assert status == 403 and "somebody other" in body["error"] |
| 372 | status, body = books.put("loss_events", event, {"status": "approved", "final_amount_cents": 170_000, |
| 373 | "evidence_refs": "police report 25-11873"}, who="mgr") |
| 374 | assert status == 200, body |
| 375 | approved = books.get("loss_events", event) |
| 376 | assert approved["reported_by"] == "dan" and approved["approved_by"] == "mgr" and approved["approved_at"] |
| 377 | books.run("2025-12-31", asset_id=laptop) |
| 378 | journal = books.journal(f"asset_disposals/{disposal}") |
| 379 | assert books.lines(journal["id"]) == {("Accumulated depreciation", 70_000, 0), |
| 380 | ("Loss on disposal", 170_000, 0), ("Equipment", 0, 240_000)} |
| 381 | |
| 382 | |
| 383 | def test_a_casualty_with_insurance_books_the_recovery_once(books): |
| 384 | # Freezer 4,800.00 / 48 months from Mar 2025: 100.00 a month. Burst pipe |
| 385 | # 2025-11-03: Mar..Oct = 800.00. NBV 4,000.00; insurer pays 3,500.00: |
| 386 | # a loss of 500.00, and the recovery is on the disposal, not twice. |
| 387 | freezer = books.asset("Freezer", 480_000, "2025-03-01", 48) |
| 388 | event = books.create("loss_events", {"occurred_on": "2025-11-03", "kind": "casualty", "subject": "equipment", |
| 389 | "asset_id": freezer, "what": "Freezer destroyed by a burst pipe", |
| 390 | "how_discovered": "Water on the floor at opening", |
| 391 | "evidence_refs": "photos IMG_4410-4418; plumber invoice 993", |
| 392 | "estimated_amount_cents": 400_000, "insurance_status": "claimed", |
| 393 | "insurance_claim_ref": "CLM-5521"}) |
| 394 | assert books.put("loss_events", event, {"status": "approved", "final_amount_cents": 400_000}, |
| 395 | who="mgr")[0] == 200 |
| 396 | assert books.put("loss_events", event, {"insurance_status": "paid", "insurance_recovery_cents": 350_000, |
| 397 | "recovered_on": "2025-11-28"})[0] == 200 |
| 398 | disposal = books.create("asset_disposals", {"asset_id": freezer, "disposed_on": "2025-11-03", |
| 399 | "kind": "casualty", "insurance_recovery_cents": 350_000, |
| 400 | "evidence_refs": "adjuster report CLM-5521", |
| 401 | "loss_event_id": event}) |
| 402 | books.run("2025-12-31") |
| 403 | journal = books.journal(f"asset_disposals/{disposal}") |
| 404 | assert books.lines(journal["id"]) == {("Accumulated depreciation", 80_000, 0), |
| 405 | ("Insurance receivable", 350_000, 0), |
| 406 | ("Loss on disposal", 50_000, 0), ("Equipment", 0, 480_000)} |
| 407 | assert not [j for j in books.journals() if j.get("generated_from") == f"loss_events/{event}/recovery"] |
| 408 | # paid is final: the recovery cannot be restated. |
| 409 | assert books.put("loss_events", event, {"insurance_recovery_cents": 1})[0] == 409 |
| 410 | |
| 411 | |
| 412 | def test_a_disposal_cannot_be_dated_before_service_or_in_the_future(books): |
| 413 | van = books.asset("Van", 3_000_000, "2025-01-10", 60) |
| 414 | books.create("asset_disposals", {"asset_id": van, "disposed_on": "2024-12-01", "kind": "scrap"}, expect=409) |
| 415 | books.create("asset_disposals", {"asset_id": van, "disposed_on": "2999-01-01", "kind": "scrap"}, expect=409) |
| 416 | books.create("asset_disposals", {"asset_id": van, "disposed_on": "2025-05-01", "kind": "theft"}, expect=400) |
| 417 | draft = books.create("fixed_assets", {"name": "Spare", "cost_cents": 100, "book_life_months": 12}) |
| 418 | books.create("asset_disposals", {"asset_id": draft, "disposed_on": "2025-05-01", "kind": "scrap"}, expect=409) |
| 419 | |
| 420 | |
| 421 | # --- improvements and repairs ----------------------------------------------- |
| 422 | |
| 423 | def test_a_repair_is_expensed_and_an_improvement_is_capitalized_and_depreciated(books): |
| 424 | # Van 36,000.00, salvage 6,000.00, 60 months: 500.00 a month from Jan. |
| 425 | # Paint job (repair) 1,800.00 in April: an expense, schedule unchanged. |
| 426 | # Engine rebuild (improvement) 7,200.00 in August over 36 months: +200.00 |
| 427 | # a month from August. |
| 428 | van = books.asset("Van", 3_600_000, "2025-01-10", 60, salvage=600_000) |
| 429 | paint = books.create("asset_work", {"asset_id": van, "performed_on": "2025-04-12", "amount_cents": 180_000, |
| 430 | "description": "Repaint scratched panels", "treatment": "repair", |
| 431 | "basis": "routine_maintenance", |
| 432 | "reason": "Restores its ordinary condition; adds no life or value", |
| 433 | "evidence_refs": "invoice PB-118"}) |
| 434 | engine = books.create("asset_work", {"asset_id": van, "performed_on": "2025-08-20", "amount_cents": 720_000, |
| 435 | "description": "Engine rebuild", "treatment": "improvement", |
| 436 | "basis": "restoration", "life_months": 36, |
| 437 | "reason": "Rebuilt engine extends the van's life by three years", |
| 438 | "evidence_refs": "invoice GA-2291"}) |
| 439 | books.run("2025-12-31", asset_id=van) |
| 440 | assert books.lines(books.journal(f"asset_work/{paint}")["id"]) == {("Repairs", 180_000, 0), ("Cash", 0, 180_000)} |
| 441 | assert books.lines(books.journal(f"asset_work/{engine}")["id"]) == {("Equipment", 720_000, 0), |
| 442 | ("Cash", 0, 720_000)} |
| 443 | july = books.journal(f"fixed_assets/{van}/depreciation/2025-07") |
| 444 | august = books.journal(f"fixed_assets/{van}/depreciation/2025-08") |
| 445 | assert ("Depreciation expense", 50_000, 0) in books.lines(july["id"]) |
| 446 | assert ("Depreciation expense", 70_000, 0) in books.lines(august["id"]) |
| 447 | balances = books.balances() |
| 448 | assert balances["Accumulated depreciation"] == -(12 * 50_000 + 5 * 20_000) |
| 449 | assert balances["Repairs"] == 180_000 and balances["Equipment"] == 4_320_000 |
| 450 | assert books.get("asset_work", engine)["status"] == "posted" |
| 451 | assert books.put("asset_work", engine, {"amount_cents": 1})[0] == 409 |
| 452 | assert books.put("asset_work", engine, {"notes": "warranty 24 months"})[0] == 200 |
| 453 | |
| 454 | |
| 455 | def test_a_late_improvement_is_caught_up_in_the_next_unbooked_month(books): |
| 456 | # 1,200.00 over 12 months from Jan = 100.00 a month; booked Jan..Jun. |
| 457 | # An improvement of 600.00 dated March, 6 months life, recorded in July: |
| 458 | # March..June already booked without it (4 x 100.00 missing), so July |
| 459 | # books 100.00 + 4 x 100.00 + 100.00 = 600.00, and the totals agree. |
| 460 | tool = books.asset("Lathe", 120_000, "2025-01-02", 12) |
| 461 | books.run("2025-06-30", asset_id=tool) |
| 462 | books.create("asset_work", {"asset_id": tool, "performed_on": "2025-03-05", "amount_cents": 60_000, |
| 463 | "description": "Digital readout", "treatment": "improvement", |
| 464 | "basis": "betterment", "life_months": 6, |
| 465 | "reason": "Adds a capability it did not have"}) |
| 466 | books.run("2025-07-31", asset_id=tool) |
| 467 | july = books.journal(f"fixed_assets/{tool}/depreciation/2025-07") |
| 468 | assert ("Depreciation expense", 60_000, 0) in books.lines(july["id"]) |
| 469 | status, body = books.call("GET", f"/objects/action_asset_books?asset_id={tool}") |
| 470 | assert status == 200 |
| 471 | july_row = next(r for r in body["book"]["rows"] if r["month"] == "2025-07") |
| 472 | assert july_row["accumulated_cents"] == body["booked_total_cents"] == 7 * 10_000 + 5 * 10_000 |
| 473 | |
| 474 | |
| 475 | def test_work_must_fit_the_asset_and_its_rule_of_thumb(books): |
| 476 | van = books.asset("Van", 3_000_000, "2025-01-10", 60) |
| 477 | base = {"asset_id": van, "performed_on": "2025-05-01", "amount_cents": 100, "description": "x", "reason": "why not"} |
| 478 | books.create("asset_work", {**base, "treatment": "improvement", "basis": "routine_maintenance"}, expect=409) |
| 479 | books.create("asset_work", {**base, "treatment": "repair", "basis": "betterment"}, expect=409) |
| 480 | books.create("asset_work", {**base, "performed_on": "2024-12-31", "treatment": "repair", |
| 481 | "basis": "routine_maintenance"}, expect=409) |
| 482 | books.create("asset_work", {**base, "performed_on": "2999-01-01", "treatment": "repair", |
| 483 | "basis": "routine_maintenance"}, expect=409) |
| 484 | books.create("asset_work", {**base, "treatment": "repair", "basis": "de_minimis"}) |
| 485 | |
| 486 | |
| 487 | # --- loss events -------------------------------------------------------------- |
| 488 | |
| 489 | def test_an_unapproved_loss_is_counted_until_somebody_else_decides_it(books): |
| 490 | status, body = books.box.call("dan", "GET", "/objects/action_nav_entries") |
| 491 | assert "losses_to_approve" not in {row["id"] for row in body["attention"]} |
| 492 | event = books.create("loss_events", {"occurred_on": "2025-05-02", "kind": "shrinkage", "subject": "inventory", |
| 493 | "what": "Two cases of tonic", "how_discovered": "Shelf count", |
| 494 | "estimated_amount_cents": 4_800}) |
| 495 | for who in ("dan", "mgr"): |
| 496 | status, body = books.box.call(who, "GET", "/objects/action_nav_entries") |
| 497 | rows = {row["id"]: row for row in body["attention"]} |
| 498 | assert rows["losses_to_approve"]["count"] == 1, who |
| 499 | status, body = books.box.call("eve", "GET", "/objects/action_nav_entries") |
| 500 | assert "losses_to_approve" not in {row["id"] for row in body["attention"]} |
| 501 | assert books.put("loss_events", event, {"status": "rejected"}, who="mgr")[0] == 200 |
| 502 | status, body = books.box.call("dan", "GET", "/objects/action_nav_entries") |
| 503 | assert "losses_to_approve" not in {row["id"] for row in body["attention"]} |
| 504 | |
| 505 | |
| 506 | def test_the_stamps_are_never_typed_and_an_approved_loss_is_frozen(books): |
| 507 | status, body = books.call("POST", "/collections/loss_events/records", { |
| 508 | "owner_id": "dan", "occurred_on": "2025-05-02", "kind": "other", "subject": "other", "what": "Float", |
| 509 | "how_discovered": "Till short", "reported_by": "mgr", "approved_by": "mgr"}) |
| 510 | assert status == 201 |
| 511 | event = body["record"]["id"] |
| 512 | assert body["record"]["reported_by"] == "dan" and not body["record"].get("approved_by") |
| 513 | assert books.put("loss_events", event, {"reported_by": "eve"})[0] == 400 |
| 514 | assert books.create("loss_events", {"occurred_on": "2025-05-02", "kind": "other", "subject": "other", |
| 515 | "what": "x", "how_discovered": "y", "status": "approved"}, expect=400) |
| 516 | assert books.put("loss_events", event, {"status": "approved", "final_amount_cents": 2_000, |
| 517 | "evidence_refs": "till roll 0502"}, who="mgr")[0] == 200 |
| 518 | assert books.put("loss_events", event, {"what": "Something else"}, who="mgr")[0] == 409 |
| 519 | assert books.box.call("dan", "DELETE", f"/collections/loss_events/records/{event}")[0] in (403, 409) |
| 520 | # Other people's losses are not theirs to see. |
| 521 | assert books.box.call("eve", "GET", f"/collections/loss_events/records/{event}")[0] in (403, 404) |
| 522 | |
| 523 | |
| 524 | def test_the_locked_check_refuses_a_self_approval_from_any_writer(books): |
| 525 | with pytest.raises(object_records.CheckRefusedError): |
| 526 | object_records.create_collection_record("loss_events", { |
| 527 | "id": "le-1", "occurred_on": "2025-01-01", "kind": "other", "subject": "other", "what": "x", |
| 528 | "how_discovered": "y", "status": "approved", "reported_by": "dan", "approved_by": "dan", |
| 529 | "final_amount_cents": "1", "evidence_refs": "z", "owner_id": "dan"}, base_dir=books.box.data_dir) |
| 530 | |
| 531 | |
| 532 | def test_a_loss_nothing_else_books_is_written_off_on_approval_and_recovered_once(books): |
| 533 | # A stolen cash float of 200.00, insured; the insurer pays 150.00. |
| 534 | event = books.create("loss_events", {"occurred_on": "2025-05-02", "kind": "theft", "subject": "other", |
| 535 | "what": "Cash float taken from the till", "how_discovered": "Till short at close", |
| 536 | "write_off_account_id": books.acct["Cash"], |
| 537 | "evidence_refs": "police report 25-7781; till roll 0502", |
| 538 | "insurance_status": "claimed", "insurance_claim_ref": "CLM-90"}) |
| 539 | books.run("2025-12-31", loss_event_id=event) |
| 540 | assert not [j for j in books.journals() if str(j.get("generated_from")).startswith("loss_events/")] |
| 541 | books.put("loss_events", event, {"status": "approved", "final_amount_cents": 20_000}, who="mgr") |
| 542 | books.run("2025-12-31", loss_event_id=event) |
| 543 | writeoff = books.journal(f"loss_events/{event}") |
| 544 | assert books.lines(writeoff["id"]) == {("Theft losses", 20_000, 0), ("Cash", 0, 20_000)} |
| 545 | books.put("loss_events", event, {"insurance_status": "paid", "insurance_recovery_cents": 15_000, |
| 546 | "recovered_on": "2025-06-30"}) |
| 547 | books.run("2025-12-31", loss_event_id=event) |
| 548 | books.run("2025-12-31") |
| 549 | recovery = books.journal(f"loss_events/{event}/recovery") |
| 550 | assert recovery["date"] == "2025-06-30" |
| 551 | assert books.lines(recovery["id"]) == {("Insurance receivable", 15_000, 0), ("Insurance recoveries", 0, 15_000)} |
| 552 | stamped = books.get("loss_events", event) |
| 553 | assert stamped["writeoff_journal_id"] == writeoff["id"] and stamped["recovery_journal_id"] == recovery["id"] |
| 554 | |
| 555 | |
| 556 | # --- permissions ------------------------------------------------------------------ |
| 557 | |
| 558 | def test_somebody_elses_assets_are_not_found(books): |
| 559 | van = books.asset("Van", 3_000_000, "2025-01-10", 60) |
| 560 | assert books.box.call("eve", "GET", f"/collections/fixed_assets/records/{van}")[0] in (403, 404) |
| 561 | status, body = books.box.call("eve", "POST", "/objects/action_asset_books", {"asset_id": van}) |
| 562 | assert status == 404 |
| 563 | assert books.box.call("eve", "GET", f"/objects/action_asset_books?asset_id={van}")[0] == 404 |
| 564 | assert books.box.call("eve", "GET", f"/objects/site_asset_schedule?asset_id={van}")[0] == 404 |
| 565 | status, body = books.box.call("eve", "POST", "/collections/asset_work/records", { |
| 566 | "owner_id": "eve", "asset_id": van, "performed_on": "2025-05-01", "amount_cents": 1, "description": "x", |
| 567 | "treatment": "repair", "basis": "routine_maintenance", "reason": "mine now"}) |
| 568 | assert status == 400 and "missing record" in body["error"] |
| 569 | # eve's whole-register run touches nothing of dan's. |
| 570 | status, body = books.box.call("eve", "POST", "/objects/action_asset_books", {"as_of": "2025-06-30"}) |
| 571 | assert status == 200 and body["assets"] == [] and not books.journals() |
| 572 | status, page = books.call("GET", f"/objects/site_asset_schedule?asset_id={van}") |
| 573 | assert status == 200 and "Book depreciation" in page and "ask your accountant" in page |
| 574 | |
| 575 | |
| 576 | def test_tax_columns_are_shown_and_never_booked(books): |
| 577 | van = books.asset("Van", 3_000_000, "2025-01-10", 60, tax_method="operator_entered") |
| 578 | books.create("asset_tax_entries", {"asset_id": van, "tax_year": 2025, "amount_cents": 600_000, |
| 579 | "basis_note": "MACRS 5-year half-year, per accountant letter 2026-02-10"}) |
| 580 | books.run("2025-12-31", asset_id=van) |
| 581 | status, body = books.call("GET", f"/objects/action_asset_books?asset_id={van}") |
| 582 | assert body["tax"]["rows"] == [{"year": 2025, "amount_cents": 600_000, |
| 583 | "basis_note": "MACRS 5-year half-year, per accountant letter 2026-02-10"}] |
| 584 | assert "ask your accountant" in body["tax"]["note"] |
| 585 | assert books.balances()["Depreciation expense"] == 12 * 50_000 # book, not tax |
| 586 | simple = books.asset("Oven", 1_200_000, "2025-07-01", 120, tax_method="straight_line", tax_life_months=60) |
| 587 | status, body = books.call("GET", f"/objects/action_asset_books?asset_id={simple}") |
| 588 | assert body["tax"]["rows"] == [{"year": 2025, "amount_cents": 6 * 20_000, "basis_note": "simple method"}, |
| 589 | {"year": 2026, "amount_cents": 12 * 20_000, "basis_note": "simple method"}, |
| 590 | {"year": 2027, "amount_cents": 12 * 20_000, "basis_note": "simple method"}, |
| 591 | {"year": 2028, "amount_cents": 12 * 20_000, "basis_note": "simple method"}, |
| 592 | {"year": 2029, "amount_cents": 12 * 20_000, "basis_note": "simple method"}, |
| 593 | {"year": 2030, "amount_cents": 6 * 20_000, "basis_note": "simple method"}] |
| 594 | |
| 595 | |
| 596 | # --- stock: a count above normal opens a loss event ------------------------------ |
| 597 | # (decimal quantities and the new loss reasons on their own, without app-assets: |
| 598 | # tests/test_stock_losses_and_decimals.py) |
| 599 | |
| 600 | def _whisky(books, expected_bps="250"): |
| 601 | product = books.create("products", {"name": "Whisky (cask)", "unit": "L", "cost_cents": 1_100, |
| 602 | "expected_loss_bps": expected_bps}) |
| 603 | shelf = books.create("locations", {"name": "Bonded store", "location_type": "warehouse"}) |
| 604 | return product, shelf |
| 605 | |
| 606 | |
| 607 | def test_a_count_shortage_above_normal_opens_a_loss_event_for_somebody_else(books): |
| 608 | product, shelf = _whisky(books, expected_bps="200") |
| 609 | books.create("stock_moves", {"product_id": product, "to_location_id": shelf, "quantity": "200.5", |
| 610 | "unit_cost_cents": 1_100, "reason": "purchase", "occurred_at": "2025-01-05"}) |
| 611 | # 194.2 of 200.5: 6.3 short = 314.2 bps > 200 |
| 612 | status, body = books.call("POST", "/objects/action_apply_count", { |
| 613 | "product_id": product, "location_id": shelf, "counted_qty": "194.2", "counted_on": "2025-12-15", |
| 614 | "reason": "evaporation"}) |
| 615 | assert status == 200 and body["expected_loss"]["above_expected"] is True |
| 616 | assert body["expected_loss"]["actual_bps"] == 314 |
| 617 | event = books.get("loss_events", body["expected_loss"]["loss_event"]["id"]) |
| 618 | assert (event["status"], event["kind"], event["subject"], event["reported_by"], |
| 619 | event["stock_move_id"], event["estimated_amount_cents"]) == ( |
| 620 | "reported", "evaporation", "inventory", "dan", body["move_id"], "6930") # 6.3 x 1100 |
| 621 | assert books.put("loss_events", event["id"], {"status": "approved", "final_amount_cents": 6_930, |
| 622 | "evidence_refs": "count sheet CS-12"})[0] == 403 |
| 623 | assert books.put("loss_events", event["id"], {"status": "approved", "final_amount_cents": 6_930, |
| 624 | "evidence_refs": "count sheet CS-12"}, who="mgr")[0] == 200 |
| 625 | # The loss is booked by the count's move, so approval books nothing more. |
| 626 | report = books.run("2025-12-31", loss_event_id=event["id"]) |
| 627 | assert report["posted"] == 0 |
| 628 | # An overage cannot be evaporation. |
| 629 | status, body = books.call("POST", "/objects/action_apply_count", { |
| 630 | "product_id": product, "location_id": shelf, "counted_qty": "500", "reason": "evaporation"}) |
| 631 | assert status == 400 |
| 632 | |
| 633 | |
| 634 | # --- a year of books ------------------------------------------------------------------ |
| 635 | |
| 636 | def book_a_year(books): |
| 637 | """2025 for a small food business, the way it would be entered. Returns |
| 638 | the ids the checks need. Worked by hand in test_a_year_balances_and_ |
| 639 | every_number_traces_to_evidence_and_approval.""" |
| 640 | ids = {} |
| 641 | b = books |
| 642 | b.hand_journal("2025-01-01", "Owner's capital", "Cash", "Owner equity", 10_000_000, "bank statement Jan 2025") |
| 643 | # The van, its paint job (repair) and engine rebuild (improvement). |
| 644 | ids["van"] = b.asset("Delivery van", 3_600_000, "2025-01-10", 60, salvage=600_000, |
| 645 | asset_tag="VIN 1FTBW3XG", custodian="Sam", location="Depot", |
| 646 | tax_method="operator_entered", acquired_on="2025-01-08") |
| 647 | ids["paint"] = b.create("asset_work", {"asset_id": ids["van"], "performed_on": "2025-04-12", "amount_cents": 180_000, |
| 648 | "description": "Paint job", "treatment": "repair", |
| 649 | "basis": "routine_maintenance", |
| 650 | "reason": "Repaints worn panels: keeps it in ordinary condition", |
| 651 | "evidence_refs": "invoice PB-118"}) |
| 652 | ids["engine"] = b.create("asset_work", {"asset_id": ids["van"], "performed_on": "2025-08-20", "amount_cents": 720_000, |
| 653 | "description": "Engine rebuild", "treatment": "improvement", |
| 654 | "basis": "restoration", "life_months": 36, |
| 655 | "reason": "Rebuilt engine extends the van's life by three years", |
| 656 | "evidence_refs": "invoice GA-2291"}) |
| 657 | # A laptop, stolen in September. |
| 658 | ids["laptop"] = b.asset("Laptop", 240_000, "2025-02-03", 24, asset_tag="SN C02X") |
| 659 | ids["theft"] = b.create("loss_events", {"occurred_on": "2025-09-14", "discovered_on": "2025-09-15", |
| 660 | "kind": "theft", "subject": "equipment", "asset_id": ids["laptop"], |
| 661 | "what": "Laptop taken from the van", |
| 662 | "how_discovered": "Van found unlocked on Monday morning", |
| 663 | "evidence_refs": "police report 25-11873", |
| 664 | "estimated_amount_cents": 170_000}) |
| 665 | ids["theft_disposal"] = b.create("asset_disposals", {"asset_id": ids["laptop"], "disposed_on": "2025-09-14", |
| 666 | "kind": "theft", "evidence_refs": "police report 25-11873", |
| 667 | "loss_event_id": ids["theft"]}) |
| 668 | # A freezer, lost to a burst pipe in November; the insurer pays 3,500.00. |
| 669 | ids["freezer"] = b.asset("Chest freezer", 480_000, "2025-03-01", 48) |
| 670 | ids["casualty"] = b.create("loss_events", {"occurred_on": "2025-11-03", "kind": "casualty", |
| 671 | "subject": "equipment", "asset_id": ids["freezer"], |
| 672 | "what": "Freezer destroyed by a burst pipe", |
| 673 | "how_discovered": "Water on the floor at opening", |
| 674 | "evidence_refs": "photos IMG_4410-4418; plumber invoice 993", |
| 675 | "estimated_amount_cents": 400_000, "insurance_status": "claimed", |
| 676 | "insurance_claim_ref": "CLM-5521"}) |
| 677 | ids["casualty_disposal"] = b.create("asset_disposals", {"asset_id": ids["freezer"], "disposed_on": "2025-11-03", |
| 678 | "kind": "casualty", "insurance_recovery_cents": 350_000, |
| 679 | "counterparty": "Mutual Insurance", |
| 680 | "evidence_refs": "adjuster report CLM-5521", |
| 681 | "loss_event_id": ids["casualty"]}) |
| 682 | # Stock: cheese (a spoiled batch) and a whisky cask (evaporation at count). |
| 683 | store = b.create("locations", {"name": "Store room", "location_type": "warehouse"}) |
| 684 | ids["cheese"] = b.create("products", {"name": "Cheese wheel", "unit": "each", "cost_cents": 1_500}) |
| 685 | ids["whisky"] = b.create("products", {"name": "Whisky (cask)", "unit": "L", "cost_cents": 4_000, |
| 686 | "expected_loss_bps": "200"}) |
| 687 | b.create("stock_moves", {"product_id": ids["cheese"], "to_location_id": store, "quantity": "200", |
| 688 | "unit_cost_cents": 1_500, "reason": "purchase", "occurred_at": "2025-05-02", |
| 689 | "reference": "supplier invoice CH-4"}) |
| 690 | b.hand_journal("2025-05-02", "Cheese purchase", "Inventory", "Cash", 300_000, "supplier invoice CH-4") |
| 691 | b.create("stock_moves", {"product_id": ids["whisky"], "to_location_id": store, "quantity": "200.5", |
| 692 | "unit_cost_cents": 4_000, "reason": "purchase", "occurred_at": "2025-02-10", |
| 693 | "reference": "distillery invoice D-17"}) |
| 694 | b.hand_journal("2025-02-10", "Whisky cask purchase", "Inventory", "Cash", 802_000, "distillery invoice D-17") |
| 695 | ids["spoiled"] = b.create("stock_moves", {"product_id": ids["cheese"], "from_location_id": store, |
| 696 | "quantity": "12", "reason": "waste", "occurred_at": "2025-06-20", |
| 697 | "reference": "fridge failure 06-20"}) |
| 698 | # system_stock_books is a reaction (off on this box): run it as the daemon would. |
| 699 | body = react(b.box, "system_stock_books", {"action": "create", "collection": "stock_moves", |
| 700 | "record_id": ids["spoiled"]}) |
| 701 | assert body.get("posted"), body |
| 702 | ids["spoilage"] = b.create("loss_events", {"occurred_on": "2025-06-20", "kind": "spoilage", "subject": "inventory", |
| 703 | "what": "12 cheese wheels spoiled", "product_id": ids["cheese"], |
| 704 | "stock_move_id": ids["spoiled"], |
| 705 | "how_discovered": "Walk-in fridge at 11C at opening", |
| 706 | "evidence_refs": "temperature log 06-20; photo IMG_3301", |
| 707 | "estimated_amount_cents": 18_000}) |
| 708 | status, body = b.call("POST", "/objects/action_apply_count", { |
| 709 | "product_id": ids["whisky"], "location_id": store, "counted_qty": "194.2", |
| 710 | "counted_on": "2025-12-15", "reason": "evaporation"}) |
| 711 | assert status == 200 and body["expected_loss"]["above_expected"], body |
| 712 | ids["evaporated"] = body["move_id"] |
| 713 | ids["evaporation"] = body["expected_loss"]["loss_event"]["id"] |
| 714 | # Somebody else approves every loss, with the evidence. |
| 715 | for event, amount, evidence in ((ids["theft"], 170_000, None), (ids["casualty"], 400_000, None), |
| 716 | (ids["spoilage"], 18_000, None), |
| 717 | (ids["evaporation"], 25_200, "count sheet CS-2025-12")): |
| 718 | changes = {"status": "approved", "final_amount_cents": amount} |
| 719 | if evidence: |
| 720 | changes["evidence_refs"] = evidence |
| 721 | status, body = b.put("loss_events", event, changes, who="mgr") |
| 722 | assert status == 200, body |
| 723 | assert b.put("loss_events", ids["casualty"], {"insurance_status": "paid", "insurance_recovery_cents": 350_000, |
| 724 | "recovered_on": "2025-11-28"})[0] == 200 |
| 725 | # Year end: book the register, then book it again (a replay posts nothing). |
| 726 | first = b.run("2025-12-31") |
| 727 | assert first["ok"], first |
| 728 | assert b.run("2025-12-31")["posted"] == 0 |
| 729 | return ids |
| 730 | |
| 731 | |
| 732 | def test_a_year_balances_and_every_number_traces_to_evidence_and_approval(books): |
| 733 | ids = book_a_year(books) |
| 734 | balances = books.balances() |
| 735 | # By hand: |
| 736 | # Cash 10,000,000 - van 3,600,000 - paint 180,000 - engine 720,000 |
| 737 | # - laptop 240,000 - freezer 480,000 - cheese 300,000 - whisky 802,000 = 3,678,000 |
| 738 | # Equipment 3,600,000 + 720,000 (engine) + 240,000 + 480,000 - 240,000 - 480,000 = 4,320,000 |
| 739 | # Depreciation: van 12 x 50,000 = 600,000; engine Aug-Dec 5 x 20,000 = 100,000; |
| 740 | # laptop Feb-Aug 7 x 10,000 = 70,000; freezer Mar-Oct 8 x 10,000 = 80,000 => 850,000 |
| 741 | # Accumulated at year end: 700,000 (laptop's and freezer's removed on disposal) |
| 742 | # Loss on disposal: laptop NBV 170,000; freezer NBV 400,000 - 350,000 insurance = 50,000 |
| 743 | # Inventory 300,000 + 802,000 - 12 x 1,500 - 6.3 L x 4,000 (25,200) = 1,058,800 |
| 744 | assert balances == { |
| 745 | "Cash": 3_678_000, "Equipment": 4_320_000, "Accumulated depreciation": -700_000, |
| 746 | "Inventory": 1_058_800, "Insurance receivable": 350_000, "Owner equity": -10_000_000, |
| 747 | "Depreciation expense": 850_000, "Repairs": 180_000, "Loss on disposal": 220_000, |
| 748 | "Spoilage": 18_000, "Evaporation": 25_200, |
| 749 | } |
| 750 | assert sum(balances.values()) == 0 # the trial balance balances |
| 751 | sheet = object_finance.balance_sheet(base_dir=books.box.data_dir, owner="dan", as_of="2025-12-31") |
| 752 | assert sheet["balances"] and sheet["difference_cents"] == 0 |
| 753 | |
| 754 | # Every journal traces to a record; every loss to an approved event with evidence. |
| 755 | data = books.box.data_dir |
| 756 | events = {e["id"]: e for e in object_records.read_collection_records("loss_events", base_dir=data)} |
| 757 | disposals = {d["id"]: d for d in object_records.read_collection_records("asset_disposals", base_dir=data)} |
| 758 | work = {w["id"]: w for w in object_records.read_collection_records("asset_work", base_dir=data)} |
| 759 | moves = {m["id"]: m for m in object_records.read_collection_records("stock_moves", base_dir=data)} |
| 760 | assets = {a["id"]: a for a in object_records.read_collection_records("fixed_assets", base_dir=data)} |
| 761 | |
| 762 | def approved_with_evidence(event): |
| 763 | return (event["status"] == "approved" and event["evidence_refs"] and event["reported_by"] |
| 764 | and event["approved_by"] and event["reported_by"] != event["approved_by"]) |
| 765 | |
| 766 | for journal in books.journals(): |
| 767 | assert journal["status"] == "posted" |
| 768 | marker = journal.get("generated_from") or "" |
| 769 | kind, _, rest = marker.partition("/") |
| 770 | if not marker: |
| 771 | assert journal.get("reference"), journal # hand entry: its paper |
| 772 | elif kind == "fixed_assets": |
| 773 | assert rest.split("/")[0] in assets |
| 774 | elif kind == "asset_work": |
| 775 | row = work[rest] |
| 776 | assert row["reason"] and row["basis"] and row["evidence_refs"] and row["journal_id"] == journal["id"] |
| 777 | elif kind == "asset_disposals": |
| 778 | disposal = disposals[rest] |
| 779 | assert disposal["journal_id"] == journal["id"] and disposal["evidence_refs"] |
| 780 | assert approved_with_evidence(events[disposal["loss_event_id"]]) |
| 781 | elif kind == "stock_moves": |
| 782 | move = moves[rest] |
| 783 | linked = [e for e in events.values() if e.get("stock_move_id") == move["id"]] |
| 784 | assert linked and all(approved_with_evidence(e) for e in linked), move |
| 785 | else: |
| 786 | raise AssertionError(f"untraced journal {marker}") |
| 787 | assert all(approved_with_evidence(e) for e in events.values()) |
| 788 | assert sorted(d["gain_loss_cents"] for d in disposals.values()) == ["-170000", "-50000"] |
| 789 | assert books.get("fixed_assets", ids["laptop"])["status"] == "disposed" |