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
receipt_lines.py · 8.3 KB · 184 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
4Four 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 ten of an order line that ordered eight -- it is the second
8delivery quietly claiming three more after the first already took eight.
9So the count is over EVERY receipt line pointing at that order line, and
10the refusal shows all three numbers ("ordered 8, already received 8, this
11would make 11"), because a gate that only says "no" leaves the person on
12the dock guessing which of the two deliveries is the wrong one. Receiving
13more than was ordered is not a clerical curiosity: it is the shape of an
14over-shipment nobody agreed to pay for, and finding it at the door is
15cheap where finding it at invoice-matching time is not.
16
17Lines belonging to CANCELLED receipts do not count. A receipt raised and
18then abandoned before anything was counted describes no goods, and a shop
19that had to re-check-in a delivery after voiding a mistyped receipt would
20otherwise be told it was over-receiving on the second attempt -- refused
21by its own paperwork for doing exactly the right thing.
22
23**A settled receipt is settled.** Once a receipt is `received`, its lines
24are the record of what the driver handed over. A carton found at the back
25of the van is a NEW receipt against the same PO, not a retroactive edit to
26what was already signed for; otherwise the delivery note in the supplier's
27file and the row in the database stop agreeing, and only one of them can
28be shown to a judge.
29
30**Quantities must not be negative.** A negative receipt line would be a
31correction pretending to be a fact (docs/logic-decisions.md #3); the
32correction for over-counting a pallet is an adjustment move, which says
33what it is.
34
35**A line that received nothing must SAY why.** quantity_received of zero
36with no rejected quantity and no discrepancy note is indistinguishable
37from a half-finished data entry -- and the two need opposite responses:
38one is a short delivery to chase the supplier about, the other is a row
39somebody has not finished typing. Refusing the ambiguous one is how the
40distinction survives to the day the supplier's invoice arrives.
41
42Trusted server-side writes bypass hooks by design
43(docs/validation-and-logic.md), so action_receive_goods carries the same
44cumulative check itself and reports every blocker at once, checkout-style.
45That duplication is deliberate and named in both files: the hook guards
46the generic HTTP write path a form or an API client uses, the action
47guards the friendly path, and neither can be removed without opening the
48other's door. app-shipping's hook/action pair says the same thing about
49the sales side; this is the mirror of it.
50"""
51
52import os
53from decimal import Decimal, InvalidOperation
54
55import object_records
56
57# A receipt abandoned before anything was counted describes no goods, so
58# its lines consume none of what was ordered.
59NOT_RECEIVED_STATUSES = {"cancelled"}
60
61# Once a receipt is in one of these, the delivery has been signed for and
62# its contents are history, not a draft.
63SETTLED_STATUSES = {"received"}
64
65
66def _base_dir():
67 return os.environ.get("DBBASIC_DATA_DIR", "data")
68
69
70def _text(value):
71 return str(value if value is not None else "").strip()
72
73
74def _quantity(value):
75 """Decimal, never a bare float: quantities may be fractional (1.5 kg of
76 coffee) and binary-float arithmetic would make an exact-fit delivery
77 round itself into an over-receipt."""
78 try:
79 return Decimal(_text(value) or "0")
80 except InvalidOperation:
81 return None
82
83
84def _number(value):
85 """Render a Decimal the way a human wrote it: 8 not 8.000, 1.5 not 1.50.
86 The refusal message is read by whoever has to fix the receipt, so the
87 numbers in it have to look like the numbers on their screen."""
88 return format(value.normalize(), "f")
89
90
91def BEFORE_WRITE(request):
92 action = _text(request.get("action"))
93 if action not in ("create", "update"):
94 return None
95 record = request.get("record") or {}
96 base = _base_dir()
97
98 received = _quantity(record.get("quantity_received"))
99 rejected = _quantity(record.get("quantity_rejected"))
100 if received is None or rejected is None:
101 return None # schema validation owns the type error
102 if received < 0 or rejected < 0:
103 return {"error": ("A receipt line cannot receive or reject a negative "
104 "quantity. Nothing arrived is what a zero means, and "
105 "a miscount is corrected by an adjustment move, "
106 "never by a negative row."),
107 "status": 400}
108
109 if received == 0 and rejected == 0 and not _text(
110 record.get("discrepancy_note")):
111 return {"error": ("This line received nothing and says nothing about "
112 "why. A short delivery has to be recorded as one -- "
113 "give a rejected quantity or a discrepancy note, "
114 "because a blank zero is indistinguishable from a "
115 "row somebody has not finished typing, and the two "
116 "need opposite answers when the supplier's invoice "
117 "arrives."),
118 "status": 400}
119
120 receipt_id = _text(record.get("receipt_id"))
121 try:
122 receipt = object_records.get_collection_record(
123 "receipts", receipt_id, base_dir=base)
124 except Exception:
125 return None # relation validation owns a missing receipt
126 receipt_status = _text(receipt.get("status"))
127 if receipt_status in SETTLED_STATUSES:
128 return {"error": (f"Receipt {receipt_id} is already {receipt_status}. "
129 f"A delivery is settled once it has been signed for "
130 f"-- a carton found afterwards is a NEW receipt "
131 f"against the same purchase order, not a change to "
132 f"what the driver already handed over."),
133 "status": 409}
134
135 order_line_id = _text(record.get("order_line_id"))
136 try:
137 order_line = object_records.get_collection_record(
138 "order_lines", order_line_id, base_dir=base)
139 except Exception:
140 return {"error": (f"No such order line: {order_line_id or '(blank)'}. "
141 f"A receipt line has to say which ordered thing "
142 f"turned up, or nothing can tell whether the "
143 f"supplier sent what we bought."),
144 "status": 400}
145
146 ordered = _quantity(order_line.get("quantity")) or Decimal(0)
147
148 try:
149 existing_lines = object_records.read_collection_records(
150 "receipt_lines", base_dir=base)
151 except Exception:
152 return {"error": ("Receipt history unreadable; refusing to receive "
153 "against an unknown history."), "status": 503}
154 try:
155 receipts = {row["id"]: row for row in
156 object_records.read_collection_records("receipts",
157 base_dir=base)}
158 except Exception:
159 receipts = {}
160
161 record_id = _text(record.get("id"))
162 already = Decimal(0)
163 for line in existing_lines:
164 if _text(line.get("order_line_id")) != order_line_id:
165 continue
166 if record_id and _text(line.get("id")) == record_id:
167 continue # an update replaces its own earlier quantity
168 parent = receipts.get(_text(line.get("receipt_id"))) or {}
169 if _text(parent.get("status")) in NOT_RECEIVED_STATUSES:
170 continue
171 already += _quantity(line.get("quantity_received")) or Decimal(0)
172
173 would_be = already + received
174 if would_be > ordered:
175 return {"error": (f"That would receive more than was ordered: ordered "
176 f"{_number(ordered)}, already received "
177 f"{_number(already)}, this would make "
178 f"{_number(would_be)}. Amend the purchase order "
179 f"first if the supplier really sent more, so what "
180 f"we agreed to pay for and what is on the shelf go "
181 f"on saying the same thing."),
182 "status": 409}
183
184 return None