# Build-a-Kit feature — design

The net-new beachhead for the site-ng (Flask) migration: let a visitor
assemble a kit of AR-15/AR-10 parts, share it at a short URL, collect
upvotes, and — the killer hook — get **restock alerts** when an
out-of-stock part in their build comes back. Aligns with the site's
raison d'être: detecting restocks in minutes.
(See memory: `feature-site-share-builds`, `site-migration-perl-to-flask`,
`site-ng-decisions`.)

## Deferred from v1a — explicit follow-up list

Captured here so they don't drop off the radar:

- **"Notify me when this restocks"** on every OOS item in a build. The
  killer hook tying the kit-builder back to the site's restock-latency
  raison d'être. Blocked on build persistence + email transport (v2a).
- **"Exclude OOS from total" toggle** on the build summary so the
  user can see the cost of *what's actually buyable right now*. Cheap
  to implement once we add a build-page settings UI; held until
  there's at least one other setting to share that affordance with.
- **Price-history chart** below the build summary — sparkline of the
  build's value over time + per-line mini-charts. Designed; deferred
  until `price_history` has accumulated ~30+ days of data (currently
  ~1 day on prod). One-step deltas via `last_price` ship in v1a.
- **Chart backfill — option D evaluation.** v1a ships "option A" for
  the build-value chart: when an item joins the data later than the
  chart's earliest date, its first-known price is backfilled flat to
  all prior dates. Keeps the line continuous, avoids a jarring
  vertical cliff each time a new item enters the build. The honest-er
  alternative ("option D") is to render the backfilled portion of the
  line in a **dashed or lighter style** so it's visually distinct
  from real-data segments — preserves continuity but discloses which
  span is estimated. Worth evaluating once we have user feedback on
  whether anyone misreads the backfilled segment as real data. Code
  hint: per-item backfill state is already in
  `_build_value_series` (`item_obs[*]["first_price"]`); the chart-side
  change is splitting the dataset into two series (solid for
  per-date-real-data, dashed for backfilled) keyed by whether `d <
  obs[0][0]` for any contributing item on that date.
- **Restock-alert email subscription** on a shared build (see v2a
  below). Same email-transport blocker.

## Goals / non-goals

**Goals (v1):**
- Add/remove parts to a working build from the browse grid (htmx, no reload).
- A build view: parts grouped by type, running price total, live in-stock status.
- Share → mint a short URL; public build page is server-rendered (crawlable — SEO is the commission channel).
- Upvotes on public builds.
- Buy links route through the existing prod `jump.cgi?site=<parts.id>` (affiliate + click logging — per `site-ng-decisions`).

**Goals (v2):**
- Restock email alerts on a build (double opt-in).
- Popular-builds gallery (engagement + SEO surface).
- "Fork this build" (copy a shared build into your own working set).

**Non-goals:**
- No passwords. No OAuth / social login in v1 (deferred — see "Identity
  model" below; the `app_user` table is designed to accept additional
  auth providers later without rework).
- No Disqus / comments in v1.

> **v2 design update (2026-05-25):** The "anonymous secret-edit-token
> cookie" identity model from the 2026-05-22 spec is REPLACED with an
> email-based magic-link model. Drafts (working copies) stay session-
> scoped; saving a build can optionally associate it with an email →
> magic-link auth → `/my-builds` recoverable from any browser. See
> the "Identity model" section below for the locked design.
- No payments — we never transact; we hand off to the retailer via jump.cgi.

## Identity model — drafts (session) + saved builds (URL or email-owned)

**Three-layer identity, locked 2026-05-25:**

### Layer 1 — Drafts (working copies)

The working build lives in the **Flask session cookie**: up to 3 drafts
(`max_drafts=3`), each holding `{slot, name, items: {parts_id: qty}}`.
Already shipped (v1a). Drafts are ephemeral — lost when the user
clears cookies or the session expires. They're "scratch space."

The header chip dropdown lets the user switch between drafts (1-3 slot
buttons + "+ New draft" + currently-active marker). The +Add button on
every card reads `+ Add to {{ build.name|truncate(15, True, '…') }}` so
the active draft's name is always visible at the click point.

### Layer 2 — Anonymous saved builds (URL-as-token)

