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/object_stock.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, 8 minutes ago History
object_stock.py · 18.7 KB · 441 lines
1"""Derived stock levels, folded from the immutable stock_moves append log.
2
3This module belongs to the STOCK slice of packages/app-catalog (locations +
4stock_moves), but lives here at the repo root next to the other shared
5object_*.py modules (object_records.py, object_record_changes.py, ...)
6rather than inside packages/app-catalog/ itself. That placement is
7deliberate, not a convenience shortcut: package installs only ever copy the
8artifacts a manifest declares (objects/schemas/permissions/seed -- see
9object_packages.install_package) into the runtime's object/data roots, so a
10plain Python module sitting inside a package directory would never actually
11land anywhere importable at runtime. Every object in this codebase that
12needs shared logic imports a bare top-level module the same way
13packages/app-orders/objects/system/order_totals.py imports object_records
14and object_record_changes; this module follows that exact precedent so
15packages/app-catalog/objects/site/stock.py can `import object_stock` and
16have it resolve.
17
18Source model (reconciled against a private predecessor-system catalog
19audit, not part of this repo): a StockMove is immutable -- product_id moves
20quantity from from_location_id to to_location_id, once, forever. Current
21stock is never a stored column anywhere; it is always the fold of every
22move for a product (docs/append-only-storage-design.md's own "stock_moves
23is the textbook append-mode collection" framing, and the same source
24audit's own note: "StockMove (immutable, levels DERIVED not stored)").
25This module is that fold, nothing more.
26
27Quantity discipline: every quantity here is a Decimal, never a bare float.
28quantity is a count/measure, not currency -- may be fractional (e.g. 2.5
29kg) -- but Decimal arithmetic is still required so a fractional quantity
30can never introduce binary-float rounding error, the same "count/measure,
31not money" exception app-orders' order_lines.quantity documents.
32
33Blank from_location_id/to_location_id ("external origin"/"external
34destination" in the source model -- e.g. a purchase with no supplier
35location on file, or a sale with no customer location on file) simply have
36nothing to accumulate at: the fold below only touches a (product,
37location) key when the id is non-empty. The paired real location's balance
38still moves normally either way.
39
40Virtual locations (location_type customer/supplier/virtual) hold balances
41like any other location -- a stock move into a virtual "customer" location
42models stock that left the business, for instance -- but they are excluded
43from total_quantity's on-hand figure, matching the source model's own
44total_quantity semantics: only real, physical locations count as "on
45hand."
46
47Negative levels: no floor or clamp is applied anywhere in this module. A
48location that has shipped out more than it ever received folds to a
49negative Decimal and is left visible rather than floored to zero. The
50predecessor audit's own business-records notes admit stock/balance
51integrity is enforced nowhere at write time ("WEAK: ... balance NOT
52enforced at post" -- said there of the ledger, but the same honesty
53applies here); inventing a clamp the append log itself does not assert
54would hide a real data-quality signal (overselling) rather than surface
55it. This is the documented choice where the source audit does not spell
56out clamp-vs-negative behavior explicitly.
57
58Scale note: every function here is a pure O(len(stock_moves)) fold over
59the full log on every call -- no materialized rollup, no cache. That is
60the right, honest trade for a first slice at this collection's expected
61scale (append-mode collections read fine up to the thresholds documented
62in docs/storage-modes.md). A materialized/incremental rollup -- recomputed
63only from moves newer than the last snapshot, or a per-(product,location)
64sidecar -- is future work, the same trade docs/append-only-storage-design.md
65already calls out for any derived index over an append log ("Secondary
66sidecar indexes are future work, only when a named workload demands one").
67"""
68from __future__ import annotations
69
70from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
71from pathlib import Path
72from typing import Any, Iterable
73
74import object_collections
75import object_records
76import object_schemas
77
78STOCK_MOVES_COLLECTION = "stock_moves"
79LOCATIONS_COLLECTION = "locations"
80
81# Location types that are counterparties, not physical inventory --
82# excluded from total_quantity's on-hand figure. Matches locations.json's
83# location_type enum tail (customer, supplier, virtual).
84VIRTUAL_LOCATION_TYPES = frozenset({"customer", "supplier", "virtual"})
85
86
87def _decimal(value: Any) -> Decimal:
88 """Parse a stored quantity as Decimal; blank/invalid -> 0."""
89 text = str(value if value is not None else "").strip()
90 if not text:
91 return Decimal("0")
92 try:
93 return Decimal(text)
94 except InvalidOperation:
95 return Decimal("0")
96
97
98def _stock_moves(
99 *,
100 base_dir: Path | str,
101 owner: str | None = None,
102 roots: Iterable[Path] | None = None,
103) -> list[dict[str, str]]:
104 moves = object_records.read_collection_records(
105 STOCK_MOVES_COLLECTION, base_dir=base_dir, roots=roots
106 )
107 if owner is not None:
108 moves = [move for move in moves if move.get("owner_id") == owner]
109 return moves
110
111
112def _locations(
113 *,
114 base_dir: Path | str,
115 owner: str | None = None,
116 roots: Iterable[Path] | None = None,
117) -> list[dict[str, str]]:
118 """Return locations records, or [] when the collection isn't known yet.
119
120 Defensive only: in every real install locations and stock_moves ship
121 together in the same package, but a caller could point base_dir at a
122 data dir where locations was never installed (e.g. an isolated test of
123 stock_moves alone) -- rather than raising, virtual-location resolution
124 degrades to "nothing is virtual" instead of failing the whole fold.
125 """
126 try:
127 locations = object_records.read_collection_records(
128 LOCATIONS_COLLECTION, base_dir=base_dir, roots=roots
129 )
130 except (object_schemas.SchemaNotFoundError, LookupError, OSError):
131 return []
132 if owner is not None:
133 locations = [loc for loc in locations if loc.get("owner_id") == owner]
134 return locations
135
136
137def virtual_location_ids(
138 *,
139 base_dir: Path | str,
140 owner: str | None = None,
141 roots: Iterable[Path] | None = None,
142) -> set[str]:
143 """Return the set of location ids whose location_type is virtual
144 (customer, supplier, or virtual) -- the ids total_quantity excludes.
145 """
146 return {
147 loc["id"]
148 for loc in _locations(base_dir=base_dir, owner=owner, roots=roots)
149 if loc.get("id") and loc.get("location_type") in VIRTUAL_LOCATION_TYPES
150 }
151
152
153def _fold_levels(moves: Iterable[dict[str, str]]) -> dict[tuple[str, str], Decimal]:
154 """Fold immutable stock_moves rows into net (product_id, location_id) deltas.
155
156 A move INTO a location adds quantity; a move OUT OF a location
157 subtracts it. A blank from/to id has no location to accumulate at and
158 is simply skipped for that side of the move.
159 """
160 levels: dict[tuple[str, str], Decimal] = {}
161 for move in moves:
162 product_id = move.get("product_id")
163 if not product_id:
164 continue
165 quantity = _decimal(move.get("quantity"))
166
167 to_location_id = move.get("to_location_id")
168 if to_location_id:
169 key = (product_id, to_location_id)
170 levels[key] = levels.get(key, Decimal("0")) + quantity
171
172 from_location_id = move.get("from_location_id")
173 if from_location_id:
174 key = (product_id, from_location_id)
175 levels[key] = levels.get(key, Decimal("0")) - quantity
176
177 return levels
178
179
180def quantity_at_location(
181 product_id: str,
182 location_id: str,
183 *,
184 base_dir: Path | str,
185 owner: str | None = None,
186 roots: Iterable[Path] | None = None,
187) -> Decimal:
188 """Return the net on-hand quantity of one product at one location.
189
190 Sum of quantity for every move INTO location_id minus every move OUT
191 OF it, for product_id only. A blank location_id (the "external
192 origin/destination" sentinel -- see module docstring) always returns 0:
193 it names no real location to hold a balance at.
194 """
195 if not location_id:
196 return Decimal("0")
197 levels = _fold_levels(_stock_moves(base_dir=base_dir, owner=owner, roots=roots))
198 return levels.get((product_id, location_id), Decimal("0"))
199
200
201def location_state(
202 product_id: str,
203 location_id: str,
204 *,
205 base_dir: Path | str,
206 roots: Iterable[Path] | None = None,
207) -> tuple[Decimal, str]:
208 """(quantity_at_location, basis) from ONE read of the log.
209
210 `basis` fingerprints exactly which moves the quantity was folded from
211 (the sorted ids of every move of this product touching this location).
212 A writer that decides from the quantity -- a count posting the
213 variance -- derives its move id from it, so two decisions taken against
214 the same state produce the same id and the second create is refused
215 inside the write lock (action_apply_count).
216 """
217 import hashlib
218
219 moves = [m for m in _stock_moves(base_dir=base_dir, roots=roots)
220 if m.get("product_id") == product_id and location_id
221 and location_id in (m.get("from_location_id"), m.get("to_location_id"))]
222 quantity = _fold_levels(moves).get((product_id, location_id), Decimal("0"))
223 ids = ",".join(sorted(str(m.get("id") or "") for m in moves))
224 basis = hashlib.sha256(f"{product_id}|{location_id}|{ids}".encode()).hexdigest()
225 return quantity, basis
226
227
228def total_quantity(
229 product_id: str,
230 *,
231 base_dir: Path | str,
232 owner: str | None = None,
233 roots: Iterable[Path] | None = None,
234) -> Decimal:
235 """Return one product's total real on-hand quantity.
236
237 Sums net quantity across every location the product's moves touch,
238 EXCLUDING virtual location types (customer/supplier/virtual) -- matches
239 the source model's total_quantity semantics: only physical locations
240 count as "on hand." A location id referenced by a move but no longer
241 present in the locations collection (e.g. deleted) is treated as real
242 (included), the conservative default when its type can no longer be
243 resolved.
244 """
245 levels = _fold_levels(_stock_moves(base_dir=base_dir, owner=owner, roots=roots))
246 virtual_ids = virtual_location_ids(base_dir=base_dir, owner=owner, roots=roots)
247
248 total = Decimal("0")
249 for (moved_product_id, location_id), quantity in levels.items():
250 if moved_product_id != product_id:
251 continue
252 if location_id in virtual_ids:
253 continue
254 total += quantity
255 return total
256
257
258def stock_levels(
259 *,
260 base_dir: Path | str,
261 owner: str | None = None,
262 roots: Iterable[Path] | None = None,
263) -> dict[str, list[dict[str, str]]]:
264 """Return a page-ready summary: per-(product, location) net quantity,
265 and per-product on-hand totals (virtual locations excluded).
266
267 One fold over stock_moves serves both halves of the summary, so this
268 is cheaper than calling quantity_at_location/total_quantity in a loop
269 per product. Quantities are returned as strings (str(Decimal(...))) --
270 JSON- and TSV-safe, exact, never a float.
271 """
272 moves = _stock_moves(base_dir=base_dir, owner=owner, roots=roots)
273 levels = _fold_levels(moves)
274 virtual_ids = virtual_location_ids(base_dir=base_dir, owner=owner, roots=roots)
275
276 totals: dict[str, Decimal] = {}
277 level_rows = []
278 for (product_id, location_id), quantity in sorted(levels.items()):
279 level_rows.append({
280 "product_id": product_id,
281 "location_id": location_id,
282 "quantity": str(quantity),
283 })
284 if location_id not in virtual_ids:
285 totals[product_id] = totals.get(product_id, Decimal("0")) + quantity
286
287 total_rows = [
288 {"product_id": product_id, "quantity": str(quantity)}
289 for product_id, quantity in sorted(totals.items())
290 ]
291
292 return {"levels": level_rows, "totals": total_rows}
293
294
295# === valuation: what the goods cost, for COGS ==================================
296#
297# The stock fold above answers "how many"; this answers "at what cost",
298# which is the prerequisite COGS-on-sale was blocked on. The method is
299# WEIGHTED AVERAGE, and it is a decision rather than a default:
300#
301# FIFO would be more precise, and it is what a lot-tracked warehouse
302# should use -- but it requires cost LAYERS (which units, from which
303# receipt, are still on the shelf), and stock_moves has no lot dimension
304# at all. Bolting layers on to satisfy one journal entry would be a
305# storage change driven by an accounting report. LIFO is not permitted
306# under IFRS and is a bad fit besides. Weighted average needs nothing the
307# append log does not already carry, is accepted under both GAAP and
308# IFRS, and is what most small shops actually run.
309#
310# MOVING average, specifically, folded in move order -- not the simpler
311# "total spent / total ever bought". The two genuinely differ: buy 10 at
312# 100, sell 10, buy 1 at 300, and the lifetime average says 118 while the
313# moving average says 300, which is what the next sale actually costs.
314# The lifetime version quietly reprices goods you no longer own.
315#
316# A depletion at an unknown average (nothing on hand) consumes nothing and
317# says so by leaving the value alone; the caller sees None and must skip
318# rather than guess, which is the whole point of the exercise.
319#
320# What counts as arriving and leaving is decided by WHERE the goods are,
321# the same rule total_quantity uses: a customer, supplier or virtual
322# location is outside the shop. Until 2026-11-28 the fold decided it by
323# which end of a move was BLANK, so a sale into a customer location
324# (shelf -> customer, which is how order_fulfillment writes every sale once
325# shop.customer_location is set) read as a shelf-to-shelf transfer: sold
326# stock never left the average. Buy 10 at 250, sell 10, buy 10 at 350, and
327# it answered 300 for a shelf holding only 350-unit stock, so every later
328# sale was costed with goods already sold. A receipt from a supplier
329# location (supplier -> shelf, receipt_posting's shape) was likewise read
330# as a transfer and never entered the average at all.
331
332def _move_order_key(move: dict) -> tuple:
333 """Chronological order, falling back to insertion order.
334
335 occurred_at is the business date and may be blank or coarse (a plain
336 date), so created_at breaks ties -- two receipts on the same day must
337 still fold in the order they were recorded.
338 """
339 return (str(move.get("occurred_at") or move.get("created_at") or ""),
340 str(move.get("created_at") or ""))
341
342
343def weighted_average_cost_cents(
344 moves: Iterable[dict[str, str]],
345 product_id: str,
346 virtual_locations: Iterable[str] = (),
347) -> int | None:
348 """The moving weighted-average unit cost of one product, in cents.
349
350 Returns None when there is nothing on hand or no acquisition ever
351 carried a cost -- there is no honest average to report, and a caller
352 that stamps one anyway has invented a valuation method by accident.
353
354 `virtual_locations`: the ids of customer/supplier/virtual locations
355 (virtual_location_ids). A move from outside (blank or virtual) into a
356 real location is an acquisition; a move from a real location to
357 outside is a depletion; real to real is a transfer and changes
358 nothing. Leave it empty only for moves that name no virtual locations.
359
360 Pure: takes rows, returns a number. No I/O, no clock.
361 """
362 outside = {str(v) for v in virtual_locations}
363 on_hand = Decimal("0")
364 value = Decimal("0")
365
366 for move in sorted((m for m in moves if m.get("product_id") == product_id),
367 key=_move_order_key):
368 quantity = _decimal(move.get("quantity"))
369 if quantity <= 0:
370 continue
371 cost = _decimal(move.get("unit_cost_cents"))
372 to_location = str(move.get("to_location_id") or "").strip()
373 from_location = str(move.get("from_location_id") or "").strip()
374 # "Real" = a location the shop holds stock in.
375 into = bool(to_location) and to_location not in outside
376 out_of = bool(from_location) and from_location not in outside
377
378 # An acquisition is stock arriving from outside with a price on
379 # it. A transfer (both ends real) moves goods between shelves and
380 # must not re-average anything.
381 if into and not out_of:
382 if cost > 0:
383 value += quantity * cost
384 on_hand += quantity
385 else:
386 # Free/uncosted stock still occupies the shelf, and
387 # pretending it does not would inflate the average for
388 # everything else on it.
389 on_hand += quantity
390 continue
391
392 if out_of and not into:
393 # A depletion consumes stock at the average it was carried at,
394 # which leaves the average itself unchanged -- the defining
395 # property of weighted average.
396 if on_hand <= 0:
397 continue
398 unit = value / on_hand
399 consumed = min(quantity, on_hand)
400 value -= consumed * unit
401 on_hand -= consumed
402
403 if on_hand <= 0 or value <= 0:
404 return None
405 return int((value / on_hand).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
406
407
408def average_cost_for_product(
409 product_id: str,
410 *,
411 base_dir: Path | str = object_records.DEFAULT_DATA_DIR,
412 owner: str | None = None,
413 roots: Iterable[Path] | None = None,
414) -> int | None:
415 """weighted_average_cost_cents against stored moves.
416
417 The locations are read strictly: one that cannot be read raises rather
418 than reading as "nothing is virtual", which would turn every sale into
419 a transfer again. Not installed is still "nothing is virtual". What a
420 caller does with the raise differs, and has to: hook_stock_moves is a
421 gate and REFUSES the sale (falling back there wrote the typed-in
422 standard cost down as that sale's cost for good, which is the fail-open
423 this read was made strict to prevent); order_fulfillment is a reaction
424 to a parcel that has already shipped and cannot refuse, so it writes
425 the sale move with no cost and a marker saying why, rather than the
426 standard cost (system_order_fulfillment, "An average that cannot be
427 READ is not no average").
428 """
429 try:
430 locations = object_records.read_collection_records(
431 LOCATIONS_COLLECTION, base_dir=base_dir, roots=roots)
432 except (object_schemas.SchemaNotFoundError,
433 object_collections.CollectionNotFoundError):
434 locations = []
435 if owner is not None:
436 locations = [loc for loc in locations if loc.get("owner_id") == owner]
437 virtual = {loc["id"] for loc in locations
438 if loc.get("id") and loc.get("location_type") in VIRTUAL_LOCATION_TYPES}
439 return weighted_average_cost_cents(
440 _stock_moves(base_dir=base_dir, owner=owner, roots=roots), product_id,
441 virtual)