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
apply_count.py · 5.5 KB · 131 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 | Deliberately per-product v1: count-sheet workflows (a counts collection + |
| 19 | a runner) arrive when someone actually counts more than a shelf at a time |
| 20 | (docs/logic-decisions.md #4). |
| 21 | """ |
| 22 | |
| 23 | import os |
| 24 | from datetime import date |
| 25 | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 26 | |
| 27 | import object_finance |
| 28 | import object_ids |
| 29 | import object_records |
| 30 | import object_stock |
| 31 | |
| 32 | ACTOR = "action_apply_count" |
| 33 | |
| 34 | |
| 35 | def _base_dir(): |
| 36 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 37 | |
| 38 | |
| 39 | def _setting(base, key, default=""): |
| 40 | try: |
| 41 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 42 | if row.get("key") == key and row.get("value"): |
| 43 | return row["value"].strip() |
| 44 | except Exception: |
| 45 | pass |
| 46 | return default |
| 47 | |
| 48 | |
| 49 | def _compose_variance_journal(base, move, direction): |
| 50 | inventory_acct = _setting(base, "inventory.journal.inventory_account") |
| 51 | shrinkage_acct = _setting(base, "inventory.journal.shrinkage_account") |
| 52 | if not inventory_acct or not shrinkage_acct: |
| 53 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 54 | try: |
| 55 | quantity = Decimal(str(move.get("quantity") or "0")) |
| 56 | unit_cost = int(move.get("unit_cost_cents") or 0) |
| 57 | except (InvalidOperation, ValueError): |
| 58 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 59 | amount = int((quantity * unit_cost).to_integral_value(rounding=ROUND_HALF_UP)) |
| 60 | if amount <= 0: |
| 61 | return {"ok": True, "skipped": "no stamped cost; nothing to book"} |
| 62 | if direction == "shortage": |
| 63 | debit_acct, credit_acct, what = shrinkage_acct, inventory_acct, "Count shortage" |
| 64 | else: |
| 65 | debit_acct, credit_acct, what = inventory_acct, shrinkage_acct, "Count overage" |
| 66 | return object_finance.compose_posted_journal( |
| 67 | base, |
| 68 | generated_from=f"stock_moves/{move['id']}", |
| 69 | date=str(move.get("occurred_at") or "")[:10], |
| 70 | description=f"{what}: product {move.get('product_id')} x {move.get('quantity')} (count variance)", |
| 71 | lines=[ |
| 72 | {"account_id": debit_acct, "debit_cents": amount, "credit_cents": 0}, |
| 73 | {"account_id": credit_acct, "debit_cents": 0, "credit_cents": amount}, |
| 74 | ], |
| 75 | owner_id=move.get("owner_id", ""), |
| 76 | entity_id=move.get("entity_id", ""), |
| 77 | actor=ACTOR, |
| 78 | ) |
| 79 | |
| 80 | |
| 81 | def POST(request): |
| 82 | identity = request.get("_identity") or {} |
| 83 | user_id = identity.get("user_id") or "" |
| 84 | if not user_id: |
| 85 | return {"status": 403, "error": "Sign in to apply a count."} |
| 86 | |
| 87 | product_id = str(request.get("product_id") or "").strip() |
| 88 | location_id = str(request.get("location_id") or "").strip() |
| 89 | if not product_id or not location_id: |
| 90 | return {"status": 400, "error": "product_id and location_id are required."} |
| 91 | try: |
| 92 | counted = Decimal(str(request.get("counted_qty"))) |
| 93 | except (InvalidOperation, TypeError): |
| 94 | return {"status": 400, "error": "counted_qty must be a number."} |
| 95 | if counted < 0: |
| 96 | return {"status": 400, "error": "counted_qty must not be negative."} |
| 97 | |
| 98 | base = _base_dir() |
| 99 | try: |
| 100 | product = object_records.get_collection_record("products", product_id, base_dir=base) |
| 101 | except Exception: |
| 102 | return {"status": 404, "error": f"Product not found: {product_id}"} |
| 103 | |
| 104 | on_hand = object_stock.quantity_at_location(product_id, location_id, base_dir=base) |
| 105 | variance = counted - on_hand |
| 106 | if variance == 0: |
| 107 | return {"status": 200, "variance": "0", |
| 108 | "note": "count matches the book quantity; no move written"} |
| 109 | |
| 110 | counted_on = str(request.get("counted_on") or "").strip() or date.today().isoformat() |
| 111 | move = { |
| 112 | "id": object_ids.new_uuid4(), |
| 113 | "product_id": product_id, |
| 114 | "from_location_id": location_id if variance < 0 else "", |
| 115 | "to_location_id": location_id if variance > 0 else "", |
| 116 | "quantity": str(abs(variance)), |
| 117 | "unit_cost_cents": str(product.get("cost_cents") or "").strip(), |
| 118 | "reason": "adjustment", |
| 119 | "reference": "count variance", |
| 120 | "occurred_at": counted_on, |
| 121 | "owner_id": user_id, |
| 122 | } |
| 123 | if product.get("entity_id"): |
| 124 | move["entity_id"] = product["entity_id"] |
| 125 | object_records.create_collection_record("stock_moves", move, base_dir=base, actor=ACTOR) |
| 126 | |
| 127 | direction = "shortage" if variance < 0 else "overage" |
| 128 | journal = _compose_variance_journal(base, move, direction) |
| 129 | return {"status": 200, "move_id": move["id"], "variance": str(variance), |
| 130 | "direction": direction, "on_hand_before": str(on_hand), |
| 131 | "journal": journal} |