Enforce a Preferred Approver for Each Project
There are two types of approvers in WorklogPRO. First you can define approvers for each project in project’s permission schema. Of course there may be multiple approvers fora project. Later each user can decide their preferred approver when submitting their timesheet. This is normally optional. If you want, you can enforce a preferred approver using this script.
import org.slf4j.*;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.user.util.*;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.security.roles.ProjectRoleManager;
import com.atlassian.jira.security.groups.*;
import com.deniz.jira.worklog.services.*;
import com.deniz.jira.worklog.utils.*;
import com.deniz.jira.worklog.approval.*;
import com.atlassian.jira.project.*;
Logger log = LoggerFactory.getLogger(com.deniz.jira.worklog.scripting.ScriptingService.class);
log.debug("Running 'before timesheet approval' script!");
def submittingUserKey = timesheetApprovalRequest.userKey;
def period = timesheetApprovalRequest.period;
def action = timesheetApprovalRequest.action;
log.debug("submittingUserKey={}, period={}, action={}", submittingUserKey, period, action);
if (action != "SEND_TO_APPROVAL") {
return;
}
def timesheetApprovalService = ComponentAccessor.getOSGiComponentInstanceOfType(TimesheetApprovalService.class);
def projectManager = ComponentAccessor.getOSGiComponentInstanceOfType(ProjectManager.class);
def projectsUserWork= timesheetApprovalService.getWorkedProjectsForUser(period.id, submittingUserKey);
log.debug("Worked project Ids:{}", projectsUserWork);
//We need to convert from project ids to project keys
def projectKeys = [] as Set;
projectsUserWork.each { projectId ->
def project = projectManager.getProjectObj(projectId);
if (project != null) {
log.debug("{} -> {}}", projectId, project.key);
projectKeys << project.key;
}
}
log.debug("Worked Project Keys:{}", projectKeys);
def projectApprovers = timesheetApprovalService.getApprovers(submittingUserKey, projectKeys);
def projectsWithoutPreferredApprover = [] as Set;
projectApprovers.each {pKey, approvers ->
log.debug("{}:approvers:{}", pKey, approvers);
def preferredApprovers = approvers.find {u -> u.preferredApprover};
log.debug("{}:preferredApprovers:{}", pKey, preferredApprovers);
if (preferredApprovers == null)
//record project it it doesn't have a preferred approver
projectsWithoutPreferredApprover << pKey;
};
if (projectsWithoutPreferredApprover.size() > 0) {
//reject submission if there are projects without preffered approvers.
return "You have to specify a preferred approver for " + projectsWithoutPreferredApprover;
}
return null;