All files / apps/web/src/backoffice/pages Settings.jsx

0% Statements 0/87
0% Branches 0/102
0% Functions 0/33
0% Lines 0/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useLocation } from 'react-router-dom';
import { Key, Globe, CheckCircle, XCircle, Loader2, Save, TestTube } from 'lucide-react';
import api from '../../services/api';
import toast from 'react-hot-toast';
import { useOrganizationStore } from '../../store/organizationStore';
import OrgApiKeysManager from './OrgApiKeysManager';
 
// Fallback : extraire l'orgId depuis l'URL si le store n'est pas encore chargé
function getOrgIdFromPath(pathname) {
  const parts = pathname.split('/').filter(Boolean);
  return parts[0] && /^[0-9a-f]{24}$/.test(parts[0]) ? parts[0] : null;
}
 
const PROVIDERS = [
  { key: 'openrouter', label: 'OpenRouter (LLM)', icon: Key, description: 'Appels API LLM — Obligatoire', placeholder: 'sk-or-v1-...', docUrl: 'https://openrouter.ai/keys', docLabel: 'openrouter.ai' },
  { key: 'marker', label: 'Datalab (extraction fichiers)', icon: Key, description: 'Extraction md/html depuis PDF, images…', placeholder: 'Votre clé API Datalab', docUrl: 'https://datalab.to', docLabel: 'datalab.to' },
  { key: 'browserless', label: 'Browserless.io', icon: Globe, description: 'Navigateur cloud pour le crawling', placeholder: 'Votre token Browserless', docUrl: null, docLabel: null },
  { key: 'brightdata', label: 'Bright Data', icon: Globe, description: 'Proxy résidentiel pour le crawling', placeholder: 'wss://brd-customer-...', docUrl: null, docLabel: null },
];
 
function ProviderCard({ provider, formData, setFormData, testStatus, testConnection, isKeyConfigured, isKeyReadOnly }) {
  const data = formData[provider.key] || { value: '', custom: false };
 
  return (
    <div className="bg-white rounded-lg shadow p-6">
      <div className="flex items-center mb-4">
        <div className="p-2 bg-indigo-100 rounded-lg mr-3">
          <provider.icon className="w-5 h-5 text-indigo-600" />
        </div>
        <div>
          <h3 className="text-lg font-medium text-gray-900">{provider.label}</h3>
          <p className="text-sm text-gray-500">{provider.description}</p>
        </div>
      </div>
 
      <div className="space-y-4">
        <label className="flex items-center justify-between p-3 bg-gray-50 rounded-lg cursor-pointer">
          <div>
            <span className="text-sm font-medium text-gray-700">Utiliser ma propre clé</span>
            {!data.custom && <p className="text-xs text-gray-500 mt-0.5">Clé système active</p>}
          </div>
          <input
            type="checkbox"
            checked={data.custom}
            onChange={(e) => setFormData(prev => ({
              ...prev,
              [provider.key]: { ...prev[provider.key], custom: e.target.checked }
            }))}
            className="w-5 h-5 text-indigo-600 border-gray-300 rounded"
          />
        </label>
 
        {data.custom && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {provider.key === 'openrouter' || provider.key === 'marker' ? 'API Key' : 'Token / Endpoint'}
              {isKeyConfigured(provider.key) && !isKeyReadOnly(provider.key) && (
                <span className="ml-2 text-green-600 text-xs">✓ Configuré</span>
              )}
              {isKeyReadOnly(provider.key) && (
                <span className="ml-2 text-yellow-600 text-xs">🔒 Défini dans .env</span>
              )}
            </label>
            <input
              type="password"
              value={data.value}
              onChange={(e) => setFormData(prev => ({
                ...prev,
                [provider.key]: { ...prev[provider.key], value: e.target.value }
              }))}
              placeholder={provider.placeholder}
              disabled={isKeyReadOnly(provider.key)}
              className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent ${
                isKeyReadOnly(provider.key) ? 'bg-gray-100 cursor-not-allowed' : 'border-gray-300'
              }`}
            />
            {provider.docUrl && (
              <p className="text-xs text-gray-500 mt-1">
                Obtenez votre clé sur <a href={provider.docUrl} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{provider.docLabel}</a>
              </p>
            )}
          </div>
        )}
 
        <div className="flex items-center justify-end pt-2">
          <button
            type="button"
            onClick={() => testConnection(provider.key)}
            disabled={testStatus[provider.key] === 'loading'}
            className="flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 disabled:opacity-50"
          >
            <TestTube className="w-4 h-4 mr-2" />
            Tester
          </button>
        </div>
 
        {testStatus[provider.key] && (
          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
            testStatus[provider.key] === 'loading' ? 'bg-yellow-100 text-yellow-800' :
            testStatus[provider.key] === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
          }`}>
            {testStatus[provider.key] === 'loading' && <Loader2 className="w-3 h-3 mr-1 animate-spin" />}
            {testStatus[provider.key] === 'success' && <CheckCircle className="w-3 h-3 mr-1" />}
            {testStatus[provider.key] === 'error' && <XCircle className="w-3 h-3 mr-1" />}
            {testStatus[`${provider.key}Message`] || (testStatus[provider.key] === 'loading' ? 'Test en cours...' : testStatus[provider.key] === 'success' ? 'OK' : 'Erreur')}
          </span>
        )}
      </div>
    </div>
  );
}
 
