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.
object_corrections.py · 35.9 KB · 729 lines
| 1 | """A sale that has been rung up is corrected by a new record, never rewritten. |
| 2 | |
| 3 | **What was wrong (Corner Cup, a Haiku simulation of a counter café, |
| 4 | 2026-11-30).** A paid soup was turned into a salad by editing the order line |
| 5 | and, separately, the invoice line. Nothing linked the two edits, nothing |
| 6 | asked why, nobody approved, and the documents drifted: the order said |
| 7 | salad, the invoice said paid with 150 still "due". Deleting a line of an |
| 8 | unpaid order left the invoice billing it. Doctrine #3 (money never mutates; |
| 9 | it moves) and #5 (state freezes fields) both said this could not happen; |
| 10 | neither was enforced for lines, because a line's state lives on its parent |
| 11 | and on the payments against the parent. |
| 12 | |
| 13 | **The rule, in three states of the bill that covers a line:** |
| 14 | |
| 15 | - *Not issued* (no invoice, or only a draft or a voided one): the order is |
| 16 | still being written. Anything goes, as before. |
| 17 | - *Issued, nothing received*: the priced facts of a line (what, how many, |
| 18 | at what price) change only by a VOID -- quantity to zero with a reason |
| 19 | code, on the order line and the invoice line together, done by |
| 20 | app-counter's action_counter_void. A line is never deleted: the row and |
| 21 | its reason are the record of what happened. |
| 22 | - *Money received*: nothing priced changes, by anybody. A correction is a |
| 23 | new record citing the original line -- a line refund, a credit note, a |
| 24 | goodwill record or a remake -- so "what was charged" stays true and "what |
| 25 | we gave back, and why" is its own fact. The only line that may still be |
| 26 | added is a zero-priced one (a remake's new kitchen ticket line), which |
| 27 | changes nobody's money. |
| 28 | |
| 29 | The verdict is a locked check on order_lines and on invoice_lines (lock |
| 30 | `ledger`, shared with payments and refunds), so it holds for every writer |
| 31 | -- HTTP, actions, handlers, imports -- and a payment landing at the same |
| 32 | instant as an edit cannot slip between the read and the write. Pure |
| 33 | functions here, no I/O; the two package objects read the rows and ask. |
| 34 | |
| 35 | How an invoice's status reads after a refund or a credit is the owner's |
| 36 | decision of 2026-11-30, written down in money_status below: an issued |
| 37 | invoice's total never changes, a debt is cancelled only by a credit note, |
| 38 | and the status follows the money. So an issued invoice line is never voided |
| 39 | in place either: an item comes off an issued bill by a credit note citing |
| 40 | it (credit_note_documents), and only the order line is voided. A void |
| 41 | restates the ORDER only by the amounts stamped on the voided line itself, |
| 42 | and refuses where the tax was computed over the whole document (see |
| 43 | void_restatement). |
| 44 | """ |
| 45 | |
| 46 | from __future__ import annotations |
| 47 | |
| 48 | import dataclasses |
| 49 | from decimal import Decimal, InvalidOperation |
| 50 | from typing import Any, Iterable, Mapping |
| 51 | |
| 52 | import object_permissions |
| 53 | |
| 54 | # What a line says was sold. A kitchen note (order_lines.line_note) is an |
| 55 | # instruction, not a term of the sale, and stays editable. unit_code (what |
| 56 | # the quantity counts, UN/ECE Rec 20, app-exchange) is a term of the sale: |
| 57 | # ten kilograms and ten bags are different sales, so it freezes with the |
| 58 | # quantity. A partner's line id (order_lines.partner_line_id) is a |
| 59 | # reference, not a term, and stays writable. |
| 60 | ORDER_LINE_PRICED = ("order_id", "product_id", "description", "quantity", "unit_code", |
| 61 | "unit_price_cents", "modifier_cents", "discount_bps", |
| 62 | "line_discount_cents", "line_total_cents", "tax_rate_bps", |
| 63 | "line_tax_cents") |
| 64 | INVOICE_LINE_PRICED = ("invoice_id", "order_line_id", "description", "quantity", "unit_code", |
| 65 | "unit_price_cents", "discount_bps", "line_discount_cents", |
| 66 | "line_total_cents", "tax_rate_bps", "line_tax_cents") |
| 67 | VOID_FIELDS = ("voided_at", "void_reason_code", "voided_by") |
| 68 | |
| 69 | # Frozen once the bill is ISSUED (and not yet paid): the inputs that decide |
| 70 | # what is owed. Narrower than the paid set on purpose. A description and |
| 71 | # the derived amounts (line_total_cents, line_tax_cents) stay writable |
| 72 | # while nothing has been paid, because the totals handlers restate the |
| 73 | # derived amounts and how they round is an owner decision not yet made |
| 74 | # (tests/test_findings_handlers.py M1, M2, M18 hold it as strict xfails |
| 75 | # that edit a description and let the fold restate). Freezing them here |
| 76 | # would change that behaviour as a side effect rather than as a decision. |
| 77 | ORDER_LINE_INPUTS = ("order_id", "product_id", "quantity", "unit_code", "unit_price_cents", |
| 78 | "modifier_cents", "discount_bps", "tax_rate_bps") |
| 79 | INVOICE_LINE_INPUTS = ("invoice_id", "order_line_id", "quantity", "unit_code", "unit_price_cents", |
| 80 | "discount_bps", "tax_rate_bps") |
| 81 | |
| 82 | # The fields a void writes, besides VOID_FIELDS: the line's amounts go to |
| 83 | # zero. Everything else priced must be unchanged by a void. |
| 84 | VOID_ZEROED = ("quantity", "line_total_cents", "line_tax_cents", "line_discount_cents") |
| 85 | |
| 86 | NOT_ISSUED = frozenset({"", "draft", "void"}) |
| 87 | |
| 88 | |
| 89 | def text(value: Any) -> str: |
| 90 | return str(value if value is not None else "").strip() |
| 91 | |
| 92 | |
| 93 | def cents(value: Any) -> int: |
| 94 | try: |
| 95 | return int(Decimal(text(value) or "0")) |
| 96 | except (InvalidOperation, ValueError): |
| 97 | return 0 |
| 98 | |
| 99 | |
| 100 | def qty(value: Any) -> Decimal: |
| 101 | try: |
| 102 | return Decimal(text(value) or "0") |
| 103 | except (InvalidOperation, ValueError): |
| 104 | return Decimal("0") |
| 105 | |
| 106 | |
| 107 | def fmt_qty(value: Decimal) -> str: |
| 108 | return format(value.normalize(), "f") if value else "0" |
| 109 | |
| 110 | |
| 111 | def is_bill(invoice: Mapping[str, Any] | None) -> bool: |
| 112 | """An invoice proper (not a quote or a credit note).""" |
| 113 | return bool(invoice) and text(invoice.get("doc_type") or "invoice") == "invoice" |
| 114 | |
| 115 | |
| 116 | def issued(invoice: Mapping[str, Any] | None) -> bool: |
| 117 | return is_bill(invoice) and text(invoice.get("status")).lower() not in NOT_ISSUED |
| 118 | |
| 119 | |
| 120 | def received_cents(invoice_ids: Iterable[str], payments: Iterable[Mapping[str, Any]]) -> int: |
| 121 | """Money that arrived against these invoices: received payments, before |
| 122 | refunds. A refund corrects a paid bill; it does not un-pay it.""" |
| 123 | wanted = {text(i) for i in invoice_ids if text(i)} |
| 124 | return sum(cents(p.get("amount_cents")) for p in payments |
| 125 | if text(p.get("invoice_id")) in wanted |
| 126 | and text(p.get("status") or "received") == "received") |
| 127 | |
| 128 | |
| 129 | def bills_for_order(order: Mapping[str, Any] | None, |
| 130 | invoices: Iterable[Mapping[str, Any]]) -> list[dict]: |
| 131 | """The invoices billing this order: those raised from it |
| 132 | (source_order_id) and the one it names (orders.invoice_id).""" |
| 133 | if not order: |
| 134 | return [] |
| 135 | order_id = text(order.get("id")) |
| 136 | named = text(order.get("invoice_id")) |
| 137 | return [dict(inv) for inv in invoices if is_bill(inv) |
| 138 | and (text(inv.get("source_order_id")) == order_id |
| 139 | or (named and text(inv.get("id")) == named))] |
| 140 | |
| 141 | |
| 142 | def _changed(existing: Mapping[str, Any], record: Mapping[str, Any], |
| 143 | fields: Iterable[str]) -> list[str]: |
| 144 | return [f for f in fields if text(existing.get(f)) != text(record.get(f))] |
| 145 | |
| 146 | |
| 147 | def is_void(existing: Mapping[str, Any], record: Mapping[str, Any], inputs: Iterable[str]) -> bool: |
| 148 | """Is this update exactly a void: a line not yet voided, now carrying a |
| 149 | reason code and a time, its quantity and amounts zero, no other input |
| 150 | changed?""" |
| 151 | if text(existing.get("voided_at")): |
| 152 | return False |
| 153 | if not (text(record.get("void_reason_code")) and text(record.get("voided_at"))): |
| 154 | return False |
| 155 | if qty(record.get("quantity")) != 0: |
| 156 | return False |
| 157 | for field in VOID_ZEROED: |
| 158 | if text(record.get(field)) not in ("", "0"): |
| 159 | return False |
| 160 | others = [f for f in inputs if f not in VOID_ZEROED] |
| 161 | return not _changed(existing, record, others) |
| 162 | |
| 163 | |
| 164 | def zero_priced(record: Mapping[str, Any]) -> bool: |
| 165 | return (cents(record.get("unit_price_cents")) == 0 |
| 166 | and cents(record.get("modifier_cents")) == 0) |
| 167 | |
| 168 | |
| 169 | def line_refusal(*, kind: str, action: str, existing: Mapping[str, Any] | None, |
| 170 | record: Mapping[str, Any], issued_bill: bool, received: int) -> str | None: |
| 171 | """Why this write to an order line (kind "order") or invoice line |
| 172 | (kind "invoice") may not land, or None. |
| 173 | |
| 174 | issued_bill: the line's bill is issued (not draft, not void). |
| 175 | received: money received against it, in minor units. |
| 176 | """ |
| 177 | priced = ORDER_LINE_PRICED if kind == "order" else INVOICE_LINE_PRICED |
| 178 | inputs = ORDER_LINE_INPUTS if kind == "order" else INVOICE_LINE_INPUTS |
| 179 | what = "order" if kind == "order" else "invoice" |
| 180 | after_payment = (f"This {what} has been paid, so its lines are not changed in " |
| 181 | f"place. Correct it with a new record that cites the line: a " |
| 182 | f"line refund or credit note (action_counter_correct), goodwill, " |
| 183 | f"or a remake.") |
| 184 | if action == "create": |
| 185 | if received > 0 and not zero_priced(record) and kind == "order": |
| 186 | return after_payment |
| 187 | if received > 0 and kind == "invoice": |
| 188 | return after_payment |
| 189 | # Adding a line while nothing is paid stays allowed on both |
| 190 | # documents: checkout raises its invoice as sent and then writes the |
| 191 | # lines, and an operator may raise the bill before the order's lines. |
| 192 | return None |
| 193 | if action == "delete": |
| 194 | if received > 0: |
| 195 | return after_payment |
| 196 | if issued_bill: |
| 197 | return (f"This {what}'s bill has been issued, so a line is never deleted: " |
| 198 | f"void it with a reason (action_counter_void), which removes it " |
| 199 | f"from the order and the invoice together and keeps the record.") |
| 200 | return None |
| 201 | existing = existing or {} |
| 202 | touched = _changed(existing, record, (*priced, *VOID_FIELDS)) |
| 203 | if not touched: |
| 204 | return None |
| 205 | if text(existing.get("voided_at")) and _changed(existing, record, (*inputs, *VOID_FIELDS)): |
| 206 | return "This line was voided; a voided line is not changed again." |
| 207 | if received > 0: |
| 208 | return after_payment |
| 209 | touched = _changed(existing, record, (*inputs, *VOID_FIELDS)) |
| 210 | if touched and issued_bill and kind == "invoice": |
| 211 | # An issued invoice's total never changes (the owner's decision of |
| 212 | # 2026-11-30): an item comes off it by a credit note citing the |
| 213 | # line, which action_counter_void issues. Only an order line is |
| 214 | # voided in place; a draft invoice is still being written. |
| 215 | return (f"This invoice has been issued, so its total never changes: a line comes off " |
| 216 | f"it by a credit note citing the line (action_counter_void issues one), not " |
| 217 | f"by an edit. Changed: {', '.join(touched)}.") |
| 218 | if touched and issued_bill and not is_void(existing, record, inputs): |
| 219 | return (f"This {what}'s bill has been issued, so what a line sold and for how " |
| 220 | f"much changes only by a void with a reason (action_counter_void), " |
| 221 | f"which keeps the order and its invoice in step. Changed: " |
| 222 | f"{', '.join(touched)}.") |
| 223 | return None |
| 224 | |
| 225 | |
| 226 | # --- status follows the money (decision 1, owner, 2026-11-30) ---------------------- |
| 227 | # |
| 228 | # An issued invoice's total never changes. What it still owes moves only by |
| 229 | # money (payments, refunds, bounces) and by credit notes, and its status is |
| 230 | # read off those facts every time one of them moves: |
| 231 | # |
| 232 | # owed = total - credited (a credit note cancels debt) |
| 233 | # net_paid = received - refunded (a refund gives money back; it |
| 234 | # cancels no debt on its own) |
| 235 | # balance = owed - net_paid (invoices.balance_due_cents) |
| 236 | # |
| 237 | # "Refund this sale" is therefore a credit note AND a refund: the credit |
| 238 | # cancels what was owed, the refund returns the money, and the invoice reads |
| 239 | # `refunded` with nothing due. A refund with no credit note leaves the debt |
| 240 | # standing (a payment returned in error), so the invoice reopens -- as does a |
| 241 | # bounced or deleted payment -- and the aging pass duns it again. |
| 242 | # |
| 243 | # The states this decides, and nothing else (draft and void are a person's): |
| 244 | # paid balance 0, something was paid |
| 245 | # partial something paid, something still owed |
| 246 | # sent nothing paid, something owed (aging turns it overdue) |
| 247 | # overdue kept while anything is still owed and it was overdue |
| 248 | # credit_owed balance below 0: the shop owes the customer (a credit |
| 249 | # note on a paid bill before the money goes back, or an |
| 250 | # overpayment) |
| 251 | # refunded the debt was credited away and the money given back |
| 252 | # credited the debt was credited away and nothing was ever paid |
| 253 | |
| 254 | MONEY_STATES = frozenset({"sent", "partial", "overdue", "paid", "credit_owed", |
| 255 | "refunded", "credited"}) |
| 256 | |
| 257 | |
| 258 | def money_status(current: Any, *, total: Any, received: Any, refunded: Any, |
| 259 | credited: Any) -> str: |
| 260 | """The status an issued invoice reads from its money, or `current` |
| 261 | unchanged for a status that is not the money's to move (draft, void, a |
| 262 | quote, a credit note's own row).""" |
| 263 | current = text(current).lower() |
| 264 | if current not in MONEY_STATES: |
| 265 | return current |
| 266 | total, received = cents(total), cents(received) |
| 267 | refunded, credited = cents(refunded), cents(credited) |
| 268 | owed = total - credited |
| 269 | net_paid = received - refunded |
| 270 | balance = owed - net_paid |
| 271 | if balance < 0: |
| 272 | return "credit_owed" |
| 273 | if credited > 0 and owed <= 0: |
| 274 | return "refunded" if received > 0 else "credited" |
| 275 | if balance == 0: |
| 276 | if net_paid > 0: |
| 277 | return "paid" |
| 278 | return "credited" if credited > 0 else current |
| 279 | if net_paid > 0: |
| 280 | return "overdue" if current == "overdue" else "partial" |
| 281 | return "overdue" if current == "overdue" else "sent" |
| 282 | |
| 283 | |
| 284 | # --- reason codes --------------------------------------------------------------- |
| 285 | |
| 286 | ACTS = ("void", "refund", "credit_note", "goodwill", "remake", "waste") |
| 287 | TRUE = ("true", "1", "yes", "on") |
| 288 | |
| 289 | |
| 290 | def truthy(value: Any) -> bool: |
| 291 | return text(value).lower() in TRUE |
| 292 | |
| 293 | |
| 294 | def find_reason(reasons: Iterable[Mapping[str, Any]], code: str, act: str) -> tuple[dict | None, str]: |
| 295 | """(the correction_reasons row, "") or (None, why). The codes are data |
| 296 | (app-counter's correction_reasons), so the refusal lists what may be |
| 297 | cited instead of a schema enum doing it.""" |
| 298 | code = text(code) |
| 299 | usable = [] |
| 300 | found = None |
| 301 | for row in reasons: |
| 302 | acts = {a.strip() for a in text(row.get("applies_to")).split(",") if a.strip()} |
| 303 | if not truthy(row.get("active") or "true") or act not in acts: |
| 304 | continue |
| 305 | usable.append(text(row.get("code"))) |
| 306 | if text(row.get("code")) == code: |
| 307 | found = dict(row) |
| 308 | if found is not None: |
| 309 | return found, "" |
| 310 | listed = ", ".join(sorted(usable)) or "none are configured" |
| 311 | if not code: |
| 312 | return None, f"A reason code is required for a {act.replace('_', ' ')}: {listed}." |
| 313 | return None, (f"'{code}' is not a reason a {act.replace('_', ' ')} may cite. " |
| 314 | f"Use one of: {listed} (a manager adds codes in correction_reasons).") |
| 315 | |
| 316 | |
| 317 | # --- a void restates a document by exactly the voided line --------------------- |
| 318 | |
| 319 | |
| 320 | class VoidRefused(Exception): |
| 321 | """The void cannot be applied without deciding something that is the |
| 322 | owner's to decide (tax basis, a discount's basis).""" |
| 323 | |
| 324 | |
| 325 | def void_restatement(document: Mapping[str, Any], line: Mapping[str, Any], |
| 326 | siblings: Iterable[Mapping[str, Any]] = (), *, |
| 327 | billed: Mapping[str, Any] | None = None, |
| 328 | billed_siblings: Iterable[Mapping[str, Any]] = ()) -> dict[str, str]: |
| 329 | """The total fields an ORDER takes when `line` is voided, by subtracting |
| 330 | exactly what the line itself stamped -- never by re-folding the document, |
| 331 | because a fold must not replace a value it cannot reproduce (AGENTS.md). |
| 332 | |
| 333 | `billed` is the issued invoice line that billed this order line, when |
| 334 | there is one: its stamped rate and share of the tax (decision 2, |
| 335 | 2026-11-30) say what tax the item carried, so a void of a checkout sale |
| 336 | whose tax was computed over the whole bill takes off exactly that. |
| 337 | `billed_siblings` are that invoice's other lines. |
| 338 | |
| 339 | Refuses (VoidRefused) where the answer is still an open owner decision: |
| 340 | - the document carries tax and neither the line nor the invoice line |
| 341 | billing it states a rate (an order with document-level tax and no |
| 342 | issued invoice): how much of the tax was this line's is not recorded; |
| 343 | - the sale carries a basket discount (orders.discount_cents, or a |
| 344 | negative discount line on the invoice): whether it shrinks with the |
| 345 | basket, and by how much, is not decided. |
| 346 | `siblings` are the document's other lines (a discount line is negative). |
| 347 | """ |
| 348 | billed_siblings = list(billed_siblings) + list(siblings) |
| 349 | states_rate = cents(line.get("tax_rate_bps")) > 0 |
| 350 | line_total = cents(line.get("line_total_cents")) |
| 351 | line_tax = cents(line.get("line_tax_cents")) if states_rate else 0 |
| 352 | if billed is not None and cents(billed.get("tax_rate_bps")) > 0: |
| 353 | # Decision 2 (2026-11-30): the rate and the line's share of the |
| 354 | # tax are stamped on the invoice line at issue, so the tax this |
| 355 | # item carried is recorded -- on the line that billed it -- and |
| 356 | # comes off with it, never recomputed. |
| 357 | states_rate = True |
| 358 | line_tax = cents(billed.get("line_tax_cents")) |
| 359 | if cents(document.get("discount_cents")) > 0 or any( |
| 360 | cents(row.get("unit_price_cents")) < 0 or cents(row.get("line_total_cents")) < 0 |
| 361 | for row in billed_siblings): |
| 362 | raise VoidRefused( |
| 363 | "This bill carries a discount worked out over the whole basket, and whether " |
| 364 | "it shrinks when an item is removed is a decision the shop owner has not made " |
| 365 | "yet; nothing was voided.") |
| 366 | if not states_rate and cents(document.get("tax_cents")) != 0: |
| 367 | raise VoidRefused( |
| 368 | "This sale's tax was worked out over the whole bill, not per line, so how " |
| 369 | "much of it this item carried is not recorded. Restating the tax when a line " |
| 370 | "is removed is a decision the shop owner has not made yet (tax basis and " |
| 371 | "rounding); nothing was voided. Refund the line after payment instead, or " |
| 372 | "ask the owner to decide.") |
| 373 | return { |
| 374 | "subtotal_cents": str(cents(document.get("subtotal_cents")) - line_total), |
| 375 | "tax_cents": str(cents(document.get("tax_cents")) - line_tax), |
| 376 | "total_cents": str(cents(document.get("total_cents")) - line_total - line_tax), |
| 377 | } |
| 378 | |
| 379 | |
| 380 | def voided(line: Mapping[str, Any], *, when: str, reason_code: str, by: str, |
| 381 | fields: Iterable[str]) -> dict[str, str]: |
| 382 | """The changes that void a line: quantity and amounts to zero, the |
| 383 | reason, the time and the person. Only fields the schema declares.""" |
| 384 | have = set(fields) |
| 385 | out = {"quantity": "0", "voided_at": when, "void_reason_code": reason_code, "voided_by": by} |
| 386 | for field in ("line_total_cents", "line_tax_cents", "line_discount_cents"): |
| 387 | if field in have and text(line.get(field)) not in ("",): |
| 388 | out[field] = "0" |
| 389 | return {k: v for k, v in out.items() if k in have} |
| 390 | |
| 391 | |
| 392 | # --- goods leave the shelf at the counter ------------------------------------------ |
| 393 | |
| 394 | |
| 395 | def counter_marker(order_id: str, line_id: str) -> str: |
| 396 | """The provenance a move carries when it takes an order line's goods off |
| 397 | the shelf with no shipment (a counter hand-over, a remake's waste). |
| 398 | object_reservations.moved_by_line reads it, so a hold becomes the move |
| 399 | and a shipment later finds the line already moved.""" |
| 400 | return f"orders/{text(order_id)}:line/{text(line_id)}" |
| 401 | |
| 402 | |
| 403 | COUNTER_METHODS = ("counter", "pickup") |
| 404 | |
| 405 | |
| 406 | def to_move(lines: Iterable[Mapping[str, Any]], moved: Mapping[str, Decimal], |
| 407 | tracked: Mapping[str, bool]) -> list[tuple[dict, Decimal]]: |
| 408 | """[(line, quantity still to leave the shelf)] for a hand-over: each |
| 409 | line of a tracked product, less what has already moved for it (by a |
| 410 | shipment, an earlier hand-over or a remake's waste). Voided lines are |
| 411 | quantity zero and move nothing.""" |
| 412 | out = [] |
| 413 | for line in lines: |
| 414 | product_id = text(line.get("product_id")) |
| 415 | if not product_id or not tracked.get(product_id): |
| 416 | continue |
| 417 | rest = qty(line.get("quantity")) - moved.get(text(line.get("id")), Decimal("0")) |
| 418 | if rest > 0: |
| 419 | out.append((dict(line), rest)) |
| 420 | return out |
| 421 | |
| 422 | |
| 423 | # --- the waste log ------------------------------------------------------------------ |
| 424 | |
| 425 | WASTE_DESTINATIONS = ("trash", "compost", "animal_feed", "donation", "rendering", "digester") |
| 426 | |
| 427 | |
| 428 | def weight_cost(weight_grams: Any, cost_per_kg_cents: Any) -> int | None: |
| 429 | """grams x cost per kg / 1000, rounded half up, in whole cents. None when |
| 430 | there is no cost per kilo to estimate with -- unknown, not zero.""" |
| 431 | from decimal import ROUND_HALF_UP |
| 432 | per_kg = text(cost_per_kg_cents) |
| 433 | if not per_kg: |
| 434 | return None |
| 435 | try: |
| 436 | grams = Decimal(text(weight_grams) or "0") |
| 437 | value = grams * Decimal(int(per_kg)) / Decimal(1000) |
| 438 | except (InvalidOperation, ValueError): |
| 439 | return None |
| 440 | return int(value.to_integral_value(rounding=ROUND_HALF_UP)) |
| 441 | |
| 442 | |
| 443 | def count_cost(quantity: Any, unit_cost_cents: Any) -> int | None: |
| 444 | from decimal import ROUND_HALF_UP |
| 445 | if not text(unit_cost_cents): |
| 446 | return None |
| 447 | return int((qty(quantity) * cents(unit_cost_cents)).to_integral_value(rounding=ROUND_HALF_UP)) |
| 448 | |
| 449 | |
| 450 | def licence_warning(*, needs_licence: Any, licence_number: Any, expires_on: Any, today: str) -> str: |
| 451 | """Record and warn, never decide: the sentence a waste row carries when |
| 452 | a licence is marked needed and none is given, or it has expired.""" |
| 453 | if not truthy(needs_licence): |
| 454 | return "" |
| 455 | if not text(licence_number): |
| 456 | return ("Marked as needing a licence or registration, and none was recorded. Check " |
| 457 | "what this destination needs where you are before the waste goes.") |
| 458 | expires = text(expires_on)[:10] |
| 459 | if expires and expires < text(today)[:10]: |
| 460 | return (f"The licence recorded ({text(licence_number)}) expired on {expires}. Check it " |
| 461 | f"is renewed before the waste goes.") |
| 462 | return "" |
| 463 | |
| 464 | |
| 465 | # --- corrections after payment cite the line, and never exceed it ---------------- |
| 466 | |
| 467 | |
| 468 | def corrected_quantity(order_line_id: str, *, refunds: Iterable[Mapping[str, Any]], |
| 469 | invoices: Iterable[Mapping[str, Any]], |
| 470 | invoice_lines: Iterable[Mapping[str, Any]], |
| 471 | exclude_refund_id: str = "", |
| 472 | exclude_invoice_line_id: str = "") -> Decimal: |
| 473 | """How much of an order line has already been corrected: the quantity |
| 474 | of refunds citing it plus the quantity on credit-note lines citing it |
| 475 | (credit notes not voided). A refund and a credit note for the same unit |
| 476 | are the same correction made twice.""" |
| 477 | order_line_id = text(order_line_id) |
| 478 | total = Decimal("0") |
| 479 | for row in refunds: |
| 480 | if text(row.get("credit_note_id")): |
| 481 | # Money back for a credit note: the credit note's line is the |
| 482 | # correction and is counted below; the refund only pays it out. |
| 483 | continue |
| 484 | if (text(row.get("order_line_id")) == order_line_id |
| 485 | and text(row.get("id")) != text(exclude_refund_id)): |
| 486 | total += qty(row.get("quantity")) |
| 487 | credit_notes = {text(inv.get("id")) for inv in invoices |
| 488 | if text(inv.get("doc_type")) == "credit_note" |
| 489 | and text(inv.get("status")).lower() != "void"} |
| 490 | for row in invoice_lines: |
| 491 | if (text(row.get("order_line_id")) == order_line_id |
| 492 | and text(row.get("invoice_id")) in credit_notes |
| 493 | and text(row.get("id")) != text(exclude_invoice_line_id)): |
| 494 | total += qty(row.get("quantity")) |
| 495 | return total |
| 496 | |
| 497 | |
| 498 | def ceiling_refusal(order_line: Mapping[str, Any] | None, wanted: Any, already: Decimal) -> str | None: |
| 499 | """A correction of `wanted` units of a line that already had `already` |
| 500 | corrected: refused when it is not a positive quantity or would correct |
| 501 | more than was sold.""" |
| 502 | if order_line is None: |
| 503 | return "The order line this correction cites does not exist." |
| 504 | want = qty(wanted) |
| 505 | if want <= 0: |
| 506 | return "A correction that cites a line says how many of it (a quantity above zero)." |
| 507 | sold = qty(order_line.get("quantity")) |
| 508 | if already + want > sold: |
| 509 | return (f"{text(order_line.get('description')) or 'This line'} sold " |
| 510 | f"{fmt_qty(sold)}; {fmt_qty(already)} already corrected, so " |
| 511 | f"{fmt_qty(want)} more would correct more than was sold.") |
| 512 | return None |
| 513 | |
| 514 | |
| 515 | def correction_amount(order_line: Mapping[str, Any], quantity: Any) -> int: |
| 516 | """What `quantity` units of a line were charged, priced the way the |
| 517 | line was (object_lines.line_amounts: modifier, line discount, the |
| 518 | line's own tax), the same rule app-returns refunds by. Tax the |
| 519 | document computed over the whole bill is not apportioned here: that is |
| 520 | the owner's open tax-basis decision, so a line correction gives back |
| 521 | the line's net plus only the tax the line itself states.""" |
| 522 | import object_lines |
| 523 | amounts = object_lines.line_amounts({**dict(order_line), "quantity": text(quantity)}) |
| 524 | return amounts["line_total_cents"] + amounts["line_tax_cents"] |
| 525 | |
| 526 | |
| 527 | def credit_note_documents(*, bill: Mapping[str, Any], order: Mapping[str, Any], |
| 528 | line: Mapping[str, Any], billing: Mapping[str, Any] | None, |
| 529 | quantity: Any, reason_code: str, reason_label: str, |
| 530 | approved_by: str, note: str, today: str, credit_note_id: str, |
| 531 | line_id: str, credit_id: str) -> tuple[dict, dict, dict]: |
| 532 | """(header, line, applied credit): the three rows that issue a credit |
| 533 | note for `quantity` of an order line against its issued bill and apply |
| 534 | it at once (one credit-note model: an invoice_credits row, source |
| 535 | counter). Shared by action_counter_correct (after payment) and |
| 536 | action_counter_void (issued, unpaid: an issued invoice's total never |
| 537 | changes, so an item comes off it by a credit note). |
| 538 | |
| 539 | Priced the way the line was billed: the invoice line's own stamped |
| 540 | rate when there is one (tax is never recalculated after issue), its |
| 541 | unit price, modifier and discount. The amount is the credit line's net |
| 542 | plus its tax (object_lines.line_amounts).""" |
| 543 | import object_lines |
| 544 | source = dict(billing or line) |
| 545 | credit_line = {"id": line_id, "invoice_id": credit_note_id, |
| 546 | "description": f"Credit: {text(line.get('description'))}", |
| 547 | "quantity": text(quantity), |
| 548 | "unit_price_cents": str(cents(line.get("unit_price_cents")) |
| 549 | + cents(line.get("modifier_cents"))), |
| 550 | "order_line_id": text(line.get("id")), |
| 551 | "owner_id": text(bill.get("owner_id"))} |
| 552 | if billing: |
| 553 | credit_line["credits_line_id"] = text(billing.get("id")) |
| 554 | credit_line["unit_price_cents"] = text(billing.get("unit_price_cents")) \ |
| 555 | or credit_line["unit_price_cents"] |
| 556 | # unit_code: what the quantity counts (app-exchange's units on lines), |
| 557 | # so one bag credited is sent as one bag, not as one "one". |
| 558 | for field in ("unit_code", "discount_bps", "tax_rate_bps"): |
| 559 | value = text(source.get(field)) or text(line.get(field)) |
| 560 | if value: |
| 561 | credit_line[field] = value |
| 562 | amounts = object_lines.line_amounts(credit_line) |
| 563 | if billing and qty(quantity) == qty(billing.get("quantity")) and text( |
| 564 | billing.get("line_tax_cents")) and cents(billing.get("tax_rate_bps")): |
| 565 | # The whole line back: exactly what it was stamped with at issue, |
| 566 | # its share of the document's tax included (decision 2). Part of a |
| 567 | # line is priced at the original rate, rounded half-up on its own. |
| 568 | amounts = {**amounts, "line_total_cents": cents(billing.get("line_total_cents")), |
| 569 | "line_tax_cents": cents(billing.get("line_tax_cents"))} |
| 570 | credit_line["line_total_cents"] = str(amounts["line_total_cents"]) |
| 571 | credit_line["line_tax_cents"] = str(amounts["line_tax_cents"]) |
| 572 | amount = amounts["line_total_cents"] + amounts["line_tax_cents"] |
| 573 | header = {"id": credit_note_id, "doc_type": "credit_note", |
| 574 | "number": f"CN-{text(bill.get('number'))}-{credit_note_id[:6].upper()}", |
| 575 | "customer_id": text(bill.get("customer_id")), |
| 576 | "customer_name": text(bill.get("customer_name")) or "Customer", |
| 577 | "customer_email": text(bill.get("customer_email")), |
| 578 | "currency": text(bill.get("currency")) or "USD", |
| 579 | "status": "sent", "issue_date": today, |
| 580 | "subtotal_cents": str(amounts["line_total_cents"]), |
| 581 | "tax_cents": str(amounts["line_tax_cents"]), "total_cents": str(amount), |
| 582 | "source_order_id": text(order.get("id")), |
| 583 | "credits_invoice_id": text(bill.get("id")), |
| 584 | "reason_code": reason_code, "approved_by": approved_by, |
| 585 | "notes": (f"Credits {text(bill.get('number'))}: {text(line.get('description'))} " |
| 586 | f"x {text(quantity)} ({reason_label})" + (f". {note}" if note else "")), |
| 587 | "owner_id": text(bill.get("owner_id"))} |
| 588 | credit = {"id": credit_id, "credit_note_id": credit_note_id, |
| 589 | "invoice_id": text(bill.get("id")), "amount_cents": str(amount), |
| 590 | "applied_on": today, "source": "counter", |
| 591 | "owner_id": text(bill.get("owner_id"))} |
| 592 | return header, credit_line, credit |
| 593 | |
| 594 | |
| 595 | def approval_refusal(approval: Mapping[str, Any] | None, *, kind: str, order_line_id: str, |
| 596 | amount: int, caller: str) -> str | None: |
| 597 | """Does this counter_approvals row approve this correction?""" |
| 598 | if approval is None: |
| 599 | return "That approval does not exist." |
| 600 | if text(approval.get("used_at")): |
| 601 | return "That approval has already been used." |
| 602 | if text(approval.get("kind")) not in (kind, "correction"): |
| 603 | return f"That approval is for a {text(approval.get('kind'))}, not a {kind.replace('_', ' ')}." |
| 604 | if not text(approval.get("order_line_id")): |
| 605 | # No blanket approvals: the schema refuses one at creation, and one |
| 606 | # written before that (or below the record API) is not honoured. |
| 607 | return "That approval does not name the item it approves." |
| 608 | if text(approval.get("order_line_id")) != text(order_line_id): |
| 609 | return "That approval is for a different item." |
| 610 | if cents(approval.get("max_amount_cents")) < amount: |
| 611 | return (f"That approval covers up to {cents(approval.get('max_amount_cents'))}; this " |
| 612 | f"correction is {amount}.") |
| 613 | if text(approval.get("owner_id")) == text(caller): |
| 614 | return "An approval is given by somebody other than the person asking for it." |
| 615 | return None |
| 616 | |
| 617 | |
| 618 | def waste_approval_refusal(approval: Mapping[str, Any] | None, *, product_id: str, |
| 619 | quantity: Decimal, caller: str) -> str | None: |
| 620 | """Does this counter_approvals row approve writing off this much of |
| 621 | this product? Only a waste approval naming the product, for at least |
| 622 | the quantity, unused, from somebody else; a correction approval does |
| 623 | not cover waste.""" |
| 624 | if approval is None: |
| 625 | return "That approval does not exist." |
| 626 | if text(approval.get("used_at")): |
| 627 | return "That approval has already been used." |
| 628 | if text(approval.get("kind")) != "waste": |
| 629 | return f"That approval is for a {text(approval.get('kind'))}, not waste." |
| 630 | if not text(approval.get("product_id")): |
| 631 | return "That approval does not name the item it approves." |
| 632 | if text(approval.get("product_id")) != text(product_id): |
| 633 | return "That approval is for a different item." |
| 634 | if qty(approval.get("max_quantity")) < quantity: |
| 635 | return (f"That approval covers up to {fmt_qty(qty(approval.get('max_quantity')))}; this " |
| 636 | f"waste is {fmt_qty(quantity)}.") |
| 637 | if text(approval.get("owner_id")) == text(caller): |
| 638 | return "An approval is given by somebody other than the person asking for it." |
| 639 | return None |
| 640 | |
| 641 | |
| 642 | # --- who may run a counter action ---------------------------------------------------- |
| 643 | # |
| 644 | # The counter actions write payments, refunds, credit notes and stock moves |
| 645 | # that point at records the caller may only read, while those rows' relations |
| 646 | # declare `requires update`. That is deliberate: the action is the grant |
| 647 | # (docs/permissions-model.md "Pointing at a record you may not act on"), so |
| 648 | # the action, not the relation check, has to say who it is for. The server |
| 649 | # asks the execute rule only with enforcement on; with it off, every |
| 650 | # signed-in user reached every counter action (a plain user recorded waste |
| 651 | # with a stock move and paid an invoice they owned). So each action asks |
| 652 | # itself, from the rules that already name its roles. |
| 653 | |
| 654 | |
| 655 | def staff_refusal(access: Any, object_id: str, *, doing: str) -> dict | None: |
| 656 | """None when the caller may run ``object_id`` by role, else a 403 answer. |
| 657 | |
| 658 | Asked of the installed policy, but only of its role grants: the rules |
| 659 | that give a role execute on this object (app-counter's permissions name |
| 660 | them), an admin, and every deny. A public or registered grant, the |
| 661 | access mode and the owner fallback do not count, so this holds whatever |
| 662 | the server's enforcement setting and the box's access mode are. An |
| 663 | unreadable policy refuses. |
| 664 | """ |
| 665 | if role_grants(access, "execute", object_id=object_id): |
| 666 | return None |
| 667 | return {"status": 403, "error": f"Only the shop's staff {doing}."} |
| 668 | |
| 669 | |
| 670 | def role_grants(access: Any, action: str, *, object_id: str | None = None, |
| 671 | collection: str | None = None, |
| 672 | record: Mapping[str, Any] | None = None) -> bool: |
| 673 | """Does a ROLE grant (or admin) allow the caller ``action`` here? |
| 674 | |
| 675 | The question staff_refusal asks, for any action: only the installed |
| 676 | rules whose principal is a role, plus every deny, under role-based |
| 677 | mode. A registered or public grant, an owner-row grant and the owner |
| 678 | fallback do not count, so "this cashier owns the row" never reads as |
| 679 | "this cashier holds the role that may act on every row". Signed-out |
| 680 | callers and an unreadable policy get False. |
| 681 | """ |
| 682 | policy = getattr(access, "policy", None) |
| 683 | if policy is None or not getattr(access, "signed_in", False): |
| 684 | return False |
| 685 | # The owner fallback is switched off for this one question: a row the |
| 686 | # caller owns is not a role grant. |
| 687 | no_fallback = object_permissions.PermissionRule( |
| 688 | effect="deny", actions=frozenset({action.lower()}), |
| 689 | principal=object_permissions.OWNER_FALLBACK, |
| 690 | collection=collection, object_id=object_id, |
| 691 | reason="role grants only") |
| 692 | by_role = dataclasses.replace( |
| 693 | policy, access_mode="role_based", |
| 694 | rules=tuple(rule for rule in policy.rules |
| 695 | if rule.effect == "deny" or rule.principal.startswith("role:")) |
| 696 | + (no_fallback,)) |
| 697 | try: |
| 698 | decision = object_permissions.check_permission( |
| 699 | access.subject, action, policy=by_role, object_id=object_id, |
| 700 | collection=collection, record=record) |
| 701 | except (TypeError, ValueError): |
| 702 | return False |
| 703 | return bool(decision.allowed) |
| 704 | |
| 705 | |
| 706 | def denied_by_rule(access: Any, action: str, collection: str, record: Mapping[str, Any]) -> bool: |
| 707 | """Does an explicit deny rule refuse the caller ``action`` on this record? |
| 708 | |
| 709 | For a role-granted action that reads a record under its own authority |
| 710 | rather than as the caller: the caller's grants do not decide, but a |
| 711 | deny the box wrote for them still wins. Only the deny rules are asked |
| 712 | (an admin passes, as with every rule); an unreadable policy refuses. |
| 713 | ``action`` is read or execute: the deny-only policy allows those by |
| 714 | its access mode, so any other action would read as denied. |
| 715 | """ |
| 716 | if action not in object_permissions.PUBLIC_READ_ACTIONS: |
| 717 | raise ValueError(f"denied_by_rule asks read or execute, not {action!r}") |
| 718 | policy = getattr(access, "policy", None) |
| 719 | if policy is None: |
| 720 | return True |
| 721 | denies_only = dataclasses.replace( |
| 722 | policy, access_mode="public", |
| 723 | rules=tuple(rule for rule in policy.rules if rule.effect == "deny")) |
| 724 | try: |
| 725 | decision = object_permissions.check_permission( |
| 726 | access.subject, action, policy=denies_only, collection=collection, record=record) |
| 727 | except (TypeError, ValueError): |
| 728 | return True |
| 729 | return not decision.allowed |