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
reorder_check.py · 7.8 KB · 212 lines
| 1 | """system_reorder_check -- which shelves are low, said once a night. |
| 2 | |
| 3 | POST {today?, limit?} -- the scheduled pass declared in this package's |
| 4 | `schedules`. It folds the stock ledger, compares each product against its |
| 5 | own reorder_point, and writes a SUGGESTION for the ones at or below it. |
| 6 | |
| 7 | **It suggests. It does not order.** That is the entire design and it is |
| 8 | worth being blunt about, because every inventory system eventually gets |
| 9 | asked to "just raise the PO automatically". The fold can see the shelf. |
| 10 | It cannot see the supplier's minimum, the lead time, the case size, the |
| 11 | promotion that is about to triple demand, the line somebody has already |
| 12 | decided to run down, or how much cash is in the bank this week. A machine |
| 13 | that orders on its own is how a business ends up with forty pallets of |
| 14 | the wrong thing, and the honest division of labour is that the server |
| 15 | NOTICES and the person DECIDES. Nothing here writes a purchase order, |
| 16 | touches a supplier, or moves stock. |
| 17 | |
| 18 | **At or below, not merely below.** "Reorder at 5" means five is the |
| 19 | moment. A shop that had to fall to four before anyone was told has been |
| 20 | given a threshold that means something other than what it says. |
| 21 | |
| 22 | **Zero means off.** A product with no reorder_point is not in this pass at |
| 23 | all -- not "reorder when it hits zero". Most catalogues have a handful of |
| 24 | lines anybody actually reorders, and a queue that lit up for every |
| 25 | made-to-order item and every service would be a queue nobody reads. |
| 26 | |
| 27 | **One open suggestion per product.** A nightly pass that appended a row |
| 28 | every night would produce ninety copies of one fact within a quarter, |
| 29 | which is the classic way a good signal becomes noise. The open row is |
| 30 | REFRESHED instead -- today's on-hand, today's date -- so the number in |
| 31 | front of a human is current, and `ordered` or `dismissed` rows are left |
| 32 | exactly as the human left them. Re-running the pass twice in one day is |
| 33 | therefore a no-op, which is what makes it safe for the scheduler to |
| 34 | retry (docs/logic-decisions.md #7). |
| 35 | |
| 36 | **Time-driven work belongs to a daemon pass** (#2). Nothing writes when a |
| 37 | shelf becomes low -- a sale writes a stock move, and noticing that the |
| 38 | move crossed a line is a different question asked at a different time -- |
| 39 | so a reaction could not see this, and a page computing it live would ask |
| 40 | every visitor to pay for a fold over the whole ledger. |
| 41 | |
| 42 | Degrades to a zero-work report when products or stock_moves cannot be |
| 43 | read, rather than raising: a pass should not log an error every night |
| 44 | about an app nobody installed. |
| 45 | """ |
| 46 | |
| 47 | import os |
| 48 | from datetime import date |
| 49 | |
| 50 | import object_ids |
| 51 | import object_records |
| 52 | import object_stock |
| 53 | |
| 54 | ACTOR = "system_reorder_check" |
| 55 | |
| 56 | DEFAULT_LIMIT = 500 |
| 57 | |
| 58 | OPEN = "open" |
| 59 | |
| 60 | |
| 61 | def _base_dir(): |
| 62 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 63 | |
| 64 | |
| 65 | def _text(value): |
| 66 | return str(value if value is not None else "").strip() |
| 67 | |
| 68 | |
| 69 | def _int(value, default=0): |
| 70 | try: |
| 71 | return int(_text(value) or default) |
| 72 | except (TypeError, ValueError): |
| 73 | return default |
| 74 | |
| 75 | |
| 76 | def _number(value): |
| 77 | try: |
| 78 | return float(_text(value) or 0) |
| 79 | except (TypeError, ValueError): |
| 80 | return 0.0 |
| 81 | |
| 82 | |
| 83 | def _truthy(value, default=True): |
| 84 | text = _text(value).lower() |
| 85 | if not text: |
| 86 | return default |
| 87 | return text in ("true", "1", "yes", "on") |
| 88 | |
| 89 | |
| 90 | def _rows(collection, base): |
| 91 | try: |
| 92 | return object_records.read_collection_records(collection, base_dir=base) |
| 93 | except Exception: |
| 94 | return None |
| 95 | |
| 96 | |
| 97 | def below_the_point(products, on_hand): |
| 98 | """The pure half: which products are at or below their own point. |
| 99 | |
| 100 | Kept as a plain function over two dicts so the rule can be read and |
| 101 | tested without a data directory -- the same posture object_cart and |
| 102 | object_promotions take about the arithmetic they own. |
| 103 | |
| 104 | Returns a list of {product_id, on_hand, reorder_point, |
| 105 | suggested_quantity}, in a stable order so two runs produce the same |
| 106 | report. |
| 107 | """ |
| 108 | low = [] |
| 109 | for product in products: |
| 110 | point = _int(product.get("reorder_point")) |
| 111 | if point <= 0: |
| 112 | continue # 0 means off, not "reorder at zero" |
| 113 | if not _truthy(product.get("is_active")): |
| 114 | continue # nobody reorders what is not for sale |
| 115 | level = _number(on_hand.get(_text(product.get("id")), 0)) |
| 116 | if level > point: |
| 117 | continue # at or below, not merely below |
| 118 | low.append({ |
| 119 | "product_id": _text(product.get("id")), |
| 120 | "on_hand": level, |
| 121 | "reorder_point": point, |
| 122 | "suggested_quantity": _int(product.get("reorder_quantity")), |
| 123 | "owner_id": _text(product.get("owner_id")), |
| 124 | }) |
| 125 | low.sort(key=lambda row: (row["on_hand"] - row["reorder_point"], |
| 126 | row["product_id"])) |
| 127 | return low |
| 128 | |
| 129 | |
| 130 | def _quantity_text(value): |
| 131 | """A level as the row should read it: 4 rather than 4.0.""" |
| 132 | if float(value).is_integer(): |
| 133 | return str(int(value)) |
| 134 | return str(value) |
| 135 | |
| 136 | |
| 137 | def POST(request): |
| 138 | base = _base_dir() |
| 139 | products = _rows("products", base) |
| 140 | if products is None: |
| 141 | return {"ok": True, "skipped": "no catalogue on this server", |
| 142 | "suggested": 0} |
| 143 | existing = _rows("reorder_suggestions", base) |
| 144 | if existing is None: |
| 145 | return {"ok": True, |
| 146 | "skipped": "reorder_suggestions is not installed", |
| 147 | "suggested": 0} |
| 148 | |
| 149 | today = _text(request.get("today")) or date.today().isoformat() |
| 150 | limit = max(1, _int(request.get("limit"), DEFAULT_LIMIT)) |
| 151 | |
| 152 | tracked = [row for row in products if _int(row.get("reorder_point")) > 0] |
| 153 | on_hand = {} |
| 154 | for product in tracked: |
| 155 | product_id = _text(product.get("id")) |
| 156 | try: |
| 157 | on_hand[product_id] = object_stock.total_quantity(product_id, |
| 158 | base_dir=base) |
| 159 | except Exception: |
| 160 | # A product whose level cannot be folded is left alone rather |
| 161 | # than reported as empty: "we cannot tell" is not "buy more". |
| 162 | continue |
| 163 | low = [row for row in below_the_point(tracked, on_hand) |
| 164 | if row["product_id"] in on_hand][:limit] |
| 165 | |
| 166 | open_by_product = {} |
| 167 | for row in existing: |
| 168 | if _text(row.get("status")) != OPEN: |
| 169 | continue |
| 170 | open_by_product.setdefault(_text(row.get("product_id")), row) |
| 171 | |
| 172 | created, refreshed = [], [] |
| 173 | for row in low: |
| 174 | patch = { |
| 175 | "on_hand": _quantity_text(row["on_hand"]), |
| 176 | "reorder_point": str(row["reorder_point"]), |
| 177 | "suggested_quantity": str(row["suggested_quantity"]), |
| 178 | "suggested_on": today, |
| 179 | } |
| 180 | current = open_by_product.get(row["product_id"]) |
| 181 | if current is not None: |
| 182 | # Refresh rather than append: ninety copies of one fact is a |
| 183 | # queue nobody reads, and a stale number is worse than none. |
| 184 | try: |
| 185 | object_records.update_collection_record( |
| 186 | "reorder_suggestions", current["id"], patch, |
| 187 | base_dir=base, actor=ACTOR) |
| 188 | refreshed.append(current["id"]) |
| 189 | except Exception: |
| 190 | continue |
| 191 | continue |
| 192 | suggestion_id = object_ids.new_uuid4() |
| 193 | try: |
| 194 | object_records.create_collection_record( |
| 195 | "reorder_suggestions", |
| 196 | {"id": suggestion_id, "product_id": row["product_id"], |
| 197 | "status": OPEN, "owner_id": row["owner_id"], **patch}, |
| 198 | base_dir=base, actor=ACTOR) |
| 199 | except Exception: |
| 200 | continue |
| 201 | created.append(suggestion_id) |
| 202 | |
| 203 | return { |
| 204 | "ok": True, |
| 205 | "checked": len(tracked), |
| 206 | "low": len(low), |
| 207 | "suggested": len(created), |
| 208 | "refreshed": len(refreshed), |
| 209 | "ordered": 0, |
| 210 | "note": ("suggestions only -- this pass never raises a purchase " |
| 211 | "order, because the shelf is the only thing it can see"), |
| 212 | } |