Skip to content

Vulnerability Types#175

Merged
iTzGooDLife merged 30 commits intofeature/vulnerability-custom-datafrom
bugfix/remaining-fixes-vulnerability-types
Nov 13, 2024
Merged

Vulnerability Types#175
iTzGooDLife merged 30 commits intofeature/vulnerability-custom-datafrom
bugfix/remaining-fixes-vulnerability-types

Conversation

@iTzGooDLife
Copy link
Copy Markdown
Collaborator

@iTzGooDLife iTzGooDLife commented Nov 13, 2024

Descripción

Inicialmente la branch estaba destinada para arreglar algunos bugs, pero durante el desarrollo se terminó agregando bastante de la funcionalidad faltante en Vulnerability Type en Custom Data.
Cambios realizados:

  • Traducciones agregadas
  • Lógica de actualizar Draggable List cuando se añade un Vulnerability Type
  • Lógica de onCancel Edit Card
  • Actualizar elementos al editar vulnerability types
  • Actualizar items en Draggable List cuando se cambia idioma
  • Reducir el número de solicitudes realizadas

Motivación y Contexto

Se realiza para completar la funcionalidad requerida para la presentación del viernes (y apoyar al massi).

¿Cómo ha sido probado?

Para probar se debe:

  • Añadir Vulnerability types (ojalá con más de un lenguage)
  • Eliminar vulnerability type
  • Editar vulnerability Type
  • Ver como se modifican los items editables al cambiar de idioma
  • Ver como la lista vuelve al estado inicial al "cancelar" la edición
  • Todo lo anterior junto xd

Capturas de pantalla (si es apropiado):

No aplica

Tipos de cambios

  • Bugfix (cambio que no interrumpe el funcionamiento y que soluciona un problema)
  • New feature (cambio que no interrumpe el funcionamiento y que añade funcionalidad)
  • Breaking change (corrección o funcionalidad que podría causar que la funcionalidad existente cambie)

Lista de verificación:

  • Mi código sigue el estilo de código de este proyecto.
  • Mi cambio requiere una modificación en la documentación.
  • He actualizado la documentación en consecuencia.
  • Requiere nuevos tests.

Summary by CodeRabbit

  • Nuevas características

    • Se han añadido mensajes de éxito y error para la gestión de tipos de vulnerabilidad, mejorando la retroalimentación al usuario.
    • Se ha mejorado la capacidad de internacionalización en los componentes relacionados con tipos de vulnerabilidad.
    • Se ha actualizado la lógica de manejo de estado y efectos secundarios en el componente de tipos de vulnerabilidad.
  • Correcciones de errores

    • Se ha mejorado el manejo de errores en la creación de tipos de vulnerabilidad y campos personalizados, proporcionando mensajes de error más específicos.
  • Documentación

    • Se ha agregado un nuevo tipo VulnerabilityType para mejorar la seguridad de tipos en la gestión de vulnerabilidades.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 13, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

Este pull request introduce cambios significativos en varios componentes de la aplicación, principalmente relacionados con la gestión de tipos de vulnerabilidades y la internacionalización. Se añaden nuevos mensajes de éxito y error en el archivo de localización para inglés, se mejora la lógica de actualización en el componente VulnerabilityTypeList, y se refactoriza el componente VulnerabilityTypes para mejorar la gestión del estado y el manejo de errores. También se realizan ajustes en la lógica de manejo de errores en los servicios de creación de tipos de vulnerabilidades.

Changes

File Change Summary
frontend/src/i18n/en-US/index.ts Se añaden nuevos mensajes en las secciones msg y err relacionados con la creación y gestión de tipos de vulnerabilidades.
frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx Se agrega la función t para la internacionalización y se actualiza el texto del placeholder. Se simplifica la lógica de actualización de datos en useEffect.
frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx Se actualizan las rutas de importación, se define un nuevo tipo VulnerabilityType, se refactoriza la lógica de obtención de datos y se mejora el manejo de errores.
frontend/src/services/data.ts Se mejora el manejo de errores en las funciones createVulnerabilityType y addCustomField, proporcionando mensajes de error más específicos según la respuesta del servidor.

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • Icksir
  • jllanosg
  • massi-ponce
  • Sealra
  • caverav

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/frontend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "frontend/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (7)
frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx (1)

