275 lines
9.9 KiB
JavaScript
275 lines
9.9 KiB
JavaScript
// Module ES6 pour la création d'entités depuis le modal d'événement
|
|
import { apiFetch } from './agenda-api.js';
|
|
import { notifyError, notifySuccess } from './agenda-notifications.js';
|
|
import { openSubModal } from './agenda-modal.js';
|
|
import { populateSelects } from './agenda-modal-select.js';
|
|
|
|
// Configuration des entités
|
|
const ENTITY_CONFIG = {
|
|
beneficiaire: {
|
|
modalId: 'createBeneficiaireModal',
|
|
formId: 'createBeneficiaireForm',
|
|
saveBtnId: 'saveBeneficiaireBtn',
|
|
selectId: 'id_beneficiaire',
|
|
endpoint: 'agenda/beneficiaires',
|
|
displayField: 'nom',
|
|
linkId: 'createBeneficiaireLink'
|
|
},
|
|
intervenant: {
|
|
modalId: 'createIntervenantModal',
|
|
formId: 'createIntervenantForm',
|
|
saveBtnId: 'saveIntervenantBtn',
|
|
selectId: 'id_intervenant',
|
|
endpoint: 'agenda/intervenants',
|
|
displayField: 'nom',
|
|
linkId: 'createIntervenantLink'
|
|
},
|
|
traducteur: {
|
|
modalId: 'createTraducteurModal',
|
|
formId: 'createTraducteurForm',
|
|
saveBtnId: 'saveTraducteurBtn',
|
|
selectId: 'id_traducteur',
|
|
endpoint: 'agenda/traducteurs',
|
|
displayField: 'nom',
|
|
linkId: 'createTraducteurLink'
|
|
},
|
|
local: {
|
|
modalId: 'createLocalModal',
|
|
formId: 'createLocalForm',
|
|
saveBtnId: 'saveLocalBtn',
|
|
selectId: 'id_local',
|
|
endpoint: 'agenda/locaux',
|
|
displayField: 'nom',
|
|
linkId: 'createLocalLink'
|
|
}
|
|
};
|
|
|
|
// Variable pour suivre si les créateurs d'entités ont déjà été initialisés
|
|
let entityCreatorsInitialized = false;
|
|
|
|
// Initialisation des modals de création d'entités
|
|
export function initializeEntityCreators() {
|
|
// Éviter la double initialisation
|
|
if (entityCreatorsInitialized) {
|
|
// console.log('Créateurs d\'entités déjà initialisés, ignoré.');
|
|
return;
|
|
}
|
|
|
|
// console.log('Initialisation des créateurs d\'entités...');
|
|
|
|
// Ajout des event listeners pour chaque type d'entité
|
|
Object.entries(ENTITY_CONFIG).forEach(([entityType, config]) => {
|
|
const createLink = document.getElementById(config.linkId);
|
|
const saveBtn = document.getElementById(config.saveBtnId);
|
|
|
|
if (createLink) {
|
|
// Supprimer les anciens event listeners s'ils existent
|
|
createLink.removeEventListener('click', createLink._entityCreatorHandler);
|
|
|
|
// Créer un nouveau handler et le stocker pour pouvoir le supprimer plus tard
|
|
createLink._entityCreatorHandler = (e) => {
|
|
// console.log('click sur le lien de création d\'entité');
|
|
e.preventDefault();
|
|
openCreateEntityModal(entityType);
|
|
};
|
|
|
|
createLink.addEventListener('click', createLink._entityCreatorHandler);
|
|
}
|
|
|
|
if (saveBtn) {
|
|
// Supprimer les anciens event listeners s'ils existent
|
|
saveBtn.removeEventListener('click', saveBtn._entityCreatorHandler);
|
|
|
|
// Créer un nouveau handler et le stocker pour pouvoir le supprimer plus tard
|
|
saveBtn._entityCreatorHandler = () => handleEntityCreation(entityType);
|
|
|
|
saveBtn.addEventListener('click', saveBtn._entityCreatorHandler);
|
|
}
|
|
});
|
|
|
|
entityCreatorsInitialized = true;
|
|
}
|
|
|
|
// Ouvre le modal de création d'une entité
|
|
function openCreateEntityModal(entityType) {
|
|
const config = ENTITY_CONFIG[entityType];
|
|
if (!config) {
|
|
console.error(`Configuration non trouvée pour l'entité: ${entityType}`);
|
|
return;
|
|
}
|
|
|
|
// Utiliser la fonction générique pour ouvrir la sous-modale
|
|
openSubModal(
|
|
config.modalId,
|
|
// Callback avant ouverture : réinitialiser le formulaire
|
|
(subModal) => {
|
|
const form = document.getElementById(config.formId);
|
|
if (form) {
|
|
form.reset();
|
|
}
|
|
// Les selects sont maintenant initialisés automatiquement par jQuery('.select2').select2()
|
|
}
|
|
);
|
|
}
|
|
|
|
// Les selects sont maintenant initialisés automatiquement par jQuery('.select2').select2()
|
|
// Les options sont générées en PHP dans le template
|
|
|
|
// Gère la création d'une entité
|
|
async function handleEntityCreation(entityType) {
|
|
const config = ENTITY_CONFIG[entityType];
|
|
if (!config) {
|
|
console.error(`Configuration non trouvée pour l'entité: ${entityType}`);
|
|
return;
|
|
}
|
|
|
|
const form = document.getElementById(config.formId);
|
|
if (!form) {
|
|
console.error(`Formulaire non trouvé: ${config.formId}`);
|
|
return;
|
|
}
|
|
|
|
// Validation du formulaire
|
|
if (!form.checkValidity()) {
|
|
form.reportValidity();
|
|
return;
|
|
}
|
|
|
|
// Récupération des données du formulaire
|
|
const formData = new FormData(form);
|
|
const data = Object.fromEntries(formData.entries());
|
|
|
|
// Gestion spéciale pour les selects multiples
|
|
if (entityType === 'traducteur') {
|
|
const languesSelect = document.getElementById('traducteur_langues');
|
|
if (languesSelect && window.jQuery) {
|
|
const selectedLangues = jQuery(languesSelect).select2('data').map(item => item.id);
|
|
data.langues_parlees = selectedLangues.join('|');
|
|
}
|
|
} else if (entityType === 'intervenant') {
|
|
const departementsSelect = document.getElementById('intervenant_departements');
|
|
if (departementsSelect && window.jQuery) {
|
|
const selectedDepartements = jQuery(departementsSelect).select2('data').map(item => item.id);
|
|
data.departements_ids = selectedDepartements.join('|');
|
|
}
|
|
}
|
|
|
|
try {
|
|
// console.log(`Création de l'entité ${entityType}:`, data);
|
|
|
|
// Appel API pour créer l'entité
|
|
const response = await apiFetch(config.endpoint, {
|
|
method: 'POST',
|
|
body: JSON.stringify(data)
|
|
});
|
|
|
|
// console.log(`Entité ${entityType} créée:`, response);
|
|
|
|
// Fermer le modal de création
|
|
const modal = document.getElementById(config.modalId);
|
|
if (modal && window.bootstrap && window.bootstrap.Modal) {
|
|
const bsModal = window.bootstrap.Modal.getInstance(modal);
|
|
if (bsModal) {
|
|
bsModal.hide();
|
|
}
|
|
}
|
|
|
|
// Attendre que le modal se ferme avant de rouvrir le modal principal
|
|
setTimeout(async () => {
|
|
// Ajouter la nouvelle entité au select correspondant
|
|
await addEntityToSelect(entityType, response);
|
|
|
|
// Rafraîchir les selects pour mettre à jour les disponibilités
|
|
await populateSelects();
|
|
|
|
// Rouvrir le modal principal d'événement avec les données préservées
|
|
const eventModal = document.getElementById('eventModal');
|
|
if (eventModal && window.bootstrap && window.bootstrap.Modal) {
|
|
const newEventModal = new window.bootstrap.Modal(eventModal);
|
|
newEventModal.show();
|
|
}
|
|
|
|
notifySuccess(`${entityType.charAt(0).toUpperCase() + entityType.slice(1)} créé avec succès`);
|
|
}, 300);
|
|
|
|
} catch (error) {
|
|
console.error(`Erreur lors de la création de l'entité ${entityType}:`, error);
|
|
notifyError(`Erreur lors de la création du ${entityType}: ${error.message || 'Erreur inconnue'}`);
|
|
}
|
|
}
|
|
|
|
// Ajoute une nouvelle entité au select correspondant
|
|
async function addEntityToSelect(entityType, entityData) {
|
|
const config = ENTITY_CONFIG[entityType];
|
|
if (!config) return;
|
|
|
|
const select = document.getElementById(config.selectId);
|
|
if (!select) return;
|
|
|
|
// Créer l'option pour la nouvelle entité
|
|
const option = document.createElement('option');
|
|
option.value = entityData.id;
|
|
|
|
// Construire le texte d'affichage enrichi selon le type d'entité
|
|
let displayText = '';
|
|
|
|
switch (entityType) {
|
|
case 'beneficiaire':
|
|
displayText = `${entityData.prenom || ''} ${entityData.nom || ''}`.trim();
|
|
if (entityData.email) {
|
|
displayText += ` (${entityData.email})`;
|
|
}
|
|
break;
|
|
|
|
case 'intervenant':
|
|
displayText = `${entityData.prenom || ''} ${entityData.nom || ''}`.trim();
|
|
if (entityData.specialite) {
|
|
displayText += ` - ${entityData.specialite}`;
|
|
}
|
|
if (entityData.email) {
|
|
displayText += ` (${entityData.email})`;
|
|
}
|
|
break;
|
|
|
|
case 'traducteur':
|
|
displayText = `${entityData.prenom || ''} ${entityData.nom || ''}`.trim();
|
|
if (entityData.langues_parlees) {
|
|
displayText += ` - ${entityData.langues_parlees}`;
|
|
}
|
|
if (entityData.email) {
|
|
displayText += ` (${entityData.email})`;
|
|
}
|
|
break;
|
|
|
|
case 'local':
|
|
displayText = entityData.nom || '';
|
|
if (entityData.capacite) {
|
|
displayText += ` (${entityData.capacite} places)`;
|
|
}
|
|
if (entityData.adresse) {
|
|
displayText += ` - ${entityData.adresse}`;
|
|
}
|
|
break;
|
|
|
|
default:
|
|
displayText = entityData[config.displayField] || entityData.nom || '';
|
|
if (entityData.prenom) {
|
|
displayText += ` ${entityData.prenom}`;
|
|
}
|
|
}
|
|
|
|
option.textContent = displayText;
|
|
|
|
// Ajouter l'option au select
|
|
select.appendChild(option);
|
|
|
|
// Sélectionner automatiquement la nouvelle entité
|
|
select.value = entityData.id;
|
|
|
|
// console.log(`Entité ${entityType} ajoutée au select ${config.selectId}:`, entityData);
|
|
}
|
|
|
|
// Fonction utilitaire pour obtenir la configuration d'une entité
|
|
export function getEntityConfig(entityType) {
|
|
return ENTITY_CONFIG[entityType];
|
|
}
|