@KcEventMethod
  public boolean processCheckBaseSalaryFormat(BudgetSaveEvent event) {
    boolean valid = true;

    MessageMap messageMap = GlobalVariables.getMessageMap();
    int i = 0;
    List<BudgetPerson> budgetPersons = event.getBudget().getBudgetPersons();
    for (BudgetPerson budgetPerson : budgetPersons) {
      if (budgetPerson.getCalculationBase() == null) {
        messageMap.putError(
            BUDGET_PERSONS_FIELD_NAME_START + i + BUDGET_PERSONS_FIELD_NAME_CALC_BASE,
            RiceKeyConstants.ERROR_REQUIRED,
            new String[] {"Base Salary"});
        valid = false;
      } else if (budgetPerson.getCalculationBase().isNegative()) {
        messageMap.putError(
            BUDGET_PERSONS_FIELD_NAME_START + i + BUDGET_PERSONS_FIELD_NAME_CALC_BASE,
            KeyConstants.ERROR_NEGATIVE_AMOUNT,
            new String[] {"Base Salary"});
        valid = false;
      }
      i++;
    }

    return valid;
  }
  /**
   * Retrieves validation errors from GlobalVariables MessageMap and appends to the given list of
   * RemotableAttributeError
   *
   * @param validationErrors list to append validation errors
   */
  protected void retrieveValidationErrorsFromGlobalVariables(
      List<RemotableAttributeError> validationErrors) {
    // can we use KualiConfigurationService?  It seemed to be used elsewhere...
    ConfigurationService configurationService =
        CoreApiServiceLocator.getKualiConfigurationService();

    if (GlobalVariables.getMessageMap().hasErrors()) {
      MessageMap deepCopy =
          (MessageMap) SerializationUtils.deepCopy(GlobalVariables.getMessageMap());
      for (String errorKey : deepCopy.getErrorMessages().keySet()) {
        List<ErrorMessage> errorMessages = deepCopy.getErrorMessages().get(errorKey);
        if (CollectionUtils.isNotEmpty(errorMessages)) {
          List<String> errors = new ArrayList<String>();
          for (ErrorMessage errorMessage : errorMessages) {
            // need to materialize the message from it's parameters so we can send it back to the
            // framework
            String error =
                MessageFormat.format(
                    configurationService.getPropertyValueAsString(errorMessage.getErrorKey()),
                    errorMessage.getMessageParameters());
            errors.add(error);
          }
          RemotableAttributeError remotableAttributeError =
              RemotableAttributeError.Builder.create(errorKey, errors).build();
          validationErrors.add(remotableAttributeError);
        }
      }
      // we should now strip the error messages from the map because they have moved to
      // validationErrors
      GlobalVariables.getMessageMap().clearErrorMessages();
    }
  }
  /*
   * ensure the uniqueness of award type/basis of payment
   */
  private boolean validateUniqueueCodes(
      final AwardType awardType, final AwardBasisOfPayment basisOfPayment) {

    boolean valid = true;
    if (awardType != null
        && basisOfPayment != null
        && StringUtils.isNotBlank(awardType.getAwardTypeCode().toString())
        && StringUtils.isNotBlank(basisOfPayment.getBasisOfPaymentCode())) {
      final Map<String, String> pkMap = new HashMap<String, String>();
      pkMap.put("awardTypeCode", awardType.getAwardTypeCode().toString());
      pkMap.put("basisOfPaymentCode", basisOfPayment.getBasisOfPaymentCode());
      final int matchingCount =
          KraServiceLocator.getService(BusinessObjectService.class)
              .countMatching(ValidAwardBasisPayment.class, pkMap);

      if (matchingCount > 0) {
        final MessageMap errorMap = GlobalVariables.getMessageMap();
        errorMap.putError(
            "document.newMaintainableObject.awardTypeCode",
            KeyConstants.ERROR_AWARD_BASIS_EXIST,
            new String[] {awardType.getDescription(), basisOfPayment.getDescription()});
        valid = false;
      }
    }
    return valid;
  }
  /**
   * Checks for errors in the error map and transforms them to struts action messages then stores in
   * the request.
   */
  private void publishMessages(HttpServletRequest request) {
    MessageMap errorMap = GlobalVariables.getMessageMap();
    if (!errorMap.hasNoErrors()) {
      ErrorContainer errorContainer = new ErrorContainer(errorMap);

      request.setAttribute("ErrorContainer", errorContainer);
      request.setAttribute(Globals.ERROR_KEY, errorContainer.getRequestErrors());
      request.setAttribute("ErrorPropertyList", errorContainer.getErrorPropertyList());
    }

    if (errorMap.hasWarnings()) {
      WarningContainer warningsContainer = new WarningContainer(errorMap);

      request.setAttribute("WarningContainer", warningsContainer);
      request.setAttribute("WarningActionMessages", warningsContainer.getRequestMessages());
      request.setAttribute("WarningPropertyList", warningsContainer.getMessagePropertyList());
    }

    if (errorMap.hasInfo()) {
      InfoContainer infoContainer = new InfoContainer(errorMap);

      request.setAttribute("InfoContainer", infoContainer);
      request.setAttribute("InfoActionMessages", infoContainer.getRequestMessages());
      request.setAttribute("InfoPropertyList", infoContainer.getMessagePropertyList());
    }
  }
  /**
   * Validates a single collection activity document detail object.
   *
   * @param event The object to get validated.
   * @return Returns true if all validations succeed otherwise false.
   */
  public boolean validateEvent(Event event) {
    MessageMap errorMap = GlobalVariables.getMessageMap();

    boolean isValid = true;

    int originalErrorCount = errorMap.getErrorCount();
    // call the DD validation which checks basic data integrity
    SpringContext.getBean(DictionaryValidationService.class).validateBusinessObject(event);
    isValid = (errorMap.getErrorCount() == originalErrorCount);

    if (ObjectUtils.isNotNull(event.isFollowup())
        && event.isFollowup()
        && event.getFollowupDate() == null) {
      errorMap.putError(
          ArPropertyConstants.EventFields.FOLLOW_UP_DATE,
          ArKeyConstants.CollectionActivityDocumentErrors.ERROR_FOLLOW_UP_DATE_REQUIRED);
      isValid = false;
    }
    if (ObjectUtils.isNotNull(event.isCompleted())
        && event.isCompleted()
        && event.getCompletedDate() == null) {
      errorMap.putError(
          ArPropertyConstants.EventFields.COMPLETED_DATE,
          ArKeyConstants.CollectionActivityDocumentErrors.ERROR_COMPLETED_DATE_REQUIRED);
      isValid = false;
    }
    return isValid;
  }
  /**
   * Decreases the registered error path, so that field highlighting can occur on the appropriate
   * object attribute
   *
   * @param errorPathPrefix
   */
  private void decreaseErrorPath(String errorPathPrefix) {
    MessageMap errorMap = GlobalVariables.getMessageMap();

    if (!StringUtils.isBlank(errorPathPrefix)) {
      errorMap.removeFromErrorPath(errorPathPrefix);
    }
  }
  /**
   * @see
   *     org.kuali.rice.kns.maintenance.KualiMaintainableImpl#processAfterEdit(org.kuali.rice.kns.document.MaintenanceDocument,
   *     java.util.Map)
   */
  @Override
  public void processAfterEdit(MaintenanceDocument document, Map<String, String[]> parameters) {
    List<ErrorMessage> errorMessages = null;
    AgencyStagingData agency =
        (AgencyStagingData) document.getNewMaintainableObject().getBusinessObject();

    if (TemConstants.ExpenseImportTypes.IMPORT_BY_TRIP.equals(agency.getImportBy())) {
      errorMessages = getExpenseImportByTripService().validateAgencyData(agency);
    } else if (TemConstants.ExpenseImportTypes.IMPORT_BY_TRAVELLER.equals(agency.getImportBy())) {
      errorMessages = getExpenseImportByTravelerService().validateAgencyData(agency);
    }

    if (errorMessages.isEmpty()) {
      agency.setErrorCode(AgencyStagingDataErrorCodes.AGENCY_NO_ERROR);
    }

    MessageMap messageMap = GlobalVariables.getMessageMap();
    for (ErrorMessage message : errorMessages) {
      messageMap.putError(
          KFSConstants.GLOBAL_ERRORS, message.getErrorKey(), message.getMessageParameters());
    }

    updateCreditCardAgency(
        (AgencyStagingData) document.getNewMaintainableObject().getBusinessObject());

    super.processAfterEdit(document, parameters);
  }
  /**
   * This method checks business rules related to Budget Expenses functionality
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetExpenseBusinessRules(BudgetDocument budgetDocument) {
    boolean valid = true;

    MessageMap errorMap = GlobalVariables.getMessageMap();

    List<BudgetPeriod> budgetPeriods = budgetDocument.getBudget().getBudgetPeriods();
    int i = 0;
    int j = 0;
    for (BudgetPeriod budgetPeriod : budgetPeriods) {
      j = 0;
      List<BudgetLineItem> budgetLineItems = budgetPeriod.getBudgetLineItems();
      for (BudgetLineItem budgetLineItem : budgetLineItems) {
        if (budgetLineItem != null
            && budgetLineItem.getStartDate() != null
            && budgetLineItem.getStartDate().before(budgetPeriod.getStartDate())) {
          errorMap.putError(
              "budgetCategoryTypes["
                  + budgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode()
                  + "].budgetPeriods["
                  + i
                  + "].budgetLineItems["
                  + j
                  + "].startDate",
              KeyConstants.ERROR_LINEITEM_STARTDATE_BEFORE_PERIOD_STARTDATE);
          valid = false;
        }
        if (budgetLineItem != null
            && budgetLineItem.getEndDate() != null
            && budgetLineItem.getEndDate().after(budgetPeriod.getEndDate())) {
          errorMap.putError(
              "budgetCategoryTypes["
                  + budgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode()
                  + "].budgetPeriods["
                  + i
                  + "].budgetLineItems["
                  + j
                  + "].endDate",
              KeyConstants.ERROR_LINEITEM_ENDDATE_AFTER_PERIOD_ENDDATE);
          valid = false;
        }

        if (budgetLineItem != null
            && budgetLineItem.getQuantity() != null
            && budgetLineItem.getQuantity().intValue() < 0) {
          errorMap.putError(
              "budgetPeriod[" + i + "].budgetLineItem[" + j + "].quantity",
              KeyConstants.ERROR_NEGATIVE_AMOUNT,
              "Quantity");
          valid = false;
        }

        j++;
      }
      i++;
    }
    return valid;
  }
 protected boolean validateActiveDate(
     String errorPath, Timestamp activeFromDate, Timestamp activeToDate) {
   // TODO : do not have detail bus rule yet, so just check this for now.
   boolean valid = true;
   if (activeFromDate != null && activeToDate != null && activeToDate.before(activeFromDate)) {
     MessageMap errorMap = GlobalVariables.getMessageMap();
     errorMap.putError(errorPath, RiceKeyConstants.ERROR_ACTIVE_TO_DATE_BEFORE_FROM_DATE);
     valid = false;
   }
   return valid;
 }
  /**
   * Validates if the job code is a valid value.
   *
   * @param person the current person
   * @return true is valid false if not valid
   */
  private boolean validateJobCodeValue(BudgetPerson person, String errorKey) {
    assert person != null : "the person is null";

    boolean valid = true;
    if (person.getJobCode() == null) {
      final MessageMap messageMap = GlobalVariables.getMessageMap();
      messageMap.putError(
          errorKey, KeyConstants.ERROR_PERSON_JOBCODE_VALUE, person.getPersonName());
      valid = false;
    }
    return valid;
  }
 /**
  * Validates if the job code is a valid change.
  *
  * @param person the current person
  * @return true is valid false if not valid
  */
 private boolean validateJobCodeChange(final BudgetPerson person, String errorKey) {
   boolean valid = true;
   BudgetPerson personCopy = getOriginalBudgetPerson(person);
   if (personCopy != null && !person.isDuplicatePerson(personCopy)) {
     if (!StringUtils.equals(person.getJobCode(), personCopy.getJobCode())) {
       final MessageMap messageMap = GlobalVariables.getMessageMap();
       messageMap.putError(
           errorKey, KeyConstants.ERROR_PERSON_JOBCODE_CHANGE, person.getPersonName());
       valid = false;
     }
   }
   return valid;
 }
  @KcEventMethod
  public boolean processCheckExistBudgetPersonnelDetailsBusinessRules(
      DeleteBudgetLineItemEvent event) {
    boolean valid = true;

    MessageMap errorMap = getGlobalVariableService().getMessageMap();
    if (CollectionUtils.isNotEmpty(event.getBudgetLineItem().getBudgetPersonnelDetailsList())) {
      // just try to make sure key is on budget personnel tab
      errorMap.putError(event.getErrorPath() + COST_ELEMENT, KeyConstants.ERROR_DELETE_LINE_ITEM);
      valid = false;
    }

    return valid;
  }
  /**
   * @see
   *     org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomRouteDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument)
   */
  @Override
  protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {

    boolean isValid = true;
    isValid &= super.processCustomRouteDocumentBusinessRules(document);
    MessageMap errorMap = GlobalVariables.getMessageMap();
    isValid &= errorMap.hasNoErrors();

    if (isValid) {

      isValid = validateReportingGroupOrder(newReportingGroup);
    }

    return isValid;
  }
  /**
   * This action executes an insert of a SourceAccountingLine into a document only after validating
   * the accounting line and checking any appropriate business rules.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   * @throws Exception
   */
  public ActionForward insertSourceLine(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    KualiAccountingDocumentFormBase financialDocumentForm = (KualiAccountingDocumentFormBase) form;
    SourceAccountingLine line = financialDocumentForm.getNewSourceLine();

    // populate chartOfAccountsCode from account number if accounts cant cross chart and Javascript
    // is turned off
    // SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);

    boolean rulePassed = true;
    // DV acct line amount got error during form populate; should not insert this line.
    // KFSUPGRADE-847
    MessageMap msgMap = GlobalVariables.getMessageMap();
    if (msgMap.hasErrors()
        && msgMap.getErrorMessages().keySet().contains("newSourceLine.amount")
        && financialDocumentForm.getDocument() instanceof DisbursementVoucherDocument) {
      rulePassed = false;
    }
    // before we check the regular rules we need to check the sales tax rules
    // TODO: Refactor rules so we no longer have to call this before a copy of the
    // accountingLine
    rulePassed &=
        checkSalesTax(
            (AccountingDocument) financialDocumentForm.getDocument(), line, true, true, 0);
    // check any business rules
    rulePassed &=
        SpringContext.getBean(KualiRuleService.class)
            .applyRules(
                new AddAccountingLineEvent(
                    KFSConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME,
                    financialDocumentForm.getDocument(),
                    line));

    if (rulePassed) {
      // add accountingLine
      SpringContext.getBean(PersistenceService.class).refreshAllNonUpdatingReferences(line);
      insertAccountingLine(true, financialDocumentForm, line);

      // clear the used newTargetLine
      financialDocumentForm.setNewSourceLine(null);
    }

    return mapping.findForward(KFSConstants.MAPPING_BASIC);
  }
  private void checkErrorState(String errorProperty, String errorMessageKey) {
    MessageMap messageMap = GlobalVariables.getMessageMap();
    Assert.assertTrue(messageMap.getErrorCount() >= 1);
    @SuppressWarnings("unchecked")
    List<ErrorMessage> errors = messageMap.getErrorMessagesForProperty(errorProperty);
    if (errors != null) {
      Assert.assertEquals(1, errors.size());
      Assert.assertEquals(errorMessageKey, errors.get(0).getErrorKey());
    } else {
      Assert.fail("No errors posted");
    }

    Assert.assertFalse(
        "rule should return false",
        rule.processSaveAwardProjectPersonsBusinessRules(award.getProjectPersons()));
  }
 /**
  * This method to check the 'selected' person to delete is not associate with budget personnel
  * details
  *
  * @return
  */
 @KcEventMethod
 public boolean processCheckExistBudgetPersonnelDetailsBusinessRules(
     DeleteBudgetPersonEvent event) {
   boolean valid = true;
   String errorPath = event.getErrorPath();
   // User  may delete person before the deleted detail is persisted
   if (isPersonDetailsFound(event.getBudget(), event.getBudgetPerson())) {
     final MessageMap messageMap = GlobalVariables.getMessageMap();
     messageMap.putError(
         errorPath,
         KeyConstants.ERROR_DELETE_PERSON_WITH_PERSONNEL_DETAIL,
         event.getBudgetPerson().getPersonName());
     valid = false;
   }
   return valid;
 }
  @KcEventMethod
  public boolean processApplyToLaterPeriodsWithPersonnelDetails(ApplyToPeriodsBudgetEvent event) {
    MessageMap errorMap = getGlobalVariableService().getMessageMap();
    Budget budget = event.getBudget();
    BudgetLineItem budgetLineItem = event.getBudgetLineItem();

    List<BudgetPeriod> budgetPeriods = budget.getBudgetPeriods();
    BudgetLineItem prevBudgetLineItem = budgetLineItem;
    for (BudgetPeriod budgetPeriod : budgetPeriods) {
      if (budgetPeriod.getBudgetPeriod() <= event.getBudgetPeriod().getBudgetPeriod()) continue;
      QueryList<BudgetLineItem> currentBudgetPeriodLineItems =
          new QueryList<BudgetLineItem>(budgetPeriod.getBudgetLineItems());
      for (BudgetLineItem budgetLineItemToBeApplied : currentBudgetPeriodLineItems) {
        if (prevBudgetLineItem
            .getLineItemNumber()
            .equals(budgetLineItemToBeApplied.getBasedOnLineItem())) {
          if (budgetLineItemToBeApplied
                  .getBudgetCategory()
                  .getBudgetCategoryTypeCode()
                  .equals(PERSONNEL_CATEGORY)
              && (!budgetLineItemToBeApplied.getBudgetPersonnelDetailsList().isEmpty()
                  || !prevBudgetLineItem.getBudgetPersonnelDetailsList().isEmpty())) {
            errorMap.putError(
                event.getErrorPath() + COST_ELEMENT,
                KeyConstants.ERROR_APPLY_TO_LATER_PERIODS,
                budgetLineItemToBeApplied.getBudgetPeriod().toString());
            return false;
          }
        } else if (StringUtils.equals(
            budgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode(), PERSONNEL_CATEGORY)) {
          // Additional Check for Personnel Source Line Item
          if (StringUtils.equals(
                  budgetLineItem.getCostElement(), budgetLineItemToBeApplied.getCostElement())
              && StringUtils.equals(
                  budgetLineItem.getGroupName(), budgetLineItemToBeApplied.getGroupName())) {
            errorMap.putError(
                event.getErrorPath() + COST_ELEMENT,
                KeyConstants.ERROR_PERSONNELLINEITEM_APPLY_TO_LATER_PERIODS,
                budgetLineItemToBeApplied.getBudgetPeriod().toString());
            return false;
          }
        }
      }
    }

    return true;
  }
  /**
   * This method checks budget versions business rules.
   *
   * @param budgetParentDocument the document
   * @param runDatactionaryValidation if dd validation should be run
   * @return true if valid false if not
   * @throws NullPointerException if the proposalDevelopmentDocument is null
   */
  protected boolean processBudgetVersionsBusinessRule(
      final BudgetParentDocument budgetParentDocument, final boolean runDatactionaryValidation) {
    if (budgetParentDocument == null) {
      throw new NullPointerException("the parentDocument is null.");
    }

    boolean valid = true;
    final MessageMap errorMap = GlobalVariables.getMessageMap();
    boolean finalVersionFound = false;

    final DictionaryValidationService dictionaryValidationService =
        getKnsDictionaryValidationService();

    int index = 0;
    for (BudgetDocumentVersion budgetDocumentVersion :
        budgetParentDocument.getBudgetDocumentVersions()) {
      BudgetVersionOverview budgetVersion = budgetDocumentVersion.getBudgetVersionOverview();
      if (runDatactionaryValidation) {
        dictionaryValidationService.validateBusinessObject(budgetVersion, true);
      }
      if (budgetVersion.isFinalVersionFlag()) {
        if (finalVersionFound) {
          errorMap.putError("finalVersionFlag", KeyConstants.ERROR_MULTIPLE_FINAL_BUDGETS);
        } else {
          finalVersionFound = true;
        }
      }

      final String budgetStatusCompleteCode =
          getParameterService()
              .getParameterValueAsString(
                  BudgetDocument.class, Constants.BUDGET_STATUS_COMPLETE_CODE);

      if (budgetStatusCompleteCode.equalsIgnoreCase(budgetVersion.getBudgetStatus())) {
        if (!budgetVersion.isFinalVersionFlag()) {
          errorMap.putError(
              "budgetVersionOverview[" + index + "].budgetStatus",
              KeyConstants.ERROR_NO_FINAL_BUDGET);
          valid = false;
        }
      }
      index++;
    }

    return valid;
  }
  /**
   * This method...
   *
   * @param nonInvoiced
   * @param paymentApplicationDocument
   * @param totalFromControl
   * @return
   */
  private static boolean validateNonInvoicedLineAmount(
      NonInvoiced nonInvoiced,
      PaymentApplicationDocument paymentApplicationDocument,
      KualiDecimal totalFromControl) {
    MessageMap errorMap = GlobalVariables.getMessageMap();
    KualiDecimal nonArLineAmount = nonInvoiced.getFinancialDocumentLineAmount();
    // check that dollar amount is not zero before continuing
    if (ObjectUtils.isNull(nonArLineAmount)) {
      errorMap.putError(
          ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_AMOUNT,
          ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_AMOUNT_REQUIRED);
      return false;
    } else {
      KualiDecimal cashControlBalanceToBeApplied = totalFromControl;
      cashControlBalanceToBeApplied =
          cashControlBalanceToBeApplied.add(paymentApplicationDocument.getTotalFromControl());
      cashControlBalanceToBeApplied.subtract(paymentApplicationDocument.getTotalApplied());
      cashControlBalanceToBeApplied.subtract(
          paymentApplicationDocument.getNonAppliedHoldingAmount());

      if (nonArLineAmount.isZero()) {
        errorMap.putError(
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_AMOUNT,
            ArKeyConstants.PaymentApplicationDocumentErrors.AMOUNT_TO_BE_APPLIED_CANNOT_BE_ZERO);
        return false;
      } else if (nonArLineAmount.isNegative()) {
        errorMap.putError(
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_AMOUNT,
            ArKeyConstants.PaymentApplicationDocumentErrors.AMOUNT_TO_BE_APPLIED_MUST_BE_POSTIIVE);
        return false;
      }
      //  check that we're not trying to apply more funds to the invoice than the invoice has
      // balance (ie, over-applying)
      else if (KualiDecimal.ZERO.isGreaterThan(
          cashControlBalanceToBeApplied.subtract(nonArLineAmount))) {
        errorMap.putError(
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_AMOUNT,
            ArKeyConstants.PaymentApplicationDocumentErrors
                .NON_AR_AMOUNT_EXCEEDS_BALANCE_TO_BE_APPLIED);
        return false;
      }
    }
    return true;
  }
  /**
   * This method is checks individual line item start and end dates for validity and proper
   * ordering.
   *
   * @param currentBudgetPeriod the period containing the line item
   * @param budgetLineItem the number of the line item
   * @return true if the dates are valid, false otherwise
   */
  protected boolean processCheckLineItemDates(
      BudgetPeriod currentBudgetPeriod, BudgetLineItem budgetLineItem, String errorPath) {
    boolean valid = true;
    MessageMap errorMap = getGlobalVariableService().getMessageMap();

    if (budgetLineItem.getEndDate() == null) {
      errorMap.putError(errorPath + END_DATE, KeyConstants.ERROR_REQUIRED, UPPER_END_DATE);
      valid = false;
    }

    if (budgetLineItem.getStartDate() == null) {
      errorMap.putError(errorPath + START_DATE, KeyConstants.ERROR_REQUIRED, UPPER_START_DATE);
      valid = false;
    }

    if (!valid) return valid;

    if (budgetLineItem.getEndDate().compareTo(budgetLineItem.getStartDate()) < 0) {
      errorMap.putError(errorPath + END_DATE, KeyConstants.ERROR_LINE_ITEM_DATES);
      valid = false;
    }

    if (currentBudgetPeriod.getEndDate().compareTo(budgetLineItem.getEndDate()) < 0) {
      errorMap.putError(
          errorPath + END_DATE,
          KeyConstants.ERROR_LINE_ITEM_END_DATE,
          new String[] {CAN_NOT_BE_AFTER, LOWER_END_DATE});
      valid = false;
    }
    if (currentBudgetPeriod.getStartDate().compareTo(budgetLineItem.getEndDate()) > 0) {
      errorMap.putError(
          errorPath + END_DATE,
          KeyConstants.ERROR_LINE_ITEM_END_DATE,
          new String[] {CAN_NOT_BE_BEFORE, LOWER_START_DATE});
      valid = false;
    }
    if (currentBudgetPeriod.getStartDate().compareTo(budgetLineItem.getStartDate()) > 0) {
      errorMap.putError(
          errorPath + START_DATE,
          KeyConstants.ERROR_LINE_ITEM_START_DATE,
          new String[] {CAN_NOT_BE_BEFORE, LOWER_START_DATE});
      valid = false;
    }
    if (currentBudgetPeriod.getEndDate().compareTo(budgetLineItem.getStartDate()) < 0) {
      errorMap.putError(
          errorPath + START_DATE,
          KeyConstants.ERROR_LINE_ITEM_START_DATE,
          new String[] {CAN_NOT_BE_AFTER, LOWER_END_DATE});
      valid = false;
    }

    return valid;
  }
 public void populateDeferredMessages(
     ProposalDevelopmentDocumentForm proposalDevelopmentDocumentForm) {
   if (proposalDevelopmentDocumentForm.getDeferredMessages() != null
       && proposalDevelopmentDocumentForm.getDeferredMessages().hasMessages()) {
     MessageMap messageMap = proposalDevelopmentDocumentForm.getDeferredMessages();
     MessageMap currentMessageMap = getGlobalVariableService().getMessageMap();
     messageMap.getErrorMessages().putAll(currentMessageMap.getErrorMessages());
     messageMap.getInfoMessages().putAll(currentMessageMap.getInfoMessages());
     messageMap.getWarningMessages().putAll(currentMessageMap.getWarningMessages());
     getGlobalVariableService().setMessageMap(messageMap);
   }
   proposalDevelopmentDocumentForm.setDeferredMessages(null);
 }
