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

9 downloads

Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
receipt_lines.py · 9.8 KB · 217 lines
1"""Pre-write hook for receipt_lines: you cannot receive what was not
2ordered, and you cannot add to a delivery that has already been signed for.
3
4Three gates, all of them things the schema has no way to say. (Two it used
5to carry are declared now: quantities are never negative --
6`validation.min` 0 on `quantity_received` and `quantity_rejected` -- and the
7order line has to exist -- a `relation` on `order_line_id`; both hold for
8every writer, the storage-level ones included.)
9
10**Cumulative, not per-line.** The interesting failure is never one line
11claiming ten of an order line that ordered eight -- it is the second
12delivery quietly claiming three more after the first already took eight.
13So the count is over EVERY receipt line pointing at that order line, and
14the refusal shows all three numbers ("ordered 8, already received 8, this
15would make 11"), because a gate that only says "no" leaves the person on
16the dock guessing which of the two deliveries is the wrong one. Receiving
17more than was ordered is not a clerical curiosity: it is the shape of an
18over-shipment nobody agreed to pay for, and finding it at the door is
19cheap where finding it at invoice-matching time is not.
20
21Lines belonging to CANCELLED receipts do not count. A receipt raised and
22then abandoned before anything was counted describes no goods, and a shop
23that had to re-check-in a delivery after voiding a mistyped receipt would
24otherwise be told it was over-receiving on the second attempt -- refused
25by its own paperwork for doing exactly the right thing.
26
27**A settled receipt is settled.** Once a receipt is `received`, its lines
28are the record of what the driver handed over. A carton found at the back
29of the van is a NEW receipt against the same PO, not a retroactive edit to
30what was already signed for; otherwise the delivery note in the supplier's
31file and the row in the database stop agreeing, and only one of them can
32be shown to a judge.
33
34That rule is about the receipt the line is ON as much as the receipt it
35is going to. This hook used to read only the receipt_id the line would
36have after the write, so a line was moved out of a received receipt by
37PUTting receipt_id to an open one -- the new parent was open, the hook
38passed -- and was then freely editable there: nine received units left
39the record of a signed-for delivery. An update is now checked against
40BOTH parents, and a delete (which no rule grants a signed-in user today,
41but an admin has) against the one the line is on.
42
43**A line that received nothing must SAY why.** quantity_received of zero
44with no rejected quantity and no discrepancy note is indistinguishable
45from a half-finished data entry -- and the two need opposite responses:
46one is a short delivery to chase the supplier about, the other is a row
47somebody has not finished typing. Refusing the ambiguous one is how the
48distinction survives to the day the supplier's invoice arrives.
49
50Trusted server-side writes bypass hooks by design
51(docs/validation-and-logic.md), so action_receive_goods carries the same
52cumulative check itself and reports every blocker at once, checkout-style.
53That duplication is deliberate and named in both files: the hook guards
54the generic HTTP write path a form or an API client uses, the action
55guards the friendly path, and neither can be removed without opening the
56other's door. app-shipping's hook/action pair says the same thing about
57the sales side; this is the mirror of it.
58"""
59
60import os
61from decimal import Decimal, InvalidOperation
62
63import object_collections
64import object_records
65
66_MISSING = (object_records.RecordNotFoundError,
67 object_collections.CollectionNotFoundError,
68 object_records.InvalidRecordIdError)
69
70# A receipt abandoned before anything was counted describes no goods, so
71# its lines consume none of what was ordered.
72NOT_RECEIVED_STATUSES = {"cancelled"}
73
74# Once a receipt is in one of these, the delivery has been signed for and
75# its contents are history, not a draft.
76SETTLED_STATUSES = {"received"}
77
78
79def _base_dir():
80 return os.environ.get("DBBASIC_DATA_DIR", "data")
81
82
83def _text(value):
84 return str(value if value is not None else "").strip()
85
86
87def _quantity(value):
88 """Decimal, never a bare float: quantities may be fractional (1.5 kg of
89 coffee) and binary-float arithmetic would make an exact-fit delivery
90 round itself into an over-receipt."""
91 try:
92 return Decimal(_text(value) or "0")
93 except InvalidOperation:
94 return None
95
96
97def _number(value):
98 """Render a Decimal the way a human wrote it: 8 not 8.000, 1.5 not 1.50.
99 The refusal message is read by whoever has to fix the receipt, so the
100 numbers in it have to look like the numbers on their screen."""
101 return format(value.normalize(), "f")
102
103
104def _settled(receipt_id, base):
105 """A refusal when this receipt has been signed for, so its lines are
106 history. None for a receipt that does not exist: relation validation
107 owns that on create/update, and a line with no receipt records no
108 delivery. A receipt that exists and cannot be READ is a refusal --
109 "could not tell" is not "still open"."""
110 if not receipt_id:
111 return None
112 try:
113 receipt = object_records.get_collection_record(
114 "receipts", receipt_id, base_dir=base)
115 except _MISSING:
116 return None
117 except Exception:
118 return {"error": (f"Receipt {receipt_id} could not be read, so nothing "
119 f"can say whether it has been signed for. Nothing "
120 f"was changed."), "status": 503}
121 receipt_status = _text(receipt.get("status"))
122 if receipt_status in SETTLED_STATUSES:
123 return {"error": (f"Receipt {receipt_id} is already {receipt_status}. "
124 f"A delivery is settled once it has been signed for "
125 f"-- a carton found afterwards is a NEW receipt "
126 f"against the same purchase order, not a change to "
127 f"what the driver already handed over."),
128 "status": 409}
129 return None
130
131
132def BEFORE_WRITE(request):
133 action = _text(request.get("action"))
134 existing = request.get("existing") or {}
135 base = _base_dir()
136 if action == "delete":
137 return _settled(_text(existing.get("receipt_id")), base)
138 if action not in ("create", "update"):
139 return None
140 record = request.get("record") or {}
141
142 received = _quantity(record.get("quantity_received"))
143 rejected = _quantity(record.get("quantity_rejected"))
144 if received is None or rejected is None:
145 return None # schema validation owns the type error
146 if received == 0 and rejected == 0 and not _text(
147 record.get("discrepancy_note")):
148 return {"error": ("This line received nothing and says nothing about "
149 "why. A short delivery has to be recorded as one -- "
150 "give a rejected quantity or a discrepancy note, "
151 "because a blank zero is indistinguishable from a "
152 "row somebody has not finished typing, and the two "
153 "need opposite answers when the supplier's invoice "
154 "arrives."),
155 "status": 400}
156
157 receipt_id = _text(record.get("receipt_id"))
158 parents = [receipt_id]
159 if action == "update":
160 # The receipt the line is leaving first: moving a line out of a
161 # settled receipt is the edit this gate exists to refuse.
162 parents.insert(0, _text(existing.get("receipt_id")))
163 for parent in dict.fromkeys(parents):
164 refusal = _settled(parent, base)
165 if refusal:
166 return refusal
167
168 order_line_id = _text(record.get("order_line_id"))
169 try:
170 order_line = object_records.get_collection_record(
171 "order_lines", order_line_id, base_dir=base)
172 except _MISSING:
173 return None # the field's relation validation refuses it
174 except Exception:
175 return {"error": (f"Order line {order_line_id} could not be read, so "
176 f"nothing can say how much was ordered. Nothing "
177 f"was changed."), "status": 503}
178
179 ordered = _quantity(order_line.get("quantity")) or Decimal(0)
180
181 try:
182 existing_lines = object_records.read_collection_records(
183 "receipt_lines", base_dir=base)
184 except Exception:
185 return {"error": ("Receipt history unreadable; refusing to receive "
186 "against an unknown history."), "status": 503}
187 try:
188 receipts = {row["id"]: row for row in
189 object_records.read_collection_records("receipts",
190 base_dir=base)}
191 except Exception:
192 receipts = {}
193
194 record_id = _text(record.get("id"))
195 already = Decimal(0)
196 for line in existing_lines:
197 if _text(line.get("order_line_id")) != order_line_id:
198 continue
199 if record_id and _text(line.get("id")) == record_id:
200 continue # an update replaces its own earlier quantity
201 parent = receipts.get(_text(line.get("receipt_id"))) or {}
202 if _text(parent.get("status")) in NOT_RECEIVED_STATUSES:
203 continue
204 already += _quantity(line.get("quantity_received")) or Decimal(0)
205
206 would_be = already + received
207 if would_be > ordered:
208 return {"error": (f"That would receive more than was ordered: ordered "
209 f"{_number(ordered)}, already received "
210 f"{_number(already)}, this would make "
211 f"{_number(would_be)}. Amend the purchase order "
212 f"first if the supplier really sent more, so what "
213 f"we agreed to pay for and what is on the shelf go "
214 f"on saying the same thing."),
215 "status": 409}
216
217 return None