← back to Dear Bubbe Nextjs

PRICING_INTEGRATION_GUIDE.md

225 lines

# Bubbe.ai Pricing Integration Guide

## Overview
The pricing system has been implemented as a **parallel, non-interrupting system** that doesn't modify your existing Bubbe chat logic. You can integrate it gradually without breaking anything.

## What's Been Created

### 1. Core Pricing Module (`lib/bubbe-pricing.ts`)
- Defines 3 plans: Basic (Free), Plus ($18/mo), Max ($36/mo)
- 12 feature flags for different Bubbe capabilities
- Helper functions for plan recommendations and feature checking

### 2. User Session Management (`lib/user-session.ts`)
- Tracks user plans (defaults to Basic/Free)
- Manages feature access permissions
- In-memory storage (replace with database in production)

### 3. Feature Middleware (`lib/feature-middleware.ts`)
- Detects when users request premium features
- Returns Bubbe-style rejection messages for locked features
- Logs feature usage for analytics

### 4. API Endpoints (`app/api/pricing/route.ts`)
- GET /api/pricing - Get all plan information
- POST /api/pricing - Recommend plans, upgrade users, check status

### 5. Chat v2 Endpoint (`app/api/chat-v2/route.ts`)
- Example of how to integrate feature checking with chat
- Parallel to existing /api/chat endpoint

## How to Integrate (Without Breaking Anything)

### Option 1: Gradual Integration (Recommended)

1. **Keep your existing /api/chat endpoint untouched**
2. **Add feature detection to specific responses:**

```typescript
// In your existing chat handler
import { checkChatFeatures } from '@/lib/feature-middleware';
import { getUserSession } from '@/lib/user-session';

// After getting the user's message
const userId = getUserIdFromRequest(req);
const featureCheck = checkChatFeatures(message, userId);

if (featureCheck.hasRestriction) {
  // Prepend the upsell message to your normal response
  response = featureCheck.bubbeResponse + "\n\n" + normalBubbeResponse;
}
```

### Option 2: Feature-Specific Endpoints

Protect premium endpoints individually:

```typescript
// For voice endpoint
import { requireFeature } from '@/lib/feature-middleware';

export const POST = requireFeature('voice_notes')(async (req) => {
  // Your voice generation logic here
  // This only runs if user has Max plan
});
```

### Option 3: Client-Side Integration

Add plan checking to your frontend:

```javascript
// Check user's plan before showing features
const response = await fetch('/api/pricing', {
  method: 'POST',
  body: JSON.stringify({ action: 'check' })
});

const { plan, features } = await response.json();

// Hide/show UI elements based on plan
if (!features.includes('voice_notes')) {
  document.querySelector('#voice-button').disabled = true;
  document.querySelector('#voice-button').title = 'Upgrade to Max plan';
}
```

## Feature Flags Reference

### Basic Plan (Free)
- ✅ `advice_guilt` - Classic Bubbe advice
- ✅ `yiddish_sayings` - Basic Yiddish phrases
- ✅ `oy_vey_responses` - "Oy vey" reactions
- ✅ `storytelling` - Short Bubbe stories
- ✅ `yiddish_dictionary_basic` - Common terms

### Plus Plan ($18/mo)
Everything in Basic, plus:
- ✅ `daily_reminders` - "Did you eat?" reminders
- ✅ `eat_skinny_mode` - "You look skinny" prompts
- ✅ `cooking_tips` - Recipe advice
- ✅ `family_gossip` - Playful gossip mode

### Max Plan ($36/mo)
Everything in Plus, plus:
- ✅ `voice_notes` - Real Bubbe voice messages
- ✅ `holiday_mode` - Full Jewish holiday features
- ✅ `yiddish_dictionary_full` - Complete dictionary with slang

