NeahStable/app/mission-tab/[missionId]/page.tsx
2026-01-16 22:55:13 +01:00

580 lines
24 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { FileIcon, Calendar, Eye, MapPin, Users, Clock, ThumbsUp, Languages, ArrowLeft, FileText } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
// Define types for mission details
interface User {
id: string;
email: string;
}
interface Attachment {
id: string;
filename: string;
filePath: string;
fileType: string;
fileSize: number;
publicUrl: string;
createdAt: string;
}
interface Mission {
id: string;
name: string;
logo?: string | null;
logoUrl?: string | null;
oddScope: string[];
niveau: string;
missionType: string;
projection: string;
intention?: string;
donneurDOrdre?: string;
participation?: string;
services?: string[];
profils?: string[];
attachments?: Attachment[];
createdAt: string;
creator: User;
missionUsers: any[];
rocketChatChannelId?: string | null;
outlineCollectionId?: string | null;
giteaRepositoryUrl?: string | null;
leantimeProjectId?: string | null;
}
export default function MissionTabDetailPage() {
const [mission, setMission] = useState<Mission | null>(null);
const [loading, setLoading] = useState(true);
const { toast } = useToast();
const params = useParams();
const router = useRouter();
const missionId = params.missionId as string;
// Fetch mission details
useEffect(() => {
const fetchMissionDetails = async () => {
try {
setLoading(true);
const response = await fetch(`/api/missions/${missionId}`);
if (!response.ok) {
throw new Error('Failed to fetch mission details');
}
const data = await response.json();
console.log("Mission details:", data);
setMission(data);
} catch (error) {
console.error('Error fetching mission details:', error);
toast({
title: "Erreur",
description: "Impossible de charger les détails de la mission",
variant: "destructive",
});
} finally {
setLoading(false);
}
};
if (missionId) {
fetchMissionDetails();
}
}, [missionId, toast]);
// Helper function to format date
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString('fr-FR', {
day: '2-digit',
month: 'long',
year: 'numeric'
});
};
// Helper functions to get labels
const getMissionTypeLabel = (type: string) => {
switch(type) {
case 'remote': return 'À distance';
case 'onsite': return 'Sur site';
case 'hybrid': return 'Hybride';
default: return type;
}
};
const getDurationLabel = (projection: string) => {
switch(projection) {
case 'short': return '< 1 mois';
case 'medium': return '1-3 mois';
case 'long': return '> 3 mois';
default: return projection;
}
};
const getNiveauLabel = (niveau: string) => {
switch(niveau) {
case 'a': return 'Apprentissage';
case 'b': return 'Basique';
case 'c': return 'Complexe';
case 's': return 'Spécial';
default: return niveau;
}
};
// Function to get odd info
const getODDInfo = (oddScope: string[]) => {
const oddCode = oddScope && oddScope.length > 0
? oddScope[0]
: null;
// Extract number from odd code (e.g., "odd-3" -> "3")
const oddNumber = oddCode ? oddCode.replace('odd-', '') : null;
return {
number: oddNumber,
label: oddNumber ? `ODD ${oddNumber}` : "Non catégorisé",
iconPath: oddNumber ? `/F SDG Icons 2019 WEB/F-WEB-Goal-${oddNumber.padStart(2, '0')}.png` : ""
};
};
// Function to sanitize mission name (same logic as N8N)
const sanitizeMissionName = (name: string): string => {
if (!name || typeof name !== "string") return "unnamed-mission";
return name.toLowerCase()
.split("")
.map(c => {
if (c >= "a" && c <= "z") return c;
if (c >= "0" && c <= "9") return c;
if (c === " " || c === "-") return c;
return "";
})
.join("")
.split(" ")
.filter(Boolean)
.join("-");
};
// Loading state
if (loading) {
return (
<div className="flex justify-center items-center h-[calc(100vh-64px)] bg-gray-50">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-600"></div>
</div>
);
}
// Error state if mission not found
if (!mission) {
return (
<div className="flex justify-center items-center h-[calc(100vh-64px)] bg-gray-50 px-4">
<div className="text-center bg-white p-8 rounded-lg shadow-sm border border-gray-200 max-w-md">
<h2 className="text-xl font-semibold text-gray-800 mb-2">Mission non trouvée</h2>
<p className="text-gray-600 mb-6">Cette mission n'existe pas ou a été supprimée.</p>
<Button
onClick={() => router.push('/mission-tab')}
className="bg-blue-600 hover:bg-blue-700 text-white"
>
Retour au tableau des missions
</Button>
</div>
</div>
);
}
const oddInfo = getODDInfo(mission.oddScope);
return (
<div className="bg-gray-50 min-h-screen p-6">
{/* Back Button */}
<div className="mb-4">
<Button
variant="ghost"
className="flex items-center text-gray-600 hover:text-gray-900"
onClick={() => router.push('/mission-tab')}
>
<ArrowLeft className="mr-2 h-4 w-4" />
Retour au tableau des missions
</Button>
</div>
{/* Header */}
<div className="bg-white rounded-lg shadow-sm border border-gray-100 mb-6 p-6">
<div className="flex justify-between items-start">
<div>
<h1 className="text-2xl font-bold text-gray-900 mb-2">{mission.name}</h1>
<div className="flex items-center text-gray-500 text-sm gap-4">
<div className="flex items-center">
<Calendar className="h-4 w-4 mr-1" />
{formatDate(mission.createdAt)}
</div>
<div className="flex items-center">
<Eye className="h-4 w-4 mr-1" />
{Math.floor(Math.random() * 100) + 1} Views
</div>
</div>
</div>
{/* Display logo instead of Participate button */}
<div className="w-24 h-24 rounded-md overflow-hidden flex-shrink-0">
{mission.logoUrl ? (
<Image
src={mission.logoUrl}
alt={mission.name}
width={96}
height={96}
className="w-full h-full object-cover rounded-md"
onError={(e) => {
console.error("Logo failed to load:", {
missionId: mission.id,
missionName: mission.name,
logoUrl: mission.logoUrl,
logoPath: mission.logo
});
// Show placeholder on error
(e.currentTarget as HTMLImageElement).style.display = 'none';
const parent = e.currentTarget.parentElement;
if (parent) {
parent.classList.add('bg-gray-100');
parent.classList.add('flex');
parent.classList.add('items-center');
parent.classList.add('justify-center');
const fallback = document.createElement('span');
fallback.className = 'text-3xl font-medium text-gray-500';
fallback.textContent = mission.name.slice(0, 2).toUpperCase();
parent.appendChild(fallback);
}
}}
unoptimized={mission.logoUrl?.includes('localhost') || mission.logoUrl?.includes('127.0.0.1')}
/>
) : (
<div className="bg-gray-100 w-full h-full flex items-center justify-center">
<span className="text-3xl font-medium text-gray-500">{mission.name.slice(0, 2).toUpperCase()}</span>
</div>
)}
</div>
</div>
</div>
{/* Mission Details Content */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Details and Metadata */}
<div className="lg:col-span-2 space-y-6">
{/* Mission Information */}
<div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-4">À propos de la mission</h2>
{/* Mission Badge Row */}
<div className="mb-6 flex flex-wrap gap-2">
{oddInfo.number && (
<div className="flex items-center gap-2 bg-gray-100 px-3 py-2 rounded-lg">
<img
src={oddInfo.iconPath}
alt={oddInfo.label}
className="w-8 h-8"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<span className="text-sm font-medium text-gray-700">{oddInfo.label}</span>
</div>
)}
<div className="flex items-center gap-2 bg-gray-100 px-3 py-2 rounded-lg">
<MapPin className="w-4 h-4 text-gray-500" />
<span className="text-sm font-medium text-gray-700">{getMissionTypeLabel(mission.missionType)}</span>
</div>
<div className="flex items-center gap-2 bg-gray-100 px-3 py-2 rounded-lg">
<Clock className="w-4 h-4 text-gray-500" />
<span className="text-sm font-medium text-gray-700">{getDurationLabel(mission.projection)}</span>
</div>
<div className="flex items-center gap-2 bg-gray-100 px-3 py-2 rounded-lg">
<ThumbsUp className="w-4 h-4 text-gray-500" />
<span className="text-sm font-medium text-gray-700">Niveau: {getNiveauLabel(mission.niveau)}</span>
</div>
</div>
{/* Mission Description */}
{mission.intention && (
<div className="mb-6">
<h3 className="text-md font-medium text-gray-800 mb-2">Description</h3>
<p className="text-gray-600 whitespace-pre-line">{mission.intention}</p>
</div>
)}
{/* Mission Creator */}
<div>
<h3 className="text-md font-medium text-gray-800 mb-2">Mission créée par</h3>
<div className="flex items-center">
<div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center mr-2">
<span className="text-xs font-medium text-blue-700">
{mission.creator.email.substring(0, 2).toUpperCase()}
</span>
</div>
<div>
<p className="text-sm text-gray-700">{mission.creator.email}</p>
<p className="text-xs text-gray-500">{formatDate(mission.createdAt)}</p>
</div>
</div>
</div>
</div>
{/* Attachments Section */}
{mission.attachments && mission.attachments.length > 0 && (
<div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Fichiers joints</h2>
<div className="space-y-3">
{mission.attachments.map((attachment) => (
<div key={attachment.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
<div className="flex items-center">
<div className="p-2 bg-blue-100 rounded-md mr-3">
<FileIcon className="h-5 w-5 text-blue-600" />
</div>
<div>
<p className="text-sm font-medium text-gray-800">{attachment.filename}</p>
<p className="text-xs text-gray-500">
{(attachment.fileSize / 1024).toFixed(1)} KB • {attachment.fileType}
</p>
</div>
</div>
<a
href={attachment.publicUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 hover:text-blue-800 font-medium"
>
Télécharger
</a>
</div>
))}
</div>
</div>
)}
</div>
{/* Right Column - Services and Profils */}
<div className="space-y-6">
{/* Services Section */}
{mission.services && mission.services.length > 0 && (
<div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Services</h2>
<div className="space-y-2">
{mission.services.map((service, index) => (
<div
key={index}
className="flex items-center py-2 px-3 bg-blue-50 text-blue-700 rounded-md"
>
<span className="text-sm font-medium">{service}</span>
</div>
))}
</div>
</div>
)}
{/* Profils Requis Section */}
{mission.profils && mission.profils.length > 0 && (
<div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Profils requis</h2>
<div className="space-y-2">
{mission.profils.map((profil, index) => (
<div
key={index}
className="flex items-center py-2 px-3 bg-purple-50 text-purple-700 rounded-md"
>
<Languages className="h-4 w-4 mr-2" />
<span className="text-sm font-medium">{profil}</span>
</div>
))}
</div>
</div>
)}
{/* Ressources Métiers */}
{(() => {
// Helper function to check if a value is valid (not null, not undefined, not empty string, not "0", not "null", not "undefined")
const isValid = (value: any): boolean => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed !== '' && trimmed !== '0' && trimmed !== 'null' && trimmed !== 'undefined';
}
if (typeof value === 'number') return value !== 0;
return true;
};
const hasRocketChat = isValid(mission.rocketChatChannelId);
const hasOutline = isValid(mission.outlineCollectionId);
const hasGitea = isValid(mission.giteaRepositoryUrl);
const hasLeantime = isValid(mission.leantimeProjectId);
console.log('Ressources Métiers check (mission-tab):', {
hasRocketChat,
hasOutline,
hasGitea,
hasLeantime,
rocketChatValue: mission.rocketChatChannelId,
outlineValue: mission.outlineCollectionId,
giteaValue: mission.giteaRepositoryUrl,
leantimeValue: mission.leantimeProjectId,
});
return hasRocketChat || hasOutline || hasGitea || hasLeantime;
})() && (
<div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Ressources Métiers</h2>
<div className="space-y-3">
{(() => {
const isValid = (value: any): boolean => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed !== '' && trimmed !== '0' && trimmed !== 'null' && trimmed !== 'undefined';
}
return true;
};
return isValid(mission.rocketChatChannelId);
})() && (() => {
// Build RocketChat URL: parole.slm-lab.net/channel/[channelId]
// If it's already a full URL, use it; otherwise build from ID
const rocketChatUrl = mission.rocketChatChannelId.startsWith('http')
? mission.rocketChatChannelId
: `https://parole.slm-lab.net/channel/${mission.rocketChatChannelId}`;
return (
<a
href={rocketChatUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 transition-colors cursor-pointer"
>
<div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
<Users className="h-5 w-5 text-blue-600" />
</div>
<div className="flex-1">
<p className="font-medium text-gray-900">Tenant de Parole</p>
<p className="text-sm text-gray-500">Espace de discussion</p>
</div>
</a>
);
})()}
{(() => {
const isValid = (value: any): boolean => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed !== '' && trimmed !== '0' && trimmed !== 'null' && trimmed !== 'undefined';
}
return true;
};
return isValid(mission.outlineCollectionId);
})() && (() => {
// Build Outline URL: chapitre.slm-lab.net/collection/[collectionId]
// If it's already a full URL, use it; otherwise build from ID
const outlineUrl = mission.outlineCollectionId.startsWith('http')
? mission.outlineCollectionId
: `https://chapitre.slm-lab.net/collection/${mission.outlineCollectionId}`;
return (
<a
href={outlineUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 p-3 bg-purple-50 rounded-lg border border-purple-100 hover:bg-purple-100 transition-colors cursor-pointer"
>
<div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
<FileText className="h-5 w-5 text-purple-600" />
</div>
<div className="flex-1">
<p className="font-medium text-gray-900">Tenant du Chapitre</p>
<p className="text-sm text-gray-500">Espace de documentation</p>
</div>
</a>
);
})()}
{(() => {
const isValid = (value: any): boolean => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed !== '' && trimmed !== '0' && trimmed !== 'null' && trimmed !== 'undefined';
}
return true;
};
return isValid(mission.giteaRepositoryUrl);
})() && (() => {
// Use mission name (sanitized) as repo name
const repoName = sanitizeMissionName(mission.name);
// Get Gitea owner from environment variable (default: "alma")
// Note: In Next.js client components, we need NEXT_PUBLIC_ prefix
const giteaOwner = typeof window !== 'undefined'
? (process.env.NEXT_PUBLIC_GITEA_OWNER || 'alma')
: 'alma';
// Build the correct Gitea URL: gite.slm-lab.net/owner/repo-name
const giteaUrl = `https://gite.slm-lab.net/${giteaOwner}/${repoName}`;
return (
<a
href={giteaUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 p-3 bg-green-50 rounded-lg border border-green-100 hover:bg-green-100 transition-colors cursor-pointer"
>
<div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
<FileIcon className="h-5 w-5 text-green-600" />
</div>
<div className="flex-1">
<p className="font-medium text-gray-900">Tenant du Code</p>
<p className="text-sm text-gray-500">Espace pour les codes sources</p>
</div>
</a>
);
})()}
{(() => {
const isValid = (value: any): boolean => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed !== '' && trimmed !== '0' && trimmed !== 'null' && trimmed !== 'undefined';
}
if (typeof value === 'number') return value !== 0;
return true;
};
return isValid(mission.leantimeProjectId);
})() && (() => {
// Build Leantime URL: agilite.slm-lab.net/projects/showProject/[projectId]
// If it's already a full URL, use it; otherwise build from ID
const leantimeUrl = mission.leantimeProjectId.startsWith('http')
? mission.leantimeProjectId
: `https://agilite.slm-lab.net/projects/showProject/${mission.leantimeProjectId}`;
return (
<a
href={leantimeUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 p-3 bg-amber-50 rounded-lg border border-amber-100 hover:bg-amber-100 transition-colors cursor-pointer"
>
<div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center">
<Calendar className="h-5 w-5 text-amber-600" />
</div>
<div className="flex-1">
<p className="font-medium text-gray-900">Tenant des Devoirs</p>
<p className="text-sm text-gray-500">Espace d'organisation</p>
</div>
</a>
);
})()}
</div>
</div>
)}
</div>
</div>
</div>
);
}