Skip to content

Conversation

@cesar-carlos
Copy link

@cesar-carlos cesar-carlos commented Oct 26, 2025

πŸ“‹ Description

πŸ”— Related Issue

Closes #(issue_number)

πŸ§ͺ Type of Change

  • πŸ› Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ’₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ“š Documentation update
  • πŸ”§ Refactoring (no functional changes)
  • ⚑ Performance improvement
  • 🧹 Code cleanup
  • πŸ”’ Security fix

πŸ§ͺ 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

Summary by Sourcery

Migrate the codebase to ES modules, update build configuration, enforce stronger input validation and error handling, and optimize performance by reducing various delays and tuning timeouts across Chatwoot and WhatsApp integrations.

Bug Fixes:

  • Validate Chatwoot setup inputs and handle missing WhatsApp instance gracefully
  • Fix broadcast filtering by using remoteJid
  • Gracefully ignore database lookup errors when checking duplicate messages
  • Ensure message tag generator always returns a string

Enhancements:

  • Convert project to ES modules by updating package.json, tsconfig.json, and tsup.config.ts
  • Adjust imports in i18n and Chatwoot service via createRequire to support ESM
  • Wrap router execution and Chatwoot controller methods in try-catch with logging

Build:

  • Configure tsup to emit only ESM bundles targeting ES2020 on Node

Documentation:

  • Add PR templates and descriptive documentation files

DavidsonGomes and others added 28 commits October 15, 2025 09:25
- Updated subproject reference in evolution-manager-v2.
- Replaced old JavaScript and CSS asset files with new versions for improved performance and styling.
- Added new CSS file for consistent font styling across the application.
- Updated the evolution logo image to the latest version.
- Added features for Chatwoot enhancements, participants data handling, and LID to phone number conversion.
- Updated Docker configurations to include Kafka and frontend services.
- Fixed PostgreSQL migration errors and improved message handling in Baileys and Chatwoot services.
- Refactored TypeScript build process and implemented exponential backoff patterns.
- Updated the release date for version 2.3.5 to 2025-10-15.
- Adjusted subproject reference in evolution-manager-v2 to the latest commit.
- Integrated telemetry logging for received messages in Evolution, WhatsApp Business, and Baileys services.
- Enhanced message tracking by sending the message type to the telemetry system for better observability.
- Updated subproject reference in evolution-manager-v2 to the latest commit.
- Enhanced the manager_install.sh script to include npm install and build steps for the evolution-manager-v2.
- Replaced old JavaScript asset file with a new version for improved performance.
- Added a new CSS file for consistent styling across the application.
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 26, 2025

Reviewer's Guide

Migrates the codebase to ES Modules and refactors Chatwoot and WhatsApp integrations with enhanced validation, error handling, updated connection settings, and reduced processing delays to optimize performance and compatibility.

Sequence diagram for createChatwoot with enhanced validation and error handling

sequenceDiagram
participant User
participant ChatwootController
participant ConfigService
participant ChatwootService
participant waMonitor
User->>ChatwootController: Request createChatwoot(instance, data)
ChatwootController->>ConfigService: get('CHATWOOT').ENABLED
ChatwootController->>ChatwootController: Validate data fields
alt Validation fails
  ChatwootController-->>User: Throw BadRequestException
else Validation passes
  ChatwootController->>ChatwootService: create(instance, data)
  ChatwootService->>waMonitor: waInstances[instance.instanceName].setChatwoot(data)
  ChatwootController->>ConfigService: get('SERVER').URL
  ChatwootController-->>User: Return result with webhook_url
end
Loading

Sequence diagram for improved message processing and retry logic

sequenceDiagram
participant BaileysMessageProcessor
participant ProcessorLogs
participant MessageBatch
BaileysMessageProcessor->>MessageBatch: Process batch
alt Error occurs
  BaileysMessageProcessor->>ProcessorLogs: warn("Retrying message batch due to error")
  BaileysMessageProcessor->>MessageBatch: Retry after 200ms (reduced delay)
end
Loading

Sequence diagram for receiveWebhook with removed delay

sequenceDiagram
participant ChatwootService
participant ClientCw
participant Instance
participant Body
ChatwootService->>ClientCw: clientCw(instance)
ClientCw->>ChatwootService: Process webhook (no fixed delay)
ChatwootService-->>ClientCw: Immediate response
Loading

Class diagram for updated ChatwootController and ChatwootService

classDiagram
class ChatwootController {
  +createChatwoot(instance: InstanceDto, data: ChatwootDto)
  +findChatwoot(instance: InstanceDto): ChatwootDto
  +findChatwootWebhookUrl(instance: InstanceDto): string
  +receiveWebhook(instance: InstanceDto, data: any)
}
class ChatwootService {
  +create(instance: InstanceDto, data: ChatwootDto)
  +find(instance: InstanceDto): ChatwootDto
  +receiveWebhook(instance: InstanceDto, body: any)
  +eventWhatsapp(...)
}
ChatwootController --> ChatwootService: uses
ChatwootService --> waMonitor: uses
waMonitor --> waInstances: contains
waInstances --> BaileysStartupService: contains
BaileysStartupService --> ChatwootService: uses
Loading

Class diagram for BaileysStartupService changes

