agenda widget mia 4

This commit is contained in:
Alma 2025-04-13 20:25:47 +02:00
parent 2961a7f516
commit b2881c7242
2 changed files with 148 additions and 41 deletions

80
app/api/emails/route.ts Normal file
View File

@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email || !session.accessToken) {
return NextResponse.json(
{ error: "Non authentifié" },
{ status: 401 }
);
}
// Get Nextcloud base URL from environment variable
const nextcloudUrl = process.env.NEXTCLOUD_URL;
if (!nextcloudUrl) {
throw new Error("NEXTCLOUD_URL not configured");
}
// Fetch unread messages from Nextcloud Mail API using OIDC token
const response = await fetch(`${nextcloudUrl}/apps/mail/api/v1/messages?filter=unseen`, {
headers: {
'Authorization': `Bearer ${session.accessToken}`,
'Accept': 'application/json',
'OCS-APIRequest': 'true',
'Content-Type': 'application/json',
},
});
if (!response.ok) {
console.error('Failed to fetch emails:', {
status: response.status,
statusText: response.statusText
});
// If token is expired or invalid, return 401
if (response.status === 401) {
return NextResponse.json(
{ error: "Session expirée" },
{ status: 401 }
);
}
throw new Error('Failed to fetch emails from Nextcloud');
}
const data = await response.json();
console.log('Nextcloud mail response:', {
status: response.status,
dataLength: data?.ocs?.data?.length || 0
});
// Transform the response to match our Email interface
const emails = (data?.ocs?.data || []).map((email: any) => ({
id: email.id,
subject: email.subject || '(No subject)',
sender: {
name: email.from?.name || email.from?.email || 'Unknown',
email: email.from?.email || '',
},
date: email.sentDate,
isUnread: true, // Since we're only fetching unread messages
}));
// Sort by date (newest first) and limit to 5 messages
const sortedEmails = emails
.sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
.slice(0, 5);
return NextResponse.json(sortedEmails);
} catch (error) {
console.error('Error fetching emails:', error);
return NextResponse.json(
{ error: "Erreur lors de la récupération des emails" },
{ status: 500 }
);
}
}

View File

@ -4,7 +4,9 @@ import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, Mail } from "lucide-react";
import { useSession } from "next-auth/react";
import { useSession, signIn } from "next-auth/react";
import { format, formatDistance } from "date-fns";
import { fr } from "date-fns/locale/fr";
interface Email {
id: string;
@ -26,37 +28,24 @@ export function Email() {
const fetchEmails = async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
setLoading(true);
// Placeholder data - replace with actual API call
const mockEmails = [
{
id: '1',
subject: 'Project Update: Q1 Milestones',
sender: { name: 'Project Manager', email: 'pm@example.com' },
date: '2024-03-20 09:30',
isUnread: true
},
{
id: '2',
subject: 'Team Meeting Notes',
sender: { name: 'Team Lead', email: 'lead@example.com' },
date: '2024-03-19 15:45',
isUnread: false
},
{
id: '3',
subject: 'Important: System Maintenance',
sender: { name: 'IT Support', email: 'it@example.com' },
date: '2024-03-19 11:20',
isUnread: true
},
];
if (!isRefresh) setLoading(true);
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
setEmails(mockEmails);
const response = await fetch('/api/emails');
if (!response.ok) {
const data = await response.json();
// Handle session expiration
if (response.status === 401) {
signIn(); // Redirect to login
return;
}
throw new Error(data.error || 'Failed to fetch emails');
}
const data = await response.json();
setEmails(data);
setError(null);
} catch (err) {
setError('Failed to fetch emails');
@ -67,20 +56,52 @@ export function Email() {
}
};
// Initial fetch
useEffect(() => {
if (status === 'authenticated') {
fetchEmails();
}
}, [status]);
// Auto-refresh every 5 minutes
useEffect(() => {
if (status !== 'authenticated') return;
const interval = setInterval(() => {
fetchEmails(true);
}, 5 * 60 * 1000);
return () => clearInterval(interval);
}, [status]);
const formatDate = (dateString: string) => {
try {
const date = new Date(dateString);
return formatDistance(date, new Date(), {
addSuffix: true,
locale: fr
});
} catch (err) {
console.error('Error formatting date:', err);
return dateString;
}
};
if (status === 'loading' || loading) {
return (
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
<CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
<CardTitle className="text-lg font-semibold text-gray-800">Email</CardTitle>
<CardTitle className="text-lg font-semibold text-gray-800">
<div className="flex items-center gap-2">
<Mail className="h-5 w-5" />
<span>Emails non lus</span>
</div>
</CardTitle>
</CardHeader>
<CardContent className="p-6">
<p className="text-center text-gray-500">Loading...</p>
<div className="flex items-center justify-center">
<RefreshCw className="h-5 w-5 animate-spin text-gray-400" />
</div>
</CardContent>
</Card>
);
@ -89,7 +110,12 @@ export function Email() {
return (
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-x-4 border-b border-gray-100">
<CardTitle className="text-lg font-semibold text-gray-800">Email</CardTitle>
<CardTitle className="text-lg font-semibold text-gray-800">
<div className="flex items-center gap-2">
<Mail className="h-5 w-5" />
<span>Emails non lus</span>
</div>
</CardTitle>
<Button
variant="ghost"
size="icon"
@ -106,23 +132,24 @@ export function Email() {
) : (
<div className="space-y-2 max-h-[220px] overflow-y-auto">
{emails.length === 0 ? (
<p className="text-center text-gray-500">No emails available</p>
<p className="text-center text-gray-500">Aucun email non lu</p>
) : (
emails.map((email) => (
<div
key={email.id}
className="p-2 hover:bg-gray-50/50 rounded-lg transition-colors"
className="p-2 hover:bg-gray-50/50 rounded-lg transition-colors cursor-pointer"
onClick={() => window.open(process.env.NEXT_PUBLIC_IFRAME_MAIL_URL, '_blank')}
>
<div className="flex items-center justify-between mb-1">
<span className="text-sm text-gray-600">{email.sender.name}</span>
<span className="text-sm text-gray-600 truncate max-w-[60%]" title={email.sender.name}>
{email.sender.name}
</span>
<div className="flex items-center space-x-2">
{email.isUnread && (
<span className="w-1.5 h-1.5 bg-blue-600 rounded-full"></span>
)}
<span className="text-sm text-gray-500">{email.date}</span>
<span className="w-1.5 h-1.5 bg-blue-600 rounded-full"></span>
<span className="text-xs text-gray-500">{formatDate(email.date)}</span>
</div>
</div>
<h3 className={`text-sm ${email.isUnread ? 'font-semibold' : 'font-medium'} text-gray-800 line-clamp-2`}>
<h3 className="text-sm font-semibold text-gray-800 line-clamp-2" title={email.subject}>
{email.subject}
</h3>
</div>