askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
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. |
| 2 | GET /shipments/manifest?date=&carrier= |
| 3 | |
| 4 | A FOLD OVER FACTS, NEVER EDITABLE FROM THIS PAGE. There is no manifests |
| 5 | collection, no form, no button and no link on here that changes anything. |
| 6 | That is the whole character of the document: a manifest is the piece of |
| 7 | paper a driver signs at the dock, and a manifest you can edit after the van |
| 8 | has left is not a manifest -- it is a story about a van. Everything on it is |
| 9 | read 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 |
| 11 | copy in the driver's hand and the copy on the screen cannot drift, and a |
| 12 | correction is a correction to a SHIPMENT, made where that shipment lives, |
| 13 | with the change log that comes with it. |
| 14 | |
| 15 | PER CARRIER, because that is the unit of handover. Two carriers collect from |
| 16 | the same dock on the same morning and each takes their own pile; one list |
| 17 | mixing them is a list neither driver can sign. With no ?carrier= the page |
| 18 | prints every carrier as its own section with its own count and its own |
| 19 | signature line, so the whole morning is one print job; with ?carrier= it is |
| 20 | the single pile, for the shop that prints as each van pulls up. |
| 21 | |
| 22 | ONE DAY, keyed on shipped_on -- the date the box was handed over, stamped by |
| 23 | system_order_fulfillment the moment a shipment reaches `shipped`. Not |
| 24 | created_at: a parcel packed on Friday and collected on Monday belongs on |
| 25 | Monday's manifest, because Monday is the day somebody signed for it. A |
| 26 | shipment with no shipped_on therefore appears on no manifest at all, which |
| 27 | is the honest answer -- it has not been handed to anybody. |
| 28 | |
| 29 | NO PRICES, the same rule as the packing slip and for a stronger reason: this |
| 30 | document is handed to a third party who has no business knowing what the |
| 31 | contents cost, and a carrier that can read the value of every parcel in the |
| 32 | van is a shop that has published its own theft target. |
| 33 | |
| 34 | Columns are the four things a handover argument is ever about -- tracking |
| 35 | number, order, who it is going to, and which service was paid for -- plus |
| 36 | weight WHEN THE ROWS HAVE ONE. shipments declares no weight field: a |
| 37 | deployment that weighs parcels adds one as an extra field, and the column |
| 38 | appears because rows carry it, rather than a column of blanks appearing |
| 39 | because a schema hoped somebody would. |
| 40 | |
| 41 | Sign-in gated exactly like site_pick_list: a sign-in prompt, not a 403, and |
| 42 | shipments belonging to the signed-in operator OR to nobody (guest checkout |
| 43 | leaves owner_id blank by design, so filtering strictly by owner would show |
| 44 | an empty dock to the one person with parcels going out). |
| 45 | """ |
| 46 | |
| 47 | import html |
| 48 | import os |
| 49 | from datetime import date, timedelta |
| 50 | from decimal import Decimal, InvalidOperation |
| 51 | |
| 52 | import object_records |
| 53 | |
| 54 | ACTOR = "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. |
| 58 | HANDED_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. |
| 64 | NO_CARRIER = "No carrier named" |
| 65 | |
| 66 | |
| 67 | def _base_dir(): |
| 68 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 69 | |
| 70 | |
| 71 | def _text(value): |
| 72 | return str(value if value is not None else "").strip() |
| 73 | |
| 74 | |
| 75 | def _esc(value): |
| 76 | return html.escape(_text(value)) |
| 77 | |
| 78 | |
| 79 | def _weight(value): |
| 80 | try: |
| 81 | return Decimal(_text(value) or "0") |
| 82 | except InvalidOperation: |
| 83 | return Decimal(0) |
| 84 | |
| 85 | |
| 86 | def _number(value): |
| 87 | return format(value.normalize(), "f") |
| 88 | |
| 89 | |
| 90 | def _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 | |
| 123 | def _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 | |
| 181 | def _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 | |
| 192 | def _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 | |
| 201 | def _carrier_block(carrier, rows, weighed): |
| 202 | total = sum((_weight(row["weight"]) for row in rows), Decimal(0)) |
| 203 | weight_line = (f" · {_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 | Signature ______________________________ |
| 213 | Time __________</div> |
| 214 | </div>""" |
| 215 | |
| 216 | |
| 217 | def 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)} · {scope} · {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}">← {_esc(previous)}</a> |
| 260 | <a href="/shipments/manifest?date={_esc(following)}{query}">{_esc(following)} →</a> |
| 261 | <a href="/shipments">All shipments</a> |
| 262 | </p> |
| 263 | <p class="hint noprint">This page is a read of the shipment records and |
| 264 | cannot be edited here: a manifest you can change after the van has left is |
| 265 | not a manifest. Correct a parcel on its shipment.</p> |
| 266 | """ |
| 267 | return _page(body, title=f"Shipping manifest -- {day}") |
| 268 | |
| 269 | |
| 270 | def _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>"""} |