✨ feat: Add percentage to charts#172
Conversation
…nd display percentage values on SeverityPieChart.
…ith empty formatter for datalabels
|
Warning Rate limit exceeded@caverav has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 30 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 Walkthrough📝 Walkthrough📝 Walkthrough📝 Walkthrough📝 WalkthroughWalkthroughSe ha actualizado el archivo Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Frontend
participant ChartLibrary
User->>Frontend: Solicita gráfico
Frontend->>ChartLibrary: Configura gráfico con datalabels
ChartLibrary-->>Frontend: Devuelve gráfico configurado
Frontend-->>User: Muestra gráfico
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Outside diff range and nitpick comments (4)
frontend/src/components/charts/RemediationPriorityChart.tsx (2)
Line range hint
1-15: ¡El plugin de datalabels no está registrado!Es necesario registrar el plugin de datalabels con ChartJS para que funcione correctamente. Debes importarlo y registrarlo junto con los demás plugins.
Aplica este cambio:
import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip, } from 'chart.js'; + import ChartDataLabels from 'chartjs-plugin-datalabels'; import { t } from 'i18next'; import React from 'react'; import { Bar } from 'react-chartjs-2'; ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, + ChartDataLabels );
Line range hint
19-23: Mejora la tipificación de los datosLa interfaz PriorityData podría beneficiarse de una mejor definición de tipos para garantizar la integridad de los datos.
Considera esta mejora:
type PriorityData = { - name: string; - count: number; - color: string; + name: string; + count: number; + color: `#${string}` | string; // Permite colores hexadecimales o nombres de colores CSS };frontend/src/components/charts/CVSSChart.tsx (2)
Line range hint
1-116: ¡El tipado puede mejorarse significativamente!El componente necesita mejoras en sus definiciones de tipos:
- Las opciones del gráfico deberían estar tipadas:
import { ChartOptions } from 'chart.js'; const options: ChartOptions<'bar'> = { // ... configuración actual };
- Los datos del gráfico también deberían tener un tipo explícito:
import { ChartData } from 'chart.js'; const chartData: ChartData<'bar'> = { // ... datos actuales };Estos cambios proporcionarán:
- Mejor autocompletado en el IDE
- Detección temprana de errores
- Documentación más clara
Line range hint
1-116: ¡Considera extraer la lógica de colores a una función utilitaria!La lógica para determinar los colores basados en la puntuación CVSS debería estar en una función separada para mejorar la mantenibilidad y reusabilidad.
const getCVSSColor = (score: number): string => { if (score >= 9.0) return '#dc3545'; if (score >= 7.0) return '#fd7e14'; if (score >= 4.0) return '#ffc107'; if (score >= 0.1) return '#28a745'; return '#6c757d'; };Esto haría el código más limpio y permitiría reutilizar la lógica de colores en otros componentes si fuera necesario.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
frontend/package.json(1 hunks)frontend/src/components/charts/CIATriadChart.tsx(1 hunks)frontend/src/components/charts/CVSSChart.tsx(1 hunks)frontend/src/components/charts/RemediationPriorityChart.tsx(1 hunks)frontend/src/components/charts/SeverityPieChart.tsx(2 hunks)frontend/src/components/charts/TimePerAuditChart.tsx(3 hunks)
🔇 Additional comments (4)
frontend/src/components/charts/SeverityPieChart.tsx (1)
1-8: ¡La importación y registro del plugin están correctos!
La integración del plugin ChartDataLabels se ha realizado adecuadamente.
frontend/src/components/charts/CIATriadChart.tsx (1)
100-102: Verificar la implementación en otros componentes de gráficos
Es necesario verificar si este patrón de deshabilitar las etiquetas de datos se repite en otros componentes de gráficos, ya que podría indicar un problema más amplio en la implementación.
✅ Verification successful
El patrón de deshabilitar etiquetas es consistente y justificado
La implementación actual es coherente en todo el código base:
CIATriadChart.tsx,CVSSChart.tsxyRemediationPriorityChart.tsxdeshabilitan las etiquetas de datos retornando una cadena vacíaSeverityPieChart.tsxyTimePerAuditChart.tsxtienen implementaciones personalizadas del formateador para mostrar datos específicos
Este patrón no representa un problema arquitectónico, sino una decisión de diseño deliberada donde las etiquetas se muestran selectivamente según el tipo de gráfico.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Buscar patrones similares en otros componentes de gráficos
echo "Buscando implementaciones similares en otros componentes:"
rg -A 3 "datalabels.*formatter.*=>" frontend/src/components/charts/
Length of output: 194
Script:
#!/bin/bash
# Buscar todos los archivos de gráficos
echo "Archivos de gráficos encontrados:"
fd ".*Chart\.tsx$" frontend/src/components/charts/
# Buscar patrones de configuración de datalabels
echo -e "\nBuscando configuraciones de datalabels:"
rg -U "datalabels:.*\{[\s\S]+?\}" frontend/src/components/charts/
# Buscar cualquier uso de formatter en los archivos
echo -e "\nBuscando otros usos de formatter:"
rg "formatter" frontend/src/components/charts/
Length of output: 3449
frontend/src/components/charts/TimePerAuditChart.tsx (1)
3-3: ¡Las importaciones y el registro del plugin son correctos!
La integración del plugin ChartDataLabels y los tipos necesarios está bien implementada.
Also applies to: 8-8, 12-12, 24-24
frontend/package.json (1)
35-35: ¡Verificar la compatibilidad con chart.js!
La nueva dependencia chartjs-plugin-datalabels@^2.2.0 se ha añadido correctamente, pero es crucial verificar su compatibilidad con la versión actual de chart.js (^4.4.4).
✅ Verification successful
¡La compatibilidad está confirmada y todo está en orden!
La versión de chart.js (^4.4.4) es totalmente compatible con chartjs-plugin-datalabels ^2.2.0. El plugin está siendo utilizado correctamente en:
frontend/src/components/charts/TimePerAuditChart.tsxfrontend/src/components/charts/SeverityPieChart.tsx
La implementación es correcta y las importaciones están bien estructuradas. No hay ningún problema de compatibilidad o integración que reportar.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Descripción: Verificar la compatibilidad de versiones y buscar vulnerabilidades conocidas
# Verificar la compatibilidad de versiones en el README del plugin
curl -s https://raw.githubusercontent.com/chartjs/chartjs-plugin-datalabels/master/README.md | grep -A 5 "Compatibility"
# Buscar vulnerabilidades conocidas
npm audit chartjs-plugin-datalabels@2.2.0 || true
Length of output: 520
Script:
#!/bin/bash
# Buscar en el package.json la versión de chart.js
cat frontend/package.json | jq -r '.dependencies["chart.js"]'
# Buscar archivos que usen el plugin de datalabels
rg -l "chartjs-plugin-datalabels" --type js --type ts
# Buscar importaciones específicas del plugin
ast-grep --pattern 'import $_ from "chartjs-plugin-datalabels"'
# Buscar registros del plugin
rg "plugin.*datalabel" -A 2 -B 2
Length of output: 1445
…onents to handle edge cases and improve readability
…y string in CIATriad component.
…rageCVSS component
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Outside diff range and nitpick comments (7)
frontend/src/components/dashboard/RemediationPriority.tsx (3)
Line range hint
1-8: ¡El registro del plugin datalabels está ausente!Es necesario importar y registrar el plugin de datalabels para que funcione correctamente:
import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip, + ChartDataLabels, } from 'chart.js'; +import 'chartjs-plugin-datalabels';
Line range hint
12-22: ¡Falta registrar el plugin en ChartJS!Después de importar el plugin, es necesario registrarlo:
ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, + ChartDataLabels );
Line range hint
65-75: ¡Mejora la visualización de los datos!Para mejorar la presentación visual del gráfico, sugiero ajustar los colores para que sean más accesibles y consistentes con el tema oscuro:
datasets: [ { data: priorityData, - backgroundColor: ['#2ECC40', '#FFDC00', '#FF851B', '#FF4136'], + backgroundColor: ['#4CAF50', '#FFC107', '#FF9800', '#F44336'], + borderRadius: 6, + borderSkipped: false, }, ],frontend/src/components/dashboard/RemediationComplexity.tsx (1)
Line range hint
1-8: Falta registrar el plugin de datalabelsEs necesario importar y registrar el plugin para que funcione correctamente.
Agrega estas modificaciones:
import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip, + Chart, } from 'chart.js'; +import ChartDataLabels from 'chartjs-plugin-datalabels'; +Chart.register(ChartDataLabels);frontend/src/components/dashboard/CIATriad.tsx (1)
Line range hint
52-67: ¡La generación de colores necesita una mejor implementación!El código actual tiene varios problemas:
- Duplicación de la lógica de generación de colores
- Posible generación de colores muy similares
- Falta de reutilización del código
Te propongo extraer la lógica a una función de utilidad:
// Agregar al archivo utils.ts export const generateChartColor = (index: number) => { const predefinedColors = [ { r: 255, g: 99, b: 132 }, { r: 54, g: 162, b: 235 }, { r: 255, g: 206, b: 86 }, { r: 75, g: 192, b: 192 }, // Añadir más colores según necesidad ]; const color = predefinedColors[index % predefinedColors.length]; return { backgroundColor: `rgba(${color.r}, ${color.g}, ${color.b}, 0.2)`, borderColor: 'rgba(255, 255, 255, 0.2)' }; };Y luego simplificar el código del componente:
- backgroundColor: `rgba(${Math.floor(Math.random() * 155 + 100)}, ${Math.floor(Math.random() * 155 + 100)}, ${Math.floor(Math.random() * 155 + 100)}, 0.2)`, - borderColor: 'rgba(255, 255, 255, 0.2)', + ...generateChartColor(index),Esta solución:
- Elimina la duplicación de código
- Garantiza colores visualmente distintos
- Mejora la mantenibilidad
frontend/src/components/dashboard/AverageCVSS.tsx (2)
Line range hint
41-163: ¡El código necesita varias mejoras críticas!
- La lógica de colores usando operadores ternarios anidados es difícil de mantener y propensa a errores.
- El manejo de errores solo registra en consola, lo cual no es suficiente para una aplicación en producción.
- Los cálculos dentro de useEffect podrían optimizarse.
Sugiero las siguientes mejoras:
- Extraer la lógica de colores a una función utilitaria:
const getCVSSColor = (score: number): string => { if (score >= 9) return '#FF4136'; if (score >= 7) return '#FF851B'; if (score >= 4) return '#FFDC00'; return '#2ECC40'; };
- Mejorar el manejo de errores:
.catch((error) => { console.error('Error al cargar datos del audit:', error); setData({ labels: ['Error al cargar datos'], datasets: [{ data: [0], backgroundColor: '#FF4136' }] }); // Aquí deberías agregar notificación al usuario });
- Optimizar los cálculos:
const calculateAverageCVSS = (findings: Finding[]): number => { const sum = findings.reduce((acc, finding) => acc + cvssStringToScore(finding.cvssv3 ?? ''), 0); return Math.round((sum / findings.length) * 10) / 10; };
Line range hint
1-40: ¡Las importaciones necesitan organización y tipado más estricto!La estructura actual de las importaciones podría mejorarse, y faltan algunos tipos importantes.
Sugiero:
- Agregar tipos para los datos:
interface Finding { title: string; cvssv3: string | null; } interface ChartData { labels: string[]; datasets: { data: number[]; backgroundColor: string; }[]; }
- Organizar las importaciones por grupos (externos, internos, tipos).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
frontend/src/components/dashboard/AverageCVSS.tsx(1 hunks)frontend/src/components/dashboard/CIATriad.tsx(1 hunks)frontend/src/components/dashboard/CVSSScore.tsx(1 hunks)frontend/src/components/dashboard/RemediationComplexity.tsx(1 hunks)frontend/src/components/dashboard/RemediationPriority.tsx(1 hunks)
Descripción
Se ha añadido la dependencia
chartjs-plugin-datalabelsy se ha integrado en varios componentes de gráficos (CIATriadChart,CVSSChart,RemediationPriorityChart,SeverityPieChart,TimePerAuditChart). Se ha configurado el plugin para que formatee las etiquetas de datos según los requisitos específicos de cada gráfico.Motivación y Contexto
Este cambio es necesario para mejorar la visualización de los datos en los gráficos, proporcionando etiquetas de datos personalizadas que muestran porcentajes y otros formatos específicos. Esto soluciona el problema de la falta de claridad en la representación de los datos en los gráficos.
¿Cómo ha sido probado?
Verificar que se muestren los porcentajes
Tipos de cambios
Lista de verificación:
Summary by CodeRabbit
Nuevas Funciones
Mejoras