--- id: "SAAS-022" title: "Goals" type: "Module" status: "Specified" priority: "P2" module: "goals" version: "1.0.0" created_date: "2026-01-24" updated_date: "2026-01-24" estimated_sp: 13 --- # SAAS-022: Goals ## Metadata - **Codigo:** SAAS-022 - **Modulo:** Goals - **Prioridad:** P2 - **Estado:** Especificado - **Fase:** 6 - Advanced Features - **Story Points:** 13 ## Descripcion Sistema de metas y objetivos para equipos y usuarios individuales. Permite definir OKRs, KPIs, metas de ventas, y trackear progreso en tiempo real. Se integra con Sales para metas comerciales y con Commissions para bonos por cumplimiento. ## Objetivos 1. Definir metas con periodos y metricas 2. Asignar metas a usuarios/equipos 3. Tracking de progreso automatico 4. Notificaciones de hitos 5. Reportes de cumplimiento ## Alcance ### Incluido - Tipos de metas: numerica, porcentual, booleana - Periodos: diario, semanal, mensual, trimestral, anual - Metas individuales y de equipo - Tracking automatico (integracion con fuentes) - Actualizacion manual de progreso - Dashboard de metas - Notificaciones de progreso - Reportes de cumplimiento ### Excluido - OKRs jerarquicos complejos - Metas en cascada automaticas - Gamificacion avanzada (puntos, badges) ## Modelo de Datos ### Schema: goals ```sql -- Definiciones de metas CREATE TABLE goals.definitions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL REFERENCES tenants.tenants(id), -- Info basica name VARCHAR(200) NOT NULL, description TEXT, category VARCHAR(100), -- Tipo de meta type goals.goal_type NOT NULL, metric goals.metric_type NOT NULL, -- Objetivo target_value DECIMAL(15,2) NOT NULL, unit VARCHAR(50), -- 'USD', 'units', '%', etc. -- Periodo period goals.period_type NOT NULL, starts_at DATE NOT NULL, ends_at DATE NOT NULL, -- Fuente de datos (para tracking automatico) source goals.data_source, source_config JSONB DEFAULT '{}', -- { -- module: 'sales', -- entity: 'opportunities', -- filter: { status: 'won' }, -- aggregation: 'sum', -- field: 'amount' -- } -- Hitos milestones JSONB DEFAULT '[]', -- [{ percentage: 25, notify: true }, { percentage: 50, notify: true }] -- Estado status goals.goal_status NOT NULL DEFAULT 'draft', -- Metadata tags JSONB DEFAULT '[]', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), created_by UUID REFERENCES users.users(id) ); -- Asignaciones de metas CREATE TABLE goals.assignments ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL REFERENCES tenants.tenants(id), definition_id UUID NOT NULL REFERENCES goals.definitions(id), -- Asignado a assignee_type goals.assignee_type NOT NULL, user_id UUID REFERENCES users.users(id), team_id UUID, -- Si hay modulo de teams -- Objetivo personalizado (override) custom_target DECIMAL(15,2), -- Progreso current_value DECIMAL(15,2) DEFAULT 0, progress_percentage DECIMAL(5,2) DEFAULT 0, last_updated_at TIMESTAMPTZ, -- Estado status goals.assignment_status NOT NULL DEFAULT 'active', achieved_at TIMESTAMPTZ, -- Metadata notes TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Historial de progreso CREATE TABLE goals.progress_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), assignment_id UUID NOT NULL REFERENCES goals.assignments(id), -- Valores previous_value DECIMAL(15,2), new_value DECIMAL(15,2) NOT NULL, change_amount DECIMAL(15,2), -- Fuente del cambio source goals.progress_source NOT NULL, source_reference VARCHAR(200), -- ID de la transaccion origen notes TEXT, logged_at TIMESTAMPTZ DEFAULT NOW(), logged_by UUID REFERENCES users.users(id) ); -- Notificaciones de hitos CREATE TABLE goals.milestone_notifications ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), assignment_id UUID NOT NULL REFERENCES goals.assignments(id), milestone_percentage INTEGER NOT NULL, achieved_value DECIMAL(15,2) NOT NULL, notified_at TIMESTAMPTZ DEFAULT NOW() ); -- Enums CREATE TYPE goals.goal_type AS ENUM ( 'target', 'limit', 'maintain' ); CREATE TYPE goals.metric_type AS ENUM ( 'number', 'currency', 'percentage', 'boolean', 'count' ); CREATE TYPE goals.period_type AS ENUM ( 'daily', 'weekly', 'monthly', 'quarterly', 'yearly', 'custom' ); CREATE TYPE goals.data_source AS ENUM ( 'manual', 'sales', 'billing', 'commissions', 'custom' ); CREATE TYPE goals.goal_status AS ENUM ( 'draft', 'active', 'paused', 'completed', 'cancelled' ); CREATE TYPE goals.assignee_type AS ENUM ( 'user', 'team', 'tenant' ); CREATE TYPE goals.assignment_status AS ENUM ( 'active', 'achieved', 'failed', 'cancelled' ); CREATE TYPE goals.progress_source AS ENUM ( 'manual', 'automatic', 'import', 'api' ); ``` ### RLS Policies ```sql ALTER TABLE goals.definitions ENABLE ROW LEVEL SECURITY; ALTER TABLE goals.assignments ENABLE ROW LEVEL SECURITY; ALTER TABLE goals.progress_log ENABLE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON goals.definitions USING (tenant_id = current_setting('app.current_tenant_id')::UUID); ``` ## Endpoints API ### Definitions | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /goals | Listar definiciones | | POST | /goals | Crear meta | | GET | /goals/:id | Obtener meta | | PATCH | /goals/:id | Actualizar meta | | DELETE | /goals/:id | Eliminar meta | | POST | /goals/:id/activate | Activar meta | | POST | /goals/:id/duplicate | Duplicar meta | ### Assignments | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /goals/:id/assignments | Listar asignaciones | | POST | /goals/:id/assignments | Asignar meta | | PATCH | /goals/assignments/:id | Actualizar asignacion | | DELETE | /goals/assignments/:id | Eliminar asignacion | | POST | /goals/assignments/:id/progress | Actualizar progreso | ### Progress | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /goals/assignments/:id/history | Historial progreso | | POST | /goals/sync | Sincronizar con fuentes | ### My Goals | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /goals/my | Mis metas | | GET | /goals/my/summary | Resumen de progreso | | POST | /goals/my/:id/update | Actualizar mi progreso | ### Reports | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /goals/reports/completion | Tasa de cumplimiento | | GET | /goals/reports/by-user | Por usuario | | GET | /goals/reports/by-period | Por periodo | ## Frontend ### Paginas - `/goals` - Dashboard de metas - `/goals/new` - Crear meta - `/goals/:id` - Detalle de meta - `/goals/:id/assignments` - Asignaciones - `/goals/my` - Mis metas ### Componentes - `GoalsDashboard` - Overview con metricas - `GoalsList` - Lista de metas - `GoalForm` - Formulario de meta - `GoalCard` - Tarjeta de meta con progreso - `GoalProgress` - Barra/indicador de progreso - `AssignmentsList` - Lista de asignados - `AssignmentForm` - Formulario de asignacion - `ProgressUpdater` - Actualizar progreso manual - `ProgressChart` - Grafico de progreso temporal - `MilestoneTimeline` - Timeline de hitos - `GoalFilters` - Filtros por periodo/estado/categoria ### Hooks - `useGoals` - CRUD metas - `useAssignments` - CRUD asignaciones - `useMyGoals` - Metas del usuario actual - `useProgress` - Historial de progreso - `useGoalReports` - Reportes ## Integraciones ### Tracking Automatico ```typescript // Configuracion de fuente de datos interface SourceConfig { module: 'sales' | 'billing' | 'commissions'; entity: string; filter: Record; aggregation: 'sum' | 'count' | 'avg'; field: string; } // Ejemplo: Meta de ventas { module: 'sales', entity: 'opportunities', filter: { status: 'won' }, aggregation: 'sum', field: 'amount' } ``` ### Notificaciones ```typescript // Eventos de notificacion - goal.milestone_reached (25%, 50%, 75%, 100%) - goal.achieved - goal.at_risk (< 50% progreso en > 75% tiempo) - goal.failed ``` ## Dependencias ### Modulos Requeridos - SAAS-001 Auth - SAAS-002 Tenants - SAAS-003 Users - SAAS-007 Notifications ### Modulos Opcionales - SAAS-018 Sales (fuente de datos) - SAAS-004 Billing (fuente de datos) - SAAS-020 Commissions (bonos por cumplimiento) ## Criterios de Aceptacion 1. [ ] CRUD de metas con todos los tipos 2. [ ] Asignacion a usuarios y equipos 3. [ ] Tracking automatico funcional 4. [ ] Actualizacion manual de progreso 5. [ ] Notificaciones de hitos 6. [ ] Dashboard con progreso visual 7. [ ] Reportes de cumplimiento 8. [ ] Tests unitarios (>70% coverage) ## Estimacion | Componente | SP | |------------|-----| | DDL + Entities | 2 | | Backend Services | 4 | | Controllers + DTOs | 2 | | Frontend Pages | 3 | | Frontend Components | 2 | | Tests | 1 | | **Total** | **13** | --- **Ultima actualizacion:** 2026-01-24 **Autor:** Claude Opus 4.5