personnal/ecole/public copy/js/projet-form-tppc.js

1303 lines
57 KiB
JavaScript

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 = `<span id="${option.value}-chip" class="chip" for="${option.value}" style="color:darkblue">${garantieTagName}</span>`;
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 = `
<td><input type="text" name="nom" value="${nomValue}" class="input-field" /></td>
<td><input type="text" name="adresse" value="${adresseValue}" class="input-field" /></td>
<td><input type="text" name="siret" value="${siretValue}" class="input-field" /></td>
<td>
<button class="btn delete-btn" type="button">
<i class="material-icons">delete</i>
</button>
</td>
`;
// Réinitialiser les valeurs de saisie
document.getElementById('nomAdditionnel').value = '';
document.getElementById('adresseAditionnel').value = '';
document.getElementById('siretAdditionnel').value = '';
// Ajouter un écouteur d'événements pour supprimer
newRow.querySelector('.delete-btn').addEventListener('click', function() {
deleteRow(this);
});
}
// Ajouter une ligne au tableau Vehicule
function addRowVehicule(marqueValue, genreValue, typeValue, immatValue, capitalValue) {
const table = document.getElementById('empTableVehicules');
// Créer une nouvelle ligne avec des inputs éditables
const newRow = table.insertRow(table.rows.length - 1);
newRow.innerHTML = `
<td><input type="text" name="marque" value="${marqueValue}" class="input-field" /></td>
<td><input type="text" name="genre" value="${genreValue}" class="input-field" /></td>
<td><input type="text" name="type" value="${typeValue}" class="input-field" /></td>
<td><input type="text" name="immat" value="${immatValue}" class="input-field" /></td>
<td><input type="text" name="capital" value="${capitalValue}" class="input-field" /></td>
<td>
<button class="btn delete-btn" type="button">
<i class="material-icons">delete</i>
</button>
</td>
`;
// Réinitialiser les valeurs de saisie
document.getElementById('marqueVehicule').value = '';
document.getElementById('genreVehicule').value = '';
document.getElementById('typeVehicule').value = '';
document.getElementById('immatVehicule').value = '';
document.getElementById('capitalVehicule').value = '';
// Ajouter un écouteur d'événements pour supprimer
newRow.querySelector('.delete-btn').addEventListener('click', function() {
deleteRow(this);
});
}
function addRowTarif(typeVehTarifValue, capitalTarifValue, primeVehObj, nbVehiculesTarifValue, primeHTObj, garTarifValue = '', typeMarTarifValue = '', moduloValue = 1) {
const table = document.getElementById('empTableTarif');
var primeVehComTarifValue = primeVehObj.commercial
const primeVehModRefTarifValue = primeVehObj.modulee
const primeVehTarifValue = primeVehObj.reference
var primeHTComTarifValue = primeHTObj.commercial
const primeHTModRefTarifValue = primeHTObj.modulee
const primeHTTarifValue = primeHTObj.reference
// Créer une nouvelle ligne avec des inputs éditables
const newRow = table.insertRow(table.rows.length - 1);
if (primeVehComTarifValue == undefined) {
primeVehComTarifValue = 0
}
if (primeHTComTarifValue == undefined) {
primeHTComTarifValue = 0
}
newRow.innerHTML = `
<td><input type="text" name="typeVehTarif" value="${typeVehTarifValue}" class="input-field" /></td>
<td><input type="text" name="capitalTarif" value="${capitalTarifValue}" class="input-field" /></td>
<td><input type="text" name="primeVehModRefTarif" value="${primeVehModRefTarifValue}" class="input-field" disabled/></td>
<td><input type="text" name="primeVehComTarif" value="${primeVehComTarifValue}" class="input-field" /></td>
<td><input type="text" name="nbVehiculesTarif" value="${nbVehiculesTarifValue}" class="input-field" /></td>
<td><input type="text" name="primeHTModRefTarif" value="${primeHTModRefTarifValue}" class="input-field" disabled /></td>
<td><input type="text" name="primeHTComTarif" value="${primeHTComTarifValue}" class="input-field" /></td>
<td style="display : none"><input type="text" name="garTarif" value="${garTarifValue}" class="input-field" /></td>
<td style="display : none"><input type="text" name="typeMarTarif" value="${typeMarTarifValue}" class="input-field" /></td>
<td style="display : none"><input type="text" name="primeVehTarif" value="${primeVehTarifValue}" class="input-field" disabled/></td>
<td style="display : none"><input type="text" name="primeHTTarif" value="${primeHTTarifValue}" class="input-field" disabled/></td>
<td style="display : none"><input type="text" name="modulo" value="${moduloValue}" class="input-field" /></td>
<td>
<button class="btn delete-btn" type="button">
<i class="material-icons">delete</i>
</button>
</td>
`;
// Réinitialiser les valeurs de saisie
document.getElementById('typeVehTarif').value = '';
document.getElementById('capitalTarif').value = '';
document.getElementById('primeVehComTarif').value = '';
document.getElementById('nbVehiculesTarif').value = '';
document.getElementById('primeHTComTarif').value = '';
document.getElementById('garTarif').value = '';
document.getElementById('typeMarTarif').value = '';
document.getElementById('modulo').value = '';
// Ajouter un écouteur d'événements pour Calculer Prime HT et prime Annuelle
const inputsInNewRow = newRow.querySelectorAll('input');
attachEventListenersToInputsTarif(inputsInNewRow);
//update Nombre de Vehicule
newRow.querySelector('input[name="nbVehiculesTarif"]').addEventListener('input', calculNombreVehicule);
// Ajouter un écouteur d'événements pour supprimer
newRow.querySelector('.delete-btn').addEventListener('click', function() {
if (tppc.tarif) {
openModaleModif()
} else {
deleteRow(this);
calculCotisationAnnuelleHTPrimeVehicule();
calculNombreVehicule();
}
});
}
// Supprimer une ligne du tableau
function deleteRow(btn) {
const row = btn.parentElement.parentElement;
row.parentElement.removeChild(row);
}
// Calcul nombre de Vehicule
function calculNombreVehicule() {
const tarifRows = document.querySelectorAll('#empTableTarif tbody tr');
let totalVehicules = 0;
tarifRows.forEach((row) => {
const nbVehiculesInput = row.querySelector('input[name="nbVehiculesTarif"]');
const nbVehiculesValue = parseInt(nbVehiculesInput.value) || 0;
totalVehicules += nbVehiculesValue;
});
document.getElementById('nombreVehicules').value = totalVehicules;
}
function calculCotisationAnnuelleHTPrimeVehicule() {
const tableTarif = document.getElementById('empTableTarif');
let somme = 0;
const inputs = tableTarif.querySelectorAll('input[name="primeHTComTarif"]');
for (let i = 0; i < inputs.length; i++) {
const value = parseFloat(inputs[i].value) || 0;
somme += value;
}
document.getElementById('cotisationAnnuelleHT').value = somme;
calculCotisationAnnuelleTTC()
}
// Calcul de la Prime Totale en HT
function calculPrimeHT(event) {
const input = event.currentTarget;
const row = input.parentNode.parentNode; //Selection de la ligne en cours
const nbVehiculeInput = row.querySelector('input[name="nbVehiculesTarif"]');
const primeVehiculeInput = row.querySelector('input[name="primeVehComTarif"]');
const primeHTInput = row.querySelector('input[name="primeHTComTarif"]');
const nbVehicule = parseFloat(nbVehiculeInput.value) || 0;
const primeVehicule = parseFloat(primeVehiculeInput.value) || 0;
const somme = (nbVehicule * primeVehicule);
primeHTInput.value = somme;
calculCotisationAnnuelleTTC();
}
//Calcul de la cotisation Annuel
function calculCotisationAnnuelleTTC() {
cotisationAnnuelleHT = parseFloat(document.getElementById("cotisationAnnuelleHT").value) || 0
let fract = 0;
if (document.getElementById("annuel").checked) {fract = 1};
if (document.getElementById("semestriel").checked) {fract = 2};
if (document.getElementById("trimestriel").checked) {fract = 4};
if (document.getElementById("mensuel").checked) {fract = 1};
const resultat = (cotisationAnnuelleHT + 6.50 + (36 * fract)).toFixed(2);
document.getElementById("cotisationAnnuelle").value = resultat;
validateField('cotisationAnnuelleHT', true);
updateSubmitButtonState('projetForm');
}
function calculCotisationCA(event) {
const input = event.target;
if (input.id === 'chiffreAffaires') {
cotisationAnnuelleHT = parseFloat(input.value * document.getElementById("tauxCA").value / 100) || 0
document.getElementById('cotisationAnnuelleHT').value = cotisationAnnuelleHT.toFixed(2)
} else if (input.id === 'tauxCA') {
cotisationAnnuelleHT = parseFloat(input.value * document.getElementById("chiffreAffaires").value / 100) || 0
document.getElementById('cotisationAnnuelleHT').value = cotisationAnnuelleHT.toFixed(2)
}
calculCotisationAnnuelleTTC()
}
function handleLoadHistoriqueBtn() {
var selectedId = document.getElementById('idSelect').value;
if (selectedId != "") {
fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${selectedId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => {
if (data.valid) {
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=projet`;
} else {
console.log('Echec lors de la mise à jour de la relation id contrat - id client :', data);
}
});
}
}
// Contruit la structure Assuré additionnel à envoyer à la BDD
function extractAssureAdditionnel(tableId) {
const jsonArr = [];
const table = document.getElementById(tableId);
if (table && document.getElementById("additionel").checked) {
const rows = table.querySelectorAll('tr:not(:first-child)');
rows.forEach(row => {
const allInputsEmpty = Array.from(row.querySelectorAll('input')).every(input => input.value === '');
if (!allInputsEmpty) {
const inputs = row.querySelectorAll('input');
const dataObj = {};
inputs.forEach(input => {
const fieldName = input.getAttribute('name');
const fieldValue = input.value || "Non défini";
dataObj[fieldName] = fieldValue;
});
jsonArr.push(dataObj);
}
});
const jsonResult = JSON.stringify(jsonArr, null, 2);
return jsonResult;
}
return "[]"; // Retourne un tableau JSON vide si aucune saisie n'est trouvée dans le tableau
}
// Contruit la structure Designation à envoyer à la BDD
function extractDesignationVehicule(tableId) {
const jsonArr = [];
const table = document.getElementById(tableId);
if (table) {
const rows = table.querySelectorAll('tr:not(:first-child)');
rows.forEach(row => {
const allInputsEmpty = Array.from(row.querySelectorAll('input')).every(input => input.value === '');
if (!allInputsEmpty) {
const inputs = row.querySelectorAll('input');
const dataObj = {};
inputs.forEach(input => {
const fieldName = input.getAttribute('name');
const fieldValue = input.value || "Non défini";
dataObj[fieldName] = fieldValue;
});
jsonArr.push(dataObj);
}
});
const jsonResult = JSON.stringify(jsonArr, null, 2);
return jsonResult;
}
return "[]"; // Retourne un tableau JSON vide si aucune saisie n'est trouvée dans le tableau
}
// Contruit la structure Designation à envoyer à la BDD
function extractTarificationFlotte(tableId) {
const jsonArr = [];
const table = document.getElementById(tableId);
if (table) {
const rows = table.querySelectorAll('tr');
rows.forEach(row => {
const allInputsEmpty = Array.from(row.querySelectorAll('input')).every(input => input.value === '');
if (!allInputsEmpty) {
const inputs = row.querySelectorAll('input');
const dataObj = {};
inputs.forEach(input => {
const fieldName = input.getAttribute('name');
var fieldValue
fieldValue = input.value || "Non défini";
dataObj[fieldName] = fieldValue;
});
jsonArr.push(dataObj);
}
});
const jsonResult = JSON.stringify(jsonArr, null, 2);
return jsonResult;
}
return "[]"; // Retourne un tableau JSON vide si aucune saisie n'est trouvée dans le tableau
}
function extractTempo() {
let tempo = "";
if (document.getElementById("mensuel").checked == true) {tempo = "mensuel";}
if (document.getElementById("trimestriel").checked == true) {tempo = "trimestriel";}
if (document.getElementById("semestriel").checked == true) {tempo = "semestriel";}
if (document.getElementById("annuel").checked == true) {tempo = "annuel";}
return tempo;
}
function extractTypeCot() {
if (document.getElementById("forfaitaire").checked == true) {return "forfaitaire";}
if (document.getElementById("revisable").checked == true) {return "revisable";}
}
function extractTypeRev() {
if (extractTypeCot() == "revisable") {
if (document.getElementById("cotisationCA").checked == true) {return "CotCA";}
if (document.getElementById("cotisationFlotte").checked == true) {return "FlotteOuverte";}
} else {
return ""
}
}
function extractGaranties() {
const garanties = new Set()
if (document.getElementById('HIAC').checked) {
garanties.add('HIAC')
}
if (document.getElementById('IAC').checked) {
garanties.add('IAC')
}
if (document.getElementById('garantieVol').checked) {
garanties.add('Vol')
}
return [...garanties]
}
async function redirectToTarif() {
if (await submitForm(false, false)) {
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
}
}
// Gérer la soumission du formulaire
async function submitForm(updateTPPC = true, generateProject = true) {
const bodyProjet = {
//Informations sur l'assuré :
"assureAdditionnel": extractAssureAdditionnel('empTableAdditionnel'),
//Nombre exosition
// "nbExp": document.getElementById("nombre-exposition").value,
//Antécedent de sinitre
"antSin": document.getElementById("nombreDeSinistres").value == "" ? "" : document.getElementById("nombreDeSinistres").value,
// Informations sur le contrat :
// Fractionnement
"tempo": extractTempo(),
"typeCot": extractTypeCot(),
// Dates du contrat
"dateEffet": document.getElementById("dateEffet").value,
"dateEcheance": document.getElementById("dateEcheance").value,
"dateFin": document.getElementById("dateFin").value,
// Informations sur les cotisations :
"typeRev": extractTypeRev(),
// Informations sur les cotisations :
"designationVehicule": (extractTypeCot() == "forfaitaire") ? extractDesignationVehicule('empTableVehicules') : "",
"cotIrreductible": (extractTypeCot() == "revisable") ? document.getElementById("cotisationIrreductible").value : "",
"cotTauxTax": (extractTypeRev() == "CotCA") ? document.getElementById("tauxCA").value : '',
// "tarifComHT": document.getElementById("cotisationAnnuelleHT").value,
"tarifComTTC": updateTPPC ? document.getElementById("cotisationAnnuelle").value : '',
"ca": document.getElementById('chiffreAffaires').value,
// Vous pouvez ajouter d'autres données pour la saisie dans la collection TPPC PROJET ici
}
const responseProjet = await fetch(`/tppc/createProjet`, {
method: 'POST',
body: JSON.stringify(bodyProjet), headers: {
'Content-Type': 'application/json',
},
});
const dataProjet = await responseProjet.json();
if (dataProjet.valid) {
const idProjet = dataProjet.tppc.id
var bodyTPPC = {}
var tarif = ""
if (tppc.tarif && extractTypeRev() !== "CotCA") {
tarif = tppc.tarif
}
if (updateTPPC) {
bodyTPPC = {
"actAssuree": document.getElementById("activite").value,
"projet": idProjet,
"tarif": tarif,
"nbVehic": document.getElementById("nombreVehicules").value,
"cotCapVeh": document.getElementById("capital").value,
"garanties": extractGaranties(),
"ca": document.getElementById("chiffreAffaires").value,
"tarFlotte": extractTarificationFlotte('empTableTarif'),
"primeHT": document.getElementById('cotisationAnnuelleHT').value,
"commentaire": commentaire,
"marOrdinaires": tppc.marOrdinaires || '',
"marBennes": tppc.marBennes || '',
"marDenreesHorsTemp": tppc.marDenreesHorsTemp || '',
"marRisques": tppc.marRisques || '',
"marEngins": tppc.marEngines || '',
"marFranchise": document.getElementById('marFranchise').selected,
"marEnExpo": tppc.marEnExpo || '',
"marCiternes": document.getElementById('marCiternes').selected,
"marAnimaux": document.getElementById('marAnimaux').selected,
"marDenreesSousTemp": document.getElementById('marDenreesSousTemp').selected,
"nbExpo": tppc.nbExpo || '',
"capExpo": tppc.capExpo || '',
"typeMarExpo": tppc.typeMarExpo || '',
"franchiseMarExpo": tppc.franchiseMarExpo || '',
}
} else {
bodyTPPC = {
"actAssuree": tppc.actAssuree,
"projet": idProjet,
"tarif": tppc.tarif,
"nbVehic": tppc.nbVehic,
"cotCapVeh": tppc.cotCapVeh,
"garanties": tppc.garanties,
"tarFlotte": tppc.tarFlotte,
"primeHT": tppc.primeHT,
"commentaire": tppc.commentaire,
"marOrdinaires": tppc.marOrdinaires,
"marBennes": tppc.marBennes,
"marDenreesHorsTemp": tppc.marDenreesHorsTemp,
"marRisques": tppc.marRisques,
"marEngins": tppc.marEngines,
"marFranchise": tppc.marFranchise,
"marEnExpo": tppc.marEnExpo,
"marCiternes": tppc.marCiternes,
"marAnimaux": tppc.marAnimaux,
"marDenreesSousTemp": tppc.marDenreesSousTemp,
"nbExpo": tppc.nbExpo,
"capExpo": tppc.capExpo,
"typeMarExpo": tppc.typeMarExpo,
"franchiseMarExpo": tppc.franchiseMarExpo,
}
}
const responseTPPC = await fetch(`/tppc/create`, {
method: 'POST',
body: JSON.stringify(bodyTPPC), headers: {
'Content-Type': 'application/json',
},
});
const dataTPPC = await responseTPPC.json();
if (dataTPPC.valid) {
const idTPPC = dataTPPC.tppc.id;
// Mettre à jour le champ "enCours" dans le contrat avec l'ID de la nouvelle saisie tppc
const responseContratEnCours = await fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${idTPPC}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const dataContratEnCours = await responseContratEnCours.json();
if (dataContratEnCours.valid) {
// Obtenir la date actuelle au format "JJ/MM/AAAA"
const currentDate = new Date();
const day = String(currentDate.getDate()).padStart(2, '0');
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Les mois sont indexés à partir de 0, donc +1
const year = currentDate.getFullYear();
const formattedDate = `${day}/${month}/${year}`;
//Obtenir l'user
const token = localStorage.getItem('jwtToken');
const decoded = jwt_decode(token);
const userFirstName = decoded.userFirstName;
const userLastName = decoded.userLastName;
// Obtenir l'heure actuelle au format "HHhMM"
const hours = String(currentDate.getHours()).padStart(2, '0');
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const seconds = String(currentDate.getSeconds()).padStart(2, '0');
const formattedTime = `${hours}:${minutes}:${seconds}`;
const nom = userLastName;
const prenom = userFirstName;
// Mettre à jour le champ "historique" dans le contrat avec les nouvelles données d'historique
const historiqueData = [
{
"type": contrat.type,
"date": formattedDate,
"heure": formattedTime,
"produit": "TPPC",
"id": idTPPC,
"nom": nom,
"prenom": prenom,
}
];
const responseHistoriqueUpdate = await fetch(`/contrat/update/historique/${contrat.id}`, {
method: 'POST',
body: JSON.stringify({historiqueData}),
headers: {
'Content-Type': 'application/json',
},
});
const dataHistoriqueUpdate = await responseHistoriqueUpdate.json();
if (dataHistoriqueUpdate.valid) {
if (generateProject == false) {
return true
} else {
const numParcours = getNumParcoursFromURL();
let filename;
// Envoi de la requête POST au serveur pour générer le projet
fetch(`/generate/tppc/projet/${numParcours}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
if (!response.ok) {
throw new Error('Erreur réseau ou serveur');
}
const disposition = response.headers.get('content-disposition');
filename = disposition.split(';')[1].trim().split('=')[1];
return response.blob(); // On attend une réponse sous forme de blob pour un fichier
})
.then(blob => {
// Crée un URL pour le blob
const url = window.URL.createObjectURL(blob);
// Crée un élément a temporaire pour simuler un clic pour téléchargement
const a = document.createElement('a');
a.href = url;
a.download = filename; // Nomme le fichier téléchargé
document.body.appendChild(a); // Ajoute l'élément au document
a.click(); // Simule un clic sur l'élément pour déclencher le téléchargement
window.URL.revokeObjectURL(url); // Nettoie l'URL objet
a.remove(); // Supprime l'élément a du document
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=projet`;
})
.catch(error => console.error('Erreur lors de la génération du projet:', error));
/// TODO FIN Génération fichier à l'enregistrement A RETIRER QUAND MODE CONTRAT
///////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO NE PAS OUBLIER LE HREF QUI EST DANS LE GEN ACTUELLEMENT
// window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=projet`;
}
} else {
console.log('Echec lors de la mise à jour de l\'historique du contrat :', dataHistoriqueUpdate.message);
}
}
} else {
console.log('Echec lors de la mise à jour du champ "enCours" dans le contrat :', dataContratEnCours.message);
}
} else {
console.log('Echec lors de la création de la saisie dans la collection TPPC :', dataProjet.message);
}
}
window.initSubmenuForm = init;
})();