protected void isAuthorized() {
   // check permissions
   boolean userHasPermission = false;
   String permissionName = AwardPermissionConstants.VIEW_AWARD.getAwardPermission();
   userHasPermission =
       getUnitAuthorizationService()
           .hasPermission(
               GlobalVariables.getUserSession().getPrincipalId(), "KC-AWARD", permissionName);
   if (!userHasPermission) {
     permissionName = AwardPermissionConstants.MODIFY_AWARD.getAwardPermission();
     userHasPermission =
         getUnitAuthorizationService()
             .hasPermission(
                 GlobalVariables.getUserSession().getPrincipalId(), "KC-AWARD", permissionName);
   }
   if (!userHasPermission) {
     permissionName = AwardPermissionConstants.MODIFY_AWARD_REPORT_TRACKING.getAwardPermission();
     userHasPermission =
         getUnitAuthorizationService()
             .hasPermission(
                 GlobalVariables.getUserSession().getPrincipalId(), "KC-AWARD", permissionName);
   }
   if (!userHasPermission) {
     throw new AuthorizationException(
         GlobalVariables.getUserSession().getPrincipalName(), "Search", "Report Tracking");
   }
 }
  @Override
  public List<KeyValue> getKeyValues() {
    List<KeyValue> keyValues = new ArrayList<KeyValue>();
    TimeAndMoneyDocument document = (TimeAndMoneyDocument) getDocument();

    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 ConcreteKeyValue(
                (String) awardNumber,
                document.getAwardHierarchyItems().get(awardNumber).getAwardNumber()));
      }
    }

    return keyValues;
  }
  @Override
  protected void populateAdHocActionRequestCodes(KualiDocumentFormBase formBase) {
    Document document = formBase.getDocument();
    DocumentAuthorizer documentAuthorizer =
        getDocumentHelperService().getDocumentAuthorizer(document);
    Map<String, String> adHocActionRequestCodes = new HashMap<String, String>();

    if (documentAuthorizer.canSendAdHocRequests(
        document,
        KewApiConstants.ACTION_REQUEST_FYI_REQ,
        GlobalVariables.getUserSession().getPerson())) {
      adHocActionRequestCodes.put(
          KewApiConstants.ACTION_REQUEST_FYI_REQ, KewApiConstants.ACTION_REQUEST_FYI_REQ_LABEL);
    }
    if ((document.getDocumentHeader().getWorkflowDocument().isInitiated()
            || document.getDocumentHeader().getWorkflowDocument().isSaved()
            || document.getDocumentHeader().getWorkflowDocument().isEnroute())
        && documentAuthorizer.canSendAdHocRequests(
            document,
            KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ,
            GlobalVariables.getUserSession().getPerson())) {
      adHocActionRequestCodes.put(
          KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ,
          KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL);
    }
    formBase.setAdHocActionRequestCodes(adHocActionRequestCodes);
  }
 /**
  * Takes a routeHeaderId for a particular document and constructs the URL to forward to that
  * document Copied from KraTransactionalDocument as this does not extend from that.
  *
  * @param routeHeaderId
  * @return String
  */
 protected String buildForwardUrl(String routeHeaderId) {
   ResearchDocumentService researchDocumentService =
       KraServiceLocator.getService(ResearchDocumentService.class);
   String forward = researchDocumentService.getDocHandlerUrl(routeHeaderId);
   // forward = forward.replaceFirst(DEFAULT_TAB, ALTERNATE_OPEN_TAB);
   if (forward.indexOf("?") == -1) {
     forward += "?";
   } else {
     forward += "&";
   }
   forward += KewApiConstants.DOCUMENT_ID_PARAMETER + "=" + routeHeaderId;
   forward +=
       "&"
           + KewApiConstants.COMMAND_PARAMETER
           + "="
           + NotificationConstants.NOTIFICATION_DETAIL_VIEWS.DOC_SEARCH_VIEW;
   if (GlobalVariables.getUserSession().isBackdoorInUse()) {
     forward +=
         "&"
             + KewApiConstants.BACKDOOR_ID_PARAMETER
             + "="
             + GlobalVariables.getUserSession().getPrincipalName();
   }
   return forward;
 }
