vibes.diy Make an app → Discord
creator docs · reference · generated

Shippo — read a merchant's own orders, the labels bought for them, and the box each one used

This is the same document the Vibes code generator reads when it builds apps — rendered from prompts/pkg/llms/shippo.md on every deploy, so it can't drift from what the platform actually does. Read it from your terminal any time with npx vibes-diy skills.

When someone who ships with Shippo asks for an app over their shipping — "my Shippo orders", "a packing station for the orders in Shippo", "which box each label went out in", "my saved box sizes" — build it on the merchant's own Shippo API key from backend.js. The owner pastes the key into the vibe's Secrets once, and backend.js reads their orders, labels, parcels and saved boxes with it on a schedule. This page reads; the owner keeps buying labels, refunding them and editing orders in Shippo, where they already do.

This is a backend.js feature, and the key is the owner's own (the owner-key rules that load with this page). This page is the recipe that keeps every Shippo call on the server, copies the merchant's orders and labels into the app's own records, and keeps those records the owner's alone.

1. The setup item: the owner's Shippo API key

The Shippo item is the API key: the backend answers missing-key while ctx.secrets.SHIPPO_API_KEY is absent, and its steps link the Shippo developer keys page by URL and name SHIPPO_API_KEY in so many words.

The Setup surface the item lands on (the owner-only entry in the app's navigation, the verdict from /setup, the re-read on focus) is the use-vibe docs' Some apps need setup before they work; this recipe contributes one item to it. The steps use Shippo's own words:

  1. Open https://portal.goshippo.com/api-config/api and sign in with the Shippo account you ship with.
  2. In the API Configuration menu, select Developer keys, then choose Live keys (or Test keys to try the app on test data first).
  3. Copy the key: a live key begins shippo_live_, a test key shippo_test_.
  4. Save it under Secrets on this vibe's Settings tab as SHIPPO_API_KEY, then come back: the owner-key steps every item ends with.

Test and live keep separate data: a test key sees only the orders and labels made in test mode. The backend tells the page which one it holds (the key's prefix), and the page shows a Test mode badge while it reads test data. The item is done when the key is saved and Shippo answered the backend's first read of the orders list. A key Shippo refuses leaves the item To do with the status it answered.

2. Shippo stays on the server

Every Shippo request is made in backend.js with ctx.fetch and ctx.secrets.SHIPPO_API_KEY, sent as Authorization: ShippoToken ; App.jsx never calls api.goshippo.com.

The scheme word is ShippoToken, never Bearer. The host is https://api.goshippo.com, and paths take no version prefix.

backend.js calls only the Shippo reads the platform admits: GET /orders/, GET /orders/{id}, GET /transactions/, GET /transactions/{id}, GET /parcels/{id} and GET /user-parcel-templates.

Write each path exactly so: the two lists end in / (/orders/, /transactions/), a single record has no trailing / (/parcels/{id}), and /user-parcel-templates has none. The platform admits those spellings and no other, so /orders or /parcels/{id}/ is refused before it leaves.

Buying a label (POST /transactions/), creating orders, shipments or parcels, refunds, addresses, carrier accounts and webhook subscriptions stay in Shippo. Shippo's webhooks cover labels and tracking only (transaction_created, transaction_updated, track_updated, batches): there is no order-created event, and the platform does not admit the webhooks endpoint, so the app learns about orders and labels by asking on a schedule.

3. A scheduled poll reads the orders a few pages at a time

A scheduled poll every 15 minutes reads the orders list with start_date, results=100 and page, a few pages per poll, and saves one record per Shippo order keyed by its object_id, so a changed order replaces its own record.

  • GET /orders/ pages with page (from 1) and results (up to 100). The answer is { next, previous, results }; next is empty on the last page.
  • start_date and end_date (ISO 8601 UTC) filter on placed_at, when the order was placed, not when Shippo last changed it. So the poll reads a rolling window, the orders placed in the last 14 days, and re-reads it: an order placed last week turns SHIPPED today, and only a re-read sees it.
  • order_status[] narrows the list (PAID, PARTIALLY_FULFILLED, SHIPPED, AWAITPAY, CANCELLED, REFUNDED, UNKNOWN), repeated once per status. Leave it off to see orders leave the to-pack list.

The poll keeps its place in a sync record: each poll reads up to four pages from the page the last one reached, and once a page comes back with no next the following poll starts again at page 1. A poll that stops early (a refused key, a 429) keeps the page it stopped on, and the next poll asks for that page again. Saving is an upsert that writes only a record whose fields changed, so a poll that finds nothing new writes nothing.

An order still open when it leaves the window (AWAITPAY, PAID or PARTIALLY_FULFILLED after 14 days) would never be seen to ship by the sweep, so each open order goes on a follow-up list the moment it is saved, due when it ages out. From then it is read by id, GET /orders/{id}, once an hour until it ships or for 90 days, a few per poll.

An order record keeps what the app shows: order_number, placed_at, order_status, shop_app (where Shippo imported it from: Shopify, Etsy, WooCommerce, Shippo for one made in Shippo, and so on), each line item's title, quantity, sku and variant_title, the ship-to name and city, and total_price with currency. Shippo sends amounts and weights as decimal strings ("24.93", "0.4"): read them with Number(...).

To match a Shippo order to the store it came from, join on order_number, the store's own number. Shippo's documented shop_app values do not include Squarespace, so an order imported from a Squarespace store is matched by its number, never by shop_app.

4. The box a label used comes from its parcel

The box a label used comes from the label's transaction: GET /transactions/{id} names its parcel, and GET /parcels/{id} gives that box's length, width, height, weight and carrier template.

An order's transactions array lists the labels bought for it, each by its object_id, with only a few fields. Read each new one once:

  • GET /transactions/{id}: status (SUCCESS, QUEUED, WAITING, ERROR, REFUNDED, …), tracking_number, tracking_status, test, object_created, and parcel, the parcel's object id.
  • GET /parcels/{id}: length, width, height in distance_unit, weight in mass_unit, and template when the label used a carrier's own box (USPS_SmallFlatRateBox).
  • GET /user-parcel-templates: the merchant's saved boxes, in results, each with name, length, width, height, distance_unit, weight and weight_unit. One call answers all of them.

Detail reads wait on a list. The poll puts each label it has not read yet on a sync record it reads by id, and each poll reads a few of them (6), most overdue first. A label still QUEUED or WAITING stays on the list and is read again a poll later for up to a day. A parcel already copied is never read again: a parcel does not change once a label is bought. A label whose parcel Shippo does not send (a label bought some other way) is saved with no box, and the page says box not recorded beside it. A label Shippo answers 404 for is saved as gone, so the next sweep does not queue it again.

Each follow-up list (labels to read, open orders to re-read) is one sync record, capped at 500 entries, read by id and saved once per poll whether or not its reads ran. Never find the due entries with a ctx.db.query on a flag field: that filters one raw page, and due entries go unread once other records outnumber them.

5. Rate limits and errors keep their reason

Shippo counts per minute. A list read (GET /orders/, GET /transactions/) allows 50 a minute on a live key and only 10 on a test key; a single-record read (GET /transactions/{id}, GET /parcels/{id}) allows 4,000 live and 400 test. So a poll makes at most five list reads (four order pages and the saved boxes), keeps the single-record reads on the list above, and /setup reads Shippo only until the key has worked once: coming back to the tab spends none of the limit. The platform adds its own limit, 30 outside calls in 10 seconds per vibe, so a poll makes at most 23: five list reads, six open orders, and six labels with their parcels. A poll that meets a 429 stops where it is, keeps its page and its list, and tries again on the next tick; it never retries in a loop.

Return { ok: false, reason, message } so the page can say why:

  • missing-key: the key is not saved yet. The owner sees the Setup item.
  • 401 or 403 from Shippo: it refused the key. The item reads To do, and the fix is a fresh key from Developer keys.
  • 429: Shippo asked us to slow down; the next poll picks up where this one stopped. The orders on the page stay open.
  • A 403 whose body has vibesEgressDenied: true is the platform's own answer (its burst limit, for one), never Shippo refusing the key: read the body before the status, and treat it like a 429.

Wrap every route in try/catch and answer with a reason, because an uncaught throw reaches the page as a bare 500 that names nothing the owner can fix.

6. The records are the owner's alone

Orders carry buyers' names and addresses, so access.js takes every order, label, box, boxes, sync and setup record from backend.js alone and grants them to the owner's role only. A visitor who opens the app sees the Setup verdict and nothing of the shop.

Complete backend.js

The worked example is a packing station: the owner sees the orders still to pack, the orders shipped with the box each label used, and the saved box sizes to pick from.

backend.js

js// A Shippo merchant's orders, labels and boxes, read with the owner's own API key and copied into
// the app's records on a schedule. Read only: labels are bought and refunded in Shippo.
export const config = {
  scheduled: { interval: "15m" },
};

const DB = "station";
const HOST = "https://api.goshippo.com";
const SYNC_ID = "sync:orders";
const LABELS_ID = "sync:labels";
const OPEN_ID = "sync:open";
const SETUP_ID = "setup:shippo";
const BOXES_ID = "boxes:saved";
const DAY_MS = 24 * 60 * 60 * 1000;
const LOOK_BACK_MS = 14 * DAY_MS; // the sweep re-reads the orders placed in the last 14 days
const OPEN_WATCH_MS = 90 * DAY_MS; // an order still open past the window is read by id for 90 days
const PAGES_PER_POLL = 4; // with the saved boxes, five list reads: under a test key's 10 a minute
// Single-record reads per follow-up list per poll. A label can take two calls (its transaction, then
// its parcel), so one poll makes at most 5 + 6 + 12 = 23 calls: under the platform's 30 in 10 seconds.
const READS_PER_POLL = 6;
const LABEL_WAIT_MS = DAY_MS; // a label still queued in Shippo is re-read for a day
const LABEL_EVERY_MS = 10 * 60 * 1000; // at most one re-read per label per poll
const OPEN_EVERY_MS = 60 * 60 * 1000; // an open order past the window is re-read once an hour
const LIST_MAX = 500;
const OPEN = ["AWAITPAY", "PAID", "PARTIALLY_FULFILLED"];

function json(body, status = 200) {
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}

// One Shippo read on the owner's account. The key rides only this request.
async function shippo(ctx, path) {
  const key = ctx.secrets.SHIPPO_API_KEY;
  if (!key) return { ok: false, reason: "missing-key" };
  const res = await ctx.fetch(`${HOST}${path}`, {
    method: "GET",
    headers: { authorization: `ShippoToken ${key}` },
  });
  const out = await res.json().catch(() => null);
  // The platform's own refusal (its burst limit, for one) is a 403 that says so; it is never Shippo
  // refusing the key, so it waits for the next poll like a 429.
  if (out?.vibesEgressDenied === true) return { ok: false, reason: "rate-limited", status: res.status, message: "Too many calls at once; the next poll picks up where this one stopped." };
  if (res.status === 429) return { ok: false, reason: "rate-limited", status: 429, message: "Shippo asked us to slow down." };
  if (res.status === 404) return { ok: false, reason: "not-found", status: 404, message: "Shippo has no such record." };
  if (!res.ok) {
    const said = typeof out?.detail === "string" ? out.detail : `HTTP ${res.status}`;
    return { ok: false, reason: res.status === 401 || res.status === 403 ? "unauthorized" : "shippo", status: res.status, message: said };
  }
  return { ok: true, body: out };
}

// Shippo sends amounts and weights as decimal strings.
const amount = (value, currency) => (value == null || value === "" ? null : { currency: currency || "USD", value: Number(value) });

// A poll that changes nothing writes nothing: every field is compared with the stored record, and
// only a real change is put. The stored copy can come back with its object keys in another order,
// so keys are sorted before comparing.
function canonical(v) {
  if (Array.isArray(v)) return v.map(canonical);
  if (v && typeof v === "object") return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical(v[k])]));
  return v;
}
function unchanged(existing, next) {
  if (!existing) return false;
  return Object.keys(next).every((k) => JSON.stringify(canonical(existing[k])) === JSON.stringify(canonical(next[k])));
}
async function putIfChanged(ctx, next) {
  const existing = await ctx.db.get(next._id, { db: DB });
  if (unchanged(existing, next)) return false;
  await ctx.db.put(next, { db: DB, id: next._id });
  return true;
}

