Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_inventory_adjustments.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_inventory_adjustments.py · 14.3 KB · 328 lines
1"""Inventory adjustments (plan/inventory-adjustments-spec.md): the loss
2taxonomy, the cost-stamping/gating hook, the shrinkage composer, and count
3reconciliation. Losses are MOVEMENTS with a financial shadow -- never edits
4to an on-hand number (docs/logic-decisions.md #3)."""
5
6import pathlib
7from decimal import Decimal
8
9import pytest
10
11import object_execution
12import object_records
13import object_schemas
14import object_stock
15import python_object_runtime
16from conftest import stage_collection
17
18REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
19PACKAGES = REPO_ROOT / "packages"
20RUNTIME = python_object_runtime.PythonObjectRuntime()
21CATALOG_OBJECTS = PACKAGES / "app-catalog" / "objects"
22
23INV, SHRINK, THEFT = "acct-inventory", "acct-shrinkage", "acct-theft"
24
25
26def setup_env(tmp_path, monkeypatch, *, settings=None):
27 data_dir = tmp_path / "data"
28 wanted = [("app-catalog", "products"), ("app-catalog", "locations"),
29 ("app-catalog", "stock_moves"),
30 ("app-finance", "fin_journals"), ("app-finance", "fin_journal_lines"),
31 ("app-finance", "fin_accounts")]
32 for pkg, name in wanted:
33 stage_collection(data_dir, pkg, name)
34
35 if settings is None:
36 settings = (("inventory.journal.inventory_account", INV),
37 ("inventory.journal.shrinkage_account", SHRINK))
38 rows = ""
39 for i, (k, v) in enumerate(settings):
40 rows += f"s{i}\t{k}\t{v}\t\n"
41 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
42
43 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
44 for acct in (INV, SHRINK, THEFT):
45 object_records.create_collection_record(
46 "fin_accounts",
47 {"id": acct, "name": acct, "account_type": "asset", "owner_id": "dan"},
48 base_dir=data_dir)
49 return data_dir
50
51
52def make_product(data_dir, pid="prod1", cost="250"):
53 return object_records.create_collection_record(
54 "products",
55 {"id": pid, "name": f"Widget {pid}", "product_type": "physical",
56 "cost_cents": cost, "owner_id": "dan"},
57 base_dir=data_dir)
58
59
60def make_location(data_dir, lid="loc1"):
61 return object_records.create_collection_record(
62 "locations",
63 {"id": lid, "name": f"Shelf {lid}", "owner_id": "dan"},
64 base_dir=data_dir)
65
66
67def make_move(data_dir, mid, *, reason, qty="1", cost="250",
68 from_loc="", to_loc="", product="prod1"):
69 return object_records.create_collection_record(
70 "stock_moves",
71 {"id": mid, "product_id": product, "from_location_id": from_loc,
72 "to_location_id": to_loc, "quantity": qty, "unit_cost_cents": cost,
73 "reason": reason, "occurred_at": "2026-07-24", "owner_id": "dan"},
74 base_dir=data_dir)
75
76
77def run_hook(record, action="create"):
78 result = object_execution.execute_object(
79 RUNTIME,
80 object_execution.ObjectExecutionRequest(
81 "hook_stock_moves", method="BEFORE_WRITE",
82 payload={"action": action, "collection": "stock_moves", "record": record}),
83 roots=[CATALOG_OBJECTS])
84 return result.result
85
86
87def fire_stock_books(record_id):
88 # Mirror the REAL dispatcher payload: event name participle, action RAW.
89 result = object_execution.execute_object(
90 RUNTIME,
91 object_execution.ObjectExecutionRequest(
92 "system_stock_books", method="EVENT",
93 payload={"event": "stock_moves.record.created",
94 "collection": "stock_moves", "record_id": record_id,
95 "action": "create"}),
96 roots=[CATALOG_OBJECTS])
97 return result.result
98
99
100def apply_count(payload):
101 result = object_execution.execute_object(
102 RUNTIME,
103 object_execution.ObjectExecutionRequest(
104 "action_apply_count", method="POST",
105 payload={"_identity": {"user_id": "dan"}, **payload}),
106 roots=[CATALOG_OBJECTS])
107 return result.result
108
109
110def journals(data_dir):
111 return object_records.read_collection_records("fin_journals", base_dir=data_dir)
112
113
114def lines_for(data_dir, journal_id):
115 return [l for l in object_records.read_collection_records(
116 "fin_journal_lines", base_dir=data_dir)
117 if l["journal_id"] == journal_id]
118
119
120# --- 1. taxonomy -----------------------------------------------------------
121
122def test_all_six_loss_reasons_are_valid_and_old_reasons_unaffected(tmp_path, monkeypatch):
123 data_dir = setup_env(tmp_path, monkeypatch)
124 make_product(data_dir)
125 make_location(data_dir)
126 for i, reason in enumerate(("waste", "breakage", "theft", "expiry",
127 "damage", "disaster")):
128 make_move(data_dir, f"m{i}", reason=reason, from_loc="loc1")
129 make_move(data_dir, "m-old", reason="transfer", from_loc="loc1", to_loc="loc1")
130 rows = object_records.read_collection_records("stock_moves", base_dir=data_dir)
131 assert len(rows) == 7
132
133
134def test_schema_declares_the_hook_and_reason_filter(tmp_path, monkeypatch):
135 data_dir = setup_env(tmp_path, monkeypatch)
136 schema = object_schemas.get_schema("stock_moves", base_dir=data_dir)
137 assert schema["hooks"]["before_write"] == "hook_stock_moves"
138 assert "reason" in schema["views"]["filter_fields"]
139
140
141# --- 2/3. hook: stamps and gates -------------------------------------------
142
143def test_hook_stamps_product_cost_when_absent_and_keeps_explicit_cost(tmp_path, monkeypatch):
144 data_dir = setup_env(tmp_path, monkeypatch)
145 make_product(data_dir, cost="250")
146 stamped = run_hook({"product_id": "prod1", "quantity": "3",
147 "reason": "waste", "from_location_id": "loc1"})
148 assert stamped["record"]["unit_cost_cents"] == "250"
149 explicit = run_hook({"product_id": "prod1", "quantity": "3", "reason": "purchase",
150 "to_location_id": "loc1", "unit_cost_cents": "199"})
151 assert explicit is None # no transform: the client's invoice cost is kept
152
153
154def test_later_product_cost_edit_never_touches_the_stamped_move(tmp_path, monkeypatch):
155 data_dir = setup_env(tmp_path, monkeypatch)
156 make_product(data_dir, cost="250")
157 make_location(data_dir)
158 stamped = run_hook({"id": "mv-stamp", "product_id": "prod1", "quantity": "2",
159 "reason": "waste", "from_location_id": "loc1",
160 "occurred_at": "2026-07-24", "owner_id": "dan"})
161 object_records.create_collection_record(
162 "stock_moves", stamped["record"], base_dir=data_dir)
163 object_records.update_collection_record(
164 "products", "prod1", {"cost_cents": "999"}, base_dir=data_dir)
165 move = object_records.get_collection_record("stock_moves", "mv-stamp", base_dir=data_dir)
166 assert move["unit_cost_cents"] == "250"
167
168
169def test_hook_gates_quantity_and_loss_shape(tmp_path, monkeypatch):
170 data_dir = setup_env(tmp_path, monkeypatch)
171 make_product(data_dir)
172 # Positive quantity and "a loss leaves a location" are the schema's
173 # `exclusive_min` and `required_when`, checked by the write path for
174 # every writer (the hook no longer says either).
175 schema = object_schemas.get_schema("stock_moves", base_dir=data_dir)
176 fields = {field["name"]: field for field in schema["fields"]}
177 assert fields["quantity"]["validation"] == {"exclusive_min": 0}
178 for quantity in ("0", "-2"):
179 with pytest.raises(object_records.InvalidRecordPayloadError,
180 match="'quantity' must be greater than 0"):
181 make_move(data_dir, "m-bad", reason="sale", qty=quantity)
182 for reason in ("waste", "breakage", "theft", "expiry", "damage", "disaster"):
183 with pytest.raises(object_records.InvalidRecordPayloadError,
184 match="'from_location_id' is required when reason is one of"):
185 make_move(data_dir, "m-bad", reason=reason)
186 with_to = run_hook({"product_id": "p", "quantity": "1", "reason": "waste",
187 "from_location_id": "loc1", "to_location_id": "loc2"})
188 assert with_to["status"] == 400 and "destination" in with_to["error"]
189 update = run_hook({"quantity": "0"}, action="update")
190 assert update is None # create-only
191
192
193# --- 4. shrinkage composer ---------------------------------------------------
194
195def test_waste_composes_posted_shrinkage_journal_idempotently(tmp_path, monkeypatch):
196 data_dir = setup_env(tmp_path, monkeypatch)
197 make_product(data_dir)
198 make_location(data_dir)
199 make_move(data_dir, "mv1", reason="waste", qty="3", cost="250", from_loc="loc1")
200 result = fire_stock_books("mv1")
201 assert result["posted"] is True
202 journal = journals(data_dir)[0]
203 assert journal["status"] == "posted"
204 assert journal["generated_from"] == "stock_moves/mv1"
205 by_account = {l["account_id"]: l for l in lines_for(data_dir, result["journal_id"])}
206 assert by_account[SHRINK]["debit_cents"] == "750"
207 assert by_account[INV]["credit_cents"] == "750"
208 replay = fire_stock_books("mv1")
209 assert "already composed" in replay["skipped"]
210 assert len(journals(data_dir)) == 1
211
212
213def test_per_reason_account_override_routes_theft(tmp_path, monkeypatch):
214 data_dir = setup_env(tmp_path, monkeypatch, settings=(
215 ("inventory.journal.inventory_account", INV),
216 ("inventory.journal.shrinkage_account", SHRINK),
217 ("inventory.journal.theft_account", THEFT),
218 ))
219 make_product(data_dir)
220 make_location(data_dir)
221 make_move(data_dir, "mv-theft", reason="theft", qty="1", cost="1000", from_loc="loc1")
222 result = fire_stock_books("mv-theft")
223 by_account = {l["account_id"]: l for l in lines_for(data_dir, result["journal_id"])}
224 assert by_account[THEFT]["debit_cents"] == "1000"
225 assert by_account[INV]["credit_cents"] == "1000"
226
227
228def test_unconfigured_accounts_skip_and_move_is_unaffected(tmp_path, monkeypatch):
229 data_dir = setup_env(tmp_path, monkeypatch, settings=())
230 make_product(data_dir)
231 make_location(data_dir)
232 make_move(data_dir, "mv1", reason="waste", qty="3", from_loc="loc1")
233 result = fire_stock_books("mv1")
234 assert result["skipped"] == "accounts unconfigured"
235 assert journals(data_dir) == []
236 assert object_records.get_collection_record("stock_moves", "mv1", base_dir=data_dir)
237
238
239def test_a_transfer_shaped_adjustment_composes_nothing(tmp_path, monkeypatch):
240 """Both locations set: goods moved between shelves, no value changed."""
241 data_dir = setup_env(tmp_path, monkeypatch)
242 make_product(data_dir)
243 make_location(data_dir)
244 make_move(data_dir, "mv-tr", reason="adjustment", qty="2",
245 from_loc="loc1", to_loc="loc1")
246 assert fire_stock_books("mv-tr")["skipped"] == "not a loss event"
247 assert journals(data_dir) == []
248
249
250def test_a_sale_needs_its_own_account_and_never_borrows_shrinkage(
251 tmp_path, monkeypatch):
252 """A sale IS a composable direction now (COGS-on-sale, see
253 test_cogs_on_sale.py) -- but this env configures only inventory and
254 shrinkage, and cost of sales must never fall back to the shrinkage
255 account the loss reasons default to. Goods sold are not goods lost,
256 and routing one into the other misstates the P&L while still
257 balancing, which is the failure mode nobody notices."""
258 data_dir = setup_env(tmp_path, monkeypatch)
259 make_product(data_dir)
260 make_location(data_dir)
261 make_move(data_dir, "mv-sale", reason="sale", qty="2", from_loc="loc1")
262 assert fire_stock_books("mv-sale")["skipped"] == "accounts unconfigured"
263 assert journals(data_dir) == []
264
265
266# --- 5. count reconciliation -------------------------------------------------
267
268def test_count_shortage_writes_move_out_and_shrinkage_journal(tmp_path, monkeypatch):
269 data_dir = setup_env(tmp_path, monkeypatch)
270 make_product(data_dir, cost="250")
271 make_location(data_dir)
272 make_move(data_dir, "mv-in", reason="purchase", qty="10", to_loc="loc1")
273 result = apply_count({"product_id": "prod1", "location_id": "loc1",
274 "counted_qty": "7"})
275 assert result["status"] == 200 and result["direction"] == "shortage"
276 assert result["variance"] == "-3"
277 move = object_records.get_collection_record("stock_moves", result["move_id"],
278 base_dir=data_dir)
279 assert move["from_location_id"] == "loc1" and move["to_location_id"] == ""
280 assert move["quantity"] == "3" and move["reference"] == "count variance"
281 assert move["unit_cost_cents"] == "250"
282 by_account = {l["account_id"]: l
283 for l in lines_for(data_dir, result["journal"]["journal_id"])}
284 assert by_account[SHRINK]["debit_cents"] == "750"
285 assert object_stock.quantity_at_location(
286 "prod1", "loc1", base_dir=data_dir) == Decimal("7")
287
288
289def test_count_overage_writes_move_in_and_mirror_journal(tmp_path, monkeypatch):
290 data_dir = setup_env(tmp_path, monkeypatch)
291 make_product(data_dir, cost="100")
292 make_location(data_dir)
293 make_move(data_dir, "mv-in", reason="purchase", qty="10", to_loc="loc1")
294 result = apply_count({"product_id": "prod1", "location_id": "loc1",
295 "counted_qty": "12"})
296 assert result["direction"] == "overage" and result["variance"] == "2"
297 by_account = {l["account_id"]: l
298 for l in lines_for(data_dir, result["journal"]["journal_id"])}
299 assert by_account[INV]["debit_cents"] == "200"
300 assert by_account[SHRINK]["credit_cents"] == "200"
301 assert object_stock.quantity_at_location(
302 "prod1", "loc1", base_dir=data_dir) == Decimal("12")
303
304
305def test_count_match_is_a_no_op(tmp_path, monkeypatch):
306 data_dir = setup_env(tmp_path, monkeypatch)
307 make_product(data_dir)
308 make_location(data_dir)
309 make_move(data_dir, "mv-in", reason="purchase", qty="5", to_loc="loc1")
310 result = apply_count({"product_id": "prod1", "location_id": "loc1",
311 "counted_qty": "5"})
312 assert result["variance"] == "0"
313 moves = object_records.read_collection_records("stock_moves", base_dir=data_dir)
314 assert len(moves) == 1 # only the purchase
315 assert journals(data_dir) == []
316
317
318# --- 6. levels reflect losses -----------------------------------------------
319
320def test_stock_levels_reflect_loss_moves(tmp_path, monkeypatch):
321 data_dir = setup_env(tmp_path, monkeypatch)
322 make_product(data_dir)
323 make_location(data_dir)
324 make_move(data_dir, "mv-in", reason="purchase", qty="10", to_loc="loc1")
325 make_move(data_dir, "mv-waste", reason="waste", qty="3", from_loc="loc1")
326 make_move(data_dir, "mv-theft", reason="theft", qty="1", from_loc="loc1")
327 assert object_stock.quantity_at_location(
328 "prod1", "loc1", base_dir=data_dir) == Decimal("6")