function initSubmenuForm() { // Accéder aux informations stockées du parcours const parcours = JSON.parse(sessionStorage.getItem('parcours')); } // Exposer initSubmenuForm globalement pour y accéder depuis l'extérieur window.initSubmenuForm = initSubmenuForm;// Module IIFE pour éviter la pollution de l'espace global (function() { // Variables globales du module let parcours, contrat, client, intermediaire; //Variables pour les modales let commentaire = ''; // Initialisation des tag pour select var tagAnimauxVivants = false; var tagVehiculeTransporte = false; //Variables pour extensions var extPopulate // Initialisation du formulaire et des données function init() { // Materialize init select var select = document.querySelectorAll('select'); M.FormSelect.init(select); // Materialize init Modal var modals = document.querySelectorAll('.modal'); M.Modal.init(modals, {'dismissible': false}); // Accéder aux informations stockées du parcours parcours = JSON.parse(sessionStorage.getItem('parcours')); contrat = JSON.parse(sessionStorage.getItem('contrat')); client = contrat?.["@expand"]?.client || null; intermediaire = contrat?.["@expand"]?.intermediaire || null; tppc = contrat?.["@expand"]?.enCours || null; projet = tppc?.["@expand"]?.projet || null; tarif = tppc?.["@expand"]?.tarif || null; console.log("Initialisation pour formulaire projet :", parcours); // Appel des différentes fonctions d'initialisation setupEventListeners(); constantsJSON().then(() => { fillSelects() populateFormData(); }) updateSubmitButtonState('projetForm'); } // Configuration des écouteurs d'événements function setupEventListeners() { document.getElementById('projetFormBtn').addEventListener('click', function(event) { event.preventDefault(); if (client && intermediaire) { submitForm() } else { openModaleClientInter() } }); document.getElementById('loadHistoriqueBtn').addEventListener('click', function() { handleLoadHistoriqueBtn(); }); //Assure additionnel document.getElementById('additionel').addEventListener('change', function() { toggler(this.id, 'checkAdditionnel'); }); // Bouton Add Assure Additionnel document.getElementById('btnAddAdditionnel').addEventListener('click', function() { const nomValue = document.getElementById('nomAdditionnel').value || 'Non défini'; const adresseValue = document.getElementById('adresseAditionnel').value || 'Non défini'; const siretValue = document.getElementById('siretAdditionnel').value || 'Non défini'; addRowAdditionnel(nomValue, adresseValue, siretValue); }); // Garantie Tout Risque document.querySelectorAll('#HIAC, #garantieVol').forEach((checkbox) => { checkbox.addEventListener('click', function(e) { if (tppc.tarif) { e.preventDefault() openModaleModif() } else { showOrHideTousRisques() } }); }) // Bouton Add Vehicule Additionnel document.getElementById('btnAddVehicule').addEventListener('click', function() { const marqueValue = document.getElementById('marqueVehicule').value || 'Non défini'; const genreValue = document.getElementById('genreVehicule').value || 'Non défini'; const typeValue = document.getElementById('typeVehicule').value || 'Non défini'; const immatValue = document.getElementById('immatVehicule').value || 'Non défini'; const capitalValue = document.getElementById('capitalVehicule').value || 'Non défini'; addRowVehicule(marqueValue, genreValue, typeValue, immatValue, capitalValue); }); // Bouton Add Tarif Additionnel document.getElementById('btnAddTarif').addEventListener('click', function() { if (tppc.tarif) { openModaleModif() } else { const typeVehTarifValue = document.getElementById('typeVehTarif').value || 'Non défini'; const capitalTarifValue = document.getElementById('capitalTarif').value || 'Non défini'; const primeVehComTarifValue = document.getElementById('primeVehComTarif').value || 'Non défini'; const nbVehiculesTarifValue = document.getElementById('nbVehiculesTarif').value || 'Non défini'; const primeHTComTarifValue = document.getElementById('primeHTComTarif').value || 'Non défini'; const primeVehObj = { commercial: primeVehComTarifValue, modulee: 'Non Défini', reference: 'Non Défini' } const primeHTObj = { commercial: primeHTComTarifValue, modulee: 'Non Défini', reference: 'Non Défini' } addRowTarif(typeVehTarifValue, capitalTarifValue, primeVehObj, nbVehiculesTarifValue, primeHTObj); } }); //Extension garantie Select document.getElementById('extensionsGarantie').addEventListener('change', function() { const extChoisies = Array.from(this.selectedOptions).map(option => option.value); //Liste des extensions avec modulo const extAvecModulo = Object.keys(objModMar).filter((extension) => objModMar[extension].modulo) var openModal = false if (tppc.tarif) { //Verifie s'il y a un change dans les extensions initialement selectionnées // et si elles sont dans la liste des extensions avec modulo extAvecModulo.forEach((extension) => { if ((extPopulate.includes(extension) && !extChoisies.includes(extension)) || (!extPopulate.includes(extension) && extChoisies.includes(extension)) && extAvecModulo.includes(extension)) { openModal = true } }) } if (openModal) { document.getElementById("marCiternes").selected = tppc.marCiternes ? true : false document.getElementById("marDenreesSousTemp").selected = tppc.marDenreesSousTemp ? true : false; document.getElementById("marAnimaux").selected = tppc.marAnimaux ? true : false; document.getElementById("marFranchise").selected = tppc.marFranchise ? true : false; openModaleModif() } else { if (extChoisies.includes('marAnimaux')) { if (tagAnimauxVivants == false) { M.FormSelect.init(document.querySelectorAll('select')); const elem = document.getElementById('modalAnimauxVivants'); const instance = M.Modal.getInstance(elem); instance.open(); } tagAnimauxVivants = true; } else { if (!(extChoisies.includes("marAnimaux"))) { tagAnimauxVivants = false; } } if (extChoisies.includes('vehicule-transporte')) { if (tagVehiculeTransporte == false) { M.FormSelect.init(document.querySelectorAll('select')); const elem = document.getElementById('modalFranchiseVehiculeTransporte'); const instance = M.Modal.getInstance(elem); instance.open(); } tagVehiculeTransporte = true; } else { if (!(extChoisies.includes("vehicule-transporte"))) { tagVehiculeTransporte = false; } } } addGarantieTag(); }); // Type cotisation var radioButtonsCot = document.getElementsByName('cotisation'); radioButtonsCot.forEach((radio) => { radio.addEventListener('change', function() { if (tarif && tarif.typeContrat == "ensemble") { const previousState = document.querySelector("[name='cotisation']:not(:checked)") previousState.checked = true document.getElementById(this.value).checked = false; openModaleModif() } else { if (this.value == "revisable") { document.getElementById("colCotMini").style.display = 'block'; document.getElementById('colTypeDeRevision').style.display = 'block'; document.getElementById('designationVehicule').style.display = 'none'; if (document.getElementById("cotisationCA").checked) { document.getElementById('tableCotisation').style.display = 'block'; document.getElementById('tarificationFlotte').style.display = 'none'; } else if (document.getElementById("cotisationFlotte").checked) { document.getElementById('tableCotisation').style.display = 'none'; document.getElementById('tarificationFlotte').style.display = 'block'; } } else if (this.value == "forfaitaire") { document.getElementById("colCotMini").style.display = 'none'; document.getElementById('designationVehicule').style.display = 'block'; document.getElementById('colTypeDeRevision').style.display = 'none'; document.getElementById('tableCotisation').style.display = 'none'; document.getElementById('tarificationFlotte').style.display = 'none'; } } }); }); // Type Revision var radioButtonsRev = document.getElementsByName('typeRevision'); radioButtonsRev.forEach((radio) => { radio.addEventListener('change', function() { document.getElementById(this.value).checked = true if (this.value == "cotisationCA") { openModaleCotCa() document.getElementById('tableCotisation').style.display = 'block'; document.getElementById('tarificationFlotte').style.display = 'none'; } else if (this.value == "cotisationFlotte") { document.getElementById('tableCotisation').style.display = 'none'; document.getElementById('tarificationFlotte').style.display = 'block'; } }); }); document.getElementById('cotisationIrreductible').addEventListener('input', function() { validateField('cotisationIrreductible', true); updateSubmitButtonState('projetForm'); }); document.getElementById('cotisationAnnuelle').addEventListener('input', function() { validateField('cotisationAnnuelle', true); updateSubmitButtonState('projetForm'); }); // ADD Event listenner to Fractionnement and cot annuelle, to get the value of the Cotisation Annuelle TTC const radios = document.getElementsByName("fractionnement"); const cotisationAnnuelleHTInput = document.getElementById("cotisationAnnuelleHT"); // Add event listeners to the radio buttons radios.forEach((radio) => { radio.addEventListener("change", calculCotisationAnnuelleTTC); }); // Add event listener to the text input cotisationAnnuelleHTInput.addEventListener("input", calculCotisationAnnuelleTTC); document.getElementById('btnNullDateDebut').addEventListener('click', function() { document.getElementById('dateEffet').value = "00/00/0000"; validateField('dateEffet', true); updateSubmitButtonState('projetForm'); }); document.getElementById('btnNullDateEcheance').addEventListener('click', function() { document.getElementById('dateEcheance').value = "00/00"; validateField('dateEcheance', true); updateSubmitButtonState('projetForm'); }); document.getElementById('btnNullDateFin').addEventListener('click', function() { document.getElementById('dateFin').value = "00/00/0000"; validateField('dateFin', true); updateSubmitButtonState('projetForm'); }); document.getElementById('btnModalDate').addEventListener('click', function() { const elem = document.getElementById('modalDate'); const instance = M.Modal.getInstance(elem); instance.open(); }); document.getElementById('dateEffet').addEventListener('input', function() { validateField('dateEffet', true); updateSubmitButtonState('projetForm'); }); document.getElementById('dateFin').addEventListener('input', function() { validateField('dateFin', true); updateSubmitButtonState('projetForm'); }); document.getElementById('dateEcheance').addEventListener('input', function() { validateField('dateEcheance', true); updateSubmitButtonState('projetForm'); }); document.getElementById("nombreDeSinistres").addEventListener('input', function() { if (tarif && tarif.montantSinistre && (tarif.montantSinistre > 0 && this.value <= 0)) { document.getElementById('nombreDeSinistres-error').innerText = "Vous avez renseigné " + tarif.montantSinistre + "€ de montant sinistre" document.getElementById('nombreDeSinistres-error').style.display = " block" } else { document.getElementById('nombreDeSinistres-error').style.display = " none" } }) document.getElementById('activite').addEventListener('keydown', function(e) { if (tppc.tarif) { e.preventDefault() openModaleModif() } }) document.getElementById('activite').addEventListener('input', function(e) { validateField('activite', true) updateSubmitButtonState('projetForm'); }) document.getElementById('cotisationAnnuelleHT').addEventListener('keydown', function(e) { if (extractTypeRev() !== "CotCA" && tppc.tarif) { e.preventDefault() openModaleModif() } validateField('cotisationAnnuelleHT', true) updateSubmitButtonState('projetForm'); }) document.getElementById('cotisationAnnuelle').addEventListener('keydown', function(e) { if (extractTypeRev() !== "CotCA" && tppc.tarif) { e.preventDefault() openModaleModif() } validateField('cotisationAnnuelle', true) updateSubmitButtonState('projetForm'); }) document.getElementById('modif-OK').addEventListener('click', function(event) { event.preventDefault() redirectToTarif() }) document.getElementById('modal-client').addEventListener('click', function(event) { event.preventDefault() window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=client`; }) document.getElementById('modal-inter').addEventListener('click', function(event) { event.preventDefault() window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=intermediaire`; }) // attach Listener to get the Total of vehicule in the table Tarification document.querySelector('input[name="nbVehiculesTarif"]').addEventListener('input', calculNombreVehicule); const tableCotisation = document.getElementById('tableCotisation'); const inputsCotisation = tableCotisation.querySelectorAll('input'); inputsCotisation.forEach((inputCotisation) => { inputCotisation.addEventListener('input',(event) => { calculCotisationCA(event); validateField('capital', true); validateField('chiffreAffaires', true); validateField('tauxCA', true); updateSubmitButtonState('projetForm'); }); }); // attach event to Table Tarif to get Cotisation Annuelle const tableTarif = document.getElementById('empTableTarif'); const inputsTarif = tableTarif.querySelectorAll('input'); attachEventListenersToInputsTarif(inputsTarif); } function attachEventListenersToInputsTarif(inputs) { inputs.forEach((input) => { input.addEventListener('keydown', (event) => { if (input.name == 'capitalTarif' || input.name == 'nbVehiculesTarif' || input.name == 'primeHTComTarif') { if (tppc.tarif) { event.preventDefault() openModaleModif() } } }); input.addEventListener('input', (event) => { if (input.name == 'primeVehComTarif' || input.name == 'capitalTarif' || input.name == 'nbVehiculesTarif' || input.name == 'primeHTComTarif' && !tppc.tarif) { calculPrimeHT(event); calculCotisationAnnuelleHTPrimeVehicule(event); } }); }); } async function constantsJSON() { try { const responsesJSON = await Promise.all([ fetch('/tppc/modulo/marchandise'), fetch('/tppc/list/vehicule') ]); // Appeler .json() pour chaque réponse pour convertir en JSON const jsonResponses = await Promise.all(responsesJSON.map(r => r.json())); // Récupérer toutes les réponses JSON // Extraire la valeur objRetourne de chaque réponse [ objModMar, listTypeVehicule, ] = jsonResponses.map(response => response.objRetourne); // Adapter pour extraire objRetourne } catch (err) { throw err; } } function fillSelects() { const selectExt = document.getElementById('extensionsGarantie') const optionCreator = (text, value) => { let option = document.createElement('option') option.value = value option.text = text option.id = value return option } for (const [key, value] of Object.entries(objModMar)) { if (value['projet']) { const option = optionCreator(value['projet'], key) selectExt.add(option) } } var select = document.querySelectorAll('select'); M.FormSelect.init(select); } // Garantie Tout Risque function showOrHideTousRisques() { const tousRisques = document.getElementById("tousRisques"); const garantieVol = document.getElementById("garantieVol"); const hiac = document.getElementById("HIAC"); if (garantieVol.checked && hiac.checked) { tousRisques.style.display = "block"; } else { tousRisques.style.display = "none"; } } function openModaleModif() { const elem = document.getElementById('modalModif'); const instance = M.Modal.getInstance(elem); instance.open(); } function openModaleCotCa() { if (tppc.tarif) { const elem = document.getElementById('modalCotCA'); const instance = M.Modal.getInstance(elem) instance.open() } } function openModaleClientInter() { if (!client) { document.getElementById('modal-client').style.display = "inline-block" document.getElementById('list-client').style.display = "block" } if (!intermediaire) { document.getElementById('modal-inter').style.display = "inline-block" document.getElementById('list-inter').style.display = "block" } const elem = document.getElementById('modalClientInter'); const instance = M.Modal.getInstance(elem); instance.open(); } //display add additionnel function toggler(btn, div) { if (document.getElementById(btn).checked) { document.getElementById(div).style.display = 'block'; } else { document.getElementById(div).style.display = 'none'; } } // Handle event spécifique au limite de garantie activité window.handleInputActivity = function(inputId) { validateField(inputId, true); updateSubmitButtonState('projetForm'); }; function addGarantieTag() { const select = document.getElementById('extensionsGarantie'); const garantieContainer = document.getElementById('selected-garanties'); // Clear previous entries garantieContainer.innerHTML = ''; // Clear any existing entries // Iterate over each selected option Array.from(select.options).forEach(option => { if (option.selected && option.value) { if (option.selected && option.value) { const garantieTagName = option.textContent; const garantieTagDiv = document.createElement('div'); garantieTagDiv.classList.add('garantieTag-input', 'row'); garantieTagDiv.style.display = 'flex'; garantieTagDiv.style.alignItems = 'center'; garantieTagDiv.style.justifyContent = 'start'; garantieTagDiv.style.marginBottom = '10px'; garantieTagDiv.innerHTML = `${garantieTagName}`; garantieContainer.appendChild(garantieTagDiv); } } }); } // Peupler le formulaire avec les données function populateFormData() { //Poupulate select historique if (!contrat.historique) { document.getElementById('historiqueDiv').style.display = "none"; } else { document.getElementById('historiqueDiv').style.display = "block"; const idSelect = document.getElementById('idSelect'); contrat.historique.forEach(function(item) { var option = document.createElement('option'); option.value = item.id; option.textContent = item.type + " " + item.produit + " - " + item.date + " - " + item.heure; if (item.nom != undefined && item.prenom != undefined) { option.textContent += " - " + item.nom + " " + item.prenom; } idSelect.appendChild(option); }); M.FormSelect.init(idSelect); } // Populate activité if (tppc.actAssuree) { document.getElementById("activite").value = tppc.actAssuree; } // Populate assurés additionnel if (!projet || !projet.assureAdditionnel || Object.keys(projet.assureAdditionnel).length === 0) { console.error("Le JSON est vide, pas d'assurés additionnels à pré-remplir."); } else { document.getElementById('additionel').checked = true; document.getElementById('checkAdditionnel').style.display = "block"; for (let i = 0; i < projet.assureAdditionnel.length; i++) { const row = projet.assureAdditionnel[i]; addRowAdditionnel(row.nom, row.adresse, row.siret); } } if (projet && projet.antSin !== undefined) {document.getElementById("nombreDeSinistres").value = projet.antSin}; //Les garanties if (tppc.garanties) { if (tppc.garanties.includes('IAC')) {document.getElementById("IAC").checked = true}; if (tppc.garanties.includes('HIAC')) {document.getElementById("HIAC").checked = true}; if (tppc.garanties.includes('Vol')) {document.getElementById("garantieVol").checked = true}; showOrHideTousRisques(); } //Extensions Garanties if (tppc.marCiternes) {document.getElementById("marCiternes").selected = true}; if (tppc.marDenreesSousTemp) {document.getElementById("marDenreesSousTemp").selected = true}; if (tppc.marAnimaux) { tagAnimauxVivants = true; document.getElementById("marAnimaux").selected = true; }; if (tppc.marFranchise) { tagVehiculeTransporte = true; document.getElementById("marFranchise").selected = true; }; //Remplissage du tableau par les extensions qui sont déjà sélectionnées extPopulate = [...document.querySelectorAll('#extensionsGarantie option:checked:not([value=""])')].map((option => option.value)) addGarantieTag(); // Populate temporalité if (projet && projet.tempo) {document.getElementById(projet.tempo).checked = true}; if (projet && projet.dateEffet) {document.getElementById("dateEffet").value = projet.dateEffet}; if (projet && projet.dateEcheance) {document.getElementById("dateEcheance").value = projet.dateEcheance}; if (contrat.type === "TEMPORAIRE") {document.getElementById('rowDateFin').style.display = 'block';} if (projet && projet.dateFin) {document.getElementById("dateFin").value = projet.dateFin}; if (projet && projet.typeCot) {document.getElementById(projet.typeCot).checked = true} // Populate Cotisation var typeRev = "cotisationFlotte", typeCot = "revisable" if (tarif && tarif.typeContrat) { if (tarif.typeContrat == "detaillee") { typeRev = "cotisationFlotte" typeCot = "revisable" } else if (tarif.typeContrat == "ensemble") { typeCot = "forfaitaire" } } else if (projet && projet.typeCot) { typeCot = projet.typeCot typeRev = (projet.typeRev == "CotCA") ? "cotisationCA" : "cotisationFlotte" } document.getElementById(typeCot).checked = true document.getElementById(typeRev).checked = true if (typeCot == "revisable") { document.getElementById('colTypeDeRevision').style.display = 'block'; document.getElementById('designationVehicule').style.display = 'none'; document.getElementById("colCotMini").style.display = 'block'; if (typeRev == "cotisationCA") { document.getElementById('tableCotisation').style.display = 'block'; document.getElementById('tarificationFlotte').style.display = 'none'; } else if (typeRev == "cotisationFlotte") { document.getElementById('tableCotisation').style.display = 'none'; document.getElementById('tarificationFlotte').style.display = 'block'; if (tarif) { document.getElementById('inputRow').style.display = "none" } } } else if (typeCot == "forfaitaire") { document.getElementById("colCotMini").style.display = 'none' document.getElementById('tarificationFlotte').style.display = 'none'; document.getElementById('designationVehicule').style.display = 'block'; document.getElementById('colTypeDeRevision').style.display = 'none'; document.getElementById('tableCotisation').style.display = 'none'; } if (projet && projet.cotIrreductible) {document.getElementById("cotisationIrreductible").value = projet.cotIrreductible}; if (tppc.nbVehic) {document.getElementById("nombreVehicules").value = tppc.nbVehic}; if (tppc.cotCapVeh) {document.getElementById("capital").value = tppc.cotCapVeh}; if (projet && projet.ca) {document.getElementById("chiffreAffaires").value = projet.ca}; if (projet && projet.cotTauxTax) {document.getElementById("tauxCA").value = projet.cotTauxTax}; if (tppc.tarif) { const tarifRef = tppc['@expand'].tarif['tarifRef'] document.getElementById("tarifRef").value = tarifRef; document.getElementById('cotAnnHTMessage').style.display = "block" } else { document.querySelectorAll('[name="tarifRefCell"]').forEach((cell) => cell.style.display = "none") } if (tppc.primeHT) { document.getElementById("cotisationAnnuelleHT").value = tppc.primeHT calculCotisationAnnuelleTTC() } // Populate tableau vehicule if (projet && projet.designationVehicule && Object.keys(projet.designationVehicule).length !== 0) { for (let i = 0; i < projet.designationVehicule.length; i++) { const row = projet.designationVehicule[i]; addRowVehicule(row.marque, row.genre, row.type, row.immat, row.capital); } } // Populate tableau Tarification if (tppc && tppc.tarFlotte && Object.keys(tppc.tarFlotte).length !== 0) { for (let i = 0; i < tppc.tarFlotte.length; i++) { const row = tppc.tarFlotte[i]; const primeVehObj = { commercial: row.primeVehComTarif, modulee: row.primeVehModRefTarif, reference: row.primeVehTarif } const primeHTObj = { commercial: row.primeHTComTarif, modulee: row.primeHTModRefTarif, reference: row.primeHTTarif } addRowTarif(listTypeVehicule[row.typeVehTarif] || row.typeVehTarif, row.capitalTarif, primeVehObj, row.nbVehiculesTarif, primeHTObj, row.garTarif, row.typeMarTarif, row.modulo); } calculNombreVehicule() } } // Ajouter une ligne au tableau function addRowAdditionnel(nomValue, adresseValue, siretValue) { const table = document.getElementById('empTableAdditionnel'); // Créer une nouvelle ligne avec des inputs éditables const newRow = table.insertRow(table.rows.length - 1); newRow.innerHTML = `