001package org.kuali.ole.select.controller;
002
003import org.apache.commons.lang3.StringUtils;
004import org.apache.log4j.Logger;
005import org.kuali.ole.OLEPropertyConstants;
006import org.kuali.ole.select.bo.OLEDonor;
007import org.kuali.ole.select.bo.OLELinkPurapDonor;
008import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
009import org.kuali.ole.select.document.OlePurchaseOrderDocument;
010import org.kuali.ole.select.form.OLEEncumberedReportForm;
011import org.kuali.ole.service.impl.OleLicenseRequestServiceImpl;
012import org.kuali.ole.sys.OLEConstants;
013import org.kuali.rice.core.api.config.property.ConfigContext;
014import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
015import org.kuali.rice.core.api.util.type.KualiDecimal;
016import org.kuali.rice.krad.service.BusinessObjectService;
017import org.kuali.rice.krad.service.KRADServiceLocator;
018import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
019import org.kuali.rice.krad.service.LookupService;
020import org.kuali.rice.krad.uif.UifConstants;
021import org.kuali.rice.krad.uif.UifParameters;
022import org.kuali.rice.krad.util.GlobalVariables;
023import org.kuali.rice.krad.util.KRADConstants;
024import org.kuali.rice.krad.web.controller.UifControllerBase;
025import org.kuali.rice.krad.web.form.UifFormBase;
026import org.springframework.stereotype.Controller;
027import org.springframework.validation.BindingResult;
028import org.springframework.web.bind.annotation.ModelAttribute;
029import org.springframework.web.bind.annotation.RequestMapping;
030import org.springframework.web.servlet.ModelAndView;
031
032import javax.servlet.http.HttpServletRequest;
033import javax.servlet.http.HttpServletResponse;
034import java.text.SimpleDateFormat;
035import java.util.*;
036
037/**
038 * Created with IntelliJ IDEA.
039 * User: chenchulakshmig
040 * Date: 12/6/13
041 * Time: 2:12 PM
042 * To change this template use File | Settings | File Templates.
043 */
044@Controller
045@RequestMapping(value = "/searchDonorEncumberedReportController")
046public class OLEEncumberedReportController extends UifControllerBase {
047
048    private BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
049    private static final Logger LOG = Logger.getLogger(OLEEResourceSearchController.class);
050    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(org.kuali.ole.OLEConstants.OLEEResourceRecord.CREATED_DATE_FORMAT);
051
052    private LookupService getLookupService() {
053        return KRADServiceLocatorWeb.getLookupService();
054    }
055
056    @Override
057    protected UifFormBase createInitialForm(HttpServletRequest httpServletRequest) {
058        return new OLEEncumberedReportForm();
059    }
060
061    @RequestMapping(params = "methodToCall=search")
062    public ModelAndView search(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
063                               HttpServletRequest request, HttpServletResponse response) throws Exception {
064        OLEEncumberedReportForm oleEncumberedReportForm = (OLEEncumberedReportForm) form;
065        List<OLEDonor> oleDonorList = new ArrayList<>();
066        List<OLELinkPurapDonor> oleLinkPurapDonors = new ArrayList<>();
067        if (StringUtils.isEmpty(oleEncumberedReportForm.getDonorCode())) {
068            oleLinkPurapDonors = (List<OLELinkPurapDonor>) KRADServiceLocator.getBusinessObjectService().findAll(OLELinkPurapDonor.class);
069        } else {
070            Map map = new HashMap();
071            map.put(OLEConstants.DONOR_CODE, oleEncumberedReportForm.getDonorCode());
072            List<OLEDonor> donorList = (List<OLEDonor>) KRADServiceLocator.getBusinessObjectService().findMatching(OLEDonor.class, map);
073            if (donorList != null && donorList.size() > 0) {
074                oleLinkPurapDonors = (List<OLELinkPurapDonor>) KRADServiceLocator.getBusinessObjectService().findMatching(OLELinkPurapDonor.class, map);
075            } else {
076                oleEncumberedReportForm.setEncumberedReportDocumentList(null);
077                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, org.kuali.ole.OLEConstants.DONOR_NOT_FOUND);
078                return getUIFModelAndView(oleEncumberedReportForm);
079            }
080        }
081        Map<String, List<Integer>> donorMap = new HashMap<>();
082        for (OLELinkPurapDonor oleLinkPurapDonor : oleLinkPurapDonors) {
083            Map poItemIdList = new HashMap();
084            poItemIdList.put("itemIdentifier", oleLinkPurapDonor.getPoItemId());
085            OlePurchaseOrderItem olePurchaseOrderItem = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderItem.class, poItemIdList);
086            if (oleLinkPurapDonor.getDonorCode() != null && olePurchaseOrderItem != null && olePurchaseOrderItem.getItemIdentifier() != null) {
087                if (!(oleEncumberedReportForm.getFromDate() == null && oleEncumberedReportForm.getToDate() == null)) {
088                    Map map = new HashMap();
089                    map.put(org.kuali.ole.OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
090                    OlePurchaseOrderDocument olePurchaseOrderDocument = boService.findByPrimaryKey(OlePurchaseOrderDocument.class, map);
091                    Date purchaseOrderDate = olePurchaseOrderDocument.getPurchaseOrderCreateTimestamp();
092                    try {
093                        String begin = null;
094                        if (oleEncumberedReportForm.getFromDate() != null) {
095                            begin = dateFormat.format(oleEncumberedReportForm.getFromDate());
096                        }
097                        String end = null;
098                        if (oleEncumberedReportForm.getToDate() != null) {
099                            end = dateFormat.format(oleEncumberedReportForm.getToDate());
100                        }
101                        boolean isValid = false;
102                        OleLicenseRequestServiceImpl oleLicenseRequestService = GlobalResourceLoader.getService(org.kuali.ole.OLEConstants.OleLicenseRequest.LICENSE_REQUEST_SERVICE);
103                        isValid = oleLicenseRequestService.validateDate(purchaseOrderDate, begin, end);
104                        if (isValid) {
105                            if (donorMap.containsKey(oleLinkPurapDonor.getDonorCode())) {
106                                donorMap.get(oleLinkPurapDonor.getDonorCode()).add(olePurchaseOrderItem.getItemIdentifier());
107                            } else {
108                                List<Integer> poItemIds = new ArrayList<>();
109                                poItemIds.add(olePurchaseOrderItem.getItemIdentifier());
110                                donorMap.put(oleLinkPurapDonor.getDonorCode(), poItemIds);
111                            }
112                        }
113                    } catch (Exception e) {
114                        LOG.error("Exception while calling the licenseRequest service" + e.getMessage());
115                        throw new RuntimeException(e);
116                    }
117                } else {
118                    if (donorMap.containsKey(oleLinkPurapDonor.getDonorCode())) {
119                        donorMap.get(oleLinkPurapDonor.getDonorCode()).add(olePurchaseOrderItem.getItemIdentifier());
120                    } else {
121                        List<Integer> poItemIds = new ArrayList<>();
122                        poItemIds.add(olePurchaseOrderItem.getItemIdentifier());
123                        donorMap.put(oleLinkPurapDonor.getDonorCode(), poItemIds);
124                    }
125                }
126            }
127        }
128        for (Object donorKey : donorMap.keySet()) {
129            OLEDonor oleDonor = new OLEDonor();
130            oleDonor.setDonorCode((String) donorKey);
131            Map map = new HashMap();
132            map.put(OLEConstants.DONOR_CODE, oleDonor.getDonorCode());
133            OLEDonor donor = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEDonor.class, map);
134            if (donor != null) {
135                oleDonor.setDonorAmount(donor.getDonorAmount() != null ? donor.getDonorAmount() : KualiDecimal.ZERO);
136                oleDonor.setDonorNote(donor.getDonorNote());
137                oleDonor.setDonorId(donor.getDonorId());
138            }
139            if (oleDonor.getDonorAmount() != null) {
140                KualiDecimal encAmt = KualiDecimal.ZERO;
141                KualiDecimal expAmt = KualiDecimal.ZERO;
142                List<Integer> poLineItemIds = (ArrayList) donorMap.get((String) donorKey);
143                for (Integer poLineItemId : poLineItemIds) {
144                    map.clear();
145                    map.put(org.kuali.ole.OLEConstants.BIB_ITEM_ID, poLineItemId);
146                    OlePurchaseOrderItem olePurchaseOrderItem = boService.findByPrimaryKey(OlePurchaseOrderItem.class, map);
147                    if (olePurchaseOrderItem.getItemOutstandingEncumberedAmount() != null) {
148                        encAmt = encAmt.add(olePurchaseOrderItem.getItemOutstandingEncumberedAmount().divide(new KualiDecimal(olePurchaseOrderItem.getOleDonors().size())));
149                    }
150                    if (olePurchaseOrderItem.getItemInvoicedTotalAmount() != null) {
151                        expAmt = expAmt.add(olePurchaseOrderItem.getItemInvoicedTotalAmount().divide(new KualiDecimal(olePurchaseOrderItem.getOleDonors().size())));
152                    }
153                }
154                oleDonor.setEncumberedAmount(encAmt);
155                oleDonor.setExpensedAmount(expAmt);
156            }
157            oleDonorList.add(oleDonor);
158        }
159        if (oleDonorList.size() == 0) {
160            oleEncumberedReportForm.setEncumberedReportDocumentList(null);
161            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, org.kuali.ole.OLEConstants.NO_RECORD_FOUND);
162        } else {
163            oleEncumberedReportForm.setEncumberedReportDocumentList(oleDonorList);
164        }
165        return getUIFModelAndView(oleEncumberedReportForm);
166    }
167
168    @RequestMapping(params = "methodToCall=clearSearch")
169    public ModelAndView clearSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
170                                    HttpServletRequest request, HttpServletResponse response) {
171        OLEEncumberedReportForm oleEncumberedReportForm = (OLEEncumberedReportForm) form;
172        oleEncumberedReportForm.setDonorCode(null);
173        oleEncumberedReportForm.setFromDate(null);
174        oleEncumberedReportForm.setToDate(null);
175        oleEncumberedReportForm.setEncumberedReportDocumentList(null);
176        return getUIFModelAndView(oleEncumberedReportForm);
177    }
178
179    @RequestMapping(params = "methodToCall=cancel")
180    public ModelAndView cancel(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
181                               HttpServletRequest request, HttpServletResponse response) {
182        String baseUrl = ConfigContext.getCurrentContextConfig().getProperty(OLEPropertyConstants.OLE_URL_BASE);
183        String url = baseUrl + "/portal.do";
184        Properties props = new Properties();
185        props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.REFRESH);
186        if (org.apache.commons.lang.StringUtils.isNotBlank(form.getReturnFormKey())) {
187            props.put(UifParameters.FORM_KEY, form.getReturnFormKey());
188        }
189        return performRedirect(form, url, props);
190    }
191
192}