Skip to content

fix(chatwoot): make LID contact lookup work and ignore LID digits stored as phone - #2754

Open
gobeyondpty wants to merge 1 commit into
evolution-foundation:developfrom
gobeyondpty:fix/chatwoot-lid-contact-lookup
Open

gobeyondpty wants to merge 1 commit into
evolution-foundation:developfrom
gobeyondpty:fix/chatwoot-lid-contact-lookup

Conversation

@gobeyondpty

@gobeyondpty gobeyondpty commented Oct 11, 2026 •

Copy link
Copy Markdown

📋 Description

ChatwootService.findContactByIdentifier calls client.get('contacts/search', …) and client.post('contacts/filter', …). ChatwootClient from @figuro/chatwoot-sdk has no get/post methods (it exposes resource namespaces such as client.contacts.search), so every call throws:

WARN [ChatwootService] Error resolving LID from database: TypeError: t.get is not a function
WARN [ChatwootService] Could not resolve LID: …@lid

Two callers are affected:

  • resolveLidToPhone step 3 (lookup in Chatwoot) can never succeed; the error is swallowed and logged.
  • The 422 recovery path in createContact ("Checking if it already exists...") rethrows the TypeError instead of returning the existing contact.

This PR:

  1. Uses client.contacts.search and the same contacts/filter request findContact already uses.
  2. Accepts only an exact identifier match. Chatwoot's contact search is a substring match across name, email, phone and identifier, so returning payload[0] can pick the wrong contact.
  3. In resolveLidToPhone, ignores a phone_number that is just the LID digits. createContact stores +<lid digits> as phone_number for contacts created from a LID, so once the lookup works those contacts would otherwise resolve to <lid digits>@s.whatsapp.net, which is not a WhatsApp number.

Point 3 matters in practice: on our instance 692 of 828 contacts with an @lid identifier have the LID digits as their phone number.

🔗 Related Issue

Overlaps with #2747, which rewrites the same function as part of a larger LID change. This PR is limited to the broken lookup and adds the exact-match and LID-digits guards, which #2747 does not have (it falls back to payload[0]).

🧪 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)

🧪 Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced
  • Tested with different connection types (if applicable)

Checked read-only against a production Chatwoot from inside a running 2.4.0 container, using the same SDK calls:

Case search exact filter exact resolves
@lid contact whose phone is the LID digits 1 1 no (guard)
@lid contact with a real phone number 1 1 yes
unknown @lid 0 0 no

The same script confirms typeof client.get === 'undefined' and typeof client.contacts.search === 'function'.

eslint --ext .ts passes on the file. tsc --noEmit reports the same errors before and after (Prisma client not generated in my checkout); none are in the changed lines. I have not run a full build or an end-to-end message flow with this exact source build.

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings

🤖 Generated with Claude Code

Summary by Sourcery

Fix Chatwoot LID contact resolution and avoid treating stored LID digits as real phone numbers.

Bug Fixes:

  • Fix Chatwoot contact lookup for LID identifiers by using supported client APIs and accepting only exact identifier matches.
  • Prevent LID contacts whose stored phone number is just the LID digits from being resolved as WhatsApp phone numbers, while allowing valid phone numbers to resolve.

…red as phone

findContactByIdentifier called client.get() and client.post(), which do not
exist on ChatwootClient, so every call threw "TypeError: get is not a
function". resolveLidToPhone swallowed it as "Error resolving LID from
database", and the 422 recovery path in createContact rethrew it.

Use client.contacts.search and the contacts/filter request already used by
findContact, and accept only an exact identifier match because search is a
substring match across several fields.

Contacts created from a LID carry the LID digits as phone_number. Skip those
in resolveLidToPhone so a LID is never mapped to <lid digits>@s.whatsapp.net.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Fixes Chatwoot LID contact resolution by using the SDK's supported APIs, requiring exact identifier matches to avoid substring-search false positives, and rejecting placeholder phone numbers that contain only the LID digits.

Sequence diagram for exact Chatwoot LID contact resolution

sequenceDiagram
    participant Resolver as ChatwootService
    participant SDK as ChatwootClient
    participant API as ChatwootAPI

    Resolver->>SDK: contacts.search(accountId, q)
    SDK->>API: Search contacts
    API-->>SDK: payload
    SDK-->>Resolver: search result
    alt exact identifier match
        Resolver-->>Resolver: return contact
    else no exact match
        Resolver->>API: chatwootRequest(POST contacts/filter)
        API-->>Resolver: filtered payload
        alt exact identifier match
            Resolver-->>Resolver: return contact
        else no match
            Resolver-->>Resolver: return null
        end
    end
Loading

Flow diagram for rejecting LID placeholder phone numbers

flowchart TD
    A[Resolve LID contact] --> B[Read contact phone_number]
    B --> C[Remove non-digits]
    C --> D{Phone digits equal LID digits?}
    D -->|Yes| E[Do not resolve]
    D -->|No| F[Build WhatsApp JID]
    F --> G[Save LID mapping]
Loading

File-Level Changes

Change Details Files
Replace unsupported generic Chatwoot client calls with supported search and request paths while enforcing exact identifier matches.
  • Use client.contacts.search with the account ID for identifier lookup.
  • Retain the contacts/filter fallback through chatwootRequest.
  • Normalize both response shapes and return only contacts whose identifier exactly equals the requested value.
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Prevent LID contacts from resolving to a fabricated WhatsApp number when their stored phone is only the LID digits.
  • Compare normalized contact phone digits against the remote JID's LID digits.
  • Resolve and persist a mapping only when the phone digits differ from the LID digits.
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

Possibly linked issues

  • #meta-lid-jid-handling: PR fixes Chatwoot-specific @lid lookup and conversion failures covered by the umbrella issue.

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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. If the exact-match lookup or LID-versus-phone comparison is wrong, the service could persist an incorrect WhatsApp mapping and route messages to the wrong phone number. Reverting stops the new behavior, but any messages already sent externally and mappings already saved would require separate remediation.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

This branch has not been deployed

No deployments
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.

1 participant