# SaaS - Pricing e Billing

## Modelos de Pricing

| Modelo | Descricao | Exemplo | Quando Usar |
|--------|-----------|---------|-------------|
| **Flat Rate** | Preco fixo mensal | 29EUR/mes | Simplicidade, previsibilidade |
| **Per Seat** | Por utilizador | 10EUR/user/mes | B2B, equipas |
| **Usage Based** | Pay-as-you-go | 0.01EUR/API call | Variacao alta de uso |
| **Tiered** | Planos com limites | Free/Pro/Enterprise | Upsell natural |
| **Hybrid** | Base + usage | 20EUR + 0.001EUR/email | Receita previsivel + escala |

Recomendacao Descomplicar:

```
B2B (equipas 5-50 users): PER SEAT
B2C (individual): TIERED
API/Infra (desenvolvedores): USAGE BASED
SaaS tradicional: HYBRID (base + usage caps)
```

## Exemplo de Tiers

**FREE (0EUR/mes):**
- 1 user
- 100 records/mes
- 1 GB storage
- Sem integracoes, API, suporte prioritario

**PRO (29EUR/mes):**
- 5 users
- 10.000 records/mes
- 50 GB storage
- Integracoes basicas
- API access (10k calls/mes)
- Email support (24h)

**ENTERPRISE (Custom):**
- Users ilimitados
- Records ilimitados
- Storage dedicado
- Todas as integracoes
- API ilimitado
- Suporte 24/7 + Account Manager
- SSO/SAML
- SLA 99.9%

## Billing com Stripe

### Setup Basico

```typescript
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const subscription = await stripe.subscriptions.create({
  customer: customerId,
  items: [{ price: 'price_free' }],
  trial_period_days: 14,
  payment_behavior: 'default_incomplete',
  expand: ['latest_invoice.payment_intent']
});

// Webhooks para sincronizar estado:
// - customer.subscription.created
// - customer.subscription.updated
// - customer.subscription.deleted
// - invoice.payment_succeeded
// - invoice.payment_failed

// Verificar feature access
const canUseFeature = (user: User, feature: string) => {
  if (user.subscription.status !== 'active') return false;
  return PLAN_FEATURES[user.subscription.plan].includes(feature);
};
```

### Trial -> Paid Conversion

```
Trial 14 dias (sem cartao)
  |
  +- Dia 7: Email "Metade do trial"
  +- Dia 12: Email "2 dias restantes + valor criado"
  +- Dia 14: Soft paywall (pedir cartao)
  |
  v
Converteu? -> Pro (29EUR/mes)
Nao converteu? -> Free (downgrade features)
```

## Feature Flags por Plano

```typescript
export const PLAN_FEATURES = {
  free: [
    'basic_dashboard',
    'limited_records',
    'email_support'
  ],
  pro: [
    'basic_dashboard',
    'unlimited_records',
    'api_access',
    'integrations_basic',
    'priority_support',
    'export_csv'
  ],
  enterprise: [
    '*', // todas as features
    'sso_saml',
    'audit_logs',
    'custom_domain',
    'dedicated_support',
    'sla_guarantee'
  ]
};

export function requireFeature(feature: string) {
  return async (req, res, next) => {
    const user = req.user;
    const plan = user.subscription.plan;

    if (!PLAN_FEATURES[plan].includes(feature) &&
        !PLAN_FEATURES[plan].includes('*')) {
      return res.status(403).json({
        error: 'Upgrade required',
        feature: feature,
        current_plan: plan,
        upgrade_to: 'pro'
      });
    }

    next();
  };
}
```
