Checkpoint: Audit et fiabilisation SONUM : suppression des composants de démonstration non référencés, nettoyage des dépendances inutilisées, contrôles d’écriture cohérents pour les comptes readonly, validation et normalisation des entrées, transactions sur les opérations multi-étapes, optimisations de requêtes et découpage dynamique des pages lourdes. TypeScript, 37 tests Vitest et build de production validés.
This commit is contained in:
@@ -1,21 +1,33 @@
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import NotFound from "@/pages/NotFound";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { Route, Switch } from "wouter";
|
||||
import ErrorBoundary from "./components/ErrorBoundary";
|
||||
import { ThemeProvider } from "./contexts/ThemeContext";
|
||||
import Home from "./pages/Home";
|
||||
import MesEtablissements from "./pages/MesEtablissements";
|
||||
import MesDemandes from "./pages/MesDemandes";
|
||||
import FicheEtablissement from "./pages/FicheEtablissement";
|
||||
import Admin from "./pages/Admin";
|
||||
import Login from "./pages/Login";
|
||||
import LoginLocal from "./pages/LoginLocal";
|
||||
import MesSolutions from "./pages/MesSolutions";
|
||||
import SolutionsLogicielles from "./pages/SolutionsLogicielles";
|
||||
import Statistiques from "./pages/Statistiques";
|
||||
import MesEchanges from "./pages/MesEchanges";
|
||||
import MiseEnRelation from "./pages/MiseEnRelation";
|
||||
|
||||
// Les espaces métier, dont l'administration (import Excel) et les statistiques,
|
||||
// ne sont utiles qu'après navigation. Leur chargement différé réduit le JS initial.
|
||||
const MesEtablissements = lazy(() => import("./pages/MesEtablissements"));
|
||||
const MesDemandes = lazy(() => import("./pages/MesDemandes"));
|
||||
const FicheEtablissement = lazy(() => import("./pages/FicheEtablissement"));
|
||||
const Admin = lazy(() => import("./pages/Admin"));
|
||||
const MesSolutions = lazy(() => import("./pages/MesSolutions"));
|
||||
const SolutionsLogicielles = lazy(() => import("./pages/SolutionsLogicielles"));
|
||||
const Statistiques = lazy(() => import("./pages/Statistiques"));
|
||||
const MesEchanges = lazy(() => import("./pages/MesEchanges"));
|
||||
const MiseEnRelation = lazy(() => import("./pages/MiseEnRelation"));
|
||||
|
||||
function RouteLoading() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background" role="status" aria-label="Chargement de la page">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Router() {
|
||||
return (
|
||||
@@ -49,7 +61,9 @@ function App() {
|
||||
<ThemeProvider defaultTheme="light">
|
||||
<TooltipProvider>
|
||||
<Toaster richColors position="top-right" />
|
||||
<Suspense fallback={<RouteLoading />}>
|
||||
<Router />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
</ErrorBoundary>
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Loader2, Send, User, Sparkles } from "lucide-react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
/**
|
||||
* Message type matching server-side LLM Message interface
|
||||
*/
|
||||
export type Message = {
|
||||
role: "system" | "user" | "assistant";
|
||||
content: string;
|
||||
};
|
||||
|
||||
export type AIChatBoxProps = {
|
||||
/**
|
||||
* Messages array to display in the chat.
|
||||
* Should match the format used by invokeLLM on the server.
|
||||
*/
|
||||
messages: Message[];
|
||||
|
||||
/**
|
||||
* Callback when user sends a message.
|
||||
* Typically you'll call a tRPC mutation here to invoke the LLM.
|
||||
*/
|
||||
onSendMessage: (content: string) => void;
|
||||
|
||||
/**
|
||||
* Whether the AI is currently generating a response
|
||||
*/
|
||||
isLoading?: boolean;
|
||||
|
||||
/**
|
||||
* Placeholder text for the input field
|
||||
*/
|
||||
placeholder?: string;
|
||||
|
||||
/**
|
||||
* Custom className for the container
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* Height of the chat box (default: 600px)
|
||||
*/
|
||||
height?: string | number;
|
||||
|
||||
/**
|
||||
* Empty state message to display when no messages
|
||||
*/
|
||||
emptyStateMessage?: string;
|
||||
|
||||
/**
|
||||
* Suggested prompts to display in empty state
|
||||
* Click to send directly
|
||||
*/
|
||||
suggestedPrompts?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A ready-to-use AI chat box component that integrates with the LLM system.
|
||||
*
|
||||
* Features:
|
||||
* - Matches server-side Message interface for seamless integration
|
||||
* - Markdown rendering with Streamdown
|
||||
* - Auto-scrolls to latest message
|
||||
* - Loading states
|
||||
* - Uses global theme colors from index.css
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const ChatPage = () => {
|
||||
* const [messages, setMessages] = useState<Message[]>([
|
||||
* { role: "system", content: "You are a helpful assistant." }
|
||||
* ]);
|
||||
*
|
||||
* const chatMutation = trpc.ai.chat.useMutation({
|
||||
* onSuccess: (response) => {
|
||||
* // Assuming your tRPC endpoint returns the AI response as a string
|
||||
* setMessages(prev => [...prev, {
|
||||
* role: "assistant",
|
||||
* content: response
|
||||
* }]);
|
||||
* },
|
||||
* onError: (error) => {
|
||||
* console.error("Chat error:", error);
|
||||
* // Optionally show error message to user
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* const handleSend = (content: string) => {
|
||||
* const newMessages = [...messages, { role: "user", content }];
|
||||
* setMessages(newMessages);
|
||||
* chatMutation.mutate({ messages: newMessages });
|
||||
* };
|
||||
*
|
||||
* return (
|
||||
* <AIChatBox
|
||||
* messages={messages}
|
||||
* onSendMessage={handleSend}
|
||||
* isLoading={chatMutation.isPending}
|
||||
* suggestedPrompts={[
|
||||
* "Explain quantum computing",
|
||||
* "Write a hello world in Python"
|
||||
* ]}
|
||||
* />
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
export function AIChatBox({
|
||||
messages,
|
||||
onSendMessage,
|
||||
isLoading = false,
|
||||
placeholder = "Type your message...",
|
||||
className,
|
||||
height = "600px",
|
||||
emptyStateMessage = "Start a conversation with AI",
|
||||
suggestedPrompts,
|
||||
}: AIChatBoxProps) {
|
||||
const [input, setInput] = useState("");
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const inputAreaRef = useRef<HTMLFormElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Filter out system messages
|
||||
const displayMessages = messages.filter((msg) => msg.role !== "system");
|
||||
|
||||
// Calculate min-height for last assistant message to push user message to top
|
||||
const [minHeightForLastMessage, setMinHeightForLastMessage] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerRef.current && inputAreaRef.current) {
|
||||
const containerHeight = containerRef.current.offsetHeight;
|
||||
const inputHeight = inputAreaRef.current.offsetHeight;
|
||||
const scrollAreaHeight = containerHeight - inputHeight;
|
||||
|
||||
// Reserve space for:
|
||||
// - padding (p-4 = 32px top+bottom)
|
||||
// - user message: 40px (item height) + 16px (margin-top from space-y-4) = 56px
|
||||
// Note: margin-bottom is not counted because it naturally pushes the assistant message down
|
||||
const userMessageReservedHeight = 56;
|
||||
const calculatedHeight = scrollAreaHeight - 32 - userMessageReservedHeight;
|
||||
|
||||
setMinHeightForLastMessage(Math.max(0, calculatedHeight));
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Scroll to bottom helper function with smooth animation
|
||||
const scrollToBottom = () => {
|
||||
const viewport = scrollAreaRef.current?.querySelector(
|
||||
'[data-radix-scroll-area-viewport]'
|
||||
) as HTMLDivElement;
|
||||
|
||||
if (viewport) {
|
||||
requestAnimationFrame(() => {
|
||||
viewport.scrollTo({
|
||||
top: viewport.scrollHeight,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const trimmedInput = input.trim();
|
||||
if (!trimmedInput || isLoading) return;
|
||||
|
||||
onSendMessage(trimmedInput);
|
||||
setInput("");
|
||||
|
||||
// Scroll immediately after sending
|
||||
scrollToBottom();
|
||||
|
||||
// Keep focus on input
|
||||
textareaRef.current?.focus();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSubmit(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
"flex flex-col bg-card text-card-foreground rounded-lg border shadow-sm",
|
||||
className
|
||||
)}
|
||||
style={{ height }}
|
||||
>
|
||||
{/* Messages Area */}
|
||||
<div ref={scrollAreaRef} className="flex-1 overflow-hidden">
|
||||
{displayMessages.length === 0 ? (
|
||||
<div className="flex h-full flex-col p-4">
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-6 text-muted-foreground">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Sparkles className="size-12 opacity-20" />
|
||||
<p className="text-sm">{emptyStateMessage}</p>
|
||||
</div>
|
||||
|
||||
{suggestedPrompts && suggestedPrompts.length > 0 && (
|
||||
<div className="flex max-w-2xl flex-wrap justify-center gap-2">
|
||||
{suggestedPrompts.map((prompt, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => onSendMessage(prompt)}
|
||||
disabled={isLoading}
|
||||
className="rounded-lg border border-border bg-card px-4 py-2 text-sm transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{prompt}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="h-full">
|
||||
<div className="flex flex-col space-y-4 p-4">
|
||||
{displayMessages.map((message, index) => {
|
||||
// Apply min-height to last message only if NOT loading (when loading, the loading indicator gets it)
|
||||
const isLastMessage = index === displayMessages.length - 1;
|
||||
const shouldApplyMinHeight =
|
||||
isLastMessage && !isLoading && minHeightForLastMessage > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
"flex gap-3",
|
||||
message.role === "user"
|
||||
? "justify-end items-start"
|
||||
: "justify-start items-start"
|
||||
)}
|
||||
style={
|
||||
shouldApplyMinHeight
|
||||
? { minHeight: `${minHeightForLastMessage}px` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{message.role === "assistant" && (
|
||||
<div className="size-8 shrink-0 mt-1 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"max-w-[80%] rounded-lg px-4 py-2.5",
|
||||
message.role === "user"
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-foreground"
|
||||
)}
|
||||
>
|
||||
{message.role === "assistant" ? (
|
||||
<div className="prose prose-sm dark:prose-invert max-w-none">
|
||||
<Streamdown>{message.content}</Streamdown>
|
||||
</div>
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap text-sm">
|
||||
{message.content}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{message.role === "user" && (
|
||||
<div className="size-8 shrink-0 mt-1 rounded-full bg-secondary flex items-center justify-center">
|
||||
<User className="size-4 text-secondary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{isLoading && (
|
||||
<div
|
||||
className="flex items-start gap-3"
|
||||
style={
|
||||
minHeightForLastMessage > 0
|
||||
? { minHeight: `${minHeightForLastMessage}px` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="size-8 shrink-0 mt-1 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
</div>
|
||||
<div className="rounded-lg bg-muted px-4 py-2.5">
|
||||
<Loader2 className="size-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input Area */}
|
||||
<form
|
||||
ref={inputAreaRef}
|
||||
onSubmit={handleSubmit}
|
||||
className="flex gap-2 p-4 border-t bg-background/50 items-end"
|
||||
>
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={placeholder}
|
||||
className="flex-1 max-h-32 resize-none min-h-9"
|
||||
rows={1}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="icon"
|
||||
disabled={!input.trim() || isLoading}
|
||||
className="shrink-0 h-[38px] w-[38px]"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
import { useAuth } from "@/_core/hooks/useAuth";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarHeader,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { getLoginUrl } from "@/const";
|
||||
import { useIsMobile } from "@/hooks/useMobile";
|
||||
import { LayoutDashboard, LogOut, PanelLeft, Users, Building2, BookOpen, BarChart3, MessageSquare, UserPlus, Settings, FileText } from "lucide-react";
|
||||
import { CSSProperties, useEffect, useRef, useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { DashboardLayoutSkeleton } from './DashboardLayoutSkeleton';
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
const menuItems = [
|
||||
{ icon: LayoutDashboard, label: "Accueil", path: "/", adminOnly: false },
|
||||
{ icon: Building2, label: "Mes Établissements", path: "/mes-etablissements", adminOnly: false },
|
||||
{ icon: BookOpen, label: "Solutions Logicielles", path: "/solutions", adminOnly: false },
|
||||
{ icon: FileText, label: "Mes Solutions", path: "/mes-solutions", adminOnly: false },
|
||||
{ icon: MessageSquare, label: "Mes Échanges", path: "/mes-echanges", adminOnly: false },
|
||||
{ icon: UserPlus, label: "Mise en relation", path: "/mise-en-relation", adminOnly: false },
|
||||
{ icon: BarChart3, label: "Statistiques", path: "/statistiques", adminOnly: false },
|
||||
{ icon: Settings, label: "Administration", path: "/admin", adminOnly: true },
|
||||
];
|
||||
|
||||
const SIDEBAR_WIDTH_KEY = "sidebar-width";
|
||||
const DEFAULT_WIDTH = 280;
|
||||
const MIN_WIDTH = 200;
|
||||
const MAX_WIDTH = 480;
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const [sidebarWidth, setSidebarWidth] = useState(() => {
|
||||
const saved = localStorage.getItem(SIDEBAR_WIDTH_KEY);
|
||||
return saved ? parseInt(saved, 10) : DEFAULT_WIDTH;
|
||||
});
|
||||
const { loading, user } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(SIDEBAR_WIDTH_KEY, sidebarWidth.toString());
|
||||
}, [sidebarWidth]);
|
||||
|
||||
if (loading) {
|
||||
return <DashboardLayoutSkeleton />
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="flex flex-col items-center gap-8 p-8 max-w-md w-full">
|
||||
<div className="flex flex-col items-center gap-6">
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-center">
|
||||
Sign in to continue
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground text-center max-w-sm">
|
||||
Access to this dashboard requires authentication. Continue to launch the login flow.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
window.location.href = getLoginUrl();
|
||||
}}
|
||||
size="lg"
|
||||
className="w-full shadow-lg hover:shadow-xl transition-all"
|
||||
>
|
||||
Sign in
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarProvider
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": `${sidebarWidth}px`,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
<DashboardLayoutContent setSidebarWidth={setSidebarWidth}>
|
||||
{children}
|
||||
</DashboardLayoutContent>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type DashboardLayoutContentProps = {
|
||||
children: React.ReactNode;
|
||||
setSidebarWidth: (width: number) => void;
|
||||
};
|
||||
|
||||
function DashboardLayoutContent({
|
||||
children,
|
||||
setSidebarWidth,
|
||||
}: DashboardLayoutContentProps) {
|
||||
const { user, logout } = useAuth();
|
||||
const [location, setLocation] = useLocation();
|
||||
const { state, toggleSidebar } = useSidebar();
|
||||
const isCollapsed = state === "collapsed";
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||
const isAdmin = user?.role === "admin" || user?.sonumRole === "gestionnaire";
|
||||
const visibleMenuItems = menuItems.filter(item => !item.adminOnly || isAdmin);
|
||||
const activeMenuItem = visibleMenuItems.find(item => item.path === location);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useEffect(() => {
|
||||
if (isCollapsed) {
|
||||
setIsResizing(false);
|
||||
}
|
||||
}, [isCollapsed]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
if (!isResizing) return;
|
||||
|
||||
const sidebarLeft = sidebarRef.current?.getBoundingClientRect().left ?? 0;
|
||||
const newWidth = e.clientX - sidebarLeft;
|
||||
if (newWidth >= MIN_WIDTH && newWidth <= MAX_WIDTH) {
|
||||
setSidebarWidth(newWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setIsResizing(false);
|
||||
};
|
||||
|
||||
if (isResizing) {
|
||||
document.addEventListener("mousemove", handleMouseMove);
|
||||
document.addEventListener("mouseup", handleMouseUp);
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("mousemove", handleMouseMove);
|
||||
document.removeEventListener("mouseup", handleMouseUp);
|
||||
document.body.style.cursor = "";
|
||||
document.body.style.userSelect = "";
|
||||
};
|
||||
}, [isResizing, setSidebarWidth]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative" ref={sidebarRef}>
|
||||
<Sidebar
|
||||
collapsible="icon"
|
||||
className="border-r-0"
|
||||
disableTransition={isResizing}
|
||||
>
|
||||
<SidebarHeader className="h-16 justify-center">
|
||||
<div className="flex items-center gap-3 px-2 transition-all w-full">
|
||||
<button
|
||||
onClick={toggleSidebar}
|
||||
className="h-8 w-8 flex items-center justify-center hover:bg-accent rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring shrink-0"
|
||||
aria-label="Toggle navigation"
|
||||
>
|
||||
<PanelLeft className="h-4 w-4 text-muted-foreground" />
|
||||
</button>
|
||||
{!isCollapsed ? (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="font-semibold tracking-tight truncate">
|
||||
Navigation
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarMenu className="px-2 py-1">
|
||||
{visibleMenuItems.map(item => {
|
||||
const isActive = location === item.path;
|
||||
return (
|
||||
<SidebarMenuItem key={item.path}>
|
||||
<SidebarMenuButton
|
||||
isActive={isActive}
|
||||
onClick={() => setLocation(item.path)}
|
||||
tooltip={item.label}
|
||||
className={`h-10 transition-all font-normal`}
|
||||
>
|
||||
<item.icon
|
||||
className={`h-4 w-4 ${isActive ? "text-primary" : ""}`}
|
||||
/>
|
||||
<span>{item.label}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter className="p-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center gap-3 rounded-lg px-1 py-1 hover:bg-accent/50 transition-colors w-full text-left group-data-[collapsible=icon]:justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<Avatar className="h-9 w-9 border shrink-0">
|
||||
<AvatarFallback className="text-xs font-medium">
|
||||
{user?.name?.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0 group-data-[collapsible=icon]:hidden">
|
||||
<p className="text-sm font-medium truncate leading-none">
|
||||
{user?.name || "-"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate mt-1.5">
|
||||
{user?.email || "-"}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={logout}
|
||||
className="cursor-pointer text-destructive focus:text-destructive"
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
<span>Sign out</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
<div
|
||||
className={`absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-primary/20 transition-colors ${isCollapsed ? "hidden" : ""}`}
|
||||
onMouseDown={() => {
|
||||
if (isCollapsed) return;
|
||||
setIsResizing(true);
|
||||
}}
|
||||
style={{ zIndex: 50 }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<SidebarInset>
|
||||
{isMobile && (
|
||||
<div className="flex border-b h-14 items-center justify-between bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:backdrop-blur sticky top-0 z-40">
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="h-9 w-9 rounded-lg bg-background" />
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="tracking-tight text-foreground">
|
||||
{activeMenuItem?.label ?? "Menu"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<main className="flex-1 p-4">{children}</main>
|
||||
</SidebarInset>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { Skeleton } from './ui/skeleton';
|
||||
|
||||
export function DashboardLayoutSkeleton() {
|
||||
return (
|
||||
<div className="flex min-h-screen bg-background">
|
||||
{/* Sidebar skeleton */}
|
||||
<div className="w-[280px] border-r border-border bg-background p-4 space-y-6">
|
||||
{/* Logo area */}
|
||||
<div className="flex items-center gap-3 px-2">
|
||||
<Skeleton className="h-8 w-8 rounded-md" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
|
||||
{/* Menu items */}
|
||||
<div className="space-y-2 px-2">
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
</div>
|
||||
|
||||
{/* User profile area at bottom */}
|
||||
<div className="absolute bottom-4 left-4 right-4">
|
||||
<div className="flex items-center gap-3 px-1">
|
||||
<Skeleton className="h-9 w-9 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-3 w-20" />
|
||||
<Skeleton className="h-2 w-32" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main content skeleton */}
|
||||
<div className="flex-1 p-4 space-y-4">
|
||||
{/* Content blocks */}
|
||||
<Skeleton className="h-12 w-48 rounded-lg" />
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
<Skeleton className="h-32 rounded-xl" />
|
||||
<Skeleton className="h-32 rounded-xl" />
|
||||
<Skeleton className="h-32 rounded-xl" />
|
||||
</div>
|
||||
<Skeleton className="h-64 rounded-xl" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
interface ManusDialogProps {
|
||||
title?: string;
|
||||
logo?: string;
|
||||
open?: boolean;
|
||||
onLogin: () => void;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export function ManusDialog({
|
||||
title,
|
||||
logo,
|
||||
open = false,
|
||||
onLogin,
|
||||
onOpenChange,
|
||||
onClose,
|
||||
}: ManusDialogProps) {
|
||||
const [internalOpen, setInternalOpen] = useState(open);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onOpenChange) {
|
||||
setInternalOpen(open);
|
||||
}
|
||||
}, [open, onOpenChange]);
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (onOpenChange) {
|
||||
onOpenChange(nextOpen);
|
||||
} else {
|
||||
setInternalOpen(nextOpen);
|
||||
}
|
||||
|
||||
if (!nextOpen) {
|
||||
onClose?.();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={onOpenChange ? open : internalOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
>
|
||||
<DialogContent className="py-5 bg-[#f8f8f7] rounded-[20px] w-[400px] shadow-[0px_4px_11px_0px_rgba(0,0,0,0.08)] border border-[rgba(0,0,0,0.08)] backdrop-blur-2xl p-0 gap-0 text-center">
|
||||
<div className="flex flex-col items-center gap-2 p-5 pt-12">
|
||||
{logo ? (
|
||||
<div className="w-16 h-16 bg-white rounded-xl border border-[rgba(0,0,0,0.08)] flex items-center justify-center">
|
||||
<img
|
||||
src={logo}
|
||||
alt="Dialog graphic"
|
||||
className="w-10 h-10 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Title and subtitle */}
|
||||
{title ? (
|
||||
<DialogTitle className="text-xl font-semibold text-[#34322d] leading-[26px] tracking-[-0.44px]">
|
||||
{title}
|
||||
</DialogTitle>
|
||||
) : null}
|
||||
<DialogDescription className="text-sm text-[#858481] leading-5 tracking-[-0.154px]">
|
||||
Please login with Manus to continue
|
||||
</DialogDescription>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="px-5 py-5">
|
||||
{/* Login button */}
|
||||
<Button
|
||||
onClick={onLogin}
|
||||
className="w-full h-10 bg-[#1a1a19] hover:bg-[#1a1a19]/90 text-white rounded-[10px] text-sm font-medium leading-5 tracking-[-0.154px]"
|
||||
>
|
||||
Login with Manus
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
/**
|
||||
* GOOGLE MAPS FRONTEND INTEGRATION - ESSENTIAL GUIDE
|
||||
*
|
||||
* USAGE FROM PARENT COMPONENT:
|
||||
* ======
|
||||
*
|
||||
* const mapRef = useRef<google.maps.Map | null>(null);
|
||||
*
|
||||
* <MapView
|
||||
* initialCenter={{ lat: 40.7128, lng: -74.0060 }}
|
||||
* initialZoom={15}
|
||||
* onMapReady={(map) => {
|
||||
* mapRef.current = map; // Store to control map from parent anytime, google map itself is in charge of the re-rendering, not react state.
|
||||
* </MapView>
|
||||
*
|
||||
* ======
|
||||
* Available Libraries and Core Features:
|
||||
* -------------------------------
|
||||
* 📍 MARKER (from `marker` library)
|
||||
* - Attaches to map using { map, position }
|
||||
* new google.maps.marker.AdvancedMarkerElement({
|
||||
* map,
|
||||
* position: { lat: 37.7749, lng: -122.4194 },
|
||||
* title: "San Francisco",
|
||||
* });
|
||||
*
|
||||
* -------------------------------
|
||||
* 🏢 PLACES (from `places` library)
|
||||
* - Does not attach directly to map; use data with your map manually.
|
||||
* const place = new google.maps.places.Place({ id: PLACE_ID });
|
||||
* await place.fetchFields({ fields: ["displayName", "location"] });
|
||||
* map.setCenter(place.location);
|
||||
* new google.maps.marker.AdvancedMarkerElement({ map, position: place.location });
|
||||
*
|
||||
* -------------------------------
|
||||
* 🧭 GEOCODER (from `geocoding` library)
|
||||
* - Standalone service; manually apply results to map.
|
||||
* const geocoder = new google.maps.Geocoder();
|
||||
* geocoder.geocode({ address: "New York" }, (results, status) => {
|
||||
* if (status === "OK" && results[0]) {
|
||||
* map.setCenter(results[0].geometry.location);
|
||||
* new google.maps.marker.AdvancedMarkerElement({
|
||||
* map,
|
||||
* position: results[0].geometry.location,
|
||||
* });
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* -------------------------------
|
||||
* 📐 GEOMETRY (from `geometry` library)
|
||||
* - Pure utility functions; not attached to map.
|
||||
* const dist = google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
|
||||
*
|
||||
* -------------------------------
|
||||
* 🛣️ ROUTES (from `routes` library)
|
||||
* - Combines DirectionsService (standalone) + DirectionsRenderer (map-attached)
|
||||
* const directionsService = new google.maps.DirectionsService();
|
||||
* const directionsRenderer = new google.maps.DirectionsRenderer({ map });
|
||||
* directionsService.route(
|
||||
* { origin, destination, travelMode: "DRIVING" },
|
||||
* (res, status) => status === "OK" && directionsRenderer.setDirections(res)
|
||||
* );
|
||||
*
|
||||
* -------------------------------
|
||||
* 🌦️ MAP LAYERS (attach directly to map)
|
||||
* - new google.maps.TrafficLayer().setMap(map);
|
||||
* - new google.maps.TransitLayer().setMap(map);
|
||||
* - new google.maps.BicyclingLayer().setMap(map);
|
||||
*
|
||||
* -------------------------------
|
||||
* ✅ SUMMARY
|
||||
* - “map-attached” → AdvancedMarkerElement, DirectionsRenderer, Layers.
|
||||
* - “standalone” → Geocoder, DirectionsService, DistanceMatrixService, ElevationService.
|
||||
* - “data-only” → Place, Geometry utilities.
|
||||
*/
|
||||
|
||||
/// <reference types="@types/google.maps" />
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { usePersistFn } from "@/hooks/usePersistFn";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
google?: typeof google;
|
||||
}
|
||||
}
|
||||
|
||||
const API_KEY = import.meta.env.VITE_FRONTEND_FORGE_API_KEY;
|
||||
const FORGE_BASE_URL =
|
||||
import.meta.env.VITE_FRONTEND_FORGE_API_URL ||
|
||||
"https://forge.butterfly-effect.dev";
|
||||
const MAPS_PROXY_URL = `${FORGE_BASE_URL}/v1/maps/proxy`;
|
||||
|
||||
function loadMapScript() {
|
||||
return new Promise(resolve => {
|
||||
const script = document.createElement("script");
|
||||
script.src = `${MAPS_PROXY_URL}/maps/api/js?key=${API_KEY}&v=weekly&libraries=marker,places,geocoding,geometry`;
|
||||
script.async = true;
|
||||
script.crossOrigin = "anonymous";
|
||||
script.onload = () => {
|
||||
resolve(null);
|
||||
script.remove(); // Clean up immediately
|
||||
};
|
||||
script.onerror = () => {
|
||||
console.error("Failed to load Google Maps script");
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
interface MapViewProps {
|
||||
className?: string;
|
||||
initialCenter?: google.maps.LatLngLiteral;
|
||||
initialZoom?: number;
|
||||
onMapReady?: (map: google.maps.Map) => void;
|
||||
}
|
||||
|
||||
export function MapView({
|
||||
className,
|
||||
initialCenter = { lat: 37.7749, lng: -122.4194 },
|
||||
initialZoom = 12,
|
||||
onMapReady,
|
||||
}: MapViewProps) {
|
||||
const mapContainer = useRef<HTMLDivElement>(null);
|
||||
const map = useRef<google.maps.Map | null>(null);
|
||||
|
||||
const init = usePersistFn(async () => {
|
||||
await loadMapScript();
|
||||
if (!mapContainer.current) {
|
||||
console.error("Map container not found");
|
||||
return;
|
||||
}
|
||||
map.current = new window.google.maps.Map(mapContainer.current, {
|
||||
zoom: initialZoom,
|
||||
center: initialCenter,
|
||||
mapTypeControl: true,
|
||||
fullscreenControl: true,
|
||||
zoomControl: true,
|
||||
streetViewControl: true,
|
||||
mapId: "DEMO_MAP_ID",
|
||||
});
|
||||
if (onMapReady) {
|
||||
onMapReady(map.current);
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
init();
|
||||
}, [init]);
|
||||
|
||||
return (
|
||||
<div ref={mapContainer} className={cn("w-full h-[500px]", className)} />
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
import { useAuth } from "@/_core/hooks/useAuth";
|
||||
import { getLoginUrl } from "@/const";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import {
|
||||
BarChart2,
|
||||
Bell,
|
||||
Building2,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
@@ -13,7 +11,6 @@ import {
|
||||
Menu,
|
||||
Package,
|
||||
Search,
|
||||
Settings,
|
||||
Shield,
|
||||
Users,
|
||||
X,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,300..700;1,14..32,300..700&family=Playfair+Display:wght@600;700&display=swap');
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,300..700;1,14..32,300..700&family=Playfair+Display:wght@600;700&display=swap');
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,6 @@ import {
|
||||
Building2,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Filter,
|
||||
Mail,
|
||||
MapPin,
|
||||
RotateCcw,
|
||||
@@ -16,7 +15,7 @@ import {
|
||||
SlidersHorizontal,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useState, useMemo, Fragment } from "react";
|
||||
import { useEffect, useMemo, useState, Fragment } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { REGIONS, TYPES_ACTIVITE, TAILLES_EFFECTIFS } from "../../../shared/referentiel";
|
||||
import ContactModal from "@/components/ContactModal";
|
||||
@@ -53,12 +52,23 @@ export default function Home() {
|
||||
if (typeof window === "undefined" || !sessionKey) return false;
|
||||
return sessionStorage.getItem(sessionKey) === "1";
|
||||
});
|
||||
|
||||
// La clé dépend de l'utilisateur renvoyé après l'authentification : synchroniser
|
||||
// l'état lorsque la requête CGU termine, sans conserver l'acceptation d'un autre compte.
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
setSessionCguAccepted(sessionKey ? sessionStorage.getItem(sessionKey) === "1" : false);
|
||||
}, [sessionKey]);
|
||||
|
||||
const blocsQuery = trpc.referentiel.blocsFonctionnels.useQuery();
|
||||
const editeursQuery = trpc.referentiel.editeurs.useQuery();
|
||||
const solutionsQuery = trpc.referentiel.solutions.useQuery({ search: searchText.length >= 2 ? searchText : undefined });
|
||||
const solutionsInput = useMemo(
|
||||
() => ({ search: searchText.trim().length >= 2 ? searchText.trim() : undefined }),
|
||||
[searchText]
|
||||
);
|
||||
const solutionsQuery = trpc.referentiel.solutions.useQuery(solutionsInput);
|
||||
const cguFullyAccepted = sessionCguAccepted && (cguQuery.data?.accepted ?? false);
|
||||
const searchQuery = trpc.etablissements.search.useQuery(filters, { enabled: isAuthenticated && cguFullyAccepted });
|
||||
const tracabiliteUtils = trpc.useUtils();
|
||||
|
||||
const recordConsultation = trpc.tracabilite.enregistrerConsultation.useMutation();
|
||||
|
||||
@@ -297,7 +307,7 @@ export default function Home() {
|
||||
<th
|
||||
key={col}
|
||||
onClick={() => handleSort(col)}
|
||||
className={`text-left px-${i === 0 ? 5 : 4} py-3.5 font-semibold text-muted-foreground text-xs uppercase tracking-wider cursor-pointer hover:text-foreground select-none transition-colors ${
|
||||
className={`text-left ${i === 0 ? "px-5" : "px-4"} py-3.5 font-semibold text-muted-foreground text-xs uppercase tracking-wider cursor-pointer hover:text-foreground select-none transition-colors ${
|
||||
i > 0 && i < 2 ? "hidden md:table-cell" : i >= 2 ? "hidden lg:table-cell" : ""
|
||||
}`}
|
||||
>
|
||||
|
||||
16
package.json
16
package.json
@@ -46,9 +46,7 @@
|
||||
"@trpc/client": "^11.6.0",
|
||||
"@trpc/react-query": "^11.6.0",
|
||||
"@trpc/server": "^11.6.0",
|
||||
"@types/bcrypt": "^6.0.0",
|
||||
"axios": "^1.12.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"axios": "^1.19.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -73,7 +71,6 @@
|
||||
"react-resizable-panels": "^3.0.6",
|
||||
"recharts": "^2.15.2",
|
||||
"sonner": "^2.0.7",
|
||||
"streamdown": "^1.4.0",
|
||||
"superjson": "^1.13.3",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
@@ -86,7 +83,6 @@
|
||||
"@builder.io/vite-plugin-jsx-loc": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@tailwindcss/vite": "^4.1.3",
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/express": "4.17.21",
|
||||
"@types/google.maps": "^3.58.1",
|
||||
"@types/node": "^24.7.0",
|
||||
@@ -108,13 +104,5 @@
|
||||
"vite-plugin-manus-runtime": "^0.0.57",
|
||||
"vitest": "^2.1.4"
|
||||
},
|
||||
"packageManager": "pnpm@10.4.1+sha512.c753b6c3ad7afa13af388fa6d808035a008e30ea9993f58c6663e2bc5ff21679aa834db094987129aa4d488b86df57f7b634981b2f827cdcacc698cc0cfb88af",
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"wouter@3.7.1": "patches/wouter@3.7.1.patch"
|
||||
},
|
||||
"overrides": {
|
||||
"tailwindcss>nanoid": "3.3.7"
|
||||
}
|
||||
}
|
||||
"packageManager": "pnpm@10.4.1+sha512.c753b6c3ad7afa13af388fa6d808035a008e30ea9993f58c6663e2bc5ff21679aa834db094987129aa4d488b86df57f7b634981b2f827cdcacc698cc0cfb88af"
|
||||
}
|
||||
2238
pnpm-lock.yaml
generated
2238
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
8
pnpm-workspace.yaml
Normal file
8
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
packages:
|
||||
- .
|
||||
|
||||
patchedDependencies:
|
||||
wouter@3.7.1: patches/wouter@3.7.1.patch
|
||||
|
||||
overrides:
|
||||
tailwindcss>nanoid: 3.3.7
|
||||
169
server/db.ts
169
server/db.ts
@@ -299,18 +299,46 @@ export async function upsertLogicielEtablissement(data: {
|
||||
}) {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
if (data.id) {
|
||||
await db.update(logicielsEtablissements).set({ ...data, updatedAt: new Date() }).where(eq(logicielsEtablissements.id, data.id));
|
||||
return data.id;
|
||||
const { id, ...values } = data;
|
||||
if (id) {
|
||||
/**
|
||||
* L'identifiant de la fiche ne suffit pas : le contrôle sur l'établissement
|
||||
* rend impossible une mise à jour croisée en cas d'identifiant falsifié.
|
||||
*/
|
||||
const existing = await db
|
||||
.select({ id: logicielsEtablissements.id })
|
||||
.from(logicielsEtablissements)
|
||||
.where(and(
|
||||
eq(logicielsEtablissements.id, id),
|
||||
eq(logicielsEtablissements.etablissementId, values.etablissementId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!existing.length) return null;
|
||||
|
||||
await db
|
||||
.update(logicielsEtablissements)
|
||||
.set({ ...values, updatedAt: new Date() })
|
||||
.where(eq(logicielsEtablissements.id, id));
|
||||
return id;
|
||||
}
|
||||
const result = await db.insert(logicielsEtablissements).values(data);
|
||||
const result = await db.insert(logicielsEtablissements).values(values);
|
||||
return result[0];
|
||||
}
|
||||
|
||||
export async function deleteLogicielEtablissement(id: number) {
|
||||
/**
|
||||
* Supprime une fiche seulement si elle appartient à l'établissement déjà autorisé
|
||||
* par le routeur. Cette seconde condition protège la couche SQL elle-même.
|
||||
*/
|
||||
export async function deleteLogicielEtablissement(id: number, etablissementId: number): Promise<boolean> {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
await db.delete(logicielsEtablissements).where(eq(logicielsEtablissements.id, id));
|
||||
if (!db) return false;
|
||||
const result = await db
|
||||
.delete(logicielsEtablissements)
|
||||
.where(and(
|
||||
eq(logicielsEtablissements.id, id),
|
||||
eq(logicielsEtablissements.etablissementId, etablissementId),
|
||||
));
|
||||
return Number((result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0) > 0;
|
||||
}
|
||||
|
||||
// ─── Traçabilité ──────────────────────────────────────────────────────────────
|
||||
@@ -663,21 +691,29 @@ export async function getAllUsersWithAffectations() {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
|
||||
const allUsers = await db.select().from(users).orderBy(users.name);
|
||||
const allAffectations = await db
|
||||
const [allUsers, allAffectations] = await Promise.all([
|
||||
db.select().from(users).orderBy(users.name),
|
||||
db
|
||||
.select({
|
||||
userId: userEtablissements.userId,
|
||||
etablissementId: userEtablissements.etablissementId,
|
||||
etablissementNom: etablissements.nom,
|
||||
})
|
||||
.from(userEtablissements)
|
||||
.innerJoin(etablissements, eq(userEtablissements.etablissementId, etablissements.id));
|
||||
.innerJoin(etablissements, eq(userEtablissements.etablissementId, etablissements.id)),
|
||||
]);
|
||||
|
||||
// Évite un filter() complet pour chaque utilisateur : coût linéaire même avec un grand annuaire.
|
||||
const affectationsParUtilisateur = new Map<number, { id: number; nom: string }[]>();
|
||||
for (const affectation of allAffectations) {
|
||||
const affectations = affectationsParUtilisateur.get(affectation.userId) ?? [];
|
||||
affectations.push({ id: affectation.etablissementId, nom: affectation.etablissementNom });
|
||||
affectationsParUtilisateur.set(affectation.userId, affectations);
|
||||
}
|
||||
|
||||
return allUsers.map((u) => ({
|
||||
...u,
|
||||
etablissements: allAffectations
|
||||
.filter((a) => a.userId === u.id)
|
||||
.map((a) => ({ id: a.etablissementId, nom: a.etablissementNom })),
|
||||
etablissements: affectationsParUtilisateur.get(u.id) ?? [],
|
||||
hasLocalCredentials: false, // sera enrichi côté router si besoin
|
||||
}));
|
||||
}
|
||||
@@ -714,7 +750,9 @@ export async function getMesSolutionsGroupees(userId: number, sonumRole: string)
|
||||
.select({
|
||||
solutionId: solutions.id,
|
||||
solutionNom: solutions.nom,
|
||||
editeurId: solutions.editeurId,
|
||||
editeurNom: editeurs.nom,
|
||||
blocFonctionnelId: solutions.blocFonctionnelId,
|
||||
blocFonctionnelNom: blocsFonctionnels.nom,
|
||||
etablissementId: etablissements.id,
|
||||
etablissementNom: etablissements.nom,
|
||||
@@ -745,9 +783,9 @@ export async function getMesSolutionsGroupees(userId: number, sonumRole: string)
|
||||
map.set(row.solutionId, {
|
||||
solutionId: row.solutionId,
|
||||
solutionNom: row.solutionNom ?? "",
|
||||
editeurId: null,
|
||||
editeurId: row.editeurId ?? null,
|
||||
editeurNom: row.editeurNom ?? "",
|
||||
blocFonctionnelId: null,
|
||||
blocFonctionnelId: row.blocFonctionnelId ?? null,
|
||||
blocFonctionnelNom: row.blocFonctionnelNom ?? null,
|
||||
nbEtablissements: 0,
|
||||
etablissements: [],
|
||||
@@ -882,28 +920,22 @@ export async function getStatistiques() {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
|
||||
// Total établissements
|
||||
const [{ total: totalEtablissements }] = await db
|
||||
.select({ total: sql<number>`COUNT(*)` })
|
||||
.from(etablissements);
|
||||
|
||||
// Total solutions distinctes utilisées
|
||||
const [{ total: totalSolutions }] = await db
|
||||
.select({ total: sql<number>`COUNT(DISTINCT solutionId)` })
|
||||
.from(logicielsEtablissements);
|
||||
|
||||
// Total fiches logiciels (lignes logiciels_etablissements)
|
||||
const [{ total: totalFiches }] = await db
|
||||
.select({ total: sql<number>`COUNT(*)` })
|
||||
.from(logicielsEtablissements);
|
||||
|
||||
// Établissements avec au moins un logiciel
|
||||
const [{ total: etabAvecLogiciel }] = await db
|
||||
.select({ total: sql<number>`COUNT(DISTINCT etablissementId)` })
|
||||
.from(logicielsEtablissements);
|
||||
|
||||
// Répartition par bloc fonctionnel
|
||||
const parBloc = await db
|
||||
/** Toutes ces agrégations sont indépendantes : les lancer ensemble évite huit allers-retours séquentiels. */
|
||||
const [
|
||||
[{ total: totalEtablissements }],
|
||||
[{ total: totalSolutions }],
|
||||
[{ total: totalFiches }],
|
||||
[{ total: etabAvecLogiciel }],
|
||||
parBloc,
|
||||
parRegion,
|
||||
parEtat,
|
||||
topSolutions,
|
||||
] = await Promise.all([
|
||||
db.select({ total: sql<number>`COUNT(*)` }).from(etablissements),
|
||||
db.select({ total: sql<number>`COUNT(DISTINCT solutionId)` }).from(logicielsEtablissements),
|
||||
db.select({ total: sql<number>`COUNT(*)` }).from(logicielsEtablissements),
|
||||
db.select({ total: sql<number>`COUNT(DISTINCT etablissementId)` }).from(logicielsEtablissements),
|
||||
db
|
||||
.select({
|
||||
blocNom: blocsFonctionnels.nom,
|
||||
count: sql<number>`COUNT(DISTINCT ${logicielsEtablissements.etablissementId})`,
|
||||
@@ -912,30 +944,24 @@ export async function getStatistiques() {
|
||||
.innerJoin(solutions, eq(logicielsEtablissements.solutionId, solutions.id))
|
||||
.leftJoin(blocsFonctionnels, eq(solutions.blocFonctionnelId, blocsFonctionnels.id))
|
||||
.groupBy(blocsFonctionnels.nom)
|
||||
.orderBy(sql`COUNT(DISTINCT ${logicielsEtablissements.etablissementId}) DESC`);
|
||||
|
||||
// Répartition par région
|
||||
const parRegion = await db
|
||||
.orderBy(sql`COUNT(DISTINCT ${logicielsEtablissements.etablissementId}) DESC`),
|
||||
db
|
||||
.select({
|
||||
region: etablissements.region,
|
||||
count: sql<number>`COUNT(DISTINCT ${etablissements.id})`,
|
||||
})
|
||||
.from(etablissements)
|
||||
.groupBy(etablissements.region)
|
||||
.orderBy(sql`COUNT(DISTINCT ${etablissements.id}) DESC`);
|
||||
|
||||
// Répartition par état de déploiement
|
||||
const parEtat = await db
|
||||
.orderBy(sql`COUNT(DISTINCT ${etablissements.id}) DESC`),
|
||||
db
|
||||
.select({
|
||||
etat: logicielsEtablissements.etatDeploiement,
|
||||
count: sql<number>`COUNT(*)`,
|
||||
})
|
||||
.from(logicielsEtablissements)
|
||||
.groupBy(logicielsEtablissements.etatDeploiement)
|
||||
.orderBy(sql`COUNT(*) DESC`);
|
||||
|
||||
// Top 10 solutions les plus utilisées
|
||||
const topSolutions = await db
|
||||
.orderBy(sql`COUNT(*) DESC`),
|
||||
db
|
||||
.select({
|
||||
solutionNom: solutions.nom,
|
||||
editeurNom: editeurs.nom,
|
||||
@@ -946,7 +972,8 @@ export async function getStatistiques() {
|
||||
.leftJoin(editeurs, eq(solutions.editeurId, editeurs.id))
|
||||
.groupBy(solutions.id, solutions.nom, editeurs.nom)
|
||||
.orderBy(sql`COUNT(DISTINCT ${logicielsEtablissements.etablissementId}) DESC`)
|
||||
.limit(10);
|
||||
.limit(10),
|
||||
]);
|
||||
|
||||
// Taux de remplissage (% établissements avec au moins 1 logiciel)
|
||||
const tauxRemplissage = totalEtablissements > 0
|
||||
@@ -1024,17 +1051,22 @@ export async function setReferentForEtablissement(etablissementId: number, refer
|
||||
export async function setAdherentsForEtablissement(etablissementId: number, userIds: number[]) {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
// Supprimer les affectations existantes pour cet établissement (seulement les adhérents)
|
||||
// On supprime toutes les lignes user_etablissements pour cet établissement
|
||||
await db
|
||||
const uniqueUserIds = Array.from(new Set(userIds));
|
||||
|
||||
/**
|
||||
* Le remplacement est atomique : une erreur d'insertion ne doit jamais laisser
|
||||
* l'établissement sans ses affectations précédentes.
|
||||
*/
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.delete(userEtablissements)
|
||||
.where(eq(userEtablissements.etablissementId, etablissementId));
|
||||
// Réinsérer
|
||||
if (userIds.length > 0) {
|
||||
await db.insert(userEtablissements).values(
|
||||
userIds.map((uid) => ({ userId: uid, etablissementId }))
|
||||
if (uniqueUserIds.length > 0) {
|
||||
await tx.insert(userEtablissements).values(
|
||||
uniqueUserIds.map((userId) => ({ userId, etablissementId }))
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Canaux de Discussion ─────────────────────────────────────────────────────
|
||||
@@ -1055,7 +1087,11 @@ export async function createCanal(data: {
|
||||
}) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("DB unavailable");
|
||||
const [result] = await db.insert(canauxDiscussion).values({
|
||||
const membreIds = Array.from(new Set(data.membreIds));
|
||||
|
||||
// Un canal sans ses membres ne doit jamais être observable : tout est validé ensemble.
|
||||
return db.transaction(async (tx) => {
|
||||
const [result] = await tx.insert(canauxDiscussion).values({
|
||||
titre: data.titre,
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
@@ -1065,13 +1101,14 @@ export async function createCanal(data: {
|
||||
demandeMiseEnRelationId: data.demandeMiseEnRelationId,
|
||||
creePar: data.creePar,
|
||||
});
|
||||
const canalId = (result as any).insertId as number;
|
||||
if (data.membreIds.length > 0) {
|
||||
await db.insert(membresCanauxDiscussion).values(
|
||||
data.membreIds.map((uid) => ({ canalId, userId: uid, role: "membre" as const }))
|
||||
const canalId = (result as { insertId: number }).insertId;
|
||||
if (membreIds.length > 0) {
|
||||
await tx.insert(membresCanauxDiscussion).values(
|
||||
membreIds.map((userId) => ({ canalId, userId, role: "membre" as const }))
|
||||
);
|
||||
}
|
||||
return canalId;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1121,12 +1158,14 @@ export async function sendMessageCanal(data: {
|
||||
}) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("DB unavailable");
|
||||
await db.insert(messagesCanaux).values(data);
|
||||
// Mettre à jour updatedAt du canal
|
||||
await db
|
||||
// L'ajout du message et le rafraîchissement de l'ordre des conversations sont indissociables.
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(messagesCanaux).values(data);
|
||||
await tx
|
||||
.update(canauxDiscussion)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(canauxDiscussion.id, data.canalId));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
getMesSolutionsGroupees,
|
||||
getToutesLesSolutionsGroupees,
|
||||
getSolutions,
|
||||
searchEtablissements,
|
||||
recordConsultation,
|
||||
removeEtablissementFromUser,
|
||||
repondreDemandeContact,
|
||||
@@ -48,14 +49,12 @@ import {
|
||||
getMessagesCanal,
|
||||
sendMessageCanal,
|
||||
isMemberOfCanal,
|
||||
getCanalById,
|
||||
getMembresCanal,
|
||||
addMembresCanal,
|
||||
createDemandeMiseEnRelation,
|
||||
getAllDemandesMiseEnRelation,
|
||||
getDemandesMiseEnRelationByUser,
|
||||
traiterDemandeMiseEnRelation,
|
||||
getDemandeMiseEnRelationById,
|
||||
updateUser,
|
||||
updateUserCgu,
|
||||
updateUserSonumRole,
|
||||
@@ -74,32 +73,48 @@ import { sdk } from "./_core/sdk";
|
||||
|
||||
// ─── Middleware gestionnaire SONUM ────────────────────────────────────────────
|
||||
|
||||
/** Détermine l'accès de gestionnaire une seule fois et évite des règles divergentes. */
|
||||
function isGestionnaire(user: { sonumRole?: string | null; role?: string | null }) {
|
||||
return user.sonumRole === "gestionnaire" || user.role === "admin";
|
||||
}
|
||||
|
||||
const gestionnaireProcedure = protectedProcedure.use(({ ctx, next }) => {
|
||||
if (ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
||||
if (!isGestionnaire(ctx.user)) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Accès réservé aux gestionnaires SONUM" });
|
||||
}
|
||||
return next({ ctx });
|
||||
});
|
||||
|
||||
/** Bloque les mutations pour les utilisateurs en lecture seule (role === 'readonly') */
|
||||
const writeProcedure = protectedProcedure.use(({ ctx, next }) => {
|
||||
if (ctx.user.role === "readonly") {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Votre compte est en lecture seule. Contactez un gestionnaire SONUM pour obtenir les droits de modification." });
|
||||
/** Bloque les mutations pour les utilisateurs en lecture seule (role === 'readonly'). */
|
||||
function assertWritable(role?: string | null) {
|
||||
if (role === "readonly") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Votre compte est en lecture seule. Contactez un gestionnaire SONUM pour obtenir les droits de modification.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const writeProcedure = protectedProcedure.use(({ ctx, next }) => {
|
||||
assertWritable(ctx.user.role);
|
||||
return next({ ctx });
|
||||
});
|
||||
|
||||
/** Les gestionnaires en lecture seule conservent les consultations, mais jamais les écritures. */
|
||||
const gestionnaireWriteProcedure = gestionnaireProcedure.use(({ ctx, next }) => {
|
||||
assertWritable(ctx.user.role);
|
||||
return next({ ctx });
|
||||
});
|
||||
|
||||
/// ─── Canaux de Discussion ────────────────────────────────────────────────────
|
||||
const canauxRouter = router({
|
||||
list: protectedProcedure.query(async ({ ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
return getCanauxForUser(ctx.user.id, isGestionnaire);
|
||||
return getCanauxForUser(ctx.user.id, isGestionnaire(ctx.user));
|
||||
}),
|
||||
messages: protectedProcedure
|
||||
.input(z.object({ canalId: z.number().int() }))
|
||||
.query(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
if (!isGestionnaire) {
|
||||
if (!isGestionnaire(ctx.user)) {
|
||||
const isMember = await isMemberOfCanal(input.canalId, ctx.user.id);
|
||||
if (!isMember) throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
@@ -108,33 +123,32 @@ const canauxRouter = router({
|
||||
membres: protectedProcedure
|
||||
.input(z.object({ canalId: z.number().int() }))
|
||||
.query(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
if (!isGestionnaire) {
|
||||
if (!isGestionnaire(ctx.user)) {
|
||||
const isMember = await isMemberOfCanal(input.canalId, ctx.user.id);
|
||||
if (!isMember) throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
return getMembresCanal(input.canalId);
|
||||
}),
|
||||
sendMessage: writeProcedure
|
||||
.input(z.object({ canalId: z.number().int(), contenu: z.string().min(1).max(5000) }))
|
||||
.input(z.object({ canalId: z.number().int().positive(), contenu: z.string().trim().min(1).max(5000) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
if (!isGestionnaire) {
|
||||
if (!isGestionnaire(ctx.user)) {
|
||||
const isMember = await isMemberOfCanal(input.canalId, ctx.user.id);
|
||||
if (!isMember) throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
await sendMessageCanal({ canalId: input.canalId, auteurId: ctx.user.id, auteurNom: ctx.user.name ?? "Inconnu", contenu: input.contenu });
|
||||
return { success: true };
|
||||
}),
|
||||
create: gestionnaireProcedure
|
||||
create: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
titre: z.string().min(1).max(255),
|
||||
description: z.string().optional(),
|
||||
titre: z.string().trim().min(1).max(255),
|
||||
description: z.string().trim().max(2000).optional(),
|
||||
type: z.enum(["contact_referent", "mise_en_relation_public", "mise_en_relation_prive"]),
|
||||
visibilite: z.enum(["public", "prive"]),
|
||||
etablissementId: z.number().int().optional(),
|
||||
demandeMiseEnRelationId: z.number().int().optional(),
|
||||
membreIds: z.array(z.number().int()),
|
||||
etablissementId: z.number().int().positive().optional(),
|
||||
demandeMiseEnRelationId: z.number().int().positive().optional(),
|
||||
// La contrainte d'unicité évite les doublons lors de la création multi-sélection.
|
||||
membreIds: z.array(z.number().int().positive()).min(1).transform((ids) => Array.from(new Set(ids))),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const canalId = await createCanal({ ...input, creePar: ctx.user.id });
|
||||
@@ -143,15 +157,19 @@ const canauxRouter = router({
|
||||
}
|
||||
return { canalId };
|
||||
}),
|
||||
addMembres: gestionnaireProcedure
|
||||
.input(z.object({ canalId: z.number().int(), userIds: z.array(z.number().int()) }))
|
||||
addMembres: gestionnaireWriteProcedure
|
||||
.input(z.object({ canalId: z.number().int().positive(), userIds: z.array(z.number().int().positive()).min(1).transform((ids) => Array.from(new Set(ids))) }))
|
||||
.mutation(async ({ input }) => { await addMembresCanal(input.canalId, input.userIds); return { success: true }; }),
|
||||
});
|
||||
|
||||
// ─── Demandes de Mise en Relation ─────────────────────────────────────────────
|
||||
const miseEnRelationRouter = router({
|
||||
soumettre: writeProcedure
|
||||
.input(z.object({ sujet: z.string().min(1).max(500), message: z.string().min(1), etablissementDemandeurId: z.number().int().optional() }))
|
||||
.input(z.object({
|
||||
sujet: z.string().trim().min(1).max(500),
|
||||
message: z.string().trim().min(1).max(5000),
|
||||
etablissementDemandeurId: z.number().int().positive().optional(),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const id = await createDemandeMiseEnRelation({
|
||||
demandeurId: ctx.user.id, demandeurNom: ctx.user.name ?? "Inconnu",
|
||||
@@ -188,8 +206,8 @@ export const appRouter = router({
|
||||
*/
|
||||
loginLocal: publicProcedure
|
||||
.input(z.object({
|
||||
// Accepte email ou login court
|
||||
email: z.string().min(1),
|
||||
// Accepte email ou login court, sans conserver les espaces saisis autour de l'identifiant.
|
||||
email: z.string().trim().min(1).max(320),
|
||||
password: z.string().min(1),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
@@ -242,58 +260,53 @@ export const appRouter = router({
|
||||
.input(z.object({ search: z.string().optional() }))
|
||||
.query(({ input }) => getSolutions(input.search)),
|
||||
|
||||
createEditeur: protectedProcedure
|
||||
.input(z.object({ nom: z.string().min(1) }))
|
||||
createEditeur: writeProcedure
|
||||
.input(z.object({ nom: z.string().trim().min(1).max(255) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
return createEditeur(input.nom, isGestionnaire);
|
||||
return createEditeur(input.nom, isGestionnaire(ctx.user));
|
||||
}),
|
||||
|
||||
createBlocFonctionnel: protectedProcedure
|
||||
.input(z.object({ nom: z.string().min(1) }))
|
||||
createBlocFonctionnel: writeProcedure
|
||||
.input(z.object({ nom: z.string().trim().min(1).max(255) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
return createBlocFonctionnel(input.nom, isGestionnaire);
|
||||
return createBlocFonctionnel(input.nom, isGestionnaire(ctx.user));
|
||||
}),
|
||||
updateBlocFonctionnel: gestionnaireProcedure
|
||||
.input(z.object({ id: z.number().int(), nom: z.string().min(1) }))
|
||||
updateBlocFonctionnel: gestionnaireWriteProcedure
|
||||
.input(z.object({ id: z.number().int().positive(), nom: z.string().trim().min(1).max(255) }))
|
||||
.mutation(({ input }) => updateBlocFonctionnel(input.id, input.nom)),
|
||||
deleteBlocFonctionnel: gestionnaireProcedure
|
||||
.input(z.object({ id: z.number().int() }))
|
||||
deleteBlocFonctionnel: gestionnaireWriteProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(({ input }) => deleteBlocFonctionnel(input.id)),
|
||||
updateEditeur: gestionnaireProcedure
|
||||
.input(z.object({ id: z.number().int(), nom: z.string().min(1) }))
|
||||
updateEditeur: gestionnaireWriteProcedure
|
||||
.input(z.object({ id: z.number().int().positive(), nom: z.string().trim().min(1).max(255) }))
|
||||
.mutation(({ input }) => updateEditeur(input.id, input.nom)),
|
||||
deleteEditeur: gestionnaireProcedure
|
||||
.input(z.object({ id: z.number().int() }))
|
||||
deleteEditeur: gestionnaireWriteProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(({ input }) => deleteEditeur(input.id)),
|
||||
statistiques: gestionnaireProcedure.query(() => getStatistiques()),
|
||||
|
||||
createSolution: protectedProcedure
|
||||
createSolution: writeProcedure
|
||||
.input(z.object({
|
||||
nom: z.string().min(1),
|
||||
editeurId: z.number().int(),
|
||||
blocFonctionnelId: z.number().int().optional().nullable(),
|
||||
nom: z.string().trim().min(1).max(255),
|
||||
editeurId: z.number().int().positive(),
|
||||
blocFonctionnelId: z.number().int().positive().optional().nullable(),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
||||
return createSolution(input.nom, input.editeurId, input.blocFonctionnelId, isGestionnaire);
|
||||
return createSolution(input.nom, input.editeurId, input.blocFonctionnelId, isGestionnaire(ctx.user));
|
||||
}),
|
||||
updateSolution: protectedProcedure
|
||||
updateSolution: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int(),
|
||||
nom: z.string().min(1),
|
||||
editeurId: z.number().int(),
|
||||
blocFonctionnelId: z.number().int().optional().nullable(),
|
||||
id: z.number().int().positive(),
|
||||
nom: z.string().trim().min(1).max(255),
|
||||
editeurId: z.number().int().positive(),
|
||||
blocFonctionnelId: z.number().int().positive().optional().nullable(),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
if (ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") throw new TRPCError({ code: "FORBIDDEN" });
|
||||
.mutation(({ input }) => {
|
||||
return updateSolution(input.id, input.nom, input.editeurId, input.blocFonctionnelId ?? null);
|
||||
}),
|
||||
deleteSolution: protectedProcedure
|
||||
.input(z.object({ id: z.number().int() }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
if (ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") throw new TRPCError({ code: "FORBIDDEN" });
|
||||
deleteSolution: gestionnaireWriteProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(({ input }) => {
|
||||
return deleteSolution(input.id);
|
||||
}),
|
||||
}),
|
||||
@@ -348,17 +361,13 @@ export const appRouter = router({
|
||||
tailleEffectifs: z.string().optional(),
|
||||
etatDeploiement: z.string().optional(),
|
||||
}))
|
||||
.query(({ input, ctx }) => {
|
||||
return import("./db").then(({ searchEtablissements }) =>
|
||||
searchEtablissements({
|
||||
.query(({ input, ctx }) => searchEtablissements({
|
||||
...input,
|
||||
userId: ctx.user.id,
|
||||
sonumRole: ctx.user.sonumRole,
|
||||
})
|
||||
);
|
||||
}),
|
||||
})),
|
||||
|
||||
create: gestionnaireProcedure
|
||||
create: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
finess: z.string().optional(),
|
||||
nom: z.string().min(1),
|
||||
@@ -375,7 +384,7 @@ export const appRouter = router({
|
||||
return result[0];
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
update: writeProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int(),
|
||||
visibilite: z.enum(["tous", "gestionnaires"]).optional(),
|
||||
@@ -413,7 +422,7 @@ export const appRouter = router({
|
||||
return getLogicielsByEtablissement(input.etablissementId);
|
||||
}),
|
||||
|
||||
upsert: protectedProcedure
|
||||
upsert: writeProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int().optional(),
|
||||
etablissementId: z.number().int(),
|
||||
@@ -434,20 +443,19 @@ export const appRouter = router({
|
||||
if (etab.referentId !== ctx.user.id && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
if (ctx.user.role === "readonly") throw new TRPCError({ code: "FORBIDDEN", message: "Compte en lecture seule" });
|
||||
return upsertLogicielEtablissement({ ...input, saisiePar: ctx.user.id });
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
delete: writeProcedure
|
||||
.input(z.object({ id: z.number().int(), etablissementId: z.number().int() }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
if (ctx.user.role === "readonly") throw new TRPCError({ code: "FORBIDDEN", message: "Compte en lecture seule" });
|
||||
const etab = await getEtablissementById(input.etablissementId);
|
||||
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
if (etab.referentId !== ctx.user.id && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
await deleteLogicielEtablissement(input.id);
|
||||
const wasDeleted = await deleteLogicielEtablissement(input.id, input.etablissementId);
|
||||
if (!wasDeleted) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return { success: true };
|
||||
}),
|
||||
mesSolutions: protectedProcedure
|
||||
@@ -493,7 +501,7 @@ export const appRouter = router({
|
||||
envoyer: writeProcedure
|
||||
.input(z.object({
|
||||
etablissementCibleId: z.number().int(),
|
||||
message: z.string().min(1),
|
||||
message: z.string().trim().min(1).max(5000),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const etab = await getEtablissementById(input.etablissementCibleId);
|
||||
@@ -525,10 +533,10 @@ export const appRouter = router({
|
||||
|
||||
toutesLesDemandes: gestionnaireProcedure.query(() => getAllDemandes()),
|
||||
|
||||
repondre: protectedProcedure
|
||||
repondre: writeProcedure
|
||||
.input(z.object({
|
||||
id: z.number().int(),
|
||||
reponse: z.string().min(1),
|
||||
id: z.number().int().positive(),
|
||||
reponse: z.string().trim().min(1).max(5000),
|
||||
}))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const demande = await getDemandeById(input.id);
|
||||
@@ -547,7 +555,7 @@ export const appRouter = router({
|
||||
users: gestionnaireProcedure.query(() => getAllUsersWithAffectations()),
|
||||
|
||||
/** Crée un utilisateur manuellement avec un mot de passe local */
|
||||
createUser: gestionnaireProcedure
|
||||
createUser: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
firstName: z.string().min(1),
|
||||
lastName: z.string().min(1),
|
||||
@@ -574,7 +582,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Met à jour les informations d'un utilisateur */
|
||||
updateUser: gestionnaireProcedure
|
||||
updateUser: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
firstName: z.string().min(1).optional(),
|
||||
@@ -592,7 +600,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Réinitialise le mot de passe d'un utilisateur local */
|
||||
resetPassword: gestionnaireProcedure
|
||||
resetPassword: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
newPassword: z.string().min(8),
|
||||
@@ -603,7 +611,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Supprime un utilisateur */
|
||||
deleteUser: gestionnaireProcedure
|
||||
deleteUser: gestionnaireWriteProcedure
|
||||
.input(z.object({ userId: z.number().int() }))
|
||||
.mutation(async ({ input }) => {
|
||||
await deleteUser(input.userId);
|
||||
@@ -611,7 +619,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Ancienne procédure de mise à jour du rôle (rétrocompatibilité) */
|
||||
updateRole: gestionnaireProcedure
|
||||
updateRole: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
sonumRole: z.enum(["referent", "gestionnaire", "adherent"]),
|
||||
@@ -627,7 +635,7 @@ export const appRouter = router({
|
||||
.query(({ input }) => getAffectationsByUser(input.userId)),
|
||||
|
||||
/** Remplace toutes les affectations d'un adhérent */
|
||||
setAffectations: gestionnaireProcedure
|
||||
setAffectations: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
etablissementIds: z.array(z.number().int()),
|
||||
@@ -638,7 +646,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Ajoute un établissement à un utilisateur */
|
||||
assignEtablissement: gestionnaireProcedure
|
||||
assignEtablissement: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
etablissementId: z.number().int(),
|
||||
@@ -649,7 +657,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Retire un établissement d'un utilisateur */
|
||||
removeEtablissement: gestionnaireProcedure
|
||||
removeEtablissement: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
userId: z.number().int(),
|
||||
etablissementId: z.number().int(),
|
||||
@@ -665,7 +673,7 @@ export const appRouter = router({
|
||||
.query(({ input }) => getUsersForEtablissement(input.etablissementId)),
|
||||
|
||||
/** Définit le référent numérique d'un établissement */
|
||||
setReferentForEtablissement: gestionnaireProcedure
|
||||
setReferentForEtablissement: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
etablissementId: z.number().int(),
|
||||
referentId: z.number().int().nullable(),
|
||||
@@ -676,7 +684,7 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
/** Remplace tous les adhérents affectés à un établissement */
|
||||
setAdherentsForEtablissement: gestionnaireProcedure
|
||||
setAdherentsForEtablissement: gestionnaireWriteProcedure
|
||||
.input(z.object({
|
||||
etablissementId: z.number().int(),
|
||||
userIds: z.array(z.number().int()),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appRouter } from "./routers";
|
||||
import { COOKIE_NAME } from "../shared/const";
|
||||
import type { TrpcContext } from "./_core/context";
|
||||
@@ -247,3 +247,43 @@ describe("auth.loginLocal - validation", () => {
|
||||
).rejects.toMatchObject({ code: "UNAUTHORIZED" });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests : politiques d'écriture et validation des messages ─────────────────
|
||||
|
||||
describe("politique lecture seule", () => {
|
||||
it("bloque une mutation d'administration même pour un gestionnaire", async () => {
|
||||
const readonlyGestionnaire = makeUser({ sonumRole: "gestionnaire", role: "readonly" });
|
||||
const caller = appRouter.createCaller(makeCtx(readonlyGestionnaire));
|
||||
|
||||
await expect(
|
||||
caller.admin.updateRole({ userId: 2, sonumRole: "referent" })
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
|
||||
it("bloque l'envoi de message pour un compte lecture seule avant tout accès aux données", async () => {
|
||||
const readonlyReferent = makeUser({ role: "readonly" });
|
||||
const caller = appRouter.createCaller(makeCtx(readonlyReferent));
|
||||
|
||||
await expect(
|
||||
caller.canaux.sendMessage({ canalId: 1, contenu: "Message de test" })
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("validation des contenus libres", () => {
|
||||
it("rejette un message de canal constitué uniquement d'espaces", async () => {
|
||||
const caller = appRouter.createCaller(makeCtx(makeUser()));
|
||||
|
||||
await expect(
|
||||
caller.canaux.sendMessage({ canalId: 1, contenu: " " })
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
|
||||
it("rejette une demande de mise en relation dont le message est vide après normalisation", async () => {
|
||||
const caller = appRouter.createCaller(makeCtx(makeUser()));
|
||||
|
||||
await expect(
|
||||
caller.miseEnRelation.soumettre({ sujet: "Recherche partenaire", message: " " })
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
});
|
||||
|
||||
10
todo.md
10
todo.md
@@ -109,3 +109,13 @@
|
||||
- [x] seed-admin.mjs : créer le compte adminItinova / Itinova69! (login=adminItinova, email=adminItinova@santinova-soft.org, rôle=admin)
|
||||
- [x] Nettoyage de l'ancien compte mal créé (id=180019)
|
||||
- [x] Redéploiement Gitea avec seed corrigé
|
||||
|
||||
## Maintenance — Audit, robustesse et optimisation
|
||||
|
||||
- [x] Auditer les dépendances, les fichiers suivis et les artefacts inutiles
|
||||
- [x] Identifier puis supprimer le code mort et les imports inutilisés sans modifier les comportements métier
|
||||
- [x] Renforcer les accès et mutations sensibles avec des validations, des contrôles d’autorisation et des erreurs explicites
|
||||
- [x] Optimiser les calculs et rendus React identifiés comme coûteux ou répétitifs
|
||||
- [x] Ajouter des commentaires ciblés pour les invariants métier et les décisions techniques non évidentes
|
||||
- [x] Ajouter des tests de non-régression pour les corrections critiques
|
||||
- [x] Exécuter TypeScript, les tests unitaires et le build de production avant livraison
|
||||
|
||||
Reference in New Issue
Block a user