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
manifest.py · 11.5 KB · 288 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
42shipments belonging to the signed-in operator OR to nobody (guest checkout
43leaves owner_id blank by design, so filtering strictly by owner would show
44an empty dock to the one person with parcels going out).
45"""
46
47import html
48import os
49from datetime import date, timedelta
50from decimal import Decimal, InvalidOperation
51
52import object_records
53
54ACTOR = "site_manifest"
55
56# What a driver can be handed. `open` and `packed` are still on the bench;
57# the inbound ladder is somebody else's parcel coming back to us.
58HANDED_OVER = {"shipped", "in_transit", "delivered", "returned_to_sender",
59 "lost"}
60
61# The heading for parcels whose carrier nobody typed. Not "Unknown": the
62# shop knows perfectly well who took them, it just did not write it down,
63# and a manifest that says so is a manifest somebody fixes.
64NO_CARRIER = "No carrier named"
65
66
67def _base_dir():
68 return os.environ.get("DBBASIC_DATA_DIR", "data")
69
70
71def _text(value):
72 return str(value if value is not None else "").strip()
73
74
75def _esc(value):
76 return html.escape(_text(value))
77
78
79def _weight(value):
80 try:
81 return Decimal(_text(value) or "0")
82 except InvalidOperation:
83 return Decimal(0)
84
85
86def _number(value):
87 return format(value.normalize(), "f")
88
89
90def _day(value):
91 """The requested day, or today. A date nobody can parse is answered with
92 today plus a note rather than a traceback: somebody is standing at a dock
93 holding parcels, and the page's job is to print."""
94 raw = _text(value)
95 if not raw:
96 return date.today().isoformat(), ""
97 try:
98 return date.fromisoformat(raw).isoformat(), ""
99 except ValueError:
100 return date.today().isoformat(), (
101 f"{raw!r} is not a date this page can read (use YYYY-MM-DD); "
102 f"showing today instead.")
103
104
105_STYLE = """
106.manifest-table { width: 100%; border-collapse: collapse; margin: 0.4rem 0 1rem; }
107.manifest-table th, .manifest-table td { text-align: left; padding: 0.35rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
108.manifest-table th { font-weight: 600; }
109.manifest-table td.num, .manifest-table th.num { text-align: right; }
110.carrier { margin: 1.75rem 0 0; }
111.carrier h2 { font-size: 1.05rem; margin: 0 0 0.2rem; }
112.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); }
113.hint { color: var(--muted, #999); font-size: 0.9rem; }
114@media print {
115 nav, header.app, .noprint, .btn { display: none !important; }
116 body { background: #fff; color: #000; }
117 .carrier { page-break-inside: avoid; }
118 .sign { color: #000; border-top-color: #999; }
119}
120"""
121
122
123def _rows_for(base, user_id, day, carrier_filter):
124 """Every parcel handed over on one day, grouped by carrier.
125
126 Full scans of three collections, the same trade site_pick_list makes: a
127 dock that hands over a million parcels a day is not running this
128 software, and a fold that reads the records is a fold that cannot
129 disagree with them.
130 """
131 try:
132 shipments = object_records.read_collection_records("shipments",
133 base_dir=base)
134 except Exception:
135 return {}, False
136
137 wanted = _text(carrier_filter).lower()
138 mine = []
139 for row in shipments:
140 if _text(row.get("direction")) == "inbound":
141 continue
142 if _text(row.get("status")) not in HANDED_OVER:
143 continue
144 if _text(row.get("shipped_on")) != day:
145 continue
146 if _text(row.get("owner_id")) not in ("", user_id):
147 continue
148 carrier = _text(row.get("carrier"))
149 if wanted and carrier.lower() != wanted:
150 continue
151 mine.append(row)
152 if not mine:
153 return {}, False
154
155 try:
156 orders = {row["id"]: row for row in
157 object_records.read_collection_records("orders", base_dir=base)}
158 except Exception:
159 orders = {}
160
161 weighed = any(_text(row.get("weight")) for row in mine)
162 grouped = {}
163 for row in mine:
164 carrier = _text(row.get("carrier")) or NO_CARRIER
165 order = orders.get(_text(row.get("order_id")), {})
166 grouped.setdefault(carrier, []).append({
167 "tracking": _text(row.get("tracking_number")),
168 "order": _text(order.get("number")) or _text(row.get("order_id")),
169 "ship_to": (_text(row.get("ship_to_name"))
170 or _text(order.get("customer_name"))),
171 "service": _text(row.get("service")),
172 "weight": _text(row.get("weight")),
173 })
174 for rows in grouped.values():
175 # Tracking-number order, so checking the pile against the paper is a
176 # walk down the list rather than a search for each parcel.
177 rows.sort(key=lambda entry: (entry["tracking"] or "zzz", entry["order"]))
178 return grouped, weighed
179
180
181def _row(row, weighed):
182 # A parcel with no tracking number is on the manifest anyway and says so:
183 # it is in the van either way, and leaving it off would make the paper
184 # disagree with the pile.
185 tracking = _esc(row["tracking"]) or '<span class="hint">not recorded</span>'
186 weight = f'<td class="num">{_esc(row["weight"])}</td>' if weighed else ""
187 return (f"<tr><td>{tracking}</td><td>{_esc(row['order'])}</td>"
188 f"<td>{_esc(row['ship_to'])}</td><td>{_esc(row['service'])}</td>"
189 f"{weight}</tr>")
190
191
192def _table(rows, weighed):
193 head = ("<tr><th>Tracking number</th><th>Order</th><th>Ship to</th>"
194 "<th>Service</th>" + ('<th class="num">Weight</th>' if weighed else "")
195 + "</tr>")
196 body = "".join(_row(row, weighed) for row in rows)
197 return (f'<table class="manifest-table"><thead>{head}</thead>'
198 f"<tbody>{body}</tbody></table>")
199
200
201def _carrier_block(carrier, rows, weighed):
202 total = sum((_weight(row["weight"]) for row in rows), Decimal(0))
203 weight_line = (f" &middot; {_esc(_number(total))} total weight"
204 if weighed and total > 0 else "")
205 parcels = f"{len(rows)} parcel" + ("s" if len(rows) != 1 else "")
206 return f"""
207<div class="carrier">
208<h2>{_esc(carrier)}</h2>
209<p class="hint">{parcels}{weight_line}</p>
210{_table(rows, weighed)}
211<div class="sign">Received by (print name) ______________________________
212&nbsp; Signature ______________________________
213&nbsp; Time __________</div>
214</div>"""
215
216
217def GET(request):
218 base = _base_dir()
219 identity = request.get("_identity") or {}
220 user_id = _text(identity.get("user_id"))
221 day, date_problem = _day(request.get("date"))
222 carrier_filter = _text(request.get("carrier"))
223
224 if not user_id:
225 body = ('<div class="pagehead"><h1>Shipping manifest</h1></div>'
226 '<p class="hint"><a href="/login?next=/shipments/manifest">Sign in</a> '
227 'to see what went out.</p>')
228 return _page(body, title="Shipping manifest")
229
230 grouped, weighed = _rows_for(base, user_id, day, carrier_filter)
231 parcels = sum(len(rows) for rows in grouped.values())
232
233 if grouped:
234 blocks = "".join(_carrier_block(carrier, grouped[carrier], weighed)
235 for carrier in sorted(grouped))
236 else:
237 blocks = ('<p class="hint">Nothing was handed over on this day'
238 + (f" by {_esc(carrier_filter)}" if carrier_filter else "")
239 + ". A shipment joins the manifest for the day it reaches "
240 "<em>shipped</em>, which is when its shipped_on is "
241 "stamped.</p>")
242
243 previous = (date.fromisoformat(day) - timedelta(days=1)).isoformat()
244 following = (date.fromisoformat(day) + timedelta(days=1)).isoformat()
245 query = f"&carrier={_esc(carrier_filter)}" if carrier_filter else ""
246 scope = (f"Carrier: {_esc(carrier_filter)}" if carrier_filter
247 else f"{len(grouped)} carrier" + ("s" if len(grouped) != 1 else ""))
248 problem = f'<p class="hint">{_esc(date_problem)}</p>' if date_problem else ""
249
250 body = f"""
251<div class="breadcrumb noprint"><a href="/">Home</a> / <a href="/shipments">Shipments</a> / Manifest</div>
252<div class="pagehead">
253<h1>Shipping manifest</h1>
254<p class="hint">{_esc(day)} &middot; {scope} &middot; {parcels} parcel{'' if parcels == 1 else 's'}</p>
255</div>
256{problem}
257{blocks}
258<p class="hint noprint">
259<a href="/shipments/manifest?date={_esc(previous)}{query}">&larr; {_esc(previous)}</a>
260&nbsp; <a href="/shipments/manifest?date={_esc(following)}{query}">{_esc(following)} &rarr;</a>
261&nbsp; <a href="/shipments">All shipments</a>
262</p>
263<p class="hint noprint">This page is a read of the shipment records and
264cannot be edited here: a manifest you can change after the van has left is
265not a manifest. Correct a parcel on its shipment.</p>
266"""
267 return _page(body, title=f"Shipping manifest -- {day}")
268
269
270def _page(body, *, title):
271 return {"content_type": "text/html; charset=utf-8",
272 "body": f"""<!doctype html>
273<html lang="en">
274<head>
275<meta charset="utf-8">
276<meta name="viewport" content="width=device-width, initial-scale=1">
277<title>{_esc(title)}</title>
278<link rel="stylesheet" href="/style">
279<style>{_STYLE}</style>
280</head>
281<body>
282<div class="wrap">
283<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
284{body}
285</div>
286<script src="/nav"></script>
287</body>
288</html>"""}