View Javadoc

1   /**
2    * Copyright 2004-2014 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.kpme.tklm.leave.block.web;
17  
18  import java.text.DateFormat;
19  import java.text.ParseException;
20  import java.text.SimpleDateFormat;
21  import java.util.ArrayList;
22  import java.util.Date;
23  import java.util.Iterator;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.apache.commons.lang.StringUtils;
28  import org.apache.log4j.Logger;
29  import org.joda.time.DateTime;
30  import org.joda.time.LocalDate;
31  import org.kuali.kpme.core.KPMENamespace;
32  import org.kuali.kpme.core.department.Department;
33  import org.kuali.kpme.core.job.Job;
34  import org.kuali.kpme.core.lookup.KPMELookupableImpl;
35  import org.kuali.kpme.core.role.KPMERole;
36  import org.kuali.kpme.core.service.HrServiceLocator;
37  import org.kuali.kpme.core.util.HrContext;
38  import org.kuali.kpme.core.util.TKUtils;
39  import org.kuali.kpme.tklm.leave.block.LeaveBlock;
40  import org.kuali.kpme.tklm.leave.block.LeaveBlockHistory;
41  import org.kuali.kpme.tklm.leave.service.LmServiceLocator;
42  import org.kuali.kpme.tklm.leave.workflow.LeaveCalendarDocumentHeader;
43  import org.kuali.rice.core.api.search.Range;
44  import org.kuali.rice.core.api.search.SearchExpressionUtils;
45  import org.kuali.rice.krad.bo.BusinessObject;
46  import org.kuali.rice.krad.uif.view.LookupView;
47  import org.kuali.rice.krad.util.GlobalVariables;
48  import org.kuali.rice.krad.web.form.LookupForm;
49  
50  public class LeaveBlockHistoryLookupableHelperServiceImpl extends KPMELookupableImpl  {
51  	/**
52  	 * 
53  	 */
54  	private static final long serialVersionUID = 1L;
55  	
56  	private static final String DOC_ID = "documentId";
57  	private static final String DOC_STATUS_ID = "leaveCalendarDocumentHeader.documentStatus";
58  	private static final String BEGIN_DATE_ID = "beginDate";
59  	private static final String BEGIN_TIMESTAMP = "beginTimestamp";
60  
61  	private static final Logger LOG = Logger.getLogger(LeaveBlockHistoryLookupableHelperServiceImpl.class);
62  	
63  
64  	@Override
65  	protected List<?> getSearchResults(LookupForm form,
66  			Map<String, String> searchCriteria, boolean unbounded) {
67  		// TODO Auto-generated method stub
68  		 if (searchCriteria.containsKey(BEGIN_DATE_ID)) {
69  			 //beginDate = searchCriteria.get(BEGIN_DATE);
70  			 searchCriteria.put(BEGIN_TIMESTAMP, searchCriteria.get(BEGIN_DATE_ID));
71  			 searchCriteria.remove(BEGIN_DATE_ID);
72  		 }
73  		 
74  		String documentId = searchCriteria.get(DOC_ID);
75  		String principalId = searchCriteria.get("principalId");
76  		String userPrincipalId = searchCriteria.get("userPrincipalId");
77  		String leaveBlockType = searchCriteria.get("leaveBlockType");
78  		
79  		
80  		
81  		
82  		LocalDate fromDate = null;
83  		LocalDate toDate = null;
84  		if(StringUtils.isNotBlank(searchCriteria.get(BEGIN_TIMESTAMP))) {			
85  			String fromDateString = TKUtils.getFromDateString(searchCriteria.get(BEGIN_TIMESTAMP));
86  			String toDateString = TKUtils.getToDateString(searchCriteria.get(BEGIN_TIMESTAMP));
87  			Range range = SearchExpressionUtils.parseRange(searchCriteria.get(BEGIN_TIMESTAMP));
88  			boolean invalid = false;
89  			if(range.getLowerBoundValue() != null && range.getUpperBoundValue() != null) {
90  				fromDate = TKUtils.formatDateString(fromDateString);
91  				if(fromDate == null) {
92  					GlobalVariables.getMessageMap().putError("lookupCriteria[rangeLowerBoundKeyPrefix_beginDate]", "error.invalidLookupDate", range.getLowerBoundValue());
93  					invalid = true;
94  				}
95  
96  				toDate = TKUtils.formatDateString(toDateString);
97  				if(toDate == null) {
98  					GlobalVariables.getMessageMap().putError("lookupCriteria[beginDate]", "error.invalidLookupDate", range.getUpperBoundValue());
99  					invalid = true;
100 				}
101 			}
102 			else if(range.getLowerBoundValue() != null) {
103 				fromDate = TKUtils.formatDateString(fromDateString);
104 				if(fromDate == null) {
105 					GlobalVariables.getMessageMap().putError("lookupCriteria[rangeLowerBoundKeyPrefix_beginDate]", "error.invalidLookupDate", range.getLowerBoundValue());
106 					invalid = true;
107 				}
108 			}
109 			else if(range.getUpperBoundValue() != null) {
110 				toDate = TKUtils.formatDateString(toDateString);
111 				if(toDate == null) {
112 					GlobalVariables.getMessageMap().putError("lookupCriteria[beginDate]", "error.invalidLookupDate", range.getUpperBoundValue());
113 					invalid = true;
114 				}
115 			}
116 			if(invalid) {
117 				return new ArrayList<LeaveBlockHistory>();
118 			}
119 		}
120 		
121 		LocalDate modifiedFromDate = null;
122 		LocalDate modifiedToDate = null;
123 		if(StringUtils.isNotBlank(searchCriteria.get("timestamp"))) {
124 			String fromDateString = TKUtils.getFromDateString(searchCriteria.get("timestamp"));
125 			String toDateString = TKUtils.getToDateString(searchCriteria.get("timestamp"));
126 			Range range = SearchExpressionUtils.parseRange(searchCriteria.get("timestamp"));
127 			boolean invalid = false;
128 			if(range.getLowerBoundValue() != null && range.getUpperBoundValue() != null) {
129 				modifiedFromDate = TKUtils.formatDateString(fromDateString);
130 				if(modifiedFromDate == null) {
131 					GlobalVariables.getMessageMap().putError("lookupCriteria[rangeLowerBoundKeyPrefix_beginDate]", "error.invalidLookupDate", range.getLowerBoundValue());
132 					invalid = true;
133 				}
134 
135 				modifiedToDate = TKUtils.formatDateString(toDateString);
136 				if(modifiedToDate == null) {
137 					GlobalVariables.getMessageMap().putError("lookupCriteria[beginDate]", "error.invalidLookupDate", range.getUpperBoundValue());
138 					invalid = true;
139 				}
140 			}
141 			else if(range.getLowerBoundValue() != null) {
142 				modifiedFromDate = TKUtils.formatDateString(fromDateString);
143 				if(modifiedFromDate == null) {
144 					GlobalVariables.getMessageMap().putError("lookupCriteria[rangeLowerBoundKeyPrefix_beginDate]", "error.invalidLookupDate", range.getLowerBoundValue());
145 					invalid = true;
146 				}
147 			}
148 			else if(range.getUpperBoundValue() != null) {
149 				modifiedToDate = TKUtils.formatDateString(toDateString);
150 				if(modifiedToDate == null) {
151 					GlobalVariables.getMessageMap().putError("lookupCriteria[beginDate]", "error.invalidLookupDate", range.getUpperBoundValue());
152 					invalid = true;
153 				}
154 			}
155 			if(invalid) {
156 				return new ArrayList<LeaveBlockHistory>();
157 			}
158 		}
159 		
160 		//Could also simply use super.getSearchResults for an initial object list, then invoke LeaveBlockService with the relevant query params.
161 		//List<LeaveBlock> leaveBlockList = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLookup(documentId, principalId, userPrincipalId, fromDate, toDate, leaveBlockType);
162 		List<LeaveBlock> leaveBlockList = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLookup(documentId, principalId, userPrincipalId, fromDate, toDate,leaveBlockType);
163 		List<LeaveBlockHistory> objectList = new ArrayList<LeaveBlockHistory>();
164 		
165 		for(LeaveBlock leaveBlock : leaveBlockList) {
166 			List<LeaveBlockHistory> histories = LmServiceLocator.getLeaveBlockHistoryService().getLeaveBlockHistoryByLmLeaveBlockId(leaveBlock.getLmLeaveBlockId());
167 			for(LeaveBlockHistory history : histories) {
168 				
169 				boolean addToResults = false;
170 				if(modifiedFromDate != null && modifiedToDate != null) {
171 					if(history.getTimestamp().compareTo(modifiedFromDate.toDate()) >= 0
172 							&& history.getTimestamp().compareTo(modifiedToDate.toDate()) <= 0) {
173 						addToResults = true;
174 					}
175 				}
176 				else if(modifiedFromDate != null) {
177 					if(history.getTimestamp().compareTo(modifiedFromDate.toDate()) >= 0) {
178 						addToResults = true;
179 					}
180 				}
181 				else if(modifiedToDate != null) {
182 					if(history.getTimestamp().compareTo(modifiedToDate.toDate()) <= 0) {
183 						addToResults = true;
184 					}
185 				}
186 				else {
187 					addToResults = true;
188 				}
189 				if(addToResults) {
190 					LeaveCalendarDocumentHeader lcHeader = LmServiceLocator.getLeaveCalendarDocumentHeaderService().getDocumentHeader(history.getDocumentId());
191 					
192 					if(lcHeader != null) {
193 						if(StringUtils.isNotBlank(searchCriteria.get(DOC_STATUS_ID))) {
194 							//only add if doc status is one of those specified
195 							if(searchCriteria.get(DOC_STATUS_ID).contains("category")) {
196 								//format for categorical statuses is "category:Q" where 'Q' is one of "P,S,U".
197 								//which category was selected, and is the time block on a timesheet with this status.
198 								if(searchCriteria.get(DOC_STATUS_ID).contains("P")) {
199 									//pending statuses
200 									if("I,S,R,E".contains(lcHeader.getDocumentStatus())) {
201 										objectList.add(history);
202 									}
203 								}
204 								else if(searchCriteria.get(DOC_STATUS_ID).contains("S")) {
205 									//successful statuses
206 									if("P,F".contains(lcHeader.getDocumentStatus())) {
207 										objectList.add(history);
208 									}
209 								}
210 								else if(searchCriteria.get(DOC_STATUS_ID).contains("U")) {
211 									//unsuccessful statuses
212 									if("X,D".contains(lcHeader.getDocumentStatus())) {
213 										objectList.add(history);
214 									}
215 								}
216 							}
217 							else if(searchCriteria.get(DOC_STATUS_ID).contains(lcHeader.getDocumentStatus())) {
218 								//match the specific doc status
219 								objectList.add(history);
220 							}
221 						}
222 						else {
223 							//no status specified, add regardless of status
224 							objectList.add(history);
225 						}
226 							
227 						
228 					} else if(StringUtils.isBlank(searchCriteria.get(DOC_STATUS_ID))) {
229 						//can't match doc status with a non existent header
230 						//only add to list if no status was selected
231 						objectList.add(history);
232 					}
233 				}
234 		
235 			}
236 		}
237 	        if(!objectList.isEmpty()) {
238         	Iterator<? extends BusinessObject> itr = objectList.iterator();
239 
240             //TODO - performance  -- need to get roles outside of loop for user, and check inside... too many db calls
241         	while (itr.hasNext()) {
242         		LeaveBlockHistory tb = (LeaveBlockHistory) itr.next();
243 				
244 				Long workArea = tb.getWorkArea();
245 				
246 				Job job = HrServiceLocator.getJobService().getJob(tb.getPrincipalId(), tb.getJobNumber(), LocalDate.fromDateFields(tb.getLeaveDate()), false);
247 				String department = job != null ? job.getDept() : null;
248 				
249 				Department departmentObj = HrServiceLocator.getDepartmentService().getDepartmentWithoutRoles(department, LocalDate.fromDateFields(tb.getLeaveDate()));
250 				String location = departmentObj != null ? departmentObj.getLocation() : null;
251 				DateTime date = LocalDate.now().toDateTimeAtStartOfDay();
252 				boolean valid = false;
253 				if (HrServiceLocator.getKPMEGroupService().isMemberOfSystemAdministratorGroup(HrContext.getPrincipalId(), date)
254 						|| HrServiceLocator.getKPMEGroupService().isMemberOfSystemViewOnlyGroup(HrContext.getPrincipalId(), date)
255 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInWorkArea(HrContext.getPrincipalId(), KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.APPROVER.getRoleName(), workArea, date)
256 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInDepartment(HrContext.getPrincipalId(), KPMENamespace.KPME_TK.getNamespaceCode(), KPMERole.TIME_DEPARTMENT_ADMINISTRATOR.getRoleName(), department, date)
257 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInDepartment(HrContext.getPrincipalId(), KPMENamespace.KPME_LM.getNamespaceCode(), KPMERole.LEAVE_DEPARTMENT_ADMINISTRATOR.getRoleName(), department, date)
258 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInLocation(HrContext.getPrincipalId(), KPMENamespace.KPME_TK.getNamespaceCode(), KPMERole.TIME_LOCATION_ADMINISTRATOR.getRoleName(), location, date)
259 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInLocation(HrContext.getPrincipalId(), KPMENamespace.KPME_LM.getNamespaceCode(), KPMERole.LEAVE_LOCATION_ADMINISTRATOR.getRoleName(), location, date)
260 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInLocation(HrContext.getPrincipalId(), KPMENamespace.KPME_LM.getNamespaceCode(), KPMERole.LEAVE_LOCATION_VIEW_ONLY.getRoleName(), location, date)
261 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInDepartment(HrContext.getPrincipalId(), KPMENamespace.KPME_LM.getNamespaceCode(), KPMERole.LEAVE_DEPARTMENT_VIEW_ONLY.getRoleName(), location, date)
262 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInDepartment(HrContext.getPrincipalId(), KPMENamespace.KPME_TK.getNamespaceCode(), KPMERole.TIME_DEPARTMENT_VIEW_ONLY.getRoleName(), location, date)
263 						|| HrServiceLocator.getKPMERoleService().principalHasRoleInLocation(HrContext.getPrincipalId(), KPMENamespace.KPME_TK.getNamespaceCode(), KPMERole.TIME_LOCATION_VIEW_ONLY.getRoleName(), location, date)) {
264 					valid = true;
265 				}
266 				
267 				if (!valid) {
268 				
269 					itr.remove();
270 					continue;
271 				}
272         	}
273 					
274 			
275         }
276         return objectList;
277 	}
278 		 
279 	 
280 
281 	@Override
282 	protected String getActionUrlHref(LookupForm lookupForm, Object dataObject,
283 			String methodToCall, List<String> pkNames) {
284 		String actionUrlHref = super.getActionUrlHref(lookupForm, dataObject, methodToCall, pkNames);
285 		LeaveBlockHistory lbh = null;
286 		String concreteBlockId = null;
287 		if(dataObject instanceof LeaveBlockHistory) {
288 			lbh = (LeaveBlockHistory) dataObject;
289 			concreteBlockId = lbh.getLmLeaveBlockHistoryId();
290 		}
291 		if(concreteBlockId == null) {
292 			return null;
293 		}
294 
295 		return actionUrlHref;
296 	}
297 
298 	@Override
299 	public void initSuppressAction(LookupForm lookupForm) {
300 		((LookupView) lookupForm.getView()).setSuppressActions(false);
301 	}
302 
303 }