Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions order/fabsrv/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -287,18 +289,41 @@ 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)
if not admin_ok(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():
Expand Down
108 changes: 89 additions & 19 deletions order/fabsrv/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import datetime
import html
import json
import urllib.parse

from . import config, duties

Expand Down Expand Up @@ -139,20 +140,73 @@ def tax_flag(q, ship):
f"ships to {e(state)} ({rate:g}%): {e(what)}.</p>")


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 = ["<style>main{max-width:1100px}</style><h1>Orders</h1><p class=sub>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.</p>"]
if not rows:
out.append("<div class=card>No paid orders yet.</div>")
# 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"<a class='{'on' if k == view else ''}' href='{e(_view_url(k, find))}'>{e(label)} <span class=muted>{count[k]}</span></a>"
for k, label, _ in VIEWS)
out = ["<style>main{max-width:1100px}.tabs{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 12px}"
".tabs a{border:1px solid var(--line);border-radius:999px;padding:4px 12px;text-decoration:none;color:var(--text);font-size:13px}"
".tabs a.on{background:var(--accent);border-color:var(--accent);color:#fff}.tabs a.on .muted{color:#fff}"
".find{display:flex;gap:8px;margin:0 0 8px}.find input{flex:1;padding:6px 10px;font:inherit}"
".badge{border:1px solid var(--line);border-radius:6px;padding:1px 6px;font-size:12px}"
".b-paid{color:var(--warn);border-color:var(--warn)}.b-expired,.b-open{color:var(--muted)}"
"details{margin-top:8px}summary{cursor:pointer;color:var(--muted);font-size:13px}</style>"
"<h1>Orders</h1><p class=sub>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.</p>",
f"<form class=find method=get action='/admin'><input type=hidden name=view value='{e(view)}'>"
f"<input name=find value='{e(find)}' placeholder='Find: name, email, project, order or quote id, tracking, note, country, city'>"
"<button style='width:auto;padding:6px 16px'>Find</button>"
+ (f"<a href='{e(_view_url(view, ''))}' style='align-self:center'>Clear</a>" if find else "") + "</form>",
f"<nav class=tabs>{tabs}</nav>"]
shown = [p for p in parsed if kinds is None or p[3] in kinds]
if not shown:
out.append("<div class=card>No orders here" + (" match that search." if find else ".") + "</div>")
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", []):
Expand All @@ -161,17 +215,33 @@ def admin(rows):
+ f"<br><span class='muted small'>{e(p.get('summary'))}<br>{e(_opts(mp))}</span></td></tr>")
costs = "".join(f"<tr><td class=small>{e(ln['label'])}</td><td class='n small'>{money(ln['amount'])}</td></tr>" for ln in q.get("part_lines", []))
costs += "".join(f"<tr><td class=small>{e(ln['label'])}</td><td class='n small'>{money(ln['amount'])}</td></tr>" for ln in q.get("lines", [])[1:])
tax = tax_flag(q, ship)
opts = "".join(f"<option{' selected' if s == o['status'] else ''}>{s}</option>"
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"<div class=card><table><tr><td><b>{e(q.get('title') or o['quote_id'])}</b> · {money(o['amount'] / 100)} paid · {e(when)}"
f"<br><span class='muted small'>{e(o['id'])} · {e(o['quote_id'])}</span></td>"
f"<div class=card><table><tr><td><b>{e(q.get('title') or o['quote_id'])}</b> · {money(o['amount'] / 100)} {'not paid' if unpaid else 'paid'}"
f" · {e(_utc(o['created']))} <span class='badge b-{e(k)}'>{e(label)}</span>"
f"<br><span class='muted small'>{e(o['id'])} · {e(o['quote_id'])} · updated {e(_utc(o['updated']))}</span></td>"
f"<td class=n><a href='/admin/files/{e(o['quote_id'])}'>Files (.zip)</a></td></tr></table>"
f"<table style='margin-top:10px'><tr><td style='width:55%'><table>{''.join(rows_html)}</table></td>"
f"<td><table>{costs}</table><p class=small><b>Ship to</b> {e(ship.get('name'))}, {e(a)}<br>{e(o['email'])} · {e(ship.get('phone'))}"
f"<br>{e((q.get('shipping') or {}).get('method'))}</p>{tax}</td></tr></table>"
f"<form method=post action='/admin/order/{e(o['id'])}' style='display:flex;gap:8px;margin-top:8px'>"
f"<select name=status>{opts}</select><input name=tracking placeholder='tracking number' value='{e(o['tracking'])}'>"
f"<input name=note placeholder=note value='{e(o['note'])}' style='flex:1'><button style='width:auto;padding:6px 16px'>Save</button></form></div>")
f"<br>{e((q.get('shipping') or {}).get('method'))}</p>{tax_flag(q, ship)}</td></tr></table>")
if unpaid: # Stripe alone moves a checkout nobody paid
out.append("<p class='muted small'>Stripe sets this one's status: it changes here only if the customer pays.</p>")
else:
opts = "".join(f"<option{' selected' if s == o['status'] else ''}>{s}</option>" for s in STATUSES)
out.append(f"<form method=post action='/admin/order/{e(o['id'])}' style='display:flex;gap:8px;margin-top:8px'>"
f"<input type=hidden name=back value='{e(back)}'>"
f"<select name=status>{opts}</select><input name=tracking placeholder='tracking number' value='{e(o['tracking'])}'>"
f"<input name=note placeholder=note value='{e(o['note'])}' style='flex:1'><button style='width:auto;padding:6px 16px'>Save</button></form>")
hist = logs.get(o["id"], [])
if hist:
items = "".join(f"<li>{e(_utc(h['at']))} · {e('you' if h['by'] == 'admin' else h['by'])}: {e(h['status'])} → {e(h['new_status'])}"
+ (f" <span class=muted>(tracking was “{e(h['tracking'])}”)</span>" if h["tracking"] else "")
+ (f" <span class=muted>(note was “{e(h['note'])}”)</span>" if h["note"] else "") + "</li>" for h in hist)
mine = hist[0]["by"] == "admin"
undo = (f"<form method=post action='/admin/order/{e(o['id'])}/undo' style='margin:4px 0'>"
f"<input type=hidden name=back value='{e(back)}'><button style='width:auto;padding:4px 12px;font-size:13px'>"
f"Undo: back to {e(hist[0]['status'])}</button></form>") if mine else ""
out.append(f"<details{' open' if mine else ''}><summary>History ({len(hist)})</summary>{undo}<ul class=small>{items}</ul></details>")
out.append("</div>")
return page("Orders", "".join(out))
4 changes: 2 additions & 2 deletions order/fabsrv/pay.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
85 changes: 83 additions & 2 deletions order/fabsrv/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
"""


Expand Down Expand Up @@ -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():
Expand Down
Loading
Loading