public boolean processSyncModularBusinessRules(Document document) {
    if (!(document instanceof BudgetDocument)) {
      return false;
    }

    boolean valid = true;

    BudgetDocument budgetDocument = (BudgetDocument) document;

    GlobalVariables.getErrorMap().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.getErrorMap()
          .putError("modularBudget", KeyConstants.ERROR_NO_DETAILED_BUDGET);
    }

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

    return valid;
  }
  public List<KeyLabelPair> getKeyValues() {
    List<KeyLabelPair> keyValues = new ArrayList<KeyLabelPair>();
    keyValues.add(new KeyLabelPair("", "select:"));
    keyValues.add(new KeyLabelPair(Constants.AWARD_HIERARCHY_DEFAULT_PARENT_OF_ROOT, "External"));
    TimeAndMoneyForm timeAndMoneyForm = (TimeAndMoneyForm) GlobalVariables.getKualiForm();
    TimeAndMoneyDocument document = timeAndMoneyForm.getTimeAndMoneyDocument();

    document.setAwardHierarchyItems(
        ((TimeAndMoneyDocument)
                GlobalVariables.getUserSession()
                    .retrieveObject(
                        GlobalVariables.getUserSession().getKualiSessionId()
                            + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION))
            .getAwardHierarchyItems());

    if (document.getAwardHierarchyItems() != null
        && document.getAwardHierarchyItems().size() != 0) {
      Object[] keyset = document.getAwardHierarchyItems().keySet().toArray();
      Arrays.sort(keyset);
      for (Object awardNumber : keyset) {
        keyValues.add(
            new KeyLabelPair(
                (String) awardNumber,
                document.getAwardHierarchyItems().get(awardNumber).getAwardNumber()));
      }
    }

    return keyValues;
  }
 public PurchasingCapitalAssetLocationBase() {
   super();
   if (GlobalVariables.getUserSession() != null
       && GlobalVariables.getUserSession().getPerson() != null) {
     Person user = GlobalVariables.getUserSession().getPerson();
     this.campusCode = user.getCampusCode();
   }
 }
