Skip to content

Conversation

Vitordotpy
Copy link
Contributor

@Vitordotpy Vitordotpy commented Sep 26, 2025

This pull request resolves two distinct issues to enhance application stability and ensure correct internationalization (i18n) in production environments. It addresses a critical Prisma validation error during message status updates and corrects a file path issue that prevented translation files from being loaded after the build process.

Fixes:

1. Prevent Prisma Validation Error on Message Updates:

  • Issue: A PrismaClientValidationError would occur when processing incoming message status updates (e.g., "read" receipts). This happened when an update was received for a message that did not exist in the local database, causing an unhandled promise rejection because the required Message relation could not be linked.
  • Solution: A validation check has been added to the messages.update handler in the Baileys service. Before attempting to create a MessageUpdate record, the system now queries for the original message. If the original message is not found, the operation is gracefully skipped for that specific update, preventing the validation error and ensuring the stability of the message processing queue.

2. Correct Dynamic Path for i18n Translations:

  • Issue: The i18n utility was failing to load translation files in production builds, causing translation keys (e.g., qrgeneratedsuccesfully) to be displayed to the user instead of the actual translated text. The file path was hardcoded to look inside the src/ directory, which is not present in the compiled dist/ output.
  • Solution: The i18n initialization script has been refactored to dynamically resolve the path to the translation files. It now checks for the existence of the dist directory at runtime. If dist exists, it loads translations from dist/translations; otherwise, it falls back to src/utils/translations for the development environment. This ensures that localization works correctly in all environments.

Enhancements:

  • Increased Stability: The application no longer crashes due to missing message records during status updates, making the message handling process more resilient.
  • Improved User Experience: All text is now correctly translated in production, providing a professional and clear interface for all users, regardless of their language.

Summary

This PR improves the application's reliability by fixing a critical crash in the Baileys message update handler and ensures proper localization in production by correcting the i18n module's translation file path.

Summary by Sourcery

Prevent message processing crashes by guarding missing records during updates and fix production i18n by resolving translation paths dynamically.

Bug Fixes:

  • Skip message status updates for missing records to prevent PrismaClientValidationError
  • Refactor i18n initialization to dynamically resolve translation file path for production

Enhancements:

  • Improve message handling stability by gracefully skipping invalid updates
  • Ensure correct loading of translation resources in all environments

- Ajustada a lógica de verificação para garantir que o ID da mensagem seja definido apenas quando disponível, evitando possíveis erros de referência.
- Atualizada a definição do caminho de traduções para suportar a estrutura de diretórios em produção.
Copy link
Contributor

sourcery-ai bot commented Sep 26, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds a guard in the Baileys message update handler to skip missing message records—preventing Prisma validation errors—and refactors the i18n initialization to dynamically resolve translation file paths for production and development environments.

Sequence diagram for Baileys message update handler with missing message guard

sequenceDiagram
participant BaileysService
participant Database
participant Prisma
BaileysService->>Database: Query for original message
Database-->>BaileysService: Return message (may be null)
alt Message found
    BaileysService->>Prisma: Create MessageUpdate record
    Prisma-->>BaileysService: Success
else Message not found
    BaileysService->>BaileysService: Skip update, continue loop
end
Loading

Class diagram for i18n initialization and translation path resolution

classDiagram
class ConfigService {
}
class I18n {
  +languages: string[]
  +translationsPath: string
  +resources: any
}
I18n -- ConfigService: uses
I18n : +resolveTranslationsPath()
I18n : +initialize()
Loading

File-Level Changes

Change Details Files
Prevent PrismaClientValidationError by skipping message status updates when no original message exists
  • Added a check for findMessage.id before processing each update
  • Replaced direct assignment with a continue statement when the original message is missing
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Refactor i18n initialization to dynamically resolve translation paths
  • Use fs.existsSync to detect a dist directory at runtime
  • Set translationsPath conditionally to dist/translations or src/utils/translations based on environment
src/utils/i18n.ts

Possibly linked issues

  • #0: The PR fixes the Prisma validation error during message updates by skipping updates for non-existent messages, which prevents the 'Argument status is missing' error.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • Consider logging a warning or info when skipping a message update due to a missing original message to aid debugging and monitoring.
  • In the i18n initializer, verify the existence of the resolved translations directory (not just the ‘dist’ folder) before loading to avoid false positives when ‘dist’ exists but translations are missing.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider logging a warning or info when skipping a message update due to a missing original message to aid debugging and monitoring.
- In the i18n initializer, verify the existence of the resolved translations directory (not just the ‘dist’ folder) before loading to avoid false positives when ‘dist’ exists but translations are missing.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

- Implementada uma mensagem de aviso no serviço Baileys quando a mensagem original não é encontrada durante a atualização, melhorando a rastreabilidade de erros.
- Ajustada a lógica de verificação do caminho de traduções para garantir que o diretório correto seja utilizado, com tratamento de erro caso não seja encontrado.
@Vitordotpy Vitordotpy changed the title Fixed message update and i18n errors fix(baileys): message update and i18n errors Sep 26, 2025
@DavidsonGomes DavidsonGomes merged commit b62917e into EvolutionAPI:develop Sep 26, 2025
5 checks passed
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