template-saas/docs/01-modulos/SAAS-022-goals.md
Adrian Flores Cortes 7d05081b4d
Some checks are pending
CI / Backend CI (push) Waiting to run
CI / Frontend CI (push) Waiting to run
CI / Security Scan (push) Waiting to run
CI / CI Summary (push) Blocked by required conditions
[SAAS-018-022] docs: Add specifications for advanced modules
Add complete specifications for 5 advanced modules:
- SAAS-018 Sales Foundation (21 SP) - Leads, opportunities, pipeline
- SAAS-019 Portfolio (13 SP) - Product/service catalog
- SAAS-020 Commissions (13 SP) - Commission system for salespeople
- SAAS-021 MLM (21 SP) - Multi-level marketing networks
- SAAS-022 Goals (13 SP) - Goals and objectives tracking

Each specification includes:
- Complete DDL with RLS policies
- Full API endpoint documentation
- Frontend pages and components
- Dependencies and integration points
- Story point estimates

Total new SP: 81 (bringing total to 260 SP)
Core modules: 14 (100% complete)
Advanced modules: 5 (specified, ready for implementation)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 20:12:07 -06:00

8.9 KiB

id title type status priority module version created_date updated_date estimated_sp
SAAS-022 Goals Module Specified P2 goals 1.0.0 2026-01-24 2026-01-24 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

-- 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

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

// Configuracion de fuente de datos
interface SourceConfig {
  module: 'sales' | 'billing' | 'commissions';
  entity: string;
  filter: Record<string, any>;
  aggregation: 'sum' | 'count' | 'avg';
  field: string;
}

// Ejemplo: Meta de ventas
{
  module: 'sales',
  entity: 'opportunities',
  filter: { status: 'won' },
  aggregation: 'sum',
  field: 'amount'
}

Notificaciones

// 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