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 { 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
function SimplifiedLoadingFix() {
// 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() {
const router = useRouter();
const { data: session } = useSession();
@ -124,16 +129,18 @@ export default function CourrierPage() {
const [showAddAccountForm, setShowAddAccountForm] = useState(false);
// Email accounts for the sidebar
const [accounts, setAccounts] = useState<Account[]>([
{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' },
const defaultAccounts: Account[] = [
{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-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);
// Track expanded folders for each account
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(() => {
console.log('Mailboxes updated:', mailboxes);
setAccounts(prev => {
@ -143,7 +150,7 @@ export default function CourrierPage() {
if (updated[1]) {
updated[1] = {
...updated[1],
folders: mailboxes
folders: mailboxes || []
};
}
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 || accounts.length === 0) {
console.warn('Accounts array is empty, restoring defaults');
setAccounts([
{ id: 'all-accounts', name: 'All', email: '', color: 'bg-gray-500' },
{ id: 'loading-account', name: 'Loading...', email: '', color: 'bg-blue-500', folders: mailboxes }
]);
setAccounts(defaultAccounts);
}
}, [accounts, mailboxes]);
}, [accounts]);
// Initialize session and start prefetching
useEffect(() => {
@ -296,81 +300,31 @@ export default function CourrierPage() {
setPrefetchStarted(Boolean(data.prefetchStarted));
// 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
if (data.allAccounts && Array.isArray(data.allAccounts) && data.allAccounts.length > 0) {
console.log('[DEBUG] Multiple accounts found:', data.allAccounts.length);
// First, validate the structure of each account
data.allAccounts.forEach((account: any, index: number) => {
console.log(`[DEBUG] Account ${index+1} structure check:`, {
id: account.id,
email: account.email,
display_name: account.display_name,
hasFolders: !!account.folders,
foldersIsArray: Array.isArray(account.folders),
foldersCount: Array.isArray(account.folders) ? account.folders.length : 0,
folders: account.folders || []
});
});
// 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' });
if (data.allAccounts && Array.isArray(data.allAccounts)) {
data.allAccounts.forEach((account: any) => {
// Get folders for this account
const accountFolders = account.folders || [];
// 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 {
updatedAccounts.push({
id: account.id || `account-${Date.now()}`,
name: account.display_name || account.email,
email: account.email,
color: account.color || 'bg-blue-500',
folders: accountFolders
} as Account);
});
} else if (data.email) {
// Fallback to single account if allAccounts is not available
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) ?
data.mailboxes : fallbackFolders;
// Update the loading account if it exists
if (updatedAccounts.length > 1) {
updatedAccounts[1] = {
id: 'default-account', // Use consistent ID
name: data.displayName || data.email,
email: data.email,
color: 'bg-blue-500',
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
});
}
updatedAccounts.push({
id: 'default-account' as string | number,
name: data.displayName || data.email,
email: data.email,
color: 'bg-blue-500',
folders: folderList
} as Account);
}
console.log('Setting accounts:', updatedAccounts);
@ -503,12 +444,13 @@ export default function CourrierPage() {
// Also prefetch additional pages to make scrolling smoother
if (session?.user?.id) {
// Prefetch next 2 pages beyond the current next page
const accountIdStr = selectedAccount?.id ? String(selectedAccount.id) : undefined;
prefetchFolderEmails(
session.user.id,
currentFolder,
2,
nextPage + 1,
selectedAccount?.id
accountIdStr
).catch(err => {
console.error(`Error prefetching additional pages for ${currentFolder}:`, err);
});
@ -572,32 +514,36 @@ export default function CourrierPage() {
};
// 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
setPage(1);
setCurrentView(folder);
changeFolder(folder);
// If we have a specific accountId, store it with the folder
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}`);
} else {
setSelectedAccount(null);
}
// Change folder in the state
changeFolder(folder);
setCurrentView(folder);
// Start prefetching additional pages for this folder
if (session?.user?.id && folder) {
// First two pages are most important - prefetch immediately
prefetchFolderEmails(session.user.id, folder, 3, 1, accountId).catch(err => {
console.error(`Error prefetching ${folder}:`, err);
const accountIdStr = accountId ? String(accountId) : undefined;
prefetchFolderEmails(session.user.id, folder, 3, 1, accountIdStr).catch(err => {
console.error('Error prefetching folder emails:', err);
});
}
};
// Handle sending email
const handleSendEmail = async (emailData: EmailData) => {
return await sendEmail(emailData);
const handleSendEmail = async (emailData: EmailData): Promise<void> => {
const result = await sendEmail(emailData);
if (!result.success) {
throw new Error(result.error || 'Failed to send email');
}
};
// Handle delete confirmation