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
receipt_posting.py · 16.0 KB · 381 lines
| 1 | """system_receipt_posting -- the pallet landed, so the shelf is heavier and |
| 2 | the purchase order says so. |
| 3 | |
| 4 | HANDLES receipts and receipt_lines writes. Two jobs, both of them reads |
| 5 | turned into facts, mirroring system_order_fulfillment on the sales side. |
| 6 | |
| 7 | **Stock moves when goods physically move.** One `purchase` move PER |
| 8 | RECEIPT LINE at the moment a receipt reaches `received`, from |
| 9 | receiving.supplier_location to receiving.stock_location (falling back to |
| 10 | shop.stock_location, because a one-warehouse shop has already configured |
| 11 | that and should not have to say the same thing twice). Per line rather |
| 12 | than per receipt because a level is a fold over moves per product, and a |
| 13 | delivery routinely carries several products with different fates. |
| 14 | |
| 15 | **Rejected quantities compose NOTHING.** Goods being sent back never |
| 16 | entered stock: the carton was opened at the door, judged crushed, and put |
| 17 | straight on the driver's trolley. A move for it would put damaged goods on |
| 18 | the shelf and then require a compensating move to take them off again -- |
| 19 | two lies that happen to cancel, which is worse than one honest silence. |
| 20 | The rejection is still RECORDED, on the receipt line, where the argument |
| 21 | with the supplier can find it. |
| 22 | |
| 23 | **unit_cost_cents is stamped from the PO line's unit_price_cents.** This |
| 24 | is the move that makes inventory valuation possible later: a `sale` move |
| 25 | today carries no cost at all, which is exactly why COGS-on-sale cannot be |
| 26 | composed (see tests/test_cogs_on_sale.py, which specifies that gap as a |
| 27 | strict xfail -- its point 3 says in as many words that "nothing stamps |
| 28 | that cost on a sale move today, and where a sale move carries no cost, no |
| 29 | honest journal can be composed at all"). FIFO or weighted average both |
| 30 | need a cost on the way IN, per layer, per location; stamping the price we |
| 31 | actually agreed to pay at the moment the goods arrive is the input both |
| 32 | methods consume, and it costs nothing to record now and cannot be |
| 33 | reconstructed later once the supplier's price list has moved on. Choosing |
| 34 | BETWEEN FIFO and average stays out of this handler on purpose -- picking a |
| 35 | valuation method by accident inside a receiving reaction would be worse |
| 36 | than the current silence. |
| 37 | |
| 38 | **The purchase order's status is derived, never set.** Some of the ordered |
| 39 | quantity received is `partial`; all of it is `received` |
| 40 | (docs/logic-decisions.md #1: the QUANTITIES on receipt lines are the |
| 41 | facts, the order's status is a read of them). A human never types either |
| 42 | one and no surface computes it at read time; it is stored, so the PO list, |
| 43 | the receiving sheet and a report cannot disagree. |
| 44 | |
| 45 | `received` is a NEW value on the shared SO/PO status enum (orders v3), and |
| 46 | it is deliberately not a reuse of `delivered`. `delivered` on a purchase |
| 47 | order reads as a claim about something WE sent -- in a mixed order list, |
| 48 | filtered by status rather than by doc_type, it is actively misleading, and |
| 49 | "the goods completed their journey" is a gloss nobody applies at a glance. |
| 50 | `received` can only ever mean one thing in either direction: the goods |
| 51 | turned up HERE. The spec says the same (plan/fulfillment-logistics-spec.md: |
| 52 | "PO status derives: partial | received"), and the cost of the alternative |
| 53 | is a word that means the opposite of itself depending on a field two |
| 54 | columns away. |
| 55 | |
| 56 | Placement follows docs/logic-decisions.md #6 -- a REACTION, post-commit, |
| 57 | best-effort, never blocking the write that triggered it. A dock that |
| 58 | cannot record a stock move must still be able to sign for the delivery; |
| 59 | the discrepancy is visible and fixable, whereas a refused receipt is a |
| 60 | driver standing at the door with a pallet nobody can accept. |
| 61 | |
| 62 | Idempotency by provenance (#7): each move is stamped |
| 63 | `receipts/{receipt_id}:line/{line_id}` in its reference, PER LINE. A |
| 64 | replayed event -- and events are replayed here, by design: the change |
| 65 | dispatcher promises at-least-once (object_change_dispatch.py) -- finds its |
| 66 | own marker and moves nothing. Per line and not per receipt because a |
| 67 | receipt can gain a line while still open, and a receipt-level marker would |
| 68 | silently skip the goods added after the first pass. |
| 69 | |
| 70 | Missing settings do not cost anybody the record that goods arrived. If no |
| 71 | stock location is configured the receipt still stands, the PO status still |
| 72 | derives, and the gap is reported in `warning` -- the same posture |
| 73 | system_order_fulfillment has always had, for the same reason: a missing |
| 74 | location is a five-second fix, and a lost delivery record is not. |
| 75 | """ |
| 76 | |
| 77 | import os |
| 78 | from datetime import date |
| 79 | from decimal import Decimal, InvalidOperation |
| 80 | |
| 81 | import object_ids |
| 82 | import object_records |
| 83 | |
| 84 | HANDLES = [ |
| 85 | "receipts.record.created", |
| 86 | "receipts.record.updated", |
| 87 | "receipt_lines.record.created", |
| 88 | ] |
| 89 | |
| 90 | ACTOR = "system_receipt_posting" |
| 91 | |
| 92 | # The delivery has been signed for: the goods are ours and on the shelf. |
| 93 | RECEIVED_STATUSES = {"received"} |
| 94 | |
| 95 | # A receipt abandoned before anything was counted describes no goods, so |
| 96 | # its lines count for nothing when deriving what has arrived. |
| 97 | NOT_RECEIVED_STATUSES = {"cancelled"} |
| 98 | |
| 99 | # A purchase order in one of these is not something receiving may touch: a |
| 100 | # draft is not a commitment, and a cancelled PO must not quietly come back |
| 101 | # to life because a supplier delivered against it anyway. |
| 102 | UNTOUCHABLE_ORDER_STATUSES = {"draft", "cancelled"} |
| 103 | |
| 104 | |
| 105 | def _base_dir(): |
| 106 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 107 | |
| 108 | |
| 109 | def _text(value): |
| 110 | return str(value if value is not None else "").strip() |
| 111 | |
| 112 | |
| 113 | def _quantity(value): |
| 114 | """Decimal, never a bare float -- quantities may be fractional.""" |
| 115 | try: |
| 116 | return Decimal(_text(value) or "0") |
| 117 | except InvalidOperation: |
| 118 | return Decimal(0) |
| 119 | |
| 120 | |
| 121 | def _number(value): |
| 122 | return format(value.normalize(), "f") |
| 123 | |
| 124 | |
| 125 | def _setting(base, key, default=""): |
| 126 | """Duplicated on purpose, same as every other package that reads |
| 127 | app_settings: there is no shared settings module in this codebase yet, |
| 128 | and inventing one for a fifth copy is the layer this house rule |
| 129 | (docs/logic-decisions.md #4) says to wait on.""" |
| 130 | try: |
| 131 | for row in object_records.read_collection_records("app_settings", |
| 132 | base_dir=base): |
| 133 | if row.get("key") == key and _text(row.get("value")): |
| 134 | return _text(row["value"]) |
| 135 | except Exception: |
| 136 | pass |
| 137 | return default |
| 138 | |
| 139 | |
| 140 | def _receipt_for(request, base): |
| 141 | """The receipt this event is about, whichever collection fired it. |
| 142 | |
| 143 | A receipt_lines event names a line; the thing that matters is its |
| 144 | parent, because a line added to an already-received receipt is goods |
| 145 | that still have to land on the shelf. |
| 146 | |
| 147 | Both the record itself and a bare record_id are accepted: the HTTP |
| 148 | dispatcher and the change-log dispatcher both send record_id, while an |
| 149 | operator poking this by hand (or a sibling handler calling it in |
| 150 | process) has the row already. |
| 151 | """ |
| 152 | collection = _text(request.get("collection")) |
| 153 | record = request.get("record") |
| 154 | record_id = _text(request.get("record_id") or request.get("id")) |
| 155 | |
| 156 | if collection == "receipt_lines": |
| 157 | line = record if isinstance(record, dict) and record.get("id") else None |
| 158 | if line is None and record_id: |
| 159 | try: |
| 160 | line = object_records.get_collection_record( |
| 161 | "receipt_lines", record_id, base_dir=base) |
| 162 | except Exception: |
| 163 | return None |
| 164 | if not line: |
| 165 | return None |
| 166 | record_id = _text(line.get("receipt_id")) |
| 167 | record = None |
| 168 | |
| 169 | if isinstance(record, dict) and record.get("id") and collection != "receipt_lines": |
| 170 | # Re-read rather than trust the payload: an event carrying a stale |
| 171 | # copy (dispatched from the change log, minutes later) must not make |
| 172 | # this handler act on a status the receipt has since moved past. |
| 173 | record_id = _text(record.get("id")) |
| 174 | |
| 175 | if not record_id: |
| 176 | return None |
| 177 | try: |
| 178 | return object_records.get_collection_record("receipts", record_id, |
| 179 | base_dir=base) |
| 180 | except Exception: |
| 181 | return None |
| 182 | |
| 183 | |
| 184 | def _lines_of(base, receipt_id): |
| 185 | try: |
| 186 | rows = object_records.read_collection_records("receipt_lines", |
| 187 | base_dir=base) |
| 188 | except Exception: |
| 189 | return [] |
| 190 | return [row for row in rows if _text(row.get("receipt_id")) == receipt_id] |
| 191 | |
| 192 | |
| 193 | def _order_lines_of(base, order_id): |
| 194 | try: |
| 195 | rows = object_records.read_collection_records("order_lines", |
| 196 | base_dir=base) |
| 197 | except Exception: |
| 198 | return [] |
| 199 | return [row for row in rows if _text(row.get("order_id")) == order_id] |
| 200 | |
| 201 | |
| 202 | def _move_stock(base, receipt, order, moves): |
| 203 | """One purchase move per line, idempotent per line by provenance marker. |
| 204 | |
| 205 | Returns (moved, warning). `moves` is the already-read stock_moves log, |
| 206 | or None when the collection does not exist at all (a shop buying |
| 207 | services has nothing to shelve and is not broken). |
| 208 | """ |
| 209 | if moves is None: |
| 210 | return 0, "stock not installed; nothing to move" |
| 211 | |
| 212 | from_location = _setting(base, "receiving.supplier_location") |
| 213 | to_location = (_setting(base, "receiving.stock_location") |
| 214 | or _setting(base, "shop.stock_location")) |
| 215 | existing = [_text(move.get("reference")) for move in moves] |
| 216 | |
| 217 | # The agreed price per ordered thing, for the cost stamp. Read from the |
| 218 | # PO line rather than from the product: what we are about to own it for |
| 219 | # is what this purchase actually cost, not what the catalog guesses. |
| 220 | prices = {row["id"]: _text(row.get("unit_price_cents")) |
| 221 | for row in _order_lines_of(base, order["id"])} |
| 222 | |
| 223 | moved = 0 |
| 224 | warning = "" |
| 225 | when = _text(receipt.get("received_on")) or date.today().isoformat() |
| 226 | for line in _lines_of(base, receipt["id"]): |
| 227 | product_id = _text(line.get("product_id")) |
| 228 | if not product_id: |
| 229 | continue # a service never sat on a shelf |
| 230 | quantity = _quantity(line.get("quantity_received")) |
| 231 | if quantity <= 0: |
| 232 | # A rejected-only line, or a wholly short delivery. Nothing |
| 233 | # entered stock, so nothing moves; the discrepancy lives on the |
| 234 | # receipt line where the supplier argument can find it. |
| 235 | continue |
| 236 | marker = f"receipts/{receipt['id']}:line/{line['id']}" |
| 237 | if any(marker in reference for reference in existing): |
| 238 | continue # this line already landed |
| 239 | if not to_location: |
| 240 | warning = ("receiving.stock_location (or shop.stock_location) is " |
| 241 | "not configured, so nothing landed on a shelf; the " |
| 242 | "receipt still stands") |
| 243 | break |
| 244 | move = { |
| 245 | "id": object_ids.new_uuid4(), |
| 246 | "product_id": product_id, |
| 247 | "from_location_id": from_location, |
| 248 | "to_location_id": to_location, |
| 249 | "quantity": _number(quantity), |
| 250 | "reason": "purchase", |
| 251 | "reference": f"{marker} {_text(order.get('number'))}".strip(), |
| 252 | "occurred_at": when, |
| 253 | "owner_id": _text(receipt.get("owner_id")), |
| 254 | "entity_id": _text(receipt.get("entity_id")), |
| 255 | } |
| 256 | unit_cost = prices.get(_text(line.get("order_line_id")), "") |
| 257 | if unit_cost: |
| 258 | # The cost on the way IN, stamped at the moment of movement -- |
| 259 | # the input FIFO and weighted average both consume, and the one |
| 260 | # that cannot be reconstructed once the price list moves on. |
| 261 | move["unit_cost_cents"] = unit_cost |
| 262 | object_records.create_collection_record("stock_moves", move, |
| 263 | base_dir=base, actor=ACTOR) |
| 264 | existing.append(marker) |
| 265 | moved += 1 |
| 266 | return moved, warning |
| 267 | |
| 268 | |
| 269 | def _derive_order_status(base, order): |
| 270 | """What the receipt lines say this purchase order's status is. |
| 271 | |
| 272 | Returns "" when the facts say nothing yet (nothing received), so the PO |
| 273 | is left exactly as a human last set it rather than being dragged |
| 274 | backwards by a machine that knows less than they do. |
| 275 | """ |
| 276 | order_lines = _order_lines_of(base, order["id"]) |
| 277 | if not order_lines: |
| 278 | return "" |
| 279 | |
| 280 | try: |
| 281 | receipts = [row for row in object_records.read_collection_records( |
| 282 | "receipts", base_dir=base) |
| 283 | if _text(row.get("order_id")) == order["id"]] |
| 284 | except Exception: |
| 285 | return "" |
| 286 | |
| 287 | counted = {row["id"]: _text(row.get("status")) for row in receipts |
| 288 | if _text(row.get("status")) not in NOT_RECEIVED_STATUSES} |
| 289 | if not counted: |
| 290 | return "" |
| 291 | |
| 292 | try: |
| 293 | all_lines = object_records.read_collection_records("receipt_lines", |
| 294 | base_dir=base) |
| 295 | except Exception: |
| 296 | return "" |
| 297 | |
| 298 | received_by_line = {} |
| 299 | for line in all_lines: |
| 300 | if counted.get(_text(line.get("receipt_id")), "") not in RECEIVED_STATUSES: |
| 301 | continue # an open receipt is a count in |
| 302 | key = _text(line.get("order_line_id")) # progress, not a fact |
| 303 | received_by_line[key] = received_by_line.get(key, Decimal(0)) + \ |
| 304 | _quantity(line.get("quantity_received")) |
| 305 | |
| 306 | if sum(received_by_line.values(), Decimal(0)) <= 0: |
| 307 | return "" |
| 308 | |
| 309 | everything = all( |
| 310 | received_by_line.get(line["id"], Decimal(0)) >= _quantity(line.get("quantity")) |
| 311 | for line in order_lines) |
| 312 | if not everything: |
| 313 | return "partial" |
| 314 | return "received" |
| 315 | |
| 316 | |
| 317 | def EVENT(request): |
| 318 | base = _base_dir() |
| 319 | receipt = _receipt_for(request, base) |
| 320 | if not receipt: |
| 321 | return {"ok": True, "skipped": "no receipt in the event"} |
| 322 | |
| 323 | try: |
| 324 | order = object_records.get_collection_record( |
| 325 | "orders", _text(receipt.get("order_id")), base_dir=base) |
| 326 | except Exception: |
| 327 | return {"ok": True, "skipped": "no order for this receipt", |
| 328 | "receipt_id": receipt["id"]} |
| 329 | |
| 330 | if _text(order.get("doc_type")) != "purchase": |
| 331 | # Belt and braces behind action_receive_goods' refusal: a receipt |
| 332 | # written straight through the HTTP path against a sales order must |
| 333 | # not silently move stock the wrong way. |
| 334 | return {"ok": True, "skipped": "not a purchase order", |
| 335 | "receipt_id": receipt["id"], "order_id": order["id"]} |
| 336 | |
| 337 | order_status = _text(order.get("status")) |
| 338 | if order_status in UNTOUCHABLE_ORDER_STATUSES: |
| 339 | return {"ok": True, "skipped": f"order is {order_status}", |
| 340 | "receipt_id": receipt["id"], "order_id": order["id"]} |
| 341 | |
| 342 | result = {"ok": True, "receipt_id": receipt["id"], "order_id": order["id"], |
| 343 | "moved": 0} |
| 344 | |
| 345 | if _text(receipt.get("status")) in RECEIVED_STATUSES: |
| 346 | try: |
| 347 | moves = object_records.read_collection_records("stock_moves", |
| 348 | base_dir=base) |
| 349 | except Exception: |
| 350 | moves = None |
| 351 | moved, warning = _move_stock(base, receipt, order, moves) |
| 352 | result["moved"] = moved |
| 353 | if warning: |
| 354 | # The receipt stands and the gap is visible, which is the right |
| 355 | # way round: a missing setting must not cost somebody the record |
| 356 | # that goods arrived, and an invisible discrepancy is the one |
| 357 | # nobody fixes. |
| 358 | result["warning"] = warning |
| 359 | |
| 360 | derived = _derive_order_status(base, order) |
| 361 | result["order_status"] = order_status |
| 362 | if derived and derived != order_status: |
| 363 | try: |
| 364 | object_records.update_collection_record( |
| 365 | "orders", order["id"], {"status": derived}, |
| 366 | base_dir=base, actor=ACTOR) |
| 367 | result["order_status"] = derived |
| 368 | result["order_status_changed"] = True |
| 369 | except Exception as exc: |
| 370 | # A ladder that refuses the derived move is a real answer, not a |
| 371 | # crash: say so and leave the order where a human put it. |
| 372 | result["order_status_error"] = str(exc)[:200] |
| 373 | return result |
| 374 | |
| 375 | |
| 376 | # EVENT is the verb the change dispatcher calls handlers with (see |
| 377 | # object_change_dispatch); POST stays as an alias so an operator can poke |
| 378 | # the handler by hand over HTTP. The alias is not decoration -- a handler |
| 379 | # shipped with only POST silently matched nothing in production once, and |
| 380 | # every handler in this house has carried both ever since. |
| 381 | POST = EVENT |