diff --git a/order/fabsrv/app.py b/order/fabsrv/app.py index 12bb100315..4d4db9a587 100644 --- a/order/fabsrv/app.py +++ b/order/fabsrv/app.py @@ -8,9 +8,10 @@ GET /q/{id}?t=token Backplane's Buy now: straight to Stripe Checkout (no quote page) GET /q/{id}/done?s=session back from Stripe: payment confirmed with Stripe itself GET /q/{id}/cancelled back from Stripe without paying - GET /admin paid orders (FAB_ADMIN_TOKEN as a cookie or ?k=) + GET /admin orders by status (?view=), searched (?find=) (FAB_ADMIN_TOKEN as a cookie or ?k=) GET /admin/files/{id} a paid quote's files as one zip - POST /admin/order/{id} an order's status, tracking and note + POST /admin/order/{id} an order's status, tracking and note (kept in its history) + POST /admin/order/{id}/undo the order list's newest change to it, undone Every client sends X-Backplane-Install, a random id made once per install; limits apply to it and to the address (limits.py). @@ -42,6 +43,7 @@ async def lifespan(_app): app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) INSTALL = re.compile(r"^[A-Za-z0-9_-]{16,64}$") QID = re.compile(r"^q_[A-Za-z0-9_-]{20,24}$") +ADMIN_BACK = re.compile(r"^/admin\?view=[a-z]{1,20}(&find=[A-Za-z0-9%+._~-]{0,600})?$") @app.middleware("http") @@ -256,11 +258,11 @@ def admin_ok(request: Request, k=""): @app.get("/admin", response_class=HTMLResponse) -async def admin(request: Request, k: str = ""): +async def admin(request: Request, k: str = "", view: str = "todo", find: str = ""): limited("pay", request) if not admin_ok(request, k): raise HTTPException(404, "not found") - resp = HTMLResponse(pages.admin(store.orders())) + resp = HTMLResponse(pages.admin(store.orders(), view=view[:20], find=find[:200], logs=store.logs())) if k: resp.set_cookie("fab_admin", k, httponly=True, secure=config.PUBLIC_URL.startswith("https"), samesite="strict", max_age=7 * 86400) @@ -287,6 +289,12 @@ async def admin_files(qid: str, request: Request): headers={"Content-Disposition": f"attachment; filename={qid}.zip"}) +def back_to(form): + """Where a Save or Undo returns: the order list's view it came from (never another site).""" + b = str(form.get("back") or "") + return b if ADMIN_BACK.match(b) else "/admin" + + @app.post("/admin/order/{oid}") async def admin_order(oid: str, request: Request): limited("pay", request) @@ -294,11 +302,28 @@ async def admin_order(oid: str, request: Request): raise HTTPException(404, "not found") form = await request.form(max_files=0, max_fields=4, max_part_size=4096) status = str(form.get("status") or "") - if status not in ("paid", "placed", "shipped", "delivered", "refunded", "cancelled"): + if status not in pages.STATUSES: raise HTTPException(400, "bad status") - store.set_order(oid, status=status, tracking=str(form.get("tracking") or "")[:200], - note=str(form.get("note") or "")[:2000]) - return RedirectResponse("/admin", status_code=303) + o = store.order(oid) + if o is None: + raise HTTPException(404, "not found") + if store.never_paid(o): + raise HTTPException(400, "nobody paid this checkout: only Stripe changes its status") + store.change_order(oid, "admin", status=status, tracking=str(form.get("tracking") or "")[:200], + note=str(form.get("note") or "")[:2000]) + return RedirectResponse(back_to(form), status_code=303) + + +@app.post("/admin/order/{oid}/undo") +async def admin_undo(oid: str, request: Request): + """Put back what the order list's newest change to the order replaced.""" + limited("pay", request) + if not admin_ok(request): + raise HTTPException(404, "not found") + form = await request.form(max_files=0, max_fields=2, max_part_size=4096) + if not store.undo(oid): + raise HTTPException(400, "nothing to undo: the newest change was not made here") + return RedirectResponse(back_to(form), status_code=303) async def housekeeping(): diff --git a/order/fabsrv/pages.py b/order/fabsrv/pages.py index 25b42811d3..475997b4cb 100644 --- a/order/fabsrv/pages.py +++ b/order/fabsrv/pages.py @@ -5,6 +5,7 @@ import datetime import html import json +import urllib.parse from . import config, duties @@ -139,20 +140,73 @@ def tax_flag(q, ship): f"ships to {e(state)} ({rate:g}%): {e(what)}.

