/**
   * @param searchCriteria
   * @param fieldsForLookup
   */
  protected void buildReportForSearchCriteia(
      List<ContractsGrantsReportSearchCriteriaDataHolder> searchCriteria, Map fieldsForLookup) {
    DataDictionaryService dataDictionaryService =
        SpringContext.getBean(DataDictionaryService.class);
    for (Object field : fieldsForLookup.keySet()) {

      String fieldString = (ObjectUtils.isNull(field)) ? "" : field.toString();
      String valueString =
          (ObjectUtils.isNull(fieldsForLookup.get(field)))
              ? ""
              : fieldsForLookup.get(field).toString();

      if (!fieldString.equals("")
          && !valueString.equals("")
          && !CGConstants.ReportsConstants.reportSearchCriteriaExceptionList.contains(
              fieldString)) {
        ContractsGrantsReportSearchCriteriaDataHolder criteriaData =
            new ContractsGrantsReportSearchCriteriaDataHolder();
        String label = dataDictionaryService.getAttributeLabel(Award.class, fieldString);
        criteriaData.setSearchFieldLabel(label);
        criteriaData.setSearchFieldValue(valueString);
        searchCriteria.add(criteriaData);
      }
    }
  }
  /**
   * @see
   *     org.kuali.kfs.module.ar.document.service.CustomerInvoiceDocumentService#checkIfInvoiceNumberIsFinal(java.lang.String)
   */
  @Override
  public boolean checkIfInvoiceNumberIsFinal(String invDocumentNumber) {
    boolean isSuccess = true;
    if (StringUtils.isBlank(invDocumentNumber)) {
      isSuccess &= false;
    } else {
      CustomerInvoiceDocument customerInvoiceDocument =
          getInvoiceByInvoiceDocumentNumber(invDocumentNumber);

      if (ObjectUtils.isNull(customerInvoiceDocument)) {
        isSuccess &= false;
      } else {
        Document doc = null;
        try {
          doc = documentService.getByDocumentHeaderId(invDocumentNumber);
        } catch (WorkflowException e) {
          isSuccess &= false;
        }
        if (ObjectUtils.isNull(doc)
            || ObjectUtils.isNull(doc.getDocumentHeader())
            || doc.getDocumentHeader().getWorkflowDocument() == null
            || !(doc.getDocumentHeader().getWorkflowDocument().isApproved()
                || doc.getDocumentHeader().getWorkflowDocument().isProcessed())) {
          isSuccess &= false;
        }
      }
    }
    return isSuccess;
  }
  /**
   * @see
   *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidMaximumNumberOfRecurrences(int,String)
   */
  @Override
  public boolean isValidMaximumNumberOfRecurrences(
      Integer totalRecurrenceNumber, String intervalCode) {

    if (ObjectUtils.isNull(intervalCode) || ObjectUtils.isNull(totalRecurrenceNumber)) {
      return true;
    }
    Integer maximumRecurrencesByInterval;
    if (ObjectUtils.isNotNull(intervalCode)) {
      List<String> maximumRecurrences =
          new ArrayList<String>(
              SpringContext.getBean(ParameterService.class)
                  .getSubParameterValuesAsString(
                      InvoiceRecurrence.class,
                      ArConstants.MAXIMUM_RECURRENCES_BY_INTERVAL,
                      intervalCode));
      if (maximumRecurrences.size() > 0 && StringUtils.isNotBlank(maximumRecurrences.get(0))) {
        maximumRecurrencesByInterval = Integer.valueOf(maximumRecurrences.get(0));
        if (totalRecurrenceNumber > maximumRecurrencesByInterval) {
          return false;
        }
      }
    }
    return true;
  }
  @Override
  public void recalculateCustomerCreditMemoDocument(
      CustomerCreditMemoDocument customerCreditMemoDocument,
      boolean blanketApproveDocumentEventFlag) {
    KualiDecimal customerCreditMemoDetailItemAmount;
    BigDecimal itemQuantity;

    String invDocumentNumber =
        customerCreditMemoDocument.getFinancialDocumentReferenceInvoiceNumber();
    List<CustomerCreditMemoDetail> customerCreditMemoDetails =
        customerCreditMemoDocument.getCreditMemoDetails();

    if (!blanketApproveDocumentEventFlag) {
      customerCreditMemoDocument.resetTotals();
    }

    for (CustomerCreditMemoDetail customerCreditMemoDetail : customerCreditMemoDetails) {
      // no data entered for the current credit memo detail -> no processing needed
      itemQuantity = customerCreditMemoDetail.getCreditMemoItemQuantity();
      customerCreditMemoDetailItemAmount = customerCreditMemoDetail.getCreditMemoItemTotalAmount();
      if (ObjectUtils.isNull(itemQuantity)
          && ObjectUtils.isNull(customerCreditMemoDetailItemAmount)) {
        if (!blanketApproveDocumentEventFlag) {
          customerCreditMemoDetail.setDuplicateCreditMemoItemTotalAmount(null);
        }
        continue;
      }

      // if item amount was entered, it takes precedence, if not, use the item quantity to re-calc
      // amount
      if (ObjectUtils.isNotNull(customerCreditMemoDetailItemAmount)) {
        customerCreditMemoDetail.recalculateBasedOnEnteredItemAmount(customerCreditMemoDocument);
      } // if item quantity was entered
      else {
        customerCreditMemoDetail.recalculateBasedOnEnteredItemQty(customerCreditMemoDocument);
        if (!blanketApproveDocumentEventFlag) {
          customerCreditMemoDetailItemAmount =
              customerCreditMemoDetail.getCreditMemoItemTotalAmount();
        }
      }

      if (!blanketApproveDocumentEventFlag) {
        customerCreditMemoDetail.setDuplicateCreditMemoItemTotalAmount(
            customerCreditMemoDetailItemAmount);
        boolean isCustomerInvoiceDetailTaxable =
            accountsReceivableTaxService.isCustomerInvoiceDetailTaxable(
                customerCreditMemoDocument.getInvoice(),
                customerCreditMemoDetail.getCustomerInvoiceDetail());
        customerCreditMemoDocument.recalculateTotals(
            customerCreditMemoDetailItemAmount, isCustomerInvoiceDetailTaxable);
      }
    }

    //  force the docHeader docTotal
    customerCreditMemoDocument
        .getFinancialSystemDocumentHeader()
        .setFinancialDocumentTotalAmount(customerCreditMemoDocument.getCrmTotalAmount());
  }
  /**
   * This method validates the unapplied attribute of the document.
   *
   * @param document
   * @return
   * @throws WorkflowException
   */
  public static boolean validateNonAppliedHolding(
      PaymentApplicationDocument applicationDocument, KualiDecimal totalFromControl)
      throws WorkflowException {
    NonAppliedHolding nonAppliedHolding = applicationDocument.getNonAppliedHolding();
    if (ObjectUtils.isNull(nonAppliedHolding)) {
      return true;
    }
    if (StringUtils.isNotEmpty(nonAppliedHolding.getCustomerNumber())) {
      KualiDecimal nonAppliedAmount = nonAppliedHolding.getFinancialDocumentLineAmount();
      if (null == nonAppliedAmount) {
        nonAppliedAmount = KualiDecimal.ZERO;
      }
      boolean isValid = totalFromControl.isGreaterEqual(nonAppliedAmount);
      if (!isValid) {
        String propertyName = ArPropertyConstants.PaymentApplicationDocumentFields.UNAPPLIED_AMOUNT;
        String errorKey =
            ArKeyConstants.PaymentApplicationDocumentErrors
                .UNAPPLIED_AMOUNT_CANNOT_EXCEED_AVAILABLE_AMOUNT;
        GlobalVariables.getMessageMap().putError(propertyName, errorKey);
      }
      // The amount of the unapplied can't exceed the remaining balance to be applied
      KualiDecimal totalBalanceToBeApplied = applicationDocument.getUnallocatedBalance();
      isValid = KualiDecimal.ZERO.isLessEqual(totalBalanceToBeApplied);
      if (!isValid) {
        String propertyName = ArPropertyConstants.PaymentApplicationDocumentFields.UNAPPLIED_AMOUNT;
        String errorKey =
            ArKeyConstants.PaymentApplicationDocumentErrors
                .UNAPPLIED_AMOUNT_CANNOT_EXCEED_BALANCE_TO_BE_APPLIED;
        GlobalVariables.getMessageMap().putError(propertyName, errorKey);
      }

      //  the unapplied amount cannot be negative
      isValid = nonAppliedAmount.isPositive() || nonAppliedAmount.isZero();
      if (!isValid) {
        String propertyName = ArPropertyConstants.PaymentApplicationDocumentFields.UNAPPLIED_AMOUNT;
        String errorKey =
            ArKeyConstants.PaymentApplicationDocumentErrors.AMOUNT_TO_BE_APPLIED_MUST_BE_POSTIIVE;
        GlobalVariables.getMessageMap().putError(propertyName, errorKey);
      }
      return isValid;
    } else {
      if (ObjectUtils.isNull(nonAppliedHolding.getFinancialDocumentLineAmount())
          || KualiDecimal.ZERO.equals(nonAppliedHolding.getFinancialDocumentLineAmount())) {
        // All's OK. Both customer number and amount are empty/null.
        return true;
      } else {
        // Error. Customer number is empty but amount wasn't.
        String propertyName =
            ArPropertyConstants.PaymentApplicationDocumentFields.UNAPPLIED_CUSTOMER_NUMBER;
        String errorKey =
            ArKeyConstants.PaymentApplicationDocumentErrors
                .UNAPPLIED_AMOUNT_CANNOT_BE_EMPTY_OR_ZERO;
        GlobalVariables.getMessageMap().putError(propertyName, errorKey);
        return false;
      }
    }
  }
 /**
  * @see
  *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidEndDateOrTotalRecurrenceNumber(Date,int)
  */
 @Override
 public boolean isValidEndDateOrTotalRecurrenceNumber(
     Date endDate, Integer totalRecurrenceNumber) {
   boolean success = true;
   if (ObjectUtils.isNull(endDate) && ObjectUtils.isNull(totalRecurrenceNumber)) {
     return false;
   }
   return success;
 }
  /**
   * This method checks that an invoice paid applied is for a valid amount.
   *
   * @param invoicePaidApplied
   * @return
   */
  public static boolean validateInvoicePaidApplied(
      InvoicePaidApplied invoicePaidApplied,
      String fieldName,
      PaymentApplicationDocument document) {
    boolean isValid = true;

    invoicePaidApplied.refreshReferenceObject("invoiceDetail");
    if (ObjectUtils.isNull(invoicePaidApplied)
        || ObjectUtils.isNull(invoicePaidApplied.getInvoiceDetail())) {
      return true;
    }
    KualiDecimal amountOwed = invoicePaidApplied.getInvoiceDetail().getAmountOpen();
    KualiDecimal amountPaid = invoicePaidApplied.getInvoiceItemAppliedAmount();

    if (ObjectUtils.isNull(amountOwed)) {
      amountOwed = KualiDecimal.ZERO;
    }
    if (ObjectUtils.isNull(amountPaid)) {
      amountPaid = KualiDecimal.ZERO;
    }

    // Can't pay more than you owe.
    if (!amountPaid.isLessEqual(amountOwed)) {
      isValid = false;
      LOG.debug(
          "InvoicePaidApplied is not valid. Amount to be applied exceeds amount outstanding.");
      GlobalVariables.getMessageMap()
          .putError(
              fieldName,
              ArKeyConstants.PaymentApplicationDocumentErrors
                  .AMOUNT_TO_BE_APPLIED_EXCEEDS_AMOUNT_OUTSTANDING);
    }

    // Can't apply more than the amount received via the related CashControlDocument
    if (amountPaid.isGreaterThan(document.getTotalFromControl())) {
      isValid = false;
      LOG.debug(
          "InvoicePaidApplied is not valid. Cannot apply more than cash control total amount.");
      GlobalVariables.getMessageMap()
          .putError(
              fieldName,
              ArKeyConstants.PaymentApplicationDocumentErrors
                  .CANNOT_APPLY_MORE_THAN_CASH_CONTROL_TOTAL_AMOUNT);
    }

    //  cant apply negative amounts
    if (amountPaid.isNegative() && !document.hasCashControlDocument()) {
      isValid = false;
      LOG.debug("InvoicePaidApplied is not valid. Amount to be applied must be positive.");
      GlobalVariables.getMessageMap()
          .putError(
              fieldName,
              ArKeyConstants.PaymentApplicationDocumentErrors
                  .AMOUNT_TO_BE_APPLIED_MUST_BE_POSTIIVE);
    }
    return isValid;
  }
  /**
   * This method prepare the report model object to display on jsp page.
   *
   * @param invoices
   * @param results
   */
  protected void populateReportDetails(
      List<ContractsGrantsInvoiceDocument> invoices, List results) {
    for (ContractsGrantsInvoiceDocument invoice : invoices) {
      ContractsGrantsAgingOpenInvoicesReport detail = new ContractsGrantsAgingOpenInvoicesReport();
      // Document Type
      detail.setDocumentType(
          invoice.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
      // Document Number
      detail.setDocumentNumber(invoice.getDocumentNumber());
      // Document Description
      String documentDescription = invoice.getDocumentHeader().getDocumentDescription();
      if (ObjectUtils.isNotNull(documentDescription)) {
        detail.setDocumentDescription(documentDescription);
      } else {
        detail.setDocumentDescription("");
      }
      // Billing Date
      detail.setBillingDate(invoice.getBillingDate());
      // Due Date
      detail.setDueApprovedDate(invoice.getInvoiceDueDate());
      // Document Payment Amount
      detail.setDocumentPaymentAmount(
          invoice.getFinancialSystemDocumentHeader().getFinancialDocumentTotalAmount());
      // Unpaid/Unapplied Amount
      detail.setUnpaidUnappliedAmount(
          customerInvoiceDocumentService.getOpenAmountForCustomerInvoiceDocument(invoice));
      detail.setFinalInvoice(
          !ObjectUtils.isNull(invoice.getInvoiceGeneralDetail())
                  && invoice.getInvoiceGeneralDetail().isFinalBillIndicator()
              ? KFSConstants.ParameterValues.STRING_YES
              : KFSConstants.ParameterValues.STRING_NO);
      // set agency number, proposal number, account number
      if (!ObjectUtils.isNull(invoice.getInvoiceGeneralDetail())
          && !ObjectUtils.isNull(invoice.getInvoiceGeneralDetail().getProposalNumber())) {
        detail.setProposalNumber(invoice.getInvoiceGeneralDetail().getProposalNumber().toString());
      }

      // Set Agency Number
      ContractsAndGrantsBillingAgency cgAgency =
          this.getAgencyByCustomer(
              invoice.getAccountsReceivableDocumentHeader().getCustomerNumber());
      if (ObjectUtils.isNotNull(cgAgency)) {
        detail.setAgencyNumber(cgAgency.getAgencyNumber());
      }

      // Set Account number
      List<CustomerInvoiceDetail> details = invoice.getSourceAccountingLines();
      String accountNum =
          (CollectionUtils.isNotEmpty(details) && ObjectUtils.isNotNull(details.get(0)))
              ? details.get(0).getAccountNumber()
              : "";
      detail.setAccountNumber(accountNum);
      results.add(detail);
    }
  }
  /**
   * @see
   *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidEndDateAndTotalRecurrenceNumber(Date,Date,int,String)
   */
  @Override
  public boolean isValidEndDateAndTotalRecurrenceNumber(
      Date recurrenceBeginDate,
      Date recurrenceEndDate,
      Integer totalRecurrenceNumber,
      String recurrenceIntervalCode) {

    if (ObjectUtils.isNull(recurrenceBeginDate)
        || ObjectUtils.isNull(recurrenceIntervalCode)
        || ObjectUtils.isNull(recurrenceEndDate)
        || ObjectUtils.isNull(totalRecurrenceNumber)) {
      return true;
    }

    Calendar beginCalendar = Calendar.getInstance();
    beginCalendar.setTime(recurrenceBeginDate);
    Date beginDate = recurrenceBeginDate;
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(recurrenceEndDate);
    Date endDate = recurrenceEndDate;
    Calendar nextCalendar = Calendar.getInstance();
    Date nextDate = beginDate;

    int totalRecurrences = 0;
    int addCounter = 0;
    String intervalCode = recurrenceIntervalCode;
    if (intervalCode.equals("M")) {
      addCounter = 1;
    }
    if (intervalCode.equals("Q")) {
      addCounter = 3;
    }
    /* perform this loop while begin_date is less than or equal to end_date */
    while (!(beginDate.after(endDate))) {
      beginCalendar.setTime(beginDate);
      beginCalendar.add(Calendar.MONTH, addCounter);
      beginDate = KfsDateUtils.convertToSqlDate(beginCalendar.getTime());
      totalRecurrences++;

      nextDate = beginDate;
      nextCalendar.setTime(nextDate);
      nextCalendar.add(Calendar.MONTH, addCounter);
      nextDate = KfsDateUtils.convertToSqlDate(nextCalendar.getTime());
      if (endDate.after(beginDate) && endDate.before(nextDate)) {
        totalRecurrences++;
        break;
      }
    }
    if (totalRecurrences != totalRecurrenceNumber.intValue()) {
      return false;
    }

    return true;
  }
 /**
  * For reimbursable documents, sets the proper payee type code and profile id after a profile
  * lookup
  */
 public void updatePayeeTypeForReimbursable() {
   if (!ObjectUtils.isNull(getTraveler())
       && !ObjectUtils.isNull(getTravelPayment())
       && !StringUtils.isBlank(getTraveler().getTravelerTypeCode())) {
     if (getTravelerService().isEmployee(getTraveler())) {
       getTravelPayment().setPayeeTypeCode(KFSConstants.PaymentPayeeTypes.EMPLOYEE);
     } else {
       getTravelPayment().setPayeeTypeCode(KFSConstants.PaymentPayeeTypes.CUSTOMER);
     }
   }
 }
  /**
   * calculates the remainder of fiscal year estimated income for pooled funds
   *
   * @param security
   * @param holdingTaxLot
   * @return amount
   */
  protected BigDecimal getRemainderOfFiscalYearEstimatedIncomeForPooledFunds(
      Security security, HoldingTaxLot holdingTaxLot) {
    BigDecimal amount = BigDecimal.ZERO;

    if (ObjectUtils.isNull(security.getIncomeNextPayDate())
        || ObjectUtils.isNull(security.getFrequencyCode())) {
      return amount;
    }

    Date nextIncomeDueDate = security.getIncomeNextPayDate();
    if (ObjectUtils.isNull(nextIncomeDueDate)) {
      return amount;
    }

    Date fiscalYearEndDate = getFiscalYearEndDate();

    // BONDS - rule 4.a
    if (nextIncomeDueDate.after(fiscalYearEndDate)) {
      return BigDecimal.ZERO;
    }

    // rule 4.b
    if (nextIncomeDueDate.before(fiscalYearEndDate)) {
      String incomePayFrequency = security.getIncomePayFrequency();
      if (ObjectUtils.isNull(incomePayFrequency)) {
        return amount;
      }

      Date lastPaymentDate = getLastPaymentDate(incomePayFrequency, fiscalYearEndDate);

      long paymentsRemaining =
          getTotalPaymentsRemaining(
              lastPaymentDate, fiscalYearEndDate, incomePayFrequency, nextIncomeDueDate);

      long totalNumberOfPayments = kEMService.getTotalNumberOfPaymentsForFiscalYear();

      amount =
          KEMCalculationRoundingHelper.multiply(
              holdingTaxLot.getUnits(),
              security.getIncomeRate(),
              EndowConstants.Scale.SECURITY_MARKET_VALUE);
      amount = amount.multiply(BigDecimal.valueOf(paymentsRemaining));
      amount =
          KEMCalculationRoundingHelper.divide(
              amount,
              BigDecimal.valueOf(totalNumberOfPayments),
              EndowConstants.Scale.SECURITY_MARKET_VALUE);
      amount = amount.add(holdingTaxLot.getCurrentAccrual());
    }

    return amount;
  }
  /**
   * calculates the remainder of fiscal year estimated income for stocks
   *
   * @param security
   * @param holdingTaxLot
   * @return amount
   */
  protected BigDecimal getRemainderOfFiscalYearEstimatedIncomeForStocks(
      Security security, HoldingTaxLot holdingTaxLot) {
    BigDecimal amount = BigDecimal.ZERO;

    if (ObjectUtils.isNull(security.getIncomeRate())
        || security.getIncomeRate().compareTo(BigDecimal.ZERO) == 0) {
      return amount;
    }

    String incomePayFrequency = security.getIncomePayFrequency();
    Date nextIncomeDueDate = security.getIncomeNextPayDate();

    if (ObjectUtils.isNull(nextIncomeDueDate)) {
      return amount;
    }

    Date fiscalYearEndDate = getFiscalYearEndDate();

    // BONDS - rule 4.a
    if (nextIncomeDueDate.after(fiscalYearEndDate)) {
      return BigDecimal.ZERO;
    }

    int numberOfMonthsRemaing = getNumberOfMonthsRemaining(fiscalYearEndDate, nextIncomeDueDate);

    if (nextIncomeDueDate.before(fiscalYearEndDate) && numberOfMonthsRemaing < 4) {
      return BigDecimal.ZERO;
    }

    long quartersLeftToFiscalYear = getQuartersLeftToFiscalYear(fiscalYearEndDate);

    // calculate holding units times security rate....
    amount =
        KEMCalculationRoundingHelper.multiply(
            holdingTaxLot.getUnits(),
            security.getIncomeRate(),
            EndowConstants.Scale.SECURITY_MARKET_VALUE);

    // now multiply the above amount by 4 to get amount for 4 quarters or for the year...
    amount =
        KEMCalculationRoundingHelper.divide(
            amount, BigDecimal.valueOf(4), EndowConstants.Scale.SECURITY_MARKET_VALUE);

    // now compute the amount for the quarters remaining in the fiscal year....
    amount =
        KEMCalculationRoundingHelper.multiply(
            amount,
            BigDecimal.valueOf(quartersLeftToFiscalYear),
            EndowConstants.Scale.SECURITY_MARKET_VALUE);

    return amount;
  }
 /**
  * @see
  *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidRecurrenceEndDate(Date)
  */
 @Override
 public boolean isValidRecurrenceEndDate(Date beginDate, Date endDate) {
   boolean success = true;
   if (ObjectUtils.isNull(beginDate) || ObjectUtils.isNull(endDate)) {
     return success;
   }
   Timestamp beginDateTimestamp = new Timestamp(beginDate.getTime());
   Timestamp endDateTimestamp = new Timestamp(endDate.getTime());
   if ((ObjectUtils.isNotNull(endDateTimestamp))
       && (endDateTimestamp.before(beginDateTimestamp)
           || endDateTimestamp.equals(beginDateTimestamp))) {
     return false;
   }
   return success;
 }
  /**
   * @see
   *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isInvoiceApproved(String)
   */
  @Override
  public boolean isInvoiceApproved(String invoiceNumber) {
    boolean success = true;

    if (ObjectUtils.isNull(invoiceNumber)) {
      return success;
    }

    CustomerInvoiceDocument customerInvoiceDocument = null;
    try {
      customerInvoiceDocument =
          (CustomerInvoiceDocument)
              SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(invoiceNumber);
    } catch (WorkflowException e) {

    }
    if (ObjectUtils.isNotNull(customerInvoiceDocument)) {
      WorkflowDocument workflowDocument =
          customerInvoiceDocument.getDocumentHeader().getWorkflowDocument();
      if (!(workflowDocument.isApproved())) {
        success = false;
      }
    } else {
      success = false;
    }
    return success;
  }
 /**
  * Finds the vendor number from the first historical travel expense associated with the given
  * document
  *
  * @param document a document to find a corporate card vendor for
  * @return the id of the found vendor or null if nothing was found
  */
 protected String findCorporateCardVendorNumber(TEMReimbursementDocument document) {
   final CreditCardAgency creditCardAgency = getCorporateCreditCardAgency(document);
   if (!ObjectUtils.isNull(creditCardAgency)) {
     return creditCardAgency.getVendorNumber();
   }
   return null;
 }
  /**
   * Validates that the existance of the building room number is consistent with the asset type
   * requirements.
   *
   * @param roomNumber
   * @param detail
   * @prarm asset
   * @return boolean
   * @deprecated this method is replaced by
   *     validateBuildingCodeAndRoomNumber(BarcodeInventoryErrorDetail, Asset)
   */
  @Deprecated
  protected boolean validateBuildingRoomNumber(
      String roomNumber, BarcodeInventoryErrorDetail detail, Asset asset) {
    boolean result = true;
    String label =
        SpringContext.getBean(DataDictionaryService.class)
            .getDataDictionary()
            .getBusinessObjectEntry(BarcodeInventoryErrorDetail.class.getName())
            .getAttributeDefinition(CamsPropertyConstants.BarcodeInventory.BUILDING_ROOM_NUMBER)
            .getLabel();
    // String description = asset.getCapitalAssetType().getCapitalAssetTypeDescription();
    String description = asset.getCapitalAssetTypeCode();

    // if the asset has empty building room number, then the BCIE should too
    if (StringUtils.isBlank(asset.getBuildingRoomNumber())) {
      if (StringUtils.isNotBlank(roomNumber)) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.BUILDING_ROOM_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_NOT_ALLOWED_FIELD,
                label,
                description);
        result &= false;
      }
    }
    // otherwise the BCIE should have a non-empty and existing active building room number
    else {
      HashMap<String, Object> fields = new HashMap<String, Object>();
      fields.put(KFSPropertyConstants.CAMPUS_CODE, detail.getCampusCode());
      fields.put(KFSPropertyConstants.BUILDING_CODE, detail.getBuildingCode());
      fields.put(KFSPropertyConstants.BUILDING_ROOM_NUMBER, detail.getBuildingRoomNumber());
      Room room = getBusinessObjectService().findByPrimaryKey(Room.class, fields);

      if (StringUtils.isBlank(roomNumber)) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.BUILDING_ROOM_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_REQUIRED_FIELD,
                label,
                description);
        result &= false;
      } else if (ObjectUtils.isNull(room)) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.BUILDING_ROOM_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_INVALID_FIELD,
                label);
        result = false;
      } else if (!room.isActive()) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.BUILDING_ROOM_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_INACTIVE_FIELD,
                label);
        result &= false;
      }
    }

    return result;
  }
  /**
   * Validates the campus code exists in the campus code table
   *
   * @param campusCode
   * @param detail
   * @return boolean
   */
  protected boolean validateCampusCode(String campusCode, BarcodeInventoryErrorDetail detail) {
    boolean result = true;
    String label =
        SpringContext.getBean(DataDictionaryService.class)
            .getDataDictionary()
            .getBusinessObjectEntry(BarcodeInventoryErrorDetail.class.getName())
            .getAttributeDefinition(CamsPropertyConstants.BarcodeInventory.CAMPUS_CODE)
            .getLabel();

    Campus campus;
    HashMap<String, Object> fields = new HashMap<String, Object>();
    fields.put(KFSPropertyConstants.CAMPUS_CODE, detail.getCampusCode());
    campus =
        SpringContext.getBean(CampusService.class)
            .getCampus(campusCode /*RICE_20_REFACTORME  fields */);

    if (ObjectUtils.isNull(campus)) {
      GlobalVariables.getMessageMap()
          .putError(
              CamsPropertyConstants.BarcodeInventory.CAMPUS_CODE,
              CamsKeyConstants.BarcodeInventory.ERROR_INVALID_FIELD,
              label);
      result = false;
    } else if (!campus.isActive()) {
      GlobalVariables.getMessageMap()
          .putError(
              CamsPropertyConstants.BarcodeInventory.CAMPUS_CODE,
              CamsKeyConstants.BarcodeInventory.ERROR_INACTIVE_FIELD,
              label);
      result &= false;
    }
    return result;
  }
  /** This method changes account to suspenseAccount */
  protected Message useSuspenseAccount(LaborOriginEntry workingEntry) {
    String suspenseAccountNumber =
        parameterService.getParameterValueAsString(
            LaborScrubberStep.class, LaborConstants.Scrubber.SUSPENSE_ACCOUNT);
    String suspenseCOAcode =
        parameterService.getParameterValueAsString(
            LaborScrubberStep.class, LaborConstants.Scrubber.SUSPENSE_CHART);
    String suspenseSubAccountNumber =
        parameterService.getParameterValueAsString(
            LaborScrubberStep.class, LaborConstants.Scrubber.SUSPENSE_SUB_ACCOUNT);

    Account account = accountService.getByPrimaryId(suspenseCOAcode, suspenseAccountNumber);

    if (ObjectUtils.isNull(account)) {
      return MessageBuilder.buildMessage(
          LaborKeyConstants.ERROR_INVALID_SUSPENSE_ACCOUNT, Message.TYPE_FATAL);
    }

    workingEntry.setAccount(account);
    workingEntry.setAccountNumber(suspenseAccountNumber);
    workingEntry.setChartOfAccountsCode(suspenseCOAcode);
    workingEntry.setSubAccountNumber(suspenseSubAccountNumber);

    return MessageBuilder.buildMessageWithPlaceHolder(
        LaborKeyConstants.MESSAGE_SUSPENSE_ACCOUNT_APPLIED,
        Message.TYPE_WARNING,
        new Object[] {suspenseCOAcode, suspenseAccountNumber, suspenseSubAccountNumber});
  }