classDiagram
class BaileysStartupService {
  +client: any
  +configService: ConfigService
  +localChatwoot: ChatwootDto
  +chatwootService: ChatwootService
  +baileysGenerateMessageTag()
  +baileysSignalRepositoryDecryptMessage(jid, type, ciphertext)
}
BaileysStartupService --> ChatwootService: uses
BaileysStartupService --> ConfigService: uses
Loading

File-Level Changes

Change Details Files
ES Module migration and build configuration
  • Switched package.json to "type": "module"
  • Updated tsconfig.json to use ES2020 module format
  • Modified tsup.config.ts to emit only esm with Node target
  • Replaced __dirname/__filename usage via fileURLToPath in i18n
  • Imported CommonJS SDK via createRequire
package.json
tsconfig.json
tsup.config.ts
src/utils/i18n.ts
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Enhanced ChatwootController with validations and unified error handling
  • Wrapped createChatwoot in try/catch with console error logging
  • Added checks for accountId, token, and explicit signMsg boolean
  • Reset signDelimiter when signMsg is false
  • Ensured default nameInbox fallback
  • Merged response creation and webhook_url generation
src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts
Robust ChatwootService improvements
  • Validated existence of waInstance before calls with error logging
  • Removed fixed 500ms webhook processing delay
  • Added graceful handling of duplicate message DB checks
  • Enhanced find method error logging and fallback return
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
WhatsApp Baileys service connection and filtering updates
  • Increased connectTimeoutMs to 60s and reduced keepAliveIntervalMs to 10s
  • Replaced broadcast key check with remoteJid filter
  • Cast onWhatsApp response to proper type
  • Provided fallback empty string for generateMessageTag
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Unified error handling in abstract router
  • Wrapped execute call in try/catch with logger.error
  • Re-threw caught errors to propagate upstream
src/api/abstract/abstract.router.ts
Reduced processing delays for typing and message retries
  • Lowered typing minDelay to 500ms and maxDelay to 8000ms
  • Reduced retry backoff in BaileysMessage.processor from 1000ms to 200ms
src/api/integrations/chatbot/base-chatbot.service.ts
src/api/integrations/channel/whatsapp/baileysMessage.processor.ts

Possibly linked issues

  • #ERR_REQUIRE_ESM: The PR migrates the project to ES Modules, which directly resolves the ERR_REQUIRE_ESM error described in the issue, making CommonJS require() compatible with ES Modules.

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 there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:119-121` </location>
<code_context>
+-    await this.waMonitor.waInstances[instance.instanceName].setChatwoot(data);
++    const waInstance = this.waMonitor.waInstances[instance.instanceName];
++
++    if (!waInstance) {
++      this.logger.error(`Instance ${instance.instanceName} not found`);
++      throw new Error(`Instance ${instance.instanceName} not found`);
++    }
++
</code_context>

<issue_to_address>
**suggestion:** Error thrown for missing waInstance could be more specific.

Using a custom error type like NotFoundError or BadRequestException will make it easier to handle this specific case and improve clarity for error consumers.

Suggested implementation:

```typescript
++    if (!waInstance) {
++      this.logger.error(`Instance ${instance.instanceName} not found`);
++      throw new NotFoundException(`Instance ${instance.instanceName} not found`);
++    }

```

```typescript
import { NotFoundException } from '@nestjs/common';

```
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:3401` </location>
<code_context>
+ 
+     if (normalNumbersNotInCache.length > 0) {
+       this.logger.verbose(`Checking ${normalNumbersNotInCache.length} numbers via Baileys (not found in cache)`);
+-      verify = await this.client.onWhatsApp(...normalNumbersNotInCache);
++      verify = (await this.client.onWhatsApp(...normalNumbersNotInCache)) as any;
+     }
+ 
</code_context>

<issue_to_address>
**suggestion:** Casting to 'any' may hide type issues.

Consider specifying the expected type for the result of onWhatsApp instead of casting to 'any' to preserve type safety.

Suggested implementation:

```typescript
      verify = (await this.client.onWhatsApp(...normalNumbersNotInCache)) as WhatsAppVerificationResult[];

```

You will need to ensure that the type `WhatsAppVerificationResult` (or the correct expected type) is defined and imported in this file. If the type is not already defined, create an appropriate interface or type alias that matches the structure returned by `onWhatsApp`.
</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 on lines +119 to +121
if (!waInstance) {
this.logger.error(`Instance ${instance.instanceName} not found`);
throw new Error(`Instance ${instance.instanceName} not found`);
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Error thrown for missing waInstance could be more specific.

Using a custom error type like NotFoundError or BadRequestException will make it easier to handle this specific case and improve clarity for error consumers.

Suggested implementation:

++    if (!waInstance) {
++      this.logger.error(`Instance ${instance.instanceName} not found`);
++      throw new NotFoundException(`Instance ${instance.instanceName} not found`);
++    }
import { NotFoundException } from '@nestjs/common';

- Add Vue.js QR code scanner interface in dist_extensions/
- Configure Express to serve static files from dist_extensions/ at /qrcode route
- Add comprehensive QR code documentation in docs/scan_qrcode/
- Include nginx configuration examples and setup guides
- Add documentation for editMessage feature

BREAKING CHANGE: QR code interface now served as separate Vue.js SPA at /qrcode/ endpoint
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.

4 participants