") -def admin(rows): - """The paid orders, each with what to order where: its parts, options and costs, the - customer's address, and the files to download.""" - out = ["

Orders

Paid orders, newest first. " - "Place each with the fab using its files and options, then set its status: the customer's buy thread follows it.

"] - if not rows: - out.append("
No paid orders yet.
") +# The order list's views: (key, tab label, the kinds of order shown). An order's kind is its status, +# except a checkout nobody paid: "open" while Stripe can still take it, "expired" once it cannot. +VIEWS = (("todo", "To do", ("paid", "placed", "shipped")), ("paid", "Paid: to place", ("paid",)), + ("placed", "Placed", ("placed",)), ("shipped", "Shipped", ("shipped",)), ("delivered", "Delivered", ("delivered",)), + ("refunded", "Refunded", ("refunded",)), ("cancelled", "Cancelled after paying", ("cancelled",)), + ("open", "Open checkouts", ("open",)), ("expired", "Expired checkouts", ("expired",)), ("all", "All", None)) +STATUSES = ("paid", "placed", "shipped", "delivered", "refunded", "cancelled") + + +def kind(o): + if o["status"] == "checkout": + return "open" + return "expired" if o["status"] == "cancelled" and not o["email"] else o["status"] + + +def _utc(t, fmt="%-d %b %Y %H:%M UTC"): + return datetime.datetime.fromtimestamp(t, datetime.timezone.utc).strftime(fmt) + + +def _haystack(o, q, ship): + addr = ship.get("address") or {} + return " ".join(str(x or "") for x in (q.get("title"), o["id"], o["quote_id"], o["email"], o["tracking"], o["note"], + ship.get("name"), ship.get("phone"), o["country"], *addr.values())).lower() + + +def _view_url(view, find): + return "/admin?" + urllib.parse.urlencode({"view": view, **({"find": find} if find else {})}) + + +def admin(rows, view="todo", find="", logs=None): + """The orders in one view (VIEWS) matching `find`, each with what to order where: its parts, + options and costs, the customer's address, the files to download, and its history with Undo.""" + logs = logs or {} + view = view if any(v[0] == view for v in VIEWS) else "todo" + words = find.lower().split() + parsed = [] for o in rows: q = json.loads(o["result"] or "{}") - man = json.loads(o["manifest"] or "{}") if "manifest" in o.keys() else {} ship = json.loads(o["shipping"] or "{}") + if all(w in _haystack(o, q, ship) for w in words): + parsed.append((o, q, ship, kind(o))) + count = {k: sum(1 for p in parsed if ks is None or p[3] in ks) for k, _, ks in VIEWS} + kinds = {k: ks for k, _, ks in VIEWS}[view] + back = _view_url(view, find) + tabs = "".join(f"{e(label)} {count[k]}" + for k, label, _ in VIEWS) + out = ["" + "

Orders

Place each paid order with the fab using its files and options, then set its status: " + "the customer's buy thread follows it. Every change is kept under History, with Undo.

