Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
shipment_lines.py · 6.7 KB · 159 lines
1"""Pre-write hook for shipment_lines: you cannot ship what was not ordered,
2and you cannot add to a box that has already gone.
3
4Three gates, all of them things the schema has no way to say.
5
6**Cumulative, not per-line.** The interesting failure is never one line
7claiming five of an order line that ordered three -- it is the second
8shipment quietly claiming two more after the first already sent two. So
9the count is over EVERY shipment line pointing at that order line, and
10the refusal shows all three numbers ("ordered 3, already on shipments 2,
11this would make 4"), because a gate that only says "no" leaves a packer
12guessing which of the two shipments is the wrong one.
13
14Lines belonging to shipments that were LOST or RETURNED TO SENDER do not
15count. Those goods did not reach the customer, the order is still owed
16them, and a shop that had to re-send a lost parcel would otherwise be
17told it was over-shipping on the replacement -- refused by its own
18paperwork for doing exactly the right thing.
19
20**A settled manifest is settled.** Once a shipment is shipped (or beyond),
21its lines are a record of what was physically in the box. A forgotten item
22is a NEW shipment, not a retroactive edit to what a courier already took;
23otherwise the packing slip in the customer's hands and the row in the
24database stop agreeing, and only one of them can be shown to a judge.
25
26**Quantity must be positive.** Direction is what the shipment's direction
27field is for; a negative shipment line would be a correction pretending to
28be a fact (docs/logic-decisions.md #3).
29
30Trusted server-side writes bypass hooks by design (docs/validation-and-logic.md),
31so action_create_shipment carries the same cumulative check itself and
32reports every blocker at once, checkout-style. That duplication is
33deliberate and named in both files: the hook guards the generic HTTP write
34path a form or an API client uses, the action guards the friendly path,
35and neither can be removed without opening the other's door.
36"""
37
38import os
39from decimal import Decimal, InvalidOperation
40
41import object_records
42
43# A shipment in one of these never reached the customer, so its lines do
44# not consume the order: the goods are still owed and still shippable.
45NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"}
46
47# Once a shipment is in one of these, the box is with a courier or a
48# customer and its contents are history, not a draft.
49SETTLED_STATUSES = {"shipped", "in_transit", "delivered",
50 "returned_to_sender", "lost"}
51
52
53def _base_dir():
54 return os.environ.get("DBBASIC_DATA_DIR", "data")
55
56
57def _text(value):
58 return str(value if value is not None else "").strip()
59
60
61def _quantity(value):
62 """Decimal, never a bare float: quantities may be fractional (1.5 kg)
63 and binary-float arithmetic would make an exact-fit shipment round
64 itself into an over-ship."""
65 try:
66 return Decimal(_text(value) or "0")
67 except InvalidOperation:
68 return None
69
70
71def _number(value):
72 """Render a Decimal the way a human wrote it: 3 not 3.000, 1.5 not 1.50.
73 The refusal message is read by whoever has to fix the shipment, so the
74 numbers in it have to look like the numbers on their screen."""
75 quantized = value.normalize()
76 text = format(quantized, "f")
77 return text
78
79
80def BEFORE_WRITE(request):
81 action = _text(request.get("action"))
82 if action not in ("create", "update"):
83 return None
84 record = request.get("record") or {}
85 base = _base_dir()
86
87 quantity = _quantity(record.get("quantity"))
88 if quantity is None:
89 return None # schema validation owns the type error
90 if quantity <= 0:
91 return {"error": ("A shipment line must ship a positive quantity. "
92 "Nothing physically moved is what an absent line "
93 "means, and a correction is a new document, never "
94 "a negative row."),
95 "status": 400}
96
97 shipment_id = _text(record.get("shipment_id"))
98 try:
99 shipment = object_records.get_collection_record(
100 "shipments", shipment_id, base_dir=base)
101 except Exception:
102 return None # relation validation owns a missing shipment
103 shipment_status = _text(shipment.get("status"))
104 if shipment_status in SETTLED_STATUSES:
105 return {"error": (f"Shipment {shipment_id} is already "
106 f"{shipment_status}. A manifest is settled once it "
107 f"leaves the dock -- a forgotten item is a NEW "
108 f"shipment against the same order, not a change to "
109 f"what the courier already took."),
110 "status": 409}
111
112 order_line_id = _text(record.get("order_line_id"))
113 try:
114 order_line = object_records.get_collection_record(
115 "order_lines", order_line_id, base_dir=base)
116 except Exception:
117 return {"error": (f"No such order line: {order_line_id or '(blank)'}. "
118 f"A shipment line has to say which ordered thing it "
119 f"satisfies, or nothing can tell whether the "
120 f"customer got what they paid for."),
121 "status": 400}
122
123 ordered = _quantity(order_line.get("quantity")) or Decimal(0)
124
125 try:
126 existing_lines = object_records.read_collection_records(
127 "shipment_lines", base_dir=base)
128 except Exception:
129 return {"error": ("Shipment history unreadable; refusing to ship "
130 "against an unknown history."), "status": 503}
131 try:
132 shipments = {row["id"]: row for row in
133 object_records.read_collection_records("shipments",
134 base_dir=base)}
135 except Exception:
136 shipments = {}
137
138 record_id = _text(record.get("id"))
139 already = Decimal(0)
140 for line in existing_lines:
141 if _text(line.get("order_line_id")) != order_line_id:
142 continue
143 if record_id and _text(line.get("id")) == record_id:
144 continue # an update replaces its own earlier quantity
145 parent = shipments.get(_text(line.get("shipment_id"))) or {}
146 if _text(parent.get("status")) in NOT_DELIVERED_STATUSES:
147 continue
148 already += _quantity(line.get("quantity")) or Decimal(0)
149
150 would_be = already + quantity
151 if would_be > ordered:
152 return {"error": (f"That would ship more than was ordered: ordered "
153 f"{_number(ordered)}, already on shipments "
154 f"{_number(already)}, this would make "
155 f"{_number(would_be)}. Add the extra to the order "
156 f"first if the customer really wants more."),
157 "status": 409}
158
159 return None