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.
counter_stock.py · 7.5 KB · 166 lines
| 1 | """system_counter_stock -- goods handed over the counter leave the shelf. |
| 2 | |
| 3 | **What was wrong (Corner Cup, a Haiku simulation of a counter cafe).** |
| 4 | Stock moved only through a shipment: system_shop_fulfillment raises one on |
| 5 | payment when shop.auto_fulfill is on, and system_order_fulfillment writes |
| 6 | the sale moves when it ships, from shop.stock_location. A counter or pickup |
| 7 | sale with auto_fulfill off, or no stock location, or no shipment, never |
| 8 | moved anything: the cafe sold soup all day and the shelf said it still had |
| 9 | all of it. |
| 10 | |
| 11 | **When goods leave.** At the hand-over: action_counter_hand_over (served |
| 12 | at the counter, collected at pickup) calls MOVE here before it marks the |
| 13 | order collected, and this object also HANDLES orders updated to |
| 14 | `collected` for a counter or pickup order, so a status set any other way |
| 15 | (over the API, with reactions on) moves the goods too. One `sale` move per |
| 16 | order line, from shop.stock_location to shop.customer_location, carrying |
| 17 | object_corrections.counter_marker(order, line) in its reference. |
| 18 | |
| 19 | **Nothing counted twice.** What still has to move for a line is its |
| 20 | quantity less what object_reservations.moved_by_line says already moved for |
| 21 | it: a shipment's sale move (shop_fulfillment's auto path), an earlier |
| 22 | hand-over, a remake's waste. The same fold is what holds stock for an |
| 23 | online order, so the instant this move exists the hold is the move; the |
| 24 | order is marked collected only after (a hold released on the status before |
| 25 | the move landed would show goods available that are already in a bag). |
| 26 | system_order_fulfillment subtracts these moves in turn, so a shipment |
| 27 | recorded after a hand-over moves nothing again. A replay finds its marker. |
| 28 | |
| 29 | **Costed like a shipped sale**: the moving weighted average on the shelf |
| 30 | (object_stock.average_cost_for_product), else the product's cost_cents. |
| 31 | Unlike the shipment handler (a reaction that cannot refuse a parcel that |
| 32 | left) MOVE is asked by a person at the counter, so an unreadable cost or a |
| 33 | missing shop.stock_location REFUSES and names what to configure, writing |
| 34 | nothing. The reaction path reports the same in its result and moves |
| 35 | nothing; the next hand-over or replay moves it. |
| 36 | """ |
| 37 | |
| 38 | from __future__ import annotations |
| 39 | |
| 40 | import os |
| 41 | from datetime import date |
| 42 | |
| 43 | import object_collections |
| 44 | import object_corrections |
| 45 | import object_ids |
| 46 | import object_records |
| 47 | import object_reservations |
| 48 | import object_stock |
| 49 | |
| 50 | HANDLES = ["orders.record.updated"] |
| 51 | ACTOR = "system_counter_stock" |
| 52 | |
| 53 | |
| 54 | def _base_dir(): |
| 55 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 56 | |
| 57 | |
| 58 | def _rows(base, collection): |
| 59 | try: |
| 60 | return object_records.read_collection_records(collection, base_dir=base) |
| 61 | except object_collections.CollectionNotFoundError: |
| 62 | return [] |
| 63 | |
| 64 | |
| 65 | def _setting(base, key): |
| 66 | for row in _rows(base, "app_settings"): |
| 67 | if object_corrections.text(row.get("key")) == key and object_corrections.text(row.get("value")): |
| 68 | return object_corrections.text(row["value"]) |
| 69 | return "" |
| 70 | |
| 71 | |
| 72 | def plan(base, order): |
| 73 | """(moves to write, refusal or ""). Reads only.""" |
| 74 | text = object_corrections.text |
| 75 | lines = [row for row in _rows(base, "order_lines") if text(row.get("order_id")) == text(order.get("id"))] |
| 76 | products = {text(p.get("id")): p for p in _rows(base, "products")} |
| 77 | tracked = {pid: object_reservations.tracked(p) for pid, p in products.items()} |
| 78 | moved = object_reservations.moved_by_line(_rows(base, "stock_moves"), _rows(base, "shipment_lines")) |
| 79 | pending = object_corrections.to_move(lines, moved, tracked) |
| 80 | if not pending: |
| 81 | return [], "" |
| 82 | if _text_dropship(order): |
| 83 | return [], "" |
| 84 | from_location = _setting(base, "shop.stock_location") |
| 85 | if not from_location: |
| 86 | return [], ("shop.stock_location is not configured, so the shop does not know which " |
| 87 | "shelf the goods leave from. Set it in app_settings; nothing was moved.") |
| 88 | to_location = _setting(base, "shop.customer_location") |
| 89 | moves = [] |
| 90 | for line, quantity in pending: |
| 91 | product_id = text(line.get("product_id")) |
| 92 | try: |
| 93 | cost = object_stock.average_cost_for_product(product_id, base_dir=base) |
| 94 | except Exception as exc: # noqa: BLE001 |
| 95 | return [], (f"The cost of {text(line.get('description'))} could not be read " |
| 96 | f"({str(exc)[:120]}); nothing was moved. Try again in a moment.") |
| 97 | cost = cost or object_corrections.cents(products[product_id].get("cost_cents")) or None |
| 98 | move = {"id": object_ids.new_uuid4(), "product_id": product_id, |
| 99 | "from_location_id": from_location, "quantity": object_corrections.fmt_qty(quantity), |
| 100 | "reason": "sale", |
| 101 | "reference": (f"{object_corrections.counter_marker(order['id'], line['id'])} " |
| 102 | f"{text(order.get('number'))}").strip(), |
| 103 | "occurred_at": date.today().isoformat(), |
| 104 | "owner_id": text(order.get("owner_id"))} |
| 105 | if to_location: |
| 106 | move["to_location_id"] = to_location |
| 107 | if cost: |
| 108 | move["unit_cost_cents"] = str(cost) |
| 109 | moves.append(move) |
| 110 | return moves, "" |
| 111 | |
| 112 | |
| 113 | def _text_dropship(order): |
| 114 | return object_corrections.text(order.get("fulfillment_source")) == "dropship" |
| 115 | |
| 116 | |
| 117 | def write(base, moves, actor): |
| 118 | for move in moves: |
| 119 | object_records.create_collection_record("stock_moves", move, base_dir=base, actor=actor) |
| 120 | return [m["id"] for m in moves] |
| 121 | |
| 122 | |
| 123 | def MOVE(request): |
| 124 | """Called in process by action_counter_hand_over before it marks the |
| 125 | order collected. {"order_id", "actor"} -> {"ok", "moved": [...]} or |
| 126 | {"ok": False, "status", "error"}.""" |
| 127 | base = request.get("base_dir") or _base_dir() |
| 128 | try: |
| 129 | order = object_records.get_collection_record("orders", object_corrections.text(request.get("order_id")), |
| 130 | base_dir=base) |
| 131 | except Exception: |
| 132 | return {"ok": False, "status": 404, "error": "No such order."} |
| 133 | try: |
| 134 | moves, refusal = plan(base, order) |
| 135 | except Exception as exc: # noqa: BLE001 -- an unreadable ledger is not "nothing to move" |
| 136 | return {"ok": False, "status": 503, |
| 137 | "error": f"The stock log could not be read ({str(exc)[:120]}); nothing was moved."} |
| 138 | if refusal: |
| 139 | return {"ok": False, "status": 409, "error": refusal} |
| 140 | return {"ok": True, "moved": write(base, moves, object_corrections.text(request.get("actor")) or ACTOR)} |
| 141 | |
| 142 | |
| 143 | def EVENT(request): |
| 144 | """Reaction: an order of a counter or pickup sale reached `collected`.""" |
| 145 | base = _base_dir() |
| 146 | record_id = object_corrections.text(request.get("record_id") or request.get("id")) |
| 147 | if object_corrections.text(request.get("collection")) != "orders" or not record_id: |
| 148 | return {"ok": True, "skipped": "not an orders event"} |
| 149 | try: |
| 150 | order = object_records.get_collection_record("orders", record_id, base_dir=base) |
| 151 | except Exception: |
| 152 | return {"ok": True, "skipped": "order gone"} |
| 153 | if (object_corrections.text(order.get("status")) != "collected" |
| 154 | or object_corrections.text(order.get("fulfillment_method")) not in object_corrections.COUNTER_METHODS |
| 155 | or object_corrections.text(order.get("doc_type") or "sale") != "sale"): |
| 156 | return {"ok": True, "skipped": "not a collected counter or pickup sale"} |
| 157 | try: |
| 158 | moves, refusal = plan(base, order) |
| 159 | if refusal: |
| 160 | return {"ok": False, "warning": refusal} |
| 161 | return {"ok": True, "moved": write(base, moves, ACTOR)} |
| 162 | except Exception as exc: # noqa: BLE001 -- a reaction never raises into the dispatcher |
| 163 | return {"ok": False, "error": str(exc)[:200]} |
| 164 | |
| 165 | |
| 166 | POST = EVENT |