mirror of
https://github.com/R0m1k3/LogiFlow.git
synced 2026-10-11 17:27:31 +02:00
Merge pull request #345 from R0m1k3/1.1
Add SQL execution tool for administrators to manage database tables
This commit is contained in:
6 files changed
+324
-101
No files matched your search
@@ -37,4 +37,4 @@ args = "npm run dev"
|
||||
waitForPort = 5000
|
||||
|
||||
[agent]
|
||||
integrations = ["javascript_database==1.0.0", "javascript_object_storage==1.0.0", "javascript_log_in_with_replit==1.0.0"]
|
||||
integrations = ["javascript_log_in_with_replit==1.0.0", "javascript_database==1.0.0", "javascript_object_storage==1.0.0"]
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Upload, Play, Copy, AlertTriangle, Database } from "lucide-react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { apiRequest } from "@/lib/queryClient";
|
||||
|
||||
export default function SQLExecutor() {
|
||||
const { toast } = useToast();
|
||||
const [sqlContent, setSqlContent] = useState("");
|
||||
const [logs, setLogs] = useState<string[]>([]);
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const executeMutation = useMutation({
|
||||
mutationFn: async (sql: string) => {
|
||||
setLogs([]);
|
||||
setIsExecuting(true);
|
||||
|
||||
const response = await fetch('/api/admin/execute-sql', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sql }),
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || 'Erreur lors de l\'exécution SQL');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
setLogs(prev => [...prev, '✅ Exécution SQL terminée avec succès']);
|
||||
if (result.logs) {
|
||||
setLogs(prev => [...prev, ...result.logs]);
|
||||
}
|
||||
if (result.results) {
|
||||
setLogs(prev => [...prev, `📊 Résultats: ${JSON.stringify(result.results, null, 2)}`]);
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Succès",
|
||||
description: "SQL exécuté avec succès",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
setLogs(prev => [...prev, `❌ Erreur: ${error.message}`]);
|
||||
|
||||
toast({
|
||||
title: "Erreur",
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
});
|
||||
|
||||
const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
if (!file.name.endsWith('.sql')) {
|
||||
toast({
|
||||
title: "Erreur",
|
||||
description: "Veuillez sélectionner un fichier .sql",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
const content = e.target?.result as string;
|
||||
setSqlContent(content);
|
||||
setLogs([`📁 Fichier ${file.name} chargé (${content.length} caractères)`]);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleExecuteSQL = () => {
|
||||
if (!sqlContent.trim()) {
|
||||
toast({
|
||||
title: "Erreur",
|
||||
description: "Veuillez saisir du SQL à exécuter",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLogs([`🔄 Début de l'exécution SQL...`]);
|
||||
executeMutation.mutate(sqlContent);
|
||||
};
|
||||
|
||||
const handleCopyWebhookSQL = () => {
|
||||
const webhookSQL = `-- Script pour créer la table webhook_bap_config
|
||||
CREATE TABLE IF NOT EXISTS webhook_bap_config (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL DEFAULT 'Configuration BAP',
|
||||
webhook_url TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Insérer la configuration par défaut
|
||||
INSERT INTO webhook_bap_config (name, webhook_url, description, is_active)
|
||||
SELECT
|
||||
'Configuration BAP',
|
||||
'https://workflow.ffnancy.fr/webhook/a3d03176-b72f-412d-8fb9-f920b9fbab4d',
|
||||
'Configuration par défaut pour envoi des fichiers BAP vers n8n',
|
||||
true
|
||||
WHERE NOT EXISTS (SELECT 1 FROM webhook_bap_config);
|
||||
|
||||
-- Commentaire sur la table
|
||||
COMMENT ON TABLE webhook_bap_config IS 'Configuration pour webhook BAP n8n';
|
||||
|
||||
-- Vérification finale
|
||||
SELECT 'Table webhook_bap_config créée!' AS message;
|
||||
SELECT COUNT(*) AS nb_configs FROM webhook_bap_config;`;
|
||||
|
||||
setSqlContent(webhookSQL);
|
||||
navigator.clipboard.writeText(webhookSQL);
|
||||
|
||||
toast({
|
||||
title: "SQL copié",
|
||||
description: "Le script webhook BAP a été copié et collé",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="h-6 w-6 text-blue-600" />
|
||||
<h1 className="text-2xl font-bold">Exécution SQL</h1>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-orange-500" />
|
||||
Avertissement de Sécurité
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Cette fonctionnalité permet d'exécuter du SQL directement sur la base de données.
|
||||
Utilisez-la avec précaution et uniquement pour des opérations de maintenance.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Script SQL</CardTitle>
|
||||
<CardDescription>
|
||||
Collez votre SQL ou uploadez un fichier .sql
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Upload className="h-4 w-4" />
|
||||
Charger fichier SQL
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCopyWebhookSQL}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
SQL Webhook BAP
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".sql"
|
||||
onChange={handleFileUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
placeholder="-- Collez votre SQL ici ou utilisez le bouton pour charger un fichier..."
|
||||
value={sqlContent}
|
||||
onChange={(e) => setSqlContent(e.target.value)}
|
||||
className="min-h-[300px] font-mono text-sm"
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={handleExecuteSQL}
|
||||
disabled={!sqlContent.trim() || isExecuting}
|
||||
className="w-full flex items-center gap-2"
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
{isExecuting ? 'Exécution en cours...' : 'Exécuter SQL'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Logs d'exécution</CardTitle>
|
||||
<CardDescription>
|
||||
Résultats et messages de l'exécution SQL
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="bg-black text-green-400 p-4 rounded-md min-h-[300px] font-mono text-sm overflow-auto">
|
||||
{logs.length === 0 ? (
|
||||
<div className="text-gray-500">Aucun log pour l'instant...</div>
|
||||
) : (
|
||||
logs.map((log, index) => (
|
||||
<div key={index} className="mb-1">
|
||||
{log}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
Server,
|
||||
Bug,
|
||||
Cloud,
|
||||
Send
|
||||
Send,
|
||||
Code
|
||||
} from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
@@ -19,6 +20,7 @@ import NocoDBConfig from "./NocoDBConfig";
|
||||
import DatabaseDebug from "./DatabaseDebug";
|
||||
import WeatherSettings from "./WeatherSettings";
|
||||
import WebhookBAPConfig from "./WebhookBAPConfig";
|
||||
import SQLExecutor from "./SQLExecutor";
|
||||
|
||||
export default function Utilities() {
|
||||
const { user } = useAuthUnified();
|
||||
@@ -38,9 +40,10 @@ export default function Utilities() {
|
||||
const canDebugDatabase = user?.role === 'admin';
|
||||
const canManageWeather = user?.role === 'admin';
|
||||
const canManageWebhookBAP = user?.role === 'admin';
|
||||
const canExecuteSQL = user?.role === 'admin';
|
||||
|
||||
// Si l'utilisateur n'a aucune permission, afficher le message d'accès refusé
|
||||
if (!canManageBackups && !canManageNocoDB && !canDebugDatabase && !canManageWeather && !canManageWebhookBAP) {
|
||||
if (!canManageBackups && !canManageNocoDB && !canDebugDatabase && !canManageWeather && !canManageWebhookBAP && !canExecuteSQL) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Card className="w-96">
|
||||
@@ -76,7 +79,7 @@ export default function Utilities() {
|
||||
{/* Content avec onglets */}
|
||||
<div className="flex-1 p-6 overflow-hidden">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
|
||||
<TabsList className="grid w-full grid-cols-5 mb-6">
|
||||
<TabsList className="grid w-full grid-cols-6 mb-6">
|
||||
{canManageBackups && (
|
||||
<TabsTrigger value="backups" className="flex items-center gap-2">
|
||||
<Database className="w-4 h-4" />
|
||||
@@ -107,6 +110,12 @@ export default function Utilities() {
|
||||
Configuration BAP
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{canExecuteSQL && (
|
||||
<TabsTrigger value="sql" className="flex items-center gap-2">
|
||||
<Code className="w-4 h-4" />
|
||||
Exécution SQL
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
|
||||
{/* Contenu des onglets */}
|
||||
@@ -149,6 +158,14 @@ export default function Utilities() {
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{canExecuteSQL && (
|
||||
<TabsContent value="sql" className="flex-1 overflow-hidden">
|
||||
<div className="h-full bg-gray-50 -m-6 p-6">
|
||||
<SQLExecutor />
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
-- Script SQL DEFINITIF à exécuter manuellement sur votre base PostgreSQL de production
|
||||
-- Usage: psql -U postgres -d votre_base -f fix-webhook-bap-FINAL.sql
|
||||
|
||||
-- Vérifier si la table existe déjà
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_schema='public' AND table_name='webhook_bap_config') THEN
|
||||
RAISE NOTICE 'Création de la table webhook_bap_config...';
|
||||
|
||||
CREATE TABLE webhook_bap_config (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL DEFAULT 'Configuration BAP',
|
||||
webhook_url TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Insérer la configuration par défaut
|
||||
INSERT INTO webhook_bap_config (name, webhook_url, description, is_active)
|
||||
VALUES (
|
||||
'Configuration BAP',
|
||||
'https://workflow.ffnancy.fr/webhook/a3d03176-b72f-412d-8fb9-f920b9fbab4d',
|
||||
'Configuration par défaut pour envoi des fichiers BAP vers n8n',
|
||||
true
|
||||
);
|
||||
|
||||
-- Commentaire sur la table
|
||||
COMMENT ON TABLE webhook_bap_config IS 'Configuration pour webhook BAP n8n';
|
||||
|
||||
RAISE NOTICE 'Table webhook_bap_config créée avec succès!';
|
||||
ELSE
|
||||
RAISE NOTICE 'Table webhook_bap_config existe déjà.';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Vérification finale
|
||||
SELECT 'Vérification: Table webhook_bap_config' AS check_table;
|
||||
SELECT COUNT(*) AS nb_configs FROM webhook_bap_config;
|
||||
SELECT * FROM webhook_bap_config;
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Script de secours pour créer la table webhook_bap_config manuellement
|
||||
|
||||
set -e
|
||||
|
||||
echo "🔧 [MANUAL-FIX] Création manuelle de la table webhook_bap_config..."
|
||||
|
||||
# Vérifier la connection
|
||||
if ! psql "$DATABASE_URL" -c "SELECT 1;" > /dev/null 2>&1; then
|
||||
echo "❌ [MANUAL-FIX] Impossible de se connecter à la base de données"
|
||||
echo "🔍 [MANUAL-FIX] DATABASE_URL: ${DATABASE_URL:0:50}..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ [MANUAL-FIX] Connexion à la base de données réussie"
|
||||
|
||||
# Créer la table
|
||||
echo "🔧 [MANUAL-FIX] Création de la table webhook_bap_config..."
|
||||
psql "$DATABASE_URL" << 'EOF'
|
||||
-- Création sécurisée de la table
|
||||
CREATE TABLE IF NOT EXISTS webhook_bap_config (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL DEFAULT 'Configuration BAP',
|
||||
webhook_url TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Insérer la configuration par défaut si pas présente
|
||||
INSERT INTO webhook_bap_config (name, webhook_url, description, is_active)
|
||||
SELECT
|
||||
'Configuration BAP',
|
||||
'https://workflow.ffnancy.fr/webhook/a3d03176-b72f-412d-8fb9-f920b9fbab4d',
|
||||
'Configuration par défaut pour envoi des fichiers BAP vers n8n',
|
||||
true
|
||||
WHERE NOT EXISTS (SELECT 1 FROM webhook_bap_config);
|
||||
|
||||
-- Commentaire
|
||||
COMMENT ON TABLE webhook_bap_config IS 'Configuration pour webhook BAP n8n';
|
||||
EOF
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ [MANUAL-FIX] Table webhook_bap_config créée avec succès!"
|
||||
|
||||
# Vérification
|
||||
echo "🔍 [MANUAL-FIX] Vérification finale..."
|
||||
psql "$DATABASE_URL" -c "SELECT COUNT(*) as nb_configs FROM webhook_bap_config;"
|
||||
psql "$DATABASE_URL" -c "SELECT * FROM webhook_bap_config;"
|
||||
else
|
||||
echo "❌ [MANUAL-FIX] Échec de la création de la table"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🎉 [MANUAL-FIX] Terminé avec succès!"
|
||||
@@ -4157,6 +4157,73 @@ RÉSUMÉ DU SCAN
|
||||
}
|
||||
});
|
||||
|
||||
// API d'exécution SQL pour admin uniquement
|
||||
app.post('/api/admin/execute-sql', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
// Vérifier que l'utilisateur est admin
|
||||
const userId = req.user?.claims?.sub || req.user?.id;
|
||||
if (!userId) {
|
||||
return res.status(401).json({ error: 'Utilisateur non authentifié' });
|
||||
}
|
||||
|
||||
const user = await storage.getUser(userId);
|
||||
if (!user || user.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Accès refusé - Admin uniquement' });
|
||||
}
|
||||
|
||||
const { sql: sqlQuery } = req.body;
|
||||
|
||||
if (!sqlQuery || typeof sqlQuery !== 'string') {
|
||||
return res.status(400).json({ error: 'SQL query requis' });
|
||||
}
|
||||
|
||||
console.log('🔧 [SQL-EXECUTOR] Début exécution SQL pour admin:', userId);
|
||||
console.log('🔧 [SQL-EXECUTOR] Query:', sqlQuery.substring(0, 200) + '...');
|
||||
|
||||
const logs = [`🔄 Exécution SQL démarrée...`];
|
||||
|
||||
try {
|
||||
// Utilisation de drizzle-orm pour l'exécution
|
||||
const { sql } = await import('drizzle-orm');
|
||||
const result = await db.execute(sql.raw(sqlQuery));
|
||||
|
||||
logs.push(`✅ SQL exécuté avec succès`);
|
||||
logs.push(`📊 Nombre de lignes affectées: ${result.rowCount || 0}`);
|
||||
|
||||
if (result.rows && result.rows.length > 0) {
|
||||
logs.push(`📋 Nombre de lignes retournées: ${result.rows.length}`);
|
||||
if (result.rows.length <= 10) {
|
||||
logs.push(`📋 Résultats: ${JSON.stringify(result.rows, null, 2)}`);
|
||||
} else {
|
||||
logs.push(`📋 Échantillon (10 premières lignes): ${JSON.stringify(result.rows.slice(0, 10), null, 2)}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ [SQL-EXECUTOR] Exécution réussie');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
logs,
|
||||
results: result.rows,
|
||||
rowCount: result.rowCount
|
||||
});
|
||||
|
||||
} catch (sqlError: any) {
|
||||
console.error('❌ [SQL-EXECUTOR] Erreur SQL:', sqlError);
|
||||
logs.push(`❌ Erreur SQL: ${sqlError.message}`);
|
||||
|
||||
return res.status(500).json({
|
||||
error: `Erreur SQL: ${sqlError.message}`,
|
||||
logs
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('❌ [SQL-EXECUTOR] Erreur générale:', error);
|
||||
res.status(500).json({ error: 'Erreur serveur', details: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Create server instance
|
||||
const httpServer = createServer(app);
|
||||
|
||||
|
||||
Reference in new issue
Block a user