public boolean isAuthorizedToDeleteNarrative(Narrative narrative, Person user) {
    final ProposalDevelopmentDocument pdDocument =
        (ProposalDevelopmentDocument) narrative.getDevelopmentProposal().getDocument();

    // First, the user must have the MODIFY_NARRATIVE permission.  This is really
    // a sanity check.  If they have the MODIFY_NARRATIVE_RIGHT, then they are
    // required to have the MODIFY_NARRATIVE permission.

    KcDocumentRejectionService documentRejectionService = getKcDocumentRejectionService();
    boolean rejectedDocument =
        documentRejectionService.isDocumentOnInitialNode(
            pdDocument.getDocumentHeader().getWorkflowDocument());
    boolean hasPermission = false;

    boolean inWorkflow = getKcWorkflowService().isInWorkflow(pdDocument);

    if ((!inWorkflow || rejectedDocument) && !pdDocument.getDevelopmentProposal().getSubmitFlag()) {
      if (getModifyNarrativePermission(pdDocument, user)) {
        hasPermission =
            hasNarrativeRight(
                user.getPrincipalId(), narrative, NarrativeRight.MODIFY_NARRATIVE_RIGHT);
      }
    }
    return hasPermission;
  }
  protected boolean hasModifyS2sEnroutePermission(Document document, Person user) {
    DocumentRequestAuthorizationCache documentRequestAuthorizationCache =
        getDocumentRequestAuthorizationCache(document);
    final String cacheKey =
        buildPermissionCacheKey(document, user, PermissionConstants.MODIFY_S2S_ENROUTE);
    Boolean cachedResult = getCachedPermissionResult(document, cacheKey);
    boolean hasS2sPermission;

    if (cachedResult != null) {
      hasS2sPermission = cachedResult;
    } else {
      ProposalDevelopmentDocument pdDocument = (ProposalDevelopmentDocument) document;
      hasS2sPermission =
          getKcAuthorizationService()
              .hasPermission(
                  user.getPrincipalId(), pdDocument, PermissionConstants.MODIFY_S2S_ENROUTE);
    }

    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
    final DevelopmentProposal proposal = pdDocument.getDevelopmentProposal();

    if (proposal.isChild() && hasS2sPermission) {
      final Document parent = proposal.getParent().getDocument();
      final String parentResultCacheKey =
          buildPermissionCacheKey(parent, user, PermissionConstants.MODIFY_S2S_ENROUTE);
      documentRequestAuthorizationCache.getPermissionResultCache().remove(parentResultCacheKey);
      hasS2sPermission = isAuthorizedToModifyBudget(parent, user);
    }

    addCachedPermissionResult(document, cacheKey, hasS2sPermission);

    return hasS2sPermission;
  }
 protected boolean isAuthorizedToSubmitToWorkflow(Document document, Person user) {
   final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
   return !getKcWorkflowService().isInWorkflow(pdDocument)
       && getKcAuthorizationService()
           .hasPermission(user.getPrincipalId(), pdDocument, PermissionConstants.SUBMIT_PROPOSAL)
       && !pdDocument.getDevelopmentProposal().isChild();
 }
  protected boolean isAuthorizedToViewNarrative(Narrative narrative, Person user) {
    final ProposalDevelopmentDocument pdDocument =
        (ProposalDevelopmentDocument) narrative.getDevelopmentProposal().getDocument();

    // First, the user must have the VIEW_NARRATIVE permission.  This is really
    // a sanity check.  If they have the VIEW or MODIFY_NARRATIVE_RIGHT, then they are
    // required to have the VIEW_NARRATIVE permission.

    boolean hasPermission = false;
    if (getKcAuthorizationService()
        .hasPermission(user.getPrincipalId(), pdDocument, PermissionConstants.VIEW_NARRATIVE)) {
      hasPermission =
          hasNarrativeRight(user.getPrincipalId(), narrative, NarrativeRight.VIEW_NARRATIVE_RIGHT)
              || hasNarrativeRight(
                  user.getPrincipalId(), narrative, NarrativeRight.MODIFY_NARRATIVE_RIGHT);
    }

    if (!hasPermission) {
      hasPermission =
          getUnitAuthorizationService()
                  .hasPermission(
                      user.getPrincipalId(),
                      pdDocument.getDevelopmentProposal().getOwnedByUnitNumber(),
                      Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                      PermissionConstants.VIEW_NARRATIVE)
              || getKcWorkflowService().hasWorkflowPermission(user.getPrincipalId(), pdDocument);
    }

    return hasPermission;
  }
 public boolean canOpen(Document document, Person user) {
   ProposalDevelopmentDocument proposalDocument = (ProposalDevelopmentDocument) document;
   if (proposalDocument.getDevelopmentProposal().getProposalNumber() == null) {
     return isAuthorizedToCreate(document, user);
   }
   return isAuthorizedToView(document, user);
 }
  @Override
  public Set<String> getEditModes(Document document, Person user, Set<String> currentEditModes) {
    Set<String> editModes = new HashSet<>();

    ProposalDevelopmentDocument proposalDoc = (ProposalDevelopmentDocument) document;
    DevelopmentProposal developmentProposal = proposalDoc.getDevelopmentProposal();
    String proposalNbr = developmentProposal.getProposalNumber();

    // The getEditMode() method is invoked when a proposal is accessed for creation and when it
    // is accessed for modification.  New proposals under creation don't have a proposal number.
    // For a new proposal, we have to know if the user has the permission to create a proposal.
    // For a current proposal, we have to know if the user the permission to modify or view the
    // proposal.

    if (proposalNbr == null) {
      if (isAuthorizedToCreate(document, user)) {
        editModes.add(AuthorizationConstants.EditMode.FULL_ENTRY);
        setPermissions(user, proposalDoc, editModes);
      } else {
        editModes.add(AuthorizationConstants.EditMode.UNVIEWABLE);
      }
    } else {
      if (canEdit(document, user)) {
        editModes.add(AuthorizationConstants.EditMode.FULL_ENTRY);
        setPermissions(user, proposalDoc, editModes);
      } else if (isAuthorizedToView(document, user)) {
        editModes.add(AuthorizationConstants.EditMode.VIEW_ONLY);
        setPermissions(user, proposalDoc, editModes);
      } else {
        editModes.add(AuthorizationConstants.EditMode.UNVIEWABLE);
      }
    }

    return editModes;
  }
  protected boolean isAuthorizedToAlterProposalData(Document document, Person user) {
    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
    // standard is authorized calculation without taking child status into account.
    boolean ret =
        getKcWorkflowService().isEnRoute(pdDocument)
            && !pdDocument.getDevelopmentProposal().getSubmitFlag()
            && getKcAuthorizationService()
                .hasPermission(
                    user.getPrincipalId(), pdDocument, PermissionConstants.ALTER_PROPOSAL_DATA);

    // check to see if the parent is enroute, if so deny the edit attempt.
    if (pdDocument.getDevelopmentProposal().isChild()) {
      try {
        if (getProposalHierarchyService().getParentWorkflowDocument(pdDocument).isEnroute()) {
          ret = false;
        }
      } catch (ProposalHierarchyException e) {
        LOG.error(
            String.format(
                "Exception looking up parent of DevelopmentProposal %s, authorizer is going to deny edit access to this child.",
                pdDocument.getDevelopmentProposal().getProposalNumber()),
            e);
        ret = false;
      }
    }
    return ret;
  }
  @Override
  protected void prepareData(ProposalDevelopmentDocument document) throws Exception {

    ProposalDevelopmentBudgetExt budget = new ProposalDevelopmentBudgetExt();
    budget.setBudgetId(new Long("000001"));
    budget.setBudgetStatus("1");
    budget.setStartDate(new Date(new Long("1183316613046")));
    budget.setEndDate(new Date(new Long("1214852613046")));
    budget.setOnOffCampusFlag("Y");
    budget.setOhRateClassCode("1");
    budget.setUrRateClassCode("1");
    budget.setModularBudgetFlag(false);
    budget.setParentDocumentTypeCode("PRDV");
    budget.setDevelopmentProposal(document.getDevelopmentProposal());
    budget.setName("test document description");

    List<BudgetPeriod> budgetPeriods = new ArrayList<BudgetPeriod>();
    BudgetPeriod budgetPeriod = new BudgetPeriod();
    budgetPeriod.setBudgetPeriod(1);
    budgetPeriod.setStartDate(new Date(new Long("1183316613046")));
    budgetPeriod.setEndDate(new Date(new Long("1214852613046")));
    budgetPeriods.add(budgetPeriod);
    budget.setBudgetPeriods(budgetPeriods);

    budget = getService(DataObjectService.class).save(budget);
    List<ProposalDevelopmentBudgetExt> budgets = new ArrayList<>();
    budgets.add(budget);
    document.getDevelopmentProposal().setBudgets(budgets);
    document.getDevelopmentProposal().setFinalBudget(budget);
  }
  protected boolean getModifyNarrativePermission(
      ProposalDevelopmentDocument document, Person user) {
    DocumentRequestAuthorizationCache documentRequestAuthorizationCache =
        getDocumentRequestAuthorizationCache(document);

    boolean hasModifyNarrativePermission;

    String modifyNarrativeCacheKey =
        "ModifyNarrative|" + document.getDocumentNumber() + "|" + user.getPrincipalId();
    if (documentRequestAuthorizationCache.hasPermissionResult(modifyNarrativeCacheKey)) {
      hasModifyNarrativePermission =
          documentRequestAuthorizationCache.getPermissionResult(modifyNarrativeCacheKey);
    } else {
      hasModifyNarrativePermission =
          getKcAuthorizationService()
              .hasPermission(user.getPrincipalId(), document, PermissionConstants.MODIFY_NARRATIVE);
      documentRequestAuthorizationCache.addPermissionResult(
          modifyNarrativeCacheKey, hasModifyNarrativePermission);
    }
    if (!hasModifyNarrativePermission) {
      hasModifyNarrativePermission =
          !document.getDevelopmentProposal().getSubmitFlag()
              && document.getDocumentHeader().getWorkflowDocument().isEnroute()
              && getKcAuthorizationService()
                  .hasPermission(
                      user.getPrincipalId(), document, PermissionConstants.ALTER_PROPOSAL_DATA);
      documentRequestAuthorizationCache.addPermissionResult(
          modifyNarrativeCacheKey, hasModifyNarrativePermission);
    }

    return hasModifyNarrativePermission;
  }
  @Override
  protected void prepareData(ProposalDevelopmentDocument document) throws Exception {
    ProposalType type = new ProposalType();
    type.setCode("2");
    document.getDevelopmentProposal().setProposalType(type);
    ProposalYnq proposalYnq = new ProposalYnq();
    proposalYnq.setAnswer("Y");
    proposalYnq.setQuestionId("22");
    proposalYnq.setExplanation("David,Blain");

    Ynq ynq = new Ynq();
    ynq.setQuestionId("22");
    ynq.setGroupName("groupName");
    ynq.setDescription("description");
    ynq.setEffectiveDate(new Date(1));
    ynq.setNoOfAnswers(1);
    ynq.setQuestionType("A");
    ynq.setStatus("A");
    proposalYnq.setYnq(ynq);
    proposalYnq.setProposalNumber(document.getDevelopmentProposal().getProposalNumber());
    saveBO(ynq);

    List<ProposalYnq> ynqList = new ArrayList<ProposalYnq>();
    ynqList.add(proposalYnq);
    document.getDevelopmentProposal().setProposalYnqs(ynqList);
  }
 protected boolean isAuthorizedToRecallProposal(Document document, Person user) {
   final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
   return pdDocument.getDocumentHeader().hasWorkflowDocument()
       && pdDocument.getDocumentHeader().getWorkflowDocument().isEnroute()
       && getKcAuthorizationService()
           .hasPermission(user.getPrincipalId(), pdDocument, PermissionConstants.RECALL_DOCUMENT)
       && !isRevisionRequested(pdDocument.getDevelopmentProposal().getProposalStateTypeCode());
 }
  public boolean isAuthorized(String userId, BudgetTask task) {
    BudgetDocument budgetDocument = task.getBudgetDocument();
    ProposalDevelopmentDocument doc =
        (ProposalDevelopmentDocument) budgetDocument.getParentDocument();

    return !doc.isViewOnly()
        && hasParentPermission(userId, doc, PermissionConstants.MAINTAIN_PROPOSAL_HIERARCHY);
  }
  @Override
  public void populateProposalPerson(ProposalPerson person, ProposalDevelopmentDocument document) {
    /* populate certification questions for new person */
    person = getYnqService().getPersonYNQ(person, document);

    if (person.isInvestigator()) {
      if (!document.getDevelopmentProposal().getInvestigators().contains(person)) {
        document.getDevelopmentProposal().getInvestigators().add(person);
      }
      populateCreditTypes(person);
    }

    person.setRoleChanged(false);

    try {
      if (person.getPersonId() != null && person.getPerson().getExtendedAttributes() != null) {
        KcPerson origPerson = person.getPerson();
        for (PersonDegree degree : origPerson.getExtendedAttributes().getPersonDegrees()) {
          ProposalPersonDegree newDegree = new ProposalPersonDegree();
          newDegree.setDegree(degree.getDegree());
          newDegree.setDegreeCode(degree.getDegreeCode());
          newDegree.setFieldOfStudy(degree.getFieldOfStudy());
          newDegree.setGraduationYear(degree.getGraduationYear());
          newDegree.setSchool(degree.getSchool());
          newDegree.setSchoolId(degree.getSchoolId());
          newDegree.setSchoolIdCode(degree.getSchoolIdCode());
          newDegree.setDegreeSequenceNumber(
              document.getDocumentNextValue(Constants.PROPOSAL_PERSON_DEGREE_SEQUENCE_NUMBER));
          person.addDegree(newDegree);
        }
        if (origPerson.getExtendedAttributes().getAttachments() != null) {
          for (PersonBiosketch attachment : origPerson.getExtendedAttributes().getAttachments()) {
            ProposalPersonBiography bio = new ProposalPersonBiography();
            bio.setProposalPersonNumber(person.getProposalPersonNumber());
            bio.setDocumentTypeCode(getDefaultPersonAttachmentDocType());
            bio.setDescription(attachment.getDescription());
            bio.setName(attachment.getFileName());
            bio.setType(attachment.getContentType());

            ProposalPersonBiographyAttachment personnelAttachment =
                new ProposalPersonBiographyAttachment();
            personnelAttachment.setName(attachment.getFileName());
            personnelAttachment.setProposalNumber(
                document.getDevelopmentProposal().getProposalNumber());
            personnelAttachment.setProposalPersonNumber(person.getProposalPersonNumber());
            personnelAttachment.setData(attachment.getAttachmentContent());
            personnelAttachment.setType(attachment.getContentType());
            bio.setPersonnelAttachment(personnelAttachment);

            document.getDevelopmentProposal().addProposalPersonBiography(bio);
          }
        }
      }
    } catch (IllegalArgumentException e) {
      // catching the possibility that person.getPerson can not
      // find a EntityContract for this person id.
    }
  }
 /**
  * This method checks if the user has full (pre-workflow/pre-submission) proposal access
  * maintenance rights
  *
  * @param user the user requesting access
  * @param document the document object
  * @return true if the user has full (pre-workflow/pre-submission) proposal access maintenance
  *     rights
  */
 protected boolean hasFullAuthorization(Document document, Person user) {
   final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
   return !pdDocument.isViewOnly()
       && getKcAuthorizationService()
           .hasPermission(
               user.getPrincipalId(), pdDocument, PermissionConstants.MAINTAIN_PROPOSAL_ACCESS)
       && !getKcWorkflowService().isInWorkflow(pdDocument)
       && !pdDocument.getDevelopmentProposal().getSubmitFlag();
 }
  private void setNarrativePermissions(
      Person user, ProposalDevelopmentDocument doc, Set<String> editModes) {

    List<Narrative> narratives = doc.getDevelopmentProposal().getNarratives();
    synchronized (narratives) {
      for (Narrative narrative : narratives) {
        String prefix = "proposalAttachment." + narrative.getModuleNumber() + ".";
        if (isAuthorizedToViewNarrative(narrative, user)) {
          editModes.add(prefix + "download");
        }
        if (isAuthorizedToReplaceNarrative(narrative, user)) {
          editModes.add(prefix + "replace");
        }
        if (isAuthorizedToDeleteNarrative(narrative, user)) {
          editModes.add(prefix + "delete");
        }
        if (isAuthorizedToModifyNarrative(narrative, user)) {
          editModes.add(prefix + "modifyStatus");
        }
        if (isAuthorizedToModifyNarrative(narrative, user)) {
          editModes.add(prefix + "modifyRights");
        }
      }

      narratives = doc.getDevelopmentProposal().getInstituteAttachments();
      for (Narrative narrative : narratives) {
        String prefix = "instituteAttachment." + narrative.getModuleNumber() + ".";
        if (isAuthorizedToViewNarrative(narrative, user)) {
          editModes.add(prefix + "download");
        }
        if (isAuthorizedToReplaceNarrative(narrative, user)) {
          editModes.add(prefix + "replace");
        }
        if (isAuthorizedToDeleteNarrative(narrative, user)) {
          editModes.add(prefix + "delete");
        }
        if (isAuthorizedToModifyNarrative(narrative, user)) {
          editModes.add(prefix + "modifyRights");
        }
      }

      int i = 0;
      boolean canReplace = isAuthorizedToReplacePersonnelAttachement(doc, user);
      for (ProposalPersonBiography ppb : doc.getDevelopmentProposal().getPropPersonBios()) {
        ppb.setPositionNumber(i);
        String prefix = "biographyAttachments." + ppb.getPositionNumber() + ".";
        if (canReplace) {
          editModes.add(prefix + "replace");
        }

        i++;
      }
    }
  }
 protected boolean isAuthorizedToReplaceNarrative(Document document, Person user) {
   final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
   boolean hasPermission = false;
   if (!pdDocument.getDevelopmentProposal().getSubmitFlag()
       && pdDocument.getDocumentHeader().getWorkflowDocument().isEnroute()) {
     hasPermission =
         getModifyNarrativePermission(pdDocument, user)
             || isAuthorizedToAlterProposalData(document, user);
   }
   return hasPermission;
 }
  protected boolean isAuthorizedToAddBudget(Document document, Person user) {
    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);

    boolean rejectedDocument =
        getKcDocumentRejectionService()
            .isDocumentOnInitialNode(pdDocument.getDocumentHeader().getWorkflowDocument());

    return (!getKcWorkflowService().isInWorkflow(pdDocument) || rejectedDocument)
        && !pdDocument.isViewOnly()
        && !pdDocument.getDevelopmentProposal().getSubmitFlag()
        && !pdDocument.getDevelopmentProposal().isParent();
  }
  protected boolean isAuthorizedToRejectProposal(Document document, Person user) {
    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
    DocumentRequestAuthorizationCache.WorkflowDocumentInfo workflowDocumentInfo =
        getDocumentRequestAuthorizationCache(document).getWorkflowDocumentInfo();

    return ((!workflowDocumentInfo.isCompletionRequested()
                && workflowDocumentInfo.isApprovalRequested())
            || canReject(user))
        && !getKcDocumentRejectionService()
            .isDocumentOnInitialNode(pdDocument.getDocumentHeader().getWorkflowDocument())
        && workflowDocumentInfo.isEnroute();
  }
  protected boolean isAuthorizedToModify(Document document, Person user) {
    DocumentRequestAuthorizationCache documentRequestAuthorizationCache =
        getDocumentRequestAuthorizationCache(document);

    final String resultCacheKey = buildPermissionCacheKey(document, user, IS_AUTHORIZED_TO_MODIFY);
    if (documentRequestAuthorizationCache.hasPermissionResult(resultCacheKey)) {
      return documentRequestAuthorizationCache.getPermissionResult(resultCacheKey);
    }

    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
    final DevelopmentProposal proposal = pdDocument.getDevelopmentProposal();

    if (!isEditableState(proposal.getProposalStateTypeCode())) {
      return false;
    }

    final String proposalNbr = proposal.getProposalNumber();

    boolean hasPermission;
    if (proposalNbr == null) {
      hasPermission = hasPermissionByOwnedByUnit(document, user);
    } else {
      /*
       * After the initial save, the proposal can only be modified if it is not in workflow
       * and the user has the require permission.
       */

      final boolean hasBeenRejected =
          ProposalState.REVISIONS_REQUESTED.equals(proposal.getProposalStateTypeCode());

      hasPermission =
          !pdDocument.isViewOnly()
              && getKcAuthorizationService()
                  .hasPermission(
                      user.getPrincipalId(), pdDocument, PermissionConstants.MODIFY_PROPOSAL)
              && (!getKcWorkflowService().isInWorkflow(document) || hasBeenRejected)
              && !proposal.getSubmitFlag();
    }

    if (proposal.isChild() && hasPermission) {
      final Document parent = proposal.getParent().getDocument();
      final String parentResultCacheKey =
          buildPermissionCacheKey(parent, user, IS_AUTHORIZED_TO_MODIFY);
      documentRequestAuthorizationCache.getPermissionResultCache().remove(parentResultCacheKey);
      hasPermission = isAuthorizedToModify(parent, user);
    }

    documentRequestAuthorizationCache.addPermissionResult(resultCacheKey, hasPermission);

    return hasPermission;
  }
  protected boolean isAuthorizedToReplaceNarrative(Narrative narrative, Person user) {
    final ProposalDevelopmentDocument pdDocument =
        (ProposalDevelopmentDocument) narrative.getDevelopmentProposal().getDocument();

    boolean hasPermission = false;
    if (!pdDocument.getDevelopmentProposal().getSubmitFlag()
        && getModifyNarrativePermission(pdDocument, user)) {
      hasPermission =
          hasNarrativeRight(user.getPrincipalId(), narrative, NarrativeRight.MODIFY_NARRATIVE_RIGHT)
              || isAuthorizedToAlterProposalData(pdDocument, user);
    }

    return hasPermission;
  }
  protected boolean isAuthorizedToAddNarrative(Document document, Person user) {
    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);

    boolean rejectedDocument =
        getKcDocumentRejectionService()
            .isDocumentOnInitialNode(pdDocument.getDocumentHeader().getWorkflowDocument());
    boolean hasPermission = false;
    if ((!getKcWorkflowService().isInWorkflow(pdDocument) || rejectedDocument)
        && !pdDocument.isViewOnly()
        && !pdDocument.getDevelopmentProposal().getSubmitFlag()) {
      hasPermission = getModifyNarrativePermission(pdDocument, user);
    }
    return hasPermission;
  }
  /**
   * Populate investigators
   *
   * @param document The <code>{@link ProposalDevelopmentDocument}</code> to populate investigators
   *     on
   */
  public void populateInvestigators(ProposalDevelopmentDocument document) {
    // Populate Investigators from a proposal document's persons
    LOG.debug("Populating Investigators");
    LOG.debug("Clearing investigator list");
    document.getDevelopmentProposal().getInvestigators().clear();

    for (ProposalPerson person : document.getDevelopmentProposal().getProposalPersons()) {
      LOG.debug(person.getFullName() + " is " + person.isInvestigator());

      if (person.isInvestigator()) {
        LOG.info("Adding investigator " + person.getFullName());
        document.getDevelopmentProposal().getInvestigators().add(person);
      }
    }
  }
 /**
  * Part of a complete breakfast, it has everything you need to populate Key Personnel into a
  * <code>{@link ProposalDevelopmentDocument}</code>
  *
  * @param document
  */
 public void populateDocument(ProposalDevelopmentDocument document) {
   if (hasBeenRoutedOrCanceled(document)) {
     Collection<InvestigatorCreditType> availableCreditTypes = getAllInvestigatorCreditTypes();
     Set<InvestigatorCreditType> usedCreditTypes = new HashSet<InvestigatorCreditType>();
     for (ProposalPerson person : document.getDevelopmentProposal().getInvestigators()) {
       for (ProposalPersonCreditSplit creditSplit : person.getCreditSplits()) {
         for (InvestigatorCreditType currentCreditType : availableCreditTypes) {
           if (currentCreditType.getCode().equals(creditSplit.getInvCreditTypeCode())) {
             usedCreditTypes.add(currentCreditType);
           }
         }
       }
     }
     document.getDevelopmentProposal().setInvestigatorCreditTypes(usedCreditTypes);
   } else {
     document.getDevelopmentProposal().setInvestigatorCreditTypes(getInvestigatorCreditTypes());
   }
   if (document.getDevelopmentProposal().getInvestigators().isEmpty()
       && !document.getDevelopmentProposal().getProposalPersons().isEmpty()) {
     LOG.info("Need to repopulate investigator list");
     populateInvestigators(document);
     if (!(document.getDocumentHeader().getWorkflowDocument().getStatus().getCode().equals("R"))) {
       populateActiveCredittypesPerson(document);
     }
   }
   /* check for new certification questions */
   for (ProposalPerson person : document.getDevelopmentProposal().getProposalPersons()) {
     getYnqService().getPersonYNQ(person, document);
   }
 }
  protected void populateProposalSpecialReview(
      Protocol protocol, ProposalDevelopmentDocument proposalDocument) {
    if (protocol != null) {
      Integer specialReviewNumber =
          proposalDocument.getDocumentNextValue(Constants.SPECIAL_REVIEW_NUMBER);

      ProposalSpecialReview specialReview = new ProposalSpecialReview();
      specialReview.setSpecialReviewNumber(specialReviewNumber);
      specialReview.setSpecialReviewTypeCode(SpecialReviewType.HUMAN_SUBJECTS);
      specialReview.setApprovalTypeCode(SpecialReviewApprovalType.PENDING);
      specialReview.setProtocolNumber(protocol.getProtocolNumber());
      specialReview.setDevelopmentProposal(proposalDocument.getDevelopmentProposal());

      specialReview.setProtocolStatus(protocol.getProtocolStatus().getDescription());
      specialReview.setComments(ComplianceConstants.NEW_SPECIAL_REVIEW_COMMENT);
      proposalDocument.getDevelopmentProposal().getPropSpecialReviews().add(specialReview);
    }
  }
  protected boolean hasPermissionByOwnedByUnit(Document document, Person user) {
    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);
    final DevelopmentProposal proposal = pdDocument.getDevelopmentProposal();

    String unitNumber = proposal.getOwnedByUnitNumber();

    // If the unit number is not specified, we will let the save operation continue because it
    // will fail with an error.  But if the user tries to save a proposal for a wrong unit, then
    // we will indicate that the user does not have permission to do that.
    return (unitNumber != null
            && getUnitAuthorizationService()
                .hasPermission(
                    user.getPrincipalId(),
                    unitNumber,
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    PermissionConstants.CREATE_PROPOSAL)
        || unitNumber == null);
  }
  @Override
  protected void prepareData(ProposalDevelopmentDocument document) throws Exception {

    ProposalAbstract propsAbstract = new ProposalAbstract();
    propsAbstract.setAbstractTypeCode("14");
    propsAbstract.setAbstractDetails("NSFSuggestedReviewers AbstractDetails");
    ProposalAbstract propsAbstract1 = new ProposalAbstract();
    propsAbstract1.setAbstractTypeCode("12");
    propsAbstract1.setAbstractDetails("AbstractDetails");
    List<ProposalAbstract> proList = new ArrayList<ProposalAbstract>();
    proList.add(propsAbstract);
    proList.add(propsAbstract1);

    propsAbstract.setProposalNumber(document.getDevelopmentProposal().getProposalNumber());
    propsAbstract1.setProposalNumber(document.getDevelopmentProposal().getProposalNumber());

    document.getDevelopmentProposal().setProposalAbstracts(proList);
  }
  @Transactional
  @RequestMapping(
      value = "/proposalDevelopment",
      params = {"methodToCall=addUserAttachedForm"})
  public ModelAndView addUserAttachedForm(
      @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception {
    S2sUserAttachedForm s2sUserAttachedForm = form.getS2sUserAttachedForm();
    ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument();

    MultipartFile userAttachedFormFile = s2sUserAttachedForm.getNewFormFile();

    s2sUserAttachedForm.setNewFormFileBytes(userAttachedFormFile.getBytes());
    s2sUserAttachedForm.setFormFileName(userAttachedFormFile.getOriginalFilename());
    s2sUserAttachedForm.setProposalNumber(
        proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber());
    try {
      List<S2sUserAttachedForm> userAttachedForms =
          getS2sUserAttachedFormService()
              .extractNSaveUserAttachedForms(proposalDevelopmentDocument, s2sUserAttachedForm);
      proposalDevelopmentDocument
          .getDevelopmentProposal()
          .getS2sUserAttachedForms()
          .addAll(userAttachedForms);
      form.setS2sUserAttachedForm(new S2sUserAttachedForm());
    } catch (S2SException ex) {
      LOG.error(ex.getMessage(), ex);
      if (ex.getTabErrorKey() != null) {
        if (getGlobalVariableService()
                .getMessageMap()
                .getErrorMessagesForProperty(ex.getTabErrorKey())
            == null) {
          getGlobalVariableService()
              .getMessageMap()
              .putError(ex.getTabErrorKey(), ex.getErrorKey(), ex.getParams());
        }
      } else {
        getGlobalVariableService()
            .getMessageMap()
            .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams());
      }
    }

    return super.save(form);
  }
 /**
  * If the sponsor has changed, default the key personnel role codes to COI if the role can't be
  * found
  */
 public void handleSponsorChange(ProposalDevelopmentDocument proposalDevelopmentDocument) {
   for (int i = 0;
       i < proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().size();
       i++) {
     ProposalPerson person =
         proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().get(i);
     if (person.getRole() == null) {
       person.setProposalPersonRoleId(PropAwardPersonRole.CO_INVESTIGATOR);
       String propertyName = ProposalDevelopmentConstants.PropertyConstants.PROPOSAL_PERSONS;
       getGlobalVariableService()
           .getMessageMap()
           .putInfo(
               propertyName + "[" + i + "].proposalPersonRoleId",
               KeyConstants.INFO_PERSONNEL_INVALID_ROLE,
               person.getDevelopmentProposal().getSponsorCode(),
               person.getFullName());
     }
   }
 }
  protected boolean isAuthorizedToAddNote(Document document, Person user) {

    final ProposalDevelopmentDocument pdDocument = ((ProposalDevelopmentDocument) document);

    String proposalNbr = pdDocument.getDevelopmentProposal().getProposalNumber();

    final boolean hasPermission;
    if (proposalNbr == null) {
      hasPermission = hasPermissionByOwnedByUnit(document, user);
    } else {

      hasPermission =
          getKcAuthorizationService()
                  .hasPermission(
                      user.getPrincipalId(), pdDocument, PermissionConstants.VIEW_PROPOSAL)
              || getKcWorkflowService().hasWorkflowPermission(user.getPrincipalId(), document);
    }
    return hasPermission;
  }
  protected boolean isAuthorizedToModifyNarrative(Narrative narrative, Person user) {
    final ProposalDevelopmentDocument pdDocument =
        (ProposalDevelopmentDocument) narrative.getDevelopmentProposal().getDocument();

    boolean rejectedDocument =
        getKcDocumentRejectionService()
            .isDocumentOnInitialNode(pdDocument.getDocumentHeader().getWorkflowDocument());
    boolean hasPermission = false;
    boolean inWorkflow = getKcWorkflowService().isInWorkflow(pdDocument);

    if ((!inWorkflow || rejectedDocument) && !pdDocument.getDevelopmentProposal().getSubmitFlag()) {
      hasPermission = getModifyNarrativePermission(pdDocument, user);
    } else if (inWorkflow
        && !rejectedDocument
        && !pdDocument.getDevelopmentProposal().getSubmitFlag()) {
      if (getModifyNarrativePermission(pdDocument, user)) {
        hasPermission = getModifyNarrativePermission(pdDocument, user);
      }
    }
    return hasPermission;
  }