// One record per Shippo order, keyed by its object_id: a changed order replaces its own record.
function orderRecord(o) {
  const to = o.to_address ?? null;
  return {
    _id: `order-${o.object_id}`,
    type: "order",
    shippoId: o.object_id,
    orderNumber: o.order_number ?? null,
    placedAt: o.placed_at ?? null,
    status: o.order_status ?? "UNKNOWN",
    shopApp: o.shop_app ?? null,
    shipTo: to ? { name: to.name ?? null, city: to.city ?? null, state: to.state ?? null, country: to.country ?? null } : null,
    lines: (o.line_items ?? []).map((l) => ({ title: l.title ?? "", qty: l.quantity ?? 1, sku: l.sku ?? null, variant: l.variant_title ?? null })),
    total: amount(o.total_price, o.currency),
    labelIds: (o.transactions ?? []).map((t) => (typeof t === "string" ? t : t?.object_id)).filter(Boolean),
  };
}

function labelRecord(tx, orderId) {
  const parcel = typeof tx.parcel === "string" ? tx.parcel : tx.parcel?.object_id ?? null;
  return {
    _id: `label-${tx.object_id}`,
    type: "label",
    orderId,
    status: tx.status ?? null,
    trackingNumber: tx.tracking_number || null,
    trackingStatus: tx.tracking_status ?? null,
    parcelId: parcel,
    test: tx.test === true,
    createdAt: tx.object_created ?? null,
  };
}

