import { AfterContentChecked, ChangeDetectorRef, Component, KeyValueDiffers, OnInit, ViewEncapsulation } from '@angular/core'; import {ProductCollectionService} from '../entities/product-collection/product-collection.service'; import {CustomerVariableService} from '../entities/product-collection/customer-variable.service'; import {ProductTemplateService} from '../entities/product-collection/product-template.service'; import {DocumentReaderService} from '../entities/product-collection/document-reader.service'; import {OrganismeService} from '../entities/product-collection/organisme.service'; import {ContractDocumentService} from '../entities/product-collection/contract-document.service'; import {ActivatedRoute, Router} from '@angular/router'; import {FormlyFieldConfig, FormlyFormOptions} from '@ngx-formly/core'; import {FormArray, FormGroup} from '@angular/forms'; import {FileStorageManagerService} from "../entities/product-collection/file-storage-manager.service"; import {Observable, Subject} from 'rxjs'; import {environment} from '../../environments/environment'; import {ModalWarningService} from '../services/modal-warning.service'; import {ContractService} from '../entities/product-collection/contract.service'; import {ContractManagerService} from '../entities/product-collection/contract-manager.service'; import {ReferenceManagerService} from '../entities/product-collection/referencemanager.service'; import {JsonEditorOptions} from 'ang-jsoneditor'; export interface StepType { label: string; fields: FormlyFieldConfig[]; } @Component({ selector: 'app-preview', templateUrl: './preview.component.html', styleUrls: ['./preview.component.scss'], encapsulation: ViewEncapsulation.None }) export class PreviewComponent implements OnInit, AfterContentChecked { variables: any[] = []; model: any = {}; options: FormlyFormOptions = {}; fields: FormlyFieldConfig[] = []; steps: StepType[] = []; form = new FormArray(this.steps.map(() => new FormGroup({}))); data: { variables: Array; steps: Array; } = { variables: [], steps: [] }; modelDiffer: any; activedStep = 0; public modelReady = false; services = {}; variableToCheck: Array = []; variableToCheckInitialValues: Array = []; projectid: any = ''; customerid: any = ''; productid: any = ''; contractid: any = ''; productcollectionid: any = ''; brokerid: any = ''; contractType: any = ''; medicalCriteria: any = ''; hasMedical = false; eventsDetectStepSubject: Subject = new Subject(); loadIframeSaveMultiple = false; product: any = {}; showModalRecalcul = false; showModalLemoine = false; configurationPreview = {}; contract = {id: null, currentStepId: ''}; loadPositionStep = false; showDebug = false; showModel = false; editorOptions = null; constructor( private productCollectionService: ProductCollectionService, private customerVariableService: CustomerVariableService, private productTemplateService: ProductTemplateService, private documentReaderService: DocumentReaderService, private organismeService: OrganismeService, private contractDocumentService: ContractDocumentService, private fileStorageManagerService: FileStorageManagerService, private modalWarningService: ModalWarningService, private contractService: ContractService, private contractManagerService: ContractManagerService, private referenceManagerService: ReferenceManagerService, private route: ActivatedRoute, private differs: KeyValueDiffers, private cdref: ChangeDetectorRef, private router: Router ) { document.addEventListener('showDebug', () => { this.showDebug = true; }); this.editorOptions = new JsonEditorOptions(); this.editorOptions.modes = ['code', 'text', 'tree', 'view']; // à appeler depuis la console via : document.dispatchEvent(new CustomEvent('showDebug', { bubbles: true })); } ngOnInit(): void { this.services['customerVariableService'] = this.customerVariableService; this.services['productTemplateService'] = this.productTemplateService; this.services['documentReaderService'] = this.documentReaderService; this.services['contractDocumentService'] = this.contractDocumentService; this.services['organismeService'] = this.organismeService; this.services['fileStorageManagerService'] = this.fileStorageManagerService; this.services['modalWarningService'] = this.modalWarningService; this.services['contractService'] = this.contractService; this.services['contractManagerService'] = this.contractManagerService; this.services['referenceManagerService'] = this.referenceManagerService; this.projectid = this.route.snapshot.paramMap.get('projectid') ? this.route.snapshot.paramMap.get('projectid') : ''; this.customerid = this.route.snapshot.paramMap.get('customerid') ? this.route.snapshot.paramMap.get('customerid') : ''; this.productid = this.route.snapshot.paramMap.get('productid') ? this.route.snapshot.paramMap.get('productid') : ''; this.contractid = this.route.snapshot.paramMap.get('contractid') ? this.route.snapshot.paramMap.get('contractid') : ''; this.brokerid = this.route.snapshot.paramMap.get('brokerid') ? this.route.snapshot.paramMap.get('brokerid') : ''; this.productcollectionid = this.route.snapshot.paramMap.get('productcollectionid') ? this.route.snapshot.paramMap.get('productcollectionid') : ''; this.getData().then(() => { this.buildKeyModel(); this.setVariableToCheck(); this.form = new FormArray(this.steps.map(() => new FormGroup({}))); this.modelDiffer = this.differs.find(this.model).create(); }); this.configurationPreview = environment.configurationPreview; this.configurationPreview['environmentName'] = environment.environmentName; } ngAfterContentChecked(): void { this.cdref.detectChanges(); } async getData(): Promise { const responseCustomerVariable = await this.customerVariableService .getCustomersVariablesByCustomerAndProjectId(this.customerid, this.projectid, this.productid) .toPromise(); if (responseCustomerVariable.body) { this.model = responseCustomerVariable.body['variables']; this.variables = responseCustomerVariable.body['variables']; } const findById = this.productcollectionid ? this.productcollectionid : this.productid; const responseProductCollectionService: { body: any } = await this.productCollectionService.preview(findById).toPromise(); if (responseProductCollectionService.body && responseProductCollectionService.body['steps']) { this.steps = responseProductCollectionService.body['steps']; this.loadPositionStep = responseProductCollectionService.body['loadPositionStep']; } const productCollection = await this.productCollectionService.getProduct(this.productid).toPromise(); if (productCollection.body) { this.product = productCollection.body; } if (productCollection.body && productCollection.body['medicalCriteria']) { this.medicalCriteria = productCollection.body['medicalCriteria']; this.checkIfMedicalData(); } if (productCollection.body && productCollection['shortcutCriteria']) { this.model['insured_has_shortcut'] = eval(productCollection['shortcutCriteria']); } const contractHttpResponse = await this.contractService.find(this.contractid).toPromise(); if (contractHttpResponse.body) { this.contract = contractHttpResponse.body; } } buildKeyModel(): void { this.steps.forEach((step: any) => { step.fields.forEach((field: any) => { field.fieldGroup.forEach((element: any) => { element.fieldGroup.forEach((group: any) => { this.model[group.key] = []; }); }); }); }); this.modelReady = true; } saveDataStep(data: any) { this.loadIframeSaveMultiple = true; const dataForApi = {...data.model}; const dataSaved = dataForApi; if (this.form.valid) { this.steps.forEach((step: any) => { step.fields.forEach((field: any) => { field.fieldGroup.forEach((element: any) => { if (element.fieldGroup) { element.fieldGroup.forEach((f: any) => { dataSaved[f.key] = dataForApi[f.key]; delete dataForApi[f.key]; }); } }); }); }); let recalculate = (this.model['recalculate'] || this.variablesHasChanged(data.model)) ? true : false; console.log('variableHaschanged : ', this.variablesHasChanged(data.model)); if (recalculate && this.model['loan_already_insured_company'] !== 'T') { recalculate = false; } const arrayBuiltinSEPA = ['5f00f00bc491764ec6c30b47', 'nom', 'Prenom', 'adresse', 'cp', 'ville', 'iban', 'bic', 'FILECNI', 'recalculate', 'summaryDate']; if (this.model['insured_identity_current_zipcode_city']) { arrayBuiltinSEPA.push('insured_identity_current_zipcode', 'insured_identity_current_city'); } arrayBuiltinSEPA.forEach(fieldName => { delete dataForApi[fieldName]; }); const arrayVarProject = ['project_insurance_total_cost', 'project_prime_monthly', 'project_insurance_annual_average_rate', 'project_total_money_saved']; arrayVarProject.forEach(fieldName => { delete dataForApi[fieldName]; }); dataForApi['signature_date'] = this.currentDate(); // Réinitialisation de la variable project_product_changed if (recalculate) { dataForApi['project_product_changed'] = null; } this.customerVariableService .updateMultipleCustomerVariable(this.customerid, this.projectid, dataForApi, recalculate) .toPromise() .then(response => { this.loadIframeSaveMultiple = false; if (response && response.body) { this.contractService.saveContractHistory( this.contractid, recalculate ? 0 : data.productStepId ).subscribe((result: any) => { if (result.status === 'LEMOINE_LOCKED') { this.showModalLemoine = true; } else { this.model = data.model; this.showModalRecalcul = recalculate; if (!recalculate) { this.eventsDetectStepSubject.next(); } } }); } else { this.loadIframeSaveMultiple = false; this.eventsDetectStepSubject.next('error multiple'); } }, error => { this.contractService.saveContractHistory(this.contractid, data.productStepId).subscribe(); console.log(error); this.loadIframeSaveMultiple = false; this.eventsDetectStepSubject.next('error multiple'); }); } } recalculate(): void { const productcollectionid = this.route.snapshot.paramMap.get('productcollectionid') ? this.route.snapshot.paramMap.get('productcollectionid') : ''; const productId = (this.model['project_product_selected'] && this.model['project_product_selected'] !== this.productid) ? this.model['project_product_selected'] : this.productid; window.location.href = '/preview/' + productId + '/' + this.customerid + '/' + this.projectid + '/' + this.contractid + '/' + this.brokerid + '/' + productcollectionid; } updateVariables(data: any): void { // const dataSaved = this.saveVariableFromFormly(data); this.checkIfMedicalData(); /* this.customerVariableService .getCustomersVariablesCalculatedByCustomerAndProjectId(this.customerid, this.projectid, this.productid, data) .toPromise() .then(response => { if (response && response.body) { const mTemp = response.body['variables']; this.steps.forEach((step: any) => { step.fields.forEach((field: any) => { field.fieldGroup.forEach((element: any) => { element.fieldGroup.forEach((f: any) => { mTemp[f.key] = dataSaved[f.key]; }); }); }); }); this.model = mTemp; } }); */ } checkIfMedicalData(): void { this.hasMedical = eval(this.medicalCriteria); console.log('HAS MEDICAL : ', this.hasMedical); } saveVariableFromFormly(data: any): any { const dataSaved = {}; this.steps.forEach((step: any) => { step.fields.forEach((field: any) => { field.fieldGroup.forEach((element: any) => { if (element.fieldGroup) { element.fieldGroup.forEach((f: any) => { dataSaved[f.key] = data[f.key]; delete data[f.key]; }); } }); }); }); return dataSaved; } setVariableToCheck(): void { this.productCollectionService .getVariablesToListenByProjectId(this.productid) .toPromise() .then((data) => { this.variableToCheck = data.body; if (this.variableToCheck) { this.variableToCheck.forEach(element => { this.variableToCheckInitialValues[element] = this.model[element]; }); } }); } variablesHasChanged(model): boolean { let hasChanged = null; hasChanged = this.variableToCheck.find(element => { if (element === 'loan_already_insured_company') { if (model[element] === null || (this.variableToCheckInitialValues[element] === null && model[element] === 'F')) { return false; } } return this.variableToCheckInitialValues[element] !== model[element]; }); return !!hasChanged; } hideModel() { this.showDebug = false; } currentDate() { const d = new Date(); let month = '' + (d.getMonth() + 1); let day = '' + d.getDate(); const year = d.getFullYear(); if (month.length < 2) { month = '0' + month; } if (day.length < 2) { day = '0' + day; } return [year, month, day].join('-'); } showSaving(event): void { this.loadIframeSaveMultiple = event.show; } setOriginalVariableValue(data): void { this.variableToCheckInitialValues[data.variableName] = data.variableValue; } navigateToHome(): void { this.router.navigate(['']).then(); } }