template-saas/docs/01-modulos/SAAS-004-billing.md
rckrdmrd 4dafffa386 feat: Add superadmin metrics, onboarding and module documentation
- Add MetricsPage and useOnboarding hook
- Update superadmin controller and service
- Add module documentation (docs/01-modulos/)
- Add CONTEXT-MAP.yml and Sprint 5 execution report
- Update project status and task traces

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 05:40:26 -06:00

190 lines
4.2 KiB
Markdown

# SAAS-004: Billing y Suscripciones
## Metadata
- **Codigo:** SAAS-004
- **Modulo:** Billing
- **Prioridad:** P0
- **Estado:** Completado
- **Fase:** 2 - Billing
## Descripcion
Sistema de facturacion completo con Stripe: suscripciones recurrentes, trials, upgrades/downgrades, facturas, y webhooks para sincronizacion.
## Objetivos
1. Integracion completa con Stripe
2. Suscripciones mensuales/anuales
3. Trial period (14 dias)
4. Upgrade/downgrade de plan
5. Facturas y recibos
## Alcance
### Incluido
- Stripe Checkout
- Suscripciones recurrentes
- Trial gratuito
- Cambio de plan (prorateo)
- Portal de cliente Stripe
- Webhooks de Stripe
- Historial de facturas
### Excluido
- Metered billing - fase posterior
- Multiples metodos de pago guardados
- Facturacion fiscal mexicana
## Modelo de Datos
### Tablas (schema: billing)
**subscriptions**
- id, tenant_id, plan_id
- stripe_subscription_id, stripe_customer_id
- status, current_period_start, current_period_end
- trial_ends_at, cancelled_at
**invoices**
- id, tenant_id, subscription_id
- stripe_invoice_id, number
- amount, currency, status
- paid_at, pdf_url
## Integracion Stripe
### Productos y Precios
```typescript
// Configurados en Stripe Dashboard
const STRIPE_PRODUCTS = {
starter: {
monthly: 'price_xxx_monthly',
yearly: 'price_xxx_yearly'
},
pro: {
monthly: 'price_yyy_monthly',
yearly: 'price_yyy_yearly'
}
};
```
### Webhooks Manejados
- `customer.subscription.created`
- `customer.subscription.updated`
- `customer.subscription.deleted`
- `invoice.paid`
- `invoice.payment_failed`
- `customer.updated`
## Endpoints API
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | /billing/plans | Planes disponibles |
| GET | /billing/subscription | Suscripcion actual |
| POST | /billing/checkout | Crear sesion checkout |
| POST | /billing/portal | URL portal de cliente |
| PUT | /billing/change-plan | Cambiar plan |
| POST | /billing/cancel | Cancelar suscripcion |
| POST | /billing/resume | Reanudar suscripcion |
| GET | /billing/invoices | Historial facturas |
| GET | /billing/invoices/:id/pdf | Descargar factura |
| POST | /billing/webhook | Webhook Stripe |
## Flujos
### Nueva Suscripcion
```
1. Usuario selecciona plan
2. Click "Suscribirse"
3. Backend crea Checkout Session
4. Usuario redirigido a Stripe Checkout
5. Usuario completa pago
6. Stripe envia webhook
7. Backend actualiza suscripcion
8. Usuario redirigido a app
```
### Upgrade de Plan
```
1. Usuario en plan Starter
2. Click "Upgrade a Pro"
3. Backend llama Stripe API
4. Stripe calcula prorateo
5. Se cobra diferencia
6. Plan actualizado inmediatamente
7. Features Pro desbloqueadas
```
### Trial Expirando
```
Dia -3: Email "Tu trial termina en 3 dias"
Dia -1: Email "Tu trial termina manana"
Dia 0: Email "Tu trial ha terminado"
Si no hay pago: downgrade a Free
```
## Estados de Suscripcion
```
trialing ──► active ──► past_due ──► cancelled
└──► paused
```
| Estado | Acceso | Descripcion |
|--------|--------|-------------|
| trialing | Completo | En periodo de prueba |
| active | Completo | Pagando |
| past_due | Limitado | Pago fallido (grace) |
| cancelled | Sin acceso | Cancelada |
| paused | Sin acceso | Pausada |
## Entregables
| Entregable | Estado | Archivo |
|------------|--------|---------|
| billing.module.ts | Completado | `modules/billing/` |
| stripe.service.ts | Completado | `services/` |
| billing.controller.ts | Completado | `controllers/` |
| DDL billing schema | Completado | `ddl/schemas/billing/` |
## Dependencias
### Depende de
- SAAS-001 (Auth)
- SAAS-002 (Tenants)
- SAAS-005 (Plans)
### Bloquea a
- Ninguno (pero habilita features por plan)
## Criterios de Aceptacion
- [x] Checkout funciona
- [x] Webhooks se procesan
- [x] Upgrade/downgrade funciona
- [x] Facturas se generan
- [x] Trial funciona
- [x] Cancelacion funciona
## Configuracion
```typescript
{
stripe: {
secretKey: process.env.STRIPE_SECRET_KEY,
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
portalReturnUrl: 'https://app.example.com/settings/billing'
},
trial: {
days: 14,
requiresCard: false
}
}
```
---
**Ultima actualizacion:** 2026-01-07