Skip to content

Solución filtro de language en Custom Sections de Audits#176

Merged
caverav merged 2 commits intodevelopmentfrom
hotfix/audit-custom-section
Nov 15, 2024
Merged

Solución filtro de language en Custom Sections de Audits#176
caverav merged 2 commits intodevelopmentfrom
hotfix/audit-custom-section

Conversation

@Sealra
Copy link
Copy Markdown
Collaborator

@Sealra Sealra commented Nov 13, 2024

Descripción

Cambia el match de label a value, para hacerlo correctamente.

Motivación y Contexto

Soluciona Issue #156

¿Cómo ha sido probado?

npm run build

  1. Crear un customSection
  2. Crear un customField con la opción Audit Section
  3. Crear un AuditType con los customSection creados
  4. Crear un Audit con aquel AuditType
  5. Verificar que el Audit tenga un language (deberia tener uno por defecto)
  6. Ver que renderice el customField dentro del customSection

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

  • Mejoras

    • Se ha mejorado la lógica para la coincidencia del idioma de la auditoría con la lista de idiomas, haciendo que la identificación del idioma actual sea más precisa.
  • Corrección de errores

    • Se mantiene la gestión de errores en funciones asíncronas, con notificaciones de éxito y error durante la operación de guardado.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 13, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

El cambio principal en esta solicitud de extracción se centra en la lógica de comparación para la selección del idioma de auditoría. Se modificó el useEffect para que ahora compare la propiedad value del objeto de idioma en lugar de la propiedad label. Esto afecta cómo se identifica el idioma actual según la configuración del idioma de la auditoría. Aunque la estructura general del componente se mantiene, la lógica de manejo de errores y la gestión del estado continúan siendo consistentes.

Changes

Archivo Resumen de cambios
frontend/src/routes/audits/edit/sections/sections.tsx Modificación en la lógica del useEffect para comparar la propiedad value en lugar de label para el idioma actual. Mantenimiento de la estructura del componente y la lógica de manejo de errores.

Possibly related PRs

Suggested reviewers

  • Icksir
  • jllanosg
  • massi-ponce
  • caverav

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.

@Sealra Sealra changed the title fix: change label to value hotifx/audit-custom-section Nov 13, 2024
@Sealra Sealra changed the title hotifx/audit-custom-section hotfix/audit-custom-section Nov 13, 2024
@Sealra Sealra changed the title hotfix/audit-custom-section bugfix/audit-custom-section Nov 13, 2024
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: 0

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

Line range hint 145-149: ¡El cambio de propiedad de comparación es correcto, pero falta manejo de errores!

La modificación para usar value en lugar de label es la solución correcta, ya que auditLanguage almacena el código de localización y no el nombre mostrado del idioma. Sin embargo, el código actual no maneja adecuadamente el caso donde no se encuentra una coincidencia.

Te sugiero implementar un manejo más robusto:

  useEffect(() => {
    if (auditLanguage && languagesList.length > 0) {
      const matchedLanguage = languagesList.find(
        language => language.value === auditLanguage,
      );
      if (matchedLanguage) {
        setCurrentLanguage(matchedLanguage);
+     } else {
+       console.error(`No se encontró el idioma: ${auditLanguage}`);
+       toast.error(t('err.languageNotFound'));
+       // Usar un idioma por defecto o manejar el error según la lógica de negocio
      }
    }
  }, [auditLanguage, languagesList]);

Line range hint 42-149: ¡La gestión de estado y efectos necesita optimización!

El componente presenta varios puntos que requieren atención:

  1. Hay demasiados efectos interdependientes que podrían consolidarse
  2. El manejo de errores es inconsistente: algunos lugares usan toast.error y otros solo console.error
  3. La dependencia de fetchAuditSections con currentLanguage podría causar renders innecesarios

Recomendaciones de mejora:

  1. Consolida los efectos relacionados con la carga inicial:
useEffect(() => {
  const initializeData = async () => {
    try {
      const [languages, audit] = await Promise.all([
        getLanguages(),
        getAuditById(auditId)
      ]);
      
      const languageNames = languages.datas.map((item: LanguageData, index: number) => ({
        id: index,
        value: item.locale,
        label: item.language,
      }));
      
      setLanguagesList(languageNames);
      setAuditLanguage(audit.datas.language);
    } catch (error) {
      console.error('Error en la inicialización:', error);
      toast.error(t('err.initializationError'));
    }
  };

  void initializeData();
}, [auditId]);
  1. Implementa un hook personalizado para manejar los errores de manera consistente:
const useErrorHandler = () => {
  return useCallback((error: Error, message: string) => {
    console.error(error);
    toast.error(t(message));
  }, [t]);
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 34ee97d and 0843527.

📒 Files selected for processing (1)
  • frontend/src/routes/audits/edit/sections/sections.tsx (1 hunks)

@jllanosg
Copy link
Copy Markdown
Collaborator

  1. El nombre del PR está mal
  2. Deberías probar la funcionalidad, no basta con buildeear (eso ya lo hace github)

@Sealra Sealra changed the title bugfix/audit-custom-section Solución filtro de language en Custom Sections de Audits Nov 13, 2024
@Sealra
Copy link
Copy Markdown
Collaborator Author

Sealra commented Nov 13, 2024

  1. El nombre del PR está mal

    1. Deberías probar la funcionalidad, no basta con buildeear (eso ya lo hace github)
  1. El nombre quedó así de realizar el PR rapidamente anoche, pero lo modifiqué
  2. Claramente probé la funcionalidad, pensé que quedó claro implicitamente, de todas formas agregaré pasos para quien revise pueda testear esto correctamente.

@jllanosg
Copy link
Copy Markdown
Collaborator

2. Claramente probé la funcionalidad, pensé que quedó claro implicitamente, de todas formas agregaré pasos para quien revise pueda testear esto correctamente.

No es tan claro porque no lo especificaste, la gracia de esa sección es que podamos repetir los mismos pasos

Copy link
Copy Markdown
Collaborator

@jllanosg jllanosg left a comment

Choose a reason for hiding this comment

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

good work!

Copy link
Copy Markdown
Collaborator

@iTzGooDLife iTzGooDLife 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 3be083e into development Nov 15, 2024
@caverav caverav deleted the hotfix/audit-custom-section branch November 15, 2024 02:02
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.

[BUG] Al agregar un Lenguage a un audit los custom section no se renderizan

4 participants