// A parcel's sizes stay strings with their units, as Shippo sends them.
function boxRecord(p) {
  return {
    _id: `box-${p.object_id}`,
    type: "box",
    length: p.length ?? null,
    width: p.width ?? null,
    height: p.height ?? null,
    distanceUnit: p.distance_unit ?? null,
    weight: p.weight ?? null,
    massUnit: p.mass_unit ?? null,
    template: p.template ?? null,
  };
}

// A follow-up list: one record the poll reads by id, a few entries per poll, most overdue first.
// `read` answers { ok, again }: with `again` the entry stays, due again at that time; without it the
// entry is done. A failed read stops the rest and keeps its entry, so nothing is lost to a 429. With
// no `read` (the poll already stopped), the list is only saved, new entries included.
async function drain(ctx, id, list, read) {
  const now = Date.now();
  const kept = [];
  let reads = 0;
  let stopped = null;
  for (const entry of [...list].sort((a, b) => a.next - b.next)) {
    if (!read || stopped || reads >= READS_PER_POLL || entry.next > now) {
      kept.push(entry);
      continue;
    }
    reads += 1;
    const r = await read(entry);
    if (!r.ok) {
      stopped = r;
      kept.push(entry);
    } else if (r.again) {
      kept.push({ ...entry, next: r.again });
    }
  }
  // Past the cap, the entries due soonest stay and the ones furthest off drop.
  kept.sort((a, b) => a.next - b.next);
  await putIfChanged(ctx, { _id: id, type: "sync", list: kept.slice(0, LIST_MAX) });
  return stopped ?? { ok: true };
}

