askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
counter_remake.py · 10.2 KB · 195 lines
| 1 | """action_counter_remake -- make an item again: a waste move for the unit |
| 2 | that went in the bin, a zero-priced kitchen ticket line for the new one, |
| 3 | and a remakes record linking both to the original line. |
| 4 | |
| 5 | POST {"order_line_id": "...", "quantity": "1", "reason_code": "quality", |
| 6 | "note": "...", "approval_id": "..."} |
| 7 | |
| 8 | Corner Cup remade dishes by editing the paid line. That turned three facts |
| 9 | (the sale, the kitchen's second go, the waste) into one edit that said |
| 10 | none of them. Here the sale stays exactly as charged; the replacement is a |
| 11 | new order line at price zero with remake_of_line_id (the paid bill's lines |
| 12 | stay frozen, and a zero-priced line is the one line the freeze lets onto a |
| 13 | paid order); the wasted unit is a `waste` stock move. |
| 14 | |
| 15 | **Which line the waste counts for**, so the shelf goes down by exactly the |
| 16 | two items used: if the original line still has units that have not left |
| 17 | the shelf, the waste is one of those (marker orders/{order}:line/{original}) |
| 18 | and the remake line is what the hand-over will move; if the original was |
| 19 | already handed over, the waste is the remake's own unit (marker on the |
| 20 | remake line), because the original already left as a sale and the second |
| 21 | dish is the one that cost the shop without revenue. object_reservations |
| 22 | reads both markers, so neither the hand-over nor a hold counts it again. |
| 23 | |
| 24 | Staff (cashier and up). A reason marked needs_manager needs an approval |
| 25 | (counter_approvals, kind remake) unless the caller may give one. |
| 26 | A tracked product needs shop.stock_location; without it nothing is |
| 27 | written and the answer names the setting. Writes: the ticket line, then the |
| 28 | waste move, then the record; a failure part way says what landed. |
| 29 | """ |
| 30 | |
| 31 | from __future__ import annotations |
| 32 | |
| 33 | import os |
| 34 | from datetime import date, datetime, timezone |
| 35 | |
| 36 | import object_access |
| 37 | import object_collections |
| 38 | import object_corrections |
| 39 | import object_ids |
| 40 | import object_record_changes |
| 41 | import object_records |
| 42 | import object_reservations |
| 43 | import object_stock |
| 44 | |
| 45 | ACTOR = "action_counter_remake" |
| 46 | |
| 47 | |
| 48 | def _base_dir(): |
| 49 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 50 | |
| 51 | |
| 52 | def _rows(base, collection): |
| 53 | try: |
| 54 | # access: rows read here are filtered to the order and product the caller read through access.get above |
| 55 | return object_records.read_collection_records(collection, base_dir=base) |
| 56 | except object_collections.CollectionNotFoundError: |
| 57 | return [] |
| 58 | |
| 59 | |
| 60 | def _post(request): |
| 61 | text = object_corrections.text |
| 62 | base = _base_dir() |
| 63 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 64 | if not access.signed_in: |
| 65 | return {"status": 401, "error": "Sign in to record a remake."} |
| 66 | staff = object_corrections.staff_refusal(access, "action_counter_remake", doing="record a remake") |
| 67 | if staff: |
| 68 | return staff |
| 69 | line = access.get("order_lines", text(request.get("order_line_id"))) |
| 70 | if line is None: |
| 71 | return {"status": 404, "error": "No such order line."} |
| 72 | order = access.get("orders", text(line.get("order_id"))) |
| 73 | if order is None: |
| 74 | return {"status": 404, "error": "No order for that line."} |
| 75 | if text(line.get("voided_at")): |
| 76 | return {"status": 409, "error": "That item was voided; there is nothing to remake."} |
| 77 | quantity = object_corrections.qty(request.get("quantity") or "1") |
| 78 | if quantity <= 0 or quantity > object_corrections.qty(line.get("quantity")): |
| 79 | return {"status": 409, "error": (f"A remake is of 1 to {text(line.get('quantity'))} of " |
| 80 | f"this item.")} |
| 81 | # access: reason codes are shop configuration every staff role reads |
| 82 | reasons = object_records.read_collection_records("correction_reasons", base_dir=base) |
| 83 | reason, why = object_corrections.find_reason(reasons, request.get("reason_code"), "remake") |
| 84 | if reason is None: |
| 85 | return {"status": 422, "error": why} |
| 86 | who = access.user_id |
| 87 | approval = None |
| 88 | if object_corrections.truthy(reason.get("needs_manager")) and not access.can( |
| 89 | "create", "counter_approvals", None): |
| 90 | approval = access.get("counter_approvals", text(request.get("approval_id"))) |
| 91 | refusal = object_corrections.approval_refusal( |
| 92 | approval, kind="remake", order_line_id=text(line.get("id")), amount=0, caller=who) |
| 93 | if refusal: |
| 94 | return {"status": 403, "approval_required": True, |
| 95 | "error": f"This reason needs a manager's approval: {refusal}"} |
| 96 | |
| 97 | product_id = text(line.get("product_id")) |
| 98 | product = None |
| 99 | if product_id: |
| 100 | try: |
| 101 | # access: the product of an order line the caller read through access.get above; only whether it is stocked and its cost are used, and nothing of it is returned |
| 102 | product = object_records.get_collection_record("products", product_id, base_dir=base) |
| 103 | except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError, |
| 104 | object_records.InvalidRecordIdError): |
| 105 | product = None |
| 106 | tracked = object_reservations.tracked(product) |
| 107 | from_location = "" |
| 108 | cost = None |
| 109 | moved = {} |
| 110 | if tracked: |
| 111 | from_location = next((text(r.get("value")) for r in _rows(base, "app_settings") |
| 112 | if text(r.get("key")) == "shop.stock_location"), "") |
| 113 | if not from_location: |
| 114 | return {"status": 409, "error": ("shop.stock_location is not configured, so the waste " |
| 115 | "cannot say which shelf it came from. Set it in " |
| 116 | "app_settings; nothing was recorded.")} |
| 117 | try: |
| 118 | cost = object_stock.average_cost_for_product(product_id, base_dir=base) |
| 119 | moved = object_reservations.moved_by_line(_rows(base, "stock_moves"), |
| 120 | _rows(base, "shipment_lines")) |
| 121 | except Exception as exc: # noqa: BLE001 |
| 122 | return {"status": 503, "error": f"The stock log could not be read ({str(exc)[:120]}); " |
| 123 | f"nothing was recorded."} |
| 124 | cost = cost or object_corrections.cents(product.get("cost_cents")) or None |
| 125 | |
| 126 | remake_id = object_ids.new_uuid4() |
| 127 | new_line_id = object_ids.new_uuid4() |
| 128 | actor = f"{ACTOR}:{who}" |
| 129 | qty_text = object_corrections.fmt_qty(quantity) |
| 130 | unmoved = object_corrections.qty(line.get("quantity")) - moved.get(text(line.get("id")), 0) |
| 131 | waste_for = text(line.get("id")) if unmoved >= quantity else new_line_id |
| 132 | done = [] |
| 133 | try: |
| 134 | ticket = {"id": new_line_id, "order_id": text(order.get("id")), "product_id": product_id, |
| 135 | "description": f"{text(line.get('description'))} (remake)", |
| 136 | "quantity": qty_text, "unit_price_cents": "0", "modifier_cents": "0", |
| 137 | "line_total_cents": "0", "line_tax_cents": "0", |
| 138 | "line_note": text(line.get("line_note")), |
| 139 | "remake_of_line_id": text(line.get("id")), |
| 140 | "owner_id": text(order.get("owner_id"))} |
| 141 | if text(line.get("unit_code")): |
| 142 | # The remake counts in the unit the original did (app-exchange's |
| 143 | # units on lines): a second kilogram, not a second "one". |
| 144 | ticket["unit_code"] = text(line.get("unit_code")) |
| 145 | # access: system write after access check above (access.get on the order and its line) |
| 146 | object_records.create_collection_record("order_lines", ticket, base_dir=base, actor=actor, |
| 147 | preserve_read_only=True) |
| 148 | done.append(f"order_lines/{new_line_id}") |
| 149 | waste_id = "" |
| 150 | if tracked: |
| 151 | move = {"id": object_ids.new_uuid4(), "product_id": product_id, |
| 152 | "from_location_id": from_location, "quantity": qty_text, "reason": "waste", |
| 153 | "reference": (f"{object_corrections.counter_marker(order['id'], waste_for)} " |
| 154 | f"remakes/{remake_id}"), |
| 155 | "occurred_at": date.today().isoformat(), |
| 156 | "owner_id": text(order.get("owner_id"))} |
| 157 | if cost: |
| 158 | move["unit_cost_cents"] = str(cost) |
| 159 | # access: system write after access check above (access.get on the product) |
| 160 | object_records.create_collection_record("stock_moves", move, base_dir=base, actor=actor) |
| 161 | waste_id = move["id"] |
| 162 | done.append(f"stock_moves/{waste_id}") |
| 163 | record = {"id": remake_id, "order_id": text(order.get("id")), |
| 164 | "original_line_id": text(line.get("id")), "remake_line_id": new_line_id, |
| 165 | "waste_move_id": waste_id, "quantity": qty_text, |
| 166 | "reason_code": text(reason.get("code")), |
| 167 | "note": text(request.get("note"))[:300], "owner_id": who} |
| 168 | if approval is not None: |
| 169 | record["approval_id"] = text(approval.get("id")) |
| 170 | now = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") |
| 171 | # access: system write after access check above (access.get on the approval) |
| 172 | object_records.update_collection_record( |
| 173 | "counter_approvals", approval["id"], {"used_at": now, "used_for": f"remakes/{remake_id}"}, |
| 174 | base_dir=base, actor=actor, preserve_read_only=True, |
| 175 | expected_rev=object_records.compute_record_rev(approval)) |
| 176 | # access: system write after access check above (the remake of a line the caller read) |
| 177 | object_records.create_collection_record("remakes", record, base_dir=base, actor=actor) |
| 178 | except Exception as exc: # noqa: BLE001 |
| 179 | return {"status": getattr(exc, "status", None) or 409, |
| 180 | "error": (f"The remake stopped part way: {str(exc)[:200]}. " |
| 181 | + (f"Already written: {', '.join(done)}." if done else "Nothing was written.")), |
| 182 | "changed": done} |
| 183 | return {"status": 200, "ok": True, "remake_id": remake_id, "remake_line_id": new_line_id, |
| 184 | "waste_move_id": waste_id, "waste_counts_for_line": waste_for if tracked else ""} |
| 185 | |
| 186 | |
| 187 | def _t(value): |
| 188 | return str(value if value is not None else "").strip() |
| 189 | |
| 190 | |
| 191 | def POST(request): |
| 192 | """Every record change this action writes carries why, as the history |
| 193 | entry's message (object_record_changes.change_reason).""" |
| 194 | with object_record_changes.change_reason(f"remake ({_t(request.get('reason_code'))})" + (f": {_t(request.get('note'))}" if _t(request.get("note")) else "")): |
| 195 | return _post(request) |