Fix markContactEmailsAsRead to match by email address and fix duplicate contact IDs

This commit is contained in:
richardtekula
2025-11-20 08:05:02 +01:00
parent ed8875c00e
commit a1e9936a3f

View File

@@ -209,11 +209,40 @@ export const markContactEmailsAsRead = async (userId, contactId) => {
});
}
const result = await db
// 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 });