'use client'; import React, { useState, useRef, useEffect } from 'react'; import { useAuth } from '../../../../contexts/AuthContext'; import ProtectedRoute from '../../../../components/auth/ProtectedRoute'; import { Card } from 'primereact/card'; import { Button } from 'primereact/button'; import { InputText } from 'primereact/inputtext'; import { InputTextarea } from 'primereact/inputtextarea'; import { InputNumber } from 'primereact/inputnumber'; import { InputSwitch } from 'primereact/inputswitch'; import { Dropdown } from 'primereact/dropdown'; import { Toast } from 'primereact/toast'; import { TabView, TabPanel } from 'primereact/tabview'; import { FileUpload } from 'primereact/fileupload'; import { Divider } from 'primereact/divider'; import { ColorPicker } from 'primereact/colorpicker'; import { SelectButton } from 'primereact/selectbutton'; import { Calendar } from 'primereact/calendar'; import { Chip } from 'primereact/chip'; import { ConfirmDialog, confirmDialog } from 'primereact/confirmdialog'; import { Toolbar } from 'primereact/toolbar'; import { SpeedDial } from 'primereact/speeddial'; import { Panel } from 'primereact/panel'; import { Accordion, AccordionTab } from 'primereact/accordion'; import { Badge } from 'primereact/badge'; import { Tag } from 'primereact/tag'; import { Avatar } from 'primereact/avatar'; import { AvatarGroup } from 'primereact/avatargroup'; import { Knob } from 'primereact/knob'; import { ProgressBar } from 'primereact/progressbar'; import { Skeleton } from 'primereact/skeleton'; import { Message } from 'primereact/message'; import { Messages } from 'primereact/messages'; import { Fieldset } from 'primereact/fieldset'; import { ScrollPanel } from 'primereact/scrollpanel'; import { Splitter, SplitterPanel } from 'primereact/splitter'; import { DataView } from 'primereact/dataview'; import { Timeline } from 'primereact/timeline'; import { Steps } from 'primereact/steps'; import { MenuItem } from 'primereact/menuitem'; import { Menu } from 'primereact/menu'; import { TieredMenu } from 'primereact/tieredmenu'; import { ContextMenu } from 'primereact/contextmenu'; import { Sidebar } from 'primereact/sidebar'; import { OverlayPanel } from 'primereact/overlaypanel'; import { Dialog } from 'primereact/dialog'; import { Rating } from 'primereact/rating'; import { Slider } from 'primereact/slider'; import { ToggleButton } from 'primereact/togglebutton'; import { MultiSelect } from 'primereact/multiselect'; import { Checkbox } from 'primereact/checkbox'; import { RadioButton } from 'primereact/radiobutton'; import { ListBox } from 'primereact/listbox'; import { InputMask } from 'primereact/inputmask'; import { AutoComplete } from 'primereact/autocomplete'; import { Password } from 'primereact/password'; import { BlockUI } from 'primereact/blockui'; import { PickList } from 'primereact/picklist'; import { OrderList } from 'primereact/orderlist'; import { DataScroller } from 'primereact/datascroller'; import { VirtualScroller } from 'primереact/virtualscroller'; import { Galleria } from 'primereact/galleria'; import { Image } from 'primereact/image'; import { Carousel } from 'primereact/carousel'; import { Chart } from 'primereact/chart'; import { Terminal } from 'primereact/terminal'; import { DeferredContent } from 'primereact/deferredcontent'; import { InlineMessage } from 'primereact/inlinemessage'; import { ScrollTop } from 'primereact/scrolltop'; import { CascadeSelect } from 'primereact/cascadeselect'; import { TreeSelect } from 'primereact/treeselect'; import { Mention } from 'primereact/mention'; import { Editor } from 'primereact/editor'; import { Tree } from 'primereact/tree'; import { TreeTable } from 'primereact/treetable'; import { Column } from 'primereact/column'; interface CompanySettings { nom: string; adresse: string; telephone: string; email: string; siteWeb: string; numeroTVA: string; numeroSiret: string; capitalSocial: number; formeJuridique: string; logo: string; } interface InvoiceSettings { prefixFacture: string; prefixDevis: string; prochainNumeroFacture: number; prochainNumeroDevis: number; tauxTVADefaut: number; conditionsPaiement: string; mentionsLegales: string; delaiPaiementDefaut: number; penalitesRetard: number; } interface EmailSettings { serveurSMTP: string; portSMTP: number; utilisateurSMTP: string; motDePasseSMTP: string; expediteurDefaut: string; useTLS: boolean; emailsNotification: string[]; } interface SystemSettings { langue: string; fuseau: string; deviseDefaut: string; formatDate: string; formatHeure: string; theme: string; couleurPrimaire: string; activerNotifications: boolean; activerRappels: boolean; delaiRappelFacture: number; delaiRappelDevis: number; } interface BackupSettings { sauvegardeAuto: boolean; frequenceSauvegarde: string; heureSauvegarde: Date; retention: number; destination: string; chiffrementActif: boolean; } const ParametresPage = () => { const [activeIndex, setActiveIndex] = useState(0); const [loading, setLoading] = useState(false); const [blocked, setBlocked] = useState(false); const [darkMode, setDarkMode] = useState(false); const [compactMode, setCompactMode] = useState(false); const [expertMode, setExpertMode] = useState(false); const [autoSave, setAutoSave] = useState(true); const [settingsHistory, setSettingsHistory] = useState([]); const [lastSaved, setLastSaved] = useState(null); const [unsavedChanges, setUnsavedChanges] = useState(false); const [configProfile, setConfigProfile] = useState('standard'); const [performanceLevel, setPerformanceLevel] = useState(75); const [securityScore, setSecurityScore] = useState(85); const [systemHealth, setSystemHealth] = useState(92); const [backupProgress, setBackupProgress] = useState(0); const [exportProgress, setExportProgress] = useState(0); const [sidebarVisible, setSidebarVisible] = useState(false); const [helpVisible, setHelpVisible] = useState(false); const [historyVisible, setHistoryVisible] = useState(false); const [configWizard, setConfigWizard] = useState(false); const [wizardStep, setWizardStep] = useState(0); const [autoRefresh, setAutoRefresh] = useState(true); const [refreshInterval, setRefreshInterval] = useState(30); const [notifications, setNotifications] = useState([]); const [searchTerm, setSearchTerm] = useState(''); const [filteredSettings, setFilteredSettings] = useState([]); const [settingsComparison, setSettingsComparison] = useState(false); const [recommendedSettings, setRecommendedSettings] = useState([]); const [quickActions, setQuickActions] = useState([]); const toast = useRef(null); const messages = useRef(null); const overlayPanel = useRef(null); const contextMenu = useRef(null); const tieredMenu = useRef(null); const terminal = useRef(null); // TODO: Charger les paramètres de l'entreprise depuis l'API // Exemple: useEffect(() => { fetch('/api/admin/company-settings').then(res => res.json()).then(setCompanySettings); }, []); const [companySettings, setCompanySettings] = useState({ nom: '', adresse: '', telephone: '', email: '', siteWeb: '', numeroTVA: '', numeroSiret: '', capitalSocial: 0, formeJuridique: '', logo: '' }); // TODO: Charger les paramètres de facturation depuis l'API const [invoiceSettings, setInvoiceSettings] = useState({ prefixFacture: '', prefixDevis: '', prochainNumeroFacture: 0, prochainNumeroDevis: 0, tauxTVADefaut: 0, conditionsPaiement: '', mentionsLegales: '', delaiPaiementDefaut: 0, penalitesRetard: 0 }); // TODO: Charger les paramètres email depuis l'API const [emailSettings, setEmailSettings] = useState({ serveurSMTP: '', portSMTP: 0, utilisateurSMTP: '', motDePasseSMTP: '', expediteurDefaut: '', useTLS: false, emailsNotification: [] }); // TODO: Charger les paramètres système depuis l'API const [systemSettings, setSystemSettings] = useState({ langue: '', fuseau: '', deviseDefaut: '', formatDate: '', formatHeure: '', theme: '', couleurPrimaire: '', activerNotifications: false, activerRappels: false, delaiRappelFacture: 0, delaiRappelDevis: 0 }); // TODO: Charger les paramètres de sauvegarde depuis l'API const [backupSettings, setBackupSettings] = useState({ sauvegardeAuto: false, frequenceSauvegarde: '', heureSauvegarde: new Date(), retention: 0, destination: '', chiffrementActif: false }); const formesJuridiques = [ { label: 'SARL', value: 'SARL' }, { label: 'SAS', value: 'SAS' }, { label: 'SA', value: 'SA' }, { label: 'EURL', value: 'EURL' }, { label: 'Auto-entrepreneur', value: 'AUTO' }, { label: 'Autre', value: 'AUTRE' } ]; const langues = [ { label: 'Français', value: 'fr' }, { label: 'English', value: 'en' }, { label: 'Español', value: 'es' }, { label: 'Deutsch', value: 'de' } ]; const fuseaux = [ { label: 'Europe/Paris', value: 'Europe/Paris' }, { label: 'Europe/London', value: 'Europe/London' }, { label: 'America/New_York', value: 'America/New_York' }, { label: 'Asia/Tokyo', value: 'Asia/Tokyo' } ]; const devises = [ { label: 'Euro (EUR)', value: 'EUR' }, { label: 'Dollar US (USD)', value: 'USD' }, { label: 'Livre Sterling (GBP)', value: 'GBP' }, { label: 'Franc CFA (XOF)', value: 'XOF' } ]; const themes = [ { label: 'Clair', value: 'light', icon: 'sun' }, { label: 'Sombre', value: 'dark', icon: 'moon' }, { label: 'Auto', value: 'auto', icon: 'adjust' }, { label: 'Contraste élevé', value: 'contrast', icon: 'eye' }, { label: 'Mode nuit', value: 'night', icon: 'moon' } ]; const configProfiles = [ { label: 'Basique', value: 'basic', description: 'Configuration simplifiée' }, { label: 'Standard', value: 'standard', description: 'Configuration recommandée' }, { label: 'Avancé', value: 'advanced', description: 'Toutes les options' }, { label: 'Expert', value: 'expert', description: 'Configuration complète' }, { label: 'Personnalisé', value: 'custom', description: 'Configuration sur mesure' } ]; const wizardSteps = [ { label: 'Entreprise', icon: 'pi pi-building' }, { label: 'Utilisateurs', icon: 'pi pi-users' }, { label: 'Sécurité', icon: 'pi pi-shield' }, { label: 'Intégrations', icon: 'pi pi-link' }, { label: 'Finalisation', icon: 'pi pi-check' } ]; const quickActionsData = [ { label: 'Sauvegarde rapide', icon: 'pi pi-save', command: () => quickBackup() }, { label: 'Mode maintenance', icon: 'pi pi-wrench', command: () => toggleMaintenance() }, { label: 'Réinitialiser cache', icon: 'pi pi-refresh', command: () => clearCache() }, { label: 'Export complet', icon: 'pi pi-download', command: () => exportAll() }, { label: 'Test connectivité', icon: 'pi pi-wifi', command: () => testConnections() }, { label: 'Optimiser DB', icon: 'pi pi-database', command: () => optimizeDatabase() } ]; const performanceMetrics = [ { label: 'CPU', value: 45, color: '#10B981' }, { label: 'Mémoire', value: 67, color: '#F59E0B' }, { label: 'Disque', value: 23, color: '#3B82F6' }, { label: 'Réseau', value: 89, color: '#8B5CF6' } ]; const securityAudits = [ { date: new Date(), action: 'Connexion admin', status: 'success', ip: '192.168.1.100' }, { date: new Date(), action: 'Modification paramètres', status: 'success', ip: '192.168.1.100' }, { date: new Date(), action: 'Tentative accès', status: 'warning', ip: '192.168.1.205' }, { date: new Date(), action: 'Sauvegarde auto', status: 'success', ip: 'system' } ]; const integrationsList = [ { name: 'QuickBooks', status: 'connected', icon: 'pi pi-calculator' }, { name: 'Slack', status: 'connected', icon: 'pi pi-slack' }, { name: 'Google Drive', status: 'disconnected', icon: 'pi pi-google' }, { name: 'Dropbox', status: 'error', icon: 'pi pi-cloud' }, { name: 'Microsoft 365', status: 'connected', icon: 'pi pi-microsoft' }, { name: 'Zapier', status: 'pending', icon: 'pi pi-bolt' } ]; const frequenceOptions = [ { label: 'Horaire', value: 'horaire' }, { label: 'Quotidien', value: 'quotidien' }, { label: 'Hebdomadaire', value: 'hebdomadaire' }, { label: 'Mensuel', value: 'mensuel' } ]; const destinationOptions = [ { label: 'Stockage local', value: 'local' }, { label: 'Cloud (Google Drive)', value: 'google' }, { label: 'Cloud (Dropbox)', value: 'dropbox' }, { label: 'Serveur FTP', value: 'ftp' } ]; const saveSettings = (section: string) => { setLoading(true); // Simuler la sauvegarde setTimeout(() => { setLoading(false); toast.current?.show({ severity: 'success', summary: 'Succès', detail: `Les paramètres ${section} ont été sauvegardés`, life: 3000 }); }, 1000); }; const resetSettings = (section: string) => { confirmDialog({ message: `Êtes-vous sûr de vouloir réinitialiser les paramètres ${section} ?`, header: 'Confirmation', icon: 'pi pi-exclamation-triangle', acceptLabel: 'Oui', rejectLabel: 'Non', accept: () => { toast.current?.show({ severity: 'info', summary: 'Réinitialisation', detail: `Les paramètres ${section} ont été réinitialisés`, life: 3000 }); } }); }; const testEmailConnection = () => { setLoading(true); setTimeout(() => { setLoading(false); toast.current?.show({ severity: 'success', summary: 'Test réussi', detail: 'La connexion au serveur SMTP a été établie avec succès', life: 3000 }); }, 2000); }; useEffect(() => { if (autoRefresh) { const interval = setInterval(() => { updateSystemMetrics(); }, refreshInterval * 1000); return () => clearInterval(interval); } }, [autoRefresh, refreshInterval]); const updateSystemMetrics = () => { setPerformanceLevel(Math.floor(Math.random() * 20) + 70); setSecurityScore(Math.floor(Math.random() * 15) + 80); setSystemHealth(Math.floor(Math.random() * 10) + 85); }; const quickBackup = () => { setBackupProgress(0); const interval = setInterval(() => { setBackupProgress(prev => { if (prev >= 100) { clearInterval(interval); toast.current?.show({ severity: 'success', summary: 'Sauvegarde terminée', detail: 'Sauvegarde rapide effectuée avec succès', life: 3000 }); return 100; } return prev + 10; }); }, 200); }; const toggleMaintenance = () => { confirmDialog({ message: 'Activer le mode maintenance ?', header: 'Mode Maintenance', icon: 'pi pi-wrench', acceptLabel: 'Activer', rejectLabel: 'Annuler', accept: () => { toast.current?.show({ severity: 'info', summary: 'Mode maintenance', detail: 'Le mode maintenance a été activé', life: 3000 }); } }); }; const clearCache = () => { toast.current?.show({ severity: 'success', summary: 'Cache vidé', detail: 'Le cache système a été réinitialisé', life: 3000 }); }; const exportAll = () => { setExportProgress(0); const interval = setInterval(() => { setExportProgress(prev => { if (prev >= 100) { clearInterval(interval); exportSettings(); return 100; } return prev + 5; }); }, 100); }; const testConnections = () => { toast.current?.show({ severity: 'info', summary: 'Test en cours', detail: 'Test de connectivité en cours...', life: 3000 }); setTimeout(() => { toast.current?.show({ severity: 'success', summary: 'Connectivité OK', detail: 'Toutes les connexions sont opérationnelles', life: 3000 }); }, 2000); }; const optimizeDatabase = () => { toast.current?.show({ severity: 'info', summary: 'Optimisation DB', detail: 'Optimisation de la base de données en cours...', life: 5000 }); }; const exportSettings = () => { const allSettings = { company: companySettings, invoice: invoiceSettings, email: emailSettings, system: systemSettings, backup: backupSettings, metadata: { exportDate: new Date().toISOString(), version: '2.1.0', profile: configProfile } }; const blob = new Blob([JSON.stringify(allSettings, null, 2)], { type: 'application/json' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = `btpxpress-settings-${new Date().toISOString().split('T')[0]}.json`; link.click(); toast.current?.show({ severity: 'success', summary: 'Export réussi', detail: 'Les paramètres ont été exportés', life: 3000 }); setLastSaved(new Date()); setUnsavedChanges(false); }; const renderCompanySettings = () => (
Informations de l'entreprise
setCompanySettings({...companySettings, nom: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, formeJuridique: e.value})} className="w-full" />
setCompanySettings({...companySettings, adresse: e.target.value})} rows={3} className="w-full" />
setCompanySettings({...companySettings, telephone: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, email: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, siteWeb: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, numeroTVA: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, numeroSiret: e.target.value})} className="w-full" />
setCompanySettings({...companySettings, capitalSocial: e.value || 0})} mode="currency" currency="EUR" locale="fr-FR" className="w-full" />
Glissez et déposez le logo ici ou cliquez pour sélectionner.

} />
); const renderInvoiceSettings = () => (
Paramètres de facturation
setInvoiceSettings({...invoiceSettings, prefixFacture: e.target.value})} className="w-full" />
setInvoiceSettings({...invoiceSettings, prochainNumeroFacture: e.value || 1})} className="w-full" />
setInvoiceSettings({...invoiceSettings, prefixDevis: e.target.value})} className="w-full" />
setInvoiceSettings({...invoiceSettings, prochainNumeroDevis: e.value || 1})} className="w-full" />
setInvoiceSettings({...invoiceSettings, tauxTVADefaut: e.value || 0})} suffix="%" min={0} max={100} className="w-full" />
setInvoiceSettings({...invoiceSettings, delaiPaiementDefaut: e.value || 30})} suffix=" jours" min={0} className="w-full" />
setInvoiceSettings({...invoiceSettings, penalitesRetard: e.value || 0})} suffix="%" min={0} max={100} className="w-full" />
setInvoiceSettings({...invoiceSettings, conditionsPaiement: e.target.value})} rows={3} className="w-full" />
setInvoiceSettings({...invoiceSettings, mentionsLegales: e.target.value})} rows={4} className="w-full" />
); const renderEmailSettings = () => (
Configuration email
setEmailSettings({...emailSettings, serveurSMTP: e.target.value})} className="w-full" />
setEmailSettings({...emailSettings, portSMTP: e.value || 587})} className="w-full" />
setEmailSettings({...emailSettings, utilisateurSMTP: e.target.value})} className="w-full" />
setEmailSettings({...emailSettings, motDePasseSMTP: e.target.value})} className="w-full" />
setEmailSettings({...emailSettings, expediteurDefaut: e.target.value})} className="w-full" />
setEmailSettings({...emailSettings, useTLS: e.value})} />
{emailSettings.emailsNotification.map((email, index) => ( { const newEmails = [...emailSettings.emailsNotification]; newEmails.splice(index, 1); setEmailSettings({...emailSettings, emailsNotification: newEmails}); }} /> ))}
{ if (e.key === 'Enter') { const input = e.currentTarget; if (input.value && input.value.includes('@')) { setEmailSettings({ ...emailSettings, emailsNotification: [...emailSettings.emailsNotification, input.value] }); input.value = ''; } } }} />
); const renderSystemSettings = () => (
Paramètres système
setSystemSettings({...systemSettings, langue: e.value})} className="w-full" />
setSystemSettings({...systemSettings, fuseau: e.value})} className="w-full" />
setSystemSettings({...systemSettings, deviseDefaut: e.value})} className="w-full" />
setSystemSettings({...systemSettings, theme: e.value})} />
setSystemSettings({...systemSettings, couleurPrimaire: `#${e.value}`})} /> setSystemSettings({...systemSettings, couleurPrimaire: e.target.value})} className="flex-1" />
Notifications et rappels
setSystemSettings({...systemSettings, activerNotifications: e.value})} />
setSystemSettings({...systemSettings, activerRappels: e.value})} />
setSystemSettings({...systemSettings, delaiRappelFacture: e.value || 7})} suffix=" jours" min={1} className="w-full" disabled={!systemSettings.activerRappels} />
setSystemSettings({...systemSettings, delaiRappelDevis: e.value || 3})} suffix=" jours" min={1} className="w-full" disabled={!systemSettings.activerRappels} />
); const renderSystemOverview = () => (
Performance Système

Optimal

Score Sécurité

Excellent

Santé Système

Très bon

{performanceMetrics.map((metric, index) => (
{metric.label} {metric.value}%
))}
24h
Uptime
1,247
Utilisateurs actifs
2.4GB
Données traitées
156ms
Temps réponse
); const renderIntegrationsTab = () => (
(
{item.name}
)} layout="grid" />
); const renderSecurityTab = () => (
(
{item.action}
{item.ip} - {item.date.toLocaleTimeString()}
)} className="w-full" />
); const renderAdvancedTab = () => (
Navigation rapide
); const leftToolbarTemplate = () => (
Paramètres Système
{lastSaved ? `Dernière sauvegarde: ${lastSaved.toLocaleString()}` : 'Aucune sauvegarde'} {unsavedChanges && }
); const rightToolbarTemplate = () => (
setAutoRefresh(e.value)} onIcon="pi pi-pause" offIcon="pi pi-play" onLabel="Auto-refresh" offLabel="Manual" size="small" />
); return (
{exportProgress > 0 && exportProgress < 100 && (

Export en cours...

)} {backupProgress > 0 && backupProgress < 100 && (

Sauvegarde en cours...

)} setActiveIndex(e.index)} className="tabview-custom" > {renderSystemOverview()} {renderCompanySettings()} {renderInvoiceSettings()} {renderEmailSettings()} {renderSystemSettings()} {renderSecurityTab()} {renderIntegrationsTab()} {renderAdvancedTab()} setSidebarVisible(false)} position="right" className="w-20rem" >

