# RF-SETTINGS-004: Feature Flags ## Identificacion | Campo | Valor | |-------|-------| | **ID** | RF-SETTINGS-004 | | **Modulo** | MGN-006 Settings | | **Titulo** | Feature Flags | | **Prioridad** | P1 - Alta | | **Estado** | Draft | | **Fecha** | 2025-12-05 | --- ## Descripcion El sistema debe permitir habilitar o deshabilitar funcionalidades mediante feature flags, tanto a nivel global como por tenant o usuario, permitiendo rollouts graduales y A/B testing. --- ## Requisitos Funcionales ### RF-SETTINGS-004.1: Estructura de Feature Flag | Campo | Tipo | Descripcion | |-------|------|-------------| | id | UUID | Identificador unico | | key | VARCHAR(100) | Clave unica del flag | | name | VARCHAR(255) | Nombre descriptivo | | description | TEXT | Descripcion detallada | | flag_type | ENUM | boolean, percentage, variant | | default_value | JSONB | Valor por defecto | | is_active | BOOLEAN | Flag activo en sistema | | created_at | TIMESTAMPTZ | Fecha creacion | | expires_at | TIMESTAMPTZ | Fecha expiracion (opcional) | ### RF-SETTINGS-004.2: Tipos de Feature Flags ```typescript enum FeatureFlagType { BOOLEAN = 'boolean', // On/Off simple PERCENTAGE = 'percentage', // % de usuarios/tenants VARIANT = 'variant' // A/B/C testing } ``` ### RF-SETTINGS-004.3: Niveles de Aplicacion Los flags pueden aplicarse en diferentes niveles: | Nivel | Descripcion | Override | |-------|-------------|----------| | `global` | Todos los tenants | Base | | `plan` | Por plan de suscripcion | Override global | | `tenant` | Por tenant especifico | Override plan | | `user` | Por usuario especifico | Override tenant | ### RF-SETTINGS-004.4: Feature Flags Predefinidos ```typescript const FEATURE_FLAGS = [ { key: 'feature.oauth_login', name: 'Login con OAuth', type: 'boolean', default: true }, { key: 'feature.dark_mode', name: 'Modo Oscuro', type: 'boolean', default: true }, { key: 'feature.export_excel', name: 'Exportar a Excel', type: 'boolean', default: true }, { key: 'feature.new_dashboard', name: 'Nuevo Dashboard', type: 'percentage', default: 0 // 0% = deshabilitado }, { key: 'feature.checkout_flow', name: 'Flujo de Checkout', type: 'variant', default: 'control' // control, variant_a, variant_b } ]; ``` ### RF-SETTINGS-004.5: Overrides por Nivel ```typescript // Tabla: feature_flag_overrides interface FeatureFlagOverride { id: UUID; feature_flag_id: UUID; level: 'plan' | 'tenant' | 'user'; level_id: UUID; // ID del plan/tenant/user value: JSONB; is_active: boolean; created_at: TIMESTAMPTZ; created_by: UUID; } ``` ### RF-SETTINGS-004.6: Rollout Gradual Para flags tipo `percentage`: ```typescript interface RolloutConfig { percentage: number; // 0-100 sticky: boolean; // Mismo usuario siempre igual seed?: string; // Seed para determinismo exclude_tenants?: UUID[]; // Tenants excluidos include_tenants?: UUID[]; // Tenants incluidos siempre } ``` **Algoritmo:** 1. Si tenant esta en `include_tenants` -> habilitado 2. Si tenant esta en `exclude_tenants` -> deshabilitado 3. Hash(user_id + seed) % 100 < percentage -> habilitado ### RF-SETTINGS-004.7: Variantes para A/B Testing Para flags tipo `variant`: ```typescript interface VariantConfig { variants: { name: string; weight: number; // Peso relativo }[]; sticky: boolean; } // Ejemplo: { variants: [ { name: 'control', weight: 50 }, { name: 'variant_a', weight: 25 }, { name: 'variant_b', weight: 25 } ], sticky: true } ``` --- ## Operaciones ### Verificar Feature Flag ```typescript GET /api/v1/features/:key Response: { "key": "feature.new_dashboard", "enabled": true, "variant": null, // o nombre de variante "source": "tenant_override" } ``` ### Verificar Multiples Flags ```typescript POST /api/v1/features/evaluate { "keys": ["feature.new_dashboard", "feature.dark_mode"] } Response: { "feature.new_dashboard": { "enabled": true }, "feature.dark_mode": { "enabled": true } } ``` ### Listar Feature Flags (Admin) ```typescript GET /api/v1/admin/features Response: { "data": [ { "key": "feature.new_dashboard", "name": "Nuevo Dashboard", "type": "percentage", "globalValue": 25, "overrides": [ { "level": "tenant", "count": 3 } ] } ] } ``` ### Crear Override ```typescript POST /api/v1/admin/features/:key/overrides { "level": "tenant", "levelId": "tenant-uuid", "value": true } ``` ### Actualizar Rollout ```typescript PATCH /api/v1/admin/features/:key { "percentage": 50 // Incrementar rollout al 50% } ``` --- ## Reglas de Negocio | ID | Regla | Severidad | |----|-------|-----------| | BR-001 | Solo admin puede crear/modificar feature flags | Error | | BR-002 | Flags expirados se evaluan como default | Info | | BR-003 | Evaluacion debe ser < 5ms | Performance | | BR-004 | Sticky flags usan hash determinista | Info | | BR-005 | Cambios se propagan a cache en < 1s | Info | --- ## Criterios de Aceptacion - [ ] Tres tipos de flags (boolean, percentage, variant) - [ ] Override en cuatro niveles - [ ] Rollout gradual funcional - [ ] A/B testing con variantes - [ ] Evaluacion rapida con cache - [ ] UI de administracion de flags - [ ] Expiracion automatica --- ## Historial | Version | Fecha | Autor | Cambios | |---------|-------|-------|---------| | 1.0 | 2025-12-05 | Requirements-Analyst | Creacion inicial |