Exemple #22
0
  /**
   * This method build a string list of error message keys out of the error map in GlobalVariables
   *
   * @return a String representing the list of error message keys
   */
  private String buildErrorMesageKeyList() {
    MessageMap errorMap = GlobalVariables.getMessageMap();
    StringBuffer errorList = new StringBuffer();

    for (String errorKey : (List<String>) errorMap.getPropertiesWithErrors()) {
      for (ErrorMessage errorMessage : (List<ErrorMessage>) errorMap.getMessages(errorKey)) {

        errorList.append(errorMessage.getErrorKey());
        errorList.append(PdpParameterConstants.ERROR_KEY_LIST_SEPARATOR);
      }
    }
    if (errorList.length() > 0) {
      errorList.replace(
          errorList.lastIndexOf(PdpParameterConstants.ERROR_KEY_LIST_SEPARATOR),
          errorList.lastIndexOf(PdpParameterConstants.ERROR_KEY_LIST_SEPARATOR)
              + PdpParameterConstants.ERROR_KEY_LIST_SEPARATOR.length(),
          "");
    }

    return errorList.toString();
  }
 /**
  * This method...
  *
  * @param map
  */
 protected void removeRestrictedFieldChangedErrors(MessageMap map, String propertyKey) {
   AutoPopulatingList<ErrorMessage> errorMessages = map.getErrorMessagesForProperty(propertyKey);
   if (errorMessages != null) {
     for (int i = 0; i < errorMessages.size(); i++) {
       ErrorMessage eMessage = (ErrorMessage) errorMessages.get(i);
       String errorKey = eMessage.getErrorKey();
       if (errorKey.equals(
           KFSKeyConstants.ERROR_DOCUMENT_AUTHORIZATION_RESTRICTED_FIELD_CHANGED)) {
         errorMessages.remove(i);
       }
     }
   }
 }
  protected KcEventResult isNotDuplicateBudgetPersons(List<BudgetPerson> budgetPersons) {
    KcEventResult result = new KcEventResult();
    MessageMap messages = new MessageMap();
    result.setSuccess(true);

    for (int i = 0; i < budgetPersons.size(); i++) {
      BudgetPerson budgetPerson = budgetPersons.get(i);
      for (int j = i + 1; j < budgetPersons.size(); j++) {
        BudgetPerson budgetPersonCompare = budgetPersons.get(j);
        if (budgetPerson.isDuplicatePerson(budgetPersonCompare)) {
          messages.putError(
              "budgetPersons[" + j + "].personName",
              KeyConstants.ERROR_DUPLICATE_BUDGET_PERSON,
              budgetPerson.getPersonName());
          result.setSuccess(false);
        }
      }
    }

    result.setMessageMap(messages);
    return result;
  }
  protected boolean processBudgetFormulatedCostValidations(
      BudgetFormulatedCostDetail budgetFormulatedCost, String errorKey) {
    boolean valid = true;
    MessageMap errorMap = getGlobalVariableService().getMessageMap();

    BigDecimal unitCost = budgetFormulatedCost.getUnitCost().bigDecimalValue();
    BigDecimal count = new ScaleTwoDecimal(budgetFormulatedCost.getCount()).bigDecimalValue();
    BigDecimal frequency =
        new ScaleTwoDecimal(budgetFormulatedCost.getFrequency()).bigDecimalValue();
    BigDecimal calculatedExpense = unitCost.multiply(count).multiply(frequency);
    if (new ScaleTwoDecimal(unitCost)
        .isGreaterThan(new ScaleTwoDecimal(MAX_BUDGET_DECIMAL_VALUE))) {
      valid = false;
      errorMap.putError(errorKey + UNIT_COST, KeyConstants.ERROR_FORMULATED_UNIT_COST);
    }
    if (new ScaleTwoDecimal(calculatedExpense)
        .isGreaterThan(new ScaleTwoDecimal(MAX_BUDGET_DECIMAL_VALUE))) {
      valid = false;
      errorMap.putError(
          errorKey + CALCULATED_EXPENSES, KeyConstants.ERROR_FORMULATED_CALCULATED_EXPENSES);
    }
    return valid;
  }
 protected static void putError(String errorPropertyName, String errorMessageKey, String value) {
   MessageMap errorMap = GlobalVariables.getMessageMap();
   errorMap.putError(errorPropertyName, errorMessageKey, value);
 }
  /**
   * Validate non-ar/non-invoice line items on a PaymentApplicationDocument.
   *
   * @param nonInvoiced
   * @return
   */
  public static boolean validateNonInvoiced(
      NonInvoiced nonInvoiced,
      PaymentApplicationDocument paymentApplicationDocument,
      KualiDecimal totalFromControl)
      throws WorkflowException {
    MessageMap errorMap = GlobalVariables.getMessageMap();
    int originalErrorCount = errorMap.getErrorCount();

    //  validate the NonInvoiced BO
    String sNonInvoicedErrorPath = "nonInvoicedAddLine";
    errorMap.addToErrorPath(sNonInvoicedErrorPath);
    SpringContext.getBean(DictionaryValidationService.class).validateBusinessObject(nonInvoiced);
    errorMap.removeFromErrorPath(sNonInvoicedErrorPath);

    if (errorMap.getErrorCount() != originalErrorCount) {
      return false;
    }

    boolean isValid = true;

    // Required fields, so always validate these.
    nonInvoiced.refreshReferenceObject("account");
    if (ObjectUtils.isNull(nonInvoiced.getAccount())) {
      isValid &= false;
      putError(
          ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_ACCOUNT,
          ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_ACCOUNT_INVALID,
          nonInvoiced.getAccountNumber());
    }
    isValid &=
        validateNonInvoicedLineItem(
            "chartOfAccountsCode",
            nonInvoiced.getChartOfAccountsCode(),
            Chart.class,
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_CHART,
            ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_CHART_INVALID);
    isValid &=
        validateNonInvoicedLineItem(
            "accountNumber",
            nonInvoiced.getAccountNumber(),
            Account.class,
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_ACCOUNT,
            ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_ACCOUNT_INVALID);
    isValid &=
        validateNonInvoicedLineItem(
            "financialObjectCode",
            nonInvoiced.getFinancialObjectCode(),
            ObjectCode.class,
            ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_OBJECT,
            ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_OBJECT_CODE_INVALID);

    // Optional fields, so only validate if a value was entered.
    if (StringUtils.isNotBlank(nonInvoiced.getSubAccountNumber())) {
      isValid &=
          validateNonInvoicedLineItem(
              "subAccountNumber",
              nonInvoiced.getSubAccountNumber(),
              SubAccount.class,
              ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_SUBACCOUNT,
              ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_SUB_ACCOUNT_INVALID);
    }
    if (StringUtils.isNotBlank(nonInvoiced.getFinancialSubObjectCode())) {
      isValid &=
          validateNonInvoicedLineItem(
              "financialSubObjectCode",
              nonInvoiced.getFinancialSubObjectCode(),
              SubObjectCode.class,
              ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_SUBOBJECT,
              ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_SUB_OBJECT_CODE_INVALID);
    }
    if (StringUtils.isNotBlank(nonInvoiced.getProjectCode())) {
      isValid &=
          validateNonInvoicedLineItem(
              "code",
              nonInvoiced.getProjectCode(),
              ProjectCode.class,
              ArPropertyConstants.PaymentApplicationDocumentFields.NON_INVOICED_LINE_PROJECT,
              ArKeyConstants.PaymentApplicationDocumentErrors.NON_AR_PROJECT_CODE_INVALID);
    }

    isValid &=
        validateNonInvoicedLineAmount(nonInvoiced, paymentApplicationDocument, totalFromControl);

    return isValid;
  }
