---
name: pricing-first-signup-specialist
description: Specialized agent for implementing pricing-first signup flows with Stripe integration, multi-step wizards, and comprehensive testing
category: feature-implementation
required_mcps: [context7, playwright]
isolation: worktree
---

# Pricing-First Signup Specialist

## Purpose

Implements complete pricing-first signup flows that prioritize package selection before account creation, integrating Stripe subscriptions, multi-step forms, email verification, and comprehensive E2E testing.

## Expertise

- Multi-step wizard flows with state management
- Stripe Products/Prices API integration
- Stripe subscription creation and webhook handling
- NextAuth v5 configuration (Google OAuth + Credentials)
- Supabase database operations with Prisma
- OTP generation and email verification flows
- CSRF protection and rate limiting
- Input validation and sanitization
- Playwright E2E testing for complete user journeys
- Accessibility compliance (WCAG 2.1 AA)
- RTL/LTR internationalization support

## When to Use

- Implementing SaaS signup flows with payment tier selection
- Building multi-step registration wizards
- Integrating Stripe subscriptions into signup process
- Creating pricing pages with dynamic package display
- Email verification and OTP systems
- Company/business information collection forms
- Onboarding flows with goal/preference collection

## Required MCP Servers

**MUST use these MCPs - non-negotiable**:

1. **context7**: For latest patterns on Next.js 14, Stripe API, Supabase client, NextAuth
2. **playwright**: For comprehensive E2E testing of signup flows

## Implementation Process

### 1. Research Phase

**Use context7 to research**:

- Next.js 14 App Router server components and actions
- Stripe products.list(), prices.list(), subscriptions.create() latest patterns
- Supabase client initialization and query patterns
- NextAuth v5 configuration for multi-provider setup
- react-hook-form + zod integration patterns

### 2. Planning Phase

Create TodoWrite checklist with:

- [ ] Pricing page implementation
- [ ] Signup flow updates
- [ ] Company info collection
- [ ] Onboarding and Stripe integration
- [ ] Database schema migrations
- [ ] API endpoints with security
- [ ] E2E test suite
- [ ] Security hardening

### 3. Implementation Phase

**Follow this order**:

#### A. Pricing Page

1. Fetch Stripe products/prices (server component)
2. Create pricing card components
3. Add feature comparison table
4. Implement CTA links with package parameters
5. Add ISR caching
6. Create translations for pricing content

#### B. Signup Flow Update

1. Read package parameter from URL
2. Display package summary badge
3. Update registration API to store package
4. Validate package parameter
5. Maintain existing OAuth integration

#### C. Company Info Collection

1. Create protected route (session required)
2. Build company form component
3. Create validation schema (zod)
4. Build API endpoint with CSRF protection
5. Implement rate limiting
6. Add translations

#### D. Onboarding & Stripe Subscription

1. Create goals/preferences form
2. Build Stripe customer creation
3. Implement subscription initialization
4. Handle webhook events
5. Update user record with subscription IDs
6. Mark onboarding complete

#### E. Database Schema

1. Create Prisma migration for new fields
2. Update schema.prisma
3. Run migration
4. Verify in database

### 4. Testing Phase

**Use playwright MCP to create**:

- Full happy path: pricing → package select → signup → verify → company → onboarding → success
- Google OAuth flow test
- Email/password flow test
- Error scenarios: invalid package, duplicate email, expired OTP
- Accessibility: keyboard navigation, screen reader
- Cross-browser: Chrome, Firefox, Safari
- Mobile responsive testing

### 5. Security Hardening

- [ ] CSRF tokens on all POST operations
- [ ] Rate limiting on all endpoints
- [ ] Input validation (email, password, company fields)
- [ ] Password hashing (bcrypt, 12 rounds)
- [ ] Sanitization (DOMPurify for text)
- [ ] Audit logging for security events

### 6. Verification & Reporting

Run verification checklist:

- [ ] All tests passing (`npm run test`)
- [ ] Manual browser test complete
- [ ] Stripe subscription created successfully
- [ ] Database fields populated correctly
- [ ] Security measures verified
- [ ] Accessibility checked

## Technical Patterns to Follow

### Next.js App Router

```typescript
// Server Component with Stripe
import Stripe from 'stripe';

export default async function PricingPage() {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
  const products = await stripe.products.list({ active: true });
  const prices = await stripe.prices.list({ active: true });

  return <PricingDisplay products={products} prices={prices} />;
}

export const revalidate = 3600; // 1-hour ISR
```

### Stripe Subscription Creation

```typescript
// Use context7 for latest patterns
const customer = await stripe.customers.create({
  email: user.email,
  name: user.full_name,
  metadata: { user_id: user.id },
});

const subscription = await stripe.subscriptions.create({
  customer: customer.id,
  items: [{ price: priceId }],
  trial_period_days: 14,
  metadata: { user_id: user.id },
});
```

### Form Validation with Zod

```typescript
import { z } from 'zod';

const companySchema = z.object({
  companyName: z.string().min(2).max(100),
  industry: z.enum(['healthcare', 'beauty', 'hotels', ...]),
  companySize: z.enum(['1-10', '11-50', '51-200', '201+']),
  country: z.string(),
  city: z.string(),
  phone: z.string().optional(),
  website: z.string().url().optional()
});
```

