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.
stock_books.py · 9.8 KB · 224 lines
| 1 | """system_stock_books -- inventory losses reach the books. |
| 2 | |
| 3 | Event handler (HANDLES stock_moves.record.created): when a LOSS move lands |
| 4 | (waste/breakage/theft/expiry/damage/disaster -- plan/inventory-adjustments- |
| 5 | spec.md), compose and post DR loss-expense / CR inventory-asset for |
| 6 | round(quantity * unit_cost_cents), through the shared composer |
| 7 | (object_finance.compose_posted_journal -- this module is the third |
| 8 | composer, the one that triggered the doctrine-#4 extraction). |
| 9 | |
| 10 | Count variances (reason=adjustment, written by action_apply_count) compose |
| 11 | too: a shortage books like a loss; an overage books the mirror (DR |
| 12 | inventory / CR shrinkage). Transfer-shaped adjustments (both locations set) |
| 13 | carry no financial meaning and are skipped. |
| 14 | |
| 15 | Account mapping is configuration (app_settings): |
| 16 | inventory.journal.inventory_account the CR side (asset) |
| 17 | inventory.journal.shrinkage_account the default DR side (expense) |
| 18 | inventory.journal.{reason}_account optional per-reason DR override -- |
| 19 | e.g. route theft to its own account |
| 20 | for the insurance claim. |
| 21 | Soft dependency, same posture as system_books: books absent or accounts |
| 22 | unmapped -> skip with a reason; stock keeping works without books. |
| 23 | |
| 24 | COGS-on-sale composes too, now that a valuation method exists: a sale |
| 25 | move books DR cost-of-goods-sold / CR inventory from the cost STAMPED on |
| 26 | the move (hook_stock_moves stamps the moving weighted average at write |
| 27 | time -- object_stock.weighted_average_cost_cents). This handler never |
| 28 | values anything itself; a costless sale skips rather than reaching for |
| 29 | the product's current cost, because picking a valuation method by |
| 30 | accident inside a handler is exactly what the old boundary existed to |
| 31 | prevent. Purchase composition (DR inventory / CR payable) is still not |
| 32 | here -- that belongs with receiving, which has its own composer. |
| 33 | """ |
| 34 | |
| 35 | import os |
| 36 | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 37 | |
| 38 | import object_finance |
| 39 | import object_collections |
| 40 | import object_records |
| 41 | |
| 42 | HANDLES = ["stock_moves.record.created"] |
| 43 | |
| 44 | ACTOR = "system_stock_books" |
| 45 | |
| 46 | LOSS_REASONS = {"waste", "breakage", "theft", "expiry", "damage", "disaster", |
| 47 | "evaporation", "shrinkage"} |
| 48 | |
| 49 | |
| 50 | def _base_dir(): |
| 51 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 52 | |
| 53 | |
| 54 | def _setting(base, key, default=""): |
| 55 | try: |
| 56 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 57 | if row.get("key") == key and row.get("value"): |
| 58 | return row["value"].strip() |
| 59 | except Exception: |
| 60 | pass |
| 61 | return default |
| 62 | |
| 63 | |
| 64 | def _books_ready(base): |
| 65 | """True when the books can be read, False when they are not installed |
| 66 | (a fact: nothing to post into), BooksUnreadable for anything else. |
| 67 | |
| 68 | It used to answer False for both, so an unreadable fin_journals read as |
| 69 | "books not installed" and the movement was never booked -- and this |
| 70 | handler fires once, on create, so nothing ever booked it later.""" |
| 71 | try: |
| 72 | object_records.read_collection_records("fin_journals", base_dir=base) |
| 73 | object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 74 | except object_collections.CollectionNotFoundError: |
| 75 | return False |
| 76 | except Exception as exc: |
| 77 | raise BooksUnreadable(str(exc)[:160]) from exc |
| 78 | return True |
| 79 | |
| 80 | |
| 81 | class BooksUnreadable(Exception): |
| 82 | """The books are installed but could not be read.""" |
| 83 | |
| 84 | |
| 85 | def _books_unreadable(exc, record_id): |
| 86 | return {"ok": False, "skipped": "books unreadable; nothing was booked", |
| 87 | "books_unreadable": str(exc), "record_id": record_id, |
| 88 | "error": (f"The books could not be read ({exc}), so nothing was " |
| 89 | f"booked for {record_id}. This handler books once, when " |
| 90 | f"the record is created: post the journal by hand once " |
| 91 | f"the books are readable.")} |
| 92 | |
| 93 | |
| 94 | def _loss_amount_cents(move): |
| 95 | """round(quantity * unit_cost_cents) -- Decimal, never float.""" |
| 96 | try: |
| 97 | quantity = Decimal(str(move.get("quantity") or "0")) |
| 98 | unit_cost = int(move.get("unit_cost_cents") or 0) |
| 99 | except (InvalidOperation, ValueError): |
| 100 | return 0 |
| 101 | if quantity <= 0 or unit_cost <= 0: |
| 102 | return 0 |
| 103 | return int((quantity * unit_cost).to_integral_value(rounding=ROUND_HALF_UP)) |
| 104 | |
| 105 | |
| 106 | def compose_for_move(base, move): |
| 107 | """Compose the loss/variance journal for one stock move. |
| 108 | |
| 109 | action_apply_count writes at the storage level (never reaches the |
| 110 | dispatcher) and composes its own variance journal with the SAME |
| 111 | generated_from marker ("stock_moves/{id}"), so the two paths stay |
| 112 | idempotent against each other whichever runs first.""" |
| 113 | reason = (move.get("reason") or "").strip() |
| 114 | from_loc = (move.get("from_location_id") or "").strip() |
| 115 | to_loc = (move.get("to_location_id") or "").strip() |
| 116 | |
| 117 | if reason in LOSS_REASONS: |
| 118 | direction = "loss" |
| 119 | elif reason == "adjustment" and from_loc and not to_loc: |
| 120 | direction = "loss" # count shortage |
| 121 | elif reason == "adjustment" and to_loc and not from_loc: |
| 122 | direction = "overage" # count overage: the mirror |
| 123 | elif reason == "sale" and from_loc: |
| 124 | direction = "sale" |
| 125 | else: |
| 126 | return {"ok": True, "skipped": "not a loss event"} |
| 127 | |
| 128 | try: |
| 129 | ready = _books_ready(base) |
| 130 | except BooksUnreadable as exc: |
| 131 | return _books_unreadable(exc, f"stock_moves/{move.get('id')}") |
| 132 | if not ready: |
| 133 | return {"ok": True, "skipped": "books not installed (fin_journals absent)"} |
| 134 | |
| 135 | inventory_acct = _setting(base, "inventory.journal.inventory_account") |
| 136 | shrinkage_acct = _setting(base, "inventory.journal.shrinkage_account") |
| 137 | if direction == "sale": |
| 138 | # Deliberately NOT defaulted to shrinkage the way loss reasons are. |
| 139 | # Goods sold are not goods lost, and routing cost of sales into a |
| 140 | # shrinkage account would misstate the P&L in a way that still |
| 141 | # balances -- the failure mode nobody notices. Either key works: |
| 142 | # cogs_account reads naturally, sale_account fits the existing |
| 143 | # per-reason override shape. |
| 144 | loss_acct = (_setting(base, "inventory.journal.cogs_account") |
| 145 | or _setting(base, "inventory.journal.sale_account")) |
| 146 | else: |
| 147 | loss_acct = _setting(base, f"inventory.journal.{reason}_account", shrinkage_acct) |
| 148 | if not inventory_acct or not loss_acct: |
| 149 | # Loud, not silent (Corner Cup: a cafe recorded waste for weeks and |
| 150 | # nothing said its books were not receiving any of it). The books |
| 151 | # are installed, so an unmapped account is a gap somebody must |
| 152 | # close: the result names the settings. The move itself stands -- |
| 153 | # stock keeping works without books. |
| 154 | needed = [] |
| 155 | if not inventory_acct: |
| 156 | needed.append("inventory.journal.inventory_account") |
| 157 | if not loss_acct: |
| 158 | needed.append("inventory.journal.cogs_account" if direction == "sale" |
| 159 | else f"inventory.journal.{reason}_account or " |
| 160 | f"inventory.journal.shrinkage_account") |
| 161 | return {"ok": False, "skipped": "accounts unconfigured", "needs_settings": needed, |
| 162 | "error": (f"Nothing was booked for stock move {move.get('id')}: set " |
| 163 | f"{' and '.join(needed)} in app_settings to accounts in the chart " |
| 164 | f"of accounts.")} |
| 165 | |
| 166 | amount = _loss_amount_cents(move) |
| 167 | if amount <= 0: |
| 168 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 169 | |
| 170 | if direction == "sale": |
| 171 | # The one entry a shop cannot do without: the cost of what left |
| 172 | # the shelf stops being an asset and becomes an expense. Without |
| 173 | # it every sale looks like pure margin. |
| 174 | debit_acct, credit_acct = loss_acct, inventory_acct |
| 175 | what = "Cost of goods sold" |
| 176 | elif direction == "loss": |
| 177 | debit_acct, credit_acct = loss_acct, inventory_acct |
| 178 | what = f"Inventory {reason}" if reason in LOSS_REASONS else "Count shortage" |
| 179 | else: |
| 180 | debit_acct, credit_acct = inventory_acct, shrinkage_acct |
| 181 | what = "Count overage" |
| 182 | reference = (move.get("reference") or "").strip() |
| 183 | description = f"{what}: product {move.get('product_id')} x {move.get('quantity')}" |
| 184 | if reference: |
| 185 | description += f" ({reference})" |
| 186 | |
| 187 | return object_finance.compose_posted_journal( |
| 188 | base, |
| 189 | generated_from=f"stock_moves/{move.get('id')}", |
| 190 | date=str(move.get("occurred_at") or move.get("created_at") or "")[:10], |
| 191 | description=description, |
| 192 | lines=[ |
| 193 | {"account_id": debit_acct, "debit_cents": amount, "credit_cents": 0}, |
| 194 | {"account_id": credit_acct, "debit_cents": 0, "credit_cents": amount}, |
| 195 | ], |
| 196 | owner_id=move.get("owner_id", ""), |
| 197 | entity_id=move.get("entity_id", ""), |
| 198 | actor=ACTOR, |
| 199 | ) |
| 200 | |
| 201 | |
| 202 | def EVENT(request): |
| 203 | """Best-effort reaction: every failure returns a reason, never raises |
| 204 | into the dispatcher.""" |
| 205 | # The dispatcher's payload carries the RAW action ("create"); the event |
| 206 | # NAME uses the participle. Accept both (the lesson system_books learned |
| 207 | # in production). |
| 208 | action = str(request.get("action") or "") |
| 209 | action = {"create": "created", "update": "updated", "delete": "deleted"}.get(action, action) |
| 210 | if action != "created" or str(request.get("collection") or "") != "stock_moves": |
| 211 | return {"ok": True, "skipped": "not a stock_moves create"} |
| 212 | record_id = str(request.get("record_id") or "") |
| 213 | if not record_id: |
| 214 | return {"ok": True, "skipped": "no record id"} |
| 215 | |
| 216 | base = _base_dir() |
| 217 | try: |
| 218 | move = object_records.get_collection_record("stock_moves", record_id, base_dir=base) |
| 219 | except Exception: |
| 220 | return {"ok": True, "skipped": "move gone"} |
| 221 | try: |
| 222 | return compose_for_move(base, move) |
| 223 | except Exception as exc: # never break the dispatcher |
| 224 | return {"ok": False, "error": str(exc)[:200]} |