// Read one label and, the first time, its parcel. A label Shippo no longer has is saved as gone, so
// the sweep never queues it again; any other failure comes back to stop the list.
async function readLabel(ctx, entry) {
  const t = await shippo(ctx, `/transactions/${encodeURIComponent(entry.id)}`);
  if (!t.ok && t.reason !== "not-found") return t;
  const label = t.ok ? labelRecord(t.body ?? {}, entry.orderId) : { ...labelRecord({ object_id: entry.id }, entry.orderId), status: "GONE" };
  if (label.parcelId && !(await ctx.db.get(`box-${label.parcelId}`, { db: DB }))) {
    const p = await shippo(ctx, `/parcels/${encodeURIComponent(label.parcelId)}`);
    if (p.ok) await putIfChanged(ctx, boxRecord(p.body ?? {}));
    else if (p.reason !== "not-found") return p;
  }
  await putIfChanged(ctx, label);
  const waiting = label.status === "QUEUED" || label.status === "WAITING";
  return { ok: true, again: waiting && Date.now() < entry.until ? Date.now() + LABEL_EVERY_MS : 0 };
}

// The merchant's saved boxes, one record holding the whole list, so a box deleted in Shippo leaves.
async function readSavedBoxes(ctx) {
  const r = await shippo(ctx, "/user-parcel-templates");
  if (!r.ok) return r;
  const list = (r.body?.results ?? []).map((b) => ({
    id: b.object_id,
    name: b.name ?? b.template?.name ?? "Saved box",
    length: b.length ?? b.template?.length ?? null,
    width: b.width ?? b.template?.width ?? null,
    height: b.height ?? b.template?.height ?? null,
    distanceUnit: b.distance_unit ?? b.template?.distance_unit ?? null,
  }));
  await putIfChanged(ctx, { _id: BOXES_ID, type: "boxes", list });
  return { ok: true };
}

