template-saas/apps/database
rckrdmrd 40d57f8124 feat: Add AI Integration, Notifications UI and Settings Page
FASE 1: Notifications UI
- Add NotificationBell, NotificationDrawer, NotificationItem components
- Integrate notification bell in DashboardLayout header
- Real-time unread count with polling

FASE 2: AI Integration Backend
- Add AI module with OpenRouter client
- Endpoints: POST /ai/chat, GET /ai/models, GET/PATCH /ai/config
- GET /ai/usage, GET /ai/usage/current, GET /ai/health
- Database: schema ai with configs and usage tables
- Token tracking and cost calculation

FASE 3: Settings Page Refactor
- Restructure with tabs navigation
- GeneralSettings: profile, organization, appearance
- NotificationSettings: channels and categories toggles
- SecuritySettings: password change, 2FA placeholder, sessions

Files created: 25+
Endpoints added: 7
Story Points completed: 21

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 07:04:29 -06:00
..
ddl feat: Add AI Integration, Notifications UI and Settings Page 2026-01-07 07:04:29 -06:00
scripts feat: Initial commit - template-saas 2026-01-07 04:41:24 -06:00
seeds/prod feat: Initial commit - template-saas 2026-01-07 04:41:24 -06:00
README.md feat: Initial commit - template-saas 2026-01-07 04:41:24 -06:00

Template SaaS - Database

Version: 1.0.0 Database: PostgreSQL 16+ Multi-tenancy: Row-Level Security (RLS)


Schemas

Schema Descripcion RLS
auth Sesiones, tokens, OAuth Si
tenants Tenants y configuracion No*
users Usuarios, roles, permisos Si
billing Subscripciones, facturas, pagos Si
plans Planes y features No
audit Logs de auditoria y actividad Si
notifications Templates y notificaciones Si
feature_flags Feature flags y evaluaciones Si
storage Archivos y metadata Si

*tenants.tenants no usa RLS ya que es la tabla base de multi-tenancy.


Estructura de Archivos

database/
├── ddl/
│   ├── 00-extensions.sql     # Extensiones PostgreSQL
│   ├── 01-schemas.sql        # Creacion de schemas
│   ├── 02-enums.sql          # Tipos enum
│   ├── 03-functions.sql      # Funciones de utilidad
│   └── schemas/
│       ├── auth/tables/      # Sesiones, tokens, OAuth
│       ├── tenants/tables/   # Tenants, settings
│       ├── users/tables/     # Users, roles, invitations
│       ├── billing/tables/   # Subscriptions, invoices
│       ├── plans/tables/     # Plans, features
│       ├── audit/tables/     # Audit logs, activity
│       ├── notifications/tables/
│       └── feature_flags/tables/
├── seeds/
│   ├── prod/                 # Seeds para produccion
│   └── dev/                  # Seeds para desarrollo
└── scripts/
    ├── create-database.sh
    └── drop-and-recreate.sh

Uso de RLS

Establecer Contexto de Tenant

-- En cada request
SELECT auth.set_current_tenant('tenant-uuid-here');

-- Opcional: establecer usuario
SELECT auth.set_current_user('user-uuid-here');

Desde el Backend

// Middleware de tenant
async function setTenantContext(tenantId: string) {
  await dataSource.query('SELECT auth.set_current_tenant($1)', [tenantId]);
}

// En el request handler
const tenantId = req.user.tenantId;
await setTenantContext(tenantId);
// Ahora todas las queries respetan RLS

Funciones de Utilidad

Contexto

  • auth.set_current_tenant(uuid) - Establece tenant para RLS
  • auth.get_current_tenant() - Obtiene tenant actual
  • auth.set_current_user(uuid) - Establece usuario actual
  • auth.clear_context() - Limpia contexto

Limites de Plan

  • plans.get_tenant_limits(tenant_id) - Obtiene limites del plan
  • plans.check_limit(tenant_id, key, count) - Verifica limite
  • plans.has_feature(tenant_id, feature_code) - Verifica feature

Usuarios

  • users.count_active_users(tenant_id) - Cuenta usuarios activos
  • users.can_add_user(tenant_id) - Puede agregar usuario

Feature Flags

  • feature_flags.evaluate_flag(code, tenant_id, user_id) - Evalua flag

Utilidades

  • public.slugify(text) - Genera slug
  • public.generate_token(length) - Genera token aleatorio
  • public.hash_token(token) - Hash SHA256

Scripts

Crear Base de Datos

cd apps/database/scripts
./create-database.sh

Recrear Base de Datos

./drop-and-recreate.sh

Variables de Entorno

DB_HOST=localhost
DB_PORT=5432
DB_NAME=template_saas_dev
DB_USER=template_saas_user
DB_PASSWORD=your_password
DB_ADMIN_USER=postgres
DB_ADMIN_PASSWORD=admin_password

Orden de Ejecucion DDL

  1. 00-extensions.sql
  2. 01-schemas.sql
  3. 02-enums.sql
  4. schemas/tenants/tables/*.sql
  5. schemas/plans/tables/*.sql
  6. schemas/users/tables/*.sql
  7. schemas/auth/tables/*.sql
  8. schemas/billing/tables/*.sql
  9. schemas/audit/tables/*.sql
  10. schemas/notifications/tables/*.sql
  11. schemas/feature_flags/tables/*.sql
  12. 03-functions.sql

Seeds Iniciales

Produccion

  • Planes default (Free, Starter, Pro, Enterprise)
  • Roles de sistema (owner, admin, member)
  • Permisos base
  • Templates de notificacion

Desarrollo

  • Tenant de prueba
  • Usuarios de prueba
  • Datos de ejemplo

Actualizado: 2026-01-07