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

1347 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, tppc, tarif, projet;
// Variables propositions
let franchise150, franchise300, mini150, mini300
//Variables modulos et liste
let objModAct, objModMar, objModFlotte, objModCot, objModSinistre, objPrimeMini, listTypeVehicule, objMarEnExpo
//variables modale tarif commercial
const seuil = 15
// 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);
// Accéder aux informations stockées du parcours
parcours = JSON.parse(sessionStorage.getItem('parcours'));
contrat = JSON.parse(sessionStorage.getItem('contrat'));
tppc = contrat?.["@expand"]?.enCours || null;
tarif = tppc?.["@expand"]?.tarif || null;
projet = tppc?.["@expand"]?.projet || null;
console.log("Initialisation pour formulaire projet :", parcours);
// Appel des différentes fonctions d'initialisation
setupEventListeners();
//Appel des constantes JSON pour remplir les selects puis remplir les champs
constantsJSON().then(() => {
fillSelects();
populateFormData();
})
}
// Configuration des écouteurs d'événements
function setupEventListeners() {
document.getElementById('loadHistoriqueBtn').addEventListener('click', function() {
handleLoadHistoriqueBtn();
});
document.getElementById('btnAddTypeVehicule').addEventListener('click', function() {
const typeVehTarif = document.getElementById('typeVehTarif').value
const capitalTarif = document.getElementById('capitalTarif').value
const garTarif = document.getElementById('garTarif').value
const typeMarTarif = document.getElementById('typeMarTarif').value
const nbVehiculesTarif = document.getElementById('nbVehiculesTarif').value
const primeVehTarif = document.getElementById('primeVehTarif').value
const primeHTTarif = document.getElementById('primeHTTarif').value
const modulo = document.getElementById('modulo').value
addRowTarification(typeVehTarif, capitalTarif, garTarif, typeMarTarif, nbVehiculesTarif, primeVehTarif, primeHTTarif, modulo);
// Réinitialiser les valeurs de saisie
emptyRowTarification()
});
document.querySelectorAll('input[name=typeContrat]').forEach((element) =>
element.addEventListener('click', function() {
toggleTypeContrat(this.value)
if (tarif && tarif.montantSinistre !== undefined) {
document.getElementById('sinistre').value = tarif.montantSinistre
} else {
document.getElementById('sinistre').value = ""
}
checkSinistre()
}))
document.getElementById('capitalVehicule').addEventListener('input', function() {
validateField('capitalVehicule', true)
updateSubmitButtonState('tarifFormTPPC')
if (isSelected('marAnimaux') && this.value > 200000) {
openModaleAniViv()
}
})
document.getElementById('flotte').addEventListener('input', function () {
validateField('flotte', true)
updateSubmitButtonState('tarifFormTPPC')
const moduloChipFlotte = document.getElementById('chip-modulo-flotte')
updateModuloChip(moduloChipFlotte, calcModFlotte(this.value))
})
document.getElementById('marAssuree').addEventListener('change', function() {
updateMarAssuree()
})
document.querySelectorAll('input[type="checkbox"][name="garSouhaitees"]').forEach((checkbox) => {
checkbox.addEventListener('click', function() {
checkBennesGaranties()
})
})
document.getElementById('activite').addEventListener('change', function () {
validateField('activite', true)
updateSubmitButtonState('tarifFormTPPC')
checkActivite(this);
})
document.querySelectorAll('.franchise-card button').forEach((button) => button.addEventListener('click', function (e) {
e.preventDefault()
openModaleTarifCom(this.name)
}))
document.getElementById('bouton-grille').addEventListener('click', function() {
const modal = document.getElementById('modalGrille')
const instance = M.Modal.getInstance(modal)
instance.open()
})
document.getElementById('marEnExpo').addEventListener('change', function() {
document.getElementById('marEnExpo-div').style.display = (this.checked) ? "block" : "none"
})
document.querySelectorAll('input').forEach((element) => {
element.addEventListener('input', function () {
affichagePropositions();
})
})
document.querySelectorAll('select').forEach((element) => {
element.addEventListener('change', function () {
affichagePropositions();
})
})
document.getElementById('comm-OK').addEventListener('click', function () {
submitForm(this.name)
})
document.getElementById('commentaire').addEventListener('input', function () {
if (document.getElementById('commentaire').value == "") {
document.getElementById('comm-OK').disabled = true
} else {
document.getElementById('comm-OK').disabled = false
}
})
setupTableEventListeners()
}
function setupTableEventListeners() {
const lignes = document.querySelectorAll('table#empTableTarifVehicules tr:not(#header)')
lignes.forEach((ligne) => {
const selectTypeMar = ligne.querySelector('select[name="typeMarTarif"]')
const selectGarChoisies = ligne.querySelector('select[name="garTarif"]')
const chipModulo = ligne.querySelector('div[name="moduloTarif"]')
const inputModulo = ligne.querySelector('input[name="modulo"]')
const inputPrimeVehicule = ligne.querySelector('input[name="primeVehTarif"]')
const inputPrimeHTTarif = ligne.querySelector('input[name="primeHTTarif"]')
const inputCapital = ligne.querySelector('input[name="capitalTarif"]')
const inputNbrVehicule = ligne.querySelector('input[name="nbVehiculesTarif"]')
const deleteButton = ligne.querySelector('.delete-btn')
inputPrimeVehicule.addEventListener('input', function () {
inputPrimeHTTarif.value = inputPrimeVehicule.value * inputNbrVehicule.value
})
inputNbrVehicule.addEventListener('input', function () {
inputPrimeHTTarif.value = inputPrimeVehicule.value * inputNbrVehicule.value
})
selectTypeMar.addEventListener('change', function() {
const moduloMar = calcModMar(this.value)
updateModuloChip(chipModulo, moduloMar)
inputModulo.value = moduloMar
})
inputCapital.addEventListener('input', function () {
inputPrimeVehicule.value = calcModCot(selectGarChoisies.value, inputCapital.value) || 0
inputPrimeHTTarif.value = inputPrimeVehicule.value * inputNbrVehicule.value
})
selectGarChoisies.addEventListener('change', function() {
inputPrimeVehicule.value = calcModCot(selectGarChoisies.value, inputCapital.value) || 0
inputPrimeHTTarif.value = inputPrimeVehicule.value * inputNbrVehicule.value
})
if (deleteButton !== null) {
deleteButton.addEventListener('click', function () {
deleteRow(this);
affichagePropositions();
});
}
ligne.querySelectorAll('select').forEach((select) => {
select.addEventListener('change', function() {
checkBennesGarantiesTarif(ligne)
affichagePropositions();
})
})
ligne.querySelectorAll('input').forEach((input) => {
input.addEventListener('input', function () {
checkBennesGarantiesTarif(ligne)
affichagePropositions();
})
})
})
}
//Appel pour recevoir les constantes
async function constantsJSON() {
try {
const responsesJSON = await Promise.all([
fetch('/tppc/modulo/activite'),
fetch('/tppc/modulo/marchandise'),
fetch('/tppc/modulo/flotte'),
fetch('/tppc/modulo/cotisation'),
fetch('/tppc/modulo/sinistre'),
fetch('/tppc/modulo/primeMini'),
fetch('/tppc/list/vehicule'),
fetch('/tppc/modulo/marEnExpo')
]);
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
[
objModAct,
objModMar,
objModFlotte,
objModCot,
objModSinistre,
objPrimeMini,
listTypeVehicule,
objMarEnExpo
] = jsonResponses.map(response => response.objRetourne); // Adapter pour extraire objRetourne
} catch (err) {
throw err;
}
}
//Remplissage des select et des champs avec les propositions
function fillSelects() {
//Remplissage des activites
const listeActiviteObj = {}
//Creation objets avec liste d'activité en clé, et null en valeur
for (const activite of Object.keys(objModAct)) {
listeActiviteObj[activite] = null
}
var elems = document.querySelectorAll('.autocomplete');
M.Autocomplete.init(elems, {
data: listeActiviteObj,
limit: 10
})
/******************************************/
//Remplissage des selects
const selectMar = document.getElementById('marAssuree')
const selectMarTarif = document.getElementById('typeMarTarif')
const selectMarEnExp = document.getElementById('typeMarEnExp')
//Fonction pour créer les select options
const optionCreator = (text, value) => {
let option = document.createElement('option')
option.value = value
option.text = text
return option
}
for (const [key, value] of Object.entries(objModMar)) {
if (value['tarif']) {
selectMar.add(optionCreator(value['tarif'], key))
selectMarTarif.add(optionCreator(value['tarif'], key))
}
}
for (const [key, value] of Object.entries(objMarEnExpo)) {
selectMarEnExp.add(optionCreator(value['nom'], key))
}
var select = document.querySelectorAll('select');
M.FormSelect.init(select);
}
//Remplissage des champs et des selects avec les données sauvegardées
function populateFormData() {
// Populate 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);
}
if (tppc.actAssuree) {
document.getElementById('activite').value = tppc.actAssuree
checkActivite(document.getElementById('activite'))
}
if (tppc.cotCapVeh) {
document.getElementById('capitalVehicule').value = tppc.cotCapVeh
}
if (tppc.nbVehic) {
document.getElementById('flotte').value = tppc.nbVehic
updateModuloChip(document.getElementById('chip-modulo-flotte'), calcModFlotte(tppc.nbVehic))
}
if (tppc.garanties) {
if (tppc.garanties.includes('HIAC')) {
document.getElementById('garSouhaitees-HIAC').checked = true
}
if (tppc.garanties.includes('Vol')) {
document.getElementById('garSouhaitees-vol').checked = true
}
}
// Remplissage des marchandises assurées
const marAssuree = []
if (tppc.marOrdinaires) {
document.querySelector('select#marAssuree option[value="marOrdinaires"]').selected = true;
marAssuree.push("marOrdinaires")
}
if (tppc.marBennes) {
document.querySelector('select#marAssuree option[value="marBennes"]').selected = true;
marAssuree.push("marBennes")
}
if (tppc.marDenreesHorsTemp) {
document.querySelector('select#marAssuree option[value="marDenreesHorsTemp"]').selected = true;
marAssuree.push("marDenreesHorsTemp")
}
if (tppc.marDenreesSousTemp) {
document.querySelector('select#marAssuree option[value="marDenreesSousTemp"]').selected = true;
marAssuree.push("marDenreesSousTemp")
}
if (tppc.marAuto) {
document.querySelector('select#marAssuree option[value="marAuto"]').selected = true;
marAssuree.push("marAuto")
}
if (tppc.marRisques) {
document.querySelector('select#marAssuree option[value="marRisques"]').selected = true;
marAssuree.push("marRisques")
}
if (tppc.marCiternes) {
document.querySelector('select#marAssuree option[value="marCiternes"]').selected = true;
marAssuree.push("marCiternes")
}
if (tppc.marEngins) {
document.querySelector('select#marAssuree option[value="marEngins"]').selected = true;
marAssuree.push("marEngins")
}
if (tppc.marAnimaux) {
document.querySelector('select#marAssuree option[value="marAnimaux"]').selected = true;
marAssuree.push("marAnimaux")
}
if (marAssuree.length > 0) {
updateMarAssuree()
}
M.FormSelect.init(document.querySelector('select#marAssuree'))
// Remplissage des marchandises en exposition
if(tppc.marEnExpo) {
document.getElementById('marEnExpo').checked = true
document.getElementById('marEnExpo-div').style.display = "block"
document.getElementById('nombreExposition').value = tppc.nbExpo
document.getElementById('capitalExposition').value = tppc.capExpo
document.querySelector('select#typeMarEnExp option[value="'+ tppc.typeMarExpo +'"]').selected = true;
}
M.FormSelect.init(document.querySelector('select#typeMarEnExp'))
if (tarif && tarif.typeContrat) {
//Si Le Parcours Possede Un Type De Contrat
toggleTypeContrat(tarif.typeContrat)
if (tarif.typeContrat == 'detaillee') {
document.getElementById('cotisationDetaillee').checked = true
document.getElementById('cotisationEnsemble').checked = false
} else if (tarif.typeContrat == 'ensemble') {
document.getElementById('cotisationDetaillee').checked = false
document.getElementById('cotisationEnsemble').checked = true
}
} else if (tppc.tarFlotte && tppc.tarFlotte.length > 0) {
// Si Le Parcours N'a Pas De Type De Contrat (Tarif) Mais Une flotte détaillée (Projet)
toggleTypeContrat('detaillee')
document.getElementById('cotisationDetaillee').checked = true
document.getElementById('cotisationEnsemble').checked = false
} else {
document.getElementById('cotisationEnsemble').checked = true
toggleTypeContrat('ensemble')
}
if (tarif && tarif.montantSinistre !== undefined && tarif.montantSinistre >= 0) {
document.getElementById('sinistre').value = tarif.montantSinistre
updateModuloChip(document.getElementById('chip-modulo-sinistre'), calcModSinistre(tarif.montantSinistre))
}
if (tppc.tarFlotte && Object.keys(tppc.tarFlotte).length !== 0) {
for (let i = 0; i < tppc.tarFlotte.length; i++) {
const row = tppc.tarFlotte[i];
addRowTarification(row.typeVehTarif, row.capitalTarif, row.garTarif, row.typeMarTarif, row.nbVehiculesTarif, row.primeVehTarif, row.primeHTTarif, row.modulo)
}
}
affichagePropositions()
}
function updateMarAssuree() {
const options = document.querySelectorAll('#marAssuree option:not([value=""])');
options.forEach((option) => {
if (option.selected) {
document.getElementById(option.value + '-chip').style.display = "inline-block"
} else {
document.getElementById(option.value + '-chip').style.display = "none"
}
})
const capitalVehicule = document.getElementById('capitalVehicule').value
if (isSelected('marAnimaux') && capitalVehicule > 200000) {
openModaleAniViv()
}
const selectedOpt = [...document.querySelectorAll('#marAssuree option:checked:not([value=""])')].map((option => option.value))
const moduloChipMarAssuree = document.getElementById('chip-modulo-marAssuree')
updateModuloChip(moduloChipMarAssuree, calcModMar(selectedOpt))
checkBennesGaranties()
}
function toggleTypeContrat(typeContrat) {
if (typeContrat == "ensemble") {
document.getElementById('row-tarification-vehicules').style.display = "none"
document.getElementById('card-tarif-mod-mar').style.display = "none"
document.getElementById('card-tarif-mod-mar').style.display = "none"
document.getElementById('col-capitalVehicule').style.display = "block"
document.getElementById('col-flotte').style.display = "block"
document.getElementById('col-marAssuree').style.display = "block"
document.getElementById('col-garSouhaitees').style.display = "block"
document.getElementById('card-tarif-par-vehicule').style.display = "block"
document.getElementById('card-nbr-vehicule').style.display = "block"
document.getElementById('card-tarif-mod').style.display = "none"
} else if (typeContrat == "detaillee") {
document.getElementById('row-tarification-vehicules').style.display = "block"
document.getElementById('card-tarif-mod-mar').style.display = "block"
document.getElementById('card-tarif-mod-mar').style.display = "block"
document.getElementById('card-tarif-mod').style.display = "block"
document.getElementById('col-capitalVehicule').style.display = "none"
document.getElementById('col-flotte').style.display = "none"
document.getElementById('col-marAssuree').style.display = "none"
document.getElementById('col-garSouhaitees').style.display = "none"
document.getElementById('card-tarif-par-vehicule').style.display = "none"
document.getElementById('card-nbr-vehicule').style.display = "none"
}
fillTarifCard('tarif-total-vehicule', 0.00)
}
function getGaranties() {
return [...document.querySelectorAll('[name = "garSouhaitees"]:checked')]
.map((garantie) => garantie.value)
.join('+')
}
function getGarantiesFromFlotte() {
const garSet = new Set();
const selectsArray = document.querySelectorAll('#empTableTarifVehicules tr:not(#header) [name="garTarif"]')
selectsArray.forEach((select) => {
select.value.split('+').forEach(garantie => garSet.add(garantie))
})
return [...garSet]
}
function calcModFlotte(flotte) {
if (flotte == "" || !validateField('flotte')) {
return null
}
flotte = parseFloat(flotte);
// Parcourir le JSON modFlotte pour trouver la valeur correspondante
for (let palier in objModFlotte) {
if (flotte <= parseFloat(palier)) {
return parseFloat(objModFlotte[palier]); // Retourner la valeur correspondante
}
}
return 1.00; // Par défaut, retourner 1.00 si aucune correspondance n'est trouvée
}
function calcModMar(marchandises) {
if (marchandises == "" || marchandises.length == 0) {
return null
}
if (typeof marchandises == "object") {
var modulo = 1
marchandises.forEach((mar) => {
modulo = parseFloat(modulo * objModMar[mar]['modulo'])
})
return modulo.toFixed(2)
} else {
return parseFloat(objModMar[marchandises]['modulo'])
}
}
function calcModAct(activite) {
if (activite == "") {
return null
}
if (!Object.keys(objModAct).includes(activite)) {
return null
}
return parseFloat(objModAct[activite])
}
function calcModCot(garanties, capital) {
const paliers = Object.keys(objModCot)
for (let maxMontant in paliers) {
if (capital <= parseFloat(paliers[maxMontant])) {
return parseFloat(objModCot[paliers[maxMontant]][garanties])
}
}
return null
}
function calcNbrVehiculesTotal() {
const lignes = document.querySelectorAll('#empTableTarifVehicules tr:not(#header)')
var nbrVehicules = 0
lignes.forEach((ligne) => {
nbrVehicules += parseInt(ligne.querySelector("[name='nbVehiculesTarif']").value)
})
return nbrVehicules
}
function calcPrimeMinimum(prime) {
if (prime <= objPrimeMini["IAC + Vol"]) {
if (document.getElementById('garSouhaitees-vol').checked) { //SI IAC + HIAC + VOL ou IAC + VOL
return parseFloat(objPrimeMini["IAC + Vol"])
} else { //SI IAC + HIAC ou IAC
return parseFloat(objPrimeMini["IAC + HIAC"])
}
} else {
return prime
}
}
function calcPrimeTotaleHT() {
const lignes = document.querySelectorAll('#empTableTarifVehicules tr:not(#header)')
var cotBase = 0
lignes.forEach((ligne) => {
const primeHT = parseFloat(ligne.querySelector('[name="primeHTTarif"]').value) || 0
cotBase += primeHT
})
return cotBase.toFixed(2)
}
function calcPrimeTotaleHTModulee() {
const lignes = document.querySelectorAll('#empTableTarifVehicules tr:not(#header)')
var cotBrute = 0
lignes.forEach((ligne) => {
const modMarchandise = ligne.querySelector('input[name="modulo"]').value || 0
const primeHT = ligne.querySelector('[name="primeHTTarif"]').value || 0
const primeModulee = primeHT * modMarchandise
cotBrute += primeModulee
})
return cotBrute.toFixed(2)
}
function calcPrimeMoyenne() {
const nbrVehicules = document.getElementById('flotte').value
const capital = document.getElementById('capitalVehicule').value
const selectedOpt = [...document.querySelectorAll('#marAssuree option:checked:not([value=""])')].map((option => option.value))
const tarifVehicule = calcModCot(getGaranties(), capital)
const prime = tarifVehicule * nbrVehicules
const moduloAct = calcModAct(document.getElementById('activite').value)
const moduloMar = calcModMar(selectedOpt)
const moduloCA = 1
const moduloFlotte = calcModFlotte(document.getElementById('flotte').value)
const coeffMoyen = moduloFlotte > moduloCA ? moduloCA : moduloFlotte
return Number.parseInt(prime * coeffMoyen * moduloAct * moduloMar).toFixed(2)
}
function calcPrimeMoyenneTarif() {
const moduloFlotte = calcModFlotte(calcNbrVehiculesTotal())
const moduloCA = 1
const moduloAct = calcModAct(document.getElementById('activite').value)
const coeffMoyen = moduloFlotte > moduloCA ? moduloCA : moduloFlotte
const cotMarchandise = calcPrimeTotaleHTModulee()
return Number.parseFloat(cotMarchandise * coeffMoyen * moduloAct)
}
function calcModSinistre(sinistre) {
const pourcentages = Object.keys(objModSinistre).map(Number).sort() //Récupération, conversion en float puis classement des pourcentages
const cotDetaillee = document.getElementById('cotisationDetaillee').checked
const primeMoyenne = cotDetaillee ? calcPrimeMoyenneTarif() : calcPrimeMoyenne()
sinistre = parseFloat(sinistre)
if ((primeMoyenne == 0 && sinistre == 0)) {
return 1.00
} else if (sinistre < (primeMoyenne * pourcentages[0])) { //- que 40% de la prime
return objModSinistre[pourcentages[0]]
} else if ((sinistre >= (primeMoyenne * pourcentages[0])) && (sinistre < (primeMoyenne * pourcentages[1]))) { //entre 40 et 70% de la prime
return objModSinistre[pourcentages[1]]
} else if ((sinistre >= (primeMoyenne * pourcentages[1])) && (sinistre <= (primeMoyenne * pourcentages[2]))) { //entre 40 et 70% de la prime
return objModSinistre[pourcentages[2]]
} else if (sinistre > primeMoyenne || sinistre == '') { //superieur à la prime
return null
} else {
return 1.00
}
}
function updateModuloChip(elementModulo, valeur) {
if (valeur == null) {
elementModulo.style.display = "none"
} else {
elementModulo.style.display = "inline-block"
const titreModulo = elementModulo.innerText.split(' : ')[0]
elementModulo.innerText = titreModulo + ' : x' + valeur
}
}
function checkBennesGaranties() {
const caseHIAC = document.querySelector('input[name="garSouhaitees"][value="HIAC"]')
const caseVol = document.querySelector('input[name="garSouhaitees"][value="Vol"]')
if (document.querySelector('#marAssuree option[value="marBennes"]:checked') !== null) {
const textError = "Vous ne pouvez choisir la garantie tous risques avec pour marchandise assurée : Bennes"
if (caseHIAC.checked && caseVol.checked) {
caseHIAC.checked = false
caseVol.checked = false
document.getElementById('garSouhaitees-error').innerText = textError
document.getElementById('garSouhaitees-error').style.display = "block"
} else if (caseHIAC.checked || caseVol.checked) {
document.getElementById('garSouhaitees-error').innerText = textError
document.getElementById('garSouhaitees-error').style.display = "block"
if (caseHIAC.checked) {
caseVol.disabled = true
} else if (caseVol.checked) {
caseHIAC.disabled = true
}
} else if (!caseHIAC.checked && !caseVol.checked) {
caseHIAC.disabled = false
caseVol.disabled = false
document.getElementById('garSouhaitees-error').innerText = ""
}
} else {
document.getElementById('garSouhaitees-error').innerText = ""
caseHIAC.disabled = false
caseVol.disabled = false
}
}
function checkSinistre() {
const inputSinistre = document.getElementById('sinistre')
if (validateField('sinistre'), true) {
updateSubmitButtonState('tarifFormTPPC')
if (inputSinistre.value !== "") {
const errorElement = document.getElementById('sinistre-error')
const modSinistre = calcModSinistre(inputSinistre.value)
const moduloChipSinistre = document.getElementById('chip-modulo-sinistre')
updateModuloChip(moduloChipSinistre, modSinistre)
if (projet && projet.antSin !== undefined && projet.antSin !== "" && (projet.antSin == 0 && inputSinistre.value > 0)) {
errorElement.textContent = "Vous avez renseigné " + projet.antSin + " antécédent"
errorElement.style.display = "block"
return true
}
if (modSinistre == null) {
errorElement.textContent = "Le montant d'antécédent de sinistre est supérieur au montant de la prime"
errorElement.style.display = "block"
return false
} else {
errorElement.textContent = ""
errorElement.style.display = "none"
return true
}
} else {
return false
}
}
}
function checkBennesGarantiesTarif(row) {
const typeVehicule = row.querySelector("input[name = typeVehTarif]")
const typeMar = row.querySelector("select[name = typeMarTarif]")
const garSouscrites = row.querySelector("select[name = garTarif]")
const regex = /\bbenne\b|\b.*benne.*\b/i;
if ((typeVehicule.value.match(regex) || typeMar.value == "marBennes")) {
garSouscrites.querySelector('[value="IAC+HIAC+Vol"]').disabled = true
typeMar.querySelector('[value="marBennes"]').disabled = false
if (garSouscrites.value == "IAC+HIAC+Vol") {
garSouscrites.value = ""
document.getElementById("message-BenneTousRisques").style.display = "block"
}
} else if (garSouscrites.value == "IAC+HIAC+Vol") {
typeMar.querySelector('[value="marBennes"]').disabled = true
} else {
typeMar.querySelector('[value="marBennes"]').disabled = false
garSouscrites.querySelector('[value="IAC+HIAC+Vol"]').disabled = false
document.getElementById("message-BenneTousRisques").style.display = "none"
}
var select = row.querySelectorAll('select');
M.FormSelect.init(select);
}
function checkActivite(input) {
const errorElement = document.getElementById('activite-error')
const moduloChipAct = document.getElementById('chip-modulo-activite')
if (Object.keys(objModAct).includes(input.value)) {
errorElement.textContent = ""
errorElement.style.display = "none"
updateModuloChip(moduloChipAct, calcModAct(input.value))
return true
} else {
errorElement.textContent = "Veuillez selectionner une activité parmi la liste"
errorElement.style.display = "block"
updateModuloChip(moduloChipAct, null)
return false
}
}
function openModaleAniViv() {
const elem = document.getElementById('modalAnimauxVivants');
const instance = M.Modal.getInstance(elem);
instance.open();
}
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);
}
});
}
}
function addRowTarification(typeVehTarif, capitalTarif, garTarif, typeMarTarif, nbVehiculesTarif, primeVehTarif, primeHTTarif, modulo) {
const table = document.getElementById('empTableTarifVehicules');
const newRow = table.insertRow(table.rows.length - 1);
const emptyRow = `
<tr name="tarifRow">
<td>
<input name="typeVehTarif" placeholder="Ex: Voiture" />
</td>
<td>
<input type="number" name="capitalTarif" min="0" placeholder="Non défini" />
</td>
<td>
<select name="garTarif">
<option value="Non défini" disabled selected>Garanties souscrites:
</option>
<option value="IAC">IAC</option>
<option value="IAC+HIAC">IAC + Hors IAC</option>
<option value="IAC+Vol">IAC + Vol</option>
<option value="IAC+HIAC+Vol">IAC + hors IAC + Vol</option>
</select>
</td>
<td>
<select name="typeMarTarif">
<option value="Non défini" disabled selected>Type de marchandise:
</option>
</select>
</td>
<td>
<input type="number" name="nbVehiculesTarif" min="0" placeholder="Non défini" />
</td>
<td>
<input type="number" name="primeVehTarif" min="0" placeholder="Non défini"/>
</td>
<td>
<input type="number" name="primeHTTarif" min="0" placeholder="Non défini" />
</td>
<td>
<div class="chip modulo" name="moduloTarif" id="chip-modulo-mar-tarif-`+ (table.rows.length - 1) + `" style="display : none">
Mod. Marchandise : x2
</div>
<input type="number" name="modulo" disabled
style="display : none" />
</td>
<td>
<button class="btn delete-btn" type="button">
<i class="material-icons">delete</i>
</button>
</td>
</tr>`
//Création de l'élément HTML
newRow.innerHTML = emptyRow
//Remplissage des Selects
newRow.querySelector('[name = typeMarTarif]').innerHTML = document.querySelector('tr[id=inputRow] select[name = typeMarTarif]').innerHTML
newRow.querySelector('[name = garTarif]').innerHTML = document.querySelector('tr[id=inputRow] select[name = garTarif]').innerHTML
//Ajout des valeurs
newRow.querySelector('[name = capitalTarif]').value = capitalTarif
newRow.querySelector('[name = garTarif]').value = garTarif
newRow.querySelector('[name = typeMarTarif]').value = typeMarTarif
newRow.querySelector('[name = nbVehiculesTarif]').value = nbVehiculesTarif
newRow.querySelector('[name = primeVehTarif]').value = primeVehTarif
newRow.querySelector('[name = primeHTTarif]').value = primeHTTarif
newRow.querySelector('[name = typeVehTarif]').value = typeVehTarif
const moduloInput = newRow.querySelector('[name = modulo]')
const moduloChip = newRow.querySelector('[name = moduloTarif]')
moduloInput.value = modulo
updateModuloChip(moduloChip, modulo)
var select = document.querySelectorAll('select');
M.FormSelect.init(select);
checkBennesGarantiesTarif(newRow)
emptyRowTarification()
setupTableEventListeners()
}
// Supprimer une ligne du tableau
function deleteRow(btn) {
const row = btn.parentElement.parentElement;
if (row.parentElement) {
row.parentElement.removeChild(row);
}
}
function emptyRowTarification() {
document.querySelector('[id = typeVehTarif]').value = ""
document.querySelector('[id = capitalTarif]').value = ""
document.querySelector('[id = garTarif]').value = ""
document.querySelector('[id = typeMarTarif]').value = ""
document.querySelector('[id = nbVehiculesTarif]').value = 0
document.querySelector('[id = primeVehTarif]').value = ""
document.querySelector('[id = primeHTTarif]').value = ""
document.querySelector('[id = modulo]').value = ""
document.querySelector('[id = modulo-mar-tarif-0]').style.display = "none"
checkBennesGarantiesTarif(document.getElementById('inputRow'))
var select = document.querySelectorAll('select');
M.FormSelect.init(select);
}
function fillPropCard(idCard, cardData) {
const card = document.getElementById(idCard)
const pourcentageAct = parseFloat(cardData.pourcentAct).toFixed(0)
const pourcentageMar = parseFloat(cardData.pourcentMar).toFixed(0)
const pourcentageFlotteCA = parseFloat(cardData.pourcentFlotteCA).toFixed(0)
const pourcentageFranchise = parseFloat(cardData.pourcentFranchise).toFixed(0)
const primeVehicule = parseFloat(cardData.primeVehicule).toFixed(2)
const proposition = parseFloat(cardData.proposition).toFixed(2)
const franchiseMarExpo = cardData.franchiseMarExpo
if (tarif && tarif.franchiseId && tarif.franchiseId == idCard) {
card.classList.add('selected-card')
}
card.querySelector("[id = mod-activite-" + idCard + "]").innerText = "Modulation Activité : +" + pourcentageAct + "%"
if (document.getElementById('cotisationDetaillee').checked) {
card.querySelector("[id = mod-marchandise-" + idCard + "]").style.display = "none"
} else {
card.querySelector("[id = mod-marchandise-" + idCard + "]").style.display = "block"
card.querySelector("[id = mod-marchandise-" + idCard + "]").innerText = "Modulation Marchandise : " + pourcentageMar + "%"
}
card.querySelector("[id = mod-ca-" + idCard + "]").innerText = "Modulation Flotte : " + pourcentageFlotteCA + "%"
card.querySelector("[id = mod-franchise-" + idCard + "]").innerText = "Modulation Franchise : " + pourcentageFranchise + "%"
card.querySelector("[id = prime-vehicule-" + idCard + "]").innerText = "Prime par véhicule : " + primeVehicule + "€"
document.getElementById("proposition-" + idCard).innerText = proposition + "€"
}
function fillTarifCard(idTarif, valeur) {
if (valeur == NaN || valeur == "NaN") {
valeur = 0
}
document.getElementById(idTarif).innerText = Number.parseFloat(valeur).toFixed(2) + " €"
}
function calcTarifCards() {
if (document.getElementById('cotisationDetaillee').checked) {
const tarifTousVehicules = calcPrimeTotaleHT() || 0
const tarifModuleMar = calcPrimeTotaleHTModulee() || 0
const primeMoyenne = calcPrimeMoyenneTarif() || 0
const moduloSinistre = calcModSinistre(document.getElementById('sinistre').value) || 1
const tarifModule = primeMoyenne * moduloSinistre
fillTarifCard('tarif-total-vehicule', tarifTousVehicules)
fillTarifCard('tarif-mod-mar', tarifModuleMar)
fillTarifCard('tarif-mod', tarifModule)
} else {
const inputCapital = document.getElementById('capitalVehicule')
const inputNbrVehicules = document.getElementById('flotte')
const tarifVehicule = calcModCot(getGaranties(), inputCapital.value)
const tarifTousVehicules = tarifVehicule * inputNbrVehicules.value
const tarifModule = calcPrimeMoyenne() || 0
fillTarifCard('tarif-par-vehicule', tarifVehicule)
fillTarifCard('tarif-total-vehicule', tarifTousVehicules)
fillTarifCard('tarif-nbr-vehicule', tarifModule)
}
}
function calcCard(modFranchise) {
const selectedOpt = [...document.querySelectorAll('#marAssuree option:checked:not([value=""])')].map((option => option.value))
const moduloAct = calcModAct(document.getElementById('activite').value) || 1
const moduloMar = calcModMar(selectedOpt) || 1
const moduloCA = 1
const moduloSinistre = calcModSinistre(document.getElementById('sinistre').value) || 1
var marEnExpo = 0
var franchiseMarExpo = ""
const cotDetaillee = document.getElementById('cotisationDetaillee').checked
var primeMoyenne, moduloFlotte, primeVehicule, flotte
if (cotDetaillee) {
primeMoyenne = calcPrimeMoyenneTarif()
moduloFlotte = calcModFlotte(calcNbrVehiculesTotal()) || 1
flotte = calcNbrVehiculesTotal()
} else {
primeMoyenne = calcPrimeMoyenne()
moduloFlotte = calcModFlotte(document.getElementById('flotte').value) || 1
flotte = document.getElementById('flotte').value || 1
}
const modFlotteCa = moduloCA > moduloFlotte ? moduloFlotte : moduloCA
const pourcentAct = ((100 - (parseFloat(moduloAct) * 100)) * (-1)).toFixed(0) || 0
const pourcentMar = ((100 - (parseFloat(moduloMar) * 100)) * (-1)).toFixed(0) || 0
const pourcentFranchise = ((100 - (parseFloat(modFranchise) * 100)) * (-1)).toFixed(0) || 0
const pourcentFlotteCA = ((100 - (parseFloat(modFlotteCa) * 100)) * (-1)).toFixed(0) || 0
var proposition = calcPrimeMinimum((primeMoyenne * moduloSinistre) * modFranchise) || 0
// Calcul de la majoration en exposition
if (document.getElementById('marEnExpo').checked) {
const nbExpo = document.getElementById('nombreExposition').value
const capital = document.getElementById('capitalExposition').value
const type = document.getElementById('typeMarEnExp').value
if (nbExpo && capital && type) {
if (nbExpo > 3 || capital > 50000) {
marEnExpo = nbExpo * capital * objMarEnExpo[type]['modulo'] / 100
marEnExpo = marEnExpo > proposition * 0.1 ? proposition * 0.1 : marEnExpo
franchiseMarExpo = "mini150"
} else {
marEnExpo = proposition * 0.1 < 150 ? proposition * 0.1 : 150
franchiseMarExpo = "500"
}
}
}
proposition = (proposition + marEnExpo).toFixed(2)
primeVehicule = (proposition / flotte).toFixed(2) || 0
return {
pourcentAct: pourcentAct,
pourcentMar: pourcentMar,
pourcentFlotteCA: pourcentFlotteCA,
pourcentFranchise: pourcentFranchise,
primeVehicule: primeVehicule,
proposition: proposition,
franchiseMarExpo: franchiseMarExpo
}
}
function affichagePropositions() {
const actIsIncorrect = (calcModAct(document.getElementById('activite').value) == null)
const sinIsIncorrect = checkSinistre() == false
const marIsEmpty = isMarAssureeEmpty()
document.getElementById('row-champsManquants').style.display = (actIsIncorrect || sinIsIncorrect || marIsEmpty) ? "block" : "none"
document.getElementById('propositions').style.display = (actIsIncorrect || sinIsIncorrect || marIsEmpty) ? "none" : "block"
// AFFICHAGE DES CHIPS D'ERREUR
document.getElementById('chip-sinistre').style.display = sinIsIncorrect ? "inline-block" : "none"
document.getElementById('chip-act').style.display = actIsIncorrect ? "inline-block" : "none"
document.getElementById('chip-marAssuree').style.display = marIsEmpty ? "inline-block" : "none"
if (actIsIncorrect == false || sinIsIncorrect == false) {
franchise150 = (calcCard(1));
fillPropCard(
'150',
franchise150
);
franchise300 = (calcCard(0.75));
fillPropCard(
'300',
franchise300
);
mini150 = (calcCard(0.7));
fillPropCard(
'mini150',
mini150
);
mini300 = (calcCard(0.65));
fillPropCard(
'mini300',
mini300
);
calcTarifCards();
}
}
function extractTarifTableau(selectedCardId) {
const jsonArr = [];
const table = document.getElementById("empTableTarifVehicules");
if (table && document.getElementById("cotisationDetaillee").checked) {
const rows = table.querySelectorAll('tr:not(:first-child)');
rows.forEach(row => {
const inputs = row.querySelectorAll(' input:not(.select-dropdown.dropdown-trigger), select');
const allInputsEmpty = Array.from(inputs).every(input => input.value == '' || input.value == 0);
if (!allInputsEmpty) {
const dataObj = {};
inputs.forEach(input => {
const fieldName = input.getAttribute('name');
if (fieldName) {
const fieldValue = input.value || "Non défini";
dataObj[fieldName] = fieldValue;
}
});
const selectedFranchise = extractPropoCard(selectedCardId)
const moduloTotale = (1 + parseFloat(selectedFranchise.pourcentFranchise) / 100) *
(1 + parseFloat(selectedFranchise.pourcentAct)/100) *
(1 + parseFloat(selectedFranchise.pourcentFlotteCA) / 100)
dataObj['primeVehModRefTarif'] = (moduloTotale * dataObj['primeVehTarif']).toFixed(2)
dataObj['primeHTModRefTarif'] = (moduloTotale * dataObj['primeHTTarif']).toFixed(2)
jsonArr.push(dataObj);
}
});
return jsonArr;
}
return "[]"; // Retourne un tableau JSON vide si aucune saisie n'est trouvée dans le tableau
}
function extractPropoCard(idCard) {
switch (idCard) {
case '150':
return franchise150
case '300':
return franchise300
case 'mini150':
return mini150
case 'mini300':
return mini300
}
return null
}
function isSelected(marchandise) {
const cotDetaillee = document.getElementById('cotisationDetaillee').checked
if (cotDetaillee) {
const selectedOpt = [...document.querySelectorAll('#empTableTarifVehicules [name="typeMarTarif"] ')].map((option => option.value))
return selectedOpt.includes(marchandise)
} else {
const selectedOpt = [...document.querySelectorAll('#marAssuree option:checked:not([value=""])')].map((option => option.value))
return selectedOpt.includes(marchandise)
}
}
function isMarAssureeEmpty() {
const cotDetaillee = document.getElementById('cotisationDetaillee').checked
var selectedOpt
if (cotDetaillee) {
selectedOpt = document.querySelectorAll('#empTableTarifVehicules [name="typeMarTarif"] option:checked:not([value=""]) ')
} else {
selectedOpt = document.querySelectorAll('#marAssuree option:checked:not([value=""])')
}
return selectedOpt.length == 0
}
function openModaleTarifCom(cardId) {
const franchise = extractPropoCard(cardId)
document.getElementById('tarifRefText').innerText = "Tarif de Référence : " + franchise.proposition + "€"
document.getElementById('tarifCom').value = ""
document.getElementById('commentaire').value = ""
document.getElementById('comm-OK').disabled = false
document.getElementById('tarifCom-error').style.display = "none"
document.getElementById('col-commentaire').style.display = "none"
document.getElementById('qualiteDiv').style.display = "none"
document.getElementById('comm-OK').name = cardId
document.getElementById('tarifCom').addEventListener('input', function() {
var qualitePrime
var emoji
var showComment
diff = 100 * parseFloat(document.getElementById('tarifCom').value / franchise.proposition)
if (diff < (100 + seuil) && diff > (100 - seuil)) {
emoji = "mood"
showComment = false
if (diff > 100) {
qualitePrime = "Tarif correct (+" + (diff - 100).toFixed(2) + "%)"
} else if (diff < 100) {
qualitePrime = "Tarif correct (-" + (100 - diff).toFixed(2) + "%)"
} else if (diff == 100) {
qualitePrime = "Le juste prix"
emoji = "thumb_up_alt"
}
} else {
emoji = "mood_bad"
showComment = true
if (diff > (100 + seuil)) {
qualitePrime = "Tarif trop élevé (+" + (diff - 100).toFixed(2) + "%)"
} else if (diff < (100 - seuil)) {
qualitePrime = "Tarif trop bas (-" + (100 - diff).toFixed(2) + "%)"
}
}
document.getElementById('qualiteDiv').style.display = "block"
document.getElementById('qualitePrime').innerText = qualitePrime
document.getElementById('modalTarifCom-icon').innerText = emoji
document.getElementById('modalTarifCom-icon').style.color = (emoji == "mood_bad") ? "red" : "green"
if (showComment) {
document.getElementById('tarifCom-error').style.display = "flex"
document.getElementById('col-commentaire').style.display = "flex"
if (document.getElementById('commentaire').value == "") {
document.getElementById('comm-OK').disabled = true
}
} else {
document.getElementById('comm-OK').disabled = false
document.getElementById('tarifCom-error').style.display = "none"
document.getElementById('col-commentaire').style.display = "none"
}
})
const modal = document.getElementById('modalTarifCom')
const instance = M.Modal.getInstance(modal);
instance.open();
}
// Gérer la soumission du formulaire
async function submitForm(selectedCardId) {
const cotDetaillee = document.getElementById('cotisationDetaillee').checked
const bodyTarif = {
montantSinistre: document.getElementById('sinistre').value,
franchise150: franchise150,
franchise300: franchise300,
franchiseMini150: mini150,
franchiseMini300: mini300,
franchiseId: selectedCardId,
tarifRef: extractPropoCard(selectedCardId).proposition,
typeContrat: document.querySelector('[name="typeContrat"]:checked').value,
}
const responseTarif = await fetch(`/tppc/createTarif`, {
method: 'POST',
body: JSON.stringify(bodyTarif),
headers: {
'Content-Type': 'application/json',
},
});
const dataTarif = await responseTarif.json();
if (dataTarif.valid) {
const idTarif = dataTarif.tarif.id
const bodyTPPC = {
actAssuree: document.getElementById('activite').value,
cotCapVeh: cotDetaillee ? '' : document.getElementById('capitalVehicule').value,
tarFlotte: extractTarifTableau(selectedCardId),
nbVehic: cotDetaillee ? '' : document.getElementById('flotte').value,
garanties: cotDetaillee ? getGarantiesFromFlotte() : [...document.querySelectorAll('[name = "garSouhaitees"]:checked')].map((select) => select.value),
tarif: idTarif,
projet: tppc.projet || '',
primeHT: document.getElementById('tarifCom').value,
commentaire: document.getElementById('commentaire').value,
marOrdinaires: isSelected('marOrdinaires'),
marBennes: isSelected('marBennes'),
marDenreesHorsTemp: isSelected('marDenreesHorsTemp'),
marRisques: isSelected('marRisques'),
marEngins: isSelected('marEngines'),
marFranchise: tppc.marFranchise || '',
marEnExpo: document.getElementById('marEnExpo').checked,
marCiternes: isSelected('marCiternes'),
marAnimaux: isSelected('marAnimaux'),
marDenreesSousTemp: isSelected('marDenreesSousTemp'),
nbExpo: document.getElementById('nombreExposition').value || 0,
capExpo: document.getElementById('capitalExposition').value || 0,
typeMarExpo: document.getElementById('typeMarEnExp').value || '',
franchiseMarExpo: extractPropoCard(selectedCardId).franchiseMarExpo,
}
const responseTPPC = await fetch(`/tppc/create`, {
method: 'POST',
body: JSON.stringify(bodyTPPC),
headers: {
'Content-Type': 'application/json',
},
});
const data = await responseTPPC.json();
if (data.valid) {
const idProjet = data.tppc.id;
// Mettre à jour le champ "enCours" dans le contrat avec l'ID de la nouvelle saisie RC
const responseContratEnCours = await fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${idProjet}`, {
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": idProjet,
"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) {
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 création de la saisie dans la collection TPPC :', data.message);
}
} else {
console.log('Echec lors de la création de la saisie dans la collection TPPCtarif :', data.message);
}
}
// Exposer init globalement pour y accéder depuis l'extérieur
window.initSubmenuForm = init;
})();