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);
|
||||
};
|
||||
|
||||
// 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 = () => (
|
||||
<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">
|
||||
{/* Standard folder items */}
|
||||
{initialSidebarItems.slice(0, 5).map((item) => (
|
||||
{sidebarItems.map((item) => (
|
||||
<li key={item.view}>
|
||||
<Button
|
||||
variant={currentView === item.view ? 'secondary' : 'ghost'}
|
||||
@ -1343,38 +1238,6 @@ export default function CourrierPage() {
|
||||
</Button>
|
||||
</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>
|
||||
</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) {
|
||||
return (
|
||||
<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>
|
||||
</div>
|
||||
</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>
|
||||
|
||||
{/* Accounts Section */}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user