private void validateAdvancePaymentExists() {

    if (advanceRequisition != null
        && advanceRequisition.getEgAdvanceReqMises().getVoucherheader() != null
        && advanceRequisition.getEgAdvanceReqMises().getVoucherheader().getStatus() != 4) {
      populateBankAccounts(Integer.parseInt(commonBean.getBankId().split("-")[1]), fund.getId());
      throw new ValidationException(
          Arrays.asList(
              new ValidationError(
                  "arf.payment.uniqueCheck.validate.message",
                  getText(
                      "arf.payment.uniqueCheck.validate.message",
                      new String[] {advanceRequisition.getAdvanceRequisitionNumber()}))));
    }
  }
  @ValidationErrorPage(value = NEW)
  @Action(value = "/payment/advancePayment-save")
  public String save() {

    voucherHeader.setType(FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT);
    voucherHeader.setName(FinancialConstants.PAYMENTVOUCHER_NAME_ADVANCE);
    voucherHeader.setDescription(description);
    try {
      validateAdvancePaymentExists();
      if (commonBean.getModeOfPayment().equalsIgnoreCase(FinancialConstants.MODEOFPAYMENT_RTGS)) {
        validateRTGS();
      }
      voucherHeader = createVoucherAndledger();
      paymentheader =
          paymentService.createPaymentHeader(
              voucherHeader,
              Integer.valueOf(commonBean.getAccountNumberId()),
              commonBean.getModeOfPayment(),
              advanceRequisition.getAdvanceRequisitionAmount());

      createMiscBill();
      paymentheader.start().withOwner(paymentService.getPosition());
      advanceRequisition.getEgAdvanceReqMises().setVoucherheader(paymentheader.getVoucherheader());
      sendForApproval();
      addActionMessage(
          getText("arf.payment.transaction.success") + " " + voucherHeader.getVoucherNumber());

    } catch (ValidationException e) {
      List<ValidationError> errorList = e.getErrors();
      for (ValidationError error : errorList) {
        if (error.getMessage().contains("DatabaseSequenceFirstTimeException")) {
          prepare();
          throw new ValidationException(
              Arrays.asList(new ValidationError("error", error.getMessage())));
        } else throw new ValidationException(e.getErrors());
      }
      populateBankAccounts(Integer.parseInt(commonBean.getBankId().split("-")[1]), fund.getId());
    } catch (NumberFormatException e) {
      LOGGER.error(e.getMessage(), e);
      throw e;
    } catch (ApplicationRuntimeException e) {
      LOGGER.error(e.getMessage(), e);
      throw e;
    } finally {
      loadApproverUser(FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT);
    }
    return VIEW;
  }
  public void validate() {
    String actionName = "";
    if (parameters.get(ACTION_NAME) != null && parameters.get(ACTION_NAME)[0] != null)
      actionName = parameters.get(ACTION_NAME)[0];

    if (!(actionName.equalsIgnoreCase(REJECT_ACTION)
        || actionName.equalsIgnoreCase(CANCEL_ACTION))) {
      if (voucherHeader.getVoucherDate() == null)
        addFieldError("voucherDate", getText("arf.payment.voucherdate.required"));
      if (!DateUtils.compareDates(
          voucherHeader.getVoucherDate(), advanceRequisition.getAdvanceRequisitionDate()))
        addFieldError(
            "advanceRequisitionDate",
            getText("arf.payment.voucherdate.lessthan.advancerequisitiondate"));
      if (!DateUtils.compareDates(new Date(), voucherHeader.getVoucherDate()))
        addFieldError(
            "advanceRequisitionDate",
            getText("arf.validate.payment.voucherdate.greaterthan.currentDate"));

      if (StringUtils.isBlank(commonBean.getBankId()) || commonBean.getBankId().equals("-1"))
        addFieldError("commonBean.bankId", getText("arf.bankbranch.required"));

      if (StringUtils.isBlank(commonBean.getAccountNumberId())
          || commonBean.getAccountNumberId().equals("-1"))
        addFieldError("commonBean.accountNumberId", getText("arf.accountnumber.required"));
      if (StringUtils.isBlank(commonBean.getModeOfPayment()))
        addFieldError("commonBean.modeOfPayment", getText("arf.modeOfPayment.required"));
    }
  }
  @SuppressWarnings("unchecked")
  private void prepareForView() {
    voucherHeader =
        (CVoucherHeader)
            HibernateUtil.getCurrentSession().load(CVoucherHeader.class, voucherHeader.getId());
    paymentheader =
        (Paymentheader)
            persistenceService.find("from Paymentheader where voucherheader=?", voucherHeader);
    advanceRequisition =
        (EgAdvanceRequisition)
            persistenceService.find(
                "from EgAdvanceRequisition where egAdvanceReqMises.voucherheader = ?",
                voucherHeader);
    advanceRequisitionId = advanceRequisition.getId();
    commonBean.setAmount(paymentheader.getPaymentAmount());
    commonBean.setAccountNumberId(paymentheader.getBankaccount().getId().toString());

    String bankBranchId =
        paymentheader.getBankaccount().getBankbranch().getBank().getId()
            + "-"
            + paymentheader.getBankaccount().getBankbranch().getId();
    commonBean.setBankId(bankBranchId);
    commonBean.setModeOfPayment(paymentheader.getType().toUpperCase());
    Miscbilldetail miscbillDetail =
        (Miscbilldetail)
            persistenceService.find(" from Miscbilldetail where payVoucherHeader=?", voucherHeader);

    commonBean.setPaidTo(miscbillDetail.getPaidto());
    loadAjaxedDropDowns();
    // find it last so that rest of the data loaded
    if (!"view".equalsIgnoreCase(showMode)) {
      validateUser("balancecheck");
    }
  }
  private void validateRTGS() {
    EntityType entity = null;
    List<ValidationError> errors = new ArrayList<ValidationError>();
    for (EgAdvanceRequisitionDetails advanceDetail :
        advanceRequisition.getEgAdvanceReqDetailses()) {
      if (!advanceDetail.getEgAdvanceReqpayeeDetailses().isEmpty()) {
        for (EgAdvanceReqPayeeDetails payeeDetail : advanceDetail.getEgAdvanceReqpayeeDetailses()) {
          try {
            entity =
                paymentService.getEntity(
                    payeeDetail.getAccountDetailType().getId(),
                    (Serializable) payeeDetail.getAccountdetailKeyId());
            if (entity == null) {
              throw new ValidationException(
                  Arrays.asList(
                      new ValidationError(
                          "no.entity.for.detailkey",
                          getText(
                              "no.entity.for.detailkey",
                              new String[] {entity.getCode() + "-" + entity.getName()}))));
            }
          } catch (ApplicationException e) {
            throw new ValidationException(
                Arrays.asList(
                    new ValidationError("Exception to get EntityType  ", e.getMessage())));
          }

          if ((StringUtils.isBlank(entity.getPanno())
              || StringUtils.isBlank(entity.getBankname())
              || StringUtils.isBlank(entity.getBankaccount())
              || StringUtils.isBlank(entity.getIfsccode()))) {
            populateBankAccounts(
                Integer.parseInt(commonBean.getBankId().split("-")[1]), fund.getId());
            LOGGER.error(
                getText(
                    "validate.paymentMode.rtgs.subledger.details",
                    new String[] {entity.getCode() + "-" + entity.getName()}));
            errors.add(
                new ValidationError(
                    "validate.paymentMode.rtgs.subledger.details",
                    getText(
                        "validate.paymentMode.rtgs.subledger.details",
                        new String[] {entity.getCode() + "-" + entity.getName()})));
            throw new ValidationException(errors);
          }
        }
      } else {
        throw new ValidationException(
            Arrays.asList(
                new ValidationError(
                    "no.subledger.cannot.create.rtgs.payment",
                    "arf.payment.no.subledger.cannot.create.rtgs.payment")));
      }
    }
  }
  @Override
  protected HashMap<String, Object> createHeaderAndMisDetails() throws ValidationException {
    HashMap<String, Object> headerdetails = new HashMap<String, Object>();
    headerdetails.put(VoucherConstant.VOUCHERNAME, voucherHeader.getName());
    headerdetails.put(VoucherConstant.VOUCHERTYPE, voucherHeader.getType());
    headerdetails.put(VoucherConstant.VOUCHERDATE, voucherHeader.getVoucherDate());
    headerdetails.put(VoucherConstant.DESCRIPTION, voucherHeader.getDescription());

    EgAdvanceRequisitionMis egAdvanceReqMises = advanceRequisition.getEgAdvanceReqMises();
    if (egAdvanceReqMises != null) {
      if (egAdvanceReqMises.getFund() != null && egAdvanceReqMises.getFund().getId() != null) {
        headerdetails.put(VoucherConstant.FUNDCODE, egAdvanceReqMises.getFund().getCode());
      }
      if (egAdvanceReqMises.getEgDepartment() != null
          && egAdvanceReqMises.getEgDepartment().getId() != null) {
        headerdetails.put(
            VoucherConstant.DEPARTMENTCODE, egAdvanceReqMises.getEgDepartment().getCode());
      }
      if (egAdvanceReqMises.getFundsource() != null
          && egAdvanceReqMises.getFundsource().getId() != null) {
        headerdetails.put(
            VoucherConstant.FUNDSOURCECODE, egAdvanceReqMises.getFundsource().getCode());
      }
      if (egAdvanceReqMises.getScheme() != null && egAdvanceReqMises.getScheme().getId() != null) {
        headerdetails.put(VoucherConstant.SCHEMECODE, egAdvanceReqMises.getScheme().getCode());
      }
      if (egAdvanceReqMises.getSubScheme() != null
          && egAdvanceReqMises.getSubScheme().getId() != null) {
        headerdetails.put(
            VoucherConstant.SUBSCHEMECODE, egAdvanceReqMises.getSubScheme().getCode());
      }
      if (egAdvanceReqMises.getFunctionaryId() != null
          && egAdvanceReqMises.getFunctionaryId().getId() != null) {
        headerdetails.put(
            VoucherConstant.FUNCTIONARYCODE, egAdvanceReqMises.getFunctionaryId().getCode());
      }
      if (egAdvanceReqMises.getFunction() != null
          && egAdvanceReqMises.getFunction().getId() != null) {
        headerdetails.put(VoucherConstant.FUNCTIONCODE, egAdvanceReqMises.getFunction().getCode());
      }
      if (egAdvanceReqMises.getFieldId() != null
          && egAdvanceReqMises.getFieldId().getId() != null) {
        headerdetails.put(VoucherConstant.DIVISIONID, egAdvanceReqMises.getFieldId().getId());
      }
    }
    return headerdetails;
  }
 private void createMiscBill() {
   Miscbilldetail miscbilldetail = new Miscbilldetail();
   // Since we are not creating any bill for advance payment, we are updating bill no, bill date
   // and bill amount from ARF
   miscbilldetail.setBillnumber(advanceRequisition.getAdvanceRequisitionNumber());
   miscbilldetail.setBilldate(advanceRequisition.getAdvanceRequisitionDate());
   miscbilldetail.setBillamount(advanceRequisition.getAdvanceRequisitionAmount());
   miscbilldetail.setPassedamount(advanceRequisition.getAdvanceRequisitionAmount());
   miscbilldetail.setPaidamount(advanceRequisition.getAdvanceRequisitionAmount());
   miscbilldetail.setPaidto(advanceRequisition.getEgAdvanceReqMises().getPayto());
   miscbilldetail.setPayVoucherHeader(paymentheader.getVoucherheader());
   miscbilldetailService.persist(miscbilldetail);
 }
  private CVoucherHeader createVoucherAndledger() {
    try {
      final HashMap<String, Object> headerDetails = createHeaderAndMisDetails();
      headerDetails.put(
          VoucherConstant.SOURCEPATH, "/EGF/payment/advancePayment!view.action?voucherHeader.id=");
      HashMap<String, Object> detailMap = null;
      HashMap<String, Object> subledgertDetailMap = null;
      final List<HashMap<String, Object>> accountdetails = new ArrayList<HashMap<String, Object>>();
      final List<HashMap<String, Object>> subledgerDetails =
          new ArrayList<HashMap<String, Object>>();

      detailMap = new HashMap<String, Object>();
      detailMap.put(VoucherConstant.CREDITAMOUNT, advanceRequisition.getAdvanceRequisitionAmount());
      detailMap.put(VoucherConstant.DEBITAMOUNT, ZERO);
      Bankaccount account =
          (Bankaccount)
              HibernateUtil.getCurrentSession()
                  .load(Bankaccount.class, Integer.valueOf(commonBean.getAccountNumberId()));
      detailMap.put(VoucherConstant.GLCODE, account.getChartofaccounts().getGlcode());
      accountdetails.add(detailMap);
      Map<String, Object> glcodeMap = new HashMap<String, Object>();
      detailMap = new HashMap<String, Object>();

      detailMap.put(VoucherConstant.DEBITAMOUNT, advanceRequisition.getAdvanceRequisitionAmount());
      detailMap.put(VoucherConstant.CREDITAMOUNT, ZERO);
      for (EgAdvanceRequisitionDetails advanceRequisitionDetails :
          advanceRequisition.getEgAdvanceReqDetailses()) {
        detailMap.put(
            VoucherConstant.GLCODE, advanceRequisitionDetails.getChartofaccounts().getGlcode());
      }
      accountdetails.add(detailMap);
      glcodeMap.put(detailMap.get(VoucherConstant.GLCODE).toString(), VoucherConstant.DEBIT);

      subledgertDetailMap = new HashMap<String, Object>();
      for (EgAdvanceRequisitionDetails advanceDetail :
          advanceRequisition.getEgAdvanceReqDetailses()) {
        for (EgAdvanceReqPayeeDetails payeeDetail : advanceDetail.getEgAdvanceReqpayeeDetailses()) {
          subledgertDetailMap = new HashMap<String, Object>();
          subledgertDetailMap.put(VoucherConstant.DEBITAMOUNT, payeeDetail.getDebitAmount());
          subledgertDetailMap.put(VoucherConstant.CREDITAMOUNT, payeeDetail.getCreditAmount());
          subledgertDetailMap.put(
              VoucherConstant.DETAILTYPEID, payeeDetail.getAccountDetailType().getId());
          subledgertDetailMap.put(VoucherConstant.DETAILKEYID, payeeDetail.getAccountdetailKeyId());
          subledgertDetailMap.put(
              VoucherConstant.GLCODE, advanceDetail.getChartofaccounts().getGlcode());
          subledgerDetails.add(subledgertDetailMap);
        }
      }

      final CreateVoucher cv = new CreateVoucher();
      voucherHeader = cv.createPreApprovedVoucher(headerDetails, accountdetails, subledgerDetails);

    } catch (final HibernateException e) {
      LOGGER.error(e.getMessage(), e);
      throw new ValidationException(
          Arrays.asList(new ValidationError(EXCEPTION_WHILE_SAVING_DATA, FAILED)));
    } catch (final ApplicationRuntimeException e) {
      LOGGER.error(e.getMessage(), e);
      throw new ValidationException(
          Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    } catch (final ValidationException e) {
      LOGGER.error(e.getMessage(), e);
      throw e;
    } catch (final Exception e) {
      // handle engine exception
      LOGGER.error(e.getMessage(), e);
      throw new ValidationException(
          Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    }
    if (LOGGER.isDebugEnabled()) LOGGER.debug("Posted to Ledger " + voucherHeader.getId());
    return voucherHeader;
  }
 private void populateFund() {
   if (advanceRequisition != null && advanceRequisition.getEgAdvanceReqMises() != null)
     fund = advanceRequisition.getEgAdvanceReqMises().getFund();
 }