import {Component, OnInit} from '@angular/core'; import {AllService} from '../../../all.service'; import {FieldType, FormlyFieldConfig} from '@ngx-formly/core'; import {ActivatedRoute} from '@angular/router'; import {faCheck} from '@fortawesome/free-solid-svg-icons'; import {FormGroup} from '@angular/forms'; import { IVariableInsuranceAfterIncreaseModel } from "../../../entities/product-collection/variableInsuranceAfterIncrease.model"; @Component({ selector: 'jhi-step-medical-decision', templateUrl: './step-medical-decision.component.html', styleUrls: ['./step-medical-decision.component.scss'] }) export class StepMedicalDecisionComponent extends FieldType implements OnInit { constructor(private allService: AllService, private route: ActivatedRoute) { super(); } products = []; productsSelectable = []; productIdSelected = null; contractMedicalDecision = null; showLoader = false; productSelectable = true; userCanSelectProduct = true; classXl = 'col-xl'; faCheck = faCheck; formReadMore = new FormGroup({}); fieldsReadMore: FormlyFieldConfig[] = [ { fieldGroup: [ { key: 'remoretext', className: 'mt-3', type: 'textElement', templateOptions: { label: 'Comprendre mes garanties', autocomplete: false } }, { key: 'read-more-legende', type: 'readMore', templateOptions: { label: 'Comprendre mes garanties', autocomplete: false, title: 'Comprendre mes garanties', content: '' } } ] } ]; isNotEnvFluo = true; static camelCaseToSnakeCase(strCamel: string): string { if (strCamel) { return strCamel.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); } return strCamel; } ngOnInit(): void { this.isNotEnvFluo = this.allService.configurationPreview.environmentName !== 'fluo'; this.contractMedicalDecision = this.model['contract_medical_decision']; this.productIdSelected = this.model['project_product_selected_by_user']; this.allService.showButtonPrevious = false; this.allService.showButtonNext = false; // Appel de l'api pour charger les décisions medicale this.loadMedicalsDecisions(); // Check si le conseiller a rempli son le message, si oui on va activer la sélection de produit // this.productsCanBeSelected(); // set du logo du produit sélectionné if (this.productIdSelected) { this.setLogoSelected(this.productIdSelected); } } async loadMedicalsDecisions(): Promise { const contractId = this.route.snapshot.paramMap.get('contractid'); this.showLoader = true; try { const result = await this.allService.contractManagerService.getMedicalDecisionForPartnerre(contractId).toPromise(); this.showLoader = false; if (result.length > 0 && result.length !== 1) { this.products = result; this.classXl = 'col-xl'; this.setProductAdviceFirstPosition(); this.productsCanBeSelected(); } else if (result.length === 1) { this.products = result; this.allService.currentStepCustomError = false; this.allService.showButtonNext = true; } this.productsSelectable = this.products.filter(product => product.selectable || product.productCode == this.model['project_product_selected']); this.allService.showButtonNext = !!this.model['project_product_choosen_by_user'] || this.productsSelectable.length === 1 || this.contractMedicalDecision === 'NEED_MEDICAL_ANALYSIS' || this.contractMedicalDecision === 'OK'; } catch (err) { this.handleErrorLoadMedicalsDecisions(err); this.allService.showButtonNext = !!this.model['project_product_choosen_by_user'] || this.productsSelectable.length === 1 || this.contractMedicalDecision === 'NEED_MEDICAL_ANALYSIS' || this.contractMedicalDecision === 'OK'; } } handleErrorLoadMedicalsDecisions(err): boolean { this.products = []; this.productsSelectable = this.products.filter(product => product.selectable || product.productCode == this.model['project_product_selected']); this.showLoader = false; this.productsCanBeSelected(); if (this.allService.Sentry) { this.allService.Sentry.captureException(err); this.allService.Sentry.captureMessage('Une erreur est survenue durant la récupération de la décision médicale.'); } return true; } productsCanBeSelected(): void { if (this.products.length > 1 && this.contractMedicalDecision !== 'NEED_MEDICAL_ANALYSIS' && this.contractMedicalDecision !== 'OK') { if (!this.model['contract_duty_of_advice_suggestion_message'] || !this.model['contract_duty_of_advice_suggested_product_id']) { this.allService.currentStepCustomError = true; this.userCanSelectProduct = false; } if (!this.model['project_product_choosen_by_user']) { this.allService.currentStepCustomError = true; } } } private updateVariableInsurancesAfterIncrease(variablesLoansInsurance: IVariableInsuranceAfterIncreaseModel[]): void { variablesLoansInsurance.forEach((insurance, idx) => { const loanPrefix = `loan_${idx + 1}_`; if (insurance.capital !== null) { for (const key in insurance) { if (insurance.hasOwnProperty(key)) { const keyToReplace = `${loanPrefix}${StepMedicalDecisionComponent.camelCaseToSnakeCase(key)}`; this.model[keyToReplace] = insurance[key]; } } } }); } saveSelectedProduct(params: any): void { const product = params.product; const nextStep = params.nextStep; const productId = product.productCode; if (!this.userCanSelectProduct) { return; } if (product && product.variablesLoansInsurance && product.variablesLoansInsurance.length > 0) { this.updateVariableInsurancesAfterIncrease(product.variablesLoansInsurance); } this.allService.saveAnythingFromStepBuiltIn.emit({show: true}); const contract = { id: this.route.snapshot.paramMap.get('contractid'), productId }; this.allService.contractManagerService.updateProductOnContract(contract).toPromise().then((result) => { this.allService.saveAnythingFromStepBuiltIn.emit({show: false}); this.productIdSelected = productId; this.model['project_product_selected'] = this.productIdSelected; this.model['project_product_changed'] = productId === this.allService.productIdOriginal ? 'F' : 'T'; this.model['project_product_choosen_by_user'] = this.productIdSelected; this.model['product_need_medical_analysis'] = product.selectable ? 'F' : 'T'; this.allService.currentStepCustomError = false; this.allService.showButtonNext = true; this.allService.contract.productId = this.productIdSelected; if (this.allService.productIdOriginal !== this.productIdSelected) { this.resetInsuredCompany(); } this.setLogoSelected(productId); // this.allService.saveDataStep.emit({model: this.model, productStepId: this.allService.activeStep.productStepId}); this.allService.currentStepCustomError = false; if (nextStep) { this.allService.stepsSubject.next('next'); } // appel au multiple }).catch(e => { this.allService.saveAnythingFromStepBuiltIn.emit({show: false}); }); } setProductAdviceFirstPosition(): void { const productAdviceId = this.model['contract_duty_of_advice_suggested_product_id']; const productSelect = this.model['project_product_selected']; // On positionne le produit conseillé en premier if (productAdviceId) { this.products.sort((product, y) => { return product.productCode === productAdviceId ? -1 : y.productCode === productAdviceId ? 1 : 0; }); } // Si il n'y a pas de produit sélectionné, on met le produit entrant if (!productAdviceId && productSelect && this.products.length > 2 && this.products[0].productCode !== productSelect) { this.products.sort((product, y) => { return product.productCode === productSelect ? -1 : y.productCode === productSelect ? 1 : 0; }); } // Sinon on met le produit entrant second if (productAdviceId && productSelect && this.products.length > 2 && this.products[0].productCode !== productSelect) { // on trouve l'index const position = this.products.findIndex(product => product.productCode === productSelect); // On extrait l'élément const save = this.products.splice(position, 1); // on le positionne en 2snd position this.products.splice(1, 0, save[0]); } } resetInsuredCompany(): void { this.model['loan_already_insured_company'] = null; this.model['loan_total_amount_capital_company_already_insured'] = null; let data = { variableName: 'loan_already_insured_company', variableValue: null }; this.allService.setOriginalVariableValue.emit(data); data = { variableName: 'loan_total_amount_capital_company_already_insured', variableValue: null }; this.allService.setOriginalVariableValue.emit(data); } setLogoSelected(productId): void { this.products.forEach((product) => { product.productLogo = product.productLogo.replace('_selected', ''); }); const productSelected = this.products.find(product => product.productCode === productId); if (productSelected) { productSelected.productLogo = productSelected.productLogo.replace('.svg', '_selected.svg'); } } }