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
pick_list.py · 9.2 KB · 240 lines
1"""site_pick_list -- everything that is owed and not yet in a box. GET
2/pick-list.
3
4A READ, never a table. There is no pick_list collection and there must
5never be one: the list is ordered quantity minus shipped quantity, folded
6live, exactly the way stock levels are folded from stock_moves
7(object_stock.py) instead of stored. Storing it would mean two answers to
8"what is left to pick" that can disagree, and the stored one is always the
9one somebody trusts at the wrong moment.
10
11GROUPED BY PRODUCT, because a picker walks the room once. Two orders each
12wanting a mug is one trip to the mug shelf carrying two, not two trips --
13and a per-order list is what makes small warehouses walk the same aisle
14five times a morning. The orders each row is for are listed alongside, so
15the packing bench can split the pile back out again.
16
17Oldest first: the order that has waited longest is picked first, which is
18the only fair rule that needs no judgement and the one a customer would
19choose if asked.
20
21Sorting by LOCATION walk order -- the bin-typed locations app-catalog
22already models -- is the obvious next improvement and is deliberately not
23here: nothing in this repo yet records which product lives in which bin,
24and a walk order derived from data that does not exist would be a
25confident wrong answer. Grouping by product is the honest half of that
26idea and is most of its value.
27
28Requires a signed-in identity, the same gate site_stock uses (and the same
29shape: a sign-in prompt, not a 403). The orders folded are the ones the
30permission engine (object_access) lets the caller read, the same rows the
31orders API would list. An order that carries no owner at all used to be
32included for every signed-in account, so a stranger was shown another
33shop's order numbers, products and quantities; guest checkout stamps the
34shop's owner (shop.owner_id) on the basket, and the orders API shows an
35unowned order to nobody but an admin.
36"""
37
38import html
39import os
40from decimal import Decimal, InvalidOperation
41
42import object_access
43import object_records
44
45# What a picker is asked to pick against: an order that has been committed
46# and is not yet fully out the door. draft is not a commitment; shipped and
47# delivered have nothing left; cancelled must never be picked.
48PICKABLE_ORDER_STATUSES = {"confirmed", "processing", "partial"}
49
50# Shipments in these never reached anybody, so their lines do not reduce
51# what is still owed -- the goods have to be picked again.
52NOT_DELIVERED_STATUSES = {"lost", "returned_to_sender"}
53
54
55def _base_dir():
56 return os.environ.get("DBBASIC_DATA_DIR", "data")
57
58
59def _text(value):
60 return str(value if value is not None else "").strip()
61
62
63def _esc(value):
64 return html.escape(_text(value))
65
66
67def _quantity(value):
68 try:
69 return Decimal(_text(value) or "0")
70 except InvalidOperation:
71 return Decimal(0)
72
73
74def _number(value):
75 return format(value.normalize(), "f")
76
77
78_STYLE = """
79.pick-table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
80.pick-table th, .pick-table td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
81.pick-table th { font-weight: 600; }
82.pick-table td.num, .pick-table th.num { text-align: right; }
83.hint { color: var(--muted, #999); font-size: 0.9rem; }
84@media print {
85 nav, header.app, .noprint, .btn { display: none !important; }
86 body { background: #fff; color: #000; }
87}
88"""
89
90
91def _rows_for(base, identity):
92 """Fold orders x order lines x shipment lines into one row per product.
93
94 Full scans of four collections: the right cost at this scale (a shop
95 with a warehouse this size has hundreds of open lines, not millions),
96 and the same trade site_stock's own summary makes.
97 """
98 try:
99 orders = object_records.read_collection_records("orders", base_dir=base)
100 except Exception:
101 return []
102 orders = object_access.Access(identity, base_dir=base).visible("orders", orders)
103 open_orders = {
104 order["id"]: order for order in orders
105 if _text(order.get("status")) in PICKABLE_ORDER_STATUSES
106 and _text(order.get("doc_type") or "sale") == "sale"
107 }
108 if not open_orders:
109 return []
110
111 try:
112 # access: lines of the orders the caller may read (Access.visible above)
113 order_lines = [line for line in object_records.read_collection_records(
114 "order_lines", base_dir=base)
115 if _text(line.get("order_id")) in open_orders]
116 except Exception:
117 return []
118
119 try:
120 # access: what has shipped, folded per line of the orders the caller may read; nothing else is shown
121 shipments = object_records.read_collection_records("shipments",
122 base_dir=base)
123 except Exception:
124 shipments = []
125 counted = {row["id"] for row in shipments
126 if _text(row.get("status")) not in NOT_DELIVERED_STATUSES}
127 try:
128 # access: what has shipped, folded per line of the orders the caller may read; nothing else is shown
129 shipment_lines = object_records.read_collection_records(
130 "shipment_lines", base_dir=base)
131 except Exception:
132 shipment_lines = []
133
134 shipped = {}
135 for line in shipment_lines:
136 if _text(line.get("shipment_id")) not in counted:
137 continue
138 key = _text(line.get("order_line_id"))
139 shipped[key] = shipped.get(key, Decimal(0)) + _quantity(line.get("quantity"))
140
141 try:
142 # access: names the products on the lines of the orders the caller may read
143 products = {row["id"]: row for row in
144 object_records.read_collection_records("products",
145 base_dir=base)}
146 except Exception:
147 products = {}
148
149 grouped = {}
150 for line in order_lines:
151 remaining = _quantity(line.get("quantity")) - shipped.get(line["id"], Decimal(0))
152 if remaining <= 0:
153 continue
154 order = open_orders[_text(line.get("order_id"))]
155 product_id = _text(line.get("product_id"))
156 description = _text(line.get("description"))
157 # Group by product where there is one; a free-text line groups by
158 # what it says, which is the only identity it has.
159 key = product_id or f"text:{description.lower()}"
160 row = grouped.setdefault(key, {
161 "product_id": product_id,
162 "name": (_text(products.get(product_id, {}).get("name"))
163 or description or product_id),
164 "sku": _text(products.get(product_id, {}).get("sku")),
165 "quantity": Decimal(0),
166 "orders": [],
167 "oldest": "",
168 })
169 row["quantity"] += remaining
170 number = _text(order.get("number")) or order["id"]
171 if number not in row["orders"]:
172 row["orders"].append(number)
173 placed = _text(order.get("order_date")) or _text(order.get("created_at"))[:10]
174 if placed and (not row["oldest"] or placed < row["oldest"]):
175 row["oldest"] = placed
176
177 rows = list(grouped.values())
178 # Oldest waiting first; a row with no date sorts last rather than first,
179 # because "we do not know when this was ordered" is not a claim to
180 # urgency.
181 rows.sort(key=lambda row: (row["oldest"] or "9999-12-31", row["name"]))
182 return rows
183
184
185def GET(request):
186 identity = request.get("_identity") or {}
187 user_id = _text(identity.get("user_id"))
188
189 if not user_id:
190 body = ('<div class="pagehead"><h1>Pick list</h1></div>'
191 '<p class="hint"><a href="/login?next=/pick-list">Sign in</a> '
192 'to see what is waiting to be picked.</p>')
193 else:
194 rows = _rows_for(_base_dir(), identity)
195 table_rows = "".join(
196 "<tr>"
197 f"<td>{_esc(row['name'])}</td>"
198 f"<td>{_esc(row['sku'])}</td>"
199 f"<td class=\"num\">{_esc(_number(row['quantity']))}</td>"
200 f"<td>{_esc(', '.join(row['orders']))}</td>"
201 f"<td>{_esc(row['oldest'])}</td>"
202 "</tr>"
203 for row in rows
204 ) or ('<tr><td colspan="5" class="hint">Nothing is waiting to be '
205 'picked.</td></tr>')
206
207 body = f"""
208<div class="breadcrumb noprint"><a href="/">Home</a> / Pick list</div>
209<div class="pagehead"><h1>Pick list</h1></div>
210<p class="hint">Everything ordered and not yet on a shipment, grouped by
211product so each shelf is visited once. Oldest orders first. This is a read
212of the order and shipment records, never a stored list.</p>
213<table class="pick-table">
214<thead><tr><th>Product</th><th>SKU</th><th class="num">To pick</th><th>Orders</th><th>Oldest</th></tr></thead>
215<tbody>{table_rows}</tbody>
216</table>
217<p class="hint noprint">Pack a shipment from an order to take lines off this
218list.</p>
219"""
220
221 who = (f"signed in as <strong>{_esc(user_id)}</strong>" if user_id
222 else '<a href="/login?next=/pick-list">sign in</a>')
223 page = f"""<!doctype html>
224<html lang="en">
225<head>
226<meta charset="utf-8">
227<meta name="viewport" content="width=device-width, initial-scale=1">
228<title>Pick list</title>
229<link rel="stylesheet" href="/style">
230<style>{_STYLE}</style>
231</head>
232<body>
233<div class="wrap">
234<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
235{body}
236</div>
237<script src="/nav"></script>
238</body>
239</html>"""
240 return {"content_type": "text/html; charset=utf-8", "body": page}