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

9 downloads

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, 49 minutes ago History
receipt_posting.py · 17.1 KB · 403 lines
1"""system_receipt_posting -- the pallet landed, so the shelf is heavier and
2the purchase order says so.
3
4HANDLES receipts and receipt_lines writes. Two jobs, both of them reads
5turned into facts, mirroring system_order_fulfillment on the sales side.
6
7**Stock moves when goods physically move.** One `purchase` move PER
8RECEIPT LINE at the moment a receipt reaches `received`, from
9receiving.supplier_location to receiving.stock_location (falling back to
10shop.stock_location, because a one-warehouse shop has already configured
11that and should not have to say the same thing twice). Per line rather
12than per receipt because a level is a fold over moves per product, and a
13delivery routinely carries several products with different fates.
14
15**Rejected quantities compose NOTHING.** Goods being sent back never
16entered stock: the carton was opened at the door, judged crushed, and put
17straight on the driver's trolley. A move for it would put damaged goods on
18the shelf and then require a compensating move to take them off again --
19two lies that happen to cancel, which is worse than one honest silence.
20The rejection is still RECORDED, on the receipt line, where the argument
21with the supplier can find it.
22
23**unit_cost_cents is stamped from the PO line's unit_price_cents.** This
24is the move that makes inventory valuation possible later: a `sale` move
25today carries no cost at all, which is exactly why COGS-on-sale cannot be
26composed (see tests/test_cogs_on_sale.py, which specifies that gap as a
27strict xfail -- its point 3 says in as many words that "nothing stamps
28that cost on a sale move today, and where a sale move carries no cost, no
29honest journal can be composed at all"). FIFO or weighted average both
30need a cost on the way IN, per layer, per location; stamping the price we
31actually agreed to pay at the moment the goods arrive is the input both
32methods consume, and it costs nothing to record now and cannot be
33reconstructed later once the supplier's price list has moved on. Choosing
34BETWEEN FIFO and average stays out of this handler on purpose -- picking a
35valuation method by accident inside a receiving reaction would be worse
36than the current silence.
37
38**The purchase order's status is derived, never set.** Some of the ordered
39quantity received is `partial`; all of it is `received`
40(docs/logic-decisions.md #1: the QUANTITIES on receipt lines are the
41facts, the order's status is a read of them). A human never types either
42one and no surface computes it at read time; it is stored, so the PO list,
43the receiving sheet and a report cannot disagree.
44
45`received` is a NEW value on the shared SO/PO status enum (orders v3), and
46it is deliberately not a reuse of `delivered`. `delivered` on a purchase
47order reads as a claim about something WE sent -- in a mixed order list,
48filtered by status rather than by doc_type, it is actively misleading, and
49"the goods completed their journey" is a gloss nobody applies at a glance.
50`received` can only ever mean one thing in either direction: the goods
51turned up HERE. The spec says the same (plan/fulfillment-logistics-spec.md:
52"PO status derives: partial | received"), and the cost of the alternative
53is a word that means the opposite of itself depending on a field two
54columns away.
55
56Placement follows docs/logic-decisions.md #6 -- a REACTION, post-commit,
57best-effort, never blocking the write that triggered it. A dock that
58cannot record a stock move must still be able to sign for the delivery;
59the discrepancy is visible and fixable, whereas a refused receipt is a
60driver standing at the door with a pallet nobody can accept.
61
62Idempotency by provenance (#7): each move is stamped
63`receipts/{receipt_id}:line/{line_id}` in its reference, PER LINE. A
64replayed event -- and events are replayed here, by design: the change
65dispatcher promises at-least-once (object_change_dispatch.py) -- finds its
66own marker and moves nothing. Per line and not per receipt because a
67receipt can gain a line while still open, and a receipt-level marker would
68silently skip the goods added after the first pass.
69
70Missing settings do not cost anybody the record that goods arrived. If no
71stock location is configured the receipt still stands, the PO status still
72derives, and the gap is reported in `warning` -- the same posture
73system_order_fulfillment has always had, for the same reason: a missing
74location is a five-second fix, and a lost delivery record is not.
75"""
76
77import os
78from datetime import date
79from decimal import Decimal, InvalidOperation
80
81import object_collections
82import object_ids
83import object_records
84
85HANDLES = [
86 "receipts.record.created",
87 "receipts.record.updated",
88 "receipt_lines.record.created",
89]
90
91ACTOR = "system_receipt_posting"
92
93# The delivery has been signed for: the goods are ours and on the shelf.
94RECEIVED_STATUSES = {"received"}
95
96# A receipt abandoned before anything was counted describes no goods, so
97# its lines count for nothing when deriving what has arrived.
98NOT_RECEIVED_STATUSES = {"cancelled"}
99
100# A purchase order in one of these is not something receiving may touch: a
101# draft is not a commitment, and a cancelled PO must not quietly come back
102# to life because a supplier delivered against it anyway.
103UNTOUCHABLE_ORDER_STATUSES = {"draft", "cancelled"}
104
105
106def _base_dir():
107 return os.environ.get("DBBASIC_DATA_DIR", "data")
108
109
110def _text(value):
111 return str(value if value is not None else "").strip()
112
113
114def _quantity(value):
115 """Decimal, never a bare float -- quantities may be fractional."""
116 try:
117 return Decimal(_text(value) or "0")
118 except InvalidOperation:
119 return Decimal(0)
120
121
122def _number(value):
123 return format(value.normalize(), "f")
124
125
126def _setting(base, key, default=""):
127 """Duplicated on purpose, same as every other package that reads
128 app_settings: there is no shared settings module in this codebase yet,
129 and inventing one for a fifth copy is the layer this house rule
130 (docs/logic-decisions.md #4) says to wait on."""
131 try:
132 for row in object_records.read_collection_records("app_settings",
133 base_dir=base):
134 if row.get("key") == key and _text(row.get("value")):
135 return _text(row["value"])
136 except Exception:
137 pass
138 return default
139
140
141def _receipt_for(request, base):
142 """The receipt this event is about, whichever collection fired it.
143
144 A receipt_lines event names a line; the thing that matters is its
145 parent, because a line added to an already-received receipt is goods
146 that still have to land on the shelf.
147
148 Both the record itself and a bare record_id are accepted: the HTTP
149 dispatcher and the change-log dispatcher both send record_id, while an
150 operator poking this by hand (or a sibling handler calling it in
151 process) has the row already.
152 """
153 collection = _text(request.get("collection"))
154 record = request.get("record")
155 record_id = _text(request.get("record_id") or request.get("id"))
156
157 if collection == "receipt_lines":
158 line = record if isinstance(record, dict) and record.get("id") else None
159 if line is None and record_id:
160 try:
161 line = object_records.get_collection_record(
162 "receipt_lines", record_id, base_dir=base)
163 except Exception:
164 return None
165 if not line:
166 return None
167 record_id = _text(line.get("receipt_id"))
168 record = None
169
170 if isinstance(record, dict) and record.get("id") and collection != "receipt_lines":
171 # Re-read rather than trust the payload: an event carrying a stale
172 # copy (dispatched from the change log, minutes later) must not make
173 # this handler act on a status the receipt has since moved past.
174 record_id = _text(record.get("id"))
175
176 if not record_id:
177 return None
178 try:
179 return object_records.get_collection_record("receipts", record_id,
180 base_dir=base)
181 except Exception:
182 return None
183
184
185class LedgerUnreadable(Exception):
186 """An installed collection the stock move decides from could not be
187 read: an unknown, not "nothing to move"."""
188
189
190def _ledger(collection, base):
191 """Every row of `collection`, None only when it is not installed (a
192 fact), LedgerUnreadable for anything else."""
193 try:
194 return object_records.read_collection_records(collection, base_dir=base)
195 except object_collections.CollectionNotFoundError:
196 return None
197 except Exception as exc:
198 raise LedgerUnreadable(f"{collection}: {str(exc)[:160]}") from exc
199
200
201def _lines_of(base, receipt_id):
202 rows = _ledger("receipt_lines", base) or []
203 return [row for row in rows if _text(row.get("receipt_id")) == receipt_id]
204
205
206def _order_lines_of(base, order_id):
207 """Raises LedgerUnreadable; _derive_order_status reads it as "say
208 nothing", _move_stock as "move nothing" (no price to stamp)."""
209 rows = _ledger("order_lines", base) or []
210 return [row for row in rows if _text(row.get("order_id")) == order_id]
211
212
213def _move_stock(base, receipt, order, moves):
214 """One purchase move per line, idempotent per line by provenance marker.
215
216 Returns (moved, warning). `moves` is the already-read stock_moves log,
217 or None when the collection does not exist at all (a shop buying
218 services has nothing to shelve and is not broken).
219 """
220 if moves is None:
221 return 0, "stock not installed; nothing to move"
222
223 from_location = _setting(base, "receiving.supplier_location")
224 to_location = (_setting(base, "receiving.stock_location")
225 or _setting(base, "shop.stock_location"))
226 existing = [_text(move.get("reference")) for move in moves]
227
228 # The agreed price per ordered thing, for the cost stamp. Read from the
229 # PO line rather than from the product: what we are about to own it for
230 # is what this purchase actually cost, not what the catalog guesses.
231 prices = {row["id"]: _text(row.get("unit_price_cents"))
232 for row in _order_lines_of(base, order["id"])}
233
234 moved = 0
235 warning = ""
236 when = _text(receipt.get("received_on")) or date.today().isoformat()
237 for line in _lines_of(base, receipt["id"]):
238 product_id = _text(line.get("product_id"))
239 if not product_id:
240 continue # a service never sat on a shelf
241 quantity = _quantity(line.get("quantity_received"))
242 if quantity <= 0:
243 # A rejected-only line, or a wholly short delivery. Nothing
244 # entered stock, so nothing moves; the discrepancy lives on the
245 # receipt line where the supplier argument can find it.
246 continue
247 marker = f"receipts/{receipt['id']}:line/{line['id']}"
248 if any(marker in reference for reference in existing):
249 continue # this line already landed
250 if not to_location:
251 warning = ("receiving.stock_location (or shop.stock_location) is "
252 "not configured, so nothing landed on a shelf; the "
253 "receipt still stands")
254 break
255 move = {
256 "id": object_ids.new_uuid4(),
257 "product_id": product_id,
258 "from_location_id": from_location,
259 "to_location_id": to_location,
260 "quantity": _number(quantity),
261 "reason": "purchase",
262 "reference": f"{marker} {_text(order.get('number'))}".strip(),
263 "occurred_at": when,
264 "owner_id": _text(receipt.get("owner_id")),
265 "entity_id": _text(receipt.get("entity_id")),
266 }
267 unit_cost = prices.get(_text(line.get("order_line_id")), "")
268 if unit_cost:
269 # The cost on the way IN, stamped at the moment of movement --
270 # the input FIFO and weighted average both consume, and the one
271 # that cannot be reconstructed once the price list moves on.
272 move["unit_cost_cents"] = unit_cost
273 object_records.create_collection_record("stock_moves", move,
274 base_dir=base, actor=ACTOR)
275 existing.append(marker)
276 moved += 1
277 return moved, warning
278
279
280def _derive_order_status(base, order):
281 """What the receipt lines say this purchase order's status is.
282
283 Returns "" when the facts say nothing yet (nothing received), so the PO
284 is left exactly as a human last set it rather than being dragged
285 backwards by a machine that knows less than they do.
286 """
287 try:
288 order_lines = _order_lines_of(base, order["id"])
289 except LedgerUnreadable:
290 return ""
291 if not order_lines:
292 return ""
293
294 try:
295 receipts = [row for row in object_records.read_collection_records(
296 "receipts", base_dir=base)
297 if _text(row.get("order_id")) == order["id"]]
298 except Exception:
299 return ""
300
301 counted = {row["id"]: _text(row.get("status")) for row in receipts
302 if _text(row.get("status")) not in NOT_RECEIVED_STATUSES}
303 if not counted:
304 return ""
305
306 try:
307 all_lines = object_records.read_collection_records("receipt_lines",
308 base_dir=base)
309 except Exception:
310 return ""
311
312 received_by_line = {}
313 for line in all_lines:
314 if counted.get(_text(line.get("receipt_id")), "") not in RECEIVED_STATUSES:
315 continue # an open receipt is a count in
316 key = _text(line.get("order_line_id")) # progress, not a fact
317 received_by_line[key] = received_by_line.get(key, Decimal(0)) + \
318 _quantity(line.get("quantity_received"))
319
320 if sum(received_by_line.values(), Decimal(0)) <= 0:
321 return ""
322
323 everything = all(
324 received_by_line.get(line["id"], Decimal(0)) >= _quantity(line.get("quantity"))
325 for line in order_lines)
326 if not everything:
327 return "partial"
328 return "received"
329
330
331def EVENT(request):
332 base = _base_dir()
333 receipt = _receipt_for(request, base)
334 if not receipt:
335 return {"ok": True, "skipped": "no receipt in the event"}
336
337 try:
338 order = object_records.get_collection_record(
339 "orders", _text(receipt.get("order_id")), base_dir=base)
340 except Exception:
341 return {"ok": True, "skipped": "no order for this receipt",
342 "receipt_id": receipt["id"]}
343
344 if _text(order.get("doc_type")) != "purchase":
345 # Belt and braces behind action_receive_goods' refusal: a receipt
346 # written straight through the HTTP path against a sales order must
347 # not silently move stock the wrong way.
348 return {"ok": True, "skipped": "not a purchase order",
349 "receipt_id": receipt["id"], "order_id": order["id"]}
350
351 order_status = _text(order.get("status"))
352 if order_status in UNTOUCHABLE_ORDER_STATUSES:
353 return {"ok": True, "skipped": f"order is {order_status}",
354 "receipt_id": receipt["id"], "order_id": order["id"]}
355
356 result = {"ok": True, "receipt_id": receipt["id"], "order_id": order["id"],
357 "moved": 0}
358
359 if _text(receipt.get("status")) in RECEIVED_STATUSES:
360 try:
361 moves = _ledger("stock_moves", base)
362 moved, warning = _move_stock(base, receipt, order, moves)
363 except LedgerUnreadable as exc:
364 # Installed but unreadable is not "stock not installed": the
365 # per-line markers (or the PO prices) cannot be read, so nothing
366 # lands and the result says so. The receipt stands; the next
367 # event for it lands the goods once, costed.
368 moved = 0
369 result["stock_unreadable"] = str(exc)
370 warning = (f"The stock for this receipt did not move: {exc}. The "
371 f"receipt still stands; once the ledger can be read, "
372 f"re-save the receipt (or replay its event) and its "
373 f"lines will land exactly once.")
374 result["moved"] = moved
375 if warning:
376 # The receipt stands and the gap is visible, which is the right
377 # way round: a missing setting must not cost somebody the record
378 # that goods arrived, and an invisible discrepancy is the one
379 # nobody fixes.
380 result["warning"] = warning
381
382 derived = _derive_order_status(base, order)
383 result["order_status"] = order_status
384 if derived and derived != order_status:
385 try:
386 object_records.update_collection_record(
387 "orders", order["id"], {"status": derived},
388 base_dir=base, actor=ACTOR)
389 result["order_status"] = derived
390 result["order_status_changed"] = True
391 except Exception as exc:
392 # A ladder that refuses the derived move is a real answer, not a
393 # crash: say so and leave the order where a human put it.
394 result["order_status_error"] = str(exc)[:200]
395 return result
396
397
398# EVENT is the verb the change dispatcher calls handlers with (see
399# object_change_dispatch); POST stays as an alias so an operator can poke
400# the handler by hand over HTTP. The alias is not decoration -- a handler
401# shipped with only POST silently matched nothing in production once, and
402# every handler in this house has carried both ever since.
403POST = EVENT