Add configuration interface for enterprise task webhook

Implement a new UI component and backend routes for configuring and testing enterprise task webhooks, including database schema and migration scripts.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: cfbfe47c-0c9a-4ebf-8a41-2937407eccff
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/1957c339-2757-4d1f-8e92-e9f71a1ce58e/cfbfe47c-0c9a-4ebf-8a41-2937407eccff/vzUkIk6
This commit is contained in:
michaelschal committed 2025-09-03 13:15:50 +00:00
1 parent 6ce9ec90a4
commit f938fdb95d
9 files changed
+582 -7

No files matched your search

+1 -1
View File
@@ -37,4 +37,4 @@ args = "npm run dev"
waitForPort = 5000
[agent]
integrations = ["javascript_object_storage==1.0.0", "javascript_log_in_with_replit==1.0.0", "javascript_database==1.0.0"]
integrations = ["javascript_object_storage==1.0.0", "javascript_database==1.0.0", "javascript_log_in_with_replit==1.0.0"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

+20 -3
View File
@@ -6,7 +6,8 @@ import {
Database,
Server,
Bug,
Cloud
Cloud,
Send
} from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -17,6 +18,7 @@ import BackupManager from "./BackupManager";
import NocoDBConfig from "./NocoDBConfig";
import DatabaseDebug from "./DatabaseDebug";
import WeatherSettings from "./WeatherSettings";
import WebhookBAPConfig from "./WebhookBAPConfig";
export default function Utilities() {
const { user } = useAuthUnified();
@@ -35,9 +37,10 @@ export default function Utilities() {
const canManageNocoDB = user?.role === 'admin';
const canDebugDatabase = user?.role === 'admin';
const canManageWeather = user?.role === 'admin';
const canManageWebhookBAP = user?.role === 'admin';
// Si l'utilisateur n'a aucune permission, afficher le message d'accès refusé
if (!canManageBackups && !canManageNocoDB && !canDebugDatabase && !canManageWeather) {
if (!canManageBackups && !canManageNocoDB && !canDebugDatabase && !canManageWeather && !canManageWebhookBAP) {
return (
<div className="flex-1 flex items-center justify-center">
<Card className="w-96">
@@ -73,7 +76,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-4 mb-6">
<TabsList className="grid w-full grid-cols-5 mb-6">
{canManageBackups && (
<TabsTrigger value="backups" className="flex items-center gap-2">
<Database className="w-4 h-4" />
@@ -98,6 +101,12 @@ export default function Utilities() {
Météo
</TabsTrigger>
)}
{canManageWebhookBAP && (
<TabsTrigger value="webhookbap" className="flex items-center gap-2">
<Send className="w-4 h-4" />
Configuration BAP
</TabsTrigger>
)}
</TabsList>
{/* Contenu des onglets */}
@@ -132,6 +141,14 @@ export default function Utilities() {
</div>
</TabsContent>
)}
{canManageWebhookBAP && (
<TabsContent value="webhookbap" className="flex-1 overflow-hidden">
<div className="h-full bg-gray-50 -m-6 p-6">
<WebhookBAPConfig />
</div>
</TabsContent>
)}
</Tabs>
</div>
</div>
+289
View File
@@ -0,0 +1,289 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Send, Globe, AlertCircle, CheckCircle2, Copy } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
interface WebhookBapConfig {
id: number;
name: string;
webhookUrl: string;
description: string | null;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
export default function WebhookBAPConfig() {
const { toast } = useToast();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
name: "Configuration BAP",
webhookUrl: "",
description: "",
isActive: true
});
const { data: config, isLoading } = useQuery({
queryKey: ['/api/webhook-bap-config'],
});
const testMutation = useMutation({
mutationFn: async () => {
if (!formData.webhookUrl) {
throw new Error("URL webhook requise pour le test");
}
const response = await fetch('/api/webhook-bap-config/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ webhookUrl: formData.webhookUrl }),
credentials: 'include'
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Erreur lors du test');
}
return response.json();
},
onSuccess: () => {
toast({
title: "Test réussi",
description: "Le webhook BAP répond correctement",
});
},
onError: (error: any) => {
toast({
title: "Échec du test",
description: error.message,
variant: "destructive",
});
},
});
const saveMutation = useMutation({
mutationFn: async (data: typeof formData) => {
return apiRequest('/api/webhook-bap-config', 'POST', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/webhook-bap-config'] });
toast({
title: "Configuration sauvegardée",
description: "La configuration du webhook BAP a été mise à jour",
});
},
onError: (error: any) => {
toast({
title: "Erreur de sauvegarde",
description: error.message,
variant: "destructive",
});
},
});
useEffect(() => {
if (config) {
// Gérer à la fois les cas où l'API retourne un objet ou un array
const configData = Array.isArray(config) && config.length > 0 ? config[0] : config;
if (configData && typeof configData === 'object') {
setFormData({
name: configData.name || "Configuration BAP",
webhookUrl: configData.webhookUrl || "",
description: configData.description || "",
isActive: configData.isActive ?? true
});
}
}
}, [config]);
const handleSave = () => {
if (!formData.webhookUrl.trim()) {
toast({
title: "Erreur",
description: "L'URL du webhook est requise",
variant: "destructive",
});
return;
}
if (!formData.webhookUrl.startsWith('http')) {
toast({
title: "Erreur",
description: "L'URL doit commencer par http:// ou https://",
variant: "destructive",
});
return;
}
saveMutation.mutate(formData);
};
const handleTest = () => {
if (!formData.webhookUrl.trim()) {
toast({
title: "Erreur",
description: "L'URL du webhook est requise pour effectuer le test",
variant: "destructive",
});
return;
}
testMutation.mutate();
};
const copyUrl = () => {
navigator.clipboard.writeText(formData.webhookUrl);
toast({
title: "URL copiée",
description: "L'URL a été copiée dans le presse-papiers",
});
};
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<div className="text-gray-500">Chargement de la configuration...</div>
</div>
);
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Send className="w-5 h-5 text-blue-600" />
Configuration Webhook BAP
</CardTitle>
<CardDescription>
Configurez l'URL du webhook n8n pour l'envoi des fichiers BAP vers Prissela et Célia
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-2">
<Label htmlFor="name">Nom de la configuration</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Configuration BAP"
/>
</div>
<div className="space-y-2">
<Label htmlFor="webhookUrl">URL du Webhook n8n *</Label>
<div className="flex gap-2">
<Input
id="webhookUrl"
value={formData.webhookUrl}
onChange={(e) => setFormData({ ...formData, webhookUrl: e.target.value })}
placeholder="https://workflow.ffnancy.fr/webhook/..."
className="flex-1"
/>
<Button variant="outline" size="icon" onClick={copyUrl} disabled={!formData.webhookUrl}>
<Copy className="w-4 h-4" />
</Button>
</div>
<p className="text-xs text-gray-500">
URL complète du webhook n8n qui recevra les fichiers PDF BAP
</p>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Description optionnelle de cette configuration..."
className="h-20"
/>
</div>
<div className="flex items-center space-x-2">
<Switch
id="isActive"
checked={formData.isActive}
onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
/>
<Label htmlFor="isActive">Configuration active</Label>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Globe className="w-5 h-5 text-green-600" />
Test de Connexion
</CardTitle>
<CardDescription>
Testez la connectivité avec le webhook n8n configuré
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4">
<Button
onClick={handleTest}
disabled={testMutation.isPending || !formData.webhookUrl}
className="flex items-center gap-2"
>
{testMutation.isPending ? (
<>
<div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
Test en cours...
</>
) : (
<>
<Send className="w-4 h-4" />
Tester le Webhook
</>
)}
</Button>
{testMutation.isSuccess && (
<div className="flex items-center gap-2 text-green-600">
<CheckCircle2 className="w-4 h-4" />
<span className="text-sm">Connexion réussie</span>
</div>
)}
{testMutation.isError && (
<div className="flex items-center gap-2 text-red-600">
<AlertCircle className="w-4 h-4" />
<span className="text-sm">Échec de la connexion</span>
</div>
)}
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-4">
<Button
onClick={handleSave}
disabled={saveMutation.isPending}
className="flex items-center gap-2"
>
{saveMutation.isPending ? (
<>
<div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
Sauvegarde...
</>
) : (
<>
<CheckCircle2 className="w-4 h-4" />
Sauvegarder
</>
)}
</Button>
</div>
</div>
);
}
+22 -1
View File
@@ -380,10 +380,31 @@ CREATE INDEX "idx_sav_ticket_history_ticket_id" ON "sav_ticket_history" USING bt
CREATE INDEX "idx_weather_data_date_year" ON "weather_data" USING btree ("date" text_ops, "is_current_year" bool_ops);
CREATE INDEX "idx_invoice_verification_expires" ON "invoice_verification_cache" USING btree ("expires_at" timestamp_ops);
-- Table pour configuration webhook BAP
CREATE TABLE IF NOT EXISTS "webhook_bap_config" (
"id" serial PRIMARY KEY NOT NULL,
"name" varchar(100) DEFAULT 'Configuration BAP' NOT NULL,
"webhook_url" text NOT NULL,
"description" text,
"is_active" boolean DEFAULT true NOT NULL,
"created_at" timestamp DEFAULT now(),
"updated_at" timestamp DEFAULT now()
);
-- Configuration par défaut webhook BAP
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 l''envoi des fichiers BAP vers n8n',
true
) ON CONFLICT DO NOTHING;
-- Commentaires sur les tables
COMMENT ON TABLE "announcements" IS 'Admin-managed announcements/information system';
COMMENT ON COLUMN "announcements"."priority" IS 'Priority level: normal, important, urgent';
COMMENT ON COLUMN "announcements"."group_id" IS 'NULL for global announcements, specific group_id for store-specific announcements';
COMMENT ON TABLE "sav_tickets" IS 'Service après-vente tickets management';
COMMENT ON TABLE "weather_data" IS 'Cache for weather API data';
COMMENT ON TABLE "invoice_verification_cache" IS 'Cache for NocoDB invoice verification results';
COMMENT ON TABLE "invoice_verification_cache" IS 'Cache for NocoDB invoice verification results';
COMMENT ON TABLE "webhook_bap_config" IS 'Configuration pour webhook BAP n8n';
+24
View File
@@ -0,0 +1,24 @@
-- Script pour créer la table webhook_bap_config en production
-- À exécuter sur le serveur de production PostgreSQL
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 une 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 l''envoi des fichiers BAP',
true
) ON CONFLICT DO NOTHING;
-- Commande pour exécuter ce script :
-- psql -U username -d database_name -f scripts/create-webhook-bap-table.sql
+141 -2
View File
@@ -68,6 +68,139 @@ export async function registerRoutes(app: Express): Promise<Server> {
// Auth middleware
await setupAuth(app);
// Routes pour configuration webhook BAP
app.get('/api/webhook-bap-config', 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 config = await storage.getWebhookBapConfig();
res.json(config || null);
} catch (error: any) {
console.error('❌ Erreur récupération config webhook BAP:', error);
res.status(500).json({ error: 'Erreur serveur', details: error.message });
}
});
app.post('/api/webhook-bap-config', 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' });
}
// Valider les données avec Zod
const validatedData = insertWebhookBapConfigSchema.parse(req.body);
// Vérifier si une configuration existe déjà
const existingConfig = await storage.getWebhookBapConfig();
let config: any;
if (existingConfig) {
// Mettre à jour la configuration existante
config = await storage.updateWebhookBapConfig(existingConfig.id, validatedData);
} else {
// Créer une nouvelle configuration
config = await storage.createWebhookBapConfig(validatedData);
}
console.log('✅ Configuration webhook BAP sauvegardée:', {
id: config.id,
name: config.name,
isActive: config.isActive
});
res.json(config);
} catch (error: any) {
console.error('❌ Erreur sauvegarde config webhook BAP:', error);
res.status(500).json({ error: 'Erreur serveur', details: error.message });
}
});
app.post('/api/webhook-bap-config/test', 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 { webhookUrl } = req.body;
if (!webhookUrl) {
return res.status(400).json({ error: 'URL webhook requise' });
}
console.log('🔍 Test webhook BAP:', { url: webhookUrl });
// Tester la connectivité avec le webhook
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 secondes
const testResponse = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
test: true,
timestamp: new Date().toISOString(),
message: 'Test de connectivité depuis LogiFlow'
}),
signal: controller.signal
});
clearTimeout(timeoutId);
console.log('🌐 Réponse test webhook:', { status: testResponse.status, ok: testResponse.ok });
if (!testResponse.ok) {
throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`);
}
const result = await testResponse.text();
res.json({
success: true,
status: testResponse.status,
message: 'Webhook accessible',
response: result.substring(0, 200) // Limiter la réponse
});
} catch (error: any) {
console.error('❌ Erreur test webhook BAP:', error);
let errorMessage = 'Échec du test de connectivité';
if (error.name === 'AbortError') {
errorMessage = 'Timeout - Le webhook ne répond pas';
} else if (error.message) {
errorMessage = error.message;
}
res.status(500).json({ error: errorMessage, details: error.message });
}
});
// Route BAP pour envoi webhook n8n
app.post('/api/bap/send-webhook', isAuthenticated, async (req: any, res) => {
try {
@@ -143,8 +276,14 @@ export async function registerRoutes(app: Express): Promise<Server> {
fileSize: fileBuffer.length
});
// Envoyer vers le webhook n8n
const webhookUrl = 'https://workflow.ffnancy.fr/webhook/a3d03176-b72f-412d-8fb9-f920b9fbab4d';
// Récupérer l'URL du webhook depuis la configuration
const webhookConfig = await storage.getWebhookBapConfig();
if (!webhookConfig || !webhookConfig.isActive) {
console.error('❌ BAP: Configuration webhook non trouvée ou inactive');
return res.status(500).json({ error: 'Configuration webhook BAP non disponible' });
}
const webhookUrl = webhookConfig.webhookUrl;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 secondes
+63
View File
@@ -66,6 +66,9 @@ import {
type InsertWeatherData,
type WeatherSettings,
type InsertWeatherSettings,
webhookBapConfig,
type WebhookBapConfig,
type InsertWebhookBapConfig,
} from "@shared/schema";
import { db } from "./db";
import { eq, and, inArray, desc, sql, gte, lte, lt, gt, or, isNull, isNotNull, asc, ne } from "drizzle-orm";
@@ -219,6 +222,11 @@ export interface IStorage {
updateWeatherData(id: number, data: Partial<InsertWeatherData>): Promise<WeatherData>;
deleteOldWeatherData(daysToKeep: number): Promise<void>;
clearWeatherCache(): Promise<void>;
// Webhook BAP Configuration
getWebhookBapConfig(): Promise<WebhookBapConfig | undefined>;
createWebhookBapConfig(config: InsertWebhookBapConfig): Promise<WebhookBapConfig>;
updateWebhookBapConfig(id: number, config: Partial<InsertWebhookBapConfig>): Promise<WebhookBapConfig>;
}
export class DatabaseStorage implements IStorage {
@@ -2211,6 +2219,29 @@ export class DatabaseStorage implements IStorage {
await db.delete(weatherData);
console.log('🧹 Weather cache cleared due to location change');
}
// Webhook BAP Configuration
async getWebhookBapConfig(): Promise<WebhookBapConfig | undefined> {
const [config] = await db.select().from(webhookBapConfig).limit(1);
return config;
}
async createWebhookBapConfig(configData: InsertWebhookBapConfig): Promise<WebhookBapConfig> {
const [config] = await db
.insert(webhookBapConfig)
.values(configData)
.returning();
return config;
}
async updateWebhookBapConfig(id: number, configData: Partial<InsertWebhookBapConfig>): Promise<WebhookBapConfig> {
const [config] = await db
.update(webhookBapConfig)
.set({ ...configData, updatedAt: new Date() })
.where(eq(webhookBapConfig.id, id))
.returning();
return config;
}
}
// MemStorage class for development
@@ -3859,6 +3890,38 @@ export class MemStorage implements IStorage {
console.log('🧹 DEV: Weather cache cleared due to location change');
}
// Webhook BAP Configuration
async getWebhookBapConfig(): Promise<WebhookBapConfig | undefined> {
// En développement, retourner une config par défaut
return {
id: 1,
name: "Configuration BAP",
webhookUrl: "https://workflow.ffnancy.fr/webhook/a3d03176-b72f-412d-8fb9-f920b9fbab4d",
description: "Configuration par défaut pour développement",
isActive: true,
createdAt: new Date(),
updatedAt: new Date()
};
}
async createWebhookBapConfig(config: InsertWebhookBapConfig): Promise<WebhookBapConfig> {
return {
id: 1,
...config,
createdAt: new Date(),
updatedAt: new Date()
};
}
async updateWebhookBapConfig(id: number, config: Partial<InsertWebhookBapConfig>): Promise<WebhookBapConfig> {
const existing = await this.getWebhookBapConfig();
return {
...existing!,
...config,
updatedAt: new Date()
};
}
// Announcement operations
async createAnnouncement(announcementData: InsertAnnouncement): Promise<Announcement> {
const announcementStorage = getAnnouncementStorage(
+22
View File
@@ -802,3 +802,25 @@ export type WeatherData = typeof weatherData.$inferSelect;
export type InsertWeatherData = z.infer<typeof insertWeatherDataSchema>;
export type WeatherSettings = typeof weatherSettings.$inferSelect;
export type InsertWeatherSettings = z.infer<typeof insertWeatherSettingsSchema>;
// Configuration Webhook BAP
export const webhookBapConfig = pgTable("webhook_bap_config", {
id: serial("id").primaryKey(),
name: varchar("name", { length: 100 }).notNull().default("Configuration BAP"),
webhookUrl: text("webhook_url").notNull(),
description: text("description"),
isActive: boolean("is_active").notNull().default(true),
createdAt: timestamp("created_at").defaultNow(),
updatedAt: timestamp("updated_at").defaultNow(),
});
// Webhook BAP Schemas
export const insertWebhookBapConfigSchema = createInsertSchema(webhookBapConfig).omit({
id: true,
createdAt: true,
updatedAt: true,
});
// Webhook BAP Types
export type WebhookBapConfig = typeof webhookBapConfig.$inferSelect;
export type InsertWebhookBapConfig = z.infer<typeof insertWebhookBapConfigSchema>;