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_stock_valuation.py · 14.8 KB · 343 lines
| 1 | """What the goods cost: the valuation COGS-on-sale was blocked on. |
| 2 | |
| 3 | The journal shape was never the hard part. `DR cost of goods sold, CR |
| 4 | inventory` is two lines. The blocker was knowing what number to put on |
| 5 | them, and system_stock_books said so in its own docstring for as long as |
| 6 | it declined to compose sales: "COGS-on-sale needs a real valuation method |
| 7 | (FIFO/weighted average)". |
| 8 | |
| 9 | **Weighted average**, and it is a decision. FIFO is more precise and is |
| 10 | right for a lot-tracked warehouse, but it needs cost LAYERS -- which |
| 11 | units, from which receipt, are still on the shelf -- and stock_moves has |
| 12 | no lot dimension at all. Adding one to satisfy a journal entry would be a |
| 13 | storage change driven by a report. LIFO is not permitted under IFRS. |
| 14 | Weighted average needs nothing the append log does not already carry. |
| 15 | |
| 16 | MOVING average specifically, folded in move order. The distinction is not |
| 17 | academic and the first test below is the proof: a lifetime "total spent |
| 18 | over total ever bought" average silently reprices goods you no longer |
| 19 | own. |
| 20 | """ |
| 21 | |
| 22 | import pathlib |
| 23 | |
| 24 | from conftest import stage_collection |
| 25 | |
| 26 | import object_execution |
| 27 | import object_records |
| 28 | import object_stock |
| 29 | import python_object_runtime |
| 30 | |
| 31 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 32 | CATALOG_OBJECTS = REPO_ROOT / "packages" / "app-catalog" / "objects" |
| 33 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 34 | |
| 35 | |
| 36 | def move(quantity, *, cost=None, reason="purchase", into="shelf", |
| 37 | out_of="", when="2026-01-01", product="p1"): |
| 38 | return {"product_id": product, "quantity": str(quantity), |
| 39 | "unit_cost_cents": "" if cost is None else str(cost), |
| 40 | "reason": reason, "to_location_id": into, |
| 41 | "from_location_id": out_of, "occurred_at": when} |
| 42 | |
| 43 | |
| 44 | # --- the fold (pure) ------------------------------------------------------------ |
| 45 | |
| 46 | def test_the_average_blends_two_purchase_prices_by_quantity(): |
| 47 | moves = [move(10, cost=200, when="2026-01-01"), |
| 48 | move(30, cost=300, when="2026-01-02")] |
| 49 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 275 |
| 50 | |
| 51 | |
| 52 | def test_a_sale_does_not_change_the_average(): |
| 53 | """The defining property: depletion consumes stock at the average it |
| 54 | was carried at, so the average survives it unchanged.""" |
| 55 | moves = [move(10, cost=200), move(30, cost=300, when="2026-01-02")] |
| 56 | before = object_stock.weighted_average_cost_cents(moves, "p1") |
| 57 | moves.append(move(5, reason="sale", into="", out_of="shelf", |
| 58 | when="2026-01-03")) |
| 59 | assert object_stock.weighted_average_cost_cents(moves, "p1") == before |
| 60 | |
| 61 | |
| 62 | def test_moving_average_differs_from_a_lifetime_average(): |
| 63 | """THE test for why this is folded in order rather than summed. |
| 64 | |
| 65 | Buy 10 at 100, sell all 10, buy 1 at 300. The next sale costs 300 -- |
| 66 | that is the only unit on the shelf. A lifetime average would answer |
| 67 | 118 by averaging in ten units the shop no longer owns. |
| 68 | """ |
| 69 | moves = [ |
| 70 | move(10, cost=100, when="2026-01-01"), |
| 71 | move(10, reason="sale", into="", out_of="shelf", when="2026-01-02"), |
| 72 | move(1, cost=300, when="2026-01-03"), |
| 73 | ] |
| 74 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 300 |
| 75 | |
| 76 | lifetime = (10 * 100 + 1 * 300) / 11 |
| 77 | assert round(lifetime) == 118 # what the wrong version reports |
| 78 | |
| 79 | |
| 80 | def test_a_transfer_between_shelves_does_not_re_average(): |
| 81 | """Both ends set means the goods never left; value is unchanged.""" |
| 82 | moves = [move(10, cost=200), |
| 83 | move(4, reason="transfer", into="back-room", out_of="shelf", |
| 84 | when="2026-01-02")] |
| 85 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 200 |
| 86 | |
| 87 | |
| 88 | def test_free_stock_dilutes_the_average_rather_than_being_ignored(): |
| 89 | """Uncosted stock still occupies the shelf. Skipping it entirely would |
| 90 | report the average of the priced units as if the free ones were not |
| 91 | there to be sold.""" |
| 92 | moves = [move(10, cost=300), move(10, cost=None, when="2026-01-02")] |
| 93 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 150 |
| 94 | |
| 95 | |
| 96 | def test_nothing_on_hand_has_no_honest_average(): |
| 97 | assert object_stock.weighted_average_cost_cents([], "p1") is None |
| 98 | sold_out = [move(10, cost=200), |
| 99 | move(10, reason="sale", into="", out_of="shelf", |
| 100 | when="2026-01-02")] |
| 101 | assert object_stock.weighted_average_cost_cents(sold_out, "p1") is None |
| 102 | |
| 103 | |
| 104 | def test_stock_that_never_carried_a_price_has_no_average(): |
| 105 | """None, not zero. A caller must skip rather than book a zero-cost |
| 106 | sale that makes the margin look perfect.""" |
| 107 | assert object_stock.weighted_average_cost_cents( |
| 108 | [move(10, cost=None)], "p1") is None |
| 109 | |
| 110 | |
| 111 | def test_products_do_not_contaminate_each_other(): |
| 112 | moves = [move(10, cost=200, product="p1"), |
| 113 | move(10, cost=900, product="p2")] |
| 114 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 200 |
| 115 | assert object_stock.weighted_average_cost_cents(moves, "p2") == 900 |
| 116 | |
| 117 | |
| 118 | def test_moves_fold_in_date_order_not_file_order(): |
| 119 | """stock_moves is an append log; a backdated receipt can land after a |
| 120 | later one. Order is a property of the dates, not the rows.""" |
| 121 | late_first = [move(1, cost=300, when="2026-03-01"), |
| 122 | move(9, cost=100, when="2026-01-01")] |
| 123 | assert object_stock.weighted_average_cost_cents(late_first, "p1") == 120 |
| 124 | |
| 125 | |
| 126 | # --- the hook stamps it at write time ------------------------------------------- |
| 127 | |
| 128 | def setup_shop(tmp_path, monkeypatch): |
| 129 | data_dir = tmp_path / "data" |
| 130 | for pkg, name in (("app-catalog", "products"), ("app-catalog", "locations"), |
| 131 | ("app-catalog", "stock_moves")): |
| 132 | stage_collection(data_dir, pkg, name) |
| 133 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 134 | for loc in ("loc-shelf", "loc-customer"): |
| 135 | object_records.create_collection_record( |
| 136 | "locations", {"id": loc, "name": loc, "owner_id": "shop"}, |
| 137 | base_dir=data_dir) |
| 138 | object_records.create_collection_record( |
| 139 | "products", |
| 140 | {"id": "p1", "name": "Enamel Mug", "product_type": "physical", |
| 141 | "cost_cents": "250", "owner_id": "shop"}, |
| 142 | base_dir=data_dir) |
| 143 | return data_dir |
| 144 | |
| 145 | |
| 146 | def buy(data_dir, move_id, quantity, cost, when="2026-01-01"): |
| 147 | return object_records.create_collection_record( |
| 148 | "stock_moves", |
| 149 | {"id": move_id, "product_id": "p1", "to_location_id": "loc-shelf", |
| 150 | "quantity": str(quantity), "unit_cost_cents": str(cost), |
| 151 | "reason": "purchase", "occurred_at": when, "owner_id": "shop"}, |
| 152 | base_dir=data_dir) |
| 153 | |
| 154 | |
| 155 | def hook(record, action="create"): |
| 156 | return object_execution.execute_object( |
| 157 | RUNTIME, |
| 158 | object_execution.ObjectExecutionRequest( |
| 159 | "hook_stock_moves", method="BEFORE_WRITE", |
| 160 | payload={"action": action, "collection": "stock_moves", |
| 161 | "record": record}), |
| 162 | roots=[CATALOG_OBJECTS]).result |
| 163 | |
| 164 | |
| 165 | def sale_record(**overrides): |
| 166 | record = {"id": "mv-sale", "product_id": "p1", |
| 167 | "from_location_id": "loc-shelf", "to_location_id": "loc-customer", |
| 168 | "quantity": "3", "reason": "sale", "occurred_at": "2026-02-01", |
| 169 | "owner_id": "shop"} |
| 170 | record.update(overrides) |
| 171 | return record |
| 172 | |
| 173 | |
| 174 | def test_a_sale_is_stamped_with_the_average_of_what_is_on_the_shelf( |
| 175 | tmp_path, monkeypatch): |
| 176 | """Not products.cost_cents (250), which is a planning figure someone |
| 177 | typed. What was actually paid: 10 at 200 and 30 at 300 blends to 275.""" |
| 178 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 179 | buy(data_dir, "mv-buy-1", 10, 200, when="2026-01-01") |
| 180 | buy(data_dir, "mv-buy-2", 30, 300, when="2026-01-02") |
| 181 | |
| 182 | result = hook(sale_record()) |
| 183 | assert result["record"]["unit_cost_cents"] == "275" |
| 184 | |
| 185 | |
| 186 | def test_the_stamp_excludes_the_sale_being_written(tmp_path, monkeypatch): |
| 187 | """BEFORE_WRITE: the average is the one at the moment of sale, and |
| 188 | the sale itself is not in the log yet to distort it.""" |
| 189 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 190 | buy(data_dir, "mv-buy-1", 10, 200) |
| 191 | assert hook(sale_record(quantity="10"))["record"]["unit_cost_cents"] == "200" |
| 192 | |
| 193 | |
| 194 | def test_a_sale_with_no_priced_stock_falls_back_to_the_standard_cost( |
| 195 | tmp_path, monkeypatch): |
| 196 | """A shop that never recorded a purchase still gets an honest-ish |
| 197 | number rather than nothing -- and it is the same fallback losses have |
| 198 | always used, not a new invention.""" |
| 199 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 200 | assert hook(sale_record())["record"]["unit_cost_cents"] == "250" |
| 201 | |
| 202 | |
| 203 | def test_a_client_supplied_cost_is_never_overwritten(tmp_path, monkeypatch): |
| 204 | """Purchases carry their invoice cost; nothing may second-guess it.""" |
| 205 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 206 | buy(data_dir, "mv-buy-1", 10, 200) |
| 207 | assert hook(sale_record(unit_cost_cents="999")) is None |
| 208 | |
| 209 | |
| 210 | def test_a_loss_still_uses_the_standard_cost_not_the_average( |
| 211 | tmp_path, monkeypatch): |
| 212 | """Deliberate asymmetry. Writing off a broken mug at standard cost is |
| 213 | fine and was always the behaviour; reporting cost of SALES at a |
| 214 | typed-in number is how gross margin quietly becomes fiction. Only the |
| 215 | sale path changed.""" |
| 216 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 217 | buy(data_dir, "mv-buy-1", 10, 200) |
| 218 | breakage = {"id": "mv-break", "product_id": "p1", |
| 219 | "from_location_id": "loc-shelf", "quantity": "1", |
| 220 | "reason": "breakage", "occurred_at": "2026-02-01", |
| 221 | "owner_id": "shop"} |
| 222 | assert hook(breakage)["record"]["unit_cost_cents"] == "250" |
| 223 | |
| 224 | |
| 225 | # --- arriving and leaving are about WHERE the goods are (2026-11-28) ------------- |
| 226 | # |
| 227 | # The fold used to decide "acquisition / depletion / transfer" by which end |
| 228 | # of a move was blank. A sale written the way order_fulfillment writes it |
| 229 | # (shelf -> the customer location) has both ends, so it read as a transfer |
| 230 | # and sold stock never left the average; a receipt from a supplier location |
| 231 | # (receipt_posting's shape) read as a transfer and never entered it. |
| 232 | |
| 233 | OUTSIDE = {"loc-customer", "loc-supplier"} |
| 234 | |
| 235 | |
| 236 | def test_a_sale_into_a_customer_location_leaves_the_average(): |
| 237 | """The reported case. Buy 10 at 250, sell all 10 to the customer |
| 238 | location, buy 10 at 350: only 350-unit stock is on the shelf.""" |
| 239 | moves = [ |
| 240 | move(10, cost=250, when="2026-01-01"), |
| 241 | move(10, reason="sale", out_of="shelf", into="loc-customer", |
| 242 | when="2026-01-02"), |
| 243 | move(10, cost=350, when="2026-01-03"), |
| 244 | ] |
| 245 | assert object_stock.weighted_average_cost_cents(moves, "p1", OUTSIDE) == 350 |
| 246 | # What the old rule answered, and still answers when nobody says the |
| 247 | # customer location is outside: the 10 sold units still averaged in. |
| 248 | assert object_stock.weighted_average_cost_cents(moves, "p1") == 300 |
| 249 | |
| 250 | |
| 251 | def test_a_receipt_from_a_supplier_location_enters_the_average(): |
| 252 | moves = [move(10, cost=200, out_of="loc-supplier"), |
| 253 | move(30, cost=300, out_of="loc-supplier", when="2026-01-02")] |
| 254 | assert object_stock.weighted_average_cost_cents(moves, "p1", OUTSIDE) == 275 |
| 255 | |
| 256 | |
| 257 | def test_a_return_from_the_customer_comes_back_at_its_cost(): |
| 258 | moves = [move(10, cost=200, out_of="loc-supplier"), |
| 259 | move(10, reason="sale", out_of="shelf", into="loc-customer", |
| 260 | when="2026-01-02"), |
| 261 | move(2, cost=200, reason="return", out_of="loc-customer", |
| 262 | when="2026-01-03")] |
| 263 | assert object_stock.weighted_average_cost_cents(moves, "p1", OUTSIDE) == 200 |
| 264 | |
| 265 | |
| 266 | def test_a_shelf_to_shelf_transfer_still_does_not_re_average(): |
| 267 | moves = [move(10, cost=200, out_of="loc-supplier"), |
| 268 | move(4, reason="transfer", into="back-room", out_of="shelf", |
| 269 | when="2026-01-02"), |
| 270 | move(10, cost=500, out_of="loc-supplier", when="2026-01-03")] |
| 271 | assert object_stock.weighted_average_cost_cents(moves, "p1", OUTSIDE) == 350 |
| 272 | |
| 273 | |
| 274 | def _typed_shop(tmp_path, monkeypatch): |
| 275 | data_dir = setup_shop(tmp_path, monkeypatch) |
| 276 | object_records.update_collection_record( |
| 277 | "locations", "loc-customer", {"location_type": "customer"}, |
| 278 | base_dir=data_dir) |
| 279 | object_records.create_collection_record( |
| 280 | "locations", {"id": "loc-supplier", "name": "Supplier", |
| 281 | "location_type": "supplier", "owner_id": "shop"}, |
| 282 | base_dir=data_dir) |
| 283 | return data_dir |
| 284 | |
| 285 | |
| 286 | def _move(data_dir, move_id, quantity, *, cost="", reason="purchase", |
| 287 | from_location="loc-supplier", to_location="loc-shelf", when): |
| 288 | object_records.create_collection_record( |
| 289 | "stock_moves", |
| 290 | {"id": move_id, "product_id": "p1", "from_location_id": from_location, |
| 291 | "to_location_id": to_location, "quantity": str(quantity), |
| 292 | "unit_cost_cents": str(cost), "reason": reason, "occurred_at": when, |
| 293 | "owner_id": "shop"}, |
| 294 | base_dir=data_dir) |
| 295 | |
| 296 | |
| 297 | def test_the_next_sale_is_stamped_with_what_is_actually_on_the_shelf( |
| 298 | tmp_path, monkeypatch): |
| 299 | """End to end through stored moves and the hook that stamps a sale |
| 300 | (order_fulfillment calls the same average_cost_for_product).""" |
| 301 | data_dir = _typed_shop(tmp_path, monkeypatch) |
| 302 | _move(data_dir, "b1", 10, cost=250, when="2026-01-01") |
| 303 | _move(data_dir, "s1", 10, cost=250, reason="sale", from_location="loc-shelf", |
| 304 | to_location="loc-customer", when="2026-01-02") |
| 305 | _move(data_dir, "b2", 10, cost=350, when="2026-01-03") |
| 306 | |
| 307 | assert object_stock.average_cost_for_product("p1", base_dir=data_dir) == 350 |
| 308 | assert object_stock.total_quantity("p1", base_dir=data_dir) == 10 |
| 309 | stamped = hook(sale_record(occurred_at="2026-01-04"))["record"] |
| 310 | assert stamped["unit_cost_cents"] == "350" |
| 311 | |
| 312 | |
| 313 | def test_unreadable_locations_refuse_the_sale_rather_than_stamp_the_standard_cost( |
| 314 | tmp_path, monkeypatch): |
| 315 | """Reading the locations as "nothing is virtual" would quietly bring |
| 316 | the old answer back; the average refuses instead. And so does the |
| 317 | hook: this test first pinned a fall back to products.cost_cents "as |
| 318 | for no average at all", but could-not-read is not no-average. The |
| 319 | stamp is a point-in-time fact, so falling back wrote a planning figure |
| 320 | somebody typed (250) down as the cost of goods bought at 400, for |
| 321 | good -- the fail-open bug-reports/...gates-fail-open-on-read-errors |
| 322 | names. A sale that cannot be costed is refused and nothing is stamped; |
| 323 | a product with no priced acquisitions is a different, known answer and |
| 324 | still falls back (the tests above).""" |
| 325 | data_dir = _typed_shop(tmp_path, monkeypatch) |
| 326 | _move(data_dir, "b1", 10, cost=400, when="2026-01-01") |
| 327 | real = object_records.read_collection_records |
| 328 | |
| 329 | def failing(collection, *a, **k): |
| 330 | if collection == "locations": |
| 331 | raise OSError("locations unreadable") |
| 332 | return real(collection, *a, **k) |
| 333 | |
| 334 | monkeypatch.setattr(object_records, "read_collection_records", failing) |
| 335 | try: |
| 336 | object_stock.average_cost_for_product("p1", base_dir=data_dir) |
| 337 | except OSError: |
| 338 | pass |
| 339 | else: |
| 340 | raise AssertionError("an unreadable locations read must raise") |
| 341 | answer = hook(sale_record()) |
| 342 | assert answer.get("status") == 503 and "record" not in answer, answer |
| 343 | assert "could not be read" in answer["error"] |