panel 2 courier api restore
This commit is contained in:
parent
28a63aef31
commit
77fdd5cd46
@ -533,159 +533,90 @@ export default function CourrierPage() {
|
|||||||
return emails.find(email => email.id === selectedEmail?.id);
|
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(() => {
|
useEffect(() => {
|
||||||
const initialize = async () => {
|
const loadInitialData = async () => {
|
||||||
try {
|
try {
|
||||||
console.log('Initializing email client...');
|
console.log('Loading initial email data...');
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setIsLoadingInitial(true);
|
setIsLoadingInitial(true);
|
||||||
setError(null);
|
|
||||||
|
|
||||||
// First check stored credentials
|
// Check credentials first
|
||||||
console.log('Checking for stored credentials...');
|
|
||||||
const credResponse = await fetch('/api/courrier');
|
const credResponse = await fetch('/api/courrier');
|
||||||
if (!credResponse.ok) {
|
if (!credResponse.ok) {
|
||||||
const errorData = await credResponse.json();
|
const errorData = await credResponse.json();
|
||||||
console.log('API response error:', errorData);
|
|
||||||
if (errorData.error === 'No stored credentials found') {
|
if (errorData.error === 'No stored credentials found') {
|
||||||
console.log('No credentials found, redirecting to login...');
|
|
||||||
router.push('/courrier/login');
|
router.push('/courrier/login');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw new Error(errorData.error || 'Failed to check credentials');
|
throw new Error(errorData.error || 'Failed to check credentials');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then check mail credentials
|
// Then load emails (forced fetch with timestamp)
|
||||||
const mailCredResponse = await fetch('/api/courrier/login');
|
const timestamp = Date.now();
|
||||||
if (!mailCredResponse.ok) {
|
const emailResponse = await fetch(
|
||||||
throw new Error('Mail credentials not found');
|
`/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
|
const data = await emailResponse.json();
|
||||||
console.log('Loading emails and folders...');
|
console.log(`Loaded ${data.emails?.length || 0} emails`);
|
||||||
await loadEmails();
|
|
||||||
|
|
||||||
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) {
|
} catch (err) {
|
||||||
console.error('Error initializing email client:', err);
|
console.error('Error loading initial data:', err);
|
||||||
setError(err instanceof Error ? err.message : 'Failed to initialize email client');
|
setError(err instanceof Error ? err.message : 'Failed to load data');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setIsLoadingInitial(false);
|
setIsLoadingInitial(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
initialize();
|
loadInitialData();
|
||||||
}, [router]);
|
}, [router, currentView, page, emailsPerPage]);
|
||||||
|
|
||||||
// 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]);
|
|
||||||
|
|
||||||
// Get account color
|
// Get account color
|
||||||
const getAccountColor = (accountId: number) => {
|
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 = () => (
|
const renderSidebarNav = () => (
|
||||||
<nav className="p-3">
|
<nav className="p-3">
|
||||||
<div className="flex justify-between items-center mb-3 px-2">
|
|
||||||
<h2 className="text-sm font-semibold">Mail</h2>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
// Force reload with skipCache=true
|
|
||||||
fetch(`/api/courrier?folder=${encodeURIComponent(currentView)}&skipCache=true`)
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.folders && data.folders.length > 0) {
|
|
||||||
setAvailableFolders(data.folders);
|
|
||||||
const folderSidebarItems = data.folders.map((folderName: string) => ({
|
|
||||||
label: folderName,
|
|
||||||
view: folderName,
|
|
||||||
icon: getFolderIcon(folderName)
|
|
||||||
}));
|
|
||||||
|
|
||||||
setSidebarItems(prevItems => {
|
|
||||||
const standardItems = initialSidebarItems.slice(0, 5);
|
|
||||||
return [...standardItems, ...folderSidebarItems];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
loadEmails();
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Error refreshing folders:', error);
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
className="h-8 w-8 p-0"
|
|
||||||
title="Refresh folders"
|
|
||||||
>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<ul className="space-y-0.5 px-2">
|
<ul className="space-y-0.5 px-2">
|
||||||
{/* Standard folder items */}
|
{sidebarItems.map((item) => (
|
||||||
{initialSidebarItems.slice(0, 5).map((item) => (
|
|
||||||
<li key={item.view}>
|
<li key={item.view}>
|
||||||
<Button
|
<Button
|
||||||
variant={currentView === item.view ? 'secondary' : 'ghost'}
|
variant={currentView === item.view ? 'secondary' : 'ghost'}
|
||||||
@ -1343,38 +1238,6 @@ export default function CourrierPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{/* Divider */}
|
|
||||||
<li className="py-2">
|
|
||||||
<div className="flex items-center">
|
|
||||||
<div className="h-px flex-1 bg-gray-200"></div>
|
|
||||||
<div className="text-xs text-gray-500 px-2">Folders</div>
|
|
||||||
<div className="h-px flex-1 bg-gray-200"></div>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
|
|
||||||
{/* Folder items from server */}
|
|
||||||
{availableFolders
|
|
||||||
.filter(folder => !['INBOX', 'Sent', 'Drafts', 'Trash', 'Spam'].includes(folder)) // Filter out standard folders
|
|
||||||
.map((folder) => (
|
|
||||||
<li key={folder}>
|
|
||||||
<Button
|
|
||||||
variant={currentView === folder ? 'secondary' : 'ghost'}
|
|
||||||
className={`w-full justify-start py-2 ${
|
|
||||||
currentView === folder ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'
|
|
||||||
}`}
|
|
||||||
onClick={() => {
|
|
||||||
setCurrentView(folder);
|
|
||||||
setSelectedEmail(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="flex items-center">
|
|
||||||
<Folder className="h-4 w-4 mr-2" />
|
|
||||||
<span>{folder}</span>
|
|
||||||
</div>
|
|
||||||
</Button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
@ -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) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
|
<div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
|
||||||
@ -1625,17 +1580,6 @@ export default function CourrierPage() {
|
|||||||
<span>Compose</span>
|
<span>Compose</span>
|
||||||
</div>
|
</div>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={() => {
|
|
||||||
setLoading(true);
|
|
||||||
loadEmails();
|
|
||||||
}}
|
|
||||||
className="text-gray-600 hover:text-gray-900 hover:bg-gray-100"
|
|
||||||
>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Accounts Section */}
|
{/* Accounts Section */}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user