Skip to content

fix(baileys): resolve Brazilian 9th digit lost in LID/PN mapping (#2687) - #2688

Open
IgorLimaJesus wants to merge 2 commits into
evolution-foundation:developfrom
IgorLimaJesus:fix/2687-brazilian-9th-digit-lid-mapping
Open

fix(baileys): resolve Brazilian 9th digit lost in LID/PN mapping (#2687)#2688
IgorLimaJesus wants to merge 2 commits into
evolution-foundation:developfrom
IgorLimaJesus:fix/2687-brazilian-9th-digit-lid-mapping

Conversation

@IgorLimaJesus

@IgorLimaJesus IgorLimaJesus commented Aug 13, 2026

Copy link
Copy Markdown

📋 Description

Fixed Brazilian 9th digit handling and LID/PN mapping resolution in Baileys integration:

  1. Fixed formatBRNumber stripping the 9th digit:

    • Resolved legacy regex behavior in src/utils/createJid.ts and src/api/services/channel.service.ts that stripped the 9th digit ('9') from Brazilian mobile numbers with area codes (DDD) ≥ 31 and subscriber numbers starting with ≥ 7 (e.g. converting 5547989211984 into invalid 554789211984).
    • Updated formatBRNumber to preserve valid 13-digit Brazilian mobile numbers (55 + DDD + 9 + 8 digits) across all area codes (11-99) and add '9' only when formatting legacy 12-digit mobile numbers.
  2. Cache and JID Resolution (onWhatsappCache.ts & whatsapp.baileys.service.ts):

    • Refined getAvailableNumbers and saveOnWhatsappCache to prevent existing 13-digit BR JIDs from being downgraded to 12-digit JIDs when updating cache records.
    • Updated whatsappNumber resolution in whatsapp.baileys.service.ts to prioritize 13-digit BR mobile JIDs over 12-digit legacy JIDs returned by Baileys onWhatsApp checks, ensuring outbound messages target valid recipient JIDs and receive SERVER_ACK / DELIVERY_ACK instead of remaining PENDING.

🔗 Related Issue

Closes #2687

🧪 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)

📸 Screenshots (if applicable)

✅ 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
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

  • Tested in Docker development environment (evolution-api:local).
  • To clean up existing corrupted cache entries in production databases without deleting WhatsApp instances, run:
    DELETE FROM "IsOnWhatsapp" WHERE "remoteJid" LIKE '55%' AND LENGTH(SPLIT_PART("remoteJid", '@', 1)) = 12;
    

Summary by Sourcery

Fix Brazilian WhatsApp number handling to preserve valid 13-digit mobile JIDs and prefer them over legacy 12-digit mappings in Baileys integration.

Bug Fixes:

  • Ensure Brazilian 13-digit mobile numbers retain the 9th digit during BR formatting instead of being incorrectly converted to 12-digit numbers.
  • Prevent cache updates from downgrading existing 13-digit Brazilian JIDs to 12-digit legacy JIDs in the onWhatsApp cache.
  • Adjust Baileys WhatsApp number resolution to favor 13-digit Brazilian mobile JIDs over 12-digit JIDs returned by onWhatsApp checks.

@sourcery-ai

sourcery-ai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adjusts Brazilian phone number normalization and Baileys WhatsApp JID/cache handling so valid 13-digit BR mobile numbers keep their 9th digit and are preferred over legacy 12-digit JIDs in cache and message routing.

Sequence diagram for Baileys BR JID selection preferring 13-digit mobiles

sequenceDiagram
participant BaileysStartupService
participant Baileys_onWhatsApp

BaileysStartupService->>Baileys_onWhatsApp: onWhatsApp(user.number)
Baileys_onWhatsApp-->>BaileysStartupService: verify (list of jids)
BaileysStartupService->>BaileysStartupService: OnWhatsAppDto(numberVerified?.jid || user.jid)
alt [user.number is 13-digit BR mobile and numberJid is 12-digit @s.whatsapp.net]
  BaileysStartupService->>BaileysStartupService: numberJid = user.number@s.whatsapp.net
end
BaileysStartupService-->>BaileysStartupService: OnWhatsAppDto(numberJid)
Loading

File-Level Changes

Change Details Files
Normalize Brazilian numbers by only adding or stripping the 9th digit when clearly dealing with mobile numbers and preserving already-correct 13-digit JIDs.
  • Replaced regex-based BR number formatter with explicit length/prefix checks for 55 + DDD + local number.
  • Ensured 13-digit Brazilian mobile numbers (55 + DDD + 9 + 8 digits) are returned unchanged.
  • For 12-digit Brazilian numbers whose local part starts with 6–9, insert a 9 after the country+DDD prefix to produce a mobile number; otherwise leave unchanged.
src/api/services/channel.service.ts
src/utils/createJid.ts
Prevent cache from downgrading existing 13-digit BR JIDs to 12-digit variants and generate both 12- and 13-digit options more carefully.
  • Reworked Brazilian branch of getAvailableNumbers to derive 13-digit and 12-digit variants based on current length and first local digit instead of always injecting/removing a 9.
  • When saving cache records, keep an existing 13-digit BR JID with a 9th digit if a new resolution only provides a 12-digit JID for the same number.
  • Continue to store jidOptions as a sorted, comma-separated list and set lid based on incoming data and remoteJid type.
src/utils/onWhatsappCache.ts
Prefer a verified 13-digit BR JID over a 12-digit Baileys JID when sending messages so outbound traffic targets valid mobile recipients.
  • After selecting the candidate JID (verified or user.jid), detect Brazilian 13-digit mobile numbers with a 9 at the 5th position.
  • If Baileys returned a 12-digit @s.whatsapp.net JID for such a user, rewrite numberJid to use the 13-digit user.number instead.
  • Keep the existing logic for choosing verified JIDs when present.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Assessment against linked issues

Issue Objective Addressed Explanation
#2687 Preserve the Brazilian 9th digit when creating/formatting JIDs so that numbers like +55 47 98921-1984 map to 5547989211984@s.whatsapp.net instead of incorrectly stripping the 9th digit.
#2687 Correct LID/PN cache handling and Baileys onWhatsApp resolution so that existing 13-digit Brazilian JIDs are not downgraded to 12 digits, and outbound messages to LID-mapped contacts are sent to the correct JID and no longer remain PENDING.
#2687 Document/provide a safe procedure to clean up existing corrupted Brazilian cache entries (incorrect 12-digit JIDs) without deleting WhatsApp instances.

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

@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 found 1 issue, and left some high level feedback:

  • The Brazilian number formatting logic is now duplicated in both ChannelStartupService.formatBRNumber and utils/createJid.formatBRNumber; consider centralizing this in a shared helper to avoid divergence and make future updates easier.
  • The new BR handling logic relies on several magic indices and numeric thresholds (jid[4], firstDigit >= 6, startsWith('55'), etc.); adding intermediate variables or small helper functions with descriptive names would make the conditions clearer and reduce the risk of subtle off‑by‑one bugs.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The Brazilian number formatting logic is now duplicated in both `ChannelStartupService.formatBRNumber` and `utils/createJid.formatBRNumber`; consider centralizing this in a shared helper to avoid divergence and make future updates easier.
- The new BR handling logic relies on several magic indices and numeric thresholds (`jid[4]`, `firstDigit >= 6`, `startsWith('55')`, etc.); adding intermediate variables or small helper functions with descriptive names would make the conditions clearer and reduce the risk of subtle off‑by‑one bugs.

## Individual Comments

### Comment 1
<location path="src/utils/onWhatsappCache.ts" line_range="24-27" />
<code_context>
-    const numberWithDigit =
-      number.slice(4, 5) === '9' && number.length === 13 ? number : `${number.slice(0, 4)}9${number.slice(4)}`;
-    const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 4) + number.slice(5);
+    let numberWithDigit = number;
+    let numberWithoutDigit = number;
+
+    if (number.length === 13 && number.slice(4, 5) === '9') {
+      numberWithDigit = number;
+      numberWithoutDigit = `${number.slice(0, 4)}${number.slice(5)}`;
</code_context>
<issue_to_address>
**issue (bug_risk):** Avoid pushing duplicate numbers into `numbersAvailable` when no transformation is applied.

With the new branching, there are scenarios where both `numberWithDigit` and `numberWithoutDigit` stay equal to the original `number` (e.g., certain 12- or 13-digit BR numbers that don't meet the transformation conditions), so the same value can be pushed twice into `numbersAvailable`. If callers assume distinct variants or use the list for lookups, this can cause subtle bugs. Either deduplicate before pushing or only push the second variant when it differs from the first.
</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.

Comment thread src/utils/onWhatsappCache.ts
@IgorLimaJesus
IgorLimaJesus changed the base branch from main to develop August 13, 2026 15:53
@IgorLimaJesus
IgorLimaJesus force-pushed the fix/2687-brazilian-9th-digit-lid-mapping branch from 2cae956 to 9b94b49 Compare August 13, 2026 15:58
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.

[BUG] Brazilian 9th digit lost in LID/PN mapping - messages remain PENDING

1 participant