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
counter_waste.py · 15.2 KB · 285 lines
1"""action_counter_waste -- record what was thrown away, by count or by weight.
2
3POST {"mode": "count", "product_id": "croissant", "quantity": "3",
4 "reason_code": "quality", "destination": "compost", ...}
5POST {"mode": "weight", "category": "peelings", "weight_grams": "4200",
6 "reason_code": "quality", "destination": "animal_feed",
7 "recipient_contact_id": "...", "needs_licence": "true",
8 "licence_number": "...", "licence_expires_on": "2027-03-31"}
9
10See waste_logs.json for the shape and why it has two modes. By count, a
11`waste` stock move leaves shop.stock_location (required: without it nothing
12is written and the answer names it), costed at the moving weighted average,
13and the row's estimated cost is quantity x that cost. By weight, no stock
14moves; the estimate is grams x the cost per kilo in force now
15(counter.waste_cost_per_kg_cents.<category>, else
16counter.waste_cost_per_kg_cents), stamped on the row, or blank with a warning
17when none is set -- an unknown cost is not a zero one.
18
19Licences: recorded and warned about (object_corrections.licence_warning),
20never decided. The books: this writes at storage level, so the waste move's
21journal comes from system_stock_books through the change-log replay
22(docs/logic-decisions.md #9; reactions are off on a stock install). What
23this action can do at the counter is SAY when that journal will not happen
24-- books installed but the inventory accounts unset or missing from the
25chart -- and it does, in `books_warning`, instead of letting the move sit
26unbooked in silence (Corner Cup's empty journals).
27
28Staff (cashier and up, checked here whatever the server's enforcement
29setting: object_corrections.staff_refusal); the row's owner is the person
30who recorded it. By count, the product is read under the action's own
31authority, as the other counter actions reach records the cashier holds
32no update on (the action is the grant); a deny rule naming the caller for
33it still wins and is answered as a missing product, and a caller who is
34not staff is refused before any lookup, so the answer confirms no ids. A
35cashier writes off up to counter.waste_approval_quantity of it
36in one entry (unset: DEFAULT_LIMIT; not a number: 0). Above that the entry
37cites a counter_approvals row of kind waste naming the product and at
38least the quantity, given by somebody else and spent once; whoever may
39give approvals approves their own, as with corrections. By weight nothing
40leaves the shelf and no limit applies.
41"""
42
43from __future__ import annotations
44
45import os
46from datetime import date, datetime, timezone
47from decimal import Decimal, InvalidOperation
48
49import object_access
50import object_collections
51import object_corrections
52import object_finance
53import object_ids
54import object_record_changes
55import object_records
56import object_reservations
57import object_stock
58
59ACTOR = "action_counter_waste"
60PER_KG = "counter.waste_cost_per_kg_cents"
61LIMIT_KEY = "counter.waste_approval_quantity"
62# Unset: a cashier writes off up to this many of one product in one entry
63# without an approval. The refund threshold's unset value is 0 (approval
64# always), but here that would stop the ordinary waste a counter records
65# every day (Corner Cup's cashier binning three soups from a burnt pot), so
66# the default is the smallest that keeps that working. A value that is not
67# a number is 0: approval always, never no limit.
68DEFAULT_LIMIT = Decimal("3")
69
70
71def _base_dir():
72 return os.environ.get("DBBASIC_DATA_DIR", "data")
73
74
75def _settings(base):
76 try:
77 # access: box configuration
78 rows = object_records.read_collection_records("app_settings", base_dir=base)
79 except object_collections.CollectionNotFoundError:
80 return {}
81 return {object_corrections.text(r.get("key")): object_corrections.text(r.get("value")) for r in rows}
82
83
84def _limit(settings):
85 raw = settings.get(LIMIT_KEY, "")
86 if not raw:
87 return DEFAULT_LIMIT
88 try:
89 value = Decimal(raw)
90 except (InvalidOperation, ValueError):
91 return Decimal("0")
92 return value if value.is_finite() and value > 0 else Decimal("0")
93
94
95def _books_warning(base, settings, reason):
96 try:
97 # access: only whether the books exist is read, nothing of them is returned
98 object_records.read_collection_records("fin_journals", base_dir=base)
99 except object_collections.CollectionNotFoundError:
100 return ""
101 except Exception:
102 return "The books could not be read, so whether this waste will be booked is unknown."
103 inventory = settings.get("inventory.journal.inventory_account", "")
104 loss = (settings.get(f"inventory.journal.{reason}_account", "")
105 or settings.get("inventory.journal.shrinkage_account", ""))
106 needed = [k for k, v in (("inventory.journal.inventory_account", inventory),
107 ("inventory.journal.shrinkage_account", loss)) if not v]
108 if needed:
109 return (f"The books will not receive this waste: set {' and '.join(needed)} in "
110 f"app_settings to accounts in the chart of accounts.")
111 missing = object_finance.accounts_missing(base, [inventory, loss])
112 if missing is object_finance.UNREADABLE:
113 return "The chart of accounts could not be read, so whether this waste will be booked is unknown."
114 if missing:
115 return (f"The books will not receive this waste: the chart of accounts has no account "
116 f"{', '.join(repr(m) for m in missing)}.")
117 return ""
118
119
120def _post(request):
121 text = object_corrections.text
122 base = _base_dir()
123 access = object_access.Access(request.get("_identity"), base_dir=base)
124 if not access.signed_in:
125 return {"status": 401, "error": "Sign in to record waste."}
126 staff = object_corrections.staff_refusal(access, "action_counter_waste", doing="record waste")
127 if staff:
128 return staff
129 mode = text(request.get("mode") or "count")
130 if mode not in ("count", "weight"):
131 return {"status": 400, "error": "mode is count or weight."}
132 destination = text(request.get("destination") or "trash")
133 if destination not in object_corrections.WASTE_DESTINATIONS:
134 return {"status": 400, "error": ("destination is one of "
135 + ", ".join(object_corrections.WASTE_DESTINATIONS) + ".")}
136 # access: reason codes are shop configuration every staff role reads
137 reasons = object_records.read_collection_records("correction_reasons", base_dir=base)
138 reason, why = object_corrections.find_reason(reasons, request.get("reason_code"), "waste")
139 if reason is None:
140 return {"status": 422, "error": why}
141 recipient = text(request.get("recipient_contact_id"))
142 if recipient and access.get("contacts", recipient) is None:
143 return {"status": 404, "error": "No such contact to record as the recipient."}
144
145 settings = _settings(base)
146 today = date.today().isoformat()
147 log_id = object_ids.new_uuid4()
148 row = {"id": log_id, "mode": mode, "reason_code": text(reason.get("code")),
149 "destination": destination, "recipient_contact_id": recipient,
150 "needs_licence": "true" if object_corrections.truthy(request.get("needs_licence")) else "false",
151 "licence_number": text(request.get("licence_number"))[:120],
152 "licence_expires_on": text(request.get("licence_expires_on"))[:10],
153 "note": text(request.get("note"))[:300],
154 "occurred_at": (text(request.get("occurred_at"))
155 or datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")),
156 "owner_id": access.user_id}
157 row["licence_warning"] = object_corrections.licence_warning(
158 needs_licence=row["needs_licence"], licence_number=row["licence_number"],
159 expires_on=row["licence_expires_on"], today=today)
160 warnings = [row["licence_warning"]] if row["licence_warning"] else []
161 move = None
162 approval = None
163 if mode == "count":
164 product_id = text(request.get("product_id"))
165 quantity = object_corrections.qty(request.get("quantity") or "1")
166 if not product_id or not quantity.is_finite() or quantity <= 0:
167 return {"status": 400, "error": "By count: product_id and a quantity above zero."}
168 # Read under the action's own authority: the action is the grant
169 # (staff_refusal above ran first, so a caller who is not staff never
170 # reaches this lookup and its answer confirms no ids). A deny rule
171 # that names the caller for this product still wins, and is answered
172 # as a missing product.
173 try:
174 # access: staff action after staff_refusal above; only whether the item is stocked and its cost are used, nothing of it is returned, and a deny rule is honoured below
175 product = object_records.get_collection_record("products", product_id, base_dir=base)
176 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError,
177 object_collections.CollectionNotFoundError):
178 product = None
179 if product is None or object_corrections.denied_by_rule(access, "read", "products", product):
180 return {"status": 404, "error": "No such product to record waste of."}
181 limit = _limit(settings)
182 if quantity > limit and not access.can("create", "counter_approvals", None):
183 approval_id = text(request.get("approval_id"))
184 if not approval_id:
185 return {"status": 403, "approval_required": True,
186 "error": (f"Writing off more than {object_corrections.fmt_qty(limit)} in "
187 f"one entry needs a manager's approval ({LIMIT_KEY}). Ask a "
188 f"manager to approve it and pass approval_id.")}
189 approval = access.get("counter_approvals", approval_id)
190 refusal = object_corrections.waste_approval_refusal(
191 approval, product_id=product_id, quantity=quantity, caller=access.user_id)
192 if refusal:
193 return {"status": 403, "approval_required": True, "error": refusal}
194 row.update({"product_id": product_id, "quantity": object_corrections.fmt_qty(quantity)})
195 if object_reservations.tracked(product):
196 shelf = settings.get("shop.stock_location", "")
197 if not shelf:
198 return {"status": 409, "error": ("shop.stock_location is not configured, so the "
199 "waste cannot say which shelf it left. Set it in "
200 "app_settings; nothing was recorded.")}
201 try:
202 cost = object_stock.average_cost_for_product(product_id, base_dir=base)
203 except Exception as exc: # noqa: BLE001
204 return {"status": 503, "error": f"The cost could not be read ({str(exc)[:120]}); "
205 f"nothing was recorded."}
206 cost = cost or object_corrections.cents(product.get("cost_cents")) or None
207 move = {"id": object_ids.new_uuid4(), "product_id": product_id,
208 "from_location_id": shelf, "quantity": row["quantity"], "reason": "waste",
209 "reference": f"waste_logs/{log_id}", "occurred_at": today,
210 "owner_id": text(product.get("owner_id")) or access.user_id}
211 if cost:
212 move["unit_cost_cents"] = str(cost)
213 row["stock_move_id"] = move["id"]
214 estimate = object_corrections.count_cost(quantity, cost or "")
215 else:
216 estimate = object_corrections.count_cost(quantity, product.get("cost_cents"))
217 if estimate is None:
218 warnings.append("This item has no cost recorded, so the waste has no estimated cost.")
219 else:
220 category = text(request.get("category"))
221 grams = text(request.get("weight_grams"))
222 if not category or not grams.isdigit():
223 return {"status": 400, "error": "By weight: a category (bin) and weight_grams, a whole number."}
224 per_kg = settings.get(f"{PER_KG}.{category}", "") or settings.get(PER_KG, "")
225 row.update({"category": category[:80], "weight_grams": grams})
226 if per_kg:
227 row["cost_per_kg_cents"] = per_kg
228 estimate = object_corrections.weight_cost(grams, per_kg)
229 if estimate is None:
230 warnings.append(f"No cost per kilo is set ({PER_KG}), so this waste has no estimated "
231 f"cost; it is recorded by weight only.")
232 if estimate is not None:
233 row["estimated_cost_cents"] = str(estimate)
234 books_warning = _books_warning(base, settings, "waste") if move else ""
235 actor = f"{ACTOR}:{access.user_id}"
236 if approval is not None:
237 row["approval_id"] = text(approval.get("id"))
238 now = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
239 try:
240 # access: system write after access check above (access.get on the approval)
241 object_records.update_collection_record(
242 "counter_approvals", approval["id"], {"used_at": now, "used_for": f"waste_logs/{log_id}"},
243 base_dir=base, actor=actor, preserve_read_only=True,
244 expected_rev=object_records.compute_record_rev(approval))
245 except Exception as exc: # noqa: BLE001
246 return {"status": 409, "error": f"That approval could not be spent ({str(exc)[:160]}); "
247 f"it may have just been used. Nothing was recorded."}
248 moved = False
249 try:
250 if move:
251 # access: system write after access check above (staff action; the waste of a stocked item)
252 object_records.create_collection_record("stock_moves", move, base_dir=base, actor=actor)
253 moved = True
254 # access: system write after access check above (the caller's own waste record)
255 object_records.create_collection_record("waste_logs", row, base_dir=base, actor=actor,
256 preserve_read_only=True)
257 except Exception as exc: # noqa: BLE001
258 if approval is not None and not moved:
259 try:
260 # access: system write after access check above (giving back the approval this call spent)
261 object_records.update_collection_record(
262 "counter_approvals", approval["id"], {"used_at": "", "used_for": ""},
263 base_dir=base, actor=actor, preserve_read_only=True)
264 except Exception: # noqa: BLE001
265 pass
266 return {"status": getattr(exc, "status", None) or 409,
267 "error": (f"Nothing more was recorded: {str(exc)[:200]}"
268 + (f" (the stock move {move['id']} was written)" if moved else ""))}
269 out = {"status": 200, "ok": True, "waste_log_id": log_id,
270 "estimated_cost_cents": estimate, "stock_move_id": move["id"] if move else "",
271 "warnings": warnings}
272 if books_warning:
273 out["books_warning"] = books_warning
274 return out
275
276
277def _t(value):
278 return str(value if value is not None else "").strip()
279
280
281def POST(request):
282 """Every record change this action writes carries why, as the history
283 entry's message (object_record_changes.change_reason)."""
284 with object_record_changes.change_reason(f"waste ({_t(request.get('reason_code'))}, {_t(request.get('mode')) or 'count'})" + (f": {_t(request.get('note'))}" if _t(request.get("note")) else "")):
285 return _post(request)