Skip to content

fix(api): modifica fetchChats para trazer mensagens de contatos não salvos #1384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 30, 2025

Conversation

leandrosroc
Copy link
Contributor

@leandrosroc leandrosroc commented Apr 21, 2025

fix(api): modifica fetchChats para trazer mensagens de contatos não salvos

  • Muda tabela base da consulta de Contact para Message
  • Altera INNER JOIN para LEFT JOIN entre Message e Contact
  • Usa COALESCE para campos que podem estar vazios
  • Adiciona flag isSaved para identificar contatos salvos/não salvos
  • Preserva toda funcionalidade de filtros existente

Resolve issue #1376

Summary by Sourcery

Modify the fetchChats query to support retrieving messages from unsaved contacts by changing the base table and join strategy

Bug Fixes:

  • Enables fetching chat messages for contacts that are not saved in the contact list by changing the query base table and join type

Enhancements:

  • Improved query to handle contacts without a saved record
  • Added an 'isSaved' flag to distinguish between saved and unsaved contacts
  • Implemented more flexible message retrieval logic

…alvos

- Muda tabela base da consulta de Contact para Message
- Altera INNER JOIN para LEFT JOIN entre Message e Contact
- Usa COALESCE para campos que podem estar vazios
- Adiciona flag isSaved para identificar contatos salvos/não salvos
- Preserva toda funcionalidade de filtros existente

Resolve issue EvolutionAPI#1376
Copy link
Contributor

sourcery-ai bot commented Apr 21, 2025

Reviewer's Guide by Sourcery

This pull request modifies the fetchChats function to include messages from unsaved contacts. It changes the base table for the query from Contact to Message, uses a LEFT JOIN instead of an INNER JOIN between Message and Contact, and uses COALESCE to handle potentially empty fields. Additionally, it adds an isSaved flag to identify saved/unsaved contacts and preserves existing filter functionality.

ER Diagram for fetchChats Query Change

erDiagram
    Message {
        string key
        string pushName
        bigint messageTimestamp
        string instanceId
    }
    Contact {
        string id
        string remoteJid
        string pushName
        string profilePicUrl
        datetime updatedAt
        string instanceId
    }
    Chat {
        string remoteJid
        datetime createdAt
        string instanceId
    }
    Message ||--o{ Contact : remoteJid
    Message ||--o{ Chat : remoteJid
Loading

File-Level Changes

Change Details Files
Modified the base table and join type in the SQL query to include messages from unsaved contacts.
  • Changed the base table of the main query from Contact to Message.
  • Changed the INNER JOIN between Message and Contact to a LEFT JOIN.
  • Added LEFT JOIN to Chat table.
  • Removed limit from the first query and applied it after the mapping.
src/api/services/channel.service.ts
Implemented logic to handle potentially missing contact information and identify saved/unsaved contacts.
  • Used COALESCE to populate pushName with the value from Message when Contact is null.
  • Added an isSaved flag to the returned data, indicating whether the contact is saved or not.
  • Set id to null when contact is not found.
src/api/services/channel.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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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

Overall Comments:

  • Consider adding a comment explaining why the limit clause was removed.
  • The query is complex; consider adding comments to the SQL query to improve readability.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

@nestordavalos
Copy link
Contributor

🛠️ Complemento à PR: Suporte a mensagens de contatos não salvos em fetchChats

Primeiramente, parabéns pelo avanço com esse PR. 🙌
A alteração feita em fetchChats resolveu corretamente o problema de não exibir mensagens de contatos que não estão salvos.

A estratégia usada foi válida:

  • ✅ Mudança da tabela base de Contact para Message
  • ✅ Troca de INNER JOIN por LEFT JOIN
  • ✅ Uso de COALESCE para evitar campos nulos
  • ✅ Inclusão da flag isSaved para diferenciar contatos salvos e não salvos

⚠️ Contudo, ainda havia um problema em fetchContacts

Mesmo com esse PR, ao consumir o endpoint chat/findContacts, continuavam aparecendo:

  • Contatos reais ✅
  • Grupos ✅
  • Usuários que apenas participam de grupos mas não estão salvos na agenda

Esses usuários eram retornados como se fossem contatos comuns, o que pode confundir o frontend ou outras integrações.


✅ Solução aplicada (a partir da linha 516 de channel.service.ts)

Fizemos uma alteração pontual na função fetchContacts, a partir da linha 516, substituindo o retorno direto por um map() com enriquecimento dos dados:

const contacts = await this.prismaRepository.contact.findMany(contactFindManyArgs);

return contacts.map(contact => {
  const remoteJid = contact.remoteJid;
  const isGroup = remoteJid.endsWith('@g.us');
  const isSaved = !!contact.pushName || !!contact.profilePicUrl;
  const type = isGroup ? 'group' : isSaved ? 'contact' : 'group_member';

  return {
    ...contact,
    isGroup,
    isSaved,
    type,
  };
});

Com essa mudança simples, agora cada contato traz:

isGroup: se é grupo (@g.us)

isSaved: se o contato está salvo (possui pushName ou profilePicUrl)

type: com valores possíveis: contact, group, group_member

🎯 Benefícios

Essa solução:

🧼 É mais enxuta e de fácil manutenção
⚡️ Não altera estrutura de joins nem queries SQL complexas
✅ Resolve completamente o problema pendente em fetchContacts
🧩 Funciona de forma complementar ao que já foi implementado no PR original de fetchChats

@leandrosroc
Copy link
Contributor Author

irei fazer o commit com a solução proposta

@leandrosroc
Copy link
Contributor Author

e muito obrigado 😀😀

neocol83 added a commit to neocol83/evolution-api that referenced this pull request Apr 29, 2025
@DavidsonGomes DavidsonGomes merged commit ccbd866 into EvolutionAPI:develop Apr 30, 2025
1 check passed
@nestordavalos nestordavalos mentioned this pull request May 12, 2025
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