Skip to content

Conversation

@onerrogus
Copy link
Contributor

@onerrogus onerrogus commented Aug 4, 2025

Summary by Sourcery

Add configuration flags to control message persistence and history retrieval, enabling selective saving and logging of incoming messages and updates based on SAVE_DATA settings

Enhancements:

  • Use SAVE_DATA.HISTORIC and SAVE_DATA.NEW_MESSAGE flags to conditionally fetch and assign stored message IDs
  • Guard creation of message update records behind the SAVE_DATA.MESSAGE_UPDATE flag
  • Bypass message formatting and editing validations when new message persistence is disabled

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Aug 4, 2025

Reviewer's Guide

Refactor persistence logic to conditionally perform database operations based on configurable SAVE_DATA flags, ensuring correct behavior when messages are not stored.

Flow diagram for conditional message persistence logic

flowchart TD
    A[Receive message update] --> B{SAVE_DATA.HISTORIC or SAVE_DATA.NEW_MESSAGE?}
    B -- Yes --> C[Find message in DB]
    C -- Found --> D[Set messageId]
    C -- Not found --> E[Skip setting messageId]
    B -- No --> F[Skip DB lookup]
Loading

Flow diagram for conditional message update persistence

flowchart TD
    A[Message update event] --> B{SAVE_DATA.MESSAGE_UPDATE?}
    B -- Yes --> C[Create messageUpdate in DB]
    B -- No --> D[Skip DB operation]
Loading

Flow diagram for conditional message edit validation

flowchart TD
    A[Edit message request] --> B{SAVE_DATA.NEW_MESSAGE?}
    B -- Yes --> C[Validate oldMessage exists and is valid]
    B -- No --> D[Skip validation]
Loading

File-Level Changes

Change Details Files
DB fetch and messageId assignment gated by persistence flags
  • Add configService.get('DATABASE').SAVE_DATA.HISTORIC or NEW_MESSAGE check before prismaRepository.message.findFirst
  • Assign message.messageId only if findMessage exists and persistence enabled
  • Early return in formatUpdateMessage when NEW_MESSAGE disabled
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Wrap creation of messageUpdate records under MESSAGE_UPDATE flag
  • Guard prismaRepository.messageUpdate.create in delete flow with SAVE_DATA.MESSAGE_UPDATE
  • Guard prismaRepository.messageUpdate.create in edit flow with SAVE_DATA.MESSAGE_UPDATE
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Status update and deletion flows require persisted message
  • Change status comparison branch to only run when findMessage is truthy
  • Add guard if (!message) return response before deleteMany
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Edit message validation gated by NEW_MESSAGE flag
  • Wrap NotFoundException, BadRequestException and timestamp checks under NEW_MESSAGE guard
  • Only perform post-send DB lookup and update logic when NEW_MESSAGE enabled
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Possibly linked issues


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 @onerrogus - I've reviewed your changes - here's some feedback:

  • Cache the DATABASE.SAVE_DATA config at the start of the method or as a class property to avoid repeating configService.get calls and improve readability.
  • Extract the conditional logic for historic, new message, and message update handling into dedicated helper methods to reduce nesting and duplication.
  • Centralize the SAVE_DATA flag checks into a single guard or utility function to ensure consistent behavior across all message operations.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Cache the DATABASE.SAVE_DATA config at the start of the method or as a class property to avoid repeating configService.get calls and improve readability.
- Extract the conditional logic for historic, new message, and message update handling into dedicated helper methods to reduce nesting and duplication.
- Centralize the SAVE_DATA flag checks into a single guard or utility function to ensure consistent behavior across all message operations.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:3789` </location>
<code_context>

   private async formatUpdateMessage(data: UpdateMessageDto) {
     try {
+      if (!this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
+        return data;
+      }
</code_context>

<issue_to_address>
Early return skips formatting if NEW_MESSAGE is false.

Ensure that all consumers of this method are prepared to handle unformatted data when NEW_MESSAGE is false, as this may affect downstream processing.
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:3852` </location>
<code_context>

           const messageId = messageSent.message?.protocolMessage?.key?.id;
-          if (messageId) {
+          if (messageId && this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
             let message = await this.prismaRepository.message.findFirst({
               where: { key: { path: ['id'], equals: messageId } },
</code_context>

<issue_to_address>
Message update logic is now gated by NEW_MESSAGE flag.

Consider whether message updates should ever occur when NEW_MESSAGE is false, as this change will prevent all such updates.
</issue_to_address>

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.


private async formatUpdateMessage(data: UpdateMessageDto) {
try {
if (!this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
Copy link
Contributor

Choose a reason for hiding this comment

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

question (bug_risk): Early return skips formatting if NEW_MESSAGE is false.

Ensure that all consumers of this method are prepared to handle unformatted data when NEW_MESSAGE is false, as this may affect downstream processing.


const messageId = messageSent.message?.protocolMessage?.key?.id;
if (messageId) {
if (messageId && this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
Copy link
Contributor

Choose a reason for hiding this comment

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

question (bug_risk): Message update logic is now gated by NEW_MESSAGE flag.

Consider whether message updates should ever occur when NEW_MESSAGE is false, as this change will prevent all such updates.

@onerrogus
Copy link
Contributor Author

onerrogus commented Aug 4, 2025

@DavidsonGomes as alterações são referentes ao uso da Evolution sem salvar as mensagens em banco de dados.
As principais alterações são devido aos métodos fazerem busca do banco de dados para validar as mensagens, porém no caso quando não existe informações no banco ocorria erro ao utilizar a API.

  1. Referente a alteração dentro do "message.update" onde foi adicionada a verificação do configDatabaseData.HISTORIC ou configDatabaseData.NEW_MESSAGE é devido que não era enviado os eventos de webhook quando o ACK da mensagem era atualizado.

  2. Referente a alteração do "deleteMessage" é que ao utilizar a rota da API para deletar uma mensagem ocorria erro no deleteMany pois usava o message.id, porem message sempre é undefined.

  3. Referente ao método "formatUpdateMessage", o this.getMessage nunca encontrava nada e sempre retornava null, fazendo com que as mensagens não fosse editadas.

  4. Referente ao "updateMessage", foi ajustado para que as validações e chamadas do prisma só sejam feitas quando os dados estão persistidos em banco, caso contrário acusa falso erro ou update em registro inexistente.

Lembrando que essas alterações são referentes a quando as opções na env de SAVE_NEW_MESSAGE está definida como false, no nosso caso, usamos a EvolutionAPI apenas como intermediário para troca de mensagens, com envio e recebimento e re-envio dos eventos via webhook/socket, não utilizamos as tabelas da Evolution para salvar as mensagens.

@DavidsonGomes DavidsonGomes merged commit 03a44cf into EvolutionAPI:develop Aug 4, 2025
1 check 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