Actions rapides

{quickActionsData.map((action, index) => (

Profil de configuration

setConfigProfile(e.value)} optionLabel="label" optionValue="value" className="w-full" />
Options d'affichage
setDarkMode(e.value)} />
setCompactMode(e.value)} />
setExpertMode(e.value)} />
setConfigWizard(false)} style={{ width: '50vw' }} modal > setWizardStep(e.index)} readOnly={false} className="mb-4" />
{wizardStep === 0 && (

Configuration de l'entreprise

Configurons d'abord les informations de base de votre entreprise.

{renderCompanySettings()}
)} {wizardStep === 1 && (

Gestion des utilisateurs

Définissez les paramètres d'accès et de sécurité.

)} {wizardStep === 4 && (

Configuration terminée !

Votre système est maintenant configuré et prêt à l'emploi.

)}
); }; const ProtectedParametresPage = () => { return ( ); }; export default ProtectedParametresPage; // Style CSS personnalisé pour améliorer l'apparence const customStyles = ` .tabview-custom .p-tabview-nav { background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); border-radius: 10px 10px 0 0; } .tabview-custom .p-tabview-nav li .p-tabview-nav-link { color: white; border: none; } .tabview-custom .p-tabview-nav li.p-highlight .p-tabview-nav-link { background: rgba(255, 255, 255, 0.2); border-radius: 8px; margin: 4px; } .bg-gradient-to-r { background: linear-gradient(90deg, var(--tw-gradient-stops)); } .from-blue-500 { --tw-gradient-from: #3b82f6; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(59, 130, 246, 0)); } .to-purple-600 { --tw-gradient-to: #9333ea; } .wizard-content { min-height: 300px; } `; // Injection du style dans le document if (typeof document !== 'undefined') { const style = document.createElement('style'); style.textContent = customStyles; document.head.appendChild(style); }