When the user clicks **"Save as build"** on a draft, the draft items
snapshot into a `build` row + `build_item` rows in the DB. The build
gets a short `code` (base62, 8 chars) → share URL `/b/<code>`.

**The URL itself IS the access token** for anonymous saves. Anyone
with the URL can view; nothing in the URL identifies the creator. If
the creator never associates an email, the build is *uneditable* —
view-only forever (or until the URL is shared with someone who forks
it). This is fine for "share this build with my buddy" use cases
where ownership doesn't matter.

### Layer 3 — Owned saved builds (email + magic-link)

If the user provides an email — either at save-time OR by subscribing
to restock alerts later — the build becomes associated with their
`app_user` row (the email is the identity). They can manage all owned
builds via `/my-builds` from any browser by triggering a magic-link.

**Magic-link mechanics:**
- A row in `magic_link (id, user_id, token CHAR(32), created,
  expires_at, consumed_at)` holds each link's state.
- `expires_at` = ~30 min from creation. `consumed_at` = NULL until the
  link is clicked; click sets it (single-use; replay-proof).
- Requesting a new link for the same user invalidates any existing
  unconsumed links (prevents stale-link-as-backdoor if the user later
  thinks they didn't get the email and requests another).
- Click → session cookie set tying browser → user_id, long-lived
  (~30-90 days). User stays logged in on that browser until cookie
  expires or is cleared. Fresh magic link required only when
  re-establishing a session on a new browser / after a cookie clear.

**No password, no OAuth (yet):**
- Magic-link covers 100% of users (everyone has email).
- Social login (Google / Apple) is **deferred** — additive later if real
  user demand emerges. The `app_user` table is structured to accept a
  separate `(provider, provider_user_id)` row when that day comes,
  without changing the rest of the schema. Cost-benefit at this scale
  doesn't justify the maintenance overhead (per-provider OAuth app
  registration + library upgrades + verification flows + ~5-10
  hrs/year keeping up with provider API changes).
- Friction comparison: magic-link ~30-60s round trip (email + click),
  Google ~3-5s click-through. For this site's low-frequency use case
  (user saves a build, returns weekly-ish to check restocks), the
  speed gap doesn't justify the dependency / complexity. Email is
  already required for restock alerts anyway.

### Promotion flows

```
Drafts (session)
    │
    │  "Save as build" — persists snapshot
    ▼
Anonymous saved build (URL-only access)
    │
    │  Provide email (at save OR via alert subscribe)
    ▼
Owned saved build  ←→  /my-builds  (magic-link auth)
```

The same /build page renders all three states; conditional sections
appear as the build "grows up": draft → anonymous save → owned. A
saved build adds Share-link, "Subscribe to restock alerts", "Update
saved build" / "Save as new build", and (future) Compare-with-other-
build affordances. A draft is minimal.

### Forking

Any visitor to a `/b/<code>` URL can click "Open in draft" → the saved
build's snapshot copies into one of THEIR draft slots (consumes a slot,
creates one if they have < 3). They edit and can save-as-new — a fork
chain doesn't link parent/child in v1 (could revisit). The fork
preserves snapshot fields (description / company / price-at-add) and
fresh-reads parts_id refs for live data.

## Data model (InnoDB)

All build tables are **InnoDB** — row-level locking, FKs, transactions.
(NOTE 2026-06: `parts` is **InnoDB** now too — the whole prod DB was converted
from MyISAM, see memory `myisam-to-innodb-conversion-future` — so the original
"avoid MyISAM's table-lock cascade" rationale is moot.) `parts_id` stays a
**soft reference** (no FK): the conversion was an engine flip only and added no
foreign keys, and the soft reference keeps build data decoupled from scanner
churn on `parts` (see deletion handling below).

