multiple vm

In this example below you will see how to do a multiple vm with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by tecayehuatl, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright tecayehuatl ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>multiple vm</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/tecayehuatl/multiple-vm-pdzWyY */
define('vm/mortgage-loan',
    ['jquery', 'core', 'knockout', 'vm/common', 'data/mortgage-loan', 'data/client', 'vm/client', 'data/financial', 'data/commons', 'knockout-mapping', 'knockout-postbox', 'utils', 'enums', 'axios', 'knockout-validation', 'nanoscroller'],
    function ($, core, ko, common, data, dataClient, vmClient, financial, dataCommons, km, kp, utils, enums, axiosLib) {
        'use strict';
        //BORRAR LA LIBRERIA NANOSCROLLER, ESTA SOLO COMO TEST CON REQUIREJS
        ko.mapping = km;
        ko.postbox = kp;

        var vm = {};

        var axios = axiosLib.create();

        axios.interceptors.response.use(function (response) {
            return response;
        },
            function (error) {
                console.log(error);
                if (error.response.status == 401) {
                    core.snackbar.show({
                        text: "Por favor, vuelve a loguearte.",
                        typeAlert: 'c-danger'
                    });
                    setTimeout(function () {
                        window.location = window.location;
                    },
                        1500);
                } /*else if (error.response.status == 400) {
                    console.log("400: ", error.response);
                }*/
                return Promise.reject(error);
            });

        vm.NewFinancialInstitution = function () {
            var self = this;

            self.showAddBankForm = ko.observable(false);
            self.leadId = ko.observable();
            self.financialInstitutionId = ko.observable().extend({ required: true });
            self.financialInstution = ko.observable();
            self.mortgageLoanId = ko.observable().extend({ required: true });
            self.stage = ko.observable();

            self.creditAmount = ko.observable('').extend({ required: true });
            self.downPayment = ko.observable('').extend({ required: true });
            self.initialInterestRate = ko.observable();
            self.initialInterestRateFormatted = ko.observable('').extend({ required: true });
            self.propertyValue = ko.observable('').extend({ required: true });
            self.monthlyPayment = ko.observable('').extend({ required: true });
            self.totalAnnualCost = ko.observable();
            self.totalAnnualCostFormatted = ko.observable('').extend({ required: true });
            self.creditStatusId = ko.observable().extend({ required: true });
            self.termId = ko.observable().extend({ required: true });
            self.showAddBankErrors = ko.observable(false);
            self.customErrorMessage = ko.observable(false);
            self.onShowAddBankButton = ko.observable(true);

            self.financialInstitutions = ko.observableArray();
            self.mortgageLoanTerms = ko.observableArray();
            self.financialTerms = ko.observableArray();
            self.financialStatus = ko.observableArray();
            self.creditStatus = ko.observableArray();

            self.financialInstitutionId.subscribe(function (val) {
                if (val) {
                    axios.get(core.router().financial("mortgage-loan").get, { params: { parentId: val } })
                        .then(function (response) {
                            self.mortgageLoanTerms(response.data);
                        })
                        .catch(function() {});
                }
            });
            self.mortgageLoanId.subscribe(function (val) {
                if (val) self.onGetFinancialStatus();
                self.getTerms(self.mortgageLoanId());
            });

            self.onGetFinancialInstitutions = function () {
                axios.get(core.router().financial("financial-institution").get)
                    .then(function (response) {
                        self.financialInstitutions(response.data);
                    })
                    .catch(function() {
                    });
            };

            self.onGetFinancialStatus = function () {
                axios.get(core.router().financial("mortgage-loan-status").get)
                    .then(function (response) {
                        self.creditStatus(response.data);
                        self.creditStatusId(enums.AmountStatus.PreApproved);
                    })
                    .catch(function() {});
            };

            self.getTerms = function () {
                if (self.mortgageLoanId()) {
                    axios.get(core.router().financial("term").get, { params : { "parentId" : self.mortgageLoanId() } })
                        .then(function (response) {
                        self.financialTerms(response.data);
                    }).catch(function () { });
                }
            };

            self.onShowAddBankForm = function () {
                self.onShowAddBankButton(false);
                self.showAddBankForm() ? self.showAddBankForm(false) : self.showAddBankForm(true);
                if (self.showAddBankForm) self.onGetFinancialInstitutions();
            };

            self.onHideAddBankForm = function () {
                self.onShowAddBankButton(true);
                self.clearInputs();
                self.showAddBankForm(false);
            };

            self.onAddFinancial = function () {
                
                if (parseInt(self.propertyValue()) >= 0 && parseInt(self.creditAmount()) >= 0) {

                    if (parseInt(self.propertyValue()) > parseInt(self.creditAmount())) {
                        self.customErrorMessage(false);
                    }
                    else {
                        self.customErrorMessage(true);
                        return;
                    }
                }
                else {
                    self.customErrorMessage(true);
                }

                if (self.errors().length > 0) {
                    self.errors.showAllMessages();
                    self.showAddBankErrors(true);
                    return;
                }
                core.loading.showAppLoader();
                var initialInterestRateResult = self.initialInterestRateFormatted() / 100;
                self.initialInterestRate(initialInterestRateResult.toFixed(4));

                var totalAnnualCostResult = self.totalAnnualCostFormatted() / 100;
                self.totalAnnualCost(totalAnnualCostResult.toFixed(4));

                var payload = {
                    'leadId': self.leadId(),
                    'mortgageLoanId': self.mortgageLoanId(), 
                    'term': self.termId(),
                    'creditAmount': self.creditAmount(),
                    'propertyValue': self.propertyValue(),
                    'downPayment': self.downPayment(),
                    'monthlyPayment': self.monthlyPayment(),
                    'creditStatus': self.creditStatusId(),
                    'initialInterestRate': self.initialInterestRate(),
                    'totalAnnualCost': self.totalAnnualCost()
                };
                
                axios.post(core.router().mortgageLoanLead(self.leadId()).mortgageLoans, payload )
                    .then(function (response) {
                        response.data.leadId = self.leadId();
                        ko.postbox.publish('AddedLeadsMortgageLoanMortgageLoans', response.data);
                        self.onHideAddBankForm();
                        core.loading.hideAppLoader();
                    })
                    .catch(function(response) {
                        core.loading.hideAppLoader();
                    });
            };

            self.setFinancialInstitution = function (id) {
                self.leadId(id);
            };

            self.clearInputs = function () {
                self.financialInstitutionId(undefined);
                self.financialInstitutionId.isModified(false);
                self.mortgageLoanId(undefined);
                self.mortgageLoanId.isModified(false);
                self.mortgageLoanTerms.removeAll();
                self.creditStatusId(undefined);
                self.creditStatusId.isModified(false);
                self.creditStatus.removeAll();
                self.termId(undefined);
                self.termId.isModified(false);
                self.financialTerms.removeAll();

                self.creditAmount('');
                self.creditAmount.isModified(false);
                self.propertyValue('');
                self.propertyValue.isModified(false);
                self.downPayment('');
                self.downPayment.isModified(false);
                self.monthlyPayment('');
                self.monthlyPayment.isModified(false);
                self.initialInterestRateFormatted('');
                self.initialInterestRateFormatted.isModified(false);
                self.totalAnnualCostFormatted('');
                self.totalAnnualCostFormatted.isModified(false);
            };

            self.errors = ko.validation.group(self);

            self.init = function () {
                ko.postbox.subscribe('setSidebarClient', function (payload) {
                    self.stage(payload.stage);
                });
            }();
        };

        vm.EditFinancialInstitution = function (initData) {
            var self = this;
            
            self.autorizedManagement = ko.observable(initData.autorizedManagement); self.showEditForm = ko.observable(false);
            self.leadId = ko.observable(initData.leadId);
            self.id = ko.observable(initData.id);
            self.creditAmount = ko.observable(initData.creditAmount || '').extend({ required: true });
            self.downPayment = ko.observable(initData.downPayment || '').extend({ required: true });
            self.initialInterestRateFormatted = ko.observable();
            self.initialInterestRate = ko.observable(initData.initialInterestRate * 100 || '').extend({ required: true });
            self.propertyValue = ko.observable(initData.propertyValue || '').extend({ required: true });
            self.monthlyPayment = ko.observable(initData.monthlyPayment || '').extend({ required: true });
            self.totalAnnualCost = ko.observable(initData.totalAnnualCost * 100 || '').extend({ required: true });
            self.totalAnnualCostFormatted = ko.observable();
            self.creditStatusId = ko.observable().extend({ required: true });
            self.termId = ko.observable(initData.termId || '').extend({ required: true });
            self.showEditBankErrors = ko.observable(false);
            self.customErrorMessage = ko.observable(false);

            self.creditStatus = ko.observableArray();
            self.financialTerms = ko.observableArray();

            var getCreditStatus = function () {
                axios.get(core.router().financial("mortgage-loan-status").get)
                    .then(function (response) {
                        self.creditStatus(response.data);
                        if (!self.creditStatusId()) {
                            self.creditStatusId(initData.creditStatus);
                        }
                    })
                    .catch(function () { });
            };

            var getFinancialTerms = function (mortgageLoanId) {
                if (mortgageLoanId) {

                    axios.get(core.router().financial("term").get, { params: { "parentId": mortgageLoanId } })
                        .then(function (response) {
                            self.financialTerms(response.data);
                            self.termId(initData.termId || '');
                        }).catch(function () { });
                }
            };

            self.onEdit = function () {
                getCreditStatus();
                getFinancialTerms(initData.mortgageLoanId);
                ko.postbox.publish('ShowedHidedEditForm', { id: self.id(), show: !self.showEditForm() });
            };

            self.onUpdate = function () {

                if (parseInt(self.propertyValue()) >= 0 && parseInt(self.creditAmount()) >= 0) {

                    if (parseInt(self.propertyValue()) > parseInt(self.creditAmount())) {
                        self.customErrorMessage(false);
                    }
                    else {
                        self.customErrorMessage(true);
                        return;
                    }
                }
                else {
                    self.customErrorMessage(true);
                }

                if (self.errors().length > 0) {
                    self.showEditBankErrors(true);
                    self.errors.showAllMessages();
                    return;
                }

                self.showEditBankErrors(false);

                self.initialInterestRateFormatted = ko.computed(function () {
                    return self.initialInterestRate() / 100;
                });

                self.totalAnnualCostFormatted = ko.computed(function () {
                    return self.totalAnnualCost() / 100;
                });

                var payload = {
                    'leadId': self.leadId(),
                    'mortgageLoanLeadMortgageLoanId': self.id(),
                    'creditStatus': self.creditStatusId(),
                    'creditAmount': self.creditAmount(),
                    'downPayment': self.downPayment(),
                    'initialInterestRate': self.initialInterestRateFormatted(),
                    'monthlyPayment': self.monthlyPayment(),
                    'propertyValue': self.propertyValue(),
                    'term': self.termId(),
                    'totalAnnualCost': self.totalAnnualCostFormatted(),
                    'action': 'update-data'
                };

                axios.patch(core.router().mortgageLoanLead(self.leadId()).mortgageLoans, payload )
                    .then(function (response) {
                        
                        self.showEditForm(false);
                        self.creditAmount(response.data.creditAmount);
                        self.downPayment(response.data.downPayment);
                        self.initialInterestRate(response.data.initialInterestRate * 100);
                        self.propertyValue(response.data.propertyValue);
                        self.monthlyPayment(response.data.monthlyPayment);
                        self.totalAnnualCost(response.data.totalAnnualCost * 100);
                        self.creditStatusId(response.data.creditStatus);
                        initData.termId = response.data.termId;
                        self.termId('' + response.data.termId);
                        ko.postbox.publish('UpdatedProduct', response.data);
                    })
                    .catch(function(response) {
                    });
            };

            var dialogOpts = {};

            self.deleteBank = function () {

                dialogOpts = {
                    viewModel: new vm.DeleteBankDialog(initData)
                }

                var payload = {
                    'leadId': self.leadId(),
                    'mortgageLoanLeadMortgageLoanId': self.id()
                };

                core.modals.showModal(dialogOpts)
                    .done(function (response) {
                        ko.postbox.publish('DeleteLeadsMortgageLoanMortgageLoans', payload);
                    })
                    .fail(function (response) {
                    });
            };

            self.errors = ko.validation.group(self);

        };

        vm.FinancialInstitution = function (initData) {
            var self = this;

            self.editFinancialInstitution = new vm.EditFinancialInstitution(initData);

            self.id = ko.observable(initData.id);
            self.name = ko.observable(initData.financialInstitutionName);
            self.productName = ko.observable(initData.name);
            self.status = ko.observable(initData.creditStatus);
            self.statusText = ko.observable(initData.creditStatusText);
            self.creditAmount = ko.observable(initData.creditAmount);
            self.creditAmountFormatted = ko.observable(initData.creditAmountFormatted);
            self.logoUrl = ko.observable(initData.financialInstitutionLogoUrl);
            self.isoUrl = ko.observable(initData.financialInstitutionIsoLogoUrl);

            var init = function () {
                ko.postbox.subscribe('UpdatedProduct', function (data) {
                    if (data.id === self.id()) {
                        self.creditAmountFormatted(data.creditAmountFormatted);
                        self.statusText(data.creditStatusText);
                    }
                });
            }();
        };

        vm.Summary = function () {
            var self = this;

            self.newFinancialInstitution = new vm.NewFinancialInstitution();

            self.loaded = ko.observable(false);

            self.id = ko.observable();
            self.code = ko.observable();
            self.stage = ko.observable();
            self.stageText = ko.observable();
            self.stageCategory = ko.observable();
            self.stageCategoryText = ko.observable();
            self.leadType = ko.observable();
            self.leadTypeText = ko.observable();
            self.buyPeriod = ko.observable();
            self.maxCreditAmount = ko.observable();
            self.maxCreditAmountFormatted = ko.observable();
            self.isSelected = ko.observable(false);
            self.autorizedManagement = ko.observable(false);
            self.hasCoborrower = ko.observable();
            self.detailUrl = ko.observable();
            self.customerWebAppLoginHomeUrl = ko.observable();

            self.coborrowerFirstName = ko.observable();
            self.coborrowerLastName = ko.observable();
            self.coborrowerMaidenName = ko.observable();
            self.coborrowerNin = ko.observable();
            self.coborrowerName = ko.computed(function () {
                return self.coborrowerFirstName() + ' ' +
                    self.coborrowerLastName() + ' ' +
                    self.coborrowerMaidenName();
            });
            self.coborrowerFicoScoreDays = ko.observable();
            self.coborrowerFicoScoreRating = ko.observable();
            self.coborrowerFicoScoreRatingText = ko.observable();
            self.coborrowerFicoScoreValue = ko.observable();
            self.coborrowerFicoExpired = ko.observable(false);
            self.coborrowerAllowFicoEvaluation = ko.observable(false);

            self.financialInstitutions = ko.observableArray();

            self.checkFicoExpiration = function () {

                if (self.autorizedManagement()) {
                    if (self.coborrowerFicoScoreDays() >= 31 || self.coborrowerFicoScoreRating() === 'NotAvailable') {
                        self.coborrowerFicoExpired(true);
                        self.coborrowerAllowFicoEvaluation(true);
                    } else {
                        self.coborrowerFicoExpired(false);
                        self.coborrowerAllowFicoEvaluation(false);
                    }
                } else {
                    if (self.coborrowerFicoScoreDays() >= 31 || self.coborrowerFicoScoreRating() === 'NotAvailable') {
                        self.coborrowerFicoExpired(true);
                        self.coborrowerAllowFicoEvaluation(false);
                    } else {
                        self.coborrowerFicoExpired(false);
                        self.coborrowerAllowFicoEvaluation(false);
                    }
                }
            };

            ko.postbox.subscribe('setSidebarClient', function (payload) {
                self.autorizedManagement(payload.autorizedManagement);
            });

            // enable, disable the red of to evaluate fico
            self.enabledCoborrowerFicoEvaluate = ko.computed(function () {
                if (((self.stage() === 'Prequalification' && (self.stageCategory() === 'MyCredit' || self.stageCategory() === 'Selection')) || (self.stage() !== 'Prequalification')) && (self.coborrowerFicoScoreDays() >= 31 || self.coborrowerFicoScoreRating() === 'NotAvailable')) {
                    return true;
                } else {
                    return false;
                }
            });

            self.setSummary = function (mortgageLoanId) {
                if (self.loaded()) return;
                self.newFinancialInstitution.clearInputs();

                axios.get(core.router().mortgageLoanLead(mortgageLoanId).get,
                    { params: { view: 'sidebar-item' } })
                    .then(function (response) {
                        var data = response.data;
                        self.loaded(true);

                        self.id(data.id);
                        self.code(data.code);
                        self.stage(data.stage);
                        self.stageText(data.stageText);
                        self.stageCategory(data.stageCategory);
                        self.stageCategoryText(data.stageCategoryText);
                        self.leadType(data.leadType);
                        self.leadTypeText(data.leadTypeText);
                        self.buyPeriod(data.buyPeriod);
                        self.maxCreditAmount(data.maxCreditAmount);
                        self.maxCreditAmountFormatted(data.maxCreditAmountFormatted);

                        self.hasCoborrower(data.coBorrower.hasCoborrower);
                        self.detailUrl(data.detailUrl);
                        self.customerWebAppLoginHomeUrl(data.customerWebAppLoginHomeUrl);
                        if (self.hasCoborrower()) {
                            self.coborrowerFirstName(data.coBorrower.firstName || '');
                            self.coborrowerLastName(data.coBorrower.lastName || '');
                            self.coborrowerMaidenName(data.coBorrower.maidenName || '');
                            self.coborrowerNin(data.coBorrower.nin || '');

                            self.coborrowerFicoScoreDays(data.coBorrower.ficoScore.days);
                            self.coborrowerFicoScoreRating(data.coBorrower.ficoScore.rating);
                            self.coborrowerFicoScoreRatingText(data.coBorrower.ficoScore.ratingText);
                            self.coborrowerFicoScoreValue(data.coBorrower.ficoScore.value);

                            self.checkFicoExpiration();
                        }

                        var result = [];

                        var existIsSelected = ko.utils.arrayFirst(data.mortgageLoans, function (item) {
                            return item.isSelected === true;
                        });

                        if (existIsSelected) {
                            //La siguiente línea consulta si el usuario ya ha seleccionado un banco, que ya no se pueda agregar banco.
                            self.isSelected(true);
                            ko.utils.arrayForEach(data.mortgageLoans, function (item) {
                                if (item.isSelected) {
                                    item.leadId = self.id();
                                    item.autorizedManagement = self.autorizedManagement();
                                    result.push(new vm.FinancialInstitution(item));
                                }
                            });
                        } else {
                            //La siguiente línea consulta si el usuario ya ha seleccionado un banco, que ya no se pueda agregar banco.
                            self.isSelected(false);
                            ko.utils.arrayForEach(data.mortgageLoans, function (item) {
                                item.leadId = self.id();
                                item.autorizedManagement = self.autorizedManagement();
                                result.push(new vm.FinancialInstitution(item));
                            });
                        }
                        self.financialInstitutions(result);
                        self.newFinancialInstitution.setFinancialInstitution(data.id);
                        if (self.newFinancialInstitution.showAddBankForm()) {
                            self.newFinancialInstitution.showAddBankForm(false);
                            self.newFinancialInstitution.onShowAddBankButton(true);
                        }

                    })
                    .catch(function (error) {

                    });

             
            };

            self.showEvaluateFicoDialog = function (leadId) {

                var dialogOpts = {};

                dialogOpts = {
                    viewModel: new vm.EvaluateFicoDialog(leadId.id())
                }

                core.modals.showModal(dialogOpts);

            };

            self.onEditCoborrower = function () {
                axios.get(core.router().mortgageLoanLead(self.id()).coborrower)
                    .then(function (response) {
                        response.data.id = self.id();
                        var dialogOpts = {};
                        dialogOpts = { viewModel: new vm.EditCoborrowerDialog(response.data) }
                        core.modals.showModal(dialogOpts);
                    })
                    .catch(function(response) {});
            };

            self.init = function () {
                ko.postbox.subscribe('AddedLeadsMortgageLoanMortgageLoans', function (newLeadsMortgageLoanMortgageLoans) {
                    newLeadsMortgageLoanMortgageLoans.autorizedManagement = self.autorizedManagement();
                    self.financialInstitutions.push(new vm.FinancialInstitution(newLeadsMortgageLoanMortgageLoans));
                });

                ko.postbox.subscribe('DeleteLeadsMortgageLoanMortgageLoans', function (response) {
                    self.financialInstitutions.remove(function (item) {
                        return item.id() === response.mortgageLoanLeadMortgageLoanId;
                    });
                });

                ko.postbox.subscribe('ShowedHidedEditForm', function (data) {

                    var verifyShowItem = ko.utils.arrayFirst(self.financialInstitutions(), function (item) {
                        return item.editFinancialInstitution.showEditForm() === true;
                    });

                    if (verifyShowItem) {
                        verifyShowItem.editFinancialInstitution.showEditForm(false);
                    }

                    var showItem = ko.utils.arrayFirst(self.financialInstitutions(), function (item) {
                        return item.id() === data.id;
                    });

                    if (showItem) {
                        showItem.editFinancialInstitution.showEditForm(data.show);
                    }
                });

                ko.postbox.subscribe('UpdatedMortgageLoanMortgageLoans', function (item) {

                    if (item) {
                        item.isSelected = true;
                        self.isSelected(item.isSelected);
                        item.leadId = self.id();
                        self.financialInstitutions(new vm.FinancialInstitution(item));

                    } else {
                        //La siguiente línea consulta si el usuario ya ha seleccionado un banco, que ya no se pueda agregar banco.
                        item.isSelected = false;
                        item.leadId = self.id();
                        self.financialInstitutions(new vm.FinancialInstitution(item));
                    }
                });

                ko.postbox.subscribe('currentCoborrowerData', function (data) {
                    self.coborrowerFirstName(data.firstName).coborrowerLastName(data.lastName).coborrowerMaidenName(data.maidenName).coborrowerNin(data.nin);
                });

                //For coborrower
                ko.postbox.subscribe('updatedCoborrowerFicoScore', function (response) {

                    if (response.rating !== 'NotAvailable') {

                        self.coborrowerFicoScoreValue(response.value);
                        self.coborrowerFicoScoreRating(response.rating);
                        self.coborrowerFicoScoreRatingText(response.ratingText);
                        self.coborrowerFicoExpired(false);
                        self.coborrowerFicoScoreDays(response.days);
                    }

                });

                ko.postbox.subscribe('UpdatedCoborrowerPersonalInformation', function (data) {
                    self.coborrowerFirstName(data.firstName).coborrowerLastName(data.lastName).coborrowerMaidenName(data.maidenName).coborrowerNin(data.nin);
                });

            }();
        };

        vm.Notes = function () {
            var self = this;

            self.loaded = ko.observable(false);

            self.id = ko.observable();
            self.note = ko.observable();
            self.autorizedManagement = ko.observable(false);

            self.notes = ko.observableArray();

            self.onAddNote = function () {

                axios.post(core.router().mortgageLoanLead(self.id()).notes, { comment: self.note() })
                    .then(function (response) {
                        self.note('');
                        self.notes.unshift(response.data);
                    })
                    .catch(function (error) { });
            };

            self.setNotes = function (mortgageLoanId) {
                axios.get(core.router().mortgageLoanLead(mortgageLoanId).notes)
                    .then(function (response) {
                        if (self.loaded()) return;
                        self.id(mortgageLoanId);
                        self.loaded(true);
                        self.notes(response.data);
                    })
                    .catch(function (error) { });
            };

            ko.postbox.subscribe('setSidebarClient', function (payload) {
                self.autorizedManagement(payload.autorizedManagement);
            });

            ko.postbox.subscribe('LeadNoteAdded', function (response) {
                if (self.id() === response.leadId) {
                    self.notes.unshift(response);
                }
            });
        };

        vm.PipelineItem = function (initData) {
            var self = this;

            var oldMonths = initData.remainingMonthsToBuy;
            self.autorizedManagement = ko.observable(initData.autorizedManagement);
            self.id = ko.observable(initData.id);
            self.code = ko.observable(initData.code);
            self.origin = ko.observable(initData.origin);
            self.type = ko.observable(initData.type);
            self.stage = ko.observable(initData.stage);
            self.stageDays = ko.observable(initData.stageDays);
            self.amount = ko.observable(initData.approvalAmount ? initData.approvalAmount : initData.creditAmount);
            self.formattedAmount = ko.observable(initData.formattedAmount);
            self.contactData = ko.observable(initData.contactOptionText);
            self.filesToReviewCount = ko.observable(initData.filesToReviewCount);
            self.noteCount = ko.observable(initData.noteCount);
            self.remainingMonthsToBuy = ko.observable(initData.remainingMonthsToBuy);
            self.approvedCredit = ko.observable(initData.approvedCredit);
            self.isPropertyFound = ko.observable(initData.isPropertyFound);

            self.clientId = ko.observable(initData.client.id);
            self.name = ko.observable(initData.client.name);

            self.creditScore = ko.observable(initData.ficoScore.value);
            self.creditScoreRatingText = ko.observable(initData.ficoScore.ratingText);

            self.financialInstitutions = ko.observableArray(initData.financialInstitutions);

            self.creditScoreCss = ko.pureComputed(function () {
                return utils.lead.getCreditScoreDecoratorClass(self.creditScore());
            });

            self.urgencyCss = ko.computed(function () {
                return utils.lead.getBootstrapSelectUrgencyClass(self.remainingMonthsToBuy());
            });
            var genericOnject = {};
            self.setNewRemainingMonthsToBuy = function (val) {
                genericOnject = val; //tiene que ser un objeto
                if (!genericOnject.val) { console.error("Required New Value"); return; }
                if (Number.parseFloat(genericOnject.val) === self.remainingMonthsToBuy()) {
                    if (genericOnject.callback) {
                        genericOnject.callback({
                            'name': self.name(),
                            'status': 'success',
                            'id': self.id()
                        });
                    }
                } else {
                    self.remainingMonthsToBuy(Number.parseFloat(genericOnject.val));
                }
            };
            self.updateTimeToBuyNewValue = function (value) {
                var months = value - oldMonths;
                if (months === 0) {
                    if (genericOnject.callback) {
                        genericOnject.callback({
                            'name': self.name(),
                            'status': 'success',
                            'id': self.id()
                        });
                    }
                    return;
                }
                var payload = {
                    id: self.id(),
                    months: months
                }
                axios.put(core.router().mortgageLoanLead(self.id()).estimatedBuyDate, payload)
                    .then(function (response) {
                        oldMonths = value;
                        if (genericOnject.callback) {
                            genericOnject.callback({
                                'name': self.name(),
                                'status': 'success',
                                'id': self.id()
                            });
                        }
                    })
                    .catch(function (response) {
                        if (genericOnject.callback) {
                            genericOnject.callback({
                                'name': self.name(),
                                'status': 'fail',
                                'id': self.id()
                            });
                        }
                    });
            };

            self.remainingMonthsToBuy.subscribe(function (value) {
                self.updateTimeToBuyNewValue(value);
            });
            self.isChecked = ko.observable();

            self.loadFinancialInstitutions = function (institutions) {
                var financials = [];
                //console.log(institutions, "Carga institutions");
                var isSelected = ko.utils.arrayFirst(institutions, function (item) {
                    return item.isSelected === true;
                });

                if (isSelected) {
                    ko.utils.arrayForEach(self.financialInstitutions(), function (item) {
                        //console.log(item);
                        if (item.isSelected === true) {
                            var result = {
                                name: item.name,
                                status: item.status,
                                imageName: utils.financialInstitution.getImageName(item.code, item.isSelected === true),
                                mortgageLoanLeadMortgageLoanId: item.id
                            }
                            financials.push(result);
                        }
                    });
                } else {
                    ko.utils.arrayForEach(self.financialInstitutions(), function (item) {
                        //console.log(item);
                        var result = {
                            name: item.name,
                            status: item.status,
                            imageName: utils.financialInstitution.getImageName(item.code, item.isSelected === true),
                            mortgageLoanLeadMortgageLoanId: item.id
                        }
                        financials.push(result);
                    });
                }
                self.financialInstitutions(financials);
            };

            self.onMoveStageClosed = function () {
                var dialogOptions = {
                    viewModel: new vm.MoveToStageDialog(self.id(), self.stage(), 'Closed')
                };

                core.modals.showModal(dialogOptions)
                    .done(function (response) {
                        ko.postbox.publish('changeOfStepClosed', { stage: self.stage(), code: self.code() });
                    })
                    .fail(function () {

                    });
            };

            self.onMoveStageLost = function () {
                var dataPayload = {
                    leadIds: [self.id()],
                    stage: self.stage()
                };
                core.loading.showAppLoader();
                axios.get(core.router().leadLookups('stage-category').lookups,
                    {
                        params: { parentId: enums.stage.Lost }
                    })
                    .then(function (response) {
                        core.loading.hideAppLoader();
                        dataPayload.stageCategorys = response.data;
                        var dialogOptions = {
                            viewModel: new vm.MoveToLostDialog(dataPayload)
                        };
                        core.modals.showModal(dialogOptions)
                            .done(function (responseDialog) {
                                if (responseDialog.fail.length > 0) {
                                    var optionsInitData = {
                                        actionText: 'Notificar',
                                        items: [{ name: self.name() }]
                                    };
                                    var dialogOption = {
                                        viewModel: new vm.BulkActionErrorDialog(optionsInitData)
                                    };
                                    core.modals.showModal(dialogOption);
                                } else {
                                    ko.postbox.publish('ChangeOfStepLost', dataPayload);
                                }
                            });
                    })
                    .catch(function (error) {
                        core.loading.hideAppLoader();
                    });
            };

            self.onEdit = function () {

                core.loading.showAppLoader();
                axios.get(core.router().client(self.clientId()).get, {
                    params: { view: 'sidebar' }
                })
                    .then(function (response) {
                        core.loading.hideAppLoader();
                        var optionsDialog = { viewModel: new vmClient.EditClientDialog(response.data) };

                        core.modals.showModal(optionsDialog)
                            .done(function (response) {
                                var name = response.firstName + ' ' + response.lastName + ' ' + response.maidenName;
                                self.name(name);
                            })
                            .fail();
                    })
                    .catch(function (error) {
                        core.loading.hideAppLoader();
                    });
            };

            var init = function () {
                self.loadFinancialInstitutions(initData.financialInstitutions);
            }();
        };

        vm.PipelineColumn = function (initData, pipeline) {
            var self = this;
            self.id = ko.observable(initData.id);
            self.name = ko.observable(initData.name);

            self.autorizedManagement = ko.observable(initData.autorizedManagement);
            self.items = ko.observableArray();

            self.columnAmount = ko.pureComputed(function () {
                if (self.items().length <= 0) return 0;

                var result = self.items().reduce((a, b) => ({ amount: a.amount + b.amount() }), { amount: 0 });
                return result.amount;
            });

            // Droppable

            self.canDrop = ko.computed(function () {
                if (!self.autorizedManagement()) return false;

                var activeDragItem = pipeline.activeDragItem();

                var isChild = ko.utils.arrayFirst(self.items(),
                    function (item) {
                        if (activeDragItem) {
                            return activeDragItem.id() === item.id();
                        }
                        return false;
                    });

                var canDrop = true;
                if (activeDragItem) {
                    canDrop = pipeline.canDropFromStage(activeDragItem.stage(), self.id());
                }

                return !isChild && canDrop;
            });

            //self.deleteItem = function (code) {
            //    self.items.remove(function (item) {
            //        return item.code() === code;
            //    });
            //};

            self.setItems = function () {
                ko.utils.arrayForEach(initData.items, function (item) {
                    self.items.push(new vm.PipelineItem(item));
                });
            };

            var init = function () {
                self.setItems();
            }();
        };

        vm.Pipeline = function () {
            var self = this;

            self.elementDragged = {};
            self.isDragging = ko.observable(false);
            self.pipelineColumns = ko.observableArray();

            self.setColumns = function (items) {
                var result = [];
                ko.utils.arrayForEach(items,
                    function (item) {
                        result.push(new vm.PipelineColumn(item, self));
                    });

                self.pipelineColumns(result);
            }

            var dialogOpts = {};
            self.processStageTransition = function (toPipelineColumn, lead) {
                var toStageId = toPipelineColumn.id();

                var fromPipelineColumn = ko.utils.arrayFirst(self.pipelineColumns(),
                    function (item) {
                        return item.id() === lead.stage();
                    });
                var fromStageId = fromPipelineColumn.id();

                var itemSelected = ko.utils.arrayFirst(fromPipelineColumn.items(), function (item) {
                    return item.code() === lead.code();
                });
                //console.log(itemSelected, 'itemSelected');
                dialogOpts = {
                    viewModel: new vm.MoveToStageDialog(lead.id(), fromStageId, toStageId)
                }

                core.modals.showModal(dialogOpts)
                    .done(function (response) {
                        var toColumnStage = ko.utils.arrayFirst(self.pipelineColumns(), function (item) {
                            return item.id() === toStageId;
                        });

                        toColumnStage.items.push(new vm.PipelineItem(response));
                        var elementRemoved = fromPipelineColumn.items.remove(function (item) {
                            return item.code() === lead.code();
                        });
                    })
                    .fail(function () {
                        self.elementDragged.helper.css({
                            'left': self.elementDragged.originalPosition.left,
                            'top': self.elementDragged.originalPosition.top
                        });
                    });
            };

            self.setSidebar = function (pipelineItem) {
                var payload = {
                    autorizedManagement: pipelineItem.autorizedManagement(),
                    clientId: pipelineItem.clientId(),
                    leadId: pipelineItem.id(),
                    type: 'mortgage-loan-summary',
                    stage: pipelineItem.stage(),
                    code: pipelineItem.code()
                };
                if (self.isDragging()) return;
                ko.postbox.publish('setSidebarClient', payload);
            };

            // Droppable

            self.activeDragItem = ko.observable();

            self.setActiveDragItem = function (item, e, ui) {
                self.isDragging(true);
                self.elementDragged = ui;
                self.activeDragItem(item);
            }
            self.stopDrag = function (item, e, ui) {
                setTimeout(function () {
                    self.isDragging(false);
                }, 0);
            };
            self.canDropFromStage = function (fromStageId, toStageId) {

                if (fromStageId === 'Signature') return false;
                if (toStageId === 'CreditIntegration') return false;
                if (fromStageId === 'GuarantyIntegration') {
                    if (toStageId === 'CreditAnalysis') return false;
                }
                if (fromStageId === 'GuarantyAnalysis') {
                    if (toStageId === 'CreditAnalysis') return false;
                    if (toStageId === 'GuarantyIntegration') return false;
                }

                return true;
            };
        };

        vm.ListViewRow = function (initData, row) {
            var self = this;
            //variables

            var oldMonths = initData.remainingMonthsToBuy;
            //observables
            self.id = ko.observable(initData.id);
            self.autorizedManagement = ko.observable(initData.autorizedManagement);
            self.clientId = ko.observable(initData.client.id);
            self.code = ko.observable(initData.code);
            self.name = ko.observable(initData.client.name);
            self.email = ko.observable(initData.client.email);
            self.mobileNumber = ko.observable(initData.client.mobileNumber);
            self.creditScore = ko.observable(initData.ficoScore.value);//ficoScoreValue
            self.ratingClass = ko.observable();
            self.formattedAmount = ko.observable(initData.formattedAmount);
            self.approvedCredit = ko.observable(initData.approvedCredit);
            self.maximumAmount = ko.observable(initData.maxCreditAmountFormatted);
            self.maxCreditAmountFormatted = ko.observable(initData.maxCreditAmountFormatted);
            self.orign = ko.observable(initData.origin);
            self.stage = ko.observable(initData.stage);
            self.numberStage = ko.observable();
            self.stageText = ko.observable(initData.stageText);
            self.stageDateText = ko.observable(initData.stageDateText);
            self.lastStage = ko.observable(initData.lastStage);
            self.lastStageText = ko.observable(initData.lastStageText === 'Selección' ? 'Precalificación' : initData.lastStageText);
            self.stageCategory = ko.observable(initData.stageCategory);
            self.stageCategoryText = ko.observable(initData.stageCategoryText);
            self.stageAmount = ko.observable(initData.stageAmount);
            self.leadType = ko.observable(initData.type);
            self.isPropertyFound = ko.observable(initData.isPropertyFound);
            self.remainingMonthsToBuy = ko.observable(initData.remainingMonthsToBuy);
            self.creditIntegrationDateText = ko.observable(initData.creditIntegrationDateText);
            self.createdDateText = ko.observable(initData.createdDateText);
            self.closeDateText = ko.observable(initData.closedDateDateText);
            self.isChecked = ko.observable();
            self.hasErrorActionBulKAction = ko.observable(false);
            self.reasonError = ko.observable('');
            // self.isSuccessUpdateTime = ko.observable(false);

            //arrays
            self.financialInstitutions = ko.observableArray(initData.financialInstitutions);
            self.logos = ko.observableArray();
            self.items = ko.observableArray();

            //computeds
            self.urgencyCss = ko.computed(function () {
                var classColor = utils.lead.getUrgencyClass(self.remainingMonthsToBuy());
                return 'c-urgency-dropdown--' + classColor;
            });

            self.propertyClasses = ko.computed(function () {
                var classes = "";
                if (self.leadType() === 'New' && self.isPropertyFound()) {
                    classes = 'cm-house c-credit-property-found';
                }
                if (self.leadType() === 'New' && !self.isPropertyFound()) {
                    classes = 'cm-house c-credit-property-not-found';
                }
                if (self.leadType() === 'Refinance') {
                    classes = 'cm-exchange';
                }
                return classes;
            });

            self.rowAmount = ko.pureComputed(function () {
                if (self.items().length <= 0) return 0;

                var result = self.items().reduce((a, b) => ({ amount: a.amount + b.amount }), { amount: 0 });
                return result.amount;
            });

            self.remainingMonthsToBuy.subscribe(function (val) {
                self.updateTimeToBuyNewValue(val);
            });

            //functions
            var stagesCompleted = function () {
                if (self.stage() === enums.stage.CreditIntegration || self.stageCategory() === enums.prequalifierStages.PersonalInformation) {
                    self.numberStage(1);
                }
                if (self.stage() === enums.stage.CreditAnalysis || self.stageCategory() === enums.prequalifierStages.EmploymentAndIncome) {
                    self.numberStage(2);
                }
                if (self.stage() === enums.stage.GuarantyIntegration || self.stageCategory() === enums.prequalifierStages.CreditAnalysis) {
                    self.numberStage(3);
                }
                if (self.stage() === enums.stage.GuarantyAnalysis || self.stageCategory() === enums.prequalifierStages.MyCredit) {
                    self.numberStage(4);
                }
                if (self.stage() === enums.stage.Signature || self.stageCategory() === enums.prequalifierStages.Selection) {
                    self.numberStage(5);
                }
            }();

            self.loadFinancialInstitutions = function (institutions) {
                var financials = [];
                var isSelected = ko.utils.arrayFirst(institutions, function (item) {
                    return item.isSelected === true;
                });

                if (isSelected) {
                    ko.utils.arrayForEach(self.financialInstitutions(), function (item) {
                        if (item.isSelected === true) {
                            var result = {
                                name: item.name,
                                status: item.status,
                                imageName: utils.financialInstitution.getImageName(item.code, item.isSelected === true),
                                mortgageLoanLeadMortgageLoanId: item.id,
                                logoUrl: item.logoUrl
                            }
                            financials.push(result);
                        }
                    });
                } else {
                    ko.utils.arrayForEach(self.financialInstitutions(), function (item) {
                        var result = {
                            name: item.name,
                            status: item.status,
                            imageName: utils.financialInstitution.getImageName(item.code, item.isSelected === true),
                            mortgageLoanLeadMortgageLoanId: item.id,
                            logoUrl: item.isoLogoUrl
                        }
                        financials.push(result);
                    });
                }
                self.financialInstitutions(financials);
            };

            self.scoreRating = function () {
                var scoreScope = core.ficoscoreScope(self.creditScore());
                switch (scoreScope) {
                    case "Excellent":
                        {
                            self.ratingClass("c-credit-score-label--excellent");
                            break;
                        }
                    case "VeryGood":
                        {
                            self.ratingClass("c-credit-score-label--very-good");
                            break;
                        }
                    case "Good":
                        {
                            self.ratingClass("c-credit-score-label--good");
                            break;
                        }
                    case "Regular":
                        {
                            self.ratingClass("c-credit-score-label--regular");
                            break;
                        }
                    case "Low":
                        {
                            self.ratingClass("c-credit-score-label--low");
                            break;
                        }
                    case "VeryLow":
                        {
                            self.ratingClass("c-credit-score-label--very-low");
                            break;
                        }
                    default:
                        {
                            self.ratingClass("c-credit-score-label--very-low");
                            break;
                        }
                }
            };

            self.onMoveStageClosed = function () {
                var dialogOptions = {
                    viewModel: new vm.MoveToStageDialog(self.id(), self.stage(), 'Closed')
                };

                core.modals.showModal(dialogOptions)
                    .done(function (response) {
                        ko.postbox.publish('changeOfStepClosed', { id: self.id(), stage: self.stage(), code: self.code() });

                    })
                    .fail(function () {

                    });
            };

            self.onMoveStageLost = function () {
                var dataPayload = {
                    leadIds: [self.id()],
                    code: self.code(),
                    stage: self.stage()
                };

                core.loading.showAppLoader();
                axios.get(core.router().leadLookups('stage-category').lookups, {
                    params: { parentId: enums.stage.Lost }
                })
                    .then(function (response) {
                        core.loading.hideAppLoader();
                        dataPayload.stageCategorys = response.data;
                        var dialogOptions = {
                            viewModel: new vm.MoveToLostDialog(dataPayload)
                        };
                        core.modals.showModal(dialogOptions)
                            .done(function (responseDialog) {
                                if (responseDialog.fail.length > 0) {
                                    var optionsInitData = {
                                        actionText: 'Notificar',
                                        items: [{ name: self.name() }]
                                    };
                                    var dialogOption = {
                                        viewModel: new vm.BulkActionErrorDialog(optionsInitData)
                                    };
                                    core.modals.showModal(dialogOption);
                                } else {
                                    ko.postbox.publish('ChangeOfStepLost', dataPayload);
                                }
                            });
                    })
                    .catch(function (error) {
                        core.loading.hideAppLoader();
                    });
            };

            self.onRecoveryLead = function() {
                var dialogLostOptions = { viewModel: new vm.ReactivateLeadsDialog({ 'leads': [self.id()] }) };
                core.modals.showModal(dialogLostOptions)
                   .done(function (responseDialog) {
                        ko.postbox.publish("RecoveredLead", responseDialog);
                    })
                   .fail(function (response) {
                   });
            };

            self.onEdit = function () {
                axios.get(core.router().client(self.clientId()).get, { params: { view: 'sidebar' } })
                    .then(function (responseClient) {
                    var optionsDialog = {
                            viewModel: new vmClient.EditClientDialog(responseClient.data)
                    };
                    core.modals.showModal(optionsDialog)
                        .done(function (response) {
                            var name = response.firstName + ' ' + response.lastName + ' ' + response.maidenName;
                            self.name(name);
                    });
                    });
            };

            var genericOnject = {};
            self.setNewRemainingMonthsToBuy = function (val) {
                genericOnject = val; //tiene que ser un objeto
                if (!genericOnject.val) { console.error("Required New Value"); return; }
                if (Number.parseFloat(genericOnject.val) === self.remainingMonthsToBuy()) {
                    if (genericOnject.callback) {
                        genericOnject.callback({
                            'name': self.name(),
                            'status': 'success',
                            'id': self.id()
                        });
                    }
                } else {
                    self.remainingMonthsToBuy(Number.parseFloat(genericOnject.val));
                }
            };
            self.updateTimeToBuyNewValue = function (value) {
                var months = value - oldMonths;
                if (months === 0) {
                    if (genericOnject.callback) {
                        genericOnject.callback({
                            'name': self.name(),
                            'status': 'success',
                            'id': self.id()
                        });
                    }
                    return;
                }
                var payload = {
                    id: self.id(),
                    months: months
                }
                axios.put(core.router().mortgageLoanLead(self.id()).estimatedBuyDate, payload)
                    .then(function (response) {
                        oldMonths = value;
                        if (genericOnject.callback) {
                            genericOnject.callback({
                                'name': self.name(),
                                'status': 'success',
                                'id': self.id()
                            });
                        }
                    })
                    .catch(function (error) {
                        if (genericOnject.callback) {
                            genericOnject.callback({
                                'name': self.name(),
                                'status': 'fail',
                                'id': self.id()
                            });
                        }
                    });
            };

            var init = function () {
                self.scoreRating();
                self.loadFinancialInstitutions(initData.financialInstitutions);
            }();
        };

        vm.ListView = function () {
            var self = this;

            self.listRow = ko.observableArray();

            self.setRows = function (items) {
                var result = [];
                ko.utils.arrayForEach(items, function (item) {
                    result.push(new vm.ListViewRow(item, self));
                });

                self.listRow(result);
            }

            self.setSidebar = function (rowItem) {

                var payload = {
                    autorizedManagement: rowItem.autorizedManagement(),
                    clientId: rowItem.clientId(),
                    leadId: rowItem.id(),
                    type: 'mortgage-loan-summary',
                    code: rowItem.code(),
                    stage: rowItem.stage(),
                    stageCategory: rowItem.stageCategory()

                };

                ko.postbox.publish('setSidebarClient', payload);
            };
        };

        /// TODO: refactor group filter to generic viewmodel
        vm.Search = function (initData) {
            var self = this;
            //variables
            var searchTimeout;
            var payload;
            if (core.localStorage.getData('leadStatusFilter')) {
                initData.leadStatus = core.localStorage.getDataJsonParse('leadStatusFilter').leadStatus;
                if (initData.leadStatus === 'prequalification' || initData.leadStatus === 'closed' || initData.leadStatus === 'lost') initData.view = 'list';
                if (initData.leadStatus === 'inProcess') initData.view = 'pipeline';

            } else {
                initData.view = 'pipeline';
                initData.leadStatus = 'inProcess';
            }

            //observables
            self.notarySignatureDate = ko.observable();
            self.leadStatus = ko.observable(initData.leadStatus);
            self.leadStatusText = ko.observable("En proceso");
            self.notarySignatureDate = ko.observable();
            self.view = ko.observable(initData.view);
            self.orderBy = ko.observable('modified-desc');
            self.totalAmount = ko.observable(0);
            self.isSearchInProcess = ko.observable(false);
            //arrays
            self.itemsPipeline = ko.observableArray();
            self.itemsList = ko.observableArray();
            self.selectedIds = ko.observableArray();
            self.selectedItems = ko.observableArray();
            //computeds
            self.totalItemsText = ko.pureComputed(function () {
                var totalItemsText = !self.totalItems() ? " No hay resultados"
                    : self.totalItems() > 1 ? self.totalItems() + " Resultados" : self.totalItems() + " Resultado";
                return totalItemsText;
            });

            //instances
            self.pipeline = new vm.Pipeline();
            self.list = new vm.ListView();

            //applys
            common.Pager.apply(self, [{}]);
            common.GroupsFilter.apply(self, [initData.filterGroups]);
            ko.utils.arrayForEach(self.groups(), function (group, index) {
                if (group.id() === 'origins') {
                    if (group.items().length > 1) {
                        group.enabled(true);
                    } else {
                        group.enabled(false);
                    }

                }
            }); //hide orign menu in sponsor user

            //functions
            var selectView = function (data) {
                self.selectedIds.removeAll();
                if (self.view() === 'pipeline') {

                    var totalAmount = 0;
                    self.itemsPipeline(data.items);
                    ko.utils.arrayForEach(self.itemsPipeline(), function (item) {
                        var result = item.items.reduce((a, b) => ({ stageAmount: a.stageAmount + b.stageAmount }), { stageAmount: 0 });
                        totalAmount += result.stageAmount;
                    });
                    self.totalItems(data.totalItems);
                    self.totalAmount(totalAmount);
                    self.pipeline.setColumns(self.itemsPipeline());

                }
                if (self.view() === 'list') {

                    self.pageCount(data.pageCount);
                    self.totalItems(data.totalItems);
                    self.itemsList(data.items);
                    self.setItems();

                    var totalAmountList = 0;
                    self.list.setRows(self.itemsList());

                    self.totalItems(data.totalItems);

                    ko.utils.arrayForEach(self.itemsList(), function (item) {
                        totalAmountList += item.stageAmount;
                    });
                    self.totalAmount(totalAmountList);

                }
            };

            var getPayload = function () {
                var sortOptions = self.orderBy().split('-');

                payload = {
                    view: self.view(),
                    pageNumber: self.pageNumber(),
                    sortColumn: sortOptions[0],
                    sortAscending: sortOptions[1] === 'asc' ? true : false
                };

                switch (self.leadStatus()) {
                    case 'prequalification':
                        {
                            self.view('list');
                            payload.view = self.view();
                            payload.stages = 'prequalification';
                            break;
                        }
                    case 'closed':
                        {
                            self.view('list');
                            payload.view = self.view();
                            payload.stages = 'closed';
                            break;
                        }
                    case 'lost':
                        {

                            self.view("list");
                            payload.stages = 'lost';
                            payload.view = 'with-last-stage';
                            payload.pageSize = self.pageSize();
                            break;
                        }
                    case 'inProcess':
                        {
                            payload.pageNumber = 0;

                            if (self.view() === 'list') {
                                payload.pageNumber = self.pageNumber();
                                payload.pageSize = self.pageSize();
                            }
                            payload.stages = 'CreditIntegration,CreditAnalysis,GuarantyIntegration,GuarantyAnalysis,Signature';
                            payload.view = self.view();
                            break;
                        }

                    default:
                        {
                            payload.stages = 'CreditIntegration,CreditAnalysis,GuarantyIntegration,GuarantyAnalysis,Signature';
                        }
                }
                var selectionItems = {};
                ko.utils.objectForEach(self.getSelection(), function (key, value) {
                    if (key === 'stageCategoriesLost') selectionItems['stageCategories'] = value;
                    else selectionItems[key] = value;
                });
                
                ko.utils.objectForEach(selectionItems, function (key, value) {
                    if (Array.isArray(selectionItems[key])) {
                        selectionItems[key] = selectionItems[key] = selectionItems[key] = value.join();
                    }
                });
                ko.utils.extend(payload, selectionItems);

                if (self.view() === 'list') payload.pageSize = self.pageSize();
                return payload;
            };

            var search = function () {
                var payload = getPayload();
                core.loading.showAppLoader();

                axios.get(core.router().mortgageLoanLead().search, //"/api/v2/leads/mortgage-loan/search",
                    {
                        params: payload
                    }).then(function (response) {
                        selectView(response.data);
                        self.isSearchInProcess(false);
                        core.loading.hideAppLoader();
                    })
                    .catch(function (error) {
                        self.isSearchInProcess(false);
                        core.loading.hideAppLoader();
                    });

                //data.search(payload)
                //    .done(function (response) {

                //        selectView(response);
                //        self.isSearchInProcess(false);
                //        core.loading.hideAppLoader();

                //    }).fail(function (response) {
                //        self.isSearchInProcess(false);
                //        core.loading.hideAppLoader();

                //    });
            };

            self.addCheckedItem = function (event) {
                console.log(event);
            };

            self.onAddNotes = function () {
                var dialogOpts = { viewModel: new vm.AddNoteToLeadsDialog({ leadDtos: self.selectedItems() }) };
                core.modals.showModal(dialogOpts);
            };

            self.onAddCredit = function () {
                self.selectedIds.push('16002701');
            };

            var itemsUpdated = 0;
            var lengthUpdatedTimeToBuy = 0;
            var successUpdatedTimeToBuy = [];
            var failUpdatedTimeToBuy = [];

            var saveLeadStatusLocalStorage = function (val) {
                core.localStorage.save('leadStatusFilter', { 'leadStatus': val });
            };
            var saveGroupFiltersLocalStorage = function (jsonFilters) {
                core.localStorage.save('groupfilters', jsonFilters);
            };

            self.onRecoverLeadsDialog = function () {
                
                //var dialogLostOptions = { viewModel: new vm.ReactivateLeadsDialog({ 'leads': self.selectedIds() }) };
                //core.modals.showModal(dialogLostOptions)
                //    .done(function (responseDialog) {

                //        if (responseDialog.fail.length > 0) {
                //            var localArray = [];
                //            if (self.view() === 'list') {
                //                ko.utils.arrayForEach(responseDialog.fail, function (item) {
                //                    ko.utils.arrayForEach(self.list.listRow(), function (listItem) {
                //                        if (item.leadId === listItem.id()) {
                                            
                //                            listItem.hasErrorActionBulKAction(true);
                //                            listItem.reasonError(item.reasonError);
                //                        }
                //                    });
                //                });
                //            }
                //        }
                //        if (responseDialog.success.length > 0) {
                //            core.snackbar.show({
                //                text: responseDialog.success.length == 1 ? "1 crédito recuperado con éxito" : responseDialog.success.length + " créditos recuperados con éxito"
                //            });
                //            if (self.view() === 'list') {
                //                ko.utils.arrayForEach(responseDialog.success, function (id) {
                //                    self.list.listRow.remove(function (item) {
                //                        return item.id() === id;
                //                    });
                //                });
                //            }
                //        }
                //        self.selectedIds.removeAll();
                //    })
                //    .fail(function (response) {
                //    });
            };

            self.onMoveToLostLeads = function () {
                axios.get(core.router().leadLookups('stage-category').lookups, { params: { parentId: enums.stage.Lost } })
                    .then(function (response) {
                        var dialogLostOptions = {
                            viewModel: new vm.MoveToLostDialog({
                                'leadIds': self.selectedIds(),
                                'stageCategorys': response.data
                            })
                        };
                        core.modals.showModal(dialogLostOptions)
                            .done(function (responseDialog) {
                                if (responseDialog.fail.length > 0) {
                                    var localArray = [];
                                    if (self.view() === 'list') {

                                        ko.utils.arrayForEach(responseDialog.fail, function (id) {
                                            ko.utils.arrayForEach(self.list.listRow(), function (listItem) {
                                                if (id === listItem.id()) { localArray.push({ 'name': listItem.name() }); }
                                            });
                                        });

                                        core.modals.showModal({ viewModel: new vm.BulkActionErrorDialog({ 'actionText': 'Cancelar', 'items': localArray }) });
                                    }
                                    if (self.view() === 'pipeline') {
                                        ko.utils.arrayForEach(responseDialog.fail, function (id) {
                                            ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                                                ko.utils.arrayForEach(column.items(), function (itemLead) {
                                                    if (itemLead.id() === id) {
                                                        if (id === itemLead.id()) { localArray.push({ 'name': itemLead.name() }); }
                                                    }
                                                });
                                            });
                                        });
                                        core.modals.showModal({ viewModel: new vm.BulkActionErrorDialog({ 'actionText': 'Cancelar', 'items': localArray }) });
                                    }
                                }
                                if (responseDialog.success.length > 0) {
                                    core.snackbar.show({ text: "Se cancelo con éxito a los " + responseDialog.success.length + " clientes seleccionados" });
                                    if (self.view() === 'list') {
                                        ko.utils.arrayForEach(responseDialog.success, function (id) {
                                            self.list.listRow.remove(function (item) {
                                                return item.id() === id;
                                            });
                                        });
                                    }
                                    if (self.view() === 'pipeline') {
                                        ko.utils.arrayForEach(responseDialog.success, function (id) {
                                            ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                                                column.items.remove(function (itemLead) {
                                                    return itemLead.id() === id;
                                                });
                                            });
                                        });
                                    }
                                }
                                self.selectedIds.removeAll();
                            });
                    })
                    .catch(function (error) {

                    });
            };

            self.onSendNotifications = function () {
                var dialogOpts = { viewModel: new vm.SendNotificationLeads(self.selectedIds()) }
                core.modals.showModal(dialogOpts)
                    .done(function (response) {
                        if (response.success.length > 0) {
                            core.snackbar.show({
                                text: "Se notificó con éxito a los " + response.success.length + " clientes seleccionados"
                            });
                        }
                        if (response.fail.length > 0) {
                            if (self.view() === 'pipeline') {
                                var failLeads = [];

                                ko.utils.arrayForEach(self.selectedIds(), function (id) {
                                    var findLead;
                                    ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                                        findLead = ko.utils.arrayFirst(column.items(), function (itemLead) {
                                            return id === itemLead.id();
                                        });
                                        if (findLead) {
                                            failLeads.push({ 'name': findLead.name() });
                                        }
                                    });
                                });
                                var payloadError = {
                                    items: failLeads,
                                    actionText: "Notificar "
                                };
                                var dialogOptsError = { viewModel: new vm.BulkActionErrorDialog(payloadError) };
                                core.modals.showModal(dialogOptsError);

                            }
                            if (self.view() === 'list') {
                                var findLeadList;
                                var failLeadsList = [];
                                ko.utils.arrayForEach(self.selectedIds(), function (id) {
                                    findLeadList = ko.utils.arrayFirst(self.list.listRow(), function (itemList) {
                                        return id === itemList.id();
                                    });
                                    if (findLeadList) {
                                        failLeadsList.push({
                                            'name': findLeadList.name()
                                        });
                                    }
                                });
                                var payloadErrorList = {
                                    items: failLeadsList,
                                    actionText: "Notificar "
                                };
                                var dialogOptsErrorList = { viewModel: new vm.BulkActionErrorDialog(payloadErrorList) };
                                core.modals.showModal(dialogOptsErrorList);
                            }
                        }

                        self.selectedIds.removeAll();
                    });
            };

            self.onUpdateTimeToBuy = function () {
                itemsUpdated = 0;
                lengthUpdatedTimeToBuy = self.selectedIds().length;
                successUpdatedTimeToBuy = [];
                failUpdatedTimeToBuy = [];

                var dialogOpts = { viewModel: new vm.UpdateTimeToBuyLeadsDialog() }
                core.modals.showModal(dialogOpts)
                .done(function (response) {
                    core.loading.showAppLoader();
                    ko.utils.arrayForEach(self.selectedIds(), function (item) {
                        var p = {
                            id: item,
                            callback: self.onSuccessOrErrorUpdateTimeToBuyLeads,
                            val: response.month
                        };
                        var findLead;
                        if (self.view() === 'pipeline') {
                            ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                                if (!findLead) {
                                    findLead = ko.utils.arrayFirst(column.items(), function (itemLead) {
                                        return itemLead.id() === item;
                                    });
                                    if (findLead) findLead.setNewRemainingMonthsToBuy(p);
                                }
                            });
                        }
                        if (self.view() === 'list') {
                            findLead = ko.utils.arrayFirst(self.list.listRow(), function (itemList) {
                                return itemList.id() === item;
                            });
                            if (findLead) findLead.setNewRemainingMonthsToBuy(p);
                        }
                    });

                });
            };

            self.onSuccessOrErrorUpdateTimeToBuyLeads = function (val) {
                itemsUpdated = ++itemsUpdated;

                if (val.status === 'success') {
                    successUpdatedTimeToBuy.push(val);
                }
                if (val.status === 'fail') {
                    failUpdatedTimeToBuy.push(val);
                }
                if (itemsUpdated === lengthUpdatedTimeToBuy) {
                    core.loading.hideAppLoader();
                    if (successUpdatedTimeToBuy.length > 0) {
                        core.snackbar.show({
                            text: "Se actualizó con éxito el tiempo a los " + successUpdatedTimeToBuy.length + " clientes seleccionados"
                        });
                        //ko.utils.arrayForEach(successUpdatedTimeToBuy, function(item) {
                        //    self.selectedIds.remove(function(id) {
                        //        return id === item.id;
                        //    });    
                        //});

                    }
                    if (failUpdatedTimeToBuy.length > 0) {
                        var dialogData = {
                            items: failUpdatedTimeToBuy,
                            actionText: "Cambiar tiempo de compra"
                        };
                        var dialogOpts = { viewModel: new vm.BulkActionErrorDialog(dialogData) };
                        core.modals.showModal(dialogOpts);
                    }
                    self.selectedIds.removeAll();
                }
            };

            self.clearSelected = function () {
                self.selectedIds.removeAll();
                self.selectedItems.removeAll();
            };

            self.doSearch = function (timeout) {

                timeout = timeout ? timeout : 0;
                if (searchTimeout) clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function () {
                    search();
                }, timeout);
            };

            self.hideMenus = ko.computed(function () {
                var leadStatus = self.leadStatus();
                //console.warn(leadStatus, "Etapa ");
                if (leadStatus === 'prequalification') {
                    self.view('list');
                    self.leadStatusText("Perfilados");
                    ko.utils.arrayForEach(self.groups(), function (group) {
                        if (group.id() === 'buyPeriods') group.enabled(true);
                        if (group.id() === 'stageCategories') group.enabled(true);

                        if (group.id() === 'stages') group.enabled(false);
                        if (group.id() === 'lastStages') group.enabled(false);
                        if (group.id() === 'stageCategoriesLost') group.enabled(false);

                    });
                }
                if (leadStatus === 'inProcess') {
                    self.leadStatusText("En proceso");
                    self.view('pipeline');
                    ko.utils.arrayForEach(self.groups(), function (group) {
                        if (group.id() === 'buyPeriods') group.enabled(true);
                        if (group.id() === 'stages') group.enabled(true);

                        if (group.id() === 'stageCategories') group.enabled(false);
                        if (group.id() === 'lastStages') group.enabled(false);
                        if (group.id() === 'stageCategoriesLost') group.enabled(false);
                    });
                }
                if (leadStatus === 'closed') {
                    self.leadStatusText("Otorgados");
                    //self.view('list');
                    ko.utils.arrayForEach(self.groups(), function (group) {
                        if (group.id() === 'buyPeriods') group.enabled(false);
                        if (group.id() === 'stages') group.enabled(false);

                        if (group.id() === 'stageCategories') group.enabled(false);
                        if (group.id() === 'lastStages') group.enabled(false);
                        if (group.id() === 'stageCategoriesLost') group.enabled(false);
                    });

                }
                if (leadStatus === 'lost') {
                    self.leadStatusText("Cancelados");
                    self.view("list");
                    ko.utils.arrayForEach(self.groups(), function (group) {
                        if (group.id() === 'lastStages') group.enabled(true);
                        if (group.id() === 'stageCategoriesLost') group.enabled(true);

                        if (group.id() === 'buyPeriods') group.enabled(false);
                        if (group.id() === 'stages') group.enabled(false);
                        if (group.id() === 'stageCategories') group.enabled(false);
                    });
                }
            });

            ko.computed(function () {
                if (self.leadStatus() && self.view() && self.orderBy()) {
                    self.doSearch(750);
                }
            });

            //subscribes
            self.leadStatus.subscribe(function (val) {
                ko.postbox.publish('CloseSideBar');
                self.list.listRow([]);
                self.pipeline.pipelineColumns([]);
                self.isSearchInProcess(true);
                //self.clearGroups();
                self.hideMenus();
                saveLeadStatusLocalStorage(val);
            });

            self.view.subscribe(function (val) {
                self.list.listRow([]);
                self.pipeline.pipelineColumns([]);
                self.isSearchInProcess(true);
            });

            self.pageSize.subscribe(function () {
                self.doSearch(750);
            });

            ko.postbox.subscribe('LeadNoteAdded', function (response) {
                self.selectedIds.remove(function (id) {
                    return id === response.leadId;
                });

                self.selectedItems.remove(function (item) {
                    return item.id === response.leadId;
                });
            });

            ko.postbox.subscribe('LeadTimeToBuyUpdate', function (response) {
                self.selectedIds.remove(function (id) {
                    return id === response.leadId;
                });

                self.selectedItems.remove(function (item) {
                    return item.id === response.leadId;
                });

            });

            self.pageNumber.subscribe(function (val) {
                var valor = parseInt(val);
                if (!isNaN(valor) && valor !== 0 && valor > 0) {
                    self.doSearch(750);
                }
            });

            self.selectedGroups.subscribe(function (e) {
                var jsonToSave = [];

                ko.utils.arrayForEach(e, function (group) {
                    var selectedIds = [];
                    ko.utils.arrayForEach(group.selectedItems(), function (groupItem) {
                        selectedIds.push(groupItem);
                    });
                    jsonToSave.push({ id: group.id(), selectedIds: selectedIds });
                });
                saveGroupFiltersLocalStorage(jsonToSave);
            });

            self.activeGroups.subscribe(function (e) {
                self.pageNumber(1);
                self.doSearch(750);
            });

            self.init = function () {
                ko.postbox.subscribe('AddedLeadsMortgageLoanMortgageLoans', function (data) {
                    var itemChanged;
                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                            if (!itemChanged) {
                                itemChanged = ko.utils.arrayFirst(column.items(), function (item) {
                                    return data.leadId === item.id();
                                });
                            }
                        });
                        if (itemChanged) {
                            var result = {
                                name: data.financialInstitutionName,
                                status: data.creditStatus,
                                imageName: utils.financialInstitution.getImageName(data.code, data.isSelected === true),
                                mortgageLoanLeadMortgageLoanId: data.id
                            }
                            itemChanged.financialInstitutions.push(result);
                        }
                    }
                    if (self.view() === 'list') {
                        itemChanged = ko.utils.arrayFirst(self.list.listRow(), function (item) {
                            return item.id() === data.leadId;
                        });
                        if (itemChanged) {
                            var resultList = {
                                name: data.financialInstitutionName,
                                status: data.creditStatus,
                                imageName: utils.financialInstitution.getImageName(data.code, data.isSelected === true),
                                mortgageLoanLeadMortgageLoanId: data.id,
                                logoUrl: data.financialInstitutionIsoLogoUrl
                            }
                            itemChanged.financialInstitutions.push(resultList);
                        }
                    }
                });
                ko.postbox.subscribe('DeleteLeadsMortgageLoanMortgageLoans', function (data) {
                    var deletedItem;

                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                            ko.utils.arrayForEach(column.items(), function (item) {
                                if (item.id() === data.leadId) {
                                    if (!deletedItem) {
                                        deletedItem = item.financialInstitutions.remove(function (itemF) {
                                            return data.mortgageLoanLeadMortgageLoanId === itemF.mortgageLoanLeadMortgageLoanId;
                                        });
                                    }
                                }
                            });

                        });
                    }
                    if (self.view() === 'list') {
                        deletedItem = ko.utils.arrayFirst(self.list.listRow(), function (item) {
                            return item.id() === data.leadId;
                        });
                        if (deletedItem) {
                            deletedItem.financialInstitutions.remove(function (itemF) {
                                return data.mortgageLoanLeadMortgageLoanId === itemF.mortgageLoanLeadMortgageLoanId;
                            });
                        }
                    }
                });
                ko.postbox.subscribe('updatedFicoScore', function (data) {
                    var findLead;
                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                            if (!findLead) {
                                findLead = ko.utils.arrayFirst(column.items(), function (item) {
                                    return data.id === item.clientId();
                                });
                            }
                        });
                        if (findLead) {
                            if (data.value >= 0) findLead.creditScore(data.value);
                        }
                    }
                    if (self.view() === 'list') {
                        findLead = ko.utils.arrayFirst(self.list.listRow(), function (item) {
                            return data.id === item.clientId();
                        });
                        if (findLead) {
                            if (data.value >= 0) findLead.creditScore(data.value);
                        }
                    }
                });
                ko.postbox.subscribe('UpdatedClientPersonalInformation', function (data) {
                    var findClient;
                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                            if (!findClient) {
                                findClient = ko.utils.arrayFirst(column.items(), function (item) {
                                    return data.id === item.clientId();
                                });
                            }
                        });
                        if (findClient) {
                            var name = data.firstName + ' ' + data.lastName + ' ' + data.maidenName;
                            findClient.name(name);
                        }
                    }
                    if (self.view() === 'list') {                        
                        findClient = ko.utils.arrayFirst(self.list.listRow(), function (item) {
                            return item.clientId() === data.id;
                        });
                        if (findClient) {
                            var nameClient = data.firstName + ' ' + data.lastName + ' ' + data.maidenName;
                            findClient.name(nameClient);
                            if (data.phone1Number) findClient.mobileNumber(data.phone1Number);
                            if (data.email) findClient.email(data.email);
                        }


                    }
                });
                ko.postbox.subscribe('changeOfStepClosed', function (data) {
                    var findLead;
                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                            findLead = column.items.remove(function (item) {
                                return item.code() === data.code;
                            });
                        });
                    }
                    if (self.view() === 'list') {
                        self.list.listRow.remove(function (item) {
                            return item.code() === data.code;
                        });
                    }
                });
                ko.postbox.subscribe('ChangeOfStepLost', function (data) {
                    var findLead;
                    if (self.view() === 'pipeline') {
                        ko.utils.arrayForEach(data.leadIds, function (id) {
                            ko.utils.arrayForEach(self.pipeline.pipelineColumns(), function (column) {
                                findLead = column.items.remove(function (item) {
                                    return item.id() === id;
                                });
                            });
                        });
                    }
                    if (self.view() === 'list') {
                        ko.utils.arrayForEach(data.leadIds, function () {
                            self.list.listRow.remove(function (item) {
                                return item.code() === data.code;
                            });
                        });
                    }
                });
                ko.postbox.subscribe('RecoveredLead', function(data) {
                    if (data.fail.length > 0) {
                        var localArray = [];
                        if (self.view() === 'list') {
                            ko.utils.arrayForEach(data.fail, function (item) {
                                ko.utils.arrayForEach(self.list.listRow(), function (listItem) {
                                    if (item.leadId === listItem.id()) {

                                        listItem.hasErrorActionBulKAction(true);
                                        listItem.reasonError(item.reasonError);
                                    }
                                });
                            });
                        }
                    }
                    if (data.success.length > 0) {
                        core.snackbar.show({
                            text: data.success.length == 1 ? "1 crédito recuperado con éxito" : data.success.length + " créditos recuperados con éxito"
                        });
                        if (self.view() === 'list') {
                            ko.utils.arrayForEach(data.success, function (id) {
                                self.list.listRow.remove(function (item) {
                                    return item.id() === id;
                                });
                            });
                        }
                    }
                });
            }();
        };

        vm.MoveToCreditIntegrationForm = function () {
            var self = this;

            self.stageId = ko.observable('CreditIntegration');
            self.name = 'Integración de expediente';
            self.description = '';
            self.step = 'Etapa 1';

        };

        vm.MoveToCreditAnalysisForm = function () {
            var self = this;

            self.stageId = ko.observable('CreditAnalysis');
            self.name = 'Evaluación de crédito';
            self.description = 'Solicita al ejecutivo del banco el <b>número de folio</b> con el que se ingreso el expediente de tu cliente.';
            self.step = 'Etapa 2';
            //self.missingData = ko.observable(true);

            self.creditNumber = ko.observable().extend({ required: true, number: true });

            self.getPayload = function () {
                return {
                    creditAnalysisData: {
                        creditNumber: self.creditNumber()
                    }
                };
            }

            self.errors = ko.validation.group(self);
        };

        vm.MoveToGuarantyIntegrationForm = function (id) {
            var self = this;
            self.stageId = ko.observable('GuarantyIntegration');
            self.name = 'Documentación del inmueble';
            self.step = 'Etapa 3';
            self.mortgageLoanLeadMortgageLoanId = ko.observable();
            self.approvalAmount = ko.observable('');
            self.mortgageLoanTermId = ko.observable();
            self.missingData = ko.observable(false);

            self.financialInstitutions = ko.observableArray();
            //extend rules validation
            self.mortgageLoanLeadMortgageLoanId.extend({
                required: {
                    params: true,
                    message: function () { return self.financialInstitutions().length > 0 ? 'Selecciona un banco.' : 'Necesita aprobar un crédito en el sidebar.'; }
                }
            });
            self.approvalAmount.extend({
                required: {
                    onlyIf: function () { return self.financialInstitutions().length > 0; }
                },
                number: true
            });

            self.description = ko.computed(function () {
                if (self.financialInstitutions().length === 0) return '<b>¡Algo salió mal!</b><br/> Es necesario que apruebes por lo menos una solicitud de crédito antes de hacer el movimiento de etapa.';
                return 'Aquí se muestran los bancos que aprobaron la solicitud de crédito, es necesario <b>seleccionar uno</b> y <b>confirmar monto</b> aprobado para continuar el proceso.';
            });

            self.getPayload = function () {
                return {
                    guarantyIntegrationData: {
                        mortgageLoanLeadMortgageLoanId: self.mortgageLoanLeadMortgageLoanId(), //solo se ocupa para actualizar en el banco o producto
                        approvalAmount: self.approvalAmount(),
                        mortgageLoanTermId: self.mortgageLoanTermId()
                    }
                }
            }

            self.onGetFinancialInstitutions = function () {
                axios.get(core.router().mortgageLoanLead(id).mortgageLoans)
                    .then(function (response) {
                        var financialsApproved = [];
                        ko.utils.arrayForEach(response.data, function (financial) {
                            if (financial.creditStatus === enums.AmountStatus.Approved) financialsApproved.push(financial);
                        });
                        self.financialInstitutions(financialsApproved);
                        if (self.financialInstitutions().length === 0) {
                            self.missingData(true);
                        }
                    })
                    .catch();
            };


            self.mortgageLoanLeadMortgageLoanId.subscribe(function (value) {
                var mortgage = ko.utils.arrayFirst(self.financialInstitutions(), function (item) {
                    return item.id === value;
                });
                if (mortgage) self.mortgageLoanTermId(mortgage.mortgageLoanTermId);
            });

            self.errors = ko.validation.group(self);

            var init = function () {
                self.onGetFinancialInstitutions();
            }();
        };

        vm.MoveToGuarantyAnalysisForm = function () {
            var self = this;

            self.stageId = ko.observable('GuarantyAnalysis');
            self.name = 'Validación del inmueble';
            self.description = 'Estos datos te son proporcionados por el banco cuando haces la <b>solicitud de avalúo</b>.';
            self.step = 'Etapa 4';

            self.notaryName = ko.observable().extend({ required: true });
            self.notaryCode = ko.observable().extend({ required: true });

            self.valuationUnitName = ko.observable().extend({ required: true });
            self.valuationUnitCode = ko.observable().extend({ required: true });

            self.getPayload = function () {
                return {
                    guarantyAnalysisData: {
                        notaryName: self.notaryName(),
                        notaryCode: self.notaryCode(),
                        valuationUnitName: self.valuationUnitName(),
                        valuationUnitCode: self.valuationUnitCode()
                    }
                }
            };

            self.errors = ko.validation.group(self);
        };

        vm.MoveToSignatureForm = function () {
            var self = this;

            self.stageId = ko.observable('Signature');
            self.name = 'Firma de contrato';
            self.description = 'Acuerda con el cliente y el banco fecha y hora óptimas para la firma.';
            self.step = 'Etapa 5';

            self.notarySignatureDate = ko.observable().extend({ required: true });
            self.hour = ko.observable().extend({ required: true });
            self.notaryAddress = ko.observable().extend({ required: true });

            self.creditDate = ko.computed(function () {
                if (!self.hour()) {
                    return new Date(new Date(self.notarySignatureDate()).toDateString());
                } else {
                    return new Date(new Date(self.notarySignatureDate()).toDateString() + ' ' + self.hour());
                }
            });

            self.getPayload = function () {
                return {
                    signatureData: {
                        creditDate: self.creditDate(),
                        notaryAddress: self.notaryAddress()
                    }
                }
            };

            self.errors = ko.validation.group(self);
        };

        vm.MoveToClosedForm = function (id) {
            var self = this;

            self.stageId = ko.observable('Closed');
            self.name = 'Otorgar crédito';
            self.disbursementAmount = ko.observable();

            self.creditAmount = ko.observable();
            self.propertyValue = ko.observable();
            self.downPayment = ko.observable();
            self.monthlyPayment = ko.observable();
            self.termId = ko.observable();
            self.initialInterestRate = ko.observable();
            self.totalAnnualCost = ko.observable();


            self.propertyValueFormatted = ko.observable();
            self.downPaymentFormatted = ko.observable();
            self.monthlyPaymentFormatted = ko.observable();
            self.term = ko.observable();
            self.initialInterestRateFormatted = ko.observable();
            self.totalAnnualCostFormatted = ko.observable();
            self.missingData = ko.observable(false);

            self.financialInstitutions = ko.observableArray();

            self.creditAmountFormatted = ko.computed(function () {
                if (self.creditAmount() > 0) return self.creditAmount().formatMoney(0);
                return '';
            });
            self.propertyValueFormatted = ko.computed(function () {
                if (self.propertyValue() > 0) return self.propertyValue().formatMoney(0);
                return '';
            });
            self.downPaymentFormatted = ko.computed(function () {
                if (self.downPayment() > 0) return self.downPayment().formatMoney(0);
                return '';
            });
            self.monthlyPaymentFormatted = ko.computed(function () {
                if (self.monthlyPayment() > 0) return self.monthlyPayment().formatMoney(0);
                return '';
            });
            self.termFormatted = ko.computed(function () {
                return self.termId() + ' años';
            });

            self.completeData = ko.computed(function () {
                if (self.creditAmount() > 0 && self.propertyValue() > 0 && self.downPayment() > 0 && self.monthlyPayment() > 0 && self.termId() > 0 && self.initialInterestRate() > 0 && self.totalAnnualCost() > 0) {
                    self.missingData(false);
                    return true;
                }
                self.missingData(true);
                return false;
            });

            self.description = ko.computed(function () {
                if (!self.completeData()) {
                    return '<b>¡Algo salió mal!</b><br/> Es necesario que completes los datos de la solicitud de crédito antes de hacer el movimiento de etapa.';
                }
                return '';

            });


            self.mortgageLoans = ko.observableArray();

            self.getPayload = function () {
                return {
                    'closedData': {
                        'disbursementAmount': self.disbursementAmount()
                    }
                }
            };

            self.setDataIsSelected = function (mortgageLoanMortgage) {
                self.creditAmount(mortgageLoanMortgage.creditAmount);
                self.propertyValue(mortgageLoanMortgage.propertyValue);
                self.downPayment(mortgageLoanMortgage.downPayment);
                self.monthlyPayment(mortgageLoanMortgage.monthlyPayment);
                self.termId(mortgageLoanMortgage.termId);
                self.initialInterestRate(mortgageLoanMortgage.initialInterestRate);
                self.totalAnnualCost(mortgageLoanMortgage.totalAnnualCost);

                self.term(mortgageLoanMortgage.termId);
                self.initialInterestRateFormatted(mortgageLoanMortgage.initialInterestRateFormatted);
                self.totalAnnualCostFormatted(mortgageLoanMortgage.totalAnnualCostFormatted);
                self.disbursementAmount(mortgageLoanMortgage.creditAmount);
            };

            self.getMortgageLoans = function () {
                axios.get(core.router().mortgageLoanLead(id).mortgageLoans)
                    .then(function (response) {
                        var selected = ko.utils.arrayFirst(response.data, function (item) {
                            return item.isSelected === true;
                        });
                        if (selected) {
                            self.setDataIsSelected(selected);
                        } else {
                            self.financialInstitutions(response.data);
                        }
                    })
                    .catch();
            };

            self.errors = ko.validation.group(self);

            var init = function () {
                self.getMortgageLoans();

                ko.postbox.subscribe('IsSelectedMortgageLoan', function (data) {
                    var selected = ko.utils.arrayFirst(self.financialInstitutions(), function (item) {
                        return item.id === data.mortgageLoanLeadMortgageLoanId; //.toString();
                    });

                    if (selected) {
                        selected.isSelected = true;
                        selected.creditAmount = parseInt(data.creditAmount);
                        self.setDataIsSelected(selected);
                    }
                });
            }();

        };

        vm.BulkActionErrorDialog = function (initData) {
            var self = this;
            self.template = "ko-bulk-action-error";
            
            self.actionText = ko.observable(initData.actionText);
            self.items = ko.observableArray(initData.items);
        };

        vm.AddNoteToLeadsDialog = function (initData) {
            var self = this;
            self.template = 'ko-add-note-to-leads';

            self.comment = ko.observable();
            self.onAddnote = function () {
                var errorRequests = [];
                var errorItems = [];

                core.loading.blockModal();

                var requests = Promise.all(initData.leadDtos.map(function (leadItem) {
                    return axios.post(core.router().mortgageLoanLead(leadItem.id).notes, { comment: self.comment() })
                        .then(function (response) {
                            return response;
                        })
                        .catch(function (errorResponse) {
                            errorItems.push(leadItem);
                            return errorResponse;
                        });
                }));

                requests.then(function (responses) {
                    core.loading.unblockModal();

                    var sucessRequestCount = 0;

                    for (var i = 0; i < responses.length; i++) {
                        if (responses[i].status == 200) {
                            ko.postbox.publish('LeadNoteAdded', responses[i].data);
                            sucessRequestCount++;
                        }
                    }

                    if (errorItems.length > 0) {
                        var dialogData = {
                            items: errorItems,
                            errorRequests: errorRequests,
                            actionText: "Agregar nota"
                        };
                        var dialogOpts = { viewModel: new vm.BulkActionErrorDialog(dialogData) };
                        core.modals.showModal(dialogOpts);
                    }

                    if (sucessRequestCount > 0) {
                        core.snackbar.show({
                            text: "Se agregó con éxito la Nota a los " + sucessRequestCount + " clientes seleccionados"
                        });
                    }


                    self.modal.close();
                });
            };
        };

        vm.SendNotificationLeads = function (leadIds) {
            var self = this;

            var notificationsType = [
                    { id: 'PendingDocuments', name: 'Tienes documentos pendientes por cargar.' },
                    { id: 'DocumentsWithError', name: 'Algunos de tus documentos tienen errores.' },
                    { id: 'DocumentsApproved', name: 'Tus documentos han sido aprobados.' }
            ];
            var fail = [];
            var success = [];

            self.action = ko.observable('send-lead-document-notification');
            self.notificationType = ko.observable().extend({ required: true });

            self.optionsNotificationsType = ko.observableArray(notificationsType);
            self.leadsId = ko.observableArray(leadIds);

            self.template = 'ko-send-notification-leads';

            self.onSendNotifications = function () {
                var payload = {
                    action: self.action(),
                    documentNotifiactionType: self.notificationType()
                };
                core.loading.blockModal();
                var requests = Promise.all(leadIds.map(function (leadItem) {
                    return axios.put(core.router().mortgageLoanLead(leadItem).documents, payload)
                        .then(function (response) {
                            success.push(leadItem);
                            return response;
                        })
                        .catch(function (errorResponse) {
                            fail.push(leadItem);
                            return errorResponse;
                        });
                }));

                requests.then(function () {
                    core.loading.unblockModal();
                    self.modal.close({
                        'success': success,
                        'fail': fail
                    });
                });
            };

        };

        vm.ReactivateLeadsDialog = function (initData) {
            var self = this;
            self.template = "ko-reactivate-leads";

            var errorItems = [];
            var successItems = [];
            
            self.showItemsSelected = function () {

                core.loading.blockModal();

                var requests = Promise.all(initData.leads.map(function (item) {
                    return axios
                        //old line -> .put(core.routes.reactivateLeads + item.id + '/recover-leads')
                        .put('/api/v2/leads/mortgage-loan/' + item + '/recover-leads')
                        .then(function (response) {
                            successItems.push(item);
                        })
                        .catch(function (response) {
                            var reasonError = 'Ocurrio algo inesperado';
                            if (response.response.status === 400) { //Error de validacion 
                                if (response.response.data.errors.length > 0) reasonError =  response.response.data.errors[0].message
                            }                            
                            errorItems.push({ 'leadId': item, 'reasonError': reasonError });
                        });
                }));

                requests.then(function (responses) {

                    core.loading.unblockModal();
                    self.modal.close({
                        'success': successItems,
                        'fail': errorItems
                    });
                });
            };
        };

        vm.MoveToStageDialog = function (id, fromStageId, toStageId) { //dataResponse
            var self = this;

            var payload = { id: id };

            self.template = 'ko-move-stage-dialog';

            self.onCloseSuccess = function (data) {
                self.modal.close(data);
            };

            self.onClose = function () {
                self.modal.close();
            };

            self.stages = ko.observableArray();

            self.currentIndex = ko.observable(0);
            self.currentForm = ko.observable();

            self.lastForm = ko.observable();

            self.title = ko.pureComputed(function () {
                if (!self.lastForm().name) return 'Mover a etapa';

                return self.lastForm().name;
            });

            self.formCount = ko.pureComputed(function () {
                return self.stages().length;
            });

            var setError = function (response) {

                if (self.stages().length > 1) {

                    var modelExistError = ko.utils.arrayFirst(self.stages(), function (stageModel, index) {
                        if (ko.isObservable(stageModel[response.errors[0].fieldName])) {
                            stageModel.positionModel = index;
                            return true;
                        }
                        return false;
                    });

                    if (modelExistError) {

                        ko.postbox.publish('CarouselWizard.prev', { 'index': modelExistError.positionModel });

                        setTimeout(function () {

                            self.currentIndex(modelExistError.positionModel);
                            self.currentForm(self.stages()[modelExistError.positionModel]);


                            var insertErrors = true;
                            ko.utils.arrayForEach(response.errors, function (error) {
                                if (error.fieldName) {
                                    core.errors.showResponseError(self.currentForm(), response);
                                    insertErrors = false;
                                }
                            });
                            if (insertErrors)
                                core.errors.insertModalError(response);
                        }, 500);


                    } else {
                        console.error('Not found Observable');
                        return;
                    }
                } else {

                    var insertErrors = true;
                    if (response['errors']) {
                        ko.utils.arrayForEach(response.errors, function (error) {
                            if (error.fieldName) {
                                core.errors.showResponseError(self.currentForm(), response);
                                insertErrors = false;
                            }
                        });
                    }

                    if (insertErrors)
                        core.errors.insertModalError(response);
                }
            };

            var moveToNextForm = function () {
                ko.postbox.publish('CarouselWizard.next', {});
                setTimeout(function () {
                    self.currentIndex(self.currentIndex() + 1);
                    self.currentForm(self.stages()[self.currentIndex()]);
                }, 500);
            };

            var moveToStage = function () {
                payload.toStage = self.currentForm().stageId();
                //console.log("Test");
                if (payload.guarantyIntegrationData) {
                    var payloadProduct = {
                        leadId: id,
                        creditAmount: payload.guarantyIntegrationData.approvalAmount,
                        mortgageLoanLeadMortgageLoanId: payload.guarantyIntegrationData.mortgageLoanLeadMortgageLoanId,
                        action: 'update-data'
                    };
                    core.loading.blockModal();
                    axios.patch(core.router().mortgageLoanLead(id).mortgageLoans, payloadProduct)
                        .then(function (responseUpdate) {
                            ko.postbox.publish('UpdatedMortgageLoanMortgageLoans', responseUpdate.data);
                            axios.put(core.router().mortgageLoanLead(id).stage, payload)
                                .then(function (response) {
                                    ko.postbox.publish('MovedOfStage', response.data);
                                    self.onCloseSuccess(response.data);
                                    core.loading.unblockModal();
                                })
                                .catch(function (error) {
                                    setError(error.response.data);
                                    core.loading.unblockModal();
                                });
                        })
                        .catch(function (error) {
                            core.loading.unblockModal();
                            setError(error.response.data);
                        });
                } else {
                    core.loading.blockModal();
                    axios.put(core.router().mortgageLoanLead(id).stage, payload)
                        .then(function (response) {
                            ko.postbox.publish('MovedOfStage', response.data);
                            self.onCloseSuccess(response.data);
                            core.loading.unblockModal();
                        })
                        .catch(function (error) {
                            core.loading.unblockModal();
                            setError(error.response.data);
                        });
                }
            };

            self.onAccept = function () {
                var currentForm = self.currentForm();
                if (currentForm.errors().length > 0) {
                    currentForm.errors.showAllMessages();
                    return;
                }
                if (currentForm.getPayload()['guarantyIntegrationData'] && toStageId === enums.stage.Closed) {
                    //alert(toStageId);
                    var updateDatePayload = {
                        mortgageLoanLeadMortgageLoanId: currentForm.getPayload()['guarantyIntegrationData'].mortgageLoanLeadMortgageLoanId,
                        creditAmount: currentForm.getPayload()['guarantyIntegrationData'].approvalAmount
                    };

                    ko.postbox.publish('IsSelectedMortgageLoan', updateDatePayload);
                }



                payload = ko.utils.extend(payload, currentForm.getPayload());


                if (self.currentIndex() === self.formCount() - 1) moveToStage();
                else moveToNextForm();
            };

            self.checkCurrentModalIncompleData = ko.computed(function () {
                if (self.currentForm()) {
                    if (self.currentForm()["missingData"]) {
                        if (self.currentForm()["missingData"]()) return true;
                        else return false;
                    }
                }
                return false;
            });

            self.init = function () { // THIS IS UGLY AND DIRTY

                var stages = ['CreditIntegration', 'CreditAnalysis', 'GuarantyIntegration', 'GuarantyAnalysis', 'Signature', 'Closed'];

                var fromIndex = stages.indexOf(fromStageId) + 1;
                var toIndex = stages.indexOf(toStageId) + 1;
                var stagesToProcess = stages.slice(fromIndex, toIndex);

                var stageForms = [];

                ko.utils.arrayForEach(stagesToProcess, function (item) {
                    stageForms.push(new vm['MoveTo' + item + 'Form'](id));
                });

                self.stages(stageForms);

                self.currentForm(stageForms[0]);
                self.lastForm(stageForms[stageForms.length - 1]);

            }();
        };

        vm.MoveToLostDialog = function (response) {
            var self = this;

            var success = [];
            var fail = [];
            self.template = 'ko-move-stage-lost-dialog';

            self.title = ko.computed(function () {
                if (response.leadIds.length > 1) {
                    return 'Cancelar créditos seleccionados';
                } else { return 'Cancelar crédito'; }
            });
            self.stageCategory = ko.observable().extend({ required: true });
            self.comment = ko.observable();
            self.stageCategorys = ko.observableArray(response.stageCategorys);

            var getPayload = function () {
                var payload = {
                    //'id': response.leadId,
                    'toStage': 'Lost',
                    'lostData': { 'stageCategory': self.stageCategory() }
                }
                if (self.comment()) payload.lostData.comment = self.comment();
                return payload;
            }

            self.description = ko.pureComputed(function () {
                var itemCategory = ko.utils.arrayFirst(self.stageCategorys(), function (item) {
                    return item.id === self.stageCategory();
                });
                return itemCategory ? itemCategory.data : '';
            });

            self.onLost = function () {
                if (self.errors().length > 0) {
                    self.errors.showAllMessages();
                    return;
                }
                core.loading.blockModal();
                var requests = Promise.all(response.leadIds.map(function (id) {
                    return axios.put(core.router().mortgageLoanLead(id).stage, getPayload())
                        .then(function (responseStage) {
                            success.push(id);
                        })
                        .catch(function (error) {
                            fail.push(id);
                        });
                }));

                requests.then(function (response) {
                    core.loading.unblockModal();
                    self.modal.close({
                        'fail': fail,
                        'success': success
                    });
                });
            };

            self.errors = ko.validation.group(self);
        };

        vm.DeleteBankDialog = function (info) {
            var self = this;

            self.template = 'ko-delete-bank';

            self.id = ko.observable(info.id);
            self.leadId = ko.observable(info.leadId);
            self.financialInstitutionLogoUrl = ko.observable(info.financialInstitutionLogoUrl);
            self.name = ko.observable(info.name);
            self.creditAmountFormatted = ko.observable(info.creditAmountFormatted);
            self.propertyValueFormatted = ko.observable(info.propertyValueFormatted);
            self.downPaymentFormatted = ko.observable(info.downPaymentFormatted);
            self.monthlyPaymentFormatted = ko.observable(info.monthlyPaymentFormatted);
            self.termId = ko.observable(info.termId);
            self.initialInterestRateFormatted = ko.observable(info.initialInterestRateFormatted);
            self.totalAnnualCostFormatted = ko.observable(info.totalAnnualCostFormatted);

            self.onDeleteBank = function () {
                axios.delete(core.router().mortgageLoanLead(self.leadId(), self.id()).deleteMortgageLoans)
                    .then(function (response) {
                        self.modal.close(response.data);
                    })
                    .catch(function (response) {
                        self.modal.close(response.data);
                    });

            };
        };

        vm.UpdateTimeToBuyLeadsDialog = function (initData) {
            var self = this;
            self.template = 'ko-update-time-to-buy-leads';

            self.month = ko.observable().extend({ required: true });
            self.months = ko.observableArray([
               { id: '0', name: 'Inmediato' },
               { id: '1', name: '1 mes' },
               { id: '2', name: '2 meses' },
               { id: '3', name: '3 meses' },
               { id: '4', name: '4 meses' },
               { id: '5', name: '5 meses' },
               { id: '6', name: '6 meses' },
               { id: '7', name: '7 meses' },
               { id: '8', name: '8 meses' },
               { id: '9', name: '9 meses' },
               { id: '10', name: '10 meses' },
               { id: '11', name: '11 meses' },
               { id: '12', name: '12 meses' }
            ]);
            var month;
            self.onUpdateTime = function () {
                month = parseInt(self.month());

                if (self.errors().length > 0) {
                    self.errors.showAllMessages();
                    return;
                }

                self.modal.close({ 'month': self.month() });
                //ko.postbox.publish('updateTimeToBuy', month);
                //self.modal.close();
            };

            self.errors = ko.validation.group(self);

        };

        vm.EvaluateFicoDialog = function (id) {

            var self = this;
            self.template = 'ko-evaluate-fico';
            self.id = ko.observable(id);

            var showErrorDialog = function (payload) {
                var dialogOpts = {};
                dialogOpts = {
                    viewModel: new vm.FicoErrorDialog(payload.id)
                }
                core.modals.showModal(dialogOpts);
            }

            self.onReviewClientDataDialog = function () {

                axios.get(core.router().mortgageLoanLead(id).coborrower)
                    .then(function (response) {
                        var dialogOpts = {};
                        dialogOpts = { viewModel: new vm.FicoReviewClientDataDialog(response.data, id) }
                        core.modals.showModal(dialogOpts);
                        self.modal.close(response.data);
                    })
                    .catch(function (response) {
                        self.modal.close(response.data);
                    });
            };
            
            self.onUpdateFicoScore = function () {

                var payload = {
                    'id': self.id()
                };
                core.loading.showAppLoader();

                axios.put(core.router().mortgageLoanLead(self.id()).coborrower, { action: "refresh" })
                    .then(function (response) {
                        response.data.id = self.id();
                        ko.postbox.publish('updatedCoborrowerFicoScore', response.data);
                        core.loading.hideAppLoader();
                        self.modal.close(response.data);
                    })
                    .catch(function (response) {
                        core.loading.hideAppLoader();
                        self.modal.close(response.data);
                        showErrorDialog(payload);
                    });
            };

        };

        vm.FicoErrorDialog = function (id) {

            var self = this;
            self.template = 'ko-error-evaluating-fico';
            self.id = ko.observable(id);

            self.onReviewClientDataDialog = function () {
                axios.get(core.router().mortgageLoanLead(id).coborrower)
                    .then(function (response) {
                        var dialogOpts = {};
                        dialogOpts = { viewModel: new vm.FicoReviewClientDataDialog(response.data, id) }
                        core.modals.showModal(dialogOpts);
                        self.modal.close(response.data);
                    })
                    .catch(function (response) {
                        self.modal.close(response.data);
                    });
            };
        };

        vm.MoveToPersonalDataForm = function (initData) {

            var self = this;

            self.step = 'Datos personales.';
            self.stageId = ko.observable('PersonalData');

            self.firstName = ko.observable(initData.firstName || '').extend({ required: true });
            self.lastName = ko.observable(initData.lastName || '').extend({ required: true });
            self.maidenName = ko.observable(initData.maidenName || '').extend({ required: true });
            self.nin = ko.observable(initData.nin || '').extend({ required: true });

            self.name = ko.computed(function () {
                return self.firstName() + ' ' + self.lastName() + ' ' + self.maidenName();
            });

            self.errors = ko.validation.group(self);
        };

        vm.MoveToAddressForm = function (initData) {

            var self = this;

            self.step = 'Dirección.';
            self.stageId = ko.observable('Address');

            self.street = ko.observable(initData.street || '').extend({ required: true });
            self.exteriorNumber = ko.observable(initData.exteriorNumber || '').extend({ required: true });
            self.interiorNumber = ko.observable(initData.interiorNumber || '');
            self.colony = ko.observable(initData.colony || '').extend({ required: true });
            self.postalCode = ko.observable(initData.postalCode || '').extend({ required: true });
            self.areaLevel1Id = ko.observable().extend({ required: true });
            self.areaLevel2Id = ko.observable().extend({ required: true });

            self.areaLevel1 = ko.observableArray();
            self.areaLevel2 = ko.observableArray();

            self.areaLevel1Id.subscribe(function (val) {
                if (val) {
                    dataCommons.getCounty(val)
                    .done(function (response) {
                        self.areaLevel2(response);
                        self.areaLevel2Id(initData.areaLevel2Id || '');
                    })
                    .fail(function () {
                    });
                }
            });

            var getStates = function () {
                dataCommons.getStates()
                    .done(function (response) {
                        self.areaLevel1(response);
                        self.areaLevel1Id(initData.areaLevel1Id);
                    })
                    .fail(function () { });
            };

            self.errors = ko.validation.group(self);

            self.init = function () {
                getStates();
            }();
        };

        vm.MoveToCreditDataForm = function (initData) {

            var self = this;

            self.step = 'Datos crediticios.';
            self.stageId = ko.observable('CreditData');

            if (typeof (initData.hasCreditCard) === "boolean") initData.hasCreditCard ? initData.hasCreditCard = 'Yes' : initData.hasCreditCard = 'No';
            self.hasCreditCard = ko.observable(initData.hasCreditCard).extend({ required: true });
            self.hasCreditCardValue = ko.observable(false);

            self.creditCardLastDigits = ko.observable(initData.creditCardLastDigits).extend({
                required: {
                    onlyIf: function () {
                        return self.hasCreditCard() === 'Yes';
                    }
                }
            });

            if (typeof (initData.hasMortgageLoan) === "boolean") initData.hasMortgageLoan ? initData.hasMortgageLoan = 'Yes' : initData.hasMortgageLoan = 'No';
            self.hasMortgageLoan = ko.observable(initData.hasMortgageLoan).extend({ required: true });
            self.hasMortgageLoanValue = ko.observable(false);

            if (typeof (initData.hasCarCredit) === "boolean") initData.hasCarCredit ? initData.hasCarCredit = 'Yes' : initData.hasCarCredit = 'No';
            self.hasCarCredit = ko.observable(initData.hasCarCredit).extend({ required: true });
            self.hasCarCreditValue = ko.observable(false);


            self.errors = ko.validation.group(self);
        };

        vm.FicoReviewClientDataDialog = function (initData, id) {

            var self = this;
            self.template = 'ko-review-client-data-fico';
            self.currentIndex = ko.observable(0);
            self.id = ko.observable(id);
            self.showEvaluateFicoScoreText = ko.observable(false);
            self.stageForms = ko.observableArray();

            self.stageFormsCount = ko.computed(function () {
                return self.stageForms().length;
            });
            self.currentViewModel = ko.computed(function () {
                return self.stageForms()[self.currentIndex()];
            });
            self.currentStage = ko.computed(function () {
                return self.stageForms()[self.currentIndex()];
            });

            var showErrorDialog = function (payload) {
                var dialogOpts = {};
                dialogOpts = {
                    viewModel: new vm.FicoErrorDialog(payload.id)
                }
                core.modals.showModal(dialogOpts);
            }

            var onUpdateFicoScore = function () {

                var payload = {
                    'id': self.id()
                };

                core.loading.showAppLoader();

                axios.put(core.router().mortgageLoanLead(self.id()).coborrower, { action: "refresh" })
                    .then(function(response) {
                        response.data.id = self.id();
                        ko.postbox.publish('updatedCoborrowerFicoScore', response.data);
                        core.loading.hideAppLoader();
                        self.modal.close(data);
                    })
                    .catch(function(response) {
                        core.loading.hideAppLoader();
                        self.modal.close(response.data);
                        showErrorDialog(payload);
                    });
            };

            self.onAccept = function () {

                var currentViewModel = self.currentViewModel();
                if (currentViewModel.errors().length > 0) {
                    currentViewModel.errors.showAllMessages();
                    return;
                }

                ko.postbox.publish('CarouselWizard.next', {});

                setTimeout(function () {
                    self.currentIndex(self.currentIndex() + 1);

                }, 500);

                if (self.stageForms()[self.currentIndex()].stageId() === 'Address') {
                    self.showEvaluateFicoScoreText(true);
                }

                if (self.stageForms()[2].hasCreditCard() === 'No') {
                    self.stageForms()[2].hasCreditCardValue(false);
                    self.stageForms()[2].creditCardLastDigits('');
                } else if (self.stageForms()[2].hasCreditCard() === 'Yes') {
                    self.stageForms()[2].hasCreditCardValue(true);
                }

                if (self.stageForms()[2].hasMortgageLoan() === 'No') {
                    self.stageForms()[2].hasMortgageLoanValue(false);
                } else if (self.stageForms()[2].hasMortgageLoan() === 'Yes') {
                    self.stageForms()[2].hasMortgageLoanValue(true);
                }

                if (self.stageForms()[2].hasCarCredit() === 'No') {
                    self.stageForms()[2].hasCarCreditValue(false);
                } else if (self.stageForms()[2].hasCarCredit() === 'Yes') {
                    self.stageForms()[2].hasCarCreditValue(true);
                }

                if (self.stageForms()[self.currentIndex()].stageId() === 'CreditData') {
                    var payload = {
                        'id': self.id(),
                        'firstName': self.stageForms()[0].firstName(),
                        'lastName': self.stageForms()[0].lastName(),
                        'maidenName': self.stageForms()[0].maidenName(),
                        'nin': self.stageForms()[0].nin(),
                        'name': self.stageForms()[0].name(),

                        'street': self.stageForms()[1].street(),
                        'exteriorNumber': self.stageForms()[1].exteriorNumber(),
                        'interiorNumber': self.stageForms()[1].interiorNumber(),
                        'colony': self.stageForms()[1].colony(),
                        'postalCode': self.stageForms()[1].postalCode(),
                        'areaLevel1Id': parseInt(self.stageForms()[1].areaLevel1Id()),
                        'areaLevel2Id': parseInt(self.stageForms()[1].areaLevel2Id()),

                        'hasCreditCard': self.stageForms()[2].hasCreditCardValue(),
                        'creditCardLastDigits': self.stageForms()[2].creditCardLastDigits(),
                        'hasMortgageLoan': self.stageForms()[2].hasMortgageLoanValue(),
                        'hasCarCredit': self.stageForms()[2].hasCarCreditValue()
                    };
                    axios.patch(core.router().mortgageLoanLead(self.id()).coborrower, { id : self.id(), action : 'update', data : payload})
                        .then(function (response) {
                            ko.postbox.publish('currentCoborrowerData', payload);
                            onUpdateFicoScore();
                            self.modal.close(data);
                        })
                        .catch(function (response) {
                            showErrorDialog(payload);
                            self.modal.close(data);
                        });
                }

                core.loading.hideAppLoader();
            };

            // THIS CONTINUES BEING UGLY AND DIRTY
            self.init = function () {
                var stages = ['PersonalData', 'Address', 'CreditData'];
                ko.utils.arrayForEach(stages, function (item) {
                    self.stageForms.push(new vm['MoveTo' + item + 'Form'](initData));
                });
            }();
        };

        vm.EditCoborrowerDialog = function (clientData) {

            var self = this;
            self.template = 'ko-edit-coborrower-information';

            self.title = ko.observable('Editar <b>datos del coacréditado<b/>');

            self.id = ko.observable(clientData.id);
            self.firstName = ko.observable(clientData.firstName || '').extend({ required: true });
            self.lastName = ko.observable(clientData.lastName || '').extend({ required: true });
            self.maidenName = ko.observable(clientData.maidenName || '').extend({ required: true });
            self.nin = ko.observable(clientData.nin || '').extend({ required: true, minLength: 18, maxLength: 18, nin: true });

            self.onUpdateData = function () {

                if (self.errors().length > 0) {
                    self.errors.showAllMessages();
                    return;
                }

                core.loading.showAppLoader();

                var payload = {
                    id: self.id(),
                    firstName: self.firstName(),
                    maidenName: self.maidenName(),
                    lastName: self.lastName(),
                    nin: self.nin()
                };
                
                axios.patch(core.router().mortgageLoanLead(self.id()).coborrowerPersonalData, payload)
                    .then(function(response) {
                        ko.postbox.publish('UpdatedCoborrowerPersonalInformation', payload);
                        core.loading.hideAppLoader();
                        self.modal.close(response.data);
                    })
                    .catch(function (response) {
                        core.loading.hideAppLoader();
                });
            };

            self.errors = ko.validation.group(self);
        };

        return vm;
    });

Comments