3441 lines
170 KiB
JavaScript
3441 lines
170 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, rc, projet, tarif;
|
||
|
||
let modRCActRCC, modRCMar, modRCZone, modRCActCompl, modRCGarAdd;
|
||
let hasSavedGrilleData = false; // évite d'écraser une grille déjà enregistrée
|
||
|
||
// Initialisation des tag pour select
|
||
var tagAnimauxVivants = false;
|
||
var tagMultimodal = false;
|
||
var tagDemenageur = false;
|
||
var tagDemenageurParticulier = false;
|
||
var tagDemenageurParticulierDeclaree = false;
|
||
var tagDemenageurParticulierAdvalorem = false;
|
||
var tagGardeMeubles = false;
|
||
var tagVoiturier = false;
|
||
var tagDemenageurEntrInter = false;
|
||
|
||
// 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'));
|
||
client = contrat?.["@expand"]?.client || null;
|
||
intermediaire = contrat?.["@expand"]?.intermediaire || null;
|
||
|
||
// Récupérer les données RC depuis la nouvelle structure (EXACTEMENT comme TPPC)
|
||
rc = contrat?.["@expand"]?.enCours || null; // RC principal
|
||
projet = rc?.["@expand"]?.projet || null; // Données projet (normalized by contratService)
|
||
tarif = rc?.["@expand"]?.tarif || null; // Données tarif (normalized by contratService)
|
||
|
||
// Exposer ces variables globalement pour que rc-orchestrator puisse y accéder
|
||
window.rc = rc;
|
||
window.tarif = tarif;
|
||
window.projet = projet;
|
||
|
||
console.log("Initialisation pour formulaire projet :", parcours);
|
||
console.log("📊 RC:", rc);
|
||
console.log("📊 Tarif:", tarif);
|
||
console.log("📊 Projet:", projet);
|
||
|
||
loadModulateurs();
|
||
|
||
// Appel des différentes fonctions d'initialisation
|
||
setupEventListeners();
|
||
populateFormData();
|
||
setupTarifImpactListeners();
|
||
updateSubmitButtonState('projetForm');
|
||
}
|
||
|
||
let tarifOriginalData = null;
|
||
|
||
async function loadModulateurs() {
|
||
try {
|
||
const response = await fetch('/rc/modulo/activiteRCC');
|
||
const data = await response.json();
|
||
if (data.valid) {
|
||
modRCActRCC = data.objRetourne;
|
||
}
|
||
const response2 = await fetch('/rc/modulo/marchandiseRC');
|
||
const data2 = await response2.json();
|
||
if (data2.valid) {
|
||
modRCMar = data2.objRetourne;
|
||
}
|
||
const response3 = await fetch('/rc/modulo/zoneRC');
|
||
const data3 = await response3.json();
|
||
if (data3.valid) {
|
||
modRCZone = data3.objRetourne;
|
||
}
|
||
const response4 = await fetch('/rc/modulo/activiteComplRC');
|
||
const data4 = await response4.json();
|
||
if (data4.valid) {
|
||
modRCActCompl = data4.objRetourne;
|
||
}
|
||
const response5 = await fetch('/rc/modulo/garAdditionelRC');
|
||
const data5 = await response5.json();
|
||
if (data5.valid) {
|
||
modRCGarAdd = data5.objRetourne;
|
||
}
|
||
} catch (error) {
|
||
console.error('Erreur lors du chargement des modulateurs:', error);
|
||
}
|
||
}
|
||
|
||
function saveOriginalTarifData() {
|
||
if (!tarif || !tarif.id) return;
|
||
|
||
const garantieRCCSelector = document.getElementById('garantieRCC-selector');
|
||
let garantiesRCC = [];
|
||
if (garantieRCCSelector) {
|
||
garantiesRCC = Array.from(garantieRCCSelector.selectedOptions).map(opt => opt.value);
|
||
} else if (projet) {
|
||
if (projet.extRCCConfie) garantiesRCC.push('contenant-confie');
|
||
if (projet.extRCCTPPC) garantiesRCC.push('tppc');
|
||
if (projet.extRCCModifCalArrim) garantiesRCC.push('modif-calage-arrimage');
|
||
if (projet.extRCCFerroutage) garantiesRCC.push('ferroutage');
|
||
if (projet.extRCCFraisRecons) garantiesRCC.push('frais-reconstitution');
|
||
if (projet.extRCCRegie) garantiesRCC.push('regie');
|
||
if (projet.extRCCSansMontageDemontage) garantiesRCC.push('sans-montage-demontage');
|
||
}
|
||
|
||
const parseArray = (value) => {
|
||
if (Array.isArray(value)) return value;
|
||
if (typeof value === 'string') {
|
||
try {
|
||
return JSON.parse(value);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
return [];
|
||
};
|
||
|
||
tarifOriginalData = {
|
||
checkVoiturier: rc?.checkVoiturier || false,
|
||
checkLoueur: rc?.checkLoueur || false,
|
||
checkCommissionnaire: rc?.checkCommissionnaire || false,
|
||
checkDemenageur: rc?.checkDemenageur || false,
|
||
checkLogistique: rc?.checkLogistique || false,
|
||
checkAutocariste: rc?.checkAutocariste || false,
|
||
checkAutres: rc?.checkAutres || false,
|
||
capitalVoiturier: rc?.capitalVoiturier || 0,
|
||
capitalCommissionnaire: rc?.capitalCommissionnaire || 0,
|
||
capitalDemenageur: rc?.capitalDemenageur || 0,
|
||
capitalLogistique: rc?.capitalLogistique || 0,
|
||
capitalAutocariste: rc?.capitalAutocariste || 0,
|
||
capitalAutres: rc?.capitalAutres || 0,
|
||
marchandisesVoiturier: parseArray(rc?.marchandisesVoiturier),
|
||
marchandisesCommissionnaire: parseArray(rc?.marchandisesCommissionnaire),
|
||
marchandisesDemenageur: parseArray(rc?.marchandisesDemenageur),
|
||
marchandisesLogistique: parseArray(rc?.marchandisesLogistique),
|
||
marchandisesAutocariste: parseArray(rc?.marchandisesAutocariste),
|
||
marchandisesAutres: parseArray(rc?.marchandisesAutres),
|
||
activitesVoiturier: parseArray(rc?.activitesVoiturier),
|
||
activitesCommissionnaire: parseArray(rc?.activitesCommissionnaire),
|
||
activitesDemenageur: parseArray(rc?.activitesDemenageur),
|
||
activitesLogistique: parseArray(rc?.activitesLogistique),
|
||
zone1: rc?.zone1 || false,
|
||
zone2: rc?.zone2 || false,
|
||
zone3: rc?.zone3 || false,
|
||
zone4: rc?.zone4 || false,
|
||
zone5: rc?.zone5 || false,
|
||
zone6: rc?.zone6 || false,
|
||
typeCotisation: rc?.typeCotisation || 'revisable',
|
||
checkRCE: rc?.checkRCE || false,
|
||
garantiesRCC: garantiesRCC,
|
||
ca: rc?.chiffreAffaires || tarif?.ca || '',
|
||
pj: tarif?.checkPJ || false
|
||
};
|
||
}
|
||
|
||
function checkTarifImpact(fieldType, fieldValue) {
|
||
if (!tarif || !tarif.id || !tarifOriginalData) return false;
|
||
|
||
switch(fieldType) {
|
||
case 'activity':
|
||
return checkActivityImpact(fieldValue);
|
||
case 'marchandise':
|
||
return checkMarchandiseImpact(fieldValue);
|
||
case 'zone':
|
||
return checkZoneImpact(fieldValue);
|
||
case 'activiteCompl':
|
||
return checkActiviteComplImpact(fieldValue);
|
||
case 'typeCotisation':
|
||
return fieldValue === 'forfaitaire' && tarifOriginalData.typeCotisation === 'forfaitaire';
|
||
default:
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function checkActivityImpact(activityData) {
|
||
if (!modRCActRCC) return false;
|
||
|
||
const activities = ['checkVoiturier', 'checkCommissionnaire', 'checkDemenageur', 'checkLogistique', 'checkAutocariste', 'checkAutres'];
|
||
for (let act of activities) {
|
||
if (activityData[act] !== tarifOriginalData[act]) return true;
|
||
const capitalKey = act.replace('check', 'capital');
|
||
const originalCapital = parseFloat(tarifOriginalData[capitalKey]) || 0;
|
||
const currentCapital = parseFloat(activityData[capitalKey]) || 0;
|
||
if (Math.abs(originalCapital - currentCapital) > 0.01) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function checkMarchandiseImpact(marchandiseData) {
|
||
if (!modRCMar) return false;
|
||
|
||
const normalizeArray = (arr) => {
|
||
if (!arr) return [];
|
||
const normalized = Array.isArray(arr) ? arr : (typeof arr === 'string' ? JSON.parse(arr) : []);
|
||
return normalized.map(item => String(item).trim()).sort();
|
||
};
|
||
|
||
const marchandiseKeys = ['marchandisesVoiturier', 'marchandisesCommissionnaire', 'marchandisesDemenageur',
|
||
'marchandisesLogistique', 'marchandisesAutocariste', 'marchandisesAutres'];
|
||
for (let key of marchandiseKeys) {
|
||
const original = normalizeArray(tarifOriginalData[key]);
|
||
const current = normalizeArray(marchandiseData[key]);
|
||
if (JSON.stringify(original) !== JSON.stringify(current)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function checkZoneImpact(zoneData) {
|
||
if (!modRCZone) return false;
|
||
|
||
function getMaxZoneCoefficient(zones) {
|
||
let maxRCC = 1;
|
||
let maxRCE = 1;
|
||
|
||
const zoneLabels = [
|
||
"France Métropolitaine et pays limitrophes",
|
||
"Union Européenne",
|
||
"Autres pays européens sauf Russie et Ukraine (y compris UK et Norvège)",
|
||
"Pays du Maghreb et Amérique du Nord ( USA / Canada / Mexique )",
|
||
"Amérique Centrale et Sud / Caraïbes, Asie et Océanie",
|
||
"Afrique Hors Maghreb / Proche Orient / Moyen Orient"
|
||
];
|
||
|
||
for (let i = 1; i <= 6; i++) {
|
||
if (zones[`zone${i}`]) {
|
||
const zoneKey = zoneLabels[i - 1];
|
||
if (modRCZone[zoneKey]) {
|
||
if (typeof modRCZone[zoneKey].modRCC === "number") {
|
||
maxRCC = Math.max(maxRCC, modRCZone[zoneKey].modRCC);
|
||
}
|
||
if (typeof modRCZone[zoneKey].modRCE === "number") {
|
||
maxRCE = Math.max(maxRCE, modRCZone[zoneKey].modRCE);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return { maxRCC, maxRCE };
|
||
}
|
||
|
||
const originalMax = getMaxZoneCoefficient(tarifOriginalData);
|
||
const currentMax = getMaxZoneCoefficient(zoneData);
|
||
|
||
return originalMax.maxRCC !== currentMax.maxRCC || originalMax.maxRCE !== currentMax.maxRCE;
|
||
}
|
||
|
||
function checkActiviteComplImpact(activiteComplData) {
|
||
if (!modRCActCompl) return false;
|
||
|
||
const activiteKeys = ['activitesVoiturier', 'activitesCommissionnaire', 'activitesDemenageur', 'activitesLogistique'];
|
||
for (let key of activiteKeys) {
|
||
const original = Array.isArray(tarifOriginalData[key]) ? tarifOriginalData[key] : (tarifOriginalData[key] ? JSON.parse(tarifOriginalData[key]) : []);
|
||
const current = Array.isArray(activiteComplData[key]) ? activiteComplData[key] : (activiteComplData[key] ? JSON.parse(activiteComplData[key]) : []);
|
||
if (JSON.stringify(original.sort()) !== JSON.stringify(current.sort())) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function getCurrentActiviteComplData() {
|
||
const activitesCompl = {
|
||
activitesVoiturier: getActivitesComplFromForm('actComplVoiturier/Loueur'),
|
||
activitesCommissionnaire: getActivitesComplFromForm('actComplCommissionnaire de Transport'),
|
||
activitesDemenageur: getActivitesComplFromForm('actComplDéménageur'),
|
||
activitesLogistique: getActivitesComplFromForm('actComplLogistique')
|
||
};
|
||
return activitesCompl;
|
||
}
|
||
|
||
function getActivitesComplFromForm(containerName) {
|
||
const container = document.querySelector(`[name="${containerName}"]`);
|
||
if (!container) return [];
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]:checked');
|
||
const activites = [];
|
||
checkboxes.forEach(cb => {
|
||
const text = cb.nextElementSibling ? cb.nextElementSibling.textContent.trim() : cb.value;
|
||
activites.push(text);
|
||
});
|
||
return activites;
|
||
}
|
||
|
||
let lastChangedField = null;
|
||
let lastChangedValue = null;
|
||
let isRestoringValue = false;
|
||
|
||
function showTarifImpactModal(callback, fieldElement, originalValue) {
|
||
const modal = document.getElementById('modalModif');
|
||
if (!modal) return;
|
||
|
||
const instance = M.Modal.getInstance(modal);
|
||
|
||
lastChangedField = fieldElement;
|
||
lastChangedValue = originalValue;
|
||
|
||
const okBtn = document.getElementById('modif-OK');
|
||
const noBtn = document.getElementById('modif-NO');
|
||
|
||
if (okBtn) {
|
||
okBtn.onclick = function() {
|
||
instance.close();
|
||
if (callback) callback(true);
|
||
};
|
||
}
|
||
|
||
if (noBtn) {
|
||
noBtn.onclick = function() {
|
||
instance.close();
|
||
isRestoringValue = true;
|
||
|
||
if (lastChangedField && lastChangedValue !== null) {
|
||
if (lastChangedField.tagName === 'INPUT') {
|
||
lastChangedField.value = lastChangedValue;
|
||
} else if (lastChangedField.tagName === 'SELECT') {
|
||
if (lastChangedField.multiple && Array.isArray(lastChangedValue)) {
|
||
Array.from(lastChangedField.options).forEach(opt => {
|
||
opt.selected = lastChangedValue.includes(opt.value);
|
||
});
|
||
} else {
|
||
lastChangedField.value = lastChangedValue;
|
||
}
|
||
M.FormSelect.init(lastChangedField);
|
||
|
||
if (lastChangedField.id === 'activity-selector') {
|
||
handleActivitySelection();
|
||
}
|
||
} else if (lastChangedField.type === 'checkbox' || lastChangedField.type === 'radio') {
|
||
lastChangedField.checked = lastChangedValue;
|
||
}
|
||
}
|
||
|
||
setTimeout(() => {
|
||
isRestoringValue = false;
|
||
}, 100);
|
||
|
||
if (callback) callback(false);
|
||
};
|
||
}
|
||
|
||
instance.open();
|
||
}
|
||
|
||
function setupTarifImpactListeners() {
|
||
if (!tarif || !tarif.id) return;
|
||
|
||
setTimeout(() => {
|
||
saveOriginalTarifData();
|
||
}, 500);
|
||
|
||
const activitySelector = document.getElementById('activity-selector');
|
||
if (activitySelector) {
|
||
activitySelector.addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentActivityData();
|
||
if (checkTarifImpact('activity', currentData)) {
|
||
e.stopImmediatePropagation();
|
||
e.preventDefault();
|
||
const originalSelection = Array.from(this.options).filter(opt => {
|
||
const wasSelected = tarifOriginalData.checkVoiturier && (opt.value === 'voiturier' || opt.value === 'loueur') ||
|
||
tarifOriginalData.checkCommissionnaire && opt.value === 'commissionnaire-multimodal' ||
|
||
tarifOriginalData.checkDemenageur && (opt.value === 'demenageur-particulier' || opt.value === 'demenageur-entreprise' || opt.value === 'demenageur-interne') ||
|
||
tarifOriginalData.checkLogistique && (opt.value === 'entrepositaire-depositaire' || opt.value === 'prestataire-logistique') ||
|
||
tarifOriginalData.checkAutocariste && opt.value === 'autocariste' ||
|
||
tarifOriginalData.checkAutres && opt.value === 'autres';
|
||
return wasSelected;
|
||
}).map(opt => opt.value);
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalSelection);
|
||
return false;
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
|
||
const marchandiseSelector = document.getElementById('marchandise-selector');
|
||
if (marchandiseSelector) {
|
||
let lastMarchandiseSelection = Array.from(marchandiseSelector.selectedOptions).map(opt => opt.value);
|
||
|
||
marchandiseSelector.addEventListener('mousedown', function() {
|
||
if (!isRestoringValue) {
|
||
lastMarchandiseSelection = Array.from(this.selectedOptions).map(opt => opt.value);
|
||
}
|
||
}, true);
|
||
|
||
marchandiseSelector.addEventListener('change', function(e) {
|
||
if (isRestoringValue) {
|
||
handleMarchandiseSelection();
|
||
return;
|
||
}
|
||
|
||
const originalSelection = lastMarchandiseSelection;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentMarchandiseData();
|
||
if (checkTarifImpact('marchandise', currentData)) {
|
||
e.stopImmediatePropagation();
|
||
e.preventDefault();
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalSelection);
|
||
} else {
|
||
lastMarchandiseSelection = Array.from(this.selectedOptions).map(opt => opt.value);
|
||
handleMarchandiseSelection();
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
|
||
for (let i = 1; i <= 6; i++) {
|
||
const zoneCheckbox = document.getElementById(`zone${i}`);
|
||
if (zoneCheckbox) {
|
||
zoneCheckbox.addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
const checkboxId = this.id;
|
||
const originalChecked = tarifOriginalData[checkboxId] || false;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
e.stopImmediatePropagation();
|
||
e.preventDefault();
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalChecked);
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
}
|
||
|
||
const garantieRCCSelector = document.getElementById('garantieRCC-selector');
|
||
if (garantieRCCSelector) {
|
||
garantieRCCSelector.addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentGarantieRCCData();
|
||
if (checkGarantieRCCImpact(currentData)) {
|
||
e.stopImmediatePropagation();
|
||
const originalSelection = Array.from(this.selectedOptions).map(opt => opt.value);
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalSelection);
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
|
||
const activiteComplContainers = [
|
||
'actComplVoiturier/Loueur',
|
||
'actComplCommissionnaire de Transport',
|
||
'actComplDéménageur',
|
||
'actComplLogistique'
|
||
];
|
||
|
||
activiteComplContainers.forEach(containerName => {
|
||
const container = document.querySelector(`[name="${containerName}"]`);
|
||
if (container) {
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
|
||
checkboxes.forEach(checkbox => {
|
||
checkbox.addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
const originalChecked = !this.checked;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentActiviteComplData();
|
||
if (checkTarifImpact('activiteCompl', currentData)) {
|
||
e.stopImmediatePropagation();
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalChecked);
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
});
|
||
}
|
||
});
|
||
|
||
const radioButtonsCot = document.getElementsByName('cotisation');
|
||
for (let i = 0; i < radioButtonsCot.length; i++) {
|
||
radioButtonsCot[i].addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const originalValue = tarifOriginalData.typeCotisation;
|
||
if (this.value !== originalValue) {
|
||
e.stopImmediatePropagation();
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalValue);
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
|
||
const capitalFields = ['voiturier', 'loueur', 'commissionnaire-multimodal', 'demenageur-particulier',
|
||
'demenageur-particulier-dommage', 'demenageur-particulier-advalorem',
|
||
'demenageur-entreprise', 'demenageur-interne', 'entrepositaire-depositaire',
|
||
'prestataire-logistique', 'autocariste', 'autres'];
|
||
|
||
capitalFields.forEach(fieldId => {
|
||
const field = document.getElementById(fieldId);
|
||
if (field) {
|
||
let originalValue = field.value || field.dataset.defaultValue || '';
|
||
field.addEventListener('input', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentActivityData();
|
||
if (checkTarifImpact('activity', currentData)) {
|
||
const currentValue = this.value;
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalValue);
|
||
} else {
|
||
originalValue = this.value;
|
||
}
|
||
}, 200);
|
||
});
|
||
}
|
||
});
|
||
|
||
const observer = new MutationObserver(function(mutations) {
|
||
mutations.forEach(function(mutation) {
|
||
if (mutation.addedNodes.length) {
|
||
capitalFields.forEach(fieldId => {
|
||
const field = document.getElementById(fieldId);
|
||
if (field && !field.hasAttribute('data-tarif-listener')) {
|
||
field.setAttribute('data-tarif-listener', 'true');
|
||
let originalValue = field.value || field.dataset.defaultValue || '';
|
||
field.addEventListener('input', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
const currentData = getCurrentActivityData();
|
||
if (checkTarifImpact('activity', currentData)) {
|
||
const currentValue = this.value;
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalValue);
|
||
} else {
|
||
originalValue = this.value;
|
||
}
|
||
}, 200);
|
||
});
|
||
}
|
||
});
|
||
}
|
||
});
|
||
});
|
||
|
||
observer.observe(document.body, {
|
||
childList: true,
|
||
subtree: true
|
||
});
|
||
|
||
const switchPJ = document.getElementById('switchPJ');
|
||
if (switchPJ) {
|
||
switchPJ.addEventListener('change', function(e) {
|
||
if (isRestoringValue) return;
|
||
|
||
const originalChecked = tarifOriginalData.pj || false;
|
||
|
||
setTimeout(() => {
|
||
if (!tarif || !tarif.id || !tarifOriginalData || isRestoringValue) return;
|
||
if (this.checked !== originalChecked) {
|
||
e.stopImmediatePropagation();
|
||
e.preventDefault();
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalChecked);
|
||
}
|
||
}, 200);
|
||
}, true);
|
||
}
|
||
}
|
||
|
||
function checkGarantieRCCImpact(garantieData) {
|
||
if (!modRCActCompl && !modRCGarAdd) return false;
|
||
|
||
const garantiesImpactantes = ['contenant-confie', 'tppc'];
|
||
const originalGaranties = tarifOriginalData?.garantiesRCC || [];
|
||
const currentGaranties = garantieData || [];
|
||
|
||
for (let garantie of garantiesImpactantes) {
|
||
const wasSelected = originalGaranties.includes(garantie);
|
||
const isSelected = currentGaranties.includes(garantie);
|
||
if (wasSelected !== isSelected) return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
function getCurrentActivityData() {
|
||
const activitySelector = document.getElementById('activity-selector');
|
||
const selectedActivities = Array.from(activitySelector.selectedOptions).map(opt => opt.value);
|
||
|
||
return {
|
||
checkVoiturier: selectedActivities.includes('voiturier') || selectedActivities.includes('loueur'),
|
||
checkCommissionnaire: selectedActivities.includes('commissionnaire-multimodal'),
|
||
checkDemenageur: selectedActivities.includes('demenageur-particulier') || selectedActivities.includes('demenageur-entreprise') || selectedActivities.includes('demenageur-interne'),
|
||
checkLogistique: selectedActivities.includes('entrepositaire-depositaire') || selectedActivities.includes('prestataire-logistique'),
|
||
checkAutocariste: selectedActivities.includes('autocariste'),
|
||
checkAutres: selectedActivities.includes('autres'),
|
||
capitalVoiturier: document.getElementById("voiturier") ? parseFloat(document.getElementById("voiturier").value) || 0 : (document.getElementById("select-voiturier")?.dataset.defaultValue ? parseFloat(document.getElementById("select-voiturier").dataset.defaultValue) : 0),
|
||
capitalCommissionnaire: document.getElementById("commissionnaire-multimodal") ? parseFloat(document.getElementById("commissionnaire-multimodal").value) || 0 : (document.getElementById("select-commissionnaire-multimodal")?.dataset.defaultValue ? parseFloat(document.getElementById("select-commissionnaire-multimodal").dataset.defaultValue) : 0),
|
||
capitalDemenageur: document.getElementById("demenageur-particulier") ? parseFloat(document.getElementById("demenageur-particulier").value) || 0 : (document.getElementById("select-demenageur-particulier")?.dataset.defaultValue ? parseFloat(document.getElementById("select-demenageur-particulier").dataset.defaultValue) : 0),
|
||
capitalLogistique: document.getElementById("entrepositaire-depositaire") ? parseFloat(document.getElementById("entrepositaire-depositaire").value) || 0 : (document.getElementById("select-entrepositaire-depositaire")?.dataset.defaultValue ? parseFloat(document.getElementById("select-entrepositaire-depositaire").dataset.defaultValue) : 0)
|
||
};
|
||
}
|
||
|
||
function getCurrentMarchandiseData() {
|
||
const selectedMarchandises = getSelectedMarchandises();
|
||
const marchandiseTexts = selectedMarchandises.map(val => {
|
||
const option = document.querySelector(`#marchandise-selector option[value="${val}"]`);
|
||
return option ? option.textContent.trim() : val;
|
||
});
|
||
|
||
return {
|
||
marchandisesVoiturier: marchandiseTexts,
|
||
marchandisesCommissionnaire: marchandiseTexts,
|
||
marchandisesDemenageur: marchandiseTexts,
|
||
marchandisesLogistique: marchandiseTexts,
|
||
marchandisesAutocariste: marchandiseTexts,
|
||
marchandisesAutres: marchandiseTexts
|
||
};
|
||
}
|
||
|
||
function getCurrentZoneData() {
|
||
const zone1 = document.getElementById("zone1");
|
||
const zone2 = document.getElementById("zone2");
|
||
return {
|
||
zone1: zone1 && (zone1.checked || zone1.disabled),
|
||
zone2: zone2 && (zone2.checked || zone2.disabled),
|
||
zone3: document.getElementById("zone3") && document.getElementById("zone3").checked,
|
||
zone4: document.getElementById("zone4") && document.getElementById("zone4").checked,
|
||
zone5: document.getElementById("zone5") && document.getElementById("zone5").checked,
|
||
zone6: document.getElementById("zone6") && document.getElementById("zone6").checked
|
||
};
|
||
}
|
||
|
||
function getCurrentGarantieRCCData() {
|
||
const selector = document.getElementById('garantieRCC-selector');
|
||
return Array.from(selector.selectedOptions).map(opt => opt.value);
|
||
}
|
||
|
||
function getSelectedMarchandises() {
|
||
const selector = document.getElementById('marchandise-selector');
|
||
return Array.from(selector.selectedOptions).map(opt => opt.value);
|
||
}
|
||
|
||
function prefillFromTarif() {
|
||
if (!tarif || !rc) {
|
||
console.log('⚠️ Pas de données tarif/rc pour pré-remplir');
|
||
return;
|
||
}
|
||
|
||
console.log('📝 Pré-remplissage depuis tarif...', { rc, tarif });
|
||
|
||
function parseArray(value) {
|
||
if (Array.isArray(value)) return value;
|
||
if (typeof value === 'string') {
|
||
try {
|
||
return JSON.parse(value);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
return [];
|
||
}
|
||
|
||
const activitySelector = document.getElementById('activity-selector');
|
||
const marchandiseSelector = document.getElementById('marchandise-selector');
|
||
|
||
// ===== ACTIVITÉS =====
|
||
|
||
// Voiturier
|
||
if (rc.checkVoiturier && !projet?.actVoiturier && activitySelector) {
|
||
console.log(' ✓ Sélection Voiturier, capital:', rc.capitalVoiturier);
|
||
const voiturierOption = activitySelector.querySelector('option[value="voiturier"]');
|
||
if (voiturierOption) {
|
||
voiturierOption.selected = true;
|
||
if (rc.capitalVoiturier) {
|
||
voiturierOption.setAttribute('data-default-value', rc.capitalVoiturier);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Loueur (souvent coché avec Voiturier)
|
||
if (rc.checkVoiturier && !projet?.actLoueur && activitySelector) {
|
||
console.log(' ✓ Sélection Loueur (car Voiturier coché)');
|
||
const loueurOption = activitySelector.querySelector('option[value="loueur"]');
|
||
if (loueurOption) {
|
||
loueurOption.selected = true;
|
||
}
|
||
}
|
||
|
||
// Commissionnaire → Commissionnaire multimodal
|
||
if (rc.checkCommissionnaire && !projet?.actMultimodal && activitySelector) {
|
||
console.log(' ✓ Sélection Commissionnaire multimodal, capital:', rc.capitalCommissionnaire);
|
||
const multimodalOption = activitySelector.querySelector('option[value="commissionnaire-multimodal"]');
|
||
if (multimodalOption) {
|
||
multimodalOption.selected = true;
|
||
if (rc.capitalCommissionnaire) {
|
||
multimodalOption.setAttribute('data-default-value', rc.capitalCommissionnaire);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Déménageur → Déménageur d'entreprises (pas particuliers)
|
||
if (rc.checkDemenageur && !projet?.actDemEntr && activitySelector) {
|
||
console.log(' ✓ Sélection Déménageur d\'entreprises, capital:', rc.capitalDemenageur);
|
||
const demenageurOption = activitySelector.querySelector('option[value="demenageur-entreprise"]');
|
||
if (demenageurOption) {
|
||
demenageurOption.selected = true;
|
||
if (rc.capitalDemenageur) {
|
||
demenageurOption.setAttribute('data-default-value', rc.capitalDemenageur);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Logistique → Prestataire logistique
|
||
if (rc.checkLogistique && !projet?.actPrestaLog && activitySelector) {
|
||
console.log(' ✓ Sélection Prestataire logistique, capital:', rc.capitalLogistique);
|
||
const logistiqueOption = activitySelector.querySelector('option[value="prestataire-logistique"]');
|
||
if (logistiqueOption) {
|
||
logistiqueOption.selected = true;
|
||
if (rc.capitalLogistique) {
|
||
logistiqueOption.setAttribute('data-default-value', rc.capitalLogistique);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Autocariste
|
||
if (rc.checkAutocariste && activitySelector) {
|
||
console.log(' ✓ Sélection Autocariste, capital:', rc.capitalAutocariste);
|
||
const autocaristeOption = activitySelector.querySelector('option[value="autocariste"]');
|
||
if (autocaristeOption) {
|
||
autocaristeOption.selected = true;
|
||
if (rc.capitalAutocariste) {
|
||
autocaristeOption.setAttribute('data-default-value', rc.capitalAutocariste);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Autres
|
||
if (rc.checkAutres && activitySelector) {
|
||
console.log(' ✓ Sélection Autres activités, capital:', rc.capitalAutres);
|
||
const autresOption = activitySelector.querySelector('option[value="autres"]');
|
||
if (autresOption) {
|
||
autresOption.selected = true;
|
||
if (rc.capitalAutres) {
|
||
autresOption.setAttribute('data-default-value', rc.capitalAutres);
|
||
}
|
||
}
|
||
}
|
||
|
||
// IMPORTANT : Trigger change event pour que Materialize mette à jour l'affichage
|
||
if (activitySelector) {
|
||
console.log(' 🔄 Trigger change event sur activity-selector');
|
||
const changeEvent = new Event('change', { bubbles: true });
|
||
activitySelector.dispatchEvent(changeEvent);
|
||
|
||
// Réinitialiser Materialize FormSelect
|
||
setTimeout(() => {
|
||
if (window.M && window.M.FormSelect) {
|
||
window.M.FormSelect.init(activitySelector);
|
||
console.log(' ✅ Materialize FormSelect réinitialisé');
|
||
}
|
||
}, 100);
|
||
}
|
||
|
||
// ===== MARCHANDISES =====
|
||
|
||
if (marchandiseSelector) {
|
||
const allMarchandises = [
|
||
...(parseArray(rc.marchandisesVoiturier)),
|
||
...(parseArray(rc.marchandisesCommissionnaire)),
|
||
...(parseArray(rc.marchandisesDemenageur)),
|
||
...(parseArray(rc.marchandisesLogistique)),
|
||
...(parseArray(rc.marchandisesAutocariste)),
|
||
...(parseArray(rc.marchandisesAutres))
|
||
];
|
||
|
||
const uniqueMarchandises = [...new Set(allMarchandises)];
|
||
console.log(' 📦 Marchandises:', uniqueMarchandises);
|
||
|
||
const marchandiseMapping = {
|
||
'Marchandises ordinaires': 'ordinaire',
|
||
'Marchandises ordinaires et assimilées, les marchandises dangereuses dans le respect de la réglementation': 'ordinaire',
|
||
'Véhicules roulants': 'roulant',
|
||
'Engins de chantier et engins agricoles': 'engins-chantier-agricole',
|
||
'Engins de chantier': 'engins-chantier-agricole',
|
||
'Véhicules roulants dans le cadre d\'une activité de déménagement': 'roulant-demenagement',
|
||
'Mobiliers usagés – Objets et effets personnels en déménagement': 'mobilier-usages',
|
||
'Mobiliers en déménagement': 'mobilier-usages',
|
||
'Marchandises périssables sous température dirigée': 'perissable-temperature-dirigee',
|
||
'Marchandises périssables': 'perissable-temperature-dirigee',
|
||
'Animaux vivants': 'animaux-vivant',
|
||
'Marchandises en citerne': 'citerne',
|
||
'Transports de béton': 'beton',
|
||
'Transport de béton': 'beton',
|
||
'Transports exceptionnels': 'exceptionnels',
|
||
'Marchandises en vrac transportées en benne': 'vrac',
|
||
'Marchandises en benne': 'vrac'
|
||
};
|
||
|
||
uniqueMarchandises.forEach(marchText => {
|
||
const mappedValue = marchandiseMapping[marchText] || marchText.toLowerCase().replace(/\s+/g, '-');
|
||
const option = marchandiseSelector.querySelector(`option[value="${mappedValue}"]`);
|
||
if (option && !option.selected) {
|
||
option.selected = true;
|
||
} else if (!option) {
|
||
// Recherche floue si mapping exact échoue
|
||
const options = marchandiseSelector.querySelectorAll('option');
|
||
options.forEach(opt => {
|
||
if (opt.textContent.trim().includes(marchText) || marchText.includes(opt.textContent.trim().substring(0, 20))) {
|
||
if (!opt.selected) opt.selected = true;
|
||
}
|
||
});
|
||
}
|
||
});
|
||
|
||
// Trigger change event pour Materialize
|
||
const changeEvent = new Event('change', { bubbles: true });
|
||
marchandiseSelector.dispatchEvent(changeEvent);
|
||
|
||
setTimeout(() => {
|
||
if (window.M && window.M.FormSelect) {
|
||
window.M.FormSelect.init(marchandiseSelector);
|
||
}
|
||
}, 100);
|
||
}
|
||
|
||
// ===== ZONES GÉOGRAPHIQUES =====
|
||
|
||
if (rc.zone1 !== undefined && !projet?.zone1) {
|
||
const zone1El = document.getElementById("zone1");
|
||
if (zone1El) {
|
||
zone1El.checked = rc.zone1;
|
||
console.log(' ✓ Zone 1:', rc.zone1);
|
||
}
|
||
}
|
||
if (rc.zone2 !== undefined && !projet?.zone2) {
|
||
const zone2El = document.getElementById("zone2");
|
||
if (zone2El) {
|
||
zone2El.checked = rc.zone2;
|
||
console.log(' ✓ Zone 2:', rc.zone2);
|
||
}
|
||
}
|
||
if (rc.zone3 !== undefined && !projet?.zone3) {
|
||
const zone3El = document.getElementById("zone3");
|
||
if (zone3El) {
|
||
zone3El.checked = rc.zone3;
|
||
console.log(' ✓ Zone 3:', rc.zone3);
|
||
}
|
||
}
|
||
if (rc.zone4 !== undefined && !projet?.zone4) {
|
||
const zone4El = document.getElementById("zone4");
|
||
if (zone4El) {
|
||
zone4El.checked = rc.zone4;
|
||
console.log(' ✓ Zone 4:', rc.zone4);
|
||
}
|
||
}
|
||
if (rc.zone5 !== undefined && !projet?.zone5) {
|
||
const zone5El = document.getElementById("zone5");
|
||
if (zone5El) {
|
||
zone5El.checked = rc.zone5;
|
||
console.log(' ✓ Zone 5:', rc.zone5);
|
||
}
|
||
}
|
||
if (rc.zone6 !== undefined && !projet?.zone6) {
|
||
const zone6El = document.getElementById("zone6");
|
||
if (zone6El) {
|
||
zone6El.checked = rc.zone6;
|
||
console.log(' ✓ Zone 6:', rc.zone6);
|
||
}
|
||
}
|
||
|
||
// ===== TYPE DE COTISATION =====
|
||
|
||
if (rc.typeCotisation && !projet?.typeCot) {
|
||
const radioCot = document.querySelector(`input[name="typeCot"][value="${rc.typeCotisation}"]`);
|
||
if (radioCot) {
|
||
radioCot.checked = true;
|
||
console.log(' ✓ Type cotisation:', rc.typeCotisation);
|
||
}
|
||
}
|
||
|
||
// ===== CA =====
|
||
|
||
if (rc.chiffreAffaires && !projet?.ca) {
|
||
const caEl = document.getElementById("CA");
|
||
if (caEl) {
|
||
caEl.value = rc.chiffreAffaires;
|
||
console.log(' ✓ CA:', rc.chiffreAffaires);
|
||
}
|
||
}
|
||
|
||
// ===== RCE (INCLURE LES AUTRES RC) =====
|
||
|
||
const hasRCEFromRC = rc && rc.checkRCE;
|
||
const hasRCEFromTarif = tarif && tarif.checkRCE;
|
||
if (hasRCEFromRC || hasRCEFromTarif) {
|
||
console.log(' ✓ RCE activée (checkRCE)');
|
||
const choixRCEEl = document.getElementById("choixRCE");
|
||
if (choixRCEEl) {
|
||
choixRCEEl.checked = true;
|
||
const garantieRCEEl = document.getElementById('garantieRCE');
|
||
if (garantieRCEEl) garantieRCEEl.style.display = 'block';
|
||
const rce1El = document.getElementById('RCE1');
|
||
if (rce1El) rce1El.style.display = '';
|
||
const rce2El = document.getElementById('RCE2');
|
||
if (rce2El) rce2El.style.display = '';
|
||
}
|
||
}
|
||
|
||
// ===== PROTECTION JURIDIQUE =====
|
||
|
||
if (tarif && tarif.checkPJ && !projet?.pj) {
|
||
console.log(' ✓ Protection Juridique activée');
|
||
const switchPJEl = document.getElementById("switchPJ");
|
||
if (switchPJEl) {
|
||
switchPJEl.checked = true;
|
||
|
||
// Afficher la section PJ
|
||
const pj1El = document.getElementById('PJ1');
|
||
if (pj1El) pj1El.style.display = '';
|
||
const pj2El = document.getElementById('PJ2');
|
||
if (pj2El) pj2El.style.display = '';
|
||
|
||
// Pré-remplir les cotisations PJ si disponibles
|
||
if (tarif.cotPJHT && !projet?.cotPJHT) {
|
||
const cotPJHTEl = document.getElementById('cotPJHT');
|
||
if (cotPJHTEl) {
|
||
cotPJHTEl.value = tarif.cotPJHT;
|
||
console.log(' ├─ Cotisation PJ HT:', tarif.cotPJHT);
|
||
}
|
||
}
|
||
if (tarif.cotPJTTC && !projet?.cotPJTTC) {
|
||
const cotPJTTCEl = document.getElementById('cotPJTTC');
|
||
if (cotPJTTCEl) {
|
||
cotPJTTCEl.value = tarif.cotPJTTC;
|
||
console.log(' └─ Cotisation PJ TTC:', tarif.cotPJTTC);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Appliquer les capitaux APRÈS trigger (les inputs sont créés dynamiquement)
|
||
setTimeout(() => {
|
||
console.log(' 💰 Application des capitaux sur les inputs créés...');
|
||
|
||
// Mapping des activités vers leurs capitaux
|
||
const capitalMapping = {
|
||
'voiturier': rc.capitalVoiturier,
|
||
'commissionnaire-multimodal': rc.capitalCommissionnaire,
|
||
'demenageur-entreprise': rc.capitalDemenageur,
|
||
'prestataire-logistique': rc.capitalLogistique,
|
||
'autocariste': rc.capitalAutocariste,
|
||
'autres': rc.capitalAutres
|
||
};
|
||
|
||
for (const [activity, capital] of Object.entries(capitalMapping)) {
|
||
if (capital) {
|
||
const input = document.getElementById(activity);
|
||
if (input && !input.value) {
|
||
input.value = capital;
|
||
console.log(` ├─ ${activity}: ${capital}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
console.log(' ✅ Capitaux appliqués');
|
||
}, 300);
|
||
|
||
// Autres champs (garanties RCC, etc.)
|
||
const garantieRCCSelector = document.getElementById('garantieRCC-selector');
|
||
if (garantieRCCSelector && !projet) {
|
||
if (rc.extRCCModifCalArrim) {
|
||
const option = garantieRCCSelector.querySelector('option[value="modif-calage-arrimage"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCFerroutage) {
|
||
const option = garantieRCCSelector.querySelector('option[value="ferroutage"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCFraisRecons) {
|
||
const option = garantieRCCSelector.querySelector('option[value="frais-reconstitution"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCConfie) {
|
||
const option = garantieRCCSelector.querySelector('option[value="confie"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCTPPC) {
|
||
const option = garantieRCCSelector.querySelector('option[value="tppc"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCRegie) {
|
||
const option = garantieRCCSelector.querySelector('option[value="regie"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (rc.extRCCSansMontageDemontage) {
|
||
const option = garantieRCCSelector.querySelector('option[value="sans-montage-demontage"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
}
|
||
|
||
// ===== ACTIVITÉS COMPLÉMENTAIRES =====
|
||
|
||
const activitesVoiturier = parseArray(rc.activitesVoiturier);
|
||
if (activitesVoiturier.length > 0) {
|
||
const container = document.querySelector('[name="actComplVoiturier/Loueur"]');
|
||
if (container) {
|
||
activitesVoiturier.forEach(activite => {
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
|
||
checkboxes.forEach(cb => {
|
||
const label = cb.nextElementSibling;
|
||
if (label && label.textContent.trim() === activite) {
|
||
cb.checked = true;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
const activitesCommissionnaire = parseArray(rc.activitesCommissionnaire);
|
||
if (activitesCommissionnaire.length > 0) {
|
||
const container = document.querySelector('[name="actComplCommissionnaire de Transport"]');
|
||
if (container) {
|
||
activitesCommissionnaire.forEach(activite => {
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
|
||
checkboxes.forEach(cb => {
|
||
const label = cb.nextElementSibling;
|
||
if (label && label.textContent.trim() === activite) {
|
||
cb.checked = true;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
const activitesDemenageur = parseArray(rc.activitesDemenageur);
|
||
if (activitesDemenageur.length > 0) {
|
||
const container = document.querySelector('[name="actComplDéménageur"]');
|
||
if (container) {
|
||
activitesDemenageur.forEach(activite => {
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
|
||
checkboxes.forEach(cb => {
|
||
const label = cb.nextElementSibling;
|
||
if (label && label.textContent.trim() === activite) {
|
||
cb.checked = true;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
const activitesLogistique = parseArray(rc.activitesLogistique);
|
||
if (activitesLogistique.length > 0) {
|
||
const container = document.querySelector('[name="actComplLogistique"]');
|
||
if (container) {
|
||
activitesLogistique.forEach(activite => {
|
||
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
|
||
checkboxes.forEach(cb => {
|
||
const label = cb.nextElementSibling;
|
||
if (label && label.textContent.trim() === activite) {
|
||
cb.checked = true;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
if (activitySelector) {
|
||
activitySelector.dispatchEvent(new Event('change'));
|
||
}
|
||
if (marchandiseSelector) {
|
||
marchandiseSelector.dispatchEvent(new Event('change'));
|
||
}
|
||
}
|
||
|
||
// Configuration des écouteurs d'événements
|
||
function setupEventListeners() {
|
||
document.getElementById('projetFormBtn').addEventListener('click', handleSubmitForm);
|
||
|
||
document.getElementById('loadHistoriqueBtn').addEventListener('click', function () {
|
||
handleLoadHistoriqueBtn();
|
||
});
|
||
|
||
document.getElementById('activity-selector').addEventListener('change', function () {
|
||
handleActivitySelection();
|
||
});
|
||
|
||
document.getElementById('marchandise-selector').addEventListener('change', function () {
|
||
handleMarchandiseSelection();
|
||
});
|
||
|
||
document.getElementById('garantieRCC-selector').addEventListener('change', function () {
|
||
handleGarantieRCCSelection();
|
||
});
|
||
|
||
document.getElementById('garantieRCE-selector').addEventListener('change', function () {
|
||
handleGarantieRCESelection();
|
||
});
|
||
|
||
document.getElementById('choixRCE').addEventListener('change', function () {
|
||
if (document.getElementById("choixRCE").checked) {
|
||
document.getElementById('garantieRCE').style.display = 'block';
|
||
document.getElementById('RCE1').style.display = '';
|
||
document.getElementById('RCE2').style.display = '';
|
||
} else {
|
||
document.getElementById('garantieRCE').style.display = 'none';
|
||
document.getElementById('RCE1').style.display = 'none';
|
||
document.getElementById('RCE2').style.display = 'none';
|
||
document.getElementById('cotRCEHT').value = '';
|
||
document.getElementById('cotRCETTC').value = '';
|
||
document.getElementById('tauxRCEHT').value = '';
|
||
document.getElementById('tauxRCETTC').value = '';
|
||
}
|
||
|
||
calcCotTotal();
|
||
});
|
||
|
||
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);
|
||
});
|
||
|
||
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);
|
||
});
|
||
|
||
document.getElementById('btnAdvaloTerrestre').addEventListener('click', function () {
|
||
document.getElementById('divAdvaloTerrestre').style.display = "block";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
});
|
||
|
||
document.getElementById('btnAdvaloMultimodal').addEventListener('click', function () {
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "block";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
});
|
||
|
||
document.getElementById('btnAdvaloAerien').addEventListener('click', function () {
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
document.getElementById('divAdvaloAerien').style.display = "block";
|
||
});
|
||
|
||
document.getElementById('switchPJ').addEventListener('change', function () {
|
||
if (document.getElementById("switchPJ").checked) {
|
||
document.getElementById('PJ1').style.display = '';
|
||
document.getElementById('PJ2').style.display = '';
|
||
} else {
|
||
document.getElementById('PJ1').style.display = 'none';
|
||
document.getElementById('PJ2').style.display = 'none';
|
||
document.getElementById('cotPJHT').value = '';
|
||
document.getElementById('cotPJTTC').value = '';
|
||
}
|
||
calcCotTotal();
|
||
});
|
||
|
||
function restoreZonesFromOriginal() {
|
||
const orig = tarifOriginalData || {};
|
||
['zone1','zone2','zone3','zone4','zone5','zone6'].forEach(z => {
|
||
const el = document.getElementById(z);
|
||
if (el) {
|
||
el.disabled = false;
|
||
el.checked = Boolean(orig[z]);
|
||
}
|
||
});
|
||
}
|
||
|
||
document.getElementById('btnMondeEntier').addEventListener('click', function () {
|
||
document.getElementById('zone1').checked = true;
|
||
document.getElementById('zone1').disabled = true;
|
||
document.getElementById('zone2').checked = true;
|
||
document.getElementById('zone2').disabled = true;
|
||
document.getElementById('zone3').checked = true;
|
||
document.getElementById('zone4').checked = true;
|
||
document.getElementById('zone5').checked = true;
|
||
document.getElementById('zone6').checked = true;
|
||
|
||
// Détection impact tarif : zones
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
// Revenir à l'état original visuel
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
});
|
||
|
||
document.getElementById('btnReset').addEventListener('click', function () {
|
||
document.getElementById('zone1').checked = false;
|
||
document.getElementById('zone1').disabled = false;
|
||
document.getElementById('zone2').checked = false;
|
||
document.getElementById('zone2').disabled = false;
|
||
document.getElementById('zone3').checked = false;
|
||
document.getElementById('zone4').checked = false;
|
||
document.getElementById('zone5').checked = false;
|
||
document.getElementById('zone6').checked = false;
|
||
|
||
// Détection impact tarif : zones
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
// Revenir à l'état original visuel
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
});
|
||
|
||
document.getElementById('btnZone1').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone1');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone2').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone2');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone3').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone3');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone4').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone4');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone5').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone5');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone6').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZone6');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('btnZone7').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalZoneExclus');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('zone1').addEventListener('click', function () {
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
document.getElementById('zone2').addEventListener('click', function () {
|
||
if (document.getElementById('zone2').checked == true) {
|
||
document.getElementById('zone1').checked = true;
|
||
document.getElementById('zone1').disabled = true;
|
||
} else if (document.getElementById('zone2').checked == false) {
|
||
document.getElementById('zone1').checked = true;
|
||
document.getElementById('zone1').disabled = false;
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
document.getElementById('zone3').addEventListener('click', function () {
|
||
if (document.getElementById('zone3').checked == true) {
|
||
document.getElementById('zone2').checked = true;
|
||
document.getElementById('zone1').checked = true;
|
||
document.getElementById('zone2').disabled = true;
|
||
document.getElementById('zone1').disabled = true;
|
||
} else if (document.getElementById('zone3').checked == false) {
|
||
document.getElementById('zone1').checked = true;
|
||
document.getElementById('zone1').disabled = true;
|
||
document.getElementById('zone2').checked = true;
|
||
document.getElementById('zone2').disabled = false;
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
document.getElementById('zone4').addEventListener('click', function () {
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
document.getElementById('zone5').addEventListener('click', function () {
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
document.getElementById('zone6').addEventListener('click', function () {
|
||
handleGrAdvalo();
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentData = getCurrentZoneData();
|
||
if (checkTarifImpact('zone', currentData)) {
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, null, null);
|
||
restoreZonesFromOriginal();
|
||
}
|
||
}
|
||
});
|
||
|
||
var radioButtonsCot = document.getElementsByName('cotisation');
|
||
for (var i = 0; i < radioButtonsCot.length; i++) {
|
||
radioButtonsCot[i].addEventListener('change', function () {
|
||
if (this.value == "forfaitaire") {
|
||
document.getElementById("checkVehicules").style.display = 'block';
|
||
document.getElementById("colTauxAjustement").style.display = 'none';
|
||
document.getElementById("colCA").style.display = 'none';
|
||
document.getElementById("colCotMini").style.display = 'none';
|
||
document.getElementById("colTypeCot").classList.remove('s4');
|
||
document.getElementById("colTypeCot").classList.add('s6');
|
||
document.getElementById("colTypeCot").style.margin = "0 auto";
|
||
document.getElementById("colTypeCot").style.float = "none";
|
||
document.getElementById("colDetailCot").classList.remove('s6');
|
||
document.getElementById("colDetailCot").classList.add('s12');
|
||
} else if (this.value == "revisable") {
|
||
document.getElementById("checkVehicules").style.display = 'none';
|
||
document.getElementById("colTauxAjustement").style.display = 'block';
|
||
document.getElementById("colCA").style.display = 'block';
|
||
document.getElementById("colCotMini").style.display = 'block';
|
||
document.getElementById("colTypeCot").classList.remove('s6');
|
||
document.getElementById("colTypeCot").classList.add('s4');
|
||
document.getElementById("colTypeCot").style.margin = "";
|
||
document.getElementById("colTypeCot").style.float = "left";
|
||
document.getElementById("colDetailCot").classList.remove('s12');
|
||
document.getElementById("colDetailCot").classList.add('s6');
|
||
}
|
||
});
|
||
};
|
||
|
||
var radioButtonsFract = document.getElementsByName('fractionnement');
|
||
for (var i = 0; i < radioButtonsFract.length; i++) {
|
||
radioButtonsFract[i].addEventListener('change', function () {
|
||
if (this.value == "mensuel") {
|
||
document.getElementById("cotFraisHT").value = 36.00;
|
||
document.getElementById("cotFraisTTC").value = 36.00;
|
||
|
||
calcCotTotal();
|
||
} else if (this.value == "trimestriel") {
|
||
document.getElementById("cotFraisHT").value = 144.00;
|
||
document.getElementById("cotFraisTTC").value = 144.00;
|
||
|
||
calcCotTotal();
|
||
} else if (this.value == "semestriel") {
|
||
document.getElementById("cotFraisHT").value = 72.00;
|
||
document.getElementById("cotFraisTTC").value = 72.00;
|
||
|
||
calcCotTotal();
|
||
} else if (this.value == "annuel") {
|
||
document.getElementById("cotFraisHT").value = 36.00;
|
||
document.getElementById("cotFraisTTC").value = 36.00;
|
||
|
||
calcCotTotal();
|
||
}
|
||
});
|
||
};
|
||
|
||
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('btnGarContenantConfie').addEventListener('click', function () {
|
||
const elem = document.getElementById('modalContenantConfie');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
});
|
||
|
||
document.getElementById('speClauses').addEventListener('click', function () {
|
||
const url = `/download/CLAUSES_PLATEFORME_RC_TRANSPORT_VALIDE_AU_26_02_2025.docx`;
|
||
|
||
fetch(url)
|
||
.then(response => response.blob())
|
||
.then(blob => {
|
||
const link = document.createElement('a');
|
||
link.href = URL.createObjectURL(blob);
|
||
link.download = 'CLAUSES_PLATEFORME_RC_TRANSPORT_VALIDE_AU_26_02_2025';
|
||
link.click();
|
||
})
|
||
.catch(error => console.error('Error downloading file:', error));
|
||
});
|
||
|
||
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('CA').addEventListener('input', function () {
|
||
if (isRestoringValue) {
|
||
validateField('CA', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcCotFromTauxCA('tauxRCCHT', 'cotRCCHT');
|
||
calcAddTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotFromTauxCA('tauxRCEHT', 'cotRCEHT');
|
||
calcAddTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
return;
|
||
}
|
||
|
||
if (tarif && tarif.id && tarifOriginalData) {
|
||
const currentValue = this.value.trim();
|
||
const originalValue = tarifOriginalData.ca || '';
|
||
|
||
if (currentValue !== originalValue) {
|
||
const originalValueToRestore = originalValue;
|
||
showTarifImpactModal((confirmed) => {
|
||
if (confirmed) {
|
||
window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
|
||
}
|
||
}, this, originalValueToRestore);
|
||
return;
|
||
}
|
||
}
|
||
|
||
validateField('CA', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcCotFromTauxCA('tauxRCCHT', 'cotRCCHT');
|
||
calcAddTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotFromTauxCA('tauxRCEHT', 'cotRCEHT');
|
||
calcAddTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotisationIrreductible').addEventListener('input', function () {
|
||
validateField('cotisationIrreductible', true);
|
||
updateSubmitButtonState('projetForm');
|
||
});
|
||
|
||
document.getElementById('tauxRCCHT').addEventListener('input', function () {
|
||
validateField('tauxRCCHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('tauxRCCHT', 0, 'tauxRCCTTC');
|
||
calcTauxTotal();
|
||
calcCotFromTauxCA('tauxRCCHT', 'cotRCCHT');
|
||
calcAddTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('tauxRCCTTC').addEventListener('input', function () {
|
||
validateField('tauxRCCTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('tauxRCCHT', 0, 'tauxRCCTTC');
|
||
calcTauxTotal();
|
||
calcCotFromTauxCA('tauxRCCHT', 'cotRCCHT');
|
||
calcAddTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('tauxRCEHT').addEventListener('input', function () {
|
||
validateField('tauxRCEHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('tauxRCEHT', 0.09, 'tauxRCETTC');
|
||
calcTauxTotal();
|
||
calcCotFromTauxCA('tauxRCEHT', 'cotRCEHT');
|
||
calcAddTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('tauxRCETTC').addEventListener('input', function () {
|
||
validateField('tauxRCETTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('tauxRCEHT', 0.09, 'tauxRCETTC');
|
||
calcTauxTotal();
|
||
calcCotFromTauxCA('tauxRCEHT', 'cotRCEHT');
|
||
calcAddTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotIrreductible();
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('tauxTotalHT').addEventListener('input', function () {
|
||
validateField('tauxTotalHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
});
|
||
|
||
document.getElementById('tauxTotalTTC').addEventListener('input', function () {
|
||
validateField('tauxTotalTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
});
|
||
|
||
document.getElementById('cotRCCHT').addEventListener('input', function () {
|
||
validateField('cotRCCHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotRCCTTC').addEventListener('input', function () {
|
||
validateField('cotRCCTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('cotRCCHT', 0, 'cotRCCTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotRCEHT').addEventListener('input', function () {
|
||
validateField('cotRCEHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotRCETTC').addEventListener('input', function () {
|
||
validateField('cotRCETTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('cotRCEHT', 0.09, 'cotRCETTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotPJHT').addEventListener('input', function () {
|
||
validateField('cotPJHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('cotPJHT', 0.134, 'cotPJTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotPJTTC').addEventListener('input', function () {
|
||
validateField('cotPJTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('cotPJHT', 0.134, 'cotPJTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotFraisHT').addEventListener('input', function () {
|
||
validateField('cotFraisHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcAddTaxe('cotFraisHT', 0, 'cotFraisTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotFraisTTC').addEventListener('input', function () {
|
||
validateField('cotFraisTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
calcSubTaxe('cotFraisHT', 0, 'cotFraisTTC');
|
||
calcCotTotal();
|
||
});
|
||
|
||
document.getElementById('cotTotalHT').addEventListener('input', function () {
|
||
validateField('cotTotalHT', true);
|
||
updateSubmitButtonState('projetForm');
|
||
});
|
||
|
||
document.getElementById('cotTotalTTC').addEventListener('input', function () {
|
||
validateField('cotTotalTTC', true);
|
||
updateSubmitButtonState('projetForm');
|
||
});
|
||
|
||
document.getElementById('activity-selector').addEventListener('change', function () {
|
||
const currentSelection = Array.from(this.selectedOptions).map(option => option.value);
|
||
|
||
if (currentSelection.includes("commissionnaire-multimodal")) {
|
||
if (tagMultimodal == false) {
|
||
M.toast({html: "Monde entier pour l'activité commissionnaire de transports multimodal"})
|
||
document.getElementById("btnAdvaloMultimodal").style.display = 'block';
|
||
document.getElementById("btnAdvaloAerien").style.display = 'block';
|
||
document.getElementById("btnAdvaloTerrestre").style.display = 'block';
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "block";
|
||
}
|
||
|
||
tagMultimodal = true;
|
||
} else {
|
||
document.getElementById("btnAdvaloMultimodal").style.display = 'none';
|
||
document.getElementById("btnAdvaloAerien").style.display = 'none';
|
||
document.getElementById("btnAdvaloTerrestre").style.display = 'none';
|
||
document.getElementById('divAdvaloTerrestre').style.display = "block";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
|
||
tagMultimodal = false;
|
||
}
|
||
|
||
if (currentSelection.includes("demenageur-particulier") || currentSelection.includes("demenageur-particulier-dommage") || currentSelection.includes("demenageur-particulier-advalorem") || currentSelection.includes("demenageur-entreprise") || currentSelection.includes("demenageur-interne")) {
|
||
if (tagDemenageur == false) {
|
||
document.getElementById('marchandise-selector').querySelector('option[value="roulant-demenagement"]').selected = true;
|
||
document.getElementById('marchandise-selector').querySelector('option[value="mobilier-usages"]').selected = true;
|
||
document.getElementById('marchandise-selector').querySelector('option[value="ordinaire"]').selected = false;
|
||
document.getElementById('marchandise-selector').dispatchEvent(new Event('change'));
|
||
}
|
||
|
||
tagDemenageur = true;
|
||
} else {
|
||
// Aucune activité déménageur n'est sélectionnée
|
||
document.getElementById('marchandise-selector').querySelector('option[value="roulant-demenagement"]').selected = false;
|
||
document.getElementById('marchandise-selector').querySelector('option[value="mobilier-usages"]').selected = false;
|
||
document.getElementById('marchandise-selector').querySelector('option[value="ordinaire"]').selected = true;
|
||
document.getElementById('marchandise-selector').dispatchEvent(new Event('change'));
|
||
|
||
tagDemenageur = false;
|
||
}
|
||
|
||
if (currentSelection.includes("garde-meubles")) {
|
||
if (tagGardeMeubles == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier"]').selected = true;
|
||
tagGardeMeubles = true;
|
||
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
|
||
document.getElementById('selected-demenageur-error').style.display = "block";
|
||
}
|
||
} else {
|
||
if (!(currentSelection.includes("garde-meubles"))) {
|
||
document.getElementById('selected-demenageur-error').style.display = "none";
|
||
tagGardeMeubles = false;
|
||
}
|
||
}
|
||
|
||
if (currentSelection.includes("demenageur-particulier")) {
|
||
if (tagDemenageurParticulier == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier-dommage"]').selected = false;
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier-advalorem"]').selected = false;
|
||
tagDemenageurParticulier = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
}
|
||
} else {
|
||
tagDemenageurParticulier = false;
|
||
}
|
||
|
||
if (currentSelection.includes("demenageur-particulier-dommage")) {
|
||
if (tagDemenageurParticulierDeclaree == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier"]').selected = false;
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier-advalorem"]').selected = false;
|
||
tagDemenageurParticulierDeclaree = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
}
|
||
} else {
|
||
tagDemenageurParticulierDeclaree = false;
|
||
}
|
||
|
||
if (currentSelection.includes("demenageur-particulier-advalorem")) {
|
||
if (tagDemenageurParticulierAdvalorem == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier-dommage"]').selected = false;
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-particulier"]').selected = false;
|
||
tagDemenageurParticulierAdvalorem = true;
|
||
tagDemenageurParticulierDeclaree = false;
|
||
tagDemenageurParticulier = false;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
}
|
||
} else {
|
||
tagDemenageurParticulierAdvalorem = false;
|
||
}
|
||
|
||
if (currentSelection.includes("demenageur-entreprise")) {
|
||
if (tagDemenageurEntrInter == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="demenageur-interne"]').selected = true;
|
||
tagDemenageurEntrInter = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
document.getElementById('selected-demenageur-entreprise-error').style.display = "block";
|
||
}
|
||
} else {
|
||
document.getElementById('selected-demenageur-entreprise-error').style.display = "none";
|
||
tagDemenageurEntrInter = false;
|
||
}
|
||
|
||
if (currentSelection.includes("entrepositaire-depositaire") || currentSelection.includes("prestataire-logistique") || currentSelection.includes("manutentionnaire-levageur")) {
|
||
if (tagVoiturier == false) {
|
||
document.getElementById('activity-selector').querySelector('option[value="voiturier"]').selected = true;
|
||
tagVoiturier = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
document.getElementById('selected-voiturier-error').style.display = "block";
|
||
}
|
||
} else {
|
||
// Aucune activité nécessitant voiturier n'est sélectionnée
|
||
tagVoiturier = false;
|
||
document.getElementById('selected-voiturier-error').style.display = "none";
|
||
}
|
||
|
||
if (currentSelection.length == 1) {
|
||
document.getElementById('activity-selector').querySelector('option[value="voiturier"]').selected = true;
|
||
document.getElementById('activity-selector').querySelector('option[value="loueur"]').selected = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
M.FormSelect.init(document.querySelectorAll('select'));
|
||
document.getElementById('mini-activity-error').style.display = "block";
|
||
} else {
|
||
document.getElementById("mini-activity-error").style.display = "none";
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
});
|
||
|
||
document.getElementById('marchandise-selector').addEventListener('change', function () {
|
||
const currentSelection = Array.from(this.selectedOptions).map(option => option.value);
|
||
|
||
if (currentSelection.includes("beton")) {
|
||
document.getElementById("choixRCE").checked = false;
|
||
document.getElementById('garantieRCE').style.display = 'none';
|
||
document.getElementById('RCE1').style.display = 'none';
|
||
document.getElementById('RCE2').style.display = 'none';
|
||
document.getElementById('selected-RCE2-error').style.display = "block";
|
||
} else {
|
||
if (!(currentSelection.includes("beton"))) {
|
||
document.getElementById('selected-RCE2-error').style.display = "none";
|
||
}
|
||
}
|
||
|
||
if (currentSelection.length == 1) {
|
||
document.getElementById('marchandise-selector').querySelector('option[value="ordinaire"]').selected = true;
|
||
document.getElementById('marchandise-selector').dispatchEvent(new Event('change'));
|
||
document.getElementById("mini-marchandise-error").style.display = "block";
|
||
} else {
|
||
document.getElementById("mini-marchandise-error").style.display = "none";
|
||
}
|
||
|
||
if (currentSelection.includes("animaux-vivant")) {
|
||
if (tagAnimauxVivants == false) {
|
||
// Retire le display select en cas d'animaux vivants
|
||
M.FormSelect.init(document.querySelectorAll('select'));
|
||
|
||
const elem = document.getElementById('modalAnimauxVivants');
|
||
const instance = M.Modal.getInstance(elem);
|
||
instance.open();
|
||
}
|
||
|
||
tagAnimauxVivants = true;
|
||
} else {
|
||
if (!(currentSelection.includes("animaux-vivant"))) {
|
||
tagAnimauxVivants = false;
|
||
}
|
||
}
|
||
|
||
handleGrAdvalo();
|
||
});
|
||
|
||
document.getElementById('garantieRCC-selector').addEventListener('change', function () {
|
||
const currentSelection = Array.from(this.selectedOptions).map(option => option.value);
|
||
|
||
if (currentSelection.includes("contenant-confie")) {
|
||
document.getElementById('garContenantConfie').style.display = "block";
|
||
} else {
|
||
if (!(currentSelection.includes("contenant-confie"))) {
|
||
document.getElementById('garContenantConfie').style.display = "none";
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// Handle event spécifique au limite de garantie activité
|
||
window.handleInputActivity = function (inputId) {
|
||
validateField(inputId, true);
|
||
updateSubmitButtonState('projetForm');
|
||
};
|
||
|
||
// Peupler le formulaire avec les données
|
||
function populateFormData() {
|
||
//Poupulate select historique (toujours affiché, options ajoutées si présentes)
|
||
const historiqueDiv = document.getElementById('historiqueDiv');
|
||
const idSelect = document.getElementById('idSelect');
|
||
if (historiqueDiv) {
|
||
historiqueDiv.style.display = "block";
|
||
}
|
||
if (idSelect && contrat?.historique && contrat.historique.length) {
|
||
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);
|
||
}
|
||
|
||
// Pré-remplir depuis le tarif si disponible (même si projet existe, on complète avec les données du tarif)
|
||
if (tarif && tarif.id) {
|
||
setTimeout(() => {
|
||
prefillFromTarif();
|
||
|
||
// S'assurer que "Inclure les autres RC" est coché après prefillFromTarif
|
||
setTimeout(() => {
|
||
const hasRCEProjet = projet && (projet.autresRC || projet.extRCEBraDebra || projet.extRCEMontageDemontage);
|
||
const hasRCERC = rc && rc.checkRCE;
|
||
const hasRCETarif = tarif && tarif.checkRCE;
|
||
const hasRCE = hasRCEProjet || hasRCERC || hasRCETarif;
|
||
|
||
if (hasRCE) {
|
||
const choixRCEEl = document.getElementById("choixRCE");
|
||
if (choixRCEEl) {
|
||
choixRCEEl.checked = true;
|
||
const garantieRCEEl = document.getElementById('garantieRCE');
|
||
if (garantieRCEEl) garantieRCEEl.style.display = 'block';
|
||
const rce1El = document.getElementById('RCE1');
|
||
if (rce1El) rce1El.style.display = '';
|
||
const rce2El = document.getElementById('RCE2');
|
||
if (rce2El) rce2El.style.display = '';
|
||
}
|
||
}
|
||
}, 200);
|
||
}, 300);
|
||
}
|
||
|
||
// S'assurer que "Inclure les autres RC" est coché si nécessaire (après le chargement de toutes les données projet)
|
||
setTimeout(() => {
|
||
const hasRCEProjet = projet && (projet.autresRC || projet.extRCEBraDebra || projet.extRCEMontageDemontage);
|
||
const hasRCERC = rc && rc.checkRCE;
|
||
const hasRCETarif = tarif && tarif.checkRCE;
|
||
const hasRCE = hasRCEProjet || hasRCERC || hasRCETarif;
|
||
|
||
if (hasRCE) {
|
||
const choixRCEEl = document.getElementById("choixRCE");
|
||
if (choixRCEEl && !choixRCEEl.checked) {
|
||
choixRCEEl.checked = true;
|
||
const garantieRCEEl = document.getElementById('garantieRCE');
|
||
if (garantieRCEEl) garantieRCEEl.style.display = 'block';
|
||
const rce1El = document.getElementById('RCE1');
|
||
if (rce1El) rce1El.style.display = '';
|
||
const rce2El = document.getElementById('RCE2');
|
||
if (rce2El) rce2El.style.display = '';
|
||
}
|
||
}
|
||
}, 600);
|
||
|
||
// Populate par défaut Voiturier / Loueur
|
||
if (!projet && !tarif) {
|
||
document.getElementById('activity-selector').querySelector('option[value="voiturier"]').selected = true;
|
||
document.getElementById('activity-selector').querySelector('option[value="loueur"]').selected = true;
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
|
||
// Marchandises ordinaires par défaut
|
||
document.getElementById('marchandise-selector').querySelector('option[value="ordinaire"]').selected = true;
|
||
document.getElementById('marchandise-selector').dispatchEvent(new Event('change'));
|
||
}
|
||
|
||
// Populate assurés additionnel
|
||
if (!projet || !projet.assureAdditionnel || Object.keys(projet.assureAdditionnel).length === 0) {
|
||
console.log("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);
|
||
}
|
||
}
|
||
|
||
// Populate activite
|
||
const activitySelector = document.getElementById('activity-selector');
|
||
|
||
if (projet && projet.actVoiturier) {
|
||
activitySelector.querySelector('option[value="voiturier"]').selected = true;
|
||
document.getElementById("select-voiturier").dataset.defaultValue = projet.valueActVoiturier;
|
||
};
|
||
|
||
if (projet && projet.actLoueur) {
|
||
activitySelector.querySelector('option[value="loueur"]').selected = true;
|
||
document.getElementById("select-loueur").dataset.defaultValue = projet.valueActLoueur;
|
||
};
|
||
|
||
if (projet && projet.actMultimodal) {
|
||
tagMultimodal = true;
|
||
activitySelector.querySelector('option[value="commissionnaire-multimodal"]').selected = true;
|
||
document.getElementById("select-commissionnaire-multimodal").dataset.defaultValue = projet.valueActMultimodal;
|
||
document.getElementById("btnAdvaloMultimodal").style.display = 'block';
|
||
document.getElementById("btnAdvaloAerien").style.display = 'block';
|
||
document.getElementById("btnAdvaloTerrestre").style.display = 'block';
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "block";
|
||
};
|
||
|
||
if (projet && projet.actDouane) {
|
||
activitySelector.querySelector('option[value="représentant-douane"]').selected = true;
|
||
document.getElementById("select-représentant-douane").dataset.defaultValue = projet.valueActDouane;
|
||
};
|
||
|
||
if (projet && projet.actDemPar) {
|
||
activitySelector.querySelector('option[value="demenageur-particulier"]').selected = true;
|
||
document.getElementById("select-demenageur-particulier").dataset.defaultValue = projet.valueActDemPar;
|
||
}
|
||
|
||
if (projet && projet.actDemParDom) {
|
||
activitySelector.querySelector('option[value="demenageur-particulier-dommage"]').selected = true;
|
||
document.getElementById("select-demenageur-particulier-dommage").dataset.defaultValue = projet.valueActDemParDom;
|
||
}
|
||
|
||
if (projet && projet.actDemParAdv) {
|
||
activitySelector.querySelector('option[value="demenageur-particulier-advalorem"]').selected = true;
|
||
document.getElementById("select-demenageur-particulier-advalorem").dataset.defaultValue = projet.valueActDemParAdv;
|
||
}
|
||
|
||
if (projet && projet.actDemEntr) {
|
||
activitySelector.querySelector('option[value="demenageur-entreprise"]').selected = true;
|
||
document.getElementById("select-demenageur-entreprise").dataset.defaultValue = projet.valueActDemEntr;
|
||
}
|
||
|
||
if (projet && projet.actDemInterne) {
|
||
activitySelector.querySelector('option[value="demenageur-interne"]').selected = true;
|
||
document.getElementById("select-demenageur-interne").dataset.defaultValue = projet.valueActDemInterne;
|
||
}
|
||
|
||
if (projet && projet.actGardeMeuble) {
|
||
activitySelector.querySelector('option[value="garde-meubles"]').selected = true;
|
||
document.getElementById("select-garde-meubles").dataset.defaultValue = projet.valueActGardeMeuble;
|
||
}
|
||
|
||
if (projet && projet.actEntDep) {
|
||
activitySelector.querySelector('option[value="entrepositaire-depositaire"]').selected = true;
|
||
document.getElementById("select-entrepositaire-depositaire").dataset.defaultValue = projet.valueActEntDep;
|
||
}
|
||
|
||
if (projet && projet.actPrestaLog) {
|
||
activitySelector.querySelector('option[value="prestataire-logistique"]').selected = true;
|
||
document.getElementById("select-prestataire-logistique").dataset.defaultValue = projet.valueActPrestaLog;
|
||
}
|
||
|
||
if (projet && projet.actLevageur) {
|
||
activitySelector.querySelector('option[value="manutentionnaire-levageur"]').selected = true;
|
||
document.getElementById("select-manutentionnaire-levageur").dataset.defaultValue = projet.valueActLevageur;
|
||
}
|
||
|
||
if (projet && projet.actTransitaire) {
|
||
activitySelector.querySelector('option[value="transitaire"]').selected = true;
|
||
document.getElementById("select-transitaire").dataset.defaultValue = projet.valueActTransitaire;
|
||
}
|
||
|
||
document.getElementById('activity-selector').dispatchEvent(new Event('change'));
|
||
|
||
// Populate marchandises
|
||
const marchandiseSelector = document.getElementById('marchandise-selector');
|
||
|
||
if (projet && projet.marOrdinaire) { marchandiseSelector.querySelector('option[value="ordinaire"]').selected = true; };
|
||
if (projet && projet.marRoulant) { marchandiseSelector.querySelector('option[value="roulant"]').selected = true; };
|
||
if (projet && projet.marEngins) { marchandiseSelector.querySelector('option[value="engins-chantier-agricole"]').selected = true; };
|
||
if (projet && projet.marRoulantDem) { marchandiseSelector.querySelector('option[value="roulant-demenagement"]').selected = true; };
|
||
if (projet && projet.marMobilerUsag) { marchandiseSelector.querySelector('option[value="mobilier-usages"]').selected = true; };
|
||
if (projet && projet.marPerissable) { marchandiseSelector.querySelector('option[value="perissable-temperature-dirigee"]').selected = true; };
|
||
if (projet && projet.marAnimaux) {
|
||
tagAnimauxVivants = true;
|
||
marchandiseSelector.querySelector('option[value="animaux-vivant"]').selected = true;
|
||
};
|
||
if (projet && projet.marCiterne) { marchandiseSelector.querySelector('option[value="citerne"]').selected = true; };
|
||
if (projet && projet.marBeton) { marchandiseSelector.querySelector('option[value="beton"]').selected = true; };
|
||
if (projet && projet.marExceptionnels) { marchandiseSelector.querySelector('option[value="exceptionnels"]').selected = true; };
|
||
if (projet && projet.marVrac) { marchandiseSelector.querySelector('option[value="vrac"]').selected = true; };
|
||
|
||
document.getElementById('marchandise-selector').dispatchEvent(new Event('change'));
|
||
|
||
// Populate territorialité - depuis projet OU depuis rc (tarif) en fallback
|
||
const zonesSource = projet || rc;
|
||
if (zonesSource) {
|
||
if (zonesSource.zone1) {
|
||
document.getElementById("zone1").checked = true;
|
||
document.getElementById("zone1").disabled = false;
|
||
}
|
||
if (zonesSource.zone2) {
|
||
document.getElementById("zone2").checked = true;
|
||
document.getElementById("zone2").disabled = false;
|
||
if (!zonesSource.zone1) {
|
||
document.getElementById("zone1").checked = true;
|
||
document.getElementById("zone1").disabled = true;
|
||
}
|
||
}
|
||
if (zonesSource.zone3) {
|
||
document.getElementById("zone3").checked = true;
|
||
document.getElementById("zone3").disabled = false;
|
||
if (!zonesSource.zone2) {
|
||
document.getElementById("zone2").checked = true;
|
||
document.getElementById("zone2").disabled = true;
|
||
}
|
||
if (!zonesSource.zone1) {
|
||
document.getElementById("zone1").checked = true;
|
||
document.getElementById("zone1").disabled = true;
|
||
}
|
||
}
|
||
if (zonesSource.zone4) {
|
||
document.getElementById("zone4").checked = true;
|
||
document.getElementById("zone4").disabled = false;
|
||
}
|
||
if (zonesSource.zone5) {
|
||
document.getElementById("zone5").checked = true;
|
||
document.getElementById("zone5").disabled = false;
|
||
}
|
||
if (zonesSource.zone6) {
|
||
document.getElementById("zone6").checked = true;
|
||
document.getElementById("zone6").disabled = false;
|
||
}
|
||
}
|
||
|
||
// Populate extensions de garantie RCC
|
||
const garantieRCCSelector = document.getElementById('garantieRCC-selector');
|
||
|
||
if (projet && projet.extRCCModifCalArrim) { garantieRCCSelector.querySelector('option[value="modif-calage-arrimage"]').selected = true; };
|
||
if (projet && projet.extRCCFerroutage) { garantieRCCSelector.querySelector('option[value="ferroutage"]').selected = true; };
|
||
if (projet && projet.extRCCFraisRecons) { garantieRCCSelector.querySelector('option[value="frais-reconstitution"]').selected = true; };
|
||
if (projet && projet.extRCCConfie) {
|
||
garantieRCCSelector.querySelector('option[value="contenant-confie"]').selected = true;
|
||
|
||
if (projet.typeExtConfies == "ADVALOREM") {
|
||
document.getElementById("AdValorem").checked = true;
|
||
} else {
|
||
document.getElementById("ValeurDeclaree").checked = true;
|
||
}
|
||
};
|
||
if (projet && projet.extRCCTPPC) { garantieRCCSelector.querySelector('option[value="tppc"]').selected = true; };
|
||
if (projet && projet.extRCCRegie) { garantieRCCSelector.querySelector('option[value="regie"]').selected = true; };
|
||
if (projet && projet.extRCCSansMontageDemontage) { garantieRCCSelector.querySelector('option[value="sans-montage-demontage"]').selected = true; };
|
||
|
||
document.getElementById('garantieRCC-selector').dispatchEvent(new Event('change'));
|
||
|
||
// Populate extensions de garantie RCE - DOIT être fait APRÈS le chargement des données projet
|
||
setTimeout(() => {
|
||
const hasRCEProjet = projet && (projet.autresRC || projet.extRCEBraDebra || projet.extRCEMontageDemontage);
|
||
const hasRCERC = rc && rc.checkRCE;
|
||
const hasRCETarif = tarif && tarif.checkRCE;
|
||
const hasRCE = hasRCEProjet || hasRCERC || hasRCETarif;
|
||
|
||
if (hasRCE) {
|
||
const choixRCEEl = document.getElementById("choixRCE");
|
||
if (choixRCEEl) {
|
||
choixRCEEl.checked = true;
|
||
const garantieRCEEl = document.getElementById('garantieRCE');
|
||
if (garantieRCEEl) {
|
||
garantieRCEEl.style.display = 'block';
|
||
}
|
||
const rce1El = document.getElementById('RCE1');
|
||
if (rce1El) {
|
||
rce1El.style.display = '';
|
||
}
|
||
const rce2El = document.getElementById('RCE2');
|
||
if (rce2El) {
|
||
rce2El.style.display = '';
|
||
}
|
||
}
|
||
}
|
||
}, 100);
|
||
|
||
const garantieRCESelector = document.getElementById('garantieRCE-selector');
|
||
if (garantieRCESelector) {
|
||
if (projet && projet.extRCEBraDebra) {
|
||
const option = garantieRCESelector.querySelector('option[value="branchement-debranchement"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
if (projet && projet.extRCEMontageDemontage) {
|
||
const option = garantieRCESelector.querySelector('option[value="montage-demontage"]');
|
||
if (option) option.selected = true;
|
||
}
|
||
garantieRCESelector.dispatchEvent(new Event('change'));
|
||
}
|
||
|
||
// 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.programmeInternationale) { document.getElementById("programmeInternationale").checked = true; }
|
||
if (projet && projet.participationResultat) { document.getElementById("participationResultat").checked = true; }
|
||
|
||
if (projet && projet.pj) {
|
||
document.getElementById("switchPJ").checked = true;
|
||
document.getElementById('PJ1').style.display = '';
|
||
document.getElementById('PJ2').style.display = '';
|
||
}
|
||
|
||
// Populate Cotisation - charger depuis RC principal si existe
|
||
const typeCotFromRC = rc?.typeCotisation || projet?.typeCot;
|
||
if (typeCotFromRC) {
|
||
const radioCot = document.getElementById(typeCotFromRC);
|
||
if (radioCot) radioCot.checked = true;
|
||
}
|
||
|
||
// Populate CA depuis RC principal
|
||
const caFromRC = rc?.chiffreAffaires || projet?.ca;
|
||
if (caFromRC) {
|
||
document.getElementById("CA").value = caFromRC;
|
||
}
|
||
|
||
if ((typeCotFromRC || projet?.typeCot) == "forfaitaire") {
|
||
document.getElementById("checkVehicules").style.display = 'block';
|
||
document.getElementById("colTauxAjustement").style.display = 'none';
|
||
document.getElementById("colCotMini").style.display = 'none';
|
||
document.getElementById("colCA").style.display = 'none';
|
||
document.getElementById("colTypeCot").classList.remove('s4');
|
||
document.getElementById("colTypeCot").classList.add('s6');
|
||
document.getElementById("colTypeCot").style.margin = "0 auto";
|
||
document.getElementById("colTypeCot").style.float = "none";
|
||
document.getElementById("colDetailCot").classList.remove('s6');
|
||
document.getElementById("colDetailCot").classList.add('s12');
|
||
} else if (rc.typeCot == "revisable") {
|
||
document.getElementById("checkVehicules").style.display = 'none';
|
||
document.getElementById("colTauxAjustement").style.display = 'block';
|
||
document.getElementById("colCA").style.display = 'block';
|
||
document.getElementById("colCotMini").style.display = 'block';
|
||
document.getElementById("colTypeCot").style.margin = "";
|
||
document.getElementById("colTypeCot").style.float = "left";
|
||
}
|
||
|
||
if (projet && projet.ca) { document.getElementById("CA").value = projet.ca };
|
||
if (projet && projet.cotIrreductible) { document.getElementById("cotisationIrreductible").value = projet.cotIrreductible };
|
||
if (projet && projet.tauxRCCHT) { document.getElementById("tauxRCCHT").value = projet.tauxRCCHT };
|
||
if (projet && projet.tauxRCCTTC) { document.getElementById("tauxRCCTTC").value = projet.tauxRCCTTC };
|
||
if (projet && projet.tauxRCEHT) { document.getElementById("tauxRCEHT").value = projet.tauxRCEHT };
|
||
if (projet && projet.tauxRCETTC) { document.getElementById("tauxRCETTC").value = projet.tauxRCETTC };
|
||
if (projet && projet.tauxTotalHT) { document.getElementById("tauxTotalHT").value = projet.tauxTotalHT };
|
||
if (projet && projet.tauxTotalTTC) { document.getElementById("tauxTotalTTC").value = projet.tauxTotalTTC };
|
||
if (projet && projet.cotRCCHT) { document.getElementById("cotRCCHT").value = projet.cotRCCHT };
|
||
if (projet && projet.cotRCCTTC) { document.getElementById("cotRCCTTC").value = projet.cotRCCTTC };
|
||
if (projet && projet.cotRCEHT) { document.getElementById("cotRCEHT").value = projet.cotRCEHT };
|
||
if (projet && projet.cotRCETTC) { document.getElementById("cotRCETTC").value = projet.cotRCETTC };
|
||
if (projet && projet.cotPJHT) { document.getElementById("cotPJHT").value = projet.cotPJHT };
|
||
if (projet && projet.cotPJTTC) { document.getElementById("cotPJTTC").value = projet.cotPJTTC };
|
||
if (projet && projet.cotTotalHT) { document.getElementById("cotTotalHT").value = projet.cotTotalHT };
|
||
if (projet && projet.cotTotalTTC) { document.getElementById("cotTotalTTC").value = projet.cotTotalTTC };
|
||
if (projet && projet.cotFraisHT) { document.getElementById("cotFraisHT").value = projet.cotFraisHT };
|
||
if (projet && projet.cotFraisTTC) { document.getElementById("cotFraisTTC").value = projet.cotFraisTTC };
|
||
|
||
// Populate tableau vehicule
|
||
if (!rc || !projet.designationVehicule || Object.keys(projet.designationVehicule).length === 0) {
|
||
console.log("Le JSON est vide, pas de véhicules à pré-remplir.");
|
||
} else {
|
||
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 Grille Advalorem
|
||
hasSavedGrilleData = Boolean(
|
||
(projet?.grilleMultimodal && (Array.isArray(projet.grilleMultimodal) ? projet.grilleMultimodal.length : true)) ||
|
||
(projet?.grilleTerrestre && (Array.isArray(projet.grilleTerrestre) ? projet.grilleTerrestre.length : true)) ||
|
||
(projet?.grilleAerien && (Array.isArray(projet.grilleAerien) ? projet.grilleAerien.length : true))
|
||
);
|
||
|
||
const isMultimodal = Boolean(projet?.actMultimodal || rc?.actMultimodal);
|
||
if (isMultimodal) {
|
||
if (projet?.grilleAerien) {
|
||
const grilleAerien = Array.isArray(projet.grilleAerien) ? projet.grilleAerien : (typeof projet.grilleAerien === 'string' ? JSON.parse(projet.grilleAerien) : []);
|
||
populateGrAdvalo(grilleAerien, "tabAdvaloAerien");
|
||
document.getElementById('divAdvaloAerien').style.display = "block";
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
};
|
||
|
||
if (projet?.grilleTerrestre) {
|
||
const grilleTerrestre = Array.isArray(projet.grilleTerrestre) ? projet.grilleTerrestre : (typeof projet.grilleTerrestre === 'string' ? JSON.parse(projet.grilleTerrestre) : []);
|
||
populateGrAdvalo(grilleTerrestre, "tabAdvaloTerrestre");
|
||
document.getElementById('divAdvaloTerrestre').style.display = "block";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
};
|
||
|
||
if (projet?.grilleMultimodal) {
|
||
const grilleMultimodal = Array.isArray(projet.grilleMultimodal) ? projet.grilleMultimodal : (typeof projet.grilleMultimodal === 'string' ? JSON.parse(projet.grilleMultimodal) : []);
|
||
populateGrAdvalo(grilleMultimodal, "tabAdvaloMultimodal");
|
||
document.getElementById('divAdvaloMultimodal').style.display = "block";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloTerrestre').style.display = "none";
|
||
};
|
||
} else {
|
||
if (projet?.grilleTerrestre) {
|
||
const grilleTerrestre = Array.isArray(projet.grilleTerrestre) ? projet.grilleTerrestre : (typeof projet.grilleTerrestre === 'string' ? JSON.parse(projet.grilleTerrestre) : []);
|
||
populateGrAdvalo(grilleTerrestre, "tabAdvaloTerrestre");
|
||
document.getElementById('divAdvaloTerrestre').style.display = "block";
|
||
document.getElementById('divAdvaloAerien').style.display = "none";
|
||
document.getElementById('divAdvaloMultimodal').style.display = "none";
|
||
};
|
||
}
|
||
}
|
||
|
||
function populateGrAdvalo(jsonData, tableID) {
|
||
var table = document.getElementById(tableID);
|
||
if (!table) {
|
||
console.warn('Table non trouvée:', tableID);
|
||
return;
|
||
}
|
||
|
||
if (!jsonData || !Array.isArray(jsonData) || jsonData.length === 0) {
|
||
console.warn('Données grille vides ou invalides pour', tableID, ':', jsonData);
|
||
return;
|
||
}
|
||
|
||
console.log('Remplissage de la grille', tableID, 'avec', jsonData.length, 'catégories');
|
||
|
||
for (var i = 0; i < jsonData.length; i++) {
|
||
var category = jsonData[i].name;
|
||
if (!category) continue;
|
||
|
||
for (var j = 1; j < table.rows.length; j++) {
|
||
var categoryName = table.rows[j].cells[0] ? table.rows[j].cells[0].innerText.trim() : '';
|
||
|
||
if (categoryName === category) {
|
||
var categoryRow = table.rows[j];
|
||
|
||
for (var k = 1; k <= 6; k++) {
|
||
var zoneKey = "zone" + k;
|
||
var zoneInput = categoryRow.cells[k] ? categoryRow.cells[k].querySelector("input[type='text']") : null;
|
||
if (zoneInput && jsonData[i][zoneKey]) {
|
||
zoneInput.value = jsonData[i][zoneKey];
|
||
console.log('Rempli:', category, zoneKey, '=', jsonData[i][zoneKey]);
|
||
}
|
||
}
|
||
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const categories = {
|
||
multimodal: {
|
||
Cat1: [0.06, 0.06, 0.07, 0.09, 0.12, 0.14],
|
||
Cat2: [0.12, 0.13, 0.14, 0.24, 0.24, 0.3],
|
||
Cat3: [0.07, 0.08, 0.09, 0.14, 0.14, 0.18],
|
||
Cat4: [0.14, 0.17, 0.17, 0.29, 0.29, 0.36],
|
||
Cat5: [0.17, 0.19, 0.21, 0.35, 0.35, 0.43],
|
||
Cat6: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"],
|
||
Cat7: [0.30, 0.33, 0.36, 0.60, 0.60, 0.75],
|
||
Cat8: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"]
|
||
},
|
||
terrestre: {
|
||
Cat1: [0.05, 0.053, 0.06, 0.09, 0.12, 0.14],
|
||
Cat2: [0.10, 0.11, 0.12, 0.24, 0.24, 0.25],
|
||
Cat3: [0.06, 0.066, 0.07, 0.14, 0.14, 0.15],
|
||
Cat4: [0.12, 0.132, 0.14, 0.29, 0.29, 0.30],
|
||
Cat5: [0.14, 0.158, 0.17, 0.35, 0.35, 0.36],
|
||
Cat6: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"],
|
||
Cat7: [0.25, 0.275, 0.3, 0.6, 0.6, 0.63],
|
||
Cat8: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"]
|
||
},
|
||
aerien: {
|
||
Cat1: [0.04, 0.04, 0.05, 0.06, 0.08, 0.10],
|
||
Cat2: [0.09, 0.09, 0.10, 0.13, 0.17, 0.21],
|
||
Cat3: [0.05, 0.06, 0.06, 0.08, 0.10, 0.13],
|
||
Cat4: [0.10, 0.11, 0.12, 0.15, 0.20, 0.26],
|
||
Cat5: [0.12, 0.13, 0.15, 0.18, 0.24, 0.31],
|
||
Cat6: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"],
|
||
Cat7: [0.21, 0.23, 0.26, 0.32, 0.43, 0.53],
|
||
Cat8: ["Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter", "Nous consulter"]
|
||
}
|
||
};
|
||
|
||
function handleGrAdvalo() {
|
||
for (let i = 1; i <= 6; i++) {
|
||
const checkZone = document.getElementById("zone" + i).checked;
|
||
|
||
for (let j = 1; j <= 6; j++) {
|
||
// Gestion multimodal
|
||
updateCategoryValues("multimodal", i, j, checkZone);
|
||
|
||
// Gestion terrestre
|
||
updateCategoryValues("terrestre", i, j, checkZone);
|
||
|
||
// Gestion aerien
|
||
updateCategoryValues("aerien", i, j, checkZone);
|
||
}
|
||
}
|
||
}
|
||
|
||
function updateCategoryValues(mode, zone, index, checkZone) {
|
||
for (let k = 1; k <= 8; k++) {
|
||
const element = document.getElementById(`${mode}Cat${k}Zone${zone}`);
|
||
const marPerissable = document.getElementById("perissable-temperature-dirigee-chip") || null;
|
||
const marEngins = document.getElementById("engins-chantier-agricole-chip") || null;
|
||
const marMobilier = document.getElementById("mobilier-usages-chip") || null;
|
||
const marRoulantDem = document.getElementById("roulant-demenagement-chip") || null;
|
||
const marRoulant = document.getElementById("roulant-chip") || null;
|
||
|
||
let value = "Nous consulter"; // Par défaut
|
||
|
||
if (checkZone) {
|
||
if (k === 4) {
|
||
if (marPerissable) {
|
||
value = categories[mode][`Cat${k}`][zone - 1];
|
||
} else {
|
||
value = "Nous consulter";
|
||
}
|
||
} else if (k === 5) {
|
||
if (marEngins || marRoulant) {
|
||
value = categories[mode][`Cat${k}`][zone - 1];
|
||
} else {
|
||
value = "Nous consulter";
|
||
}
|
||
} else if (k === 7) {
|
||
if (marMobilier || marRoulantDem) {
|
||
value = categories[mode][`Cat${k}`][zone - 1];
|
||
} else {
|
||
value = "Nous consulter";
|
||
}
|
||
} else {
|
||
value = categories[mode][`Cat${k}`][zone - 1];
|
||
}
|
||
}
|
||
// Si une grille enregistrée existe déjà, ne pas écraser les valeurs pré-remplies
|
||
if (hasSavedGrilleData && element && element.value && element.value.trim() !== '') {
|
||
continue;
|
||
}
|
||
element.value = value;
|
||
}
|
||
}
|
||
|
||
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 handleActivitySelection() {
|
||
const select = document.getElementById('activity-selector');
|
||
const activityFormsContainer = document.getElementById('selected-activities');
|
||
|
||
// Clear previous entries
|
||
activityFormsContainer.innerHTML = ''; // Clear any existing entries
|
||
|
||
// Add a header for the "Dommage matériel (en €)" label that aligns with the input fields
|
||
const headerDiv = document.createElement('div');
|
||
headerDiv.classList.add('row');
|
||
headerDiv.style.display = 'flex';
|
||
headerDiv.style.alignItems = 'center';
|
||
headerDiv.style.justifyContent = 'start';
|
||
headerDiv.innerHTML = `
|
||
<div style="flex: 3;"> </div>
|
||
<label class="activity-forms-header" style="flex: 2;">Dommage matériel (en €)</label>
|
||
`;
|
||
activityFormsContainer.appendChild(headerDiv);
|
||
|
||
// Iterate over each selected option
|
||
Array.from(select.options).forEach(option => {
|
||
if (option.selected && option.value) {
|
||
const existingChip = document.getElementById(option.value + "-chip");
|
||
if (!existingChip) {
|
||
const activityName = option.textContent;
|
||
const activityDiv = document.createElement('div');
|
||
activityDiv.classList.add('activity-input', 'row');
|
||
activityDiv.style.marginBottom = '10px';
|
||
activityDiv.innerHTML = `
|
||
<div style="display:flex;align-items:center;justify-content:center;">
|
||
<label class="chip" id="${option.value}-chip" for="${option.value}" style="flex: 3;">${activityName} :</label>
|
||
<input type="text" id="${option.value}" name="${option.value}" value="${option.dataset.defaultValue || ''}" style="flex: 2; margin-left: 10px;" oninput="handleInputActivity(this.name)"/>
|
||
</div>
|
||
<div>
|
||
<span id="${option.value}-error" class="red-text"></span>
|
||
</div>
|
||
`;
|
||
activityFormsContainer.appendChild(activityDiv);
|
||
}
|
||
} else {
|
||
const existingChip = document.getElementById(option.value + "-chip");
|
||
if (existingChip) {
|
||
const activityDiv = existingChip.closest('.activity-input');
|
||
if (activityDiv) {
|
||
activityDiv.remove();
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
function handleGarantieRCCSelection() {
|
||
const select = document.getElementById('garantieRCC-selector');
|
||
const garantieRccFormsContainer = document.getElementById('selected-garantieRCC');
|
||
|
||
// Clear previous entries
|
||
garantieRccFormsContainer.innerHTML = ''; // Clear any existing entries
|
||
|
||
// Iterate over each selected option
|
||
Array.from(select.options).forEach(option => {
|
||
if (option.selected && option.value) {
|
||
const garantieRccName = option.textContent;
|
||
const garantieRccDiv = document.createElement('div');
|
||
garantieRccDiv.classList.add('garantieRcc-input', 'row');
|
||
garantieRccDiv.style.display = 'flex';
|
||
garantieRccDiv.style.alignItems = 'center';
|
||
garantieRccDiv.style.justifyContent = 'start';
|
||
garantieRccDiv.style.marginBottom = '10px';
|
||
garantieRccDiv.innerHTML = `
|
||
<span id="${option.value}-chip" class="chip" for="${option.value}" style="color:darkblue">${garantieRccName}</span>`;
|
||
garantieRccFormsContainer.appendChild(garantieRccDiv);
|
||
}
|
||
});
|
||
}
|
||
|
||
function handleGarantieRCESelection() {
|
||
const select = document.getElementById('garantieRCE-selector');
|
||
const garantieRceFormsContainer = document.getElementById('selected-garantieRCE');
|
||
|
||
// Clear previous entries
|
||
garantieRceFormsContainer.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 garantieRceName = option.textContent;
|
||
const garantieRceDiv = document.createElement('div');
|
||
garantieRceDiv.classList.add('garantieRce-input', 'row');
|
||
garantieRceDiv.style.display = 'flex';
|
||
garantieRceDiv.style.alignItems = 'center';
|
||
garantieRceDiv.style.justifyContent = 'start';
|
||
garantieRceDiv.style.marginBottom = '10px';
|
||
garantieRceDiv.innerHTML = `
|
||
<span id="${option.value}-chip" class="chip" for="${option.value}" style="color:darkblue">${garantieRceName}</span>
|
||
`;
|
||
garantieRceFormsContainer.appendChild(garantieRceDiv);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
function handleMarchandiseSelection() {
|
||
const select = document.getElementById('marchandise-selector');
|
||
const marchandiseFormsContainer = document.getElementById('selected-marchandises');
|
||
|
||
// Clear previous entries
|
||
marchandiseFormsContainer.innerHTML = '';
|
||
|
||
// Iterate over each option
|
||
Array.from(select.options).forEach(option => {
|
||
if (option.selected && option.value) {
|
||
const existingChip = document.getElementById(`${option.value}-chip`);
|
||
if (!existingChip) {
|
||
const marchandiseName = option.textContent;
|
||
const marchandiseDiv = document.createElement('div');
|
||
marchandiseDiv.classList.add('marchandise-input', 'row');
|
||
marchandiseDiv.style.display = 'flex';
|
||
marchandiseDiv.style.alignItems = 'center';
|
||
marchandiseDiv.style.justifyContent = 'start';
|
||
marchandiseDiv.style.marginBottom = '10px';
|
||
marchandiseDiv.innerHTML = `
|
||
<span id="${option.value}-chip" class="chip" for="${option.value}" style="color:darkblue">${marchandiseName}</span>
|
||
`;
|
||
marchandiseFormsContainer.appendChild(marchandiseDiv);
|
||
}
|
||
} else {
|
||
const existingChip = document.getElementById(`${option.value}-chip`);
|
||
if (existingChip) {
|
||
const chipContainer = existingChip.closest('.marchandise-input');
|
||
if (chipContainer) {
|
||
chipContainer.remove();
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// 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);
|
||
});
|
||
}
|
||
|
||
// Supprimer une ligne du tableau
|
||
function deleteRow(btn) {
|
||
const row = btn.parentElement.parentElement;
|
||
row.parentElement.removeChild(row);
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
function extractGrilleAdvalo(tableID) {
|
||
var jsonData = [];
|
||
var table = document.getElementById(tableID);
|
||
if (!table) {
|
||
return jsonData;
|
||
}
|
||
|
||
var parentDiv = table.closest('div');
|
||
var wasHidden = false;
|
||
var originalDisplay = '';
|
||
var originalVisibility = '';
|
||
var originalPosition = '';
|
||
var originalLeft = '';
|
||
|
||
if (parentDiv) {
|
||
originalDisplay = parentDiv.style.display || '';
|
||
originalVisibility = parentDiv.style.visibility || '';
|
||
originalPosition = parentDiv.style.position || '';
|
||
originalLeft = parentDiv.style.left || '';
|
||
|
||
if (parentDiv.style.display === 'none' || window.getComputedStyle(parentDiv).display === 'none') {
|
||
wasHidden = true;
|
||
parentDiv.style.display = 'block';
|
||
parentDiv.style.visibility = 'hidden';
|
||
parentDiv.style.position = 'absolute';
|
||
parentDiv.style.left = '-9999px';
|
||
}
|
||
}
|
||
|
||
try {
|
||
if (!table.rows || table.rows.length < 2) {
|
||
return jsonData;
|
||
}
|
||
|
||
var zonesCount = table.rows[0] ? table.rows[0].cells.length - 1 : 0;
|
||
if (zonesCount === 0) {
|
||
return jsonData;
|
||
}
|
||
|
||
for (var i = 1; i < table.rows.length; i++) {
|
||
var row = table.rows[i];
|
||
if (!row || !row.cells || row.cells.length === 0) continue;
|
||
|
||
var category = row.cells[0] ? (row.cells[0].innerText || row.cells[0].textContent || '').trim() : '';
|
||
if (!category) continue;
|
||
|
||
var categoryData = { "name": category };
|
||
|
||
for (var j = 1; j <= zonesCount && j < row.cells.length; j++) {
|
||
var zoneKey = "zone" + j;
|
||
var cell = row.cells[j];
|
||
if (!cell) {
|
||
categoryData[zoneKey] = "Nous consulter";
|
||
continue;
|
||
}
|
||
|
||
var input = cell.querySelector("input[type='text']");
|
||
if (input) {
|
||
var zoneValue = (input.value || '').trim();
|
||
categoryData[zoneKey] = zoneValue || "Nous consulter";
|
||
} else {
|
||
categoryData[zoneKey] = "Nous consulter";
|
||
}
|
||
}
|
||
|
||
if (Object.keys(categoryData).length > 1) {
|
||
jsonData.push(categoryData);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.error('Erreur lors de l\'extraction de la grille Ad Valorem:', error);
|
||
} finally {
|
||
if (wasHidden && parentDiv) {
|
||
parentDiv.style.display = originalDisplay;
|
||
parentDiv.style.visibility = originalVisibility;
|
||
parentDiv.style.position = originalPosition;
|
||
parentDiv.style.left = originalLeft;
|
||
}
|
||
}
|
||
|
||
return jsonData;
|
||
}
|
||
|
||
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() {
|
||
let cot = "";
|
||
|
||
if (document.getElementById("forfaitaire").checked == true) { cot = "forfaitaire"; }
|
||
if (document.getElementById("revisable").checked == true) { cot = "revisable"; }
|
||
|
||
return cot;
|
||
}
|
||
|
||
function calcCotTotal() {
|
||
const cotRCCHT = parseFloat(document.getElementById("cotRCCHT").value) || 0
|
||
const cotRCCTTC = parseFloat(document.getElementById("cotRCCTTC").value) || 0
|
||
const cotRCEHT = parseFloat(document.getElementById("cotRCEHT").value) || 0
|
||
const cotRCETTC = parseFloat(document.getElementById("cotRCETTC").value) || 0
|
||
const cotPJHT = parseFloat(document.getElementById("cotPJHT").value) || 0
|
||
const cotPJTTC = parseFloat(document.getElementById("cotPJTTC").value) || 0
|
||
const cotFraisHT = parseFloat(document.getElementById("cotFraisHT").value) || 0
|
||
const cotFraisTTC = parseFloat(document.getElementById("cotFraisTTC").value) || 0
|
||
|
||
document.getElementById("cotTotalHT").value = (cotRCCHT + cotRCEHT + cotPJHT + cotFraisHT).toFixed(2);
|
||
document.getElementById("cotTotalTTC").value = (cotRCCTTC + cotRCETTC + cotPJTTC + cotFraisTTC).toFixed(2);
|
||
}
|
||
|
||
function calcTauxTotal() {
|
||
const tauxRCCHT = parseFloat(document.getElementById("tauxRCCHT").value) || 0
|
||
const tauxRCCTTC = parseFloat(document.getElementById("tauxRCCTTC").value) || 0
|
||
const tauxRCEHT = parseFloat(document.getElementById("tauxRCEHT").value) || 0
|
||
const tauxRCETTC = parseFloat(document.getElementById("tauxRCETTC").value) || 0
|
||
|
||
document.getElementById("tauxTotalHT").value = (tauxRCCHT + tauxRCEHT).toFixed(3);
|
||
document.getElementById("tauxTotalTTC").value = (tauxRCCTTC + tauxRCETTC).toFixed(3);
|
||
}
|
||
|
||
function calcCotFromTauxCA(idTaux, idCot) {
|
||
const valueCA = parseFloat(document.getElementById("CA").value) || 0
|
||
const valueTaux = parseFloat(document.getElementById(idTaux).value) || 0
|
||
|
||
document.getElementById(idCot).value = (valueCA * valueTaux / 100).toFixed(2);
|
||
}
|
||
|
||
function calcCotIrreductible() {
|
||
const cotRCCHT = parseFloat(document.getElementById("cotRCCHT").value) || 0
|
||
const cotRCEHT = parseFloat(document.getElementById("cotRCEHT").value) || 0
|
||
|
||
document.getElementById("cotisationIrreductible").value = ((cotRCCHT + cotRCEHT) * 0.8).toFixed(2);
|
||
}
|
||
|
||
function calcAddTaxe(idHT, valueTaxe, idTTC) {
|
||
const valueHT = parseFloat(document.getElementById(idHT).value) || 0
|
||
|
||
if (idTTC != "tauxRCCTTC" && idTTC != "tauxRCETTC") {
|
||
document.getElementById(idTTC).value = (valueHT * (1 + valueTaxe)).toFixed(2);
|
||
} else {
|
||
document.getElementById(idTTC).value = (valueHT * (1 + valueTaxe)).toFixed(3);
|
||
}
|
||
}
|
||
|
||
function calcSubTaxe(idHT, valueTaxe, idTTC) {
|
||
const valueTTC = parseFloat(document.getElementById(idTTC).value) || 0
|
||
|
||
if (idHT != "tauxRCCHT" && idHT != "tauxRCEHT") {
|
||
document.getElementById(idHT).value = (valueTTC / (1 + valueTaxe)).toFixed(2);
|
||
} else {
|
||
document.getElementById(idHT).value = (valueTTC / (1 + valueTaxe)).toFixed(3);
|
||
}
|
||
}
|
||
|
||
// Gérer la soumission du formulaire
|
||
async function handleSubmitForm(event) {
|
||
event.preventDefault();
|
||
|
||
// Étape 1: Créer d'abord un enregistrement dans projetRC
|
||
const grilleMultimodal = extractGrilleAdvalo('tabAdvaloMultimodal');
|
||
const grilleTerrestre = extractGrilleAdvalo('tabAdvaloTerrestre');
|
||
const grilleAerien = extractGrilleAdvalo('tabAdvaloAerien');
|
||
|
||
const projetRCData = {
|
||
// Tableaux
|
||
"assureAdditionnel": extractAssureAdditionnel('empTableAdditionnel'),
|
||
"designationVehicule": extractDesignationVehicule('empTableVehicules'),
|
||
"grilleMultimodal": grilleMultimodal,
|
||
"grilleTerrestre": grilleTerrestre,
|
||
"grilleAerien": grilleAerien,
|
||
|
||
// Activitées - avec gestion "Nous consulter"
|
||
"actVoiturier": document.getElementById("voiturier-chip") ? true : false,
|
||
"valueActVoiturier": document.getElementById("voiturier-chip") ? getValueOrConsulter("voiturier") : false,
|
||
"actLoueur": document.getElementById("loueur-chip") ? true : false,
|
||
"valueActLoueur": document.getElementById("loueur-chip") ? getValueOrConsulter("loueur") : false,
|
||
"actMultimodal": document.getElementById("commissionnaire-multimodal-chip") ? true : false,
|
||
"valueActMultimodal": document.getElementById("commissionnaire-multimodal-chip") ? getValueOrConsulter("commissionnaire-multimodal") : false,
|
||
"actDouane": document.getElementById("représentant-douane-chip") ? true : false,
|
||
"valueActDouane": document.getElementById("représentant-douane-chip") ? getValueOrConsulter("représentant-douane") : false,
|
||
"actDemPar": document.getElementById("demenageur-particulier-chip") ? true : false,
|
||
"valueActDemPar": document.getElementById("demenageur-particulier-chip") ? getValueOrConsulter("demenageur-particulier") : false,
|
||
"actDemParDom": document.getElementById("demenageur-particulier-dommage-chip") ? true : false,
|
||
"valueActDemParDom": document.getElementById("demenageur-particulier-dommage-chip") ? getValueOrConsulter("demenageur-particulier-dommage") : false,
|
||
"actDemParAdv": document.getElementById("demenageur-particulier-advalorem-chip") ? true : false,
|
||
"valueActDemParAdv": document.getElementById("demenageur-particulier-advalorem-chip") ? getValueOrConsulter("demenageur-particulier-advalorem") : false,
|
||
"actDemEntr": document.getElementById("demenageur-entreprise-chip") ? true : false,
|
||
"valueActDemEntr": document.getElementById("demenageur-entreprise-chip") ? getValueOrConsulter("demenageur-entreprise") : false,
|
||
"actDemInterne": document.getElementById("demenageur-interne-chip") ? true : false,
|
||
"valueActDemInterne": document.getElementById("demenageur-interne-chip") ? getValueOrConsulter("demenageur-interne") : false,
|
||
"actGardeMeuble": document.getElementById("garde-meubles-chip") ? true : false,
|
||
"valueActGardeMeuble": document.getElementById("garde-meubles-chip") ? getValueOrConsulter("garde-meubles") : false,
|
||
"actEntDep": document.getElementById("entrepositaire-depositaire-chip") ? true : false,
|
||
"valueActEntDep": document.getElementById("entrepositaire-depositaire-chip") ? getValueOrConsulter("entrepositaire-depositaire") : false,
|
||
"actPrestaLog": document.getElementById("prestataire-logistique-chip") ? true : false,
|
||
"valueActPrestaLog": document.getElementById("prestataire-logistique-chip") ? getValueOrConsulter("prestataire-logistique") : false,
|
||
"actLevageur": document.getElementById("manutentionnaire-levageur-chip") ? true : false,
|
||
"valueActLevageur": document.getElementById("manutentionnaire-levageur-chip") ? getValueOrConsulter("manutentionnaire-levageur") : false,
|
||
"actTransitaire": document.getElementById("transitaire-chip") ? true : false,
|
||
"valueActTransitaire": document.getElementById("transitaire-chip") ? getValueOrConsulter("transitaire") : false,
|
||
|
||
//Marchandises
|
||
"marOrdinaire": document.getElementById("ordinaire-chip") ? true : false,
|
||
"marRoulant": document.getElementById("roulant-chip") ? true : false,
|
||
"marEngins": document.getElementById("engins-chantier-agricole-chip") ? true : false,
|
||
"marRoulantDem": document.getElementById("roulant-demenagement-chip") ? true : false,
|
||
"marMobilerUsag": document.getElementById("mobilier-usages-chip") ? true : false,
|
||
"marPerissable": document.getElementById("perissable-temperature-dirigee-chip") ? true : false,
|
||
"marAnimaux": document.getElementById("animaux-vivant-chip") ? true : false,
|
||
"marCiterne": document.getElementById("citerne-chip") ? true : false,
|
||
"marBeton": document.getElementById("beton-chip") ? true : false,
|
||
"marExceptionnels": document.getElementById("exceptionnels-chip") ? true : false,
|
||
"marVrac": document.getElementById("vrac-chip") ? true : false,
|
||
|
||
// Territorialités - vérifier checked même si disabled
|
||
"zone1": document.getElementById("zone1") && (document.getElementById("zone1").checked || document.getElementById("zone1").disabled) ? true : false,
|
||
"zone2": document.getElementById("zone2") && (document.getElementById("zone2").checked || document.getElementById("zone2").disabled) ? true : false,
|
||
"zone3": document.getElementById("zone3") && document.getElementById("zone3").checked ? true : false,
|
||
"zone4": document.getElementById("zone4") && document.getElementById("zone4").checked ? true : false,
|
||
"zone5": document.getElementById("zone5") && document.getElementById("zone5").checked ? true : false,
|
||
"zone6": document.getElementById("zone6") && document.getElementById("zone6").checked ? true : false,
|
||
|
||
// Extensions de garantie RCC
|
||
"extRCCModifCalArrim": document.getElementById("modif-calage-arrimage-chip") ? true : false,
|
||
"extRCCFerroutage": document.getElementById("ferroutage-chip") ? true : false,
|
||
"extRCCFraisRecons": document.getElementById("frais-reconstitution-chip") ? true : false,
|
||
"extRCCConfie": document.getElementById("contenant-confie-chip") ? true : false,
|
||
"typeExtConfies": document.getElementById("contenant-confie-chip") ? (document.getElementById('ValeurDeclaree').checked ? "VALEUR DECLAREE" : "ADVALOREM") : "",
|
||
"extRCCTPPC": document.getElementById("tppc-chip") ? true : false,
|
||
"extRCCRegie": document.getElementById("regie-chip") ? true : false,
|
||
"extRCCSansMontageDemontage": document.getElementById("sans-montage-demontage-chip") ? true : false,
|
||
|
||
// Extensions de garantie RCE
|
||
"autresRC": document.getElementById("choixRCE").checked ? true : false,
|
||
"extRCEBraDebra": document.getElementById("branchement-debranchement-chip") ? true : false,
|
||
"extRCEMontageDemontage": document.getElementById("montage-demontage-chip") ? true : false,
|
||
|
||
// Activités complémentaires
|
||
"activitesVoiturier": JSON.stringify(getActivitesComplFromForm('actComplVoiturier/Loueur')),
|
||
"activitesCommissionnaire": JSON.stringify(getActivitesComplFromForm('actComplCommissionnaire de Transport')),
|
||
"activitesDemenageur": JSON.stringify(getActivitesComplFromForm('actComplDéménageur')),
|
||
"activitesLogistique": JSON.stringify(getActivitesComplFromForm('actComplLogistique')),
|
||
|
||
// Temporalités
|
||
"tempo": extractTempo(),
|
||
"dateEffet": document.getElementById("dateEffet").value,
|
||
"dateEcheance": document.getElementById("dateEcheance").value,
|
||
"dateFin": document.getElementById("dateFin").value,
|
||
"pj": document.getElementById("switchPJ").checked ? true : false,
|
||
"programmeInternationale": document.getElementById("programmeInternationale").checked ? true : false,
|
||
"participationResultat": document.getElementById("participationResultat").checked ? true : false,
|
||
|
||
// Cotisations - avec gestion "Nous consulter"
|
||
"typeCot": extractTypeCot(),
|
||
"ca": getValueOrConsulter("CA"),
|
||
"cotIrreductible": getValueOrConsulter("cotisationIrreductible"),
|
||
"tauxRCCHT": getValueOrConsulter("tauxRCCHT"),
|
||
"tauxRCCTTC": getValueOrConsulter("tauxRCCTTC"),
|
||
"tauxRCEHT": getValueOrConsulter("tauxRCEHT"),
|
||
"tauxRCETTC": getValueOrConsulter("tauxRCETTC"),
|
||
"tauxTotalHT": getValueOrConsulter("tauxTotalHT"),
|
||
"tauxTotalTTC": getValueOrConsulter("tauxTotalTTC"),
|
||
"cotRCCHT": getValueOrConsulter("cotRCCHT"),
|
||
"cotRCCTTC": getValueOrConsulter("cotRCCTTC"),
|
||
"cotRCEHT": getValueOrConsulter("cotRCEHT"),
|
||
"cotRCETTC": getValueOrConsulter("cotRCETTC"),
|
||
"cotPJHT": getValueOrConsulter("cotPJHT"),
|
||
"cotPJTTC": getValueOrConsulter("cotPJTTC"),
|
||
"cotTotalHT": getValueOrConsulter("cotTotalHT"),
|
||
"cotTotalTTC": getValueOrConsulter("cotTotalTTC"),
|
||
"cotFraisHT": getValueOrConsulter("cotFraisHT"),
|
||
"cotFraisTTC": getValueOrConsulter("cotFraisTTC")
|
||
};
|
||
|
||
// Créer ou mettre à jour l'enregistrement projetRC
|
||
let idProjetRC;
|
||
if (projet && projet.id) {
|
||
// Mettre à jour l'enregistrement projetRC existant
|
||
const responseProjetRC = await fetch(`/rc/projet/update/${projet.id}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(projetRCData),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataProjetRC = await responseProjetRC.json();
|
||
if (dataProjetRC.valid) {
|
||
idProjetRC = dataProjetRC.projetRc.id;
|
||
} else {
|
||
console.log('Échec lors de la mise à jour de l\'enregistrement ProjetRC :', dataProjetRC.message);
|
||
return;
|
||
}
|
||
} else {
|
||
// Créer un nouvel enregistrement projetRC
|
||
const responseProjetRC = await fetch(`/rc/projet/create`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(projetRCData),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataProjetRC = await responseProjetRC.json();
|
||
if (dataProjetRC.valid) {
|
||
idProjetRC = dataProjetRC.projetRc.id;
|
||
} else {
|
||
console.log('Échec lors de la création de l\'enregistrement ProjetRC :', dataProjetRC.message);
|
||
return;
|
||
}
|
||
}
|
||
|
||
if (idProjetRC) {
|
||
|
||
// Étape 2: Créer ou mettre à jour l'enregistrement RC principal
|
||
let idRC;
|
||
if (rc && rc.id) {
|
||
// Mettre à jour l'enregistrement RC existant avec la nouvelle référence projetRC
|
||
const responseRC = await fetch(`/rc/update/${rc.id}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
projetRC: idProjetRC
|
||
}),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataRC = await responseRC.json();
|
||
if (dataRC.valid) {
|
||
idRC = dataRC.rc.id;
|
||
} else {
|
||
console.log('Échec lors de la mise à jour de l\'enregistrement RC :', dataRC.message);
|
||
return;
|
||
}
|
||
} else {
|
||
// Créer un nouvel enregistrement RC
|
||
const responseRC = await fetch(`/rc/create`, {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
projetRC: idProjetRC,
|
||
typeCotisation: extractTypeCot()
|
||
}),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataRC = await responseRC.json();
|
||
if (dataRC.valid) {
|
||
idRC = dataRC.rc.id;
|
||
} else {
|
||
console.log('Échec lors de la création de l\'enregistrement RC :', dataRC.message);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// Étape 3: Mettre à jour le champ "rc" dans le contrat avec l'ID de la saisie RC
|
||
const responseContratEnCours = await fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${idRC}`, {
|
||
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": "RC",
|
||
"id": idRC,
|
||
"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) {
|
||
///////////////////////////////////////////////////////////////////////////////////////////////////////
|
||
/// TODO DEBUT Génération fichier à l'enregistrement A RETIRER QUAND MODE CONTRAT
|
||
const numParcours = getNumParcoursFromURL();
|
||
let filename;
|
||
|
||
// Envoi de la requête POST au serveur pour générer le projet
|
||
fetch(`/generate/rc/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 111:', 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('Échec lors de la mise à jour de l\'historique du contrat :', dataHistoriqueUpdate.message);
|
||
}
|
||
} else {
|
||
console.log('Échec lors de la mise à jour du champ "rc" dans le contrat :', dataContratEnCours.message);
|
||
}
|
||
} else {
|
||
console.log('Échec lors de la création de l\'enregistrement ProjetRC :', dataProjetRC.message);
|
||
}
|
||
}
|
||
|
||
// Fonction helper pour récupérer valeur ou "Nous consulter"
|
||
function getValueOrConsulter(id) {
|
||
const element = document.getElementById(id);
|
||
if (!element) return 'Nous consulter';
|
||
const value = element.value?.trim();
|
||
return value || 'Nous consulter';
|
||
}
|
||
|
||
// Fonction exposée pour sauvegarder le projet sans générer le document
|
||
async function saveProjetRC() {
|
||
try {
|
||
// Étape 1: Créer d'abord un enregistrement dans projetRC
|
||
const grilleMultimodal = extractGrilleAdvalo('tabAdvaloMultimodal');
|
||
const grilleTerrestre = extractGrilleAdvalo('tabAdvaloTerrestre');
|
||
const grilleAerien = extractGrilleAdvalo('tabAdvaloAerien');
|
||
|
||
const projetRCData = {
|
||
// Tableaux
|
||
"assureAdditionnel": extractAssureAdditionnel('empTableAdditionnel'),
|
||
"designationVehicule": extractDesignationVehicule('empTableVehicules'),
|
||
"grilleMultimodal": grilleMultimodal,
|
||
"grilleTerrestre": grilleTerrestre,
|
||
"grilleAerien": grilleAerien,
|
||
|
||
// Activitées
|
||
"actVoiturier": document.getElementById("voiturier-chip") ? true : false,
|
||
"valueActVoiturier": document.getElementById("voiturier-chip") ? getValueOrConsulter("voiturier") : false,
|
||
"actLoueur": document.getElementById("loueur-chip") ? true : false,
|
||
"valueActLoueur": document.getElementById("loueur-chip") ? document.getElementById("loueur").value : false,
|
||
"actMultimodal": document.getElementById("commissionnaire-multimodal-chip") ? true : false,
|
||
"valueActMultimodal": document.getElementById("commissionnaire-multimodal-chip") ? document.getElementById("commissionnaire-multimodal").value : false,
|
||
"actDouane": document.getElementById("représentant-douane-chip") ? true : false,
|
||
"valueActDouane": document.getElementById("représentant-douane-chip") ? document.getElementById("représentant-douane").value : false,
|
||
"actDemPar": document.getElementById("demenageur-particulier-chip") ? true : false,
|
||
"valueActDemPar": document.getElementById("demenageur-particulier-chip") ? document.getElementById("demenageur-particulier").value : false,
|
||
"actDemParDom": document.getElementById("demenageur-particulier-dommage-chip") ? true : false,
|
||
"valueActDemParDom": document.getElementById("demenageur-particulier-dommage-chip") ? document.getElementById("demenageur-particulier-dommage").value : false,
|
||
"actDemParAdv": document.getElementById("demenageur-particulier-advalorem-chip") ? true : false,
|
||
"valueActDemParAdv": document.getElementById("demenageur-particulier-advalorem-chip") ? document.getElementById("demenageur-particulier-advalorem").value : false,
|
||
"actDemEntr": document.getElementById("demenageur-entreprise-chip") ? true : false,
|
||
"valueActDemEntr": document.getElementById("demenageur-entreprise-chip") ? document.getElementById("demenageur-entreprise").value : false,
|
||
"actDemInterne": document.getElementById("demenageur-interne-chip") ? true : false,
|
||
"valueActDemInterne": document.getElementById("demenageur-interne-chip") ? document.getElementById("demenageur-interne").value : false,
|
||
"actGardeMeuble": document.getElementById("garde-meubles-chip") ? true : false,
|
||
"valueActGardeMeuble": document.getElementById("garde-meubles-chip") ? document.getElementById("garde-meubles").value : false,
|
||
"actEntDep": document.getElementById("entrepositaire-depositaire-chip") ? true : false,
|
||
"valueActEntDep": document.getElementById("entrepositaire-depositaire-chip") ? document.getElementById("entrepositaire-depositaire").value : false,
|
||
"actPrestaLog": document.getElementById("prestataire-logistique-chip") ? true : false,
|
||
"valueActPrestaLog": document.getElementById("prestataire-logistique-chip") ? document.getElementById("prestataire-logistique").value : false,
|
||
"actLevageur": document.getElementById("manutentionnaire-levageur-chip") ? true : false,
|
||
"valueActLevageur": document.getElementById("manutentionnaire-levageur-chip") ? document.getElementById("manutentionnaire-levageur").value : false,
|
||
"actTransitaire": document.getElementById("transitaire-chip") ? true : false,
|
||
"valueActTransitaire": document.getElementById("transitaire-chip") ? document.getElementById("transitaire").value : false,
|
||
|
||
//Marchandises
|
||
"marOrdinaire": document.getElementById("ordinaire-chip") ? true : false,
|
||
"marRoulant": document.getElementById("roulant-chip") ? true : false,
|
||
"marEngins": document.getElementById("engins-chantier-agricole-chip") ? true : false,
|
||
"marRoulantDem": document.getElementById("roulant-demenagement-chip") ? true : false,
|
||
"marMobilerUsag": document.getElementById("mobilier-usages-chip") ? true : false,
|
||
"marPerissable": document.getElementById("perissable-temperature-dirigee-chip") ? true : false,
|
||
"marAnimaux": document.getElementById("animaux-vivant-chip") ? true : false,
|
||
"marCiterne": document.getElementById("citerne-chip") ? true : false,
|
||
"marBeton": document.getElementById("beton-chip") ? true : false,
|
||
"marExceptionnels": document.getElementById("exceptionnels-chip") ? true : false,
|
||
"marVrac": document.getElementById("vrac-chip") ? true : false,
|
||
|
||
// Territorialités - vérifier checked même si disabled
|
||
"zone1": document.getElementById("zone1") && (document.getElementById("zone1").checked || document.getElementById("zone1").disabled) ? true : false,
|
||
"zone2": document.getElementById("zone2") && (document.getElementById("zone2").checked || document.getElementById("zone2").disabled) ? true : false,
|
||
"zone3": document.getElementById("zone3") && document.getElementById("zone3").checked ? true : false,
|
||
"zone4": document.getElementById("zone4") && document.getElementById("zone4").checked ? true : false,
|
||
"zone5": document.getElementById("zone5") && document.getElementById("zone5").checked ? true : false,
|
||
"zone6": document.getElementById("zone6") && document.getElementById("zone6").checked ? true : false,
|
||
|
||
// Extensions de garantie RCC
|
||
"extRCCModifCalArrim": document.getElementById("modif-calage-arrimage-chip") ? true : false,
|
||
"extRCCFerroutage": document.getElementById("ferroutage-chip") ? true : false,
|
||
"extRCCFraisRecons": document.getElementById("frais-reconstitution-chip") ? true : false,
|
||
"extRCCConfie": document.getElementById("contenant-confie-chip") ? true : false,
|
||
"typeExtConfies": document.getElementById("contenant-confie-chip") ? (document.getElementById('ValeurDeclaree').checked ? "VALEUR DECLAREE" : "ADVALOREM") : "",
|
||
"extRCCTPPC": document.getElementById("tppc-chip") ? true : false,
|
||
"extRCCRegie": document.getElementById("regie-chip") ? true : false,
|
||
"extRCCSansMontageDemontage": document.getElementById("sans-montage-demontage-chip") ? true : false,
|
||
|
||
// Extensions de garantie RCE
|
||
"autresRC": document.getElementById("choixRCE").checked ? true : false,
|
||
"extRCEBraDebra": document.getElementById("branchement-debranchement-chip") ? true : false,
|
||
"extRCEMontageDemontage": document.getElementById("montage-demontage-chip") ? true : false,
|
||
|
||
// Activités complémentaires
|
||
"activitesVoiturier": JSON.stringify(getActivitesComplFromForm('actComplVoiturier/Loueur')),
|
||
"activitesCommissionnaire": JSON.stringify(getActivitesComplFromForm('actComplCommissionnaire de Transport')),
|
||
"activitesDemenageur": JSON.stringify(getActivitesComplFromForm('actComplDéménageur')),
|
||
"activitesLogistique": JSON.stringify(getActivitesComplFromForm('actComplLogistique')),
|
||
|
||
// Temporalités
|
||
"tempo": extractTempo(),
|
||
"dateEffet": document.getElementById("dateEffet").value,
|
||
"dateEcheance": document.getElementById("dateEcheance").value,
|
||
"dateFin": document.getElementById("dateFin").value,
|
||
"pj": document.getElementById("switchPJ").checked ? true : false,
|
||
"programmeInternationale": document.getElementById("programmeInternationale").checked ? true : false,
|
||
"participationResultat": document.getElementById("participationResultat").checked ? true : false,
|
||
|
||
// Cotisations - avec gestion "Nous consulter"
|
||
"typeCot": extractTypeCot(),
|
||
"ca": getValueOrConsulter("CA"),
|
||
"cotIrreductible": getValueOrConsulter("cotisationIrreductible"),
|
||
"tauxRCCHT": getValueOrConsulter("tauxRCCHT"),
|
||
"tauxRCCTTC": getValueOrConsulter("tauxRCCTTC"),
|
||
"tauxRCEHT": getValueOrConsulter("tauxRCEHT"),
|
||
"tauxRCETTC": getValueOrConsulter("tauxRCETTC"),
|
||
"tauxTotalHT": getValueOrConsulter("tauxTotalHT"),
|
||
"tauxTotalTTC": getValueOrConsulter("tauxTotalTTC"),
|
||
"cotRCCHT": getValueOrConsulter("cotRCCHT"),
|
||
"cotRCCTTC": getValueOrConsulter("cotRCCTTC"),
|
||
"cotRCEHT": getValueOrConsulter("cotRCEHT"),
|
||
"cotRCETTC": getValueOrConsulter("cotRCETTC"),
|
||
"cotPJHT": getValueOrConsulter("cotPJHT"),
|
||
"cotPJTTC": getValueOrConsulter("cotPJTTC"),
|
||
"cotTotalHT": getValueOrConsulter("cotTotalHT"),
|
||
"cotTotalTTC": getValueOrConsulter("cotTotalTTC"),
|
||
"cotFraisHT": getValueOrConsulter("cotFraisHT"),
|
||
"cotFraisTTC": getValueOrConsulter("cotFraisTTC")
|
||
};
|
||
|
||
// Créer ou mettre à jour l'enregistrement projetRC
|
||
let idProjetRC;
|
||
if (projet && projet.id) {
|
||
// Mettre à jour l'enregistrement projetRC existant
|
||
const responseProjetRC = await fetch(`/rc/projet/update/${projet.id}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(projetRCData),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataProjetRC = await responseProjetRC.json();
|
||
if (dataProjetRC.valid) {
|
||
idProjetRC = dataProjetRC.projetRc.id;
|
||
} else {
|
||
console.log('Échec lors de la mise à jour de l\'enregistrement ProjetRC :', dataProjetRC.message);
|
||
return { valid: false, message: 'Échec mise à jour ProjetRC' };
|
||
}
|
||
} else {
|
||
// Créer un nouvel enregistrement projetRC
|
||
const responseProjetRC = await fetch(`/rc/projet/create`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(projetRCData),
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
const dataProjetRC = await responseProjetRC.json();
|
||
if (dataProjetRC.valid) {
|
||
idProjetRC = dataProjetRC.projetRc.id;
|
||
} else {
|
||
console.log('Échec lors de la création de l\'enregistrement ProjetRC :', dataProjetRC.message);
|
||
return { valid: false, message: 'Échec création ProjetRC' };
|
||
}
|
||
}
|
||
|
||
if (idProjetRC) {
|
||
|
||
// Étape 2: Créer ou mettre à jour l'enregistrement RC principal
|
||
let idRC;
|
||
|
||
if (rc && rc.id) {
|
||
// Mettre à jour l'enregistrement RC existant
|
||
const responseRC = await fetch(`/rc/update/${rc.id}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify({ projetRC: idProjetRC }),
|
||
headers: { 'Content-Type': 'application/json' },
|
||
});
|
||
const dataRC = await responseRC.json();
|
||
if (dataRC.valid) {
|
||
idRC = dataRC.rc.id;
|
||
} else {
|
||
return { valid: false, message: 'Échec mise à jour RC' };
|
||
}
|
||
} else {
|
||
// Créer un nouvel enregistrement RC
|
||
const responseRC = await fetch(`/rc/create`, {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
projetRC: idProjetRC,
|
||
typeCotisation: extractTypeCot()
|
||
}),
|
||
headers: { 'Content-Type': 'application/json' },
|
||
});
|
||
const dataRC = await responseRC.json();
|
||
if (dataRC.valid) {
|
||
idRC = dataRC.rc.id;
|
||
} else {
|
||
return { valid: false, message: 'Échec création RC' };
|
||
}
|
||
}
|
||
|
||
// Étape 3: Mettre à jour le contrat
|
||
const responseContrat = await fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${idRC}`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
});
|
||
const dataContrat = await responseContrat.json();
|
||
|
||
return { valid: dataContrat.valid, idRC, idProjetRC };
|
||
} else {
|
||
return { valid: false, message: 'Échec création ProjetRC' };
|
||
}
|
||
} catch (error) {
|
||
console.error('Erreur lors de la sauvegarde:', error);
|
||
return { valid: false, message: error.message };
|
||
}
|
||
}
|
||
|
||
// Exposer les fonctions globalement pour y accéder depuis l'extérieur
|
||
window.initSubmenuForm = init;
|
||
window.saveProjetRC = saveProjetRC;
|
||
})(); |