001package org.kuali.ole.select.controller;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.apache.commons.lang.StringUtils;
005import org.kuali.ole.module.purap.PurapConstants;
006import org.kuali.ole.module.purap.PurapKeyConstants;
007import org.kuali.ole.module.purap.PurapPropertyConstants;
008import org.kuali.ole.module.purap.document.LineItemReceivingDocument;
009import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
010import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
011import org.kuali.ole.module.purap.document.service.ReceivingService;
012import org.kuali.ole.module.purap.document.web.struts.LineItemReceivingForm;
013import org.kuali.ole.select.bo.OLEDonor;
014import org.kuali.ole.select.bo.OLELinkPurapDonor;
015import org.kuali.ole.select.businessobject.*;
016import org.kuali.ole.select.document.OleDefaultValueAssignment;
017import org.kuali.ole.select.document.OleLineItemReceivingDocument;
018import org.kuali.ole.select.document.OlePurchaseOrderDocument;
019import org.kuali.ole.select.document.service.OleCopyHelperService;
020import org.kuali.ole.select.document.service.OleLineItemReceivingService;
021import org.kuali.ole.select.document.service.impl.OleLineItemReceivingServiceImpl;
022import org.kuali.ole.select.document.web.struts.OleLineItemReceivingForm;
023import org.kuali.ole.sys.OLEConstants;
024import org.kuali.ole.sys.OLEKeyConstants;
025import org.kuali.ole.sys.OLEPropertyConstants;
026import org.kuali.ole.sys.context.SpringContext;
027import org.kuali.rice.core.api.config.property.ConfigContext;
028import org.kuali.rice.core.api.datetime.DateTimeService;
029import org.kuali.rice.core.api.util.type.KualiDecimal;
030import org.kuali.rice.kew.api.exception.WorkflowException;
031import org.kuali.rice.kim.api.KimConstants;
032import org.kuali.rice.kns.question.ConfirmationQuestion;
033import org.kuali.rice.kns.service.DocumentHelperService;
034import org.kuali.rice.krad.document.TransactionalDocumentControllerBase;
035import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
036import org.kuali.rice.krad.uif.UifConstants;
037import org.kuali.rice.krad.uif.UifParameters;
038import org.kuali.rice.krad.uif.component.BindingInfo;
039import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
040import org.kuali.rice.krad.util.GlobalVariables;
041import org.kuali.rice.krad.util.KRADConstants;
042import org.kuali.rice.krad.util.ObjectUtils;
043import org.kuali.rice.krad.util.UrlFactory;
044import org.kuali.rice.krad.web.controller.MethodAccessible;
045import org.kuali.rice.krad.web.controller.UifControllerBase;
046import org.kuali.rice.krad.web.form.DialogResponse;
047import org.kuali.rice.krad.web.form.DocumentFormBase;
048import org.kuali.rice.krad.web.form.UifFormBase;
049import org.springframework.stereotype.Controller;
050import org.springframework.validation.BindingResult;
051import org.springframework.web.bind.annotation.ModelAttribute;
052import org.springframework.web.bind.annotation.RequestMapping;
053import org.springframework.web.servlet.ModelAndView;
054
055import javax.servlet.http.HttpServletRequest;
056import javax.servlet.http.HttpServletResponse;
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: aurojyotit
065 * Date: 10/29/14
066 * Time: 7:26 PM
067 * To change this template use File | Settings | File Templates.
068 */
069@Controller
070@RequestMapping(value = "/lineItemReceivingController")
071public class OLELineItemReceivingController extends TransactionalDocumentControllerBase {
072
073    private static transient OleLineItemReceivingService oleLineItemReceivingService;
074
075    public static OleLineItemReceivingService getOleLineItemReceivingService() {
076        if (oleLineItemReceivingService == null) {
077            oleLineItemReceivingService = SpringContext.getBean(OleLineItemReceivingService.class);
078        }
079        return oleLineItemReceivingService;
080    }
081
082    @Override
083    protected DocumentFormBase createInitialForm() {
084        return new OleLineItemReceivingForm();  //To change body of implemented methods use File | Settings | File Templates.
085    }
086
087    @Override
088    public ModelAndView start(UifFormBase form) {
089        return super.start(form);    //To change body of overridden methods use File | Settings | File Templates.
090    }
091
092    @Override
093    public ModelAndView docHandler(DocumentFormBase form) throws Exception {
094        super.docHandler(form);
095        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
096        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
097        if (form.getRequest().getParameter("viewTab") != null) {
098            oleLineItemReceivingForm.setViewTab(form.getRequest().getParameter("viewTab"));
099        }
100        return getModelAndView(oleLineItemReceivingForm);
101    }
102
103
104    @MethodAccessible
105    @RequestMapping(params = "methodToCall=continueReceivingLine")
106    public ModelAndView continueReceivingLine(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
107        try {
108            OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
109            OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
110            String  purchaseOrderId = "";
111            if(lineItemReceivingDocument.getPurchaseOrderIdentifier()!=null){
112                purchaseOrderId=lineItemReceivingDocument.getPurchaseOrderIdentifier().toString();
113            }
114            super.docHandler(form);
115            oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
116            lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
117            PurchaseOrderDocument po = null;
118            boolean valid = true;
119            if (StringUtils.isNotEmpty(request.getParameter("purchaseOrderId"))) {
120                String purchaseOrderNumber = request.getParameter("purchaseOrderId");
121                po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(new Integer(purchaseOrderNumber));
122                lineItemReceivingDocument.populateReceivingLineFromPurchaseOrder(po);
123                DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
124                lineItemReceivingDocument.setShipmentReceivedDate(dateTimeService.getCurrentSqlDate());
125                getOleLineItemReceivingService().getInitialCollapseSections(lineItemReceivingDocument);
126
127            } else if(StringUtils.isNotEmpty(purchaseOrderId)){
128                po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(new Integer(purchaseOrderId));
129                lineItemReceivingDocument.populateReceivingLineFromPurchaseOrder(po);
130                DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
131                lineItemReceivingDocument.setShipmentReceivedDate(dateTimeService.getCurrentSqlDate());
132                getOleLineItemReceivingService().getInitialCollapseSections(lineItemReceivingDocument);
133                oleLineItemReceivingForm.setViewTab(null);
134            }else {
135                GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_REQUIRED, PurapConstants.PREQDocumentsStrings.PURCHASE_ORDER_ID);
136                return getModelAndView(form);
137            }
138            if (ObjectUtils.isNotNull(po)) {
139                // TODO figure out a more straightforward way to do this.  ailish put this in so the link id would be set and the perm check would work
140                lineItemReceivingDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
141
142                //TODO hjs-check to see if user is allowed to initiate doc based on PO sensitive data (add this to all other docs except acm doc)
143               /* if (!SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(lineItemReceivingDocument).isAuthorizedByTemplate(lineItemReceivingDocument, KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_DOCUMENT, GlobalVariables.getUserSession().getPrincipalId())) {
144                    throw buildAuthorizatiopopulateReceivingLineFromPurchaseOrdernException("initiate document", lineItemReceivingDocument);
145                }*/
146            } else {
147                GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_PURCHASE_ORDER_NOT_EXIST);
148                return getModelAndView(form);
149            }
150
151            //TODO perform duplicate check
152            //perform duplicate check
153            /*ModelAndView forward = performDuplicateReceivingLineCheck(form, result,request, response);
154            if (forward != null) {
155                return forward;
156            }
157*/
158            if (!SpringContext.getBean(ReceivingService.class).isPurchaseOrderActiveForLineItemReceivingDocumentCreation(lineItemReceivingDocument.getPurchaseOrderIdentifier())) {
159                GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_RECEIVING_LINE_DOCUMENT_PO_NOT_ACTIVE, lineItemReceivingDocument.getPurchaseOrderIdentifier().toString());
160                valid &= false;
161            }
162
163            if (SpringContext.getBean(ReceivingService.class).canCreateLineItemReceivingDocument(lineItemReceivingDocument.getPurchaseOrderIdentifier(), lineItemReceivingDocument.getDocumentNumber()) == false) {
164                String inProcessDocNum = "";
165                List<String> inProcessDocNumbers = SpringContext.getBean(ReceivingService.class).getLineItemReceivingDocumentNumbersInProcessForPurchaseOrder(lineItemReceivingDocument.getPurchaseOrderIdentifier(), lineItemReceivingDocument.getDocumentNumber());
166                if (!inProcessDocNumbers.isEmpty()) {    // should not be empty if we reach this point
167                    inProcessDocNum = inProcessDocNumbers.get(0);
168                }
169                GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_RECEIVING_LINE_DOCUMENT_ACTIVE_FOR_PO, inProcessDocNum, lineItemReceivingDocument.getPurchaseOrderIdentifier().toString());
170                valid &= false;
171            }
172
173            //populate and save Receiving Line Document from Purchase Order, only if we passed all the rules
174            if (valid) {
175                //SpringContext.getBean(ReceivingService.class).populateAndSaveLineItemReceivingDocument(lineItemReceivingDocument);
176                //super.save(form);
177            }
178
179        } catch (Exception e) {
180            e.printStackTrace();
181        }
182
183        return getModelAndView(form);
184    }
185
186    @MethodAccessible
187    @RequestMapping(params = "methodToCall=performDuplicateReceivingLineCheck")
188    public ModelAndView performDuplicateReceivingLineCheck(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
189        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
190        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
191        HashMap<String, String> duplicateMessages = SpringContext.getBean(ReceivingService.class).receivingLineDuplicateMessages(lineItemReceivingDocument);
192        if (duplicateMessages != null && !duplicateMessages.isEmpty()) {
193            Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
194            if (question == null) {
195
196                //return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.LineItemReceivingDocumentStrings.DUPLICATE_RECEIVING_LINE_QUESTION, duplicateMessages.get(PurapConstants.LineItemReceivingDocumentStrings.DUPLICATE_RECEIVING_LINE_QUESTION), OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
197            }
198
199            Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
200            if ((PurapConstants.LineItemReceivingDocumentStrings.DUPLICATE_RECEIVING_LINE_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
201                return getModelAndView(form);
202            }
203        }
204        return getModelAndView(form);
205    }
206
207
208    @MethodAccessible
209    @RequestMapping(params = "methodToCall=clearQty")
210    public ModelAndView clearQty(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
211        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
212        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
213        for (OleLineItemReceivingItem item : (List<OleLineItemReceivingItem>) lineItemReceivingDocument.getItems()) {
214            item.setItemReceivedTotalParts(KualiDecimal.ZERO);
215        }
216        return getModelAndView(form);
217    }
218
219    /*@MethodAccessible
220    @RequestMapping(params = "methodToCall=addExceptionNote")
221    public ModelAndView addExceptionNote(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
222        OleLineItemReceivingForm oleLineItemReceivingForm=(OleLineItemReceivingForm)form;
223        OleLineItemReceivingDocument lineItemReceivingDocument=(OleLineItemReceivingDocument)oleLineItemReceivingForm.getLineItemReceivingDocument();
224       *//* OleLineItemReceivingItem selectedItem = (OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request));
225        OleReceivingLineExceptionNotes exceptionNotes = new OleReceivingLineExceptionNotes();
226        exceptionNotes.setExceptionTypeId(selectedItem.getExceptionTypeId());
227        exceptionNotes.setExceptionNotes(selectedItem.getExceptionNotes());
228        exceptionNotes.setReceivingLineItemIdentifier(selectedItem.getReceivingItemIdentifier());
229        selectedItem.addExceptionNote(exceptionNotes);
230        ((OleLineItemReceivingItem) lineItemReceivingDocument.getItem(this.getSelectedLine(request))).setExceptionTypeId(null);
231        ((OleLineItemReceivingItem) lineItemReceivingDocument.getItem(this.getSelectedLine(request))).setExceptionNotes(null);
232        LOG.debug("Leaving addExceptionNote of OleLineItemReceivingAction");*//*
233        return getModelAndView(form);
234    }*/
235
236    /*@MethodAccessible
237    @RequestMapping(params = "methodToCall=deleteExceptionNote")
238    public ModelAndView deleteExceptionNote(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
239        OleLineItemReceivingForm oleLineItemReceivingForm=(OleLineItemReceivingForm)form;
240        OleLineItemReceivingDocument lineItemReceivingDocument=(OleLineItemReceivingDocument)oleLineItemReceivingForm.getLineItemReceivingDocument();
241        *//*OleLineItemReceivingForm receiveForm = (OleLineItemReceivingForm) form;
242        OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) receiveForm.getDocument();
243        String[] indexes = getSelectedLineForDelete(request);
244        int itemIndex = Integer.parseInt(indexes[0]);
245        int noteIndex = Integer.parseInt(indexes[1]);
246        OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem((itemIndex));
247        item.getExceptionNoteList().remove(noteIndex);*//*
248        return getModelAndView(form);
249    }*/
250
251   /* @MethodAccessible
252    @RequestMapping(params = "methodToCall=addReceiptNote")
253    public ModelAndView addReceiptNote(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
254        OleLineItemReceivingForm oleLineItemReceivingForm=(OleLineItemReceivingForm)form;
255        OleLineItemReceivingDocument lineItemReceivingDocument=(OleLineItemReceivingDocument)oleLineItemReceivingForm.getLineItemReceivingDocument();
256       *//* OleLineItemReceivingItem selectedItem = (OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request));
257        OleLineItemReceivingReceiptNotes receiptNotes = new OleLineItemReceivingReceiptNotes();
258        OleNoteType oleNoteType = SpringContext.getBean(OleNoteTypeService.class).getNoteTypeDetails(selectedItem.getNoteTypeId());
259        receiptNotes.setNoteTypeId(selectedItem.getNoteTypeId());
260        receiptNotes.setNotes(selectedItem.getReceiptNotes());
261        receiptNotes.setReceivingLineItemIdentifier(selectedItem.getReceivingItemIdentifier());
262        receiptNotes.setNoteType(oleNoteType);
263        selectedItem.addReceiptNote(receiptNotes);
264        selectedItem.addNote(receiptNotes);
265        ((OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request))).setNoteTypeId(null);*//*
266        return getModelAndView(form);
267    }*/
268
269    /*@MethodAccessible
270    @RequestMapping(params = "methodToCall=deleteReceiptNote")
271    public ModelAndView deleteReceiptNote(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
272        OleLineItemReceivingForm oleLineItemReceivingForm=(OleLineItemReceivingForm)form;
273        OleLineItemReceivingDocument lineItemReceivingDocument=(OleLineItemReceivingDocument)oleLineItemReceivingForm.getLineItemReceivingDocument();
274        String operation = "AddCorrectionNote ";
275
276        *//*ReceivingQuestionCallback callback = new ReceivingQuestionCallback() {
277            public boolean questionComplete = false;
278            protected String correctionDocumentnoteText;
279
280            @Override
281            public ReceivingDocument doPostQuestion(ReceivingDocument document, String noteText) throws Exception {
282                //mark question completed
283                this.setQuestionComplete(true);
284                this.setCorrectionDocumentCreationNoteText(noteText);
285                return document;
286            }
287
288            @Override
289            public boolean isQuestionComplete() {
290                return this.questionComplete;
291            }
292
293            @Override
294            public void setQuestionComplete(boolean questionComplete) {
295                this.questionComplete = questionComplete;
296            }
297
298            @Override
299            public String getCorrectionDocumentCreationNoteText() {
300                return correctionDocumentnoteText;
301            }
302
303            @Override
304            public void setCorrectionDocumentCreationNoteText(String noteText) {
305                correctionDocumentnoteText = noteText;
306            }
307        };
308
309        //ask question
310        ActionForward forward = askQuestionWithInput(mapping, form, request, response, CorrectionReceivingDocumentStrings.NOTE_QUESTION, CorrectionReceivingDocumentStrings.NOTE_PREFIX, operation, PurapKeyConstants.MESSAGE_RECEIVING_CORRECTION_NOTE, callback);
311
312        //if question asked is complete, then route
313        if (callback.isQuestionComplete()) {
314
315            //set parameters
316            String basePath = getApplicationBaseUrl();
317            String methodToCallDocHandler = "docHandler";
318            String methodToCallReceivingCorrection = "initiate";
319
320            Properties parameters = new Properties();
321            parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
322            parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingCorrection);
323            parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVC");
324            parameters.put("receivingLineDocId", document.getDocumentHeader().getDocumentNumber());
325            parameters.put(PurapConstants.CorrectionReceivingDocumentStrings.CORRECTION_RECEIVING_CREATION_NOTE_PARAMETER, callback.getCorrectionDocumentCreationNoteText());
326
327            //create url
328            String receivingCorrectionUrl = UrlFactory.parameterizeUrl(basePath + "/" + "selectOleCorrectionReceiving.do", parameters);
329            //create forward
330            forward = new ActionForward(receivingCorrectionUrl, true);
331        }*//*
332        return getModelAndView(form);
333    }*/
334
335    @MethodAccessible
336    @RequestMapping(params = "methodToCall=createReceivingCorrection")
337    public ModelAndView createReceivingCorrection(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
338        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
339        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
340        LineItemReceivingForm rlForm = (LineItemReceivingForm) form;
341        LineItemReceivingDocument document = (LineItemReceivingDocument) rlForm.getDocument();
342
343        String operation = "AddCorrectionNote ";
344        String dialog = "OLELineItemReceivingView-QuestionPromptDialogView";
345        DialogResponse routeConfirmDialog = form.getDialogResponse(dialog);
346        if (routeConfirmDialog == null) {
347            return showDialog(dialog, true, form);
348        }
349
350        boolean dialogAnswer = routeConfirmDialog.getResponseAsBoolean();
351        if (dialogAnswer) {
352            String basePath = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
353            String methodToCallDocHandler = "docHandler";
354            String methodToCallReceivingCorrection = "initiate";
355            Properties parameters = new Properties();
356            parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
357            parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingCorrection);
358            parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVC");
359            //parameters.put("docId", document.getDocumentHeader().getDocumentNumber());
360            parameters.put("documentClass", "org.kuali.ole.select.businessobject.OleCorrectionReceivingDocument");
361            parameters.put("receivingLineDocId", document.getDocumentHeader().getDocumentNumber());
362            parameters.put(PurapConstants.CorrectionReceivingDocumentStrings.CORRECTION_RECEIVING_CREATION_NOTE_PARAMETER, routeConfirmDialog.getExplanation());
363            String receivingCorrectionUrl = UrlFactory.parameterizeUrl(basePath + "/ole-kr-krad/" + "correctionItemReceivingController?viewId=OLECorrectionReceivingView", parameters);
364            return performRedirect(form, receivingCorrectionUrl);
365        } else {
366            return getModelAndView(form);
367        }
368
369    }
370
371    @MethodAccessible
372    @RequestMapping(params = "methodToCall=loadQty")
373    public ModelAndView loadQty(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
374        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
375        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
376        for (OleLineItemReceivingItem item : (List<OleLineItemReceivingItem>) lineItemReceivingDocument.getItems()) {
377            if (item.isOrderedItem()) {
378                if (item.getItemOrderedParts().subtract(item.getItemReceivedPriorParts()).isGreaterEqual(KualiDecimal.ZERO)) {
379                    item.setItemReceivedTotalParts(item.getItemOrderedQuantity().subtract(item.getItemReceivedPriorParts()));
380                } else {
381                    item.setItemReceivedTotalParts(KualiDecimal.ZERO);
382                }
383            }
384        }
385        return getModelAndView(form);
386    }
387
388    @MethodAccessible
389    @RequestMapping(params = "methodToCall=addItem")
390    public ModelAndView addItem(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
391        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
392        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
393        /*OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument();
394
395        LOG.debug("Inside addItem >>>>>>>>>>>>>>>>>");
396
397        String documentTypeName = OLEConstants.FinancialDocumentTypeCodes.LINE_ITEM_RECEIVING;
398        String nameSpaceCode = OLEConstants.OleLineItemReceiving.LINE_ITEM_RECEIVING_NAMESPACE;
399        if (LOG.isDebugEnabled()) {
400            LOG.debug("Inside addItem documentTypeName   >>>>>>>>>>>>>>>>>" + documentTypeName);
401        }
402        LOG.debug("Inside addItem nameSpaceCode  >>>>>>>>>>>>>>>>>" + nameSpaceCode);
403        // LOG.info("Inside addItem permissionDetails >>>>>>>>>>>>>>>>>" + permissionDetails.get(documentTypeName));
404
405        boolean hasPermission = SpringContext.getBean(IdentityManagementService.class).hasPermission(GlobalVariables.getUserSession().getPerson().getPrincipalId(), nameSpaceCode,
406                OLEConstants.OleLineItemReceiving.ADD_NEW_LINE_ITEM);
407
408        if (!hasPermission) {
409            if (LOG.isDebugEnabled()) {
410                LOG.debug("Inside addItem hasPermission   if>>>>>>>>>>>>>>>>>" + hasPermission);
411            }
412            throw new DocumentAuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), "add New Line Items", lineItemReceivingDocument.getDocumentNumber());
413
414            //  throw new RuntimeException("User " + new String[]{GlobalVariables.getUserSession().getPerson().getPrincipalName() + "is not authorized to add New Line Items" + true});
415        }
416
417        boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddReceivingItemEvent(PurapPropertyConstants.NEW_LINE_ITEM_RECEIVING_ITEM_LINE, lineItemReceivingDocument, item));
418        if (rulePassed) {
419            item = (OleLineItemReceivingItem) oleLineItemReceivingForm.getAndResetNewReceivingItemLine();
420            //TODO: we need to set the line number correctly to match up to PO
421
422            BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
423            FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
424            String titleId = null;
425            boolean isBibFileExist = false;
426            Iterator itemIterator = lineItemReceivingDocument.getItems().iterator();
427            int itemCounter = 0;
428            while (itemIterator.hasNext()) {
429                OleLineItemReceivingItem tempItem = (OleLineItemReceivingItem) itemIterator.next();
430                if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
431                    itemCounter++;
432                }
433            }
434            String itemNo = String.valueOf(itemCounter);
435            //String itemNo = String.valueOf(lineItemReceivingDocument.getItems().size() - 1);
436            HashMap<String, String> dataMap = new HashMap<String, String>();
437            item.setBibInfoBean(new BibInfoBean());
438            if (item.getBibInfoBean().getDocStoreOperation() == null) {
439                item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
440            }
441            String fileName = lineItemReceivingDocument.getDocumentNumber() + "_" + itemNo;
442            // Modified for jira OLE - 2437 starts
443
444            setItemDescription(item, fileName);
445            item.setStartingCopyNumber(new KualiInteger(1));*/
446
447        // Modified for jira OLE - 2437 ends
448
449
450/*dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation());
451            dataMap.put(OleSelectConstant.FILENAME, fileName);
452            if (fileProcessingService.isCreateFileExist(dataMap)) {
453                isBibFileExist = true;
454            }
455            if (isBibFileExist) {
456                titleId = docStore.getTitleIdByMarcXMLFileProcessing(item.getBibInfoBean(), dataMap);
457                item.setItemTitleId(titleId);
458                BibInfoBean xmlBibInfoBean = new BibInfoBean();
459                dataMap.put(OleSelectConstant.TITLE_ID, titleId);
460                dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
461                xmlBibInfoBean = docStore.getBibInfo(dataMap);
462                item.setBibInfoBean(xmlBibInfoBean);
463                item.setItemDescription((item.getBibInfoBean().getTitle() != null ? item.getBibInfoBean().getTitle() : "") + (item.getBibInfoBean().getAuthor() != null ? "," + item.getBibInfoBean().getAuthor() : "") + (item.getBibInfoBean().getPublisher() != null ? "," + item.getBibInfoBean().getPublisher() : "") + (item.getBibInfoBean().getIsbn() != null ? "," + item.getBibInfoBean().getIsbn() : ""));
464
465                HashMap<String,String> queryMap = new HashMap<String,String>();
466                queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, item.getItemTitleId());
467                List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
468                Iterator bibIdIterator = docStoreResult.iterator();
469
470                if(bibIdIterator.hasNext()){
471                    DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next();
472                    item.setBibUUID(docInfoBean.getUniqueId());
473                }
474            }*//*
475
476            boolean ruleFlag = getKualiRuleService().applyRules(new OleLineItemReceivingDescEvent(lineItemReceivingDocument, item));
477            if (ruleFlag) {
478                lineItemReceivingDocument.addItem(item);
479            }
480        }*/
481        return getModelAndView(form);
482    }
483
484
485    @MethodAccessible
486    @RequestMapping(params = "methodToCall=receiveCopy")
487    public ModelAndView receiveCopy(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
488        OleLineItemReceivingForm lineItemReceivingForm = (OleLineItemReceivingForm) form;
489        Map<String, String> actionParameters = form.getActionParameters();
490        String subCollectionIndex = actionParameters.get(UifParameters.SELECTED_LINE_INDEX);
491        //String focusId = form.getFocusId();
492        //int subIndex = Integer.parseInt(subCollectionIndex);
493        String mainCollectionIndex = StringUtils.substringBefore(StringUtils.substringAfter(actionParameters.get(UifParameters.SELECTED_COLLECTION_PATH), "["), "]");
494        OleLineItemReceivingItem item =null;
495        if(StringUtils.isNotEmpty(mainCollectionIndex)){
496            item = (OleLineItemReceivingItem) ((LineItemReceivingDocument) lineItemReceivingForm.getDocument()).getItem((new Integer(mainCollectionIndex)));
497        } else {
498            int mainIndex = Integer.parseInt(subCollectionIndex);
499            item = (OleLineItemReceivingItem) ((LineItemReceivingDocument) lineItemReceivingForm.getDocument()).getItem((new Integer(mainIndex)));
500        }
501        OleCopy oleCopy = null;
502        if(item.getCopyList().size()==1){
503            oleCopy =  item.getCopyList().get(0);
504        }else {
505            int copyIndex = Integer.parseInt(subCollectionIndex);
506            oleCopy = item.getCopyList().get(copyIndex);
507        }
508        oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.RECEIVED_STATUS);
509        return getModelAndView(form);
510    }
511
512    @MethodAccessible
513    @RequestMapping(params = "methodToCall=clearInitFields")
514    public ModelAndView clearInitFields(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
515        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
516        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
517        lineItemReceivingDocument.clearInitFields(oleLineItemReceivingForm.isFromPurchaseOrder());
518        return getModelAndView(form);
519    }
520
521   /* @MethodAccessible
522    @RequestMapping(params = "methodToCall=deleteDonor")
523    public ModelAndView deleteDonor(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
524        OleLineItemReceivingForm oleLineItemReceivingForm=(OleLineItemReceivingForm)form;
525        OleLineItemReceivingDocument lineItemReceivingDocument=(OleLineItemReceivingDocument)oleLineItemReceivingForm.getLineItemReceivingDocument();
526        String[] indexes = getSelectedLineForAccounts(request);
527        int itemIndex = Integer.parseInt(indexes[0]);
528        int donorIndex = Integer.parseInt(indexes[1]);
529        OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem((itemIndex));
530        item.getOleDonors().remove(donorIndex);
531        return getUIFModelAndView(form);
532    }*/
533
534    @MethodAccessible
535    @RequestMapping(params = "methodToCall=addDonor")
536    public ModelAndView addDonor(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
537        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
538        OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument();
539        String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_PATH);
540        String selectedCollectionId = form.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_ID);
541        BindingInfo addLineBindingInfo = (BindingInfo) form.getViewPostMetadata().getComponentPostData(
542                selectedCollectionId, UifConstants.PostMetadata.ADD_LINE_BINDING_INFO);
543
544        String addLinePath = addLineBindingInfo.getBindingPath();
545        Object eventObject = ObjectPropertyUtils.getPropertyValue(form, addLinePath);
546        OLELinkPurapDonor item = (OLELinkPurapDonor) eventObject;
547        Map<String, String> actionParameters = form.getActionParameters();
548        String mainCollectionIndex = StringUtils.substringBefore(StringUtils.substringAfter(actionParameters.get(UifParameters.SELECTED_COLLECTION_PATH), "["), "]");
549        int mainIndex = Integer.parseInt(mainCollectionIndex);
550        OleLineItemReceivingItem oleLineItemReceivingItem = (OleLineItemReceivingItem) (receiveDocument).getItem((new Integer(mainIndex)));
551        Map map = new HashMap();
552        boolean flag = true;
553        if (item.getDonorCode() != null) {
554            map.put(OLEConstants.DONOR_CODE, item.getDonorCode());
555            List<OLEDonor> oleDonorList = (List<OLEDonor>) KRADServiceLocatorWeb.getLookupService().findCollectionBySearch(OLEDonor.class, map);
556            if (oleDonorList != null && oleDonorList.size() > 0) {
557                OLEDonor oleDonor = oleDonorList.get(0);
558                if (oleDonor != null) {
559                    for (OLELinkPurapDonor oleLinkPurapDonor : oleLineItemReceivingItem.getOleDonors()) {
560                        if (oleLinkPurapDonor.getDonorCode().equalsIgnoreCase(item.getDonorCode())) {
561                            flag = false;
562                            GlobalVariables.getMessageMap().putErrorForSectionId("OLELineItemReceivingView-Titles",
563                                    OLEConstants.DONOR_CODE_EXISTS, new String[]{});
564                            //return mapping.findForward(OLEConstants.MAPPING_BASIC);
565                        }
566                    }
567                    if (flag) {
568                        OLELinkPurapDonor donor = new OLELinkPurapDonor();
569                        donor.setDonorId(oleDonor.getDonorId());
570                        donor.setDonorCode(oleDonor.getDonorCode());
571                        oleLineItemReceivingItem.getOleDonors().add(donor);
572                        item.setDonorCode(null);
573                    }
574                }
575            } else {
576                GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
577                        OLEConstants.ERROR_DONOR_CODE, new String[]{});
578            }
579        }
580        return getModelAndView(form);
581    }
582
583    @MethodAccessible
584    @RequestMapping(params = "methodToCall=showAddUnorderedItem")
585    public ModelAndView showAddUnorderedItem(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
586        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
587        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
588        lineItemReceivingDocument.clearInitFields(oleLineItemReceivingForm.isFromPurchaseOrder());
589        /*boolean shouldGiveWarning = lineItemReceivingForm.shouldGiveAddUnorderedItemWarning();
590        if (!shouldGiveWarning) {
591            lineItemReceivingForm.setHideAddUnorderedItem(false);
592            return mapping.findForward(OLEConstants.MAPPING_BASIC);
593        }
594
595        String msgkey = PurapKeyConstants.WARNING_RECEIVING_LINEITEM_ADD_UNORDERED;
596        String msgtxt = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(msgkey);
597        Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
598
599        if (question == null) {
600            return performQuestionWithoutInput(mapping, form, request, response, msgkey, msgtxt, OLEConstants.CONFIRMATION_QUESTION, "showAddUnorderedItem", "");
601        }
602
603        Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
604        if ((msgkey.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
605            lineItemReceivingForm.setHideAddUnorderedItem(false);
606        }*/
607        return getModelAndView(form);
608    }
609
610    @Override
611    public ModelAndView route(DocumentFormBase form) {
612        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
613        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument();
614        List<OleLineItemReceivingItem> items = lineItemReceivingDocument.getItems();
615        for (OleLineItemReceivingItem item : items) {
616            OleLineItemReceivingService oleLineItemReceivingService = SpringContext
617                    .getBean(OleLineItemReceivingServiceImpl.class);
618            OlePurchaseOrderItem olePurchaseOrderItem = oleLineItemReceivingService.getOlePurchaseOrderItem(item.getPurchaseOrderIdentifier());
619            OleLineItemReceivingDoc oleLineItemReceivingItemDoc = new OleLineItemReceivingDoc();
620            oleLineItemReceivingItemDoc.setReceivingLineItemIdentifier(item.getReceivingItemIdentifier());
621            if (item.getItemTitleId() != null) {
622                oleLineItemReceivingItemDoc.setItemTitleId(item.getItemTitleId());
623            } else {
624
625                oleLineItemReceivingItemDoc.setItemTitleId(olePurchaseOrderItem.getItemTitleId());
626            }
627            if (olePurchaseOrderItem != null) {
628
629                /* if(item.getItemReturnedTotalQuantity().isNonZero() && item.getItemReturnedTotalParts().isNonZero()){ }*/
630
631
632                OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
633                oleCopyHelperService.updateRequisitionAndPOItems(olePurchaseOrderItem, item, null, lineItemReceivingDocument.getIsATypeOfRCVGDoc());
634                //  updateReceivingItemReceiptStatus(item);
635            }
636            // oleLineItemReceivingService.saveOleLineItemReceivingItemDoc(oleLineItemReceivingItemDoc);
637        }
638        return super.route(form);    //To change body of overridden methods use File | Settings | File Templates.
639    }
640
641    @MethodAccessible
642    @RequestMapping(params = "methodToCall=correction")
643    public ModelAndView correction(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
644        OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form;
645        OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getLineItemReceivingDocument();
646        String dialog = "OLELineItemReceivingView-QuestionPromptDialogView";
647        DialogResponse routeConfirmDialog = form.getDialogResponse(dialog);
648        if (routeConfirmDialog == null) {
649            return showDialog(dialog, true, form);
650        }
651
652        boolean dialogAnswer = routeConfirmDialog.getResponseAsBoolean();
653        if (dialogAnswer) {
654            String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
655            url = url + "/portal.do?channelTitle=Correcttion Receiving KRAD&channelUrl=" + url +
656                    "/ole-kr-krad/correctionItemReceivingController?viewId=OLECorrectionReceivingView&methodToCall=createReceive&command=initiate&documentClass=org.kuali.ole.select.businessobject.OleCorrectionReceivingDocument";
657            return performRedirect(oleLineItemReceivingForm, url);
658            //return super.route(form);
659        } else {
660            return getModelAndView(form);
661        }
662
663    }
664
665
666    protected String[] getSelectedLineForAccounts(HttpServletRequest request) {
667        String accountString = new String();
668        String parameterName = (String) request.getAttribute(OLEConstants.METHOD_TO_CALL_ATTRIBUTE);
669        if (StringUtils.isNotBlank(parameterName)) {
670            accountString = StringUtils.substringBetween(parameterName, ".line", ".");
671        }
672        String[] result = StringUtils.split(accountString, ":");
673
674        return result;
675    }
676
677
678}