feat: add RSS feeds management page with automation rules

This commit is contained in:
Manus Deploy
2026-04-25 22:51:35 +02:00
parent 8b9a1ace2f
commit ea40cdfd4f
18 changed files with 1184 additions and 912 deletions

106
.gitignore vendored
View File

@@ -1,111 +1,5 @@
node_modules/
# Dependencies
**/node_modules
.pnpm-store/
# Build outputs
dist/
build/
*.dist
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDE and editor files
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
*.bak
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# nyc test coverage
.nyc_output
# Dependency directories
jspm_packages/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
# Gatsby files
.cache/
# Storybook build outputs
.out
.storybook-out
# Temporary folders
tmp/
temp/
# Database
*.db
*.sqlite
*.sqlite3
# Webdev artifacts (checkpoint zips, migrations, etc.)
.webdev/

View File

@@ -1,95 +0,0 @@
{
"query": "SELECT * FROM app_settings; SELECT * FROM import_logs ORDER BY startedAt DESC LIMIT 5;",
"command": "mysql --batch --raw --column-names --default-character-set=utf8mb4 --host gateway02.us-east-1.prod.aws.tidbcloud.com --port 4000 --user 4CrrYuB5tme73Qo.63b125a8f9ca --database VepzDyqR8YkJNcqpZ729Bw --execute SELECT * FROM app_settings; SELECT * FROM import_logs ORDER BY startedAt DESC LIMIT 5;",
"rows": [
{
"id": "1",
"key": "source_type",
"value": "local",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "2",
"key": "veille_file_path",
"value": "D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "3",
"key": "aap_file_path",
"value": "D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "4",
"key": "ftp_host",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "5",
"key": "ftp_port",
"value": "21",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "6",
"key": "ftp_user",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "7",
"key": "ftp_password",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "8",
"key": "ftp_secure",
"value": "false",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "9",
"key": "onedrive_token",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "10",
"key": "sharepoint_site_url",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "11",
"key": "sharepoint_token",
"value": "",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "12",
"key": "auth_mode",
"value": "local",
"updatedAt": "2026-03-16 18:23:41"
},
{
"id": "13",
"key": "import_time",
"value": "06:00",
"updatedAt": "2026-03-16 18:23:41"
}
],
"messages": [
"id\tfileType\tsource\tstatus\ttotalRows\tnewRows\tskippedRows\terrorMessage\tdetails\tstartedAt\tcompletedAt",
"8\tveille\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:25:31\t2026-03-16 18:25:31",
"7\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:25:31\t2026-03-16 18:25:31",
"5\tveille\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:39\t2026-03-16 18:24:39",
"6\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:39\t2026-03-16 18:24:39",
"4\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:15\t2026-03-16 18:24:15"
],
"stdout": "id\tkey\tvalue\tupdatedAt\n1\tsource_type\tlocal\t2026-03-16 18:23:41\n2\tveille_file_path\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\t2026-03-16 18:23:41\n3\taap_file_path\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\t2026-03-16 18:23:41\n4\tftp_host\t\t2026-03-16 18:23:41\n5\tftp_port\t21\t2026-03-16 18:23:41\n6\tftp_user\t\t2026-03-16 18:23:41\n7\tftp_password\t\t2026-03-16 18:23:41\n8\tftp_secure\tfalse\t2026-03-16 18:23:41\n9\tonedrive_token\t\t2026-03-16 18:23:41\n10\tsharepoint_site_url\t\t2026-03-16 18:23:41\n11\tsharepoint_token\t\t2026-03-16 18:23:41\n12\tauth_mode\tlocal\t2026-03-16 18:23:41\n13\timport_time\t06:00\t2026-03-16 18:23:41\nid\tfileType\tsource\tstatus\ttotalRows\tnewRows\tskippedRows\terrorMessage\tdetails\tstartedAt\tcompletedAt\n8\tveille\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:25:31\t2026-03-16 18:25:31\n7\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:25:31\t2026-03-16 18:25:31\n5\tveille\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:39\t2026-03-16 18:24:39\n6\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:39\t2026-03-16 18:24:39\n4\taap\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\terror\t0\t0\t0\tFichier introuvable : D:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\tNULL\t2026-03-16 18:24:15\t2026-03-16 18:24:15\n",
"stderr": "",
"execution_time_ms": 56
}

View File

@@ -1,49 +0,0 @@
{
"query": "SELECT COUNT(*) as total_veille FROM veille_items; SELECT COUNT(*) as total_aap FROM aap_items; SELECT typeVeille, COUNT(*) as nb FROM veille_items GROUP BY typeVeille; SELECT categorie, COUNT(*) as nb FROM aap_items GROUP BY categorie;",
"command": "mysql --batch --raw --column-names --default-character-set=utf8mb4 --host gateway02.us-east-1.prod.aws.tidbcloud.com --port 4000 --user 4CrrYuB5tme73Qo.63b125a8f9ca --database VepzDyqR8YkJNcqpZ729Bw --execute SELECT COUNT(*) as total_veille FROM veille_items; SELECT COUNT(*) as total_aap FROM aap_items; SELECT typeVeille, COUNT(*) as nb FROM veille_items GROUP BY typeVeille; SELECT categorie, COUNT(*) as nb FROM aap_items GROUP BY categorie;",
"rows": [
{
"total_veille": "38"
},
{
"total_veille": "total_aap"
},
{
"total_veille": "7"
},
{
"total_veille": "typeVeille\tnb"
},
{
"total_veille": "concurrentielle\t4"
},
{
"total_veille": "technologique\t4"
},
{
"total_veille": "reglementaire\t13"
},
{
"total_veille": "generale\t17"
},
{
"total_veille": "categorie\tnb"
},
{
"total_veille": "PA\t1"
},
{
"total_veille": "Sanitaire\t4"
},
{
"total_veille": "Handicap\t1"
},
{
"total_veille": "Autre\t1"
}
],
"messages": [],
"stdout": "total_veille\n38\ntotal_aap\n7\ntypeVeille\tnb\nconcurrentielle\t4\ntechnologique\t4\nreglementaire\t13\ngenerale\t17\ncategorie\tnb\nPA\t1\nSanitaire\t4\nHandicap\t1\nAutre\t1\n",
"stderr": "",
"execution_time_ms": 66
}

View File

@@ -1,9 +0,0 @@
{
"query": "INSERT INTO local_users (email, passwordHash, name, role, isActive, createdAt, updatedAt)\nVALUES (\n 'adminItinova',\n '$2b$12$BFswq4nzwOXHx1CHW2QIq.qSlfYgJD1iPC07Wx6Bi8V8pKJyK6BBq',\n 'Admin Itinova',\n 'admin',\n 1,\n NOW(),\n NOW()\n);",
"command": "mysql --batch --raw --column-names --default-character-set=utf8mb4 --host gateway02.us-east-1.prod.aws.tidbcloud.com --port 4000 --user 4CrrYuB5tme73Qo.63b125a8f9ca --database VepzDyqR8YkJNcqpZ729Bw --execute INSERT INTO local_users (email, passwordHash, name, role, isActive, createdAt, updatedAt)\nVALUES (\n 'adminItinova',\n '$2b$12$BFswq4nzwOXHx1CHW2QIq.qSlfYgJD1iPC07Wx6Bi8V8pKJyK6BBq',\n 'Admin Itinova',\n 'admin',\n 1,\n NOW(),\n NOW()\n);",
"rows": [],
"messages": [],
"stdout": "",
"stderr": "",
"execution_time_ms": 529
}

View File

@@ -1,17 +0,0 @@
{
"query": "SELECT id, email, name, role, isActive FROM local_users WHERE email = 'adminItinova';",
"command": "mysql --batch --raw --column-names --default-character-set=utf8mb4 --host gateway02.us-east-1.prod.aws.tidbcloud.com --port 4000 --user 4CrrYuB5tme73Qo.63b125a8f9ca --database VepzDyqR8YkJNcqpZ729Bw --execute SELECT id, email, name, role, isActive FROM local_users WHERE email = 'adminItinova';",
"rows": [
{
"id": "60001",
"email": "adminItinova",
"name": "Admin Itinova",
"role": "admin",
"isActive": "1"
}
],
"messages": [],
"stdout": "id\temail\tname\trole\tisActive\n60001\tadminItinova\tAdmin Itinova\tadmin\t1\n",
"stderr": "",
"execution_time_ms": 53
}

View File

