/** This method sets flags to show finish or next button on the screens */
  public void chooseInsurance(Boolean substituteInsurance, String sectionNumber) {

    if (substituteInsurance != null && substituteInsurance) {
      showFinish = true;
      showCLSNext = false;
      dto.setCreditLifeSubstitution(true);
    } else {
      showCLSNext = true;
      showFinish = false;
      dto.setCreditLifeSubstitution(false);
    }

    if ("section5_next".equalsIgnoreCase(sectionNumber)) {
      showCLSNext = true;
      showFinish = false;
      stepsActiveIndex = 5;
      getRc().execute("PF('wizScript').next()");
    }

    if ("section5_back".equalsIgnoreCase(sectionNumber)) {
      showCLSNext = false;
      showFinish = false;
      stepsActiveIndex = 3;
      getRc().execute("PF('wizScript').back()");
    }
  }
  public boolean isBranchpre() {
    if (disVoiceContract) return true;
    else if (disBranchContract) return false;
    else if (dto.getContractingMethod() == null) return false;

    return dto.getContractingMethod().equals(EContractingMethod.BRANCH);
  }
 /** UI event. View doc button click */
 public void viewDocument(BCMDocument document) {
   try {
     super.viewDocument(document, dto.getProcessBundleLogId());
     openDocumentView(dto.getProcessBundleLogId(), document, quote.getScanner());
   } catch (ServiceException e) {
     errorMessage(e.getError());
   }
 }
 public void updatePresence(
     String agentid, String ucid, String serviceid, String phonenumber, String error) {
   try {
     if (agentid.equals("-1") || ucid.equals("-1")) {
       return;
     }
     if (dto.getPb().getUcId() != null && dto.getPb().getUcId().equals(ucid)) {
       return;
     }
     dto.getPb().setAgentId(Long.valueOf(agentid));
     dto.getPb().setUcId(ucid);
     dto.getPb().setServiceId(Long.valueOf(serviceid));
     dto.getPb().setPhoneNumber(phonenumber);
     dto.getPb().setError(error == "true");
     dto.getPb().setTid(task.getTid());
     // == Immediate save into dto for doc generation
     dto.setConfirmOfferCallUCID(dto.getPb().getUcId());
     dto.setConfirmOfferCallTimeStamp(Calendar.getInstance().getTime());
     if (!ucid.equals("BYPASS")) {
       dao.saveQuoteRecording(dto);
     }
     getRc().update("popPresence:presenceForm");
   } catch (ServiceException e) {
     popupErrorMessage(e.getError());
     dto.getPb().setUcId("-1");
     getRc().update(UI_MAIN);
   }
 }
 @Override
 public void referFraud(ActionEvent event) {
   try {
     resolveFluxTags(dto);
     dto.getNotes().add(super.baseReferFraud());
     dto.setReferToFraud(true);
     finish(event);
   } catch (ServiceException e) {
     errorMessage(e.getError(), ERR_GLOBAL);
   } catch (Exception e) {
     showThatsNotGood(dto, new ServiceException(ErrorCodes.UHE000, e), TASK);
   }
 }
  @Override
  public void reject(ActionEvent event) {
    try {
      resolveFluxTags(dto);
      dto.getNotes().add(super.baseReject());

      if (!this.getClass().getSimpleName().equals(TASK)) return;

      // insurance offer confirm reject
      setVariable(Long.valueOf(task.getPid()).intValue(), "insfraud", "false");

      if (!task.isSupport()) {
        setVariable(Long.valueOf(task.getPid()).intValue(), "branchpre", "false");
        setVariable(Long.valueOf(task.getPid()).intValue(), "loanselected", "false");
        setVariable(Long.valueOf(task.getPid()).intValue(), "cellselected", "false");
        setVariable(Long.valueOf(task.getPid()).intValue(), "fraudCO", "false");
        setVariable(Long.valueOf(task.getPid()).intValue(), "creditlifesub", "false");
        setVariable(Long.valueOf(task.getPid()).intValue(), "reject", "true");
        rejectTask(task.getTid(), bayfin.getUser());
      }
      quote.setProcessStatus(EProcessState.REJECTED);
      sendMessage(MessageBuilder.prepareRejectAllSMS(dto));
      saveAndExit();

    } catch (ServiceException e) {
      errorMessage(e.getError(), ERR_GLOBAL);
    } catch (Exception e) {
      showThatsNotGood(dto, new ServiceException(ErrorCodes.UHE000, e), TASK);
    }
  }
 /** Similar to doOffer but only refreshes the terms */
 public void refreshOffer() throws ServiceException {
   productCode = fetchFromFilteredOffers();
   String saveLoanRef = fetchLoanRefFromFilteredOffers();
   try {
     if (dto.getRequestedProduct().equals(EProductType.MEDICAL)) {
       reCalculateOffer();
     } else if (dto.isDoRecalc()) {
       reCalculateOffer();
       adjustTerm(quote.getState().getLoanCapitalRate(), productCode);
     } else {
       adjustTerm(quote.getState().getLoanCapitalRate(), productCode);
     }
     putLoanRefIntoFilteredOffer(saveLoanRef);
   } catch (ServiceException e) {
     errorMessage(e.getError());
   }
 }
 /** Like the name says; save and exit (navigate to user home) */
 private void saveAndExit() {
   try {
     dto.setErrors(getErrors());
     save();
     navigateUserHome();
   } catch (ServiceException e) {
     logger.error(e);
     dto.getErrors().add(e.getError());
     e.getError().setReference(transmitErrorData(dto, TASK));
     info.displayBugDialog(e.getError());
   } catch (Exception e) {
     logger.error(e);
     BaseError error = dto.addError(ErrorCodes.UHE000, e);
     error.setReference(transmitErrorData(dto, TASK));
     info.displayBugDialog(error);
   }
 }
 /** UI event on general note save */
 @Override
 public void generalNote(ActionEvent event) {
   try {
     dto.getNotes().add(super.baseGeneralNote());
   } catch (ServiceException e) {
     errorMessage(e.getError());
   }
 }
 /** Puts the loanref back */
 private void putLoanRef(String loanReference) {
   for (ProtoOffer offer : dto.getFilteredLoanOffers()) {
     if (offer.isSelected()) {
       offer.setLoanReference(loanReference);
       break;
     }
   }
 }
 /** Saves the DTO data as a CreditApplication entity */
 private CreditApplication save() throws ServiceException {
   solveSelected();
   // save cart first, and only if this is a confirm insurance offer task)
   if (cart != null && task.getOrigin().equals("task.confirm.offer.call.insurance")) {
     cart.setTid(task.getTid());
     cartDAO.save(cart, true);
   }
   dto.setTid(task.getTid());
   quote.bridgeWithCart(cart, false);
   return dao.save(dto);
 }
 @Override
 public void reschedule(ActionEvent event) {
   try {
     resolveFluxTags(dto);
     dto.getNotes().add(super.baseReschedule());
     if (!this.getClass().getSimpleName().equals(TASK)) return;
     saveAndExit();
   } catch (ServiceException e) {
     errorMessage(e.getError(), ERR_GLOBAL);
   } catch (Exception e) {
     showThatsNotGood(dto, new ServiceException(ErrorCodes.UHE000, e), TASK);
   }
 }
 @Override
 public void suspend(ActionEvent event) {
   try {
     resolveFluxTags(dto);
     dto.getNotes().add(super.baseSuspend());
     // settlements only
     avBuilder.submitAV(task, dto);
     saveAndExit();
   } catch (ServiceException e) {
     errorMessage(e.getError(), ERR_GLOBAL);
   } catch (Exception e) {
     showThatsNotGood(dto, new ServiceException(ErrorCodes.UHE000, e), TASK);
   }
 }
  private void completeConfirmOfferFlux() throws ServiceException {
    // non-flow task id -1 override
    if (task.getTid() == -1) return;

    boolean xdsFailed = taskRules.xdsFailed(dto.getPid(), xdsAuthenticationLogs);
    dto.setReferToFraud(dto.isReferToFraud() || xdsFailed);
    checkFraud(dto, "fraudCO");

    // Should the documents be scanned at the branch
    setVariable(
        Long.valueOf(task.getPid()).intValue(),
        "branchpre",
        String.valueOf(dto.getContractingMethod().equals(EContractingMethod.BRANCH)));
    // has a loan product been selected
    setVariable(Long.valueOf(task.getPid()).intValue(), "loanselected", "true");
    // has a cellular product been selected
    setVariable(Long.valueOf(task.getPid()).intValue(), "cellselected", "false");
    // has a cellular product been selected
    setVariable(
        Long.valueOf(task.getPid()).intValue(),
        "creditlifesub",
        String.valueOf(dto.isCreditLifeSubstitution()));

    // insurance offer confirmation only (send to fraud)
    setVariable(Long.valueOf(task.getPid()).intValue(), "insfraud", "false");
    if (task.getOrigin().equals("task.confirm.offer.call.insurance")) {
      boolean insfraud = xdsFailed || dto.isReferToFraud();
      setVariable(Long.valueOf(task.getPid()).intValue(), "insfraud", String.valueOf(insfraud));
    }

    // Now call the workflow to complete the task
    if (!task.isSupport()) completeTask(task.getTid(), bayfin.getUser());

    // Update Flux Task Branch Code for Branch Contracting
    if (dto.getContractingMethod().equals(EContractingMethod.BRANCH)) {
      long branchScanningTid =
          getTidforTask(
              Long.valueOf(task.getPid()).intValue(), "task.scan.branch.pre", "Scan pre-agreement");
      if (branchScanningTid > 0) {
        if (signingBranchCode.intValue() > 0) {
          fluxService.updateFluxInboxBranch(branchScanningTid, signingBranchCode.intValue());
        }
      }
    }
  }
  /**
   * Check for AVS verified required settlements when clicking the Next button on Capture & Review -
   * Offer page
   */
  public void offerNextButtonClick() {

    solveSelected();
    try {
      getAvCaches().clear();
      findSettlementAvData(dto);
      // forced to do the logic here since AvCache is a BayServ entity so we cannot use TaskRules
      boolean avsDone = true;
      String errorMsg = "Account verification status for AV required settlement account : ";
      for (ProtoAvCache item : avCaches) {
        if (!ValidationUtils.isIn(item.getAppStatus(), SystemConstants.AV_COMPLETED)) {
          String accountRef = "";
          for (ProtoSettlement settlement : quote.getSettlements()) {
            String compare = StringUtils.right(settlement.getAccount().getAccountNumber(), 10);
            if (compare.equals(item.getNumber().toString())) {
              accountRef = settlement.getFormattedAccountNumber();
              avsDone = false;
              break;
            }
          }
          errorMessage("AVS", errorMsg + accountRef + " : " + item.getAppStatus(), ERR_GLOBAL);
        }
      }
      if (!avsDone) return;

      taskRules.postOfferRules(quote, task);

      taskRules.loanCOCheckoutRules(quote);

      filterSelectedCellularOffers(quote);
      fixCurrentOffer(quote);
      dto.initialiseConfirmOfferCall();
      getRc().execute(UI_NEXT);

    } catch (ServiceException e) {
      popupErrorMessage(e.getError());
      getRc().update(UI_MAIN);
    }
  }
  @Override
  // confirm offer needs to load two document lists
  public void loadBCMBundle() {
    try {
      loadBCMBundleStructureByTask(task.getTaskTarget());
      dto.getScanDocuments().clear();
      dto.getScanDocuments2().clear();
      if (bundle != null) {
        bundle.setBundleId(dto.getProcessBundleLogId());
        setInitialBCMScannerVars(quote, bundle.getCode(), quote.getIdNumber());
        bundle = bcm.resolveBundle(prepareBundleFilters(bundle));

        // load loan documents
        List<BCMDocument> lonDocs =
            loadLoanDocuments(quote.getFilteredLoanOffers(), this.bundle.getDocuments());
        if (lonDocs != null && lonDocs.size() > 0) {
          lonDocs = bcm.resolveDynamicBundle(quote.getProcessBundleLogId(), lonDocs);
        }
        dto.getScanDocuments().addAll(lonDocs);

        // load pre-agreement documents
        List<BCMDocument> preDocs =
            loadPreAgreementDocuments(quote.getFilteredLoanOffers(), this.bundle.getDocuments());
        if (preDocs != null && preDocs.size() > 0) {
          preDocs = bcm.resolveDynamicBundle(quote.getProcessBundleLogId(), preDocs);
        }
        dto.getScanDocuments2().addAll(preDocs);

        taskRules.checkOfferChanges(dto);
        dto.getScanner().setRenderViewPanel(false);
        getRc().update(UI_MAIN);
      }
    } catch (ServiceException e) {
      errorMessage(e.getError());
    }
  }
  @Override
  @PostConstruct
  protected void onTaskReceive() throws ServiceException {
    try {
      super.onTaskReceive();
      if (task.getPid() == -1L) return;

      // must bypass descendants, let them initialize inside their own post constructs
      if (!this.getClass().getSimpleName().equals(TASK)) return;

      // only works with a valid PID
      dto = dao.read(task.getPid());
      super.setDto(dto);
      super.setQuote(dto);

      LookupItem jobTitle = lookupItemDAO.find(LookupItem.onCode, dto.getJobTitleCode());
      dto.setJobTitle(jobTitle);

      if (task.isSupport()) {
        // task inspector default
        xdsOnlyRequired = false;
        // look for a special support target
        if (task.getTaskTarget().equals("task.confirm.offer.xds")) {
          xdsOnlyRequired = true;
          // set it back to the real target otherwise documents won't load
          task.setTaskTarget("task.confirm.offer.call");
        }
      } else {
        xdsOnlyRequired = isSalesFlowV2_1(task) && !isCallCenterChannel(task.getPid());
      }

      // set some state
      dto.setCurrentTask(task);
      dto.setUserLink(bayfin.getUser());
      resolveLogTag(dto);
      filterSelectedSettlements(dto);
      buildOfferResponse(dto); // used for recalc
      loadBCMBundle();

      // also read in the cart data
      if (boot.findFeature("INSURANCE_CART").equals("On")) {
        cart = cartDAO.read(task.getPid());
        cart.setCurrentTask(task);
        cart.setUserLink(bayfin.getUser());
        resolveLogTag(cart);
        loadCart();
        showBanking =
            taskRules.insuredBankAccountRequired(cart.getInsuredBankAccount())
                || taskRules.insuredBankAccountRequired(cart.getOffers());
      }
      if (task.getOrigin().equals("task.confirm.offer.call.insurance")) {
        dto.setInsStandalone(true);
      }

      // now also fetch the XdsAuthenticationHIstoryLog
      fetchXdsLog(dto);
      checkXDSExistingStatus();

      // Initialize with the task associated branch details
      signingBranchCode = new Long(task.getBranchCode());

      // Search for branch name
      BranchBasedSearchRequest request = new BranchBasedSearchRequest();
      BranchSearch search = new BranchSearch();
      request.setData(search);
      GeneralSearchResponse response;
      // set
      request.setType(ESearchResultType.LIST);
      search.setSearchType(ESearchParameter.CODE);
      search.setIncludeAgentData(false);
      search.setIncludeUserData(false);
      search.setBranchCode(signingBranchCode);

      // execute
      response = bayserv.branchSearch(request);
      List<ViewBranch> branches = response.getBranchItems();
      if (branches != null && branches.size() > 0) {
        signingBranch = branches.get(0).getBranchName();
      } // end if

      dto.initialiseConfirmOfferCall();
      bindPresenceCall();

      if (pilotFlag.equals("BNW_V0")) {
        disVoiceContract = true;
        disBranchContract = false;
        dto.setContractingMethod(EContractingMethod.BRANCH);
        branchpre = true;
      } else if (info.isAppFeatureActive("CONTBRN", dto.getBranchCode().intValue())
          && dto.getRequestedProduct() != EProductType.MEDICAL
          && dto.getSubgroupType() != EEmployerType.PAYROLL
          && !isWebChannel(task.getPid())
          && !isCallCenterChannel(task.getPid())) {
        disVoiceContract = true;
        disBranchContract = false;
        dto.setContractingMethod(EContractingMethod.BRANCH);
        branchpre = true;
      } else if ((info.isAppFeatureActive("CONTVOICE", dto.getBranchCode().intValue())
              && dto.getRequestedProduct() != EProductType.MEDICAL
              && dto.getSubgroupType() != EEmployerType.PAYROLL)
          || isWebChannel(task.getPid())
          || isCallCenterChannel(task.getPid())) {
        disVoiceContract = false;
        disBranchContract = true;
        dto.setContractingMethod(EContractingMethod.VOICE);
        branchpre = false;
      } else if (info.isAppFeatureActive("CONTBOTH", dto.getBranchCode().intValue())
          && dto.getRequestedProduct() != EProductType.MEDICAL
          && dto.getSubgroupType() != EEmployerType.PAYROLL) {
        disVoiceContract = false;
        disBranchContract = false;
      } else if ((dto.getRequestedProduct() != EProductType.MEDICAL)
          && (dto.getSubgroupType() != EEmployerType.PAYROLL)) {
        if (quote.getStartRole().equals("Branch") || quote.getStartRole().equals("Agent")) {
          disVoiceContract = true;
          disBranchContract = false;
          dto.setContractingMethod(EContractingMethod.BRANCH);
          branchpre = true;
        } else {
          disVoiceContract = false;
          disBranchContract = false;
        }
      } else if ((dto.getRequestedProduct() == EProductType.MEDICAL)
          && (dto.getSubgroupType() != EEmployerType.PAYROLL)) {
        disVoiceContract = false;
        disBranchContract = true;
        dto.setContractingMethod(EContractingMethod.VOICE);
        branchpre = false;
      } else if (dto.getSubgroupType() == EEmployerType.PAYROLL) {
        disVoiceContract = true;
        disBranchContract = false;
        dto.setContractingMethod(EContractingMethod.BRANCH);
        branchpre = true;
      }

      if ((disVoiceContract == true) && (disBranchContract == true)) {
        throw new ServiceException("BAD#Error, both voice and branch contracting disabled");
      }

      if (dto.getRequestedProduct() == EProductType.MEDICAL) {
        if (dto.getSubgroupType() == EEmployerType.PAYROLL) {
          throw new Exception("Invalid product subgroup received");
        }
        dto.setContractingMethod(EContractingMethod.VOICE);
        disVoiceContract = false;
      }
      if (dto.getSubgroupType() == EEmployerType.PAYROLL) {
        disBranchContract = false;
      }
      employerName = dto.getEmployerName();

      // do not display settlements on web apps
      if (isWebChannel(task.getPid())) {
        dto.setWebChannel(true);
      }

    } catch (ServiceException e) {
      e.printStackTrace();
      popupErrorMessage(e.getError());
    } catch (Exception e) {
      e.printStackTrace();
      popupErrorMessage("Unhandled exception", e.getMessage());
    }
  }
  @Override
  public void finish(ActionEvent event) {
    dto.setSigningBranchCode(new BigDecimal(signingBranchCode));

    super.finish(event);
    // let descendants implement their own save and finish methods
    if (!this.getClass().getSimpleName().equals(TASK)) return;

    try {

      // don't do fraud checks for insurance stand-alone
      if (!dto.isInsStandalone()) runSystemFraud(dto, contructFraudSearch(dto));

      // Set Presence UCID and TimeStamp

      if (!isXdsOnlyRequired()) {

        dto.setConfirmOfferCallUCID(dto.getPb().getUcId());
        dto.setConfirmOfferCallTimeStamp(Calendar.getInstance().getTime());

        // check docs are generated and sent (contracting only)
        try {
          if (!dto.isCreditLifeSubstitution()) {

            // don't check loan offer changes if doing confirm offer insurance standalone
            if (!task.getTaskTarget().equals("task.confirm.offer.call.insurance")) {
              if (dto.getContractingMethod() == EContractingMethod.BRANCH)
                taskRules.checkOfferChangeIsGenerated(quote.getCurrentOffer());
              // TODO : Fix this, should not be disabled
              else if (!dto.getRequestedProduct().equals(EProductType.MEDICAL))
                taskRules.checkOfferChangeIsGeneratedAndSent(quote.getCurrentOffer());

              // must send it if !branchpre
              if (!dto.getContractingMethod().equals(EContractingMethod.BRANCH))
                if (!docSent) throw new ServiceException(ErrorCodes.CVA071);
            }
          }

          // generates and send all required insurance stand-alone documents (if there is no AVS)
          if (dto.isInsStandalone()) {
            String skipinsavs = getVariable(ConvertUtils.asInt(dto.getPid()), "skipinsavs");
            boolean sendDocsNow = true;
            if (skipinsavs != null) sendDocsNow = ConvertUtils.asBoolean(skipinsavs);

            if (sendDocsNow) {
              loadInsuranceDocumentsToSend();
              sendSpecificDocuments(cart, task, SystemConstants.DOC_INS_CODES);
            }
          }

          // check av (settlements only)
          avBuilder.submitAV(task, dto);
          getAvCaches().clear();
          findSettlementAvData(dto);
          // forced to do the logic here since AvCache is a BayServ entity so we cannot use
          // TaskRules
          boolean avsDone = true;
          String errorMsg = "Account verification status for AV required settlement account : ";
          for (ProtoAvCache item : avCaches) {
            if (!ValidationUtils.isIn(item.getAppStatus(), SystemConstants.AV_COMPLETED)) {
              String accountRef = "";
              for (ProtoSettlement settlement : quote.getSettlements()) {
                String compare = StringUtils.right(settlement.getAccount().getAccountNumber(), 10);
                if (compare.equals(item.getNumber().toString())) {
                  accountRef = settlement.getFormattedAccountNumber();
                  avsDone = false;
                  break;
                }
              }
              errorMessage(
                  "AVS ", errorMsg + " " + accountRef + " : " + item.getAppStatus(), ERR_GLOBAL);
            }
          }
          if (!avsDone) return;

        } catch (ServiceException e) {
          popupErrorMessage(e.getError());
          return;
        }
      }

      completeConfirmOfferFlux();

      if (!isXdsOnlyRequired()) {
        if (dto.getContractingMethod() == EContractingMethod.BRANCH
            && getFluxTask(
                        quote.getPid().intValue(),
                        "task.account.verification",
                        new EFluxTaskStatus[] {
                          EFluxTaskStatus.CREATED,
                          EFluxTaskStatus.IN_PROGRESS,
                          EFluxTaskStatus.READY,
                          EFluxTaskStatus.SUSPENDED
                        })
                    .size()
                <= 0
            && getFluxTask(
                        quote.getPid().intValue(),
                        "task.employment.confirm",
                        new EFluxTaskStatus[] {
                          EFluxTaskStatus.CREATED,
                          EFluxTaskStatus.IN_PROGRESS,
                          EFluxTaskStatus.READY,
                          EFluxTaskStatus.SUSPENDED
                        })
                    .size()
                <= 0) {
          // Now send Sign at branch sms
          if (!dto.isInsStandalone()) {
            bayserv.sendMessage(MessageBuilder.buildBranchSignSms(dto));
          }
        }
      }

      saveAndExit();

    } catch (ServiceException e) {
      logger.error(e);
      e.getError().setReference(transmitErrorData(quote, TASK));
      info.displayBugDialog(e.getError());
    } catch (Exception e) {
      logger.error(e);
      BaseError error = quote.addError(ErrorCodes.UHE000, e);
      error.setReference(transmitErrorData(quote, TASK));
      info.displayBugDialog(error);
    }
  }