Exemple #4
0
  /**
   * @see
   *     org.kuali.core.web.struts.action.KualiDocumentActionBase#docHandler(org.apache.struts.action.ActionMapping,
   *     org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  public ActionForward docHandler(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    ActionForward forward = super.docHandler(mapping, form, request, response);
    BudgetForm budgetForm = (BudgetForm) form;
    if (KEWConstants.INITIATE_COMMAND.equals(budgetForm.getCommand())) {
      budgetForm.getDocument().initialize();
    } else {
      budgetForm.initialize();
    }
    BudgetDocument budgetDocument = budgetForm.getBudgetDocument();
    if (budgetDocument.isBudgetDeleted()) {
      return mapping.findForward("deleted");
    }
    Budget budget = budgetDocument.getBudget();
    copyLineItemToPersonnelDetails(budgetDocument);
    if (budget.getActivityTypeCode().equals("x")) {
      budget.setActivityTypeCode(
          KraServiceLocator.getService(BudgetService.class)
              .getActivityTypeForBudget(budgetDocument));
    }

    if (budget.getOhRateClassCode() != null
        && ((BudgetForm) GlobalVariables.getKualiForm()) != null) {
      ((BudgetForm) GlobalVariables.getKualiForm())
          .setOhRateClassCodePrevValue(budget.getOhRateClassCode());
    }
    if (budget.getUrRateClassCode() != null
        && ((BudgetForm) GlobalVariables.getKualiForm()) != null) {
      ((BudgetForm) GlobalVariables.getKualiForm())
          .setUrRateClassCodePrevValue(budget.getUrRateClassCode());
    }

    if (budgetDocument.getParentDocument() instanceof AwardDocument
        && StringUtils.isNotBlank(budgetForm.getSyncBudgetRate())
        && budgetForm.getSyncBudgetRate().equals("Y")) {
      getBudgetRatesService().syncParentDocumentRates(budgetDocument);
      getBudgetCommonService(budgetDocument.getParentDocument()).calculateBudgetOnSave(budget);
    }

    reconcileBudgetStatus(budgetForm);
    if ("Personnel".equals(budgetForm.getActivePanelName())) {
      forward = personnel(mapping, budgetForm, request, response);
    }
    return forward;
  }
  protected boolean processBusinessRules(Document document) {
    boolean isValid = true;

    ElectronicInvoiceRejectDocument eirDocument = (ElectronicInvoiceRejectDocument) document;

    // check to see if the document is being researched
    if (eirDocument.isInvoiceResearchIndicator()) {
      GlobalVariables.getMessageMap()
          .putError(
              KFSConstants.DOCUMENT_ERRORS, PurapConstants.REJECT_DOCUMENT_RESEARCH_INCOMPETE);
      isValid = false;
    }

    if (!eirDocument.isDocumentCreationInProgress()) {
      isValid =
          isValid
              && SpringContext.getBean(ElectronicInvoiceHelperService.class)
                  .doMatchingProcess(eirDocument);
      if (isValid) {
        SpringContext.getBean(ElectronicInvoiceHelperService.class)
            .createPaymentRequest(eirDocument);
      }
    }

    return isValid;
  }
  /**
   * This method should only be called if an audit error is intending to be added because it will
   * actually add a <code>{@link List<AuditError>}</code> to the auditErrorMap.
   *
   * @return List of AuditError instances
   */
  private List<AuditError> getAuditErrors() {
    List<AuditError> auditErrors = new ArrayList<AuditError>();

    if (!GlobalVariables.getAuditErrorMap().containsKey("budgetPersonnelAuditErrors")) {
      GlobalVariables.getAuditErrorMap()
          .put(
              "budgetPersonnelAuditErrors",
              new AuditCluster("Budget Personnel Information", auditErrors, AUDIT_ERRORS));
    } else {
      auditErrors =
          ((AuditCluster) GlobalVariables.getAuditErrorMap().get("budgetPersonnelAuditErrors"))
              .getAuditErrorList();
    }

    return auditErrors;
  }
  /**
   * Gets search results and passes to access security service to apply access restrictions
   *
   * @see org.kuali.rice.kns.lookup.LookupableHelperService#getSearchResultsUnbounded(java.util.Map)
   */
  public List getSearchResultsUnbounded(Map<String, String> fieldValues) {
    List results = super.getSearchResultsUnbounded(fieldValues);

    int resultSizeBeforeRestrictions = results.size();
    accessSecurityService.applySecurityRestrictionsForLookup(
        results, GlobalVariables.getUserSession().getPerson());

    SecUtil.compareListSizeAndAddMessageIfChanged(
        resultSizeBeforeRestrictions, results, SecKeyConstants.MESSAGE_LOOKUP_RESULTS_RESTRICTED);

    return results;
  }
 protected Map<String, AwardHierarchyNode> getAwardHierarchyNodes(
     String awardNumber, String currentAwardNumber, String currentSequenceNumber) {
   if (awardHierarchyNodes == null
       || awardHierarchyNodes.size() == 0
       || StringUtils.endsWithIgnoreCase(LAST_5_CHARS_OF_ROOT, awardNumber.substring(8))) {
     if (canUseExistingTMSessionObject(awardNumber)) {
       awardHierarchyNodes =
           ((TimeAndMoneyDocument)
                   GlobalVariables.getUserSession()
                       .retrieveObject(
                           GlobalVariables.getUserSession().getKualiSessionId()
                               + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION))
               .getAwardHierarchyNodes();
     } else {
       Map<String, AwardHierarchy> awardHierarchyItems =
           awardHierarchyService.getAwardHierarchy(awardNumber, new ArrayList<String>());
       awardHierarchyService.populateAwardHierarchyNodes(
           awardHierarchyItems, awardHierarchyNodes, currentAwardNumber, currentSequenceNumber);
     }
   }
   return awardHierarchyNodes;
 }
  /**
   * @see
   *     org.kuali.kfs.sys.document.service.impl.AccountingLineRuleHelperServiceImpl#isValidAccount(org.kuali.kfs.coa.businessobject.Account,
   *     org.kuali.rice.kns.datadictionary.DataDictionary, java.lang.String)
   */
  @Override
  public boolean isValidAccount(
      Account account, DataDictionary dataDictionary, String errorPropertyName) {
    String label = getAccountLabel();

    // make sure it exists
    if (ObjectUtils.isNull(account)) {
      GlobalVariables.getMessageMap()
          .putError(errorPropertyName, KFSKeyConstants.ERROR_EXISTENCE, label);
      return false;
    }

    return true;
  }
  protected boolean canUseExistingTMSessionObject(String awardNumber) {
    String sessionObjectKey =
        GlobalVariables.getUserSession().getKualiSessionId()
            + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION;
    String prefix = null;

    TimeAndMoneyDocument tmDocFromSession =
        (TimeAndMoneyDocument) GlobalVariables.getUserSession().retrieveObject(sessionObjectKey);
    if (tmDocFromSession == null) {
      return false;
    }
    Map<String, AwardHierarchyNode> tmpNodes = tmDocFromSession.getAwardHierarchyNodes();
    if (tmpNodes != null && CollectionUtils.isNotEmpty(tmpNodes.keySet())) {
      for (String tempAwardNumber : tmpNodes.keySet()) {
        prefix = tempAwardNumber.substring(0, tempAwardNumber.indexOf("-"));
        if (!StringUtils.startsWithIgnoreCase(awardNumber, prefix)) {
          return false;
        }
      }
    }

    return true;
  }
  /**
   * If user has open permission then does further checks to verify there are no access security
   * restriction setup that prevents the user from opening the document
   *
   * @see
   *     org.kuali.rice.kns.document.authorization.DocumentAuthorizer#canOpen(org.kuali.rice.kns.document.Document,
   *     org.kuali.rice.kim.bo.Person)
   */
  public boolean canOpen(Document document, Person user) {
    AccessSecurityService securityService = SpringContext.getBean(AccessSecurityService.class);

    boolean canOpen = documentAuthorizer.canOpen(document, user);
    if (canOpen) {
      AccessSecurityRestrictionInfo restrictionInfo = new AccessSecurityRestrictionInfo();
      canOpen =
          securityService.canViewDocument((AccountingDocument) document, user, restrictionInfo);
      if (!canOpen) {
        GlobalVariables.getUserSession()
            .addObject(
                SecConstants.OPEN_DOCUMENT_SECURITY_ACCESS_DENIED_ERROR_KEY, restrictionInfo);
      }
    }

    return canOpen;
  }
  /**
   * If user has permission to view notes/attachments then does further checks to verify there are
   * no access security restriction setup that prevents the user from viewing the notes/attachments
   *
   * @see
   *     org.kuali.rice.kns.document.authorization.DocumentAuthorizer#canViewNoteAttachment(org.kuali.rice.kns.document.Document,
   *     java.lang.String, org.kuali.rice.kim.bo.Person)
   */
  public boolean canViewNoteAttachment(Document document, String attachmentTypeCode, Person user) {
    AccessSecurityService securityService = SpringContext.getBean(AccessSecurityService.class);

    boolean canView = documentAuthorizer.canViewNoteAttachment(document, attachmentTypeCode, user);
    if (canView) {
      canView =
          securityService.canViewDocumentNotesAttachments((AccountingDocument) document, user);

      if (!canView) {
        GlobalVariables.getMessageMap()
            .putInfo(
                KFSConstants.GLOBAL_ERRORS,
                SecKeyConstants.MESSAGE_DOCUMENT_NOTES_RESTRICTED,
                (String) null);
      }
    }

    return canView;
  }
  protected boolean processRunAuditBudgetVersionRule(BudgetParentDocument parentDocument) {
    // audit check for budgetversion with final status
    boolean finalAndCompleteBudgetVersionFound = false;
    boolean budgetVersionsExists = false;
    boolean retval = true;

    List<AuditError> auditErrors = new ArrayList<AuditError>();
    String budgetStatusCompleteCode =
        getParameterService()
            .getParameterValue(BudgetDocument.class, Constants.BUDGET_STATUS_COMPLETE_CODE);
    for (BudgetDocumentVersion budgetDocumentVersion : parentDocument.getBudgetDocumentVersions()) {
      BudgetVersionOverview budgetVersion = budgetDocumentVersion.getBudgetVersionOverview();
      budgetVersionsExists = true;
      if (budgetVersion.isFinalVersionFlag()) {
        BudgetParent budgetParent = parentDocument.getBudgetParent();
        if (budgetParent.getBudgetStatus() != null
            && budgetParent.getBudgetStatus().equals(budgetStatusCompleteCode)) {
          finalAndCompleteBudgetVersionFound = true;
        }
      }
    }
    if (budgetVersionsExists && !finalAndCompleteBudgetVersionFound) {
      auditErrors.add(
          new AuditError(
              "document.parentBudget.budgetVersionOverview",
              KeyConstants.AUDIT_ERROR_NO_BUDGETVERSION_COMPLETE_AND_FINAL,
              Constants.PD_BUDGET_VERSIONS_PAGE + "." + Constants.BUDGET_VERSIONS_PANEL_ANCHOR));
      retval = false;
    }
    if (auditErrors.size() > 0) {
      GlobalVariables.getAuditErrorMap()
          .put(
              "budgetVersionErrors",
              new AuditCluster(
                  Constants.BUDGET_VERSION_PANEL_NAME, auditErrors, Constants.AUDIT_ERRORS));
    }

    return retval;
  }
  /**
   * Validates before the document routes
   *
   * @see org.kuali.kfs.validation.Validation#validate(java.lang.Object[])
   */
  public boolean validate(AttributedDocumentEvent event) {
    boolean result = true;

    Document documentForValidation = getDocumentForValidation();

    LaborExpenseTransferDocumentBase expenseTransferDocument =
        (LaborExpenseTransferDocumentBase) documentForValidation;

    List sourceLines = expenseTransferDocument.getSourceAccountingLines();
    List targetLines = expenseTransferDocument.getTargetAccountingLines();

    // check to ensure totals of accounting lines in source and target sections match
    if (!isAccountingLineTotalsMatchByPayFYAndPayPeriod(sourceLines, targetLines)) {
      GlobalVariables.getMessageMap()
          .putError(
              KFSPropertyConstants.SOURCE_ACCOUNTING_LINES,
              LaborKeyConstants.ACCOUNTING_LINE_TOTALS_BY_PAYFY_PAYPERIOD_MISMATCH_ERROR);
      return false;
    }

    return result;
  }