61-63: ¡Atención! Hay más texto que necesita traducción

Has traducido correctamente el placeholder, pero hay otros textos estáticos en el componente que también deberían traducirse, como el botón "X" para eliminar elementos.

Considera aplicar estas traducciones adicionales:

- <PrimaryButton color="red" onClick={() => handleRemoveRow(row.id)}>
-   X
- </PrimaryButton>
+ <PrimaryButton color="red" onClick={() => handleRemoveRow(row.id)}>
+   {t('remove')}
+ </PrimaryButton>
frontend/src/i18n/en-US/index.ts (1)

207-209: ¡Hay que mantener consistencia en los nombres de los mensajes de error!

Los mensajes de error son claros, pero deberíamos mantener un patrón consistente en los nombres de las claves.

Sugiero este cambio para mantener la consistencia con otros mensajes de error:

-    failedCreatingVulnerabilityType: 'Failed to create vulnerability type',
-    failedUpdatingVulnerabilityTypes: 'Failed to update vulnerability types',
+    errorCreatingVulnerabilityType: 'Failed to create vulnerability type',
+    errorUpdatingVulnerabilityTypes: 'Failed to update vulnerability types',
frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (5)

70-71: Agregue retroalimentación al usuario en caso de error al cargar los idiomas.

Actualmente, si ocurre un error al obtener los idiomas en fetchLanguages, solo se registra en la consola con console.error(err). Debería notificar al usuario utilizando toast.error u otro mecanismo para informar que no se pudieron cargar los idiomas.


95-95: Agregue manejo de errores para informar al usuario si falla la carga de tipos de vulnerabilidad.

En el bloque catch de fetchVulnerabilityTypes, simplemente se registra el error en la consola. Sería recomendable informar al usuario sobre el problema.


160-164: Elimine setNewVulnerabilityTypeList de las dependencias de useCallback.

Las funciones setter de useState son estables y no cambian entre renders, por lo que no es necesario incluirlas en las dependencias de useCallback.

Aplicar este cambio para limpiar las dependencias:

 const handleUpdateVulnerabilityType = useCallback(
   (data: { name: string; locale: string }[]) => {
     setNewVulnerabilityTypeList(data);
   },
-  [setNewVulnerabilityTypeList],
+  [],
 );

204-204: Simplifique el manejador onChange en SelectDropdown.

Puede pasar la función directamente sin necesidad de una función anónima intermedia.

Aplicar este cambio para simplificar el código:

 <SelectDropdown
   items={languages}
-  onChange={value => onChangeLanguage(value)}
+  onChange={onChangeLanguage}
   selected={currentLanguage}
   title={t('language')}
 />

234-238: Considere extraer el componente de cargando a un componente reutilizable.

El código para mostrar el estado de carga se repite. Sería beneficioso extraerlo en un componente separado para mejorar la reutilización y la legibilidad.

Por ejemplo:

// Crear un componente LoadingSpinner.jsx
const LoadingSpinner = () => (
  <div className="flex items-center justify-center h-min">
    <span className="flex">
      <ArrowPathIcon className="h-8 w-8 animate-spin text-blue-500" />
    </span>
  </div>
);

// Luego, utilizarlo en el código
{loadingVulnerabilityTypes ? (
  <LoadingSpinner />
) : (
  <VulnerabilityTypeList
    data={filteredVulnerabilityTypes}
    isDisabled={!isEditing}
    onUpdateList={handleUpdateVulnerabilityType}
  />
)}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e154ce3 and ff63eee.

📒 Files selected for processing (4)
  • frontend/src/i18n/en-US/index.ts (3 hunks)
  • frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx (3 hunks)
  • frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (5 hunks)
  • frontend/src/services/data.ts (2 hunks)
🔇 Additional comments (5)
frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx (1)

2-2: ¡Bien hecho con la implementación de i18next!