@@ -1,22 +0,0 @@
{
"query": "SELECT * FROM app_settings; SELECT * FROM import_logs ORDER BY started_at DESC LIMIT 5;",
"command": "mysql --batch --raw --column-names --default-character-set=utf8mb4 --host gateway02.us-east-1.prod.aws.tidbcloud.com --port 4000 --user 4CrrYuB5tme73Qo.63b125a8f9ca --database VepzDyqR8YkJNcqpZ729Bw --execute SELECT * FROM app_settings; SELECT * FROM import_logs ORDER BY started_at DESC LIMIT 5;",
"returncode": 1,
"logs": [
"id\tkey\tvalue\tupdatedAt",
"1\tsource_type\tlocal\t2026-03-16 18:23:41",
"2\tveille_file_path\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\t2026-03-16 18:23:41",
"3\taap_file_path\tD:\\OneDrive - ITINOVA\\@ITINOVA\\Projets\\@Logiciel veille réglementaire\t2026-03-16 18:23:41",
"4\tftp_host\t\t2026-03-16 18:23:41",
"5\tftp_port\t21\t2026-03-16 18:23:41",
"6\tftp_user\t\t2026-03-16 18:23:41",
"7\tftp_password\t\t2026-03-16 18:23:41",
"8\tftp_secure\tfalse\t2026-03-16 18:23:41",
"9\tonedrive_token\t\t2026-03-16 18:23:41",
"10\tsharepoint_site_url\t\t2026-03-16 18:23:41",
"11\tsharepoint_token\t\t2026-03-16 18:23:41",
"12\tauth_mode\tlocal\t2026-03-16 18:23:41",
"13\timport_time\t06:00\t2026-03-16 18:23:41",
"ERROR 1054 (42S22) at line 1: Unknown column 'started_at' in 'order clause'"
]
}

56
Dockerfile Normal file
View File

@@ -0,0 +1,56 @@
# ─── Stage 1: Build ───────────────────────────────────────────────────────────
FROM node:22-slim AS builder
# Install pnpm (version correspondant au packageManager du projet)
RUN corepack enable && corepack prepare pnpm@10.4.1 --activate
WORKDIR /app
# Copy package files first for better layer caching
COPY package.json pnpm-lock.yaml ./
# Copy patches BEFORE pnpm install (referenced in pnpm-lock.yaml)
COPY patches/ ./patches/
# Install all dependencies (including devDependencies for build)
RUN pnpm install --frozen-lockfile
# Copy source code
COPY . .
# Build frontend (Vite) and backend (esbuild)
RUN pnpm run build
# ─── Stage 2: Production ─────────────────────────────────────────────────────
FROM node:22-slim AS production
# Install pnpm
RUN corepack enable && corepack prepare pnpm@10.4.1 --activate
WORKDIR /app
# Copy package files
COPY package.json pnpm-lock.yaml ./
# Copy patches (needed for pnpm install to apply patched dependencies)
COPY patches/ ./patches/
# Install ALL dependencies (vite is imported at top-level in the bundle even though
# it is only used in dev mode; esbuild marks it as external so it must be present)
RUN pnpm install --frozen-lockfile
# Copy built artifacts from builder
COPY --from=builder /app/dist ./dist
# Copy drizzle migrations
COPY drizzle/ ./drizzle/
COPY drizzle.config.ts ./
# Set environment
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
# Start the application
CMD ["node", "dist/index.js"]

View File

