001/*
002 * Copyright 2011 The Kuali Foundation.
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.ole.select.document.web;
017
018import org.apache.struts.action.ActionForm;
019import org.apache.struts.action.ActionForward;
020import org.apache.struts.action.ActionMapping;
021import org.kuali.ole.batch.service.OLEClaimNoticeService;
022import org.kuali.ole.select.OleSelectConstant;
023import org.kuali.ole.select.businessobject.OleLineItemReceivingItem;
024import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
025import org.kuali.ole.select.businessobject.OleReceiptStatus;
026import org.kuali.ole.select.document.OleLineItemReceivingDocument;
027import org.kuali.ole.select.document.OleReceivingQueueSearchDocument;
028import org.kuali.ole.select.document.service.OleLineItemReceivingService;
029import org.kuali.ole.sys.OLEConstants;
030import org.kuali.ole.sys.OLEKeyConstants;
031import org.kuali.ole.sys.context.SpringContext;
032import org.kuali.rice.core.api.config.property.ConfigurationService;
033import org.kuali.rice.core.api.datetime.DateTimeService;
034import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
035import org.kuali.rice.core.api.util.RiceConstants;
036import org.kuali.rice.kew.actionlist.service.ActionListService;
037import org.kuali.rice.kew.actionrequest.ActionRequestValue;
038import org.kuali.rice.kew.actionrequest.service.ActionRequestService;
039import org.kuali.rice.kew.api.KewApiConstants;
040import org.kuali.rice.kew.api.exception.WorkflowException;
041import org.kuali.rice.kew.service.KEWServiceLocator;
042import org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase;
043import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
044import org.kuali.rice.krad.document.Document;
045import org.kuali.rice.krad.service.BusinessObjectService;
046import org.kuali.rice.krad.service.KRADServiceLocator;
047import org.kuali.rice.krad.util.GlobalVariables;
048import org.kuali.rice.krad.util.KRADConstants;
049import org.kuali.rice.krad.util.ObjectUtils;
050
051import javax.servlet.http.HttpServletRequest;
052import javax.servlet.http.HttpServletResponse;
053import java.sql.Timestamp;
054import java.text.ParseException;
055import java.text.SimpleDateFormat;
056import java.util.*;
057import java.util.regex.Matcher;
058import java.util.regex.Pattern;
059
060public class OleReceivingQueueSearchAction extends KualiTransactionalDocumentActionBase {
061
062    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleReceivingQueueSearchAction.class);
063    protected Document document;
064    private static transient OleLineItemReceivingService oleLineItemReceivingService;
065
066    /**
067     * Constructs a OleReceivingQueueSearchAction.java.
068     */
069    public OleReceivingQueueSearchAction() {
070        super();
071    }
072
073    /**
074     * This method Searches and retrieves the purchase order result
075     *
076     * @param mapping
077     * @param form
078     * @param request
079     * @param response
080     * @return
081     * @throws Exception
082     */
083    public ActionForward valueSearch(ActionMapping mapping, ActionForm form,
084                                     HttpServletRequest request, HttpServletResponse response) throws Exception {
085        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
086        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument();
087        oleReceivingQueueSearchDocument.setReceivingDocumentsList(new ArrayList<String>());
088        String purchaseOrderString = oleReceivingQueueSearchDocument.getPurchaseOrderNumber();
089        String purchaseOrderStatus=oleReceivingQueueSearchDocument.getPurchaseOrderStatusDescription()!=null?oleReceivingQueueSearchDocument.getPurchaseOrderStatusDescription():"";
090        String datePattern = "\\d{2}/\\d{2}/\\d{4}";
091        boolean isValid = true;
092        if ((oleReceivingQueueSearchDocument.getEndDate() != null && !oleReceivingQueueSearchDocument.getEndDate().equalsIgnoreCase(""))) {
093            if (!oleReceivingQueueSearchDocument.getEndDate().matches(datePattern)) {
094                oleReceivingQueueSearchDocument.getPurchaseOrders().clear();
095                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_INVALID_DATE, new String[]{"PO To Date"});
096                isValid = false;
097            }
098            try {
099                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
100                sdf.setLenient(false);
101                Date date = sdf.parse(oleReceivingQueueSearchDocument.getEndDate());
102
103            } catch (ParseException e) {
104                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_INVALID_DATE, new String[]{"PO To Date"});
105                isValid = false;
106            }
107        }
108        if ((oleReceivingQueueSearchDocument.getBeginDate() != null && !oleReceivingQueueSearchDocument.getBeginDate().equalsIgnoreCase(""))) {
109            if (!oleReceivingQueueSearchDocument.getBeginDate().matches(datePattern)) {
110                oleReceivingQueueSearchDocument.getPurchaseOrders().clear();
111                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_INVALID_DATE, new String[]{"PO From Date"});
112                isValid = false;
113            }
114            try {
115                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
116                sdf.setLenient(false);
117                Date date = sdf.parse(oleReceivingQueueSearchDocument.getBeginDate());
118            } catch (ParseException e) {
119                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_INVALID_DATE, new String[]{"PO From Date"});
120                isValid = false;
121            }
122        }
123        if (!isValid) {
124            return mapping.findForward(RiceConstants.MAPPING_BASIC);
125        }
126        if (purchaseOrderString != null) {
127            boolean isValidSting = true;
128            String[] purchaseOrderNumbers = purchaseOrderString.split(",");
129            for (String purchaseOrderNumber : purchaseOrderNumbers) {
130                if (!validate(purchaseOrderNumber)) {
131                    isValidSting = false;
132                    break;
133                }
134            }
135            if (!isValidSting) {
136                oleReceivingQueueSearchDocument.getPurchaseOrders().clear();
137                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_PO_ITM_FORMAT);
138                return mapping.findForward(RiceConstants.MAPPING_BASIC);
139            }
140        }
141        if(purchaseOrderStatus.equalsIgnoreCase(OleSelectConstant.CLOSED)){
142            oleReceivingQueueSearchDocument.getPurchaseOrders().clear();
143            GlobalVariables.getMessageMap().putInfo(OleSelectConstant.RECEIVING_QUEUE_SEARCH,
144                    OLEKeyConstants.ERROR_NO_PURCHASEORDERS_FOUND_FOR_CLOSED);
145            //return mapping.findForward(RiceConstants.MAPPING_BASIC);
146
147        }else{
148        oleReceivingQueueSearchDocument.receiveingQueueRecordSearch();
149        }
150        //request.setAttribute(OLEConstants.OrderQueue.CONSTANTS, (KewApiConstants.class));
151        return mapping.findForward(RiceConstants.MAPPING_BASIC);
152    }
153
154    public boolean validate(final String hex) {
155        Pattern pattern = Pattern.compile("[0-9]+");
156        Matcher matcher = pattern.matcher(hex);
157        return matcher.matches();
158
159    }
160
161    @Override
162    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
163        ActionForward actionForward = null;
164        if(((OleReceivingQueueSearchForm) form).getMethodToCall() != null) {
165            if(((OleReceivingQueueSearchForm) form).getMethodToCall().equalsIgnoreCase("docHandler")){
166                ((OleReceivingQueueSearchForm) form).setDocId(null);
167            }
168        }
169        return super.execute(mapping, form, request, response);
170    }
171
172    /**
173     * This method clears the tabs in the UI
174     *
175     * @param mapping
176     * @param form
177     * @param request
178     * @param response
179     * @return
180     * @throws Exception
181     */
182    public ActionForward valueClear(ActionMapping mapping, ActionForm form,
183                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
184        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
185        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument();
186        oleReceivingQueueSearchDocument.setPurchaseOrders(null);
187        oleReceivingQueueSearchDocument.setPurchaseOrderNumber(null);
188        oleReceivingQueueSearchDocument.setVendorName(null);
189        //oleReceivingQueueSearchDocument.setVendor(false);
190        //oleReceivingQueueSearchDocument.setPurchaseOrderDate(false);
191        oleReceivingQueueSearchDocument.setPurchaseOrderStatusDescription(null);
192        oleReceivingQueueSearchDocument.setMonograph(false);
193        oleReceivingQueueSearchDocument.setPurchaseOrderType(null);
194        oleReceivingQueueSearchDocument.setBeginDate(null);
195        oleReceivingQueueSearchDocument.setEndDate(null);
196        oleReceivingQueueSearchDocument.setStandardNumber(null);
197        oleReceivingQueueSearchDocument.setTitle(null);
198        oleReceivingQueueSearchDocument.setClaimFilter(false);
199        oleReceivingQueueSearchDocument.setReceivingDocumentsList(new ArrayList<String>());
200        //oleReceivingQueueSearchDocument.setJournal(null);
201        //request.setAttribute(OLEConstants.OrderQueue.CONSTANTS, KewApiConstants.class.newInstance());
202        return mapping.findForward(RiceConstants.MAPPING_BASIC);
203    }
204
205
206    /**
207     * Gets the document attribute.
208     *
209     * @return Returns the document.
210     */
211    public Document getDocument() {
212        return document;
213    }
214
215    /**
216     * Sets the document attribute value.
217     *
218     * @param document The document to set.
219     */
220    public void setDocument(Document document) {
221        this.document = document;
222    }
223
224    /**
225     * This method selects all Purchase Order Items in Receiving Queue search page
226     *
227     * @param mapping
228     * @param form
229     * @param request
230     * @param response
231     * @return
232     * @throws Exception
233     */
234    public ActionForward selectAll(ActionMapping mapping, ActionForm form,
235                                   HttpServletRequest request, HttpServletResponse response) throws Exception {
236        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
237        List<OlePurchaseOrderItem> items = ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).getPurchaseOrders();
238        List<OlePurchaseOrderItem> refreshItems = new ArrayList<OlePurchaseOrderItem>(0);
239
240        for (OlePurchaseOrderItem item : items) {
241            if(item.isClaimFilter()){
242                item.setClaimPoAdded(true);
243            }
244            item.setPoAdded(true);
245            refreshItems.add(item);
246        }
247
248        ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).setPurchaseOrders(refreshItems);
249        //request.setAttribute(OLEConstants.OrderQueue.CONSTANTS, KewApiConstants.class.newInstance());
250        return mapping.findForward(RiceConstants.MAPPING_BASIC);
251    }
252
253    /**
254     * This method deselects all Purchase Order Items in Receiving Queue search page
255     *
256     * @param mapping
257     * @param form
258     * @param request
259     * @param response
260     * @return
261     * @throws Exception
262     */
263    public ActionForward unselectAll(ActionMapping mapping, ActionForm form,
264                                     HttpServletRequest request, HttpServletResponse response) throws Exception {
265        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
266        List<OlePurchaseOrderItem> items = ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).getPurchaseOrders();
267        List<OlePurchaseOrderItem> refreshItems = new ArrayList<OlePurchaseOrderItem>(0);
268
269        for (OlePurchaseOrderItem item : items) {
270            if(item.isClaimFilter()){
271                item.setClaimPoAdded(false);
272            }
273            item.setPoAdded(false);
274            refreshItems.add(item);
275        }
276
277        ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).setPurchaseOrders(refreshItems);
278        //request.setAttribute(OLEConstants.OrderQueue.CONSTANTS, KewApiConstants.class.newInstance());
279        return mapping.findForward(RiceConstants.MAPPING_BASIC);
280    }
281
282    /**
283     * This method returns a new OleLineItemReceivingDocument
284     *
285     * @return
286     * @throws WorkflowException
287     */
288    protected OleLineItemReceivingDocument createLineItemReceivingDocument() throws WorkflowException {
289        Document doc = getDocumentService().getNewDocument("OLE_RCVL");
290        return (OleLineItemReceivingDocument) doc;
291    }
292
293    /**
294     * This method validates and performs complete receiving of PO IDs selected.
295     *
296     * @param mapping
297     * @param form
298     * @param request
299     * @param response
300     * @return
301     * @throws Exception
302     */
303    public ActionForward completeReceiving(ActionMapping mapping, ActionForm form,
304                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
305        LOG.debug("Inside completeReceiving of OleReceivingQueueSearchDocument");
306        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
307        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument();
308        OleLineItemReceivingDocument rlDoc = null;
309        // Elimiate duplicate POs from the list
310        List<OlePurchaseOrderItem> olePurchaseOrderItems = new ArrayList<OlePurchaseOrderItem>();
311        HashMap<Integer, OlePurchaseOrderItem> selectedPOs = getSelectedPurchaseOrders(oleReceivingQueueSearchDocument.getPurchaseOrders());
312        if (selectedPOs.size() == 0) {
313            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_PO_ITM);
314            return mapping.findForward(RiceConstants.MAPPING_BASIC);
315        }
316        boolean isReceivingExist = false;
317        List<String> errorCreatingReceivingForPoIdList = new ArrayList<String>();
318        for (OlePurchaseOrderItem olePurchaseOrderItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
319            if (olePurchaseOrderItem.isPoAdded()) {
320                /*boolean isReceivingExisted=false;*/
321                if (validateReceivingForProcess(olePurchaseOrderItem)) {
322                    isReceivingExist = true;
323                    olePurchaseOrderItem.setPoAdded(false);
324                    if (!errorCreatingReceivingForPoIdList.contains(olePurchaseOrderItem.getPurchaseOrder().getPurapDocumentIdentifier().toString())) {
325                        errorCreatingReceivingForPoIdList.add(olePurchaseOrderItem.getPurchaseOrder().getPurapDocumentIdentifier().toString());
326                    }
327                }
328                /*if (!isReceivingExisted) {
329                if (olePurchaseOrderItem.getItemQuantity() != null) {
330                    KualiDecimal kualiDecimal = olePurchaseOrderItem.getItemQuantity();
331                    int itemQty = kualiDecimal.intValue();
332                    Map<String, String> map = new HashMap<String, String>();
333                    map.put("itemIdentifier", olePurchaseOrderItem.getItemIdentifier().toString());
334                    List<OlePurchaseOrderItem> orderItems = (List<OlePurchaseOrderItem>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, map);
335                    if (orderItems.size() > 0) {
336                        OlePurchaseOrderItem purchaseOrderItem = orderItems.get(0);
337                        if (!(purchaseOrderItem.getNoOfCopiesReceived() != null && purchaseOrderItem.getNoOfCopiesReceived().equalsIgnoreCase(""))) {
338                            if (itemQty == Integer.parseInt(purchaseOrderItem.getNoOfCopiesReceived())) {
339                                olePurchaseOrderItem.setPoAdded(false);
340
341                            }
342                        }
343                        if (!(purchaseOrderItem.getNoOfPartsReceived() != null && purchaseOrderItem.getNoOfPartsReceived().equalsIgnoreCase(""))) {
344                            if (purchaseOrderItem.getNoOfPartsReceived().equals(purchaseOrderItem.getItemNoOfParts())) {
345                                olePurchaseOrderItem.setPoAdded(false);
346
347                            }
348                        }
349                    }
350                }
351
352                }*/
353            }
354        }
355        selectedPOs = getSelectedPurchaseOrders(oleReceivingQueueSearchDocument.getPurchaseOrders());
356        // Map containing PO ID and receive PO status
357        HashMap<Integer, Boolean> receivePOStatus = new HashMap<Integer, Boolean>();
358        oleReceivingQueueSearchDocument.getReceivingDocumentsList().clear();
359        boolean isInfoMsg = false;
360        for (Map.Entry<Integer, OlePurchaseOrderItem> entry : selectedPOs.entrySet()) {
361            if (LOG.isDebugEnabled()) {
362                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey());
363            }
364            rlDoc = createLineItemReceivingDocument();
365            boolean receivePOSuccess = oleReceivingQueueSearchDocument.receivePO(rlDoc, entry.getKey(), false);
366            if (receivePOSuccess) {
367                oleReceivingQueueSearchDocument.getReceivingDocumentsList().add(rlDoc.getDocumentNumber());
368                // assignActionRequests(rlDoc.getDocumentHeader().getWorkflowDocument().getDocumentId().toString());
369                isInfoMsg = true;
370            }
371            receivePOStatus.put(entry.getKey(), receivePOSuccess);
372            if (LOG.isDebugEnabled()) {
373                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey() + " completed successfully");
374            }
375        }
376        List<OlePurchaseOrderItem> refreshedPOList = new ArrayList<OlePurchaseOrderItem>();
377        for (OlePurchaseOrderItem poItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
378            Integer poId = poItem.getPurchaseOrder().getPurapDocumentIdentifier();
379            refreshedPOList.add(poItem);
380            /*if(ObjectUtils.isNull(receivePOStatus.get(poId))){
381                refreshedPOList.add(poItem);
382            }else{
383                if(receivePOStatus.get(poId) == false) {
384                    refreshedPOList.add(poItem);
385                }
386            }*/
387        }
388
389        ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).setPurchaseOrders(refreshedPOList);
390
391        LOG.debug("Leaving completeReceiving of OleReceivingQueueSearchDocument");
392        String errorCreatingReceivingForPoIds = "";
393        for (String string : errorCreatingReceivingForPoIdList) {
394            errorCreatingReceivingForPoIds = errorCreatingReceivingForPoIds + string + ",";
395        }
396        if (isReceivingExist) {
397            errorCreatingReceivingForPoIds = errorCreatingReceivingForPoIds.substring(0, errorCreatingReceivingForPoIds.length() - 1);
398            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_RECEIVING_EXIST, errorCreatingReceivingForPoIds);
399        }
400
401        return unselectAll(mapping, oleReceivingQueueSearchForm, request, response);
402    }
403
404
405    public ActionForward claiming(ActionMapping mapping, ActionForm form,
406                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
407        LOG.debug("Inside completeReceiving of OleReceivingQueueSearchDocument");
408        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
409        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument();
410        // Elimiate duplicate POs from the list
411        List<OlePurchaseOrderItem> olePurchaseOrderItems = new ArrayList<OlePurchaseOrderItem>();
412        for (OlePurchaseOrderItem poItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
413            if (poItem.isPoAdded()) {
414                olePurchaseOrderItems.add(poItem);
415            }
416        }
417        if (olePurchaseOrderItems.size() == 0) {
418            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_PO_ITM);
419            return mapping.findForward(RiceConstants.MAPPING_BASIC);
420        }
421        OLEClaimNoticeService oleClaimNoticeService  = GlobalResourceLoader.getService("oleClaimNoticeService");
422        oleClaimNoticeService.generateClaimReportFromPO(olePurchaseOrderItems,false);
423        return unselectAll(mapping, oleReceivingQueueSearchForm, request, response);
424    }
425
426
427    /**
428     * This method validates and creates receiving document from the selected PO Items.
429     *
430     * @param mapping
431     * @param form
432     * @param request
433     * @param response
434     * @return
435     * @throws Exception
436     */
437    public ActionForward createReceiving(ActionMapping mapping, ActionForm form, HttpServletRequest request,
438                                         HttpServletResponse response) throws Exception {
439        LOG.debug("Inside completereceiving of OleReceivingQueueSearchDocument");
440        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
441        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm
442                .getDocument();
443        OleLineItemReceivingDocument rlDoc = null;
444        HashMap<Integer, OlePurchaseOrderItem> selectedPOs = getSelectedPurchaseOrders(oleReceivingQueueSearchDocument
445                .getPurchaseOrders());
446        List<OlePurchaseOrderItem> olePurchaseOrderItems = new ArrayList<OlePurchaseOrderItem>();
447        if (selectedPOs.size() == 0) {
448            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_SELECT_PO_ITM);
449            return mapping.findForward(RiceConstants.MAPPING_BASIC);
450        }
451        boolean isReceivingExist = false;
452        List<String> errorCreatingReceivingForPoIdList = new ArrayList<String>();
453        for (OlePurchaseOrderItem olePurchaseOrderItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
454            if (olePurchaseOrderItem.isPoAdded()) {
455                if (validateReceivingForProcess(olePurchaseOrderItem)) {
456                    isReceivingExist = true;
457                    olePurchaseOrderItem.setPoAdded(false);
458                    if (!errorCreatingReceivingForPoIdList.contains(olePurchaseOrderItem.getPurchaseOrder().getPurapDocumentIdentifier().toString())) {
459                        errorCreatingReceivingForPoIdList.add(olePurchaseOrderItem.getPurchaseOrder().getPurapDocumentIdentifier().toString());
460                    }
461                }
462                /*if (olePurchaseOrderItem.getItemQuantity() != null) {
463                    KualiDecimal kualiDecimal = olePurchaseOrderItem.getItemQuantity();
464                    int itemQty = kualiDecimal.intValue();
465                    Map<String, String> map = new HashMap<String, String>();
466                    map.put("itemIdentifier", olePurchaseOrderItem.getItemIdentifier().toString());
467                    List<OlePurchaseOrderItem> orderItems = (List<OlePurchaseOrderItem>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, map);
468                    if (orderItems.size() > 0) {
469                        OlePurchaseOrderItem purchaseOrderItem = orderItems.get(0);
470                        if (!(purchaseOrderItem.getNoOfCopiesReceived() != null && purchaseOrderItem.getNoOfCopiesReceived().equalsIgnoreCase(""))) {
471                            if (itemQty == Integer.parseInt(purchaseOrderItem.getNoOfCopiesReceived())) {
472                                olePurchaseOrderItem.setPoAdded(false);
473
474                            }
475                        }
476                        if (!(purchaseOrderItem.getNoOfPartsReceived() != null && purchaseOrderItem.getNoOfPartsReceived().equalsIgnoreCase(""))) {
477                            if (purchaseOrderItem.getNoOfPartsReceived().equals(purchaseOrderItem.getItemNoOfParts())) {
478                                olePurchaseOrderItem.setPoAdded(false);
479
480                            }
481                        }
482                    }
483                }*/
484            }
485        }
486        selectedPOs = getSelectedPurchaseOrders(oleReceivingQueueSearchDocument.getPurchaseOrders());
487        // Map containing PO ID and receive PO status
488        HashMap<Integer, Boolean> receivePOStatus = new HashMap<Integer, Boolean>();
489        boolean isInfoMsg = false;
490        for (Map.Entry<Integer, OlePurchaseOrderItem> entry : selectedPOs.entrySet()) {
491            if (LOG.isDebugEnabled()) {
492                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey());
493            }
494            rlDoc = createLineItemReceivingDocument();
495            getOleLineItemReceivingService().getInitialCollapseSections(rlDoc);
496            boolean receivePOSuccess = oleReceivingQueueSearchDocument.receivePO(rlDoc, entry.getKey(), true);
497            if (receivePOSuccess) {
498                oleReceivingQueueSearchDocument.getReceivingDocumentsList().add(rlDoc.getDocumentNumber());
499                isInfoMsg = true;
500            }
501            receivePOStatus.put(entry.getKey(), receivePOSuccess);
502            if (LOG.isDebugEnabled()) {
503                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey()
504                        + " completed successfully");
505            }
506        }
507        List<OlePurchaseOrderItem> refreshedPOList = new ArrayList<OlePurchaseOrderItem>();
508        for (OlePurchaseOrderItem poItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
509            Integer poId = poItem.getPurchaseOrder().getPurapDocumentIdentifier();
510            refreshedPOList.add(poItem);
511            /*if (ObjectUtils.isNull(receivePOStatus.get(poId))) {
512                refreshedPOList.add(poItem);
513            }
514            else {
515                if (receivePOStatus.get(poId) == false) {
516                    refreshedPOList.add(poItem);
517                }
518            }*/
519        }
520        if (oleReceivingQueueSearchDocument.getReceivingDocumentsList().size() == 1) {
521            ActionForward dest = returnToReceiving(oleReceivingQueueSearchDocument.getReceivingDocumentsList().get(0));
522            return dest;
523        }
524        ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument())
525                .setPurchaseOrders(refreshedPOList);
526
527        LOG.debug("Leaving completeReceiving of OleReceivingQueueSearchDocument");
528        String errorCreatingReceivingForPoIds = "";
529        for (String string : errorCreatingReceivingForPoIdList) {
530            errorCreatingReceivingForPoIds = errorCreatingReceivingForPoIds + string + ",";
531        }
532        if (isReceivingExist) {
533            errorCreatingReceivingForPoIds = errorCreatingReceivingForPoIds.substring(0, errorCreatingReceivingForPoIds.length() - 1);
534            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.ERROR_RECEIVING_EXIST, errorCreatingReceivingForPoIds);
535        }
536
537        return mapping.findForward(RiceConstants.MAPPING_BASIC);
538    }
539
540    /**
541     * This method populates a HashMap with POID and Purchase Order Item. The display is at line item level, and users can select
542     * multiple line items under same PO and click on Receive. This method removes duplicate PO selections in such cases.
543     *
544     * @param purchaseOrders Selected PurchaseOrders from UI
545     * @return
546     */
547    private HashMap<Integer, OlePurchaseOrderItem> getSelectedPurchaseOrders(List<OlePurchaseOrderItem> purchaseOrders) {
548        LOG.debug("Inside getSelectedPurchaseOrders of OleReceivingQueueSearchDocument");
549        HashMap<Integer, OlePurchaseOrderItem> poItemMap = new HashMap<Integer, OlePurchaseOrderItem>();
550        for (OlePurchaseOrderItem poItem : purchaseOrders) {
551            if (poItem.isPoAdded()) {
552                if (ObjectUtils.isNull(poItemMap.get(poItem.getPurchaseOrder().getPurapDocumentIdentifier()))) {
553                    poItemMap.put(poItem.getPurchaseOrder().getPurapDocumentIdentifier(), poItem);
554                }
555            }
556        }
557        if (LOG.isDebugEnabled()) {
558            LOG.debug("Number of actual PO selected in OleReceivingQueueSearchDocument.getSelectedPurchaseOrders - " + poItemMap.size());
559            LOG.debug("Leaving getSelectedPurchaseOrders of OleReceivingQueueSearchDocument");
560        }
561
562        return poItemMap;
563    }
564
565    /**
566     * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#cancel(org.apache.struts.action.ActionMapping,
567     *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
568     */
569    @Override
570    public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
571        KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
572        return returnToSender(request, mapping, kualiDocumentFormBase);
573    }
574
575    /**
576     * This method redirects the receiving queue to Line Item Receiving Document.
577     *
578     * @param rcvDocId
579     * @return ActionForward which will redirect the user to the docSearchDisplay for the Receiving Document with the given
580     *         documentId
581     */
582    private ActionForward returnToReceiving(String rcvDocId) {
583        String receivingUrl = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
584                OLEConstants.WORKFLOW_URL_KEY)
585                + "/DocHandler.do?docId=" + rcvDocId + "&command=displayDocSearchView";
586        return new ActionForward(receivingUrl, true);
587    }
588
589
590    /**
591     * This method redirects the receiving queue to Payment Request Document.
592     *
593     * @param purchaseOrderId
594     * @return ActionForward which will redirect the user to the docSearchDisplay for the Receiving Document with the given
595     *         documentId
596     */
597    private ActionForward returnToPayment(String purchaseOrderId) {
598        String paymentUrl = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
599                OLEConstants.WORKFLOW_URL_KEY)
600                + "/selectOlePaymentRequest.do?purchaseOrderIdentifier=" + purchaseOrderId
601                + "&methodToCall=docHandler&command=initiate&docTypeName=OLE_PREQ";
602        return new ActionForward(paymentUrl, true);
603    }
604
605    /**
606     * This method validates and creates receiving document and the Payment Request Document from the selected PO Items.
607     *
608     * @param mapping
609     * @param form
610     * @param request
611     * @param response
612     * @return
613     * @throws Exception
614     */
615    public ActionForward createPaymentRequestDocument(ActionMapping mapping, ActionForm form,
616                                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
617
618        return mapping.findForward(RiceConstants.MAPPING_BASIC);
619    }
620
621    /**
622     * This method validates and creates receiving document and the Payment Request Document from the selected PO Items.
623     *
624     * @param mapping
625     * @param form
626     * @param request
627     * @param response
628     * @return
629     * @throws Exception
630     */
631    public ActionForward receiveAndPay(ActionMapping mapping, ActionForm form, HttpServletRequest request,
632                                       HttpServletResponse response) throws Exception {
633        LOG.debug("Inside receiveAndPay of OleReceivingQueueSearchDocument");
634        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) form;
635        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument();
636        OleLineItemReceivingDocument rlDoc = null;
637        // Elimiate duplicate POs from the list
638        HashMap<Integer, OlePurchaseOrderItem> selectedPOs = getSelectedPurchaseOrders(oleReceivingQueueSearchDocument.getPurchaseOrders());
639        // Map containing PO ID and receive PO status
640        HashMap<Integer, Boolean> receivePOStatus = new HashMap<Integer, Boolean>();
641        boolean isInfoMsg = false;
642        for (Map.Entry<Integer, OlePurchaseOrderItem> entry : selectedPOs.entrySet()) {
643            if (LOG.isDebugEnabled()) {
644                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey());
645            }
646            rlDoc = createLineItemReceivingDocument();
647            boolean receivePOSuccess = oleReceivingQueueSearchDocument.receivePO(rlDoc, entry.getKey(), false);
648            if (receivePOSuccess) {
649                oleReceivingQueueSearchDocument.getReceivingDocumentsList().add(rlDoc.getDocumentNumber());
650                // assignActionRequests(rlDoc.getDocumentHeader().getWorkflowDocument().getDocumentId().toString());
651                isInfoMsg = true;
652            }
653            receivePOStatus.put(entry.getKey(), receivePOSuccess);
654            if (LOG.isDebugEnabled()) {
655                LOG.debug("Creating Line Item Receiving Document for PO ID - " + entry.getKey() + " completed successfully");
656            }
657        }
658        List<OlePurchaseOrderItem> refreshedPOList = new ArrayList<OlePurchaseOrderItem>();
659        for (OlePurchaseOrderItem poItem : oleReceivingQueueSearchDocument.getPurchaseOrders()) {
660            Integer poId = poItem.getPurchaseOrder().getPurapDocumentIdentifier();
661            if (ObjectUtils.isNull(receivePOStatus.get(poId))) {
662                refreshedPOList.add(poItem);
663            } else {
664                if (receivePOStatus.get(poId) == false) {
665                    refreshedPOList.add(poItem);
666                }
667            }
668        }
669
670        ((OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm.getDocument()).setPurchaseOrders(refreshedPOList);
671
672        LOG.debug("Leaving receiveAndPay of OleReceivingQueueSearchDocument");
673
674        return mapping.findForward(RiceConstants.MAPPING_BASIC);
675    }
676
677    @Override
678    protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
679        super.loadDocument(kualiDocumentFormBase);
680        OleReceivingQueueSearchForm oleReceivingQueueSearchForm = (OleReceivingQueueSearchForm) kualiDocumentFormBase;
681        OleReceivingQueueSearchDocument oleReceivingQueueSearchDocument = (OleReceivingQueueSearchDocument) oleReceivingQueueSearchForm
682                .getDocument();
683        oleReceivingQueueSearchDocument.setReceivingDocumentsList(new ArrayList<String>());
684    }
685
686    /**
687     * This method assigns specified document to the selector.
688     */
689    private void assignActionRequests(String routeHeaderId) {
690        LOG.debug("Inside assignActionRequests of OleOrderQueueDocument");
691        Timestamp currentTime = SpringContext.getBean(DateTimeService.class).getCurrentTimestamp();
692        ActionListService actionListSrv = KEWServiceLocator.getActionListService();
693        ActionRequestService actionReqSrv = KEWServiceLocator.getActionRequestService();
694        ActionRequestValue actionRequest = new ActionRequestValue();
695        actionRequest.setActionRequested(KewApiConstants.ACTION_REQUEST_FYI_REQ);
696        actionRequest.setPrincipalId("OLE10003");
697        actionRequest.setCreateDate(currentTime);
698        actionRequest.setForceAction(true);
699        actionReqSrv.saveActionRequest(actionRequest);
700        /*
701         * List<ActionRequestValue> actionReqValues = actionReqSrv.findAllPendingRequests(routeHeaderId); for (ActionRequestValue
702         * actionRequest : actionReqValues) { List<ActionItem> actionItems = actionRequest.getActionItems(); for (ActionItem
703         * actionItem : actionItems) { actionItem.setPrincipalId(GlobalVariables.getUserSession().getPrincipalId());
704         * actionItem.setDateAssigned(currentTime); actionListSrv.saveActionItem(actionItem); }
705         * actionRequest.setActionRequested(KewApiConstants.ACTION_REQUEST_FYI_REQ);
706         * actionRequest.setPrincipalId(GlobalVariables.getUserSession().getPrincipalId());
707         * actionRequest.setCreateDate(currentTime); actionReqSrv.saveActionRequest(actionRequest); }
708         */
709        LOG.debug("Leaving assignActionRequests of OleOrderQueueDocument");
710    }
711
712    public boolean validateReceivingForProcess(OlePurchaseOrderItem purchaseOrderItem) {
713        boolean isValid = false;
714        Map<String, String> map = new HashMap<String, String>();
715        map.put("purchaseOrderIdentifier", purchaseOrderItem.getItemIdentifier().toString());
716        List<OleLineItemReceivingItem> oleLineItemReceivingItems = (List<OleLineItemReceivingItem>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLineItemReceivingItem.class, map);
717
718        if (oleLineItemReceivingItems.size() > 0) {
719            OleLineItemReceivingItem oleLineItemReceivingItem = oleLineItemReceivingItems.get(0);
720            if (oleLineItemReceivingItem.getReceiptStatusId() != null) {
721                if (oleLineItemReceivingItem.getReceiptStatusId().toString().equalsIgnoreCase(getReceiptStatusDetails(OLEConstants.PO_RECEIPT_STATUS_FULLY_RECEIVED) + "")) {
722                    isValid = true;
723                }
724            }
725        }
726        return isValid;
727    }
728
729    public int getReceiptStatusDetails(String receiptStatusCd) {
730        int receiptStatusId = 0;
731        Map<String, String> receiptStatusCdMap = new HashMap<String, String>();
732        receiptStatusCdMap.put(OLEConstants.RCPT_STATUS_CD, receiptStatusCd);
733        List<OleReceiptStatus> oleReceiptStatusList = (List) SpringContext.getBean(BusinessObjectService.class)
734                .findMatching(OleReceiptStatus.class, receiptStatusCdMap);
735        for (OleReceiptStatus oleReceiptStatus : oleReceiptStatusList) {
736            receiptStatusId = oleReceiptStatus.getReceiptStatusId().intValue();
737        }
738        return receiptStatusId;
739    }
740
741    public static OleLineItemReceivingService getOleLineItemReceivingService() {
742        if (oleLineItemReceivingService == null) {
743            oleLineItemReceivingService = SpringContext.getBean(OleLineItemReceivingService.class);
744        }
745        return oleLineItemReceivingService;
746    }
747
748}