View Javadoc

1   /**
2    * Copyright 2004-2013 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.hr.time.workarea.web;
17  
18  import java.sql.Date;
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.apache.commons.lang.StringUtils;
23  import org.apache.log4j.Logger;
24  import org.kuali.hr.time.assignment.Assignment;
25  import org.kuali.hr.time.authorization.DepartmentalRule;
26  import org.kuali.hr.time.authorization.DepartmentalRuleAuthorizer;
27  import org.kuali.hr.time.roles.TkRole;
28  import org.kuali.hr.time.service.base.TkServiceLocator;
29  import org.kuali.hr.time.task.Task;
30  import org.kuali.hr.time.util.TKContext;
31  import org.kuali.hr.time.util.TKUtils;
32  import org.kuali.hr.time.util.TkConstants;
33  import org.kuali.hr.time.util.ValidationUtils;
34  import org.kuali.hr.time.workarea.WorkArea;
35  import org.kuali.rice.kns.document.MaintenanceDocument;
36  import org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase;
37  import org.kuali.rice.krad.bo.PersistableBusinessObject;
38  import org.kuali.rice.krad.util.GlobalVariables;
39  
40  public class WorkAreaMaintenanceDocumentRule extends
41  		MaintenanceDocumentRuleBase {
42  
43  	private static Logger LOG = Logger
44  			.getLogger(WorkAreaMaintenanceDocumentRule.class);
45  
46  	boolean validateDepartment(String dept, Date asOfDate) {
47  		boolean valid = ValidationUtils.validateDepartment(dept, asOfDate);
48  		if (!valid) {
49  			this.putFieldError("dept", "dept.notfound");
50  		}
51  		return valid;
52  	}
53  
54  	boolean validateRoles(List<TkRole> roles, Date effectiveDate) {
55  		boolean valid = false;
56  		
57  		if (roles != null && roles.size() > 0) {
58  			int pos = 0;
59  			for (TkRole role : roles) {
60  				valid |= role.isActive();
61  				if(role.getRoleName().equalsIgnoreCase(TkConstants.ROLE_TK_APPROVER_DELEGATE)){
62  					StringBuffer prefix = new StringBuffer("roles[");
63  		            prefix.append(pos).append("].");
64  					if (role.getExpirationDate() == null) {
65  						this.putFieldError(prefix + "expirationDate",
66  								"error.role.expiration.required");
67  					} else if (role.getEffectiveDate().compareTo(role.getExpirationDate()) >= 0) {
68  						this.putFieldError(prefix + "expirationDate",
69  								"error.role.expiration");
70  					} else if (TKUtils.getDaysBetween(role.getEffectiveDate(), role.getExpirationDate()) > 180) {
71  		        		   this.putFieldError(prefix + "expirationDate",
72  		     						"error.role.expiration.duration");
73  		     				valid = false;
74  		        	}
75  				}
76  				pos++;
77  			}
78  		}
79  
80  		if (!valid) {
81  			this.putGlobalError("role.required");
82  		}
83  
84  		return valid;
85  	}
86  
87  	boolean validateTask(List<TkRole> roles) {
88  		boolean valid = false;
89  
90  		if (roles != null && roles.size() > 0) {
91  			for (TkRole role : roles) {
92  				valid |= role.isActive()
93  						&& StringUtils.equals(role.getRoleName(),
94  								TkConstants.ROLE_TK_APPROVER);
95  			}
96  		}
97  
98  		if (!valid) {
99  			this.putGlobalError("role.required");
100 		}
101 
102 		return valid;
103 	}
104 	
105 	boolean validateTask(Task task, Long workArea) {
106 		boolean valid = true;
107         //Task numbers are assigned by the system and the validation below is not needed.
108 //		for (Task t : tasks) {
109 //			if (t.getTask().equals(task.getTask()) ) {   //task.getTask() is always null at this point?
110 //				this.putGlobalError("error.duplicate.entry", "task '" + task.getTask() + "'");
111 //				valid = false;
112 //			}
113 //		}
114         //validate the effective date set for the task. it should be equal to or after the effdt set for the workarea
115         WorkArea wa = TkServiceLocator.getWorkAreaService().getWorkArea(workArea,TKUtils.getCurrentDate());
116 
117         if (wa != null && task.getEffectiveDate().compareTo(wa.getEffectiveDate()) < 0) {
118             this.putGlobalError("task.workarea.invalid.effdt", "effective date '" + task.getEffectiveDate().toString() +"'");
119             valid = false;
120         }
121 		return valid;
122 	}
123 	
124 	boolean validateDefaultOTEarnCode(String earnCode, Date asOfDate) {
125 		// defaultOvertimeEarnCode is a nullable field. 
126 		if (earnCode != null
127 				&& !ValidationUtils.validateEarnCode(earnCode, asOfDate)) {
128 			this.putFieldError("defaultOvertimeEarnCode", "error.existence", "earnCode '"
129 					+ earnCode + "'");
130 			return false;
131 		} else {
132 			if (earnCode != null
133 					&& !ValidationUtils.validateEarnCode(earnCode, true, asOfDate)) {
134 				this.putFieldError("defaultOvertimeEarnCode", "earncode.ovt.required",
135 						earnCode);
136 				return false;
137 			}
138 			return true;
139 		}
140 	}
141 
142 	@Override
143 	protected boolean processCustomRouteDocumentBusinessRules(
144 			MaintenanceDocument document) {
145 		boolean valid = false;
146 
147 		PersistableBusinessObject pbo = (PersistableBusinessObject) this.getNewBo();
148 		if (pbo instanceof WorkArea) {
149 			WorkArea wa = (WorkArea) pbo;
150 			valid = validateDepartment(wa.getDept(), wa.getEffectiveDate());
151 			if(!DepartmentalRuleAuthorizer.hasAccessToWrite((DepartmentalRule)pbo)) {
152 				String[] params = new String[]{GlobalVariables.getUserSession().getPrincipalName(), wa.getDept()};
153 				this.putFieldError("dept", "dept.user.unauthorized", params);
154 			}
155 			valid &= validateRoles(wa.getRoles(), wa.getEffectiveDate());
156 			// defaultOvertimeEarnCode is a nullable field. 
157 			if ( wa.getDefaultOvertimeEarnCode() != null ){
158 				valid &= validateDefaultOTEarnCode(wa.getDefaultOvertimeEarnCode(),
159 						wa.getEffectiveDate());
160 			}
161 			
162 			if(!wa.isActive()){
163 				List<Assignment> assignments = TkServiceLocator.getAssignmentService().getActiveAssignmentsForWorkArea(wa.getWorkArea(), wa.getEffectiveDate());
164 				for(Assignment assignment: assignments){
165 					if(assignment.getWorkArea().equals(wa.getWorkArea())){
166 						this.putGlobalError("workarea.active.required");
167 						valid = false;
168 						break;
169 					}
170 				}
171 			}else{
172 				List<Long> inactiveTasks = new ArrayList<Long>();
173 				for (Task task : wa.getTasks()) {
174 					if(!task.isActive()){
175 						inactiveTasks.add(task.getTask());
176 					}
177 				}
178 				
179 				if(!inactiveTasks.isEmpty()){
180 					List<Assignment> assignments = TkServiceLocator.getAssignmentService().getActiveAssignmentsForWorkArea(wa.getWorkArea(), wa.getEffectiveDate());
181 					for(Assignment assignment : assignments){
182 						for(Long inactiveTask : inactiveTasks){
183 							if(inactiveTask.equals(assignment.getTask())){
184 								this.putGlobalError("task.active.required", inactiveTask.toString());
185 								valid = false;
186 							}
187 						}
188 					}
189 				}
190 				
191 			}
192 		}
193 
194 		return valid;
195 	}
196 
197 	@Override
198 	public boolean processCustomAddCollectionLineBusinessRules(
199 			MaintenanceDocument document, String collectionName,
200 			PersistableBusinessObject line) {
201 		boolean valid = false;
202 		LOG.debug("entering custom validation for Task");
203 		PersistableBusinessObject pboWorkArea = document.getDocumentBusinessObject();
204 		PersistableBusinessObject pbo = line;
205 		if (pbo instanceof Task && pboWorkArea instanceof WorkArea) {
206 			WorkArea wa = (WorkArea) pboWorkArea;
207 			
208 			Task task = (Task) pbo;
209 			
210 			if (task != null && wa.getTasks() != null) {
211 				valid = true;
212 				valid &= this.validateTask(task, wa.getWorkArea());
213 				// KPME-870
214 				if ( valid ){
215 					if (task.getTask() == null){
216 						Long maxTaskNumberInTable = this.getTaskNumber(wa);
217 						Long maxTaskNumberOnPage = 0L;
218 						if(wa.getTasks().size() > 0){
219 							maxTaskNumberOnPage = wa.getTasks().get((wa.getTasks().size()) -1 ).getTask();
220 						}
221 						
222 						if ( maxTaskNumberOnPage.compareTo(maxTaskNumberInTable) >= 0){
223 							task.setTask(maxTaskNumberOnPage + 1);
224 						} else {
225 							task.setTask(maxTaskNumberInTable);
226 						}
227 						task.setWorkArea(wa.getWorkArea());
228 					}
229 				}
230 			}
231 		} else if ((pbo instanceof TkRole && pboWorkArea instanceof WorkArea)) {
232 			TkRole tkRole = (TkRole)pbo;
233 			valid = true;
234 			if(StringUtils.isEmpty(tkRole.getPrincipalId())) {
235 				if (tkRole.getPositionNumber() == null || StringUtils.isEmpty(tkRole.getPositionNumber().toString())){
236 					this.putGlobalError("principal.position.required");
237 				}
238 			}
239 		}
240 		
241 		return valid;
242 	}
243 
244 	public Long getTaskNumber(WorkArea workArea) {
245 		Long task;
246 		
247 		Task maxTaskInTable = TkServiceLocator.getTaskService().getMaxTask();
248 		if(maxTaskInTable != null) {
249 			// get the max of task number of the collection
250 			task = maxTaskInTable.getTask() +1;
251 		} else {
252 			task = new Long("100");
253 		}
254 		
255 		return task;
256 	}
257 }