diff --git a/lib/services/email-service.ts b/lib/services/email-service.ts index 2b05df46..b122d16f 100644 --- a/lib/services/email-service.ts +++ b/lib/services/email-service.ts @@ -274,6 +274,11 @@ export async function getEmails( ): Promise { console.log(`Fetching emails for user ${userId}${accountId ? ` account ${accountId}` : ''} in folder ${folder}`); + // Extract the base folder name if it's an account-specific folder + const baseFolder = accountId && folder.endsWith(`-${accountId}`) + ? folder.slice(0, -accountId.length - 1) + : folder; + // Try to get from cache first const cached = await getCachedEmailList(userId, accountId || 'default', folder, page, perPage); if (cached) { @@ -288,11 +293,11 @@ export async function getEmails( } try { - // Open the mailbox - await client.mailboxOpen(folder); + // Open the mailbox using the base folder name + await client.mailboxOpen(baseFolder); // Get total count of messages - const status = await client.status(folder, { messages: true }); + const status = await client.status(baseFolder, { messages: true }); const totalEmails = status.messages || 0; const totalPages = Math.ceil(totalEmails / perPage); @@ -334,7 +339,7 @@ export async function getEmails( }, size: message.size || 0, hasAttachments: message.bodyStructure?.childNodes?.some(node => node.disposition === 'attachment') || false, - folder: folder, + folder: folder, // Use the original folder name with account ID contentFetched: false, accountId: accountId, content: '', @@ -351,26 +356,13 @@ export async function getEmails( perPage, totalPages, folder, - mailboxes: await getMailboxes(client) + mailboxes: await getMailboxes(client, accountId) // Pass accountId to getMailboxes }; - // Cache the result with the correct accountId + // Cache the result with the account-specific folder await cacheEmailList(userId, accountId || 'default', folder, page, perPage, result); - // Invalidate cache for other accounts' folders to prevent stale data - if (accountId) { - const accounts = await prisma.mailCredentials.findMany({ - where: { userId }, - select: { id: true } - }); - - for (const account of accounts) { - if (account.id !== accountId) { - await invalidateFolderCache(userId, account.id, folder); - } - } - } - + // No need to invalidate other accounts' caches since folders are now account-specific return result; } finally { try { @@ -594,11 +586,11 @@ export async function sendEmail( /** * Get list of mailboxes from an IMAP connection */ -export async function getMailboxes(client: ImapFlow): Promise { +export async function getMailboxes(client: ImapFlow, accountId?: string): Promise { try { const mailboxes = await client.list(); - // Map special folders to standard names + // Map special folders to standard names, but keep account-specific paths const specialFolders = new Map([ ['Sent Messages', 'Sent'], ['Sent Items', 'Sent'], @@ -608,27 +600,35 @@ export async function getMailboxes(client: ImapFlow): Promise { ['Spam', 'Junk'] ]); - // Process mailboxes and map special folders + // Process mailboxes and map special folders while preserving account-specific paths const processedMailboxes = mailboxes.map(mailbox => { const path = mailbox.path; // Check if this is a special folder for (const [special, standard] of specialFolders) { if (path.includes(special)) { - return standard; + // Include accountId in the folder name to make it unique per account + return accountId ? `${standard}-${accountId}` : standard; } } - return path; + // Include accountId in the folder name to make it unique per account + return accountId ? `${path}-${accountId}` : path; }); - // Ensure we have all standard folders - const standardFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; + // Ensure we have all standard folders with account-specific names + const standardFolders = accountId + ? ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'].map(f => `${f}-${accountId}`) + : ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; + const uniqueFolders = new Set([...standardFolders, ...processedMailboxes]); return Array.from(uniqueFolders); } catch (error) { console.error('Error fetching mailboxes:', error); - // Return default folders on error - return ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; + // Return default folders on error, with account-specific names if accountId is provided + const defaultFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; + return accountId + ? defaultFolders.map(f => `${f}-${accountId}`) + : defaultFolders; } }