View Javadoc
1   package org.kuali.student.ap.coursesearch.util;
2   
3   import java.beans.PropertyEditorSupport;
4   import java.util.ArrayList;
5   import java.util.HashMap;
6   import java.util.List;
7   import java.util.Map;
8   
9   import org.kuali.rice.core.api.config.property.ConfigContext;
10  import org.kuali.student.ap.framework.config.KsapFrameworkServiceLocator;
11  import org.kuali.student.ap.framework.context.PlanConstants;
12  import org.kuali.student.ap.framework.context.YearTerm;
13  import org.kuali.student.r2.core.acal.infc.Term;
14  import org.kuali.student.enrollment.courseoffering.dto.ActivityOfferingInfo;
15  import org.kuali.student.enrollment.courseoffering.service.CourseOfferingService;
16  import org.kuali.student.ap.coursesearch.dataobject.CourseDetails;
17  import org.kuali.student.myplan.plan.dataobject.AcademicRecordDataObject;
18  import org.kuali.student.myplan.plan.dataobject.PlanItemDataObject;
19  import org.kuali.student.r2.common.dto.AttributeInfo;
20  import org.kuali.student.r2.common.util.date.DateFormatters;
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  /**
25   * Created by IntelliJ IDEA. User: hemanthg Date: 5/3/12 Time: 10:46 AM To
26   * change this template use File | Settings | File Templates.
27   */
28  public class CrudMessageMatrixFormatter extends PropertyEditorSupport {
29  	private final static Logger logger = LoggerFactory.getLogger(CrudMessageMatrixFormatter.class);
30  
31  	private transient CourseOfferingService courseOfferingService;
32  
33      //We may be able to split this out so we have the URL separate from the markup of the anchor tag
34      private final String plannerScreenUrl = "<a href=\"planner?methodToCall=start&viewId=Planner-FormView&focusAtpId=";
35  
36  	protected CourseOfferingService getCourseOfferingService() {
37  		if (this.courseOfferingService == null) {
38  			this.courseOfferingService = KsapFrameworkServiceLocator
39  					.getCourseOfferingService();
40  		}
41  		return this.courseOfferingService;
42  	}
43  
44  	public void setCourseOfferingService(
45  			CourseOfferingService courseOfferingService) {
46  		this.courseOfferingService = courseOfferingService;
47  	}
48  
49  	@Override
50  	public void setValue(Object value) {
51  		super.setValue(value);
52  	}
53  
54  	@Override
55  	public String getAsText() {
56  
57  		CourseDetails courseDetails = (CourseDetails) super.getValue();
58  		StringBuilder sb = new StringBuilder();
59  		boolean currentTermRegistered = false;
60  
61  		/*
62  		 * When academic terms are not null then populating message
63  		 * "You took this course on Winter 2012" or
64  		 * "This course was withdrawn on week 6 in Spring 2012" or
65  		 * "You're enrolled in this course for Autumn 2012"
66  		 */
67  		if (courseDetails.getPlannedCourseSummary().getAcademicTerms().size() > 0) {
68  			List<String> withDrawnCourseTerms = new ArrayList<String>();
69  			List<String> nonWithDrawnCourseTerms = new ArrayList<String>();
70  
71  			for (String term : courseDetails.getPlannedCourseSummary()
72  					.getAcademicTerms()) {
73  				for (AcademicRecordDataObject academicRecordDataObject : courseDetails
74  						.getPlannedCourseSummary().getAcadRecList()) {
75  					if (term.equals(academicRecordDataObject.getAtpId())
76  							&& academicRecordDataObject.getGrade().contains(
77  									PlanConstants.WITHDRAWN_GRADE)) {
78  						if (!withDrawnCourseTerms.contains(term)) {
79  							withDrawnCourseTerms.add(term);
80  						}
81  					}
82  					if (term.equals(academicRecordDataObject.getAtpId())
83  							&& !academicRecordDataObject.getGrade().contains(
84  									PlanConstants.WITHDRAWN_GRADE)) {
85  						if (!nonWithDrawnCourseTerms.contains(term)) {
86  							nonWithDrawnCourseTerms.add(term);
87  						}
88  					}
89  				}
90  			}
91  			int counter = 0;
92  			for (String withdrawnTerm : withDrawnCourseTerms) {
93  				Term term = KsapFrameworkServiceLocator.getTermHelper()
94  						.getTerm(withdrawnTerm);
95  				if (counter == 0) {
96  					if (KsapFrameworkServiceLocator.getUserSessionHelper()
97  							.isAdviser()) {
98  						String user = KsapFrameworkServiceLocator
99  								.getUserSessionHelper().getStudentName();
100                         /*
101                          * TODO KSAP-736: Convert this tag manipulation handling
102                          * This is simply creating an orphan DD element, with no containing DL
103                          * Moreover the ends up getting rendered inside of a SPAN element;
104                          * It is bad form, and will not validate, when you put block-level elements, such as
105                          * A UL/OL/DL, inside of an inline element like a span.
106                          *
107                          * Additional recommendations:
108                          *
109                          * If we are to use a list, would be to use a UL since we are only dealing with a list of items.
110                          * DL is for a list of key/value pairs, which is not what we have in this case.
111                          *
112                          * Instead of the string appending, a formatted string would be much easier to manage.
113                          * For an example, look at ScheduledTermsPropertyEditor.java
114                          *  */
115 						sb = sb.append("<dd>")
116 								.append(user + " withdrew from this course in ")
117 								.append(plannerScreenUrl)
118 								.append(withdrawnTerm).append(">")
119 								.append(term.getName()).append("</a>");
120 					} else {
121 						sb = sb.append("<dd>")
122 								.append("You withdrew from this course in ")
123 								.append(plannerScreenUrl)
124 								.append(withdrawnTerm).append("\">")
125 								.append(term.getName()).append("</a>");
126 					}
127 				}
128 				if (counter > 0) {
129 					sb = sb.append(",")
130 							.append(plannerScreenUrl)
131 							.append(withdrawnTerm).append("\">")
132 							.append(term.getName()).append("</a>");
133 				}
134 				counter++;
135 			}
136 
137 			int counter2 = 0;
138 			int counter3 = 0;
139 
140 			for (String nonWithdrawnTerm : nonWithDrawnCourseTerms) {
141 				Term term = KsapFrameworkServiceLocator.getTermHelper()
142 						.getTerm(nonWithdrawnTerm);
143 				List<String> sections = getSections(courseDetails,
144 						nonWithdrawnTerm);
145 				if (!KsapFrameworkServiceLocator.getTermHelper().isCompleted(term.getId())) {
146 					if (counter2 == 0) {
147 						String message = "You are enrolled in ";
148 						if (KsapFrameworkServiceLocator.getUserSessionHelper()
149 								.isAdviser()) {
150 							String user = KsapFrameworkServiceLocator
151 									.getUserSessionHelper().getStudentName();
152 							message = user
153 									+ ". currently enrolled in this course for ";
154 						}
155 						StringBuilder sec = new StringBuilder();
156 						int count = 0;
157 						for (String section : sections) {
158 							if (count == 0) {
159 								sec = sec.append(section);
160 								count++;
161 							} else {
162 								sec = sec.append(" and ").append(section);
163 								count++;
164 							}
165 						}
166 						sb = sb.append("<dd>")
167 								.append(message)
168 								.append(sec)
169 								.append(" for ")
170 								.append(plannerScreenUrl)
171 								.append(nonWithdrawnTerm).append("\">")
172 								.append(term.getName()).append("</a>");
173 						currentTermRegistered = true;
174 					}
175 					if (counter2 > 0) {
176 						sb = sb.append(",")
177 								.append(plannerScreenUrl)
178 								.append(nonWithdrawnTerm).append("\">")
179 								.append(term.getName()).append("</a>");
180 						currentTermRegistered = true;
181 					}
182 					counter2++;
183 				} else {
184 					if (counter3 == 0) {
185 						String message = "You took this course in ";
186 						if (KsapFrameworkServiceLocator.getUserSessionHelper()
187 								.isAdviser()) {
188 							String user = KsapFrameworkServiceLocator
189 									.getUserSessionHelper().getStudentName();
190 							message = user + " took this course in ";
191 						}
192 						sb = sb.append("<dd>")
193 								.append(message)
194 								.append(plannerScreenUrl)
195 								.append(nonWithdrawnTerm).append("\">")
196 								.append(term.getName()).append("</a>");
197 
198 					}
199 					if (counter3 > 0) {
200 						sb = sb.append(", ")
201 								.append(plannerScreenUrl)
202 								.append(nonWithdrawnTerm).append("\">")
203 								.append(term.getName()).append("</a>");
204 					}
205 					counter3++;
206 				}
207 
208 			}
209 
210 		}
211 
212 		/*
213 		 * When plannedList or backupList are not null then populating message
214 		 * "Added to Spring 2013 Plan, Spring 2014 Plan on 01/18/2012" or
215 		 * "Added to Spring 2013 Plan on 01/18/2012 and Spring 2014 Plan on 09/18/2012"
216 		 */
217 		if ((courseDetails.getPlannedCourseSummary().getPlannedList() != null && courseDetails
218 				.getPlannedCourseSummary().getPlannedList().size() > 0)
219 				|| (courseDetails.getPlannedCourseSummary().getBackupList() != null && courseDetails
220 						.getPlannedCourseSummary().getBackupList().size() > 0)) {
221 			List<PlanItemDataObject> planItemDataObjects = new ArrayList<PlanItemDataObject>();
222 			if (courseDetails.getPlannedCourseSummary().getPlannedList() != null) {
223 				for (PlanItemDataObject pl : courseDetails
224 						.getPlannedCourseSummary().getPlannedList()) {
225 					planItemDataObjects.add(pl);
226 				}
227 			}
228 			if (courseDetails.getPlannedCourseSummary().getBackupList() != null) {
229 				for (PlanItemDataObject bl : courseDetails
230 						.getPlannedCourseSummary().getBackupList()) {
231 					planItemDataObjects.add(bl);
232 				}
233 			}
234 			/* Dividing the plan items on same date and different date */
235 			Map<String, String> planItemsMap = new HashMap<String, String>();
236 			if (planItemDataObjects.size() > 0) {
237 
238 				for (PlanItemDataObject pl : planItemDataObjects) {
239 					Term term = KsapFrameworkServiceLocator.getTermHelper()
240 							.getTerm(pl.getAtp());
241 					YearTerm yearTerm = KsapFrameworkServiceLocator
242 							.getTermHelper().getYearTerm(term);
243 					String date = DateFormatters.MONTH_DAY_YEAR_DATE_FORMATTER
244 							.format(DateFormatters.DEFAULT_DATE_FORMATTER
245 									.parse(pl.getDateAdded().toString()
246 											.substring(0, 10)));
247 					if (planItemsMap.containsKey(date)) {
248 						StringBuilder sbuf = new StringBuilder();
249 						sbuf = sbuf.append(planItemsMap.get(date)).append(",")
250 								.append(KsapFrameworkServiceLocator.getTermHelper().getTerm(yearTerm).getId());
251 						planItemsMap.put(date, sbuf.toString());
252 					} else {
253 						planItemsMap.put(date, KsapFrameworkServiceLocator.getTermHelper().getTerm(yearTerm).getId());
254 					}
255 				}
256 
257 			}
258 			int count = 0;
259 			StringBuilder startsSub = new StringBuilder();
260 			if (sb.toString().length() > 0) {
261 				startsSub = startsSub.append(sb);
262 			}
263 			if (!currentTermRegistered) {
264 				startsSub = startsSub.append("<dd>").append("Added to ");
265 			} else {
266 				startsSub = startsSub.append("<dd>").append(
267 						"This course was also added to ");
268 			}
269 
270 			for (Map.Entry<String, String> entry : planItemsMap.entrySet()) {
271                 String key = entry.getKey();
272                 String value = entry.getValue();
273 				if (count == 0) {
274 					if (value.contains(",")) {
275 						String[] terms = value.split(",");
276 						for (String t : terms) {
277 							Term term = KsapFrameworkServiceLocator
278 									.getTermHelper().getTerm(t);
279 							sb = startsSub
280 									.append(plannerScreenUrl)
281 									.append(t).append("\">")
282 									.append(term.getName()).append(" plan")
283 									.append("</a>").append(", ");
284 						}
285 						String formattedString = sb.substring(0,
286 								sb.lastIndexOf(","));
287 						StringBuilder formattedSubBuf = new StringBuilder();
288 						formattedSubBuf = formattedSubBuf
289 								.append(formattedString);
290 						sb = formattedSubBuf.append(" on ").append(key);
291 					} else {
292 						Term term = KsapFrameworkServiceLocator.getTermHelper()
293 								.getTerm(value);
294 						if (!currentTermRegistered) {
295 							sb = sb.append("<dd>")
296 									.append("Added to ")
297 									.append(plannerScreenUrl)
298 									.append(term.getId()).append("\">")
299 									.append(term.getName()).append(" plan")
300 									.append("</a> ").append(" on ").append(key)
301 									.append(" ");
302 						} else {
303 							sb = sb.append("<dd>")
304 									.append("This course was also added to ")
305 									.append(plannerScreenUrl)
306 									.append(term.getId()).append("\">")
307 									.append(term.getName()).append(" plan")
308 									.append("</a> ").append(" on ").append(key)
309 									.append(" ");
310 						}
311 					}
312 
313 				}
314 				if (count > 0) {
315 					if (value.contains(",")) {
316 						String[] terms = value.split(",");
317 						for (String t : terms) {
318 							Term term = KsapFrameworkServiceLocator
319 									.getTermHelper().getTerm(t);
320 							sb = sb.append(plannerScreenUrl)
321 									.append(t).append("\">")
322 									.append(term.getName()).append(" plan")
323 									.append("</a> ").append(",");
324 						}
325 						String formattedString = sb.substring(0,
326 								sb.lastIndexOf(",") - 1);
327 						StringBuilder formattedSubBuf = new StringBuilder();
328 						formattedSubBuf = formattedSubBuf
329 								.append(formattedString);
330 						sb = formattedSubBuf.append(" on ").append(key);
331 					} else {
332 						Term term = KsapFrameworkServiceLocator.getTermHelper()
333 								.getTerm(value);
334 						sb = sb.append(" and ")
335 								.append(plannerScreenUrl)
336 								.append(term.getId()).append("\">")
337 								.append(term.getName()).append(" plan")
338 								.append("</a> ").append(" on ").append(key);
339 					}
340 
341 				}
342 				count++;
343 
344 			}
345 		}
346 		/*
347 		 * When savedItemId and savedItemDateCreated are not null then
348 		 * populating message"Bookmarked on 8/15/2012"
349 		 */
350 		if (courseDetails.getPlannedCourseSummary().getSavedItemId() != null
351 				&& courseDetails.getPlannedCourseSummary()
352 						.getSavedItemDateCreated() != null) {
353 			sb = sb.append("<dd>")
354 					.append("<a href=lookup?methodToCall=search&viewId=SavedCoursesDetail-LookupView>")
355 					.append("Bookmarked")
356 					.append("</a>")
357 					.append(" on ")
358 					.append(courseDetails.getPlannedCourseSummary()
359 							.getSavedItemDateCreated());
360 
361 		}
362 
363 		return sb.toString();
364 	}
365 
366 	/**
367 	 * returns the section links string for given courseId and term in the form
368 	 * ("<a href="http://localhost:8080/kr-krad/inquiry?methodToCall=
369 	 * start&viewId=CourseDetails-InquiryView&courseId=60325fa8-7307-454a-be73-3
370 	 * cc1c642122d#kuali-uw-atp-2013-1-19889"> Section (SLN) </a>")
371 	 * 
372 	 * @param courseDetails
373 	 * @param term
374 	 * @return
375 	 */
376 	private List<String> getSections(CourseDetails courseDetails, String term) {
377 		String[] yearAndTerm = term.split(" ");
378 
379 		List<String> sections = new ArrayList<String>();
380 		List<String> sectionAndSln = new ArrayList<String>();
381 		for (AcademicRecordDataObject acr : courseDetails
382 				.getPlannedCourseSummary().getAcadRecList()) {
383 			if (acr.getAtpId().equals(term)) {
384 				sections.add(acr.getActivityCode());
385 			}
386 		}
387 		for (String section : sections) {
388 			String sln = getSLN(yearAndTerm[1].trim(), yearAndTerm[0].trim(),
389 					courseDetails.getCourseSummaryDetails().getSubjectArea(),
390 					courseDetails.getCourseSummaryDetails().getCourseNumber(),
391 					section);
392 			String sectionSln = String.format("Section %s (%s)", section, sln);
393 			String sec = String
394 					.format("<a href=\"%s\">%s</a>",
395 							ConfigContext.getCurrentContextConfig()
396 									.getProperty("appserver.url")
397 									+ "/kr-krad/inquiry?methodToCall=start&viewId=CourseDetails-InquiryView&courseId="
398 									+ courseDetails.getCourseSummaryDetails()
399 											.getCourseId()
400 									+ "#"
401 									+ term.replace(".", "-") + "-" + sln,
402 							sectionSln);
403 			sectionAndSln.add(sec);
404 		}
405 		return sectionAndSln;
406 	}
407 
408 	/**
409 	 * returns the SLN for the given params
410 	 * 
411 	 * @param year
412 	 * @param term
413 	 * @param curriculum
414 	 * @param number
415 	 * @param section
416 	 * @return
417 	 */
418 	private String getSLN(String year, String term, String curriculum,
419 			String number, String section) {
420 		String sln = null;
421 		ActivityOfferingInfo activityOfferingInfo = new ActivityOfferingInfo();
422 		try {
423 			activityOfferingInfo = getCourseOfferingService()
424 					.getActivityOffering(
425 							year + "," + term + "," + curriculum + "," + number
426 									+ "," + section,
427 							KsapFrameworkServiceLocator.getContext()
428 									.getContextInfo());
429 		} catch (Exception e) {
430 			logger.error("could not load the ActivityOfferinInfo from SWS", e);
431 		}
432 		for (AttributeInfo attributeInfo : activityOfferingInfo.getAttributes()) {
433 			if (attributeInfo.getKey().equalsIgnoreCase("SLN")) {
434 				sln = attributeInfo.getValue();
435 				break;
436 			}
437 		}
438 		return sln;
439 	}
440 }