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 });