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
order_fulfillment.py · 23.3 KB · 519 lines
1"""system_order_fulfillment -- the box left, so the shelf is lighter and
2the order says so.
3
4HANDLES shipments and shipment_lines writes. Two jobs, both of them reads
5turned into facts:
6
7**Stock moves when goods physically move.** One `sale` move PER SHIPMENT
8LINE at the moment a shipment reaches `shipped`, from shop.stock_location
9to shop.customer_location. Per line rather than per shipment because a
10level is a fold over moves per product, and per order rather than per
11line was only ever right while an order could not be split -- the whole
12point of the shipment noun is that it can.
13
14**The order's status is derived, never set.** Some of the ordered quantity
15on shipped-or-beyond shipments is `partial`; all of it is `shipped`; all of
16it delivered is `delivered`; a lost or returned parcel does not count, so an
17order can go back from `shipped` to `partial`, or to `processing` when no
18parcel reached the customer at all (docs/logic-decisions.md #1: the QUANTITIES on
19shipment lines are the facts, the order's status is a read of them). A
20human never types `partial` and no surface computes it at read time; it is
21stored, so the order list, the pick list and a report cannot disagree.
22
23Placement follows docs/logic-decisions.md #6 -- a REACTION, post-commit,
24best-effort, never blocking the write that triggered it. A warehouse that
25cannot record a stock move must still be able to send the parcel; the
26discrepancy is visible and fixable, whereas a refused shipment is a
27customer waiting for goods that are sitting in a box by the door.
28
29Idempotency by provenance (#7): each move is stamped
30`shipments/{shipment_id}:line/{line_id}` in its reference, PER LINE. A
31replayed event -- and events are replayed here, by design: the change
32dispatcher promises at-least-once (object_change_dispatch.py) -- finds its
33own marker and moves nothing. Per line and not per shipment because a
34shipment can gain a line while still open, and a shipment-level marker
35would silently skip the goods added after the first pass.
36
37**The handover date is stamped here too**, and only when it is blank. A
38shipment reaching `shipped` IS the handover, so shipped_on is a fact about
39that moment (#1) -- and until the carrier slice needed it, nothing in the
40box ever wrote it, so every shipment the shop's own automation raised
41carried a blank date and site_manifest, which keys on it, would have printed
42an empty page for a morning's real work. An operator-typed date is never
43overwritten: somebody backdating a parcel knows something this handler does
44not.
45
46**The sale move carries its cost.** This handler writes at storage level,
47so hook_stock_moves -- which stamps unit_cost_cents on a move written over
48HTTP -- never sees it (doctrine #9: a storage-level writer performs its
49own reactions). Each sale move is therefore stamped here with the same
50valuation the hook uses: the moving weighted average of what is on the
51shelf (object_stock.average_cost_for_product), read BEFORE the move joins
52the log, falling back to the product's standard cost_cents when no priced
53stock was ever bought (a known answer). Without it the move landed
54costless, system_stock_books skipped it as "no stamped cost", and cost of
55goods never booked on a real sale -- every sale read as pure margin and
56the inventory asset never came down.
57
58**An average that cannot be READ is not "no average".** This handler used
59to fall back to the standard cost then too, which wrote a planning figure
60somebody typed (500) down as the cost of goods bought at 800, for good --
61the stamp is a point-in-time fact, nothing ever re-costs it, and nothing
62said it was a guess. hook_stock_moves refuses that sale outright; a
63reaction cannot refuse a parcel that has already left, so the move is
64still written (the shelf really is lighter) but with NO cost, the marker
65UNCOSTED_MARKER in its reference, and its id under `uncosted_moves` with a
66`warning` in this handler's result (which the execution log keeps). No
67cost of goods is booked for it: a visible gap somebody can book by hand
68at the real cost, rather than a wrong number nobody looks at again.
69
70**A ledger that cannot be read is not a ledger that is not installed.**
71An installed stock_moves or shipment_lines that fails to read used to be
72taken for "stock not installed; nothing to move", so the parcel left and
73the shelf never got lighter with nothing saying so. Without the ledger the
74per-line markers cannot be checked, so no move is written (a replay could
75otherwise move the goods twice); the result carries `stock_unreadable`
76and a `warning`, the order keeps the status it had, and the next event for
77the shipment moves the goods once the ledger reads again.
78
79Missing settings do not cost anybody a shipment. If shop.stock_location is
80unconfigured the parcel still ships, the order status still derives, and
81the gap is reported in `warning` -- the same posture the payment-side
82handler this one took the stock work over from has always had.
83"""
84
85import os
86from datetime import date
87from decimal import Decimal, InvalidOperation
88
89import object_collections
90import object_ids
91import object_records
92import object_stock
93
94HANDLES = [
95 "shipments.record.created",
96 "shipments.record.updated",
97 "shipment_lines.record.created",
98]
99
100ACTOR = "system_order_fulfillment"
101
102# Appended to a sale move's reference when the average cost could not be
103# read, so the gap is on the move itself (module docstring).
104UNCOSTED_MARKER = "[uncosted: its cost could not be read]"
105
106
107class CostUnreadable(Exception):
108 """The weighted average could not be computed: an unknown, not zero."""
109
110
111class LedgerUnreadable(Exception):
112 """An installed collection the stock move decides from could not be
113 read: an unknown, not "nothing to move"."""
114
115# The box is with a courier or a customer: the goods have left the shelf.
116SHIPPED_ONWARD = {"shipped", "in_transit", "delivered"}
117
118# Never reached the customer -- the order still owes those goods, so these
119# shipments' lines count for nothing when deriving what has been fulfilled.
120NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"}
121
122# An order in one of these is not something fulfillment may touch: a draft
123# is not a commitment and a cancelled order must not quietly come back to
124# life because somebody shipped against it by mistake.
125UNTOUCHABLE_ORDER_STATUSES = {"draft", "cancelled"}
126
127
128def _base_dir():
129 return os.environ.get("DBBASIC_DATA_DIR", "data")
130
131
132def _text(value):
133 return str(value if value is not None else "").strip()
134
135
136def _quantity(value):
137 """Decimal, never a bare float -- quantities may be fractional."""
138 try:
139 return Decimal(_text(value) or "0")
140 except InvalidOperation:
141 return Decimal(0)
142
143
144def _number(value):
145 return format(value.normalize(), "f")
146
147
148def _setting(base, key, default=""):
149 """Duplicated on purpose, same as every other package that reads
150 app_settings: there is no shared settings module in this codebase yet,
151 and inventing one for a fourth copy is the layer this house rule
152 (docs/logic-decisions.md #4) says to wait on."""
153 try:
154 for row in object_records.read_collection_records("app_settings",
155 base_dir=base):
156 if row.get("key") == key and _text(row.get("value")):
157 return _text(row["value"])
158 except Exception:
159 pass
160 return default
161
162
163def _shipment_for(request, base):
164 """The shipment this event is about, whichever collection fired it.
165
166 A shipment_lines event names a line; the thing that matters is its
167 parent, because a line added to an already-shipped shipment is goods
168 that still have to leave the shelf.
169
170 Both the record itself and a bare record_id are accepted: the HTTP
171 dispatcher and the change-log dispatcher both send record_id, while an
172 operator poking this by hand (or a sibling handler calling it in
173 process) has the row already.
174 """
175 collection = _text(request.get("collection"))
176 record = request.get("record")
177 record_id = _text(request.get("record_id") or request.get("id"))
178
179 if collection == "shipment_lines":
180 line = record if isinstance(record, dict) and record.get("id") else None
181 if line is None and record_id:
182 try:
183 line = object_records.get_collection_record(
184 "shipment_lines", record_id, base_dir=base)
185 except Exception:
186 return None
187 if not line:
188 return None
189 record_id = _text(line.get("shipment_id"))
190 record = None
191
192 if isinstance(record, dict) and record.get("id") and collection != "shipment_lines":
193 # Re-read rather than trust the payload: an event carrying a stale
194 # copy (dispatched from the change log, minutes later) must not make
195 # this handler act on a status the shipment has since moved past.
196 record_id = _text(record.get("id"))
197
198 if not record_id:
199 return None
200 try:
201 return object_records.get_collection_record("shipments", record_id,
202 base_dir=base)
203 except Exception:
204 return None
205
206
207def _ledger(collection, base):
208 """Every row of `collection`, None only when it is not installed (a
209 fact: there is no such ledger), LedgerUnreadable for anything else."""
210 try:
211 return object_records.read_collection_records(collection, base_dir=base)
212 except object_collections.CollectionNotFoundError:
213 return None
214 except Exception as exc:
215 raise LedgerUnreadable(f"{collection}: {str(exc)[:160]}") from exc
216
217
218def _lines_of(base, shipment_id):
219 rows = _ledger("shipment_lines", base) or []
220 return [row for row in rows if _text(row.get("shipment_id")) == shipment_id]
221
222
223def _sale_unit_cost(base, product_id):
224 """What one unit leaving the shelf is carried at, as hook_stock_moves
225 stamps it for an HTTP-written sale: the weighted average on hand, else
226 the product's standard cost, else "" (stock_books then skips it with a
227 reason rather than this handler inventing a valuation).
228
229 Raises CostUnreadable when the average could not be read: the hook
230 refuses there, and falling back to the standard cost would stamp a
231 guess as the fact (module docstring)."""
232 try:
233 average = object_stock.average_cost_for_product(product_id, base_dir=base)
234 except Exception as exc:
235 raise CostUnreadable(str(exc)[:160]) from exc
236 if average:
237 return str(average)
238 try:
239 product = object_records.get_collection_record("products", product_id,
240 base_dir=base)
241 except (object_records.RecordNotFoundError,
242 object_records.InvalidRecordIdError):
243 return "" # no such product: nothing to cost it at
244 except Exception as exc:
245 raise CostUnreadable(str(exc)[:160]) from exc
246 return _text(product.get("cost_cents"))
247
248
249def _move_stock(base, shipment, order, moves):
250 """One sale move per line, idempotent per line by provenance marker.
251
252 Returns (moved, skipped_reason, uncosted_move_ids). `moves` is the
253 already-read stock_moves log, or None when the collection does not
254 exist at all (a shop selling services and downloads has nothing to
255 move and is not broken).
256 """
257 if moves is None:
258 return 0, "stock not installed; nothing to move", []
259
260 # Drop-shipped goods never sat on our shelf. The vendor posted them
261 # straight to the customer, and the parcel is recorded here so the
262 # customer can be told and the order can complete -- but decrementing
263 # our own stock for it would invent a movement that never happened,
264 # and every count from then on would disagree with the room.
265 #
266 # `fulfillment_source` is read off the ORDER rather than the shipment
267 # because it is a property of how the sale is being met, not of one
268 # parcel: a part-drop-shipped order would still be answered honestly
269 # by splitting it into two orders, which is what the linked-order
270 # model already does.
271 if _text(order.get("fulfillment_source")) == "dropship":
272 return 0, "drop-shipped: the goods never touched our shelf", []
273
274 from_location = _setting(base, "shop.stock_location")
275 to_location = _setting(base, "shop.customer_location")
276 existing = [_text(move.get("reference")) for move in moves]
277
278 moved = 0
279 warning = ""
280 uncosted = []
281 today = _text(shipment.get("shipped_on")) or date.today().isoformat()
282 # What has already left the shelf for each order line, by any path: an
283 # earlier shipment's moves and app-counter's hand-over or remake moves
284 # (object_reservations.moved_by_line, the fold the stock holds use). A
285 # counter sale handed over and THEN shipped by shop_fulfillment's auto
286 # path must not leave the shelf twice (the Corner Cup finding).
287 import object_reservations
288 already = object_reservations.moved_by_line(moves, _ledger("shipment_lines", base) or [])
289 ordered = {}
290 try:
291 for row in object_records.read_collection_records("order_lines", base_dir=base):
292 if _text(row.get("order_id")) == _text(order.get("id")):
293 ordered[_text(row.get("id"))] = _quantity(row.get("quantity"))
294 except object_collections.CollectionNotFoundError:
295 pass
296 except Exception as exc:
297 raise LedgerUnreadable(f"order_lines: {str(exc)[:160]}") from exc
298 for line in _lines_of(base, shipment["id"]):
299 product_id = _text(line.get("product_id"))
300 if not product_id:
301 continue # a service never sat on a shelf
302 marker = f"shipments/{shipment['id']}:line/{line['id']}"
303 if any(marker in reference for reference in existing):
304 continue # this line already moved
305 if not from_location:
306 warning = ("shop.stock_location is not configured, so nothing "
307 "left the shelf; the shipment still stands")
308 break
309 quantity = _quantity(_text(line.get("quantity")) or "1")
310 order_line_id = _text(line.get("order_line_id"))
311 if order_line_id in ordered:
312 left = ordered[order_line_id] - already.get(order_line_id, Decimal(0))
313 quantity = min(quantity, max(left, Decimal(0)))
314 if quantity <= 0:
315 continue # handed over at the counter already
316 move = {
317 "id": object_ids.new_uuid4(),
318 "product_id": product_id,
319 "from_location_id": from_location,
320 "to_location_id": to_location,
321 "quantity": _number(quantity),
322 "reason": "sale",
323 "reference": f"{marker} {_text(order.get('number'))}".strip(),
324 "occurred_at": today,
325 "owner_id": _text(shipment.get("owner_id")),
326 "entity_id": _text(shipment.get("entity_id")),
327 }
328 try:
329 unit_cost = _sale_unit_cost(base, product_id)
330 except CostUnreadable:
331 unit_cost = ""
332 move["reference"] = f"{move['reference']} {UNCOSTED_MARKER}"
333 uncosted.append(move["id"])
334 if unit_cost:
335 move["unit_cost_cents"] = unit_cost
336 object_records.create_collection_record(
337 "stock_moves", move, base_dir=base, actor=ACTOR)
338 existing.append(marker)
339 if order_line_id:
340 already[order_line_id] = already.get(order_line_id, Decimal(0)) + quantity
341 moved += 1
342 if uncosted and not warning:
343 warning = (f"{len(uncosted)} sale move(s) could not be costed: the "
344 f"weighted average (or the product) could not be read, so "
345 f"they were "
346 f"written without a cost and no cost of goods was booked "
347 f"for them. Book it by hand at the real cost; the moves "
348 f"carry {UNCOSTED_MARKER} in their reference.")
349 return moved, warning, uncosted
350
351
352def _derive_order_status(base, order):
353 """What the shipment lines say this order's status is.
354
355 Returns "" when the facts say nothing yet (nothing shipped), so the
356 order is left exactly as a human last set it rather than being dragged
357 backwards by a machine that knows less than they do.
358 """
359 try:
360 order_lines = [line for line in object_records.read_collection_records(
361 "order_lines", base_dir=base)
362 if _text(line.get("order_id")) == order["id"]]
363 except Exception:
364 return ""
365 if not order_lines:
366 return ""
367
368 try:
369 shipments = [row for row in object_records.read_collection_records(
370 "shipments", base_dir=base)
371 if _text(row.get("order_id")) == order["id"]
372 and _text(row.get("direction")) != "inbound"]
373 except Exception:
374 return ""
375
376 counted = {row["id"]: _text(row.get("status")) for row in shipments
377 if _text(row.get("status")) not in NOT_DELIVERED_STATUSES}
378 # Every parcel that left was lost or came back: nothing has reached the
379 # customer, so an order that SAYS goods left goes back to the pick
380 # queue. "" (leave it alone) is only right when nothing ever shipped --
381 # returning it here used to leave the order at `shipped` with all of
382 # its goods still owed, in no queue at all.
383 regress = "processing" if _text(order.get("status")) in ("partial", "shipped") else ""
384 if not counted:
385 return regress
386
387 try:
388 all_lines = _ledger("shipment_lines", base) or []
389 except LedgerUnreadable:
390 # Lines that cannot be read are not "nothing shipped": deriving from
391 # them would send a shipped order back to the pick queue.
392 return ""
393 shipped_lines = [line for line in all_lines
394 if counted.get(_text(line.get("shipment_id")), "")
395 in SHIPPED_ONWARD]
396
397 shipped_by_line = {}
398 for line in shipped_lines:
399 key = _text(line.get("order_line_id"))
400 shipped_by_line[key] = shipped_by_line.get(key, Decimal(0)) + \
401 _quantity(line.get("quantity"))
402
403 total_shipped = sum(shipped_by_line.values(), Decimal(0))
404 if total_shipped <= 0:
405 return regress
406
407 everything = all(
408 shipped_by_line.get(line["id"], Decimal(0)) >= _quantity(line.get("quantity"))
409 for line in order_lines)
410 if not everything:
411 return "partial"
412
413 # Everything is on a shipment that has left. "delivered" is the further
414 # claim that every one of those shipments arrived -- never inferred from
415 # "it has been a while", which is how systems learn to lie about parcels.
416 if all(status == "delivered" for status in counted.values()):
417 return "delivered"
418 return "shipped"
419
420
421def EVENT(request):
422 base = _base_dir()
423 shipment = _shipment_for(request, base)
424 if not shipment:
425 return {"ok": True, "skipped": "no shipment in the event"}
426
427 if _text(shipment.get("direction")) == "inbound":
428 # A return has not decided whether it is restock or waste yet, and
429 # guessing would put damaged goods back on the shelf. The
430 # disposition flow is a later slice, deliberately absent.
431 return {"ok": True, "skipped": "inbound shipments are dispositioned "
432 "by hand, not by this handler",
433 "shipment_id": shipment["id"]}
434
435 try:
436 order = object_records.get_collection_record(
437 "orders", _text(shipment.get("order_id")), base_dir=base)
438 except Exception:
439 return {"ok": True, "skipped": "no order for this shipment",
440 "shipment_id": shipment["id"]}
441
442 order_status = _text(order.get("status"))
443 if order_status in UNTOUCHABLE_ORDER_STATUSES:
444 return {"ok": True, "skipped": f"order is {order_status}",
445 "shipment_id": shipment["id"], "order_id": order["id"]}
446
447 result = {"ok": True, "shipment_id": shipment["id"], "order_id": order["id"],
448 "moved": 0}
449
450 if _text(shipment.get("status")) in SHIPPED_ONWARD:
451 if not _text(shipment.get("shipped_on")):
452 # The handover date, stamped at the moment we observe the handover
453 # (docs/logic-decisions.md #1 -- a fact about a moment). Nothing
454 # stamped it before, which meant the field was blank on every
455 # shipment the shop's own automation raised, and a manifest keyed
456 # on it printed an empty page. Only when blank: an operator who
457 # typed a date knows something this handler does not, and a
458 # backdated shipment must keep the day it actually went. The write
459 # re-fires this handler once through the change dispatcher; the
460 # second pass finds the date set and the provenance markers
461 # already there, so it writes nothing and stops.
462 today = _text(request.get("today")) or date.today().isoformat()
463 try:
464 object_records.update_collection_record(
465 "shipments", shipment["id"], {"shipped_on": today},
466 base_dir=base, actor=ACTOR)
467 shipment["shipped_on"] = today
468 result["shipped_on"] = today
469 except Exception as exc:
470 # The parcel still went; a date we could not write is a gap
471 # to see, not a shipment to refuse.
472 result["shipped_on_error"] = str(exc)[:200]
473 try:
474 moves = _ledger("stock_moves", base)
475 moved, warning, uncosted = _move_stock(base, shipment, order, moves)
476 except LedgerUnreadable as exc:
477 # Installed but unreadable is not "stock not installed". The
478 # per-line markers cannot be checked, so a move written now could
479 # take the same goods off the shelf twice; none is written, and
480 # the result says so. The parcel still ships. The next event for
481 # this shipment (any edit to it, or a replay) moves the goods
482 # once the ledger reads again.
483 moved, uncosted = 0, []
484 result["stock_unreadable"] = str(exc)
485 warning = (f"The stock for this shipment did not move: {exc}. "
486 f"The shipment still stands; once the ledger can be "
487 f"read, re-save the shipment (or replay its event) "
488 f"and its lines will move exactly once.")
489 result["moved"] = moved
490 if uncosted:
491 result["uncosted_moves"] = uncosted
492 if warning:
493 # The parcel stands and the gap is visible, which is the right
494 # way round: a missing setting must not cost a customer their
495 # goods, and an invisible discrepancy is the one nobody fixes.
496 result["warning"] = warning
497
498 derived = _derive_order_status(base, order)
499 result["order_status"] = order_status
500 if derived and derived != order_status:
501 try:
502 object_records.update_collection_record(
503 "orders", order["id"], {"status": derived},
504 base_dir=base, actor=ACTOR)
505 result["order_status"] = derived
506 result["order_status_changed"] = True
507 except Exception as exc:
508 # A ladder that refuses the derived move is a real answer, not a
509 # crash: say so and leave the order where a human put it.
510 result["order_status_error"] = str(exc)[:200]
511 return result
512
513
514# EVENT is the verb the change dispatcher calls handlers with (see
515# object_change_dispatch); POST stays as an alias so an operator can poke
516# the handler by hand over HTTP. The alias is not decoration -- a handler
517# shipped with only POST silently matched nothing in production once, and
518# every handler in this house has carried both ever since.
519POST = EVENT