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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
stock_books.py · 7.6 KB · 182 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_records |
| 40 | |
| 41 | HANDLES = ["stock_moves.record.created"] |
| 42 | |
| 43 | ACTOR = "system_stock_books" |
| 44 | |
| 45 | LOSS_REASONS = {"waste", "breakage", "theft", "expiry", "damage", "disaster"} |
| 46 | |
| 47 | |
| 48 | def _base_dir(): |
| 49 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 50 | |
| 51 | |
| 52 | def _setting(base, key, default=""): |
| 53 | try: |
| 54 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 55 | if row.get("key") == key and row.get("value"): |
| 56 | return row["value"].strip() |
| 57 | except Exception: |
| 58 | pass |
| 59 | return default |
| 60 | |
| 61 | |
| 62 | def _books_ready(base): |
| 63 | try: |
| 64 | object_records.read_collection_records("fin_journals", base_dir=base) |
| 65 | object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 66 | except Exception: |
| 67 | return False |
| 68 | return True |
| 69 | |
| 70 | |
| 71 | def _loss_amount_cents(move): |
| 72 | """round(quantity * unit_cost_cents) -- Decimal, never float.""" |
| 73 | try: |
| 74 | quantity = Decimal(str(move.get("quantity") or "0")) |
| 75 | unit_cost = int(move.get("unit_cost_cents") or 0) |
| 76 | except (InvalidOperation, ValueError): |
| 77 | return 0 |
| 78 | if quantity <= 0 or unit_cost <= 0: |
| 79 | return 0 |
| 80 | return int((quantity * unit_cost).to_integral_value(rounding=ROUND_HALF_UP)) |
| 81 | |
| 82 | |
| 83 | def compose_for_move(base, move): |
| 84 | """Compose the loss/variance journal for one stock move. |
| 85 | |
| 86 | action_apply_count writes at the storage level (never reaches the |
| 87 | dispatcher) and composes its own variance journal with the SAME |
| 88 | generated_from marker ("stock_moves/{id}"), so the two paths stay |
| 89 | idempotent against each other whichever runs first.""" |
| 90 | reason = (move.get("reason") or "").strip() |
| 91 | from_loc = (move.get("from_location_id") or "").strip() |
| 92 | to_loc = (move.get("to_location_id") or "").strip() |
| 93 | |
| 94 | if reason in LOSS_REASONS: |
| 95 | direction = "loss" |
| 96 | elif reason == "adjustment" and from_loc and not to_loc: |
| 97 | direction = "loss" # count shortage |
| 98 | elif reason == "adjustment" and to_loc and not from_loc: |
| 99 | direction = "overage" # count overage: the mirror |
| 100 | elif reason == "sale" and from_loc: |
| 101 | direction = "sale" |
| 102 | else: |
| 103 | return {"ok": True, "skipped": "not a loss event"} |
| 104 | |
| 105 | if not _books_ready(base): |
| 106 | return {"ok": True, "skipped": "books not installed (fin_journals absent)"} |
| 107 | |
| 108 | inventory_acct = _setting(base, "inventory.journal.inventory_account") |
| 109 | shrinkage_acct = _setting(base, "inventory.journal.shrinkage_account") |
| 110 | if direction == "sale": |
| 111 | # Deliberately NOT defaulted to shrinkage the way loss reasons are. |
| 112 | # Goods sold are not goods lost, and routing cost of sales into a |
| 113 | # shrinkage account would misstate the P&L in a way that still |
| 114 | # balances -- the failure mode nobody notices. Either key works: |
| 115 | # cogs_account reads naturally, sale_account fits the existing |
| 116 | # per-reason override shape. |
| 117 | loss_acct = (_setting(base, "inventory.journal.cogs_account") |
| 118 | or _setting(base, "inventory.journal.sale_account")) |
| 119 | else: |
| 120 | loss_acct = _setting(base, f"inventory.journal.{reason}_account", shrinkage_acct) |
| 121 | if not inventory_acct or not loss_acct: |
| 122 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 123 | |
| 124 | amount = _loss_amount_cents(move) |
| 125 | if amount <= 0: |
| 126 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 127 | |
| 128 | if direction == "sale": |
| 129 | # The one entry a shop cannot do without: the cost of what left |
| 130 | # the shelf stops being an asset and becomes an expense. Without |
| 131 | # it every sale looks like pure margin. |
| 132 | debit_acct, credit_acct = loss_acct, inventory_acct |
| 133 | what = "Cost of goods sold" |
| 134 | elif direction == "loss": |
| 135 | debit_acct, credit_acct = loss_acct, inventory_acct |
| 136 | what = f"Inventory {reason}" if reason in LOSS_REASONS else "Count shortage" |
| 137 | else: |
| 138 | debit_acct, credit_acct = inventory_acct, shrinkage_acct |
| 139 | what = "Count overage" |
| 140 | reference = (move.get("reference") or "").strip() |
| 141 | description = f"{what}: product {move.get('product_id')} x {move.get('quantity')}" |
| 142 | if reference: |
| 143 | description += f" ({reference})" |
| 144 | |
| 145 | return object_finance.compose_posted_journal( |
| 146 | base, |
| 147 | generated_from=f"stock_moves/{move.get('id')}", |
| 148 | date=str(move.get("occurred_at") or move.get("created_at") or "")[:10], |
| 149 | description=description, |
| 150 | lines=[ |
| 151 | {"account_id": debit_acct, "debit_cents": amount, "credit_cents": 0}, |
| 152 | {"account_id": credit_acct, "debit_cents": 0, "credit_cents": amount}, |
| 153 | ], |
| 154 | owner_id=move.get("owner_id", ""), |
| 155 | entity_id=move.get("entity_id", ""), |
| 156 | actor=ACTOR, |
| 157 | ) |
| 158 | |
| 159 | |
| 160 | def EVENT(request): |
| 161 | """Best-effort reaction: every failure returns a reason, never raises |
| 162 | into the dispatcher.""" |
| 163 | # The dispatcher's payload carries the RAW action ("create"); the event |
| 164 | # NAME uses the participle. Accept both (the lesson system_books learned |
| 165 | # in production). |
| 166 | action = str(request.get("action") or "") |
| 167 | action = {"create": "created", "update": "updated", "delete": "deleted"}.get(action, action) |
| 168 | if action != "created" or str(request.get("collection") or "") != "stock_moves": |
| 169 | return {"ok": True, "skipped": "not a stock_moves create"} |
| 170 | record_id = str(request.get("record_id") or "") |
| 171 | if not record_id: |
| 172 | return {"ok": True, "skipped": "no record id"} |
| 173 | |
| 174 | base = _base_dir() |
| 175 | try: |
| 176 | move = object_records.get_collection_record("stock_moves", record_id, base_dir=base) |
| 177 | except Exception: |
| 178 | return {"ok": True, "skipped": "move gone"} |
| 179 | try: |
| 180 | return compose_for_move(base, move) |
| 181 | except Exception as exc: # never break the dispatcher |
| 182 | return {"ok": False, "error": str(exc)[:200]} |