// What the last poll learned about the key, so /setup can answer without asking Shippo again.
async function recordOutcome(ctx, r) {
  const kept = await ctx.db.get(SETUP_ID, { db: DB });
  const verifiedOn = kept?.verifiedOn ?? (r.ok ? new Date().toISOString() : null);
  const refused = r.reason === "unauthorized" ? r.message ?? "Shippo refused the key." : null;
  const warning = r.ok || refused ? null : r.message ?? null;
  await putIfChanged(ctx, { _id: SETUP_ID, type: "setup", verifiedOn, refused, warning });
}

// Read up to four order pages from where the last poll stopped, then the saved boxes, the open
// orders that have aged out of the window, and a few labels not read yet. Every stop keeps its place.
async function sweep(ctx) {
  const sync = await ctx.db.get(SYNC_ID, { db: DB });
  const labels = new Map(((await ctx.db.get(LABELS_ID, { db: DB }))?.list ?? []).map((e) => [e.id, e]));
  const open = new Map(((await ctx.db.get(OPEN_ID, { db: DB }))?.list ?? []).map((e) => [e.id, e]));
  let saved = 0;

  // Save one order, queue its labels not read yet, and keep watching it while it is open: an order
  // can leave the window still unshipped, and then only a read by id sees it ship.
  const take = async (o) => {
    const record = orderRecord(o);
    if (await putIfChanged(ctx, record)) saved += 1;
    for (const id of record.labelIds) {
      if (labels.has(id) || (await ctx.db.get(`label-${id}`, { db: DB }))) continue;
      labels.set(id, { id, orderId: record._id, next: 0, until: Date.now() + LABEL_WAIT_MS });
    }
    const placed = Date.parse(record.placedAt ?? "") || Date.now();
    if (!OPEN.includes(record.status)) open.delete(record.shippoId);
    else if (!open.has(record.shippoId)) open.set(record.shippoId, { id: record.shippoId, next: placed + LOOK_BACK_MS, until: placed + OPEN_WATCH_MS });
    return record;
  };
  const readOpenOrder = async (entry) => {
    if (Date.now() > entry.until) return { ok: true };
    const r = await shippo(ctx, `/orders/${encodeURIComponent(entry.id)}`);
    if (!r.ok) return r.reason === "not-found" ? { ok: true } : r;
    const record = await take(r.body ?? {});
    return { ok: true, again: OPEN.includes(record.status) ? Date.now() + OPEN_EVERY_MS : 0 };
  };

  const start = encodeURIComponent(new Date(Date.now() - LOOK_BACK_MS).toISOString());
  let page = sync?.page ?? 1;
  let stopped = null;
  for (let n = 0; n < PAGES_PER_POLL; n += 1) {
    const r = await shippo(ctx, `/orders/?start_date=${start}&results=100&page=${page}`);
    if (!r.ok) {
      stopped = r;
      break;
    }
    for (const o of r.body?.results ?? []) await take(o);
    // The last page sends no `next`: the following poll starts again at page 1.
    page = r.body?.next ? page + 1 : 1;
    if (page === 1) break;
  }
  await putIfChanged(ctx, { _id: SYNC_ID, type: "sync", page });

  if (!stopped) {
    const boxes = await readSavedBoxes(ctx);
    if (!boxes.ok) stopped = boxes;
  }
  // Each list is saved by its own drain, read or not, so what this poll queued is never lost.
  const opened = await drain(ctx, OPEN_ID, [...open.values()], stopped ? null : readOpenOrder);
  if (!opened.ok) stopped = opened;
  const read = await drain(ctx, LABELS_ID, [...labels.values()], stopped ? null : (entry) => readLabel(ctx, entry));
  if (!read.ok) stopped = read;
  return stopped ? { ok: false, saved, reason: stopped.reason, message: stopped.message } : { ok: true, saved };
}

