001package org.kuali.student.enrollment.class2.autogen.controller;
002
003import org.apache.commons.lang.BooleanUtils;
004import org.apache.commons.lang.StringUtils;
005import org.kuali.rice.core.api.criteria.PredicateFactory;
006import org.kuali.rice.core.api.criteria.QueryByCriteria;
007import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
008import org.kuali.rice.kim.api.identity.Person;
009import org.kuali.rice.krad.uif.UifConstants;
010import org.kuali.rice.krad.uif.UifParameters;
011import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
012import org.kuali.rice.krad.util.GlobalVariables;
013import org.kuali.rice.krad.util.KRADConstants;
014import org.kuali.student.enrollment.class2.autogen.form.ARGCourseOfferingManagementForm;
015import org.kuali.student.enrollment.class2.courseoffering.dto.ActivityOfferingWrapper;
016import org.kuali.student.enrollment.class2.courseoffering.dto.CourseOfferingEditWrapper;
017import org.kuali.student.enrollment.class2.courseoffering.dto.CourseOfferingListSectionWrapper;
018import org.kuali.student.enrollment.class2.courseoffering.dto.CourseOfferingWrapper;
019import org.kuali.student.enrollment.class2.courseoffering.dto.RegistrationGroupWrapper;
020import org.kuali.student.enrollment.class2.courseoffering.service.adapter.AutogenRegGroupServiceAdapter;
021import org.kuali.student.enrollment.class2.courseoffering.service.util.RegistrationGroupUtil;
022import org.kuali.student.enrollment.class2.courseoffering.util.CourseOfferingResourceLoader;
023import org.kuali.student.enrollment.class2.autogen.service.ARGCourseOfferingManagementViewHelperService;
024import org.kuali.student.enrollment.class2.autogen.util.ARGToolbarUtil;
025import org.kuali.student.enrollment.courseoffering.dto.ActivityOfferingClusterInfo;
026import org.kuali.student.enrollment.courseoffering.dto.ActivityOfferingSetInfo;
027import org.kuali.student.enrollment.courseoffering.dto.CourseOfferingInfo;
028import org.kuali.student.enrollment.courseoffering.dto.FormatOfferingInfo;
029import org.kuali.student.enrollment.courseoffering.dto.RegistrationGroupInfo;
030import org.kuali.student.enrollment.courseoffering.service.CourseOfferingService;
031import org.kuali.student.enrollment.courseofferingset.dto.SocInfo;
032import org.kuali.student.enrollment.courseofferingset.service.CourseOfferingSetService;
033import org.kuali.student.enrollment.uif.form.KSUifForm;
034import org.kuali.student.r2.common.constants.CommonServiceConstants;
035import org.kuali.student.r2.common.dto.ContextInfo;
036import org.kuali.student.r2.common.exceptions.DoesNotExistException;
037import org.kuali.student.r2.common.exceptions.InvalidParameterException;
038import org.kuali.student.r2.common.exceptions.MissingParameterException;
039import org.kuali.student.r2.common.exceptions.OperationFailedException;
040import org.kuali.student.r2.common.exceptions.PermissionDeniedException;
041import org.kuali.student.r2.common.util.ContextUtils;
042import org.kuali.student.r2.common.util.constants.CourseOfferingServiceConstants;
043import org.kuali.student.r2.common.util.constants.CourseOfferingSetServiceConstants;
044import org.kuali.student.r2.core.acal.service.AcademicCalendarService;
045import org.kuali.student.r2.core.class1.state.service.StateService;
046import org.kuali.student.r2.core.class1.type.dto.TypeInfo;
047import org.kuali.student.r2.core.class1.type.service.TypeService;
048import org.kuali.student.r2.core.constants.AcademicCalendarServiceConstants;
049import org.kuali.student.r2.core.organization.dto.OrgInfo;
050import org.kuali.student.r2.core.organization.service.OrganizationService;
051import org.kuali.student.r2.lum.lrc.dto.ResultValuesGroupInfo;
052import org.kuali.student.r2.lum.lrc.service.LRCService;
053
054import javax.xml.namespace.QName;
055import java.util.ArrayList;
056import java.util.Collection;
057import java.util.HashMap;
058import java.util.List;
059import java.util.Map;
060import java.util.Properties;
061
062/**
063 * Created with IntelliJ IDEA.
064 * User: aliabad4
065 * Date: 3/4/13
066 * Time: 3:27 PM
067 * To change this template use File | Settings | File Templates.
068 */
069public class ARGUtil {
070    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ARGUtil.class);
071
072    private static ARGCourseOfferingManagementViewHelperService viewHelperService;
073    //don't think we can have two viewHelperService here
074//    private static RegistrationGroupManagementViewHelperService regViewHelperService;
075    private static OrganizationService organizationService;
076    private static CourseOfferingSetService socService;
077    private static StateService stateService;
078    private static LRCService lrcService;
079    private static TypeService typeService;
080    private static AcademicCalendarService academicCalendarService;
081    private static AutogenRegGroupServiceAdapter argServiceAdapter;
082
083
084    public static CourseOfferingService getCourseOfferingService() {
085        return CourseOfferingResourceLoader.loadCourseOfferingService();
086    }
087
088    public static ARGCourseOfferingManagementViewHelperService getViewHelperService(ARGCourseOfferingManagementForm theForm) {
089
090        if (viewHelperService == null) {
091            if (theForm.getView().getViewHelperServiceClass() != null) {
092                viewHelperService = (ARGCourseOfferingManagementViewHelperService) theForm.getView().getViewHelperService();
093            } else {
094                viewHelperService = (ARGCourseOfferingManagementViewHelperService) theForm.getPostedView().getViewHelperService();
095            }
096        }
097
098        return viewHelperService;
099    }
100
101    public static OrganizationService getOrganizationService() {
102        if (organizationService == null) {
103            organizationService = (OrganizationService) GlobalResourceLoader.getService(new QName(CommonServiceConstants.REF_OBJECT_URI_GLOBAL_PREFIX + "organization", "OrganizationService"));
104
105        }
106        return organizationService;
107    }
108
109    public static StateService getStateService() {
110        if (stateService == null) {
111            stateService = CourseOfferingResourceLoader.loadStateService();
112        }
113        return stateService;
114    }
115
116    public static LRCService getLrcService() {
117        if (lrcService == null) {
118            lrcService = CourseOfferingResourceLoader.loadLrcService();
119        }
120        return lrcService;
121    }
122
123    public static TypeService getTypeService() {
124        if (typeService == null) {
125            typeService = CourseOfferingResourceLoader.loadTypeService();
126        }
127        return typeService;
128    }
129
130    public static AcademicCalendarService getAcademicCalendarService() {
131        if (academicCalendarService == null) {
132            academicCalendarService = (AcademicCalendarService) GlobalResourceLoader.getService(new QName(AcademicCalendarServiceConstants.NAMESPACE, AcademicCalendarServiceConstants.SERVICE_NAME_LOCAL_PART));
133        }
134        return academicCalendarService;
135    }
136
137    public static CourseOfferingSetService getSocService() {
138        // If it hasn't been set by Spring, then look it up by GlobalResourceLoader
139        if (socService == null) {
140            socService = (CourseOfferingSetService) GlobalResourceLoader.getService(new QName(CourseOfferingSetServiceConstants.NAMESPACE,
141                    CourseOfferingSetServiceConstants.SERVICE_NAME_LOCAL_PART));
142        }
143        return socService;
144    }
145
146    public static AutogenRegGroupServiceAdapter getArgServiceAdapter() {
147        if (argServiceAdapter == null) {
148            argServiceAdapter = (AutogenRegGroupServiceAdapter) GlobalResourceLoader.getService(new QName("http://student.kuali.org/wsdl/autogenRegistrationGroupAppLayer", "AutogenRegGroupServiceAdapter"));
149        }
150        return argServiceAdapter;
151    }
152
153    public static String getSocState(String termCode) {
154        ContextInfo context = new ContextInfo();
155        try {
156            List<String> socIds = getSocService().getSocIdsByTerm(termCode, context);
157            if (socIds != null) {
158                if (socIds.isEmpty()) {
159                    return null;
160                }
161                List<SocInfo> targetSocs = getSocService().getSocsByIds(socIds, context);
162                for (SocInfo soc : targetSocs) {
163                    if (soc.getTypeKey().equals(CourseOfferingSetServiceConstants.MAIN_SOC_TYPE_KEY)) {
164                        return soc.getStateKey().substring(soc.getStateKey().lastIndexOf('.') + 1);
165                    }
166                }
167            }
168            return null;
169        } catch (Exception e) {
170            return null;
171        }
172
173    }
174
175    public static boolean checkEditViewAuthz(ARGCourseOfferingManagementForm theForm) {
176        Person user = GlobalVariables.getUserSession().getPerson();
177        return theForm.getView().getAuthorizer().canEditView(theForm.getView(), theForm, user);
178    }
179
180    public static void prepareManageAOsModelAndView(ARGCourseOfferingManagementForm form, CourseOfferingListSectionWrapper selectedCO) throws Exception {
181
182        CourseOfferingWrapper currentCOWrapper = new CourseOfferingWrapper(selectedCO.isCrossListed(),selectedCO.getCourseOfferingCode(),selectedCO.getCourseOfferingDesc(),selectedCO.getAlternateCOCodes(),selectedCO.getCourseOfferingId());
183        form.setSubjectCode(selectedCO.getSubjectArea());
184        prepare_AOs_RGs_AOCs_Lists(form, currentCOWrapper);
185    }
186
187    public static void prepare_AOs_RGs_AOCs_Lists (ARGCourseOfferingManagementForm form, CourseOfferingWrapper currentCOWrapper) throws Exception {
188        currentCOWrapper.setTerm( form.getTermInfo() );
189
190        CourseOfferingInfo coInfo = getCourseOfferingService().getCourseOffering(currentCOWrapper.getCourseOfferingId(),ContextUtils.createDefaultContextInfo());
191        currentCOWrapper.setCourseOfferingInfo(coInfo);
192
193        //set the ownerCode if not set
194        if (currentCOWrapper.getOwnerCode()==null ||currentCOWrapper.getOwnerCode().equals("") ) {
195            for (CourseOfferingListSectionWrapper courseOfferingListSectionWrapper : form.getCourseOfferingResultList()) {
196               if (courseOfferingListSectionWrapper.getCourseOfferingCode().equals(currentCOWrapper.getCourseOfferingCode())) {
197                   currentCOWrapper.setOwnerCode(courseOfferingListSectionWrapper.getOwnerCode());
198                   break;
199               }
200            }
201        }
202
203        ContextInfo contextInfo =  ContextUtils.createDefaultContextInfo();
204        List<String> orgIds = coInfo.getUnitsDeploymentOrgIds();
205        if(orgIds !=null && !orgIds.isEmpty()){
206            OrgInfo org = getOrganizationService().getOrg(orgIds.get(0), contextInfo);
207            currentCOWrapper.setCoOwningDeptName(org.getShortName());
208            // managing multiple orgs
209            String orgIDs = "";
210            for (String orgId : orgIds) {
211                orgIDs = orgIDs + orgId + ",";
212            }
213            if (orgIDs.length() > 0) {
214                form.setAdminOrg(orgIDs.substring(0, orgIDs.length()- 1));
215            }
216        }
217
218        form.setCurrentCourseOfferingWrapper(currentCOWrapper);
219        form.setInputCode(currentCOWrapper.getCourseOfferingCode());
220
221        form.setFormatIdForNewAO(null);
222        form.setFormatOfferingIdForNewAO(null);
223        form.setActivityIdForNewAO(null);
224        form.setNoOfActivityOfferings(null);
225        form.setPrivateClusterNamePopover("");
226        form.setPublishedClusterNamePopover("");
227
228        getViewHelperService(form).loadPreviousAndNextCourseOffering(form);
229
230        /* commented out by bonnie, replace it with a new method
231
232//        getViewHelperService(form).loadActivityOfferingsByCourseOffering(coInfo, form);
233        //get cluster info and add to the form
234        List<String> foIds = new ArrayList<String>();
235        List<ActivityOfferingClusterInfo> clusterInfos = new ArrayList<ActivityOfferingClusterInfo>();
236        for(int i=0; i < form.getActivityWrapperList().size(); i++){  //parse through AOs
237            String foId = form.getActivityWrapperList().get(i).getFormatOffering().getId();
238            String aoId = form.getActivityWrapperList().get(i).getId();
239            if (!foIds.contains(foId)) {   //get AOC if not done yet
240                foIds.add(foId);
241                clusterInfos = getCourseOfferingService().getActivityOfferingClustersByFormatOffering(foId, contextInfo);
242            }
243            for (int j=0; j < clusterInfos.size(); j++){  //parse through AOs and assign aocs to ao wrapper
244                for(ActivityOfferingSetInfo aosInfo : clusterInfos.get(j).getActivityOfferingSets()){
245                    if (aosInfo.getActivityOfferingIds().contains(aoId)) {   //add aocWrapper to aoWrapper
246                        form.getActivityWrapperList().get(i).setAoClusterName(clusterInfos.get(j).getName());
247                        form.getActivityWrapperList().get(i).setAoClusterID(clusterInfos.get(j).getId());
248                        //Should you need to load AOCs - uncomment
249                        //form.getActivityWrapperList().get(i).setAoCluster(clusterInfos.get(j));
250                    }
251                }
252            }
253            form .setFoId2aoTypeMap(foIds);
254            form.setAoCount(i+1);
255        }
256        */
257
258        getViewHelperService(form).build_AOs_RGs_AOCs_Lists_For_TheCourseOffering(form, currentCOWrapper);
259
260        //Performance fix KSENROLL-6102 the foids are now loaded in ARGCourseOfferingManagementViewHelperServiceImpl.build_AOs_RGs_AOCs_Lists_For_TheCourseOffering
261        //delete this code when performance work is complete
262//        List<FormatOfferingInfo> formatOfferingList = getCourseOfferingService().getFormatOfferingsByCourseOffering(coInfo.getId(),ContextUtils.createDefaultContextInfo());
263//        List<String> foIds = new ArrayList<String>();
264//        for(FormatOfferingInfo foInfo:formatOfferingList){
265//            foIds.add(foInfo.getId());
266//        }
267//        form.setFoId2aoTypeMap(foIds);
268//        form.setAoCount(form.getActivityWrapperList().size());
269//        ARGUtil.loadRegistrationGroupsByCourseOffering(foIds, form);
270        
271
272        //turn off authz for now
273//        form.setEditAuthz(checkEditViewAuthz(form));
274
275        ARGToolbarUtil.processAoToolbarForUser(form.getActivityWrapperList(), form);
276    }
277
278    /**
279     * Grab all the registration groups for the list of FO ids passed in and addes wrapped RGs back to the form
280     * @param foIds list of Format offering ids
281     * @param form The form
282     * @throws InvalidParameterException
283     * @throws MissingParameterException
284     * @throws DoesNotExistException
285     * @throws PermissionDeniedException
286     * @throws OperationFailedException
287     */
288    private static void loadRegistrationGroupsByCourseOffering(List<String> foIds, ARGCourseOfferingManagementForm form) throws InvalidParameterException, MissingParameterException, DoesNotExistException, PermissionDeniedException, OperationFailedException {
289        List<RegistrationGroupWrapper> wrappedRegGroups = new ArrayList<RegistrationGroupWrapper>();
290
291        HashMap<String, ActivityOfferingWrapper> filteredAOsHM = new HashMap<String, ActivityOfferingWrapper>();
292        for (ActivityOfferingWrapper wrapper : form.getActivityWrapperList()) {
293            filteredAOsHM.put(wrapper.getAoInfo().getId(), wrapper);
294        }
295
296        int index = 0;
297        //Grab the registration groups from the course
298        for(String foId:foIds){
299            List<RegistrationGroupInfo> regGroups = getCourseOfferingService().getRegistrationGroupsByFormatOffering(foId, ContextUtils.createDefaultContextInfo());
300            //Sort the AOs in the reg group
301            _fixAoIdOrderingInRegGroups(regGroups);
302
303            //Wrap the reg groups and put in the form
304            for(RegistrationGroupInfo rgInfo:regGroups){
305                RegistrationGroupWrapper rgWrapper = new RegistrationGroupWrapper();
306                rgWrapper.setRgInfo(rgInfo);
307                String aoActivityCodeText = "", aoStateNameText = "", aoTypeNameText = "", aoInstructorText = "", aoMaxEnrText = "", aoEditLinkText = "";
308                Integer minEnrollment=null;
309                for (String aoID : rgInfo.getActivityOfferingIds()) {
310                    ActivityOfferingWrapper aoWrapper = filteredAOsHM.get(aoID);
311
312                    String cssClass = (aoWrapper.getAoInfo().getScheduleId() == null ? "uif-scheduled-dl" : "uif-actual-dl");
313                    if (aoWrapper.getAoInfo().getActivityCode() != null && !aoWrapper.getAoInfo().getActivityCode().equalsIgnoreCase("")) {
314                        aoActivityCodeText = aoActivityCodeText + aoWrapper.getAoInfo().getActivityCode() + "<br/>";
315                    }
316                    if (aoWrapper.getStateName() != null && !aoWrapper.getStateName().equalsIgnoreCase("")) {
317                        aoStateNameText = aoStateNameText + aoWrapper.getStateName() + "<br/>";
318                    }
319                    if (aoWrapper.getTypeName() != null && !aoWrapper.getTypeName().equalsIgnoreCase("")) {
320                        aoTypeNameText = aoTypeNameText + aoWrapper.getTypeName() + "<br/>";
321                    }
322                    if (aoWrapper.getFirstInstructorDisplayName() != null && !aoWrapper.getFirstInstructorDisplayName().equalsIgnoreCase("")) {
323                        aoInstructorText = aoInstructorText + aoWrapper.getFirstInstructorDisplayName() + "<br/>";
324                    }
325                    if (aoWrapper.getAoInfo().getMaximumEnrollment() != null) {
326                        Integer maximumEnrollment = aoWrapper.getAoInfo().getMaximumEnrollment();
327                        aoMaxEnrText = aoMaxEnrText + Integer.toString(maximumEnrollment) + "<br/>";
328                        //Set the minimum enrollment as the smalled max enr of each AO
329                        if(minEnrollment==null || (maximumEnrollment!=null && maximumEnrollment<minEnrollment)){
330                            minEnrollment = maximumEnrollment;
331                        }
332                    }
333
334                    if(aoWrapper.getStartTimeDisplay() != null){
335                        rgWrapper.setStartTimeDisplay(aoWrapper.getStartTimeDisplay(), true, cssClass);
336                    }
337
338                    if(aoWrapper.getEndTimeDisplay() != null){
339                        rgWrapper.setEndTimeDisplay(aoWrapper.getEndTimeDisplay(), true, cssClass);
340                    }
341
342                    if(aoWrapper.getBuildingName() != null){
343                        rgWrapper.setBuildingName(aoWrapper.getBuildingName(), true, cssClass);
344                    }
345
346                    if(aoWrapper.getRoomName() != null){
347                        rgWrapper.setRoomName(aoWrapper.getRoomName(), true, cssClass);
348                    }
349
350                    if(aoWrapper.getDaysDisplayName() != null){
351                        rgWrapper.setDaysDisplayName(aoWrapper.getDaysDisplayName(), true, cssClass);
352                    }
353
354                    //Manually add links that mirror the functionality of KRAD action links. Pass in the aoID as an action param for the controller to use
355                    aoEditLinkText += "<a onclick=\"actionInvokeHandler(this);\" class=\"uif-action uif-actionLink uif-navigationActionLink uif-boxLayoutVerticalItem\"" +
356                            " tabindex=\"0\"" +
357                            " style=\"margin-bottom:0px;\"" +
358                            " data-ajaxreturntype=\"update-component\"" +
359                            " data-loadingmessage=\"Loading...\"" +
360                            " data-disableblocking=\"false\"" +
361                            " data-ajaxsubmit=\"false\"" +
362                            " data-refreshid=\"KS-CourseOfferingManagement-AllRegistrationGroupsForACourseOffering\"" +
363                            " data-validate=\"false\"" +
364                            " data-submit-data='{\"methodToCall\":\"edit\"," +
365                                               "\"actionParameters\\[selectedCollectionPath\\]\":\"rgResultList\"," +
366                                               "\"actionParameters\\[selectedLineIndex\\]\":\""+index+"\"," +
367                                               "\"actionParameters\\[aoId\\]\":\""+aoID+"\"," +
368                                               "\"showHistory\":\"false\"," +
369                                               "\"showHome\":\"false\"," +
370                                               "\"jumpToId\":\"KS-CourseOfferingManagement-AllRegistrationGroupsForACourseOffering\"}'" +
371                            ">Edit</a>";
372                    rgWrapper.setAoClusterName(aoWrapper.getAoClusterName());
373                }
374                if (aoActivityCodeText.length() > 0) {
375                    aoActivityCodeText = aoActivityCodeText.substring(0, aoActivityCodeText.lastIndexOf("<br/>"));
376                }
377                if (aoStateNameText.length() > 0) {
378                    aoStateNameText = aoStateNameText.substring(0, aoStateNameText.lastIndexOf("<br/>"));
379                }
380                if (aoTypeNameText.length() > 0) {
381                    aoTypeNameText = aoTypeNameText.substring(0, aoTypeNameText.lastIndexOf("<br/>"));
382                }
383                if (aoInstructorText.length() > 0) {
384                    aoInstructorText = aoInstructorText.substring(0, aoInstructorText.lastIndexOf("<br/>"));
385                }
386                if (aoMaxEnrText.length() > 0) {
387                    aoMaxEnrText = aoMaxEnrText.substring(0, aoMaxEnrText.lastIndexOf("<br/>"));
388                }
389
390                rgWrapper.setStateKey(rgInfo.getStateKey(), getStateService().getState(rgInfo.getStateKey(), ContextUtils.createDefaultContextInfo()).getName());
391                rgWrapper.setAoEditLink(aoEditLinkText);
392                if (minEnrollment!=null) {
393                    rgWrapper.setRgMaxEnrText(Integer.toString(minEnrollment));
394                }
395                rgWrapper.setAoActivityCodeText(aoActivityCodeText);
396                rgWrapper.setAoStateNameText(aoStateNameText);
397                rgWrapper.setAoTypeNameText(aoTypeNameText);
398                rgWrapper.setAoInstructorText(aoInstructorText);
399                rgWrapper.setAoMaxEnrText(aoMaxEnrText);
400                wrappedRegGroups.add(rgWrapper);
401                index++;
402            }
403        }
404        form.setRgResultList(wrappedRegGroups);
405    }
406
407    /*
408     *  Determine if any COs were check-boxed.
409     *  @return True if any COs where selected. Otherwise, false.
410     */
411    public static Object getSelectedObject(KSUifForm theForm, String actionLink) {
412        String selectedCollectionPath = theForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
413        if (StringUtils.isBlank(selectedCollectionPath)) {
414            throw new RuntimeException("Selected collection was not set for " + actionLink);
415        }
416
417        int selectedLineIndex = -1;
418        String selectedLine = theForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX);
419        if (StringUtils.isNotBlank(selectedLine)) {
420            selectedLineIndex = Integer.parseInt(selectedLine);
421        }
422
423        if (selectedLineIndex == -1) {
424            throw new RuntimeException("Selected line index was not set");
425        }
426
427        Collection<Object> collection = ObjectPropertyUtils.getPropertyValue(theForm, selectedCollectionPath);
428        Object selectedObject;
429        selectedObject = ((List<Object>) collection).get(selectedLineIndex);
430
431        return selectedObject;
432    }
433
434    public static void reloadCourseOfferings(ARGCourseOfferingManagementForm theForm) throws Exception {
435        getViewHelperService(theForm).loadCourseOfferingsByTermAndCourseCode(theForm.getTermInfo().getId(), theForm.getInputCode(), theForm);
436        //getViewHelperService(theForm).loadCourseOfferingsByTermAndSubjectCode(theForm.getTermInfo().getId(), theForm.getInputCode(),theForm);
437        ARGToolbarUtil.processCoToolbarForUser(theForm.getCourseOfferingResultList(), theForm);
438    }
439
440    public static void reloadTheCourseOfferingWithAOs_RGs_Clusters(ARGCourseOfferingManagementForm theForm) throws Exception {
441        // Reload the AOs
442        CourseOfferingInfo theCourseOffering = theForm.getCurrentCourseOfferingWrapper().getCourseOfferingInfo();
443//        loadActivityOfferings(theCourseOffering, theForm);
444
445        CourseOfferingWrapper coWrapper = new CourseOfferingWrapper(theCourseOffering);
446        getViewHelperService(theForm).build_AOs_RGs_AOCs_Lists_For_TheCourseOffering(theForm, coWrapper);
447
448//        List<FormatOfferingInfo> foList = getCourseOfferingService().getFormatOfferingsByCourseOffering(theCourseOffering.getId(), ContextUtils.createDefaultContextInfo());
449//        List<String> foIDs = new ArrayList<String>();
450//        for (FormatOfferingInfo fo : foList) {
451//            foIDs.add(fo.getId());
452//        }
453//        loadRegistrationGroupsByCourseOffering(foIDs, theForm);
454
455        getViewHelperService(theForm).loadPreviousAndNextCourseOffering(theForm);
456
457        ARGToolbarUtil.processAoToolbarForUser(theForm.getActivityWrapperList(), theForm);
458    }
459
460    public static void loadActivityOfferings(CourseOfferingInfo theCourseOffering, ARGCourseOfferingManagementForm theForm) throws Exception {
461        ARGUtil.getViewHelperService(theForm).loadActivityOfferingsByCourseOffering(theCourseOffering, theForm);
462        ARGToolbarUtil.processAoToolbarForUser(theForm.getActivityWrapperList(), theForm);
463    }
464
465
466    public static String getGradingOption(String gradingOptionId) throws Exception {
467        String gradingOption = "";
468        if (StringUtils.isNotBlank(gradingOptionId)) {
469            ResultValuesGroupInfo rvg = getLrcService().getResultValuesGroup(gradingOptionId, ContextUtils.createDefaultContextInfo());
470            if (rvg != null && StringUtils.isNotBlank(rvg.getName())) {
471                gradingOption = rvg.getName();
472            }
473        }
474
475        return gradingOption;
476    }
477
478    public static String getOrgNameDescription(String orgShortName) {
479        String shortName = "shortName";
480        String longName = "";
481
482        QueryByCriteria.Builder qBuilder = QueryByCriteria.Builder.create();
483        if (StringUtils.isNotBlank(orgShortName) && !orgShortName.isEmpty()) {
484            qBuilder.setPredicates(PredicateFactory.or(
485                    PredicateFactory.equal(shortName, orgShortName)));
486        } else {
487            throw new RuntimeException("Org short name is null!");
488        }
489        try {
490            QueryByCriteria query = qBuilder.build();
491
492            OrganizationService organizationService = getOrganizationService();
493
494            java.util.List<OrgInfo> orgInfos = organizationService.searchForOrgs(query, ContextUtils.createDefaultContextInfo());
495            if (!orgInfos.isEmpty()) {
496                longName = orgInfos.get(0).getLongName();
497            }
498        } catch (Exception e) {
499            throw new RuntimeException("Error! No long name description found.", e);
500        }
501        return longName;
502    }
503
504    public static Properties _buildCOURLParameters(CourseOfferingInfo courseOfferingInfo, String methodToCall) {
505        Properties props = new Properties();
506        props.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, methodToCall);
507        props.put("courseOfferingInfo.id", courseOfferingInfo.getId());
508        props.put(KRADConstants.DATA_OBJECT_CLASS_ATTRIBUTE, CourseOfferingEditWrapper.class.getName());
509        props.put(UifConstants.UrlParams.SHOW_HOME, BooleanUtils.toStringTrueFalse(false));
510        return props;
511    }
512
513
514    public static void _fixAoIdOrderingInRegGroups(List<RegistrationGroupInfo> rgInfos)
515            throws InvalidParameterException, MissingParameterException, DoesNotExistException,
516            OperationFailedException, PermissionDeniedException {
517
518        for (RegistrationGroupInfo regGroup : rgInfos) {
519            Map<String, String> aoIdsToAoTypes =
520                    RegistrationGroupUtil.createAoIdsToAoTypesMap(regGroup.getActivityOfferingIds(), getCourseOfferingService(), ContextUtils.createDefaultContextInfo());
521            RegistrationGroupUtil.orderActivityOfferingIdsInRegistrationGroup(regGroup, aoIdsToAoTypes);
522        }
523    }
524
525    public static boolean _isClusterUnique(String formatOfferingId, String privateName) throws Exception{
526        //Build up a term search criteria
527        QueryByCriteria.Builder qbcBuilder = QueryByCriteria.Builder.create();
528        qbcBuilder.setPredicates(PredicateFactory.and(
529                PredicateFactory.equalIgnoreCase("privateName", privateName),
530                PredicateFactory.equal("formatOfferingId", formatOfferingId)));
531        QueryByCriteria criteria = qbcBuilder.build();
532
533        List<ActivityOfferingClusterInfo> aoClusterList = getCourseOfferingService().searchForActivityOfferingClusters(criteria, ContextUtils.createDefaultContextInfo());
534        return aoClusterList.size() <= 0;
535    }
536
537    public static boolean _isClusterUniqueWithinCO(ARGCourseOfferingManagementForm form, String courseOfferingId, String privateName) throws Exception{
538        List<String> foIds = new ArrayList<String>();
539        //fetch all the formatOfferingIds associated with the given courseOfferingId
540        //For performance, if FOIds are already in the form, use it (most likely it is). Otherwise, fetch FOs by COId
541        if (form.getFoId2aoTypeMap()==null || form.getFoId2aoTypeMap().isEmpty()) {
542            List<FormatOfferingInfo> formatOfferingList = getCourseOfferingService().getFormatOfferingsByCourseOffering(courseOfferingId,ContextUtils.createDefaultContextInfo());
543            for(FormatOfferingInfo foInfo:formatOfferingList){
544                foIds.add(foInfo.getId());
545            }
546        } else {
547            foIds = new ArrayList<String>(form.getFoId2aoTypeMap().keySet());
548        }
549
550        //Build up a term search criteria
551        if (foIds!=null && !foIds.isEmpty()) {
552            QueryByCriteria.Builder qbcBuilder = QueryByCriteria.Builder.create();
553            qbcBuilder.setPredicates(PredicateFactory.and(
554                    PredicateFactory.in("formatOfferingId", foIds.toArray()),
555                    PredicateFactory.equalIgnoreCase("privateName", privateName)));
556            QueryByCriteria criteria = qbcBuilder.build();
557
558            List<ActivityOfferingClusterInfo> aoClusterList = getCourseOfferingService().searchForActivityOfferingClusters(criteria, ContextUtils.createDefaultContextInfo());
559            return aoClusterList.size() <= 0;
560        }
561
562        return true;
563    }
564
565
566    public static ActivityOfferingClusterInfo _buildEmptyAOCluster (String formatOfferingId, String privateName, String publishedName){
567        ActivityOfferingClusterInfo emptyCluster = new ActivityOfferingClusterInfo();
568        emptyCluster.setTypeKey(CourseOfferingServiceConstants.AOC_ROOT_TYPE_KEY);
569        emptyCluster.setStateKey(CourseOfferingServiceConstants.AOC_ACTIVE_STATE_KEY);
570        emptyCluster.setPrivateName(privateName);
571        emptyCluster.setName(publishedName);
572        emptyCluster.setFormatOfferingId(formatOfferingId);
573        List<ActivityOfferingSetInfo> activityOfferingSets = new ArrayList<ActivityOfferingSetInfo>();
574        emptyCluster.setActivityOfferingSets(activityOfferingSets);
575        return emptyCluster;
576    }
577
578    //From Bonnie: Do we still need this method?
579//    public static ActivityOfferingClusterInfo _buildDefaultAOCluster (String formatOfferingId,
580//                                                                      ARGCourseOfferingManagementForm theForm) throws Exception{
581//        ActivityOfferingClusterInfo defaultCluster = _buildEmptyAOCluster(formatOfferingId,"Default Cluster", "Default Cluster");
582//        defaultCluster = getCourseOfferingService().createActivityOfferingCluster(formatOfferingId,
583//                defaultCluster.getTypeKey(), defaultCluster, ContextUtils.createDefaultContextInfo());
584//        List<ActivityOfferingWrapper> filteredAOs = theForm.getFilteredUnassignedAOsForSelectedFO();
585//        defaultCluster = _updateAOSets(filteredAOs,defaultCluster,formatOfferingId);
586//        return defaultCluster;
587//    }
588
589    public static ActivityOfferingClusterInfo _updateAOSets(List<ActivityOfferingWrapper> aoWrapperList,
590                                                       ActivityOfferingClusterInfo clusterInfo, String formatOfferingId) throws Exception {
591        List<ActivityOfferingSetInfo> aoSetInfoList = clusterInfo.getActivityOfferingSets();
592        for (ActivityOfferingWrapper aoWrapper:aoWrapperList){
593            try {
594                TypeInfo typeInfo = getTypeService().getType(aoWrapper.getAoInfo().getTypeKey(), ContextUtils.createDefaultContextInfo());
595                aoWrapper.setTypeKey(typeInfo.getKey());
596                aoWrapper.setTypeName(typeInfo.getName());
597            } catch (Exception e) {
598                throw new RuntimeException(e);
599            }
600
601            String aoTypeKey = aoWrapper.getTypeKey();
602            for(ActivityOfferingSetInfo aoSetInfo: aoSetInfoList){
603                if(aoSetInfo.getActivityOfferingType().equals(aoTypeKey)){
604                    List<String> aoIds = aoSetInfo.getActivityOfferingIds();
605                    aoIds.add(aoWrapper.getAoInfo().getId());
606                    aoSetInfo.setActivityOfferingIds(aoIds);
607                    break;
608                }
609            }
610            clusterInfo.setActivityOfferingSets(aoSetInfoList);
611        }
612        clusterInfo = getCourseOfferingService().updateActivityOfferingCluster(formatOfferingId,
613                clusterInfo.getId(), clusterInfo, ContextUtils.createDefaultContextInfo());
614        return clusterInfo;
615    }
616
617    public static boolean _clusterForFormatOfferingValidation (FormatOfferingInfo formatOfferingInfo, ContextInfo context) {
618        try {
619            if (formatOfferingInfo.getActivityOfferingTypeKeys()!=null && formatOfferingInfo.getActivityOfferingTypeKeys().size()>1) {
620                return true;
621            } else if (formatOfferingInfo.getActivityOfferingTypeKeys()!=null && formatOfferingInfo.getActivityOfferingTypeKeys().size()==1) {
622                QueryByCriteria.Builder qbcBuilder = QueryByCriteria.Builder.create();
623                qbcBuilder.setPredicates(PredicateFactory.equal("formatOfferingId", formatOfferingInfo.getId()));
624                QueryByCriteria criteria = qbcBuilder.build();
625
626                List<String> aoClusterIds = getCourseOfferingService().searchForActivityOfferingClusterIds(criteria, context);
627                if (aoClusterIds!=null && aoClusterIds.size()>=1) {
628                    return false;
629                } else {
630                    return true;
631                }
632            } else {
633                return false;
634            }
635        } catch (Exception e) {
636            throw new RuntimeException(e);
637        }
638
639    }
640
641}