001/*
002 * Copyright 2006 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.module.purap.document.web.struts;
017
018import org.apache.commons.lang.StringEscapeUtils;
019import org.apache.commons.lang.StringUtils;
020import org.apache.struts.action.ActionForm;
021import org.apache.struts.action.ActionForward;
022import org.apache.struts.action.ActionMapping;
023import org.kuali.ole.coa.businessobject.Account;
024import org.kuali.ole.docstore.discovery.service.QueryService;
025import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
026import org.kuali.ole.docstore.model.bo.WorkBibDocument;
027import org.kuali.ole.docstore.model.enums.DocType;
028import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
029import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkInstanceOlemlRecordProcessor;
030import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
031import org.kuali.ole.module.purap.*;
032import org.kuali.ole.module.purap.PurapConstants.PODocumentsStrings;
033import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
034import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
035import org.kuali.ole.module.purap.businessobject.PurApItem;
036import org.kuali.ole.module.purap.document.*;
037import org.kuali.ole.module.purap.document.service.OlePurapService;
038import org.kuali.ole.module.purap.document.service.PurapService;
039import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
040import org.kuali.ole.pojo.OleBibRecord;
041import org.kuali.ole.pojo.OleEditorResponse;
042import org.kuali.ole.select.OleSelectConstant;
043import org.kuali.ole.select.businessobject.*;
044import org.kuali.ole.select.constants.OleSelectPropertyConstants;
045import org.kuali.ole.select.document.OlePurchaseOrderAmendmentDocument;
046import org.kuali.ole.select.document.service.OleDocstoreHelperService;
047import org.kuali.ole.select.document.service.OlePurchaseOrderService;
048import org.kuali.ole.select.document.service.OleRequisitionDocumentService;
049import org.kuali.ole.select.document.validation.event.CopiesPurchaseOrderEvent;
050import org.kuali.ole.select.document.validation.event.DiscountPurchaseOrderEvent;
051import org.kuali.ole.select.document.validation.event.ForeignCurrencyPOEvent;
052import org.kuali.ole.select.document.validation.event.OlePurchaseOrderDescEvent;
053import org.kuali.ole.select.service.BibInfoWrapperService;
054import org.kuali.ole.select.service.FileProcessingService;
055import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
056import org.kuali.ole.sys.OLEConstants;
057import org.kuali.ole.sys.OLEPropertyConstants;
058import org.kuali.ole.sys.businessobject.AccountingLineBase;
059import org.kuali.ole.sys.businessobject.SourceAccountingLine;
060import org.kuali.ole.sys.context.SpringContext;
061import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
062import org.kuali.ole.vnd.VendorConstants;
063import org.kuali.ole.vnd.businessobject.*;
064import org.kuali.ole.vnd.document.service.VendorService;
065import org.kuali.rice.core.api.config.property.ConfigurationService;
066import org.kuali.rice.core.api.util.RiceKeyConstants;
067import org.kuali.rice.core.api.util.type.KualiDecimal;
068import org.kuali.rice.core.api.util.type.KualiInteger;
069import org.kuali.rice.coreservice.framework.parameter.ParameterService;
070import org.kuali.rice.kns.question.ConfirmationQuestion;
071import org.kuali.rice.kns.service.DataDictionaryService;
072import org.kuali.rice.kns.util.KNSGlobalVariables;
073import org.kuali.rice.kns.web.struts.form.BlankFormFile;
074import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
075import org.kuali.rice.krad.bo.Note;
076import org.kuali.rice.krad.document.Document;
077import org.kuali.rice.krad.exception.ValidationException;
078import org.kuali.rice.krad.service.*;
079import org.kuali.rice.krad.util.GlobalVariables;
080import org.kuali.rice.krad.util.ObjectUtils;
081import org.kuali.rice.krad.util.UrlFactory;
082
083import javax.servlet.http.HttpServletRequest;
084import javax.servlet.http.HttpServletResponse;
085import java.io.ByteArrayOutputStream;
086import java.math.BigDecimal;
087import java.math.RoundingMode;
088import java.util.*;
089
090/**
091 * Struts Action for Purchase Order document.
092 */
093public class OlePurchaseOrderAction extends PurchaseOrderAction {
094    protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderAction.class);
095    private final String UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkIn&stringContent=";
096    private final String CHECKOUT_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkOut&uuid=";
097    private final String CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING = "docAction=ingestContent&stringContent=";
098    private WorkItemOlemlRecordProcessor workItemOlemlRecordProcessor;
099    private WorkHoldingOlemlRecordProcessor workHoldingOlemlRecordProcessor;
100    private WorkInstanceOlemlRecordProcessor workInstanceOlemlRecordProcessor;
101    private static transient ConfigurationService kualiConfigurationService;
102    private boolean sufficientFundChecklag = true;
103
104    /**
105     * Takes care of storing the action form in the User session and forwarding to the prlookup action.
106     *
107     * @param mapping
108     * @param form
109     * @param request
110     * @param response
111     * @return
112     * @throws Exception
113     */
114    public ActionForward performPRLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
115
116        ActionForward forward = super.performLookup(mapping, form, request, response);
117        String path = forward.getPath();
118        if (path.contains("kr/lookup.do")) {
119            path = path.replace("kr/lookup.do", "prlookup.do");
120            // path = path.replace("kr/lookup.do", "ptrnlookup.do");
121        } else if (path.contains("lookup.do")) {
122            path = path.replace("lookup.do", "prlookup.do");
123            // path = path.replace("lookup.do", "ptrnlookup.do");
124        }
125        forward.setPath(path);
126
127        return forward;
128
129    }
130
131    /**
132     * @see org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
133     */
134    @Override
135    public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
136
137        PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
138        List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
139        for(PurApItem purApItem:purApItems){
140            List<KualiDecimal> existingAmount=new ArrayList<>();
141            for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
142                if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
143                    if(((OlePurchaseOrderAccount)oldSourceAccountingLine).getExistingAmount()!=null){
144                        existingAmount.add(((OlePurchaseOrderAccount)oldSourceAccountingLine).getExistingAmount());
145                    }
146                }
147            }
148            int count=0;
149            for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
150
151                if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) {
152                    if (account.getAmount()!=null&&count<existingAmount.size()&&existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) {
153                        KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString());
154                        account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE));
155                    }
156                    else {
157                        if(account.getAccountLinePercent().intValue()==100&&(account.getAmount()==null||account.getAccount()!=null)){
158                            KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
159                            account.setAmount(calculatedAmount);
160                        }
161                        else{
162                            KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
163                            account.setAmount(calculatedAmount);
164                        }
165                    }
166                }
167                count++;
168            }
169            for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
170                if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
171                    ((OlePurchaseOrderAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
172                }
173            }
174        }
175        ActionForward forward = super.calculate(mapping, form, request, response);
176        /* calculateCurrency(mapping, form, request, response); */
177        purchasingForm = (PurchasingAccountsPayableFormBase) form;
178        PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
179        PurchasingFormBase formBase = (PurchasingFormBase) form;
180
181        PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) formBase.getDocument();
182        List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems();
183        if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && purDoc.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != true)) {
184            for (int i = 0; purDoc.getItems().size() > i; i++) {
185                OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i);
186                if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
187                    boolean rulePassed = getKualiRuleService().applyRules(new DiscountPurchaseOrderEvent(purchaseDoc, item));
188                    if (rulePassed) {
189                        item.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item));
190                    }
191                    rulePassed = getKualiRuleService().applyRules(new CopiesPurchaseOrderEvent(purDoc, item));
192                }
193
194            }
195        } else {
196            LOG.debug("###########Foreign Currency Field Calculation in olepurchaseOrder action###########");
197            BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
198            for (int i = 0; purItem.size() > i; i++) {
199                OlePurchaseOrderItem items = (OlePurchaseOrderItem) purchaseDoc.getItem(i);
200                if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
201                    boolean rulePassed = getKualiRuleService().applyRules(new ForeignCurrencyPOEvent(purchaseDoc, items));
202                    if (rulePassed) {
203                        SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
204                        Long id = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
205                        Map currencyTypeMap = new HashMap();
206                        currencyTypeMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
207                        List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, currencyTypeMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
208                        Iterator iterator = exchangeRateList.iterator();
209                        if (iterator.hasNext()) {
210                            OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
211                            String documentNumber = purchaseDoc.getDocumentNumber();
212                            Map documentNumberMap = new HashMap();
213                            documentNumberMap.put(OLEPropertyConstants.DOCUMENT_NUMBER, documentNumber);
214                            List<OlePurchaseOrderItem> currenctExchangeRateList = (List) businessObjectService.findMatching(OlePurchaseOrderItem.class, documentNumberMap);
215                            Iterator iterate = currenctExchangeRateList.iterator();
216                            if (iterate.hasNext()) {
217                                OlePurchaseOrderItem tempCurrentExchangeRate = (OlePurchaseOrderItem) iterate.next();
218                                String poCurrencyType = null;
219                                if (tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail().getCurrencyType() != null) {
220                                    poCurrencyType = tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail().getCurrencyType().getCurrencyType();
221                                }
222                                String poaCurrencyType = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyType();
223                                if (poCurrencyType != null && (poCurrencyType.equalsIgnoreCase(poaCurrencyType)) && !items.isLatestExchangeRate() && !purchaseDoc.getIsPODoc() && ((purchaseDoc instanceof PurchaseOrderAmendmentDocument) || (purchaseDoc instanceof PurchaseOrderSplitDocument) || (purchaseDoc instanceof PurchaseOrderReopenDocument))) {
224                                    items.setItemExchangeRate(tempCurrentExchangeRate.getItemExchangeRate());
225                                } else {
226                                    items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
227                                }
228                            }
229                            if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
230                                items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
231                                items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue());
232                                items.setItemListPrice(items.getItemUnitCostUSD());
233                            }
234                        }
235                    }
236                }
237            }
238        }
239
240        purchasingForm = (PurchasingAccountsPayableFormBase) form;
241        List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
242        for(PurApItem purApItem:newpurApItems){
243            for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
244                KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
245                account.setAmount(calculatedAmount);
246            }
247        }
248        forward = super.calculate(mapping, form, request, response);
249    //    setEnumerationToCopies(purItem);
250
251
252        // Added for SFC - Start
253
254        OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext
255                .getBean("oleRequisitionDocumentService");
256        List<SourceAccountingLine> sourceAccountingLineList = purDoc.getSourceAccountingLines();
257        for (SourceAccountingLine accLine : sourceAccountingLineList) {
258            Map searchMap = new HashMap();
259            String notificationOption = null;
260            boolean sufficientFundCheck;
261            Map<String, Object> key = new HashMap<String, Object>();
262            String chartCode = accLine.getChartOfAccountsCode();
263            String accNo = accLine.getAccountNumber();
264            String objectCd = accLine.getFinancialObjectCode();
265            key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
266            key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
267            OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
268                    OleSufficientFundCheck.class, key);
269            if (account != null) {
270                notificationOption = account.getNotificationOption();
271            }
272            if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) {
273                sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine);
274                if (sufficientFundCheck) {
275                    GlobalVariables.getMessageMap().putError(
276                            OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM,
277                            OLEConstants.SufficientFundCheck.INSUFF_FUND_POA + accLine.getAccountNumber());
278                }
279            }
280        }
281
282        // End
283
284        // formBase.setCalculated(true);
285        if (LOG.isDebugEnabled()) {
286            LOG.debug("Inside the OlePurchaseOrderAction class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice());
287        }
288        return forward;
289    }
290
291    /**
292     * @see org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction#addItem(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
293     */
294    @Override
295    public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
296
297        LOG.debug("###########Inside AddItem in olePurchaseOrderAction ###########");
298        PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
299        OlePurchaseOrderItem purchaseOrderItem = (OlePurchaseOrderItem) purchasingForm.getNewPurchasingItemLine();
300        purchaseOrderItem.getNewSourceLine().setAccountLinePercent(new BigDecimal(100));
301        //purchasingForm.getNewPurchasingItemLine().setItemDescription((purchaseOrderItem.getBibInfoBean().getTitle() != null ? purchaseOrderItem.getBibInfoBean().getTitle() : "") + (purchaseOrderItem.getBibInfoBean().getAuthor() != null ? "," + purchaseOrderItem.getBibInfoBean().getAuthor() : "") + (purchaseOrderItem.getBibInfoBean().getPublisher() != null ? "," + purchaseOrderItem.getBibInfoBean().getPublisher() : "") + (purchaseOrderItem.getBibInfoBean().getIsbn() != null ? "," + purchaseOrderItem.getBibInfoBean().getIsbn() : ""));
302        PurchaseOrderDocument document = (PurchaseOrderDocument) purchasingForm.getDocument();
303
304        // changes done for BibEditor starts
305
306        OlePurchaseOrderForm oleForm = (OlePurchaseOrderForm) form;
307        PurchaseOrderDocument doc = (PurchaseOrderDocument) oleForm.getDocument();
308        BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
309        FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
310        String titleId = null;
311        boolean isBibFileExist = false;
312        Iterator itemIterator = doc.getItems().iterator();
313        int itemCounter = 0;
314        while (itemIterator.hasNext()) {
315            OlePurchaseOrderItem tempItem = (OlePurchaseOrderItem) itemIterator.next();
316            if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
317                itemCounter++;
318            }
319        }
320        String itemNo = String.valueOf(itemCounter);
321        //String itemNo = String.valueOf(doc.getItems().size() - 4);
322        HashMap<String, String> dataMap = new HashMap<String, String>();
323        BibInfoBean xmlBibInfoBean = new BibInfoBean();
324        if (purchaseOrderItem.getBibInfoBean() == null) {
325            purchaseOrderItem.setBibInfoBean(xmlBibInfoBean);
326            if (purchaseOrderItem.getBibInfoBean().getDocStoreOperation() == null) {
327                purchaseOrderItem.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
328            }
329        }
330        String fileName = document.getDocumentNumber() + "_" + itemNo;
331
332        // Modified for jira OLE - 2437 starts
333
334        setItemDescription(purchaseOrderItem, fileName);
335    //    purchaseOrderItem.setStartingCopyNumber(new KualiInteger(1));
336
337        // Modified for jira OLE - 2437 ends
338
339       /* dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation());
340        dataMap.put(OleSelectConstant.FILENAME, fileName);
341        if (fileProcessingService.isCreateFileExist(dataMap)) {
342            isBibFileExist = true;
343        }
344        if (isBibFileExist) {
345            titleId = docStore.getTitleIdByMarcXMLFileProcessing(purchaseOrderItem.getBibInfoBean(), dataMap);
346            purchaseOrderItem.setItemTitleId(titleId);
347            dataMap.put(OleSelectConstant.TITLE_ID, titleId);
348            dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
349            xmlBibInfoBean = docStore.getBibInfo(dataMap);
350            purchaseOrderItem.setBibInfoBean(xmlBibInfoBean);
351            purchasingForm.getNewPurchasingItemLine().setItemDescription((purchaseOrderItem.getBibInfoBean().getTitle() != null ? purchaseOrderItem.getBibInfoBean().getTitle() : "") + (purchaseOrderItem.getBibInfoBean().getAuthor() != null ? "," + purchaseOrderItem.getBibInfoBean().getAuthor() : "") + (purchaseOrderItem.getBibInfoBean().getPublisher() != null ? "," + purchaseOrderItem.getBibInfoBean().getPublisher() : "") + (purchaseOrderItem.getBibInfoBean().getIsbn() != null ? "," + purchaseOrderItem.getBibInfoBean().getIsbn() : ""));
352
353            HashMap<String,String> queryMap = new HashMap<String,String>();
354            queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, purchaseOrderItem.getItemTitleId());
355            List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
356            Iterator bibIdIterator = docStoreResult.iterator();
357            if(bibIdIterator.hasNext()){
358                DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next();
359                purchaseOrderItem.setBibUUID(docInfoBean.getUniqueId());
360            }
361        }*/
362        // changes done for BibEditor ends
363        boolean ruleFlag = getKualiRuleService().applyRules(new OlePurchaseOrderDescEvent(document, purchaseOrderItem));
364        if (ruleFlag) {
365            if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && !document.getVendorDetail().getVendorHeader().getVendorForeignIndicator())) {
366                boolean rulePassed = getKualiRuleService().applyRules(new DiscountPurchaseOrderEvent(document, purchaseOrderItem));
367                if (rulePassed) {
368                    purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(purchaseOrderItem));
369                    super.addItem(mapping, purchasingForm, request, response);
370                }
371            } else {
372                boolean rulePassed = getKualiRuleService().applyRules(new ForeignCurrencyPOEvent(document, purchaseOrderItem));
373                if (rulePassed) {
374                    LOG.debug("###########Foreign Currency Field additem for purchase Order ###########");
375                    SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(purchaseOrderItem);
376                    Long id = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
377                    Map documentNumberMap = new HashMap();
378                    documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
379                    BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
380                    List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
381                    Iterator iterator = exchangeRateList.iterator();
382                    if (iterator.hasNext()) {
383                        OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
384                        purchaseOrderItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
385                    }
386                    if (purchaseOrderItem.getItemExchangeRate() != null && purchaseOrderItem.getItemForeignUnitCost() != null) {
387                        purchaseOrderItem.setItemUnitCostUSD(new KualiDecimal(purchaseOrderItem.getItemForeignUnitCost().bigDecimalValue().divide(purchaseOrderItem.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
388                        purchaseOrderItem.setItemUnitPrice(purchaseOrderItem.getItemUnitCostUSD().bigDecimalValue());
389                        purchaseOrderItem.setItemListPrice(purchaseOrderItem.getItemUnitCostUSD());
390                    }
391                    super.addItem(mapping, purchasingForm, request, response);
392                }
393            }
394        }
395        return mapping.findForward(OLEConstants.MAPPING_BASIC);
396    }
397
398    /**
399     * Add Note for the selected PurchaseOrderItem
400     *
401     * @param mapping
402     * @param form
403     * @param request
404     * @param response
405     * @return An ActionForward
406     * @throws Exception
407     */
408
409    public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
410        LOG.debug("Inside addNote Method of PurchaseOrderAction");
411        PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
412        int line = this.getSelectedLine(request);
413        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
414        OlePurchaseOrderNotes note = new OlePurchaseOrderNotes();
415        note.setNote(item.getNote());
416        note.setNoteTypeId(item.getNoteTypeId());
417        item.getNotes().add(note);
418        LOG.debug("Adding Note to PurchaseOrderItem");
419        item.setNote(null);
420        item.setNoteTypeId(null);
421        LOG.debug("Leaving addNote Method of PurchaseOrderAction");
422        return mapping.findForward(OLEConstants.MAPPING_BASIC);
423    }
424
425    /**
426     * deletes the selected Note for the selected POItem
427     *
428     * @param mapping
429     * @param form
430     * @param request
431     * @param response
432     * @return An ActionForward
433     * @throws Exception
434     */
435    public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
436        LOG.debug("Inside deleteNote Method of PurchaseOrderAction");
437        PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
438
439        String[] indexes = getSelectedLineForAccounts(request);
440        int itemIndex = Integer.parseInt(indexes[0]);
441        int noteIndex = Integer.parseInt(indexes[1]);
442        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
443        item.getNotes().remove(noteIndex);
444        LOG.debug("Note deleted for the selected Item");
445        LOG.debug("Leaving deleteNote Method of PurchaseOrderAction");
446        return mapping.findForward(OLEConstants.MAPPING_BASIC);
447    }
448
449    /**
450     * This method is overridden to change receivingitem url with respect to OLE
451     *
452     * @see org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction#createReceivingLine(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
453     */
454    @Override
455    public ActionForward createReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
456        LOG.debug("Inside createReceivingLine Method of OlePurchaseOrderAction");
457        PurchaseOrderForm poForm = (PurchaseOrderForm) form;
458        PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
459
460        String basePath = getApplicationBaseUrl();
461        String methodToCallDocHandler = "continueReceivingLine";
462        String methodToCallReceivingLine = "initiate";
463
464        //set parameters
465        Properties parameters = new Properties();
466        parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
467        parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingLine);
468        parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVL");
469        parameters.put("purchaseOrderId", document.getPurapDocumentIdentifier().toString());
470
471        //create url
472        // Changed receivingUrl to point to the OLE receiving URL (OLE-2057)
473        String receivingUrl = UrlFactory.parameterizeUrl(basePath + "/" + "selectOleLineItemReceiving.do", parameters);
474
475        //create forward
476        ActionForward forward = new ActionForward(receivingUrl, true);
477        LOG.debug("Leaving createReceivingLine Method of OlePurchaseOrderAction");
478        return forward;
479    }
480
481    /**
482     * Creates a URL to be used in printing the purchase order.
483     *
484     * @param basePath     String: The base path of the current URL
485     * @param docId        String: The document ID of the document to be printed
486     * @param methodToCall String: The name of the method that will be invoked to do this particular print
487     * @return The URL
488     */
489    @Override
490    protected String getUrlForPrintPO(String basePath, String docId, String methodToCall) {
491        StringBuffer result = new StringBuffer(basePath);
492        result.append("/purapOlePurchaseOrder.do?methodToCall=");
493        result.append(methodToCall);
494        result.append("&docId=");
495        result.append(docId);
496        result.append("&command=displayDocSearchView");
497
498        return result.toString();
499    }
500
501    @Override
502    public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
503        PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
504        PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
505        if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
506            //   setDocstoreDataForCopies((OlePurchaseOrderAmendmentDocument) purDoc);
507        }
508        // if form is not yet calculated, return and prompt user to calculate
509        if (requiresCalculate(purchasingForm)) {
510            GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
511
512            return mapping.findForward(OLEConstants.MAPPING_BASIC);
513        }
514
515        // call prorateDiscountTradeIn
516        SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
517        this.calculate(mapping, purchasingForm, request, response);
518        return super.route(mapping, form, request, response);
519
520    }
521
522    public void setDocstoreDataForCopies(OlePurchaseOrderAmendmentDocument purDoc) throws Exception {
523        List<OlePurchaseOrderItem> items = new ArrayList<OlePurchaseOrderItem>();
524        items = purDoc.getItems();
525        Iterator iterator = items.iterator();
526        while (iterator.hasNext()) {
527            Object object = iterator.next();
528            if (object instanceof OlePurchaseOrderItem) {
529                OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
530                List<String> itemTitleIdsList = new ArrayList<String>();
531                List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
532                // for (OlePurchaseOrderItem itemTitleId : items) {
533                if (null != singleItem.getItemTitleId()) {
534                    if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
535                            || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
536                        itemTitleIdsList.add(singleItem.getItemTitleId());
537                        workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
538                        for (WorkBibDocument workBibDocument : workBibDocuments) {
539
540                          /*  OleDocstoreHelperService oleDocstoreHelperService = SpringContext
541                                    .getBean(OleDocstoreHelperService.class);
542                            oleDocstoreHelperService.performDocstoreUpdationForPOItem(singleItem, workBibDocument);*/
543                        }
544                    }
545                }
546                // }
547                // setEnumerationToCopies(singleItem);
548                /*
549                 * if (null != singleItem.getItemTitleId() && workBibDocuments.size() > 0) { }
550                 */
551            }
552        }
553    }
554
555    public void setEnumerationToCopies(List<OlePurchaseOrderItem> purItem) {
556        String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
557                OLEConstants.PART_ENUMERATION_COPY);
558        String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
559                OLEConstants.PART_ENUMERATION_VOLUME);
560        for (int singleItem = 0; purItem.size() > singleItem; singleItem++) {
561            List<OleCopies> purItemCopies = purItem.get(singleItem).getCopies();
562            List<OleCopies> copiesList = new ArrayList<OleCopies>();
563            for (int copies = 0; copies < purItemCopies.size(); copies++) {
564                purItemCopies.get(copies).setParts(purItem.get(singleItem).getItemNoOfParts());
565                int startingCopyNumber = purItemCopies.get(copies).getStartingCopyNumber().intValue();
566                StringBuffer enumeration = new StringBuffer();
567                for (int noOfCopies = 0; noOfCopies < purItemCopies.get(copies).getItemCopies().intValue(); noOfCopies++) {
568                    for (int noOfParts = 0; noOfParts < purItemCopies.get(copies).getParts().intValue(); noOfParts++) {
569                        int newNoOfCopies = startingCopyNumber + noOfCopies;
570                        int newNoOfParts = noOfParts + 1;
571                        if (noOfCopies + 1 == purItemCopies.get(copies).getItemCopies().intValue()
572                                && newNoOfParts == purItemCopies.get(copies).getParts().intValue()) {
573                            enumeration = enumeration.append(
574                                    partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
575                                    partEnumerationVolume + newNoOfParts);
576                        } else {
577                            enumeration = enumeration.append(
578                                    partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
579                                    partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
580                        }
581                    }
582                }
583                purItemCopies.get(copies).setPartEnumeration(enumeration.toString());
584            }
585        }
586    }
587
588
589    /**
590     * For use with a specific set of methods of this class that create new purchase order-derived document types in response to
591     * user actions, including <code>closePo</code>, <code>reopenPo</code>, <code>paymentHoldPo</code>, <code>removeHoldPo</code>,
592     * <code>splitPo</code>, <code>amendPo</code>, and <code>voidPo</code>. It employs the question framework to ask
593     * the user for a response before creating and routing the new document. The response should consist of a note detailing a
594     * reason, and either yes or no. This method can be better understood if it is noted that it will be gone through twice (via the
595     * question framework); when each question is originally asked, and again when the yes/no response is processed, for
596     * confirmation.
597     *
598     * @param mapping      These are boiler-plate.
599     * @param form         "
600     * @param request      "
601     * @param response     "
602     * @param questionType A string identifying the type of question being asked.
603     * @param confirmType  A string identifying which type of question is being confirmed.
604     * @param documentType A string, the type of document to create
605     * @param notePrefix   A string to appear before the note in the BO Notes tab
606     * @param messageType  A string to appear on the PO once the question framework is done, describing the action taken
607     * @param operation    A string, the verb to insert in the original question describing the action to be taken
608     * @return An ActionForward
609     * @throws Exception
610     */
611    @Override
612    protected ActionForward askQuestionsAndPerformDocumentAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType, String confirmType, String documentType, String notePrefix, String messageType, String operation) throws Exception {
613        LOG.debug("askQuestionsAndPerformDocumentAction started.");
614        KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
615        PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
616        Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
617        String reason = request.getParameter(OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME);
618        String noteText = "";
619
620        try {
621            ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
622
623            // Start in logic for confirming the proposed operation.
624            if (ObjectUtils.isNull(question)) {
625                String message = "";
626                if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
627                    message = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_SPLIT_QUESTION_TEXT);
628                } else {
629                    String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
630                    message = StringUtils.replace(key, "{0}", operation);
631                }
632                // Ask question if not already asked.
633                return this.performQuestionWithInput(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "");
634            } else {
635                Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
636                if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
637
638                    // If 'No' is the button clicked, just reload the doc
639                    return returnToPreviousPage(mapping, kualiDocumentFormBase);
640                } else if (question.equals(confirmType) && buttonClicked.equals(SingleConfirmationQuestion.OK)) {
641
642                    // This is the case when the user clicks on "OK" in the end.
643                    // After we inform the user that the close has been rerouted, we'll redirect to the portal page.
644                    return mapping.findForward(OLEConstants.MAPPING_PORTAL);
645                } else {
646                    // Have to check length on value entered.
647                    String introNoteMessage = notePrefix + OLEConstants.BLANK_SPACE;
648
649                    // Build out full message.
650                    noteText = introNoteMessage + reason;
651                    int noteTextLength = noteText.length();
652
653                    // Get note text max length from DD.
654                    int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(Note.class, OLEConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
655
656                    if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
657                        // Figure out exact number of characters that the user can enter.
658                        int reasonLimit = noteTextMaxLength - noteTextLength;
659
660                        if (ObjectUtils.isNull(reason)) {
661                            // Prevent a NPE by setting the reason to a blank string.
662                            reason = "";
663                        }
664
665                        String message = "";
666                        String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
667                        message = StringUtils.replace(key, "{0}", operation);
668
669                        return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
670                    }
671                }
672            }
673            // Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
674            ActionForward returnActionForward = null;
675            if (!po.isPendingActionIndicator()) {
676                /*
677                 * Below if-else code block calls PurchaseOrderService methods that will throw ValidationException objects if errors
678                 * occur during any process in the attempt to perform its actions. Assume, if these return successfully, that the
679                 * PurchaseOrderDocument object returned from each is the newly created document and that all actions in the method
680                 * were run correctly. NOTE: IF BELOW IF-ELSE IS EDITED THE NEW METHODS CALLED MUST THROW ValidationException OBJECT
681                 * IF AN ERROR IS ADDED TO THE GlobalVariables
682                 */
683                if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
684                    po.setPendingSplit(true);
685                    // Save adding the note for after the items are picked.
686                    ((PurchaseOrderForm) kualiDocumentFormBase).setSplitNoteText(noteText);
687                    returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
688                } else {
689                    String newStatus = null;
690                    if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
691
692                        newStatus = PurchaseOrderStatuses.APPDOC_AMENDMENT;
693                        po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
694                        returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
695                    } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
696                        newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REOPEN;
697                        po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
698                    } else {
699                        if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT)) {
700                            newStatus = PurchaseOrderStatuses.APPDOC_PENDING_CLOSE;
701                        }
702                        /*else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
703                            newStatus = PurchaseOrderStatuses.PENDING_REOPEN;
704                        }*/
705                        else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
706                            newStatus = PurchaseOrderStatuses.APPDOC_PENDING_VOID;
707                        } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)) {
708                            newStatus = PurchaseOrderStatuses.APPDOC_PENDING_PAYMENT_HOLD;
709                        } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT)) {
710                            newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REMOVE_HOLD;
711                        } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT)) {
712                            newStatus = PurchaseOrderStatuses.APPDOC_PENDING_RETRANSMIT;
713                        }
714                        po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), newStatus);
715                    }
716                    if (!GlobalVariables.getMessageMap().hasNoErrors()) {
717                        throw new ValidationException("errors occurred during new PO creation");
718                    }
719
720                    String previousDocumentId = kualiDocumentFormBase.getDocId();
721                    // Assume at this point document was created properly and 'po' variable is new PurchaseOrderDocument created
722                    kualiDocumentFormBase.setDocument(po);
723                    kualiDocumentFormBase.setDocId(po.getDocumentNumber());
724                    kualiDocumentFormBase.setDocTypeName(po.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
725
726                    Note newNote = new Note();
727                    if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
728                        noteText = noteText + " (Previous Document Id is " + previousDocumentId + ")";
729                    }
730                    newNote.setNoteText(noteText);
731                    newNote.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
732                    kualiDocumentFormBase.setNewNote(newNote);
733
734                    kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
735
736                    insertBONote(mapping, kualiDocumentFormBase, request, response);
737                }
738                if (StringUtils.isNotEmpty(messageType)) {
739                    KNSGlobalVariables.getMessageList().add(messageType);
740                }
741            }
742            if (ObjectUtils.isNotNull(returnActionForward)) {
743                return returnActionForward;
744            } else {
745
746                return this.performQuestionWithoutInput(mapping, form, request, response, confirmType, kualiConfiguration.getPropertyValueAsString(messageType), PODocumentsStrings.SINGLE_CONFIRMATION_QUESTION, questionType, "");
747            }
748        } catch (ValidationException ve) {
749            throw ve;
750        }
751    }
752
753    @Override
754    public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
755        LOG.debug("<<<---------Inside OlePurchaseOrderAction Refresh------>>>");
756        ActionForward forward = super.refresh(mapping, form, request, response);
757        OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
758        PurchaseOrderDocument document = (PurchaseOrderDocument) rqForm.getDocument();
759        OlePurchaseOrderItem item = (OlePurchaseOrderItem) rqForm.getNewPurchasingItemLine();
760        // To set PurchaseOrderTransmissionMethod depend on vendor transmission format
761        if (document.getVendorDetail() != null) {
762            if (document.getVendorDetail().getVendorTransmissionFormat().size() > 0) {
763                List<VendorTransmissionFormatDetail> vendorTransmissionFormat = document.getVendorDetail().getVendorTransmissionFormat();
764                for (VendorTransmissionFormatDetail iter : vendorTransmissionFormat) {
765                    if (iter.isVendorPreferredTransmissionFormat()) {
766                        if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat() != null) {
767                            if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat().equalsIgnoreCase(OleSelectConstant.VENDOR_TRANSMISSION_FORMAT_EDI)) {
768                                document.setPurchaseOrderTransmissionMethodCode(OleSelectConstant.METHOD_OF_PO_TRANSMISSION_NOPR);
769                            } else {
770                                document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
771                            }
772                        }
773                    }
774                }
775            } else {
776                document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
777            }
778            if (document.getVendorDetail().getVendorHeader().getVendorForeignIndicator() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
779                Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
780                Map documentNumberMap = new HashMap();
781                documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
782                BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
783                List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
784                Iterator iterator = exchangeRateList.iterator();
785                if (iterator.hasNext()) {
786                    OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
787                    item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
788                }
789            }
790        }
791        return forward;
792    }
793
794    @Override
795    public ActionForward amendPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
796        // TODO Auto-generated method stub
797        ActionForward findForward = super.amendPo(mapping, form, request, response);
798        OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
799        OlePurchaseOrderAmendmentDocument olePurchaseOrderAmendmentDocument = new OlePurchaseOrderAmendmentDocument();
800        if ((rqForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
801            rqForm.getAndResetNewPurchasingItemLine();
802        }
803        KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
804        Document document = kualiDocumentFormBase.getDocument();
805        // prepare for the reload action - set doc id and command
806        kualiDocumentFormBase.setDocId(document.getDocumentNumber());
807        kualiDocumentFormBase.setCommand(DOCUMENT_LOAD_COMMANDS[1]);
808        // forward off to the doc handler
809        docHandler(mapping, form, request, response);
810
811        return findForward;
812    }
813
814    /**
815     * Is executed when the user clicks on the "print" button on a Purchase Order Print Document page. On a non
816     * javascript enabled browser, it will display a page with 2 buttons. One is to display the PDF, the other is to view the PO
817     * tabbed page where the PO document statuses, buttons, etc have already been updated (the updates of those occurred while the
818     * <code>performPurchaseOrderFirstTransmitViaPrinting</code> method is invoked. On a javascript enabled browser, it will
819     * display both the PO tabbed page containing the updated PO document info and the pdf on the next window/tab of the browser.
820     *
821     * @param mapping  An ActionMapping
822     * @param form     An ActionForm
823     * @param request  The HttpServletRequest
824     * @param response The HttpServletResponse
825     * @return An ActionForward
826     * @throws Exception
827     */
828    @Override
829    public ActionForward firstTransmitPrintPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
830        PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
831        String poDocId = ((PurchaseOrderForm) form).getDocId();
832        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
833        try {
834            SpringContext.getBean(OlePurchaseOrderService.class).performPurchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
835        } finally {
836            if (baosPDF != null) {
837                baosPDF.reset();
838            }
839        }
840        String basePath = getApplicationBaseUrl();
841        String docId = ((PurchaseOrderForm) form).getDocId();
842        String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
843        String methodToCallDocHandler = "docHandler";
844        String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
845        String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
846        request.setAttribute("printPOPDFUrl", printPOPDFUrl);
847        request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
848        String label = "";
849        if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
850            label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
851        } else {
852            label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
853        }
854        request.setAttribute("purchaseOrderLabel", label);
855
856        return mapping.findForward("printPurchaseOrderPDF");
857    }
858
859    public ActionForward printPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
860        PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
861        String poDocId = ((PurchaseOrderForm) form).getDocId();
862        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
863        try {
864            SpringContext.getBean(OlePurchaseOrderService.class).purchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
865        } finally {
866            if (baosPDF != null) {
867                baosPDF.reset();
868            }
869        }
870        String basePath = getApplicationBaseUrl();
871        String docId = ((PurchaseOrderForm) form).getDocId();
872        String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
873        String methodToCallDocHandler = "docHandler";
874        String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
875        String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
876        request.setAttribute("printPOPDFUrl", printPOPDFUrl);
877        request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
878        String label = "";
879        if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
880            label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
881        } else {
882            label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
883        }
884        request.setAttribute("purchaseOrderLabel", label);
885
886        return mapping.findForward("printPurchaseOrderPDF");
887    }
888
889    /**
890     * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
891     *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
892     */
893    @Override
894    public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
895        // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
896        PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
897
898        // index of item selected
899        int itemIndex = getSelectedLine(request);
900        PurApItem item = null;
901
902        // if custom processing of an accounting line is not done then insert a line generically.
903        if (processCustomInsertAccountingLine(purapForm, request) == false) {
904            String errorPrefix = null;
905            PurApAccountingLine line = null;
906
907            boolean rulePassed = false;
908            if (itemIndex >= 0) {
909                item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
910                //Calculating the dollar amount for the accounting Line.
911                PurApAccountingLine lineItem = item.getNewSourceLine();
912                if (lineItem.getAccountLinePercent() != null) {
913                    BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
914                    lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
915                } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
916                    KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
917                    BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
918                    lineItem.setAccountLinePercent(dollarToPercent);
919                }
920                line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
921                //end
922                //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
923                errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
924                rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
925            } else if (itemIndex == -2) {
926                //corrected: itemIndex == -2 is the only case for distribute account
927                //This is the case when we're inserting an accounting line for distribute account.
928                line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
929                //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
930                errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
931                rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
932            }
933            AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
934            if (accountingLineBase != null) {
935                String accountNumber = accountingLineBase.getAccountNumber();
936                String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
937                Map<String, String> criteria = new HashMap<String, String>();
938                criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
939                criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
940                Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
941                        criteria);
942                rulePassed = checkForValidAccount(account);
943            }
944            if (rulePassed) {
945                // add accountingLine
946                SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
947
948                PurApAccountingLine newSourceLine = item.getNewSourceLine();
949                List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();
950
951                BigDecimal initialValue = new BigDecimal(0);
952
953                for (PurApAccountingLine accountLine : existingSourceLine) {
954                    initialValue = initialValue.add(accountLine.getAccountLinePercent());
955                }
956                if (itemIndex >= 0) {
957
958                    if ((newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
959                        if (OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue() != OleSelectConstant.ZERO) {
960                            insertAccountingLine(purapForm, item, line);
961                        }
962                    }else {
963                        checkAccountingLinePercent(newSourceLine);
964
965                    }
966                    for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
967                        if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
968                            ((OlePurchaseOrderAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
969                        }
970                    }
971                    List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
972                    BigDecimal totalPercent = new BigDecimal(100);
973                    BigDecimal initialPercent = new BigDecimal(0);
974                    for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
975                        initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
976
977                    }
978                    initialPercent = totalPercent.subtract(initialPercent);
979                    BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
980                    if (maxPercent.intValue() == OleSelectConstant.ZERO) {
981                        item.resetAccount(OleSelectConstant.ZERO_PERCENT);
982
983                    } else {
984                        item.resetAccount(initialPercent);
985
986                    }
987                } else if (itemIndex == -2) {
988                    //this is the case for distribute account
989                    ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
990                }
991            }
992        }
993
994        return mapping.findForward(OLEConstants.MAPPING_BASIC);
995    }
996
997    private void checkAccountingLinePercent(PurApAccountingLine newSourceLine) {
998        if (newSourceLine.getAccountLinePercent().intValue() >= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED) {
999            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1000                    OleSelectPropertyConstants.ERROR_PERCENT_SHOULD_GREATER, OleSelectConstant.PERCENT);
1001        } else if (newSourceLine.getAccountLinePercent().intValue() == OleSelectConstant.ZERO) {
1002            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1003                    OleSelectPropertyConstants.ERROR_PERCENT_ZERO, OleSelectConstant.PERCENT);
1004        } else {
1005
1006        }
1007
1008    }
1009
1010    private boolean checkForValidAccount(Account account) {
1011        boolean result = true;
1012        if (account != null) {
1013            String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
1014                    OleSelectConstant.SUB_FUND_GRP_CD);
1015            if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
1016                GlobalVariables.getMessageMap()
1017                        .putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1018                                OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
1019                                new String[]{OleSelectConstant.PURCHASE_ORDER});
1020                result = false;
1021            }
1022        }
1023        return result;
1024    }
1025
1026    private void setItemDescription(OlePurchaseOrderItem item, String fileName) {
1027
1028        if (OleDocstoreResponse.getInstance().getDocstoreResponse() != null) {
1029            HashMap<String, OleEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getDocstoreResponse();
1030            OleEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
1031            StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
1032            OleBibRecord oleBibRecord = oleEditorResponse != null ? oleEditorResponse.getOleBibRecord() : null;
1033            Map<String, ?> bibAssociatedFieldValuesMap = oleBibRecord != null ? oleBibRecord.getBibAssociatedFieldsValueMap() : null;
1034            if (bibAssociatedFieldValuesMap != null && bibAssociatedFieldValuesMap.size() > 0) {
1035                List titleList = (List) bibAssociatedFieldValuesMap.get("Title_search");
1036                String title = titleList != null && !titleList.isEmpty() ? (String) (titleList).get(0) + ", " : "";
1037                title = stringEscapeUtils.unescapeXml(title);
1038                List authorList = (List) bibAssociatedFieldValuesMap.get("Author_search");
1039                String author = (authorList != null && !authorList.isEmpty() ? (String) (authorList).get(0) + ", " : "");
1040                author = stringEscapeUtils.unescapeXml(author);
1041                List publisherList = (List) bibAssociatedFieldValuesMap.get("Publisher_display");
1042                String publisher = (publisherList != null && !publisherList.isEmpty() ? (String) (publisherList).get(0)
1043                        + ", " : "");
1044                publisher = stringEscapeUtils.unescapeXml(publisher);
1045                List isbnList = (List) bibAssociatedFieldValuesMap.get("020a");
1046                String isbn = (isbnList != null && !isbnList.isEmpty() ? (String) (isbnList).get(0) + ", " : "");
1047                String description = title + author + publisher + isbn;
1048                item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
1049            }
1050            if (oleBibRecord != null) {
1051                item.setBibUUID(oleBibRecord.getBibUUID());
1052                item.setItemTitleId(oleBibRecord.getBibUUID());
1053            }
1054            OleDocstoreResponse.getInstance().getDocstoreResponse().remove(oleEditorResponse);
1055        }
1056
1057    }
1058
1059    // Added for Jira OLE-1900 Starts
1060
1061    public ActionForward addCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1062                                 HttpServletResponse response) throws Exception {
1063        LOG.debug("Inside addCopy Method of OleRequisitionAction");
1064        OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1065        OlePurchaseOrderAmendmentDocument purDocument = (OlePurchaseOrderAmendmentDocument) purchasingForm
1066                .getDocument();
1067        int line = this.getSelectedLine(request);
1068        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1069                .getDocument()).getItem(line);
1070        OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1071        OleDocstoreHelperService oleDocstoreHelperService = SpringContext
1072                .getBean(OleDocstoreHelperService.class);
1073        boolean isValid = true;
1074        List<String> volChar = new ArrayList<>();
1075        String[] volNumbers = item.getVolumeNumber() != null ? item.getVolumeNumber().split(",") : new String[0];
1076        for (String volStr : volNumbers) {
1077            volChar.add(volStr);
1078        }
1079        Integer itemCount = volChar.size();
1080        isValid = oleDocstoreHelperService.checkCopyEntry(
1081                item.getItemCopies(), item.getLocationCopies(), itemCount, item.getItemQuantity(), item.getItemNoOfParts(), item.getCopies(), item.getVolumeNumber(), false);
1082        if (isValid) {
1083            itemCopy.setItemCopies(item.getItemCopies());
1084            itemCopy.setLocationCopies(item.getLocationCopies());
1085            itemCopy.setParts(item.getItemNoOfParts());
1086            itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1087            itemCopy.setCaption(item.getCaption());
1088            itemCopy.setVolumeNumber(item.getVolumeNumber());
1089            List<OleCopy> copyList = oleDocstoreHelperService.setCopyValues(itemCopy, item.getItemTitleId(), volChar);
1090            item.getCopyList().addAll(copyList);
1091            item.getCopies().add(itemCopy);
1092            item.setParts(null);
1093            item.setItemCopies(null);
1094            item.setPartEnumeration(null);
1095            item.setLocationCopies(null);
1096            item.setCaption(null);
1097            item.setVolumeNumber(null);
1098           /* if (item.getCopies().size() > 0) {
1099                int startingCopies = 1;
1100                for (int copy = 0; copy < item.getCopies().size(); copy++) {
1101                    startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1102                }
1103                item.setStartingCopyNumber(new KualiInteger(startingCopies));
1104            }*/
1105        }
1106
1107        return mapping.findForward(OLEConstants.MAPPING_BASIC);
1108    }
1109
1110    public boolean checkForCopiesAndLocation(OlePurchaseOrderItem item) {
1111        boolean isValid = true;
1112        if (null == item.getItemCopies() || null == item.getLocationCopies()) {
1113            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1114                    OLEConstants.ITEM_ITEMCOPIES_OR_LOCATIONCOPIES_SHOULDNOT_BE_NULL, new String[]{});
1115            isValid = false;
1116        }
1117        return isValid;
1118    }
1119
1120    public boolean checkForItemCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1121        boolean isValid = true;
1122        if (item.getItemCopies().isGreaterThan(item.getItemQuantity())) {
1123            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1124                    OLEConstants.ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1125            isValid = false;
1126        }
1127        return isValid;
1128    }
1129
1130    public boolean checkForTotalCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1131        boolean isValid = true;
1132        int copies = 0;
1133        if (item.getCopies().size() > 0) {
1134            for (int itemCopies = 0; itemCopies < item.getCopies().size(); itemCopies++) {
1135                copies = copies + item.getCopies().get(itemCopies).getItemCopies().intValue();
1136            }
1137            if (item.getItemQuantity().isLessThan(item.getItemCopies().add(new KualiDecimal(copies)))) {
1138                GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1139                        OLEConstants.TOTAL_OF_ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1140                isValid = false;
1141            }
1142        }
1143        return isValid;
1144    }
1145
1146    /**
1147     * This method takes purchaseorderItem as parameter, it will calculate and set partEnumerations and startingCopyNumber for each
1148     * lineItem
1149     *
1150     * @param item
1151     * @return OleRequisitionCopies
1152     */
1153    public OleRequisitionCopies setCopyValues(OlePurchaseOrderItem item) {
1154        OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1155        itemCopy.setParts(item.getItemNoOfParts());
1156        itemCopy.setItemCopies(item.getItemCopies());
1157        StringBuffer enumeration = new StringBuffer();
1158        if (item.getStartingCopyNumber() != null && item.getStartingCopyNumber().isNonZero()) {
1159            itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1160        } else {
1161            int startingCopies = 1;
1162            for (int copy = 0; copy < item.getCopies().size(); copy++) {
1163                startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1164            }
1165            itemCopy.setStartingCopyNumber(new KualiInteger(startingCopies));
1166        }
1167        String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
1168                OLEConstants.PART_ENUMERATION_COPY);
1169        String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
1170                OLEConstants.PART_ENUMERATION_VOLUME);
1171        int startingCopyNumber = itemCopy.getStartingCopyNumber().intValue();
1172        for (int noOfCopies = 0; noOfCopies < item.getItemCopies().intValue(); noOfCopies++) {
1173            for (int noOfParts = 0; noOfParts < item.getItemNoOfParts().intValue(); noOfParts++) {
1174                int newNoOfCopies = startingCopyNumber + noOfCopies;
1175                int newNoOfParts = noOfParts + 1;
1176                if (noOfCopies + 1 == item.getItemCopies().intValue()
1177                        && newNoOfParts == item.getItemNoOfParts().intValue()) {
1178                    enumeration = enumeration.append(
1179                            partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1180                            partEnumerationVolume + newNoOfParts);
1181                } else {
1182                    enumeration = enumeration.append(
1183                            partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1184                            partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
1185                }
1186            }
1187        }
1188        itemCopy.setPartEnumeration(enumeration.toString());
1189        itemCopy.setLocationCopies(item.getLocationCopies());
1190        return itemCopy;
1191    }
1192
1193    /**
1194     * Remove a Copy for the selected Item .
1195     *
1196     * @param mapping  An ActionMapping
1197     * @param form     An ActionForm
1198     * @param request  The HttpServletRequest
1199     * @param response The HttpServletResponse
1200     * @return An ActionForward
1201     * @throws Exception
1202     */
1203    public ActionForward deleteCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1204                                    HttpServletResponse response) throws Exception {
1205        LOG.debug("Inside deleteCopy Method of OleRequisitionAction");
1206        OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1207        String[] indexes = getSelectedLineForAccounts(request);
1208        int itemIndex = Integer.parseInt(indexes[0]);
1209        int copyIndex = Integer.parseInt(indexes[1]);
1210        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1211                .getDocument()).getItem((itemIndex));
1212        List<OleCopy> copyList = new ArrayList<>();
1213        for(int i=0;i<item.getCopyList().size();i++){
1214            OleCopy oleCopy = item.getCopyList().get(i);
1215            if(item.getCopies().get(copyIndex).getLocationCopies().equalsIgnoreCase(oleCopy.getLocation())){
1216                copyList.add(oleCopy);
1217            }
1218        }
1219        for(OleCopy copy : copyList){
1220            item.getCopyList().remove(copy);
1221        }
1222        item.getCopies().remove(copyIndex);
1223        LOG.debug("Selected Copy is Remove");
1224        LOG.debug("Leaving deleteCopy Method of OleRequisitionAction");
1225        return mapping.findForward(OLEConstants.MAPPING_BASIC);
1226    }
1227
1228    /**
1229     * Add a Payment History for selected Item.
1230     *
1231     * @param mapping  An ActionMapping
1232     * @param form     An ActionForm
1233     * @param request  The HttpServletRequest
1234     * @param response The HttpServletResponse
1235     * @return An ActionForward
1236     * @throws Exception
1237     */
1238    public ActionForward addPaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1239                                           HttpServletResponse response) throws Exception {
1240        OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1241        OlePurchaseOrderAmendmentDocument purDocument = (OlePurchaseOrderAmendmentDocument) purchasingForm
1242                .getDocument();
1243        int line = this.getSelectedLine(request);
1244        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1245                .getDocument()).getItem(line);
1246        OleRequisitionPaymentHistory paymentHistory = new OleRequisitionPaymentHistory();
1247        paymentHistory.setPaymentHistory("");
1248        item.getRequisitionPaymentHistory().add(paymentHistory);
1249        return mapping.findForward(OLEConstants.MAPPING_BASIC);
1250    }
1251
1252    /**
1253     * Remove a Payment History for selected Item
1254     *
1255     * @param mapping
1256     * @param form
1257     * @param request
1258     * @param response
1259     * @return
1260     * @throws Exception
1261     */
1262    public ActionForward deletePaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1263                                              HttpServletResponse response) throws Exception {
1264
1265        OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1266        String[] indexes = getSelectedLineForAccounts(request);
1267        int itemIndex = Integer.parseInt(indexes[0]);
1268        int copyIndex = Integer.parseInt(indexes[1]);
1269        OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1270                .getDocument()).getItem((itemIndex));
1271        item.getRequisitionPaymentHistory().remove(copyIndex);
1272        return mapping.findForward(OLEConstants.MAPPING_BASIC);
1273    }
1274
1275    public static ConfigurationService getConfigurationService() {
1276        if (kualiConfigurationService == null) {
1277            kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
1278        }
1279        return kualiConfigurationService;
1280    }
1281
1282    /**
1283     * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
1284     * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
1285     *
1286     * @param instanceIdsList
1287     * @return List<WorkBibDocument>
1288     */
1289    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
1290        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
1291        for (String instanceId : instanceIdsList) {
1292            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
1293            instanceIdMap.put(DocType.INSTANCE.getDescription(), instanceId);
1294            instanceIdMapList.add(instanceIdMap);
1295        }
1296
1297        QueryService queryService = QueryServiceImpl.getInstance();
1298        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
1299        try {
1300            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
1301        } catch (Exception ex) {
1302            // TODO Auto-generated catch block
1303            ex.printStackTrace();
1304        }
1305        return workBibDocuments;
1306    }
1307
1308    // Added for Jira OLE-1900 Ends
1309
1310    @Override
1311    public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1312                                        HttpServletResponse response) throws Exception {
1313        PurchasingDocument document = (PurchasingDocument) ((PurchasingFormBase) form).getDocument();
1314        Iterator itemIterator = document.getItems().iterator();
1315        int itemCounter = 0;
1316        boolean rulePassed = true;
1317        while (itemIterator.hasNext()) {
1318            OlePurchaseOrderItem tempItem = (OlePurchaseOrderItem) itemIterator.next();
1319            if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
1320                List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
1321                if (accountingLineBase != null) {
1322                    for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
1323                        String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
1324                        String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
1325                        Map<String, String> criteria = new HashMap<String, String>();
1326                        criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1327                        criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1328                        Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1329                                Account.class, criteria);
1330                        rulePassed = checkForValidAccount(account);
1331                        if (!rulePassed) {
1332                            return mapping.findForward(OLEConstants.MAPPING_BASIC);
1333                        }
1334                    }
1335                }
1336            }
1337        }
1338        return super.blanketApprove(mapping, form, request, response);
1339    }
1340
1341    public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1342        OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1343        OlePurchaseOrderAmendmentDocument document = (OlePurchaseOrderAmendmentDocument) purchasingForm.getDocument();
1344        if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
1345            if (document.getVendorAliasName() != null && document.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
1346            /* Getting matching vendor for the given vendor alias name */
1347                Map vendorAliasMap = new HashMap();
1348                vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, document.getVendorAliasName());
1349                org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
1350                List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
1351                if (vendorAliasList != null && vendorAliasList.size() > 0) {  /* if there matching vendor found for the given vendor alias name */
1352                    Map vendorDetailMap = new HashMap();
1353                    vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1354                    vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1355                    VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
1356                    document.setVendorDetail(vendorDetail);
1357                    document.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1358                    document.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1359                    refreshVendor(mapping, form, request, response);
1360                } else {     /* If there is no matching vendor found*/
1361                    GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
1362                }
1363            }
1364        }
1365        return mapping.findForward(OLEConstants.MAPPING_BASIC);
1366    }
1367
1368    public ActionForward refreshVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1369        PurchasingAccountsPayableFormBase baseForm = (PurchasingAccountsPayableFormBase) form;
1370        PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
1371        if (StringUtils.equals(OLEConstants.REFRESH_VENDOR_CALLER, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && document.getVendorDetailAssignedIdentifier() != null && document.getVendorHeaderGeneratedIdentifier() != null) {
1372            document.setVendorContractGeneratedIdentifier(null);
1373            document.refreshReferenceObject(OLEConstants.VENDOR_CONTRACT);
1374
1375            // retrieve vendor based on selection from vendor lookup
1376            document.refreshReferenceObject(OLEConstants.VENDOR_DETAILS);
1377            document.templateVendorDetail(document.getVendorDetail());
1378
1379            // populate default address based on selected vendor
1380            VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), document.getDeliveryCampusCode());
1381            document.templateVendorAddress(defaultAddress);
1382        }
1383        return super.refresh(mapping, form, request, response);
1384    }
1385
1386    private LookupService getLookupService() {
1387        return KRADServiceLocatorWeb.getLookupService();
1388    }
1389
1390    @Override
1391    public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1392        Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
1393        // this should probably be moved into a protected instance variable
1394        ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
1395
1396        // logic for cancel question
1397        if (question == null) {
1398
1399            // ask question if not already asked
1400            return this.performQuestionWithoutInput(mapping, form, request, response, OLEConstants.DOCUMENT_CANCEL_QUESTION, kualiConfiguration.getPropertyValueAsString("document.question.cancel.text"), OLEConstants.CONFIRMATION_QUESTION, OLEConstants.MAPPING_CANCEL, "");
1401        } else {
1402            Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
1403            if ((OLEConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
1404
1405                // if no button clicked just reload the doc
1406                return mapping.findForward(OLEConstants.MAPPING_BASIC);
1407            }
1408            // else go to cancel logic below
1409        }
1410        KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1411        OlePurchaseOrderForm purchaseOrderForm = (OlePurchaseOrderForm) form;
1412        if ((purchaseOrderForm.getDocTypeName()).equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT)) {
1413            List<Note> noteList = new ArrayList<Note>();
1414
1415            if (kualiDocumentFormBase.getDocument().getNotes().size() > 0) {
1416                for (Note note : (List<Note>) kualiDocumentFormBase.getDocument().getNotes()) {
1417                    noteList.add(note);
1418                    getBusinessObjectService().delete(note);
1419                }
1420            }
1421            SpringContext.getBean(DocumentService.class).cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
1422            if (noteList.size() > 0) {
1423                getBusinessObjectService().save(noteList);
1424            }
1425
1426            return returnToSender(request, mapping, kualiDocumentFormBase);
1427        }
1428        return returnToSender(request, mapping, kualiDocumentFormBase);
1429    }
1430
1431
1432}
1433
1434