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_void.py · 12.1 KB · 232 lines
| 1 | """action_counter_void -- take an item off an unpaid sale, with a reason, |
| 2 | from the order and its invoice together. |
| 3 | |
| 4 | POST {"order_line_id": "...", "reason_code": "customer_error", "note": "..."} |
| 5 | |
| 6 | **What was wrong (Corner Cup, a Haiku simulation of a counter cafe).** A |
| 7 | cashier removing an item deleted the order line; the invoice kept billing |
| 8 | it, because nothing linked the two documents and nothing asked why. After |
| 9 | payment the same staff edited lines in place on each document separately. |
| 10 | |
| 11 | **What a void is.** The order line goes to quantity zero with voided_at, |
| 12 | void_reason_code and voided_by stamped; the row stays, so the receipt |
| 13 | history still shows what was rung up and why it came off, and the order's |
| 14 | totals are restated by exactly what the voided line stamped |
| 15 | (object_corrections.void_restatement), never by re-folding the order. |
| 16 | |
| 17 | An ISSUED invoice is not restated: its total never changes (the owner's |
| 18 | decision of 2026-11-30). Each invoice line billing the item is credited by |
| 19 | a credit note citing it (object_corrections.credit_note_documents, the |
| 20 | same rows action_counter_correct writes), applied at once, so the invoice |
| 21 | owes exactly that much less and still shows what was billed. This used to |
| 22 | zero the invoice line and lower the invoice's total in place. |
| 23 | |
| 24 | The locked check settled_line accepts the order line's void while nothing |
| 25 | has been paid, and nothing once money has arrived: a paid sale is corrected |
| 26 | by action_counter_correct, citing the line. |
| 27 | |
| 28 | **Who.** A cashier may void an unpaid line (execute grant: cashier, shift |
| 29 | lead, manager, owner). The caller must be able to read the order through |
| 30 | the permission engine; the writes are this object's, made in process, and |
| 31 | attributed to the caller (actor "action_counter_void:<user>"). |
| 32 | |
| 33 | **What it refuses, and why it does not guess.** A reason code that |
| 34 | correction_reasons does not list for voids (data, so a shop adds its own); a |
| 35 | line already voided; a paid bill; an issued bill with no invoice line linked |
| 36 | to this order line (raised before checkout stamped the link -- voiding one |
| 37 | document alone is the bug this exists to stop); and the two owner decisions |
| 38 | object_corrections names: tax computed over the whole document, and a |
| 39 | basket discount. Each refusal writes nothing. |
| 40 | |
| 41 | **Order of writes.** Every check runs first. The invoice lines are voided |
| 42 | before the order line (the bill is what a customer pays from), each write a |
| 43 | compare-and-set on the row as read; if a later write fails the answer says |
| 44 | exactly which documents were changed, rather than claiming success. |
| 45 | """ |
| 46 | |
| 47 | from __future__ import annotations |
| 48 | |
| 49 | import os |
| 50 | from datetime import datetime, timezone |
| 51 | |
| 52 | import object_access |
| 53 | import object_collections |
| 54 | import object_corrections |
| 55 | import object_ids |
| 56 | import object_record_changes |
| 57 | import object_records |
| 58 | import object_schemas |
| 59 | |
| 60 | ACTOR = "action_counter_void" |
| 61 | |
| 62 | |
| 63 | def _base_dir(): |
| 64 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 65 | |
| 66 | |
| 67 | def _fields(base, collection): |
| 68 | try: |
| 69 | schema = object_schemas.get_schema(collection, base_dir=base) |
| 70 | except Exception: |
| 71 | return set() |
| 72 | return {f.get("name") for f in schema.get("fields") or []} |
| 73 | |
| 74 | |
| 75 | def _rows(base, collection): |
| 76 | try: |
| 77 | # access: every caller reaches this only after access.get on the order above; rows are filtered to that order |
| 78 | return object_records.read_collection_records(collection, base_dir=base) |
| 79 | except object_collections.CollectionNotFoundError: |
| 80 | return [] |
| 81 | |
| 82 | |
| 83 | def _post(request): |
| 84 | text = object_corrections.text |
| 85 | base = _base_dir() |
| 86 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 87 | if not access.signed_in: |
| 88 | return {"status": 401, "error": "Sign in to void an item."} |
| 89 | staff = object_corrections.staff_refusal(access, "action_counter_void", doing="void an item here") |
| 90 | if staff: |
| 91 | return staff |
| 92 | line_id = text(request.get("order_line_id")) |
| 93 | if not line_id: |
| 94 | return {"status": 400, "error": "order_line_id is required."} |
| 95 | line = access.get("order_lines", line_id) |
| 96 | if line is None: |
| 97 | return {"status": 404, "error": f"No order line {line_id}."} |
| 98 | order = access.get("orders", text(line.get("order_id"))) |
| 99 | if order is None: |
| 100 | return {"status": 404, "error": f"No order for line {line_id}."} |
| 101 | if text(line.get("voided_at")): |
| 102 | return {"status": 409, "error": "That item was already voided.", |
| 103 | "voided_at": line.get("voided_at"), |
| 104 | "void_reason_code": line.get("void_reason_code")} |
| 105 | |
| 106 | # access: reason codes are shop configuration every staff role reads |
| 107 | reasons = object_records.read_collection_records("correction_reasons", base_dir=base) |
| 108 | reason, why = object_corrections.find_reason(reasons, request.get("reason_code"), "void") |
| 109 | if reason is None: |
| 110 | return {"status": 422, "error": why} |
| 111 | |
| 112 | invoices = [inv for inv in object_corrections.bills_for_order(order, _rows(base, "invoices")) |
| 113 | if access.can("read", "invoices", inv)] |
| 114 | payments = _rows(base, "payments") |
| 115 | received = object_corrections.received_cents([i.get("id") for i in invoices], payments) |
| 116 | if received > 0: |
| 117 | return {"status": 409, |
| 118 | "error": ("This sale has been paid, so an item is not voided. Correct it with " |
| 119 | "a line refund or credit note citing the item " |
| 120 | "(action_counter_correct)."), |
| 121 | "received_cents": received} |
| 122 | issued = [inv for inv in invoices if object_corrections.issued(inv)] |
| 123 | # An invoice already sent to a trading partner's box (app-exchange) is in |
| 124 | # their books as it was signed; restating ours alone would make the two |
| 125 | # sets of books disagree. The exchange corrects a sent document with a |
| 126 | # new one -- a credit note citing the line -- never a second copy. |
| 127 | sent = sorted({text(row.get("partner_domain")) for row in _rows(base, "exchange_outbox") |
| 128 | if text(row.get("source_collection")) == "invoices" |
| 129 | and text(row.get("source_record_id")) in {text(i.get("id")) for i in issued} |
| 130 | and text(row.get("document_type")) == "invoice"}) |
| 131 | if sent: |
| 132 | return {"status": 409, |
| 133 | "error": (f"This invoice was sent to {', '.join(sent)} through the exchange, so " |
| 134 | f"voiding a line here would leave their books billing it. Nothing was " |
| 135 | f"voided; issue a credit note citing the item instead."), |
| 136 | "sent_to": sent} |
| 137 | all_invoice_lines = _rows(base, "invoice_lines") |
| 138 | billing = [row for row in all_invoice_lines |
| 139 | if text(row.get("order_line_id")) == line_id |
| 140 | and text(row.get("invoice_id")) in {text(i.get("id")) for i in issued} |
| 141 | and access.can("read", "invoice_lines", row)] |
| 142 | billed_invoices = {text(row.get("invoice_id")) for row in billing} |
| 143 | unlinked = [text(inv.get("id")) for inv in issued if text(inv.get("id")) not in billed_invoices] |
| 144 | if unlinked: |
| 145 | return {"status": 409, |
| 146 | "error": ("This order's invoice has no line linked to this item (it was raised " |
| 147 | "before invoice lines named the order line they bill), so voiding the " |
| 148 | "order alone would leave the invoice billing it. Nothing was voided; " |
| 149 | "void the invoice and raise a new one."), |
| 150 | "invoice_ids": unlinked} |
| 151 | |
| 152 | # The restatements, decided before anything is written. The ORDER is |
| 153 | # restated by exactly the voided line; an issued INVOICE is not |
| 154 | # restated at all -- its total never changes (the owner's decision of |
| 155 | # 2026-11-30) -- so each invoice line billing this item is credited by a |
| 156 | # credit note applied at once, and the invoice owes that much less. |
| 157 | order_lines = [row for row in _rows(base, "order_lines") |
| 158 | if text(row.get("order_id")) == text(order.get("id"))] |
| 159 | billed = billing[0] if billing else None |
| 160 | billed_siblings = [row for row in all_invoice_lines |
| 161 | if billed is not None |
| 162 | and text(row.get("invoice_id")) == text(billed.get("invoice_id")) |
| 163 | and text(row.get("id")) != text(billed.get("id"))] |
| 164 | try: |
| 165 | order_changes = object_corrections.void_restatement( |
| 166 | order, line, [row for row in order_lines if text(row.get("id")) != line_id], |
| 167 | billed=billed, billed_siblings=billed_siblings) |
| 168 | except object_corrections.VoidRefused as exc: |
| 169 | return {"status": 409, "error": str(exc)} |
| 170 | |
| 171 | who = access.user_id |
| 172 | when = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") |
| 173 | actor = f"{ACTOR}:{who}" |
| 174 | reason_code = text(reason.get("code")) |
| 175 | note = text(request.get("note"))[:300] |
| 176 | credits = [] |
| 177 | for row in billing: |
| 178 | invoice = next(i for i in issued if text(i.get("id")) == text(row.get("invoice_id"))) |
| 179 | credits.append(object_corrections.credit_note_documents( |
| 180 | bill=invoice, order=order, line=line, billing=row, quantity=row.get("quantity"), |
| 181 | reason_code=reason_code, reason_label=text(reason.get("label")), |
| 182 | approved_by=who, note=note, today=when[:10], |
| 183 | credit_note_id=object_ids.new_uuid4(), line_id=object_ids.new_uuid4(), |
| 184 | credit_id=object_ids.new_uuid4())) |
| 185 | done = [] |
| 186 | try: |
| 187 | for header, credit_line, credit in credits: |
| 188 | # access: system write after access check above (the caller read the invoice this credits) |
| 189 | object_records.create_collection_record("invoices", header, base_dir=base, actor=actor) |
| 190 | done.append(f"invoices/{header['id']}") |
| 191 | # access: system write after access check above (the credit note this call just raised) |
| 192 | object_records.create_collection_record("invoice_lines", credit_line, base_dir=base, |
| 193 | actor=actor, preserve_read_only=True) |
| 194 | done.append(f"invoice_lines/{credit_line['id']}") |
| 195 | # access: system write after access check above (applying the credit note this call just raised) |
| 196 | object_records.create_collection_record("invoice_credits", credit, base_dir=base, |
| 197 | actor=actor) |
| 198 | done.append(f"invoice_credits/{credit['id']}") |
| 199 | # access: system write after access check above (access.get on the order line) |
| 200 | object_records.update_collection_record( |
| 201 | "order_lines", line_id, |
| 202 | object_corrections.voided(line, when=when, reason_code=reason_code, by=who, |
| 203 | fields=_fields(base, "order_lines")), |
| 204 | base_dir=base, actor=actor, preserve_read_only=True, |
| 205 | expected_rev=object_records.compute_record_rev(line)) |
| 206 | done.append(f"order_lines/{line_id}") |
| 207 | # access: system write after access check above (access.get on the order) |
| 208 | object_records.update_collection_record( |
| 209 | "orders", order["id"], order_changes, base_dir=base, actor=actor) |
| 210 | done.append(f"orders/{order['id']}") |
| 211 | except Exception as exc: # noqa: BLE001 -- say exactly what landed |
| 212 | status = getattr(exc, "status", None) or 409 |
| 213 | return {"status": status if isinstance(status, int) and 400 <= status < 600 else 409, |
| 214 | "error": (f"The void stopped part way: {str(exc)[:200]}. " |
| 215 | + (f"Already changed: {', '.join(done)}." if done |
| 216 | else "Nothing was changed.")), |
| 217 | "changed": done} |
| 218 | return {"status": 200, "ok": True, "order_line_id": line_id, |
| 219 | "reason_code": reason_code, "note": note, "voided_by": who, "voided_at": when, |
| 220 | "invoice_line_ids": [row["id"] for row in billing], |
| 221 | "credit_note_ids": [header["id"] for header, _, _ in credits], |
| 222 | "credited_cents": sum(int(header["total_cents"]) for header, _, _ in credits), |
| 223 | "order_totals": order_changes} |
| 224 | def _t(value): |
| 225 | return str(value if value is not None else "").strip() |
| 226 | |
| 227 | |
| 228 | def POST(request): |
| 229 | """Every record change this action writes carries why, as the history |
| 230 | entry's message (object_record_changes.change_reason).""" |
| 231 | with object_record_changes.change_reason(f"void ({_t(request.get('reason_code'))})" + (f": {_t(request.get('note'))}" if _t(request.get("note")) else "")): |
| 232 | return _post(request) |