From a1e9936a3fac32b7f93202be38a224e51a78be10 Mon Sep 17 00:00:00 2001 From: richardtekula Date: Thu, 20 Nov 2025 08:05:02 +0100 Subject: [PATCH] Fix markContactEmailsAsRead to match by email address and fix duplicate contact IDs --- src/services/crm-email.service.js | 39 +++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/src/services/crm-email.service.js b/src/services/crm-email.service.js index b6a7668..e73d80d 100644 --- a/src/services/crm-email.service.js +++ b/src/services/crm-email.service.js @@ -209,11 +209,40 @@ export const markContactEmailsAsRead = async (userId, contactId) => { }); } - const result = await db - .update(emails) - .set({ isRead: true, updatedAt: new Date() }) - .where(and(eq(emails.userId, userId), eq(emails.contactId, contactId), eq(emails.isRead, false))) - .returning(); + // FIX: Mark emails as read by matching sender EMAIL, not just contactId + // This fixes the issue with duplicate contacts having different IDs + let result = []; + + if (contact) { + // Update ALL emails from this sender's email address: + // 1. Set the correct contactId (fixes duplicate contact issue) + // 2. Mark as read + result = await db + .update(emails) + .set({ + contactId: contactId, // Fix contactId for duplicate contacts + isRead: true, + updatedAt: new Date() + }) + .where(and( + eq(emails.userId, userId), + or( + eq(emails.from, contact.email), + like(emails.from, `%<${contact.email}>%`) + ), + eq(emails.isRead, false) + )) + .returning(); + + console.log('🔧 Fixed contactId and marked as read for emails from:', contact.email); + } else { + // Fallback: use old method if contact not found + result = await db + .update(emails) + .set({ isRead: true, updatedAt: new Date() }) + .where(and(eq(emails.userId, userId), eq(emails.contactId, contactId), eq(emails.isRead, false))) + .returning(); + } console.log('✅ markContactEmailsAsRead result:', { count: result.length, contactId });