```sql
-- v2 (2026-05-25): app_user added; edit_token replaced with
-- owner_user_id (NULL = anonymous URL-only access).
CREATE TABLE app_user (
  id          INT UNSIGNED NOT NULL AUTO_INCREMENT,
  email       VARCHAR(255) NOT NULL,           -- identity (lowercased on insert)
  created     DATETIME     NOT NULL,
  last_login  DATETIME     DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE magic_link (
  id           INT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id      INT UNSIGNED NOT NULL,
  token        CHAR(32)     NOT NULL,           -- single-use secret in the email URL
  created      DATETIME     NOT NULL,
  expires_at   DATETIME     NOT NULL,           -- ~30 min after creation
  consumed_at  DATETIME     DEFAULT NULL,       -- NULL = unused; set on click
  PRIMARY KEY (id),
  UNIQUE KEY uq_token (token),
  KEY idx_user (user_id),
  CONSTRAINT fk_link_user FOREIGN KEY (user_id) REFERENCES app_user(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE build (
  id            INT UNSIGNED NOT NULL AUTO_INCREMENT,
  code          CHAR(8)      NOT NULL,            -- public short-url slug (base62)
  owner_user_id INT UNSIGNED DEFAULT NULL,        -- NULL = anonymous (URL-only access)
  title         VARCHAR(120) DEFAULT NULL,
  notes         VARCHAR(1000) DEFAULT NULL,
  votes         INT UNSIGNED NOT NULL DEFAULT 0,  -- denormalized cache of build_vote
  status        ENUM('draft','public') NOT NULL DEFAULT 'public',
  created       DATETIME     NOT NULL,
  updated       DATETIME     NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_code (code),
  KEY idx_owner (owner_user_id),
  CONSTRAINT fk_build_owner FOREIGN KEY (owner_user_id) REFERENCES app_user(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE build_item (
  id           INT UNSIGNED NOT NULL AUTO_INCREMENT,
  build_id     INT UNSIGNED NOT NULL,
  parts_id     INT UNSIGNED DEFAULT NULL,       -- live ref; NULL if part later purged
  -- snapshot fields: survive parts deletion + price change, keep the build legible
  type         VARCHAR(20)  NOT NULL,
  company      VARCHAR(120) NOT NULL,
  description  VARCHAR(255) NOT NULL,
  url          VARCHAR(500) NOT NULL,           -- fallback link if parts row is gone
  img          VARCHAR(500) DEFAULT NULL,
  price_at_add DECIMAL(10,2) DEFAULT NULL,
  position     SMALLINT     NOT NULL DEFAULT 0,
  added        DATETIME     NOT NULL,
  PRIMARY KEY (id),
  KEY idx_build (build_id),
  KEY idx_parts (parts_id),
  CONSTRAINT fk_item_build FOREIGN KEY (build_id) REFERENCES build(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE build_vote (
  build_id   INT UNSIGNED NOT NULL,
  voter_hash CHAR(64)     NOT NULL,             -- sha256(cookie-token | ip+daysalt)
  created    DATETIME     NOT NULL,
  PRIMARY KEY (build_id, voter_hash),           -- one vote per voter per build
  CONSTRAINT fk_vote_build FOREIGN KEY (build_id) REFERENCES build(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- v2 (2026-05-25): user_id replaces (email, verify_token) — the
-- app_user row already represents a verified email; the magic-link
-- session proves the user is who they claim before they can
-- subscribe.
CREATE TABLE build_alert (
  id            INT UNSIGNED NOT NULL AUTO_INCREMENT,
  build_id      INT UNSIGNED NOT NULL,
  user_id       INT UNSIGNED NOT NULL,
  created       DATETIME     NOT NULL,
  last_notified DATETIME     DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_build_user (build_id, user_id),
  KEY idx_build (build_id),
  KEY idx_user (user_id),
  CONSTRAINT fk_alert_build FOREIGN KEY (build_id) REFERENCES build(id) ON DELETE CASCADE,
  CONSTRAINT fk_alert_user FOREIGN KEY (user_id) REFERENCES app_user(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

**Why snapshot AND `parts_id`?** `parts_id` powers the live view (current
price, current in-stock status, the `jump.cgi` affiliate link, restock
detection). The snapshot columns keep a shared build legible and linkable
even after the part is purged by housekeeping (see memory:
`parts-deletion-fanout`, `housecleaning-stale-oos-task`). When `parts_id`'s
row is gone we render the snapshot, grey it out as "no longer tracked,"
and fall back to the stored `url` (unwrapped) for the link.

**DDL note:** `easyperl_5_w` has DML but **no DDL** (see memory:
`db-user-privileges`) — these `CREATE TABLE`s must be run via phpMyAdmin
(Mike). The dev mirror (`arpartsfinder_dev`) can take them directly.

## DB write access

site-ng currently reads as the read-only user. Build writes need a
write-capable connection. Plan: a dedicated **per-request write connection**
used only by the build mutation routes (reads keep using the read user).
Simplest path = reuse `easyperl_5_w` (the scanner/jump.cgi writer, full
DML). Revisit a least-privilege dedicated user later.

## Routes

| Method | Path | Purpose |
|---|---|---|
| POST | `/build/add` | Add `parts_id` to the session working build (htmx) → returns the header build-chip fragment (count + total) |
| POST | `/build/remove` | Remove an item from the working build (htmx) |
| GET  | `/build` | View the working build: grouped by type, total, in-stock status, remove buttons, "Share" button |
| POST | `/build/share` | Persist working build → `build` + `build_item` rows, mint `code` + `edit_token`, set edit cookie, redirect to `/b/<code>` |
| GET  | `/b/<code>` | **Public** build page (crawlable). Parts, total, in-stock %, vote button, buy links via jump.cgi, "fork"/"subscribe" CTAs |
| POST | `/b/<code>/vote` | Upvote (htmx, dedupe by `voter_hash`) → returns updated count |
| POST | `/b/<code>/alert` | (v2) Subscribe an email to restock alerts (double opt-in) |
| GET  | `/b/<code>/edit` | Edit a build you own (edit-token cookie); loads it back into the working session |
| GET  | `/builds` | (v2) Popular/recent builds gallery |

The product card in `partials/parts_grid.html` gains an **"+ Add"** button
(`hx-post="/build/add"`, `hx-vals` carrying `parts_id`). A persistent
header chip ("Build: 4 parts · $612") is the htmx swap target so feedback
is instant. The "+ Add" button lives in both the card and table views of
the browse page (see `browse-design.md`).

## Restock alerts (v2 — the killer feature)

The scanner already maintains `parts.instock` with a 30-min restock window
that **resets `parts.added`** when an item goes OOS→in-stock (see memory:
`scraper-health`, REWRITE_NOTES `allowed_oos_window_seconds`). We exploit
that: a lightweight checker — run as a hook at the end of each scan cycle,
or a standalone cron — does, per verified alert:

```
SELECT bi.description, bi.parts_id
FROM build_alert a
JOIN build_item bi ON bi.build_id = a.build_id
JOIN parts p       ON p.id = bi.parts_id
WHERE a.verified = 1
  AND p.instock = 1
  AND p.added > COALESCE(a.last_notified, a.created);
