askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
create_shipment.py · 12.4 KB · 301 lines
| 1 | """action_create_shipment -- the box, before it is a box. |
| 2 | |
| 3 | POST {order_id, lines?: [{order_line_id, quantity}], carrier?, service?, |
| 4 | notes?, today?} |
| 5 | |
| 6 | Defaults to EVERYTHING still unshipped on the order, because that is what |
| 7 | the overwhelming majority of shipments are: a small shop picks the whole |
| 8 | order, packs it, and sends it. Passing `lines` is the partial case -- two |
| 9 | of the three mugs are here and the third is on back-order -- and the |
| 10 | remainder simply stays unshipped until a second shipment carries it. That |
| 11 | is the entire mechanism behind "partial fulfillment": a second document, |
| 12 | not a flag, and orders.status follows from counting rather than from |
| 13 | somebody remembering to set it. |
| 14 | |
| 15 | Every blocker is reported TOGETHER, the way checkout does it. Revealing |
| 16 | one problem, letting the packer fix it, then revealing the next is how a |
| 17 | warehouse screen gets abandoned in favour of a spreadsheet. |
| 18 | |
| 19 | Nothing 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 |
| 21 | and must not produce a second empty shipment: it returns ok with a note |
| 22 | saying the order is fully shipped already. Idempotency by observable |
| 23 | state, which is the only kind that survives a retry (docs/logic-decisions.md #7). |
| 24 | |
| 25 | The over-shipping arithmetic here is a deliberate second copy of |
| 26 | hook_shipment_lines' gate, named in both files: trusted server-side |
| 27 | writes bypass hooks by design, so the action that writes the lines has to |
| 28 | carry the check, and the hook has to keep it for the generic HTTP write |
| 29 | path. What the action adds is the friendly all-at-once report; what the |
| 30 | hook adds is that no other door is open. |
| 31 | """ |
| 32 | |
| 33 | import os |
| 34 | from datetime import date |
| 35 | from decimal import Decimal, InvalidOperation |
| 36 | |
| 37 | import object_ids |
| 38 | import object_records |
| 39 | import object_stock |
| 40 | |
| 41 | ACTOR = "action_create_shipment" |
| 42 | |
| 43 | # Statuses whose lines never reached the customer: the order still owes |
| 44 | # those goods, so they do not consume the ordered quantity. |
| 45 | NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"} |
| 46 | |
| 47 | SERVICES = ("ground", "express", "freight", "pickup", "digital", "other") |
| 48 | |
| 49 | |
| 50 | def _base_dir(): |
| 51 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 52 | |
| 53 | |
| 54 | def _text(value): |
| 55 | return str(value if value is not None else "").strip() |
| 56 | |
| 57 | |
| 58 | def _quantity(value): |
| 59 | try: |
| 60 | return Decimal(_text(value) or "0") |
| 61 | except InvalidOperation: |
| 62 | return None |
| 63 | |
| 64 | |
| 65 | def _number(value): |
| 66 | return format(value.normalize(), "f") |
| 67 | |
| 68 | |
| 69 | def _truthy(value): |
| 70 | return _text(value).strip().lower() in ("true", "1", "yes", "on") |
| 71 | |
| 72 | |
| 73 | def _remaining_by_line(base, order_id, order_lines): |
| 74 | """How much of each order line is still owed: ordered minus everything |
| 75 | already sitting on a shipment that has not been lost or bounced back. |
| 76 | """ |
| 77 | try: |
| 78 | shipments = object_records.read_collection_records("shipments", |
| 79 | base_dir=base) |
| 80 | except Exception: |
| 81 | shipments = [] |
| 82 | counted = {row["id"] for row in shipments |
| 83 | if _text(row.get("status")) not in NOT_DELIVERED_STATUSES} |
| 84 | try: |
| 85 | lines = object_records.read_collection_records("shipment_lines", |
| 86 | base_dir=base) |
| 87 | except Exception: |
| 88 | lines = [] |
| 89 | |
| 90 | shipped = {} |
| 91 | for line in lines: |
| 92 | if _text(line.get("shipment_id")) not in counted: |
| 93 | continue |
| 94 | key = _text(line.get("order_line_id")) |
| 95 | shipped[key] = shipped.get(key, Decimal(0)) + ( |
| 96 | _quantity(line.get("quantity")) or Decimal(0)) |
| 97 | |
| 98 | # A BACKORDERED line is one the shop openly agreed it did not have. It |
| 99 | # is owed, not packable: putting it in a parcel would send the customer |
| 100 | # a short box AND drive the stock ledger negative on goods nobody could |
| 101 | # pick, breaking both halves of the promise `backorder_policy: allow` |
| 102 | # makes. So its shippable remainder is capped at what is actually on |
| 103 | # the shelf -- the rest simply stays owed until stock arrives and a |
| 104 | # second shipment carries it, which is the ordinary partial-fulfilment |
| 105 | # path this action already supports. |
| 106 | on_hand = _available_by_product(base, order_lines) |
| 107 | |
| 108 | remaining = {} |
| 109 | for line in order_lines: |
| 110 | ordered = _quantity(line.get("quantity")) or Decimal(0) |
| 111 | owed = ordered - shipped.get(line["id"], Decimal(0)) |
| 112 | if _truthy(line.get("backordered")): |
| 113 | product_id = _text(line.get("product_id")) |
| 114 | available = on_hand.get(product_id, Decimal(0)) |
| 115 | owed = min(owed, available if available > 0 else Decimal(0)) |
| 116 | on_hand[product_id] = available - owed |
| 117 | remaining[line["id"]] = owed |
| 118 | return remaining |
| 119 | |
| 120 | |
| 121 | def _available_by_product(base, order_lines): |
| 122 | """On-hand quantity for the products this order touches. |
| 123 | |
| 124 | Read once for the whole order rather than per line, and only consulted |
| 125 | for backordered lines -- an ordinary line's shippable quantity is what |
| 126 | was ordered, exactly as before, because deciding availability at |
| 127 | pack time for every line would quietly turn this action into a second |
| 128 | stock gate competing with the one at checkout. |
| 129 | """ |
| 130 | available = {} |
| 131 | for line in order_lines: |
| 132 | product_id = _text(line.get("product_id")) |
| 133 | if not product_id or product_id in available: |
| 134 | continue |
| 135 | try: |
| 136 | available[product_id] = object_stock.total_quantity( |
| 137 | product_id, base_dir=base) |
| 138 | except Exception: |
| 139 | available[product_id] = Decimal(0) |
| 140 | return available |
| 141 | |
| 142 | |
| 143 | def POST(request): |
| 144 | base = _base_dir() |
| 145 | order_id = _text(request.get("order_id")) |
| 146 | if not order_id: |
| 147 | return {"status": 400, "error": "order_id is required"} |
| 148 | |
| 149 | try: |
| 150 | order = object_records.get_collection_record("orders", order_id, |
| 151 | base_dir=base) |
| 152 | except Exception: |
| 153 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 154 | |
| 155 | order_status = _text(order.get("status")) |
| 156 | if order_status in ("draft", "cancelled"): |
| 157 | return {"status": 409, |
| 158 | "error": (f"This order is {order_status}. Commit before you " |
| 159 | f"pack -- shipping against a draft would send goods " |
| 160 | f"for a sale nobody has agreed to, and against a " |
| 161 | f"cancelled one would send them to somebody who " |
| 162 | f"asked us not to.")} |
| 163 | |
| 164 | try: |
| 165 | all_lines = object_records.read_collection_records("order_lines", |
| 166 | base_dir=base) |
| 167 | except Exception: |
| 168 | all_lines = [] |
| 169 | order_lines = [line for line in all_lines |
| 170 | if _text(line.get("order_id")) == order_id] |
| 171 | if not order_lines: |
| 172 | return {"status": 409, |
| 173 | "error": "This order has no lines, so there is nothing to put " |
| 174 | "in a box."} |
| 175 | |
| 176 | by_id = {line["id"]: line for line in order_lines} |
| 177 | remaining = _remaining_by_line(base, order_id, order_lines) |
| 178 | |
| 179 | requested = request.get("lines") |
| 180 | blockers = {"unknown_lines": [], "over_ship": [], "bad_quantities": []} |
| 181 | |
| 182 | if isinstance(requested, list) and requested: |
| 183 | wanted = [] |
| 184 | for entry in requested: |
| 185 | if not isinstance(entry, dict): |
| 186 | blockers["bad_quantities"].append( |
| 187 | {"order_line_id": "", "reason": "line is not an object"}) |
| 188 | continue |
| 189 | line_id = _text(entry.get("order_line_id")) |
| 190 | if line_id not in by_id: |
| 191 | blockers["unknown_lines"].append(line_id) |
| 192 | continue |
| 193 | quantity = _quantity(entry.get("quantity")) |
| 194 | if quantity is None or quantity <= 0: |
| 195 | blockers["bad_quantities"].append( |
| 196 | {"order_line_id": line_id, |
| 197 | "quantity": _text(entry.get("quantity")), |
| 198 | "reason": "a shipment line must ship a positive quantity"}) |
| 199 | continue |
| 200 | left = remaining.get(line_id, Decimal(0)) |
| 201 | if quantity > left: |
| 202 | ordered = _quantity(by_id[line_id].get("quantity")) or Decimal(0) |
| 203 | blockers["over_ship"].append({ |
| 204 | "order_line_id": line_id, |
| 205 | "description": _text(by_id[line_id].get("description")), |
| 206 | "ordered": _number(ordered), |
| 207 | "already_on_shipments": _number(ordered - left), |
| 208 | "asked_for": _number(quantity), |
| 209 | "would_make": _number(ordered - left + quantity), |
| 210 | }) |
| 211 | continue |
| 212 | wanted.append((by_id[line_id], quantity)) |
| 213 | else: |
| 214 | # The default and the common case: everything still owed. |
| 215 | wanted = [(by_id[line_id], left) |
| 216 | for line_id, left in remaining.items() if left > 0] |
| 217 | wanted.sort(key=lambda pair: _text(pair[0].get("description"))) |
| 218 | |
| 219 | if any(blockers.values()): |
| 220 | return {"status": 409, |
| 221 | "error": "Some of those lines cannot be shipped.", |
| 222 | **blockers} |
| 223 | |
| 224 | if not wanted: |
| 225 | # Not an error. A second click, or a handler that fired twice, must |
| 226 | # not 500 and must not raise an empty second shipment. |
| 227 | return {"ok": True, "order_id": order_id, "shipment_id": "", |
| 228 | "lines": 0, |
| 229 | "note": "nothing left to ship on this order; every ordered " |
| 230 | "quantity is already on a shipment"} |
| 231 | |
| 232 | owner = (_text(order.get("owner_id")) |
| 233 | or _text((request.get("_identity") or {}).get("user_id"))) |
| 234 | service = _text(request.get("service")) or "ground" |
| 235 | if service not in SERVICES: |
| 236 | return {"status": 400, |
| 237 | "error": f"Unknown service {service!r}; " |
| 238 | f"expected one of {', '.join(SERVICES)}."} |
| 239 | |
| 240 | shipment_id = object_ids.new_uuid4() |
| 241 | today = _text(request.get("today")) or date.today().isoformat() |
| 242 | notes = _text(request.get("notes")) |
| 243 | provenance = f"Generated by {ACTOR} [orders/{order_id}]" |
| 244 | |
| 245 | object_records.create_collection_record( |
| 246 | "shipments", |
| 247 | { |
| 248 | "id": shipment_id, |
| 249 | "order_id": order_id, |
| 250 | "direction": "outbound", |
| 251 | "status": "open", |
| 252 | "carrier": _text(request.get("carrier")), |
| 253 | "service": service, |
| 254 | # Stamped, never re-read: an address is what it was when the box |
| 255 | # left. .get() throughout because the storefront does not collect |
| 256 | # a shipping address yet -- a shipment that says nothing is |
| 257 | # honest, one that invents a plausible address is not. |
| 258 | "ship_to_name": (_text(order.get("customer_name")) |
| 259 | or _text(order.get("customer_email"))), |
| 260 | "ship_to_address": (_text(order.get("ship_to_address")) |
| 261 | or _text(order.get("shipping_address")) |
| 262 | or _text(order.get("customer_address"))), |
| 263 | "notes": f"{notes}\n{provenance}".strip() if notes else provenance, |
| 264 | "owner_id": owner, |
| 265 | "entity_id": _text(order.get("entity_id")), |
| 266 | }, |
| 267 | base_dir=base, actor=ACTOR) |
| 268 | |
| 269 | created = [] |
| 270 | for order_line, quantity in wanted: |
| 271 | line_id = object_ids.new_uuid4() |
| 272 | object_records.create_collection_record( |
| 273 | "shipment_lines", |
| 274 | { |
| 275 | "id": line_id, |
| 276 | "shipment_id": shipment_id, |
| 277 | "order_line_id": order_line["id"], |
| 278 | "product_id": _text(order_line.get("product_id")), |
| 279 | # Stamped from the order line: a slip printed next year must |
| 280 | # still say what the packer actually put in the box. |
| 281 | "description": _text(order_line.get("description")), |
| 282 | "quantity": _number(quantity), |
| 283 | "owner_id": owner, |
| 284 | }, |
| 285 | base_dir=base, actor=ACTOR) |
| 286 | created.append({"id": line_id, "order_line_id": order_line["id"], |
| 287 | "description": _text(order_line.get("description")), |
| 288 | "quantity": _number(quantity)}) |
| 289 | |
| 290 | still_owed = sum( |
| 291 | (left for line_id, left in remaining.items() if left > 0), |
| 292 | Decimal(0)) - sum((q for _, q in wanted), Decimal(0)) |
| 293 | |
| 294 | return {"ok": True, "order_id": order_id, "shipment_id": shipment_id, |
| 295 | "status_of_shipment": "open", "lines": len(created), |
| 296 | "shipment_lines": created, |
| 297 | "still_unshipped": _number(still_owed), |
| 298 | "slip_path": f"/shipments/{shipment_id}/slip", |
| 299 | "date": today, |
| 300 | "note": "shipment raised open; stock moves when it reaches " |
| 301 | "shipped, one move per line"} |