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.
apply_count.py · 13.3 KB · 279 lines
| 1 | """action_apply_count -- reconcile a physical count against derived stock. |
| 2 | |
| 3 | The inventory adjusting entry proper (plan/inventory-adjustments-spec.md |
| 4 | section 4): POST {product_id, location_id, counted_qty, optional counted_on}. |
| 5 | Reads derived on-hand (object_stock -- levels are NEVER stored), computes |
| 6 | the variance, and writes ONE compensating adjustment move: shortage moves |
| 7 | stock OUT of the location, overage moves it IN, zero variance is a no-op. |
| 8 | reason=adjustment + reference "count variance" keeps count corrections |
| 9 | distinguishable from the named loss reasons (waste/theft/... say what |
| 10 | happened; a count variance says only that the book number was wrong). |
| 11 | |
| 12 | The variance journal is composed here as well (DR shrinkage / CR inventory |
| 13 | for a shortage, the mirror for an overage): this action writes at the |
| 14 | storage level, which never reaches the event dispatcher, so it cannot rely |
| 15 | on system_stock_books firing. The shared generated_from marker |
| 16 | ("stock_moves/{id}") keeps the two paths idempotent against each other. |
| 17 | |
| 18 | Who may count: only someone the API would let UPDATE the product and READ |
| 19 | the location (object_access, the same policy file). Until 2026-11-28 any |
| 20 | signed-in user could post a count against anybody's product at anybody's |
| 21 | location, which wrote a stock move into the owner's derived stock and told |
| 22 | the caller the owner's on-hand quantity. Refused and missing are one 404. |
| 23 | |
| 24 | Two counts against the same shelf post one variance. A double click (or |
| 25 | two people counting one shelf at once) used to read the same on-hand |
| 26 | figure and BOTH write the adjustment: a shelf counted at 7 of a booked 10 |
| 27 | ended at 4, with the shrinkage booked twice. The move id is now derived |
| 28 | from the state the variance was computed from (object_stock.location_state: |
| 29 | which moves the on-hand figure folded), so the second count against the |
| 30 | same state collides on the id inside the write lock and is refused (409) |
| 31 | before anything is written. Once the first move lands the state has |
| 32 | changed, so a later recount is an ordinary count. |
| 33 | |
| 34 | Deliberately per-product v1: count-sheet workflows (a counts collection + |
| 35 | a runner) arrive when someone actually counts more than a shelf at a time |
| 36 | (docs/logic-decisions.md #4). |
| 37 | |
| 38 | A shortage may say what it was (optional `reason`): `evaporation` (a |
| 39 | liquid that lost volume in storage) or `shrinkage` (missing, cause unknown) |
| 40 | instead of the bare `adjustment`. The move then carries that loss reason |
| 41 | and its journal routes to inventory.journal.<reason>_account, falling back |
| 42 | to the shrinkage account as before. An overage cannot be a loss and is |
| 43 | refused with one. |
| 44 | |
| 45 | Expected loss. A product may declare expected_loss_bps -- the shortage a |
| 46 | count normally finds, in basis points of the book quantity (a cask's yearly |
| 47 | evaporation, a bulk bin's handling loss). A shortage above it stands out: |
| 48 | the answer says so (`expected_loss.above_expected`), and where app-assets |
| 49 | is installed a loss event is opened for it (status reported, reported by |
| 50 | the counter, linked to the move, estimated at the journal's amount) so it |
| 51 | is counted on the home page until somebody else looks at it and approves or |
| 52 | rejects it. Within the expectation nothing is opened: a normal loss that |
| 53 | raised a flag every count would train people to ignore the flag. Quantities |
| 54 | here are Decimal throughout (a count of 185.1 litres against a book 190.25 |
| 55 | is a 5.15 shortage, and 271 bps of it). |
| 56 | """ |
| 57 | |
| 58 | import os |
| 59 | import uuid |
| 60 | from datetime import date |
| 61 | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 62 | |
| 63 | import object_access |
| 64 | import object_collections |
| 65 | import object_finance |
| 66 | import object_records |
| 67 | import object_stock |
| 68 | |
| 69 | ACTOR = "action_apply_count" |
| 70 | |
| 71 | |
| 72 | def _base_dir(): |
| 73 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 74 | |
| 75 | |
| 76 | def _setting(base, key, default=""): |
| 77 | try: |
| 78 | # access: box configuration |
| 79 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 80 | if row.get("key") == key and row.get("value"): |
| 81 | return row["value"].strip() |
| 82 | except Exception: |
| 83 | pass |
| 84 | return default |
| 85 | |
| 86 | |
| 87 | LOSS_REASONS_AT_COUNT = ("evaporation", "shrinkage") |
| 88 | |
| 89 | |
| 90 | def _compose_variance_journal(base, move, direction): |
| 91 | inventory_acct = _setting(base, "inventory.journal.inventory_account") |
| 92 | shrinkage_acct = _setting(base, "inventory.journal.shrinkage_account") |
| 93 | reason = move.get("reason") or "" |
| 94 | if direction == "shortage" and reason in LOSS_REASONS_AT_COUNT: |
| 95 | shrinkage_acct = _setting(base, f"inventory.journal.{reason}_account", shrinkage_acct) |
| 96 | if not inventory_acct or not shrinkage_acct: |
| 97 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 98 | try: |
| 99 | quantity = Decimal(str(move.get("quantity") or "0")) |
| 100 | unit_cost = int(move.get("unit_cost_cents") or 0) |
| 101 | except (InvalidOperation, ValueError): |
| 102 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 103 | amount = int((quantity * unit_cost).to_integral_value(rounding=ROUND_HALF_UP)) |
| 104 | if amount <= 0: |
| 105 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 106 | if direction == "shortage": |
| 107 | what = f"Count shortage ({reason})" if reason in LOSS_REASONS_AT_COUNT else "Count shortage" |
| 108 | debit_acct, credit_acct = shrinkage_acct, inventory_acct |
| 109 | else: |
| 110 | debit_acct, credit_acct, what = inventory_acct, shrinkage_acct, "Count overage" |
| 111 | return object_finance.compose_posted_journal( |
| 112 | base, |
| 113 | generated_from=f"stock_moves/{move['id']}", |
| 114 | date=str(move.get("occurred_at") or "")[:10], |
| 115 | description=f"{what}: product {move.get('product_id')} x {move.get('quantity')} (count variance)", |
| 116 | lines=[ |
| 117 | {"account_id": debit_acct, "debit_cents": amount, "credit_cents": 0}, |
| 118 | {"account_id": credit_acct, "debit_cents": 0, "credit_cents": amount}, |
| 119 | ], |
| 120 | owner_id=move.get("owner_id", ""), |
| 121 | entity_id=move.get("entity_id", ""), |
| 122 | actor=ACTOR, |
| 123 | ) |
| 124 | |
| 125 | |
| 126 | def POST(request): |
| 127 | identity = request.get("_identity") or {} |
| 128 | base = _base_dir() |
| 129 | access = object_access.Access(identity, base_dir=base) |
| 130 | user_id = access.user_id |
| 131 | if not user_id: |
| 132 | return {"status": 403, "error": "Sign in to apply a count."} |
| 133 | |
| 134 | product_id = str(request.get("product_id") or "").strip() |
| 135 | location_id = str(request.get("location_id") or "").strip() |
| 136 | if not product_id or not location_id: |
| 137 | return {"status": 400, "error": "product_id and location_id are required."} |
| 138 | try: |
| 139 | counted = Decimal(str(request.get("counted_qty"))) |
| 140 | except (InvalidOperation, TypeError): |
| 141 | return {"status": 400, "error": "counted_qty must be a number."} |
| 142 | if counted < 0: |
| 143 | return {"status": 400, "error": "counted_qty must not be negative."} |
| 144 | reason = str(request.get("reason") or "adjustment").strip() |
| 145 | if reason not in ("adjustment",) + LOSS_REASONS_AT_COUNT: |
| 146 | return {"status": 400, "error": ("reason is adjustment (the default), evaporation " |
| 147 | "or shrinkage.")} |
| 148 | |
| 149 | try: |
| 150 | product = access.get("products", product_id, action=object_access.UPDATE) |
| 151 | location = access.get("locations", location_id) if product else None |
| 152 | except Exception: |
| 153 | product = location = None |
| 154 | if not product: |
| 155 | return {"status": 404, "error": f"Product not found: {product_id}"} |
| 156 | if not location: |
| 157 | return {"status": 404, "error": f"Location not found: {location_id}"} |
| 158 | |
| 159 | on_hand, basis = object_stock.location_state(product_id, location_id, base_dir=base) |
| 160 | variance = counted - on_hand |
| 161 | if variance == 0: |
| 162 | return {"status": 200, "variance": "0", |
| 163 | "note": "count matches the book quantity; no move written"} |
| 164 | |
| 165 | if variance > 0 and reason != "adjustment": |
| 166 | return {"status": 400, "error": (f"The count found more than the books hold; " |
| 167 | f"{reason} is a loss and cannot add stock.")} |
| 168 | |
| 169 | counted_on = str(request.get("counted_on") or "").strip() or date.today().isoformat() |
| 170 | move = { |
| 171 | "id": str(uuid.uuid5(uuid.NAMESPACE_URL, f"dbbasic:apply_count:{basis}")), |
| 172 | "product_id": product_id, |
| 173 | "from_location_id": location_id if variance < 0 else "", |
| 174 | "to_location_id": location_id if variance > 0 else "", |
| 175 | "quantity": str(abs(variance)), |
| 176 | "unit_cost_cents": str(product.get("cost_cents") or "").strip(), |
| 177 | "reason": reason, |
| 178 | "reference": "count variance", |
| 179 | "occurred_at": counted_on, |
| 180 | "owner_id": user_id, |
| 181 | } |
| 182 | if product.get("entity_id"): |
| 183 | move["entity_id"] = product["entity_id"] |
| 184 | try: |
| 185 | # access: system write after the access check above (update on the product, read on the location) |
| 186 | object_records.create_collection_record("stock_moves", move, base_dir=base, |
| 187 | actor=ACTOR) |
| 188 | except object_records.DuplicateRecordIdError: |
| 189 | return {"status": 409, "move_id": move["id"], |
| 190 | "error": ("Another count of this shelf was just applied against " |
| 191 | "the same stock (the same variance is already being " |
| 192 | "written). Nothing more was written; count again if " |
| 193 | "the shelf still disagrees.")} |
| 194 | |
| 195 | direction = "shortage" if variance < 0 else "overage" |
| 196 | journal = _compose_variance_journal(base, move, direction) |
| 197 | answer = {"status": 200, "move_id": move["id"], "variance": str(variance), |
| 198 | "direction": direction, "on_hand_before": str(on_hand), |
| 199 | "journal": journal} |
| 200 | expected = _expected_loss(product, on_hand, variance) |
| 201 | if expected is not None: |
| 202 | if expected["above_expected"]: |
| 203 | expected["loss_event"] = _open_loss_event(base, product, move, on_hand, counted, |
| 204 | expected, user_id) |
| 205 | answer["expected_loss"] = expected |
| 206 | return answer |
| 207 | |
| 208 | |
| 209 | def _expected_loss(product, on_hand, variance): |
| 210 | """{expected_bps, actual_bps, above_expected} for a shortage against a |
| 211 | product that declares an expectation; None when it declares none or the |
| 212 | count found no shortage. actual_bps is rounded half up; above means |
| 213 | strictly above, compared exactly (shortage * 10000 > on_hand * expected). |
| 214 | A shortage from a shelf the books say is empty (or negative) has no rate |
| 215 | and is always above.""" |
| 216 | text = str(product.get("expected_loss_bps") or "").strip() |
| 217 | if not text or variance >= 0: |
| 218 | return None |
| 219 | try: |
| 220 | expected_bps = int(text) |
| 221 | except ValueError: |
| 222 | return None |
| 223 | shortage = -variance |
| 224 | if on_hand <= 0: |
| 225 | return {"expected_bps": expected_bps, "actual_bps": None, "above_expected": True} |
| 226 | actual = (shortage * 10000 / on_hand).to_integral_value(rounding=ROUND_HALF_UP) |
| 227 | return {"expected_bps": expected_bps, "actual_bps": int(actual), |
| 228 | "above_expected": shortage * 10000 > on_hand * expected_bps} |
| 229 | |
| 230 | |
| 231 | def _open_loss_event(base, product, move, on_hand, counted, expected, user_id): |
| 232 | """A reported loss event for a shortage above normal, or why there is none. |
| 233 | |
| 234 | Soft dependency, the same posture as the journal: loss_events belongs to |
| 235 | app-assets, which depends on this package and not the other way round, |
| 236 | so a box without it simply gets the flag in the answer. The id is |
| 237 | derived from the move, so the event is opened once per move whatever |
| 238 | retries. A storage-level write: hook_loss_events never runs, so the |
| 239 | reporter is stamped here, from the signed-in counter -- and the |
| 240 | loss_events locked check still refuses an approval by that same person. |
| 241 | """ |
| 242 | try: |
| 243 | amount = int((Decimal(str(move["quantity"])) * int(move.get("unit_cost_cents") or 0)) |
| 244 | .to_integral_value(rounding=ROUND_HALF_UP)) |
| 245 | except (InvalidOperation, ValueError): |
| 246 | amount = 0 |
| 247 | actual = expected.get("actual_bps") |
| 248 | day = str(move["occurred_at"])[:10] |
| 249 | event = { |
| 250 | "id": str(uuid.uuid5(uuid.NAMESPACE_URL, f"dbbasic:count_loss:{move['id']}")), |
| 251 | "occurred_on": day, |
| 252 | "discovered_on": day, |
| 253 | "kind": move["reason"] if move["reason"] in LOSS_REASONS_AT_COUNT else "shrinkage", |
| 254 | "subject": "inventory", |
| 255 | "what": f"{product.get('name') or product.get('id')}: {move['quantity']} short at count"[:300], |
| 256 | "how_discovered": (f"Physical count on {day}: the books held {on_hand}, {counted} were " |
| 257 | f"counted. The shortage is " |
| 258 | f"{actual if actual is not None else 'an undefined share'} bps of the " |
| 259 | f"book quantity, above the {expected['expected_bps']} bps this product " |
| 260 | f"normally loses."), |
| 261 | "estimated_amount_cents": str(amount), |
| 262 | "product_id": product["id"], |
| 263 | "stock_move_id": move["id"], |
| 264 | "status": "reported", |
| 265 | "reported_by": user_id, |
| 266 | "owner_id": user_id, |
| 267 | } |
| 268 | if product.get("entity_id"): |
| 269 | event["entity_id"] = product["entity_id"] |
| 270 | try: |
| 271 | # access: system write of a reported (unapproved) loss for the count the caller just made |
| 272 | object_records.create_collection_record("loss_events", event, base_dir=base, actor=ACTOR) |
| 273 | except object_collections.CollectionNotFoundError: |
| 274 | return {"skipped": "loss events are not installed (app-assets)"} |
| 275 | except object_records.DuplicateRecordIdError: |
| 276 | return {"id": event["id"], "skipped": "already opened for this count"} |
| 277 | except Exception as exc: |
| 278 | return {"skipped": f"could not open a loss event: {str(exc)[:160]}"} |
| 279 | return {"id": event["id"], "status": "reported"} |