xpeditis2.0/apps/frontend/app/[locale]/dashboard/admin/organizations/page.tsx

833 lines
31 KiB
TypeScript

'use client';
import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { getAllOrganizations, verifySiret, approveSiret, rejectSiret } from '@/lib/api/admin';
import { createOrganization, updateOrganization } from '@/lib/api/organizations';
import { PageHeader } from '@/components/ui/PageHeader';
interface Organization {
id: string;
name: string;
type: string;
scac?: string;
siren?: string;
siret?: string;
siretVerified?: boolean;
statusBadge?: string;
eori?: string;
contact_phone?: string;
contact_email?: string;
address: {
street: string;
city: string;
state?: string;
postalCode: string;
country: string;
};
logoUrl?: string;
isActive: boolean;
createdAt: string;
}
interface FormData {
name: string;
type: string;
scac: string;
siren: string;
siret: string;
eori: string;
contact_phone: string;
contact_email: string;
address: {
street: string;
city: string;
state: string;
postalCode: string;
country: string;
};
logoUrl: string;
isActive: boolean;
}
const EMPTY_FORM: FormData = {
name: '',
type: 'FREIGHT_FORWARDER',
scac: '',
siren: '',
siret: '',
eori: '',
contact_phone: '',
contact_email: '',
address: { street: '', city: '', state: '', postalCode: '', country: 'FR' },
logoUrl: '',
isActive: true,
};
function FieldHint({ children }: { children: React.ReactNode }) {
return <p className="mt-1 text-xs text-gray-400">{children}</p>;
}
function FieldError({ message }: { message?: string }) {
if (!message) return null;
return <p className="mt-1 text-xs text-red-600">{message}</p>;
}
export default function AdminOrganizationsPage() {
const t = useTranslations('dashboard.admin.organizations');
const [organizations, setOrganizations] = useState<Organization[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedOrg, setSelectedOrg] = useState<Organization | null>(null);
const [showCreateModal, setShowCreateModal] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const [verifyingId, setVerifyingId] = useState<string | null>(null);
const [formData, setFormData] = useState<FormData>(EMPTY_FORM);
const [formError, setFormError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Partial<Record<string, string>>>({});
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
fetchOrganizations();
}, []);
const fetchOrganizations = async () => {
try {
setLoading(true);
const response = await getAllOrganizations();
setOrganizations(response.organizations || []);
setError(null);
} catch (err: any) {
setError(err.message || t('loadError'));
} finally {
setLoading(false);
}
};
const validateForm = (isCreate: boolean): boolean => {
const errors: Partial<Record<string, string>> = {};
if (!formData.name.trim() || formData.name.trim().length < 2) {
errors.name = t('validation.nameTooShort');
}
if (isCreate && formData.type === 'CARRIER') {
if (!formData.scac) {
errors.scac = t('validation.scacRequired');
} else if (!/^[A-Z]{4}$/.test(formData.scac)) {
errors.scac = t('validation.scacFormat');
}
}
if (formData.siren && !/^[0-9]{9}$/.test(formData.siren)) {
errors.siren = t('validation.sirenFormat');
}
if (formData.siret && !/^[0-9]{14}$/.test(formData.siret)) {
errors.siret = t('validation.siretFormat');
}
if (!formData.address.street.trim()) errors.street = t('validation.required');
if (!formData.address.city.trim()) errors.city = t('validation.required');
if (!formData.address.postalCode.trim()) errors.postalCode = t('validation.required');
if (!/^[A-Z]{2}$/.test(formData.address.country)) {
errors.country = t('validation.countryFormat');
}
setFieldErrors(errors);
return Object.keys(errors).length === 0;
};
const buildApiAddress = () => ({
street: formData.address.street,
city: formData.address.city,
postalCode: formData.address.postalCode,
country: formData.address.country,
...(formData.address.state ? { state: formData.address.state } : {}),
});
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
setFormError(null);
if (!validateForm(true)) return;
setSubmitting(true);
try {
await createOrganization({
name: formData.name.trim(),
type: formData.type as any,
address: buildApiAddress(),
contact_email: formData.contact_email || undefined,
contact_phone: formData.contact_phone || undefined,
logoUrl: formData.logoUrl || undefined,
...(formData.siren ? { siren: formData.siren } : {}),
...(formData.siret ? { siret: formData.siret } : {}),
...(formData.eori ? { eori: formData.eori } : {}),
...(formData.scac ? { scac: formData.scac } : {}),
});
await fetchOrganizations();
setShowCreateModal(false);
resetForm();
} catch (err: any) {
setFormError(err.message || t('createError'));
} finally {
setSubmitting(false);
}
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedOrg) return;
setFormError(null);
if (!validateForm(false)) return;
setSubmitting(true);
try {
await updateOrganization(selectedOrg.id, {
name: formData.name.trim(),
address: buildApiAddress(),
contact_email: formData.contact_email || undefined,
contact_phone: formData.contact_phone || undefined,
logoUrl: formData.logoUrl || undefined,
isActive: formData.isActive,
...(formData.siren ? { siren: formData.siren } : {}),
...(formData.siret ? { siret: formData.siret } : {}),
...(formData.eori ? { eori: formData.eori } : {}),
});
await fetchOrganizations();
setShowEditModal(false);
setSelectedOrg(null);
resetForm();
} catch (err: any) {
setFormError(err.message || t('updateError'));
} finally {
setSubmitting(false);
}
};
const resetForm = () => {
setFormData(EMPTY_FORM);
setFormError(null);
setFieldErrors({});
};
const handleTypeChange = (newType: string) => {
setFormData(prev => ({
...prev,
type: newType,
scac: newType !== 'CARRIER' ? '' : prev.scac,
}));
setFieldErrors(prev => ({ ...prev, scac: undefined }));
};
const handleVerifySiret = async (orgId: string) => {
try {
setVerifyingId(orgId);
const result = await verifySiret(orgId);
if (result.verified) {
alert(
t('siretVerified', {
companyName: result.companyName || 'N/A',
address: result.address || 'N/A',
})
);
await fetchOrganizations();
} else {
alert(result.message || t('siretInvalid'));
}
} catch (err: any) {
alert(err.message || t('siretError'));
} finally {
setVerifyingId(null);
}
};
const handleApproveSiret = async (orgId: string) => {
if (!confirm(t('confirmApprove'))) return;
try {
setVerifyingId(orgId);
const result = await approveSiret(orgId);
alert(result.message);
await fetchOrganizations();
} catch (err: any) {
alert(err.message || t('siretApproveError'));
} finally {
setVerifyingId(null);
}
};
const handleRejectSiret = async (orgId: string) => {
if (!confirm(t('confirmReject'))) return;
try {
setVerifyingId(orgId);
const result = await rejectSiret(orgId);
alert(result.message);
await fetchOrganizations();
} catch (err: any) {
alert(err.message || t('siretRejectError'));
} finally {
setVerifyingId(null);
}
};
const openEditModal = (org: Organization) => {
setSelectedOrg(org);
setFormData({
name: org.name,
type: org.type,
scac: org.scac || '',
siren: org.siren || '',
siret: org.siret || '',
eori: org.eori || '',
contact_phone: org.contact_phone || '',
contact_email: org.contact_email || '',
address: {
street: org.address.street,
city: org.address.city,
state: org.address.state || '',
postalCode: org.address.postalCode,
country: org.address.country,
},
logoUrl: org.logoUrl || '',
isActive: org.isActive,
});
setFormError(null);
setFieldErrors({});
setShowEditModal(true);
};
const closeModal = () => {
setShowCreateModal(false);
setShowEditModal(false);
setSelectedOrg(null);
resetForm();
};
const getTypeLabel = (type: string) => {
const allowed = ['FREIGHT_FORWARDER', 'CARRIER', 'SHIPPER'];
if (allowed.includes(type)) return t(`types.${type}` as any);
return type.replace('_', ' ');
};
const inputClass = (hasError?: string) =>
`mt-1 block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none text-sm ${
hasError
? 'border-red-400 focus:border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:border-blue-500 focus:ring-blue-500'
}`;
if (loading) {
return (
<div className="flex items-center justify-center h-96">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
<p className="mt-4 text-gray-600">{t('loading')}</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
<PageHeader
title={t('title')}
description={t('subtitle')}
actions={
<button
onClick={() => setShowCreateModal(true)}
className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
>
{t('create')}
</button>
}
/>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
{error}
</div>
)}
{/* Organizations Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{organizations.map(org => (
<div key={org.id} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h3 className="text-lg font-semibold text-gray-900">{org.name}</h3>
<span
className={`inline-block mt-2 px-2 py-1 text-xs font-semibold rounded-full ${
org.type === 'FREIGHT_FORWARDER'
? 'bg-blue-100 text-blue-800'
: org.type === 'CARRIER'
? 'bg-green-100 text-green-800'
: 'bg-purple-100 text-purple-800'
}`}
>
{getTypeLabel(org.type)}
</span>
</div>
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
org.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}
>
{org.isActive ? t('active') : t('inactive')}
</span>
</div>
<div className="space-y-2 text-sm text-gray-600 mb-4">
{org.scac && (
<div>
<span className="font-medium">{t('scac')}:</span> {org.scac}
</div>
)}
{org.siren && (
<div>
<span className="font-medium">{t('siren')}:</span> {org.siren}
</div>
)}
<div className="flex items-center gap-2">
<span className="font-medium">{t('siret')}:</span>
{org.siret ? (
<>
<span>{org.siret}</span>
{org.siretVerified ? (
<span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full bg-green-100 text-green-800">
{t('verified')}
</span>
) : (
<span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">
{t('notVerified')}
</span>
)}
</>
) : (
<span className="text-gray-400">{t('notProvided')}</span>
)}
</div>
{org.contact_email && (
<div>
<span className="font-medium">{t('email')}:</span> {org.contact_email}
</div>
)}
<div>
<span className="font-medium">{t('location')}:</span> {org.address.city},{' '}
{org.address.country}
</div>
</div>
<div className="space-y-2">
<div className="flex space-x-2">
<button
onClick={() => openEditModal(org)}
className="flex-1 px-3 py-2 bg-blue-50 text-blue-700 rounded-md hover:bg-blue-100 transition-colors text-sm font-medium"
>
{t('edit')}
</button>
{org.siret && !org.siretVerified && (
<button
onClick={() => handleVerifySiret(org.id)}
disabled={verifyingId === org.id}
className="flex-1 px-3 py-2 bg-purple-50 text-purple-700 rounded-md hover:bg-purple-100 transition-colors text-sm font-medium disabled:opacity-50"
>
{verifyingId === org.id ? t('verifying') : t('verifyApi')}
</button>
)}
</div>
{(org.siret || org.siren) && (
<div className="flex space-x-2">
{!org.siretVerified ? (
<button
onClick={() => handleApproveSiret(org.id)}
disabled={verifyingId === org.id}
className="flex-1 px-3 py-2 bg-green-50 text-green-700 rounded-md hover:bg-green-100 transition-colors text-sm font-medium disabled:opacity-50"
>
{t('approveSiret')}
</button>
) : (
<button
onClick={() => handleRejectSiret(org.id)}
disabled={verifyingId === org.id}
className="flex-1 px-3 py-2 bg-red-50 text-red-700 rounded-md hover:bg-red-100 transition-colors text-sm font-medium disabled:opacity-50"
>
{t('rejectSiret')}
</button>
)}
</div>
)}
</div>
</div>
))}
</div>
{/* Create / Edit Modal */}
{(showCreateModal || showEditModal) && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto py-4">
<div className="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
<h2 className="text-xl font-bold mb-6">
{showCreateModal ? t('modal.createTitle') : t('modal.editTitle')}
</h2>
<form
onSubmit={showCreateModal ? handleCreate : handleUpdate}
noValidate
className="space-y-5"
>
{/* ── Informations générales ── */}
<section>
<h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{t('modal.sectionGeneral')}
</h3>
<div className="grid grid-cols-2 gap-4">
<div className="col-span-2">
<label className="block text-sm font-medium text-gray-700">
{t('modal.name')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.name}
onChange={e => {
setFormData({ ...formData, name: e.target.value });
setFieldErrors(prev => ({ ...prev, name: undefined }));
}}
minLength={2}
maxLength={200}
className={inputClass(fieldErrors.name)}
placeholder="Acme Freight Forwarding"
/>
<FieldError message={fieldErrors.name} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.type')} <span className="text-red-500">*</span>
</label>
{showCreateModal ? (
<select
value={formData.type}
onChange={e => handleTypeChange(e.target.value)}
className={inputClass()}
>
<option value="FREIGHT_FORWARDER">{t('types.FREIGHT_FORWARDER')}</option>
<option value="CARRIER">{t('types.CARRIER')}</option>
<option value="SHIPPER">{t('types.SHIPPER')}</option>
</select>
) : (
<div className="mt-1 flex items-center gap-2">
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
formData.type === 'FREIGHT_FORWARDER'
? 'bg-blue-100 text-blue-800'
: formData.type === 'CARRIER'
? 'bg-green-100 text-green-800'
: 'bg-purple-100 text-purple-800'
}`}
>
{getTypeLabel(formData.type)}
</span>
<span className="text-xs text-gray-400">{t('modal.typeReadOnly')}</span>
</div>
)}
</div>
{/* SCAC — création uniquement, visible en lecture seule en édition si CARRIER */}
{showCreateModal && formData.type === 'CARRIER' && (
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.scacLabel')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.scac}
onChange={e => {
const v = e.target.value.toUpperCase().replace(/[^A-Z]/g, '');
setFormData({ ...formData, scac: v });
setFieldErrors(prev => ({ ...prev, scac: undefined }));
}}
maxLength={4}
minLength={4}
className={inputClass(fieldErrors.scac)}
placeholder="MAEU"
/>
<FieldHint>{t('modal.scacHint')}</FieldHint>
<FieldError message={fieldErrors.scac} />
</div>
)}
{showEditModal && formData.type === 'CARRIER' && formData.scac && (
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.scacLabel')}
</label>
<div className="mt-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700 font-mono">
{formData.scac}
</div>
<FieldHint>{t('modal.typeReadOnly')}</FieldHint>
</div>
)}
</div>
</section>
{/* ── Identifiants légaux ── */}
<section>
<h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{t('modal.sectionLegal')}
</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.sirenLabel')}
</label>
<input
type="text"
value={formData.siren}
onChange={e => {
const v = e.target.value.replace(/\D/g, '').slice(0, 9);
setFormData({ ...formData, siren: v });
setFieldErrors(prev => ({ ...prev, siren: undefined }));
}}
maxLength={9}
className={inputClass(fieldErrors.siren)}
placeholder="123456789"
/>
<FieldHint>{t('modal.sirenHint')}</FieldHint>
<FieldError message={fieldErrors.siren} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.siretLabel')}
</label>
<input
type="text"
value={formData.siret}
onChange={e => {
const v = e.target.value.replace(/\D/g, '').slice(0, 14);
setFormData({ ...formData, siret: v });
setFieldErrors(prev => ({ ...prev, siret: undefined }));
}}
maxLength={14}
className={inputClass(fieldErrors.siret)}
placeholder="12345678901234"
/>
<FieldHint>{t('modal.siretHint')}</FieldHint>
<FieldError message={fieldErrors.siret} />
</div>
<div className="col-span-2">
<label className="block text-sm font-medium text-gray-700">
{t('modal.eoriLabel')}
</label>
<input
type="text"
value={formData.eori}
onChange={e => setFormData({ ...formData, eori: e.target.value })}
className={inputClass()}
placeholder="FR123456789"
/>
<FieldHint>{t('modal.eoriHint')}</FieldHint>
</div>
</div>
</section>
{/* ── Contact ── */}
<section>
<h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{t('modal.sectionContact')}
</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.contactEmail')}
</label>
<input
type="email"
value={formData.contact_email}
onChange={e => setFormData({ ...formData, contact_email: e.target.value })}
className={inputClass()}
placeholder="contact@exemple.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.contactPhone')}
</label>
<input
type="tel"
value={formData.contact_phone}
onChange={e => setFormData({ ...formData, contact_phone: e.target.value })}
className={inputClass()}
placeholder="+33 6 00 00 00 00"
/>
</div>
</div>
</section>
{/* ── Adresse ── */}
<section>
<h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{t('modal.sectionAddress')}
</h3>
<div className="grid grid-cols-2 gap-4">
<div className="col-span-2">
<label className="block text-sm font-medium text-gray-700">
{t('modal.street')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.address.street}
onChange={e => {
setFormData({ ...formData, address: { ...formData.address, street: e.target.value } });
setFieldErrors(prev => ({ ...prev, street: undefined }));
}}
className={inputClass(fieldErrors.street)}
placeholder="123 Rue de la République"
/>
<FieldError message={fieldErrors.street} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.city')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.address.city}
onChange={e => {
setFormData({ ...formData, address: { ...formData.address, city: e.target.value } });
setFieldErrors(prev => ({ ...prev, city: undefined }));
}}
className={inputClass(fieldErrors.city)}
placeholder="Paris"
/>
<FieldError message={fieldErrors.city} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.postalCode')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.address.postalCode}
onChange={e => {
setFormData({ ...formData, address: { ...formData.address, postalCode: e.target.value } });
setFieldErrors(prev => ({ ...prev, postalCode: undefined }));
}}
className={inputClass(fieldErrors.postalCode)}
placeholder="75001"
/>
<FieldError message={fieldErrors.postalCode} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.state')}
</label>
<input
type="text"
value={formData.address.state}
onChange={e =>
setFormData({ ...formData, address: { ...formData.address, state: e.target.value } })
}
className={inputClass()}
placeholder="Île-de-France"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.country')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.address.country}
onChange={e => {
const v = e.target.value.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2);
setFormData({ ...formData, address: { ...formData.address, country: v } });
setFieldErrors(prev => ({ ...prev, country: undefined }));
}}
maxLength={2}
minLength={2}
className={inputClass(fieldErrors.country)}
placeholder="FR"
/>
<FieldHint>{t('modal.countryHint')}</FieldHint>
<FieldError message={fieldErrors.country} />
</div>
</div>
</section>
{/* ── Autres ── */}
<section>
<h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{t('modal.sectionOther')}
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700">
{t('modal.logoUrl')}
</label>
<input
type="url"
value={formData.logoUrl}
onChange={e => setFormData({ ...formData, logoUrl: e.target.value })}
className={inputClass()}
placeholder="https://exemple.com/logo.png"
/>
</div>
{showEditModal && (
<div className="flex items-center gap-3">
<input
id="isActive"
type="checkbox"
checked={formData.isActive}
onChange={e => setFormData({ ...formData, isActive: e.target.checked })}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="isActive" className="text-sm font-medium text-gray-700">
{t('modal.isActive')}
</label>
</div>
)}
</div>
</section>
{/* Erreur globale */}
{formError && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
{formError}
</div>
)}
<div className="flex justify-end space-x-3 pt-2 border-t border-gray-100">
<button
type="button"
onClick={closeModal}
className="px-4 py-2 border border-gray-300 rounded-md text-sm text-gray-700 hover:bg-gray-50 transition-colors"
>
{t('modal.cancel')}
</button>
<button
type="submit"
disabled={submitting}
className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
>
{submitting
? t('modal.saving')
: showCreateModal
? t('modal.create')
: t('modal.update')}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}