widget courrier refactor
This commit is contained in:
parent
7a47b89114
commit
60eb2efb20
@ -1,10 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { useSession } from "next-auth/react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { RefreshCw, MessageSquare, Mail, MailOpen, Loader2 } from "lucide-react";
|
import { RefreshCw, MessageSquare, Mail, MailOpen, Loader2 } from "lucide-react";
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { useUnifiedRefresh } from "@/hooks/use-unified-refresh";
|
||||||
|
import { REFRESH_INTERVALS } from "@/lib/constants/refresh-intervals";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
|
||||||
interface Email {
|
interface Email {
|
||||||
id: string;
|
id: string;
|
||||||
@ -24,21 +28,28 @@ interface EmailResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function Email() {
|
export function Email() {
|
||||||
|
const { data: session, status } = useSession();
|
||||||
const [emails, setEmails] = useState<Email[]>([]);
|
const [emails, setEmails] = useState<Email[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [mailUrl, setMailUrl] = useState<string | null>(null);
|
const [mailUrl, setMailUrl] = useState<string | null>(null);
|
||||||
const [accounts, setAccounts] = useState<Array<{ id: string; email: string }>>([]);
|
const [accounts, setAccounts] = useState<Array<{ id: string; email: string }>>([]);
|
||||||
|
const [unreadCount, setUnreadCount] = useState<number>(0);
|
||||||
|
const [accountErrors, setAccountErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadAccounts();
|
if (status === 'authenticated') {
|
||||||
}, []);
|
loadAccounts();
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (accounts.length > 0) {
|
|
||||||
fetchEmails();
|
|
||||||
}
|
}
|
||||||
}, [accounts]);
|
}, [status]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (accounts.length > 0 && status === 'authenticated') {
|
||||||
|
fetchEmails(false);
|
||||||
|
fetchUnreadCount();
|
||||||
|
}
|
||||||
|
}, [accounts, status]);
|
||||||
|
|
||||||
const loadAccounts = async () => {
|
const loadAccounts = async () => {
|
||||||
try {
|
try {
|
||||||
@ -57,32 +68,50 @@ export function Email() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchEmails = async (isRefresh = false) => {
|
const fetchEmails = async (forceRefresh = false) => {
|
||||||
setLoading(true);
|
// Only show loading spinner on initial load, not on auto-refresh
|
||||||
|
if (!emails.length) {
|
||||||
|
setLoading(true);
|
||||||
|
}
|
||||||
|
setRefreshing(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setAccountErrors({});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Fetch emails from all accounts in parallel
|
// Fetch emails from all accounts in parallel
|
||||||
const emailPromises = accounts.map(async (account) => {
|
const emailPromises = accounts.map(async (account) => {
|
||||||
const url = `/api/courrier?folder=INBOX&page=1&perPage=5&accountId=${encodeURIComponent(account.id)}${isRefresh ? '&refresh=true' : ''}`;
|
try {
|
||||||
const response = await fetch(url);
|
const url = `/api/courrier?folder=INBOX&page=1&perPage=5&accountId=${encodeURIComponent(account.id)}${forceRefresh ? '&refresh=true' : ''}`;
|
||||||
if (!response.ok) {
|
const response = await fetch(url);
|
||||||
console.warn(`Failed to fetch emails for account ${account.id}`);
|
if (!response.ok) {
|
||||||
|
const errorMsg = `Failed to fetch emails for ${account.email}`;
|
||||||
|
console.warn(errorMsg);
|
||||||
|
setAccountErrors(prev => ({ ...prev, [account.id]: errorMsg }));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.error || !data.emails) {
|
||||||
|
const errorMsg = data.error || `No emails returned for ${account.email}`;
|
||||||
|
setAccountErrors(prev => ({ ...prev, [account.id]: errorMsg }));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// Add accountId to each email for proper identification
|
||||||
|
return data.emails.map((email: any) => ({
|
||||||
|
...email,
|
||||||
|
accountId: account.id
|
||||||
|
}));
|
||||||
|
} catch (err) {
|
||||||
|
const errorMsg = `Error fetching emails for ${account.email}: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||||
|
console.error(errorMsg, err);
|
||||||
|
setAccountErrors(prev => ({ ...prev, [account.id]: errorMsg }));
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
const data = await response.json();
|
|
||||||
if (data.error || !data.emails) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
// Add accountId to each email for proper identification
|
|
||||||
return data.emails.map((email: any) => ({
|
|
||||||
...email,
|
|
||||||
accountId: account.id
|
|
||||||
}));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const allEmailsArrays = await Promise.all(emailPromises);
|
const allEmailsArrays = await Promise.allSettled(emailPromises);
|
||||||
const allEmails = allEmailsArrays.flat();
|
const allEmails = allEmailsArrays
|
||||||
|
.filter((result): result is PromiseFulfilledResult<any[]> => result.status === 'fulfilled')
|
||||||
|
.flatMap(result => result.value);
|
||||||
|
|
||||||
// Transform and sort all emails
|
// Transform and sort all emails
|
||||||
const transformedEmails = allEmails
|
const transformedEmails = allEmails
|
||||||
@ -103,15 +132,65 @@ export function Email() {
|
|||||||
|
|
||||||
setEmails(transformedEmails);
|
setEmails(transformedEmails);
|
||||||
setMailUrl('/courrier');
|
setMailUrl('/courrier');
|
||||||
|
|
||||||
|
// Show error only if all accounts failed
|
||||||
|
if (allEmails.length === 0 && accounts.length > 0 && Object.keys(accountErrors).length === accounts.length) {
|
||||||
|
setError('Failed to load emails from all accounts');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching emails:', error);
|
console.error('Error fetching emails:', error);
|
||||||
setError('Failed to load emails');
|
setError(error instanceof Error ? error.message : 'Failed to load emails');
|
||||||
setEmails([]);
|
setEmails([]);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
setRefreshing(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const fetchUnreadCount = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/courrier/unread-counts');
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
if (data && typeof data === 'object') {
|
||||||
|
// Sum up unread counts from all accounts and folders
|
||||||
|
let totalUnread = 0;
|
||||||
|
Object.values(data).forEach((accountCounts: any) => {
|
||||||
|
if (typeof accountCounts === 'object') {
|
||||||
|
Object.values(accountCounts).forEach((count: any) => {
|
||||||
|
if (typeof count === 'number') {
|
||||||
|
totalUnread += count;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
setUnreadCount(totalUnread);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error fetching unread count:', err);
|
||||||
|
// Don't set error state for unread count failures
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Integrate unified refresh for automatic polling
|
||||||
|
const { refresh } = useUnifiedRefresh({
|
||||||
|
resource: 'email',
|
||||||
|
interval: REFRESH_INTERVALS.EMAIL, // 1 minute
|
||||||
|
enabled: status === 'authenticated',
|
||||||
|
onRefresh: async () => {
|
||||||
|
await fetchEmails(false); // Use cache for auto-refresh
|
||||||
|
await fetchUnreadCount();
|
||||||
|
},
|
||||||
|
priority: 'medium',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Manual refresh handler (bypasses cache)
|
||||||
|
const handleManualRefresh = async () => {
|
||||||
|
await fetchEmails(true); // Force refresh, bypass cache
|
||||||
|
await fetchUnreadCount();
|
||||||
|
};
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
const formatDate = (dateString: string) => {
|
||||||
try {
|
try {
|
||||||
const date = new Date(dateString);
|
const date = new Date(dateString);
|
||||||
@ -132,23 +211,33 @@ export function Email() {
|
|||||||
<CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
|
<CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
|
||||||
<Mail className="h-5 w-5 text-gray-600" />
|
<Mail className="h-5 w-5 text-gray-600" />
|
||||||
Courrier
|
Courrier
|
||||||
|
{unreadCount > 0 && (
|
||||||
|
<Badge variant="destructive" className="ml-1 text-xs">
|
||||||
|
{unreadCount}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => fetchEmails(true)}
|
onClick={handleManualRefresh}
|
||||||
disabled={loading}
|
disabled={refreshing}
|
||||||
|
className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
|
||||||
>
|
>
|
||||||
{loading ?
|
<RefreshCw className={`h-3.5 w-3.5 text-gray-600 ${refreshing ? 'animate-spin' : ''}`} />
|
||||||
<Loader2 className="h-4 w-4 animate-spin" /> :
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
}
|
|
||||||
</Button>
|
</Button>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-4">
|
<CardContent className="p-4">
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="text-center py-4 text-gray-500">
|
<div className="text-center py-4">
|
||||||
{error}
|
<p className="text-red-500 text-sm mb-2">{error}</p>
|
||||||
|
{Object.keys(accountErrors).length > 0 && (
|
||||||
|
<div className="text-xs text-gray-500 space-y-1">
|
||||||
|
{Object.entries(accountErrors).map(([accountId, errMsg]) => (
|
||||||
|
<p key={accountId}>{errMsg}</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : loading && emails.length === 0 ? (
|
) : loading && emails.length === 0 ? (
|
||||||
<div className="text-center py-6 flex flex-col items-center">
|
<div className="text-center py-6 flex flex-col items-center">
|
||||||
@ -157,7 +246,7 @@ export function Email() {
|
|||||||
</div>
|
</div>
|
||||||
) : emails.length === 0 ? (
|
) : emails.length === 0 ? (
|
||||||
<div className="text-center py-6">
|
<div className="text-center py-6">
|
||||||
<p className="text-gray-500">Aucun email non lu</p>
|
<p className="text-gray-500">Aucun email</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user