Skip to content

Set Default Value for Audit Type and Fix Language Value on Audit Creation#166

Merged
caverav merged 4 commits intodevelopmentfrom
bugfix/language-create-audit
Nov 12, 2024
Merged

Set Default Value for Audit Type and Fix Language Value on Audit Creation#166
caverav merged 4 commits intodevelopmentfrom
bugfix/language-create-audit

Conversation

@iTzGooDLife
Copy link
Copy Markdown
Collaborator

@iTzGooDLife iTzGooDLife commented Nov 6, 2024

Descripción

Se realizan dos cambios:

  • Se agrega un valor por defecto en el tipo de auditoria (default), se puede ver el antes y después en las capturas de pantalla.
  • En el modal para agregar auditorias se agrega el campo "value" en el lenguaje y el anterior "value" queda como label.

Motivación y Contexto

El primer cambio es más que nada visual, ya que visualmente da la idea de que es opcional el seleccionar uno, cuando en realidad si no se selecciona uno, por defecto es "Default".

El segundo cambio arregla un bug existe en la app, ya que anteriormente se enviaba al backend el campo "language", y este no se reconocia en el dropdown al editar el audit, aunque los campos "auditType" y "language" tuvieran valores (si, pasaba a llevar a auditType). Con este cambio al agregar auditorias y posteriormente editarlas, aparecen los campos correspondientes.

Importante: Este cambio ayuda a las secciones de findings, debido a que anteriormente al agregar un finding se hacia utilizando el campo "language" y no "locale" de los lenguajes.

¿Cómo ha sido probado?

Para probar se debe añadir una auditoria con los campos necesarios y posteriormente ir a la edición de esta, se verá como se rellenan los dropdown correspondientes.

Capturas de pantalla (si es apropiado):

Valor por defecto

Antes:
image

Ahora:
image

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 Funciones

    • Se ha preseleccionado una opción en el grupo de botones de radio en el componente de auditorías.
    • Se ha mejorado la estructura de los datos de idiomas en el menú desplegable, diferenciando claramente entre la etiqueta mostrada y el valor subyacente.
  • Mejoras

    • Se han implementado notificaciones emergentes para mostrar mensajes de error durante la creación de auditorías.
    • Se ha ajustado el manejo del estado de carga para evitar que el indicador de carga permanezca activo indefinidamente en caso de error.
    • Se restablece el valor seleccionado al cancelar el nuevo formulario de auditoría, manteniendo la consistencia en la gestión del estado.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 6, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

Este pull request introduce varias modificaciones en el componente Audits ubicado en frontend/src/routes/audits/audits.tsx. Se actualiza la inicialización de la variable de estado selectedValue, estableciendo un valor predeterminado de '1'. Además, se modifica el mapeo de los datos de idioma, cambiando la propiedad value a item.locale y añadiendo una nueva propiedad label. También se mejora el manejo de errores en la función handleSubmitNewAudit, mostrando mensajes de error mediante notificaciones toast. Finalmente, se asegura que el estado de carga de idiomas se establezca en falso incluso si ocurre un error durante la carga.

Changes

Archivos Resumen de cambios
frontend/src/routes/audits/audits.tsx - Inicialización de selectedValue a '1'.
- Modificación de mapeo de datos de idioma (value y label).
- Mejora en el manejo de errores en handleSubmitNewAudit con notificaciones toast.
- Actualización de fetchData para manejar el estado de carga en caso de error.

Possibly related PRs

  • feat: Add remediationComplexity and priority props to audits services #138: Las modificaciones en este PR implican cambios en el tipo Finding y la función addVuln, que pueden relacionarse con la funcionalidad general de auditoría que se está mejorando en el PR principal, particularmente en cómo se gestionan las auditorías y los hallazgos.
  • hotfix: audit save translation #152: Este PR actualiza las notificaciones toast para mensajes de éxito y error durante el proceso de guardado de auditorías, lo que se alinea con el enfoque del PR principal sobre el manejo de errores y la retroalimentación del usuario en la función handleSubmitNewAudit.
  • Export dashboard as CSV #159: Este PR introduce funcionalidad para exportar datos del panel de control, lo que puede conectar con la gestión general de auditorías y las mejoras en la interfaz de usuario discutidas en el PR principal, especialmente en términos de interacción del usuario y manejo de datos.

Suggested labels

enhancement

Suggested reviewers

  • caverav
  • massi-ponce
  • Icksir
  • Sealra

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 84ce497 and b11d079.

📒 Files selected for processing (1)
  • frontend/src/routes/audits/audits.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/routes/audits/audits.tsx

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

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

Line range hint 251-267: ¡El manejo de errores necesita mejoras urgentes!

El manejo de errores en handleSubmitNewAudit tiene varias deficiencias:

  1. El mensaje "TODO: Show error" no se ha implementado
  2. El catch interno solo muestra el error en toast, pero el catch externo lo ignora
  3. No hay validación del formato de los valores antes de enviarlos

Te propongo esta mejora:

  const handleSubmitNewAudit = async () => {
    if (!currentAuditType || !currentLanguage) {
-     return; // TODO: Show error
+     toast.error(t('err.missingRequiredFields'));
+     return;
    }

    try {
-     await createAudit({
+     const response = await createAudit({
        name: nameAudit,
        auditType: currentAuditType.value,
        language: currentLanguage.value,
        type: selectedValue,
-     }).catch(error => {
-       toast.error(error.message);
-     });
+     });
+     
+     if (response.status === 'success') {
        setCurrentAuditType(null);
        setCurrentLanguage(null);
        setSelectedValue('1');
        setNameAudit('');
        void fetchAndUpdateData();
        setIsOpenNewAuditModal(false);
+     }
    } catch (error) {
-     console.error('Error:', error);
+     toast.error(t('err.failedCreateAudit'));
+     console.error('Failed to create audit:', error);
    }
-   setIsOpenNewAuditModal(!isOpenNewAuditModal);
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1a1ef20 and 84ce497.

📒 Files selected for processing (1)
  • frontend/src/routes/audits/audits.tsx (2 hunks)
🔇 Additional comments (1)
frontend/src/routes/audits/audits.tsx (1)

205-206: ¡Correcto uso de locale como valor interno!

La modificación para usar locale como valor interno y language como etiqueta visual es apropiada. Sin embargo, falta validación de tipos para asegurar que los valores sean correctos.

Ejecutemos una verificación de los tipos:

Comment thread frontend/src/routes/audits/audits.tsx
Copy link
Copy Markdown
Collaborator

@sealra sealra left a comment

Choose a reason for hiding this comment

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

lgtm

@caverav caverav merged commit 34ee97d into development Nov 12, 2024
@iTzGooDLife iTzGooDLife deleted the bugfix/language-create-audit branch November 13, 2024 14:46
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.

3 participants