", + f"
" + f"" + "" + + (f"Clear" if find else "") + "
", + f""] + shown = [p for p in parsed if kinds is None or p[3] in kinds] + if not shown: + out.append("
No orders here" + (" match that search." if find else ".") + "
") + for o, q, ship, k in shown: + man = json.loads(o["manifest"] or "{}") if "manifest" in o.keys() else {} addr = ship.get("address") or {} - a = ", ".join(str(addr.get(k)) for k in ("line1", "line2", "city", "state", "postal_code", "country") if addr.get(k)) - when = datetime.datetime.fromtimestamp(o["created"], datetime.timezone.utc).strftime("%-d %b %Y %H:%M UTC") + a = ", ".join(str(addr.get(x)) for x in ("line1", "line2", "city", "state", "postal_code", "country") if addr.get(x)) parts = {p["name"]: p for p in man.get("parts", [])} rows_html = [] for p in q.get("parts", []): @@ -161,17 +215,33 @@ def admin(rows): + f"
{e(p.get('summary'))}
{e(_opts(mp))}
") costs = "".join(f"{e(ln['label'])}{money(ln['amount'])}" for ln in q.get("part_lines", [])) costs += "".join(f"{e(ln['label'])}{money(ln['amount'])}" for ln in q.get("lines", [])[1:]) - tax = tax_flag(q, ship) - opts = "".join(f"{s}" - for s in ("paid", "placed", "shipped", "delivered", "refunded", "cancelled")) + unpaid = k in ("open", "expired") + label = {"open": "open checkout, not paid", "expired": "checkout expired, never paid"}.get(k, o["status"]) out.append( - f"
" + f"
{e(q.get('title') or o['quote_id'])} · {money(o['amount'] / 100)} paid · {e(when)}" - f"
{e(o['id'])} · {e(o['quote_id'])}
" f"
{e(q.get('title') or o['quote_id'])} · {money(o['amount'] / 100)} {'not paid' if unpaid else 'paid'}" + f" · {e(_utc(o['created']))} {e(label)}" + f"
{e(o['id'])} · {e(o['quote_id'])} · updated {e(_utc(o['updated']))}
Files (.zip)
" f"" f"
{''.join(rows_html)}
{costs}

Ship to {e(ship.get('name'))}, {e(a)}
{e(o['email'])} · {e(ship.get('phone'))}" - f"
{e((q.get('shipping') or {}).get('method'))}

{tax}
" - f"
" - f"" - f"
") + f"
{e((q.get('shipping') or {}).get('method'))}

{tax_flag(q, ship)}") + if unpaid: # Stripe alone moves a checkout nobody paid + out.append("

Stripe sets this one's status: it changes here only if the customer pays.

