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
buy_label.py · 13.9 KB · 313 lines
| 1 | """action_buy_label -- put a tracking number and a label on a parcel, |
| 2 | whichever way this shop actually gets one. |
| 3 | |
| 4 | POST {shipment_id, tracking_number?, carrier?, label_base64?, |
| 5 | label_content_type?, label_filename?} |
| 6 | |
| 7 | ONE VERB, BOTH DIRECTIONS. A return label is this action against an INBOUND |
| 8 | shipment; there is deliberately no action_buy_return_label. A return label |
| 9 | is the same purchase with the addresses the other way round, and a second |
| 10 | verb would be a second place for the credentials, the refusals, the file |
| 11 | handling and the stamping to drift -- which in practice means the return |
| 12 | half quietly rots, because it is used a tenth as often as the outbound half. |
| 13 | |
| 14 | UNCONFIGURED IS A 409 THAT NAMES THE SETTING, never a broken button and |
| 15 | never a fake success. Same posture as action_stripe_checkout, and for the |
| 16 | same reason: the shop can see the button, so the button owes them a sentence |
| 17 | they can act on. `missing_settings` carries the same fact as a list, for a |
| 18 | client that wants to render the fix rather than the prose. |
| 19 | |
| 20 | The whole flow works with no carrier at all -- that is the design, not a |
| 21 | consolation. With carrier.provider=manual the operator walks to the counter, |
| 22 | buys the postage, and brings back a tracking number (and, if they were |
| 23 | handed one, the label PDF). This action records both. It buys nothing and |
| 24 | says it bought nothing. What it gets in exchange for going through the |
| 25 | connector interface anyway is that the day a real adapter is installed, the |
| 26 | tracking number arrives on the same field, the label lands in the same file, |
| 27 | the manifest prints the same row and nothing downstream is rewritten. |
| 28 | |
| 29 | THE LABEL FILE IS EVIDENCE (docs/logic-decisions.md #8), stored exactly the |
| 30 | way a scanned receipt is: bytes through object_user_files, a `files` row so |
| 31 | it can actually be opened at /api/files/{id}, and the id stamped on the |
| 32 | shipment. A re-bought label gets a NEW file id rather than overwriting the |
| 33 | old bytes -- the first label was really printed and may really be on a box, |
| 34 | and evidence is not edited to agree with the current plan. |
| 35 | |
| 36 | A failure to store the FILE does not lose the TRACKING NUMBER. The number is |
| 37 | the thing a customer will be given and the thing the poll needs; the PDF is |
| 38 | a convenience the operator can re-upload. Refusing the whole action because |
| 39 | a file write failed would be the paperwork throwing away the fact to protect |
| 40 | the attachment. |
| 41 | """ |
| 42 | |
| 43 | import base64 |
| 44 | import os |
| 45 | from datetime import datetime, timezone |
| 46 | from pathlib import Path |
| 47 | |
| 48 | import object_connectors |
| 49 | import object_ids |
| 50 | import object_packages |
| 51 | import object_records |
| 52 | import object_user_files |
| 53 | |
| 54 | ACTOR = "action_buy_label" |
| 55 | |
| 56 | # A shipping label is a few hundred kilobytes of PDF. The cap is here to |
| 57 | # refuse an accident, not to price a service. |
| 58 | MAX_BYTES = 10 * 1024 * 1024 |
| 59 | |
| 60 | # Journeys that are over. Buying a label for one of these is somebody on the |
| 61 | # wrong record, and stamping a new tracking number onto a delivered parcel |
| 62 | # would rewrite what the customer was told last week. |
| 63 | FINISHED = {"delivered", "returned_to_sender", "lost", "received", |
| 64 | "dispositioned", "expired"} |
| 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 _setting(base, key, default=""): |
| 76 | """Duplicated on purpose, same as every other package that reads |
| 77 | app_settings (docs/logic-decisions.md #4).""" |
| 78 | try: |
| 79 | for row in object_records.read_collection_records("app_settings", |
| 80 | base_dir=base): |
| 81 | if row.get("key") == key and _text(row.get("value")): |
| 82 | return _text(row["value"]) |
| 83 | except Exception: |
| 84 | pass |
| 85 | return default |
| 86 | |
| 87 | |
| 88 | # --- the carrier boundary ----------------------------------------------------- |
| 89 | # |
| 90 | # A deliberate second copy of the pair in system_tracking_poll, named in both |
| 91 | # files: objects on this platform cannot import one another (a sibling is |
| 92 | # executed, not imported), and #4 says the third occurrence is the one that |
| 93 | # earns the extraction. |
| 94 | |
| 95 | def _carrier_declaration(): |
| 96 | """The connector declaration that owns `shipments` on this box, resolved |
| 97 | through object_packages.iter_connectors -- the existing mechanism, which |
| 98 | escape-checks the module path and lets a private overlay win.""" |
| 99 | packages = os.environ.get("DBBASIC_PACKAGES_DIR", object_packages.PACKAGES_DIR) |
| 100 | private = (os.environ.get("DBBASIC_PRIVATE_PACKAGES_DIR") |
| 101 | or str(Path(packages).parent / "packages-private")) |
| 102 | roots = ([private] if Path(private).is_dir() else []) + [packages] |
| 103 | for root in roots: |
| 104 | for declaration in object_packages.iter_connectors(root=root): |
| 105 | if declaration["collection"] == "shipments": |
| 106 | return declaration |
| 107 | return None |
| 108 | |
| 109 | |
| 110 | def _carrier(base, entry): |
| 111 | """(function, provider, problem, missing) -- the configured carrier's |
| 112 | `entry`, or the honest reason there is not one plus the settings whose |
| 113 | absence caused it.""" |
| 114 | provider = _setting(base, "carrier.provider", "none").lower() or "none" |
| 115 | if provider == "none": |
| 116 | return None, provider, ( |
| 117 | "No carrier is configured on this server, so there is no label to " |
| 118 | "buy. Set app_settings carrier.provider to `manual` and pass the " |
| 119 | "tracking number from the post office counter (with the label PDF " |
| 120 | "if you were handed one), or set it to an installed carrier " |
| 121 | "adapter's name. Until then the shipment still works: type the " |
| 122 | "tracking number on it and print the packing slip." |
| 123 | ), ["carrier.provider"] |
| 124 | |
| 125 | declaration = _carrier_declaration() |
| 126 | if declaration is None: |
| 127 | return None, provider, ( |
| 128 | f"app_settings carrier.provider is {provider!r}, but no installed " |
| 129 | f"package declares a connector for the shipments collection. " |
| 130 | f"Install the carrier adapter package, or set carrier.provider to " |
| 131 | f"`manual`." |
| 132 | ), ["carrier.provider"] |
| 133 | try: |
| 134 | function = object_connectors.load_connector(declaration["module"], entry) |
| 135 | except object_connectors.ConnectorLoadError as exc: |
| 136 | return None, provider, ( |
| 137 | f"The carrier connector for {provider!r} could not be loaded: " |
| 138 | f"{str(exc)[:200]}" |
| 139 | ), [] |
| 140 | |
| 141 | # The module's own name for itself, read off the loaded function's |
| 142 | # globals: load_connector deliberately keeps the module out of |
| 143 | # sys.modules, and a second loader to read one constant would be a |
| 144 | # second loader. |
| 145 | declared = _text(function.__globals__.get("PROVIDER")) |
| 146 | if declared and declared.lower() != provider: |
| 147 | return None, provider, ( |
| 148 | f"app_settings carrier.provider is {provider!r}, but the connector " |
| 149 | f"installed for shipments answers to {declared!r}. Nothing was " |
| 150 | f"bought: using a carrier the shop did not configure is worse than " |
| 151 | f"a refusal." |
| 152 | ), ["carrier.provider"] |
| 153 | return function, provider, "", [] |
| 154 | |
| 155 | |
| 156 | def _store_label(base, shipment, outcome): |
| 157 | """Bytes to disk, a `files` row so somebody can open them, and the id. |
| 158 | |
| 159 | Returns (file_id, url, error). The `files` row is best-effort: a |
| 160 | deployment without app-files installed still gets the bytes and the |
| 161 | stamp, and says so, because a label held and unopenable beats a label |
| 162 | refused. |
| 163 | """ |
| 164 | content = outcome.get("label_bytes") |
| 165 | if not content: |
| 166 | return "", "", "" |
| 167 | if not isinstance(content, (bytes, bytearray)): |
| 168 | return "", "", "the carrier returned a label that was not bytes" |
| 169 | |
| 170 | owner = _text(shipment.get("owner_id")) or "shipping" |
| 171 | # A NEW id per label, never a rewrite of the last one: the previous label |
| 172 | # may be on a box somewhere, and evidence is not edited (#8). |
| 173 | file_id = f"label-{object_ids.new_uuid4()}" |
| 174 | try: |
| 175 | size = object_user_files.save_file(owner, file_id, bytes(content), |
| 176 | base_dir=base) |
| 177 | except Exception as exc: # noqa: BLE001 |
| 178 | return "", "", f"the label could not be stored: {str(exc)[:160]}" |
| 179 | |
| 180 | try: |
| 181 | object_records.create_collection_record( |
| 182 | "files", |
| 183 | { |
| 184 | "id": file_id, |
| 185 | "filename": (_text(outcome.get("label_filename")) |
| 186 | or f"label-{shipment['id'][:8]}.pdf"), |
| 187 | "content_type": (_text(outcome.get("label_content_type")) |
| 188 | or "application/pdf"), |
| 189 | "size": str(size), |
| 190 | "description": (f"Shipping label for shipment " |
| 191 | f"{shipment['id']}"), |
| 192 | "parent_collection": "shipments", |
| 193 | "parent_id": shipment["id"], |
| 194 | "owner_id": owner, |
| 195 | }, |
| 196 | base_dir=base, actor=ACTOR) |
| 197 | except Exception as exc: # noqa: BLE001 |
| 198 | return file_id, "", (f"the label bytes were stored but no files record " |
| 199 | f"could be written ({str(exc)[:120]}), so it will " |
| 200 | f"not open at /api/files") |
| 201 | return file_id, f"/api/files/{file_id}", "" |
| 202 | |
| 203 | |
| 204 | def POST(request): |
| 205 | base = _base_dir() |
| 206 | shipment_id = _text(request.get("shipment_id")) |
| 207 | if not shipment_id: |
| 208 | return {"status": 400, "error": "shipment_id is required"} |
| 209 | |
| 210 | try: |
| 211 | shipment = object_records.get_collection_record("shipments", |
| 212 | shipment_id, |
| 213 | base_dir=base) |
| 214 | except Exception: |
| 215 | shipment = None |
| 216 | if not shipment: |
| 217 | return {"status": 404, "error": f"No such shipment: {shipment_id}"} |
| 218 | |
| 219 | status = _text(shipment.get("status")) |
| 220 | if status in FINISHED: |
| 221 | return {"status": 409, |
| 222 | "error": (f"This shipment is {status}: its journey is over, so " |
| 223 | f"a new label would only overwrite what the customer " |
| 224 | f"was already told. Raise a new shipment if goods " |
| 225 | f"have to move again.")} |
| 226 | |
| 227 | inbound = _text(shipment.get("direction")) == "inbound" |
| 228 | |
| 229 | label_bytes = None |
| 230 | raw = request.get("label_base64") |
| 231 | if raw: |
| 232 | try: |
| 233 | label_bytes = base64.b64decode(_text(raw), validate=True) |
| 234 | except Exception: |
| 235 | return {"status": 400, "error": "label_base64 is not valid base64."} |
| 236 | if len(label_bytes) > MAX_BYTES: |
| 237 | return {"status": 413, |
| 238 | "error": (f"That label is larger than the " |
| 239 | f"{MAX_BYTES // (1024 * 1024)}MB cap.")} |
| 240 | |
| 241 | buy, provider, problem, missing = _carrier(base, "buy_label") |
| 242 | if problem: |
| 243 | return {"status": 409, "error": problem, "provider": provider, |
| 244 | "missing_settings": missing, |
| 245 | "note": ("the manual path still works with no carrier at all: " |
| 246 | "type the tracking number onto the shipment and print " |
| 247 | "the packing slip")} |
| 248 | |
| 249 | try: |
| 250 | outcome = buy(shipment, base_dir=base, |
| 251 | tracking_number=_text(request.get("tracking_number")), |
| 252 | label_bytes=label_bytes, |
| 253 | label_content_type=_text(request.get("label_content_type")), |
| 254 | label_filename=_text(request.get("label_filename"))) |
| 255 | if not isinstance(outcome, dict): |
| 256 | outcome = {"ok": False, |
| 257 | "error": (f"the carrier connector returned " |
| 258 | f"{type(outcome).__name__}, expected a dict")} |
| 259 | except Exception as exc: # noqa: BLE001 |
| 260 | outcome = {"ok": False, |
| 261 | "error": f"the carrier connector raised: {str(exc)[:200]}"} |
| 262 | |
| 263 | if outcome.get("skip"): |
| 264 | # The connector declined rather than failed -- the host is not ready. |
| 265 | return {"status": 409, "provider": provider, |
| 266 | "error": _text(outcome.get("reason")) or |
| 267 | "the carrier connector declined to sell a label."} |
| 268 | if not outcome.get("ok"): |
| 269 | # `permanent` means the request as posed can never work (a missing |
| 270 | # tracking number, an address the carrier will not accept), which is |
| 271 | # the caller's to fix -- 400. Anything else is the provider having a |
| 272 | # bad minute, which is 502 and worth retrying, the same split |
| 273 | # action_stripe_checkout makes. |
| 274 | return {"status": 400 if outcome.get("permanent") else 502, |
| 275 | "provider": provider, |
| 276 | "error": _text(outcome.get("error")) or |
| 277 | "the carrier could not produce a label."} |
| 278 | |
| 279 | tracking_number = _text(outcome.get("tracking_number")) |
| 280 | file_id, url, file_error = _store_label(base, shipment, outcome) |
| 281 | |
| 282 | update = {} |
| 283 | if tracking_number: |
| 284 | update["tracking_number"] = tracking_number |
| 285 | if file_id: |
| 286 | update["label_file_id"] = file_id |
| 287 | carrier = _text(outcome.get("carrier")) or _text(request.get("carrier")) |
| 288 | if carrier: |
| 289 | update["carrier"] = carrier |
| 290 | if update: |
| 291 | object_records.update_collection_record( |
| 292 | "shipments", shipment_id, update, base_dir=base, actor=ACTOR) |
| 293 | |
| 294 | return { |
| 295 | "ok": True, |
| 296 | "shipment_id": shipment_id, |
| 297 | "direction": "inbound" if inbound else "outbound", |
| 298 | "kind": "return label" if inbound else "shipping label", |
| 299 | "provider": provider, |
| 300 | "tracking_number": tracking_number, |
| 301 | "label_file_id": file_id, |
| 302 | "label_url": url, |
| 303 | "carrier": carrier or _text(shipment.get("carrier")), |
| 304 | "status_of_shipment": status, |
| 305 | "bought_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), |
| 306 | "slip_path": f"/shipments/{shipment_id}/slip", |
| 307 | # The status ladder is not this action's business: a label on the |
| 308 | # bench is not a parcel out of the door, and moving it would let a |
| 309 | # printer jam look like a handover. |
| 310 | "note": (_text(outcome.get("note")) |
| 311 | or "label recorded; the shipment's status is unchanged"), |
| 312 | **({"label_error": file_error} if file_error else {}), |
| 313 | } |