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);
   }
 }
 /** Flips whether a plan is selected or not */
 public void flipPlanSelectedConfirmOffer(int index) {
   InsuranceOfferItem offer;
   Iterator<BaseOfferItem> itr = cart.getOffers().iterator();
   ShoppingBasketResponse response = null;
   while (itr.hasNext()) {
     offer = (InsuranceOfferItem) itr.next();
     Iterator<InsurancePlanItem> itr2 = offer.getPlans().iterator();
     while (itr2.hasNext()) {
       InsurancePlanItem plan = itr2.next();
       if (plan.getIndex() == index) {
         if (plan.isSelected()) {
           try {
             deselectPlan(index);
             response = checkDeselectTillSlip();
           } catch (ServiceException e) {
             selectPlan(index);
             popupErrorMessage(e.getError());
           }
         } else {
           selectPlan(index);
         }
       }
     }
   }
   if (response != null) {
     reIndexCart(cart.getOffers(), response.getOffers());
   }
 }
  @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);
    }
  }
 /** 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());
   }
 }
 /** UI event on general note save */
 @Override
 public void generalNote(ActionEvent event) {
   try {
     dto.getNotes().add(super.baseGeneralNote());
   } catch (ServiceException e) {
     errorMessage(e.getError());
   }
 }
  /** returns all cart items and summaries */
  public void loadCart() {
    if (cart == null) return;

    try {
      if (boot.findFeature("INSURANCE_CART").equals("On")) {
        cart.generateExistingItems();
        cart.generateLineItems();
        calculateCartTotals();
      }
    } catch (ServiceException e) {
      popupErrorMessage(e.getError());
    }
  }
 @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 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);
   }
 }
 /** 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);
   }
 }
 /** 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());
   }
 }
 /** Modified, overridden preOffer that does not change employer data */
 @Override
 public void preOffer() {
   try {
     saveSelectedSettlements(quote);
     defaultData();
     clearErrors();
     quote.unMask();
     if (!preOfferRules()) return;
     if (!preOffer(quote, feedback)) {
       for (BaseError item : errors) errorMessage(item, ERR_GLOBAL);
       return;
     }
   } catch (ServiceException e) {
     errorMessage(e.getError(), ERR_GLOBAL);
   } catch (Exception e) {
     errorMessage("General exception", e.getMessage(), ERR_GLOBAL);
     e.printStackTrace();
   }
 }
 @Override
 public void onExternalSettlementSelect() {
   try {
     clearErrors();
     String loanReference = findLoanRef(quote.getFilteredLoanOffers());
     preOffer();
     restoreSelectedSettlements(dto);
     if (!offer(dto, null)) {
       deSelectAllSettlements(dto);
       for (BaseError item : errors) errorMessage(item, ERR_GLOBAL);
       getRc().update(UI_MAIN);
       return;
     }
     putLoanRef(loanReference);
     getRc().update(UI_TBL_LOAN);
     getRc().update(UI_TBL_LOAN_AG);
   } catch (ServiceException e) {
     errorMessage(e.getError());
   }
 }
  /**
   * 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);
    }
  }