import { Component, OnInit, Input, ViewChild, ComponentFactoryResolver } from "@angular/core"; import { Router, ActivatedRoute } from "@angular/router"; import { InvestmentProposalForm } from "@app/models/investment-proposal-form"; import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service"; import { Instrument } from "@app/models/instrument"; import { InvestmentProposalWorkflowService } from "@app/services/investment-proposal-workflow.service"; import { InstrumentDirective } from "../instrument/instrument.directive"; import { InstrumentComponent } from "../instrument/instrument.component"; import { InstrumentsService } from "@app/services/instruments.service"; import { CatalogsService } from "@app/services/catalogs.service"; import { InvestmentsService } from "@app/services/investments.service"; import { AuthService } from "@app/services/auth2.service"; import { JwtHelperService } from "@auth0/angular-jwt"; import Swal from "sweetalert2"; @Component({ selector: "mt-wizard-result", templateUrl: "./result.component.html", styleUrls: ["./result.component.scss"] }) export class ResultComponent implements OnInit { helper = new JwtHelperService(); title = "Resumen de la propuesta"; @Input() ads: Instrument[]; @Input() formData: InvestmentProposalForm; @ViewChild(InstrumentDirective, { static: true }) adHost: InstrumentDirective; isFormValid: boolean = false; general: any; instrument: any; complement: any; final: any; workType: string; form: any; currentAdIndex = -1; interval: any; indexDynamicComponent: number; countries: any; companies: any; rates: any; revenues: any; funds: any; instrumentTypes: any; markets: any; emitters: any; periodicities: any; operations: any; format_incomes: any; base_types: any; payment_terms: any; financials: any; inversion: {}; investmentProposalID: string; investmentExists: boolean = false; reviewProposal: {}; userRole: any; state: string = ""; submitted: boolean = false; userList: any; test: any; constructor( private router: Router, private formDataService: FormInvestmentProposalService, private componentFactoryResolver: ComponentFactoryResolver, private instrumentService: InvestmentProposalWorkflowService, private loadInstrumentsService: InstrumentsService, private catalogService: CatalogsService, private investmentService: InvestmentsService, private route: ActivatedRoute, private authService: AuthService ) { this.formData = this.formDataService.getFormData(); this.isFormValid = this.formDataService.isFormValid(); this.ads = this.loadInstrumentsService.getInstruments(); const decodedToken = this.helper.decodeToken( this.authService.getJwtToken() ); this.userRole = decodedToken.groups; } ngOnInit() { this.route.params.subscribe(params => { this.investmentProposalID = params["id"]; }); if (this.investmentProposalID == undefined) this.investmentProposalID = this.route.snapshot.queryParamMap.get("id"); if (this.investmentProposalID != undefined) { this.investmentExists = true; this.investmentService .getProposalInvestment(this.investmentProposalID) .subscribe(res => { this.state = res["result"]["id_estado_inversion"]["codigo"]; }); } else { this.investmentExists = false; } this.formData.instrumentos; this.indexDynamicComponent = this.ads.findIndex( x => x.data.key == this.formData.instrumentos ); if (this.indexDynamicComponent >= 0) { this.loadComponent(); } else { console.log("No existe el componente"); } this.general = this.formDataService.getGeneralInfo(); this.instrument = this.formDataService.getWork(); this.complement = this.formDataService.getComplementInfo(); this.catalogService.getFinancialEntities().subscribe(res => { this.financials = res.find( e => e.id_entidad_financiera == this.general.casa ); this.financials = this.financials != undefined ? this.financials.nombre : "-"; }); this.catalogService.getBaseTypes().subscribe(res => { this.base_types = res.find( e => e.id_tipo_base == this.general.base_anual ); this.base_types = this.base_types != undefined ? `${this.base_types.tipo_base_dias} / ${this.base_types.tipo_base}` : "-"; }); this.catalogService.getCountries().subscribe(res => { this.countries = res.find(e => e.id_pais == this.complement.pais); this.countries = this.countries != undefined ? this.countries.nombre : "-"; }); this.catalogService.getCompanies().subscribe(res => { this.companies = res.find(e => e.id_empresa == this.complement.empresa); this.companies = this.companies != undefined ? this.companies.nombre : "-"; }); this.catalogService.getRateTypes().subscribe(res => { this.rates = res.find(e => e.id_tipo_tasa == this.general.tipo_tasa); this.rates = this.rates != undefined ? this.rates.nombre : "-"; }); this.catalogService.getRevenueTypes().subscribe(res => { this.revenues = res.find(e => e.id_tipo_renta == this.general.tipo_renta); this.revenues = this.revenues != undefined ? this.revenues.nombre : "-"; }); this.catalogService.getFundsOrigins().subscribe(res => { this.funds = res.find( e => e.id_origen_fondo == this.general.origenes_fondo ); this.funds = this.funds != undefined ? this.funds.nombre : "-"; }); this.catalogService.getInstrumentTypes().subscribe(res => { this.instrumentTypes = res.find( e => e.codigo == this.general.instrumentos ); this.instrumentTypes = this.instrumentTypes != undefined ? this.instrumentTypes.nombre : "-"; }); this.catalogService.getMarketTypes().subscribe(res => { this.markets = res.find( e => e.id_tipo_mercado == this.complement.tipo_mercado ); this.markets = this.markets != undefined ? this.markets.nombre : "-"; }); this.catalogService.getEmitterTypes().subscribe(res => { this.emitters = res.find( e => e.id_tipo_emisor == this.complement.emisores ); this.emitters = this.emitters != undefined ? this.emitters.nombre : "-"; }); this.catalogService.getPeriodicities().subscribe(res => { this.periodicities = res.find( e => e.id_periodicidad == this.general.periodicidad ); this.periodicities = this.periodicities != undefined ? this.periodicities.nombre : "-"; }); this.catalogService.getPaymentTerms().subscribe(res => { this.payment_terms = res.find(e => e.id_plazo == this.complement.plazo); this.payment_terms = this.payment_terms != undefined ? this.payment_terms.nombre : "-"; }); this.catalogService.getOperationTypes().subscribe(res => { this.operations = res.find( e => e.id_tipo_operacion == this.complement.operaciones ); this.operations = this.operations != undefined ? this.operations.nombre : "-"; }); //getIncomeFormat this.catalogService.getIncomeFormat().subscribe(res => { this.format_incomes = res.find( e => e.id_formato_ingreso == this.general.formato_ingreso ); this.format_incomes = this.format_incomes != undefined ? this.format_incomes.nombre : "-"; }); this.final = {}; Object.assign(this.final, this.general, this.instrument, this.complement); this.inversion = { codigo_instrumento: this.general.instrumentos, info_inversion: { id_empresa: +this.complement.empresa, id_pais: +this.complement.pais, id_entidad: +this.general.casa, id_origen_fondo: +this.general.origenes_fondo, id_periodicidad: +this.general.periodicidad, id_plazo: +this.complement.plazo, id_tipo_base: +this.general.base_anual, id_tipo_emisor: +this.complement.emisores, id_tipo_mercado: this.complement.tipo_mercado, id_tipo_operacion: +this.complement.operaciones, //id_tipo_pago: 1, id_formato_ingreso: +this.general.formato_ingreso, id_tipo_renta: +this.general.tipo_renta, id_tipo_tasa: +this.general.tipo_tasa, nombre_inversion: this.general.name, asunto: this.general.asunto, comentario: this.complement.comentarios, justificacion: this.complement.justificacion }, info_instrumento: this.instrument }; if ( (this.inversion["codigo_instrumento"] == "CETE" || this.inversion["codigo_instrumento"] == "DAP" || this.inversion["codigo_instrumento"] == "VCN" || this.inversion["codigo_instrumento"] == "BONO" || this.inversion["codigo_instrumento"] == "TIT" || this.inversion["codigo_instrumento"] == "EURB" || this.inversion["codigo_instrumento"] == "CINV" || this.inversion["codigo_instrumento"] == "FINV" || this.inversion["codigo_instrumento"] == "PBUR" || this.inversion["codigo_instrumento"] == "PPER" || this.inversion["codigo_instrumento"] == "PEMP") && (this.instrument["proyecciones"] != undefined || this.instrument["proyecciones"] != "") ) { this.inversion["proyecciones"] = this.instrument["proyecciones"].slice( 0, -1 ); } } loadComponent() { const adItem = this.ads[this.indexDynamicComponent]; const componentFactory = this.componentFactoryResolver.resolveComponentFactory( adItem.component ); const viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.clear(); const componentRef = viewContainerRef.createComponent(componentFactory); (componentRef.instance).data = adItem.data; (componentRef.instance).summary = true; } // Guardar propuesta de inversion (Crear) submit() { Swal.fire({ allowOutsideClick: false, icon: "info", text: "Espere por favor..." }); Swal.showLoading(); if (this.investmentProposalID != undefined) { } else { this.investmentService.createProposalInvestment(this.inversion).subscribe( success => { if (success) { Swal.fire({ allowOutsideClick: false, icon: "success", showCancelButton: false, title: "Exito", confirmButtonText: "El registro ha sido guardado" }).then(result => { if (result.value) { window.location.href = "#/investment-proposals"; } }); } }, err => { Swal.fire({ icon: "error", title: "Error al guardar", text: err.message }); } ); } } //Enviar a revision la propuesta de inversion sendToReview() { this.investmentService .getAvailableUsers(this.investmentProposalID) .subscribe(res => { this.userList = res["usuarios_next"]; this.test = "
Notificar a:
"; if (this.userList.length > 0) { for (let i = 0; i < this.userList.length; i++) { this.test += `
`; } } }); this.reviewProposal = undefined; (async () => { Swal.fire({ title: `