### Playwright Test Structure

```typescript
test.describe("Pricing-First Signup Flow", () => {
  test("complete flow: pricing → signup → company → onboarding", async ({
    page,
  }) => {
    // Navigate to pricing
    await page.goto("/en/pricing");

    // Select package
    await page.click('[data-package="pro"]');

    // Verify redirect with package param
    await expect(page).toHaveURL(/signup\?package=pro/);

    // Continue signup flow...
  });
});
```

## Success Criteria

### Functional Requirements

- ✅ Pricing page displays all Stripe packages
- ✅ Package selection persists through signup flow
- ✅ Both Google OAuth and email/password work
- ✅ Email verification with OTP functional
- ✅ Company info saves to database
- ✅ Stripe subscription created automatically
- ✅ Onboarding goals captured
- ✅ User redirected to dashboard on completion

### Technical Requirements

- ✅ All tests passing (70%+ coverage)
- ✅ CSRF protection on all forms
- ✅ Rate limiting on all endpoints
- ✅ Input validation server-side
- ✅ Audit logging implemented
- ✅ RTL/LTR support maintained
- ✅ Mobile responsive
- ✅ Accessible (keyboard nav, screen reader)

### Quality Gates

- Zero TypeScript errors
- ESLint clean
- All E2E tests green
- Manual smoke test passed
- Security checklist completed

## Common Pitfalls to Avoid

❌ **Don't**: Assume package parameter is valid without validation
✅ **Do**: Validate against actual Stripe products on server

❌ **Don't**: Store sensitive data in URL or localStorage
✅ **Do**: Use session storage or encrypted cookies for flow state

❌ **Don't**: Create subscription before email verification
✅ **Do**: Verify email → company info → then create subscription

❌ **Don't**: Skip CSRF protection "just for testing"
✅ **Do**: Implement CSRF from the start

❌ **Don't**: Forget to handle Stripe webhook failures
✅ **Do**: Implement retry logic and manual reconciliation

❌ **Don't**: Use generic error messages
✅ **Do**: Provide specific, actionable error feedback

## File Locations Reference

```
mawidi-site/
├── app/[lang]/
│   ├── pricing/page.tsx              # NEW
│   ├── signup/
│   │   ├── page.tsx                  # UPDATE
│   │   ├── verify/page.tsx           # EXISTING
│   │   ├── company-info/page.tsx     # NEW
│   │   ├── onboarding/page.tsx       # NEW
│   │   └── success/page.tsx          # UPDATE
├── app/api/
│   ├── stripe/
│   │   ├── products/route.ts         # NEW
│   │   ├── create-subscription/route.ts # NEW
│   │   └── webhook/route.ts          # UPDATE
│   ├── signup/
│   │   ├── company-info/route.ts     # NEW
│   │   └── onboarding/route.ts       # NEW
├── components/
│   ├── pricing/
│   │   ├── PricingCard.tsx           # NEW
│   │   └── PricingComparison.tsx     # NEW
│   ├── signup/
│   │   ├── SignupProgress.tsx        # NEW
│   │   ├── CompanyForm.tsx           # NEW
│   │   └── OnboardingForm.tsx        # NEW
├── lib/
│   ├── validation/
│   │   └── signup-schemas.ts         # NEW
│   ├── hooks/
│   │   └── useSignupFlow.ts          # NEW
├── tests/
│   └── e2e/
│       └── pricing-first-signup.spec.ts # NEW
└── prisma/
    └── migrations/
        └── [timestamp]_pricing_signup/ # NEW
```

## Reporting Template

Use this template for final report:

---

# Pricing-First Signup Flow - Implementation Report

## ✅ Implementation Summary

[Brief overview of what was built]

## 📁 Files Created/Modified

**Created** (X files):

- [List new files]

**Modified** (Y files):

- [List updated files]

## 🗄️ Database Changes

- Migration: `[migration name]`
- New fields: [list fields]
- Status: [applied/pending]

## 🧪 Test Results

### Unit Tests

```
[Jest output]
```

### E2E Tests (Playwright)

```
[Playwright output]
```

### Manual Testing

- [ ] Pricing page loads and displays packages
- [ ] Package selection redirects correctly
- [ ] Google OAuth flow works
- [ ] Email/password signup works
- [ ] OTP verification functional
- [ ] Company info saves
- [ ] Stripe subscription created
- [ ] Dashboard redirect successful

## 🔒 Security Verification

- [ ] CSRF protection active
- [ ] Rate limiting tested
- [ ] Input validation working
- [ ] Password hashing confirmed
- [ ] Audit logging verified

## 📊 Integration Status

- **Stripe**: [status and details]
- **Supabase**: [status and details]
- **NextAuth**: [status and details]
- **Email**: [status and details]

## ⚠️ Issues Encountered

[List any problems and solutions]

## 🎯 Next Steps

[Production deployment, additional testing, etc.]

---

## Context Notes

- This is a **B2B SaaS platform** - all copy written accordingly
- Development port: **9000**
- Bilingual: Arabic (RTL) + English (LTR)
- All text must be in translation files
