Checkpoint: Migration complète vers authentification locale (JWT + bcrypt) : schéma DB (10 tables), routes tRPC (auth, users, etablissements, inventaire, capex, opex, parametres), page de login avec branding Itinova/Santinova, protection des routes, onglets Établissements et Utilisateurs branchés sur tRPC, import inventaire/établissements/utilisateurs via tRPC, 14 tests Vitest passants.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import NotFound from "@/pages/NotFound";
|
||||
import { Route, Switch } from "wouter";
|
||||
import { Route, Switch, useLocation } from "wouter";
|
||||
import ErrorBoundary from "./components/ErrorBoundary";
|
||||
import { ThemeProvider } from "./contexts/ThemeContext";
|
||||
import { ParametresProvider } from "./contexts/ParametresContext";
|
||||
@@ -9,6 +9,7 @@ import { AnneeProvider } from "./contexts/AnneeContext";
|
||||
import { ImportModalProvider, useImportModal } from "./contexts/ImportModalContext";
|
||||
import { ImportModal } from "./components/ImportModal";
|
||||
import Home from "./pages/Home";
|
||||
import Login from "./pages/Login";
|
||||
import Parametres from "./pages/Parametres";
|
||||
import Budget2027 from "./pages/Budget2027";
|
||||
import DsiCapex from "./pages/DsiCapex";
|
||||
@@ -16,19 +17,57 @@ import DsiOpex from "./pages/DsiOpex";
|
||||
import Santinova from "./pages/Santinova";
|
||||
import SoinsSante from "./pages/SoinsSante";
|
||||
import StExupery from "./pages/StExupery";
|
||||
import { useAuth } from "./_core/hooks/useAuth";
|
||||
import { DashboardLayoutSkeleton } from "./components/DashboardLayoutSkeleton";
|
||||
|
||||
/**
|
||||
* Garde de route — redirige vers /login si non authentifié
|
||||
*/
|
||||
function ProtectedRoute({ component: Component }: { component: React.ComponentType }) {
|
||||
const { user, loading } = useAuth();
|
||||
const [, navigate] = useLocation();
|
||||
|
||||
if (loading) return <DashboardLayoutSkeleton />;
|
||||
if (!user) {
|
||||
navigate("/login");
|
||||
return null;
|
||||
}
|
||||
return <Component />;
|
||||
}
|
||||
|
||||
function Router() {
|
||||
return (
|
||||
<Switch>
|
||||
<Route path={"/"} component={Home} />
|
||||
<Route path={"/budget2027"} component={Budget2027} />
|
||||
<Route path={"/dsi-capex"} component={DsiCapex} />
|
||||
<Route path={"/dsi-opex"} component={DsiOpex} />
|
||||
<Route path={"/santinova"} component={Santinova} />
|
||||
<Route path={"/soins-sante"} component={SoinsSante} />
|
||||
<Route path={"/st-exupery"} component={StExupery} />
|
||||
<Route path={"/parametres"} component={Parametres} />
|
||||
<Route path={"/404"} component={NotFound} />
|
||||
{/* Page de login — publique */}
|
||||
<Route path="/login" component={Login} />
|
||||
|
||||
{/* Routes protégées */}
|
||||
<Route path="/">
|
||||
<ProtectedRoute component={Home} />
|
||||
</Route>
|
||||
<Route path="/budget2027">
|
||||
<ProtectedRoute component={Budget2027} />
|
||||
</Route>
|
||||
<Route path="/dsi-capex">
|
||||
<ProtectedRoute component={DsiCapex} />
|
||||
</Route>
|
||||
<Route path="/dsi-opex">
|
||||
<ProtectedRoute component={DsiOpex} />
|
||||
</Route>
|
||||
<Route path="/santinova">
|
||||
<ProtectedRoute component={Santinova} />
|
||||
</Route>
|
||||
<Route path="/soins-sante">
|
||||
<ProtectedRoute component={SoinsSante} />
|
||||
</Route>
|
||||
<Route path="/st-exupery">
|
||||
<ProtectedRoute component={StExupery} />
|
||||
</Route>
|
||||
<Route path="/parametres">
|
||||
<ProtectedRoute component={Parametres} />
|
||||
</Route>
|
||||
|
||||
<Route path="/404" component={NotFound} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
|
||||
84
client/src/_core/hooks/useAuth.ts
Normal file
84
client/src/_core/hooks/useAuth.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { getLoginUrl } from "@/const";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { TRPCClientError } from "@trpc/client";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
type UseAuthOptions = {
|
||||
redirectOnUnauthenticated?: boolean;
|
||||
redirectPath?: string;
|
||||
};
|
||||
|
||||
export function useAuth(options?: UseAuthOptions) {
|
||||
const { redirectOnUnauthenticated = false, redirectPath = getLoginUrl() } =
|
||||
options ?? {};
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const meQuery = trpc.auth.me.useQuery(undefined, {
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const logoutMutation = trpc.auth.logout.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.auth.me.setData(undefined, null);
|
||||
},
|
||||
});
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
try {
|
||||
await logoutMutation.mutateAsync();
|
||||
} catch (error: unknown) {
|
||||
if (
|
||||
error instanceof TRPCClientError &&
|
||||
error.data?.code === "UNAUTHORIZED"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
utils.auth.me.setData(undefined, null);
|
||||
await utils.auth.me.invalidate();
|
||||
}
|
||||
}, [logoutMutation, utils]);
|
||||
|
||||
const state = useMemo(() => {
|
||||
localStorage.setItem(
|
||||
"manus-runtime-user-info",
|
||||
JSON.stringify(meQuery.data)
|
||||
);
|
||||
return {
|
||||
user: meQuery.data ?? null,
|
||||
loading: meQuery.isLoading || logoutMutation.isPending,
|
||||
error: meQuery.error ?? logoutMutation.error ?? null,
|
||||
isAuthenticated: Boolean(meQuery.data),
|
||||
};
|
||||
}, [
|
||||
meQuery.data,
|
||||
meQuery.error,
|
||||
meQuery.isLoading,
|
||||
logoutMutation.error,
|
||||
logoutMutation.isPending,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!redirectOnUnauthenticated) return;
|
||||
if (meQuery.isLoading || logoutMutation.isPending) return;
|
||||
if (state.user) return;
|
||||
if (typeof window === "undefined") return;
|
||||
if (window.location.pathname === redirectPath) return;
|
||||
|
||||
window.location.href = redirectPath
|
||||
}, [
|
||||
redirectOnUnauthenticated,
|
||||
redirectPath,
|
||||
logoutMutation.isPending,
|
||||
meQuery.isLoading,
|
||||
state.user,
|
||||
]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
refresh: () => meQuery.refetch(),
|
||||
logout,
|
||||
};
|
||||
}
|
||||
335
client/src/components/AIChatBox.tsx
Normal file
335
client/src/components/AIChatBox.tsx
Normal file
@@ -0,0 +1,335 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,8 @@
|
||||
import { useState } from 'react';
|
||||
import { useImportModal } from '../contexts/ImportModalContext';
|
||||
import { useLocation } from 'wouter';
|
||||
import { useAuth } from '../_core/hooks/useAuth';
|
||||
import { LogOut, User } from 'lucide-react';
|
||||
import {
|
||||
BarChart3,
|
||||
Building2,
|
||||
@@ -172,6 +174,7 @@ export function AppSidebar({ collapsed = false, onToggle }: AppSidebarProps) {
|
||||
const [location, navigate] = useLocation();
|
||||
const [openMenus, setOpenMenus] = useState<Set<string>>(() => getInitialOpenSections(location));
|
||||
const { openModal: openImportModal } = useImportModal();
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
// Mode accordéon : ferme les autres sections du même niveau lors de l'ouverture
|
||||
const toggleSection = (id: string) => {
|
||||
@@ -336,6 +339,32 @@ export function AppSidebar({ collapsed = false, onToggle }: AppSidebarProps) {
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Utilisateur connecté + déconnexion */}
|
||||
{user && (
|
||||
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/5 border border-white/10">
|
||||
<div className="w-7 h-7 rounded-full bg-blue-500/40 flex items-center justify-center flex-shrink-0">
|
||||
<User className="w-3.5 h-3.5 text-blue-200" />
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-white/90 truncate">
|
||||
{user.firstName ? `${user.firstName} ${user.lastName || ''}`.trim() : user.login}
|
||||
</p>
|
||||
<p className="text-[10px] text-white/40 truncate capitalize">{user.role}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => logout()}
|
||||
title="Se déconnecter"
|
||||
className="text-white/30 hover:text-white/80 transition-colors p-1 rounded"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => navigate(SETTINGS_ITEM.path)}
|
||||
className={`w-full flex items-center gap-2.5 px-3 py-2.5 rounded-lg transition-all duration-150 text-left group ${
|
||||
|
||||
264
client/src/components/DashboardLayout.tsx
Normal file
264
client/src/components/DashboardLayout.tsx
Normal file
@@ -0,0 +1,264 @@
|
||||
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 } 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: "Page 1", path: "/" },
|
||||
{ icon: Users, label: "Page 2", path: "/some-path" },
|
||||
];
|
||||
|
||||
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 activeMenuItem = menuItems.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">
|
||||
{menuItems.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?.firstName || user?.login)?.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?.firstName ? `${user.firstName} ${user.lastName || ''}`.trim() : user?.login || "-"}
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
46
client/src/components/DashboardLayoutSkeleton.tsx
Normal file
46
client/src/components/DashboardLayoutSkeleton.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
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,7 +1,8 @@
|
||||
// ImportModal.tsx — Fenêtre d'import de données (Inventaire, Établissements, Utilisateurs)
|
||||
// Design: Corporate Modernism — Itinova Budget SI
|
||||
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { useAnnee, getInventaireStorageKey } from '../contexts/AnneeContext';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
@@ -253,6 +254,17 @@ interface ImportModalProps {
|
||||
|
||||
export function ImportModal({ open, onClose }: ImportModalProps) {
|
||||
const { annee } = useAnnee();
|
||||
const utils = trpc.useUtils();
|
||||
const importInventaireMutation = trpc.inventaire.import.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.inventaire.get.invalidate();
|
||||
window.dispatchEvent(new CustomEvent('budgetsi_inventaire_updated', { detail: { annee } }));
|
||||
},
|
||||
});
|
||||
const upsertEtabMutation = trpc.etablissements.upsert.useMutation({
|
||||
onSuccess: () => utils.etablissements.list.invalidate(),
|
||||
});
|
||||
const importUsersMutation = trpc.users.importBulk.useMutation();
|
||||
const [tab, setTab] = useState<ImportTab>('inventaire');
|
||||
const [inventaireStatus, setInventaireStatus] = useState<'idle' | 'success' | 'error'>('idle');
|
||||
const [inventaireMsg, setInventaireMsg] = useState('');
|
||||
@@ -514,14 +526,24 @@ export function ImportModal({ open, onClose }: ImportModalProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Sauvegarder les données complètes de l'inventaire dans localStorage ──────
|
||||
// Structure : { meta: {...}, etablissements: [ { code, nom, fixes[], portables[], stats } ] }
|
||||
// ── Construire le payload pour tRPC ──────────────────────────────────────
|
||||
const postesPayload: Array<{ etablissementCode: string; libelle?: string | null; typePoste: 'fixe' | 'portable'; dateRef?: string | null; ageAns?: string | null; modele?: string | null; fabricant?: string | null }> = [];
|
||||
|
||||
etabData.forEach((d, code) => {
|
||||
d.fixes.forEach(p => postesPayload.push({ etablissementCode: code, libelle: p.libelle || null, typePoste: 'fixe', dateRef: p.date_achat || null, ageAns: p.age_ans !== null ? String(p.age_ans) : null, modele: p.modele || null, fabricant: p.fabricant || null }));
|
||||
d.portables.forEach(p => postesPayload.push({ etablissementCode: code, libelle: p.libelle || null, typePoste: 'portable', dateRef: p.date_achat || null, ageAns: p.age_ans !== null ? String(p.age_ans) : null, modele: p.modele || null, fabricant: p.fabricant || null }));
|
||||
});
|
||||
|
||||
// ── Envoyer à la base de données via tRPC ──────────────────────────────────
|
||||
const result = await importInventaireMutation.mutateAsync({ annee, filename: file.name, postes: postesPayload });
|
||||
|
||||
// ── Aussi sauvegarder dans localStorage pour compatibilité avec les pages existantes ──
|
||||
const etablissementsArray = Array.from(etabData.entries()).map(([code, d]) => ({
|
||||
code,
|
||||
nom: d.nom,
|
||||
fixes: d.fixes,
|
||||
portables: d.portables,
|
||||
stats: { // stats provisoires, recalculées dynamiquement par useBudgetData
|
||||
stats: {
|
||||
nb_fixes_total: d.fixes.length,
|
||||
nb_portables_total: d.portables.length,
|
||||
nb_fixes_renouveler: 0,
|
||||
@@ -533,63 +555,27 @@ export function ImportModal({ open, onClose }: ImportModalProps) {
|
||||
budget_total: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
const inventaireData = {
|
||||
meta: {
|
||||
date_calcul: new Date().toISOString(),
|
||||
date_reference: `${annee}-01-01`,
|
||||
nb_etablissements: etabData.size,
|
||||
total_fixes: nbFixes,
|
||||
total_portables: nbPortables,
|
||||
filename: file.name,
|
||||
},
|
||||
meta: { date_calcul: new Date().toISOString(), date_reference: `${annee}-01-01`, nb_etablissements: etabData.size, total_fixes: nbFixes, total_portables: nbPortables, filename: file.name },
|
||||
etablissements: etablissementsArray,
|
||||
};
|
||||
localStorage.setItem(getInventaireStorageKey(annee), JSON.stringify(inventaireData));
|
||||
localStorage.setItem(`budgetsi_inventaire_import_${annee}`, JSON.stringify({ filename: file.name, date: new Date().toISOString(), size: file.size, nbLignes: rows.length - 1, nbEtablissements: etabData.size, nbFixes, nbPortables, format: useIsiFormat ? 'isi-app' : 'classique' }));
|
||||
|
||||
// ── Mettre à jour aussi la liste des établissements (code + nom) ────────────
|
||||
const existing = loadEtablissements();
|
||||
const existingMap = new Map(existing.map(e => [e.code, e]));
|
||||
let nbNouveaux = 0;
|
||||
let nbMisAJour = 0;
|
||||
|
||||
etabData.forEach((info, code) => {
|
||||
if (existingMap.has(code)) {
|
||||
const ex = existingMap.get(code)!;
|
||||
if (!ex.nom && info.nom) {
|
||||
existingMap.set(code, { ...ex, nom: info.nom });
|
||||
nbMisAJour++;
|
||||
}
|
||||
} else {
|
||||
existingMap.set(code, { code, nom: info.nom, groupe: info.groupe, ville: info.ville, actif: true });
|
||||
nbNouveaux++;
|
||||
}
|
||||
});
|
||||
saveEtablissements(Array.from(existingMap.values()));
|
||||
|
||||
// ── Métadonnées d'import ────────────────────────────────────────────────────────
|
||||
const nbLignes = rows.length - 1;
|
||||
localStorage.setItem(`budgetsi_inventaire_import_${annee}`, JSON.stringify({
|
||||
filename: file.name,
|
||||
date: new Date().toISOString(),
|
||||
size: file.size,
|
||||
nbLignes,
|
||||
nbEtablissements: etabData.size,
|
||||
nbFixes,
|
||||
nbPortables,
|
||||
format: useIsiFormat ? 'isi-app' : 'classique',
|
||||
}));
|
||||
// ── Upsert établissements dans la BDD ──────────────────────────────────────
|
||||
for (const [code, info] of Array.from(etabData.entries())) {
|
||||
try {
|
||||
await upsertEtabMutation.mutateAsync({ code, nom: info.nom, groupe: info.groupe ?? null, ville: info.ville ?? null, actif: true });
|
||||
} catch { /* ignore les erreurs d'upsert établissement */ }
|
||||
}
|
||||
|
||||
const nbNouveaux = result.nbEtablissements;
|
||||
const details = [
|
||||
`${nbLignes} poste${nbLignes > 1 ? 's' : ''}`,
|
||||
`${rows.length - 1} poste${rows.length - 1 > 1 ? 's' : ''}`,
|
||||
`${etabData.size} établissement${etabData.size > 1 ? 's' : ''} détectés`,
|
||||
nbNouveaux > 0 ? `${nbNouveaux} nouveau${nbNouveaux > 1 ? 'x' : ''}` : null,
|
||||
`${nbFixes} fixes`,
|
||||
`${nbPortables} portables`,
|
||||
].filter(Boolean).join(' — ');
|
||||
|
||||
// Notifier les autres composants (useBudgetData, DsiCapex, Budget2027)
|
||||
window.dispatchEvent(new CustomEvent('budgetsi_inventaire_updated', { detail: { annee } }));
|
||||
].join(' — ');
|
||||
|
||||
setInventaireStatus('success');
|
||||
setInventaireMsg(`"${file.name}" importé — ${details}`);
|
||||
@@ -643,10 +629,19 @@ export function ImportModal({ open, onClose }: ImportModalProps) {
|
||||
};
|
||||
}).filter(e => e.code && e.nom);
|
||||
|
||||
// Upsert dans la BDD via tRPC
|
||||
let nbImported = 0;
|
||||
for (const etab of etabs) {
|
||||
try {
|
||||
await upsertEtabMutation.mutateAsync({ code: etab.code, nom: etab.nom, groupe: etab.groupe ?? null, ville: etab.ville ?? null, actif: etab.actif });
|
||||
nbImported++;
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
// Aussi sauvegarder en localStorage pour compatibilité
|
||||
saveEtablissements(etabs);
|
||||
setEtabStatus('success');
|
||||
setEtabMsg(`${etabs.length} établissements importés`);
|
||||
toast.success('Établissements importés', { description: `${etabs.length} établissements chargés` });
|
||||
setEtabMsg(`${nbImported} établissements importés`);
|
||||
toast.success('Établissements importés', { description: `${nbImported} établissements chargés` });
|
||||
} catch {
|
||||
setEtabStatus('error');
|
||||
setEtabMsg('Erreur lors de la lecture du fichier');
|
||||
@@ -701,10 +696,27 @@ export function ImportModal({ open, onClose }: ImportModalProps) {
|
||||
};
|
||||
}).filter(u => u.nom && u.email);
|
||||
|
||||
saveUtilisateurs(users);
|
||||
setUserStatus('success');
|
||||
setUserMsg(`${users.length} utilisateurs importés`);
|
||||
toast.success('Utilisateurs importés', { description: `${users.length} utilisateurs chargés` });
|
||||
// Import dans la BDD via tRPC
|
||||
const usersPayload = users.map(u => ({
|
||||
login: u.email.split('@')[0].replace(/[^a-zA-Z0-9._-]/g, '') || `user_${Date.now()}`,
|
||||
password: 'Itinova2027!',
|
||||
email: u.email || null,
|
||||
firstName: u.prenom || null,
|
||||
lastName: u.nom || null,
|
||||
role: (u.role === 'lecture' ? 'readonly' : u.role) as 'admin' | 'standard' | 'readonly',
|
||||
}));
|
||||
try {
|
||||
const result = await importUsersMutation.mutateAsync(usersPayload);
|
||||
setUserStatus('success');
|
||||
setUserMsg(`${result.created} utilisateurs créés, ${result.skipped} ignorés (login existant)`);
|
||||
toast.success('Utilisateurs importés', { description: `${result.created} créés — mot de passe par défaut : Itinova2027!` });
|
||||
} catch (err) {
|
||||
// Fallback localStorage
|
||||
saveUtilisateurs(users);
|
||||
setUserStatus('success');
|
||||
setUserMsg(`${users.length} utilisateurs importés (local)`);
|
||||
toast.success('Utilisateurs importés', { description: `${users.length} utilisateurs chargés` });
|
||||
}
|
||||
} catch {
|
||||
setUserStatus('error');
|
||||
setUserMsg('Erreur lors de la lecture du fichier');
|
||||
|
||||
@@ -55,7 +55,11 @@ export function ManusDialog({
|
||||
<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" />
|
||||
<img
|
||||
src={logo}
|
||||
alt="Dialog graphic"
|
||||
className="w-10 h-10 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
export { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
|
||||
|
||||
// Generate login URL at runtime so redirect URI reflects the current origin.
|
||||
export const getLoginUrl = () => {
|
||||
const oauthPortalUrl = import.meta.env.VITE_OAUTH_PORTAL_URL;
|
||||
const appId = import.meta.env.VITE_APP_ID;
|
||||
const redirectUri = `${window.location.origin}/api/oauth/callback`;
|
||||
const state = btoa(redirectUri);
|
||||
|
||||
const url = new URL(`${oauthPortalUrl}/app-auth`);
|
||||
url.searchParams.set("appId", appId);
|
||||
url.searchParams.set("redirectUri", redirectUri);
|
||||
url.searchParams.set("state", state);
|
||||
url.searchParams.set("type", "signIn");
|
||||
|
||||
return url.toString();
|
||||
/**
|
||||
* Auth locale Itinova — la page de login est /login
|
||||
* (plus de redirection vers Manus OAuth)
|
||||
*/
|
||||
export const getLoginUrl = (_returnPath?: string) => {
|
||||
return "/login";
|
||||
};
|
||||
|
||||
4
client/src/lib/trpc.ts
Normal file
4
client/src/lib/trpc.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { createTRPCReact } from "@trpc/react-query";
|
||||
import type { AppRouter } from "../../../server/routers";
|
||||
|
||||
export const trpc = createTRPCReact<AppRouter>();
|
||||
@@ -1,5 +1,61 @@
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { UNAUTHED_ERR_MSG } from '@shared/const';
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { httpBatchLink, TRPCClientError } from "@trpc/client";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import superjson from "superjson";
|
||||
import App from "./App";
|
||||
import { getLoginUrl } from "./const";
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const redirectToLoginIfUnauthorized = (error: unknown) => {
|
||||
if (!(error instanceof TRPCClientError)) return;
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const isUnauthorized = error.message === UNAUTHED_ERR_MSG;
|
||||
|
||||
if (!isUnauthorized) return;
|
||||
|
||||
window.location.href = getLoginUrl();
|
||||
};
|
||||
|
||||
queryClient.getQueryCache().subscribe(event => {
|
||||
if (event.type === "updated" && event.action.type === "error") {
|
||||
const error = event.query.state.error;
|
||||
redirectToLoginIfUnauthorized(error);
|
||||
console.error("[API Query Error]", error);
|
||||
}
|
||||
});
|
||||
|
||||
queryClient.getMutationCache().subscribe(event => {
|
||||
if (event.type === "updated" && event.action.type === "error") {
|
||||
const error = event.mutation.state.error;
|
||||
redirectToLoginIfUnauthorized(error);
|
||||
console.error("[API Mutation Error]", error);
|
||||
}
|
||||
});
|
||||
|
||||
const trpcClient = trpc.createClient({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: "/api/trpc",
|
||||
transformer: superjson,
|
||||
fetch(input, init) {
|
||||
return globalThis.fetch(input, {
|
||||
...(init ?? {}),
|
||||
credentials: "include",
|
||||
});
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</trpc.Provider>
|
||||
);
|
||||
|
||||
1437
client/src/pages/ComponentShowcase.tsx
Normal file
1437
client/src/pages/ComponentShowcase.tsx
Normal file
File diff suppressed because it is too large
Load Diff
218
client/src/pages/Login.tsx
Normal file
218
client/src/pages/Login.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Page de connexion locale — Budget SI Itinova
|
||||
* Branding : logo Itinova en haut, "powered by Santinova" en bas (partie droite)
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Eye, EyeOff, Lock, User } from "lucide-react";
|
||||
|
||||
const ITINOVA_LOGO = "/manus-storage/Itinova_Logo_Couleurs_f87c931b.jpg";
|
||||
const SANTINOVA_LOGO = "/manus-storage/logo_santinova_fond_blanc_746ca8e1.webp";
|
||||
|
||||
export default function Login() {
|
||||
const [, navigate] = useLocation();
|
||||
const [login, setLogin] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const loginMutation = trpc.auth.login.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.auth.me.invalidate();
|
||||
navigate("/");
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err.message || "Identifiants invalides");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (!login.trim() || !password.trim()) {
|
||||
setError("Veuillez remplir tous les champs.");
|
||||
return;
|
||||
}
|
||||
loginMutation.mutate({ login: login.trim(), password });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex bg-[#f0f4f8]">
|
||||
{/* Panneau gauche — visuel */}
|
||||
<div
|
||||
className="hidden lg:flex flex-1 flex-col items-center justify-center relative overflow-hidden"
|
||||
style={{
|
||||
background: "linear-gradient(135deg, #0d1b3e 0%, #1a3a6e 50%, #1e5799 100%)",
|
||||
}}
|
||||
>
|
||||
{/* Motif décoratif */}
|
||||
<div className="absolute inset-0 opacity-10">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="absolute rounded-full border border-white"
|
||||
style={{
|
||||
width: `${(i + 1) * 120}px`,
|
||||
height: `${(i + 1) * 120}px`,
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="relative z-10 text-center px-8">
|
||||
<div className="w-20 h-20 rounded-2xl bg-white/10 backdrop-blur-sm flex items-center justify-center mx-auto mb-6 border border-white/20">
|
||||
<svg viewBox="0 0 24 24" fill="none" className="w-10 h-10 text-white">
|
||||
<path d="M12 2L2 7l10 5 10-5-10-5z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/>
|
||||
<path d="M2 17l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/>
|
||||
<path d="M2 12l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold text-white mb-3" style={{ fontFamily: "Sora, sans-serif" }}>
|
||||
Budget SI
|
||||
</h1>
|
||||
<p className="text-blue-200 text-lg font-medium mb-2">Itinova Group</p>
|
||||
<p className="text-blue-300 text-sm max-w-xs mx-auto leading-relaxed">
|
||||
Gestion du budget informatique — Renouvellement du parc PC, CAPEX et charges OPEX
|
||||
</p>
|
||||
|
||||
<div className="mt-10 grid grid-cols-3 gap-4 text-center">
|
||||
{[
|
||||
{ label: "Établissements", value: "30+" },
|
||||
{ label: "Exercice", value: "2027" },
|
||||
{ label: "Modules", value: "4" },
|
||||
].map((stat) => (
|
||||
<div key={stat.label} className="bg-white/10 rounded-xl p-3 border border-white/10">
|
||||
<div className="text-xl font-bold text-white">{stat.value}</div>
|
||||
<div className="text-xs text-blue-300 mt-0.5">{stat.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Panneau droit — formulaire */}
|
||||
<div className="flex-1 lg:max-w-md flex flex-col justify-between bg-white shadow-2xl">
|
||||
{/* Logo Itinova en haut */}
|
||||
<div className="flex justify-center pt-10 px-8">
|
||||
<img
|
||||
src={ITINOVA_LOGO}
|
||||
alt="Itinova"
|
||||
className="h-16 object-contain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Formulaire centré */}
|
||||
<div className="flex-1 flex flex-col justify-center px-8 py-6">
|
||||
<div className="mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900" style={{ fontFamily: "Sora, sans-serif" }}>
|
||||
Connexion
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Accédez à votre espace Budget SI
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{/* Login */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="login" className="text-sm font-medium text-gray-700">
|
||||
Identifiant
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
<Input
|
||||
id="login"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
placeholder="Votre identifiant"
|
||||
value={login}
|
||||
onChange={(e) => setLogin(e.target.value)}
|
||||
className="pl-10 h-11 border-gray-200 focus:border-blue-500 focus:ring-blue-500/20"
|
||||
disabled={loginMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mot de passe */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password" className="text-sm font-medium text-gray-700">
|
||||
Mot de passe
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="current-password"
|
||||
placeholder="Votre mot de passe"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="pl-10 pr-10 h-11 border-gray-200 focus:border-blue-500 focus:ring-blue-500/20"
|
||||
disabled={loginMutation.isPending}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((v) => !v)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message d'erreur */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5">
|
||||
<svg className="w-4 h-4 shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bouton connexion */}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-11 text-sm font-semibold transition-all duration-150 active:scale-[0.98]"
|
||||
style={{ background: "linear-gradient(135deg, #1a3a6e, #1e5799)" }}
|
||||
disabled={loginMutation.isPending}
|
||||
>
|
||||
{loginMutation.isPending ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<svg className="animate-spin w-4 h-4" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
|
||||
</svg>
|
||||
Connexion en cours…
|
||||
</span>
|
||||
) : (
|
||||
"Se connecter"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Logo Santinova en bas */}
|
||||
<div className="flex flex-col items-center pb-8 px-8 gap-2">
|
||||
<div className="w-full h-px bg-gray-100 mb-4" />
|
||||
<span className="text-xs text-gray-400">powered by</span>
|
||||
<img
|
||||
src={SANTINOVA_LOGO}
|
||||
alt="Santinova Soft"
|
||||
className="h-8 object-contain opacity-80"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,7 +33,10 @@ export default function NotFound() {
|
||||
It may have been moved or deleted.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-center">
|
||||
<div
|
||||
id="not-found-button-group"
|
||||
className="flex flex-col sm:flex-row gap-3 justify-center"
|
||||
>
|
||||
<Button
|
||||
onClick={handleGoHome}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Parametres.tsx — Page de paramétrage global
|
||||
// Page Paramètres — Budget SI Itinova
|
||||
// Design: Corporate Modernism — Itinova Budget SI 2027
|
||||
// Onglets : Paramètres | Établissements | Utilisateurs
|
||||
|
||||
@@ -26,20 +26,16 @@ import {
|
||||
ShieldCheck,
|
||||
Eye,
|
||||
User,
|
||||
Loader2,
|
||||
KeyRound,
|
||||
} from 'lucide-react';
|
||||
import { ANNEES_DISPONIBLES } from '../contexts/AnneeContext';
|
||||
import { AppSidebar } from '../components/AppSidebar';
|
||||
import { useParametres, PARAMETRES_DEFAULTS } from '../contexts/ParametresContext';
|
||||
import { formatEuros } from '../lib/format';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
loadEtablissements,
|
||||
saveEtablissements,
|
||||
loadUtilisateurs,
|
||||
saveUtilisateurs,
|
||||
type Etablissement,
|
||||
type Utilisateur,
|
||||
} from '../components/ImportModal';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { useAuth } from '../_core/hooks/useAuth';
|
||||
|
||||
// ─── Types locaux ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -132,58 +128,52 @@ function SliderInput({
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Onglet Établissements ────────────────────────────────────────────────────
|
||||
// ─── Onglet Établissements (tRPC) ─────────────────────────────────────────────
|
||||
|
||||
function OngletEtablissements() {
|
||||
const [etabs, setEtabs] = useState<Etablissement[]>([]);
|
||||
const [editId, setEditId] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState<Partial<Etablissement>>({});
|
||||
const { user } = useAuth();
|
||||
const isAdmin = user?.role === 'admin';
|
||||
|
||||
const { data: etabs = [], isLoading, refetch } = trpc.etablissements.list.useQuery();
|
||||
const upsertMutation = trpc.etablissements.upsert.useMutation({ onSuccess: () => { refetch(); } });
|
||||
const deleteMutation = trpc.etablissements.delete.useMutation({ onSuccess: () => { refetch(); } });
|
||||
|
||||
const [editCode, setEditCode] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState<{ nom: string; groupe: string; ville: string }>({ nom: '', groupe: '', ville: '' });
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const [newEtab, setNewEtab] = useState<Partial<Etablissement>>({ actif: true });
|
||||
const [newEtab, setNewEtab] = useState<{ code: string; nom: string; groupe: string; ville: string }>({ code: '', nom: '', groupe: '', ville: '' });
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setEtabs(loadEtablissements());
|
||||
}, []);
|
||||
|
||||
const save = (data: Etablissement[]) => {
|
||||
saveEtablissements(data);
|
||||
setEtabs(data);
|
||||
const startEdit = (e: typeof etabs[0]) => {
|
||||
setEditCode(e.code);
|
||||
setEditDraft({ nom: e.nom, groupe: e.groupe ?? '', ville: e.ville ?? '' });
|
||||
};
|
||||
|
||||
const toggleActif = (code: string) => {
|
||||
save(etabs.map(e => e.code === code ? { ...e, actif: !e.actif } : e));
|
||||
};
|
||||
|
||||
const startEdit = (e: Etablissement) => {
|
||||
setEditId(e.code);
|
||||
setEditDraft({ ...e });
|
||||
};
|
||||
|
||||
const commitEdit = () => {
|
||||
if (!editId || !editDraft.nom) return;
|
||||
save(etabs.map(e => e.code === editId ? { ...e, ...editDraft } as Etablissement : e));
|
||||
setEditId(null);
|
||||
const commitEdit = async () => {
|
||||
if (!editCode || !editDraft.nom) return;
|
||||
const etab = etabs.find(e => e.code === editCode);
|
||||
if (!etab) return;
|
||||
await upsertMutation.mutateAsync({ code: editCode, nom: editDraft.nom, groupe: editDraft.groupe || null, ville: editDraft.ville || null, actif: etab.actif });
|
||||
setEditCode(null);
|
||||
toast.success('Établissement modifié');
|
||||
};
|
||||
|
||||
const deleteEtab = (code: string) => {
|
||||
const toggleActif = async (e: typeof etabs[0]) => {
|
||||
await upsertMutation.mutateAsync({ code: e.code, nom: e.nom, groupe: e.groupe ?? null, ville: e.ville ?? null, actif: !e.actif });
|
||||
toast.success(e.actif ? 'Établissement désactivé' : 'Établissement activé');
|
||||
};
|
||||
|
||||
const deleteEtab = async (code: string) => {
|
||||
if (!confirm(`Supprimer l'établissement ${code} ?`)) return;
|
||||
save(etabs.filter(e => e.code !== code));
|
||||
await deleteMutation.mutateAsync({ code });
|
||||
toast.success('Établissement supprimé');
|
||||
};
|
||||
|
||||
const addEtab = () => {
|
||||
if (!newEtab.code || !newEtab.nom) {
|
||||
toast.error('Code et nom obligatoires');
|
||||
return;
|
||||
}
|
||||
if (etabs.some(e => e.code === newEtab.code)) {
|
||||
toast.error('Ce code existe déjà');
|
||||
return;
|
||||
}
|
||||
save([...etabs, { code: newEtab.code, nom: newEtab.nom, groupe: newEtab.groupe, ville: newEtab.ville, actif: true }]);
|
||||
setNewEtab({ actif: true });
|
||||
const addEtab = async () => {
|
||||
if (!newEtab.code || !newEtab.nom) { toast.error('Code et nom obligatoires'); return; }
|
||||
if (etabs.some(e => e.code === newEtab.code)) { toast.error('Ce code existe déjà'); return; }
|
||||
await upsertMutation.mutateAsync({ code: newEtab.code, nom: newEtab.nom, groupe: newEtab.groupe || null, ville: newEtab.ville || null, actif: true });
|
||||
setNewEtab({ code: '', nom: '', groupe: '', ville: '' });
|
||||
setShowAdd(false);
|
||||
toast.success('Établissement ajouté');
|
||||
};
|
||||
@@ -211,66 +201,51 @@ function OngletEtablissements() {
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
className="flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setShowAdd(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors font-medium"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Ajouter
|
||||
</button>
|
||||
{isAdmin && (
|
||||
<button
|
||||
onClick={() => setShowAdd(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors font-medium"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Ajouter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Formulaire d'ajout */}
|
||||
{showAdd && (
|
||||
{showAdd && isAdmin && (
|
||||
<div className="bg-card border border-emerald-200 rounded-xl p-4 space-y-3">
|
||||
<p className="font-semibold text-sm text-foreground">Nouvel établissement</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Code *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newEtab.code || ''}
|
||||
onChange={e => setNewEtab(d => ({ ...d, code: e.target.value }))}
|
||||
<input type="text" value={newEtab.code} onChange={e => setNewEtab(d => ({ ...d, code: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Ex: ETB001"
|
||||
/>
|
||||
placeholder="Ex: ETB001" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Nom *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newEtab.nom || ''}
|
||||
onChange={e => setNewEtab(d => ({ ...d, nom: e.target.value }))}
|
||||
<input type="text" value={newEtab.nom} onChange={e => setNewEtab(d => ({ ...d, nom: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Nom de l'établissement"
|
||||
/>
|
||||
placeholder="Nom de l'établissement" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Groupe</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newEtab.groupe || ''}
|
||||
onChange={e => setNewEtab(d => ({ ...d, groupe: e.target.value }))}
|
||||
<input type="text" value={newEtab.groupe} onChange={e => setNewEtab(d => ({ ...d, groupe: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Ex: Itinova"
|
||||
/>
|
||||
placeholder="Ex: Itinova" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Ville</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newEtab.ville || ''}
|
||||
onChange={e => setNewEtab(d => ({ ...d, ville: e.target.value }))}
|
||||
<input type="text" value={newEtab.ville} onChange={e => setNewEtab(d => ({ ...d, ville: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Ex: Lyon"
|
||||
/>
|
||||
placeholder="Ex: Lyon" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button onClick={() => setShowAdd(false)} className="px-3 py-1.5 text-sm rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground">
|
||||
Annuler
|
||||
</button>
|
||||
<button onClick={addEtab} className="px-4 py-1.5 text-sm rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 font-medium">
|
||||
<button onClick={() => setShowAdd(false)} className="px-3 py-1.5 text-sm rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground">Annuler</button>
|
||||
<button onClick={addEtab} disabled={upsertMutation.isPending} className="px-4 py-1.5 text-sm rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 font-medium flex items-center gap-2">
|
||||
{upsertMutation.isPending && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
|
||||
Ajouter
|
||||
</button>
|
||||
</div>
|
||||
@@ -278,7 +253,12 @@ function OngletEtablissements() {
|
||||
)}
|
||||
|
||||
{/* Tableau */}
|
||||
{filtered.length === 0 ? (
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground gap-2">
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-sm">Chargement…</span>
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Building2 className="w-12 h-12 mx-auto mb-3 opacity-30" />
|
||||
<p className="font-medium">Aucun établissement</p>
|
||||
@@ -294,28 +274,25 @@ function OngletEtablissements() {
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Groupe</th>
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Ville</th>
|
||||
<th className="text-center px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Actif</th>
|
||||
<th className="text-right px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Actions</th>
|
||||
{isAdmin && <th className="text-right px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Actions</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((e, i) => (
|
||||
<tr key={e.code} className={`border-b border-border last:border-0 ${i % 2 === 0 ? '' : 'bg-muted/20'}`}>
|
||||
{editId === e.code ? (
|
||||
{editCode === e.code ? (
|
||||
<>
|
||||
<td className="px-4 py-2 font-mono text-xs font-semibold text-blue-700">{e.code}</td>
|
||||
<td className="px-4 py-2">
|
||||
<input value={editDraft.code || ''} onChange={ev => setEditDraft(d => ({ ...d, code: ev.target.value }))}
|
||||
<input value={editDraft.nom} onChange={ev => setEditDraft(d => ({ ...d, nom: ev.target.value }))}
|
||||
className="w-full px-2 py-1 text-xs border border-border rounded bg-muted/50" />
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<input value={editDraft.nom || ''} onChange={ev => setEditDraft(d => ({ ...d, nom: ev.target.value }))}
|
||||
<input value={editDraft.groupe} onChange={ev => setEditDraft(d => ({ ...d, groupe: ev.target.value }))}
|
||||
className="w-full px-2 py-1 text-xs border border-border rounded bg-muted/50" />
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<input value={editDraft.groupe || ''} onChange={ev => setEditDraft(d => ({ ...d, groupe: ev.target.value }))}
|
||||
className="w-full px-2 py-1 text-xs border border-border rounded bg-muted/50" />
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<input value={editDraft.ville || ''} onChange={ev => setEditDraft(d => ({ ...d, ville: ev.target.value }))}
|
||||
<input value={editDraft.ville} onChange={ev => setEditDraft(d => ({ ...d, ville: ev.target.value }))}
|
||||
className="w-full px-2 py-1 text-xs border border-border rounded bg-muted/50" />
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">—</td>
|
||||
@@ -324,7 +301,7 @@ function OngletEtablissements() {
|
||||
<button onClick={commitEdit} className="p-1.5 rounded bg-emerald-100 text-emerald-700 hover:bg-emerald-200">
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={() => setEditId(null)} className="p-1.5 rounded bg-muted text-muted-foreground hover:bg-muted/70">
|
||||
<button onClick={() => setEditCode(null)} className="p-1.5 rounded bg-muted text-muted-foreground hover:bg-muted/70">
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -338,25 +315,28 @@ function OngletEtablissements() {
|
||||
<td className="px-4 py-2.5 text-muted-foreground text-xs">{e.ville || '—'}</td>
|
||||
<td className="px-4 py-2.5 text-center">
|
||||
<button
|
||||
onClick={() => toggleActif(e.code)}
|
||||
onClick={() => isAdmin && toggleActif(e)}
|
||||
disabled={!isAdmin}
|
||||
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium transition-colors ${
|
||||
e.actif ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-muted text-muted-foreground hover:bg-muted/70'
|
||||
}`}
|
||||
} ${!isAdmin ? 'cursor-default' : ''}`}
|
||||
>
|
||||
{e.actif ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
|
||||
{e.actif ? 'Actif' : 'Inactif'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<button onClick={() => startEdit(e)} className="p-1.5 rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={() => deleteEtab(e.code)} className="p-1.5 rounded text-muted-foreground hover:bg-red-50 hover:text-red-600 transition-colors">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
{isAdmin && (
|
||||
<td className="px-4 py-2.5 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<button onClick={() => startEdit(e)} className="p-1.5 rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={() => deleteEtab(e.code)} className="p-1.5 rounded text-muted-foreground hover:bg-red-50 hover:text-red-600 transition-colors">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</tr>
|
||||
@@ -373,52 +353,48 @@ function OngletEtablissements() {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Onglet Utilisateurs ──────────────────────────────────────────────────────
|
||||
// ─── Onglet Utilisateurs (tRPC) ───────────────────────────────────────────────
|
||||
|
||||
const ROLE_LABELS: Record<Utilisateur['role'], { label: string; icon: React.ElementType; color: string }> = {
|
||||
const ROLE_LABELS: Record<string, { label: string; icon: React.ElementType; color: string }> = {
|
||||
admin: { label: 'Administrateur', icon: ShieldCheck, color: 'bg-red-100 text-red-700' },
|
||||
standard: { label: 'Standard', icon: User, color: 'bg-blue-100 text-blue-700' },
|
||||
lecture: { label: 'Lecture seule', icon: Eye, color: 'bg-slate-100 text-slate-600' },
|
||||
readonly: { label: 'Lecture seule', icon: Eye, color: 'bg-slate-100 text-slate-600' },
|
||||
};
|
||||
|
||||
interface UserFormProps {
|
||||
initial?: Partial<Utilisateur>;
|
||||
etabs: Etablissement[];
|
||||
onSave: (u: Omit<Utilisateur, 'id'>) => void;
|
||||
onCancel: () => void;
|
||||
title: string;
|
||||
interface UserFormData {
|
||||
login: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
role: 'admin' | 'standard' | 'readonly';
|
||||
isActive: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
function UserForm({ initial, etabs, onSave, onCancel, title }: UserFormProps) {
|
||||
const [form, setForm] = useState<Partial<Utilisateur>>({
|
||||
nom: '',
|
||||
prenom: '',
|
||||
interface UserFormProps {
|
||||
initial?: Partial<UserFormData>;
|
||||
onSave: (u: UserFormData) => void;
|
||||
onCancel: () => void;
|
||||
title: string;
|
||||
isEdit?: boolean;
|
||||
}
|
||||
|
||||
function UserForm({ initial, onSave, onCancel, title, isEdit }: UserFormProps) {
|
||||
const [form, setForm] = useState<UserFormData>({
|
||||
login: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
role: 'standard',
|
||||
etablissements: [],
|
||||
actif: true,
|
||||
isActive: true,
|
||||
password: '',
|
||||
...initial,
|
||||
});
|
||||
|
||||
const toggleEtab = (code: string) => {
|
||||
setForm(f => ({
|
||||
...f,
|
||||
etablissements: f.etablissements?.includes(code)
|
||||
? f.etablissements.filter(e => e !== code)
|
||||
: [...(f.etablissements || []), code],
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (!form.nom || !form.email) { toast.error('Nom et email obligatoires'); return; }
|
||||
onSave({
|
||||
nom: form.nom!,
|
||||
prenom: form.prenom || '',
|
||||
email: form.email!,
|
||||
role: form.role || 'standard',
|
||||
etablissements: form.etablissements || [],
|
||||
actif: form.actif !== false,
|
||||
});
|
||||
if (!form.login) { toast.error('Login obligatoire'); return; }
|
||||
if (!isEdit && !form.password) { toast.error('Mot de passe obligatoire'); return; }
|
||||
onSave(form);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -426,125 +402,117 @@ function UserForm({ initial, etabs, onSave, onCancel, title }: UserFormProps) {
|
||||
<p className="font-semibold text-sm text-foreground" style={{ fontFamily: 'Sora, sans-serif' }}>{title}</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Nom *</label>
|
||||
<input value={form.nom || ''} onChange={e => setForm(f => ({ ...f, nom: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Dupont" />
|
||||
<label className="text-xs text-muted-foreground">Login *</label>
|
||||
<input value={form.login} onChange={e => setForm(f => ({ ...f, login: e.target.value }))}
|
||||
disabled={isEdit}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-60"
|
||||
placeholder="jean.dupont" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">{isEdit ? 'Nouveau mot de passe (optionnel)' : 'Mot de passe *'}</label>
|
||||
<div className="relative mt-1">
|
||||
<KeyRound className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
|
||||
<input type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
|
||||
className="w-full pl-8 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder={isEdit ? 'Laisser vide = inchangé' : 'Min. 6 caractères'} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Prénom</label>
|
||||
<input value={form.prenom || ''} onChange={e => setForm(f => ({ ...f, prenom: e.target.value }))}
|
||||
<input value={form.firstName} onChange={e => setForm(f => ({ ...f, firstName: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Jean" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Nom</label>
|
||||
<input value={form.lastName} onChange={e => setForm(f => ({ ...f, lastName: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="Dupont" />
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs text-muted-foreground">Email *</label>
|
||||
<input type="email" value={form.email || ''} onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
|
||||
<label className="text-xs text-muted-foreground">Email</label>
|
||||
<input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
placeholder="jean.dupont@itinova.fr" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Rôle</label>
|
||||
<select value={form.role || 'standard'} onChange={e => setForm(f => ({ ...f, role: e.target.value as Utilisateur['role'] }))}
|
||||
<select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value as UserFormData['role'] }))}
|
||||
className="w-full mt-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/30">
|
||||
<option value="admin">Administrateur</option>
|
||||
<option value="standard">Standard</option>
|
||||
<option value="lecture">Lecture seule</option>
|
||||
<option value="readonly">Lecture seule</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-end pb-1">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" checked={form.actif !== false} onChange={e => setForm(f => ({ ...f, actif: e.target.checked }))}
|
||||
<input type="checkbox" checked={form.isActive} onChange={e => setForm(f => ({ ...f, isActive: e.target.checked }))}
|
||||
className="w-4 h-4 accent-primary" />
|
||||
<span className="text-sm text-foreground">Compte actif</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rattachement établissements */}
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-2">
|
||||
Établissements rattachés ({(form.etablissements || []).length} sélectionné{(form.etablissements || []).length > 1 ? 's' : ''})
|
||||
</label>
|
||||
{etabs.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground italic">Aucun établissement disponible — importez-en via "Imports & Données"</p>
|
||||
) : (
|
||||
<div className="max-h-40 overflow-y-auto border border-border rounded-lg divide-y divide-border">
|
||||
{etabs.map(e => (
|
||||
<label key={e.code} className="flex items-center gap-3 px-3 py-2 hover:bg-muted/40 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(form.etablissements || []).includes(e.code)}
|
||||
onChange={() => toggleEtab(e.code)}
|
||||
className="w-4 h-4 accent-primary"
|
||||
/>
|
||||
<span className="font-mono text-xs text-blue-700 w-16 flex-shrink-0">{e.code}</span>
|
||||
<span className="text-sm text-foreground">{e.nom}</span>
|
||||
{e.groupe && <span className="text-xs text-muted-foreground ml-auto">{e.groupe}</span>}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button onClick={onCancel} className="px-3 py-1.5 text-sm rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground">
|
||||
Annuler
|
||||
</button>
|
||||
<button onClick={handleSave} className="px-4 py-1.5 text-sm rounded-lg bg-violet-600 text-white hover:bg-violet-700 font-medium">
|
||||
Enregistrer
|
||||
</button>
|
||||
<button onClick={onCancel} className="px-3 py-1.5 text-sm rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground">Annuler</button>
|
||||
<button onClick={handleSave} className="px-4 py-1.5 text-sm rounded-lg bg-violet-600 text-white hover:bg-violet-700 font-medium">Enregistrer</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OngletUtilisateurs() {
|
||||
const [users, setUsers] = useState<Utilisateur[]>([]);
|
||||
const [etabs, setEtabs] = useState<Etablissement[]>([]);
|
||||
const utils = trpc.useUtils();
|
||||
const { data: users = [], isLoading } = trpc.users.list.useQuery();
|
||||
const createMutation = trpc.users.create.useMutation({ onSuccess: () => utils.users.list.invalidate() });
|
||||
const updateMutation = trpc.users.update.useMutation({ onSuccess: () => utils.users.list.invalidate() });
|
||||
const deleteMutation = trpc.users.delete.useMutation({ onSuccess: () => utils.users.list.invalidate() });
|
||||
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const [editId, setEditId] = useState<string | null>(null);
|
||||
const [editId, setEditId] = useState<number | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [expandedUser, setExpandedUser] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setUsers(loadUtilisateurs());
|
||||
setEtabs(loadEtablissements());
|
||||
}, []);
|
||||
|
||||
const save = (data: Utilisateur[]) => {
|
||||
saveUtilisateurs(data);
|
||||
setUsers(data);
|
||||
const addUser = async (u: UserFormData) => {
|
||||
try {
|
||||
await createMutation.mutateAsync({ login: u.login, password: u.password, email: u.email || null, firstName: u.firstName || null, lastName: u.lastName || null, role: u.role });
|
||||
setShowAdd(false);
|
||||
toast.success('Utilisateur créé');
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Erreur';
|
||||
toast.error(msg);
|
||||
}
|
||||
};
|
||||
|
||||
const addUser = (u: Omit<Utilisateur, 'id'>) => {
|
||||
const newUser: Utilisateur = { ...u, id: `user_${Date.now()}` };
|
||||
save([...users, newUser]);
|
||||
setShowAdd(false);
|
||||
toast.success('Utilisateur ajouté');
|
||||
const editUser = async (u: UserFormData) => {
|
||||
if (!editId) return;
|
||||
try {
|
||||
const data: Parameters<typeof updateMutation.mutateAsync>[0] = { id: editId, email: u.email || null, firstName: u.firstName || null, lastName: u.lastName || null, role: u.role, isActive: u.isActive };
|
||||
if (u.password) data.password = u.password;
|
||||
await updateMutation.mutateAsync(data);
|
||||
setEditId(null);
|
||||
toast.success('Utilisateur modifié');
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Erreur';
|
||||
toast.error(msg);
|
||||
}
|
||||
};
|
||||
|
||||
const editUser = (u: Omit<Utilisateur, 'id'>) => {
|
||||
save(users.map(x => x.id === editId ? { ...u, id: editId! } : x));
|
||||
setEditId(null);
|
||||
toast.success('Utilisateur modifié');
|
||||
};
|
||||
|
||||
const deleteUser = (id: string) => {
|
||||
const deleteUser = async (id: number) => {
|
||||
if (!confirm('Supprimer cet utilisateur ?')) return;
|
||||
save(users.filter(u => u.id !== id));
|
||||
await deleteMutation.mutateAsync({ id });
|
||||
toast.success('Utilisateur supprimé');
|
||||
};
|
||||
|
||||
const toggleActif = (id: string) => {
|
||||
save(users.map(u => u.id === id ? { ...u, actif: !u.actif } : u));
|
||||
const toggleActif = async (u: typeof users[0]) => {
|
||||
await updateMutation.mutateAsync({ id: u.id, isActive: !u.isActive });
|
||||
toast.success(u.isActive ? 'Compte désactivé' : 'Compte activé');
|
||||
};
|
||||
|
||||
const filtered = users.filter(u =>
|
||||
!search ||
|
||||
u.nom.toLowerCase().includes(search.toLowerCase()) ||
|
||||
u.prenom.toLowerCase().includes(search.toLowerCase()) ||
|
||||
u.email.toLowerCase().includes(search.toLowerCase())
|
||||
(u.login || '').toLowerCase().includes(search.toLowerCase()) ||
|
||||
(u.firstName || '').toLowerCase().includes(search.toLowerCase()) ||
|
||||
(u.lastName || '').toLowerCase().includes(search.toLowerCase()) ||
|
||||
(u.email || '').toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
const editingUser = editId ? users.find(u => u.id === editId) : undefined;
|
||||
@@ -554,53 +522,44 @@ function OngletUtilisateurs() {
|
||||
<div className="flex items-start gap-3 p-4 bg-violet-50 border border-violet-200 rounded-xl">
|
||||
<Info className="w-4 h-4 text-violet-600 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-violet-800">
|
||||
Gérez les utilisateurs et leurs rattachements aux établissements.
|
||||
Un utilisateur peut être rattaché à <strong>plusieurs établissements</strong>.
|
||||
Les rôles disponibles sont : <strong>Administrateur</strong>, <strong>Standard</strong> et <strong>Lecture seule</strong>.
|
||||
Gérez les utilisateurs de l'application. Les rôles disponibles sont : <strong>Administrateur</strong> (accès complet), <strong>Standard</strong> (lecture/écriture) et <strong>Lecture seule</strong>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Rechercher par nom, prénom ou email…"
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
className="flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
/>
|
||||
<button
|
||||
onClick={() => { setShowAdd(true); setEditId(null); }}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors font-medium"
|
||||
>
|
||||
<input type="text" placeholder="Rechercher par login, nom ou email…" value={search} onChange={e => setSearch(e.target.value)}
|
||||
className="flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-card focus:outline-none focus:ring-2 focus:ring-primary/30" />
|
||||
<button onClick={() => { setShowAdd(true); setEditId(null); }}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors font-medium">
|
||||
<Plus className="w-4 h-4" />
|
||||
Ajouter
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showAdd && (
|
||||
<UserForm
|
||||
etabs={etabs}
|
||||
onSave={addUser}
|
||||
onCancel={() => setShowAdd(false)}
|
||||
title="Nouvel utilisateur"
|
||||
/>
|
||||
<UserForm onSave={addUser} onCancel={() => setShowAdd(false)} title="Nouvel utilisateur" />
|
||||
)}
|
||||
|
||||
{editId && editingUser && (
|
||||
<UserForm
|
||||
initial={editingUser}
|
||||
etabs={etabs}
|
||||
initial={{ login: editingUser.login, firstName: editingUser.firstName ?? '', lastName: editingUser.lastName ?? '', email: editingUser.email ?? '', role: editingUser.role as 'admin' | 'standard' | 'readonly', isActive: editingUser.isActive, password: '' }}
|
||||
onSave={editUser}
|
||||
onCancel={() => setEditId(null)}
|
||||
title={`Modifier ${editingUser.prenom} ${editingUser.nom}`}
|
||||
title={`Modifier ${editingUser.firstName ?? ''} ${editingUser.lastName ?? editingUser.login}`}
|
||||
isEdit
|
||||
/>
|
||||
)}
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground gap-2">
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-sm">Chargement…</span>
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Users className="w-12 h-12 mx-auto mb-3 opacity-30" />
|
||||
<p className="font-medium">Aucun utilisateur</p>
|
||||
<p className="text-sm mt-1">Importez une liste via "Imports & Données" ou ajoutez manuellement.</p>
|
||||
<p className="text-sm mt-1">Ajoutez des utilisateurs manuellement.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
||||
@@ -608,56 +567,37 @@ function OngletUtilisateurs() {
|
||||
<thead>
|
||||
<tr className="bg-muted/50 border-b border-border">
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Utilisateur</th>
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Login</th>
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Email</th>
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Rôle</th>
|
||||
<th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Établissements</th>
|
||||
<th className="text-center px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Statut</th>
|
||||
<th className="text-right px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wide">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((u, i) => {
|
||||
const roleInfo = ROLE_LABELS[u.role];
|
||||
const roleInfo = ROLE_LABELS[u.role] ?? ROLE_LABELS.standard;
|
||||
const RoleIcon = roleInfo.icon;
|
||||
const isExpanded = expandedUser === u.id;
|
||||
return (
|
||||
<tr key={u.id} className={`border-b border-border last:border-0 ${i % 2 === 0 ? '' : 'bg-muted/20'}`}>
|
||||
<td className="px-4 py-2.5">
|
||||
<p className="font-medium text-foreground">{u.prenom} {u.nom}</p>
|
||||
<p className="font-medium text-foreground">{u.firstName} {u.lastName}</p>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-muted-foreground text-xs">{u.email}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-blue-700">{u.login}</td>
|
||||
<td className="px-4 py-2.5 text-muted-foreground text-xs">{u.email || '—'}</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${roleInfo.color}`}>
|
||||
<RoleIcon className="w-3 h-3" />
|
||||
{roleInfo.label}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
{u.etablissements.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground italic">Aucun</span>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setExpandedUser(isExpanded ? null : u.id)}
|
||||
className="text-xs text-blue-600 hover:underline"
|
||||
>
|
||||
{u.etablissements.length} établissement{u.etablissements.length > 1 ? 's' : ''}
|
||||
{isExpanded && (
|
||||
<span className="block mt-1 text-muted-foreground font-normal text-left">
|
||||
{u.etablissements.join(', ')}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-center">
|
||||
<button
|
||||
onClick={() => toggleActif(u.id)}
|
||||
<button onClick={() => toggleActif(u)}
|
||||
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium transition-colors ${
|
||||
u.actif ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-muted text-muted-foreground hover:bg-muted/70'
|
||||
}`}
|
||||
>
|
||||
{u.actif ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
|
||||
{u.actif ? 'Actif' : 'Inactif'}
|
||||
u.isActive ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-muted text-muted-foreground hover:bg-muted/70'
|
||||
}`}>
|
||||
{u.isActive ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
|
||||
{u.isActive ? 'Actif' : 'Inactif'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-right">
|
||||
@@ -817,7 +757,7 @@ export default function Parametres() {
|
||||
<Info className="w-4 h-4 mt-0.5 flex-shrink-0 text-blue-500" />
|
||||
<p>
|
||||
Les modifications sont appliquées <strong>immédiatement</strong> après enregistrement.
|
||||
Tous les budgets des 60 établissements sont recalculés automatiquement.
|
||||
Tous les budgets des établissements sont recalculés automatiquement.
|
||||
Les valeurs sont sauvegardées dans votre navigateur.
|
||||
</p>
|
||||
</div>
|
||||
@@ -883,46 +823,27 @@ export default function Parametres() {
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border">
|
||||
<BarChart3 className="w-4 h-4 text-muted-foreground" />
|
||||
<h2 className="font-semibold text-foreground" style={{ fontFamily: 'Sora, sans-serif' }}>Paramètres en cours d'édition</h2>
|
||||
<h2 className="font-semibold text-foreground" style={{ fontFamily: 'Sora, sans-serif' }}>Aperçu des paramètres actuels</h2>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
{[
|
||||
{ label: 'Seuil PC Fixes', value: `${draft.seuilFixesAns} ans`, changed: draft.seuilFixesAns !== parametres.seuilFixesAns },
|
||||
{ label: 'Seuil PC Portables', value: `${draft.seuilPortablesAns} ans`, changed: draft.seuilPortablesAns !== parametres.seuilPortablesAns },
|
||||
{ label: 'Coût fixe unitaire', value: formatEuros(draft.coutFixe), changed: draft.coutFixe !== parametres.coutFixe },
|
||||
{ label: 'Coût portable unitaire', value: formatEuros(draft.coutPortable), changed: draft.coutPortable !== parametres.coutPortable },
|
||||
{ label: 'Année par défaut', value: `${draft.anneeDefaut}`, changed: draft.anneeDefaut !== parametres.anneeDefaut },
|
||||
].map((item) => (
|
||||
<div key={item.label} className={`rounded-lg border px-4 py-3 transition-colors ${item.changed ? 'border-orange-300 bg-orange-50' : 'border-border bg-card'}`}>
|
||||
<p className="text-xs text-muted-foreground">{item.label}</p>
|
||||
<p className={`font-bold mt-0.5 ${item.changed ? 'text-orange-700' : 'text-foreground'}`}>
|
||||
{item.value}
|
||||
{item.changed && <span className="ml-2 text-[10px] font-normal text-orange-500 uppercase tracking-wide">modifié</span>}
|
||||
</p>
|
||||
{ label: 'Seuil PC Fixes', value: `${parametres.seuilFixesAns} ans`, color: 'text-blue-700' },
|
||||
{ label: 'Seuil PC Portables', value: `${parametres.seuilPortablesAns} ans`, color: 'text-orange-700' },
|
||||
{ label: 'Coût PC Fixe', value: formatEuros(parametres.coutFixe), color: 'text-blue-700' },
|
||||
{ label: 'Coût PC Portable', value: formatEuros(parametres.coutPortable), color: 'text-orange-700' },
|
||||
].map(item => (
|
||||
<div key={item.label} className="bg-muted/40 rounded-xl p-3 text-center">
|
||||
<p className={`text-lg font-bold tabular-nums ${item.color}`}>{item.value}</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{item.label}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{hasChanges && (
|
||||
<p className="text-sm text-orange-600 flex items-center gap-1.5">
|
||||
<Info className="w-3.5 h-3.5" />
|
||||
Des modifications non enregistrées sont en attente. Cliquez sur <strong>Enregistrer</strong> pour les appliquer.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'etablissements' && (
|
||||
<div className="max-w-4xl">
|
||||
<OngletEtablissements />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'utilisateurs' && (
|
||||
<div className="max-w-5xl">
|
||||
<OngletUtilisateurs />
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'etablissements' && <OngletEtablissements />}
|
||||
{activeTab === 'utilisateurs' && <OngletUtilisateurs />}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user