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

9 downloads

Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
stock.py · 6.3 KB · 157 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 # access: own rows only: kept to owner_id == the caller's user_id in this expression
67 records = object_records.read_collection_records(collection, base_dir=base_dir)
68 except (LookupError, OSError):
69 return {}
70 return {
71 record["id"]: (record.get("name") or record["id"])
72 for record in records
73 if record.get("id") and record.get("owner_id") == owner
74 }
75
76
77def _esc(value) -> str:
78 text = "" if value is None else str(value)
79 return (
80 text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
81 .replace('"', "&quot;").replace("'", "&#39;")
82 )
83
84
85def GET(request):
86 identity = request.get("_identity", {})
87 user_id = identity.get("user_id")
88 _logger.info("site_stock served", user_id=user_id or "anonymous")
89
90 if not user_id:
91 body = '<p class="hint"><a href="/login?next=/stock">Sign in</a> to see your stock levels.</p>'
92 script = ""
93 else:
94 base_dir = _data_dir()
95 summary = object_stock.stock_levels(base_dir=base_dir, owner=user_id)
96 product_names = _name_lookup("products", user_id, base_dir)
97 location_names = _name_lookup("locations", user_id, base_dir)
98
99 level_rows = "".join(
100 "<tr><td>{product}</td><td>{location}</td><td class=\"num\">{quantity}</td></tr>".format(
101 product=_esc(product_names.get(row["product_id"], row["product_id"])),
102 location=_esc(location_names.get(row["location_id"], row["location_id"])),
103 quantity=_esc(row["quantity"]),
104 )
105 for row in summary["levels"]
106 ) or '<tr><td colspan="3" class="hint">No stock moves yet.</td></tr>'
107
108 total_rows = "".join(
109 "<tr><td>{product}</td><td class=\"num\">{quantity}</td></tr>".format(
110 product=_esc(product_names.get(row["product_id"], row["product_id"])),
111 quantity=_esc(row["quantity"]),
112 )
113 for row in summary["totals"]
114 ) or '<tr><td colspan="2" class="hint">No on-hand stock yet.</td></tr>'
115
116 body = f"""
117<div class="breadcrumb"><a href="/">Home</a> / Stock</div>
118<div class="pagehead"><h1>Stock Levels</h1><a class="btn" href="/stock">Refresh</a></div>
119<h2 style="font-size:1rem">On hand by location</h2>
120<table class="stock-table">
121<thead><tr><th>Product</th><th>Location</th><th class="num">Quantity</th></tr></thead>
122<tbody>{level_rows}</tbody>
123</table>
124<h2 style="font-size:1rem; margin-top:1.5rem">On-hand totals</h2>
125<p class="hint" style="margin-top:0">Excludes customer, supplier, and virtual locations -- see /locations for each location's type.</p>
126<table class="stock-table">
127<thead><tr><th>Product</th><th class="num">Quantity</th></tr></thead>
128<tbody>{total_rows}</tbody>
129</table>
130<p class="hint"><a href="/products">Products</a> &middot; <a href="/locations">Locations</a></p>
131"""
132 script = f"<script>{_SCRIPT}</script>"
133
134 who = (
135 f"signed in as <strong>{user_id}</strong>"
136 if user_id
137 else '<a href="/login?next=/stock">sign in</a>'
138 )
139 html = f"""<!doctype html>
140<html lang="en">
141<head>
142<meta charset="utf-8">
143<meta name="viewport" content="width=device-width, initial-scale=1">
144<title>Stock Levels</title>
145<link rel="stylesheet" href="/style">
146<style>{_STYLE}</style>
147</head>
148<body>
149<div class="wrap">
150<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
151{body}
152</div>
153{script}
154<script src="/nav"></script>
155</body>
156</html>"""
157 return {"content_type": "text/html; charset=utf-8", "body": html}