courrier multi account restore compose

This commit is contained in:
alma 2025-04-30 14:26:54 +02:00
parent e5022de6be
commit bd0a906796
2 changed files with 175 additions and 3 deletions

View File

@ -180,9 +180,38 @@ export default function EmailSidebar({
console.log(`Folder ${baseFolderName} is selected for account ${accountId}`);
}
// Get unread count
const folderUnreadCount = unreadCount[accountId]?.[baseFolderName] ||
unreadCount[accountId]?.[prefixedFolder] || 0;
// Debug unread count structure
console.log('Unread count map structure:', unreadCount);
// Get unread count - check all possible formats
let folderUnreadCount = 0;
// First check if account exists in the map
if (unreadCount && unreadCount[accountId]) {
// Try the base folder name first
if (typeof unreadCount[accountId][baseFolderName] === 'number') {
folderUnreadCount = unreadCount[accountId][baseFolderName];
console.log(`Found unread count for ${baseFolderName}: ${folderUnreadCount}`);
}
// Then try the prefixed folder name
else if (typeof unreadCount[accountId][prefixedFolder] === 'number') {
folderUnreadCount = unreadCount[accountId][prefixedFolder];
console.log(`Found unread count for ${prefixedFolder}: ${folderUnreadCount}`);
}
// Finally try with uppercase/lowercase variations
else {
// Check for case-insensitive match
const folderMap = unreadCount[accountId];
for (const key in folderMap) {
if (key.toLowerCase() === baseFolderName.toLowerCase() ||
key.toLowerCase() === prefixedFolder.toLowerCase()) {
folderUnreadCount = folderMap[key];
console.log(`Found unread count with case-insensitive match ${key}: ${folderUnreadCount}`);
break;
}
}
}
}
return (
<Button

View File

@ -611,6 +611,149 @@ export const useEmailState = () => {
}
}, [session?.user?.id, state.page, state.currentFolder, loadEmails, logEmailOp]);
// Calculate and update unread counts from emails
const updateUnreadCounts = useCallback(() => {
// This function will count unread emails in each folder and update the unreadCountMap
if (state.emails.length === 0) return;
// Create a temporary count map
const tempUnreadMap: Record<string, Record<string, number>> = {};
// Initialize with existing accounts and folders to avoid losing counts
// when switching folders
state.accounts.forEach(account => {
tempUnreadMap[account.id] = { ...state.unreadCountMap[account.id] || {} };
// Initialize each folder with 0 if it doesn't exist
account.folders.forEach(folder => {
// Extract base folder name if it has a prefix
const baseFolderName = folder.includes(':') ? folder.split(':')[1] : folder;
const prefixedFolder = folder.includes(':') ? folder : `${account.id}:${baseFolderName}`;
// Initialize both prefixed and unprefixed versions
if (tempUnreadMap[account.id][baseFolderName] === undefined) {
tempUnreadMap[account.id][baseFolderName] = 0;
}
if (tempUnreadMap[account.id][prefixedFolder] === undefined) {
tempUnreadMap[account.id][prefixedFolder] = 0;
}
});
});
// Count unread emails from current folder
state.emails.forEach(email => {
// Check if email is unread
const isUnread = email.flags && !email.flags.seen;
// Only count if it's unread
if (isUnread && email.accountId) {
// Get folder information
let folder = email.folder;
let accountId = email.accountId;
// Make sure the account exists in our map
if (!tempUnreadMap[accountId]) {
tempUnreadMap[accountId] = {};
}
// Extract folder name if it has a prefix
let baseFolderName = folder;
if (folder.includes(':')) {
const parts = folder.split(':');
// Don't override accountId from the folder prefix
baseFolderName = parts[1];
}
// Ensure we have entries for both formats
if (!tempUnreadMap[accountId][baseFolderName]) {
tempUnreadMap[accountId][baseFolderName] = 0;
}
if (!tempUnreadMap[accountId][folder]) {
tempUnreadMap[accountId][folder] = 0;
}
// Increment both formats to ensure they're both available
tempUnreadMap[accountId][baseFolderName]++;
tempUnreadMap[accountId][folder]++;
}
});
// Log the unread counts for debugging
logEmailOp('UNREAD_COUNTS', 'Updated unread counts:', tempUnreadMap);
// Update the unread count map in the state
Object.entries(tempUnreadMap).forEach(([accountId, folderCounts]) => {
Object.entries(folderCounts).forEach(([folder, count]) => {
dispatch({
type: 'UPDATE_UNREAD_COUNT',
payload: { accountId, folder, count }
});
});
});
}, [state.emails, state.accounts, state.unreadCountMap, logEmailOp]);
// Call updateUnreadCounts when emails change
useEffect(() => {
updateUnreadCounts();
}, [state.emails, updateUnreadCounts]);
// Fetch unread counts from API
const fetchUnreadCounts = useCallback(async () => {
if (!session?.user?.id) return;
try {
logEmailOp('FETCH_UNREAD', 'Fetching unread counts from API');
// Make API call to get unread counts for all folders
const response = await fetch('/api/courrier/unread-counts');
if (!response.ok) {
throw new Error('Failed to fetch unread counts');
}
const data = await response.json();
if (data.counts && typeof data.counts === 'object') {
logEmailOp('UNREAD_API', 'Received unread counts from API', data.counts);
// Update unread counts in state
Object.entries(data.counts).forEach(([accountId, folderCounts]: [string, any]) => {
Object.entries(folderCounts).forEach(([folder, count]: [string, any]) => {
dispatch({
type: 'UPDATE_UNREAD_COUNT',
payload: {
accountId,
folder,
count: typeof count === 'number' ? count : 0
}
});
});
});
}
} catch (error) {
logEmailOp('ERROR', `Failed to fetch unread counts: ${error instanceof Error ? error.message : String(error)}`);
// Don't show toast for this error as it's not critical
}
}, [session?.user?.id, dispatch, logEmailOp]);
// Fetch unread counts when accounts are loaded or when folders change
useEffect(() => {
if (state.accounts.length > 0) {
fetchUnreadCounts();
}
}, [state.accounts, state.currentFolder, fetchUnreadCounts]);
// Set up periodic refresh of unread counts (every 60 seconds)
useEffect(() => {
const intervalId = setInterval(() => {
if (state.accounts.length > 0) {
fetchUnreadCounts();
}
}, 60000);
return () => clearInterval(intervalId);
}, [state.accounts, fetchUnreadCounts]);
// Return all state values and actions
return {
// State values