async function poll(ctx) {
  const r = await sweep(ctx);
  await recordOutcome(ctx, r);
  return r;
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  try {
    // The setup verdict. The item (and the handle + slug the Setup screen links with) is the
    // owner's alone; a visitor learns only whether the app is ready.
    if (url.pathname === "/setup" && request.method === "GET") {
      const owner = ctx.userInfo?.userHandle === ctx.appInfo.ownerHandle;
      const key = ctx.secrets.SHIPPO_API_KEY;
      let kept = await ctx.db.get(SETUP_ID, { db: DB });
      // Shippo is asked only until the key has worked, or again after it was refused; after that
      // the scheduled polls keep the verdict current and coming back to the tab costs no reads.
      if (owner && key && (!kept?.verifiedOn || kept.refused)) {
        await poll(ctx);
        kept = await ctx.db.get(SETUP_ID, { db: DB });
      }
      const done = Boolean(key) && Boolean(kept?.verifiedOn) && !kept?.refused;
      const problem = !key ? null : kept?.refused ?? (done ? null : kept?.warning ?? null);
      const items = [{ id: "shippo-key", label: "Your Shippo API key", done, problem }];
      const ready = items.every((item) => item.done);
      if (!owner) return json({ ok: true, ready, owner });
      return json({
        ok: true,
        ready,
        owner,
        items,
        reason: key ? null : "missing-key",
        mode: key?.startsWith("shippo_test_") ? "test" : "live",
        warning: done ? kept?.warning ?? null : null,
        ownerHandle: ctx.appInfo.ownerHandle,
        appSlug: ctx.appInfo.appSlug,
      });
    }

    // The owner's Refresh: poll now instead of waiting for the next tick.
    if (url.pathname === "/refresh" && request.method === "POST") {
      if (ctx.userInfo?.userHandle !== ctx.appInfo.ownerHandle) return json({ ok: false, reason: "owner-only" }, 403);
      return json(await poll(ctx));
    }

    return json({ ok: false, reason: "not-found" }, 404);
  } catch (err) {
    ctx.log("error", "shippo route failed", { path: url.pathname, message: String(err?.message ?? err) });
    return json({ ok: false, reason: "handler-failed", message: "Something went wrong reaching Shippo." }, 500);
  }
}

// The poll: new orders and labels reach the app within 15 minutes of Shippo having them.
export async function scheduled(event, ctx) {
  if (!ctx.secrets.SHIPPO_API_KEY) return;
  try {
    const r = await poll(ctx);
    ctx.log(r.ok ? "info" : "warn", "shippo poll", { saved: r.saved, reason: r.reason ?? null, at: event.scheduledTime });
  } catch (err) {
    // A throw (the network, the database) still leaves a line saying which tick failed and why.
    ctx.log("error", "shippo poll failed", { message: String(err?.message ?? err), at: event.scheduledTime });
  }
}