Enviar a revisión propuesta de inversión

`, icon: "info", html: `

Comentario:

`, input: "textarea", showCancelButton: true, confirmButtonText: "Enviar propuesta", cancelButtonText: "Cancelar", showLoaderOnConfirm: true, inputValidator: value => { if (!value) { return "Debe ingresar un comentario"; } }, preConfirm: comentario => { this.reviewProposal = { id_inversion: this.investmentProposalID, step: "next", comentario: comentario }; }, allowOutsideClick: () => !Swal.isLoading() }).then(result => { if (result.dismiss) { return false; } Swal.fire({ title: `

Enviar a revisión propuesta de inversión

`, icon: "info", html: `${this.test}`, confirmButtonText: "Siguiente", showCancelButton: true, cancelButtonText: "Cancelar", showLoaderOnConfirm: true, preConfirm: () => { let array = []; for (let i = 0; i < this.userList.length; i++) { let html_input: HTMLInputElement = document.getElementById( this.userList[i] ) as HTMLInputElement; let html_value: string = html_input.value; if (html_input.checked == true) { array.push(html_value); } } this.reviewProposal["notificar"] = array.toString(); } }).then(result1 => { if (result1.dismiss) { return false; } Swal.fire({ allowOutsideClick: false, title: "Espere por favor...", icon: "info" }); Swal.showLoading(); this.investmentService .sendReviewProposalInvestment(this.reviewProposal) .subscribe( success => { if (success) { Swal.fire({ allowOutsideClick: false, icon: "success", showCancelButton: false, title: "Exito", confirmButtonText: "La propuesta ha sido enviada a revisión" }).then(result => { Swal.close(); window.location.reload(); }); } }, err => { if (err.code == 405) { Swal.fire({ icon: "error", title: "Operacion no permitida", text: err.message }).then(result => { Swal.close(); window.location.href = "#/investment-proposals"; }); } else { Swal.fire({ icon: "error", title: "Error al guardar", text: err.message }); } } ); }); //window.location.reload(); }); })(); } // Actualizar la propuesta de inversion si se han realizado cambios update_proposal() { Swal.fire({ allowOutsideClick: false, icon: "info", text: "Espere por favor..." }); Swal.showLoading(); this.investmentService .updateProposalInvestment(this.investmentProposalID, this.inversion) .subscribe( success => { if (success) { Swal.fire({ allowOutsideClick: false, icon: "success", showCancelButton: false, title: "Exito", confirmButtonText: "El registro ha sido actualizado" }).then(result => { Swal.close(); }); } }, err => { Swal.fire({ icon: "error", title: "Error al guardar", text: err.message }); } ); } goToPrevious() { this.submitted = true; if (this.investmentProposalID != undefined) { this.router.navigate(["/investment-proposal/complement-info"], { queryParams: { id: this.investmentProposalID } }); } else { this.router.navigate(["/investment-proposal/complement-info"]); } } //Enviar a revision la propuesta de inversion finishProposal() { this.investmentService .getAvailableUsers(this.investmentProposalID) .subscribe(res => { this.userList = res["usuarios_next"]; this.test = "
Notificar a:
"; if (this.userList.length > 0) { for (let i = 0; i < this.userList.length; i++) { this.test += `
`; } } }); this.reviewProposal = undefined; (async () => { Swal.fire({ title: `

