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
create_shipment.py · 16.0 KB · 365 lines
1"""action_create_shipment -- the box, before it is a box.
2
3POST {order_id, lines?: [{order_line_id, quantity}], carrier?, service?,
4 notes?, today?}
5
6Defaults to EVERYTHING still unshipped on the order, because that is what
7the overwhelming majority of shipments are: a small shop picks the whole
8order, packs it, and sends it. Passing `lines` is the partial case -- two
9of the three mugs are here and the third is on back-order -- and the
10remainder simply stays unshipped until a second shipment carries it. That
11is the entire mechanism behind "partial fulfillment": a second document,
12not a flag, and orders.status follows from counting rather than from
13somebody remembering to set it.
14
15Every blocker is reported TOGETHER, the way checkout does it. Revealing
16one problem, letting the packer fix it, then revealing the next is how a
17warehouse screen gets abandoned in favour of a spreadsheet.
18
19Nothing left to ship is deliberately NOT an error. A double-clicked
20"Ship it" button, or a handler that fires twice, must not produce a 500
21and must not produce a second empty shipment: it returns ok with a note
22saying the order is fully shipped already. Idempotency by observable
23state, which is the only kind that survives a retry (docs/logic-decisions.md #7).
24That state is read only under a claim on the order (orders.action_claim,
25object_claims): read without one, four overlapping clicks all saw the
26order unshipped and raised four shipments. A click that finds the order
27claimed is answered 409 in_progress with nothing written.
28
29The over-shipping arithmetic here is a deliberate second copy of
30hook_shipment_lines' gate, named in both files: trusted server-side
31writes bypass hooks by design, so the action that writes the lines has to
32carry the check, and the hook has to keep it for the generic HTTP write
33path. What the action adds is the friendly all-at-once report; what the
34hook adds is that no other door is open.
35"""
36
37import os
38from datetime import date
39from decimal import Decimal, InvalidOperation
40
41import object_access
42import object_claims
43import object_ids
44import object_records
45import object_stock
46
47ACTOR = "action_create_shipment"
48
49# Statuses whose lines never reached the customer: the order still owes
50# those goods, so they do not consume the ordered quantity.
51NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"}
52
53SERVICES = ("ground", "express", "freight", "pickup", "digital", "other")
54
55
56def _base_dir():
57 return os.environ.get("DBBASIC_DATA_DIR", "data")
58
59
60def _text(value):
61 return str(value if value is not None else "").strip()
62
63
64def _quantity(value):
65 try:
66 return Decimal(_text(value) or "0")
67 except InvalidOperation:
68 return None
69
70
71def _number(value):
72 return format(value.normalize(), "f")
73
74
75def _truthy(value):
76 return _text(value).strip().lower() in ("true", "1", "yes", "on")
77
78
79class HistoryUnreadable(Exception):
80 """What already shipped cannot be read, so what is still owed is
81 unknown."""
82
83
84def _remaining_by_line(base, order_id, order_lines):
85 """How much of each order line is still owed: ordered minus everything
86 already sitting on a shipment that has not been lost or bounced back.
87
88 Raises HistoryUnreadable when either collection cannot be read. An
89 unreadable history is not an empty one: read as empty it says nothing
90 has shipped, and the whole order goes into a second box
91 (bug-reports/2026-11-28-06-14-56). hook_shipment_lines, whose gate this
92 mirrors, refuses with 503 in the same situation, and so does this.
93 """
94 try:
95 # access: history of, and shipment for, the order read through Access above
96 shipments = object_records.read_collection_records("shipments",
97 base_dir=base)
98 # access: history of, and shipment for, the order read through Access above
99 lines = object_records.read_collection_records("shipment_lines",
100 base_dir=base)
101 except Exception as exc:
102 raise HistoryUnreadable(str(exc)[:160]) from exc
103 counted = {row["id"] for row in shipments
104 if _text(row.get("status")) not in NOT_DELIVERED_STATUSES}
105
106 shipped = {}
107 for line in lines:
108 if _text(line.get("shipment_id")) not in counted:
109 continue
110 key = _text(line.get("order_line_id"))
111 shipped[key] = shipped.get(key, Decimal(0)) + (
112 _quantity(line.get("quantity")) or Decimal(0))
113
114 # A BACKORDERED line is one the shop openly agreed it did not have. It
115 # is owed, not packable: putting it in a parcel would send the customer
116 # a short box AND drive the stock ledger negative on goods nobody could
117 # pick, breaking both halves of the promise `backorder_policy: allow`
118 # makes. So its shippable remainder is capped at what is actually on
119 # the shelf -- the rest simply stays owed until stock arrives and a
120 # second shipment carries it, which is the ordinary partial-fulfilment
121 # path this action already supports.
122 on_hand = _available_by_product(base, order_lines)
123
124 remaining = {}
125 for line in order_lines:
126 ordered = _quantity(line.get("quantity")) or Decimal(0)
127 owed = ordered - shipped.get(line["id"], Decimal(0))
128 if _truthy(line.get("backordered")):
129 product_id = _text(line.get("product_id"))
130 available = on_hand.get(product_id, Decimal(0))
131 owed = min(owed, available if available > 0 else Decimal(0))
132 on_hand[product_id] = available - owed
133 remaining[line["id"]] = owed
134 return remaining
135
136
137def _available_by_product(base, order_lines):
138 """On-hand quantity for the products this order touches.
139
140 Read once for the whole order rather than per line, and only consulted
141 for backordered lines -- an ordinary line's shippable quantity is what
142 was ordered, exactly as before, because deciding availability at
143 pack time for every line would quietly turn this action into a second
144 stock gate competing with the one at checkout.
145 """
146 available = {}
147 for line in order_lines:
148 product_id = _text(line.get("product_id"))
149 if not product_id or product_id in available:
150 continue
151 try:
152 available[product_id] = object_stock.total_quantity(
153 product_id, base_dir=base)
154 except Exception:
155 available[product_id] = Decimal(0)
156 return available
157
158
159def POST(request):
160 base = _base_dir()
161 order_id = _text(request.get("order_id"))
162 if not order_id:
163 return {"status": 400, "error": "order_id is required"}
164
165 # Only someone the orders API would let UPDATE this order may pack it.
166 # Every write below is a trusted server-side write, so this object is
167 # the only gate; it used to let any signed-in user raise a shipment of
168 # anybody's order (and, once it reached shipped, move their stock).
169 # Asked first, so the 409s below are only shown to somebody allowed to
170 # see the order; refused reads exactly like missing. "Packing is
171 # warehouse work, not owner-only work" (the execute rule's reason)
172 # still holds: a packer is somebody the policy lets update the
173 # shop's orders, which is a grant in the policy, not an absence of one.
174 access = object_access.Access(request.get("_identity"), base_dir=base)
175 try:
176 order = access.get("orders", order_id, action="update")
177 except Exception:
178 order = None
179 if order is None:
180 return {"status": 404, "error": f"No such order: {order_id}"}
181
182 # THE CLAIM, before anything about the order's history is read. "Nothing
183 # left to ship" was the only guard against a double click, and it is
184 # read before anything is written: four clicks that all read the order
185 # as unshipped raised four boxes of the same three mugs (and, once any
186 # reached `shipped`, moved the stock four times). Only the request
187 # holding orders.action_claim reads and writes; any other is answered
188 # 409 in_progress with nothing written.
189 try:
190 claim, order = object_claims.take("orders", order_id, base_dir=base,
191 actor=ACTOR)
192 except object_claims.Busy:
193 return object_claims.busy_answer("order", order_id)
194 except object_records.RecordNotFoundError:
195 return {"status": 404, "error": f"No such order: {order_id}"}
196 except Exception as exc:
197 return {"status": 503,
198 "error": (f"This order cannot be claimed right now "
199 f"({str(exc)[:120]}), so nothing was shipped. Try "
200 f"again in a moment.")}
201 try:
202 return _compose(base, request, access, order, order_id)
203 finally:
204 object_claims.release("orders", order_id, claim, base_dir=base,
205 actor=ACTOR)
206
207
208def _compose(base, request, access, order, order_id):
209 """Everything after the claim: read what is owed, decide, write."""
210 order_status = _text(order.get("status"))
211 if order_status in ("draft", "cancelled"):
212 return {"status": 409,
213 "error": (f"This order is {order_status}. Commit before you "
214 f"pack -- shipping against a draft would send goods "
215 f"for a sale nobody has agreed to, and against a "
216 f"cancelled one would send them to somebody who "
217 f"asked us not to.")}
218
219 try:
220 # access: history of, and shipment for, the order read through Access above
221 all_lines = object_records.read_collection_records("order_lines",
222 base_dir=base)
223 except Exception:
224 all_lines = []
225 order_lines = [line for line in all_lines
226 if _text(line.get("order_id")) == order_id]
227 if not order_lines:
228 return {"status": 409,
229 "error": "This order has no lines, so there is nothing to put "
230 "in a box."}
231
232 by_id = {line["id"]: line for line in order_lines}
233 try:
234 remaining = _remaining_by_line(base, order_id, order_lines)
235 except HistoryUnreadable as exc:
236 return {"status": 503,
237 "error": (f"What has already shipped on this order cannot be "
238 f"read right now ({exc}), so how much is still owed "
239 f"is unknown and nothing was shipped. Try again in a "
240 f"moment.")}
241
242 requested = request.get("lines")
243 blockers = {"unknown_lines": [], "over_ship": [], "bad_quantities": []}
244
245 if isinstance(requested, list) and requested:
246 wanted = []
247 for entry in requested:
248 if not isinstance(entry, dict):
249 blockers["bad_quantities"].append(
250 {"order_line_id": "", "reason": "line is not an object"})
251 continue
252 line_id = _text(entry.get("order_line_id"))
253 if line_id not in by_id:
254 blockers["unknown_lines"].append(line_id)
255 continue
256 quantity = _quantity(entry.get("quantity"))
257 if quantity is None or quantity <= 0:
258 blockers["bad_quantities"].append(
259 {"order_line_id": line_id,
260 "quantity": _text(entry.get("quantity")),
261 "reason": "a shipment line must ship a positive quantity"})
262 continue
263 left = remaining.get(line_id, Decimal(0))
264 if quantity > left:
265 ordered = _quantity(by_id[line_id].get("quantity")) or Decimal(0)
266 blockers["over_ship"].append({
267 "order_line_id": line_id,
268 "description": _text(by_id[line_id].get("description")),
269 "ordered": _number(ordered),
270 "already_on_shipments": _number(ordered - left),
271 "asked_for": _number(quantity),
272 "would_make": _number(ordered - left + quantity),
273 })
274 continue
275 wanted.append((by_id[line_id], quantity))
276 else:
277 # The default and the common case: everything still owed.
278 wanted = [(by_id[line_id], left)
279 for line_id, left in remaining.items() if left > 0]
280 wanted.sort(key=lambda pair: _text(pair[0].get("description")))
281
282 if any(blockers.values()):
283 return {"status": 409,
284 "error": "Some of those lines cannot be shipped.",
285 **blockers}
286
287 if not wanted:
288 # Not an error. A second click, or a handler that fired twice, must
289 # not 500 and must not raise an empty second shipment.
290 return {"ok": True, "order_id": order_id, "shipment_id": "",
291 "lines": 0,
292 "note": "nothing left to ship on this order; every ordered "
293 "quantity is already on a shipment"}
294
295 owner = _text(order.get("owner_id")) or access.user_id
296 service = _text(request.get("service")) or "ground"
297 if service not in SERVICES:
298 return {"status": 400,
299 "error": f"Unknown service {service!r}; "
300 f"expected one of {', '.join(SERVICES)}."}
301
302 shipment_id = object_ids.new_uuid4()
303 today = _text(request.get("today")) or date.today().isoformat()
304 notes = _text(request.get("notes"))
305 provenance = f"Generated by {ACTOR} [orders/{order_id}]"
306
307 # access: history of, and shipment for, the order read through Access above
308 object_records.create_collection_record(
309 "shipments",
310 {
311 "id": shipment_id,
312 "order_id": order_id,
313 "direction": "outbound",
314 "status": "open",
315 "carrier": _text(request.get("carrier")),
316 "service": service,
317 # Stamped, never re-read: an address is what it was when the box
318 # left. .get() throughout because the storefront does not collect
319 # a shipping address yet -- a shipment that says nothing is
320 # honest, one that invents a plausible address is not.
321 "ship_to_name": (_text(order.get("customer_name"))
322 or _text(order.get("customer_email"))),
323 "ship_to_address": (_text(order.get("ship_to_address"))
324 or _text(order.get("shipping_address"))
325 or _text(order.get("customer_address"))),
326 "notes": f"{notes}\n{provenance}".strip() if notes else provenance,
327 "owner_id": owner,
328 "entity_id": _text(order.get("entity_id")),
329 },
330 base_dir=base, actor=ACTOR)
331
332 created = []
333 for order_line, quantity in wanted:
334 line_id = object_ids.new_uuid4()
335 # access: history of, and shipment for, the order read through Access above
336 object_records.create_collection_record(
337 "shipment_lines",
338 {
339 "id": line_id,
340 "shipment_id": shipment_id,
341 "order_line_id": order_line["id"],
342 "product_id": _text(order_line.get("product_id")),
343 # Stamped from the order line: a slip printed next year must
344 # still say what the packer actually put in the box.
345 "description": _text(order_line.get("description")),
346 "quantity": _number(quantity),
347 "owner_id": owner,
348 },
349 base_dir=base, actor=ACTOR)
350 created.append({"id": line_id, "order_line_id": order_line["id"],
351 "description": _text(order_line.get("description")),
352 "quantity": _number(quantity)})
353
354 still_owed = sum(
355 (left for line_id, left in remaining.items() if left > 0),
356 Decimal(0)) - sum((q for _, q in wanted), Decimal(0))
357
358 return {"ok": True, "order_id": order_id, "shipment_id": shipment_id,
359 "status_of_shipment": "open", "lines": len(created),
360 "shipment_lines": created,
361 "still_unshipped": _number(still_owed),
362 "slip_path": f"/shipments/{shipment_id}/slip",
363 "date": today,
364 "note": "shipment raised open; stock moves when it reaches "
365 "shipped, one move per line"}