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
receive_goods.py · 13.5 KB · 308 lines
1"""action_receive_goods -- the pallet, turned into a fact.
2
3POST {order_id, lines?: [{order_line_id, quantity_received,
4 quantity_rejected?, discrepancy_note?}], supplier_reference?,
5 received_on?}
6
7Defaults to EVERYTHING still outstanding on the purchase order, at the
8full expected quantity, because that is what the overwhelming majority of
9deliveries are: the supplier sent what was ordered and somebody wants one
10button that says so. Passing `lines` is the interesting case -- eight of
11the ten arrived and two cartons were crushed -- and the remainder simply
12stays outstanding until a second delivery carries it. That is the entire
13mechanism behind a partly-received PO: a second document, not a flag, and
14orders.status follows from counting rather than from somebody remembering
15to set it.
16
17**A sales order is refused in words**, not with a validation code. Goods
18LEAVE on a shipment and ARRIVE on a receipt; the two documents share a
19schema (orders.doc_type) precisely so that the direction has to be stated
20rather than assumed, and somebody who reached this action with an SO has a
21model of the system worth correcting on the spot.
22
23Every blocker is reported TOGETHER, the way checkout does it. Revealing
24one problem, letting the receiver fix it, then revealing the next is how a
25warehouse screen gets abandoned in favour of a spreadsheet -- and the
26person doing this is standing up, in the cold, with a driver waiting.
27
28Nothing outstanding is deliberately NOT an error. A double-clicked
29"Receive" button, or a handler that fires twice, must not produce a 500
30and must not produce a second empty receipt: it returns ok with a note
31saying the PO is fully received already. Idempotency by observable state,
32which is the only kind that survives a retry (docs/logic-decisions.md #7).
33
34The receipt is raised `open` and then moved to `received` in the same
35pass, rather than created `received` outright: the ladder is what
36system_receipt_posting reacts to, and a document that was never open for
37even an instant would make the check-in-in-progress state -- a real state,
38where a pallet is on the floor and half-counted -- unreachable through the
39one path everybody uses.
40
41The over-receiving arithmetic here is a deliberate second copy of
42hook_receipt_lines' gate, named in both files: trusted server-side writes
43bypass hooks by design, so the action that writes the lines has to carry
44the check, and the hook has to keep it for the generic HTTP write path.
45What the action adds is the friendly all-at-once report; what the hook
46adds is that no other door is open.
47"""
48
49import os
50from datetime import date
51from decimal import Decimal, InvalidOperation
52
53import object_ids
54import object_records
55
56ACTOR = "action_receive_goods"
57
58# A receipt abandoned before anything was counted describes no goods, so
59# its lines do not consume the ordered quantity.
60NOT_RECEIVED_STATUSES = {"cancelled"}
61
62
63def _base_dir():
64 return os.environ.get("DBBASIC_DATA_DIR", "data")
65
66
67def _text(value):
68 return str(value if value is not None else "").strip()
69
70
71def _quantity(value):
72 try:
73 return Decimal(_text(value) or "0")
74 except InvalidOperation:
75 return None
76
77
78def _number(value):
79 return format(value.normalize(), "f")
80
81
82def _outstanding_by_line(base, order_lines):
83 """How much of each PO line is still owed by the supplier: ordered minus
84 everything already received on a receipt that was not cancelled.
85 """
86 try:
87 receipts = object_records.read_collection_records("receipts",
88 base_dir=base)
89 except Exception:
90 receipts = []
91 counted = {row["id"] for row in receipts
92 if _text(row.get("status")) not in NOT_RECEIVED_STATUSES}
93 try:
94 lines = object_records.read_collection_records("receipt_lines",
95 base_dir=base)
96 except Exception:
97 lines = []
98
99 received = {}
100 for line in lines:
101 if _text(line.get("receipt_id")) not in counted:
102 continue
103 key = _text(line.get("order_line_id"))
104 received[key] = received.get(key, Decimal(0)) + (
105 _quantity(line.get("quantity_received")) or Decimal(0))
106
107 outstanding = {}
108 for line in order_lines:
109 ordered = _quantity(line.get("quantity")) or Decimal(0)
110 outstanding[line["id"]] = ordered - received.get(line["id"], Decimal(0))
111 return outstanding
112
113
114def POST(request):
115 base = _base_dir()
116 order_id = _text(request.get("order_id"))
117 if not order_id:
118 return {"status": 400, "error": "order_id is required"}
119
120 try:
121 order = object_records.get_collection_record("orders", order_id,
122 base_dir=base)
123 except Exception:
124 return {"status": 404, "error": f"No such order: {order_id}"}
125
126 doc_type = _text(order.get("doc_type")) or "sale"
127 if doc_type != "purchase":
128 return {"status": 409,
129 "error": ("This is a sales order -- goods leave on a shipment, "
130 "they do not arrive on a receipt. If a customer is "
131 "sending something back, that is an inbound shipment "
132 "against this order, not a receipt against a "
133 "purchase order.")}
134
135 if _text(order.get("fulfillment_source")) == "dropship":
136 return {"status": 409,
137 "error": ("This purchase order is drop-shipped -- the vendor "
138 "sends it straight to the customer, so it never "
139 "arrives at a dock of ours to be checked in. "
140 "Receiving it would shelve stock nobody here has "
141 "ever seen, and every count from then on would "
142 "disagree with the room. Track it on the linked "
143 "sales order instead.")}
144
145 order_status = _text(order.get("status"))
146 if order_status in ("draft", "cancelled"):
147 return {"status": 409,
148 "error": (f"This purchase order is {order_status}. Commit "
149 f"before you receive -- booking goods in against a "
150 f"draft would create stock for a purchase nobody has "
151 f"agreed to, and against a cancelled one would "
152 f"quietly accept a delivery we told the supplier to "
153 f"stop.")}
154
155 try:
156 all_lines = object_records.read_collection_records("order_lines",
157 base_dir=base)
158 except Exception:
159 all_lines = []
160 order_lines = [line for line in all_lines
161 if _text(line.get("order_id")) == order_id]
162 if not order_lines:
163 return {"status": 409,
164 "error": "This purchase order has no lines, so there is "
165 "nothing anybody could be delivering against it."}
166
167 by_id = {line["id"]: line for line in order_lines}
168 outstanding = _outstanding_by_line(base, order_lines)
169
170 requested = request.get("lines")
171 blockers = {"unknown_lines": [], "over_receive": [], "bad_quantities": []}
172
173 if isinstance(requested, list) and requested:
174 wanted = []
175 for entry in requested:
176 if not isinstance(entry, dict):
177 blockers["bad_quantities"].append(
178 {"order_line_id": "", "reason": "line is not an object"})
179 continue
180 line_id = _text(entry.get("order_line_id"))
181 if line_id not in by_id:
182 blockers["unknown_lines"].append(line_id)
183 continue
184 received = _quantity(entry.get("quantity_received"))
185 rejected = _quantity(entry.get("quantity_rejected"))
186 note = _text(entry.get("discrepancy_note"))
187 if received is None or rejected is None:
188 blockers["bad_quantities"].append(
189 {"order_line_id": line_id,
190 "quantity_received": _text(entry.get("quantity_received")),
191 "reason": "quantities must be numbers"})
192 continue
193 if received < 0 or rejected < 0:
194 blockers["bad_quantities"].append(
195 {"order_line_id": line_id,
196 "quantity_received": _number(received),
197 "reason": "a receipt line cannot receive or reject a "
198 "negative quantity"})
199 continue
200 if received == 0 and rejected == 0 and not note:
201 blockers["bad_quantities"].append(
202 {"order_line_id": line_id,
203 "quantity_received": "0",
204 "reason": "a line that received nothing must say why: "
205 "give a rejected quantity or a discrepancy "
206 "note"})
207 continue
208 left = outstanding.get(line_id, Decimal(0))
209 if received > left:
210 ordered = _quantity(by_id[line_id].get("quantity")) or Decimal(0)
211 blockers["over_receive"].append({
212 "order_line_id": line_id,
213 "description": _text(by_id[line_id].get("description")),
214 "ordered": _number(ordered),
215 "already_received": _number(ordered - left),
216 "asked_for": _number(received),
217 "would_make": _number(ordered - left + received),
218 })
219 continue
220 wanted.append((by_id[line_id], received, rejected, note))
221 else:
222 # The default and the common case: the supplier sent what was
223 # ordered, and everything still outstanding turned up today.
224 wanted = [(by_id[line_id], left, Decimal(0), "")
225 for line_id, left in outstanding.items() if left > 0]
226 wanted.sort(key=lambda entry: _text(entry[0].get("description")))
227
228 if any(blockers.values()):
229 return {"status": 409,
230 "error": "Some of those lines cannot be received.",
231 **blockers}
232
233 if not wanted:
234 # Not an error. A second click, or a handler that fired twice, must
235 # not 500 and must not raise an empty second receipt.
236 return {"ok": True, "order_id": order_id, "receipt_id": "", "lines": 0,
237 "note": "nothing outstanding on this purchase order; every "
238 "ordered quantity has already been received"}
239
240 owner = (_text(order.get("owner_id"))
241 or _text((request.get("_identity") or {}).get("user_id")))
242 receipt_id = object_ids.new_uuid4()
243 received_on = _text(request.get("received_on")) or date.today().isoformat()
244 provenance = f"Generated by {ACTOR} [orders/{order_id}]"
245
246 object_records.create_collection_record(
247 "receipts",
248 {
249 "id": receipt_id,
250 "order_id": order_id,
251 "status": "open",
252 "received_on": received_on,
253 "supplier_reference": _text(request.get("supplier_reference")),
254 "notes": provenance,
255 "owner_id": owner,
256 "entity_id": _text(order.get("entity_id")),
257 },
258 base_dir=base, actor=ACTOR)
259
260 created = []
261 for order_line, received, rejected, note in wanted:
262 line_id = object_ids.new_uuid4()
263 expected = _quantity(order_line.get("quantity")) or Decimal(0)
264 object_records.create_collection_record(
265 "receipt_lines",
266 {
267 "id": line_id,
268 "receipt_id": receipt_id,
269 "order_line_id": order_line["id"],
270 "product_id": _text(order_line.get("product_id")),
271 # Stamped from the order line: a sheet printed next year must
272 # still say what the dock counted off the pallet.
273 "description": _text(order_line.get("description")),
274 "quantity_expected": _number(expected),
275 "quantity_received": _number(received),
276 "quantity_rejected": _number(rejected),
277 "discrepancy_note": note,
278 "owner_id": owner,
279 },
280 base_dir=base, actor=ACTOR)
281 created.append({"id": line_id, "order_line_id": order_line["id"],
282 "description": _text(order_line.get("description")),
283 "quantity_expected": _number(expected),
284 "quantity_received": _number(received),
285 "quantity_rejected": _number(rejected)})
286
287 # Open first, then received: the ladder is what system_receipt_posting
288 # reacts to, and check-in-in-progress is a real state this path must not
289 # make unreachable.
290 object_records.update_collection_record(
291 "receipts", receipt_id, {"status": "received"},
292 base_dir=base, actor=ACTOR)
293
294 still_owed = sum(
295 (left for left in outstanding.values() if left > 0),
296 Decimal(0)) - sum((received for _, received, _, _ in wanted), Decimal(0))
297 rejected_total = sum((rejected for _, _, rejected, _ in wanted), Decimal(0))
298
299 return {"ok": True, "order_id": order_id, "receipt_id": receipt_id,
300 "status_of_receipt": "received", "lines": len(created),
301 "receipt_lines": created,
302 "still_outstanding": _number(still_owed),
303 "rejected": _number(rejected_total),
304 "sheet_path": f"/purchase-orders/{order_id}/receive",
305 "received_on": received_on,
306 "note": "receipt signed off; stock moves one purchase move per "
307 "line for what was received, and nothing for what was "
308 "rejected"}