La importación de la función de traducción está correctamente implementada y se alinea con los objetivos de internacionalización del proyecto.

frontend/src/services/data.ts (1)

749-749: Cambio de formato, sin impacto funcional

frontend/src/i18n/en-US/index.ts (2)

165-166: ¡Los mensajes de éxito están bien implementados!

Los mensajes son claros y siguen el patrón de nomenclatura existente para mensajes de éxito.


741-741: ¡La nueva clave de traducción está correctamente implementada!

La clave vulnerabilityType sigue el patrón de nomenclatura existente y su valor es apropiado.

frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (1)

168-175: Verifique la lógica al combinar los tipos de vulnerabilidad actualizados.

Asegúrese de que al combinar newVulnerabilityTypeList con differentLanguageTypes, no se pierdan datos y los tipos de vulnerabilidad se actualicen correctamente.

Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx Outdated
Comment thread frontend/src/services/data.ts
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx Outdated
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (2)

189-194: ¡Optimiza el rendimiento con useCallback!

La función onClickCancel debería estar memoizada para evitar recreaciones innecesarias.

Aplica este cambio:

- const onClickCancel = () => {
+ const onClickCancel = useCallback(() => {
    setFilteredVulnerabilityTypes(
      vulnerabilityTypes.filter(type => type.locale === currentLanguage?.value),
    );
    setIsEditing(false);
- };
+ }, [vulnerabilityTypes, currentLanguage?.value]);

233-237: ¡Extrae el componente de carga!

El componente de carga debería estar separado para mejorar la reutilización y mantenibilidad.

Crea un nuevo componente:

const LoadingSpinner = () => (
  <div className="flex items-center justify-center h-min">
    <span className="flex">
      <ArrowPathIcon className="h-8 w-8 animate-spin text-blue-500" />
    </span>
  </div>
);

Y úsalo así:

- <div className="flex items-center justify-center h-min">
-   <span className="flex">
-     <ArrowPathIcon className="h-8 w-8 animate-spin text-blue-500" />
-   </span>
- </div>
+ <LoadingSpinner />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ff63eee and 0105d22.

📒 Files selected for processing (2)
  • frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx (3 hunks)
  • frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/routes/data/CustomData/VulnerabilityTypeList.tsx

Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx Outdated
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx Outdated
@iTzGooDLife iTzGooDLife requested a review from caverav November 13, 2024 02:25
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (1)

89-91: Uniformiza el uso de tipos en el filtro

En el método filter, estás tipando type como { locale: string }, pero deberías utilizar el tipo VulnerabilityType para mantener consistencia y aprovechar la definición del tipo.

Aplica este cambio:

setFilteredVulnerabilityTypes(
  types.filter(
-   (type: { locale: string }) =>
+   (type: VulnerabilityType) =>
      type.locale === languageSelected?.value,
  ),
);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0105d22 and c2b1d4e.

📒 Files selected for processing (1)
  • frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (4 hunks)
🔇 Additional comments (3)
frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx (3)

134-143: Elimina la duplicación de logs y mejora el manejo de errores

Este comentario ya fue realizado en una revisión anterior y sigue siendo válido.


69-71: El manejo de errores es insuficiente al cargar idiomas

Este comentario ya fue realizado en una revisión anterior y sigue siendo válido.


98-99: Corrige las dependencias del useCallback

Este comentario ya fue realizado en una revisión anterior y sigue siendo válido.

Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
Comment thread frontend/src/routes/data/CustomData/VulnerabilityTypes.tsx
@iTzGooDLife iTzGooDLife merged commit b618d8b into feature/vulnerability-custom-data Nov 13, 2024
@iTzGooDLife iTzGooDLife deleted the bugfix/remaining-fixes-vulnerability-types branch November 13, 2024 14:30
@iTzGooDLife iTzGooDLife restored the bugfix/remaining-fixes-vulnerability-types branch November 13, 2024 14:41
@iTzGooDLife iTzGooDLife deleted the bugfix/remaining-fixes-vulnerability-types branch November 27, 2024 13:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants