Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
stock.py · 6.2 KB · 156 lines
1"""Stock levels page: current on-hand quantities per product x location,
2plus per-product on-hand totals (customer/supplier/virtual locations
3excluded -- see object_stock.py).
4
5Stock levels are DERIVED, never stored (object_stock.py folds the
6immutable stock_moves log on every call). Every other page in this
7package (products.py, product_view.py, locations.py) reads its collection
8client-side via a browser fetch to /collections/{collection}/records and
9lets the platform's row-filter permission enforce owner-scoping -- that
10generic endpoint only exists for stored collections, though, and stock
11levels are not one: there is no "stock_levels" collection to fetch. Two
12paths were open to close that gap: add a new authenticated GET endpoint
13(e.g. /api/stock/levels), or compute the summary here, server-side, in
14this page's own GET(). This file takes the second path -- it is the
15simpler correct one: no new route, no new permission surface, and no
16duplicate owner-scoping logic to keep in sync with permissions/rules.json
17-- this page's GET() applies the exact same owner_id == signed-in-user
18scoping object_stock.stock_levels()'s `owner` parameter is built for,
19matching the row_filter every other owner-scoped collection in this
20package already enforces. The tradeoff, honestly: this page does not
21live-refresh over the websocket the instant a stock_moves row lands
22(there is no fetched JSON payload to re-render in place) -- it re-fetches
23the whole page instead when stock_moves changes, which is simple and
24correct at this collection's expected scale.
25"""
26
27_SCRIPT = """
28(function () {
29 let _lt = null;
30 const reload = () => { clearTimeout(_lt); _lt = setTimeout(() => location.reload(), 400); };
31 (function wait() {
32 if (window.dbbasicSubscribe) window.dbbasicSubscribe("stock_moves", reload);
33 else setTimeout(wait, 300);
34 })();
35})();
36"""
37
38_STYLE = """
39.stock-table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
40.stock-table th, .stock-table td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
41.stock-table th { font-weight: 600; }
42.stock-table td.num, .stock-table th.num { text-align: right; }
43"""
44
45import os
46
47import object_records
48import object_stock
49
50DATA_DIR_ENV = "DBBASIC_DATA_DIR"
51
52
53def _data_dir() -> str:
54 # Mirrors app-orders' order_totals.py's own _data_dir(): standalone,
55 # reads os.environ directly rather than depending on object_server.
56 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
57
58
59def _name_lookup(collection: str, owner: str, base_dir: str) -> dict[str, str]:
60 """Return {id: name} for one owner's records in a collection, or {}
61 when the read fails for any reason (e.g. no rows yet) -- a display
62 fallback (the raw id) always covers a lookup miss, so this never needs
63 to raise.
64 """
65 try:
66 records = object_records.read_collection_records(collection, base_dir=base_dir)
67 except (LookupError, OSError):
68 return {}
69 return {
70 record["id"]: (record.get("name") or record["id"])
71 for record in records
72 if record.get("id") and record.get("owner_id") == owner
73 }
74
75
76def _esc(value) -> str:
77 text = "" if value is None else str(value)
78 return (
79 text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
80 .replace('"', "&quot;").replace("'", "&#39;")
81 )
82
83
84def GET(request):
85 identity = request.get("_identity", {})
86 user_id = identity.get("user_id")
87 _logger.info("site_stock served", user_id=user_id or "anonymous")
88
89 if not user_id:
90 body = '<p class="hint"><a href="/login?next=/stock">Sign in</a> to see your stock levels.</p>'
91 script = ""
92 else:
93 base_dir = _data_dir()
94 summary = object_stock.stock_levels(base_dir=base_dir, owner=user_id)
95 product_names = _name_lookup("products", user_id, base_dir)
96 location_names = _name_lookup("locations", user_id, base_dir)
97
98 level_rows = "".join(
99 "<tr><td>{product}</td><td>{location}</td><td class=\"num\">{quantity}</td></tr>".format(
100 product=_esc(product_names.get(row["product_id"], row["product_id"])),
101 location=_esc(location_names.get(row["location_id"], row["location_id"])),
102 quantity=_esc(row["quantity"]),
103 )
104 for row in summary["levels"]
105 ) or '<tr><td colspan="3" class="hint">No stock moves yet.</td></tr>'
106
107 total_rows = "".join(
108 "<tr><td>{product}</td><td class=\"num\">{quantity}</td></tr>".format(
109 product=_esc(product_names.get(row["product_id"], row["product_id"])),
110 quantity=_esc(row["quantity"]),
111 )
112 for row in summary["totals"]
113 ) or '<tr><td colspan="2" class="hint">No on-hand stock yet.</td></tr>'
114
115 body = f"""
116<div class="breadcrumb"><a href="/">Home</a> / Stock</div>
117<div class="pagehead"><h1>Stock Levels</h1><a class="btn" href="/stock">Refresh</a></div>
118<h2 style="font-size:1rem">On hand by location</h2>
119<table class="stock-table">
120<thead><tr><th>Product</th><th>Location</th><th class="num">Quantity</th></tr></thead>
121<tbody>{level_rows}</tbody>
122</table>
123<h2 style="font-size:1rem; margin-top:1.5rem">On-hand totals</h2>
124<p class="hint" style="margin-top:0">Excludes customer, supplier, and virtual locations -- see /locations for each location's type.</p>
125<table class="stock-table">
126<thead><tr><th>Product</th><th class="num">Quantity</th></tr></thead>
127<tbody>{total_rows}</tbody>
128</table>
129<p class="hint"><a href="/products">Products</a> &middot; <a href="/locations">Locations</a></p>
130"""
131 script = f"<script>{_SCRIPT}</script>"
132
133 who = (
134 f"signed in as <strong>{user_id}</strong>"
135 if user_id
136 else '<a href="/login?next=/stock">sign in</a>'
137 )
138 html = f"""<!doctype html>
139<html lang="en">
140<head>
141<meta charset="utf-8">
142<meta name="viewport" content="width=device-width, initial-scale=1">
143<title>Stock Levels</title>
144<link rel="stylesheet" href="/style">
145<style>{_STYLE}</style>
146</head>
147<body>
148<div class="wrap">
149<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
150{body}
151</div>
152{script}
153<script src="/nav"></script>
154</body>
155</html>"""
156 return {"content_type": "text/html; charset=utf-8", "body": html}