Finalizar propuesta de inversión:

`, icon: "info", input: "textarea", html: `

Comentario:

`, showCancelButton: true, confirmButtonText: "Siguiente", cancelButtonText: "Cancelar", inputValidator: value => { if (!value) { return "Debe ingresar un comentario"; } }, preConfirm: comentario => { this.reviewProposal = { id_inversion: this.investmentProposalID, step: "next", comentario: comentario }; }, allowOutsideClick: () => !Swal.isLoading() }).then(result => { if (result.dismiss) { return false; } Swal.fire({ title: `

Finalizar propuesta de inversión

`, icon: "info", html: `${this.test}`, confirmButtonText: "Enviar a revision", showCancelButton: true, cancelButtonText: "Cancelar", showLoaderOnConfirm: true, preConfirm: () => { let array = []; for (let i = 0; i < this.userList.length; i++) { let html_input: HTMLInputElement = document.getElementById( this.userList[i] ) as HTMLInputElement; let html_value: string = html_input.value; if (html_input.checked == true) { array.push(html_value); } } this.reviewProposal["notificar"] = array.toString(); } }).then(result1 => { if (result1.dismiss) { return false; } Swal.fire({ allowOutsideClick: false, title: "Espere por favor...", icon: "info" }); Swal.showLoading(); this.investmentService .sendReviewProposalInvestment(this.reviewProposal) .subscribe( success => { if (success) { Swal.fire({ allowOutsideClick: false, icon: "success", showCancelButton: false, title: "Exito", confirmButtonText: "La propuesta ha sido finalizada" }).then(result => { Swal.close(); window.location.reload(); }); } }, err => { if (err.code == 405) { Swal.fire({ icon: "error", title: "Operacion no permitida", text: err.message }).then(result => { Swal.close(); window.location.href = "#/investment-proposals"; }); } else { Swal.fire({ icon: "error", title: "Error al guardar", text: err.message }); } } ); }); //window.location.reload(); }); })(); } // Verifica permisos para mostrar boton de edicion y/o envio a revision, // segun los permisos del usuario y el estado de la propuesta can_send_to_review(status: string) { if (status == "NUEVA" || status == "RECHA") { // TO DO ver que el codigo de los tipos de usuario return true; } else { return false; } } can_finish_proposal(status: string) { if (status == "LIQUI") { // TO DO ver que el codigo de los tipos de usuario return true; } else { return false; } } }