From 77fdd5cd4691d3a05399543cf83cf81d830eefb7 Mon Sep 17 00:00:00 2001 From: alma Date: Fri, 25 Apr 2025 18:54:03 +0200 Subject: [PATCH] panel 2 courier api restore --- app/courrier/page.tsx | 364 ++++++++++++++++++------------------------ 1 file changed, 154 insertions(+), 210 deletions(-) diff --git a/app/courrier/page.tsx b/app/courrier/page.tsx index f82516cd..b6155414 100644 --- a/app/courrier/page.tsx +++ b/app/courrier/page.tsx @@ -533,159 +533,90 @@ export default function CourrierPage() { return emails.find(email => email.id === selectedEmail?.id); }; - // Primary initialization effect - check credentials and load emails + // Single initialization effect that loads emails correctly on first page load useEffect(() => { - const initialize = async () => { + const loadInitialData = async () => { try { - console.log('Initializing email client...'); + console.log('Loading initial email data...'); setLoading(true); setIsLoadingInitial(true); - setError(null); - // First check stored credentials - console.log('Checking for stored credentials...'); + // Check credentials first const credResponse = await fetch('/api/courrier'); if (!credResponse.ok) { const errorData = await credResponse.json(); - console.log('API response error:', errorData); if (errorData.error === 'No stored credentials found') { - console.log('No credentials found, redirecting to login...'); router.push('/courrier/login'); return; } throw new Error(errorData.error || 'Failed to check credentials'); } - // Then check mail credentials - const mailCredResponse = await fetch('/api/courrier/login'); - if (!mailCredResponse.ok) { - throw new Error('Mail credentials not found'); + // Then load emails (forced fetch with timestamp) + const timestamp = Date.now(); + const emailResponse = await fetch( + `/api/courrier?folder=${encodeURIComponent(currentView)}&page=${page}&limit=${emailsPerPage}&_t=${timestamp}`, + { cache: 'no-store' } + ); + + if (!emailResponse.ok) { + throw new Error('Failed to load emails'); } - const mailCredData = await mailCredResponse.json(); - console.log('Mail credentials found:', mailCredData.email); - // Then load emails with folders - console.log('Loading emails and folders...'); - await loadEmails(); + const data = await emailResponse.json(); + console.log(`Loaded ${data.emails?.length || 0} emails`); - console.log('Initialization complete'); + // Set available folders if present + if (data.folders) { + setAvailableFolders(data.folders); + } + + // Process emails and sort by date + const processedEmails = (data.emails || []) + .map((email: any) => ({ + id: email.id, + accountId: 1, + from: email.from || '', + fromName: email.fromName || email.from?.split('@')[0] || '', + to: email.to || '', + subject: email.subject || '(No subject)', + content: email.preview || '', + date: email.date || new Date().toISOString(), + read: email.read || false, + starred: email.starred || false, + folder: email.folder || currentView, + cc: email.cc, + bcc: email.bcc, + flags: email.flags || [], + hasAttachments: email.hasAttachments || false + })) + .sort((a: Email, b: Email) => new Date(b.date).getTime() - new Date(a.date).getTime()); + + // Set emails + setEmails(processedEmails); + + // Update unread count for inbox + if (currentView === 'INBOX') { + const unreadInboxEmails = processedEmails.filter( + (email: Email) => !email.read && email.folder === 'INBOX' + ).length; + setUnreadCount(unreadInboxEmails); + } + + // Update pagination + setHasMore(data.hasMore); + setError(null); } catch (err) { - console.error('Error initializing email client:', err); - setError(err instanceof Error ? err.message : 'Failed to initialize email client'); + console.error('Error loading initial data:', err); + setError(err instanceof Error ? err.message : 'Failed to load data'); } finally { setLoading(false); setIsLoadingInitial(false); } }; - - initialize(); - }, [router]); - - // Update your loadEmails function for better debugging - const loadEmails = async (isLoadMore = false) => { - try { - // Skip if already loading - if (!isLoadMore && (isLoadingInitial || isLoadingMore)) { - console.log('Skipping email load - already loading'); - return; - } - - if (isLoadMore) { - setIsLoadingMore(true); - } else if (!isLoadingInitial) { - setLoading(true); - } - - console.log(`Loading emails for ${currentView}, page ${page}...`); - - // Add timestamp parameter to force fresh data when needed - const timestamp = `&_t=${Date.now()}`; - - const response = await fetch( - `/api/courrier?folder=${encodeURIComponent(currentView)}&page=${page}&limit=${emailsPerPage}${timestamp}`, - { cache: 'no-store' } - ); - - if (!response.ok) { - throw new Error('Failed to load emails'); - } - - const data = await response.json(); - console.log(`Received ${data.emails?.length || 0} emails, ${data.folders?.length || 0} folders`); - - // Set available folders - if (data.folders && data.folders.length > 0) { - setAvailableFolders(data.folders); - } - - // Process emails keeping exact folder names and sort by date - const processedEmails = (data.emails || []) - .map((email: any) => ({ - id: email.id, - accountId: 1, - from: email.from || '', - fromName: email.fromName || email.from?.split('@')[0] || '', - to: email.to || '', - subject: email.subject || '(No subject)', - content: email.preview || '', // Store preview as initial content - date: email.date || new Date().toISOString(), - read: email.read || false, - starred: email.starred || false, - folder: email.folder || currentView, - cc: email.cc, - bcc: email.bcc, - flags: email.flags || [], - hasAttachments: email.hasAttachments || false - })); - - // Sort emails by date, ensuring most recent first - const sortedEmails = processedEmails.sort((a: Email, b: Email) => { - const dateA = new Date(a.date).getTime(); - const dateB = new Date(b.date).getTime(); - return dateB - dateA; // Most recent first - }); - - // Combine with existing emails when loading more - setEmails(prev => { - if (isLoadMore) { - // Filter out duplicates when appending - const existingIds = new Set(prev.map(email => email.id)); - const uniqueNewEmails = sortedEmails.filter((email: Email) => !existingIds.has(email.id)); - return [...prev, ...uniqueNewEmails]; - } else { - return sortedEmails; - } - }); - - // Only update unread count if we're in the Inbox folder - if (currentView === 'INBOX') { - const unreadInboxEmails = sortedEmails.filter( - (email: Email) => !email.read && email.folder === 'INBOX' - ).length; - setUnreadCount(unreadInboxEmails); - } - - // Update pagination info - setHasMore(data.hasMore); - - setError(null); - console.log('Emails loaded successfully'); - } catch (err) { - console.error('Error loading emails:', err); - setError('Failed to load emails. Please try again.'); - } finally { - setLoading(false); - setIsLoadingMore(false); - setIsLoadingInitial(false); - } - }; - - // Add an effect to reload emails when the view changes - useEffect(() => { - setPage(1); // Reset page when view changes - setHasMore(true); - loadEmails(); - }, [currentView]); + + loadInitialData(); + }, [router, currentView, page, emailsPerPage]); // Get account color const getAccountColor = (accountId: number) => { @@ -1277,47 +1208,11 @@ export default function CourrierPage() { } }; - // Render the sidebar navigation + // Fix the sidebar navigation without the folders section and divider const renderSidebarNav = () => ( ); @@ -1557,6 +1420,98 @@ export default function CourrierPage() { ); }; + // Keep the loadEmails function for other parts of the code to use + const loadEmails = async (isLoadMore = false) => { + try { + // Skip if already loading + if (isLoadingInitial || isLoadingMore) { + return; + } + + if (isLoadMore) { + setIsLoadingMore(true); + } else { + setLoading(true); + } + + // Fetch emails with timestamp for cache busting + const timestamp = Date.now(); + const response = await fetch( + `/api/courrier?folder=${encodeURIComponent(currentView)}&page=${page}&limit=${emailsPerPage}&_t=${timestamp}`, + { cache: 'no-store' } + ); + + if (!response.ok) { + throw new Error('Failed to load emails'); + } + + const data = await response.json(); + + // Set available folders + if (data.folders) { + setAvailableFolders(data.folders); + } + + // Process and sort emails + const processedEmails = (data.emails || []) + .map((email: any) => ({ + id: email.id, + accountId: 1, + from: email.from || '', + fromName: email.fromName || email.from?.split('@')[0] || '', + to: email.to || '', + subject: email.subject || '(No subject)', + content: email.preview || '', + date: email.date || new Date().toISOString(), + read: email.read || false, + starred: email.starred || false, + folder: email.folder || currentView, + cc: email.cc, + bcc: email.bcc, + flags: email.flags || [], + hasAttachments: email.hasAttachments || false + })) + .sort((a: Email, b: Email) => new Date(b.date).getTime() - new Date(a.date).getTime()); + + // Set emails appropriately + setEmails(prev => { + if (isLoadMore) { + // Filter out duplicates when appending + const existingIds = new Set(prev.map(email => email.id)); + const uniqueNewEmails = processedEmails.filter((email: Email) => !existingIds.has(email.id)); + return [...prev, ...uniqueNewEmails]; + } else { + return processedEmails; + } + }); + + // Update unread count + if (currentView === 'INBOX') { + const unreadInboxEmails = processedEmails.filter( + (email: Email) => !email.read && email.folder === 'INBOX' + ).length; + setUnreadCount(unreadInboxEmails); + } + + setHasMore(data.hasMore); + setError(null); + } catch (err) { + console.error('Error loading emails:', err); + setError('Failed to load emails'); + } finally { + setLoading(false); + setIsLoadingMore(false); + setIsLoadingInitial(false); + } + }; + + // Add back the view change effect + useEffect(() => { + setPage(1); // Reset page when view changes + setHasMore(true); + loadEmails(); + }, [currentView]); + if (error) { return (
@@ -1625,17 +1580,6 @@ export default function CourrierPage() { Compose
- {/* Accounts Section */}