Exemple #15
0
  /** {@inheritDoc} */
  @Override
  public ActionForward save(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    BudgetForm budgetForm = (BudgetForm) form;
    final BudgetDocument budgetDoc = budgetForm.getDocument();
    fixDocHeaderVersion(budgetDoc);
    Budget budget = budgetDoc.getBudget();
    getBudgetCommonService(budgetDoc.getParentDocument()).calculateBudgetOnSave(budget);
    ActionForward forward = super.save(mapping, form, request, response);
    BudgetForm savedBudgetForm = (BudgetForm) form;
    BudgetDocument savedBudgetDoc = savedBudgetForm.getDocument();
    refreshBudgetDocumentVersion(savedBudgetDoc);
    getBusinessObjectService().save(savedBudgetDoc.getParentDocument().getBudgetDocumentVersions());

    final BudgetTDCValidator tdcValidator = new BudgetTDCValidator(request);
    if (budgetForm.toBudgetVersionsPage()
        || "BudgetVersionsAction".equals(budgetForm.getActionName())) {
      GlobalVariables.getErrorMap()
          .addToErrorPath(KNSConstants.DOCUMENT_PROPERTY_NAME + ".proposal");
      tdcValidator.validateGeneratingErrorsAndWarnings(budgetDoc.getParentDocument());
    } else {
      tdcValidator.validateGeneratingWarnings(budgetDoc.getParentDocument());
    }

    if (budgetForm.getMethodToCall().equals("save") && budgetForm.isAuditActivated()) {
      if (Boolean.valueOf(savedBudgetDoc.getParentDocument().getProposalBudgetFlag())) {
        forward = this.getReturnToProposalForward(budgetForm);
      } else {
        forward = mapping.findForward("budgetActions");
      }
    }

    return forward;
  }
  @Override
  protected boolean processCustomSaveDocumentBusinessRules(Document document) {
    if (!(document instanceof BudgetDocument)) {
      return false;
    }

    boolean valid = true;

    BudgetDocument budgetDocument = (BudgetDocument) document;

    GlobalVariables.getErrorMap().addToErrorPath("document");
    getDictionaryValidationService()
        .validateDocumentAndUpdatableReferencesRecursively(
            document,
            getMaxDictionaryValidationDepth(),
            VALIDATION_REQUIRED,
            CHOMP_LAST_LETTER_S_FROM_COLLECTION_NAME);
    GlobalVariables.getErrorMap().addToErrorPath("parentDocument");
    if (ObjectUtils.isNull(budgetDocument.getParentDocument())) {
      budgetDocument.refreshReferenceObject("parentDocument");
    }
    if (Boolean.valueOf(budgetDocument.getParentDocument().getProposalBudgetFlag())) {
      valid &= processBudgetVersionsBusinessRule(budgetDocument.getParentDocument(), true);
    }
    //        else {
    //            valid &= processBudgetTypeBusinessRules(budgetDocument);
    //        }
    GlobalVariables.getErrorMap().removeFromErrorPath("parentDocument");

    GlobalVariables.getErrorMap().addToErrorPath("budget");
    valid &= processBudgetPersonnelBusinessRules(budgetDocument);

    valid &= processBudgetExpenseBusinessRules(budgetDocument);

    valid &= processBudgetPersonnelBudgetBusinessRules(budgetDocument);

    valid &= processBudgetRatesBusinessRule(budgetDocument);

    valid &= processBudgetProjectIncomeBusinessRule(budgetDocument);

    GlobalVariables.getErrorMap().removeFromErrorPath("budget");
    GlobalVariables.getErrorMap().removeFromErrorPath("document");

    return valid;
  }
