Cayo oliveira/cu 86af019hb/5 backend envio de mensagens baileys#227
Conversation
…eation logic for baileys single contact conversation
…idual and group contacts
…to Cayo-Oliveira/CU-86af01932/4-Backend-Gerenciamento-dos-grupos
… keys for send message in group conversations
|
Task linked: CU-86af01932 4 - Backend - Gerenciamento dos grupos |
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThis pull request introduces WhatsApp message receipt update handling through a new handler module that processes receipt status changes (sent → delivered → read), enforces valid status transitions, and updates conversation agent/assignee timestamps. Additionally, the WhatsApp Baileys provider undergoes refactoring to centralize message key generation, and comprehensive test coverage is added for receipt transitions and group message scenarios. Changes
Sequence DiagramsequenceDiagram
actor Baileys as WhatsApp Baileys API
participant Service as IncomingMessageBaileysService
participant Handler as MessageReceiptUpdate Handler
participant Message as Message Model
participant Conversation as Conversation Model
Baileys->>Service: message-receipt.update event
Service->>Handler: process_message_receipt_update(receipts)
Handler->>Handler: iterate receipts
Handler->>Message: find message by key
Message-->>Handler: message found
Handler->>Handler: extract status (read/delivered)
Handler->>Handler: validate transition allowed?
alt Transition Valid
Handler->>Message: update status
Message->>Message: save!
Message-->>Handler: ✓ saved
alt Incoming Message & Read Status
Handler->>Conversation: update agent_last_seen_at
Handler->>Conversation: update assignee_last_seen_at
Conversation->>Conversation: save!
Conversation-->>Handler: ✓ timestamps updated
end
else Transition Invalid
Handler->>Handler: skip (no-op)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Pull request overview
Enhances the WhatsApp Baileys integration by correctly building message keys for group operations (including participant for incoming group messages) and by handling Baileys receipt events to update Chatwoot message delivery/read statuses.
Changes:
- Added a reusable
message_key_forhelper to includeparticipantfor incoming group message keys across multiple Baileys API operations. - Added a new Baileys handler for
message-receipt.updateto transition message statuses (sent → delivered → read) and update conversation last-seen timestamps. - Refactored last-seen updates in
MessagesUpdateto usesave!(instead ofupdate_columns) for consistency with the new handler.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| spec/services/whatsapp/providers/whatsapp_baileys_service_spec.rb | Adds specs ensuring group message keys include participant only when required (incoming group messages). |
| spec/services/whatsapp/incoming_message_baileys_service_spec.rb | Adds specs for message-receipt.update status transitions and conversation timestamp updates. |
| app/services/whatsapp/providers/whatsapp_baileys_service.rb | Introduces message_key_for + group participant handling and applies it across relevant methods. |
| app/services/whatsapp/incoming_message_baileys_service.rb | Wires the new MessageReceiptUpdate handler into the Baileys incoming service. |
| app/services/whatsapp/baileys_handlers/messages_update.rb | Changes conversation last-seen updates from update_columns to save!. |
| app/services/whatsapp/baileys_handlers/message_receipt_update.rb | New handler for Baileys receipt updates and conversation last-seen updates. |
| .claude/skills/rspec-tests/SKILL.md | Adds project guidance for writing/maintaining RSpec tests. |
Comments suppressed due to low confidence (3)
app/services/whatsapp/baileys_handlers/messages_update.rb:67
update_last_seen_atnow usessave!, which will updateupdated_atand runbefore_save/after_update_commitcallbacks onConversation. Elsewhere (e.g. ConversationsController)agent_last_seen_atupdates intentionally useupdate_columnsto avoid these side effects. Consider switching back toupdate_columns(with the existing rubocop disable) so receipt/read processing doesn’t create extra DB churn or trigger callbacks.
conversation.agent_last_seen_at = Time.current
conversation.assignee_last_seen_at = Time.current if conversation.assignee_id.present?
conversation.save!
app/services/whatsapp/baileys_handlers/message_receipt_update.rb:28
update_last_seen_at_from_receiptis only called afterreceipt_status_transition_allowed?. Because that method returns false when the message is alreadyread, duplicate/latereadTimestampreceipts will never updateconversation.agent_last_seen_at/assignee_last_seen_at. InMessagesUpdate, last-seen timestamps are updated before the transition guard, so they still advance even when status doesn’t change. Consider updating last-seen timestamps based on the receipt payload before/independent of the status-transition check (while still preventing status downgrades).
def handle_receipt_update
return unless find_message_by_source_id(raw_message_id)
new_status = receipt_status
return if new_status.nil?
return unless receipt_status_transition_allowed?(new_status)
update_last_seen_at_from_receipt if incoming? && new_status == 'read'
@message.update!(status: new_status)
app/services/whatsapp/baileys_handlers/message_receipt_update.rb:50
update_last_seen_at_from_receiptusesconversation.save!, which will touchupdated_atand runConversationcallbacks on every read receipt. Other parts of the codebase update last-seen fields viaupdate_columnsto avoid callbacks/timestamp churn. Consider usingupdate_columns(agent_last_seen_at: ..., assignee_last_seen_at: ...)here as well (with the rubocop disable) to keep receipt processing lightweight.
def update_last_seen_at_from_receipt
conversation = @message.conversation
conversation.agent_last_seen_at = Time.current
conversation.assignee_last_seen_at = Time.current if conversation.assignee_id.present?
conversation.save!
There was a problem hiding this comment.
🧹 Nitpick comments (1)
app/services/whatsapp/baileys_handlers/message_receipt_update.rb (1)
46-50: Consider extracting shared last-seen updater to avoid logic drift.This block duplicates
update_last_seen_atfromapp/services/whatsapp/baileys_handlers/messages_update.rband can diverge over time.♻️ Suggested refactor
# app/services/whatsapp/baileys_handlers/helpers.rb (or a shared concern) +def update_conversation_last_seen!(conversation) + now = Time.current + conversation.agent_last_seen_at = now + conversation.assignee_last_seen_at = now if conversation.assignee_id.present? + conversation.save! +end# app/services/whatsapp/baileys_handlers/message_receipt_update.rb def update_last_seen_at_from_receipt - conversation = `@message.conversation` - conversation.agent_last_seen_at = Time.current - conversation.assignee_last_seen_at = Time.current if conversation.assignee_id.present? - conversation.save! + update_conversation_last_seen!(`@message.conversation`) end# app/services/whatsapp/baileys_handlers/messages_update.rb def update_last_seen_at - conversation = `@message.conversation` - conversation.agent_last_seen_at = Time.current - conversation.assignee_last_seen_at = Time.current if conversation.assignee_id.present? - conversation.save! + update_conversation_last_seen!(`@message.conversation`) end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/services/whatsapp/baileys_handlers/message_receipt_update.rb` around lines 46 - 50, The two handlers duplicate last-seen update logic (update_last_seen_at_from_receipt in app/services/whatsapp/baileys_handlers/message_receipt_update.rb and update_last_seen_at in app/services/whatsapp/baileys_handlers/messages_update.rb); extract the shared behavior into a single helper method (e.g., Conversation#touch_last_seen!, or a small module/class LastSeenUpdater.call(conversation)) that sets agent_last_seen_at = Time.current and only sets assignee_last_seen_at when conversation.assignee_id.present?, then replace both update_last_seen_at_from_receipt and update_last_seen_at to call that new helper; ensure you preserve bang-save semantics (save! or equivalent) and run/update tests that reference either original methods.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@app/services/whatsapp/baileys_handlers/message_receipt_update.rb`:
- Around line 46-50: The two handlers duplicate last-seen update logic
(update_last_seen_at_from_receipt in
app/services/whatsapp/baileys_handlers/message_receipt_update.rb and
update_last_seen_at in
app/services/whatsapp/baileys_handlers/messages_update.rb); extract the shared
behavior into a single helper method (e.g., Conversation#touch_last_seen!, or a
small module/class LastSeenUpdater.call(conversation)) that sets
agent_last_seen_at = Time.current and only sets assignee_last_seen_at when
conversation.assignee_id.present?, then replace both
update_last_seen_at_from_receipt and update_last_seen_at to call that new
helper; ensure you preserve bang-save semantics (save! or equivalent) and
run/update tests that reference either original methods.
ℹ️ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
.claude/skills/rspec-tests/SKILL.mdapp/services/whatsapp/baileys_handlers/message_receipt_update.rbapp/services/whatsapp/baileys_handlers/messages_update.rbapp/services/whatsapp/incoming_message_baileys_service.rbapp/services/whatsapp/providers/whatsapp_baileys_service.rbspec/services/whatsapp/incoming_message_baileys_service_spec.rbspec/services/whatsapp/providers/whatsapp_baileys_service_spec.rb
…grupos' into Cayo-Oliveira/CU-86af019hb/5-Backend-Envio-de-mensagens-Baileys
…ad updates in group
|
Task linked: CU-86af00yvg 2 - Backend - Models (Main PR) |
gabrieljablonski
left a comment
There was a problem hiding this comment.
-(review needed) +(approved for merge)
@gabrieljablonski reviewed 56 files and all commit messages, and made 1 comment.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on CayoPOliveira).
…to Cayo-Oliveira/CU-86af019hb/5-Backend-Envio-de-mensagens-Baileys
569c780
into
Cayo-Oliveira/CU-86af00yvg/2-Backend-Models-Main-PR
WhatsApp Baileys: Message sending enhancements for group conversations & receipt updates
Summary
This PR builds on top of the group management branch by adding proper message key handling for group conversations and implementing message receipt status updates from Baileys.
Changes
Message key participant handling for groups
message_key_forhelper inWhatsappBaileysServicethat builds WhatsApp message keys with theparticipantfield for incoming messages in group conversations (@g.usJIDs). This ensures Baileys correctly identifies message authors when performing operations like quoting, reacting, reading, deleting, and editing messages in groups.read_messages,unread_message,received_messages,send_message(quoted replies & reactions),delete_message, andedit_message.Message receipt update handler
Whatsapp::BaileysHandlers::MessageReceiptUpdatemodule to handlemessage-receipt.updateevents from Baileys.sent → delivered(onreceiptTimestamp) andsent/delivered → read(onreadTimestamp), with guards preventing status downgrades.agent_last_seen_atandassignee_last_seen_aton the conversation when an incoming message is marked as read.with_baileys_channel_lock_on_outgoing_messagefor outgoing messages to avoid race conditions withSendOnWhatsappService.Minor refactor
update_columnstosave!inMessagesUpdate#update_last_seen_atfor consistency with the new receipt handler.Tests
MessageReceiptUpdate(status transitions, downgrade prevention, conversation timestamp updates).WhatsappBaileysServicemethods (send_message,read_messages,unread_message,received_messages,delete_message,edit_message).GroupMembersControllerspecs to remove service mocking.This change is
Summary by CodeRabbit
New Features
Tests