# CLAUDE.md — Second Amendment Cycles (2AC)

> **What this file is:** the working spec for any developer or AI coding assistant working on the 2AC codebase. Drop it into Cursor, Claude Code, Lovable, or hand it to a new engineer. They should be productive in 30 minutes.
>
> **What it isn't:** product copy, sales material, or aspirational architecture. Everything below is what the system *actually* does.
>
> **Modern Phase published this as a sample with the client's permission.** Use it as a reference for what your own CLAUDE.md will look like.

---

## Project

**Second Amendment Cycles (2AC)** — Harley-Davidson parts and accessories e-commerce. Customers pick their bike (year/make/model), then see only parts that fit. Catalog of 40,000+ SKUs aggregated from major distributor feeds.

**Business model:** direct-to-consumer parts retail. Margin on dealer-cost markup. No marketplace fees.

**Non-negotiable invariant:** the customer sees a part **only if** it has confirmed fitment for their selected bike-year, OR is flagged `universal_fit = true`. Wrong-part purchases are the metric we minimize.

---

## Stack

| Layer | Choice | Why |
|---|---|---|
| Frontend | Next.js 14 (App Router) + React + TailwindCSS | SSR for SEO, RSC for catalog reads |
| Backend | Next.js API routes + Server Actions | No separate backend service |
| Database | Neon Postgres (serverless) | Auto-scaling, native pooling, branchable |
| ORM | Prisma | Type-safe, generates migrations |
| Payments | Stripe Checkout (hosted) | PCI-compliant, no card data on our servers |
| Auth | NextAuth (email magic-links, admin only) | No customer auth required for guest checkout |
| Email | Resend + React Email templates | Transactional only (order, shipping, review) |
| Image hosting | Vercel Blob | Catalog images from supplier feeds |
| Analytics | GA4 + Microsoft Clarity | Both free, both wired in `app/layout.tsx` |
| Error monitoring | Sentry (free tier) | Server + client error capture |
| Deploy | Vercel (auto-deploy from `main`) | Preview deploys on PRs |
| Cron | Vercel Cron | Supplier feed sync, daily reports |

---

## Commands

```bash
npm run dev               # Vite dev server on :3000
npm run build             # Production build
npm run start             # Production server (after build)
npx prisma migrate dev    # Apply DB migrations to dev
npx prisma migrate deploy # Apply migrations to prod
npx prisma studio         # GUI for DB inspection
npm run import:catalog    # CSV import job (33K rows)
npm run import:fitment    # Fitment data pipeline
npm run test              # Playwright E2E + Vitest unit
npm run test:e2e          # Playwright only
```

Node 20.x required. Bun 1.x supported for scripts.

---

## File Structure

```
2ac/
├── app/                          # Next.js App Router
│   ├── (storefront)/
│   │   ├── page.tsx              # Home / pick-your-bike
│   │   ├── shop/
│   │   │   └── [...slug]/        # Filtered catalog (category/brand/etc)
│   │   ├── product/
│   │   │   └── [sku]/            # Product detail page (PDP)
│   │   ├── cart/page.tsx
│   │   └── checkout/             # Hands off to Stripe Checkout
│   ├── (admin)/
│   │   ├── orders/
│   │   ├── catalog/
│   │   ├── fitment/
│   │   └── suppliers/
│   ├── api/
│   │   ├── stripe/webhook/       # Stripe webhook handler
│   │   └── cart/
│   └── layout.tsx                # GA4 + Clarity wired here
├── lib/
│   ├── db.ts                     # Prisma client singleton
│   ├── fitment/                  # Pick-your-bike logic, fitment data prep
│   ├── stripe.ts                 # Stripe client + helpers
│   ├── email/
│   │   └── templates/            # React Email components
│   └── catalog/
│       ├── import.ts             # CSV import
│       └── search.ts             # Catalog query layer
├── prisma/
│   ├── schema.prisma
│   └── migrations/
├── scripts/                      # One-off Bun/Node scripts
└── e2e/                          # Playwright tests
```

---

## Data Model (Prisma)

