# Krafthub Checkout v2 — React / TypeScript

This is the React/TypeScript source for the Checkout v2 preview. The UI is rendered by React components with typed state, actions and order payloads. There is no legacy HTML-string renderer or embedded vanilla JavaScript application.

## Run locally

Use Node.js 20.19+ (or a supported newer LTS release) and npm.

```sh
npm ci
npm run dev
```

```sh
npm run typecheck
npm test
npm run build
npm run preview
```

`npm run build` creates `dist/`. Vite uses relative asset URLs, so the output can be hosted under `/checkout-v2/` in the preview library. `index.html` is only the standard React app entry point; the interface is authored in `.tsx` components. The lockfile pins the build dependencies.

## Files

- `src/CheckoutDrawer.tsx`: reusable controlled drawer, checkout navigation, draft selection, native dialog and scroll/focus handling.
- `src/components/`: basket, colour/needle picker, store/delivery, contact details, review, order summary and product photos.
- `src/model.ts`: exported TypeScript models, immutable reducer, totals and order payload.
- `src/fixtures.ts`: isolated illustrative catalogue, stores and initial cart for the preview.
- `src/CheckoutV2Preview.tsx`: product page and example drawer integration.
- `src/styles.css` and `src/assets/`: existing responsive design, fonts, real supplied pattern image and material imagery.
- `src/model.test.ts`: fulfillment, totals, quantity bounds, immutability and integration-payload tests.

## Integrate into your React / Node.js application

Copy `src/` into your frontend and import the component and stylesheet. Use your existing React setup and Node.js backend; no separate backend is introduced by this package.

```tsx
import { CheckoutDrawer } from './checkout-v2';
import type { CheckoutOrder } from './checkout-v2';
import './checkout-v2/styles.css';

// In your existing product page:
<CheckoutDrawer
  open={basketOpen}
  onClose={() => setBasketOpen(false)}
  product={product}
  initialState={initialCart}
  colours={catalogueColours}
  needleOptions={catalogueNeedles}
  stores={availableStores}
  currency="NOK"
  locale="en-NO"
  shippingPrice={69}
  onConfirmOrder={async (order: CheckoutOrder) => {
    // Call your existing authenticated checkout/payment service here.
    // Resolve only when that flow is confirmed successful; throw on failure.
    await checkoutService.confirmPurchase(order);
  }}
/>
```

`open` is controlled by the product page. `initialState` is read once on mount; regular quantity and selection changes are managed by the reducer. Catalogue props can be supplied from your existing API. Each material ID must be unique, colour/type indices must refer to the supplied catalogue arrays, and a physical cart must have at least one available store. The fixture’s main-yarn size quantities are illustrative; adapt them to the actual pattern’s material requirements.

The preview uses a single right-hand dialog at 50% desktop width and 100% mobile width below 768px. Keep your product page in a `.product-stage` wrapper to use the included split layout, or adapt that wrapper to your existing page. The supplied `CheckoutV2Preview` shows the integration.

Colour and needle selection are React views inside the same dialog. Changes are drafts until Add/Save. Cancel and Escape discard the draft. The basket DOM and scroll container remain mounted; updates preserve scroll position and focus. Moving between checkout stages deliberately starts at the top of the new stage.

All displayed prices use the explicit currency code, defaulting to NOK. `locale` controls number formatting and `currency` controls the code; changing either does not perform exchange-rate conversion.

## Backend boundaries

Without `onConfirmOrder`, the final button only completes an **example order**. The preview does not create accounts, orders, payments, emails or library entries. In production, use your existing signed-in Krafthub profile. Purchased interactive patterns belong in **Profile → Purchases**; email is for order confirmation. Yarn and needles must be collected in store or shipped.

Treat client prices, totals, availability and store distances as display data. Your Node.js backend must validate catalogue IDs, stock, prices, delivery eligibility, authentication and payment status. Supply stores available for the selected materials, ordered by actual distance from the customer’s chosen location. The example distances do not request geolocation. Grant pattern access only after successful payment.

## Verification

Verified: TypeScript strict checking, a clean production build, model tests, 1440px desktop split geometry, 390 × 844 mobile geometry, pattern-only completion, required fields, draft cancellation and Save, needle specification changes, store selection, shipping address and totals, contact data retention, and basket scroll retention on quantity changes and removal. The preview remains separate from the production store and its payment services.

Pattern labels read “Interactive pattern” and use the existing Craftmode purple (#7b2ff2), with white text on the purple badge.


## Lean needle selection

The pattern supplies each needle material's `requirement` (toolType, size in mm, assembled total length in cm, optional required material). One entry per tool is supported without purpose labels or notes. The basket uses these specifications before a product is chosen. The picker shows a compact specification line, an optional Change control for gauge/length adjustments, Supplier and dependent Brand selects, and matching product rows. A real matching product must be selected before Add/Save; Cancel discards changes. No checkout stage is added.

`NeedleOption` now represents an exact catalogue variant, with stable `id`, `supplierId`, `brandId`, tool specifications, price, construction and `storeIds`. The cart/order retains the selected `productId`, supplier and brand IDs as well as the original pattern requirement. `type` remains the catalogue array index for image/display compatibility. Keep the catalogue stable while a cart is mounted. Wire these records to the existing Node.js catalogue API; illustrative fixtures are not actual ChiaoGoo offers, prices or stock.

Supplier is the upstream catalogue supplier, distinct from the fulfilling retail store. Delivery lists the intersection of stores carrying all included needle products; selection carries forward a valid store, and checkout blocks an unavailable combination. Yarn and needle availability are checked against each store’s offers. Revalidate all SKUs, stock, prices, tip/cable compatibility and store eligibility on the backend. Total length is assembled length, not cable length. The current photo fixtures are fixed circular needles.

Product selection now includes compact real product-family thumbnails from ChiaoGoo, also used in basket rows. See `src/assets/PRODUCT-PHOTOS.md` for provenance and variant-photo guidance. All checkout cards, product options, form fields and image containers use shared 14px/10px corner radii; the drawer itself retains square corners on desktop and mobile. Brand filtering supports multiple brands from the API; the photographed demo catalogue currently contains ChiaoGoo.

Delivery copy: collection says “Ready to collect”; standard delivery says “1–3 working days”.


## Indicative and store-specific prices

Catalogue `material.price` and `NeedleOption.price` are estimates. `initialState.shop` is empty; never silently choose a store. Add the available stores’ `offers` records keyed by the stable product-variant ID (`productId`), with `{ price, stock }`, plus each store’s `shippingPrice`. Supply each yarn colour’s stable SKU on `ColourOption.productId`; selecting a colour copies that SKU into the yarn material. Legacy yarn fixtures without IDs use `merino:<colour-index>` as a fallback only.

`getStoreQuote` prices the complete basket, checks every included SKU, and aggregates quantities for duplicate SKUs before checking stock. `getPricing` supplies the representative estimate or chosen store’s complete quote without mutating catalogue estimates. Before selection the UI says Est. / Estimated subtotal and the action says Choose store. Store choices show complete order totals, including the fixed pattern price and the chosen collection/shipping method. Selecting a store updates all prices together; returning to the basket retains those prices. Missing or insufficient offers clear a stale selection and require choosing a store again. A physical order cannot be created without a valid selected-store quote.

The sample offers are illustrative, not live retail prices or reserved stock. Fetch authoritative offers from your Node.js service. Before payment, revalidate or reserve the complete quote on the backend, including currency, taxes, shipping and stock; show any changed price to the customer before confirming. `onConfirmOrder` receives repriced line items and totals, but client payloads are not authoritative. No new payment service is introduced.
