Skip to content

Conversation

@KokeroO
Copy link
Contributor

@KokeroO KokeroO commented Jun 13, 2025

Descrição

Melhora e refatora parte dos commits anteriores que tens como objetivo solucionar a criação dos contatos @lid no Chatwoot.

@DavidsonGomes com todo o respeito, analisei e testei essas ultimas implementações suas. Mas em certos pontos os @lid estão sendo tratados em condições junto com grupos, esses @lid são diferente disso. Em alguns momentos funciona e em outros não.

Desde 11/06 vim testando insistentemente e reproduzindo o erro com contatos que eu mesmo consegui simular. Estou com um cliente que teve 263 contatos criados com lid, cliente com fluxo atual de 40 mil a 50 mil msgs por dia.

A solução que empreguei é bem mais simples e totalmente funcional.

Nos meus teste, o script foi capaz:

  1. Criar contatos @lid com @s.whatsapp.net corretamente.
  2. Atualizar contatos já criados com @lid e atualizar o identificador para o número correto @s.whatsapp.net .
  3. Retomar conversas anteriormente já criadas.

Diferenças:

O evento é diferente que eventos de participantes de grupo:

Grupo:

    remoteJid: '142902286143727@lid',
    fromMe: false,
    id: '#',
    senderLid: '142902286143727@lid',
    senderPn: undefined,
    participant: 55########6898@s.whatsapp.net,
    participantLid: undefined
  },

lid:

    remoteJid: '#############@g.us',
    fromMe: false,
    id: '######',
    senderLid: undefined,
    senderPn: '55#######6898@s.whatsapp.net',
    participant: undefined,
    participantLid: undefined
  },

Summary by Sourcery

Refactor Chatwoot integration to streamline contact lookup and creation by unifying method signatures, removing redundant lid-specific branches, and improving detection and updating of @lid contact identifiers during conversations.

Enhancements:

  • Streamline findContact and createContact methods to accept a phone number string and drop the isLid flag
  • Consolidate contact identifier logic to uniformly handle single and group chats
  • Remove normalizeContactIdentifier helper and update createConversation to detect and refresh @lid contacts via senderPn
  • Adjust remoteJid resolution in createConversation for lid events and ensure existing contacts are updated
  • Introduce a triple-check on cache before creating new conversations to prevent race conditions
  • Update Baileys startup service to use the simplified findContact signature

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jun 13, 2025

Reviewer's Guide

This PR simplifies and refactors contact handling in Chatwoot integration by unifying method signatures, removing special-case LID logic, consolidating identifier resolution, and enhancing the createConversation flow to correctly process and update @lid contacts.

Sequence Diagram: Simplified findContact Call and Logic

sequenceDiagram
  participant Caller
  participant ChatwootService
  participant ChatwootAPI

  Caller->>ChatwootService: findContact(instance, phoneNumberString)
  Note right of ChatwootService: phoneNumberString is now a simple string (e.g., "12345...")
  ChatwootService->>ChatwootService: isGroup = phoneNumberString.includes('@g.us')
  alt if not isGroup
    ChatwootService->>ChatwootService: query = "+" + phoneNumberString
  else is group
    ChatwootService->>ChatwootService: query = phoneNumberString
  end
  Note left of ChatwootService: Internal @lid specific query path removed.
  ChatwootService->>ChatwootAPI: contacts.search({ q: query }) or contacts.filter(...)
  Note right of ChatwootService: Fallback search logic removed.
  ChatwootAPI-->>ChatwootService: contactList
  ChatwootService-->>Caller: contact
Loading

Sequence Diagram: @lid Contact Identifier Update in createConversation

sequenceDiagram
  participant EventHandler
  participant ChatwootService
  participant ChatwootAPI

  EventHandler->>ChatwootService: createConversation(instance, body)
  Note right of ChatwootService: body.key.remoteJid contains '@lid',
  Note right of ChatwootService: body.key.senderPn has correct ID

  ChatwootService->>ChatwootService: Check if remoteJid is @lid and senderPn differs
  opt if @lid contact needs identifier update
    ChatwootService->>ChatwootService: findContact(instance, body.key.remoteJid.split('@')[0])
    ChatwootService->>ChatwootAPI: Search for contact by old @lid value (via findContact)
    ChatwootAPI-->>ChatwootService: contactToUpdate
    alt if contactToUpdate AND contactToUpdate.identifier != body.key.senderPn
      ChatwootService->>ChatwootAPI: updateContact(contactToUpdate.id, { identifier: body.key.senderPn, phone_number: ... })
      ChatwootAPI-->>ChatwootService: (ack)
    end
  end
  ChatwootService->>ChatwootService: Continue with conversation creation using senderPn as primary identifier for @lid
Loading

Updated Class Diagram for ChatwootService

classDiagram
  class ChatwootService {
    +createContact(instance: InstanceDto, phoneNumber: string, inboxId: number, isGroup: boolean, name?: string, avatar_url?: string, jid?: string)
    +findContact(instance: InstanceDto, phoneNumber: string)
    +createConversation(instance: InstanceDto, body: any)
    +createChatwootBotContact(instance: InstanceDto, inboxId: number, organization?: string, logo?: string)
    %% Method Removed: normalizeContactIdentifier(msg: any) %%
  }
Loading

File-Level Changes

Change Details Files
Unified findContact signature and logic
  • Changed findContact to accept a phone number string instead of an object
  • Removed isLid detection and fallback filter endpoint
  • Simplified group vs non-group query construction
  • Adjusted contact search branches to only distinguish group identifiers
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Refactored createContact parameters and payload construction
  • Simplified phoneNumber parameter to string and removed isLid flag
  • Unified name and identifier assignment based on jid or phoneNumber
  • Adjusted when to include phone_number field in payload
  • Streamlined group vs non-group data object without redundant flags
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Removed normalizeContactIdentifier and inlined LID resolution
  • Deleted normalizeContactIdentifier helper
  • Directly detect @lid contacts and use senderPn as remoteJid
  • Replaced all normalizeContactIdentifier calls with inline logic
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Enhanced createConversation flow for @lid and group messages
  • Added initial check to update existing @lid contacts with correct senderPn
  • Unified chatId derivation for group vs individual (split on '@')
  • Adjusted participant handling and contact updates in group context
  • Inserted triple-check cache guard before conversation creation
  • Refined logging to include remoteJid context
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Updated external usage to match new findContact signature
  • Replaced object-based calls with string argument for phoneNumber in Baileys startup
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

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

@DavidsonGomes DavidsonGomes merged commit a1fae85 into EvolutionAPI:develop Jun 13, 2025
1 check passed
@BrunoShioheiFlip
Copy link

Bom dia @KokeroO, tudo bem? Consegue descrever os passos para reproduzir este caso? Estou tendo esse erro, mas não consegui reproduzir de nenhuma forma.

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