access.js — only the backend writes, and only the owner reads

access.js

jsexport function station(doc, oldDoc, user, ctx) {
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
  if (!["order", "label", "box", "boxes", "sync", "setup"].includes(doc.type)) throw { forbidden: "unknown document type" };
  // Every record is a copy of the owner's Shippo account, written by backend.js: the poll, /setup or /refresh.
  ctx.requireBackend();
  // Orders carry buyers' names and addresses, so they reach the owner alone.
  return { channels: ["station"], grant: { roles: { owner: ["station"] } } };
}

App.jsx sketch

App.jsx

jsximport React, { useEffect, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch } from "use-vibes";
import { Badge, Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";

const money = (m) => new Intl.NumberFormat(undefined, { style: "currency", currency: m.currency }).format(m.value);
const size = (b) => (b.length && b.width && b.height ? `${b.length} × ${b.width} × ${b.height} ${b.distanceUnit ?? ""}`.trim() : null);

// The setup verdict, read on mount and again whenever the app comes back into view: the owner saves
// the key in another tab and returns, and the orders appear without a reload.
function useSetup() {
  const [setup, setSetup] = useState(null); // { ready, owner, items?, mode?, warning?, ownerHandle?, appSlug? }
  const latest = useRef(0);
  useEffect(() => {
    const load = () => {
      const n = ++latest.current;
      apiFetch("/setup").then((r) => r.json()).catch(() => ({ ready: false, owner: false })).then((s) => { if (n === latest.current) setSetup(s); });
    };
    load();
    const onVisible = () => { if (document.visibilityState === "visible") load(); };
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", load);
    return () => { document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("focus", load); };
  }, []);
  return setup;
}

// The item's steps: each a link to the exact page, in Shippo's own words, with this vibe's real
// handle and slug filled in.
function setupSteps(vibe) {
  return [
    { href: "https://portal.goshippo.com/api-config/api", link: "Shippo's API Configuration", text: ": sign in, select Developer keys, and choose Live keys (or Test keys to try it on test data first)." },
    { href: "https://portal.goshippo.com/api-config/api", link: "Developer keys", text: ": copy the key. A live key begins shippo_live_, a test key shippo_test_." },
    { href: `https://vibes.diy/vibes/mine/${vibe}/settings`, link: "this vibe's Settings tab", text: `: under Secrets, enter SHIPPO_API_KEY, paste the key, and save. Or run npx vibes-diy secrets set SHIPPO_API_KEY --vibe ${vibe}.` },
  ];
}

// The Setup surface, the owner's alone.
function SetupScreen({ setup }) {
  const item = setup.items.find((i) => i.id === "shippo-key");
  return (
    <Stack>
      <Heading>Setup</Heading>
      <Row gap={2}>
        <Text>{item.label}</Text>
        <Badge tone={item.done ? "up" : "info"}>{item.done ? "Done" : "To do"}</Badge>
      </Row>
      {item.problem && <Text>Shippo said: {item.problem}</Text>}
      <ol>
        {setupSteps(`${setup.ownerHandle}/${setup.appSlug}`).map((step) => (
          <li key={step.link}>
            Open <a href={step.href} target="_blank" rel="noreferrer">{step.link}</a>
            {step.text}
          </li>
        ))}
      </ol>
      <Text muted>The key stays on the server and reads your shipping; you buy and refund labels in Shippo as you do now.</Text>
    </Stack>
  );
}

function OrderCard({ order, labels, boxes }) {
  return (
    <Stack>
      <Row gap={2}>
        <Text>{order.orderNumber ?? "Order"}{order.total ? ` · ${money(order.total)}` : ""}</Text>
        {order.shopApp && <Badge tone="info">{order.shopApp}</Badge>}
      </Row>
      <Text>{order.lines.map((l) => `${l.qty} × ${l.title}${l.variant ? ` (${l.variant})` : ""}`).join(", ")}</Text>
      {order.shipTo && <Text muted>To {order.shipTo.name}, {order.shipTo.city}</Text>}
      {labels.map((l) => {
        const box = l.parcelId ? boxes[`box-${l.parcelId}`] : null;
        const shown = box ? box.template ?? size(box) : null;
        return (
          <Text key={l._id} muted>
            Label {l.trackingNumber ?? l.status}{l.test ? " (test)" : ""}: {shown ? `went out in ${shown}` : "box not recorded"}
          </Text>
        );
      })}
    </Stack>
  );
}

export default function App() {
  const { useLiveQuery } = useFireproof("station");
  const { docs: orders } = useLiveQuery("type", { key: "order" });
  const { docs: labels } = useLiveQuery("type", { key: "label" });
  const { docs: boxDocs } = useLiveQuery("type", { key: "box" });
  const { docs: saved } = useLiveQuery("type", { key: "boxes" });
  const setup = useSetup();
  const [picked, setPicked] = useState(null);
  const [note, setNote] = useState(null);
  const boxes = Object.fromEntries(boxDocs.map((b) => [b._id, b]));
  const labelsFor = (o) => labels.filter((l) => l.orderId === o._id);
  const newest = (a, b) => ((a.placedAt ?? "") < (b.placedAt ?? "") ? 1 : -1);
  const toPack = orders.filter((o) => o.status === "PAID" || o.status === "PARTIALLY_FULFILLED").sort(newest);
  const shipped = orders.filter((o) => o.status === "SHIPPED").sort(newest).slice(0, 20);
  const refresh = async () => {
    const r = await apiFetch("/refresh", { method: "POST" }).then((res) => res.json()).catch(() => ({ ok: false }));
    setNote(r.ok ? `${r.saved} orders updated from Shippo.` : r.message ?? "Shippo did not answer; the next poll tries again.");
  };

  const ready = setup?.ready === true;
  const screen = picked ?? (setup?.owner && !ready ? "setup" : "orders");
  return (
    <Stack>
      <Row gap={2}>
        <Button variant="quiet" onClick={() => setPicked("orders")}>To pack</Button>
        {setup?.owner && (
          <Button variant={ready ? "quiet" : "solid"} onClick={() => setPicked("setup")}>
            Setup{ready ? "" : " · to do"}
          </Button>
        )}
        {setup?.mode === "test" && <Badge tone="info">Test mode</Badge>}
      </Row>
      {screen === "setup" && setup?.owner ? (
        <SetupScreen setup={setup} />
      ) : !setup?.owner ? (
        <Text muted>{setup ? "This packing station is its owner's. Make your own from the remix button." : "Opening your station…"}</Text>
      ) : !ready ? (
        <Text muted>The packing station is not open yet: finish Setup to read your Shippo orders.</Text>
      ) : (
        <Stack>
          <Row gap={2}>
            <Heading>To pack · {toPack.length}</Heading>
            <Button variant="quiet" onClick={refresh}>Refresh</Button>
          </Row>
          {setup.warning && <Text muted>Shippo said: {setup.warning} The orders below are from the last poll.</Text>}
          {note && <Text muted>{note}</Text>}
          {toPack.length === 0 ? (
            <Text muted>All packed. New orders land here within 15 minutes of reaching Shippo.</Text>
          ) : (
            toPack.map((o) => <OrderCard key={o._id} order={o} labels={labelsFor(o)} boxes={boxes} />)
          )}
          <Heading>Shipped</Heading>
          {shipped.map((o) => <OrderCard key={o._id} order={o} labels={labelsFor(o)} boxes={boxes} />)}
          <Heading>Your saved boxes</Heading>
          {(saved[0]?.list ?? []).map((b) => (
            <Text key={b.id}>{b.name}{size(b) ? ` · ${size(b)}` : ""}</Text>
          ))}
        </Stack>
      )}
    </Stack>
  );
}