Exemple #28
0
  /**
   * This method checks business rules related to Budget Personnel Budget functionality
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetPersonnelBudgetBusinessRules(BudgetDocument budgetDocument) {
    boolean valid = true;

    MessageMap errorMap = GlobalVariables.getMessageMap();

    List<BudgetPeriod> budgetPeriods = budgetDocument.getBudget().getBudgetPeriods();
    int i = 0;
    int j = 0;
    int k = 0;
    for (BudgetPeriod budgetPeriod : budgetPeriods) {
      j = 0;
      List<BudgetLineItem> budgetLineItems = budgetPeriod.getBudgetLineItems();
      k = 0;
      for (BudgetLineItem budgetLineItem : budgetLineItems) {
        for (BudgetPersonnelDetails budgetPersonnelDetails :
            budgetLineItem.getBudgetPersonnelDetailsList()) {
          if (budgetPersonnelDetails != null
              && budgetPersonnelDetails.getStartDate() != null
              && budgetPersonnelDetails.getStartDate().before(budgetLineItem.getStartDate())) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].startDate",
                KeyConstants.ERROR_PERSONNELBUDGETLINEITEM_STARTDATE_BEFORE_LINEITEM_STARTDATE);
            valid = false;
          }
          if (budgetPersonnelDetails != null
              && budgetPersonnelDetails.getEndDate() != null
              && budgetPersonnelDetails.getEndDate().after(budgetLineItem.getEndDate())) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].endDate",
                KeyConstants.ERROR_PERSONNELBUDGETLINEITEM_ENDDATE_AFTER_LINEITEM_ENDDATE);
            valid = false;
          }
          if (budgetPersonnelDetails.getPercentEffort().isGreaterThan(new ScaleTwoDecimal(100))) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].percentEffort",
                KeyConstants.ERROR_PERCENTAGE,
                Constants.PERCENT_EFFORT_FIELD);
          }
          if (budgetPersonnelDetails.getPercentCharged().isGreaterThan(new ScaleTwoDecimal(100))) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].percentCharged",
                KeyConstants.ERROR_PERCENTAGE,
                Constants.PERCENT_CHARGED_FIELD);
          }
          if (budgetPersonnelDetails
              .getPercentCharged()
              .isGreaterThan(budgetPersonnelDetails.getPercentEffort())) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].percentCharged",
                KeyConstants.ERROR_PERCENT_EFFORT_LESS_THAN_PERCENT_CHARGED);
          }
          k++;
        }
        j++;
      }
      i++;
    }
    return valid;
  }
Exemple #29
0
  /**
   * This method checks business rules related to Budget Expenses functionality
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetExpenseBusinessRules(BudgetDocument budgetDocument) {
    boolean valid = true;
    // TODO - put budget expense validation rules here.
    MessageMap errorMap = GlobalVariables.getMessageMap();

    List<BudgetPeriod> budgetPeriods = budgetDocument.getBudget().getBudgetPeriods();
    int i = 0;
    int j = 0;
    for (BudgetPeriod budgetPeriod : budgetPeriods) {
      j = 0;
      List<BudgetLineItem> budgetLineItems = budgetPeriod.getBudgetLineItems();
      for (BudgetLineItem budgetLineItem : budgetLineItems) {
        if (budgetLineItem != null
            && budgetLineItem.getStartDate() != null
            && budgetLineItem.getStartDate().before(budgetPeriod.getStartDate())) {
          errorMap.putError(
              "budgetCategoryTypes["
                  + budgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode()
                  + "].budgetPeriods["
                  + i
                  + "].budgetLineItems["
                  + j
                  + "].startDate",
              KeyConstants.ERROR_LINEITEM_STARTDATE_BEFORE_PERIOD_STARTDATE);
          valid = false;
        }
        if (budgetLineItem != null
            && budgetLineItem.getEndDate() != null
            && budgetLineItem.getEndDate().after(budgetPeriod.getEndDate())) {
          errorMap.putError(
              "budgetCategoryTypes["
                  + budgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode()
                  + "].budgetPeriods["
                  + i
                  + "].budgetLineItems["
                  + j
                  + "].endDate",
              KeyConstants.ERROR_LINEITEM_ENDDATE_AFTER_PERIOD_ENDDATE);
          valid = false;
        }
        //                if (budgetLineItem!=null && budgetLineItem.getCostSharingAmount() != null
        // && budgetLineItem.getCostSharingAmount().isNegative()) {
        //                    errorMap.putError("budgetPeriod[" + i +"].budgetLineItem[" + j +
        // "].costSharingAmount", KeyConstants.ERROR_NEGATIVE_AMOUNT,"Cost Sharing");
        //                    valid = false;
        //                }
        if (budgetLineItem != null
            && budgetLineItem.getQuantity() != null
            && budgetLineItem.getQuantity().intValue() < 0) {
          errorMap.putError(
              "budgetPeriod[" + i + "].budgetLineItem[" + j + "].quantity",
              KeyConstants.ERROR_NEGATIVE_AMOUNT,
              "Quantity");
          valid = false;
        }
        //                if (budgetLineItem!=null && budgetLineItem.getLineItemCost() != null &&
        // budgetLineItem.getLineItemCost().isNegative()) {
        //                    errorMap.putError("budgetPeriod[" + i +"].budgetLineItem[" + j +
        // "].lineItemCost", KeyConstants.ERROR_NEGATIVE_AMOUNT,"Total Base Cost");
        //                    valid = false;
        //                }
        //                if(budgetLineItem.getEndDate().compareTo(budgetLineItem.getStartDate())
        // <=0 ) {
        //
        // errorMap.putError("budgetPeriod["+i+"].budgetLineItem["+j+"].endDate",
        // KeyConstants.ERROR_LINE_ITEM_DATES);
        //                        return false;
        //                }

        j++;
      }
      i++;
    }
    return valid;
  }
Exemple #30
0
  /**
   * Validate budget rates. Applicable rates are mandatory
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetRatesBusinessRule(BudgetDocument budgetDocument) {
    boolean valid = true;
    final int APPLICABLE_RATE_LENGTH_EXCEEDED = 1;
    final int APPLICABLE_RATE_NEGATIVE = -1;

    MessageMap errorMap = GlobalVariables.getMessageMap();
    int i = 0;
    for (BudgetRate budgetRate : budgetDocument.getBudget().getBudgetRates()) {
      String rateClassType = budgetRate.getRateClass().getRateClassTypeT().getDescription();
      String errorPath = "budgetProposalRate[" + rateClassType + "][" + i + "]";
      errorMap.addToErrorPath(errorPath);
      /* look for applicable rate */
      if (budgetRate.isApplicableRateNull()) {
        valid = false;
        errorMap.putError("applicableRate", KeyConstants.ERROR_REQUIRED_APPLICABLE_RATE);
      } else if (!ScaleTwoDecimal.isNumeric(budgetRate.getApplicableRate().toString())) {
        valid = false;
        errorMap.putError("applicableRate", KeyConstants.ERROR_APPLICABLE_RATE_NOT_NUMERIC);
      } else {
        switch (verifyApplicableRate(budgetRate.getApplicableRate())) {
          case APPLICABLE_RATE_LENGTH_EXCEEDED:
            valid = false;
            errorMap.putError(
                "applicableRate",
                KeyConstants.ERROR_APPLICABLE_RATE_LIMIT,
                Constants.APPLICABLE_RATE_LIMIT);
            break;
          case APPLICABLE_RATE_NEGATIVE:
            valid = false;
            errorMap.putError("applicableRate", KeyConstants.ERROR_APPLICABLE_RATE_NEGATIVE);
            break;
        }
      }
      errorMap.removeFromErrorPath(errorPath);
      i++;
    }

    i = 0;
    for (BudgetLaRate budgetLaRate : budgetDocument.getBudget().getBudgetLaRates()) {
      String rateClassType = "";
      if (ObjectUtils.isNotNull(budgetLaRate.getRateClass())
          && ObjectUtils.isNotNull(budgetLaRate.getRateClass().getRateClassTypeT())) {
        rateClassType = budgetLaRate.getRateClass().getRateClassTypeT().getDescription();
      }
      String errorPath = "budgetRate[" + rateClassType + "][" + i + "]";
      errorMap.addToErrorPath(errorPath);
      /* look for applicable rate */
      if (budgetLaRate.isApplicableRateNull()) {
        valid = false;
        errorMap.putError("applicableRate", KeyConstants.ERROR_REQUIRED_APPLICABLE_RATE);
      } else if (!ScaleTwoDecimal.isNumeric(budgetLaRate.getApplicableRate().toString())) {
        valid = false;
        errorMap.putError("applicableRate", KeyConstants.ERROR_APPLICABLE_RATE_NOT_NUMERIC);
      } else {
        switch (verifyApplicableRate(budgetLaRate.getApplicableRate())) {
          case APPLICABLE_RATE_LENGTH_EXCEEDED:
            valid = false;
            errorMap.putError(
                "applicableRate",
                KeyConstants.ERROR_APPLICABLE_RATE_LIMIT,
                Constants.APPLICABLE_RATE_LIMIT);
            break;
          case APPLICABLE_RATE_NEGATIVE:
            valid = false;
            errorMap.putError("applicableRate", KeyConstants.ERROR_APPLICABLE_RATE_NEGATIVE);
            break;
        }
      }
      errorMap.removeFromErrorPath(errorPath);
      i++;
    }

    return valid;
  }