Exemple #17
0
  public ActionForward reject(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;

    Object question = request.getParameter(KNSConstants.QUESTION_INST_ATTRIBUTE_NAME);
    Object buttonClicked = request.getParameter(KNSConstants.QUESTION_CLICKED_BUTTON);
    String reason = request.getParameter(KNSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
    String methodToCall = ((KualiForm) form).getMethodToCall();
    final String questionText = "Are you sure you want to reject this document?";
    ActionForward forward;
    if (question == null) {
      forward =
          this.performQuestionWithInput(
              mapping,
              form,
              request,
              response,
              DOCUMENT_REJECT_QUESTION,
              questionText,
              KNSConstants.CONFIRMATION_QUESTION,
              methodToCall,
              "");
    } else if ((DOCUMENT_REJECT_QUESTION.equals(question))
        && ConfirmationQuestion.NO.equals(buttonClicked)) {
      forward = mapping.findForward(Constants.MAPPING_BASIC);
    } else {
      if (StringUtils.isEmpty(reason)) {
        String context = "";
        String errorKey = KeyConstants.ERROR_BUDGET_REJECT_NO_REASON;
        String errorPropertyName = DOCUMENT_REJECT_QUESTION;
        String errorParameter = "";
        reason = reason == null ? "" : reason;
        forward =
            this.performQuestionWithInputAgainBecauseOfErrors(
                mapping,
                form,
                request,
                response,
                DOCUMENT_REJECT_QUESTION,
                questionText,
                KNSConstants.CONFIRMATION_QUESTION,
                methodToCall,
                context,
                reason,
                errorKey,
                errorPropertyName,
                errorParameter);
      } else {
        // reject the document using the service.
        BudgetDocument document = ((BudgetForm) form).getDocument();
        document.documentHasBeenRejected(reason);
        KraServiceLocator.getService(KraDocumentRejectionService.class)
            .reject(
                document.getDocumentNumber(),
                reason,
                GlobalVariables.getUserSession().getPrincipalId());
        // tell the document it is being rejected and returned to the initial node.
        forward = super.returnToSender(request, mapping, kualiDocumentFormBase);
      }
    }
    return forward;
  }
  /**
   * This method checks business rules related to Budget Personnel Budget functionality
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetPersonnelBudgetBusinessRules(BudgetDocument budgetDocument) {
    boolean valid = true;

    ErrorMap errorMap = GlobalVariables.getErrorMap();

    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().isLessThan(new BudgetDecimal(0))
              || budgetPersonnelDetails.getPercentEffort().isGreaterThan(new BudgetDecimal(100))) {
            errorMap.putError(
                "budgetPeriod["
                    + i
                    + "].budgetLineItems["
                    + j
                    + "].budgetPersonnelDetailsList["
                    + k
                    + "].percentEffort",
                KeyConstants.ERROR_PERCENTAGE,
                Constants.PERCENT_EFFORT_FIELD);
          }
          if (budgetPersonnelDetails.getPercentCharged().isLessThan(new BudgetDecimal(0))
              || budgetPersonnelDetails.getPercentCharged().isGreaterThan(new BudgetDecimal(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;
  }
  /**
   * 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.
    ErrorMap errorMap = GlobalVariables.getErrorMap();

    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;
  }
  /**
   * 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;

    ErrorMap errorMap = GlobalVariables.getErrorMap();
    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 (!BudgetDecimal.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 (!BudgetDecimal.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;
  }
  /**
   * Validate budget project income. costshare percentage must be between 0 and 999.99
   *
   * @param budgetDocument
   * @return
   */
  protected boolean processBudgetProjectIncomeBusinessRule(BudgetDocument budgetDocument) {
    boolean valid = true;
    ErrorMap errorMap = GlobalVariables.getErrorMap();
    int i = 0;
    for (BudgetCostShare budgetCostShare : budgetDocument.getBudget().getBudgetCostShares()) {
      String errorPath = "budgetCostShare[" + i + "]";
      errorMap.addToErrorPath(errorPath);
      if (budgetCostShare.getSharePercentage() != null
          && (budgetCostShare.getSharePercentage().isLessThan(new BudgetDecimal(0))
              || budgetCostShare.getSharePercentage().isGreaterThan(new BudgetDecimal(100)))) {
        errorMap.putError("sharePercentage", KeyConstants.ERROR_COST_SHARE_PERCENTAGE);
        valid = false;
      }
      // check for duplicate fiscal year and source accounts on all unchecked cost shares
      if (i < budgetDocument.getBudget().getBudgetCostShareCount()) {
        for (int j = i + 1; j < budgetDocument.getBudget().getBudgetCostShareCount(); j++) {
          BudgetCostShare tmpCostShare = budgetDocument.getBudget().getBudgetCostShare(j);
          int thisFiscalYear =
              budgetCostShare.getProjectPeriod() == null
                  ? Integer.MIN_VALUE
                  : budgetCostShare.getProjectPeriod();
          int otherFiscalYear =
              tmpCostShare.getProjectPeriod() == null
                  ? Integer.MIN_VALUE
                  : tmpCostShare.getProjectPeriod();
          if (thisFiscalYear == otherFiscalYear
              && StringUtils.equalsIgnoreCase(
                  budgetCostShare.getSourceAccount(), tmpCostShare.getSourceAccount())) {
            errorMap.putError(
                "fiscalYear",
                KeyConstants.ERROR_COST_SHARE_DUPLICATE,
                thisFiscalYear == Integer.MIN_VALUE ? "" : thisFiscalYear + "",
                budgetCostShare.getSourceAccount() == null
                    ? "\"\""
                    : budgetCostShare.getSourceAccount());
            valid = false;
          }
        }
      }

      // validate project period stuff
      String currentField = "document.budget.budgetCostShare[" + i + "].projectPeriod";
      int numberOfProjectPeriods = budgetDocument.getBudget().getBudgetPeriods().size();
      boolean validationCheck =
          this.validateProjectPeriod(
              budgetCostShare.getProjectPeriod(), currentField, numberOfProjectPeriods);
      valid &= validationCheck;

      errorMap.removeFromErrorPath(errorPath);
      i++;
    }
    // check project income for values that are not greater than 0
    GlobalVariables.getErrorMap().removeFromErrorPath("budget");
    GlobalVariables.getErrorMap().addToErrorPath("budgets[0]");
    i = 0;
    for (BudgetProjectIncome budgetProjectIncome :
        budgetDocument.getBudget().getBudgetProjectIncomes()) {
      String errorPath = "budgetProjectIncomes[" + i + "]";
      errorMap.addToErrorPath(errorPath);
      if (budgetProjectIncome.getProjectIncome() == null
          || !budgetProjectIncome.getProjectIncome().isGreaterThan(new KualiDecimal(0.00))) {
        errorMap.putError("projectIncome", "error.projectIncome.negativeOrZero");
        valid = false;
      }
      errorMap.removeFromErrorPath(errorPath);
      i++;
    }
    GlobalVariables.getErrorMap().removeFromErrorPath("budgets[0]");
    GlobalVariables.getErrorMap().addToErrorPath("budget");

    return valid;
  }
  /**
   * @see
   *     org.kuali.ext.mm.service.ProfileService#isValidNewCustomerProfile(org.kuali.ext.mm.businessobject.Profile)
   */
  public boolean isValidNewCustomerProfile(Profile profile) {
    boolean isValid = true;
    FinancialDataService finDataService = SpringContext.getBean(FinancialDataService.class);

    if (!getAddressService().isPhoneNumberFormatValid(profile.getProfilePhoneNumber())) {
      GlobalVariables.getMessageMap()
          .putError(
              ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                  + "."
                  + MMConstants.Profile.PROFILE_PHONE_NUMBER,
              ShopCartKeyConstants.ERROR_PROFILE_PHONE_NUMBER);
      isValid = false;
    }

    if (!profile.isPersonalUseIndicator()) {
      if (StringUtils.isBlank(profile.getFinacialChartOfAccountsCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.FIN_COA_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_COA_CODE);
        isValid = false;
      } else {
        if (!finDataService.validateChart(profile.getFinacialChartOfAccountsCode())) {
          GlobalVariables.getMessageMap()
              .putError(
                  ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                      + "."
                      + MMConstants.Profile.FIN_COA_CODE,
                  ShopCartKeyConstants.ERROR_PROFILE_COA_CODE);
          isValid = false;
        }
      }
      if (StringUtils.isBlank(profile.getOrganizationCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.ORGANIZATION_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_ORG_CODE_BLANK,
                profile.getOrganizationCode());
        isValid = false;
      } else {
        if (!finDataService.validateOrg(
            profile.getFinacialChartOfAccountsCode(), profile.getOrganizationCode())) {
          GlobalVariables.getMessageMap()
              .putError(
                  ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                      + "."
                      + MMConstants.Profile.ORGANIZATION_CODE,
                  ShopCartKeyConstants.ERROR_PROFILE_ORG_CODE,
                  profile.getOrganizationCode(),
                  profile.getFinacialChartOfAccountsCode());
          isValid = false;
        }
      }
      if (StringUtils.isBlank(profile.getAccountNumber())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.ACCOUNT_NBR,
                ShopCartKeyConstants.ERROR_PROFILE_ACCOUNT_NUMBER);
        isValid = false;
      } else {
        if (!finDataService.validateAccount(
            profile.getFinacialChartOfAccountsCode(), profile.getAccountNumber())) {
          GlobalVariables.getMessageMap()
              .putError(
                  ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                      + "."
                      + MMConstants.Profile.ACCOUNT_NBR,
                  ShopCartKeyConstants.ERROR_PROFILE_ACCOUNT_NUMBER);
          isValid = false;
        } else {
          if (StringUtils.isNotBlank(profile.getSubAccountNumber())) {
            if (!finDataService.validateSubAccount(
                profile.getFinacialChartOfAccountsCode(),
                profile.getAccountNumber(),
                profile.getSubAccountNumber())) {
              GlobalVariables.getMessageMap()
                  .putError(
                      ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                          + "."
                          + MMConstants.Profile.SUB_ACCOUNT_NUMBER,
                      ShopCartKeyConstants.ERROR_PROFILE_SUB_ACCOUNT,
                      profile.getSubAccountNumber());
              isValid = false;
            }
          }
        }
      }
      if (StringUtils.isNotBlank(profile.getProjectCode())
          && !finDataService.validateProject(profile.getProjectCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.PROJECT_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_PROJECT_CODE,
                profile.getProjectCode());
        isValid = false;
      }
      if (StringUtils.isBlank(profile.getCampusCode()) || !isValidCampus(profile.getCampusCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.CAMPUS_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_CAMPUS_CODE);
        isValid = false;
      }
      if (StringUtils.isBlank(profile.getDeliveryBuildingCode())
          || !finDataService.validateBuilding(
              profile.getCampusCode(), profile.getDeliveryBuildingCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.DELIVERY_BUILDING_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_DELIVERY_BUILDING);
        isValid = false;
      }
      if (StringUtils.isBlank(profile.getDeliveryBuildingRoomNumber())
          || !finDataService.validateBuildingRoom(
              profile.getCampusCode(),
              profile.getDeliveryBuildingCode(),
              profile.getDeliveryBuildingRoomNumber())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.DELIVERY_BUILDING_ROOM,
                ShopCartKeyConstants.ERROR_PROFILE_DELIVERY_BUILDING_ROOM);
        isValid = false;
      }
      if (StringUtils.isBlank(profile.getBillingBuildingCode())
          || !finDataService.validateBuilding(
              profile.getCampusCode(), profile.getBillingBuildingCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                ShopCartConstants.ProfileForm.PROFILE_TO_EDIT
                    + "."
                    + MMConstants.Profile.BILLING_BUILDING_CODE,
                ShopCartKeyConstants.ERROR_PROFILE_BILLING_BUILDING);
        isValid = false;
      }
    }
    return isValid;
  }
 private String getUserIdentifier() {
   return GlobalVariables.getUserSession().getPrincipalId();
 }
  /**
   * If there are line restrictions and the initiator override flag is turned on, we need to disable
   * the copy and error correct buttons since those would result in documents displaying the
   * restricted lines
   *
   * @see
   *     org.kuali.rice.kns.document.authorization.DocumentAuthorizer#getDocumentActions(org.kuali.rice.kns.document.Document,
   *     org.kuali.rice.kim.bo.Person, java.util.Set)
   */
  public Set<String> getDocumentActions(
      Document document, Person user, Set<String> documentActions) {
    Set<String> documentActionsToReturn =
        documentAuthorizer.getDocumentActions(document, user, documentActions);

    AccessSecurityService securityService = SpringContext.getBean(AccessSecurityService.class);

    boolean alwaysAllowInitiatorAccess =
        SpringContext.getBean(ParameterService.class)
            .getIndicatorParameter(
                SecConstants.ACCESS_SECURITY_NAMESPACE_CODE,
                SecConstants.ALL_PARAMETER_DETAIL_COMPONENT,
                SecConstants.SecurityParameterNames.ALWAYS_ALLOW_INITIATOR_LINE_ACCESS_IND);
    if (alwaysAllowInitiatorAccess) {
      // determine if any lines are view restricted
      boolean hasViewRestrictions = false;

      AccountingDocument accountingDocument = (AccountingDocument) document;
      for (Iterator iterator = accountingDocument.getSourceAccountingLines().iterator();
          iterator.hasNext(); ) {
        AccountingLine line = (AccountingLine) iterator.next();
        if (!securityService.canViewDocumentAccountingLine(accountingDocument, line, user)) {
          hasViewRestrictions = true;
          break;
        }
      }

      if (!hasViewRestrictions) {
        for (Iterator iterator = accountingDocument.getTargetAccountingLines().iterator();
            iterator.hasNext(); ) {
          AccountingLine line = (AccountingLine) iterator.next();
          if (!securityService.canViewDocumentAccountingLine(accountingDocument, line, user)) {
            hasViewRestrictions = true;
            break;
          }
        }
      }

      // if we have restrictions then disable copy and error correction
      if (hasViewRestrictions) {
        if (documentActionsToReturn.contains(KNSConstants.KUALI_ACTION_CAN_COPY)) {
          documentActionsToReturn.remove(KNSConstants.KUALI_ACTION_CAN_COPY);
          GlobalVariables.getMessageMap()
              .putInfo(
                  KFSConstants.GLOBAL_ERRORS,
                  SecKeyConstants.MESSAGE_DOCUMENT_COPY_RESTRICTED,
                  (String) null);
        }

        if (documentActionsToReturn.contains(KFSConstants.KFS_ACTION_CAN_ERROR_CORRECT)) {
          documentActionsToReturn.remove(KFSConstants.KFS_ACTION_CAN_ERROR_CORRECT);
          GlobalVariables.getMessageMap()
              .putInfo(
                  KFSConstants.GLOBAL_ERRORS,
                  SecKeyConstants.MESSAGE_DOCUMENT_ERROR_CORRECT_RESTRICTED,
                  (String) null);
        }
      }
    }

    return documentActionsToReturn;
  }
  /**
   * Validates a definition assignment to the principal
   *
   * @param principalDefinition SecurityPrincipalDefinition to validate
   * @param errorKeyPrefix String errorPrefix to use if any errors are found
   * @return boolean true if validation was successful, false if there are errors
   */
  protected boolean validatePrincipalDefinition(
      SecurityPrincipalDefinition principalDefinition, String errorKeyPrefix) {
    boolean isValid = true;

    principalDefinition.refreshNonUpdateableReferences();

    if (ObjectUtils.isNull(principalDefinition.getSecurityDefinition())) {
      return false;
    }

    String attributeName =
        principalDefinition.getSecurityDefinition().getSecurityAttribute().getName();
    String attributeValue = principalDefinition.getAttributeValue();

    // if value is blank (which is allowed) no need to validate
    if (StringUtils.isBlank(attributeValue)) {
      return true;
    }

    // descend attributes do not allow multiple values or wildcards, and operator must be equal
    if (SecConstants.SecurityAttributeNames.CHART_DESCEND_HIERARCHY.equals(attributeName)
        || SecConstants.SecurityAttributeNames.ORGANIZATION_DESCEND_HIERARCHY.equals(
            attributeName)) {
      if (StringUtils.contains(
          attributeValue,
          SecConstants.SecurityValueSpecialCharacters.MULTI_VALUE_SEPERATION_CHARACTER)) {
        GlobalVariables.getMessageMap()
            .putError(
                errorKeyPrefix + SecPropertyConstants.ATTRIBUTE_VALUE,
                SecKeyConstants.ERROR_MODEL_DEFINITION_MULTI_ATTR_VALUE,
                attributeName);
        isValid = false;
      }

      if (StringUtils.contains(
          attributeValue, SecConstants.SecurityValueSpecialCharacters.WILDCARD_CHARACTER)) {
        GlobalVariables.getMessageMap()
            .putError(
                errorKeyPrefix + SecPropertyConstants.ATTRIBUTE_VALUE,
                SecKeyConstants.ERROR_MODEL_DEFINITION_WILDCARD_ATTR_VALUE,
                attributeName);
        isValid = false;
      }

      if (!SecConstants.SecurityDefinitionOperatorCodes.EQUAL.equals(
          principalDefinition.getOperatorCode())) {
        GlobalVariables.getMessageMap()
            .putError(
                errorKeyPrefix + SecPropertyConstants.OPERATOR_CODE,
                SecKeyConstants.ERROR_MODEL_DEFINITION_OPERATOR_CODE_NOT_EQUAL,
                attributeName);
        isValid = false;
      }
    }

    // validate attribute value for existence
    isValid =
        isValid
            && SecurityValidationUtil.validateAttributeValue(
                attributeName, attributeValue, errorKeyPrefix);

    return isValid;
  }