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
dropship_order.py · 16.3 KB · 378 lines
| 1 | """action_dropship_order -- the vendor ships straight to my customer. |
| 2 | |
| 3 | POST {order_id, vendor_id, vendor_name?, vendor_price_cents?, |
| 4 | prices?: {order_line_id: unit_price_cents}, number?, today?} |
| 5 | |
| 6 | This is the composition test plan/fulfillment-logistics-spec.md set for |
| 7 | the whole fulfillment build, in its own words: "a sale order flagged |
| 8 | `fulfillment: dropship` produces a linked PURCHASE order to the vendor |
| 9 | carrying the customer's ship-to; receiving is skipped (goods never touch |
| 10 | our shelf); margin is already a read because both orders carry money. If |
| 11 | the shipment model can't express this cleanly, the model is wrong." |
| 12 | |
| 13 | It passes, and the reason it passes is a decision made in v1 of this |
| 14 | schema for entirely different reasons: sale and purchase orders share one |
| 15 | collection. A drop-ship is not a new noun and gets no new table -- it is |
| 16 | two rows of a document type that already exists, pointing at each other. |
| 17 | The customer's order says what is owed and to whom; the vendor's order |
| 18 | says what we are buying and where to send it; both carry money, so margin |
| 19 | is subtraction rather than a project. |
| 20 | |
| 21 | **The stock rule is the whole test.** A drop-ship order must never move |
| 22 | our stock, and its purchase order must never produce a receipt. Two |
| 23 | halves, and they are honest about being different: |
| 24 | |
| 25 | - Receiving is skipped BY CONSTRUCTION. Nothing on this server creates a |
| 26 | receipt on its own -- system_receipt_posting only ever reacts to a |
| 27 | `receipts` row a human raised through action_receive_goods -- so a |
| 28 | drop-ship PO that nobody checks in never touches a shelf. What is |
| 29 | missing is a REFUSAL: nothing yet stops somebody receiving against a |
| 30 | drop-ship PO by mistake, and that gate belongs in app-receiving. |
| 31 | - The sale side is NOT yet safe, and this docstring says so rather than |
| 32 | hiding it. system_order_fulfillment (app-shipping) composes a `sale` |
| 33 | move for every shipment line the moment a shipment reaches `shipped`, |
| 34 | and it does not look at fulfillment_source. The order carries the fact |
| 35 | -- the handler already re-reads the order, so no new plumbing is needed, |
| 36 | only one condition -- but until that condition exists, recording the |
| 37 | vendor's dispatch as a shipment against the sale order would decrement |
| 38 | a shelf that never held the goods. tests/test_dropship.py holds that as |
| 39 | a strict xfail so the day somebody fixes it, the acceptance test is |
| 40 | already written. |
| 41 | |
| 42 | So this action does the one thing it can do honestly: it writes the fact |
| 43 | both handlers need onto both orders, and it does not go anywhere near |
| 44 | app-shipping's or app-receiving's code to work around them. |
| 45 | |
| 46 | **Every blocker is reported together**, checkout-style. Whoever is doing |
| 47 | this is usually deciding between two vendors with a customer waiting, and |
| 48 | revealing one problem at a time is how a screen gets abandoned. |
| 49 | |
| 50 | **You cannot drop-ship what you already picked.** If any stock move |
| 51 | already exists against this order's shipments, the goods left our shelf |
| 52 | and the sale is ours to fulfill; raising a PO now would buy a second set |
| 53 | of the same units. The refusal names the moves, because "no" alone leaves |
| 54 | somebody guessing whether they picked the wrong order or the wrong day. |
| 55 | |
| 56 | **Exactly one PO per sale order.** A second call finds linked_order_id |
| 57 | already set and refuses with the number of the PO that exists, rather |
| 58 | than quietly raising a duplicate commitment to buy -- the same class of |
| 59 | mistake as a double refund, with a supplier on the other end of it. |
| 60 | |
| 61 | **The vendor's price is asked for, never invented.** Explicit per-line |
| 62 | prices win, then a flat vendor_price_cents per unit, then the product's |
| 63 | recorded cost_cents. When none of those exist the PO is raised at zero |
| 64 | with a WARNING naming the lines, because a cost of zero reads as 100% |
| 65 | margin and a cost copied from the sale price reads as none -- both are |
| 66 | lies, and the honest move is to say the number is missing. |
| 67 | """ |
| 68 | |
| 69 | import os |
| 70 | from datetime import date |
| 71 | from decimal import Decimal, InvalidOperation |
| 72 | |
| 73 | import object_ids |
| 74 | import object_records |
| 75 | |
| 76 | ACTOR = "action_dropship_order" |
| 77 | |
| 78 | DROPSHIP = "dropship" |
| 79 | |
| 80 | # A draft is not a commitment and a cancelled order must not come back to |
| 81 | # life because somebody raised a PO against it. Everything else -- an |
| 82 | # order confirmed, in processing, even partially shipped from stock for |
| 83 | # its OTHER lines -- can still have a vendor take the rest. |
| 84 | UNTOUCHABLE_ORDER_STATUSES = {"draft", "cancelled"} |
| 85 | |
| 86 | |
| 87 | def _base_dir(): |
| 88 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 89 | |
| 90 | |
| 91 | def _text(value): |
| 92 | return str(value if value is not None else "").strip() |
| 93 | |
| 94 | |
| 95 | def _cents(value): |
| 96 | """None means NOT SAID, which is a different fact from zero. |
| 97 | |
| 98 | The whole vendor-price ladder below turns on that difference: a price |
| 99 | somebody typed as 0 is a decision, and a price nobody typed is a gap |
| 100 | to report. Collapsing the two into 0 is how the fallback chain would |
| 101 | silently stop at its first rung. |
| 102 | """ |
| 103 | text = _text(value) |
| 104 | if not text: |
| 105 | return None |
| 106 | try: |
| 107 | return int(text) |
| 108 | except ValueError: |
| 109 | return None |
| 110 | |
| 111 | |
| 112 | def _quantity(value): |
| 113 | """Decimal, never a bare float -- quantities may be fractional.""" |
| 114 | try: |
| 115 | return Decimal(_text(value) or "0") |
| 116 | except InvalidOperation: |
| 117 | return Decimal(0) |
| 118 | |
| 119 | |
| 120 | def _number(value): |
| 121 | return format(value.normalize(), "f") |
| 122 | |
| 123 | |
| 124 | def _rows(collection, base): |
| 125 | try: |
| 126 | return object_records.read_collection_records(collection, base_dir=base) |
| 127 | except Exception: |
| 128 | return None |
| 129 | |
| 130 | |
| 131 | def _vendor_name(base, vendor_id, given): |
| 132 | """A printable name for the vendor, asked of the places one might be |
| 133 | filed and never invented. |
| 134 | |
| 135 | vendor_id is plain text precisely because a vendor may be a contact, |
| 136 | an organization, or neither; so this looks in both and falls back to |
| 137 | the id itself, which at least identifies the counterparty rather than |
| 138 | leaving a required field blank. |
| 139 | """ |
| 140 | if given: |
| 141 | return given |
| 142 | for row in _rows("contacts", base) or []: |
| 143 | if _text(row.get("id")) != vendor_id: |
| 144 | continue |
| 145 | full = _text(row.get("full_name")) |
| 146 | if full: |
| 147 | return full |
| 148 | parts = [_text(row.get("first_name")), _text(row.get("last_name"))] |
| 149 | joined = " ".join(part for part in parts if part) |
| 150 | if joined: |
| 151 | return joined |
| 152 | for row in _rows("organizations", base) or []: |
| 153 | if _text(row.get("id")) == vendor_id and _text(row.get("name")): |
| 154 | return _text(row["name"]) |
| 155 | return vendor_id |
| 156 | |
| 157 | |
| 158 | def _moves_against(base, order_id): |
| 159 | """Stock moves already composed for this order's shipments. |
| 160 | |
| 161 | The marker system_order_fulfillment stamps is |
| 162 | `shipments/{shipment_id}:line/{line_id}`, so the honest question is |
| 163 | asked of the moves themselves rather than of a status somebody could |
| 164 | have typed: goods that left the shelf are the fact, and the order's |
| 165 | status is only ever a read of it. |
| 166 | """ |
| 167 | shipments = _rows("shipments", base) |
| 168 | moves = _rows("stock_moves", base) |
| 169 | if not shipments or moves is None: |
| 170 | return [], [] |
| 171 | ours = [_text(row.get("id")) for row in shipments |
| 172 | if _text(row.get("order_id")) == order_id] |
| 173 | if not ours: |
| 174 | return [], [] |
| 175 | hits = [row for row in moves |
| 176 | if any(f"shipments/{shipment_id}:" in _text(row.get("reference")) |
| 177 | for shipment_id in ours)] |
| 178 | return ours, hits |
| 179 | |
| 180 | |
| 181 | def POST(request): |
| 182 | base = _base_dir() |
| 183 | order_id = _text(request.get("order_id")) |
| 184 | if not order_id: |
| 185 | return {"status": 400, "error": "order_id is required"} |
| 186 | |
| 187 | try: |
| 188 | order = object_records.get_collection_record("orders", order_id, |
| 189 | base_dir=base) |
| 190 | except Exception: |
| 191 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 192 | |
| 193 | blockers = {"wrong_document": "", "order_status": "", "already_linked": "", |
| 194 | "stock_moved": [], "missing_vendor": "", "no_lines": ""} |
| 195 | |
| 196 | if _text(order.get("doc_type")) != "sale": |
| 197 | blockers["wrong_document"] = ( |
| 198 | "That is a purchase order. Drop-shipping is something you do to " |
| 199 | "a SALE order -- it spawns the purchase order, and a purchase " |
| 200 | "order spawning another one is a supply chain nobody asked for.") |
| 201 | |
| 202 | status = _text(order.get("status")) |
| 203 | if status in UNTOUCHABLE_ORDER_STATUSES: |
| 204 | blockers["order_status"] = ( |
| 205 | f"This order is {status}. A draft is not a commitment and a " |
| 206 | f"cancelled order must not come back to life because somebody " |
| 207 | f"raised a purchase order against it -- confirm it first, or " |
| 208 | f"leave it alone.") |
| 209 | |
| 210 | already = _text(order.get("linked_order_id")) |
| 211 | if already: |
| 212 | number = "" |
| 213 | try: |
| 214 | number = _text(object_records.get_collection_record( |
| 215 | "orders", already, base_dir=base).get("number")) |
| 216 | except Exception: |
| 217 | number = already |
| 218 | blockers["already_linked"] = ( |
| 219 | f"This order is already drop-shipped on purchase order {number} " |
| 220 | f"({already}). One sale order spawns exactly one PO; raising a " |
| 221 | f"second would commit us to buying the same goods twice, from a " |
| 222 | f"supplier who will happily send them.") |
| 223 | |
| 224 | shipment_ids, moved = _moves_against(base, order_id) |
| 225 | if moved: |
| 226 | blockers["stock_moved"] = [ |
| 227 | {"stock_move_id": _text(row.get("id")), |
| 228 | "product_id": _text(row.get("product_id")), |
| 229 | "quantity": _text(row.get("quantity")), |
| 230 | "reason": _text(row.get("reason")), |
| 231 | "reference": _text(row.get("reference"))} |
| 232 | for row in moved] |
| 233 | |
| 234 | vendor_id = _text(request.get("vendor_id")) |
| 235 | if not vendor_id: |
| 236 | blockers["missing_vendor"] = ( |
| 237 | "A drop-ship has to name who is shipping it. The purchase order " |
| 238 | "is a commitment to buy from somebody, and 'a vendor' is not " |
| 239 | "somebody anybody can send an order to.") |
| 240 | |
| 241 | lines = [row for row in _rows("order_lines", base) or [] |
| 242 | if _text(row.get("order_id")) == order_id] |
| 243 | if not lines: |
| 244 | blockers["no_lines"] = ( |
| 245 | "This order has no lines, so there is nothing to buy on its " |
| 246 | "behalf. A purchase order for an empty order would commit us to " |
| 247 | "nothing and tell the vendor nothing.") |
| 248 | |
| 249 | if any(blockers.values()): |
| 250 | return {"status": 409, |
| 251 | "error": "This order cannot be drop-shipped.", |
| 252 | "shipments": shipment_ids, |
| 253 | **blockers} |
| 254 | |
| 255 | # --- the purchase order ------------------------------------------------ |
| 256 | owner = (_text(order.get("owner_id")) |
| 257 | or _text((request.get("_identity") or {}).get("user_id"))) |
| 258 | when = _text(request.get("today")) or date.today().isoformat() |
| 259 | purchase_id = object_ids.new_uuid4() |
| 260 | number = (_text(request.get("number")) |
| 261 | or f"PO-{_text(order.get('number'))}") |
| 262 | vendor_name = _vendor_name(base, vendor_id, |
| 263 | _text(request.get("vendor_name"))) |
| 264 | |
| 265 | object_records.create_collection_record( |
| 266 | "orders", |
| 267 | { |
| 268 | "id": purchase_id, |
| 269 | "doc_type": "purchase", |
| 270 | "number": number, |
| 271 | # The counterparty, exactly as every other purchase order in |
| 272 | # this repo names it: customer_name on a PO has always been the |
| 273 | # supplier, and flipping that meaning for one kind of PO would |
| 274 | # make the order list read differently row by row. |
| 275 | "customer_name": vendor_name, |
| 276 | "currency": _text(order.get("currency")) or "USD", |
| 277 | # Confirmed, not draft: the operator choosing a vendor IS the |
| 278 | # commitment to buy, and a drop-ship PO sitting in draft is a |
| 279 | # customer waiting on a parcel nobody has ordered. |
| 280 | "status": "confirmed", |
| 281 | "order_date": when, |
| 282 | "expected_date": _text(order.get("expected_date")), |
| 283 | "fulfillment_source": DROPSHIP, |
| 284 | "linked_order_id": order_id, |
| 285 | "vendor_id": vendor_id, |
| 286 | # The customer's ship-to, carried onto the vendor's document. |
| 287 | # This is the one place in this repo where the counterparty on |
| 288 | # an order and the destination of its goods are different |
| 289 | # people, and it is why those two fields exist at all. |
| 290 | "ship_to_name": (_text(order.get("ship_to_name")) |
| 291 | or _text(order.get("customer_name")) |
| 292 | or _text(order.get("customer_email"))), |
| 293 | "ship_to_address": _text(order.get("ship_to_address")), |
| 294 | # The vendor is the packer now, so the packer's instructions and |
| 295 | # the gift message travel with the goods rather than staying on |
| 296 | # a document the person packing the box will never see. |
| 297 | "customer_note": _text(order.get("customer_note")), |
| 298 | "gift_message": _text(order.get("gift_message")), |
| 299 | "notes": (f"Generated by {ACTOR} [orders/{order_id}] -- drop-ship " |
| 300 | f"to the customer; goods never touch our shelf"), |
| 301 | "owner_id": owner, |
| 302 | }, |
| 303 | base_dir=base, actor=ACTOR) |
| 304 | |
| 305 | prices = request.get("prices") |
| 306 | prices = prices if isinstance(prices, dict) else {} |
| 307 | flat = _cents(request.get("vendor_price_cents")) |
| 308 | products = {_text(row.get("id")): row for row in _rows("products", base) or []} |
| 309 | |
| 310 | created = [] |
| 311 | unpriced = [] |
| 312 | for line in lines: |
| 313 | unit = _cents(prices.get(_text(line.get("id")))) |
| 314 | if unit is None: |
| 315 | unit = flat |
| 316 | if unit is None: |
| 317 | product = products.get(_text(line.get("product_id"))) or {} |
| 318 | unit = _cents(product.get("cost_cents")) |
| 319 | if unit is None or unit <= 0: |
| 320 | # Zero reads as 100% margin and the sale price reads as none. |
| 321 | # Both are lies; saying the number is missing is not. |
| 322 | unit = 0 |
| 323 | unpriced.append(_text(line.get("id"))) |
| 324 | quantity = _quantity(line.get("quantity")) or Decimal(1) |
| 325 | line_id = object_ids.new_uuid4() |
| 326 | object_records.create_collection_record( |
| 327 | "order_lines", |
| 328 | { |
| 329 | "id": line_id, |
| 330 | "order_id": purchase_id, |
| 331 | "product_id": _text(line.get("product_id")), |
| 332 | # Stamped from the sale line: what the vendor is being asked |
| 333 | # to send is what the customer bought, described the way the |
| 334 | # customer saw it. |
| 335 | "description": _text(line.get("description")), |
| 336 | "quantity": _number(quantity), |
| 337 | "unit_price_cents": str(unit), |
| 338 | "line_total_cents": str( |
| 339 | int((quantity * Decimal(unit)).to_integral_value())), |
| 340 | "tax_rate_bps": "0", |
| 341 | "line_tax_cents": "0", |
| 342 | "owner_id": owner, |
| 343 | }, |
| 344 | base_dir=base, actor=ACTOR) |
| 345 | created.append({"order_line_id": _text(line.get("id")), |
| 346 | "purchase_line_id": line_id, |
| 347 | "quantity": _number(quantity), |
| 348 | "unit_price_cents": str(unit)}) |
| 349 | |
| 350 | # --- and the sale order learns what it is ------------------------------ |
| 351 | # Both ends carry the fact, so neither has to walk the link to answer |
| 352 | # "is this a drop-ship?" -- which is the question a stock handler asks, |
| 353 | # and a handler that had to join to find out would eventually not. |
| 354 | object_records.update_collection_record( |
| 355 | "orders", order_id, |
| 356 | {"fulfillment_source": DROPSHIP, "linked_order_id": purchase_id, |
| 357 | "vendor_id": vendor_id}, |
| 358 | base_dir=base, actor=ACTOR) |
| 359 | |
| 360 | result = {"ok": True, "order_id": order_id, |
| 361 | "purchase_order_id": purchase_id, "number": number, |
| 362 | "vendor_id": vendor_id, "vendor_name": vendor_name, |
| 363 | "lines": len(created), "purchase_lines": created, |
| 364 | "ship_to_name": (_text(order.get("ship_to_name")) |
| 365 | or _text(order.get("customer_name"))), |
| 366 | "date": when, |
| 367 | "note": "the goods never touch our shelf: nothing has moved, no " |
| 368 | "receipt is expected, and the vendor's dispatch is the " |
| 369 | "fulfillment"} |
| 370 | if unpriced: |
| 371 | result["warning"] = ( |
| 372 | f"{len(unpriced)} line(s) carry no vendor price, so the purchase " |
| 373 | f"order totals zero and margin will read as pure profit until " |
| 374 | f"somebody types what the vendor actually charges. Pass " |
| 375 | f"vendor_price_cents or prices, or record cost_cents on the " |
| 376 | f"product.") |
| 377 | result["unpriced_lines"] = unpriced |
| 378 | return result |