") + else: + opts = "".join(f"{s}" for s in STATUSES) + out.append(f"
" + f"" + f"" + f"
") + hist = logs.get(o["id"], []) + if hist: + items = "".join(f"
  • {e(_utc(h['at']))} · {e('you' if h['by'] == 'admin' else h['by'])}: {e(h['status'])} → {e(h['new_status'])}" + + (f" (tracking was “{e(h['tracking'])}”)" if h["tracking"] else "") + + (f" (note was “{e(h['note'])}”)" if h["note"] else "") + "
  • " for h in hist) + mine = hist[0]["by"] == "admin" + undo = (f"
    " + f"
    ") if mine else "" + out.append(f"History ({len(hist)}){undo}
      {items}
    ") + out.append("") return page("Orders", "".join(out)) diff --git a/order/fabsrv/pay.py b/order/fabsrv/pay.py index 159804d18e..e9df35d105 100644 --- a/order/fabsrv/pay.py +++ b/order/fabsrv/pay.py @@ -103,12 +103,12 @@ def _apply(o, s): det = s.get("customer_details") or {} ship = (s.get("collected_information") or {}).get("shipping_details") or s.get("shipping_details") or {} addr = ship.get("address") or {} - store.set_order(o["id"], status="paid", amount=s.get("amount_total") or o["amount"], + store.change_order(o["id"], "stripe", status="paid", amount=s.get("amount_total") or o["amount"], email=det.get("email") or "", shipping={"name": ship.get("name"), "address": ship.get("address"), "phone": det.get("phone"), **shipped_state(store.quote(o["quote_id"]), addr)}) elif s.get("status") == "expired" and o["status"] == "checkout": - store.set_order(o["id"], status="cancelled") + store.change_order(o["id"], "stripe", status="cancelled") def confirm(o): diff --git a/order/fabsrv/store.py b/order/fabsrv/store.py index 272cb0dd37..e54635ab92 100644 --- a/order/fabsrv/store.py +++ b/order/fabsrv/store.py @@ -3,6 +3,7 @@ A quote's read token is shown once, in the reply that creates it; only its SHA-256 is kept, so a copy of the database cannot read anyone's quote. """ +import contextlib import hashlib import hmac import json @@ -46,6 +47,16 @@ updated real not null ); create index if not exists orders_quote on orders(quote_id); +create table if not exists order_log ( + order_id text not null references orders(id), + at real not null, + by text not null default '', -- admin | stripe + status text not null default '', -- the order as it was before the change + tracking text not null default '', + note text not null default '', + new_status text not null default '' +); +create index if not exists order_log_order on order_log(order_id, at); """ @@ -128,9 +139,79 @@ def set_order(oid, **kv): q(f"update orders set {cols} where id = ?", *kv.values(), oid) -def orders(limit=200): +@contextlib.contextmanager +def _tx(): + """One transaction under the lock (the connection otherwise commits each statement).""" + with _lock: + c = db() + c.execute("begin immediate") + try: + yield c + except BaseException: + c.execute("rollback") + raise + c.execute("commit") + + +def order(oid): + return one("select * from orders where id = ?", oid) + + +def never_paid(o): + """A checkout nobody paid (still open, or expired and cancelled): Stripe alone moves it.""" + return o["status"] in ("checkout", "cancelled") and not o["email"] + + +def change_order(oid, by, **kv): + """Set an order's status, tracking or note, keeping what they were in order_log (for the + order list's history and Undo). Nothing is written when nothing changes.""" + with _tx() as c: + o = c.execute("select * from orders where id = ?", (oid,)).fetchone() + if o is None: + return False + moved = any(str(o[k]) != str(v) for k, v in kv.items() if k in ("status", "tracking", "note")) + if not moved and set(kv) <= {"status", "tracking", "note"}: + return False + now = time.time() + if moved: + c.execute("insert into order_log (order_id, at, by, status, tracking, note, new_status) values (?,?,?,?,?,?,?)", + (oid, now, by, o["status"], o["tracking"], o["note"], kv.get("status", o["status"]))) + kv["updated"] = now + if "shipping" in kv and not isinstance(kv["shipping"], str): + kv["shipping"] = json.dumps(kv["shipping"]) + c.execute(f"update orders set {', '.join(f'{k} = ?' for k in kv)} where id = ?", (*kv.values(), oid)) + return True + + +def order_log(oid): + return q("select rowid, * from order_log where order_id = ? order by at desc, rowid desc", oid) + + +def logs(): + """Every order's changes, newest first, by order id.""" + out = {} + for r in q("select rowid, * from order_log order by at desc, rowid desc"): + out.setdefault(r["order_id"], []).append(r) + return out + + +def undo(oid): + """Put back what the newest change from the order list replaced, and forget that change. + False when the newest change was not the order list's (Stripe's are never undone).""" + with _tx() as c: + r = c.execute("select rowid, * from order_log where order_id = ? order by at desc, rowid desc limit 1", (oid,)).fetchone() + if r is None or r["by"] != "admin": + return False + c.execute("update orders set status = ?, tracking = ?, note = ?, updated = ? where id = ?", + (r["status"], r["tracking"], r["note"], time.time(), oid)) + c.execute("delete from order_log where rowid = ?", (r["rowid"],)) + return True + + +def orders(limit=1000): + """Every order, open checkouts too, newest first, with its quote.""" return q("select o.*, q.country, q.result, q.manifest from orders o join quotes q on q.id = o.quote_id " - "where o.status != 'checkout' order by o.created desc limit ?", limit) + "order by o.created desc limit ?", limit) def open_checkouts(): diff --git a/order/tests/test_server.py b/order/tests/test_server.py index f0f762162f..52e7118ead 100644 --- a/order/tests/test_server.py +++ b/order/tests/test_server.py @@ -491,3 +491,67 @@ def post(self, path, data=None, headers=None): assert sent["consent_collection[terms_of_service]"] == "required" assert f"({config.PUBLIC_URL}/terms)" in sent["custom_text[terms_of_service_acceptance][message]"] assert len(sent["custom_text[terms_of_service_acceptance][message]"]) <= 1200 + + +def test_the_order_list_filters_keeps_history_and_undoes(): + from fabsrv import config, pages, store + c = client() + c.cookies.set("fab_admin", config.ADMIN_TOKEN) + + def order(title, status, email="", name="", city=""): + qid, _ = store.create_quote("filters-install-0123456789", "127.0.0.1", "US", {"title": title}) + store.set_quote(qid, status="ready", result={"title": title, "parts": [], "lines": []}) + oid = store.create_order(qid, "cs_test_" + title.replace(" ", ""), 12345) + store.set_order(oid, status=status, email=email, + shipping={"name": name, "address": {"city": city, "country": "US"}} if name else {}) + return oid + + paid = order("Amp board", "paid", "amp@example.com", "Ada Lovelace", "Monroe") + placed = order("Pedal board", "placed", "pedal@example.com", "Bob Moog", "Asheville") + expired = order("Lamp board", "cancelled") + opened = order("Logger board", "checkout") + + def page(**params): + r = c.get("/admin", params=params) + assert r.status_code == 200, r.text + return r.text + + todo = page() # the default view: paid, placed and shipped orders only + assert "Amp board" in todo and "Pedal board" in todo and "Lamp board" not in todo and "Logger board" not in todo + assert "Lamp board" in page(view="expired") and "Amp board" not in page(view="expired") + assert "Logger board" in page(view="open") and "Lamp board" not in page(view="open") + assert all(t in page(view="all") for t in ("Amp board", "Pedal board", "Lamp board", "Logger board")) + found = page(view="all", find="moog asheville") # every word, any field, any case + assert "Pedal board" in found and "Amp board" not in found + assert "No orders here match that search." in page(find="nobody-like-this") + assert "Paid: to place 1" in page(), "the tabs count what they hold" + assert "Stripe sets this one" in page(view="expired") and f"/admin/order/{expired}'" not in page(view="expired") + + # a checkout nobody paid is never changed here (that is how one became "paid" by mistake) + for oid in (expired, opened): + r = c.post(f"/admin/order/{oid}", data={"status": "paid"}, follow_redirects=False) + assert r.status_code == 400 and store.order(oid)["status"] in ("cancelled", "checkout") + + # a change is kept, shown, and undone; Save goes back to the view it came from, and only to one + r = c.post(f"/admin/order/{paid}", data={"status": "placed", "tracking": "", "note": "fab W1", "back": "/admin?view=paid"}, + follow_redirects=False) + assert r.status_code == 303 and r.headers["location"] == "/admin?view=paid" + assert store.order(paid)["status"] == "placed" and len(store.order_log(paid)) == 1 + assert "Undo: back to paid" in page(view="placed") and "you: paid → placed" in page(view="placed") + r = c.post(f"/admin/order/{paid}", data={"status": "placed", "note": "fab W1", "back": "https://evil.example/admin?view=x"}, + follow_redirects=False) + assert r.headers["location"] == "/admin" and len(store.order_log(paid)) == 1, "an unchanged Save writes nothing" + r = c.post(f"/admin/order/{paid}/undo", data={"back": "/admin?view=all&find=amp"}, follow_redirects=False) + assert r.status_code == 303 and r.headers["location"] == "/admin?view=all&find=amp" + o = store.order(paid) + assert (o["status"], o["note"]) == ("paid", "") and store.order_log(paid) == [] + assert c.post(f"/admin/order/{paid}/undo", follow_redirects=False).status_code == 400, "nothing left to undo" + + # Stripe's changes are kept too, but never undone from the list + store.change_order(opened, "stripe", status="cancelled") + assert store.order_log(opened)[0]["by"] == "stripe" and not store.undo(opened) + assert pages.kind(store.order(opened)) == "expired" + + # without the admin cookie, nothing + anon = client() + assert anon.get("/admin").status_code == 404 and anon.post(f"/admin/order/{paid}/undo").status_code == 404