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_correct.py · 17.3 KB · 324 lines
| 1 | """action_counter_correct -- correct a PAID sale by a new record that cites |
| 2 | the item: a line refund (money back) or a credit note (credit against the bill). |
| 3 | |
| 4 | POST {"order_line_id": "...", "quantity": "1", "reason_code": "quality", |
| 5 | "settle": "refund" | "credit_note", "approval_id": "...", "note": "..."} |
| 6 | |
| 7 | **What was wrong (Corner Cup, a Haiku simulation of a counter cafe).** After |
| 8 | payment, staff edited the order line and the invoice line in place, each |
| 9 | separately, with no reason and no approval; refunds carried no line, only |
| 10 | free text. So nobody could answer "what was refunded, for which item, and |
| 11 | who agreed to it", and the documents disagreed. |
| 12 | |
| 13 | **What a correction is.** The original sale is left exactly as charged. |
| 14 | Every correction is a CREDIT NOTE, because a debt is cancelled only by a |
| 15 | credit note (the owner's decision of 2026-11-30): an invoices row of |
| 16 | doc_type credit_note that names the invoice it credits, with one line |
| 17 | citing the order line (order_line_id) and the invoice line it gives back |
| 18 | (credits_line_id), priced as the bill priced that line -- its unit price, |
| 19 | discount and stamped tax rate (object_corrections.credit_note_documents). |
| 20 | settle=refund is that credit note PLUS the money back: a refunds row citing |
| 21 | the credit note (credit_note_id), the line, quantity, reason_code, |
| 22 | approved_by and approval_id. "Refund this sale" therefore leaves the |
| 23 | invoice reading paid for what was kept, or refunded when all of it came |
| 24 | back, with nothing due; before this the refund alone left the debt |
| 25 | standing, and the invoice was dunned for the soup it had refunded. The |
| 26 | ledger's locked checks refuse a line that is not on the bill's order and a |
| 27 | quantity that, with every credit note already citing the line, would |
| 28 | correct more than was sold -- inside the lock, so two cashiers cannot both |
| 29 | give back the same soup. The units are counted once, on the credit note's |
| 30 | line; the refund that pays it out is capped at the credit note's value. |
| 31 | |
| 32 | **One credit-note model (with app-exchange).** A credit note is applied by |
| 33 | an invoice_credits row (app-invoices), written here in the same act that |
| 34 | issues it (source counter): the credited invoice's balance_due_cents falls |
| 35 | by the credit and the credit note's own balance is 0 -- exactly what |
| 36 | sending a credit note through the exchange does. Sending this credit note |
| 37 | to a trading partner later (when the invoice it credits was sent) carries |
| 38 | its line with ref_line_id naming the credited line, and applies nothing |
| 39 | twice: the exchange finds the row already written. |
| 40 | |
| 41 | **Approval.** A caller who may give approvals (the permission engine lets |
| 42 | them create counter_approvals: shift lead, manager, owner) approves their |
| 43 | own correction and is stamped approved_by. Anybody else (a cashier) may |
| 44 | correct up to counter.refund_approval_threshold_cents without one; above it, |
| 45 | or for a reason code marked needs_manager, they cite an approval_id a |
| 46 | manager gave for this item and at least this amount, spent once by a |
| 47 | compare-and-set. An unset threshold is 0: every cashier correction then |
| 48 | needs a manager, which fails closed rather than open. |
| 49 | |
| 50 | **Not here, on purpose.** Goodwill when the charge was right is |
| 51 | action_counter_goodwill (a goodwill record, separate from refunds); an |
| 52 | unpaid item is voided (action_counter_void). The invoice's status follows |
| 53 | the money (system_invoice_status): it is not set here. |
| 54 | """ |
| 55 | |
| 56 | from __future__ import annotations |
| 57 | |
| 58 | import os |
| 59 | from datetime import date, datetime, timezone |
| 60 | |
| 61 | import object_access |
| 62 | import object_collections |
| 63 | import object_corrections |
| 64 | import object_ids |
| 65 | import object_record_changes |
| 66 | import object_records |
| 67 | |
| 68 | ACTOR = "action_counter_correct" |
| 69 | THRESHOLD_KEY = "counter.refund_approval_threshold_cents" |
| 70 | |
| 71 | |
| 72 | def _base_dir(): |
| 73 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 74 | |
| 75 | |
| 76 | def _rows(base, collection): |
| 77 | try: |
| 78 | # access: every row read here is filtered to the order the caller read through access.get above, and each bill and line is asked about with access.can before it is used |
| 79 | return object_records.read_collection_records(collection, base_dir=base) |
| 80 | except object_collections.CollectionNotFoundError: |
| 81 | return [] |
| 82 | |
| 83 | |
| 84 | def _threshold(base): |
| 85 | # access: box configuration |
| 86 | for row in _rows(base, "app_settings"): |
| 87 | if object_corrections.text(row.get("key")) == THRESHOLD_KEY: |
| 88 | try: |
| 89 | return max(0, int(object_corrections.text(row.get("value")) or "0")) |
| 90 | except ValueError: |
| 91 | return 0 |
| 92 | return 0 |
| 93 | |
| 94 | |
| 95 | def _post(request): |
| 96 | text = object_corrections.text |
| 97 | base = _base_dir() |
| 98 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 99 | if not access.signed_in: |
| 100 | return {"status": 401, "error": "Sign in to correct a sale."} |
| 101 | staff = object_corrections.staff_refusal(access, "action_counter_correct", doing="correct a sale here") |
| 102 | if staff: |
| 103 | return staff |
| 104 | settle = text(request.get("settle") or "refund") |
| 105 | if settle not in ("refund", "credit_note"): |
| 106 | return {"status": 400, "error": "settle is refund or credit_note."} |
| 107 | line_id = text(request.get("order_line_id")) |
| 108 | line = access.get("order_lines", line_id) if line_id else None |
| 109 | if line is None: |
| 110 | return {"status": 404, "error": f"No order line {line_id or '(none given)'}."} |
| 111 | order = access.get("orders", text(line.get("order_id"))) |
| 112 | if order is None: |
| 113 | return {"status": 404, "error": "No order for that line."} |
| 114 | # access: reason codes are shop configuration every staff role reads |
| 115 | reasons = object_records.read_collection_records("correction_reasons", base_dir=base) |
| 116 | reason, why = object_corrections.find_reason(reasons, request.get("reason_code"), settle) |
| 117 | if reason is None: |
| 118 | return {"status": 422, "error": why} |
| 119 | quantity = text(request.get("quantity") or "1") |
| 120 | |
| 121 | bills = [b for b in object_corrections.bills_for_order(order, _rows(base, "invoices")) |
| 122 | if access.can("read", "invoices", b)] |
| 123 | payments = _rows(base, "payments") |
| 124 | paid_bills = [b for b in bills |
| 125 | if object_corrections.received_cents([b.get("id")], payments) > 0] |
| 126 | if not paid_bills: |
| 127 | return {"status": 409, |
| 128 | "error": ("Nothing has been paid on this sale, so there is nothing to correct " |
| 129 | "after payment: void the item instead (action_counter_void).")} |
| 130 | bill = paid_bills[0] |
| 131 | invoice_lines = _rows(base, "invoice_lines") |
| 132 | billing = next((row for row in invoice_lines |
| 133 | if text(row.get("order_line_id")) == line_id |
| 134 | and text(row.get("invoice_id")) == text(bill.get("id")) |
| 135 | and access.can("read", "invoice_lines", row)), None) |
| 136 | already = object_corrections.corrected_quantity( |
| 137 | line_id, refunds=_rows(base, "refunds"), invoices=_rows(base, "invoices"), |
| 138 | invoice_lines=invoice_lines) |
| 139 | refusal = object_corrections.ceiling_refusal(line, quantity, already) |
| 140 | if refusal: |
| 141 | return {"status": 409, "error": refusal} |
| 142 | # Every correction after payment is a credit note (the owner's decision |
| 143 | # of 2026-11-30: a debt is cancelled only by a credit note); a refund |
| 144 | # is that credit note plus the money back. Priced as the bill priced |
| 145 | # the line, at its stamped rate. |
| 146 | credit_note_id = object_ids.new_uuid4() |
| 147 | documents = object_corrections.credit_note_documents( |
| 148 | bill=bill, order=order, line=line, billing=billing, quantity=quantity, |
| 149 | reason_code=text(reason.get("code")), reason_label=text(reason.get("label")), |
| 150 | approved_by="", note=text(request.get("note"))[:300], |
| 151 | today=date.today().isoformat(), credit_note_id=credit_note_id, |
| 152 | line_id=object_ids.new_uuid4(), credit_id=object_ids.new_uuid4()) |
| 153 | amount = object_corrections.cents(documents[0]["total_cents"]) |
| 154 | if amount <= 0: |
| 155 | return {"status": 409, "error": "Those units were charged nothing; there is nothing to give back."} |
| 156 | |
| 157 | # Approval. |
| 158 | who = access.user_id |
| 159 | approval = None |
| 160 | may_approve = access.can("create", "counter_approvals", None) |
| 161 | needs = (not may_approve) and (amount > _threshold(base) |
| 162 | or object_corrections.truthy(reason.get("needs_manager"))) |
| 163 | approved_by = who if may_approve else "" |
| 164 | if needs: |
| 165 | approval_id = text(request.get("approval_id")) |
| 166 | if not approval_id: |
| 167 | return {"status": 403, "approval_required": True, "amount_cents": amount, |
| 168 | "error": (f"A correction of {amount} needs a manager's approval (the shop's " |
| 169 | f"limit without one is {_threshold(base)}" |
| 170 | + (", and this reason always needs one" if object_corrections.truthy( |
| 171 | reason.get("needs_manager")) else "") |
| 172 | + "). Ask a manager to approve it and pass approval_id.")} |
| 173 | approval = access.get("counter_approvals", approval_id) |
| 174 | refusal = object_corrections.approval_refusal( |
| 175 | approval, kind=settle, order_line_id=line_id, amount=amount, caller=who) |
| 176 | if refusal: |
| 177 | return {"status": 403, "error": refusal} |
| 178 | approved_by = text(approval.get("owner_id")) |
| 179 | |
| 180 | today = date.today().isoformat() |
| 181 | now = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") |
| 182 | actor = f"{ACTOR}:{who}" |
| 183 | note = text(request.get("note"))[:300] |
| 184 | header, credit_line, credit = documents |
| 185 | header["approved_by"] = approved_by |
| 186 | # A refund needs one payment with that much left to give back; found |
| 187 | # before anything is written, so a refund that cannot be paid out does |
| 188 | # not leave a credit note behind. |
| 189 | payment = None |
| 190 | if settle == "refund": |
| 191 | payment = _refundable_payment(base, bill, payments, amount) |
| 192 | if payment is None: |
| 193 | return {"status": 409, |
| 194 | "error": (f"No single payment on this bill has {amount} left to give back; " |
| 195 | f"nothing was recorded.")} |
| 196 | record_id = object_ids.new_uuid4() if settle == "refund" else credit_note_id |
| 197 | used_for = f"{'refunds' if settle == 'refund' else 'invoices'}/{record_id}" |
| 198 | if approval is not None: |
| 199 | try: |
| 200 | # access: system write after access check above (access.get on the approval) |
| 201 | object_records.update_collection_record( |
| 202 | "counter_approvals", approval["id"], {"used_at": now, "used_for": used_for}, |
| 203 | base_dir=base, actor=actor, preserve_read_only=True, |
| 204 | expected_rev=object_records.compute_record_rev(approval)) |
| 205 | except Exception as exc: # noqa: BLE001 |
| 206 | return {"status": 409, "error": f"That approval could not be spent ({str(exc)[:160]}); " |
| 207 | f"it may have just been used. Nothing was recorded."} |
| 208 | |
| 209 | reason_text = f"{text(reason.get('label'))}" + (f": {note}" if note else "") |
| 210 | try: |
| 211 | result = _credit_note(base, header, credit_line, credit, actor) |
| 212 | except Exception as exc: # noqa: BLE001 |
| 213 | if approval is not None: |
| 214 | try: |
| 215 | # access: system write after access check above (giving back the approval this call spent) |
| 216 | object_records.update_collection_record( |
| 217 | "counter_approvals", approval["id"], {"used_at": "", "used_for": ""}, |
| 218 | base_dir=base, actor=actor, preserve_read_only=True) |
| 219 | except Exception: |
| 220 | pass |
| 221 | status = getattr(exc, "status", None) |
| 222 | return {"status": status if isinstance(status, int) and 400 <= status < 600 else 409, |
| 223 | "error": f"Nothing was recorded: {str(exc)[:240]}"} |
| 224 | if settle == "refund": |
| 225 | try: |
| 226 | result.update(_refund(base, record_id, bill, payment, line, billing, quantity, |
| 227 | amount, reason, reason_text, approval, approved_by, today, |
| 228 | actor, credit_note_id)) |
| 229 | except Exception as exc: # noqa: BLE001 |
| 230 | # The credit note stands (the debt is cancelled) and the money did |
| 231 | # not go back: the invoice reads credit_owed, which is true, and |
| 232 | # the answer says so rather than claiming a refund. |
| 233 | return {"status": 409, "credit_note_id": credit_note_id, |
| 234 | "error": (f"The credit note {header['number']} was issued, but the refund " |
| 235 | f"could not be recorded ({str(exc)[:200]}). The invoice now shows " |
| 236 | f"credit owed to the customer; record the refund once the cause " |
| 237 | f"is fixed.")} |
| 238 | out = {"status": 200, "ok": True, "settle": settle, "amount_cents": amount, |
| 239 | "order_line_id": line_id, "quantity": quantity, "reason_code": text(reason.get("code")), |
| 240 | "approved_by": approved_by, **result} |
| 241 | if object_corrections.cents(bill.get("tax_cents")) and not object_corrections.cents( |
| 242 | credit_line.get("tax_rate_bps")): |
| 243 | out["note"] = ("The bill's tax was worked out over the whole sale and no rate was " |
| 244 | "stamped on this line, so none of it was given back with the line.") |
| 245 | return out |
| 246 | |
| 247 | |
| 248 | def _refundable_payment(base, bill, payments, amount): |
| 249 | text = object_corrections.text |
| 250 | refunds = _rows(base, "refunds") |
| 251 | for payment in payments: |
| 252 | if (text(payment.get("invoice_id")) != text(bill.get("id")) |
| 253 | or text(payment.get("status") or "received") != "received"): |
| 254 | continue |
| 255 | given = sum(object_corrections.cents(r.get("amount_cents")) for r in refunds |
| 256 | if text(r.get("payment_id")) == text(payment.get("id"))) |
| 257 | if object_corrections.cents(payment.get("amount_cents")) - given >= amount: |
| 258 | return payment |
| 259 | return None |
| 260 | |
| 261 | |
| 262 | def _refund(base, record_id, bill, payment, line, billing, quantity, amount, reason, |
| 263 | reason_text, approval, approved_by, today, actor, credit_note_id): |
| 264 | """The money back for the credit note just issued: a refunds row citing |
| 265 | the line (for the record) and the credit note (whose line is what |
| 266 | counts against what was sold).""" |
| 267 | text = object_corrections.text |
| 268 | row = {"id": record_id, "payment_id": payment["id"], "invoice_id": text(bill.get("id")), |
| 269 | "amount_cents": str(amount), "reason": reason_text, "refunded_on": today, |
| 270 | "order_line_id": text(line.get("id")), "quantity": quantity, |
| 271 | "reason_code": text(reason.get("code")), "approved_by": approved_by, |
| 272 | "credit_note_id": credit_note_id, |
| 273 | "owner_id": text(payment.get("owner_id"))} |
| 274 | if billing: |
| 275 | row["invoice_line_id"] = text(billing.get("id")) |
| 276 | if approval is not None: |
| 277 | row["approval_id"] = text(approval.get("id")) |
| 278 | # access: system write after access check above (the caller read the order and its bill) |
| 279 | stored = object_records.create_collection_record("refunds", row, base_dir=base, actor=actor) |
| 280 | return {"refund_id": stored["id"], "payment_id": payment["id"]} |
| 281 | |
| 282 | |
| 283 | def _credit_note(base, header, credit_line, credit, actor): |
| 284 | """Issue the credit note and apply it, in that order. The rows are |
| 285 | object_corrections.credit_note_documents', shared with the void.""" |
| 286 | record_id = header["id"] |
| 287 | # access: system write after access check above (the caller read the order and its bill) |
| 288 | object_records.create_collection_record("invoices", header, base_dir=base, actor=actor) |
| 289 | try: |
| 290 | # access: system write after access check above (the credit note this call just raised) |
| 291 | object_records.create_collection_record("invoice_lines", credit_line, base_dir=base, |
| 292 | actor=actor, preserve_read_only=True) |
| 293 | except Exception: |
| 294 | # The ceiling refused inside the lock (a racing correction took the |
| 295 | # last unit): the header must not stand alone as an empty credit. |
| 296 | # access: system write after access check above (taking back the header this call wrote) |
| 297 | object_records.update_collection_record("invoices", record_id, {"status": "void"}, |
| 298 | base_dir=base, actor=actor) |
| 299 | raise |
| 300 | # Applied in the same act that issues it, as the exchange applies a |
| 301 | # credit note it sends: the bill owes this much less, and the credit |
| 302 | # note itself is not money anybody owes. |
| 303 | try: |
| 304 | # access: system write after access check above (applying the credit note this call just raised to the bill the caller read) |
| 305 | object_records.create_collection_record("invoice_credits", credit, base_dir=base, |
| 306 | actor=actor) |
| 307 | except Exception: |
| 308 | # A credit note that reduces nothing is the bug this exists to stop: |
| 309 | # take back the header (its line stays as the record, at a void note). |
| 310 | # access: system write after access check above (taking back the header this call wrote) |
| 311 | object_records.update_collection_record("invoices", record_id, {"status": "void"}, |
| 312 | base_dir=base, actor=actor) |
| 313 | raise |
| 314 | return {"credit_note_id": record_id, "number": header["number"], |
| 315 | "invoice_credit_id": credit["id"]} |
| 316 | def _t(value): |
| 317 | return str(value if value is not None else "").strip() |
| 318 | |
| 319 | |
| 320 | def POST(request): |
| 321 | """Every record change this action writes carries why, as the history |
| 322 | entry's message (object_record_changes.change_reason).""" |
| 323 | with object_record_changes.change_reason(f"{_t(request.get('settle')) or 'refund'} of {_t(request.get('quantity')) or '1'} ({_t(request.get('reason_code'))})" + (f": {_t(request.get('note'))}" if _t(request.get("note")) else "")): |
| 324 | return _post(request) |