### Super Max Plan ($54/mo) 🆕
Everything in Max, plus:
- ✅ `local_news` - Hyper-local news from YOUR neighborhood
- ✅ `local_sports` - Your city's teams with real-time scores
- ✅ `local_weather` - Weather for YOUR exact location
- ✅ `personalized_insights` - Bubbe knows everything about your area

## Testing the System

1. **Test pricing API:**
```bash
# Get all plans
curl http://localhost:3011/api/pricing

# Recommend a plan based on features
curl -X POST http://localhost:3011/api/pricing \
  -H "Content-Type: application/json" \
  -d '{"action": "recommend", "features": ["voice_notes"]}'

# Upgrade a user
curl -X POST http://localhost:3011/api/pricing \
  -H "Content-Type: application/json" \
  -d '{"action": "upgrade", "plan": "plus"}'
```

2. **Test feature blocking:**
```bash
# Try to use voice as a basic user
curl -X POST http://localhost:3011/api/chat-v2 \
  -H "Content-Type: application/json" \
  -d '{"message": "Send me a voice note", "userId": "test_user"}'
```

## Bubbe's Rejection Messages

When users try premium features without the right plan, Bubbe responds with sass:

- **Voice request (Basic user):** "Oy, you want to hear my voice? For 36 dollars a month you can hear me kvetch all day!"
- **Holiday reminder (Basic user):** "What, you need ME to remind you about the holidays? Your mother didn't teach you?"
- **Cooking tips (Basic user):** "My secret recipes aren't FREE, bubbeleh! Fork over 18 dollars or eat takeout forever!"
- **Local news (non-Super Max):** "You want LOCAL news? What, you think I'm your personal newspaper? $54 for Super Max!"
- **Local sports (non-Super Max):** "Your teams are all terrible anyway! But for $54 I'll tell you EXACTLY how terrible!"
- **Local weather (non-Super Max):** "You can't look outside? For $54 I'll tell you the weather on YOUR street!"

## Database Integration (Production)

Replace in-memory storage with your database:

```typescript
// In lib/user-session.ts
// Replace the Map with database calls

export async function getUserSession(userId: string): Promise<UserSession> {
  // const session = await db.userSessions.findOne({ userId });
  // return session || { userId, plan: 'basic', ... };
}

export async function updateUserPlan(userId: string, plan: PlanId) {
  // await db.userSessions.updateOne(
  //   { userId },
  //   { $set: { plan, subscribedAt: new Date() } }
  // );
}
```

## Payment Processing

Add Stripe/PayPal after plan selection:

```typescript
// After user selects a plan
if (plan !== 'basic') {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [{
      price_data: {
        currency: 'usd',
        product_data: { name: `Bubbe ${plan}` },
        recurring: { interval: 'month' },
        unit_amount: PLAN_PRICES[plan] * 100
      },
      quantity: 1
    }],
    mode: 'subscription',
    success_url: `${BASE_URL}/api/pricing/success?plan=${plan}`,
    cancel_url: `${BASE_URL}/pricing`
  });
  
  // Redirect to Stripe checkout
  return redirect(session.url);
}
```

## Next Steps

1. **Build the pricing page UI** - Show the 3 plans with feature comparison
2. **Add payment processing** - Stripe or PayPal integration
3. **Persist user sessions** - Move from in-memory to database
4. **Create admin dashboard** - Track subscriptions and feature usage
5. **Add email notifications** - Send upgrade reminders and receipts

## Important Notes

- **This system is completely parallel** - Your existing Bubbe works unchanged
- **Feature flags are enforced server-side** - Can't be bypassed by clients
- **Bubbe stays in character** - All rejection messages are sassy and on-brand
- **Default is Free** - Users without a plan get Basic automatically
- **Analytics ready** - All feature attempts are logged for insights

## Support

The pricing system is designed to be non-intrusive. If you have any issues:
1. The original /api/chat endpoint still works exactly as before
2. You can disable feature checking by not calling the middleware
3. All pricing code is in separate files - easy to remove if needed

Remember: The goal is to monetize WITHOUT breaking your existing Bubbe!