Files
btpxpress-frontend/app/(main)/stock/fournisseurs/page.tsx

873 lines
36 KiB
TypeScript
Executable File

'use client';
import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Dialog } from 'primereact/dialog';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Dropdown } from 'primereact/dropdown';
import { InputTextarea } from 'primereact/inputtextarea';
import { Checkbox } from 'primereact/checkbox';
import { Badge } from 'primereact/badge';
import { Panel } from 'primereact/panel';
import { Rating } from 'primereact/rating';
import fournisseurService from '../../../../services/fournisseurService';
import type { Fournisseur } from '../../../../types/btp-extended';
import {
ActionButtonGroup,
ViewButton,
EditButton,
DeleteButton,
ActionButton
} from '../../../../components/ui/ActionButton';
interface FournisseurFormData {
id?: number;
nom: string;
contact?: string;
telephone?: string;
email?: string;
adresse?: string;
ville?: string;
codePostal?: string;
pays?: string;
typeFournisseur: 'MATERIAU' | 'EQUIPEMENT' | 'SERVICE' | 'SOUS_TRAITANT';
specialites?: string;
numeroTVA?: string;
siret?: string;
delaiLivraison?: number;
conditionsPaiement?: string;
evaluationQualite?: number;
actif: boolean;
notes?: string;
}
const FournisseursPage = () => {
const [fournisseurs, setFournisseurs] = useState<Fournisseur[]>([]);
const [loading, setLoading] = useState(true);
const [globalFilter, setGlobalFilter] = useState('');
const [selectedFournisseurs, setSelectedFournisseurs] = useState<Fournisseur[]>([]);
const [fournisseurDialog, setFournisseurDialog] = useState(false);
const [deleteFournisseurDialog, setDeleteFournisseurDialog] = useState(false);
const [commandesDialog, setCommandesDialog] = useState(false);
const [selectedFournisseurCommandes, setSelectedFournisseurCommandes] = useState<any[]>([]);
const [currentFournisseur, setCurrentFournisseur] = useState<Fournisseur | null>(null);
const [fournisseur, setFournisseur] = useState<FournisseurFormData>({
nom: '',
contact: '',
telephone: '',
email: '',
adresse: '',
ville: '',
codePostal: '',
pays: 'France',
typeFournisseur: 'MATERIAU',
specialites: '',
numeroTVA: '',
siret: '',
delaiLivraison: 7,
conditionsPaiement: '',
evaluationQualite: 5,
actif: true,
notes: ''
});
const [submitted, setSubmitted] = useState(false);
const toast = useRef<Toast>(null);
const dt = useRef<DataTable<Fournisseur[]>>(null);
const typesFournisseur = [
{ label: 'Matériaux', value: 'MATERIAU' },
{ label: 'Équipement', value: 'EQUIPEMENT' },
{ label: 'Service', value: 'SERVICE' },
{ label: 'Sous-traitant', value: 'SOUS_TRAITANT' }
];
const delaisLivraison = [
{ label: '1-3 jours', value: 3 },
{ label: '1 semaine', value: 7 },
{ label: '2 semaines', value: 14 },
{ label: '1 mois', value: 30 },
{ label: 'Sur mesure', value: 0 }
];
useEffect(() => {
loadFournisseurs();
}, []);
const loadFournisseurs = async () => {
try {
setLoading(true);
const data = await fournisseurService.getAll();
setFournisseurs(data);
} catch (error) {
console.error('Erreur lors du chargement des fournisseurs:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de charger les fournisseurs',
life: 3000
});
} finally {
setLoading(false);
}
};
const openNew = () => {
setFournisseur({
nom: '',
contact: '',
telephone: '',
email: '',
adresse: '',
ville: '',
codePostal: '',
pays: 'France',
typeFournisseur: 'MATERIAU',
specialites: '',
numeroTVA: '',
siret: '',
delaiLivraison: 7,
conditionsPaiement: '',
evaluationQualite: 5,
actif: true,
notes: ''
});
setSubmitted(false);
setFournisseurDialog(true);
};
const hideDialog = () => {
setSubmitted(false);
setFournisseurDialog(false);
};
const hideDeleteFournisseurDialog = () => {
setDeleteFournisseurDialog(false);
};
const saveFournisseur = async () => {
setSubmitted(true);
if (fournisseur.nom.trim()) {
try {
let updatedFournisseurs = [...fournisseurs];
if (fournisseur.id) {
// Mise à jour
const updatedFournisseur = await fournisseurService.update(fournisseur.id, fournisseur);
const index = fournisseurs.findIndex(f => f.id === fournisseur.id);
updatedFournisseurs[index] = updatedFournisseur;
toast.current?.show({
severity: 'success',
summary: 'Succès',
detail: 'Fournisseur mis à jour',
life: 3000
});
} else {
// Création
const newFournisseur = await fournisseurService.create(fournisseur);
updatedFournisseurs.push(newFournisseur);
toast.current?.show({
severity: 'success',
summary: 'Succès',
detail: 'Fournisseur créé',
life: 3000
});
}
setFournisseurs(updatedFournisseurs);
setFournisseurDialog(false);
setFournisseur({
nom: '',
contact: '',
telephone: '',
email: '',
adresse: '',
ville: '',
codePostal: '',
pays: 'France',
typeFournisseur: 'MATERIAU',
specialites: '',
numeroTVA: '',
siret: '',
delaiLivraison: 7,
conditionsPaiement: '',
evaluationQualite: 5,
actif: true,
notes: ''
});
} catch (error: any) {
console.error('Erreur lors de la sauvegarde:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de sauvegarder le fournisseur',
life: 3000
});
}
}
};
const editFournisseur = (fournisseur: Fournisseur) => {
setFournisseur({
id: fournisseur.id,
nom: fournisseur.nom,
contact: fournisseur.contact || '',
telephone: fournisseur.telephone || '',
email: fournisseur.email || '',
adresse: fournisseur.adresse || '',
ville: fournisseur.ville || '',
codePostal: fournisseur.codePostal || '',
pays: fournisseur.pays || 'France',
typeFournisseur: fournisseur.typeFournisseur || 'MATERIAU',
specialites: fournisseur.specialites || '',
numeroTVA: fournisseur.numeroTVA || '',
siret: fournisseur.siret || '',
delaiLivraison: fournisseur.delaiLivraison || 7,
conditionsPaiement: fournisseur.conditionsPaiement || '',
evaluationQualite: fournisseur.evaluationQualite || 5,
actif: fournisseur.actif !== undefined ? fournisseur.actif : true,
notes: fournisseur.notes || ''
});
setFournisseurDialog(true);
};
const confirmDeleteFournisseur = (fournisseur: Fournisseur) => {
setFournisseur(fournisseur as FournisseurFormData);
setDeleteFournisseurDialog(true);
};
const deleteFournisseur = async () => {
try {
if (fournisseur.id) {
await fournisseurService.delete(fournisseur.id);
let updatedFournisseurs = fournisseurs.filter(f => f.id !== fournisseur.id);
setFournisseurs(updatedFournisseurs);
setDeleteFournisseurDialog(false);
toast.current?.show({
severity: 'success',
summary: 'Succès',
detail: 'Fournisseur supprimé',
life: 3000
});
}
} catch (error) {
console.error('Erreur lors de la suppression:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de supprimer le fournisseur',
life: 3000
});
}
};
const voirCommandesFournisseur = async (fournisseur: Fournisseur) => {
try {
setCurrentFournisseur(fournisseur);
const commandes = await fournisseurService.getCommandes(fournisseur.id!);
setSelectedFournisseurCommandes(commandes || []);
setCommandesDialog(true);
} catch (error) {
console.error('Erreur lors du chargement des commandes:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de charger les commandes du fournisseur',
life: 3000
});
}
};
const exportCSV = () => {
dt.current?.exportCSV();
};
const onInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, name: string) => {
const val = (e.target && e.target.value) || '';
let _fournisseur = { ...fournisseur };
(_fournisseur as any)[name] = val;
setFournisseur(_fournisseur);
};
const onDropdownChange = (e: any, name: string) => {
let _fournisseur = { ...fournisseur };
(_fournisseur as any)[name] = e.value;
setFournisseur(_fournisseur);
};
const onNumberChange = (e: any, name: string) => {
let _fournisseur = { ...fournisseur };
(_fournisseur as any)[name] = e.value;
setFournisseur(_fournisseur);
};
const onCheckboxChange = (e: any, name: string) => {
let _fournisseur = { ...fournisseur };
(_fournisseur as any)[name] = e.checked;
setFournisseur(_fournisseur);
};
const leftToolbarTemplate = () => {
return (
<div className="my-2">
<Button
label="Nouveau"
icon="pi pi-plus"
severity="success"
className="mr-2"
onClick={openNew}
/>
<Button
label="Supprimer"
icon="pi pi-trash"
severity="danger"
onClick={() => {/* TODO: bulk delete */}}
disabled={!selectedFournisseurs || selectedFournisseurs.length === 0}
/>
</div>
);
};
const rightToolbarTemplate = () => {
return (
<Button
label="Exporter"
icon="pi pi-upload"
severity="help"
onClick={exportCSV}
/>
);
};
const actionBodyTemplate = (rowData: Fournisseur) => {
return (
<ActionButtonGroup>
<ActionButton
icon="pi pi-shopping-cart"
tooltip="Voir les commandes"
onClick={() => voirCommandesFournisseur(rowData)}
color="blue"
/>
<EditButton
tooltip="Modifier"
onClick={() => editFournisseur(rowData)}
/>
<DeleteButton
tooltip="Supprimer"
onClick={() => confirmDeleteFournisseur(rowData)}
/>
</ActionButtonGroup>
);
};
const typeFournisseurBodyTemplate = (rowData: Fournisseur) => {
const getSeverity = (type: string) => {
switch (type) {
case 'MATERIAU': return 'info';
case 'EQUIPEMENT': return 'warning';
case 'SERVICE': return 'success';
case 'SOUS_TRAITANT': return 'help';
default: return 'info';
}
};
const getLabel = (type: string) => {
switch (type) {
case 'MATERIAU': return 'Matériaux';
case 'EQUIPEMENT': return 'Équipement';
case 'SERVICE': return 'Service';
case 'SOUS_TRAITANT': return 'Sous-traitant';
default: return type;
}
};
return (
<Tag
value={getLabel(rowData.typeFournisseur || 'MATERIAU')}
severity={getSeverity(rowData.typeFournisseur || 'MATERIAU')}
/>
);
};
const contactBodyTemplate = (rowData: Fournisseur) => {
return (
<div className="flex flex-column">
{rowData.contact && (
<div className="flex align-items-center mb-1">
<i className="pi pi-user mr-2 text-color-secondary"></i>
<span className="text-sm font-medium">{rowData.contact}</span>
</div>
)}
{rowData.email && (
<div className="flex align-items-center mb-1">
<i className="pi pi-envelope mr-2 text-color-secondary"></i>
<span className="text-sm">{rowData.email}</span>
</div>
)}
{rowData.telephone && (
<div className="flex align-items-center">
<i className="pi pi-phone mr-2 text-color-secondary"></i>
<span className="text-sm">{rowData.telephone}</span>
</div>
)}
</div>
);
};
const evaluationBodyTemplate = (rowData: Fournisseur) => {
return (
<div className="flex align-items-center">
<Rating
value={rowData.evaluationQualite || 0}
readOnly
cancel={false}
className="mr-2"
/>
<span className="text-sm">({rowData.evaluationQualite || 0}/5)</span>
</div>
);
};
const delaiBodyTemplate = (rowData: Fournisseur) => {
const delai = rowData.delaiLivraison || 0;
let severity: 'success' | 'warning' | 'danger' = 'success';
let label = '';
if (delai === 0) {
label = 'Sur mesure';
severity = 'warning';
} else if (delai <= 3) {
label = `${delai} jour(s)`;
severity = 'success';
} else if (delai <= 7) {
label = `${delai} jours`;
severity = 'success';
} else if (delai <= 14) {
label = `${delai} jours`;
severity = 'warning';
} else {
label = `${delai} jours`;
severity = 'danger';
}
return <Badge value={label} severity={severity} />;
};
const statutBodyTemplate = (rowData: Fournisseur) => {
return (
<Tag
value={rowData.actif ? 'Actif' : 'Inactif'}
severity={rowData.actif ? 'success' : 'danger'}
/>
);
};
const nomFournisseurBodyTemplate = (rowData: Fournisseur) => {
return (
<div className="flex flex-column">
<span className="font-medium">{rowData.nom}</span>
{rowData.specialites && (
<span className="text-sm text-color-secondary">{rowData.specialites}</span>
)}
</div>
);
};
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Gestion des Fournisseurs</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText
type="search"
placeholder="Rechercher..."
onInput={(e) => setGlobalFilter(e.currentTarget.value)}
/>
</span>
</div>
);
const fournisseurDialogFooter = (
<>
<Button label="Annuler" icon="pi pi-times" text onClick={hideDialog} />
<Button label="Sauvegarder" icon="pi pi-check" text onClick={saveFournisseur} />
</>
);
const deleteFournisseurDialogFooter = (
<>
<Button label="Non" icon="pi pi-times" text onClick={hideDeleteFournisseurDialog} />
<Button label="Oui" icon="pi pi-check" text onClick={deleteFournisseur} />
</>
);
const commandesDialogFooter = (
<Button label="Fermer" icon="pi pi-times" onClick={() => setCommandesDialog(false)} />
);
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('fr-FR', {
style: 'currency',
currency: 'EUR'
}).format(amount);
};
const formatDate = (dateString: string | Date | null) => {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('fr-FR');
};
return (
<div className="grid">
<div className="col-12">
<Card>
<Toast ref={toast} />
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />
<DataTable
ref={dt}
value={fournisseurs}
selection={selectedFournisseurs}
onSelectionChange={(e) => setSelectedFournisseurs(e.value)}
dataKey="id"
paginator
rows={10}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} fournisseurs"
globalFilter={globalFilter}
emptyMessage="Aucun fournisseur trouvé."
header={header}
responsiveLayout="scroll"
loading={loading}
>
<Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
<Column header="Nom" body={nomFournisseurBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="typeFournisseur" header="Type" body={typeFournisseurBodyTemplate} sortable headerStyle={{ minWidth: '8rem' }} />
<Column header="Contact" body={contactBodyTemplate} headerStyle={{ minWidth: '14rem' }} />
<Column field="ville" header="Ville" sortable headerStyle={{ minWidth: '10rem' }} />
<Column header="Délai livraison" body={delaiBodyTemplate} headerStyle={{ minWidth: '8rem' }} />
<Column header="Évaluation" body={evaluationBodyTemplate} headerStyle={{ minWidth: '10rem' }} />
<Column field="actif" header="Statut" body={statutBodyTemplate} sortable headerStyle={{ minWidth: '8rem' }} />
<Column body={actionBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
</DataTable>
<Dialog
visible={fournisseurDialog}
style={{ width: '700px' }}
header="Détails du Fournisseur"
modal
className="p-fluid"
footer={fournisseurDialogFooter}
onHide={hideDialog}
>
<div className="formgrid grid">
<div className="field col-12">
<label htmlFor="nom">Nom du fournisseur</label>
<InputText
id="nom"
value={fournisseur.nom}
onChange={(e) => onInputChange(e, 'nom')}
required
className={submitted && !fournisseur.nom ? 'p-invalid' : ''}
/>
{submitted && !fournisseur.nom && <small className="p-invalid">Le nom est requis.</small>}
</div>
<div className="field col-12 md:col-6">
<label htmlFor="typeFournisseur">Type de fournisseur</label>
<Dropdown
id="typeFournisseur"
value={fournisseur.typeFournisseur}
options={typesFournisseur}
onChange={(e) => onDropdownChange(e, 'typeFournisseur')}
placeholder="Sélectionnez un type"
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="contact">Personne de contact</label>
<InputText
id="contact"
value={fournisseur.contact}
onChange={(e) => onInputChange(e, 'contact')}
/>
</div>
<div className="field col-12">
<label htmlFor="specialites">Spécialités</label>
<InputText
id="specialites"
value={fournisseur.specialites}
onChange={(e) => onInputChange(e, 'specialites')}
placeholder="Ex: Béton, Acier, Isolation..."
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="telephone">Téléphone</label>
<InputText
id="telephone"
value={fournisseur.telephone}
onChange={(e) => onInputChange(e, 'telephone')}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="email">Email</label>
<InputText
id="email"
value={fournisseur.email}
onChange={(e) => onInputChange(e, 'email')}
type="email"
/>
</div>
<div className="field col-12">
<label htmlFor="adresse">Adresse</label>
<InputTextarea
id="adresse"
value={fournisseur.adresse}
onChange={(e) => onInputChange(e, 'adresse')}
rows={2}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="ville">Ville</label>
<InputText
id="ville"
value={fournisseur.ville}
onChange={(e) => onInputChange(e, 'ville')}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="codePostal">Code postal</label>
<InputText
id="codePostal"
value={fournisseur.codePostal}
onChange={(e) => onInputChange(e, 'codePostal')}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="pays">Pays</label>
<InputText
id="pays"
value={fournisseur.pays}
onChange={(e) => onInputChange(e, 'pays')}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="delaiLivraison">Délai de livraison</label>
<Dropdown
id="delaiLivraison"
value={fournisseur.delaiLivraison}
options={delaisLivraison}
onChange={(e) => onDropdownChange(e, 'delaiLivraison')}
placeholder="Sélectionnez un délai"
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="evaluationQualite">Évaluation qualité (1-5)</label>
<Rating
value={fournisseur.evaluationQualite}
onChange={(e) => onNumberChange(e, 'evaluationQualite')}
cancel={false}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="numeroTVA">Numéro TVA</label>
<InputText
id="numeroTVA"
value={fournisseur.numeroTVA}
onChange={(e) => onInputChange(e, 'numeroTVA')}
/>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="siret">SIRET</label>
<InputText
id="siret"
value={fournisseur.siret}
onChange={(e) => onInputChange(e, 'siret')}
/>
</div>
<div className="field col-12">
<label htmlFor="conditionsPaiement">Conditions de paiement</label>
<InputText
id="conditionsPaiement"
value={fournisseur.conditionsPaiement}
onChange={(e) => onInputChange(e, 'conditionsPaiement')}
placeholder="Ex: 30 jours net, 2% escompte 10 jours..."
/>
</div>
<div className="field col-12">
<label htmlFor="notes">Notes</label>
<InputTextarea
id="notes"
value={fournisseur.notes}
onChange={(e) => onInputChange(e, 'notes')}
rows={3}
/>
</div>
<div className="field col-12">
<div className="flex align-items-center">
<Checkbox
id="actif"
checked={fournisseur.actif}
onChange={(e) => onCheckboxChange(e, 'actif')}
/>
<label htmlFor="actif" className="ml-2">Fournisseur actif</label>
</div>
</div>
</div>
</Dialog>
<Dialog
visible={deleteFournisseurDialog}
style={{ width: '450px' }}
header="Confirmer"
modal
footer={deleteFournisseurDialogFooter}
onHide={hideDeleteFournisseurDialog}
>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{fournisseur && (
<span>
Êtes-vous sûr de vouloir supprimer le fournisseur <b>{fournisseur.nom}</b> ?
</span>
)}
</div>
</Dialog>
{/* Dialog des commandes du fournisseur */}
<Dialog
visible={commandesDialog}
style={{ width: '90vw', height: '80vh' }}
header={`Commandes - ${currentFournisseur?.nom}`}
modal
className="p-fluid"
footer={commandesDialogFooter}
onHide={() => setCommandesDialog(false)}
maximizable
>
<div className="grid mb-3">
<div className="col-12 md:col-3">
<Card>
<div className="text-center">
<div className="text-2xl font-bold text-blue-500">{selectedFournisseurCommandes.length}</div>
<div className="text-color-secondary">Total commandes</div>
</div>
</Card>
</div>
<div className="col-12 md:col-3">
<Card>
<div className="text-center">
<div className="text-2xl font-bold text-green-500">
{selectedFournisseurCommandes.filter(c => c.statut === 'LIVREE').length}
</div>
<div className="text-color-secondary">Livrées</div>
</div>
</Card>
</div>
<div className="col-12 md:col-3">
<Card>
<div className="text-center">
<div className="text-2xl font-bold text-orange-500">
{selectedFournisseurCommandes.filter(c => c.statut === 'EN_COURS').length}
</div>
<div className="text-color-secondary">En cours</div>
</div>
</Card>
</div>
<div className="col-12 md:col-3">
<Card>
<div className="text-center">
<div className="text-2xl font-bold text-cyan-500">
{formatCurrency(selectedFournisseurCommandes.reduce((sum, c) => sum + (c.montantTotal || 0), 0))}
</div>
<div className="text-color-secondary">CA Total</div>
</div>
</Card>
</div>
</div>
<DataTable
value={selectedFournisseurCommandes}
paginator
rows={10}
dataKey="id"
className="datatable-responsive"
emptyMessage="Aucune commande pour ce fournisseur"
responsiveLayout="scroll"
>
<Column field="numero" header="N° Commande" sortable style={{ minWidth: '10rem' }} />
<Column
field="dateCommande"
header="Date commande"
body={(rowData) => formatDate(rowData.dateCommande)}
sortable
style={{ minWidth: '10rem' }}
/>
<Column
field="dateLivraisonPrevue"
header="Livraison prévue"
body={(rowData) => formatDate(rowData.dateLivraisonPrevue)}
sortable
style={{ minWidth: '10rem' }}
/>
<Column
header="Statut"
body={(rowData) => {
const getSeverity = (statut: string) => {
switch (statut) {
case 'EN_ATTENTE': return 'warning';
case 'EN_COURS': return 'info';
case 'LIVREE': return 'success';
case 'ANNULEE': return 'danger';
default: return 'info';
}
};
return (
<Tag
value={rowData.statut}
severity={getSeverity(rowData.statut)}
/>
);
}}
style={{ minWidth: '8rem' }}
/>
<Column
header="Montant"
body={(rowData) => formatCurrency(rowData.montantTotal || 0)}
style={{ minWidth: '8rem' }}
/>
<Column field="chantier.nom" header="Chantier" style={{ minWidth: '12rem' }} />
</DataTable>
</Dialog>
</Card>
</div>
</div>
);
};
export default FournisseursPage;