Reporting & KPIs
1. Feature Descripción General
The KPI system provides real-time visibility into operational efficiency, bottlenecks, and client satisfaction through 4-5 operational Métricas calculated from OrderHistory transactional data. Defined during Sprint 5-7 mesa de trabajo sessions, KPIs include: time from request to assignment, total order time (creation to closure), client approval rate, rejection rate, and optionally time to send quotation. The dashboard Funcionalidades visual cards with trend charts, configurable filters (date range, service type, location, provider), SLA alerts with color-coded indicators, and “Time Remaining” columns showing days until SLA breach for proActivo intervention.
2. Business Context
Algesta needed real-time visibility into operational efficiency to identify bottlenecks, track SLA compliance, and demonstrate Valor to clients. The previous manual reporting involved spreadsheet exports and periodic reviews, lacking real-time insights and proActivo alerting. The KPI dashboard enables data-driven decision-making, proActivo issue resolution, and transparent performance reporting to stakeholders.
3. KPI Definitions
KPI 1: Time from Request to Assignment
Definition: Average days from order creation (state: Creada) to provider assignment (state: ProveedorSeleccionado)
Calculation:
SELECT AVG( DATEDIFF( (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'ProveedorSeleccionado'), (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'Creada') )) AS avgDaysToAssignmentFROM Order oWHERE o.createdAt BETWEEN :startDate AND :endDateSLA Threshold: ≤ 3 days Alert Levels:
- 🟢 Green: ≤ 2 days
- 🟡 Yellow: 2-3 days
- 🔴 Red: > 3 days
Propósito: Measure marketplace efficiency and agent responsiveness
KPI 2: Total Order Time
Definition: Average days from order creation (state: Creada) to order closure (state: Cerrada)
Calculation:
SELECT AVG( DATEDIFF( (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'Cerrada'), (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'Creada') )) AS avgTotalOrderTimeFROM Order oWHERE o.state = 'Cerrada' AND o.closureDate BETWEEN :startDate AND :endDateSLA Threshold: ≤ 15 days (corrective), ≤ 10 days (preventive) Alert Levels:
- 🟢 Green: ≤ 10 days
- 🟡 Yellow: 10-15 days
- 🔴 Red: > 15 days
Propósito: Measure end-to-end service delivery efficiency
KPI 3: Client Approval Rate
Definition: Percentage of orders approved by client on first submission (no rework)
Calculation:
SELECT ( COUNT(CASE WHEN o.rejectionCount = 0 THEN 1 END) * 100.0 / COUNT(*)) AS approvalRateFROM Order oWHERE o.state IN ('TrabajoAprobado', 'Cerrada') AND o.approvalDate BETWEEN :startDate AND :endDateTarget: ≥ 90% Alert Levels:
- 🟢 Green: ≥ 90%
- 🟡 Yellow: 80-90%
- 🔴 Red: < 80%
Propósito: Measure service quality and client satisfaction
KPI 4: Rejection Rate
Definition: Percentage of orders rejected by client or requiring rework
Calculation:
SELECT ( COUNT(CASE WHEN o.rejectionCount > 0 THEN 1 END) * 100.0 / COUNT(*)) AS rejectionRateFROM Order oWHERE o.state IN ('TrabajoAprobado', 'Retrabajo', 'Cerrada') AND o.approvalDate BETWEEN :startDate AND :endDateTarget: ≤ 10% Alert Levels:
- 🟢 Green: ≤ 10%
- 🟡 Yellow: 10-15%
- 🔴 Red: > 15%
Propósito: Identify quality issues and provider performance problems
KPI 5 (Optional): Time to Send Quotation
Definition: Average days from provider selection (state: ProveedorSeleccionado) to quotation sent (state: CotizacionEnviada)
Calculation:
SELECT AVG( DATEDIFF( (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'CotizacionEnviada'), (SELECT timestamp FROM OrderHistory WHERE orderId = o._id AND newState = 'ProveedorSeleccionado') )) AS avgDaysToQuotationFROM Order oWHERE o.state IN ('CotizacionEnviada', 'CotizacionAprobada', 'TrabajoIniciado', 'Cerrada') AND o.createdAt BETWEEN :startDate AND :endDateSLA Threshold: ≤ 2 days Alert Levels:
- 🟢 Green: ≤ 1 day
- 🟡 Yellow: 1-2 days
- 🔴 Red: > 2 days
Propósito: Measure provider responsiveness after selection
4. Dashboard Layout
Visual Design
┌─────────────────────────────────────────────────────────────────┐│ KPI Dashboard [Date Filter] │├─────────────────────────────────────────────────────────────────┤│ ││ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ││ │ Time to │ │ Total Order │ │ Client │ ││ │ Assignment │ │ Time │ │ Approval Rate│ ││ │ │ │ │ │ │ ││ │ 2.5 days │ │ 12.3 days │ │ 92% │ ││ │ 🟢 │ │ 🟡 │ │ 🟢 │ ││ │ │ │ │ │ │ ││ │ [Chart] │ │ [Chart] │ │ [Chart] │ ││ └──────────────┘ └──────────────┘ └──────────────┘ ││ ││ ┌──────────────┐ ┌──────────────┐ ││ │ Rejection │ │ Time to │ ││ │ Rate │ │ Quotation │ ││ │ │ │ │ ││ │ 8% │ │ 1.8 days │ ││ │ 🟢 │ │ 🟢 │ ││ │ │ │ │ ││ │ [Chart] │ │ [Chart] │ ││ └──────────────┘ └──────────────┘ ││ │├─────────────────────────────────────────────────────────────────┤│ Orders at Risk (SLA Breach Imminent) │├─────────────────────────────────────────────────────────────────┤│ | Order # | Client | State | Time Remaining | Alert | ││ |---------|--------|-------|----------------|-------| ││ | ORD-001 | ACME | Rev. | 1 day | 🔴 | ││ | ORD-002 | XYZ | Cot. | 2 days | 🟡 | ││ | ORD-003 | ABC | Trab. | 5 days | 🟢 | │└─────────────────────────────────────────────────────────────────┘5. User Stories by Sprint
Sprint 7: KPI Design and Placeholders
US-S7-030: KPI Dashboard Design
- Descripción: As an agent, I want to see a KPI dashboard to monitor operational performance
- Acceptance Criteria:
- Dashboard with 4-5 KPI cards
- Visual indicators (color-coded: green/yellow/red)
- Trend charts showing KPI evolution over time
- Filter by date range
- Filter by service type, location, provider
- Estado: ✅ Completo
- Implementación:
algesta-dashboard-react/src/Funcionalidades/kpis/- KPI dashboard UI
- Sprint: S7
US-S7-031: SLA Configuration
- Descripción: As an admin, I want to configure SLA thresholds for KPI alerts
- Acceptance Criteria:
- Admin panel to set thresholds per KPI
- Thresholds: green, yellow, red levels
- Different thresholds per service type (if needed)
- Changes apply immediately to dashboard
- Estado: 🟡 En Progreso (basic thresholds hardcoded, admin UI Pendiente)
- Sprint: S7-S8
Sprint 8: Functional KPIs with Data
US-S8-040: KPI Calculation with Real Data
- Descripción: As a system, I want to calculate KPIs from OrderHistory transactional data
- Acceptance Criteria:
- KPIs calculated from OrderHistory table
- Calculations run on dashboard load or scheduled refresh
- Cache results for performance (refresh every 5-10 minutes)
- Show last update timestamp
- Estado: 🟡 Partial (client-side aggregation implemented, dedicated API Pendiente)
- Implementación:
algesta-ms-orders-nestjs/src/application/handlers/queries/orders/get-orders-counter.handler.ts- Order counters (implemented)- Dashboard performs client-side KPI calculations from counter data
- Dedicated server-side KPI calculation service planned for future phases
- API:
GET /api/orders/counter- Get order counts by state (✅ Implemented)GET /api/orders/kpis?from=DATE&to=DATE- Get KPI Métricas (🟡 Planned)
- Sprint: S8
US-S8-041: “Time Remaining” Column
- Descripción: As an agent, I want to see “time remaining” for orders at risk of SLA breach
- Acceptance Criteria:
- Table below KPI cards showing orders with time remaining
- Calculate: SLA threshold - current time in state
- Color-coded: green (> 5 days), yellow (2-5 days), red (< 2 days)
- Sort by time remaining (ascending)
- Click order to view details
- Estado: ✅ Completo
- Sprint: S8
6. KPI Calculation Logic
Data Source: OrderHistory
All KPI calculations use OrderHistory table for accuracy and auditability:
// Example: Calculate Time to Assignmentasync function calculateTimeToAssignment(startDate: Date, endDate: Date): Promise<number> { const orders = await orderRepository.find({ createdAt: { $gte: startDate, $lte: endDate }, state: { $in: ['ProveedorSeleccionado', 'CotizacionEnviada', 'TrabajoIniciado', 'Cerrada'] } });
const times = await Promise.all(orders.map(async (order) => { const createdEvent = await orderHistoryRepository.findOne({ orderId: order._id, newState: 'Creada' });
const assignedEvent = await orderHistoryRepository.findOne({ orderId: order._id, newState: 'ProveedorSeleccionado' });
if (!createdEvent || !assignedEvent) return null;
const diffMs = assignedEvent.timestamp.getTime() - createdEvent.timestamp.getTime(); const diffDays = diffMs / (1000 * 60 * 60 * 24); return diffDays; }));
const validTimes = times.filter(t => t !== null); const average = validTimes.reduce((sum, t) => sum + t, 0) / validTimes.length; return average;}7. SLA Configuration
Configurable Thresholds
| KPI | Green | Yellow | Red | Unit |
|---|---|---|---|---|
| Time to Assignment | ≤ 2 | 2-3 | > 3 | days |
| Total Order Time | ≤ 10 | 10-15 | > 15 | days |
| Client Approval Rate | ≥ 90 | 80-90 | < 80 | % |
| Rejection Rate | ≤ 10 | 10-15 | > 15 | % |
| Time to Quotation | ≤ 1 | 1-2 | > 2 | days |
Note: Thresholds are editable by Algesta admin for flexibility per client or service type.
8. API Endpoints Resumen
| Endpoint | Método | Description | Actor | Sprint | Status |
|---|---|---|---|---|---|
/api/orders/kpis | GET | Get KPI Métricas with filters | Agent | S8 | 🟡 Planned (not yet implemented) |
/api/orders/counter | GET | Get order counts by state | Agent | S5 | ✅ Implemented |
/api/orders/at-risk | GET | Get orders at risk of SLA breach | Agent | S8 | 🟡 Planned (not yet implemented) |
/api/admin/sla-thresholds | GET | Get SLA thresholds | Admin | S7 | 🟡 Planned (not yet implemented) |
/api/admin/sla-thresholds | PUT | Update SLA thresholds | Admin | S7 | 🟡 Planned (not yet implemented) |
Current Implementación:
- KPI data is currently surfaced via
/api/orders/counterwhich provides order counts by state - Dashboard performs client-side aggregation and calculations for KPI visualization
- The dedicated
/api/orders/kpisEndpoint and related Endpoints above are planned for future phases to provide server-side KPI calculation and caching
Reference: algesta-ms-orders-nestjs/src/application/handlers/queries/orders/get-orders-counter.handler.ts
9. Integration Points
- Orders Service: KPI data source (OrderHistory, Order)
- Dashboard: KPI visualization, filters, alerts
10. Pruebas Evidence
From Pruebas notes:
- Sprint 7-8: KPI dashboard tested with sample data
- All KPIs calculate correctly with edge cases validated
- SLA alerts trigger correctly based on thresholds
11. Known Issues and Future Enhancements
🟨 Essential Improvements
- KPI Calculation Refinements: Validate criteria with client, adjust formulas if needed
- Admin UI for SLA Configuration: Completo admin panel for threshold editing
- Real-time KPI Updates: WebSockets for live KPI updates (currently refresh-based)
🟩 Post-MVP Operaciones
- Advanced Reports by Location/Category/Provider: Drill-down analysis
- Export to Excel/PDF: KPI reports for stakeholder distribution
- Predictive Analytics: ML model to predict SLA breaches before they occur
- Historical Comparison: Compare KPIs month-over-month, year-over-year
🟦 Future Backlog
- Custom KPI Builder: Allow clients to define their own KPIs
- KPI Benchmarking: Compare against industry standards or other clients (anonymized)
- Automated Alerting: Email/WhatsApp alerts when KPIs breach thresholds
12. Referencias Cruzadas
Sprint Documentoation
Sprint 7-8 Documentoation - see docs/Sprint_7.md and Sprint_8.md in project Repositorio
Last Updated: 2025-11-20 | Next Review: End of Guarantee Phase