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_moves.py · 6.0 KB · 137 lines
| 1 | """Pre-write hook for stock_moves: loss-shape gates + cost stamping. |
| 2 | |
| 3 | Three jobs (the first two from plan/inventory-adjustments-spec.md): |
| 4 | |
| 5 | - A GATE the schema can't express: a LOSS move (waste/breakage/theft/ |
| 6 | expiry/damage/disaster) has no destination -- you cannot waste goods |
| 7 | INTO a shelf. (That it must LEAVE a real location is the schema's |
| 8 | `required_when` on from_location_id, and that quantity is positive -- |
| 9 | direction comes from from/to locations, corrections are new compensating |
| 10 | moves, never negative quantities -- is its `exclusive_min: 0`; both are |
| 11 | checked for every writer, which this hook never was.) |
| 12 | |
| 13 | - STAMPS unit_cost_cents when the client omitted it (docs/logic-decisions.md |
| 14 | #1: the cost at the moment of movement; editing the product's cost |
| 15 | tomorrow must not reprice yesterday's loss). A client-supplied cost is |
| 16 | kept -- purchases carry their invoice cost. A SALE is stamped with the |
| 17 | moving weighted average of stock actually on hand; everything else, and |
| 18 | a sale with no priced acquisitions behind it, falls back to |
| 19 | products.cost_cents. |
| 20 | |
| 21 | - THE LEDGER IS APPEND-ONLY, and that is a permission rule, not code here. |
| 22 | Stock levels ARE the moves (AGENTS.md): there is no other number, so |
| 23 | editing or deleting a move rewrites what is on the shelf with nothing to |
| 24 | show for it. This hook used to refuse a non-admin's edit or delete; the |
| 25 | rules now grant registered users create and read of the moves they |
| 26 | recorded and nothing else, and deny the owner fallback for update and |
| 27 | delete (permissions/rules.json). A person's correction is a new |
| 28 | compensating move. An admin can still edit or delete (a mistyped ledger |
| 29 | has to be repairable by somebody), but an admin's edit still passes the |
| 30 | shape gates above. The cost stamp is create-only: an edit never |
| 31 | re-prices a move. |
| 32 | |
| 33 | Trusted server-side writers (receipt posting, order fulfilment, counts, |
| 34 | returns, drop-ship) go through object_records and do not reach this hook. |
| 35 | |
| 36 | A read this hook needs and cannot make is a refusal (503), never a |
| 37 | fallback: stamping a sale at the typed-in standard cost because the |
| 38 | average could not be read is a wrong number written down for good. |
| 39 | """ |
| 40 | |
| 41 | import os |
| 42 | |
| 43 | import object_collections |
| 44 | import object_records |
| 45 | import object_stock |
| 46 | |
| 47 | LOSS_REASONS = {"waste", "breakage", "theft", "expiry", "damage", "disaster", |
| 48 | "evaporation", "shrinkage"} |
| 49 | |
| 50 | _MISSING = (object_records.RecordNotFoundError, |
| 51 | object_collections.CollectionNotFoundError, |
| 52 | object_records.InvalidRecordIdError) |
| 53 | |
| 54 | |
| 55 | def _base_dir(): |
| 56 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 57 | |
| 58 | |
| 59 | def _stored(value): |
| 60 | return "" if value is None else str(value) |
| 61 | |
| 62 | |
| 63 | def BEFORE_WRITE(request): |
| 64 | action = request.get("action") |
| 65 | if action not in ("create", "update"): |
| 66 | return None |
| 67 | record = request.get("record") or {} |
| 68 | |
| 69 | if action == "update": |
| 70 | existing = request.get("existing") or {} |
| 71 | changes = request.get("changes") or {} |
| 72 | # A change is a submitted field whose value would differ: a form |
| 73 | # posts everything it shows. |
| 74 | changed = sorted(name for name in changes |
| 75 | if name != "id" and _stored(record.get(name)) != _stored(existing.get(name))) |
| 76 | if not changed: |
| 77 | return None |
| 78 | |
| 79 | reason = (record.get("reason") or "").strip() |
| 80 | if reason in LOSS_REASONS: |
| 81 | if (record.get("to_location_id") or "").strip(): |
| 82 | return {"error": f"A {reason} move cannot have a destination -- " |
| 83 | "lost goods leave the system. Clear " |
| 84 | "to_location_id, or use reason=transfer.", |
| 85 | "status": 400} |
| 86 | |
| 87 | if action != "create": |
| 88 | return None # the cost is stamped at the moment of movement, once |
| 89 | |
| 90 | if not str(record.get("unit_cost_cents") or "").strip(): |
| 91 | product_id = record.get("product_id") or "" |
| 92 | |
| 93 | # A SALE is valued, not priced. The cost that leaves with the goods |
| 94 | # is the moving weighted average of what is actually on the shelf |
| 95 | # (object_stock.weighted_average_cost_cents) -- computed here, |
| 96 | # BEFORE this move joins the log, so it is the average at the |
| 97 | # moment of sale and excludes the sale itself. |
| 98 | # |
| 99 | # products.cost_cents is a standard cost: a planning figure someone |
| 100 | # typed, not what was paid. It stays the fallback for a product |
| 101 | # with no priced acquisitions yet, and it stays the primary for |
| 102 | # losses -- writing off a broken mug at standard cost is fine, |
| 103 | # while reporting cost of SALES at a typed-in number is how gross |
| 104 | # margin quietly becomes fiction. |
| 105 | if reason == "sale": |
| 106 | try: |
| 107 | average = object_stock.average_cost_for_product( |
| 108 | product_id, base_dir=_base_dir()) |
| 109 | except Exception: |
| 110 | # Falling through to products.cost_cents here stamped a |
| 111 | # sale of stock bought at 800 with the typed-in 500, for |
| 112 | # good: the stamp is a point-in-time fact. |
| 113 | return {"error": "The stock ledger could not be read, so this " |
| 114 | "sale cannot be costed at what the goods on " |
| 115 | "hand actually cost. Nothing was recorded.", |
| 116 | "status": 503} |
| 117 | if average: |
| 118 | stamped = dict(record) |
| 119 | stamped["unit_cost_cents"] = str(average) |
| 120 | return {"record": stamped} |
| 121 | |
| 122 | try: |
| 123 | product = object_records.get_collection_record( |
| 124 | "products", product_id, base_dir=_base_dir()) |
| 125 | except _MISSING: |
| 126 | return None # relation validation owns a missing product |
| 127 | except Exception: |
| 128 | return {"error": "The product could not be read, so this move " |
| 129 | "cannot be stamped with its cost. Nothing was " |
| 130 | "recorded.", |
| 131 | "status": 503} |
| 132 | cost = str(product.get("cost_cents") or "").strip() |
| 133 | if cost: |
| 134 | stamped = dict(record) |
| 135 | stamped["unit_cost_cents"] = cost |
| 136 | return {"record": stamped} |
| 137 | return None |