export default function BackofficeSettings() {
  const { currentOrganization } = useOrganizationStore();
  const location = useLocation();
  const organizationId = currentOrganization?.id || getOrgIdFromPath(location.pathname);
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState('api-keys');
  const [testStatus, setTestStatus] = useState({});
 
  const [formData, setFormData] = useState(
    Object.fromEntries(PROVIDERS.map(p => [p.key, { value: '', custom: false }]))
  );
 
  const { data: config, isLoading } = useQuery({
    queryKey: ['system-config', organizationId],
    queryFn: async () => {
      const response = await api.get('/config/resolve');
      return response.data.data;
    },
    enabled: !!organizationId
  });
 
  const getConfigValue = (key) => {
    if (!config || !Array.isArray(config)) return null;
    const item = config.find(c => c.key === key);
    return item ? item.value : null;
  };
 
  const getConfigSource = (key) => {
    if (!config || !Array.isArray(config)) return null;
    const item = config.find(c => c.key === key);
    return item ? item.source : 'default';
  };
 
  const isKeyConfigured = (key) => {
    if (!config || !Array.isArray(config)) return false;
    const item = config.find(c => c.key === key);
    return !!(item?.value && item.value.length > 0);
  };
 
  const isKeyReadOnly = (key) => {
    if (!config || !Array.isArray(config)) return false;
    const item = config.find(c => c.key === key);
    return item ? item.isReadOnly : false;
  };
 
  useEffect(() => {
    if (config && Array.isArray(config)) {
      setFormData(
        Object.fromEntries(PROVIDERS.map(p => [p.key, {
          value: getConfigSource(p.key) === 'database' ? 'CONFIGURED' : '',
          custom: getConfigSource(p.key) === 'database',
        }]))
      );
    }
  }, [config]);
 
  const saveConfig = useMutation({
    mutationFn: async (data) => {
      const promises = [];
      for (const provider of PROVIDERS) {
        const d = data[provider.key];
        const hadDbKey = getConfigSource(provider.key) === 'database';
        if (d.custom && d.value && d.value !== 'CONFIGURED') {
          promises.push(api.put(`/config/${provider.key}`, { value: d.value }));
        } else if (!d.custom && hadDbKey) {
          promises.push(api.delete(`/config/${provider.key}`));
        }
      }
      await Promise.all(promises);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['system-config']);
      toast.success('Configuration sauvegardée');
      setFormData(prev =>
        Object.fromEntries(Object.entries(prev).map(([k, v]) => [k, { ...v, value: '' }]))
      );
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la sauvegarde');
    }
  });
 
  const testConnection = async (provider) => {
    setTestStatus(prev => ({ ...prev, [provider]: 'loading' }));
    try {
      const response = await api.post(`/config/test/${provider}`);
      setTestStatus(prev => ({
        ...prev,
        [provider]: response.data.success ? 'success' : 'error',
        [`${provider}Message`]: response.data.message
      }));
      if (response.data.success) {
        toast.success(`${provider}: Connexion réussie`);
      } else {
        toast.error(`${provider}: ${response.data.message}`);
      }
    } catch (error) {
      setTestStatus(prev => ({
        ...prev,
        [provider]: 'error',
        [`${provider}Message`]: error.response?.data?.message || 'Erreur'
      }));
      toast.error(`Test ${provider} échoué`);
    }
  };
 
  const handleSubmit = (e) => {
    e.preventDefault();
    saveConfig.mutate(formData);
  };
 
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold text-gray-900">Configuration Système</h2>
        <p className="text-gray-600">Gérez les clés API et paramètres de tous les services</p>
      </div>
 
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('api-keys')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'api-keys'
                ? 'border-indigo-500 text-indigo-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            <Key className="w-4 h-4 inline mr-2" />
            Clés API
          </button>
          <button
            onClick={() => setActiveTab('org-api-keys')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'org-api-keys'
                ? 'border-indigo-500 text-indigo-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            <Key className="w-4 h-4 inline mr-2" />
            Clés API Organisation
          </button>
        </nav>
      </div>
 
      {activeTab === 'api-keys' && (
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <p className="text-sm text-blue-700">
              Chaque clé peut être laissée en configuration système (clé globale) ou remplacée
              par votre propre clé via le toggle. Les clés globales sont définies dans le fichier <code className="bg-blue-100 px-1 rounded">.env</code> côté serveur.
            </p>
          </div>
 
          <div className="grid gap-6">
            {PROVIDERS.map(provider => (
              <ProviderCard
                key={provider.key}
                provider={provider}
                formData={formData}
                setFormData={setFormData}
                testStatus={testStatus}
                testConnection={testConnection}
                isKeyConfigured={isKeyConfigured}
                isKeyReadOnly={isKeyReadOnly}
              />
            ))}
          </div>
 
          <div className="flex justify-end">
            <button
              type="submit"
              disabled={saveConfig.isLoading}
              className="flex items-center px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
            >
              {saveConfig.isLoading ? (
                <Loader2 className="w-5 h-5 mr-2 animate-spin" />
              ) : (
                <Save className="w-5 h-5 mr-2" />
              )}
              Sauvegarder les modifications
            </button>
          </div>
        </form>
      )}
 
      {activeTab === 'org-api-keys' && <OrgApiKeysManager organizationId={organizationId} />}
    </div>
  );
}