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.
dropship_order.py · 20.0 KB · 451 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 | A shipments or stock ledger that cannot be read is not "nothing moved": |
| 56 | it is a 503 with nothing written (a collection that is not installed is |
| 57 | the fact that nothing moved, and reads as empty). |
| 58 | |
| 59 | **Exactly one PO per sale order.** A second call finds linked_order_id |
| 60 | already set and refuses with the number of the PO that exists, rather |
| 61 | than quietly raising a duplicate commitment to buy -- the same class of |
| 62 | mistake as a double refund, with a supplier on the other end of it. |
| 63 | linked_order_id is read under a claim on the sale order |
| 64 | (orders.action_claim, object_claims), because read without one four |
| 65 | overlapping clicks all found it blank and raised four POs; the link is |
| 66 | written, and the claim cleared, in one write at the end. |
| 67 | |
| 68 | **The vendor's price is asked for, never invented.** Explicit per-line |
| 69 | prices win, then a flat vendor_price_cents per unit, then the product's |
| 70 | recorded cost_cents. When none of those exist the PO is raised at zero |
| 71 | with a WARNING naming the lines, because a cost of zero reads as 100% |
| 72 | margin and a cost copied from the sale price reads as none -- both are |
| 73 | lies, and the honest move is to say the number is missing. |
| 74 | """ |
| 75 | |
| 76 | import os |
| 77 | from datetime import date |
| 78 | from decimal import Decimal, InvalidOperation |
| 79 | |
| 80 | import object_access |
| 81 | import object_claims |
| 82 | import object_collections |
| 83 | import object_ids |
| 84 | import object_records |
| 85 | |
| 86 | ACTOR = "action_dropship_order" |
| 87 | |
| 88 | DROPSHIP = "dropship" |
| 89 | |
| 90 | # A draft is not a commitment and a cancelled order must not come back to |
| 91 | # life because somebody raised a PO against it. Everything else -- an |
| 92 | # order confirmed, in processing, even partially shipped from stock for |
| 93 | # its OTHER lines -- can still have a vendor take the rest. |
| 94 | UNTOUCHABLE_ORDER_STATUSES = {"draft", "cancelled"} |
| 95 | |
| 96 | |
| 97 | def _base_dir(): |
| 98 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 99 | |
| 100 | |
| 101 | def _text(value): |
| 102 | return str(value if value is not None else "").strip() |
| 103 | |
| 104 | |
| 105 | def _cents(value): |
| 106 | """None means NOT SAID, which is a different fact from zero. |
| 107 | |
| 108 | The whole vendor-price ladder below turns on that difference: a price |
| 109 | somebody typed as 0 is a decision, and a price nobody typed is a gap |
| 110 | to report. Collapsing the two into 0 is how the fallback chain would |
| 111 | silently stop at its first rung. |
| 112 | """ |
| 113 | text = _text(value) |
| 114 | if not text: |
| 115 | return None |
| 116 | try: |
| 117 | return int(text) |
| 118 | except ValueError: |
| 119 | return None |
| 120 | |
| 121 | |
| 122 | def _quantity(value): |
| 123 | """Decimal, never a bare float -- quantities may be fractional.""" |
| 124 | try: |
| 125 | return Decimal(_text(value) or "0") |
| 126 | except InvalidOperation: |
| 127 | return Decimal(0) |
| 128 | |
| 129 | |
| 130 | def _number(value): |
| 131 | return format(value.normalize(), "f") |
| 132 | |
| 133 | |
| 134 | def _rows(collection, base): |
| 135 | try: |
| 136 | # access: history of the order read through Access above |
| 137 | return object_records.read_collection_records(collection, base_dir=base) |
| 138 | except Exception: |
| 139 | return None |
| 140 | |
| 141 | |
| 142 | class HistoryUnreadable(Exception): |
| 143 | """What this order has already been through cannot be read, so whether |
| 144 | its goods are still on our shelf is unknown.""" |
| 145 | |
| 146 | |
| 147 | def _history(collection, base): |
| 148 | """Every row of `collection` for a read the refusal decides from: [] |
| 149 | only when it is not installed (a fact -- no shipment, no move, no line |
| 150 | exists), HistoryUnreadable for anything else (an unknown). |
| 151 | |
| 152 | _rows above answers None for both, which is right for the vendor's |
| 153 | printable name and wrong here: read as "nothing moved", an unreadable |
| 154 | ledger let an order whose goods had already left be drop-shipped, and |
| 155 | the same units were bought a second time.""" |
| 156 | try: |
| 157 | # access: history of the order read through Access above |
| 158 | return object_records.read_collection_records(collection, base_dir=base) |
| 159 | except object_collections.CollectionNotFoundError: |
| 160 | return [] |
| 161 | except Exception as exc: |
| 162 | raise HistoryUnreadable(f"{collection}: {str(exc)[:160]}") from exc |
| 163 | |
| 164 | |
| 165 | def _vendor_name(base, vendor_id, given): |
| 166 | """A printable name for the vendor, asked of the places one might be |
| 167 | filed and never invented. |
| 168 | |
| 169 | vendor_id is plain text precisely because a vendor may be a contact, |
| 170 | an organization, or neither; so this looks in both and falls back to |
| 171 | the id itself, which at least identifies the counterparty rather than |
| 172 | leaving a required field blank. |
| 173 | """ |
| 174 | if given: |
| 175 | return given |
| 176 | for row in _rows("contacts", base) or []: |
| 177 | if _text(row.get("id")) != vendor_id: |
| 178 | continue |
| 179 | full = _text(row.get("full_name")) |
| 180 | if full: |
| 181 | return full |
| 182 | parts = [_text(row.get("first_name")), _text(row.get("last_name"))] |
| 183 | joined = " ".join(part for part in parts if part) |
| 184 | if joined: |
| 185 | return joined |
| 186 | for row in _rows("organizations", base) or []: |
| 187 | if _text(row.get("id")) == vendor_id and _text(row.get("name")): |
| 188 | return _text(row["name"]) |
| 189 | return vendor_id |
| 190 | |
| 191 | |
| 192 | def _moves_against(base, order_id): |
| 193 | """Stock moves already composed for this order's shipments. |
| 194 | |
| 195 | The marker system_order_fulfillment stamps is |
| 196 | `shipments/{shipment_id}:line/{line_id}`, so the honest question is |
| 197 | asked of the moves themselves rather than of a status somebody could |
| 198 | have typed: goods that left the shelf are the fact, and the order's |
| 199 | status is only ever a read of it. |
| 200 | """ |
| 201 | ours = [_text(row.get("id")) for row in _history("shipments", base) |
| 202 | if _text(row.get("order_id")) == order_id] |
| 203 | if not ours: |
| 204 | return [], [] |
| 205 | moves = _history("stock_moves", base) |
| 206 | hits = [row for row in moves |
| 207 | if any(f"shipments/{shipment_id}:" in _text(row.get("reference")) |
| 208 | for shipment_id in ours)] |
| 209 | return ours, hits |
| 210 | |
| 211 | |
| 212 | def POST(request): |
| 213 | base = _base_dir() |
| 214 | order_id = _text(request.get("order_id")) |
| 215 | if not order_id: |
| 216 | return {"status": 400, "error": "order_id is required"} |
| 217 | |
| 218 | # Only someone the orders API would let UPDATE this sale order may |
| 219 | # commit the shop to buying its goods from a vendor. Every write below |
| 220 | # is a trusted server-side write, so this object is the only gate; it |
| 221 | # used to let any signed-in user raise a confirmed purchase order (to a |
| 222 | # vendor of their choosing) against anybody's sale. Asked first, so the |
| 223 | # 409s below are only shown to somebody allowed to see the order; |
| 224 | # refused reads exactly like missing. |
| 225 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 226 | try: |
| 227 | order = access.get("orders", order_id, action="update") |
| 228 | except Exception: |
| 229 | order = None |
| 230 | if order is None: |
| 231 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 232 | |
| 233 | # THE CLAIM, before linked_order_id and the stock moves are read. The |
| 234 | # "already linked" refusal below was read before anything is written, |
| 235 | # so four overlapping clicks all found the order unlinked and raised |
| 236 | # four confirmed purchase orders to the vendor. Only the request holding |
| 237 | # orders.action_claim reads and writes; any other is answered 409 |
| 238 | # in_progress with nothing written. |
| 239 | try: |
| 240 | claim, order = object_claims.take("orders", order_id, base_dir=base, |
| 241 | actor=ACTOR) |
| 242 | except object_claims.Busy: |
| 243 | return object_claims.busy_answer("order", order_id) |
| 244 | except object_records.RecordNotFoundError: |
| 245 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 246 | except Exception as exc: |
| 247 | return {"status": 503, |
| 248 | "error": (f"This order cannot be claimed right now " |
| 249 | f"({str(exc)[:120]}), so nothing was drop-shipped. " |
| 250 | f"Try again in a moment.")} |
| 251 | try: |
| 252 | return _dropship(base, request, access, order, order_id) |
| 253 | except HistoryUnreadable as exc: |
| 254 | return {"status": 503, |
| 255 | "error": (f"This order's history could not be read ({exc}), " |
| 256 | f"so whether its goods have already left our shelf " |
| 257 | f"is unknown. Nothing was drop-shipped; try again " |
| 258 | f"once it is readable.")} |
| 259 | finally: |
| 260 | object_claims.release("orders", order_id, claim, base_dir=base, |
| 261 | actor=ACTOR) |
| 262 | |
| 263 | |
| 264 | def _dropship(base, request, access, order, order_id): |
| 265 | """Everything after the claim: read, decide, write.""" |
| 266 | blockers ={"wrong_document": "", "order_status": "", "already_linked": "", |
| 267 | "stock_moved": [], "missing_vendor": "", "no_lines": ""} |
| 268 | |
| 269 | if _text(order.get("doc_type")) != "sale": |
| 270 | blockers["wrong_document"] = ( |
| 271 | "That is a purchase order. Drop-shipping is something you do to " |
| 272 | "a SALE order -- it spawns the purchase order, and a purchase " |
| 273 | "order spawning another one is a supply chain nobody asked for.") |
| 274 | |
| 275 | status = _text(order.get("status")) |
| 276 | if status in UNTOUCHABLE_ORDER_STATUSES: |
| 277 | blockers["order_status"] = ( |
| 278 | f"This order is {status}. A draft is not a commitment and a " |
| 279 | f"cancelled order must not come back to life because somebody " |
| 280 | f"raised a purchase order against it -- confirm it first, or " |
| 281 | f"leave it alone.") |
| 282 | |
| 283 | already = _text(order.get("linked_order_id")) |
| 284 | if already: |
| 285 | number = "" |
| 286 | try: |
| 287 | number = _text(object_records.get_collection_record( |
| 288 | "orders", already, base_dir=base).get("number")) |
| 289 | except Exception: |
| 290 | number = already |
| 291 | blockers["already_linked"] = ( |
| 292 | f"This order is already drop-shipped on purchase order {number} " |
| 293 | f"({already}). One sale order spawns exactly one PO; raising a " |
| 294 | f"second would commit us to buying the same goods twice, from a " |
| 295 | f"supplier who will happily send them.") |
| 296 | |
| 297 | shipment_ids, moved = _moves_against(base, order_id) |
| 298 | if moved: |
| 299 | blockers["stock_moved"] = [ |
| 300 | {"stock_move_id": _text(row.get("id")), |
| 301 | "product_id": _text(row.get("product_id")), |
| 302 | "quantity": _text(row.get("quantity")), |
| 303 | "reason": _text(row.get("reason")), |
| 304 | "reference": _text(row.get("reference"))} |
| 305 | for row in moved] |
| 306 | |
| 307 | vendor_id = _text(request.get("vendor_id")) |
| 308 | if not vendor_id: |
| 309 | blockers["missing_vendor"] = ( |
| 310 | "A drop-ship has to name who is shipping it. The purchase order " |
| 311 | "is a commitment to buy from somebody, and 'a vendor' is not " |
| 312 | "somebody anybody can send an order to.") |
| 313 | |
| 314 | lines = [row for row in _history("order_lines", base) |
| 315 | if _text(row.get("order_id")) == order_id] |
| 316 | if not lines: |
| 317 | blockers["no_lines"] = ( |
| 318 | "This order has no lines, so there is nothing to buy on its " |
| 319 | "behalf. A purchase order for an empty order would commit us to " |
| 320 | "nothing and tell the vendor nothing.") |
| 321 | |
| 322 | if any(blockers.values()): |
| 323 | return {"status": 409, |
| 324 | "error": "This order cannot be drop-shipped.", |
| 325 | "shipments": shipment_ids, |
| 326 | **blockers} |
| 327 | |
| 328 | # --- the purchase order ------------------------------------------------ |
| 329 | owner = _text(order.get("owner_id")) or access.user_id |
| 330 | when = _text(request.get("today")) or date.today().isoformat() |
| 331 | purchase_id = object_ids.new_uuid4() |
| 332 | number = (_text(request.get("number")) |
| 333 | or f"PO-{_text(order.get('number'))}") |
| 334 | vendor_name = _vendor_name(base, vendor_id, |
| 335 | _text(request.get("vendor_name"))) |
| 336 | |
| 337 | object_records.create_collection_record( |
| 338 | "orders", |
| 339 | { |
| 340 | "id": purchase_id, |
| 341 | "doc_type": "purchase", |
| 342 | "number": number, |
| 343 | # The counterparty, exactly as every other purchase order in |
| 344 | # this repo names it: customer_name on a PO has always been the |
| 345 | # supplier, and flipping that meaning for one kind of PO would |
| 346 | # make the order list read differently row by row. |
| 347 | "customer_name": vendor_name, |
| 348 | "currency": _text(order.get("currency")) or "USD", |
| 349 | # Confirmed, not draft: the operator choosing a vendor IS the |
| 350 | # commitment to buy, and a drop-ship PO sitting in draft is a |
| 351 | # customer waiting on a parcel nobody has ordered. |
| 352 | "status": "confirmed", |
| 353 | "order_date": when, |
| 354 | "expected_date": _text(order.get("expected_date")), |
| 355 | "fulfillment_source": DROPSHIP, |
| 356 | "linked_order_id": order_id, |
| 357 | "vendor_id": vendor_id, |
| 358 | # The customer's ship-to, carried onto the vendor's document. |
| 359 | # This is the one place in this repo where the counterparty on |
| 360 | # an order and the destination of its goods are different |
| 361 | # people, and it is why those two fields exist at all. |
| 362 | "ship_to_name": (_text(order.get("ship_to_name")) |
| 363 | or _text(order.get("customer_name")) |
| 364 | or _text(order.get("customer_email"))), |
| 365 | "ship_to_address": _text(order.get("ship_to_address")), |
| 366 | # The vendor is the packer now, so the packer's instructions and |
| 367 | # the gift message travel with the goods rather than staying on |
| 368 | # a document the person packing the box will never see. |
| 369 | "customer_note": _text(order.get("customer_note")), |
| 370 | "gift_message": _text(order.get("gift_message")), |
| 371 | "notes": (f"Generated by {ACTOR} [orders/{order_id}] -- drop-ship " |
| 372 | f"to the customer; goods never touch our shelf"), |
| 373 | "owner_id": owner, |
| 374 | }, |
| 375 | base_dir=base, actor=ACTOR) |
| 376 | |
| 377 | prices = request.get("prices") |
| 378 | prices = prices if isinstance(prices, dict) else {} |
| 379 | flat = _cents(request.get("vendor_price_cents")) |
| 380 | products = {_text(row.get("id")): row for row in _rows("products", base) or []} |
| 381 | |
| 382 | created = [] |
| 383 | unpriced = [] |
| 384 | for line in lines: |
| 385 | unit = _cents(prices.get(_text(line.get("id")))) |
| 386 | if unit is None: |
| 387 | unit = flat |
| 388 | if unit is None: |
| 389 | product = products.get(_text(line.get("product_id"))) or {} |
| 390 | unit = _cents(product.get("cost_cents")) |
| 391 | if unit is None or unit <= 0: |
| 392 | # Zero reads as 100% margin and the sale price reads as none. |
| 393 | # Both are lies; saying the number is missing is not. |
| 394 | unit = 0 |
| 395 | unpriced.append(_text(line.get("id"))) |
| 396 | quantity = _quantity(line.get("quantity")) or Decimal(1) |
| 397 | line_id = object_ids.new_uuid4() |
| 398 | # access: system write for the order read through Access above |
| 399 | object_records.create_collection_record( |
| 400 | "order_lines", |
| 401 | { |
| 402 | "id": line_id, |
| 403 | "order_id": purchase_id, |
| 404 | "product_id": _text(line.get("product_id")), |
| 405 | # Stamped from the sale line: what the vendor is being asked |
| 406 | # to send is what the customer bought, described the way the |
| 407 | # customer saw it. |
| 408 | "description": _text(line.get("description")), |
| 409 | "quantity": _number(quantity), |
| 410 | "unit_price_cents": str(unit), |
| 411 | "line_total_cents": str( |
| 412 | int((quantity * Decimal(unit)).to_integral_value())), |
| 413 | "tax_rate_bps": "0", |
| 414 | "line_tax_cents": "0", |
| 415 | "owner_id": owner, |
| 416 | }, |
| 417 | base_dir=base, actor=ACTOR) |
| 418 | created.append({"order_line_id": _text(line.get("id")), |
| 419 | "purchase_line_id": line_id, |
| 420 | "quantity": _number(quantity), |
| 421 | "unit_price_cents": str(unit)}) |
| 422 | |
| 423 | # --- and the sale order learns what it is ------------------------------ |
| 424 | # Both ends carry the fact, so neither has to walk the link to answer |
| 425 | # "is this a drop-ship?" -- which is the question a stock handler asks, |
| 426 | # and a handler that had to join to find out would eventually not. |
| 427 | object_records.update_collection_record( |
| 428 | "orders", order_id, |
| 429 | {"fulfillment_source": DROPSHIP, "linked_order_id": purchase_id, |
| 430 | "vendor_id": vendor_id, "action_claim": ""}, |
| 431 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 432 | |
| 433 | result = {"ok": True, "order_id": order_id, |
| 434 | "purchase_order_id": purchase_id, "number": number, |
| 435 | "vendor_id": vendor_id, "vendor_name": vendor_name, |
| 436 | "lines": len(created), "purchase_lines": created, |
| 437 | "ship_to_name": (_text(order.get("ship_to_name")) |
| 438 | or _text(order.get("customer_name"))), |
| 439 | "date": when, |
| 440 | "note": "the goods never touch our shelf: nothing has moved, no " |
| 441 | "receipt is expected, and the vendor's dispatch is the " |
| 442 | "fulfillment"} |
| 443 | if unpriced: |
| 444 | result["warning"] = ( |
| 445 | f"{len(unpriced)} line(s) carry no vendor price, so the purchase " |
| 446 | f"order totals zero and margin will read as pure profit until " |
| 447 | f"somebody types what the vendor actually charges. Pass " |
| 448 | f"vendor_price_cents or prices, or record cost_cents on the " |
| 449 | f"product.") |
| 450 | result["unpriced_lines"] = unpriced |
| 451 | return result |