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.
shipment_lines.py · 8.4 KB · 198 lines
| 1 | """Pre-write hook for shipment_lines: you cannot ship what was not ordered, |
| 2 | and you cannot add to a box that has already gone. |
| 3 | |
| 4 | Two gates, both of them things the schema has no way to say. (The order |
| 5 | line has to exist: that is a `relation` on `order_line_id` now, held for |
| 6 | every writer.) |
| 7 | |
| 8 | **Cumulative, not per-line.** The interesting failure is never one line |
| 9 | claiming five of an order line that ordered three -- it is the second |
| 10 | shipment quietly claiming two more after the first already sent two. So |
| 11 | the count is over EVERY shipment line pointing at that order line, and |
| 12 | the refusal shows all three numbers ("ordered 3, already on shipments 2, |
| 13 | this would make 4"), because a gate that only says "no" leaves a packer |
| 14 | guessing which of the two shipments is the wrong one. |
| 15 | |
| 16 | Lines belonging to shipments that were LOST or RETURNED TO SENDER do not |
| 17 | count. Those goods did not reach the customer, the order is still owed |
| 18 | them, and a shop that had to re-send a lost parcel would otherwise be |
| 19 | told it was over-shipping on the replacement -- refused by its own |
| 20 | paperwork for doing exactly the right thing. |
| 21 | |
| 22 | **A settled manifest is settled.** Once a shipment is shipped (or beyond), |
| 23 | its lines are a record of what was physically in the box. A forgotten item |
| 24 | is a NEW shipment, not a retroactive edit to what a courier already took; |
| 25 | otherwise the packing slip in the customer's hands and the row in the |
| 26 | database stop agreeing, and only one of them can be shown to a judge. |
| 27 | |
| 28 | That rule is about the shipment the line is ON as much as the shipment it |
| 29 | is going to. This hook used to read only the shipment_id the line would |
| 30 | have after the write, so a line was moved out of a shipped shipment by |
| 31 | PUTting shipment_id to an open one -- the new parent was open, the hook |
| 32 | passed -- and was then freely editable there: the manifest the courier |
| 33 | took was empty, the order showed 1 of 3 shipped, and 2 could ship again. |
| 34 | An update is now checked against BOTH parents, and a delete (which no |
| 35 | rule grants a signed-in user today, but an admin has) against the one the |
| 36 | line is on. |
| 37 | |
| 38 | (That the quantity is positive is the schema's `exclusive_min: 0`, for every |
| 39 | writer. Direction is what the shipment's direction field is for; a negative |
| 40 | shipment line would be a correction pretending to be a fact -- |
| 41 | docs/logic-decisions.md #3.) |
| 42 | |
| 43 | Trusted server-side writes bypass hooks by design (docs/validation-and-logic.md), |
| 44 | so action_create_shipment carries the same cumulative check itself and |
| 45 | reports every blocker at once, checkout-style. That duplication is |
| 46 | deliberate and named in both files: the hook guards the generic HTTP write |
| 47 | path a form or an API client uses, the action guards the friendly path, |
| 48 | and neither can be removed without opening the other's door. |
| 49 | """ |
| 50 | |
| 51 | import os |
| 52 | from decimal import Decimal, InvalidOperation |
| 53 | |
| 54 | import object_collections |
| 55 | import object_records |
| 56 | |
| 57 | _MISSING = (object_records.RecordNotFoundError, |
| 58 | object_collections.CollectionNotFoundError, |
| 59 | object_records.InvalidRecordIdError) |
| 60 | |
| 61 | # A shipment in one of these never reached the customer, so its lines do |
| 62 | # not consume the order: the goods are still owed and still shippable. |
| 63 | NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"} |
| 64 | |
| 65 | # Once a shipment is in one of these, the box is with a courier or a |
| 66 | # customer and its contents are history, not a draft. |
| 67 | SETTLED_STATUSES = {"shipped", "in_transit", "delivered", |
| 68 | "returned_to_sender", "lost"} |
| 69 | |
| 70 | |
| 71 | def _base_dir(): |
| 72 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 73 | |
| 74 | |
| 75 | def _text(value): |
| 76 | return str(value if value is not None else "").strip() |
| 77 | |
| 78 | |
| 79 | def _quantity(value): |
| 80 | """Decimal, never a bare float: quantities may be fractional (1.5 kg) |
| 81 | and binary-float arithmetic would make an exact-fit shipment round |
| 82 | itself into an over-ship.""" |
| 83 | try: |
| 84 | return Decimal(_text(value) or "0") |
| 85 | except InvalidOperation: |
| 86 | return None |
| 87 | |
| 88 | |
| 89 | def _number(value): |
| 90 | """Render a Decimal the way a human wrote it: 3 not 3.000, 1.5 not 1.50. |
| 91 | The refusal message is read by whoever has to fix the shipment, so the |
| 92 | numbers in it have to look like the numbers on their screen.""" |
| 93 | quantized = value.normalize() |
| 94 | text = format(quantized, "f") |
| 95 | return text |
| 96 | |
| 97 | |
| 98 | def _settled(shipment_id, base): |
| 99 | """A refusal when this shipment has left the dock, so its lines are |
| 100 | history. None for a shipment that does not exist: relation validation |
| 101 | owns that on create/update, and a line with no shipment is on no |
| 102 | manifest. A shipment that exists and cannot be READ is a refusal -- |
| 103 | "could not tell" is not "still open".""" |
| 104 | if not shipment_id: |
| 105 | return None |
| 106 | try: |
| 107 | shipment = object_records.get_collection_record( |
| 108 | "shipments", shipment_id, base_dir=base) |
| 109 | except _MISSING: |
| 110 | return None |
| 111 | except Exception: |
| 112 | return {"error": (f"Shipment {shipment_id} could not be read, so " |
| 113 | f"nothing can say whether it has left the dock. " |
| 114 | f"Nothing was changed."), "status": 503} |
| 115 | shipment_status = _text(shipment.get("status")) |
| 116 | if shipment_status in SETTLED_STATUSES: |
| 117 | return {"error": (f"Shipment {shipment_id} is already " |
| 118 | f"{shipment_status}. A manifest is settled once it " |
| 119 | f"leaves the dock -- a forgotten item is a NEW " |
| 120 | f"shipment against the same order, not a change to " |
| 121 | f"what the courier already took."), |
| 122 | "status": 409} |
| 123 | return None |
| 124 | |
| 125 | |
| 126 | def BEFORE_WRITE(request): |
| 127 | action = _text(request.get("action")) |
| 128 | existing = request.get("existing") or {} |
| 129 | base = _base_dir() |
| 130 | if action == "delete": |
| 131 | return _settled(_text(existing.get("shipment_id")), base) |
| 132 | if action not in ("create", "update"): |
| 133 | return None |
| 134 | record = request.get("record") or {} |
| 135 | |
| 136 | quantity = _quantity(record.get("quantity")) |
| 137 | if quantity is None: |
| 138 | return None # schema validation owns the type error |
| 139 | |
| 140 | shipment_id = _text(record.get("shipment_id")) |
| 141 | parents = [shipment_id] |
| 142 | if action == "update": |
| 143 | # The shipment the line is leaving first: moving a line out of a |
| 144 | # settled manifest is the edit this gate exists to refuse. |
| 145 | parents.insert(0, _text(existing.get("shipment_id"))) |
| 146 | for parent in dict.fromkeys(parents): |
| 147 | refusal = _settled(parent, base) |
| 148 | if refusal: |
| 149 | return refusal |
| 150 | |
| 151 | order_line_id = _text(record.get("order_line_id")) |
| 152 | try: |
| 153 | order_line = object_records.get_collection_record( |
| 154 | "order_lines", order_line_id, base_dir=base) |
| 155 | except _MISSING: |
| 156 | return None # the field's relation validation refuses it |
| 157 | except Exception: |
| 158 | return {"error": (f"Order line {order_line_id} could not be read, so " |
| 159 | f"nothing can say how much was ordered. Nothing " |
| 160 | f"was changed."), "status": 503} |
| 161 | |
| 162 | ordered = _quantity(order_line.get("quantity")) or Decimal(0) |
| 163 | |
| 164 | try: |
| 165 | existing_lines = object_records.read_collection_records( |
| 166 | "shipment_lines", base_dir=base) |
| 167 | except Exception: |
| 168 | return {"error": ("Shipment history unreadable; refusing to ship " |
| 169 | "against an unknown history."), "status": 503} |
| 170 | try: |
| 171 | shipments = {row["id"]: row for row in |
| 172 | object_records.read_collection_records("shipments", |
| 173 | base_dir=base)} |
| 174 | except Exception: |
| 175 | shipments = {} |
| 176 | |
| 177 | record_id = _text(record.get("id")) |
| 178 | already = Decimal(0) |
| 179 | for line in existing_lines: |
| 180 | if _text(line.get("order_line_id")) != order_line_id: |
| 181 | continue |
| 182 | if record_id and _text(line.get("id")) == record_id: |
| 183 | continue # an update replaces its own earlier quantity |
| 184 | parent = shipments.get(_text(line.get("shipment_id"))) or {} |
| 185 | if _text(parent.get("status")) in NOT_DELIVERED_STATUSES: |
| 186 | continue |
| 187 | already += _quantity(line.get("quantity")) or Decimal(0) |
| 188 | |
| 189 | would_be = already + quantity |
| 190 | if would_be > ordered: |
| 191 | return {"error": (f"That would ship more than was ordered: ordered " |
| 192 | f"{_number(ordered)}, already on shipments " |
| 193 | f"{_number(already)}, this would make " |
| 194 | f"{_number(would_be)}. Add the extra to the order " |
| 195 | f"first if the customer really wants more."), |
| 196 | "status": 409} |
| 197 | |
| 198 | return None |