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.
receive_goods.py · 18.8 KB · 409 lines
| 1 | """action_receive_goods -- the pallet, turned into a fact. |
| 2 | |
| 3 | POST {order_id, lines?: [{order_line_id, quantity_received, |
| 4 | quantity_rejected?, discrepancy_note?}], supplier_reference?, |
| 5 | received_on?} |
| 6 | |
| 7 | Defaults to EVERYTHING still outstanding on the purchase order, at the |
| 8 | full expected quantity, because that is what the overwhelming majority of |
| 9 | deliveries are: the supplier sent what was ordered and somebody wants one |
| 10 | button that says so. Passing `lines` is the interesting case -- eight of |
| 11 | the ten arrived and two cartons were crushed -- and the remainder simply |
| 12 | stays outstanding until a second delivery carries it. That is the entire |
| 13 | mechanism behind a partly-received PO: a second document, not a flag, and |
| 14 | orders.status follows from counting rather than from somebody remembering |
| 15 | to set it. |
| 16 | |
| 17 | **A sales order is refused in words**, not with a validation code. Goods |
| 18 | LEAVE on a shipment and ARRIVE on a receipt; the two documents share a |
| 19 | schema (orders.doc_type) precisely so that the direction has to be stated |
| 20 | rather than assumed, and somebody who reached this action with an SO has a |
| 21 | model of the system worth correcting on the spot. |
| 22 | |
| 23 | Every blocker is reported TOGETHER, the way checkout does it. Revealing |
| 24 | one problem, letting the receiver fix it, then revealing the next is how a |
| 25 | warehouse screen gets abandoned in favour of a spreadsheet -- and the |
| 26 | person doing this is standing up, in the cold, with a driver waiting. |
| 27 | |
| 28 | Nothing outstanding is deliberately NOT an error. A double-clicked |
| 29 | "Receive" button, or a handler that fires twice, must not produce a 500 |
| 30 | and must not produce a second empty receipt: it returns ok with a note |
| 31 | saying the PO is fully received already. Idempotency by observable state, |
| 32 | which is the only kind that survives a retry (docs/logic-decisions.md #7). |
| 33 | That state is read only under a claim on the purchase order |
| 34 | (orders.action_claim, object_claims): read without one, four overlapping |
| 35 | clicks all saw the whole PO outstanding and booked it four times. A click |
| 36 | that finds the order claimed is answered 409 in_progress. |
| 37 | |
| 38 | The receipt is raised `open` and then moved to `received` in the same |
| 39 | pass, rather than created `received` outright: the ladder is what |
| 40 | system_receipt_posting reacts to, and a document that was never open for |
| 41 | even an instant would make the check-in-in-progress state -- a real state, |
| 42 | where a pallet is on the floor and half-counted -- unreachable through the |
| 43 | one path everybody uses. |
| 44 | |
| 45 | **Only someone who may update the purchase order may receive against it.** |
| 46 | Every write below is a trusted server-side write, so this object is the |
| 47 | only gate in front of them; it used to let any signed-in user book a |
| 48 | receipt (and, through system_receipt_posting, shelve stock) against |
| 49 | anybody's purchase order. The permission engine is asked through |
| 50 | object_access, so the answer is the one the orders API would give, and a |
| 51 | refused order reads exactly like a missing one. |
| 52 | |
| 53 | **`lines` absent means everything; `lines` present must name something.** |
| 54 | Omitting the key is the one-button default above. An empty list, a |
| 55 | string, or a single object is a different request -- a client that |
| 56 | selected nothing, or a payload that got mangled -- and is refused rather |
| 57 | than read as "receive the whole PO". And the cap is a RUNNING one: each |
| 58 | accepted entry takes its quantity off what is still outstanding, so the |
| 59 | same PO line listed twice cannot receive twice what was ordered. |
| 60 | |
| 61 | **What has already been received must be readable.** An unreadable |
| 62 | receipt history is not an empty one: read as empty it says nothing has |
| 63 | arrived, and the whole order is received (and shelved) a second time. The |
| 64 | action refuses with 503 instead, as hook_receipt_lines does. |
| 65 | |
| 66 | The over-receiving arithmetic here is a deliberate second copy of |
| 67 | hook_receipt_lines' gate, named in both files: trusted server-side writes |
| 68 | bypass hooks by design, so the action that writes the lines has to carry |
| 69 | the check, and the hook has to keep it for the generic HTTP write path. |
| 70 | What the action adds is the friendly all-at-once report; what the hook |
| 71 | adds is that no other door is open. |
| 72 | """ |
| 73 | |
| 74 | import os |
| 75 | from datetime import date |
| 76 | from decimal import Decimal, InvalidOperation |
| 77 | |
| 78 | import object_access |
| 79 | import object_claims |
| 80 | import object_collections |
| 81 | import object_ids |
| 82 | import object_records |
| 83 | |
| 84 | ACTOR = "action_receive_goods" |
| 85 | |
| 86 | # A receipt abandoned before anything was counted describes no goods, so |
| 87 | # its lines do not consume the ordered quantity. |
| 88 | NOT_RECEIVED_STATUSES = {"cancelled"} |
| 89 | |
| 90 | |
| 91 | def _base_dir(): |
| 92 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 93 | |
| 94 | |
| 95 | def _text(value): |
| 96 | return str(value if value is not None else "").strip() |
| 97 | |
| 98 | |
| 99 | def _quantity(value): |
| 100 | try: |
| 101 | return Decimal(_text(value) or "0") |
| 102 | except InvalidOperation: |
| 103 | return None |
| 104 | |
| 105 | |
| 106 | def _number(value): |
| 107 | return format(value.normalize(), "f") |
| 108 | |
| 109 | |
| 110 | class HistoryUnreadable(Exception): |
| 111 | """What has already been received cannot be read, so what is still |
| 112 | outstanding is unknown.""" |
| 113 | |
| 114 | |
| 115 | def _history(base, collection): |
| 116 | """Every row of `collection`; [] only when it is not installed (a fact), |
| 117 | HistoryUnreadable for anything else (an unknown).""" |
| 118 | try: |
| 119 | # access: history and receipts of the purchase order read through Access above |
| 120 | return object_records.read_collection_records(collection, base_dir=base) |
| 121 | except object_collections.CollectionNotFoundError: |
| 122 | return [] |
| 123 | except Exception as exc: |
| 124 | raise HistoryUnreadable(f"{collection}: {str(exc)[:160]}") from exc |
| 125 | |
| 126 | |
| 127 | def _outstanding_by_line(base, order_lines): |
| 128 | """How much of each PO line is still owed by the supplier: ordered minus |
| 129 | everything already received on a receipt that was not cancelled. |
| 130 | |
| 131 | Raises HistoryUnreadable rather than folding an unreadable history to |
| 132 | "nothing received yet" (see the module docstring). |
| 133 | """ |
| 134 | receipts = _history(base, "receipts") |
| 135 | counted = {row["id"] for row in receipts |
| 136 | if _text(row.get("status")) not in NOT_RECEIVED_STATUSES} |
| 137 | lines = _history(base, "receipt_lines") |
| 138 | |
| 139 | received = {} |
| 140 | for line in lines: |
| 141 | if _text(line.get("receipt_id")) not in counted: |
| 142 | continue |
| 143 | key = _text(line.get("order_line_id")) |
| 144 | received[key] = received.get(key, Decimal(0)) + ( |
| 145 | _quantity(line.get("quantity_received")) or Decimal(0)) |
| 146 | |
| 147 | outstanding = {} |
| 148 | for line in order_lines: |
| 149 | ordered = _quantity(line.get("quantity")) or Decimal(0) |
| 150 | outstanding[line["id"]] = ordered - received.get(line["id"], Decimal(0)) |
| 151 | return outstanding |
| 152 | |
| 153 | |
| 154 | def POST(request): |
| 155 | base = _base_dir() |
| 156 | order_id = _text(request.get("order_id")) |
| 157 | if not order_id: |
| 158 | return {"status": 400, "error": "order_id is required"} |
| 159 | |
| 160 | # Asked before any other refusal, so the 409s below (which describe |
| 161 | # the order) are only shown to somebody allowed to change it. |
| 162 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 163 | try: |
| 164 | order = access.get("orders", order_id, action="update") |
| 165 | except Exception: |
| 166 | order = None |
| 167 | if order is None: |
| 168 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 169 | |
| 170 | # THE CLAIM, before anything already received is read. "Nothing |
| 171 | # outstanding" was the only guard against a double click, and it is |
| 172 | # read before anything is written: four clicks on "Receive everything" |
| 173 | # for a PO of 10 all read 10 outstanding and booked 40, which |
| 174 | # system_receipt_posting then shelves. Only the request holding |
| 175 | # orders.action_claim reads and writes; any other is answered 409 |
| 176 | # in_progress with nothing written. |
| 177 | try: |
| 178 | claim, order = object_claims.take("orders", order_id, base_dir=base, |
| 179 | actor=ACTOR) |
| 180 | except object_claims.Busy: |
| 181 | return object_claims.busy_answer("purchase order", order_id) |
| 182 | except object_records.RecordNotFoundError: |
| 183 | return {"status": 404, "error": f"No such order: {order_id}"} |
| 184 | except Exception as exc: |
| 185 | return {"status": 503, |
| 186 | "error": (f"This purchase order cannot be claimed right now " |
| 187 | f"({str(exc)[:120]}), so nothing was received. Try " |
| 188 | f"again in a moment.")} |
| 189 | try: |
| 190 | return _receive(base, request, access, order, order_id) |
| 191 | finally: |
| 192 | object_claims.release("orders", order_id, claim, base_dir=base, |
| 193 | actor=ACTOR) |
| 194 | |
| 195 | |
| 196 | def _receive(base, request, access, order, order_id): |
| 197 | """Everything after the claim: read what is outstanding, decide, write.""" |
| 198 | doc_type = _text(order.get("doc_type")) or "sale" |
| 199 | if doc_type != "purchase": |
| 200 | return {"status": 409, |
| 201 | "error": ("This is a sales order -- goods leave on a shipment, " |
| 202 | "they do not arrive on a receipt. If a customer is " |
| 203 | "sending something back, that is an inbound shipment " |
| 204 | "against this order, not a receipt against a " |
| 205 | "purchase order.")} |
| 206 | |
| 207 | if _text(order.get("fulfillment_source")) == "dropship": |
| 208 | return {"status": 409, |
| 209 | "error": ("This purchase order is drop-shipped -- the vendor " |
| 210 | "sends it straight to the customer, so it never " |
| 211 | "arrives at a dock of ours to be checked in. " |
| 212 | "Receiving it would shelve stock nobody here has " |
| 213 | "ever seen, and every count from then on would " |
| 214 | "disagree with the room. Track it on the linked " |
| 215 | "sales order instead.")} |
| 216 | |
| 217 | order_status = _text(order.get("status")) |
| 218 | if order_status in ("draft", "cancelled"): |
| 219 | return {"status": 409, |
| 220 | "error": (f"This purchase order is {order_status}. Commit " |
| 221 | f"before you receive -- booking goods in against a " |
| 222 | f"draft would create stock for a purchase nobody has " |
| 223 | f"agreed to, and against a cancelled one would " |
| 224 | f"quietly accept a delivery we told the supplier to " |
| 225 | f"stop.")} |
| 226 | |
| 227 | try: |
| 228 | # access: history and receipts of the purchase order read through Access above |
| 229 | all_lines = object_records.read_collection_records("order_lines", |
| 230 | base_dir=base) |
| 231 | except Exception: |
| 232 | return {"status": 503, |
| 233 | "error": ("The lines of this purchase order cannot be read " |
| 234 | "right now, so nothing was received. Try again in a " |
| 235 | "moment.")} |
| 236 | order_lines = [line for line in all_lines |
| 237 | if _text(line.get("order_id")) == order_id] |
| 238 | if not order_lines: |
| 239 | return {"status": 409, |
| 240 | "error": "This purchase order has no lines, so there is " |
| 241 | "nothing anybody could be delivering against it."} |
| 242 | |
| 243 | by_id = {line["id"]: line for line in order_lines} |
| 244 | try: |
| 245 | outstanding = _outstanding_by_line(base, order_lines) |
| 246 | except HistoryUnreadable as exc: |
| 247 | return {"status": 503, |
| 248 | "error": (f"What has already been received on this purchase " |
| 249 | f"order cannot be read right now ({exc}), so how much " |
| 250 | f"is still outstanding is unknown and nothing was " |
| 251 | f"received. Try again in a moment.")} |
| 252 | |
| 253 | requested = request.get("lines") |
| 254 | blockers = {"unknown_lines": [], "over_receive": [], "bad_quantities": []} |
| 255 | |
| 256 | if requested is None: |
| 257 | # The default and the common case: the supplier sent what was |
| 258 | # ordered, and everything still outstanding turned up today. Only an |
| 259 | # ABSENT `lines` means this (see the module docstring). |
| 260 | wanted = [(by_id[line_id], left, Decimal(0), "") |
| 261 | for line_id, left in outstanding.items() if left > 0] |
| 262 | wanted.sort(key=lambda entry: _text(entry[0].get("description"))) |
| 263 | elif not isinstance(requested, list) or not requested: |
| 264 | wanted = [] |
| 265 | blockers["bad_quantities"].append( |
| 266 | {"order_line_id": "", |
| 267 | "reason": ("`lines` must be a non-empty list of " |
| 268 | "{order_line_id, quantity_received}. Leave it out " |
| 269 | "altogether to receive everything outstanding; an " |
| 270 | "empty or malformed value is not read as 'all'.")}) |
| 271 | else: |
| 272 | wanted = [] |
| 273 | # A RUNNING cap: each accepted entry is taken off what is still |
| 274 | # outstanding, so the same line named twice is checked against what |
| 275 | # the first entry left rather than against the original snapshot. |
| 276 | left_by_line = dict(outstanding) |
| 277 | for entry in requested: |
| 278 | if not isinstance(entry, dict): |
| 279 | blockers["bad_quantities"].append( |
| 280 | {"order_line_id": "", "reason": "line is not an object"}) |
| 281 | continue |
| 282 | line_id = _text(entry.get("order_line_id")) |
| 283 | if line_id not in by_id: |
| 284 | blockers["unknown_lines"].append(line_id) |
| 285 | continue |
| 286 | received = _quantity(entry.get("quantity_received")) |
| 287 | rejected = _quantity(entry.get("quantity_rejected")) |
| 288 | note = _text(entry.get("discrepancy_note")) |
| 289 | if received is None or rejected is None: |
| 290 | blockers["bad_quantities"].append( |
| 291 | {"order_line_id": line_id, |
| 292 | "quantity_received": _text(entry.get("quantity_received")), |
| 293 | "reason": "quantities must be numbers"}) |
| 294 | continue |
| 295 | if received < 0 or rejected < 0: |
| 296 | blockers["bad_quantities"].append( |
| 297 | {"order_line_id": line_id, |
| 298 | "quantity_received": _number(received), |
| 299 | "reason": "a receipt line cannot receive or reject a " |
| 300 | "negative quantity"}) |
| 301 | continue |
| 302 | if received == 0 and rejected == 0 and not note: |
| 303 | blockers["bad_quantities"].append( |
| 304 | {"order_line_id": line_id, |
| 305 | "quantity_received": "0", |
| 306 | "reason": "a line that received nothing must say why: " |
| 307 | "give a rejected quantity or a discrepancy " |
| 308 | "note"}) |
| 309 | continue |
| 310 | left = left_by_line.get(line_id, Decimal(0)) |
| 311 | if received > left: |
| 312 | ordered = _quantity(by_id[line_id].get("quantity")) or Decimal(0) |
| 313 | blockers["over_receive"].append({ |
| 314 | "order_line_id": line_id, |
| 315 | "description": _text(by_id[line_id].get("description")), |
| 316 | "ordered": _number(ordered), |
| 317 | # Received before this request, plus what earlier |
| 318 | # entries of this same request already claimed. |
| 319 | "already_received": _number(ordered - left), |
| 320 | "asked_for": _number(received), |
| 321 | "would_make": _number(ordered - left + received), |
| 322 | }) |
| 323 | continue |
| 324 | left_by_line[line_id] = left - received |
| 325 | wanted.append((by_id[line_id], received, rejected, note)) |
| 326 | |
| 327 | if any(blockers.values()): |
| 328 | return {"status": 409, |
| 329 | "error": "Some of those lines cannot be received.", |
| 330 | **blockers} |
| 331 | |
| 332 | if not wanted: |
| 333 | # Not an error. A second click, or a handler that fired twice, must |
| 334 | # not 500 and must not raise an empty second receipt. |
| 335 | return {"ok": True, "order_id": order_id, "receipt_id": "", "lines": 0, |
| 336 | "note": "nothing outstanding on this purchase order; every " |
| 337 | "ordered quantity has already been received"} |
| 338 | |
| 339 | owner = _text(order.get("owner_id")) or access.user_id |
| 340 | receipt_id = object_ids.new_uuid4() |
| 341 | received_on = _text(request.get("received_on")) or date.today().isoformat() |
| 342 | provenance = f"Generated by {ACTOR} [orders/{order_id}]" |
| 343 | |
| 344 | # access: history and receipts of the purchase order read through Access above |
| 345 | object_records.create_collection_record( |
| 346 | "receipts", |
| 347 | { |
| 348 | "id": receipt_id, |
| 349 | "order_id": order_id, |
| 350 | "status": "open", |
| 351 | "received_on": received_on, |
| 352 | "supplier_reference": _text(request.get("supplier_reference")), |
| 353 | "notes": provenance, |
| 354 | "owner_id": owner, |
| 355 | "entity_id": _text(order.get("entity_id")), |
| 356 | }, |
| 357 | base_dir=base, actor=ACTOR) |
| 358 | |
| 359 | created = [] |
| 360 | for order_line, received, rejected, note in wanted: |
| 361 | line_id = object_ids.new_uuid4() |
| 362 | expected = _quantity(order_line.get("quantity")) or Decimal(0) |
| 363 | # access: history and receipts of the purchase order read through Access above |
| 364 | object_records.create_collection_record( |
| 365 | "receipt_lines", |
| 366 | { |
| 367 | "id": line_id, |
| 368 | "receipt_id": receipt_id, |
| 369 | "order_line_id": order_line["id"], |
| 370 | "product_id": _text(order_line.get("product_id")), |
| 371 | # Stamped from the order line: a sheet printed next year must |
| 372 | # still say what the dock counted off the pallet. |
| 373 | "description": _text(order_line.get("description")), |
| 374 | "quantity_expected": _number(expected), |
| 375 | "quantity_received": _number(received), |
| 376 | "quantity_rejected": _number(rejected), |
| 377 | "discrepancy_note": note, |
| 378 | "owner_id": owner, |
| 379 | }, |
| 380 | base_dir=base, actor=ACTOR) |
| 381 | created.append({"id": line_id, "order_line_id": order_line["id"], |
| 382 | "description": _text(order_line.get("description")), |
| 383 | "quantity_expected": _number(expected), |
| 384 | "quantity_received": _number(received), |
| 385 | "quantity_rejected": _number(rejected)}) |
| 386 | |
| 387 | # Open first, then received: the ladder is what system_receipt_posting |
| 388 | # reacts to, and check-in-in-progress is a real state this path must not |
| 389 | # make unreachable. |
| 390 | # access: history and receipts of the purchase order read through Access above |
| 391 | object_records.update_collection_record( |
| 392 | "receipts", receipt_id, {"status": "received"}, |
| 393 | base_dir=base, actor=ACTOR) |
| 394 | |
| 395 | still_owed = sum( |
| 396 | (left for left in outstanding.values() if left > 0), |
| 397 | Decimal(0)) - sum((received for _, received, _, _ in wanted), Decimal(0)) |
| 398 | rejected_total = sum((rejected for _, _, rejected, _ in wanted), Decimal(0)) |
| 399 | |
| 400 | return {"ok": True, "order_id": order_id, "receipt_id": receipt_id, |
| 401 | "status_of_receipt": "received", "lines": len(created), |
| 402 | "receipt_lines": created, |
| 403 | "still_outstanding": _number(still_owed), |
| 404 | "rejected": _number(rejected_total), |
| 405 | "sheet_path": f"/purchase-orders/{order_id}/receive", |
| 406 | "received_on": received_on, |
| 407 | "note": "receipt signed off; stock moves one purchase move per " |
| 408 | "line for what was received, and nothing for what was " |
| 409 | "rejected"} |