Example #5
0
  /** . The method is for doRouteStatusChange */
  @Override
  public void doRouteStatusChange(DocumentRouteStatusChange statusChangeEvent) {
    super.doRouteStatusChange(statusChangeEvent);

    String newStatus = statusChangeEvent.getNewRouteStatus();

    if (KewApiConstants.ROUTE_HEADER_FINAL_CD.equalsIgnoreCase(newStatus)) {
      getVersionHistoryService()
          .updateVersionHistory(
              getSubAward(),
              VersionStatus.ACTIVE,
              GlobalVariables.getUserSession().getPrincipalName());
    }
    if (newStatus.equalsIgnoreCase(KewApiConstants.ROUTE_HEADER_CANCEL_CD)
        || newStatus.equalsIgnoreCase(KewApiConstants.ROUTE_HEADER_DISAPPROVED_CD)) {
      getVersionHistoryService()
          .updateVersionHistory(
              getSubAward(),
              VersionStatus.CANCELED,
              GlobalVariables.getUserSession().getPrincipalName());
    }

    for (SubAward subAward : subAwardList) {
      subAward.setSubAwardDocument(this);
    }
  }
 @Override
 public void performPurchaseOrderFirstTransmitViaPrinting(
     String documentNumber, ByteArrayOutputStream baosPDF) {
   PurchaseOrderDocument po = getPurchaseOrderByDocumentNumber(documentNumber);
   String environment =
       kualiConfigurationService.getPropertyValueAsString(KFSConstants.ENVIRONMENT_KEY);
   Collection<String> generatePDFErrors =
       printService.generatePurchaseOrderPdf(po, baosPDF, environment, null);
   if (!generatePDFErrors.isEmpty()) {
     addStringErrorMessagesToMessageMap(
         PurapKeyConstants.ERROR_PURCHASE_ORDER_PDF, generatePDFErrors);
     throw new ValidationException("printing purchase order for first transmission failed");
   }
   if (ObjectUtils.isNotNull(po.getPurchaseOrderFirstTransmissionTimestamp())) {
     // should not call this method for first transmission if document has already been transmitted
     String errorMsg =
         "Method to perform first transmit was called on document (doc id "
             + documentNumber
             + ") with already filled in 'first transmit date'";
     LOG.error(errorMsg);
     throw new RuntimeException(errorMsg);
   }
   Timestamp currentDate = dateTimeService.getCurrentTimestamp();
   po.setPurchaseOrderFirstTransmissionTimestamp(currentDate);
   po.setPurchaseOrderLastTransmitTimestamp(currentDate);
   po.setOverrideWorkflowButtons(Boolean.FALSE);
   // KFSUPGRADE-336
   boolean performedAction =
       purapWorkflowIntegrationService.takeAllActionsForGivenCriteria(
           po,
           "Action taken automatically as part of document initial print transmission",
           CUPurapConstants.PurchaseOrderStatuses.NODE_DOCUMENT_TRANSMISSION,
           GlobalVariables.getUserSession().getPerson(),
           null);
   if (!performedAction) {
     Person systemUserPerson =
         getPersonService().getPersonByPrincipalName(KFSConstants.SYSTEM_USER);
     purapWorkflowIntegrationService.takeAllActionsForGivenCriteria(
         po,
         "Action taken automatically as part of document initial print transmission by user "
             + GlobalVariables.getUserSession().getPerson().getName(),
         CUPurapConstants.PurchaseOrderStatuses.NODE_DOCUMENT_TRANSMISSION,
         systemUserPerson,
         KFSConstants.SYSTEM_USER);
   }
   po.setOverrideWorkflowButtons(Boolean.TRUE);
   if (!po.getApplicationDocumentStatus()
       .equals(PurapConstants.PurchaseOrderStatuses.APPDOC_OPEN)) {
     attemptSetupOfInitialOpenOfDocument(po);
     if (shouldAdhocFyi(po.getRequisitionSourceCode())) {
       sendAdhocFyi(po);
     }
   }
   purapService.saveDocumentNoValidation(po);
 }
  /**
   * The default implementation - this retrieves all documents by a list of documentHeader for a
   * given class.
   *
   * @see
   *     org.kuali.rice.krad.service.DocumentService#getDocumentsByListOfDocumentHeaderIds(java.lang.Class,
   *     java.util.List)
   */
  @Override
  public List<Document> getDocumentsByListOfDocumentHeaderIds(
      Class<? extends Document> documentClass, List<String> documentHeaderIds)
      throws WorkflowException {
    // validate documentHeaderIdList and contents
    if (documentHeaderIds == null) {
      throw new IllegalArgumentException("invalid (null) documentHeaderId list");
    }
    int index = 0;
    for (String documentHeaderId : documentHeaderIds) {
      if (StringUtils.isBlank(documentHeaderId)) {
        throw new IllegalArgumentException(
            "invalid (blank) documentHeaderId at list index " + index);
      }
      index++;
    }

    boolean internalUserSession = false;
    try {
      // KFSMI-2543 - allowed method to run without a user session so it can be used
      // by workflow processes
      if (GlobalVariables.getUserSession() == null) {
        internalUserSession = true;
        GlobalVariables.setUserSession(new UserSession(KRADConstants.SYSTEM_USER));
        GlobalVariables.clear();
      }

      // retrieve all documents that match the document header ids
      List<? extends Document> rawDocuments =
          getLegacyDataAdapter().findByDocumentHeaderIds(documentClass, documentHeaderIds);

      // post-process them
      List<Document> documents = new ArrayList<Document>();
      for (Document document : rawDocuments) {
        WorkflowDocument workflowDocument =
            getWorkflowDocumentService()
                .loadWorkflowDocument(
                    document.getDocumentNumber(), GlobalVariables.getUserSession().getPerson());

        document = postProcessDocument(document.getDocumentNumber(), workflowDocument, document);
        documents.add(document);
      }
      return documents;
    } finally {
      // if a user session was established for this call, clear it our
      if (internalUserSession) {
        GlobalVariables.clear();
        GlobalVariables.setUserSession(null);
      }
    }
  }
  /**
   * Validates that the given accounting line is accessible for editing by the current user.
   * <strong>This method expects a document as the first parameter and an accounting line as the
   * second</strong>
   *
   * @see org.kuali.ole.sys.document.validation.Validation#validate(java.lang.Object[])
   */
  @Override
  public boolean validate(AttributedDocumentEvent event) {

    if (purapService.isDocumentStoppedInRouteNode(
        (PurchasingAccountsPayableDocument) event.getDocument(), "New Unordered Items")) {
      // DO NOTHING: do not check that user owns acct lines; at this level, they can edit all
      // accounts on PO amendment
      return true;

    } else if (SpringContext.getBean(FinancialSystemWorkflowHelperService.class)
        .isAdhocApprovalRequestedForPrincipal(
            event.getDocument().getDocumentHeader().getWorkflowDocument(),
            GlobalVariables.getUserSession().getPrincipalId())) {
      return true;
    } else {
      boolean result = false;
      boolean setDummyAccountIdentifier = false;

      if (needsDummyAccountIdentifier()) {
        ((PurApAccountingLine) getAccountingLineForValidation())
            .setAccountIdentifier(
                Integer.MAX_VALUE); // avoid conflicts with any accouting identifier on any other
        // accounting lines in the doc because, you know, you never know...
        setDummyAccountIdentifier = true;
      }

      result = super.validate(event);

      if (setDummyAccountIdentifier) {
        ((PurApAccountingLine) getAccountingLineForValidation()).setAccountIdentifier(null);
      }

      return result;
    }
  }
  @Override
  public Document saveDocument(
      Document document, Class<? extends KualiDocumentEvent> kualiDocumentEventClass)
      throws WorkflowException, ValidationException {
    checkForNulls(document);
    if (kualiDocumentEventClass == null) {
      throw new IllegalArgumentException("invalid (null) kualiDocumentEventClass");
    }
    // if event is not an instance of a SaveDocumentEvent or a SaveOnlyDocumentEvent
    if (!SaveEvent.class.isAssignableFrom(kualiDocumentEventClass)) {
      throw new ConfigurationException(
          "The KualiDocumentEvent class '"
              + kualiDocumentEventClass.getName()
              + "' does not implement the class '"
              + SaveEvent.class.getName()
              + "'");
    }
    //        if (!getDocumentActionFlags(document).getCanSave()) {
    //            throw buildAuthorizationException("save", document);
    //        }
    document.prepareForSave();
    Document savedDocument =
        validateAndPersistDocumentAndSaveAdHocRoutingRecipients(
            document, generateKualiDocumentEvent(document, kualiDocumentEventClass));
    prepareWorkflowDocument(savedDocument);
    getWorkflowDocumentService()
        .save(savedDocument.getDocumentHeader().getWorkflowDocument(), null);

    UserSessionUtils.addWorkflowDocument(
        GlobalVariables.getUserSession(), savedDocument.getDocumentHeader().getWorkflowDocument());

    return savedDocument;
  }
 protected void addNotes(
     String documentNumber,
     List<SubObjectCode> listOfSubObjects,
     String messageKey,
     PersistableBusinessObject noteParent,
     Note noteTemplate) {
   for (int i = 0; i < listOfSubObjects.size(); i += getNumSubObjectsPerNote()) {
     try {
       String subAccountString =
           createSubObjectChunk(listOfSubObjects, i, i + getNumSubObjectsPerNote());
       if (StringUtils.isNotBlank(subAccountString)) {
         String noteTextTemplate = kualiConfigurationService.getPropertyValueAsString(messageKey);
         String noteText = MessageFormat.format(noteTextTemplate, subAccountString);
         Note note =
             noteService.createNote(
                 noteTemplate, noteParent, GlobalVariables.getUserSession().getPrincipalId());
         note.setNoteText(noteText);
         note.setNotePostedTimestampToCurrent();
         noteService.save(note);
       }
     } catch (Exception e) {
       LOG.error("Unable to create/save notes for document " + documentNumber, e);
       throw new RuntimeException("Unable to create/save notes for document " + documentNumber, e);
     }
   }
 }
 @Override
 public boolean isProtocolAdmin() {
   return this.systemAuthorizationService.hasRole(
       GlobalVariables.getUserSession().getPrincipalId(),
       NAMESPACE,
       RoleConstants.IACUC_ADMINISTRATOR);
 }
 // this method should be invoked from within the transaction wrapper that covers the request
 // processing so
 // that the db-calls in this method do not each generate new transactions. If executed from within
 // the context
 // of display rendering, this logic will be quite expensive due to the number of new transactions
 // needed.
 @Override
 public Collection<CMT> getAssignmentCommittees(
     String protocolLeadUnit, String docRouteStatus, String currentCommitteeId) {
   Collection<CMT> assignmentCommittees = new ArrayList<CMT>();
   // get the initial list of all valid committees; some of them will be filtered out by the logic
   // below
   Collection<CMT> candidateCommittees = getCandidateCommittees();
   if (CollectionUtils.isNotEmpty(candidateCommittees)) {
     if (isSaved(docRouteStatus)) {
       // Use the lead unit of the protocol to determine committees
       Set<String> unitIds = getProtocolUnitIds(protocolLeadUnit);
       for (CMT committee : candidateCommittees) {
         if (StringUtils.equalsIgnoreCase(committee.getCommitteeDocument().getDocStatusCode(), "F")
             && unitIds.contains(committee.getHomeUnit().getUnitNumber())) {
           assignmentCommittees.add(committee);
         }
       }
     } else {
       // we check the current user's authorization to assign committees
       String principalId = GlobalVariables.getUserSession().getPerson().getPrincipalId();
       for (CMT committee : candidateCommittees) {
         if (isCurrentUserAuthorizedToAssignThisCommittee(principalId, committee)
             || committee.getCommitteeId().equals(currentCommitteeId)) {
           assignmentCommittees.add(committee);
         }
       }
     }
   }
   return assignmentCommittees;
 }
  /**
   * This method will use the DocumentService to create a new document. The documentTypeName is
   * gathered by using MaintenanceDocumentDictionaryService which uses Account class to get the
   * document type name.
   *
   * @param AccountCreationStatusDTO
   * @return document returns a new document for the account document type or null if there is an
   *     exception thrown.
   */
  public Document createCGAccountMaintenanceDocument(
      AccountCreationStatusDTO accountCreationStatus) {

    boolean internalUserSession = false;
    try {
      if (GlobalVariables.getUserSession() == null) {
        internalUserSession = true;
        GlobalVariables.setUserSession(new UserSession(KFSConstants.SYSTEM_USER));
        GlobalVariables.clear();
      }
      Document document =
          getDocumentService()
              .getNewDocument(
                  SpringContext.getBean(MaintenanceDocumentDictionaryService.class)
                      .getDocumentTypeName(Account.class));
      return document;

    } catch (Exception e) {
      accountCreationStatus.setErrorMessages(
          GlobalVariablesExtractHelper.extractGlobalVariableErrors());
      accountCreationStatus.setStatus(KcConstants.KcWebService.STATUS_KC_FAILURE);
      return null;
    } finally {
      // if a user session was established for this call, clear it our
      if (internalUserSession) {
        GlobalVariables.clear();
        GlobalVariables.setUserSession(null);
      }
    }
  }
 /**
  * This method is to delete alert
  *
  * @param formBase
  * @param result
  * @param request
  * @param response
  * @return ModelAndView
  */
 @RequestMapping(params = "methodToCall=approveAlert")
 public ModelAndView approveAlert(
     @ModelAttribute("KualiForm") DocumentFormBase formBase,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response) {
   AlertBo alertBo = null;
   MaintenanceDocumentForm maintenanceDocumentForm = (MaintenanceDocumentForm) formBase;
   OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
       (OlePersistableBusinessObjectBase)
           maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
   int index =
       Integer.parseInt(
           maintenanceDocumentForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
   olePersistableBusinessObjectBase.getAlertBoList().get(index).setAlertStatus(false);
   olePersistableBusinessObjectBase
       .getAlertBoList()
       .get(index)
       .setAlertModifierId(GlobalVariables.getUserSession().getPrincipalId());
   if (olePersistableBusinessObjectBase.getAlertBoList().get(index).isRepeatable()) {
     alertBo =
         alertHelperService.createNewAlertBo(
             olePersistableBusinessObjectBase.getAlertBoList().get(index));
     olePersistableBusinessObjectBase.getAlertBoList().add(alertBo);
   }
   return super.navigate(formBase, result, request, response);
 }
  /**
   * Makes service calls to rebuild the report control and sub-fund or object code select lists if
   * needed.
   *
   * @param principalName - current user requesting the report
   * @param buildHelper - contains the current and requested build states
   * @param reportSelectMode - indicates whether the report takes a sub-fund or object code select
   *     list
   */
  protected void buildControlLists(
      String principalName,
      Integer universityFiscalYear,
      ReportControlListBuildHelper buildHelper,
      ReportSelectMode reportSelectMode) {
    BudgetReportsControlListService budgetReportsControlListService =
        SpringContext.getBean(BudgetReportsControlListService.class);

    if (buildHelper.isBuildNeeded()) {
      String[] pointOfViewFields = buildHelper.getRequestedState().getPointOfView().split("[-]");
      budgetReportsControlListService.updateReportsControlList(
          principalName,
          universityFiscalYear,
          pointOfViewFields[0],
          pointOfViewFields[1],
          buildHelper.getRequestedState().getBuildMode());

      if (ReportSelectMode.SUBFUND.equals(reportSelectMode)) {
        budgetReportsControlListService.updateReportSubFundGroupSelectList(principalName);
      } else if (ReportSelectMode.OBJECT_CODE.equals(reportSelectMode)
          || ReportSelectMode.REASON.equals(reportSelectMode)) {
        budgetReportsControlListService.updateReportObjectCodeSelectList(principalName);
      }

      buildHelper.requestBuildComplete();
      GlobalVariables.getUserSession()
          .addObject(BCConstants.Report.CONTROL_BUILD_HELPER_SESSION_NAME, buildHelper);
    }
  }
  /**
   * @see
   *     org.kuali.rice.krad.service.DocumentService#cancelDocument(org.kuali.rice.krad.document.Document,
   *     java.lang.String)
   */
  @Override
  public Document cancelDocument(Document document, String annotation) throws WorkflowException {
    checkForNulls(document);
    // if (!getDocumentActionFlags(document).getCanCancel()) {
    //    throw buildAuthorizationException("cancel", document);
    // }
    if (document instanceof MaintenanceDocument) {
      MaintenanceDocument maintDoc = ((MaintenanceDocument) document);
      if (maintDoc.getOldMaintainableObject() != null
          && (maintDoc.getOldMaintainableObject().getDataObject() instanceof BusinessObject)) {
        ((BusinessObject) maintDoc.getOldMaintainableObject().getDataObject()).refresh();
      }

      if (maintDoc.getNewMaintainableObject().getDataObject() instanceof BusinessObject) {
        ((BusinessObject) maintDoc.getNewMaintainableObject().getDataObject()).refresh();
      }
    }
    prepareWorkflowDocument(document);
    getWorkflowDocumentService()
        .cancel(document.getDocumentHeader().getWorkflowDocument(), annotation);
    UserSessionUtils.addWorkflowDocument(
        GlobalVariables.getUserSession(), document.getDocumentHeader().getWorkflowDocument());

    removeAdHocPersonsAndWorkgroups(document);
    return document;
  }
  /** @see org.kuali.rice.krad.service.DocumentService#documentExists(java.lang.String) */
  @Override
  public boolean documentExists(String documentHeaderId) {
    // validate parameters
    if (StringUtils.isBlank(documentHeaderId)) {
      throw new IllegalArgumentException("invalid (blank) documentHeaderId");
    }

    boolean internalUserSession = false;
    try {
      // KFSMI-2543 - allowed method to run without a user session so it can be used
      // by workflow processes
      if (GlobalVariables.getUserSession() == null) {
        internalUserSession = true;
        GlobalVariables.setUserSession(new UserSession(KRADConstants.SYSTEM_USER));
        GlobalVariables.clear();
      }

      // look for workflowDocumentHeader, since that supposedly won't break the transaction
      if (getWorkflowDocumentService().workflowDocumentExists(documentHeaderId)) {
        // look for docHeaderId, since that fails without breaking the transaction
        return documentHeaderService.getDocumentHeaderById(documentHeaderId) != null;
      }

      return false;
    } finally {
      // if a user session was established for this call, clear it our
      if (internalUserSession) {
        GlobalVariables.clear();
        GlobalVariables.setUserSession(null);
      }
    }
  }
 /**
  * This method sorts the report.
  *
  * @param displayList
  * @param sortPropertyName
  */
 protected void sortReport(List displayList, String sortPropertyName) {
   Integer numSortIndexClick =
       (ObjectUtils.isNull(
               GlobalVariables.getUserSession()
                   .retrieveObject(ArConstants.NUM_SORT_INDEX_CLICK_SESSION_KEY)))
           ? 1
           : new Integer(
               GlobalVariables.getUserSession()
                   .retrieveObject(ArConstants.NUM_SORT_INDEX_CLICK_SESSION_KEY)
                   .toString());
   if (((numSortIndexClick) % 2) == 0) {
     DynamicCollectionComparator.sort(displayList, SortOrder.DESC, sortPropertyName);
   } else {
     DynamicCollectionComparator.sort(displayList, SortOrder.ASC, sortPropertyName);
   }
 }
 /*
  * edit an existing note
  */
 public void editNote(int noteToModify) {
   CoiDisclosureNotepad notepadObject =
       this.getCoiDisclosure().getCoiDisclosureNotepads().get(noteToModify);
   notepadObject.setUpdateUser(GlobalVariables.getUserSession().getPrincipalName());
   notepadObject.setUpdateTimestamp(dateTimeService.getCurrentTimestamp());
   notepadObject.setEditable(true);
 }
 protected boolean requiresCertification(final TravelerDetail traveler) {
   final Person user = GlobalVariables.getUserSession().getPerson();
   if (user.getPrincipalId().equals(traveler.getPrincipalId()) && isEmployee(traveler)) {
     return true;
   }
   return false;
 }
  protected void cancelOnlineReviewDocument(
      ProtocolOnlineReviewDocumentBase protocolOnlineReviewDocument,
      ProtocolSubmissionBase submission,
      String annotation) {
    try {

      final String principalId =
          identityManagementService
              .getPrincipalByPrincipalName(KRADConstants.SYSTEM_USER)
              .getPrincipalId();
      WorkflowDocument workflowDocument =
          WorkflowDocumentFactory.loadDocument(
              principalId, protocolOnlineReviewDocument.getDocumentNumber());

      if (workflowDocument.isEnroute()
          || workflowDocument.isInitiated()
          || workflowDocument.isSaved()) {
        workflowDocument.superUserCancel(
            String.format(
                "Review Cancelled from assign reviewers action by %s",
                GlobalVariables.getUserSession().getPrincipalId()));
      }
    } catch (Exception e) {
      String errorMessage =
          String.format(
              "Exception generated while executing superUserCancel on document %s in removeOnlineReviewDocument. Message: %s",
              protocolOnlineReviewDocument.getDocumentNumber(), e.getMessage());
      LOG.error(errorMessage);
      throw new RuntimeException(errorMessage, e);
    }
  }
 public ActionForward quickApproveDisclosure(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   CoiCustomSearchForm searchForm = (CoiCustomSearchForm) form;
   CustomAdminSearchHelper helper = searchForm.getCustomAdminSearchHelper();
   String coiDisclosureDocumentNumber = getCoiDisclosureDocumentNumber(request);
   CoiDisclosureDocument coiDisclosureDocument =
       (CoiDisclosureDocument)
           getDocumentService().getByDocumentHeaderId(coiDisclosureDocumentNumber);
   if (!helper.hasFinEnt(coiDisclosureDocument.getCoiDisclosure())
       && getKraAuthorizationService()
           .hasPermission(
               GlobalVariables.getUserSession().getPrincipalId(),
               coiDisclosureDocument.getCoiDisclosure(),
               PermissionConstants.APPROVE_COI_DISCLOSURE)) {
     getCoiDisclosureActionService()
         .approveDisclosure(
             coiDisclosureDocument.getCoiDisclosure(), CoiDispositionStatus.NO_CONFLICT_EXISTS);
     GlobalVariables.getMessageMap()
         .putInfo(Constants.NO_FIELD, KeyConstants.MESSAGE_COI_DISCLOSURE_QUICK_APPROVED);
   } else {
     GlobalVariables.getMessageMap()
         .putError(Constants.NO_FIELD, KeyConstants.ERROR_COI_NO_PERMISSION_APPROVE);
   }
   helper.setAllOpenReviews(getOpenReviews());
   helper.setPendingReviews(getPendingReviews());
   helper.setInProgressReviews(getInProgressReviews());
   return mapping.findForward(Constants.MAPPING_BASIC);
 }
  /**
   * This method to check whether 'lookupreturn' is specified if lookupclass is selected.
   *
   * @param maintenanceDocument
   * @return
   */
  private boolean checkLookupReturn(MaintenanceDocument maintenanceDocument) {
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "New maintainable is: " + maintenanceDocument.getNewMaintainableObject().getClass());
    }
    ProposalColumnsToAlter newEditableProposalField =
        (ProposalColumnsToAlter) maintenanceDocument.getNewMaintainableObject().getDataObject();

    if (StringUtils.isNotBlank(newEditableProposalField.getLookupClass())) {
      GlobalVariables.getUserSession()
          .addObject(
              Constants.LOOKUP_CLASS_NAME, (Object) newEditableProposalField.getLookupClass());
    }
    if (StringUtils.isNotBlank(newEditableProposalField.getLookupClass())
        && StringUtils.isBlank(newEditableProposalField.getLookupReturn())) {
      GlobalVariables.getMessageMap()
          .putError(
              Constants.PROPOSAL_EDITABLECOLUMN_LOOKUPRETURN,
              RiceKeyConstants.ERROR_REQUIRED,
              new String[] {"Lookup Return"});
      return false;
    }

    return true;
  }
  /**
   * @see
   *     org.kuali.rice.krad.service.DocumentService#disapproveDocument(org.kuali.rice.krad.document.Document,
   *     java.lang.String)
   */
  @Override
  public Document disapproveDocument(Document document, String annotation) throws Exception {
    checkForNulls(document);

    Note note = createNoteFromDocument(document, annotation);
    // if note type is BO, override and link disapprove notes to Doc Header
    if (document.getNoteType().equals(NoteType.BUSINESS_OBJECT)) {
      note.setNoteTypeCode(NoteType.DOCUMENT_HEADER.getCode());
      note.setRemoteObjectIdentifier(document.getDocumentHeader().getObjectId());
    }
    document.addNote(note);

    // SAVE THE NOTE
    // Note: This save logic is replicated here and in KualiDocumentAction, when to save (based on
    // doc state) should be moved
    //      into a doc service method
    getNoteService().save(note);

    prepareWorkflowDocument(document);
    getWorkflowDocumentService()
        .disapprove(document.getDocumentHeader().getWorkflowDocument(), annotation);
    UserSessionUtils.addWorkflowDocument(
        GlobalVariables.getUserSession(), document.getDocumentHeader().getWorkflowDocument());
    removeAdHocPersonsAndWorkgroups(document);
    return document;
  }
  /** This method test a few specila inquirey fields are set up properly. */
  @Test
  public void testGetInquiryUrl() {
    Protocol protocol = initProtocol();

    final KcPersonService kcPersonService = context.mock(KcPersonService.class);
    final String principalId = GlobalVariables.getUserSession().getPrincipalId();
    context.checking(
        new Expectations() {
          {
            one(kcPersonService).getKcPersonByPersonId(principalId);
            will(returnValue(KcPerson.fromPersonId(principalId)));
          }
        });
    protocolLookupableHelperServiceImpl.setKcPersonService(kcPersonService);

    HtmlData inquiryUrl =
        protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "leadUnitNumber");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), UNIT_INQ_URL);
    inquiryUrl = protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "investigator");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), PERSON_INQ_URL);
    ProtocolPerson protocolPerson = (ProtocolPerson) protocol.getProtocolPersons().get(0);
    protocolPerson.setPersonId("");
    protocolPerson.setRolodexId(new Integer(1727));
    protocol.getProtocolPersons().clear();
    protocol.getProtocolPersons().add(protocolPerson);
    inquiryUrl = protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "investigator");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), ROLODEX_INQ_URL);
  }
 protected boolean validAssignGroup(IdentityManagementGroupDocument document) {
   boolean rulePassed = true;
   Map<String, String> additionalPermissionDetails = new HashMap<String, String>();
   additionalPermissionDetails.put(
       KimConstants.AttributeConstants.NAMESPACE_CODE, document.getGroupNamespace());
   additionalPermissionDetails.put(
       KimConstants.AttributeConstants.GROUP_NAME, document.getGroupName());
   if (document.getMembers() != null && document.getMembers().size() > 0) {
     if (!getDocumentDictionaryService()
         .getDocumentAuthorizer(document)
         .isAuthorizedByTemplate(
             document,
             KimConstants.NAMESPACE_CODE,
             KimConstants.PermissionTemplateNames.POPULATE_GROUP,
             GlobalVariables.getUserSession().getPrincipalId(),
             additionalPermissionDetails,
             null)) {
       GlobalVariables.getMessageMap()
           .putError(
               "document.groupName",
               RiceKeyConstants.ERROR_ASSIGN_GROUP,
               new String[] {document.getGroupNamespace(), document.getGroupName()});
       rulePassed = false;
     }
   }
   return rulePassed;
 }
  public ActionForward regenerateCorrespondence(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    MeetingHelperBase meetingHelper = ((MeetingFormBase) form).getMeetingHelper();
    meetingHelper.setRegeneratedCorrespondences(new ArrayList<ProtocolCorrespondence>());
    for (ProtocolCorrespondence protocolCorrespondence : meetingHelper.getCorrespondences()) {
      if (protocolCorrespondence.isRegenerateFlag()) {
        ProtocolBase protocol = protocolCorrespondence.getProtocol();
        AttachmentDataSource dataSource =
            generateCorrespondenceDocumentAndAttach(protocol, protocolCorrespondence);
        PrintableAttachment source = new PrintableAttachment();
        if (dataSource != null) {
          protocolCorrespondence.setCorrespondence(dataSource.getData());
          protocolCorrespondence.setFinalFlag(false);
          protocolCorrespondence.setCreateUser(GlobalVariables.getUserSession().getPrincipalName());
          protocolCorrespondence.setCreateTimestamp(
              KcServiceLocator.getService(DateTimeService.class).getCurrentTimestamp());
        }
        meetingHelper.getRegeneratedCorrespondences().add(protocolCorrespondence);
      }
    }
    getBusinessObjectService().save(meetingHelper.getRegeneratedCorrespondences());
    return mapping.findForward("correspondence");
  }
  /**
   * Overridden to guarantee that form of copied document is set to whatever the entry mode of the
   * document is
   *
   * @see org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase#copy
   *     (org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
   *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  @Override
  public ActionForward copy(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ActionForward forward = null;
    String docID = "docId";
    if (request.getParameter(docID) == null) {
      forward = super.copy(mapping, form, request, response);
    } else {
      // this is copy document from Procurement Gateway:
      // use this url to call:
      // http://localhost:8080/kfs-dev/purapRequisition.do?methodToCall=copy&docId=xxxx
      String docId = request.getParameter(docID);
      KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;

      CuRequisitionDocument document = null;
      document = (CuRequisitionDocument) getDocumentService().getByDocumentHeaderId(docId);
      document.toCopyFromGateway();

      kualiDocumentFormBase.setDocument(document);
      WorkflowDocument workflowDocument = document.getDocumentHeader().getWorkflowDocument();
      kualiDocumentFormBase.setDocTypeName(workflowDocument.getDocumentTypeName());
      SpringContext.getBean(SessionDocumentService.class)
          .addDocumentToUserSession(GlobalVariables.getUserSession(), workflowDocument);

      forward = mapping.findForward(RiceConstants.MAPPING_BASIC);
    }
    return forward;
  }
 public void testGenerateSummaryWithNoZeroTotalsUsingAlternateAmount_TwoItems_OneAccount() {
   PurapAccountingServiceFixture fixture =
       PurapAccountingServiceFixture.REQ_SUMMARY_TWO_ITEMS_ONE_ACCOUNT;
   List<SourceAccountingLine> originalSourceAccounts = fixture.getSourceAccountingLineList();
   List<PurApItem> items = fixture.getItems();
   GlobalVariables.getUserSession().setBackdoorUser("parke");
   RequisitionDocumentFixture reqFixture = RequisitionDocumentFixture.REQ_ONLY_REQUIRED_FIELDS;
   RequisitionDocument req = reqFixture.createRequisitionDocument();
   GlobalVariables.getUserSession().setBackdoorUser("kfs");
   for (PurApItem item : items) {
     item.setPurapDocument(req);
   }
   List<SourceAccountingLine> sourceLines =
       purapAccountingService.generateSummaryWithNoZeroTotalsUsingAlternateAmount(items);
   assertEquals(sourceLines.size(), originalSourceAccounts.size());
   checkAccountConsolidation(sourceLines, originalSourceAccounts);
 }
 protected void checkPermissions(DocumentConfigurationViewForm form) {
   String docTypeDocumentType =
       getMaintenanceDocumentDictionaryService().getDocumentTypeName(DocumentType.class);
   try {
     if ((docTypeDocumentType != null)
         && getDocumentHelperService()
             .getDocumentAuthorizer(docTypeDocumentType)
             .canInitiate(docTypeDocumentType, GlobalVariables.getUserSession().getPerson())) {
       form.setCanInitiateDocumentTypeDocument(true);
     }
   } catch (Exception ex) {
     // just skip - and don't display links
     LOG.error(
         "Unable to check DocumentType initiation permission for " + docTypeDocumentType, ex);
   }
   String permissionDocumentType =
       getMaintenanceDocumentDictionaryService().getDocumentTypeName(PermissionBo.class);
   try {
     if ((permissionDocumentType != null)
         && getDocumentHelperService()
             .getDocumentAuthorizer(permissionDocumentType)
             .canInitiate(permissionDocumentType, GlobalVariables.getUserSession().getPerson())) {
       form.setCanInitiatePermissionDocument(true);
     }
   } catch (Exception ex) {
     // just skip - and don't display links
     LOG.error(
         "Unable to check Permission initiation permission for " + permissionDocumentType, ex);
   }
   String responsibilityDocumentType =
       getMaintenanceDocumentDictionaryService().getDocumentTypeName(ResponsibilityBo.class);
   try {
     if ((responsibilityDocumentType != null)
         && getDocumentHelperService()
             .getDocumentAuthorizer(responsibilityDocumentType)
             .canInitiate(
                 responsibilityDocumentType, GlobalVariables.getUserSession().getPerson())) {
       form.setCanInitiateResponsibilityDocument(true);
     }
   } catch (Exception ex) {
     // just skip - and don't display links
     LOG.error(
         "Unable to check Responsibility initiation permission for " + responsibilityDocumentType,
         ex);
   }
 }