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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_cogs_on_sale.py · 8.8 KB · 204 lines
| 1 | """COGS on sale: the entry the books used to miss. |
| 2 | |
| 3 | A sale takes goods off a shelf. Those goods cost money, and the moment |
| 4 | they leave, that cost stops being an asset and becomes an expense: DR |
| 5 | cost of goods sold, CR inventory. Without it the balance sheet carries |
| 6 | inventory the shop no longer owns and the profit and loss shows revenue |
| 7 | with nothing set against it -- every sale looks like pure margin, which |
| 8 | is the single most flattering way a small business can be wrong about |
| 9 | itself. |
| 10 | |
| 11 | This file was written first as a SPECIFICATION, three strict xfails |
| 12 | describing the feature that did not exist. It is now the acceptance test |
| 13 | they promised to become, and the assertions are unchanged from the day |
| 14 | they were staged -- which is the point of writing them that way. |
| 15 | |
| 16 | What unblocked it was the valuation method, which was always the real |
| 17 | prerequisite rather than the journal shape: |
| 18 | |
| 19 | **Weighted average**, moving, folded in move order |
| 20 | (object_stock.weighted_average_cost_cents). FIFO is more precise and is |
| 21 | what a lot-tracked warehouse should use, but it needs cost LAYERS and |
| 22 | stock_moves has no lot dimension -- adding one to satisfy a journal entry |
| 23 | would be a storage change driven by a report. Weighted average needs |
| 24 | nothing the append log does not already carry. |
| 25 | |
| 26 | The split that keeps it honest: hook_stock_moves VALUES the sale at write |
| 27 | time (doctrine #1, a point-in-time fact gets stamped, so tomorrow's price |
| 28 | change cannot reprice yesterday's sale), and system_stock_books only ever |
| 29 | READS the stamped cost. A costless sale still skips rather than reaching |
| 30 | for products.cost_cents, because a valuation method picked by accident |
| 31 | inside a handler is exactly what the original boundary existed to |
| 32 | prevent. |
| 33 | """ |
| 34 | |
| 35 | import pathlib |
| 36 | |
| 37 | import pytest |
| 38 | from conftest import stage_collection |
| 39 | |
| 40 | import object_execution |
| 41 | import object_records |
| 42 | import python_object_runtime |
| 43 | |
| 44 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 45 | PACKAGES = REPO_ROOT / "packages" |
| 46 | CATALOG_OBJECTS = PACKAGES / "app-catalog" / "objects" |
| 47 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 48 | |
| 49 | INV, COGS, SHRINK = "acct-inventory", "acct-cogs", "acct-shrinkage" |
| 50 | |
| 51 | # Both spellings of the account setting are staged: the existing map uses |
| 52 | # `inventory.journal.{reason}_account` as a per-reason override, so |
| 53 | # `sale_account` is the shape that already fits, while `cogs_account` is |
| 54 | # what somebody would reach for by name. The assertions below are on the |
| 55 | # ACCOUNT the journal hits, not on which key was read, so whichever |
| 56 | # convention an implementer picks, this specification still holds. |
| 57 | SETTINGS = (("inventory.journal.inventory_account", INV), |
| 58 | ("inventory.journal.shrinkage_account", SHRINK), |
| 59 | ("inventory.journal.sale_account", COGS), |
| 60 | ("inventory.journal.cogs_account", COGS)) |
| 61 | |
| 62 | |
| 63 | def setup_env(tmp_path, monkeypatch): |
| 64 | data_dir = tmp_path / "data" |
| 65 | for pkg, name in (("app-catalog", "products"), ("app-catalog", "locations"), |
| 66 | ("app-catalog", "stock_moves"), |
| 67 | ("app-finance", "fin_journals"), |
| 68 | ("app-finance", "fin_journal_lines"), |
| 69 | ("app-finance", "fin_accounts")): |
| 70 | stage_collection(data_dir, pkg, name) |
| 71 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(SETTINGS)) |
| 72 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 73 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 74 | |
| 75 | for acct in (INV, COGS, SHRINK): |
| 76 | object_records.create_collection_record( |
| 77 | "fin_accounts", |
| 78 | {"id": acct, "name": acct, "account_type": "asset", |
| 79 | "owner_id": "shop"}, |
| 80 | base_dir=data_dir) |
| 81 | for loc in ("loc-shelf", "loc-customer", "loc-back-room"): |
| 82 | object_records.create_collection_record( |
| 83 | "locations", {"id": loc, "name": loc, "owner_id": "shop"}, |
| 84 | base_dir=data_dir) |
| 85 | object_records.create_collection_record( |
| 86 | "products", |
| 87 | {"id": "p1", "name": "Enamel Mug", "product_type": "physical", |
| 88 | "cost_cents": "250", "price_cents": "1200", "owner_id": "shop"}, |
| 89 | base_dir=data_dir) |
| 90 | return data_dir |
| 91 | |
| 92 | |
| 93 | def sale_move(data_dir, move_id="mv-sale", *, quantity="3", cost="250"): |
| 94 | """The move system_shop_fulfillment composes when money arrives: |
| 95 | stock leaves the shelf and goes to the customer.""" |
| 96 | return object_records.create_collection_record( |
| 97 | "stock_moves", |
| 98 | {"id": move_id, "product_id": "p1", "from_location_id": "loc-shelf", |
| 99 | "to_location_id": "loc-customer", "quantity": quantity, |
| 100 | "unit_cost_cents": cost, "reason": "sale", |
| 101 | "occurred_at": "2026-07-24", "reference": "orders/o1:fulfil", |
| 102 | "owner_id": "shop"}, |
| 103 | base_dir=data_dir) |
| 104 | |
| 105 | |
| 106 | def fire_stock_books(record_id): |
| 107 | """The REAL dispatcher payload: event name participle, action raw.""" |
| 108 | return object_execution.execute_object( |
| 109 | RUNTIME, |
| 110 | object_execution.ObjectExecutionRequest( |
| 111 | "system_stock_books", method="EVENT", |
| 112 | payload={"event": "stock_moves.record.created", |
| 113 | "collection": "stock_moves", "record_id": record_id, |
| 114 | "action": "create"}), |
| 115 | roots=[CATALOG_OBJECTS]).result |
| 116 | |
| 117 | |
| 118 | def journals(data_dir): |
| 119 | return object_records.read_collection_records("fin_journals", |
| 120 | base_dir=data_dir) |
| 121 | |
| 122 | |
| 123 | def lines_for(data_dir, journal_id): |
| 124 | return [line for line in object_records.read_collection_records( |
| 125 | "fin_journal_lines", base_dir=data_dir) |
| 126 | if line["journal_id"] == journal_id] |
| 127 | |
| 128 | |
| 129 | # --- the boundaries that did not move ------------------------------- |
| 130 | |
| 131 | def test_a_transfer_between_shelves_still_books_nothing(tmp_path, monkeypatch): |
| 132 | """The boundary that survives COGS landing: moving goods from one |
| 133 | shelf to another changes no value, so it must compose nothing. A sale |
| 134 | is distinguished by leaving the system, not by having a from-location. |
| 135 | """ |
| 136 | data_dir = setup_env(tmp_path, monkeypatch) |
| 137 | object_records.create_collection_record( |
| 138 | "stock_moves", |
| 139 | {"id": "mv-move", "product_id": "p1", "from_location_id": "loc-shelf", |
| 140 | "to_location_id": "loc-back-room", "quantity": "3", |
| 141 | "unit_cost_cents": "250", "reason": "transfer", |
| 142 | "occurred_at": "2026-07-24", "owner_id": "shop"}, |
| 143 | base_dir=data_dir) |
| 144 | assert fire_stock_books("mv-move")["skipped"] == "not a loss event" |
| 145 | assert journals(data_dir) == [] |
| 146 | |
| 147 | |
| 148 | # --- the feature, asserted exactly as it was specified ------------------------------- |
| 149 | |
| 150 | def test_a_sale_books_cost_of_goods_sold_against_inventory( |
| 151 | tmp_path, monkeypatch): |
| 152 | """Three mugs at 250c of cost leave the shelf: DR cost of goods sold |
| 153 | 750, CR inventory 750, on the date the goods moved. Same shape as |
| 154 | the loss composer, same shared composer, same generated_from |
| 155 | provenance -- the only new thing is the direction and the account. |
| 156 | """ |
| 157 | data_dir = setup_env(tmp_path, monkeypatch) |
| 158 | sale_move(data_dir, quantity="3", cost="250") |
| 159 | |
| 160 | result = fire_stock_books("mv-sale") |
| 161 | assert result["posted"] is True |
| 162 | |
| 163 | journal = journals(data_dir)[0] |
| 164 | assert journal["status"] == "posted" |
| 165 | assert journal["generated_from"] == "stock_moves/mv-sale" |
| 166 | assert journal["date"] == "2026-07-24" |
| 167 | |
| 168 | by_account = {line["account_id"]: line |
| 169 | for line in lines_for(data_dir, result["journal_id"])} |
| 170 | assert by_account[COGS]["debit_cents"] == "750" |
| 171 | assert by_account[COGS]["credit_cents"] == "0" |
| 172 | assert by_account[INV]["credit_cents"] == "750" |
| 173 | assert by_account[INV]["debit_cents"] == "0" |
| 174 | |
| 175 | |
| 176 | def test_a_replayed_sale_event_books_one_journal_not_two( |
| 177 | tmp_path, monkeypatch): |
| 178 | """A dispatcher retry, a daemon re-run and an operator poking the |
| 179 | handler by hand all arrive as the same event. Provenance |
| 180 | ("stock_moves/{id}") is what makes the second one a no-op -- exactly |
| 181 | the guard the loss path already proves, which is why the sale path |
| 182 | must not invent its own.""" |
| 183 | data_dir = setup_env(tmp_path, monkeypatch) |
| 184 | sale_move(data_dir, quantity="3", cost="250") |
| 185 | |
| 186 | first = fire_stock_books("mv-sale") |
| 187 | assert first["posted"] is True |
| 188 | replay = fire_stock_books("mv-sale") |
| 189 | assert "already composed" in replay["skipped"] |
| 190 | assert len(journals(data_dir)) == 1 |
| 191 | assert len(lines_for(data_dir, first["journal_id"])) == 2 |
| 192 | |
| 193 | |
| 194 | def test_a_sale_with_no_stamped_cost_books_nothing_rather_than_guessing( |
| 195 | tmp_path, monkeypatch): |
| 196 | """The honest failure mode. Where a sale move carries no cost there is |
| 197 | no journal that can be composed truthfully, and inventing one from the |
| 198 | product's current cost_cents would be a valuation method chosen by |
| 199 | accident inside a handler.""" |
| 200 | data_dir = setup_env(tmp_path, monkeypatch) |
| 201 | sale_move(data_dir, move_id="mv-costless", quantity="3", cost="0") |
| 202 | result = fire_stock_books("mv-costless") |
| 203 | assert result["skipped"] == "no stamped cost; nothing to book" |
| 204 | assert journals(data_dir) == [] |