courrier multi account restore compose

This commit is contained in:
alma 2025-04-28 17:22:15 +02:00
parent cc74bfc728
commit ab75d01666
2 changed files with 69 additions and 98 deletions

View File

@ -334,29 +334,12 @@ export default function CourrierPage() {
console.log('allAccounts length:', data.allAccounts?.length || 0);
// Inspect each account's structure
if (data.allAccounts && Array.isArray(data.allAccounts)) {
data.allAccounts.forEach((account: any, idx: number) => {
console.log(`Account ${idx + 1}:`, {
id: account.id,
email: account.email,
display_name: account.display_name,
foldersExist: !!account.folders,
foldersIsArray: Array.isArray(account.folders),
foldersLength: account.folders?.length || 0,
folders: account.folders
});
});
}
if (!isMounted) return;
if (data.authenticated) {
if (data.hasEmailCredentials) {
console.log('Session initialized, prefetch status:', data.prefetchStarted ? 'running' : 'not started');
setPrefetchStarted(Boolean(data.prefetchStarted));
// Create a copy of the current accounts to update
const updatedAccounts = [{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500', folders: [] }];
let updatedAccounts: Account[] = [{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500', folders: [] }];
// Check if we have multiple accounts returned
if (data.allAccounts && Array.isArray(data.allAccounts) && data.allAccounts.length > 0) {
@ -370,9 +353,10 @@ export default function CourrierPage() {
folders: account.folders
});
// Use exact folders from IMAP without any mapping
const accountFolders = (account.folders && Array.isArray(account.folders))
? account.folders
: ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
: [];
updatedAccounts.push({
id: account.id,
@ -391,12 +375,9 @@ export default function CourrierPage() {
// Fallback to single account if allAccounts is not available
console.log(`[DEBUG] Fallback to single account: ${data.email}`);
// Force include some hardcoded folders if none are present
const fallbackFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
// Prioritize mailboxes from IMAP if available
// Use exact folders from IMAP if available
const folderList = (data.mailboxes && data.mailboxes.length > 0) ?
data.mailboxes : fallbackFolders;
data.mailboxes : [];
updatedAccounts.push({
id: 'default-account',
@ -407,52 +388,53 @@ export default function CourrierPage() {
});
}
// Update the accounts state
// Update accounts state
setAccounts(updatedAccounts);
// Auto-select the first non-All account if available
if (updatedAccounts.length > 1) {
console.log('Auto-selecting account:', updatedAccounts[1]);
setSelectedAccount(updatedAccounts[1]);
setShowFolders(true);
// Ensure folders are visible for the selected account
setExpandedAccounts(prev => ({
...prev,
[updatedAccounts[1].id]: true
}));
// Set initial selected folder
setSelectedFolders(prev => ({
...prev,
[updatedAccounts[1].id]: 'INBOX'
}));
}
// Preload first page of emails for faster initial rendering
if (session?.user?.id) {
await loadEmails();
// If the user hasn't opened this page recently, trigger a background refresh
if (data.lastVisit && Date.now() - data.lastVisit > 5 * 60 * 1000) {
// It's been more than 5 minutes, refresh in background
try {
const refreshResponse = await fetch('/api/courrier/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ folder: currentFolder })
});
console.log('Background refresh triggered');
} catch (error) {
console.error('Failed to trigger background refresh', error);
}
}
}
console.log('[DEBUG] Updated accounts:', updatedAccounts);
} else {
// User is authenticated but doesn't have email credentials
setShowLoginNeeded(true);
}
}
// Auto-select the first non-All account if available
if (updatedAccounts.length > 1) {
console.log('Auto-selecting account:', updatedAccounts[1]);
setSelectedAccount(updatedAccounts[1]);
setShowFolders(true);
// Ensure folders are visible for the selected account
setExpandedAccounts(prev => ({
...prev,
[updatedAccounts[1].id]: true
}));
// Set initial selected folder
setSelectedFolders(prev => ({
...prev,
[updatedAccounts[1].id]: 'INBOX'
}));
}
// Preload first page of emails for faster initial rendering
if (session?.user?.id) {
await loadEmails();
// If the user hasn't opened this page recently, trigger a background refresh
if (data.lastVisit && Date.now() - data.lastVisit > 5 * 60 * 1000) {
// It's been more than 5 minutes, refresh in background
try {
const refreshResponse = await fetch('/api/courrier/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ folder: currentFolder })
});
console.log('Background refresh triggered');
} catch (error) {
console.error('Failed to trigger background refresh', error);
}
}
}
} catch (error) {
console.error('Error initializing session:', error);
} finally {
@ -585,13 +567,30 @@ export default function CourrierPage() {
if (!account) {
console.warn(`Account ${accountId} not found`);
toast({
title: "Account not found",
description: `The account ${accountId} could not be found.`,
variant: "destructive",
});
return;
}
// Ensure the account has initialized folders
if (!account.folders || account.folders.length === 0) {
console.warn(`No folders initialized for account ${accountId}`);
// Set default folders if none are initialized
account.folders = ['INBOX', 'SENT', 'DRAFTS', 'TRASH'];
}
// Use the exact folder name from the account's folders list
if (!account.folders.includes(folder)) {
console.warn(`Folder ${folder} not found in account ${accountId}`);
return;
console.warn(`Folder ${folder} not found in account ${accountId}, defaulting to INBOX`);
toast({
title: "Folder not found",
description: `The folder ${folder} does not exist for this account. Defaulting to INBOX.`,
variant: "destructive",
});
folder = 'INBOX'; // Default to INBOX if folder doesn't exist
}
// Update selected folders state

View File

@ -608,40 +608,12 @@ export async function getMailboxes(client: ImapFlow, accountId?: string): Promis
try {
const mailboxes = await client.list();
// Map special folders to standard names
const specialFolders = new Map<string, string>([
['Sent Messages', 'Sent'],
['Sent Items', 'Sent'],
['Drafts', 'Drafts'],
['Deleted Items', 'Trash'],
['Junk Email', 'Junk'],
['Spam', 'Junk']
]);
// Process mailboxes and map special folders
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;
}
}
return path;
});
// Ensure we have all standard folders
const standardFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
// Combine standard folders with custom folders
const uniqueFolders = new Set([...standardFolders, ...processedMailboxes]);
// Return unique folders without appending accountId
return Array.from(uniqueFolders);
// Return the exact folder names from IMAP without any mapping
return mailboxes.map(mailbox => mailbox.path);
} catch (error) {
console.error('Error fetching mailboxes:', error);
// Return default folders on error
return ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
// Return empty array on error to avoid showing incorrect folders
return [];
}
}