```prisma
model Product {
  id              String   @id @default(cuid())
  name            String
  description     String?
  brand           String?
  base_sku        String   @unique
  status          String   @default("active") // active | discontinued | draft
  universal_fit   Boolean  @default(false)
  variants        Variant[]
  fitments        ProductFitment[]
  created_at      DateTime @default(now())

  @@index([status])
  @@index([brand])
}

model Variant {
  id          String   @id @default(cuid())
  product_id  String
  sku         String   @unique
  price       Decimal  @db.Decimal(10, 2)
  stock       Int      @default(0)
  attributes  Json?
  product     Product  @relation(fields: [product_id], references: [id])
  fitments    VariantFitment[]
  order_items OrderItem[]

  @@index([product_id])
  @@index([sku])
}

model Fitment {
  id          String   @id @default(cuid())
  make        String
  model       String
  model_code  String?
  family      String?
  engine      String?
  year        Int
  products    ProductFitment[]
  variants    VariantFitment[]

  @@unique([make, model, year])
  @@index([make, model, year])
}

model ProductFitment {
  id          String   @id @default(cuid())
  product_id  String
  fitment_id  String
  product     Product  @relation(fields: [product_id], references: [id])
  fitment     Fitment  @relation(fields: [fitment_id], references: [id])

  @@unique([product_id, fitment_id])
  @@index([product_id])
  @@index([fitment_id])
}

model VariantFitment {
  id          String   @id @default(cuid())
  variant_id  String
  fitment_id  String
  variant     Variant  @relation(fields: [variant_id], references: [id])
  fitment     Fitment  @relation(fields: [fitment_id], references: [id])

  @@unique([variant_id, fitment_id])
  @@index([variant_id])
  @@index([fitment_id])
}

model Order {
  id                  String      @id @default(cuid())
  customer_id         String?
  total               Decimal     @db.Decimal(10, 2)
  stripe_session_id   String      @unique
  status              String      // pending | paid | shipped | delivered | refunded
  items               OrderItem[]
  customer            Customer?   @relation(fields: [customer_id], references: [id])
  created_at          DateTime    @default(now())

  @@index([customer_id])
  @@index([status])
}

model OrderItem {
  id          String   @id @default(cuid())
  order_id    String
  variant_id  String
  quantity    Int
  unit_price  Decimal  @db.Decimal(10, 2)
  order       Order    @relation(fields: [order_id], references: [id])
  variant     Variant  @relation(fields: [variant_id], references: [id])
}

model Customer {
  id                  String  @id @default(cuid())
  email               String  @unique
  name                String?
  stripe_customer_id  String?
  orders              Order[]
}

model Cart {
  id            String   @id @default(cuid())
  session_token String   @unique
  customer_id   String?
  items         Json     // serialized cart items, hot path optimization
  updated_at    DateTime @updatedAt
}

model Supplier {
  id              String    @id @default(cuid())
  name            String    @unique
  feed_url        String
  last_synced_at  DateTime?
}
```

---

## Critical Code Paths

### Pick-your-bike → filtered catalog

The selected bike lives in a session cookie + localStorage. Server reads cookie. Catalog queries always include a fitment join when a bike is selected:

```ts
// lib/catalog/search.ts
async function searchCatalog(opts: { bikeId?: string; category?: string }) {
  if (!opts.bikeId) {
    return prisma.product.findMany({
      where: { status: "active", category: opts.category },
    });
  }
  return prisma.product.findMany({
    where: {
      status: "active",
      category: opts.category,
      OR: [
        { universal_fit: true },
        { fitments: { some: { fitment_id: opts.bikeId } } },
      ],
    },
  });
}
```

### Stripe checkout → order recording

1. User clicks "Checkout" → server creates Stripe Checkout Session
2. User pays on Stripe-hosted page
3. Stripe sends `checkout.session.completed` webhook to `/api/stripe/webhook`
4. Webhook handler creates `Order` + `OrderItem` rows; sends Resend confirmation email
5. Webhook is **idempotent** — keyed on `stripe_session_id`

### Supplier feed import

```ts
// scripts/import-supplier-feed.ts
// Run nightly via Vercel Cron
// Parses CSV → upserts Product/Variant rows by base_sku
// Dry-run mode: --dry to preview changes
```

