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
manifest.py · 11.7 KB · 291 lines
1"""site_manifest -- what the driver takes away, and what they sign for.
2GET /shipments/manifest?date=&carrier=
3
4A FOLD OVER FACTS, NEVER EDITABLE FROM THIS PAGE. There is no manifests
5collection, no form, no button and no link on here that changes anything.
6That is the whole character of the document: a manifest is the piece of
7paper a driver signs at the dock, and a manifest you can edit after the van
8has left is not a manifest -- it is a story about a van. Everything on it is
9read live from the shipments that carry the facts (docs/logic-decisions.md
10#1: the shipment rows are the facts, this page is a read of them), so the
11copy in the driver's hand and the copy on the screen cannot drift, and a
12correction is a correction to a SHIPMENT, made where that shipment lives,
13with the change log that comes with it.
14
15PER CARRIER, because that is the unit of handover. Two carriers collect from
16the same dock on the same morning and each takes their own pile; one list
17mixing them is a list neither driver can sign. With no ?carrier= the page
18prints every carrier as its own section with its own count and its own
19signature line, so the whole morning is one print job; with ?carrier= it is
20the single pile, for the shop that prints as each van pulls up.
21
22ONE DAY, keyed on shipped_on -- the date the box was handed over, stamped by
23system_order_fulfillment the moment a shipment reaches `shipped`. Not
24created_at: a parcel packed on Friday and collected on Monday belongs on
25Monday's manifest, because Monday is the day somebody signed for it. A
26shipment with no shipped_on therefore appears on no manifest at all, which
27is the honest answer -- it has not been handed to anybody.
28
29NO PRICES, the same rule as the packing slip and for a stronger reason: this
30document is handed to a third party who has no business knowing what the
31contents cost, and a carrier that can read the value of every parcel in the
32van is a shop that has published its own theft target.
33
34Columns are the four things a handover argument is ever about -- tracking
35number, order, who it is going to, and which service was paid for -- plus
36weight WHEN THE ROWS HAVE ONE. shipments declares no weight field: a
37deployment that weighs parcels adds one as an extra field, and the column
38appears because rows carry it, rather than a column of blanks appearing
39because a schema hoped somebody would.
40
41Sign-in gated exactly like site_pick_list: a sign-in prompt, not a 403, and
42the shipments (and the orders named on them) are the ones the permission
43engine (object_access) lets the caller read, the same rows the shipments
44API would list. A shipment with no owner at all used to be listed for every
45signed-in account, with its recipient's name and tracking number; the API
46shows it to nobody but an admin.
47"""
48
49import html
50import os
51from datetime import date, timedelta
52from decimal import Decimal, InvalidOperation
53
54import object_access
55import object_records
56
57ACTOR = "site_manifest"
58
59# What a driver can be handed. `open` and `packed` are still on the bench;
60# the inbound ladder is somebody else's parcel coming back to us.
61HANDED_OVER = {"shipped", "in_transit", "delivered", "returned_to_sender",
62 "lost"}
63
64# The heading for parcels whose carrier nobody typed. Not "Unknown": the
65# shop knows perfectly well who took them, it just did not write it down,
66# and a manifest that says so is a manifest somebody fixes.
67NO_CARRIER = "No carrier named"
68
69
70def _base_dir():
71 return os.environ.get("DBBASIC_DATA_DIR", "data")
72
73
74def _text(value):
75 return str(value if value is not None else "").strip()
76
77
78def _esc(value):
79 return html.escape(_text(value))
80
81
82def _weight(value):
83 try:
84 return Decimal(_text(value) or "0")
85 except InvalidOperation:
86 return Decimal(0)
87
88
89def _number(value):
90 return format(value.normalize(), "f")
91
92
93def _day(value):
94 """The requested day, or today. A date nobody can parse is answered with
95 today plus a note rather than a traceback: somebody is standing at a dock
96 holding parcels, and the page's job is to print."""
97 raw = _text(value)
98 if not raw:
99 return date.today().isoformat(), ""
100 try:
101 return date.fromisoformat(raw).isoformat(), ""
102 except ValueError:
103 return date.today().isoformat(), (
104 f"{raw!r} is not a date this page can read (use YYYY-MM-DD); "
105 f"showing today instead.")
106
107
108_STYLE = """
109.manifest-table { width: 100%; border-collapse: collapse; margin: 0.4rem 0 1rem; }
110.manifest-table th, .manifest-table td { text-align: left; padding: 0.35rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
111.manifest-table th { font-weight: 600; }
112.manifest-table td.num, .manifest-table th.num { text-align: right; }
113.carrier { margin: 1.75rem 0 0; }
114.carrier h2 { font-size: 1.05rem; margin: 0 0 0.2rem; }
115.sign { margin: 0.6rem 0 1.5rem; border-top: 1px solid var(--line, #38384a); padding-top: 0.6rem; font-size: 0.9rem; color: var(--muted, #999); }
116.hint { color: var(--muted, #999); font-size: 0.9rem; }
117@media print {
118 nav, header.app, .noprint, .btn { display: none !important; }
119 body { background: #fff; color: #000; }
120 .carrier { page-break-inside: avoid; }
121 .sign { color: #000; border-top-color: #999; }
122}
123"""
124
125
126def _rows_for(base, identity, day, carrier_filter):
127 """Every parcel handed over on one day, grouped by carrier.
128
129 Full scans of three collections, the same trade site_pick_list makes: a
130 dock that hands over a million parcels a day is not running this
131 software, and a fold that reads the records is a fold that cannot
132 disagree with them.
133 """
134 try:
135 shipments = object_records.read_collection_records("shipments",
136 base_dir=base)
137 except Exception:
138 return {}, False
139 access = object_access.Access(identity, base_dir=base)
140 shipments = access.visible("shipments", shipments)
141
142 wanted = _text(carrier_filter).lower()
143 mine = []
144 for row in shipments:
145 if _text(row.get("direction")) == "inbound":
146 continue
147 if _text(row.get("status")) not in HANDED_OVER:
148 continue
149 if _text(row.get("shipped_on")) != day:
150 continue
151 carrier = _text(row.get("carrier"))
152 if wanted and carrier.lower() != wanted:
153 continue
154 mine.append(row)
155 if not mine:
156 return {}, False
157
158 try:
159 orders = {row["id"]: row for row in access.visible(
160 "orders", object_records.read_collection_records("orders", base_dir=base))}
161 except Exception:
162 orders = {}
163
164 weighed = any(_text(row.get("weight")) for row in mine)
165 grouped = {}
166 for row in mine:
167 carrier = _text(row.get("carrier")) or NO_CARRIER
168 order = orders.get(_text(row.get("order_id")), {})
169 grouped.setdefault(carrier, []).append({
170 "tracking": _text(row.get("tracking_number")),
171 "order": _text(order.get("number")) or _text(row.get("order_id")),
172 "ship_to": (_text(row.get("ship_to_name"))
173 or _text(order.get("customer_name"))),
174 "service": _text(row.get("service")),
175 "weight": _text(row.get("weight")),
176 })
177 for rows in grouped.values():
178 # Tracking-number order, so checking the pile against the paper is a
179 # walk down the list rather than a search for each parcel.
180 rows.sort(key=lambda entry: (entry["tracking"] or "zzz", entry["order"]))
181 return grouped, weighed
182
183
184def _row(row, weighed):
185 # A parcel with no tracking number is on the manifest anyway and says so:
186 # it is in the van either way, and leaving it off would make the paper
187 # disagree with the pile.
188 tracking = _esc(row["tracking"]) or '<span class="hint">not recorded</span>'
189 weight = f'<td class="num">{_esc(row["weight"])}</td>' if weighed else ""
190 return (f"<tr><td>{tracking}</td><td>{_esc(row['order'])}</td>"
191 f"<td>{_esc(row['ship_to'])}</td><td>{_esc(row['service'])}</td>"
192 f"{weight}</tr>")
193
194
195def _table(rows, weighed):
196 head = ("<tr><th>Tracking number</th><th>Order</th><th>Ship to</th>"
197 "<th>Service</th>" + ('<th class="num">Weight</th>' if weighed else "")
198 + "</tr>")
199 body = "".join(_row(row, weighed) for row in rows)
200 return (f'<table class="manifest-table"><thead>{head}</thead>'
201 f"<tbody>{body}</tbody></table>")
202
203
204def _carrier_block(carrier, rows, weighed):
205 total = sum((_weight(row["weight"]) for row in rows), Decimal(0))
206 weight_line = (f" &middot; {_esc(_number(total))} total weight"
207 if weighed and total > 0 else "")
208 parcels = f"{len(rows)} parcel" + ("s" if len(rows) != 1 else "")
209 return f"""
210<div class="carrier">
211<h2>{_esc(carrier)}</h2>
212<p class="hint">{parcels}{weight_line}</p>
213{_table(rows, weighed)}
214<div class="sign">Received by (print name) ______________________________
215&nbsp; Signature ______________________________
216&nbsp; Time __________</div>
217</div>"""
218
219
220def GET(request):
221 base = _base_dir()
222 identity = request.get("_identity") or {}
223 user_id = _text(identity.get("user_id"))
224 day, date_problem = _day(request.get("date"))
225 carrier_filter = _text(request.get("carrier"))
226
227 if not user_id:
228 body = ('<div class="pagehead"><h1>Shipping manifest</h1></div>'
229 '<p class="hint"><a href="/login?next=/shipments/manifest">Sign in</a> '
230 'to see what went out.</p>')
231 return _page(body, title="Shipping manifest")
232
233 grouped, weighed = _rows_for(base, identity, day, carrier_filter)
234 parcels = sum(len(rows) for rows in grouped.values())
235
236 if grouped:
237 blocks = "".join(_carrier_block(carrier, grouped[carrier], weighed)
238 for carrier in sorted(grouped))
239 else:
240 blocks = ('<p class="hint">Nothing was handed over on this day'
241 + (f" by {_esc(carrier_filter)}" if carrier_filter else "")
242 + ". A shipment joins the manifest for the day it reaches "
243 "<em>shipped</em>, which is when its shipped_on is "
244 "stamped.</p>")
245
246 previous = (date.fromisoformat(day) - timedelta(days=1)).isoformat()
247 following = (date.fromisoformat(day) + timedelta(days=1)).isoformat()
248 query = f"&carrier={_esc(carrier_filter)}" if carrier_filter else ""
249 scope = (f"Carrier: {_esc(carrier_filter)}" if carrier_filter
250 else f"{len(grouped)} carrier" + ("s" if len(grouped) != 1 else ""))
251 problem = f'<p class="hint">{_esc(date_problem)}</p>' if date_problem else ""
252
253 body = f"""
254<div class="breadcrumb noprint"><a href="/">Home</a> / <a href="/shipments">Shipments</a> / Manifest</div>
255<div class="pagehead">
256<h1>Shipping manifest</h1>
257<p class="hint">{_esc(day)} &middot; {scope} &middot; {parcels} parcel{'' if parcels == 1 else 's'}</p>
258</div>
259{problem}
260{blocks}
261<p class="hint noprint">
262<a href="/shipments/manifest?date={_esc(previous)}{query}">&larr; {_esc(previous)}</a>
263&nbsp; <a href="/shipments/manifest?date={_esc(following)}{query}">{_esc(following)} &rarr;</a>
264&nbsp; <a href="/shipments">All shipments</a>
265</p>
266<p class="hint noprint">This page is a read of the shipment records and
267cannot be edited here: a manifest you can change after the van has left is
268not a manifest. Correct a parcel on its shipment.</p>
269"""
270 return _page(body, title=f"Shipping manifest -- {day}")
271
272
273def _page(body, *, title):
274 return {"content_type": "text/html; charset=utf-8",
275 "body": f"""<!doctype html>
276<html lang="en">
277<head>
278<meta charset="utf-8">
279<meta name="viewport" content="width=device-width, initial-scale=1">
280<title>{_esc(title)}</title>
281<link rel="stylesheet" href="/style">
282<style>{_STYLE}</style>
283</head>
284<body>
285<div class="wrap">
286<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
287{body}
288</div>
289<script src="/nav"></script>
290</body>
291</html>"""}