@@ -12,7 +12,8 @@ import AAPDashboard from "./pages/AAPDashboard";
import Settings from "./pages/Settings";
import UsersAdmin from "./pages/UsersAdmin";
import ImportLogs from "./pages/ImportLogs";
import BoiteAIdees from "./pages/BoiteAIdees";
import BoiteAIdees from "@/pages/BoiteAIdees";
import RssFeeds from "@/pages/RssFeeds";
import { Loader2 } from "lucide-react";
// ─── Guard d'authentification ─────────────────────────────────────────────────
@@ -108,6 +109,16 @@ function BoiteAIdeesPage() {
);
}
function RssFeedsPage() {
return (
<AuthGuard>
<DashboardWrapper>
<RssFeeds />
</DashboardWrapper>
</AuthGuard>
);
}
// ─── Routeur principal ────────────────────────────────────────────────────────
function Router() {
@@ -123,6 +134,7 @@ function Router() {
<Route path="/admin/users" component={UsersPage} />
<Route path="/admin/logs" component={LogsPage} />
<Route path="/boite-a-idees" component={BoiteAIdeesPage} />
<Route path="/admin/rss" component={RssFeedsPage} />
<Route path="/404" component={NotFound} />
<Route component={NotFound} />
</Switch>

View File

@@ -17,6 +17,7 @@ import {
Menu,
X,
Lightbulb,
Rss,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
@@ -64,6 +65,7 @@ const NAV_GROUPS: NavGroup[] = [
items: [
{ label: "Logs d'import", href: "/admin/logs", icon: <Activity size={16} />, adminOnly: true },
{ label: "Utilisateurs", href: "/admin/users", icon: <Users size={16} />, adminOnly: true },
{ label: "Flux RSS", href: "/admin/rss", icon: <Rss size={16} />, adminOnly: true },
{ label: "Paramètres", href: "/admin/settings", icon: <Settings size={16} />, adminOnly: true },
],
},

View File

@@ -4,6 +4,8 @@ export { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
export const getLoginUrl = () => {
const oauthPortalUrl = import.meta.env.VITE_OAUTH_PORTAL_URL;
const appId = import.meta.env.VITE_APP_ID;
// Fallback to local login when OAuth is not configured
if (!oauthPortalUrl) return "/login";
const redirectUri = `${window.location.origin}/api/oauth/callback`;
const state = btoa(redirectUri);

View File

@@ -1,17 +1,18 @@
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { createContext, useContext, useState, ReactNode } from "react";
import { trpc } from "@/lib/trpc";
interface LocalUser {
id: number;
name: string;
email: string;
username: string | null;
email: string | null;
role: "admin" | "user" | "readonly";
}
interface LocalAuthContextType {
user: LocalUser | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
login: (identifier: string, password: string) => Promise<void>;
logout: () => Promise<void>;
isAuthenticated: boolean;
}
@@ -34,10 +35,10 @@ export function LocalAuthProvider({ children }: { children: ReactNode }) {
const loginMutation = trpc.auth.localLogin.useMutation();
const logoutMutation = trpc.auth.localLogout.useMutation();
const login = async (email: string, password: string) => {
const login = async (identifier: string, password: string) => {
setLoading(true);
try {
const result = await loginMutation.mutateAsync({ email, password });
const result = await loginMutation.mutateAsync({ identifier, password });
const localUser = result.user as LocalUser;
setUser(localUser);
localStorage.setItem(LOCAL_USER_KEY, JSON.stringify(localUser));

View File

@@ -1,465 +0,0 @@
import { useState } from "react";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";
import {
Lightbulb,
Plus,
MessageSquare,
Calendar,
User,
ChevronDown,
ChevronUp,
Send,
Clock,
CheckCircle2,
XCircle,
AlertCircle,
} from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
type Statut = "ouvert" | "en_cours" | "resolu" | "ferme";
const STATUT_CONFIG: Record<Statut, { label: string; color: string; icon: React.ReactNode }> = {
ouvert: {
label: "Ouvert",
color: "bg-blue-100 text-blue-700 border-blue-200",
icon: <AlertCircle className="h-3 w-3" />,
},
en_cours: {
label: "En cours",
color: "bg-amber-100 text-amber-700 border-amber-200",
icon: <Clock className="h-3 w-3" />,
},
resolu: {
label: "Résolu",
color: "bg-emerald-100 text-emerald-700 border-emerald-200",
icon: <CheckCircle2 className="h-3 w-3" />,
},
ferme: {
label: "Fermé",
color: "bg-slate-100 text-slate-600 border-slate-200",
icon: <XCircle className="h-3 w-3" />,
},
};
type Idea = {
id: number;
userId: number;
userName: string;
titre: string;
message: string;
statut: Statut;
reponseAdmin: string | null;
reponduPar: string | null;
reponduAt: Date | null;
createdAt: Date;
updatedAt: Date;
};
export default function BoiteAIdees() {
const { user } = useAuth();
const isAdmin = user?.role === "admin";
const { data: ideas = [], refetch } = trpc.ideas.list.useQuery();
const createMutation = trpc.ideas.create.useMutation({
onSuccess: () => {
toast.success("Votre demande a été envoyée avec succès !");
setNewDialogOpen(false);
setNewTitre("");
setNewMessage("");
refetch();
},
onError: (e) => toast.error(e.message),
});
const reponseMutation = trpc.ideas.repondre.useMutation({
onSuccess: () => {
toast.success("Réponse enregistrée !");
setReponseDialogOpen(false);
setReponseText("");
setSelectedIdea(null);
refetch();
},
onError: (e) => toast.error(e.message),
});
// État nouvelle demande
const [newDialogOpen, setNewDialogOpen] = useState(false);
const [newTitre, setNewTitre] = useState("");
const [newMessage, setNewMessage] = useState("");
// État réponse admin
const [reponseDialogOpen, setReponseDialogOpen] = useState(false);
const [selectedIdea, setSelectedIdea] = useState<Idea | null>(null);
const [reponseText, setReponseText] = useState("");
const [reponseStatut, setReponseStatut] = useState<Statut>("resolu");
// État expansion des cartes
const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
// Filtre statut
const [filtreStatut, setFiltreStatut] = useState<string>("tous");
const [filtreRecherche, setFiltreRecherche] = useState("");
const toggleExpand = (id: number) => {
setExpandedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const handleRepondre = (idea: Idea) => {
setSelectedIdea(idea);
setReponseText(idea.reponseAdmin ?? "");
setReponseStatut(idea.statut === "ouvert" ? "en_cours" : idea.statut);
setReponseDialogOpen(true);
};
const filteredIdeas = (ideas as Idea[]).filter((idea) => {
const matchStatut = filtreStatut === "tous" || idea.statut === filtreStatut;
const matchRecherche =
!filtreRecherche ||
idea.titre.toLowerCase().includes(filtreRecherche.toLowerCase()) ||
idea.message.toLowerCase().includes(filtreRecherche.toLowerCase()) ||
idea.userName.toLowerCase().includes(filtreRecherche.toLowerCase());
return matchStatut && matchRecherche;
});
const counts = {
tous: (ideas as Idea[]).length,
ouvert: (ideas as Idea[]).filter((i) => i.statut === "ouvert").length,
en_cours: (ideas as Idea[]).filter((i) => i.statut === "en_cours").length,
resolu: (ideas as Idea[]).filter((i) => i.statut === "resolu").length,
ferme: (ideas as Idea[]).filter((i) => i.statut === "ferme").length,
};
return (
<div className="p-6 max-w-5xl mx-auto">
{/* En-tête */}
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-3">
<div className="p-2 bg-amber-100 rounded-xl">
<Lightbulb className="h-6 w-6 text-amber-600" />
</div>
<div>
<h1 className="text-2xl font-bold text-slate-800">Boîte à idées</h1>
<p className="text-sm text-slate-500">
{isAdmin
? "Gérez les questions et suggestions des utilisateurs"
: "Posez vos questions et partagez vos suggestions"}
</p>
</div>
</div>
<Button
onClick={() => setNewDialogOpen(true)}
className="bg-[#0a2463] hover:bg-[#0a2463]/90 text-white gap-2 shadow-md"
>
<Plus className="h-4 w-4" />
Nouvelle demande
</Button>
</div>
{/* Filtres */}
<div className="flex flex-wrap gap-3 mb-6">
<div className="flex-1 min-w-[200px]">
<Input
placeholder="Rechercher par titre, message ou demandeur..."
value={filtreRecherche}
onChange={(e) => setFiltreRecherche(e.target.value)}
className="bg-white border-slate-200"
/>
</div>
<div className="flex gap-2 flex-wrap">
{(["tous", "ouvert", "en_cours", "resolu", "ferme"] as const).map((s) => (
<button
key={s}
onClick={() => setFiltreStatut(s)}
className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-all ${
filtreStatut === s
? "bg-[#0a2463] text-white border-[#0a2463]"
: "bg-white text-slate-600 border-slate-200 hover:border-[#0a2463]/40"
}`}
>
{s === "tous" ? "Tous" : STATUT_CONFIG[s].label}{" "}
<span className="opacity-70">({counts[s]})</span>
</button>
))}
</div>
</div>
{/* Liste des demandes */}
{filteredIdeas.length === 0 ? (
<div className="text-center py-16 text-slate-400">
<MessageSquare className="h-12 w-12 mx-auto mb-3 opacity-30" />
<p className="text-lg font-medium">Aucune demande pour le moment</p>
<p className="text-sm mt-1">Soyez le premier à soumettre une question ou une suggestion.</p>
</div>
) : (
<div className="space-y-3">
{filteredIdeas.map((idea) => {
const isExpanded = expandedIds.has(idea.id);
const cfg = STATUT_CONFIG[idea.statut];
return (
<div
key={idea.id}
className="bg-white rounded-xl border border-slate-100 shadow-sm hover:shadow-md transition-shadow overflow-hidden"
>
{/* En-tête de la carte */}
<div
className="flex items-start gap-4 p-4 cursor-pointer"
onClick={() => toggleExpand(idea.id)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap mb-1">
<span
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${cfg.color}`}
>
{cfg.icon}
{cfg.label}
</span>
<h3 className="font-semibold text-slate-800 text-sm truncate">
{idea.titre}
</h3>
</div>
<div className="flex items-center gap-4 text-xs text-slate-400 mt-1">
<span className="flex items-center gap-1">
<User className="h-3 w-3" />
{idea.userName}
</span>
<span className="flex items-center gap-1">
<Calendar className="h-3 w-3" />
{format(new Date(idea.createdAt), "d MMM yyyy à HH:mm", { locale: fr })}
</span>
{idea.reponseAdmin && (
<span className="flex items-center gap-1 text-emerald-600">
<MessageSquare className="h-3 w-3" />
Réponse disponible
</span>
)}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{isAdmin && (
<Button
size="sm"
variant="outline"
className="text-xs h-7 px-2 border-[#0a2463]/30 text-[#0a2463] hover:bg-[#0a2463]/5"
onClick={(e) => {
e.stopPropagation();
handleRepondre(idea);
}}
>
<Send className="h-3 w-3 mr-1" />
Répondre
</Button>
)}
{isExpanded ? (
<ChevronUp className="h-4 w-4 text-slate-400" />
) : (
<ChevronDown className="h-4 w-4 text-slate-400" />
)}
</div>
</div>
{/* Contenu développé */}
{isExpanded && (
<div className="border-t border-slate-100 px-4 pb-4 pt-3 space-y-3">
{/* Message */}
<div className="bg-slate-50 rounded-lg p-3">
<p className="text-xs font-medium text-slate-500 mb-1.5 uppercase tracking-wide">
Message
</p>
<p className="text-sm text-slate-700 whitespace-pre-wrap">{idea.message}</p>
</div>
{/* Réponse admin */}
{idea.reponseAdmin && (
<div className="bg-emerald-50 rounded-lg p-3 border border-emerald-100">
<p className="text-xs font-medium text-emerald-600 mb-1.5 uppercase tracking-wide flex items-center gap-1">
<MessageSquare className="h-3 w-3" />
Réponse de l'équipe
{idea.reponduPar && (
<span className="text-emerald-500 normal-case ml-1">
{idea.reponduPar}
</span>
)}
{idea.reponduAt && (
<span className="text-emerald-400 normal-case ml-1">
({format(new Date(idea.reponduAt), "d MMM yyyy", { locale: fr })})
</span>
)}
</p>
<p className="text-sm text-emerald-800 whitespace-pre-wrap">
{idea.reponseAdmin}
</p>
</div>
)}
</div>
)}
</div>
);
})}
</div>
)}
{/* Dialog : Nouvelle demande */}
<Dialog open={newDialogOpen} onOpenChange={setNewDialogOpen}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Lightbulb className="h-5 w-5 text-amber-500" />
Nouvelle demande
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div>
<Label htmlFor="titre" className="text-sm font-medium">
Titre <span className="text-red-500">*</span>
</Label>
<Input
id="titre"
placeholder="Résumez votre demande en quelques mots..."
value={newTitre}
onChange={(e) => setNewTitre(e.target.value)}
className="mt-1"
/>
</div>
<div>
<Label htmlFor="message" className="text-sm font-medium">
Message <span className="text-red-500">*</span>
</Label>
<Textarea
id="message"
placeholder="Décrivez votre question, suggestion ou remarque en détail..."
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
rows={5}
className="mt-1 resize-none"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setNewDialogOpen(false)}>
Annuler
</Button>
<Button
onClick={() => {
if (!newTitre.trim() || !newMessage.trim()) {
toast.error("Veuillez remplir tous les champs");
return;
}
createMutation.mutate({ titre: newTitre.trim(), message: newMessage.trim() });
}}
disabled={createMutation.isPending}
className="bg-[#0a2463] hover:bg-[#0a2463]/90 text-white gap-2"
>
<Send className="h-4 w-4" />
{createMutation.isPending ? "Envoi..." : "Envoyer"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Dialog : Réponse admin */}
<Dialog open={reponseDialogOpen} onOpenChange={setReponseDialogOpen}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<MessageSquare className="h-5 w-5 text-[#0a2463]" />
Répondre à la demande
</DialogTitle>
</DialogHeader>
{selectedIdea && (
<div className="space-y-4 py-2">
{/* Rappel de la demande */}
<div className="bg-slate-50 rounded-lg p-3">
<p className="text-xs font-medium text-slate-500 mb-1">Demande de {selectedIdea.userName}</p>
<p className="text-sm font-semibold text-slate-800">{selectedIdea.titre}</p>
<p className="text-xs text-slate-600 mt-1 line-clamp-2">{selectedIdea.message}</p>
</div>
{/* Statut */}
<div>
<Label className="text-sm font-medium">Statut</Label>
<Select
value={reponseStatut}
onValueChange={(v) => setReponseStatut(v as Statut)}
>
<SelectTrigger className="mt-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ouvert">Ouvert</SelectItem>
<SelectItem value="en_cours">En cours</SelectItem>
<SelectItem value="resolu">Résolu</SelectItem>
<SelectItem value="ferme">Fermé</SelectItem>
</SelectContent>
</Select>
</div>
{/* Réponse */}
<div>
<Label htmlFor="reponse" className="text-sm font-medium">
Réponse <span className="text-red-500">*</span>
</Label>
<Textarea
id="reponse"
placeholder="Rédigez votre réponse..."
value={reponseText}
onChange={(e) => setReponseText(e.target.value)}
rows={5}
className="mt-1 resize-none"
/>
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setReponseDialogOpen(false)}>
Annuler
</Button>
<Button
onClick={() => {
if (!reponseText.trim()) {
toast.error("Veuillez rédiger une réponse");
return;
}
reponseMutation.mutate({
id: selectedIdea!.id,
reponseAdmin: reponseText.trim(),
statut: reponseStatut,
});
}}
disabled={reponseMutation.isPending}
className="bg-[#0a2463] hover:bg-[#0a2463]/90 text-white gap-2"
>
<Send className="h-4 w-4" />
{reponseMutation.isPending ? "Envoi..." : "Enregistrer la réponse"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,834 @@
import { useState } from "react";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogDescription,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
Rss,
Plus,
Pencil,
Trash2,
CheckCircle2,
XCircle,
Clock,
AlertCircle,
Settings2,
Zap,
Globe,
ChevronDown,
ChevronUp,
Save,
} from "lucide-react";
import { useLocalAuth } from "@/contexts/LocalAuthContext";
import { cn } from "@/lib/utils";
// ─── Types ────────────────────────────────────────────────────────────────────
type FeedType = "veille" | "aap";
type TypeVeille = "reglementaire" | "concurrentielle" | "technologique" | "generale";
type CategorieAap = "Handicap" | "PA" | "Enfance" | "Précarité" | "Sanitaire" | "Autre";
interface AutoRule {
keyword: string;
value: string;
}
interface RssFeed {
id: number;
url: string;
name: string;
feedType: FeedType;
defaultTypeVeille: TypeVeille | null;
defaultCategorieAap: CategorieAap | null;
autoRules: AutoRule[] | null;
isActive: boolean;
lastFetchedAt: Date | null;
lastFetchStatus: "ok" | "error" | "pending" | null;
lastFetchError: string | null;
}
// ─── Constantes ───────────────────────────────────────────────────────────────
const TYPE_VEILLE_LABELS: Record<TypeVeille, string> = {
reglementaire: "Réglementaire",
concurrentielle: "Concurrentielle",
technologique: "Technologique",
generale: "Générale",
};
const CATEGORIE_AAP_OPTIONS: CategorieAap[] = ["Handicap", "PA", "Enfance", "Précarité", "Sanitaire", "Autre"];
const TYPE_VEILLE_OPTIONS: TypeVeille[] = ["reglementaire", "concurrentielle", "technologique", "generale"];
const INTERVAL_OPTIONS = [
{ value: 30, label: "30 minutes" },
{ value: 60, label: "1 heure" },
{ value: 120, label: "2 heures" },
{ value: 360, label: "6 heures" },
{ value: 720, label: "12 heures" },
{ value: 1440, label: "24 heures" },
];
// ─── Formulaire de flux ───────────────────────────────────────────────────────
interface FeedFormData {
url: string;
name: string;
feedType: FeedType;
defaultTypeVeille: TypeVeille | "";
defaultCategorieAap: CategorieAap | "";
autoRules: AutoRule[];
isActive: boolean;
}
const EMPTY_FORM: FeedFormData = {
url: "",
name: "",
feedType: "veille",
defaultTypeVeille: "reglementaire",
defaultCategorieAap: "",
autoRules: [],
isActive: true,
};
function FeedFormDialog({
open,
onClose,
feed,
onSaved,
}: {
open: boolean;
onClose: () => void;
feed: RssFeed | null;
onSaved: () => void;
}) {
const isEdit = !!feed;
const [form, setForm] = useState<FeedFormData>(() =>
feed
? {
url: feed.url,
name: feed.name,
feedType: feed.feedType,
defaultTypeVeille: feed.defaultTypeVeille ?? "",
defaultCategorieAap: feed.defaultCategorieAap ?? "",
autoRules: feed.autoRules ?? [],
isActive: feed.isActive,
}
: { ...EMPTY_FORM }
);
const [newRuleKeyword, setNewRuleKeyword] = useState("");
const [newRuleValue, setNewRuleValue] = useState("");
const createMutation = trpc.rss.create.useMutation({
onSuccess: () => {
toast.success("Flux RSS ajouté");
onSaved();
onClose();
},
onError: (e) => toast.error("Erreur", { description: e.message }),
});
const updateMutation = trpc.rss.update.useMutation({
onSuccess: () => {
toast.success("Flux RSS mis à jour");
onSaved();
onClose();
},
onError: (e) => toast.error("Erreur", { description: e.message }),
});
const isPending = createMutation.isPending || updateMutation.isPending;
const handleSubmit = () => {
if (!form.url || !form.name) {
toast.error("URL et nom sont requis");
return;
}
const payload = {
url: form.url,
name: form.name,
feedType: form.feedType,
defaultTypeVeille: form.feedType === "veille" && form.defaultTypeVeille ? form.defaultTypeVeille : undefined,
defaultCategorieAap: form.feedType === "aap" && form.defaultCategorieAap ? (form.defaultCategorieAap as CategorieAap) : undefined,
autoRules: form.autoRules.length > 0 ? form.autoRules : undefined,
isActive: form.isActive,
};
if (isEdit && feed) {
updateMutation.mutate({ id: feed.id, ...payload });
} else {
createMutation.mutate(payload);
}
};
const addRule = () => {
if (!newRuleKeyword.trim() || !newRuleValue.trim()) return;
setForm((f) => ({
...f,
autoRules: [...f.autoRules, { keyword: newRuleKeyword.trim(), value: newRuleValue.trim() }],
}));
setNewRuleKeyword("");
setNewRuleValue("");
};
const removeRule = (idx: number) => {
setForm((f) => ({ ...f, autoRules: f.autoRules.filter((_, i) => i !== idx) }));
};
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Rss className="h-5 w-5 text-primary" />
{isEdit ? "Modifier le flux RSS" : "Ajouter un flux RSS"}
</DialogTitle>
<DialogDescription>
Configurez l'URL, le type de contenu et les règles d'automatisme pour ce flux.
</DialogDescription>
</DialogHeader>
<div className="space-y-5 py-2">
{/* URL */}
<div className="space-y-1.5">
<Label htmlFor="feed-url" className="flex items-center gap-1.5">
<Globe className="h-3.5 w-3.5" /> URL du flux RSS
</Label>
<Input
id="feed-url"
placeholder="https://www.legifrance.gouv.fr/rss/..."
value={form.url}
onChange={(e) => setForm((f) => ({ ...f, url: e.target.value }))}
/>
</div>
{/* Nom */}
<div className="space-y-1.5">
<Label htmlFor="feed-name">Nom descriptif</Label>
<Input
id="feed-name"
placeholder="ex : Légifrance — Textes réglementaires"
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
/>
</div>
{/* Type de flux */}
<div className="space-y-1.5">
<Label>Type de contenu</Label>
<div className="grid grid-cols-2 gap-3">
{(["veille", "aap"] as FeedType[]).map((type) => (
<button
key={type}
type="button"
onClick={() => setForm((f) => ({ ...f, feedType: type, defaultTypeVeille: type === "veille" ? "reglementaire" : "", defaultCategorieAap: type === "aap" ? "Handicap" : "" }))}
className={cn(
"flex items-center gap-3 p-3 rounded-lg border-2 text-left transition-all",
form.feedType === type
? "border-primary bg-primary/5 text-primary"
: "border-border hover:border-primary/40"
)}
>
<div className={cn("w-8 h-8 rounded-lg flex items-center justify-center", form.feedType === type ? "bg-primary text-primary-foreground" : "bg-muted")}>
{type === "veille" ? <Rss className="h-4 w-4" /> : <Zap className="h-4 w-4" />}
</div>
<div>
<p className="font-medium text-sm">{type === "veille" ? "Veille Stratégique" : "Appels à Projets"}</p>
<p className="text-xs text-muted-foreground">{type === "veille" ? "Réglementaire, concurrentielle…" : "Handicap, PA, Enfance…"}</p>
</div>
</button>
))}
</div>
</div>
{/* Valeur par défaut selon le type */}
{form.feedType === "veille" && (
<div className="space-y-1.5">
<Label>Type de veille par défaut</Label>
<Select
value={form.defaultTypeVeille}
onValueChange={(v) => setForm((f) => ({ ...f, defaultTypeVeille: v as TypeVeille }))}
>
<SelectTrigger>
<SelectValue placeholder="Choisir un type de veille" />
</SelectTrigger>
<SelectContent>
{TYPE_VEILLE_OPTIONS.map((t) => (
<SelectItem key={t} value={t}>{TYPE_VEILLE_LABELS[t]}</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{form.feedType === "aap" && (
<div className="space-y-1.5">
<Label>Catégorie AAP par défaut</Label>
<Select
value={form.defaultCategorieAap}
onValueChange={(v) => setForm((f) => ({ ...f, defaultCategorieAap: v as CategorieAap }))}
>
<SelectTrigger>
<SelectValue placeholder="Choisir une catégorie" />
</SelectTrigger>
<SelectContent>
{CATEGORIE_AAP_OPTIONS.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<Separator />
{/* Règles d'automatisme */}
<div className="space-y-3">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4 text-amber-500" />
<Label className="text-sm font-semibold">Règles d'automatisme</Label>
</div>
<p className="text-xs text-muted-foreground">
Si le titre ou le résumé d'un article contient le mot-clé, la {form.feedType === "veille" ? "catégorie de veille" : "catégorie AAP"} sera automatiquement assignée.
</p>
{/* Règles existantes */}
{form.autoRules.length > 0 && (
<div className="space-y-2">
{form.autoRules.map((rule, idx) => (
<div key={idx} className="flex items-center gap-2 p-2 bg-muted/50 rounded-lg border">
<Badge variant="outline" className="font-mono text-xs shrink-0">{rule.keyword}</Badge>
<span className="text-xs text-muted-foreground"></span>
<Badge className="text-xs shrink-0">{rule.value}</Badge>
<button
type="button"
onClick={() => removeRule(idx)}
className="ml-auto text-destructive hover:text-destructive/80 transition-colors"
>
<XCircle className="h-4 w-4" />
</button>
</div>
))}
</div>
)}
{/* Ajouter une règle */}
<div className="flex gap-2 items-end">
<div className="flex-1 space-y-1">
<Label className="text-xs text-muted-foreground">Mot-clé</Label>
<Input
placeholder="ex : SERAFIN"
value={newRuleKeyword}
onChange={(e) => setNewRuleKeyword(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && addRule()}
className="h-8 text-sm"
/>
</div>
<span className="text-muted-foreground mb-2"></span>
<div className="flex-1 space-y-1">
<Label className="text-xs text-muted-foreground">
{form.feedType === "veille" ? "Type de veille" : "Catégorie AAP"}
</Label>
{form.feedType === "veille" ? (
<Select value={newRuleValue} onValueChange={setNewRuleValue}>
<SelectTrigger className="h-8 text-sm">
<SelectValue placeholder="Choisir…" />
</SelectTrigger>
<SelectContent>
{TYPE_VEILLE_OPTIONS.map((t) => (
<SelectItem key={t} value={t}>{TYPE_VEILLE_LABELS[t]}</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Select value={newRuleValue} onValueChange={setNewRuleValue}>
<SelectTrigger className="h-8 text-sm">
<SelectValue placeholder="Choisir…" />
</SelectTrigger>
<SelectContent>
{CATEGORIE_AAP_OPTIONS.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
<Button type="button" size="sm" variant="outline" onClick={addRule} className="h-8 mb-0">
<Plus className="h-3.5 w-3.5" />
</Button>
</div>
</div>
<Separator />
{/* Actif */}
<div className="flex items-center justify-between">
<div>
<Label className="font-medium">Flux actif</Label>
<p className="text-xs text-muted-foreground mt-0.5">Désactivez pour suspendre la lecture sans supprimer le flux</p>
</div>
<Switch
checked={form.isActive}
onCheckedChange={(v) => setForm((f) => ({ ...f, isActive: v }))}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={isPending}>Annuler</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending ? "Enregistrement…" : isEdit ? "Mettre à jour" : "Ajouter le flux"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// ─── Carte d'un flux ──────────────────────────────────────────────────────────
function FeedCard({
feed,
isAdmin,
onEdit,
onDelete,
onToggle,
}: {
feed: RssFeed;
isAdmin: boolean;
onEdit: () => void;
onDelete: () => void;
onToggle: (active: boolean) => void;
}) {
const [rulesOpen, setRulesOpen] = useState(false);
const rules = feed.autoRules ?? [];
const statusIcon = () => {
if (feed.lastFetchStatus === "ok") return <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />;
if (feed.lastFetchStatus === "error") return <XCircle className="h-3.5 w-3.5 text-destructive" />;
return <Clock className="h-3.5 w-3.5 text-muted-foreground" />;
};
const statusLabel = () => {
if (feed.lastFetchStatus === "ok" && feed.lastFetchedAt) {
return `Dernière lecture : ${new Date(feed.lastFetchedAt).toLocaleString("fr-FR")}`;
}
if (feed.lastFetchStatus === "error") return `Erreur : ${feed.lastFetchError ?? "inconnue"}`;
return "Jamais lu";
};
return (
<div className={cn(
"border rounded-xl p-4 transition-all",
feed.isActive ? "bg-card border-border" : "bg-muted/30 border-dashed border-muted-foreground/30 opacity-60"
)}>
<div className="flex items-start gap-3">
{/* Icône type */}
<div className={cn(
"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5",
feed.feedType === "veille" ? "bg-blue-100 text-blue-600" : "bg-amber-100 text-amber-600"
)}>
{feed.feedType === "veille" ? <Rss className="h-5 w-5" /> : <Zap className="h-5 w-5" />}
</div>
{/* Infos */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold text-sm truncate">{feed.name}</span>
<Badge variant={feed.feedType === "veille" ? "secondary" : "outline"} className="text-xs shrink-0">
{feed.feedType === "veille" ? "Veille" : "AAP"}
</Badge>
{feed.feedType === "veille" && feed.defaultTypeVeille && (
<Badge variant="outline" className="text-xs shrink-0 border-blue-200 text-blue-700 bg-blue-50">
{TYPE_VEILLE_LABELS[feed.defaultTypeVeille]}
</Badge>
)}
{feed.feedType === "aap" && feed.defaultCategorieAap && (
<Badge variant="outline" className="text-xs shrink-0 border-amber-200 text-amber-700 bg-amber-50">
{feed.defaultCategorieAap}
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-1 truncate font-mono">{feed.url}</p>
<div className="flex items-center gap-1.5 mt-1.5">
{statusIcon()}
<span className="text-xs text-muted-foreground">{statusLabel()}</span>
</div>
{/* Règles d'automatisme */}
{rules.length > 0 && (
<div className="mt-2">
<button
type="button"
onClick={() => setRulesOpen(!rulesOpen)}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<Zap className="h-3 w-3 text-amber-500" />
{rules.length} règle{rules.length > 1 ? "s" : ""} d'automatisme
{rulesOpen ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
{rulesOpen && (
<div className="mt-1.5 flex flex-wrap gap-1.5">
{rules.map((rule, i) => (
<span key={i} className="inline-flex items-center gap-1 text-xs bg-muted px-2 py-0.5 rounded-full border">
<span className="font-mono text-primary">{rule.keyword}</span>
<span className="text-muted-foreground">→</span>
<span>{rule.value}</span>
</span>
))}
</div>
)}
</div>
)}
</div>
{/* Actions */}
{isAdmin && (
<div className="flex items-center gap-2 flex-shrink-0">
<Switch
checked={feed.isActive}
onCheckedChange={onToggle}
className="scale-90"
/>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onEdit} title="Modifier">
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={onDelete} title="Supprimer">
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
)}
</div>
</div>
);
}
// ─── Panneau de configuration ─────────────────────────────────────────────────
function SettingsPanel({ isAdmin }: { isAdmin: boolean }) {
const { data: settings, refetch } = trpc.rss.getSettings.useQuery();
const saveMutation = trpc.rss.saveSettings.useMutation({
onSuccess: () => {
toast.success("Paramètres RSS sauvegardés");
refetch();
},
onError: (e) => toast.error("Erreur", { description: e.message }),
});
const [fetchMode, setFetchMode] = useState<"interval" | "scheduled">(settings?.fetchMode ?? "scheduled");
const [fetchIntervalMinutes, setFetchIntervalMinutes] = useState(settings?.fetchIntervalMinutes ?? 360);
const [scheduledTime, setScheduledTime] = useState(settings?.scheduledTime ?? "06:00");
const [autoFetchEnabled, setAutoFetchEnabled] = useState(settings?.autoFetchEnabled ?? true);
// Sync state when settings load
if (settings && settings.fetchMode !== fetchMode && !saveMutation.isPending) {
setFetchMode(settings.fetchMode);
setFetchIntervalMinutes(settings.fetchIntervalMinutes);
setScheduledTime(settings.scheduledTime ?? "06:00");
setAutoFetchEnabled(settings.autoFetchEnabled);
}
const handleSave = () => {
saveMutation.mutate({
fetchMode,
fetchIntervalMinutes,
scheduledTime,
autoFetchEnabled,
});
};
return (
<Card className="border-2 border-dashed border-primary/20">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<Settings2 className="h-4 w-4 text-primary" />
Paramètres de lecture automatique
</CardTitle>
<CardDescription>
Configurez la fréquence et le mode de lecture des flux RSS.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{/* Activation */}
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div>
<p className="font-medium text-sm">Lecture automatique</p>
<p className="text-xs text-muted-foreground">Active la récupération périodique des flux</p>
</div>
<Switch
checked={autoFetchEnabled}
onCheckedChange={setAutoFetchEnabled}
disabled={!isAdmin}
/>
</div>
{/* Mode */}
<div className="space-y-2">
<Label className="text-sm font-medium">Mode de planification</Label>
<div className="grid grid-cols-2 gap-3">
{(["scheduled", "interval"] as const).map((mode) => (
<button
key={mode}
type="button"
disabled={!isAdmin}
onClick={() => setFetchMode(mode)}
className={cn(
"flex items-center gap-2 p-3 rounded-lg border-2 text-left transition-all text-sm",
fetchMode === mode ? "border-primary bg-primary/5" : "border-border hover:border-primary/40",
!isAdmin && "opacity-50 cursor-not-allowed"
)}
>
<Clock className={cn("h-4 w-4", fetchMode === mode ? "text-primary" : "text-muted-foreground")} />
<div>
<p className="font-medium">{mode === "scheduled" ? "Heure fixe" : "Intervalle"}</p>
<p className="text-xs text-muted-foreground">{mode === "scheduled" ? "Chaque jour à une heure précise" : "Toutes les N minutes"}</p>
</div>
</button>
))}
</div>
</div>
{/* Paramètre selon le mode */}
{fetchMode === "scheduled" ? (
<div className="space-y-1.5">
<Label className="text-sm">Heure de lecture quotidienne</Label>
<Input
type="time"
value={scheduledTime}
onChange={(e) => setScheduledTime(e.target.value)}
disabled={!isAdmin}
className="w-36"
/>
</div>
) : (
<div className="space-y-1.5">
<Label className="text-sm">Intervalle de lecture</Label>
<Select
value={String(fetchIntervalMinutes)}
onValueChange={(v) => setFetchIntervalMinutes(Number(v))}
disabled={!isAdmin}
>
<SelectTrigger className="w-48">
<SelectValue />
</SelectTrigger>
<SelectContent>
{INTERVAL_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={String(opt.value)}>{opt.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{isAdmin && (
<Button onClick={handleSave} disabled={saveMutation.isPending} size="sm" className="gap-2">
<Save className="h-3.5 w-3.5" />
{saveMutation.isPending ? "Enregistrement…" : "Sauvegarder les paramètres"}
</Button>
)}
</CardContent>
</Card>
);
}
// ─── Page principale ──────────────────────────────────────────────────────────
export default function RssFeeds() {
const { user } = useLocalAuth();
const isAdmin = user?.role === "admin";
const { data: feeds = [], refetch, isLoading } = trpc.rss.list.useQuery();
const [dialogOpen, setDialogOpen] = useState(false);
const [editFeed, setEditFeed] = useState<RssFeed | null>(null);
const [deleteId, setDeleteId] = useState<number | null>(null);
const [filterType, setFilterType] = useState<"all" | "veille" | "aap">("all");
const toggleMutation = trpc.rss.toggleActive.useMutation({
onSuccess: () => refetch(),
onError: (e) => toast.error("Erreur", { description: e.message }),
});
const deleteMutation = trpc.rss.delete.useMutation({
onSuccess: () => {
toast.success("Flux supprimé");
setDeleteId(null);
refetch();
},
onError: (e) => toast.error("Erreur", { description: e.message }),
});
const filteredFeeds = feeds.filter((f) => filterType === "all" || f.feedType === filterType);
const veilleCount = feeds.filter((f) => f.feedType === "veille").length;
const aapCount = feeds.filter((f) => f.feedType === "aap").length;
const activeCount = feeds.filter((f) => f.isActive).length;
return (
<div className="p-6 max-w-5xl mx-auto space-y-6">
{/* En-tête */}
<div className="flex items-start justify-between gap-4 flex-wrap">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Rss className="h-6 w-6 text-primary" />
Flux RSS
</h1>
<p className="text-muted-foreground text-sm mt-1">
Gérez les sources RSS qui alimentent automatiquement la veille réglementaire et les appels à projets.
</p>
</div>
{isAdmin && (
<Button onClick={() => { setEditFeed(null); setDialogOpen(true); }} className="gap-2 shrink-0">
<Plus className="h-4 w-4" />
Ajouter un flux
</Button>
)}
</div>
{/* Statistiques */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
{[
{ label: "Total", value: feeds.length, color: "text-foreground" },
{ label: "Actifs", value: activeCount, color: "text-green-600" },
{ label: "Veille", value: veilleCount, color: "text-blue-600" },
{ label: "AAP", value: aapCount, color: "text-amber-600" },
].map((stat) => (
<div key={stat.label} className="bg-card border rounded-xl p-3 text-center">
<p className={cn("text-2xl font-bold", stat.color)}>{stat.value}</p>
<p className="text-xs text-muted-foreground mt-0.5">{stat.label}</p>
</div>
))}
</div>
{/* Filtres */}
<div className="flex gap-2 flex-wrap">
{(["all", "veille", "aap"] as const).map((type) => (
<Button
key={type}
variant={filterType === type ? "default" : "outline"}
size="sm"
onClick={() => setFilterType(type)}
className="gap-1.5"
>
{type === "all" ? "Tous" : type === "veille" ? <><Rss className="h-3.5 w-3.5" /> Veille</> : <><Zap className="h-3.5 w-3.5" /> AAP</>}
<Badge variant="secondary" className="ml-1 text-xs px-1.5">
{type === "all" ? feeds.length : type === "veille" ? veilleCount : aapCount}
</Badge>
</Button>
))}
</div>
{/* Liste des flux */}
<div className="space-y-3">
{isLoading ? (
<div className="text-center py-12 text-muted-foreground">
<Rss className="h-8 w-8 mx-auto mb-2 animate-pulse" />
<p className="text-sm">Chargement des flux…</p>
</div>
) : filteredFeeds.length === 0 ? (
<div className="text-center py-12 border-2 border-dashed rounded-xl">
<Rss className="h-10 w-10 mx-auto mb-3 text-muted-foreground/40" />
<p className="font-medium text-muted-foreground">Aucun flux RSS configuré</p>
{isAdmin && (
<Button variant="outline" size="sm" className="mt-3 gap-2" onClick={() => { setEditFeed(null); setDialogOpen(true); }}>
<Plus className="h-3.5 w-3.5" />
Ajouter votre premier flux
</Button>
)}
</div>
) : (
filteredFeeds.map((feed) => (
<FeedCard
key={feed.id}
feed={feed as RssFeed}
isAdmin={isAdmin}
onEdit={() => { setEditFeed(feed as RssFeed); setDialogOpen(true); }}
onDelete={() => setDeleteId(feed.id)}
onToggle={(active) => toggleMutation.mutate({ id: feed.id, isActive: active })}
/>
))
)}
</div>
{/* Paramètres de lecture */}
<SettingsPanel isAdmin={isAdmin} />
{/* Informations sur les automatismes */}
<Card className="bg-blue-50/50 border-blue-200">
<CardContent className="pt-4 pb-4">
<div className="flex gap-3">
<AlertCircle className="h-5 w-5 text-blue-500 shrink-0 mt-0.5" />
<div className="space-y-1">
<p className="text-sm font-medium text-blue-800">Comment fonctionnent les règles d'automatisme ?</p>
<p className="text-xs text-blue-700">
Lors de la lecture d'un flux, chaque article est analysé. Si son titre ou son résumé contient un mot-clé défini dans les règles, la catégorie ou le type de veille correspondant lui est automatiquement assigné. Si aucune règle ne correspond, la valeur par défaut du flux est utilisée.
</p>
</div>
</div>
</CardContent>
</Card>
{/* Dialog ajout/édition */}
<FeedFormDialog
open={dialogOpen}
onClose={() => { setDialogOpen(false); setEditFeed(null); }}
feed={editFeed}
onSaved={() => refetch()}
/>
{/* Confirmation suppression */}
<AlertDialog open={deleteId !== null} onOpenChange={(o) => !o && setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Supprimer ce flux RSS ?</AlertDialogTitle>
<AlertDialogDescription>
Cette action est irréversible. Le flux sera définitivement supprimé mais les entrées déjà importées seront conservées.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Annuler</AlertDialogCancel>
<AlertDialogAction
onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Supprimer
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -4,7 +4,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
@@ -26,7 +26,6 @@ import {
Eye,
CheckCircle,
XCircle,
AtSign,
} from "lucide-react";
import { toast } from "sonner";
import { format } from "date-fns";
@@ -38,8 +37,7 @@ type Role = "admin" | "user" | "readonly";
interface LocalUser {
id: number;
name: string;
username: string | null;
email: string | null;
email: string;
role: Role;
isActive: boolean;
createdAt: Date;
@@ -66,21 +64,13 @@ const ROLE_ICONS: Record<Role, React.ReactNode> = {
interface UserFormData {
name: string;
username: string;
email: string;
password: string;
role: Role;
isActive: boolean;
}
const DEFAULT_FORM: UserFormData = {
name: "",
username: "",
email: "",
password: "",
role: "user",
isActive: true,
};
const DEFAULT_FORM: UserFormData = { name: "", email: "", password: "", role: "user", isActive: true };
export default function UsersAdmin() {
const [showDialog, setShowDialog] = useState(false);
@@ -128,14 +118,7 @@ export default function UsersAdmin() {
const openEdit = (user: LocalUser) => {
setEditingUser(user);
setForm({
name: user.name,
username: user.username ?? "",
email: user.email ?? "",
password: "",
role: user.role,
isActive: user.isActive,
});
setForm({ name: user.name, email: user.email, password: "", role: user.role, isActive: user.isActive });
setShowDialog(true);
};
@@ -144,21 +127,14 @@ export default function UsersAdmin() {
const data: Parameters<typeof updateMutation.mutate>[0] = {
id: editingUser.id,
name: form.name,
username: form.username || undefined,
email: form.email || undefined,
email: form.email,
role: form.role,
isActive: form.isActive,
};
if (form.password) data.password = form.password;
updateMutation.mutate(data);
} else {
createMutation.mutate({
name: form.name,
username: form.username || undefined,
email: form.email || undefined,
password: form.password,
role: form.role,
});
createMutation.mutate({ name: form.name, email: form.email, password: form.password, role: form.role });
}
};
@@ -173,9 +149,7 @@ export default function UsersAdmin() {
<Users size={22} className="text-primary" />
<h1 className="text-2xl font-bold text-foreground">Gestion des utilisateurs</h1>
</div>
<p className="text-muted-foreground text-sm">
{users.length} utilisateur{users.length !== 1 ? "s" : ""} enregistré{users.length !== 1 ? "s" : ""}
</p>
<p className="text-muted-foreground text-sm">{users.length} utilisateur{users.length !== 1 ? "s" : ""} enregistré{users.length !== 1 ? "s" : ""}</p>
</div>
<Button onClick={openCreate} className="gap-2">
<Plus size={15} />
@@ -201,7 +175,7 @@ export default function UsersAdmin() {
<thead>
<tr className="border-b border-border bg-muted/30">
<th className="text-left px-4 py-3 font-semibold text-muted-foreground">Nom</th>
<th className="text-left px-4 py-3 font-semibold text-muted-foreground">Identifiant / Email</th>
<th className="text-left px-4 py-3 font-semibold text-muted-foreground">Email</th>
<th className="text-left px-4 py-3 font-semibold text-muted-foreground w-36">Rôle</th>
<th className="text-left px-4 py-3 font-semibold text-muted-foreground w-24">Statut</th>
<th className="text-left px-4 py-3 font-semibold text-muted-foreground w-32">Dernière connexion</th>
@@ -219,25 +193,7 @@ export default function UsersAdmin() {
<span className="font-medium text-foreground">{user.name}</span>
</div>
</td>
<td className="px-4 py-3">
<div className="flex flex-col gap-0.5">
{user.username && (
<span className="inline-flex items-center gap-1 text-xs font-mono bg-violet-50 text-violet-700 border border-violet-200 rounded px-1.5 py-0.5 w-fit">
<User size={10} />
{user.username}
</span>
)}
{user.email && (
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<AtSign size={10} />
{user.email}
</span>
)}
{!user.username && !user.email && (
<span className="text-xs text-muted-foreground italic"></span>
)}
</div>
</td>
<td className="px-4 py-3 text-muted-foreground">{user.email}</td>
<td className="px-4 py-3">
<Badge variant="outline" className={cn("text-xs gap-1", ROLE_COLORS[user.role])}>
{ROLE_ICONS[user.role]}
@@ -262,20 +218,10 @@ export default function UsersAdmin() {
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="w-7 h-7 text-muted-foreground hover:text-foreground"
onClick={() => openEdit(user)}
>
<Button variant="ghost" size="icon" className="w-7 h-7 text-muted-foreground hover:text-foreground" onClick={() => openEdit(user)}>
<Pencil size={13} />
</Button>
<Button
variant="ghost"
size="icon"
className="w-7 h-7 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteId(user.id)}
>
<Button variant="ghost" size="icon" className="w-7 h-7 text-muted-foreground hover:text-destructive" onClick={() => setDeleteId(user.id)}>
<Trash2 size={13} />
</Button>
</div>
@@ -295,65 +241,23 @@ export default function UsersAdmin() {
<DialogHeader>
<DialogTitle>{editingUser ? "Modifier l'utilisateur" : "Nouvel utilisateur"}</DialogTitle>
<DialogDescription>
{editingUser
? "Modifiez les informations de l'utilisateur"
: "Créez un nouveau compte. L'identifiant ou l'e-mail servira à la connexion."}
{editingUser ? "Modifiez les informations de l'utilisateur" : "Créez un nouveau compte utilisateur"}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="grid grid-cols-2 gap-4">
{/* Nom complet */}
<div className="space-y-2 col-span-2">
<Label>Nom complet <span className="text-destructive">*</span></Label>
<Input
placeholder="Jean Dupont"
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
/>
<Label>Nom complet</Label>
<Input placeholder="Jean Dupont" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} />
</div>
{/* Identifiant */}
<div className="space-y-2 col-span-2">
<Label>
Identifiant (username)
<span className="ml-1 text-xs text-muted-foreground">(optionnel)</span>
</Label>
<Input
placeholder="jean.dupont"
value={form.username}
onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
/>
<p className="text-xs text-muted-foreground">
Permet la connexion sans e-mail. Ex : <code>adminItinova</code>
</p>
<Label>Adresse e-mail</Label>
<Input type="email" placeholder="jean@itinova.fr" value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} />
</div>
{/* Email */}
<div className="space-y-2 col-span-2">
<Label>
Adresse e-mail
<span className="ml-1 text-xs text-muted-foreground">(optionnel)</span>
</Label>
<Input
type="email"
placeholder="jean@itinova.fr"
value={form.email}
onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
/>
<Label>{editingUser ? "Nouveau mot de passe (laisser vide pour ne pas changer)" : "Mot de passe"}</Label>
<Input type="password" placeholder="••••••••" value={form.password} onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))} />
</div>
{/* Mot de passe */}
<div className="space-y-2 col-span-2">
<Label>
{editingUser
? "Nouveau mot de passe (laisser vide pour ne pas changer)"
: <>Mot de passe <span className="text-destructive">*</span></>}
</Label>
<Input
type="password"
placeholder="••••••••"
value={form.password}
onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
/>
</div>
{/* Rôle */}
<div className="space-y-2">
<Label>Rôle</Label>
<Select value={form.role} onValueChange={(v) => setForm((f) => ({ ...f, role: v as Role }))}>
@@ -367,15 +271,11 @@ export default function UsersAdmin() {
</SelectContent>
</Select>
</div>
{/* Statut (modification uniquement) */}
{editingUser && (
<div className="space-y-2">
<Label>Statut</Label>
<div className="flex items-center gap-2 pt-2">
<Switch
checked={form.isActive}
onCheckedChange={(v) => setForm((f) => ({ ...f, isActive: v }))}
/>
<Switch checked={form.isActive} onCheckedChange={(v) => setForm((f) => ({ ...f, isActive: v }))} />
<span className="text-sm">{form.isActive ? "Actif" : "Inactif"}</span>
</div>
</div>
@@ -383,16 +283,9 @@ export default function UsersAdmin() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowDialog(false)}>
Annuler
</Button>
<Button
onClick={handleSubmit}
disabled={createMutation.isPending || updateMutation.isPending}
>
{(createMutation.isPending || updateMutation.isPending) && (
<Loader2 size={14} className="animate-spin mr-2" />
)}
<Button variant="outline" onClick={() => setShowDialog(false)}>Annuler</Button>
<Button onClick={handleSubmit} disabled={createMutation.isPending || updateMutation.isPending}>
{(createMutation.isPending || updateMutation.isPending) && <Loader2 size={14} className="animate-spin mr-2" />}
{editingUser ? "Enregistrer" : "Créer"}
</Button>
</DialogFooter>
@@ -404,19 +297,11 @@ export default function UsersAdmin() {
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Supprimer l'utilisateur</DialogTitle>
<DialogDescription>
Cette action est irréversible. L'utilisateur ne pourra plus se connecter.
</DialogDescription>
<DialogDescription>Cette action est irréversible. L'utilisateur ne pourra plus se connecter.</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteId(null)}>
Annuler
</Button>
<Button
variant="destructive"
onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
disabled={deleteMutation.isPending}
>
<Button variant="outline" onClick={() => setDeleteId(null)}>Annuler</Button>
<Button variant="destructive" onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })} disabled={deleteMutation.isPending}>
{deleteMutation.isPending && <Loader2 size={14} className="animate-spin mr-2" />}
Supprimer
</Button>

View File

@@ -135,3 +135,50 @@ export const ideas = mysqlTable("ideas", {
export type Idea = typeof ideas.$inferSelect;
export type InsertIdea = typeof ideas.$inferInsert;
// ─── Flux RSS ────────────────────────────────────────────────────────────────────────────────────
export const rssFeeds = mysqlTable("rss_feeds", {
id: int("id").autoincrement().primaryKey(),
// URL du flux RSS
url: text("url").notNull(),
// Nom descriptif du flux
name: varchar("name", { length: 255 }).notNull(),
// Type de contenu alimenté par ce flux
feedType: mysqlEnum("feedType", ["veille", "aap"]).notNull(),
// Pour les flux de type veille : type de veille par défaut
defaultTypeVeille: mysqlEnum("defaultTypeVeille", ["reglementaire", "concurrentielle", "technologique", "generale"]),
// Pour les flux de type aap : catégorie par défaut
defaultCategorieAap: mysqlEnum("defaultCategorieAap", ["Handicap", "PA", "Enfance", "Précarité", "Sanitaire", "Autre"]),
// Règles d'automatisme JSON : [{keyword, typeVeille|categorieAap}]
autoRules: json("autoRules"),
// Actif ou non
isActive: boolean("isActive").default(true).notNull(),
// Dernière lecture réussie
lastFetchedAt: timestamp("lastFetchedAt"),
// Dernier statut de lecture
lastFetchStatus: mysqlEnum("lastFetchStatus", ["ok", "error", "pending"]).default("pending"),
lastFetchError: text("lastFetchError"),
createdAt: timestamp("createdAt").defaultNow().notNull(),
updatedAt: timestamp("updatedAt").defaultNow().onUpdateNow().notNull(),
});
export type RssFeed = typeof rssFeeds.$inferSelect;
export type InsertRssFeed = typeof rssFeeds.$inferInsert;
// Paramètres globaux RSS (fréquence de lecture, etc.)
export const rssSettings = mysqlTable("rss_settings", {
id: int("id").autoincrement().primaryKey(),
// Fréquence de lecture en minutes (ex: 60, 360, 1440)
fetchIntervalMinutes: int("fetchIntervalMinutes").default(360).notNull(),
// Heure de lecture automatique (format HH:MM, si mode planifié)
scheduledTime: varchar("scheduledTime", { length: 5 }).default("06:00"),
// Mode : interval (toutes les N minutes) ou scheduled (heure fixe)
fetchMode: mysqlEnum("fetchMode", ["interval", "scheduled"]).default("scheduled").notNull(),
// Activer/désactiver la lecture automatique
autoFetchEnabled: boolean("autoFetchEnabled").default(true).notNull(),
updatedAt: timestamp("updatedAt").defaultNow().onUpdateNow().notNull(),
});
export type RssSettings = typeof rssSettings.$inferSelect;
export type InsertRssSettings = typeof rssSettings.$inferInsert;

View File

@@ -11,6 +11,12 @@ import {
InsertLocalUser,
ideas,
InsertIdea,
rssFeeds,
rssSettings,
type InsertRssFeed,
type InsertRssSettings,
type RssFeed,
type RssSettings,
} from "../drizzle/schema";
import { ENV } from "./_core/env";
@@ -360,3 +366,70 @@ export async function updateIdeaStatut(id: number, statut: "ouvert" | "en_cours"
if (!db) throw new Error("Database not available");
await db.update(ideas).set({ statut }).where(eq(ideas.id, id));
}
// ─── Flux RSS ────────────────────────────────────────────────────────────────────────────────────
export async function getRssFeeds(): Promise<RssFeed[]> {
const db = await getDb();
if (!db) return [];
return db.select().from(rssFeeds).orderBy(rssFeeds.name);
}
export async function getRssFeedById(id: number): Promise<RssFeed | null> {
const db = await getDb();
if (!db) return null;
const rows = await db.select().from(rssFeeds).where(eq(rssFeeds.id, id)).limit(1);
return rows[0] ?? null;
}
export async function createRssFeed(data: Omit<InsertRssFeed, "id" | "createdAt" | "updatedAt">): Promise<number> {
const db = await getDb();
if (!db) throw new Error("Database not available");
const result = await db.insert(rssFeeds).values(data);
return (result[0] as any).insertId as number;
}
export async function updateRssFeed(id: number, data: Partial<Omit<InsertRssFeed, "id" | "createdAt" | "updatedAt">>): Promise<void> {
const db = await getDb();
if (!db) throw new Error("Database not available");
await db.update(rssFeeds).set(data).where(eq(rssFeeds.id, id));
}
export async function deleteRssFeed(id: number): Promise<void> {
const db = await getDb();
if (!db) throw new Error("Database not available");
await db.delete(rssFeeds).where(eq(rssFeeds.id, id));
}
export async function getRssSettings(): Promise<RssSettings | null> {
const db = await getDb();
if (!db) return null;
const rows = await db.select().from(rssSettings).limit(1);
if (rows.length > 0) return rows[0];
// Créer les paramètres par défaut si inexistants
await db.insert(rssSettings).values({
fetchIntervalMinutes: 360,
scheduledTime: "06:00",
fetchMode: "scheduled",
autoFetchEnabled: true,
});
const newRows = await db.select().from(rssSettings).limit(1);
return newRows[0] ?? null;
}
export async function saveRssSettings(data: Partial<Omit<InsertRssSettings, "id" | "updatedAt">>): Promise<void> {
const db = await getDb();
if (!db) throw new Error("Database not available");
const existing = await db.select().from(rssSettings).limit(1);
if (existing.length > 0) {
await db.update(rssSettings).set(data).where(eq(rssSettings.id, existing[0].id));
} else {
await db.insert(rssSettings).values({
fetchIntervalMinutes: 360,
scheduledTime: "06:00",
fetchMode: "scheduled",
autoFetchEnabled: true,
...data,
});
}
}

View File

@@ -22,6 +22,13 @@ import {
getIdeasByUser,
repondreIdea,
updateIdeaStatut,
getRssFeeds,
getRssFeedById,
createRssFeed,
updateRssFeed,
deleteRssFeed,
getRssSettings,
saveRssSettings,
} from "./db";
import { importVeille, importAAP, runFullImport, getImportConfig } from "./importer";
import { loginLocalUser, hashPassword, ensureAdminExists } from "./localAuth";
@@ -50,9 +57,9 @@ export const appRouter = router({
}),
// Connexion locale
localLogin: publicProcedure
.input(z.object({ email: z.string().min(1), password: z.string().min(1) }))
.input(z.object({ identifier: z.string().min(1), password: z.string().min(1) }))
.mutation(async ({ input, ctx }) => {
const result = await loginLocalUser(input.email, input.password);
const result = await loginLocalUser(input.identifier, input.password);
// Stocker le token dans un cookie
const cookieOptions = getSessionCookieOptions(ctx.req);
ctx.res.cookie("veille_local_auth", result.token, {
@@ -307,6 +314,94 @@ export const appRouter = router({
return { success: true };
}),
}),
});
// ─── Flux RSS ───────────────────────────────────────────────────────────────────────────────────
rss: router({
// Lister tous les flux
list: protectedProcedure.query(async () => {
return getRssFeeds();
}),
// Créer un flux
create: adminProcedure
.input(z.object({
url: z.string().url("URL invalide"),
name: z.string().min(1, "Nom requis").max(255),
feedType: z.enum(["veille", "aap"]),
defaultTypeVeille: z.enum(["reglementaire", "concurrentielle", "technologique", "generale"]).optional(),
defaultCategorieAap: z.enum(["Handicap", "PA", "Enfance", "Précarité", "Sanitaire", "Autre"]).optional(),
autoRules: z.array(z.object({
keyword: z.string(),
value: z.string(),
})).optional(),
isActive: z.boolean().optional().default(true),
}))
.mutation(async ({ input }) => {
const id = await createRssFeed({
url: input.url,
name: input.name,
feedType: input.feedType,
defaultTypeVeille: input.defaultTypeVeille ?? null,
defaultCategorieAap: input.defaultCategorieAap ?? null,
autoRules: input.autoRules ?? null,
isActive: input.isActive ?? true,
});
return { id };
}),
// Modifier un flux
update: adminProcedure
.input(z.object({
id: z.number().int().positive(),
url: z.string().url("URL invalide").optional(),
name: z.string().min(1).max(255).optional(),
feedType: z.enum(["veille", "aap"]).optional(),
defaultTypeVeille: z.enum(["reglementaire", "concurrentielle", "technologique", "generale"]).nullable().optional(),
defaultCategorieAap: z.enum(["Handicap", "PA", "Enfance", "Précarité", "Sanitaire", "Autre"]).nullable().optional(),
autoRules: z.array(z.object({
keyword: z.string(),
value: z.string(),
})).nullable().optional(),
isActive: z.boolean().optional(),
}))
.mutation(async ({ input }) => {
const { id, ...data } = input;
await updateRssFeed(id, data);
return { success: true };
}),
// Supprimer un flux
delete: adminProcedure
.input(z.object({ id: z.number().int().positive() }))
.mutation(async ({ input }) => {
await deleteRssFeed(input.id);
return { success: true };
}),
// Activer / désactiver un flux
toggleActive: adminProcedure
.input(z.object({ id: z.number().int().positive(), isActive: z.boolean() }))
.mutation(async ({ input }) => {
await updateRssFeed(input.id, { isActive: input.isActive });
return { success: true };
}),
// Lire les paramètres globaux RSS
getSettings: protectedProcedure.query(async () => {
return getRssSettings();
}),
// Sauvegarder les paramètres globaux RSS
saveSettings: adminProcedure
.input(z.object({
fetchIntervalMinutes: z.number().int().min(5).max(10080).optional(),
scheduledTime: z.string().regex(/^\d{2}:\d{2}$/, "Format HH:MM requis").optional(),
fetchMode: z.enum(["interval", "scheduled"]).optional(),
autoFetchEnabled: z.boolean().optional(),
}))
.mutation(async ({ input }) => {
await saveRssSettings(input);
return { success: true };
}),
}),
});
export type AppRouter = typeof appRouter;

28
vite.config.ts.bak Normal file
View File

@@ -0,0 +1,28 @@
import { jsxLocPlugin } from "@builder.io/vite-plugin-jsx-loc";
import react from "@vitejs/plugin-react";
import path from "path";
import { defineConfig } from "vite";
import { webDevPreviewerPlugin } from "vite-plugin-web-dev-previewer";
export default defineConfig({
plugins: [react(), jsxLocPlugin(), webDevPreviewerPlugin()],
resolve: {
alias: {
"@": path.resolve(import.meta.dirname, "client", "src"),
"@shared": path.resolve(import.meta.dirname, "shared"),
"@assets": path.resolve(import.meta.dirname, "attached_assets"),
},
},
envDir: path.resolve(import.meta.dirname),
root: path.resolve(import.meta.dirname, "client"),
build: {
outDir: path.resolve(import.meta.dirname, "dist/public"),
emptyOutDir: true,
},
server: {
fs: {
strict: true,
deny: ["**/.*"],
},
},
});