---

## Coding Conventions

- **TypeScript strict mode.** No `any`. No `as` casts unless absolutely necessary; prefer Zod schemas.
- **Prisma is the only ORM.** No raw SQL in product code paths (raw SQL is fine in `scripts/` for batch jobs).
- **Server Actions for mutations.** Use API routes only when an external system (Stripe webhooks, supplier sync) needs them.
- **Tailwind utility classes.** No CSS-in-JS, no separate `.module.css` files.
- **React Server Components by default.** Mark `"use client"` only when interactivity is required.
- **Error handling at boundaries.** Throw inside business logic; catch at the API/route boundary.
- **No `console.log` in production code.** Use Sentry breadcrumbs or structured logger.
- **Component naming:** PascalCase for components, camelCase for utility functions. One component per file.
- **File length limit:** soft cap 400 lines. Split aggressively — small files are easier for AI agents to reason about.

---

## Things to NOT do

- ❌ Don't add per-product custom fitment logic. Always use the `ProductFitment` / `VariantFitment` join tables. The pick-your-bike filter assumes uniform shape.
- ❌ Don't bypass the cart/checkout flow with custom payment integrations. Stripe Checkout is the only checkout surface; everything else is contraband.
- ❌ Don't mock Stripe in E2E tests. Use Stripe test mode + test card numbers.
- ❌ Don't mutate Prisma client state across requests. The client singleton in `lib/db.ts` is the only allowed instance.
- ❌ Don't add new third-party services without updating this file. The stack table above is the canonical list.
- ❌ Don't ship customer-facing copy without founder approval. Marketing copy is OUT of build scope; we ship the surface, founders own the words.

---

## Environment Variables

```
DATABASE_URL                # Neon Postgres connection string
DIRECT_URL                  # Neon direct connection (for migrations)
STRIPE_SECRET_KEY           # Stripe live key
STRIPE_WEBHOOK_SECRET       # Stripe webhook signing secret
NEXTAUTH_SECRET             # NextAuth JWT secret
NEXTAUTH_URL                # https://2acycles.com
RESEND_API_KEY              # Resend API key
SENTRY_DSN                  # Sentry error reporting
GOOGLE_ANALYTICS_ID         # GA4 measurement ID
CLARITY_PROJECT_ID          # Microsoft Clarity project
NEXT_PUBLIC_BASE_URL        # https://2acycles.com (for canonical URLs)
```

`.env.local` is gitignored. `.env.example` lists every required var.

---

## Deploy

- Push to `main` → Vercel auto-deploys to production
- PRs get preview URLs automatically
- Database migrations run via `prisma migrate deploy` in build step
- Vercel Cron jobs configured in `vercel.json`

Rollback: redeploy a previous commit from Vercel dashboard. Migrations are forward-only — never write a destructive migration without a rollback plan.

---

## Performance Budget

- LCP target: <2.5s on 4G mobile
- Catalog page: <500ms server response (cached)
- PDP: <300ms server response (cached at CDN)
- Stripe Checkout redirect: <1s end-to-end

---

## Security Posture

- Stripe handles all card data — we never store PAN
- Customer PII (email, addresses) encrypted at rest (Neon default)
- Admin pages gated by NextAuth + role check; magic-link auth only
- CSRF protection on all mutating endpoints (Next.js Server Actions handle this natively)
- Rate limiting on `/api/stripe/webhook` and cart mutations
- No customer-facing auth required for guest checkout — minimizes attack surface

---

## Open questions for the next iteration

1. Multi-warehouse stock — do we need it before $X revenue?
2. Returns automation vs manual — at what volume does manual break?
3. Klaviyo vs continuing on Resend for marketing email
4. Loyalty / rewards — defer until repeat-purchase rate clears 25%

These are outside the 8-week scope. Park them in the year-2 conversation.

---

*Generated as part of the Modern Phase $3,000 Discovery for Second Amendment Cycles. Published in full as a sample so future buyers know exactly what they're paying for. Your CLAUDE.md will look the same — different stack details if needed, same level of specificity.*