```

i.e. "a part in this build is in stock and (re)appeared since we last told
you." Email the user, set `last_notified = now()`. Double opt-in via
`verify_token` keeps it from being an abuse vector. Email transport on
pair.com is the one new infra dependency — phase it after the v1 share
flow proves out.

## Build phases

1. **v1a — working build + share:** session working build, add/remove
   (htmx), `/build` view with total + live in-stock, `/build/share`
   persist + short code, public `/b/<code>` with jump.cgi buy links.
   (Tables: `build`, `build_item`.)
2. **v1b — votes:** upvote with dedupe; show vote counts. (`build_vote`.)
3. **v2a — restock alerts:** `build_alert` + double opt-in + the
   post-scan checker + email transport.
4. **v2b — gallery + fork:** `/builds` popular list, "fork this build."

## Open questions for Mike

1. **Build composition** — one part per type (a true single-rifle config,
   enables "is this build complete?" guidance), or freeform multi (a
   wishlist that can hold 3 barrels)? Affects the `/build` UX and whether
   we de-dupe by type. *Recommendation: freeform v1, add an optional
   "single-rifle" mode later.*
2. **Email transport** for restock alerts — pair.com sendmail/SMTP, or a
   transactional provider? Drives the v2 timeline.
3. **Short-code length/scheme** — random base62×8 (~2.8e14 space, no
   enumeration) vs hashids of the id. *Recommendation: random base62.*
4. **Vote dedupe basis** — cookie token (easy to evade) vs IP-day hash
   (blunt on shared NAT) vs both. *Recommendation: cookie token primary,
   IP-day as a soft secondary cap; this isn't high-stakes.*
```
