courrier multi account restore compose

This commit is contained in:
alma 2025-04-28 13:48:11 +02:00
parent d3974536ff
commit 95ea63db2f

View File

@ -46,6 +46,27 @@ import { useCourrier, EmailData } from '@/hooks/use-courrier';
// Import the prefetching function // Import the prefetching function
import { prefetchFolderEmails } from '@/lib/services/prefetch-service'; import { prefetchFolderEmails } from '@/lib/services/prefetch-service';
// Import the Account interface
import { Account } from '@/lib/types';
// Frontend-specific account interface
interface FrontendAccount {
id: string | number;
name: string;
email: string;
color: string;
folders?: string[];
}
// Remove the redundant interfaces
interface EmailWithFlags {
id: string;
read?: boolean;
flags?: {
seen?: boolean;
};
}
// Simplified version for this component // Simplified version for this component
function SimplifiedLoadingFix() { function SimplifiedLoadingFix() {
// In production, don't render anything // In production, don't render anything
@ -61,22 +82,6 @@ function SimplifiedLoadingFix() {
); );
} }
interface Account {
id: string;
name: string;
email: string;
color: string;
folders?: string[];
}
interface EmailWithFlags {
id: string;
read?: boolean;
flags?: {
seen?: boolean;
};
}
export default function CourrierPage() { export default function CourrierPage() {
const router = useRouter(); const router = useRouter();
const { data: session } = useSession(); const { data: session } = useSession();
@ -124,16 +129,18 @@ export default function CourrierPage() {
const [showAddAccountForm, setShowAddAccountForm] = useState(false); const [showAddAccountForm, setShowAddAccountForm] = useState(false);
// Email accounts for the sidebar // Email accounts for the sidebar
const [accounts, setAccounts] = useState<Account[]>([ const defaultAccounts: Account[] = [
{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' }, { id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500', folders: [] },
{ id: 'loading-account', name: 'Loading...', email: '', color: 'bg-blue-500', folders: [] } { id: 'loading-account', name: 'Loading...', email: '', color: 'bg-blue-500', folders: [] }
]); ];
const [accounts, setAccounts] = useState<Account[]>(defaultAccounts);
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null); const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
// Track expanded folders for each account // Track expanded folders for each account
const [expandedAccounts, setExpandedAccounts] = useState<Record<string, boolean>>({}); const [expandedAccounts, setExpandedAccounts] = useState<Record<string, boolean>>({});
// Update account folders when mailboxes change - update this to maintain account IDs // Update account folders when mailboxes change
useEffect(() => { useEffect(() => {
console.log('Mailboxes updated:', mailboxes); console.log('Mailboxes updated:', mailboxes);
setAccounts(prev => { setAccounts(prev => {
@ -143,7 +150,7 @@ export default function CourrierPage() {
if (updated[1]) { if (updated[1]) {
updated[1] = { updated[1] = {
...updated[1], ...updated[1],
folders: mailboxes folders: mailboxes || []
}; };
} }
console.log('Updated accounts with new mailboxes:', updated); console.log('Updated accounts with new mailboxes:', updated);
@ -195,12 +202,9 @@ export default function CourrierPage() {
// If accounts array becomes empty (bug), restore default accounts // If accounts array becomes empty (bug), restore default accounts
if (!accounts || accounts.length === 0) { if (!accounts || accounts.length === 0) {
console.warn('Accounts array is empty, restoring defaults'); console.warn('Accounts array is empty, restoring defaults');
setAccounts([ setAccounts(defaultAccounts);
{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' },
{ id: 'loading-account', name: 'Loading...', email: '', color: 'bg-blue-500', folders: mailboxes }
]);
} }
}, [accounts, mailboxes]); }, [accounts]);
// Initialize session and start prefetching // Initialize session and start prefetching
useEffect(() => { useEffect(() => {
@ -296,81 +300,31 @@ export default function CourrierPage() {
setPrefetchStarted(Boolean(data.prefetchStarted)); setPrefetchStarted(Boolean(data.prefetchStarted));
// Create a copy of the current accounts to update // Create a copy of the current accounts to update
const updatedAccounts = [...accounts]; const updatedAccounts: Account[] = [
{
id: 'all-accounts' as string | number,
name: 'All',
email: '',
color: 'bg-gray-500',
folders: []
}
];
// Check if we have multiple accounts returned // Check if we have multiple accounts returned
if (data.allAccounts && Array.isArray(data.allAccounts) && data.allAccounts.length > 0) { if (data.allAccounts && Array.isArray(data.allAccounts)) {
console.log('[DEBUG] Multiple accounts found:', data.allAccounts.length); data.allAccounts.forEach((account: any) => {
// Get folders for this account
const accountFolders = account.folders || [];
// First, validate the structure of each account updatedAccounts.push({
data.allAccounts.forEach((account: any, index: number) => { id: account.id || `account-${Date.now()}`,
console.log(`[DEBUG] Account ${index+1} structure check:`, { name: account.display_name || account.email,
id: account.id,
email: account.email, email: account.email,
display_name: account.display_name, color: account.color || 'bg-blue-500',
hasFolders: !!account.folders, folders: accountFolders
foldersIsArray: Array.isArray(account.folders), } as Account);
foldersCount: Array.isArray(account.folders) ? account.folders.length : 0,
folders: account.folders || []
});
}); });
} else if (data.email) {
// Keep the All account at position 0
if (updatedAccounts.length > 0) {
// Replace the loading account with the real one
data.allAccounts.forEach((account: any, index: number) => {
// Ensure folders are valid
const accountFolders = (account.folders && Array.isArray(account.folders))
? account.folders
: (data.mailboxes && Array.isArray(data.mailboxes))
? data.mailboxes
: ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
// If we're updating the first real account (index 0 in API, position 1 in our array)
if (index === 0 && updatedAccounts.length > 1) {
// Update the loading account in place to maintain references
updatedAccounts[1] = {
id: account.id, // Use the real account ID
name: account.display_name || account.email,
email: account.email,
color: account.color || 'bg-blue-500',
folders: accountFolders
};
console.log(`[DEBUG] Updated loading account to real account: ${account.email} with ID ${account.id}`);
} else if (index > 0) {
// Add additional accounts as new entries
updatedAccounts.push({
id: account.id || `account-${index}`,
name: account.display_name || account.email,
email: account.email,
color: account.color || 'bg-blue-500',
folders: accountFolders
});
console.log(`[DEBUG] Added additional account: ${account.email} with ID ${account.id}`);
}
});
} else {
// Fallback if accounts array is empty for some reason
updatedAccounts.push({ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' });
// Add all accounts from the API response
data.allAccounts.forEach((account: any) => {
const accountFolders = (account.folders && Array.isArray(account.folders))
? account.folders
: (data.mailboxes && Array.isArray(data.mailboxes))
? data.mailboxes
: ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
updatedAccounts.push({
id: account.id,
name: account.display_name || account.email,
email: account.email,
color: account.color || 'bg-blue-500',
folders: accountFolders
});
});
}
} else {
// Fallback to single account if allAccounts is not available // Fallback to single account if allAccounts is not available
console.log(`[DEBUG] Fallback to single account: ${data.email}`); console.log(`[DEBUG] Fallback to single account: ${data.email}`);
@ -381,26 +335,13 @@ export default function CourrierPage() {
const folderList = (data.mailboxes && data.mailboxes.length > 0) ? const folderList = (data.mailboxes && data.mailboxes.length > 0) ?
data.mailboxes : fallbackFolders; data.mailboxes : fallbackFolders;
// Update the loading account if it exists updatedAccounts.push({
if (updatedAccounts.length > 1) { id: 'default-account' as string | number,
updatedAccounts[1] = { name: data.displayName || data.email,
id: 'default-account', // Use consistent ID email: data.email,
name: data.displayName || data.email, color: 'bg-blue-500',
email: data.email, folders: folderList
color: 'bg-blue-500', } as Account);
folders: folderList
};
} else {
// Fallback if accounts array is empty
updatedAccounts.push({ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' });
updatedAccounts.push({
id: 'default-account',
name: data.displayName || data.email,
email: data.email,
color: 'bg-blue-500',
folders: folderList
});
}
} }
console.log('Setting accounts:', updatedAccounts); console.log('Setting accounts:', updatedAccounts);
@ -503,12 +444,13 @@ export default function CourrierPage() {
// Also prefetch additional pages to make scrolling smoother // Also prefetch additional pages to make scrolling smoother
if (session?.user?.id) { if (session?.user?.id) {
// Prefetch next 2 pages beyond the current next page // Prefetch next 2 pages beyond the current next page
const accountIdStr = selectedAccount?.id ? String(selectedAccount.id) : undefined;
prefetchFolderEmails( prefetchFolderEmails(
session.user.id, session.user.id,
currentFolder, currentFolder,
2, 2,
nextPage + 1, nextPage + 1,
selectedAccount?.id accountIdStr
).catch(err => { ).catch(err => {
console.error(`Error prefetching additional pages for ${currentFolder}:`, err); console.error(`Error prefetching additional pages for ${currentFolder}:`, err);
}); });
@ -572,32 +514,36 @@ export default function CourrierPage() {
}; };
// Handle mailbox change with prefetching // Handle mailbox change with prefetching
const handleMailboxChange = (folder: string, accountId?: string) => { const handleMailboxChange = (folder: string, accountId?: string | number) => {
// Reset to page 1 when changing folders // Reset to page 1 when changing folders
setPage(1); setPage(1);
setCurrentView(folder);
changeFolder(folder);
// If we have a specific accountId, store it with the folder // If we have a specific accountId, store it with the folder
if (accountId) { if (accountId) {
// Store the current account ID with the folder change setSelectedAccount(accounts.find(a => String(a.id) === String(accountId)) || null);
console.log(`Changing folder to ${folder} for account ${accountId}`); console.log(`Changing folder to ${folder} for account ${accountId}`);
} else {
setSelectedAccount(null);
} }
// Change folder in the state
changeFolder(folder);
setCurrentView(folder);
// Start prefetching additional pages for this folder // Start prefetching additional pages for this folder
if (session?.user?.id && folder) { if (session?.user?.id && folder) {
// First two pages are most important - prefetch immediately // First two pages are most important - prefetch immediately
prefetchFolderEmails(session.user.id, folder, 3, 1, accountId).catch(err => { const accountIdStr = accountId ? String(accountId) : undefined;
console.error(`Error prefetching ${folder}:`, err); prefetchFolderEmails(session.user.id, folder, 3, 1, accountIdStr).catch(err => {
console.error('Error prefetching folder emails:', err);
}); });
} }
}; };
// Handle sending email // Handle sending email
const handleSendEmail = async (emailData: EmailData) => { const handleSendEmail = async (emailData: EmailData): Promise<void> => {
return await sendEmail(emailData); const result = await sendEmail(emailData);
if (!result.success) {
throw new Error(result.error || 'Failed to send email');
}
}; };
// Handle delete confirmation // Handle delete confirmation