Beispiel #19
0
 public List<SponsorDTO> getMatchingSponsors(SponsorCriteriaDto searchCriteria) {
   List<SponsorDTO> results = new ArrayList<SponsorDTO>();
   Collection<Sponsor> sponsors;
   if (ObjectUtils.isNull(searchCriteria)
       || (StringUtils.isEmpty(searchCriteria.getSponsorCode())
           && StringUtils.isEmpty(searchCriteria.getCustomerNumber()))) {
     sponsors = getBusinessObjectService().findAll(Sponsor.class);
   } else if (StringUtils.isNotEmpty(searchCriteria.getSponsorCode())) {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("sponsorCode", searchCriteria.getSponsorCode()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   } else {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("customerNumber", searchCriteria.getCustomerNumber()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   }
   if (sponsors != null && !sponsors.isEmpty()) {
     for (Sponsor sponsor : sponsors) {
       results.add(sponsorDtoService.buildDto(sponsor));
     }
   }
   return results;
 }
 /**
  * Adding the role qualifications for the processing chart and organization
  *
  * @see
  *     org.kuali.rice.kns.document.authorization.DocumentAuthorizerBase#addRoleQualification(org.kuali.rice.kns.bo.BusinessObject,
  *     java.util.Map)
  */
 @Override
 protected void addRoleQualification(Object businessObject, Map<String, String> attributes) {
   super.addRoleQualification(businessObject, attributes);
   if (businessObject != null && businessObject instanceof PaymentApplicationDocument) {
     final PaymentApplicationDocument document = (PaymentApplicationDocument) businessObject;
     final WorkflowDocument workflowDocument = document.getDocumentHeader().getWorkflowDocument();
     if (workflowDocument.isInitiated()
         || workflowDocument.isSaved()
         || workflowDocument
             .isCompletionRequested()) { // only add processing chart and org if we're PreRoute
       final AccountsReceivableDocumentHeader arDocumentHeader =
           document.getAccountsReceivableDocumentHeader();
       if (!ObjectUtils.isNull(arDocumentHeader)) {
         if (!StringUtils.isBlank(arDocumentHeader.getProcessingChartOfAccCodeAndOrgCode())) {
           attributes.put(
               KfsKimAttributes.CHART_OF_ACCOUNTS_CODE,
               arDocumentHeader.getProcessingChartOfAccountCode());
         }
         if (!StringUtils.isBlank(arDocumentHeader.getProcessingOrganizationCode())) {
           attributes.put(
               KfsKimAttributes.ORGANIZATION_CODE,
               arDocumentHeader.getProcessingOrganizationCode());
         }
       }
     }
   }
 }
 /**
  * @see
  *     org.kuali.rice.kns.web.struts.action.KualiLookupAction#execute(org.apache.struts.action.ActionMapping,
  *     org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest,
  *     javax.servlet.http.HttpServletResponse)
  */
 @Override
 public ActionForward execute(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   String sortIndexParameter = request.getParameter("d-16544-s");
   if (sortIndexParameter != null) {
     // to store how many times user clicks sort links
     Integer clickedSession =
         ObjectUtils.isNull(
                 GlobalVariables.getUserSession()
                     .retrieveObject(ArConstants.NUM_SORT_INDEX_CLICK_SESSION_KEY))
             ? new Integer(1)
             : (Integer)
                 GlobalVariables.getUserSession()
                     .retrieveObject(ArConstants.NUM_SORT_INDEX_CLICK_SESSION_KEY);
     if (ObjectUtils.isNotNull(
             GlobalVariables.getUserSession().retrieveObject(ArConstants.SORT_INDEX_SESSION_KEY))
         && GlobalVariables.getUserSession()
             .retrieveObject(ArConstants.SORT_INDEX_SESSION_KEY)
             .toString()
             .equals(sortIndexParameter)) {
       GlobalVariables.getUserSession()
           .addObject(
               ArConstants.NUM_SORT_INDEX_CLICK_SESSION_KEY, new Integer(clickedSession + 1));
     }
     GlobalVariables.getUserSession()
         .addObject(ArConstants.SORT_INDEX_SESSION_KEY, sortIndexParameter);
   }
   return super.execute(mapping, form, request, response);
 }
  /**
   * Validates the condition code exists in the condition table
   *
   * @param conditionCode
   * @param detail
   * @return boolean
   */
  protected boolean validateConditionCode(
      String conditionCode, BarcodeInventoryErrorDetail detail) {
    boolean result = true;
    String label =
        SpringContext.getBean(DataDictionaryService.class)
            .getDataDictionary()
            .getBusinessObjectEntry(BarcodeInventoryErrorDetail.class.getName())
            .getAttributeDefinition(CamsPropertyConstants.BarcodeInventory.ASSET_CONDITION_CODE)
            .getLabel();

    AssetCondition condition;
    HashMap<String, Object> fields = new HashMap<String, Object>();
    fields.put(
        CamsPropertyConstants.BarcodeInventory.ASSET_CONDITION_CODE,
        detail.getAssetConditionCode());
    condition = getBusinessObjectService().findByPrimaryKey(AssetCondition.class, fields);

    if (ObjectUtils.isNull(condition)) {
      GlobalVariables.getMessageMap()
          .putError(
              CamsPropertyConstants.BarcodeInventory.ASSET_CONDITION_CODE,
              CamsKeyConstants.BarcodeInventory.ERROR_INVALID_FIELD,
              label);
      result &= false;
    } else if (!condition.isActive()) {
      GlobalVariables.getMessageMap()
          .putError(
              CamsPropertyConstants.BarcodeInventory.ASSET_CONDITION_CODE,
              CamsKeyConstants.BarcodeInventory.ERROR_INACTIVE_FIELD,
              label);
      result &= false;
    }

    return result;
  }
Beispiel #23
0
  /**
   * @see
   *     org.kuali.kfs.module.cab.document.service.PurApLineService#setPurchaseOrderInfo(org.kuali.kfs.module.cab.document.web.struts.PurApLineForm)
   */
  public void setPurchaseOrderFromPurAp(PurApLineForm purApLineForm) {
    PurchaseOrderDocument purchaseOrderDocument =
        getCurrentDocumentForPurchaseOrderIdentifier(purApLineForm.getPurchaseOrderIdentifier());

    if (ObjectUtils.isNull(purchaseOrderDocument)) {
      return;
    }
    // Set contact email address.
    if (purchaseOrderDocument.getInstitutionContactEmailAddress() != null) {
      purApLineForm.setPurApContactEmailAddress(
          purchaseOrderDocument.getInstitutionContactEmailAddress());
    } else if (purchaseOrderDocument.getRequestorPersonEmailAddress() != null) {
      purApLineForm.setPurApContactEmailAddress(
          purchaseOrderDocument.getRequestorPersonEmailAddress());
    }

    // Set contact phone number.
    if (purchaseOrderDocument.getInstitutionContactPhoneNumber() != null) {
      purApLineForm.setPurApContactPhoneNumber(
          purchaseOrderDocument.getInstitutionContactPhoneNumber());
    } else if (purchaseOrderDocument.getRequestorPersonPhoneNumber() != null) {
      purApLineForm.setPurApContactPhoneNumber(
          purchaseOrderDocument.getRequestorPersonPhoneNumber());
    }

    // set reqs_id
    purApLineForm.setRequisitionIdentifier(purchaseOrderDocument.getRequisitionIdentifier());
  }
Beispiel #24
0
  public boolean processSyncModularBusinessRules(Document document) {
    if (!(document instanceof BudgetDocument)) {
      return false;
    }

    boolean valid = true;

    BudgetDocument budgetDocument = (BudgetDocument) document;

    GlobalVariables.getMessageMap().addToErrorPath("document");

    List budgetPeriods = budgetDocument.getBudget().getBudgetPeriods();
    if (ObjectUtils.isNotNull(budgetPeriods) || budgetPeriods.size() >= 1) {
      BudgetPeriod period1 = (BudgetPeriod) budgetPeriods.get(0);
      if (ObjectUtils.isNull(period1.getBudgetLineItems())
          || period1.getBudgetLineItems().isEmpty()) {
        valid = false;
      }
    } else {
      valid = false;
    }

    if (!valid) {
      GlobalVariables.getMessageMap()
          .putError("modularBudget", KeyConstants.ERROR_NO_DETAILED_BUDGET);
    }

    GlobalVariables.getMessageMap().removeFromErrorPath("document");

    return valid;
  }
  /**
   * validates the asset tag number exists in only one active asset.
   *
   * @param tagNumber
   * @return boolean
   * @deprecated this method is replaced by validateTagNumberAndRetrieveActiveAsset(String)
   */
  @Deprecated
  protected boolean validateTagNumber(String tagNumber) {
    boolean result = true;
    // Getting a list of active assets.
    Collection<Asset> assets = getAssetService().findAssetsMatchingTagNumber(tagNumber);

    if (ObjectUtils.isNull(assets) || assets.isEmpty()) {
      GlobalVariables.getMessageMap()
          .putError(
              CamsPropertyConstants.BarcodeInventory.ASSET_TAG_NUMBER,
              CamsKeyConstants.BarcodeInventory.ERROR_CAPITAL_ASSET_DOESNT_EXIST);
      result = false;
    } else {
      int activeAssets = assets.size();
      for (Asset asset : assets) {
        if (getAssetService().isAssetRetired(asset)) {
          activeAssets--;
        }
      }
      if (activeAssets == 0) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.ASSET_TAG_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_CAPITAL_ASSET_IS_RETIRED);
        result = false;
      } else if (activeAssets > 1) {
        GlobalVariables.getMessageMap()
            .putError(
                CamsPropertyConstants.BarcodeInventory.ASSET_TAG_NUMBER,
                CamsKeyConstants.BarcodeInventory.ERROR_DUPLICATED_TAG_NUMBER);
        result = false;
      }
    }
    return result;
  }
 protected boolean hasSalesTaxBeenEntered(
     AccountingLine accountingLine, boolean source, boolean newLine, int index) {
   boolean entered = true;
   String objCd = accountingLine.getFinancialObjectCode();
   String account = accountingLine.getAccountNumber();
   SalesTax salesTax = accountingLine.getSalesTax();
   if (ObjectUtils.isNull(salesTax)) {
     return false;
   }
   if (StringUtils.isBlank(salesTax.getChartOfAccountsCode())) {
     entered &= false;
   }
   if (StringUtils.isBlank(salesTax.getAccountNumber())) {
     entered &= false;
   }
   if (salesTax.getFinancialDocumentGrossSalesAmount() == null) {
     entered &= false;
   }
   if (salesTax.getFinancialDocumentTaxableSalesAmount() == null) {
     entered &= false;
   }
   if (salesTax.getFinancialDocumentSaleDate() == null) {
     entered &= false;
   }
   return entered;
 }
  /**
   * This method this returns true if system information row exists for processing chart and org
   *
   * @param organizationOptions
   * @return
   */
  public boolean doesSystemInformationExistForProcessingChartAngOrg(
      OrganizationOptions organizationOptions) {
    boolean success = true;

    String processingChartOfAccountCode = organizationOptions.getProcessingChartOfAccountCode();
    String processingOrganizationCode = organizationOptions.getProcessingOrganizationCode();

    Map criteria = new HashMap();
    criteria.put(
        KFSConstants.UNIVERSITY_FISCAL_YEAR_PROPERTY_NAME,
        SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear());
    criteria.put(
        ArPropertyConstants.OrganizationOptionsFields.PROCESSING_CHART_OF_ACCOUNTS_CODE,
        processingChartOfAccountCode);
    criteria.put(
        ArPropertyConstants.OrganizationOptionsFields.PROCESSING_ORGANIZATION_CODE,
        processingOrganizationCode);

    SystemInformation systemInformation =
        (SystemInformation)
            SpringContext.getBean(BusinessObjectService.class)
                .findByPrimaryKey(SystemInformation.class, criteria);

    if (ObjectUtils.isNull(systemInformation)) {
      putFieldError(
          ArPropertyConstants.OrganizationOptionsFields.PROCESSING_CHART_OF_ACCOUNTS_CODE,
          ArKeyConstants.OrganizationOptionsErrors
              .SYS_INFO_DOES_NOT_EXIST_FOR_PROCESSING_CHART_AND_ORG,
          new String[] {processingChartOfAccountCode, processingOrganizationCode});
      success = false;
    }
    return success;
  }
 /**
  * Return the New total allocation amount
  *
  * @return
  */
 public KualiDecimal getNewTotal() {
   KualiDecimal previousCostAmount = getPreviousTotalCostAmount();
   // KFSCNTRB-1667: if previous cost doesn't exist, regard the previous total as 0 amount
   if (ObjectUtils.isNull(previousCostAmount)) {
     previousCostAmount = new KualiDecimal(0);
   }
   return getAllocatedAmount().add(previousCostAmount);
 }
  private boolean verifyDocumentTypeCodes(
      String documentTypeCode, Collection<String> eligibleDocumentTypeCodes) {
    if (ObjectUtils.isNull(eligibleDocumentTypeCodes)
        || !eligibleDocumentTypeCodes.contains(documentTypeCode)) {
      return false;
    }

    return true;
  }
 /**
  * Finds the vendor for the corporate card used on the given document
  *
  * @param document the document to find a corporate card vendor for
  * @return the found vendor or null if a vendor could not be found
  */
 protected VendorDetail getCorporateCardVendor(CreditCardAgency creditCardAgency) {
   if (!ObjectUtils.isNull(creditCardAgency)) {
     final String vendorNumber = creditCardAgency.getVendorNumber();
     if (!StringUtils.isBlank(vendorNumber)) {
       return getVendorService().getByVendorNumber(vendorNumber);
     }
   }
   return null;
 }