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

0% Statements 0/48
0% Branches 0/42
0% Functions 0/20
0% Lines 0/46

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                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  Globe, 
  Save,
  Trash2,
  Link as LinkIcon
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import toast from 'react-hot-toast';
import { useOrganizationStore } from '../../store/organizationStore';
import EntitySidebar from '../../components/EntitySidebar';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
 
export default function ExternalApiEdit() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const queryClient = useQueryClient();
  const isNew = id === 'new';
 
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    url: ''
  });
 
  const { data: apiConfig, isLoading } = useQuery({
    queryKey: ['external-api', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/external-apis/${id}`);
      return response.data.data;
    },
    enabled: !isNew
  });
 
  const { data: apisList, isLoading: apisListLoading } = useQuery({
    queryKey: ['external-apis', organizationId],
    queryFn: async () => {
      const response = await api.get('/external-apis');
      return response.data.data || [];
    }
  });
 
  useEffect(() => {
    if (apiConfig) {
      setFormData({
        name: apiConfig.name || '',
        description: apiConfig.description || '',
        url: apiConfig.url || ''
      });
    }
  }, [apiConfig]);
 
  const saveApi = useMutation({
    mutationFn: async (data) => {
      const payload = { ...data, organizationId };
      if (isNew) {
        return api.post('/external-apis', payload);
      } else {
        return api.put(`/external-apis/${id}`, payload);
      }
    },
    onSuccess: () => {
      toast.success(isNew ? 'API externe créée' : 'API externe mise à jour');
      queryClient.invalidateQueries(['external-apis']);
      navigate(`/${organizationId}/backoffice/external-apis`);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la sauvegarde');
    }
  });
 
  const deleteApi = useMutation({
    mutationFn: async () => {
      return api.delete(`/external-apis/${id}`);
    },
    onSuccess: () => {
      toast.success('API externe supprimée');
      queryClient.invalidateQueries(['external-apis']);
      navigate(`/${organizationId}/backoffice/external-apis`);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la suppression');
    }
  });
 
  const handleSubmit = (e) => {
    e.preventDefault();
    saveApi.mutate(formData);
  };
 
  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };
 
  const sidebar = (
    <EntitySidebar
      items={apisList || []}
      selectedId={isNew ? null : id}
      getItemHref={(a) => `/${organizationId}/backoffice/external-apis/${a._id || a.id}`}
      searchPlaceholder="Rechercher une API..."
      emptyMessage="Aucune API externe disponible"
      title="APIs externes"
      icon={Globe}
      iconClass="text-cyan-600"
      backofficeTo={`/${organizationId}/backoffice/external-apis/new`}
      backofficeManageLabel="Créer une API externe"
      backofficeCreateLabel="Créer une API externe"
      createOnly
      loading={apisListLoading}
      filterFn={(a) => `${a.name} ${a.description || ''}`}
      renderItem={(a, isSelected) => (
        <>
          <div className="flex items-center">
            <Globe className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-cyan-400' : 'text-slate-500'}`} />
            <span className={`text-sm font-medium truncate flex-1 ${isSelected ? 'text-white' : 'text-slate-300'}`}>
              {a.name}
            </span>
          </div>
          <div className="text-xs text-slate-400 truncate mt-0.5">
            {a.url}
          </div>
        </>
      )}
    />
  );
 
  return (
    <BackofficeEntityPage selectedId={isNew ? null : id} sidebar={sidebar}>
      <div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
        <div className="space-y-6">
      <div className="flex flex-wrap justify-end gap-2">
        {!isNew && (
          <button
            onClick={() => deleteApi.mutate()}
            className="flex items-center px-4 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50"
          >
            <Trash2 className="w-5 h-5 mr-2" />
            Supprimer
          </button>
        )}
        <button
          onClick={handleSubmit}
          disabled={saveApi.isLoading}
          className="flex items-center px-4 py-2 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 disabled:opacity-50"
        >
          <Save className="w-5 h-5 mr-2" />
          {saveApi.isLoading ? 'Sauvegarde...' : isNew ? 'Créer' : 'Sauvegarder'}
        </button>
      </div>
 
      {isLoading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-600"></div>
        </div>
      ) : (
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Globe className="w-6 h-6 text-cyan-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Informations</h3>
          </div>
 
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Nom de l'API *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                placeholder="Ex: Webhook CRM"
                required
              />
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleChange('description', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                placeholder="Description de l'API..."
                rows={2}
              />
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                URL de réception *
              </label>
              <div className="flex items-center">
                <LinkIcon className="w-4 h-4 text-gray-400 mr-2 flex-shrink-0" />
                <input
                  type="url"
                  value={formData.url}
                  onChange={(e) => handleChange('url', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                  placeholder="https://exemple.com/webhook"
                  required
                />
              </div>
              <p className="text-xs text-gray-500 mt-1">
                Les données raffinées seront envoyées à cette URL (POST JSON). L'authentification et les headers seront enrichis prochainement.
              </p>
            </div>
          </div>
        </div>
      </form>
      )}
        </div>
      </div>
    </BackofficeEntityPage>
  );
}