/*
 * Arrebol Consultancy copyright.
 *
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.apc.web.beans.dashboard;

import com.arrebol.apc.controller.BitacoraController;
import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.GenericValidationController;
import com.arrebol.apc.controller.admin.ClosingDayController;
import com.arrebol.apc.controller.admin.CustomerController;
import com.arrebol.apc.controller.admin.EndorsementController;
import com.arrebol.apc.controller.admin.LoanController;
import com.arrebol.apc.controller.admin.PeopleController;
import com.arrebol.apc.controller.catalog.LoanTypeController;
import com.arrebol.apc.controller.catalog.RouteController;
import com.arrebol.apc.controller.dashboard.CustomerWithoutRenovationViewService;
import com.arrebol.apc.controller.dashboard.DashboardController;
import com.arrebol.apc.model.catalog.People;
import com.arrebol.apc.model.catalog.RouteCtlg;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.core.User;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.CustomerClassification;
import com.arrebol.apc.model.enums.FeeStatus;
import com.arrebol.apc.model.enums.LoanDetailsType;
import com.arrebol.apc.model.enums.LoanStatus;
import com.arrebol.apc.model.enums.OwnerLoan;
import com.arrebol.apc.model.enums.PeopleType;
import com.arrebol.apc.model.enums.TransferStatus;
import com.arrebol.apc.model.enums.UserType;
import com.arrebol.apc.model.loan.Loan;
import com.arrebol.apc.model.loan.LoanByUser;
import com.arrebol.apc.model.loan.LoanByUserId;
import com.arrebol.apc.model.loan.LoanDetails;
import com.arrebol.apc.model.loan.LoanFeeNotification;
import com.arrebol.apc.model.loan.LoanType;
import com.arrebol.apc.model.payroll.TotalExpectedPaymentDailyByUser;
import com.arrebol.apc.model.system.logs.Bitacora;
import com.arrebol.apc.model.views.AdvanceUserDailyDetail;
import com.arrebol.apc.model.views.AdvanceUserDailyView;
import com.arrebol.apc.model.views.CustomerView;
import com.arrebol.apc.model.views.CustomerWithoutRenovationView;
import com.arrebol.apc.model.views.LoanDetailZeroView;
import com.arrebol.apc.model.views.LoanFinishedView;
import com.arrebol.apc.model.views.TotalCashByCurdateDashboardView;
import com.arrebol.apc.model.views.TotalClosingDayByCurdateView;
import com.arrebol.apc.service.admin.CustomerService;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.chart.BarChartModel;
import org.primefaces.model.chart.PieChartModel;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named(value = "dashboardManager")
@ViewScoped
public class DashboardBean extends GenericBean implements Serializable {

   public String detailCustomer(String outcome) {
      return outcome;
   }

   public void deleteFeeLoan() {

      if (selectedLoan.getLoanStatus() == LoanStatus.APPROVED || selectedLoan.getLoanStatus() == LoanStatus.PENDING_RENOVATION) {

         List<LoanDetails> details = loanCtrl.getLoanDetailsFeeCurdatebyIdLoan(selectedLoan.getId());
         if (details != null && !details.isEmpty()) {
            Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
            Bitacora bitacora = new Bitacora();
            bitacora.setAction("Eliminar multa");
            bitacora.setCommentsUser(commentsBitacora);
            bitacora.setCreatedBy(getLoggedUser().getUser().getId());
            bitacora.setCreatedOn(new Date());
            bitacora.setNameUser(getLoggedUser().getUser().getUserName());
            bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
            BigDecimal tempMonto = BigDecimal.ZERO;
            for (LoanDetails detail : details) {
               loanUpdate.setAmountToPay(loanUpdate.getAmountToPay().subtract(detail.getPaymentAmount()));
               tempMonto = tempMonto.add(detail.getPaymentAmount());
            }
            bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
                    + "se eliminó una multa de $" + tempMonto.toString());
            if (loanCtrl.deleteLoanDetailsFeeByLoanCurdate(selectedLoan)) {
               loanCtrl.deleteLoanFeeNotificationByLoanCurdate(selectedLoan);

               Date date = new Date();
               Calendar calendar = Calendar.getInstance();
               calendar.setTime(date);
               calendar.add(Calendar.DAY_OF_YEAR, -1);
               date = calendar.getTime();
               loanUpdate.setLastUpdatedOn(date);

               loanCtrl.updateLoan(loanUpdate);
               loan.clear();
               loan = customerCtrl.findLoanByCustomer(customerId);
               bitacoraCtrl.saveBitacora(bitacora);
               commentsBitacora = "";
               selectedLoan = null;
               showMessage(FacesMessage.SEVERITY_INFO, "Multas eliminadas", "Se eliminó el/las multas del día de hoy correctamente.");
            }
         } else {
            showMessage(FacesMessage.SEVERITY_WARN, "Advertencia", "La venta no tiene registrado multas el día de hoy");
         }
      } else {
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede eliminar la multa", "Solo puedes eliminar la multa de ventas en estatus Aprobados o Pendiente por renovación");
         return;
      }

   }

   public void changeRoute() {
      if (!routeId.isEmpty()) {
         if (loanCtrl.updateRouteById(new RouteCtlg(routeId), selectedLoan.getId(), getLoggedUser().getUser().getId())) {
            showMessage(FacesMessage.SEVERITY_INFO, "Ruta modificada", "Se modificó correctamente.");
            if (loanCtrl.updatePeopleRoute(new RouteCtlg(routeId), selectedLoan.getCustomer())) {
               showMessage(FacesMessage.SEVERITY_INFO, "Cliente modificado", "Se modificó correctamente.");
            }
            if (loanCtrl.updatePeopleRoute(new RouteCtlg(routeId), selectedLoan.getEndorsement())) {
               showMessage(FacesMessage.SEVERITY_INFO, "Aval modificado", "Se modificó correctamente.");
            }
         } else {
            showMessage(FacesMessage.SEVERITY_WARN, "Ruta modificada", "Ocurrió un error durante el proceso.");
         }

      }
   }

   /**
    *
    * @param outcome
    * @return
    */
   public String detailLoan(String outcome) {
      return outcome;
   }

   /**
    *
    * @param outcome
    * @return
    */
   public String detailLoanEndorsement(String outcome) {
      return outcome;
   }

   public List<AdvanceUserDailyView> fillAdvanceUserDaily() {
      return dashboardCtrl.fillAllAdvanceUserDailyByOffice(getLoggedUser().getOffice().getId());
   }

   public void getAdvanceDetailsByUser() {
      advancesDetail = dashboardCtrl.findAllAdvancesUserDailyDetailByUser(userId);
   }

   public void getLoansByCustomer() {
      loan = customerCtrl.findLoanByCustomer(customerId);
   }

   public void getLoansJuridical() {
      String idUser = "aad0c673-eb93-11ea-b7e1-02907d0fb4e6";
      loanJuridical = customerCtrl.findLoanJuridical(idUser);
   }

   public void getLoansZero() {
      loanZero = customerCtrl.findLoanZero();
   }

   public void getLoansFinished() {
      loanFinished = customerCtrl.findLoanFinished();
   }

   public void getLoansByEndorsement() {
      loanEndorsement = endorsementCtrl.findLoanByEndorsement(endorsementId);
   }

   public List<CustomerWithoutRenovationView> findAllCustomerWithOutRenovationByOffice() {
      return dashboardCtrl.findAllCustomerWithOutRenovationByOffice(getLoggedUser().getOffice().getId());
   }

   public void getPaymentDailyExpectByUser() {
      List<User> usersTmp = genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
      if (usersTmp != null && !usersTmp.isEmpty()) {
         usersTmp.stream().filter(user -> (user.getUserType() == UserType.MOBILE && user.getCertifier() == ActiveStatus.DISABLED)).map(user -> {
            BigDecimal amountByUser = BigDecimal.valueOf(dashboardCtrl.getLoansSumPaymentDailyByUser(user.getId()));
            BigDecimal amountMoneyByUser = dashboardCtrl.getLoansSumPaymentDailyByUserMoney(user.getId());
            TotalExpectedPaymentDailyByUser expectedToday = new TotalExpectedPaymentDailyByUser();
            expectedToday.setActiveStatus(ActiveStatus.ENEBLED);
            expectedToday.setOffice(new Office(getLoggedUser().getOffice().getId()));
            expectedToday.setCreatedBy(getLoggedUser().getUser().getId());
            expectedToday.setCreatedOn(new Date());
            if (amountByUser != null) {
               expectedToday.setTotalExpected(amountByUser);
            } else {
               expectedToday.setTotalExpected(BigDecimal.ZERO);
            }
            if (amountMoneyByUser != null) {
               expectedToday.setTotalExpectedPayment(amountMoneyByUser);
            } else {
               expectedToday.setTotalExpectedPayment(BigDecimal.ZERO);
            }
            expectedToday.setUser(new User(user.getId()));
            return expectedToday;
         }).map(expectedToday -> {
            expectedToday.setLastUpdatedOn(new Date());
            return expectedToday;
         }).forEachOrdered(expectedToday -> {
            dashboardCtrl.saveTotalExpectedPaymentDailyByUser(expectedToday);
         });
      }
   }

   public void getResumenLoans() {

      totalExpectedToday = new BigDecimal(BigInteger.ONE);
      totalExpectedToday = dashboardCtrl.sumLoansApprovedByOffice(getLoggedUser().getOffice().getId());
      if (totalExpectedToday == null || totalExpectedToday == BigDecimal.ZERO) {
         totalExpectedToday = new BigDecimal(BigInteger.ONE);
      }

   }

   public void getResumenDaily() {

      List<TotalCashByCurdateDashboardView> listTotal = closingDayCtrl.getAllTotalCashByCurdateDashboardView(getLoggedUser().getOffice().getId());
      totalAmountDaily = BigDecimal.ZERO;
      totalTransferSenderDaily = BigDecimal.ZERO;
      totalTransferReceiverDaily = BigDecimal.ZERO;
      totalMoneyDailyDaily = BigDecimal.ZERO;
      totalDeliveryDaily = BigDecimal.ZERO;
      totalDepositDaily = BigDecimal.ZERO;
      totalFinalDaily = BigDecimal.ZERO;
      totalCajaDaily = BigDecimal.ZERO;
      totalOtherExpenseDaily = BigDecimal.ZERO;

      for (TotalCashByCurdateDashboardView temp : listTotal) {
         totalAmountDaily = totalAmountDaily.add(temp.getPaymentDaily());
         totalTransferSenderDaily = totalTransferSenderDaily.add(temp.getTransferSender());
         totalTransferReceiverDaily = totalTransferReceiverDaily.add(temp.getTransferReceiver());
         totalMoneyDailyDaily = totalMoneyDailyDaily.add(temp.getMoneyDaily());
         totalDeliveryDaily = totalDeliveryDaily.add(temp.getDelivery());
         totalDepositDaily = totalDepositDaily.add(temp.getDepositDaily());
         totalFinalDaily = totalFinalDaily.add(temp.getTotal());
         totalOtherExpenseDaily = totalOtherExpenseDaily.add(temp.getOtherExpense());
      }

      List<TotalClosingDayByCurdateView> closingTotal = closingDayCtrl.findAllClosingDayByCurdate(getLoggedUser().getOffice().getId());
      if (closingTotal != null && !closingTotal.isEmpty()) {
         for (TotalClosingDayByCurdateView temp : closingTotal) {
            totalCajaDaily = totalCajaDaily.add(temp.getAmountPaid());
         }
      }

   }

   public void deletePaymentLoan() {

      if (selectedLoan.getLoanStatus() == LoanStatus.APPROVED || selectedLoan.getLoanStatus() == LoanStatus.PENDING_RENOVATION) {

         List<LoanDetails> details = loanCtrl.getLoanDetailsCurdatebyIdLoan(selectedLoan.getId());
         if (details != null && !details.isEmpty()) {
            Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
            Bitacora bitacora = new Bitacora();
            bitacora.setAction("Eliminar abono");
            bitacora.setCommentsUser(commentsBitacora);
            bitacora.setCreatedBy(getLoggedUser().getUser().getId());
            bitacora.setCreatedOn(new Date());
            bitacora.setNameUser(getLoggedUser().getUser().getUserName());
            bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
            BigDecimal tempMonto = BigDecimal.ZERO;
            for (LoanDetails detail : details) {
               loanUpdate.setAmountPaid(loanUpdate.getAmountPaid().subtract(detail.getPaymentAmount()));
               loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() - 1);
               tempMonto = tempMonto.add(detail.getPaymentAmount());
            }
            bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
                    + "se eliminó un abono de $" + tempMonto.toString());
            if (loanCtrl.deleteLoanDetailsByLoanCurdate(selectedLoan)) {
               Date date = new Date();
               Calendar calendar = Calendar.getInstance();
               calendar.setTime(date);
               calendar.add(Calendar.DAY_OF_YEAR, -1);
               date = calendar.getTime();
               loanUpdate.setLastUpdatedOn(date);

               loanCtrl.updateLoan(loanUpdate);
               loan.clear();
               loan = customerCtrl.findLoanByCustomer(customerId);
               selectedLoan = null;
               bitacoraCtrl.saveBitacora(bitacora);
               commentsBitacora = "";
               showMessage(FacesMessage.SEVERITY_INFO, "Abonos eliminados", "Se eliminó el/los abonos del día de hoy correctamente.");
            }
         } else {
            showMessage(FacesMessage.SEVERITY_WARN, "Advertencia", "La venta no tiene registrado abonos el día de hoy");
         }
      } else {
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede eliminar abono", "Solo puedes eliminar el abono de ventas en estatus Aprobados o Pendiente por renovación");
         return;
      }

   }

   public void deleteLoan() {
      Bitacora bitacora = new Bitacora();
      Loan temp = loanCtrl.getLoanById(selectedLoan.getId());
      bitacora.setAction("Eliminar venta");
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(new Date());
      bitacora.setDescription("La venta del cliente " + temp.getCustomer().getFullName() + " del asesor " + temp.getAsesor() + " con monto a vender de $" + temp.getLoanType().getPayment() + " se cambió a estatus 'Eliminado' ");
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
      loanCtrl.updateLoanByStatusWeb(LoanStatus.DELETED, selectedLoan.getId(), getLoggedUser().getUser().getId());
      loanCtrl.updateLoanByUserByStatus(LoanStatus.DELETED, selectedLoan);
      loan.remove(selectedLoan);
      selectedLoan = null;
      bitacoraCtrl.saveBitacora(bitacora);
      commentsBitacora = "";

      showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "La venta se cambió a estatus 'Eliminado' de forma correcta.");
   }

   public void changeApprovedStatus() {
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      Bitacora bitacora = new Bitacora();
      bitacora.setAction("Cambio de estatus a aprobado");
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(new Date());
      bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
              + "se cambia a estatus Aprobado");
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
      loanCtrl.updateLoanByStatusWeb(LoanStatus.APPROVED, selectedLoan.getId(), getLoggedUser().getUser().getId());
      loanCtrl.updateLoanByUserByStatus(LoanStatus.APPROVED, selectedLoan);
      loan.clear();
      bitacoraCtrl.saveBitacora(bitacora);
      commentsBitacora = "";
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "La venta se cambió a estatus 'Aprobado' de forma correcta.");
   }

   public void changeBonusNewCustomer() {
      loanCtrl.updateBonusNewCustomer(ActiveStatus.ENEBLED, selectedLoan.getId(), getLoggedUser().getUser().getId());
      loan.clear();
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Cambio de bono", "La venta empezó a contar como bono de cliente nuevo.");
   }

   public void cargarBoletaPagos() {
      CustomerView clienteViewBoleta = customerCtrl.findCustomerViewByPeopleId(selectedLoan.getCustomer().getId());
      People clienteBoleta = peopleCtrl.findPeopleById(selectedLoan.getCustomer().getId());
      LoanByUser loanUser = loanCtrl.getLoanByUserByIdLoan(selectedLoan);
      String nombreVendedor = "";
      if (loanUser != null) {
         nombreVendedor = loanUser.getUser().getUserName();
      }
      String pagos = "";
      for (int i = 0; i < 50; i++) {
         pagos = pagos
                 + "            <tr>\n"
                 + "                <td></td>\n"
                 + "                <td></td>\n"
                 + "                <td></td>\n"
                 + "                <td></td>\n"
                 + "                <td></td>\n"
                 + "                <td></td>\n"
                 + "            </tr>";
      }

      String html = "<style>\n"
              + "        .platilla {\n"
              + "            font-family: Arial, sans-serif;\n"
              + "            margin: 5px auto;\n"
              + "            max-width: 1200px;\n"
              + "            padding: 0 7px;\n"
              + "        }\n"
              + "        \n"
              + "        .platilla h1, h2 {\n"
              + "            font-size: 26px;\n"
              + "        }\n"
              + "\n"
              + "        .section {\n"
              + "            margin-bottom: 10px;\n"
              + "            border-bottom: 1px solid #ccc;\n"
              + "            padding-bottom: 10px;\n"
              + "        }\n"
              + "        \n"
              + "        h3 {\n"
              + "           font-size: 22px;\n"
              + "           margin-bottom: 1px;\n"
              + "           margin-top: 1px;\n"
              + "        }\n"
              + "\n"
              + "        .row {\n"
              + "            display: flex;\n"
              + "            flex-wrap: wrap;\n"
              + "            gap: 5px 10px;\n"
              + "            margin-bottom: 2px;\n"
              + "            font-size: 20px;\n"
              + "        }\n"
              + "\n"
              + "        .field {\n"
              + "            display: flex;\n"
              + "            align-items: baseline;\n"
              + "            min-width: 300px;\n"
              + "            flex: 1 1 40%;\n"
              + "            margin-bottom: 5px;\n"
              + "        }\n"
              + "\n"
              + "        .label {\n"
              + "            font-weight: bold;\n"
              + "            min-width: 115;\n"
              + "            color: #2c3e50;\n"
              + "            margin-right: 5px;\n"
              + "            flex-shrink: 0;\n"
              + "        }\n"
              + "\n"
              + "        .value {\n"
              + "            word-break: break-word;\n"
              + "            flex-grow: 1;\n"
              + "        }\n"
              + "\n"
              + "        table {\n"
              + "            border-collapse: collapse;\n"
              + "            margin-top: 2px;\n"
              + "            width: 100%;\n"
              + "            font-size: 20px;\n"
              + "        }\n"
              + "\n"
              + "        td,\n"
              + "        th {\n"
              + "            border: 1px solid #ddd;\n"
              + "            padding: 16px;\n"
              + "            text-align: left;\n"
              + "        }\n"
              + "\n"
              + "        textarea {\n"
              + "            width: 100%;\n"
              + "            min-height: 50px;\n"
              + "            padding: 10px;\n"
              + "            resize: vertical;\n"
              + "        }\n"
              + "\n"
              + "        @media (max-width: 768px) {\n"
              + "            .field {\n"
              + "                flex: 1 1 100%;\n"
              + "                min-width: auto;\n"
              + "            }\n"
              + "\n"
              + "            .label {\n"
              + "                min-width: 120px;\n"
              + "                font-size: 0.9em;\n"
              + "            }\n"
              + "        }\n"
              + "        \n"
              + "        .salto-pagina {\n"
              + "            page-break-after: always;\n"
              + "        }\n"
              + "           @page {\n"
              + "        size: 12in 21in; /* Ancho x Alto */\n"
              + "        margin: 1cm; \n"
              + "    }\n"
              + "    @media print {\n"
              + "        body {\n"
              + "            margin: 1cm;\n"
              + "            padding: 0;\n"
              + "        }\n"
              + "        .contenido-impresion {\n"
              + "            width: 12in;\n"
              + "            height: 21in;\n"
              + "        }\n"
              + "    }"
              + "    </style>"
              + "</head>\n"
              + "\n"
              + "<div class=\"platilla\">\n"
              + "    <h1>" + clienteBoleta.getContrato() + " - " + clienteViewBoleta.getRouteName() + "</h1>\n"
              + "    <h2>" + clienteBoleta.getFullName() + "</h2>\n"
              + "\n"
              + "   <div class=\"section\">\n"
              + "         <h3>Datos del Cliente</h3>\n"
              + "         <div class=\"row\">\n"
              + "             <div class=\"label\">Dirección completa:</div>\n"
              + "             <div class=\"value\">" + clienteBoleta.getAddressHome() + "</div>\n"
              + "         </div>\n"
              + "         <div class=\"row\">\n"
              + "             <div class=\"label\">Colonia/Municipio:</div>\n"
              + "             <div class=\"value\">" + clienteBoleta.getPersonalColonia() + "</div>\n"
              + "             <div class=\"label\">Entre calles:</div>\n"
              + "             <div class=\"value\">" + clienteBoleta.getPersonalCruzamientos() + "</div>\n"
              + "             <div class=\"label\">Ciudad:</div>\n"
              + "             <div class=\"value\">" + clienteBoleta.getPersonalCiudad() + "</div>\n"
              + "         </div>\n"
              + "         <div class=\"row\">\n"
              + "             <div class=\"label\">Teléfono/Celular:</div>\n"
              + "             <div class=\"value\">" + clienteBoleta.getPersonalCelular() + "</div>\n"
              + "         </div>\n"
              + "     </div>"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <h3>Características del Domicilio</h3>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Fachada:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaDecisionFachada() + "</div>\n"
              + "            <div class=\"label\">PUERTA:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaDescripcionPuerta() + "</div>\n"
              + "            <div class=\"label\">VENTANA:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaDescripcionVentanas() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">FRENTE A NÚM:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaFrenteNumero() + "</div>\n"
              + "            <div class=\"label\">ENTRE NÚM:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaEntreNumero1() + "</div>\n"
              + "            <div class=\"label\">Y NÚM:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaEntreNumero2() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Señas especiales:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getFachadaSenasVivienda() + "</div>\n"
              + "        </div>\n"
              + "    </div>\n"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <h3>TRABAJO</h3>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Trabajo:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajo() + "</div>\n"
              + "            <div class=\"label\">Domicilio:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoDomicilio() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">ENTRE:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoCruzamientos() + "</div>\n"
              + "            <div class=\"label\">CD:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoCiudad() + "</div>\n"
              + "            <div class=\"label\">COL:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoColonia() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">TEL.1:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoTelefono1() + "</div>\n"
              + "            <div class=\"label\">EXT:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoTelefonoExtra1() + "</div>\n"
              + "            <div class=\"label\">TEL.2:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoTelefono2() + "</div>\n"
              + "            <div class=\"label\">EXT:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoTelefonoExtra2() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">TURNO:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoTurno() + "</div>\n"
              + "            <div class=\"label\">DEPARTAMENTO:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getTrabajoDepartamento() + "</div>\n"
              + "        </div>\n"
              + "    </div>\n"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <div class=\"sub-section\">\n"
              + "            <h3>Referencia 1</h3>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">Nombre:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Nombre() + "</div>\n"
              + "                <div class=\"label\">PARENTESCO:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Parentesco() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">DOM:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Domicilio() + "</div>\n"
              + "                <div class=\"label\">COL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Colonia() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">CRUZA:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Cruzamientos() + "</div>\n"
              + "                <div class=\"label\">CD:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1Ciudad() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">TEL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1TelefonoParticular() + "</div>\n"
              + "                <div class=\"label\">CEL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1CelularParticular() + "</div>\n"
              + "                <div class=\"label\">TEL. TRA:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1TelefonoTrabajo() + "</div>\n"
              + "                <div class=\"label\">EXT:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia1ExtraTelefonoTrabajo() + "</div>\n"
              + "            </div>\n"
              + "        </div>\n"
              + "\n"
              + "        <div class=\"sub-section\">\n"
              + "            <h3>Referencia 2</h3>\n"
              + "             <div class=\"row\">\n"
              + "                <div class=\"label\">Nombre:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Nombre() + "</div>\n"
              + "                <div class=\"label\">PARENTESCO:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Parentesco() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">DOM:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Domicilio() + "</div>\n"
              + "                <div class=\"label\">COL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Colonia() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">CRUZA:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Cruzamientos() + "</div>\n"
              + "                <div class=\"label\">CD:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2Ciudad() + "</div>\n"
              + "            </div>\n"
              + "            <div class=\"row\">\n"
              + "                <div class=\"label\">TEL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2TelefonoParticular() + "</div>\n"
              + "                <div class=\"label\">CEL:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2CelularParticular() + "</div>\n"
              + "                <div class=\"label\">TEL. TRA:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2TelefonoTrabajo() + "</div>\n"
              + "                <div class=\"label\">EXT:</div>\n"
              + "                <div class=\"value\">" + clienteBoleta.getReferencia2ExtraTelefonoTrabajo() + "</div>\n"
              + "            </div>\n"
              + "        </div>\n"
              + "    </div>\n"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <h3>Datos del Crédito</h3>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">COBRAR EN:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getDatosCreditoCobrarEn() + "</div>\n"
              + "            <div class=\"label\">ENTREGADO EN:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getDatosCreditoEntradaEn() + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Fecha de compra:</div>\n"
              + "            <div class=\"value\">" + formatDate(clienteBoleta.getDatosCreditoFechaCompra()) + "</div>\n"
              + "            <div class=\"label\">Primer pago:</div>\n"
              + "            <div class=\"value\">" + formatDate(clienteBoleta.getDatosCreditoPrimerPago()) + "</div>\n"
              + "            <div class=\"label\">Vence:</div>\n"
              + "            <div class=\"value\">" + calcularUltimoPago(clienteBoleta.getDatosCreditoPrimerPago(), clienteBoleta.getDatosCreditoNumeroPagos() == null ? 0 : clienteBoleta.getDatosCreditoNumeroPagos(), clienteBoleta.getDatosCreditoFormaPago() == null ? null : clienteBoleta.getDatosCreditoFormaPago().toString()) + "</div>\n"
              + "        </div>\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Vendedor:</div>\n"
              + "            <div class=\"value\">" + nombreVendedor + "</div>\n"
              + "            <div class=\"label\">Forma de pago:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getDatosCreditoFormaPago() + "</div>\n"
              + "        </div>\n"
              + "\n"
              + "        <div class=\"row\">\n"
              + "            <div class=\"label\">Investigación crediticia:</div>\n"
              + "            <div class=\"value\"></div>\n"
              + "            <div class=\"label\">Monto por pago:</div>\n"
              + "            <div class=\"value\">" + clienteBoleta.getDatosCreditoPagosDe() + "</div>\n"
              + "        </div>\n"
              + "    </div>\n"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <h3>Observación de pago:</h3>\n"
              + "        <div class=\"row\">\n"
              + "            <textarea style=\"width:100%; height:200px; padding:10px\" disabled=\"true\"></textarea>\n"
              + "        </div>\n"
              + "    </div>\n"
              + "\n"
              + "    <h3>Compra</h3>\n"
              + "    <table>\n"
              + "        <tr>\n"
              + "            <th>Cant</th>\n"
              + "            <th>Artículo</th>\n"
              + "            <th>Precio</th>\n"
              + "            <th>Importe</th>\n"
              + "        </tr>\n"
              + "        <tr>\n"
              + "            <td>1</td>\n"
              + "            <td>" + selectedLoan.getLoanType().getLoanTypeName() + "</td>\n"
              + "            <td>" + selectedLoan.getLoanType().getPayment() + "</td>\n"
              + "            <td>" + selectedLoan.getLoanType().getPayment() + "</td>\n"
              + "        </tr>\n"
              + "    </table>\n"
              + "\n"
              + "    <div class=\"row\" style=\"margin-top:15px; font-size:1.1em\">\n"
              + "        <div class=\"label\">Total de la compra:</div>\n"
              + "        <div class=\"value\">" + selectedLoan.getLoanType().getPaymentTotal() + "</div>\n"
              + "    </div>\n"
              + "\n"
              + "    <div class=\"section\">\n"
              + "        <h3>Apuntes del Cobrador</h3>\n"
              + "        <textarea style=\"width:100%; height:200px; padding:10px\" disabled=\"true\"></textarea>\n"
              + "    </div>\n"
              + "    <div class=\"salto-pagina\"></div>\n"
              + "    <div class=\"section\">\n"
              + "        <h3>PAGOS</h3>\n"
              + "        <table>\n"
              + "            <tr>\n"
              + "                <th>FECHA</th>\n"
              + "                <th>FOLIO</th>\n"
              + "                <th>CONCEPTO</th>\n"
              + "                <th>CARGOS</th>\n"
              + "                <th>ABONOS</th>\n"
              + "                <th>SALDO</th>\n"
              + "            </tr>\n"
              + pagos
              + "        </table>\n"
              + "    </div>"
              + "</div>";

      html = html.replaceAll("\\bnull\\b", " ");
      setPlantillaHTML(html);
   }

   public static String formatDate(Date date) {
      if (date == null) {
         return null; // Evita NullPointerException
      }
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); // Puedes cambiar el formato
      return formatter.format(date);
   }

   public void main(String[] args) {
      Date today = new Date();
      System.out.println("Fecha formateada: " + formatDate(today));
   }

   public static String calcularUltimoPago(Date fechaInicio, int numeroPagos, String periodoPago) {
      if (fechaInicio == null || numeroPagos <= 0 || periodoPago == null) {
         return "NA";
      }
      LocalDate fechaInicioLocal = fechaInicio.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
      int diasAIncrementar;
      switch (periodoPago.toUpperCase()) {
         case "SEMANAL":
            diasAIncrementar = 7;
            break;
         case "QUINCENAL":
            diasAIncrementar = 15;
            break;
         case "MENSUAL":
            LocalDate fechaUltimoPagoMes = fechaInicioLocal.plusMonths(numeroPagos - 1);
            return formatDate(fechaUltimoPagoMes);
         default:
            throw new IllegalArgumentException("Periodo de pago no válido");
      }
      LocalDate fechaUltimoPago = fechaInicioLocal.plusDays(diasAIncrementar * (numeroPagos - 1));
      return formatDate(fechaUltimoPago);
   }

   private static String formatDate(LocalDate date) {
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
      return formatter.format(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
   }

   public void removeBonusNewCustomer() {
      loanCtrl.updateBonusNewCustomer(ActiveStatus.DISABLED, selectedLoan.getId(), getLoggedUser().getUser().getId());
      loan.clear();
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Cambio de bono", "La venta ya no contará como bono de cliente nuevo.");
   }

   public void updateReleaseDate() {
      SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
      Date date = new Date();
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      loanUpdate.setCreatedOn(date);
      loanCtrl.updateLoan(loanUpdate);
      Bitacora bitacora = new Bitacora();
      bitacora.setAction("Cambio de fecha de liberación a " + sdf.format(date));
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(date);
      bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName()
              + " del asesor " + loanUpdate.getAsesor()
              + " con monto a vender de $" + loanUpdate.getLoanType().getPayment()
              + " cambia a fecha de liberación del día de hoy " + sdf.format(date));
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
      loan.clear();
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Fecha de liberación", "Se actualizó la fecha de liberación al día de hoy " + sdf.format(date));
   }

   public void allowRenew() {
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      loanCtrl.deleteLoanFeeNotificationByLoan(loanUpdate);
      Bitacora bitacora = new Bitacora();
      bitacora.setAction("Se eliminan las multas dla venta " + selectedLoan.getId());
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(new Date());
      bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName()
              + " del asesor " + loanUpdate.getAsesor()
              + " con monto a vender de $" + loanUpdate.getLoanType().getPayment()
              + " se eliminaron las multas");
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
      loan.clear();
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Multas eliminadas", "Se eliminó la/las multas dla venta correctamente.");
   }

   public void changeFrozenStatus(boolean freeze) {
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      Bitacora bitacora = new Bitacora();
      if (freeze) {
         bitacora.setAction("Cambio de estatus a congelado");
         bitacora.setCommentsUser(commentsBitacora);
         bitacora.setCreatedBy(getLoggedUser().getUser().getId());
         bitacora.setCreatedOn(new Date());
         bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
                 + "se cambia a estatus Congelado");
         bitacora.setNameUser(getLoggedUser().getUser().getUserName());
         bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));

         loanUpdate.setFrozen(ActiveStatus.ENEBLED);
         loanCtrl.updateLoan(loanUpdate);

         showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "La venta se cambió a estatus 'Congelado' de forma correcta.");
      } else {
         bitacora.setAction("Cambio de estatus a descongelado");
         bitacora.setCommentsUser(commentsBitacora);
         bitacora.setCreatedBy(getLoggedUser().getUser().getId());
         bitacora.setCreatedOn(new Date());
         bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
                 + "se cambia a estatus Desongelado");
         bitacora.setNameUser(getLoggedUser().getUser().getUserName());
         bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));

         loanUpdate.setFrozen(ActiveStatus.DISABLED);
         loanCtrl.updateLoan(loanUpdate);

         showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "La venta se cambió a estatus 'Descongelado' de forma correcta.");
      }

      loan.clear();
      bitacoraCtrl.saveBitacora(bitacora);
      commentsBitacora = "";
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;
   }

   public void changeFinishStatus() {
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      Bitacora bitacora = new Bitacora();
      bitacora.setAction("Cambio de estatus a finalizado");
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(new Date());
      bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
              + "se cambia a estatus Finalizado");
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
      loanCtrl.updateLoanByStatusWeb(LoanStatus.FINISH, selectedLoan.getId(), getLoggedUser().getUser().getId());
      loanCtrl.updateLoanByUserByStatus(LoanStatus.FINISH, selectedLoan);
      loan.clear();
      bitacoraCtrl.saveBitacora(bitacora);
      commentsBitacora = "";
      loan = customerCtrl.findLoanByCustomer(customerId);
      selectedLoan = null;

      showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "La venta se cambió a estatus 'Terminado' de forma correcta.");
   }

   public void changeOwner() {
      /*if (selectedLoan.getLoanStatus() != LoanStatus.APPROVED) {
            selectedLoan = null;
            userId = "";
            showMessage(FacesMessage.SEVERITY_WARN, "No se puede modificar propietario", "Solo puedes cambiar de propietario a ventas en estatus Aprobados");
            return;
        }*/
      LoanByUser old = new LoanByUser();
      old = loanCtrl.getLoanByUserByIdLoan(selectedLoan);

      LoanByUser loanByUser = new LoanByUser();
      LoanByUserId idRelation = new LoanByUserId();

      idRelation.setIdLoan(selectedLoan.getId());
      idRelation.setIdUser(userId);

      loanByUser.setId(idRelation);
      loanByUser.setComments(old.getComments());
      loanByUser.setCreatedBy(old.getCreatedBy());
      loanByUser.setLoanByUserStatus(old.getLoanByUserStatus());
      loanByUser.setLoan(selectedLoan);
      loanByUser.setCreatedOn(new Date());
      loanByUser.setOrderInList(old.getOrderInList());
      loanByUser.setOwnerLoan(OwnerLoan.CURRENT_OWNER);
      loanByUser.setUser(new User(userId));
      if (loanCtrl.deleteLoanByUser(old)) {
         loanCtrl.saveLoanByUser(loanByUser);
         selectedLoan = null;
         userId = "";
         loan.clear();
         loan = customerCtrl.findLoanByCustomer(customerId);
         showMessage(FacesMessage.SEVERITY_INFO, "Cambio de propietario", "Se reasignó la venta de forma correcta.");
      } else {
         selectedLoan = null;
         showMessage(FacesMessage.SEVERITY_ERROR, "Cambio de propietario", "Ocurrió un error al intentar hacer el cambio de propietario.");
      }
   }

   public void changeOwnerToJuridical() {
      // Id de usuario laura.marquez
      String idUser = "aad0c673-eb93-11ea-b7e1-02907d0fb4e6";
//         String idUser = "3338ce43-24fc-4d35-b51e-d8ec848937fc";

      Loan loanUpdate = selectedLoanJuridical;
      loanUpdate.setJuridicalDate(new Date());

      loanCtrl.updateLoan(loanUpdate);

      LoanByUser old = new LoanByUser();
      old = loanCtrl.getLoanByUserByIdLoan(selectedLoanJuridical);

      LoanByUser loanByUser = new LoanByUser();
      LoanByUserId idRelation = new LoanByUserId();

      idRelation.setIdLoan(selectedLoanJuridical.getId());
      idRelation.setIdUser(idUser);

      loanByUser.setId(idRelation);
      loanByUser.setComments(old.getComments());
      loanByUser.setCreatedBy(old.getCreatedBy());
      loanByUser.setLoanByUserStatus(old.getLoanByUserStatus());
      loanByUser.setLoan(selectedLoanJuridical);
      loanByUser.setCreatedOn(new Date());
      loanByUser.setOrderInList(old.getOrderInList());
      loanByUser.setOwnerLoan(OwnerLoan.CURRENT_OWNER);
      loanByUser.setUser(new User(idUser));
      if (loanCtrl.deleteLoanByUser(old)) {
         loanCtrl.saveLoanByUser(loanByUser);
         selectedLoanJuridical = null;
         loanJuridical.clear();
         getLoansJuridical();
         showMessage(FacesMessage.SEVERITY_INFO, "Cambio de propietario", "Se mandó la venta a jurídico.");
      } else {
         selectedLoan = null;
         showMessage(FacesMessage.SEVERITY_ERROR, "Cambio de propietario", "Ocurrió un error al intentar hacer el cambio de propietario.");
      }

      selectedLoanJuridical = null;
   }

   public void addPayment() {
      if (selectedLoan.getLoanStatus() == LoanStatus.APPROVED || selectedLoan.getLoanStatus() == LoanStatus.PENDING_RENOVATION) {
         LoanDetails detail = new LoanDetails();
         detail.setComments(comments);
         detail.setCreatedBy(getLoggedUser().getUser().getId());
         detail.setCreatedOn(new Date());
         detail.setLoan(selectedLoan);
         detail.setLoanDetailsType(LoanDetailsType.PAYMENT);
         detail.setPaymentAmount(payment);
         detail.setPeopleType(PeopleType.CUSTOMER);
         detail.setTransferStatus(TransferStatus.AUTHORIZED);
         detail.setTransferNumber("N/A");
         detail.setReferenceNumber(selectedLoan.getLastReferenceNumber() + 1);
         detail.setUser(new User(userId));
         if (loanCtrl.saveLoanDetail(detail)) {
            Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
            loanUpdate.setAmountPaid(loanUpdate.getAmountPaid().add(payment));
            loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() + 1);
            if (loanUpdate.getAmountToPay().compareTo(loanUpdate.getAmountPaid()) == 0) {

               LoanByUser loanByUser = loanCtrl.getLoanByUserByIdLoan(loanUpdate);
               loanByUser.setLoanByUserStatus(LoanStatus.FINISH);
               if (loanCtrl.updateLoanByUser(loanByUser)) {
                  loanUpdate.setLoanStatus(LoanStatus.FINISH);
               }
            }
            loanCtrl.updateLoan(loanUpdate);
            loan.clear();
            loan = customerCtrl.findLoanByCustomer(customerId);
            selectedLoan = null;
            userId = "";
            comments = "";
            payment = BigDecimal.ZERO;
            showMessage(FacesMessage.SEVERITY_INFO, "Agregar abono", "Se agregó el abono de forma correcta.");
         }
      } else {
         selectedLoan = null;
         userId = "";
         comments = "";
         payment = BigDecimal.ZERO;
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede abonar", "Solo puedes abonar ventas en estatus Aprobados o Pendientes por renovación");
         return;
      }

   }

   public void addDeposit() {
      if (selectedLoan.getLoanStatus() == LoanStatus.APPROVED || selectedLoan.getLoanStatus() == LoanStatus.PENDING_RENOVATION) {
         LoanDetails detail = new LoanDetails();
         detail.setComments(comments);
         detail.setCreatedBy(getLoggedUser().getUser().getId());
         detail.setCreatedOn(new Date());
         detail.setLoan(selectedLoan);
         detail.setLoanDetailsType(LoanDetailsType.TRANSFER);
         detail.setPaymentAmount(payment);
         detail.setPeopleType(PeopleType.CUSTOMER);
         detail.setTransferStatus(TransferStatus.PENDING);
         detail.setTransferNumber("N/A");
         detail.setReferenceNumber(selectedLoan.getLastReferenceNumber() + 1);
         detail.setUser(new User(userId));
         if (loanCtrl.saveLoanDetail(detail)) {
            Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
            loanUpdate.setAmountPaid(loanUpdate.getAmountPaid().add(payment));
            loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() + 1);
            if (loanUpdate.getAmountToPay().compareTo(loanUpdate.getAmountPaid()) == 0) {

               LoanByUser loanByUser = loanCtrl.getLoanByUserByIdLoan(loanUpdate);
               loanByUser.setLoanByUserStatus(LoanStatus.FINISH);
               if (loanCtrl.updateLoanByUser(loanByUser)) {
                  loanUpdate.setLoanStatus(LoanStatus.FINISH);
               }
            }
            loanCtrl.updateLoan(loanUpdate);
            loan.clear();
            loan = customerCtrl.findLoanByCustomer(customerId);
            selectedLoan = null;
            userId = "";
            comments = "";
            payment = BigDecimal.ZERO;
            showMessage(FacesMessage.SEVERITY_INFO, "Agregar depósito", "Se agregó el depósito de forma correcta.");
         }
      } else {
         selectedLoan = null;
         userId = "";
         comments = "";
         payment = BigDecimal.ZERO;
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede abonar", "Solo puedes abonar ventas en estatus Aprobados o Pendientes por renovación");
         return;
      }

   }

   public void addFee() {
      if (selectedLoan.getLoanStatus() != LoanStatus.APPROVED) {
         selectedLoan = null;
         userId = "";
         comments = "";
         fee = BigDecimal.ZERO;
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede multar", "Solo puedes multar ventas en estatus Aprobados");
         return;
      }
      LoanDetails detail = new LoanDetails();
      detail.setComments(comments);
      detail.setCreatedBy(getLoggedUser().getUser().getId());
      detail.setCreatedOn(new Date());
      detail.setLoan(selectedLoan);
      detail.setLoanDetailsType(LoanDetailsType.FEE);
      detail.setPaymentAmount(fee);
      detail.setPeopleType(PeopleType.CUSTOMER);
      detail.setTransferStatus(TransferStatus.AUTHORIZED);
      detail.setTransferNumber("N/A");
      detail.setFeeStatus(FeeStatus.TO_PAY);
      detail.setReferenceNumber(selectedLoan.getLastReferenceNumber() + 1);
      detail.setUser(new User(userId));
      if (loanCtrl.saveLoanDetail(detail)) {
         Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
         loanUpdate.setAmountToPay(loanUpdate.getAmountToPay().add(fee));
         loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() + 1);
         loanCtrl.updateLoan(loanUpdate);

         LoanFeeNotification notification = new LoanFeeNotification();
         notification.setCreatedBy(getLoggedUser().getUser().getId());
         notification.setCreatedOn(new Date());
         notification.setLoan(loanUpdate);
         notification.setUser(new User(userId));
         notification.setNotificationNumber(loanUpdate.getTotalFeeByLoan() + 1);
         loanCtrl.saveLoanNotificationFee(notification);

         loan.clear();
         loan = customerCtrl.findLoanByCustomer(customerId);
         selectedLoan = null;
         userId = "";
         comments = "";
         fee = BigDecimal.ZERO;
         showMessage(FacesMessage.SEVERITY_INFO, "Agregar multa", "Se agregó la multa de forma correcta.");
      }
   }

   public void changeLoanType() {
      if (selectedLoan.getLoanStatus() != LoanStatus.TO_DELIVERY && selectedLoan.getLoanStatus() != LoanStatus.APPROVED) {
         loanTypeId = "";
         selectedLoan = null;
         showMessage(FacesMessage.SEVERITY_WARN, "No se puede cambiar el tipo de venta", "Solo puedes cambiar el monto a vender de ventas en estatus Por liberar");
         return;
      }
      Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
      LoanType loanTypeUpdate = loanTypeCtrl.getLoanTypeById(loanTypeId);
      Bitacora bitacora = new Bitacora();
      bitacora.setAction("Cambio de monto de venta");
      bitacora.setCommentsUser(commentsBitacora);
      bitacora.setCreatedBy(getLoggedUser().getUser().getId());
      bitacora.setCreatedOn(new Date());
      bitacora.setDescription("La venta del cliente " + loanUpdate.getCustomer().getFullName() + " del asesor " + loanUpdate.getAsesor() + " con monto a vender de $" + loanUpdate.getLoanType().getPayment() + " "
              + "se cambia a monto de venta por " + loanTypeUpdate.getLoanTypeName());
      bitacora.setNameUser(getLoggedUser().getUser().getUserName());
      bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));

      loanUpdate.setLoanType(new LoanType(loanTypeId));
      loanUpdate.setAmountToPay(loanTypeUpdate.getPaymentTotal());
      if (loanCtrl.updateLoan(loanUpdate)) {
         loan.clear();
         loan = customerCtrl.findLoanByCustomer(customerId);
         loanTypeId = "";
         bitacoraCtrl.saveBitacora(bitacora);
         commentsBitacora = "";
         selectedLoan = null;
         showMessage(FacesMessage.SEVERITY_INFO, "Cambio de tipo de venta", "La venta se cambió correctamente");
      }

   }

   public void CustomerClassification(String colorClassification) {
      try {
         customerService.updatePeopleByClassification(CustomerClassification.valueOf(colorClassification), getSelectedLoanFinished().getCustomerId(), getLoggedUser().getUser().getId());

         showMessage(FacesMessage.SEVERITY_INFO, "Cliente", "Se clasificó correctamente.");
      } catch (Exception e) {
         showMessage(FacesMessage.SEVERITY_ERROR, "Cliente", "No se clasificó correctamente.");
      }
   }

   public ClosingDayController getClosingDayCtrl() {
      return closingDayCtrl;
   }

   public void setClosingDayCtrl(ClosingDayController closingDayCtrl) {
      this.closingDayCtrl = closingDayCtrl;
   }

   public DashboardController getDashboardCtrl() {
      return dashboardCtrl;
   }

   public void setDashboardCtrl(DashboardController dashboardCtrl) {
      this.dashboardCtrl = dashboardCtrl;
   }

   public BigDecimal getTotalAmountDaily() {
      return totalAmountDaily;
   }

   public void setTotalAmountDaily(BigDecimal totalAmountDaily) {
      this.totalAmountDaily = totalAmountDaily;
   }

   public BigDecimal getTotalTransferSenderDaily() {
      return totalTransferSenderDaily;
   }

   public void setTotalTransferSenderDaily(BigDecimal totalTransferSenderDaily) {
      this.totalTransferSenderDaily = totalTransferSenderDaily;
   }

   public BigDecimal getTotalTransferReceiverDaily() {
      return totalTransferReceiverDaily;
   }

   public void setTotalTransferReceiverDaily(BigDecimal totalTransferReceiverDaily) {
      this.totalTransferReceiverDaily = totalTransferReceiverDaily;
   }

   public BigDecimal getTotalMoneyDailyDaily() {
      return totalMoneyDailyDaily;
   }

   public void setTotalMoneyDailyDaily(BigDecimal totalMoneyDailyDaily) {
      this.totalMoneyDailyDaily = totalMoneyDailyDaily;
   }

   public BigDecimal getTotalDeliveryDaily() {
      return totalDeliveryDaily;
   }

   public void setTotalDeliveryDaily(BigDecimal totalDeliveryDaily) {
      this.totalDeliveryDaily = totalDeliveryDaily;
   }

   public BigDecimal getTotalFinalDaily() {
      return totalFinalDaily;
   }

   public void setTotalFinalDaily(BigDecimal totalFinalDaily) {
      this.totalFinalDaily = totalFinalDaily;
   }

   public BigDecimal getTotalCajaDaily() {
      return totalCajaDaily;
   }

   public void setTotalCajaDaily(BigDecimal totalCajaDaily) {
      this.totalCajaDaily = totalCajaDaily;
   }

   public int getNumPending() {
      return numPending;
   }

   public void setNumPending(int numPending) {
      this.numPending = numPending;
   }

   public int getNumApproved() {
      return numApproved;
   }

   public void setNumApproved(int numApproved) {
      this.numApproved = numApproved;
   }

   public int getNumFinish() {
      return numFinish;
   }

   public void setNumFinish(int numFinish) {
      this.numFinish = numFinish;
   }

   public int getNumRejected() {
      return numRejected;
   }

   public void setNumRejected(int numRejected) {
      this.numRejected = numRejected;
   }

   public int getNumToDelivery() {
      return numToDelivery;
   }

   public void setNumToDelivery(int numToDelivery) {
      this.numToDelivery = numToDelivery;
   }

   public BigDecimal getTotalExpectedToday() {
      return totalExpectedToday;
   }

   public void setTotalExpectedToday(BigDecimal totalExpectedToday) {
      this.totalExpectedToday = totalExpectedToday;
   }

   public LoanController getLoanCtrl() {
      return loanCtrl;
   }

   public void setLoanCtrl(LoanController loanCtrl) {
      this.loanCtrl = loanCtrl;
   }

   public PieChartModel getLivePieModel() {

      livePieModel.getData().put("Total cobrado", totalAmountDaily);
      livePieModel.getData().put("Total esperado por cobro", totalExpectedToday.subtract(totalAmountDaily));

      livePieModel.setTitle("Gráfica de recuperación diaria");
      livePieModel.setLegendPosition("ne");

      return livePieModel;
   }

   public void setLivePieModel(PieChartModel livePieModel) {
      this.livePieModel = livePieModel;
   }

   public PieChartModel getPieResumenCaja() {
      pieResumenCaja.getData().put("Total del día", totalFinalDaily.subtract(totalCajaDaily));
      pieResumenCaja.getData().put("Total en caja", totalCajaDaily);

      pieResumenCaja.setTitle("Gráfica de recuperación en caja");
      pieResumenCaja.setLegendPosition("ne");

      return pieResumenCaja;
   }

   public void setPieResumenCaja(PieChartModel pieResumenCaja) {
      this.pieResumenCaja = pieResumenCaja;
   }

   public BarChartModel getBarResumenLoans() {
      return barResumenLoans;
   }

   public void setBarResumenLoans(BarChartModel barResumenLoans) {
      this.barResumenLoans = barResumenLoans;
   }

   public BigDecimal getTotalOtherExpenseDaily() {
      return totalOtherExpenseDaily;
   }

   public void setTotalOtherExpenseDaily(BigDecimal totalOtherExpenseDaily) {
      this.totalOtherExpenseDaily = totalOtherExpenseDaily;
   }

   public GenericController getGenericCtrl() {
      return genericCtrl;
   }

   public void setGenericCtrl(GenericController genericCtrl) {
      this.genericCtrl = genericCtrl;
   }

   public List<AdvanceUserDailyView> getAdvances() {
      return advances;
   }

   public void setAdvances(List<AdvanceUserDailyView> advances) {
      this.advances = advances;
   }

   public List<CustomerWithoutRenovationView> getCustomersWithoutRenovation() {
      return customersWithoutRenovation;
   }

   public void setCustomersWithoutRenovation(List<CustomerWithoutRenovationView> customersWithoutRenovation) {
      this.customersWithoutRenovation = customersWithoutRenovation;
   }

   public String getUserId() {
      return userId;
   }

   public void setUserId(String userId) {
      this.userId = userId;
   }

   public List<AdvanceUserDailyDetail> getAdvancesDetail() {
      return advancesDetail;
   }

   public void setAdvancesDetail(List<AdvanceUserDailyDetail> advancesDetail) {
      this.advancesDetail = advancesDetail;
   }

   public List<User> getUsers() {
      return users;
   }

   public void setUsers(List<User> users) {
      this.users = users;
   }

   public CustomerController getCustomerCtrl() {
      return customerCtrl;
   }

   public void setCustomerCtrl(CustomerController customerCtrl) {
      this.customerCtrl = customerCtrl;
   }

   public String getCustomerId() {
      return customerId;
   }

   public void setCustomerId(String customerId) {
      this.customerId = customerId;
   }

   public List<People> getCustomers() {
      return customers;
   }

   public void setCustomers(List<People> customers) {
      this.customers = customers;
   }

   public List<Loan> getLoan() {
      return loan;
   }

   public void setLoan(List<Loan> loan) {
      this.loan = loan;
   }

   public List<Loan> getLoanJuridical() {
      return loanJuridical;
   }

   public void setLoanJuridical(List<Loan> loanJuridical) {
      this.loanJuridical = loanJuridical;
   }

   public List<LoanDetailZeroView> getLoanZero() {
      return loanZero;
   }

   public void setLoanZero(List<LoanDetailZeroView> loanZero) {
      this.loanZero = loanZero;
   }

   public List<LoanFinishedView> getLoanFinished() {
      return loanFinished;
   }

   public void setLoanFinished(List<LoanFinishedView> loanFinished) {
      this.loanFinished = loanFinished;
   }

   public Loan getSelectedLoan() {
      return selectedLoan;
   }

   public void setSelectedLoan(Loan selectedLoan) {
      this.selectedLoan = selectedLoan;
   }

   public Loan getSelectedLoanJuridical() {
      return selectedLoanJuridical;
   }

   public void setSelectedLoanJuridical(Loan selectedLoanJuridical) {
      this.selectedLoanJuridical = selectedLoanJuridical;
   }

   public LoanDetailZeroView getSelectedLoanZero() {
      return selectedLoanZero;
   }

   public void setSelectedLoanZero(LoanDetailZeroView selectedLoanZero) {
      this.selectedLoanZero = selectedLoanZero;
   }

   public LoanFinishedView getSelectedLoanFinished() {
      return selectedLoanFinished;
   }

   public void setSelectedLoanFinished(LoanFinishedView selectedLoanFinished) {
      this.selectedLoanFinished = selectedLoanFinished;
   }

   public BigDecimal getPayment() {
      return payment;
   }

   public void setPayment(BigDecimal payment) {
      this.payment = payment;
   }

   public String getComments() {
      return comments;
   }

   public void setComments(String comments) {
      this.comments = comments;
   }

   public BigDecimal getFee() {
      return fee;
   }

   public void setFee(BigDecimal fee) {
      this.fee = fee;
   }

   public String getLoanTypeId() {
      return loanTypeId;
   }

   public void setLoanTypeId(String loanTypeId) {
      this.loanTypeId = loanTypeId;
   }

   public LoanTypeController getLoanTypeCtrl() {
      return loanTypeCtrl;
   }

   public void setLoanTypeCtrl(LoanTypeController loanTypeCtrl) {
      this.loanTypeCtrl = loanTypeCtrl;
   }

   public List<LoanType> getLoanType() {
      return loanType;
   }

   public void setLoanType(List<LoanType> loanType) {
      this.loanType = loanType;
   }

   public RouteController getRouteCtrl() {
      return routeCtrl;
   }

   public void setRouteCtrl(RouteController routeCtrl) {
      this.routeCtrl = routeCtrl;
   }

   public String getRouteId() {
      return routeId;
   }

   public void setRouteId(String routeId) {
      this.routeId = routeId;
   }

   public List<RouteCtlg> getRoute() {
      return route;
   }

   public void setRoute(List<RouteCtlg> route) {
      this.route = route;
   }

   public BigDecimal getTotalDepositDaily() {
      return totalDepositDaily;
   }

   public void setTotalDepositDaily(BigDecimal totalDepositDaily) {
      this.totalDepositDaily = totalDepositDaily;
   }

   public BigDecimal getTotalColocationApproved() {
      return totalColocationApproved;
   }

   public void setTotalColocationApproved(BigDecimal totalColocationApproved) {
      this.totalColocationApproved = totalColocationApproved;
   }

   public BigDecimal getTotalColocationToDelivery() {
      return totalColocationToDelivery;
   }

   public void setTotalColocationToDelivery(BigDecimal totalColocationToDelivery) {
      this.totalColocationToDelivery = totalColocationToDelivery;
   }

   public BigDecimal getTotalDiference() {
      return totalDiference;
   }

   public void setTotalDiference(BigDecimal totalDiference) {
      this.totalDiference = totalDiference;
   }

   public BigDecimal getTotalPorcentajeDiference() {
      return totalPorcentajeDiference;
   }

   public void setTotalPorcentajeDiference(BigDecimal totalPorcentajeDiference) {
      this.totalPorcentajeDiference = totalPorcentajeDiference;
   }

   public BigDecimal getGeneralExpectedWeek() {
      return GeneralExpectedWeek;
   }

   public void setGeneralExpectedWeek(BigDecimal GeneralExpectedWeek) {
      this.GeneralExpectedWeek = GeneralExpectedWeek;
   }

   public BigDecimal getGeneralReportedWeek() {
      return generalReportedWeek;
   }

   public void setGeneralReportedWeek(BigDecimal generalReportedWeek) {
      this.generalReportedWeek = generalReportedWeek;
   }

   public List<People> getEndorsement() {
      return endorsement;
   }

   public void setEndorsement(List<People> endorsement) {
      this.endorsement = endorsement;
   }

   public EndorsementController getEndorsementCtrl() {
      return endorsementCtrl;
   }

   public void setEndorsementCtrl(EndorsementController endorsementCtrl) {
      this.endorsementCtrl = endorsementCtrl;
   }

   public String getEndorsementId() {
      return endorsementId;
   }

   public void setEndorsementId(String endorsementId) {
      this.endorsementId = endorsementId;
   }

   public List<Loan> getLoanEndorsement() {
      return loanEndorsement;
   }

   public void setLoanEndorsement(List<Loan> loanEndorsement) {
      this.loanEndorsement = loanEndorsement;
   }

   public Loan getSelectedLoanEndorsement() {
      return selectedLoanEndorsement;
   }

   public void setSelectedLoanEndorsement(Loan selectedLoanEndorsement) {
      this.selectedLoanEndorsement = selectedLoanEndorsement;
   }

   public BitacoraController getBitacoraCtrl() {
      return bitacoraCtrl;
   }

   public void setBitacoraCtrl(BitacoraController bitacoraCtrl) {
      this.bitacoraCtrl = bitacoraCtrl;
   }

   public String getCommentsBitacora() {
      return commentsBitacora;
   }

   public void setCommentsBitacora(String commentsBitacora) {
      this.commentsBitacora = commentsBitacora;
   }

   public LazyDataModel<CustomerWithoutRenovationView> getCustomersWithoutRenovationPaginator() {
      return customersWithoutRenovationPaginator;
   }

   public void setCustomersWithoutRenovationPaginator(LazyDataModel<CustomerWithoutRenovationView> customersWithoutRenovationPaginator) {
      this.customersWithoutRenovationPaginator = customersWithoutRenovationPaginator;
   }

   public GenericValidationController getGenericValidateController() {
      return genericValidateController;
   }

   public void setGenericValidateController(GenericValidationController genericController) {
      this.genericValidateController = genericController;
   }

   public Date getLastStableSmallBox() {
      return lastStableSmallBox;
   }

   public void setLastStableSmallBox(Date lastStableSmallBox) {
      this.lastStableSmallBox = lastStableSmallBox;
   }

   public String getPlantillaHTML() {
      return plantillaHTML;
   }

   public void setPlantillaHTML(String plantillaHTML) {
      this.plantillaHTML = plantillaHTML;
   }

   public PeopleController getPeopleCtrl() {
      return peopleCtrl;
   }

   public void setPeopleCtrl(PeopleController peopleCtrl) {
      this.peopleCtrl = peopleCtrl;
   }

   @Inject
   private CustomerWithoutRenovationViewService customerWithoutRenovationViewService;

   private ClosingDayController closingDayCtrl;
   private DashboardController dashboardCtrl;
   private LoanController loanCtrl;
   private GenericController genericCtrl;
   private CustomerController customerCtrl;
   private EndorsementController endorsementCtrl;
   private LoanTypeController loanTypeCtrl;
   private RouteController routeCtrl;
   private BitacoraController bitacoraCtrl;
   private PeopleController peopleCtrl;

   private BigDecimal totalAmountDaily;
   private BigDecimal totalTransferSenderDaily;
   private BigDecimal totalTransferReceiverDaily;
   private BigDecimal totalMoneyDailyDaily;
   private BigDecimal totalDeliveryDaily;
   private BigDecimal totalFinalDaily;
   private BigDecimal totalCajaDaily;
   private BigDecimal totalOtherExpenseDaily;
   private BigDecimal totalDepositDaily;

   private BigDecimal totalExpectedToday;

   private BigDecimal payment;
   private BigDecimal fee;

   private int numPending;
   private int numApproved;
   private int numFinish;
   private int numRejected;
   private int numToDelivery;
   private String userId;
   private String customerId;
   private String endorsementId;
   private String comments;
   private String loanTypeId;
   private String routeId;
   private String commentsBitacora;
   private List<User> users;
   private List<People> customers;
   private List<People> endorsement;
   private List<RouteCtlg> route;

   private PieChartModel livePieModel;
   private PieChartModel pieResumenCaja;
   private BarChartModel barResumenLoans;

   private List<AdvanceUserDailyView> advances;
   private List<CustomerWithoutRenovationView> customersWithoutRenovation;
   private LazyDataModel<CustomerWithoutRenovationView> customersWithoutRenovationPaginator;
   private List<AdvanceUserDailyDetail> advancesDetail;
   private List<Loan> loan;
   private List<Loan> loanJuridical;
   private List<LoanDetailZeroView> loanZero;
   private List<LoanFinishedView> loanFinished;
   private List<Loan> loanEndorsement;
   private List<LoanType> loanType;

   private BigDecimal totalColocationApproved;
   private BigDecimal totalColocationToDelivery;
   private BigDecimal totalDiference;
   private BigDecimal totalPorcentajeDiference;
   private BigDecimal GeneralExpectedWeek;
   private BigDecimal generalReportedWeek;

   private Loan selectedLoan;
   private Loan selectedLoanJuridical;
   private LoanDetailZeroView selectedLoanZero;
   private LoanFinishedView selectedLoanFinished;
   private Loan selectedLoanEndorsement;

   private GenericValidationController genericValidateController;
   private Date lastStableSmallBox;
   private boolean stableSmallBoxToday;

   private String plantillaHTML;

   @Inject
   private CustomerService customerService;

   @PostConstruct
   public void init() {
      livePieModel = new PieChartModel();
      pieResumenCaja = new PieChartModel();
      closingDayCtrl = new ClosingDayController();
      dashboardCtrl = new DashboardController();
      loanCtrl = new LoanController();
      genericCtrl = new GenericController();
      customerCtrl = new CustomerController();
      endorsementCtrl = new EndorsementController();
      loanTypeCtrl = new LoanTypeController();
      routeCtrl = new RouteController();
      bitacoraCtrl = new BitacoraController();
      peopleCtrl = new PeopleController();
      commentsBitacora = "";
      setGenericValidateController(new GenericValidationController());
      setLastStableSmallBox(getGenericValidateController().lastStableSmallBoxByDate(getLoggedUser().getUser()));

      if (dashboardCtrl.verifyTotalExpectedPaymentDailyByUserCreatedByOffice(getLoggedUser().getOffice().getId()) == 0) {
         getPaymentDailyExpectByUser();
      }
      advances = fillAdvanceUserDaily();
      totalColocationApproved = BigDecimal.ZERO;
      totalColocationToDelivery = BigDecimal.ZERO;
      GeneralExpectedWeek = BigDecimal.ZERO;
      generalReportedWeek = BigDecimal.ZERO;
      totalDiference = BigDecimal.ZERO;
      totalPorcentajeDiference = BigDecimal.ZERO;

      if (advances != null && !advances.isEmpty()) {
         for (AdvanceUserDailyView advance : advances) {
            totalColocationApproved = totalColocationApproved.add(advance.getColocationApproved());
            totalColocationToDelivery = totalColocationToDelivery.add(advance.getColocationToDelivery());
            GeneralExpectedWeek = GeneralExpectedWeek.add(advance.getTotalExpectedWeek());
            generalReportedWeek = generalReportedWeek.add(advance.getTotalReportedWeek());

         }
         totalDiference = generalReportedWeek.subtract(GeneralExpectedWeek);
         if (GeneralExpectedWeek.compareTo(BigDecimal.ZERO) == 1) {
            totalPorcentajeDiference = ((GeneralExpectedWeek.subtract(generalReportedWeek)).multiply(new BigDecimal(100))).divide(GeneralExpectedWeek, 2, RoundingMode.HALF_UP);
         } else {
            totalPorcentajeDiference = BigDecimal.ZERO;
         }

      }
      customersWithoutRenovation = findAllCustomerWithOutRenovationByOffice();
      listenerCustomerWithoutRenovationView();
      users = genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
      customers = customerCtrl.fillCustomersDatatable(getLoggedUser().getOffice().getId());
      endorsement = endorsementCtrl.fillEndorsementsDatatable(getLoggedUser().getOffice().getId());
      loanType = loanTypeCtrl.fillLoanTypeDatatable(getLoggedUser().getOffice().getId());
      route = routeCtrl.fillRoutesDatatable(getLoggedUser().getOffice().getId());
      getResumenDaily();
      getResumenLoans();
      getLoansJuridical();
      getLoansZero();
   }

   public boolean getAction() {
      Date date = new Date();
      System.out.println("Fecha: " + date);
      if (genericCtrl.existStableSmallBoxByCreatedOn(date)) {
         return false;
      }
      return true;
   }

   private void listenerCustomerWithoutRenovationView() {
      try {
         setCustomersWithoutRenovationPaginator(
                 new LazyDataModel<CustomerWithoutRenovationView>() {

            private List<CustomerWithoutRenovationView> listOfData;

            @Override
            public List<CustomerWithoutRenovationView> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy) {
               String generalSearch = (null != filterBy && !filterBy.isEmpty() && null != filterBy.get("globalFilter") && !filterBy.get("globalFilter").toString().equals(""))
                       ? "%" + filterBy.get("globalFilter").toString() + "%"
                       : "";

               if (null != filterBy) {
                  filterBy.remove("globalFilter");
               }

               Long total = customerWithoutRenovationViewService
                       .countAllCustomerWithOutRenovationByOfficePaginator(
                               getLoggedUser().getOffice().getId(),
                               generalSearch,
                               filterBy);

               setRowCount(total.intValue());

               listOfData = customerWithoutRenovationViewService
                       .findAllCustomerWithOutRenovationByOfficePaginator(
                               getLoggedUser().getOffice().getId(),
                               first,
                               pageSize,
                               generalSearch,
                               sortField,
                               sortOrder.toString().equals("ASCENDING") ? "ASC" : "DESC",
                               filterBy);

               return listOfData;
            }

            @Override
            public String getRowKey(CustomerWithoutRenovationView selectedRow) {
               return selectedRow.getId();
            }

            @Override
            public CustomerWithoutRenovationView getRowData(String rowKey) {
               return listOfData
                       .stream()
                       .filter(rowData -> rowKey.equals(rowData.getId()))
                       .findFirst()
                       .orElse(null);
            }

         });
      } catch (Exception e) {
      }
   }

}
