View Javadoc
1   /*
2    * Copyright 2006 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.module.purap.document.web.struts;
17  
18  import org.apache.commons.lang.StringEscapeUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.commons.lang.time.DateUtils;
21  import org.apache.struts.action.ActionForm;
22  import org.apache.struts.action.ActionForward;
23  import org.apache.struts.action.ActionMapping;
24  import org.kuali.ole.DocumentUniqueIDPrefix;
25  import org.kuali.ole.coa.businessobject.Account;
26  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
27  import org.kuali.ole.docstore.common.document.Bib;
28  import org.kuali.ole.module.purap.*;
29  import org.kuali.ole.module.purap.PurapConstants.PODocumentsStrings;
30  import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
31  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
32  import org.kuali.ole.module.purap.businessobject.PurApItem;
33  import org.kuali.ole.module.purap.document.*;
34  import org.kuali.ole.module.purap.document.service.OlePurapService;
35  import org.kuali.ole.module.purap.document.service.PurapService;
36  import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
37  import org.kuali.ole.pojo.OleBibRecord;
38  import org.kuali.ole.pojo.OleEditorResponse;
39  import org.kuali.ole.select.OleSelectConstant;
40  import org.kuali.ole.select.bo.OLEDonor;
41  import org.kuali.ole.select.bo.OLEEditorResponse;
42  import org.kuali.ole.select.bo.OLELinkPurapDonor;
43  import org.kuali.ole.select.businessobject.*;
44  import org.kuali.ole.select.constants.OleSelectPropertyConstants;
45  import org.kuali.ole.select.document.OlePurchaseOrderAmendmentDocument;
46  import org.kuali.ole.select.document.service.OleCopyHelperService;
47  import org.kuali.ole.select.document.service.OlePurchaseOrderService;
48  import org.kuali.ole.select.document.service.OleRequisitionDocumentService;
49  import org.kuali.ole.select.document.validation.event.CopiesPurchaseOrderEvent;
50  import org.kuali.ole.select.document.validation.event.DiscountPurchaseOrderEvent;
51  import org.kuali.ole.select.document.validation.event.ForeignCurrencyPOEvent;
52  import org.kuali.ole.select.document.validation.event.OlePurchaseOrderDescEvent;
53  import org.kuali.ole.sys.OLEConstants;
54  import org.kuali.ole.sys.OLEPropertyConstants;
55  import org.kuali.ole.sys.businessobject.AccountingLineBase;
56  import org.kuali.ole.sys.businessobject.SourceAccountingLine;
57  import org.kuali.ole.sys.context.SpringContext;
58  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
59  import org.kuali.ole.vnd.VendorConstants;
60  import org.kuali.ole.vnd.businessobject.*;
61  import org.kuali.ole.vnd.document.service.VendorService;
62  import org.kuali.rice.core.api.config.property.ConfigurationService;
63  import org.kuali.rice.core.api.util.RiceKeyConstants;
64  import org.kuali.rice.core.api.util.type.KualiDecimal;
65  import org.kuali.rice.core.api.util.type.KualiInteger;
66  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
67  import org.kuali.rice.kns.question.ConfirmationQuestion;
68  import org.kuali.rice.kns.util.KNSGlobalVariables;
69  import org.kuali.rice.kns.web.struts.form.BlankFormFile;
70  import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
71  import org.kuali.rice.kns.web.struts.form.KualiForm;
72  import org.kuali.rice.kns.web.struts.form.pojo.PojoForm;
73  import org.kuali.rice.krad.bo.Note;
74  import org.kuali.rice.krad.document.Document;
75  import org.kuali.rice.krad.exception.ValidationException;
76  import org.kuali.rice.krad.service.*;
77  import org.kuali.rice.krad.util.GlobalVariables;
78  import org.kuali.rice.krad.util.KRADConstants;
79  import org.kuali.rice.krad.util.ObjectUtils;
80  import org.kuali.rice.krad.util.UrlFactory;
81  
82  import javax.servlet.http.HttpServletRequest;
83  import javax.servlet.http.HttpServletResponse;
84  import java.io.ByteArrayOutputStream;
85  import java.math.BigDecimal;
86  import java.math.RoundingMode;
87  import java.util.*;
88  
89  /**
90   * Struts Action for Purchase Order document.
91   */
92  public class OlePurchaseOrderAction extends PurchaseOrderAction {
93      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderAction.class);
94      private final String UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkIn&stringContent=";
95      private final String CHECKOUT_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkOut&uuid=";
96      private final String CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING = "docAction=ingestContent&stringContent=";
97      private static transient ConfigurationService kualiConfigurationService;
98      private DocstoreClientLocator docstoreClientLocator;
99      private boolean currencyTypeIndicator = true;
100 
101     public DocstoreClientLocator getDocstoreClientLocator() {
102         if (docstoreClientLocator == null) {
103             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
104         }
105         return docstoreClientLocator;
106     }
107 
108     /**
109      * Takes care of storing the action form in the User session and forwarding to the prlookup action.
110      *
111      * @param mapping
112      * @param form
113      * @param request
114      * @param response
115      * @return
116      * @throws Exception
117      */
118     public ActionForward performPRLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
119 
120         ActionForward forward = super.performLookup(mapping, form, request, response);
121         String path = forward.getPath();
122         if (path.contains("kr/lookup.do")) {
123             path = path.replace("kr/lookup.do", "prlookup.do");
124             // path = path.replace("kr/lookup.do", "ptrnlookup.do");
125         } else if (path.contains("lookup.do")) {
126             path = path.replace("lookup.do", "prlookup.do");
127             // path = path.replace("lookup.do", "ptrnlookup.do");
128         }
129         forward.setPath(path);
130 
131         return forward;
132 
133     }
134 
135     /**
136      * @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)
137      */
138     @Override
139     public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
140 
141         PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
142         List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
143         for(PurApItem purApItem:purApItems){
144             List<KualiDecimal> existingAmount=new ArrayList<>();
145             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
146                 if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
147                     if(((OlePurchaseOrderAccount)oldSourceAccountingLine).getExistingAmount()!=null){
148                         existingAmount.add(((OlePurchaseOrderAccount)oldSourceAccountingLine).getExistingAmount());
149                     }
150                 }
151             }
152             int count=0;
153             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
154 
155                 if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) {
156                     if (account.getAmount()!=null&&count<existingAmount.size()&&existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) {
157                         KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString());
158                         account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE,BigDecimal.ROUND_CEILING));
159                     }
160                     else {
161                         if(account.getAccountLinePercent().intValue()==100&&(account.getAmount()==null||account.getAccount()!=null)){
162                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
163                             account.setAmount(calculatedAmount);
164                         }
165                         else{
166                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
167                             account.setAmount(calculatedAmount);
168                         }
169                     }
170                 }
171                 count++;
172             }
173             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
174                 if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
175                     ((OlePurchaseOrderAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
176                 }
177             }
178         }
179         ActionForward forward = super.calculate(mapping, form, request, response);
180         /* calculateCurrency(mapping, form, request, response); */
181         purchasingForm = (PurchasingAccountsPayableFormBase) form;
182         PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
183         PurchasingFormBase formBase = (PurchasingFormBase) form;
184 
185         PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) formBase.getDocument();
186         List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems();
187         if (purchaseDoc.getVendorDetail().getCurrencyType()!=null){
188             if(purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
189                 currencyTypeIndicator=true;
190             }
191             else{
192                 currencyTypeIndicator=false;
193             }
194         }
195         if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && currencyTypeIndicator)) {
196             for (int i = 0; purDoc.getItems().size() > i; i++) {
197                 OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i);
198                 if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
199                     boolean rulePassed = getKualiRuleService().applyRules(new DiscountPurchaseOrderEvent(purchaseDoc, item));
200                     if (rulePassed) {
201                         item.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item).setScale(2, BigDecimal.ROUND_HALF_UP));
202                     }
203                     rulePassed = getKualiRuleService().applyRules(new CopiesPurchaseOrderEvent(purDoc, item));
204                 }
205 
206             }
207         } else {
208             LOG.debug("###########Foreign Currency Field Calculation in olepurchaseOrder action###########");
209             BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
210             for (int i = 0; purItem.size() > i; i++) {
211                 OlePurchaseOrderItem items = (OlePurchaseOrderItem) purchaseDoc.getItem(i);
212                 if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
213                     boolean rulePassed = getKualiRuleService().applyRules(new ForeignCurrencyPOEvent(purchaseDoc, items));
214                     if (rulePassed) {
215                         SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
216                         Long id = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
217                         Map currencyTypeMap = new HashMap();
218                         currencyTypeMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
219                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, currencyTypeMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
220                         Iterator iterator = exchangeRateList.iterator();
221                         if (iterator.hasNext()) {
222                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
223                             String documentNumber = purchaseDoc.getDocumentNumber();
224                             Map documentNumberMap = new HashMap();
225                             documentNumberMap.put(OLEPropertyConstants.DOCUMENT_NUMBER, documentNumber);
226                             List<OlePurchaseOrderItem> currenctExchangeRateList = (List) businessObjectService.findMatching(OlePurchaseOrderItem.class, documentNumberMap);
227                             Iterator iterate = currenctExchangeRateList.iterator();
228                             if (iterate.hasNext()) {
229                                 OlePurchaseOrderItem tempCurrentExchangeRate = (OlePurchaseOrderItem) iterate.next();
230                                 String poCurrencyType = null;
231                                 if (tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail().getCurrencyType() != null) {
232                                     poCurrencyType = tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail().getCurrencyType().getCurrencyType();
233                                 }
234                                 String poaCurrencyType = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyType();
235                                 if (poCurrencyType != null && (poCurrencyType.equalsIgnoreCase(poaCurrencyType)) && !items.isLatestExchangeRate() && !purchaseDoc.getIsPODoc() && ((purchaseDoc instanceof PurchaseOrderAmendmentDocument) || (purchaseDoc instanceof PurchaseOrderSplitDocument) || (purchaseDoc instanceof PurchaseOrderReopenDocument))) {
236                                     items.setItemExchangeRate(tempCurrentExchangeRate.getItemExchangeRate());
237                                 } else {
238                                     items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
239                                 }
240                             }
241                             if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
242                                 items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
243                                 items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
244                                 items.setItemListPrice(items.getItemUnitCostUSD());
245                             }
246                         }
247                     }
248                 }
249             }
250         }
251 
252         purchasingForm = (PurchasingAccountsPayableFormBase) form;
253         List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
254         for(PurApItem purApItem:newpurApItems){
255             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
256                 KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
257                 account.setAmount(calculatedAmount);
258             }
259         }
260         forward = super.calculate(mapping, form, request, response);
261         //    setEnumerationToCopies(purItem);
262 
263 
264         // Added for SFC - Start
265 
266         OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext
267                 .getBean("oleRequisitionDocumentService");
268         List<SourceAccountingLine> sourceAccountingLineList = purDoc.getSourceAccountingLines();
269         for (SourceAccountingLine accLine : sourceAccountingLineList) {
270             String notificationOption = null;
271             boolean sufficientFundCheck;
272             Map<String, Object> key = new HashMap<String, Object>();
273             String chartCode = accLine.getChartOfAccountsCode();
274             String accNo = accLine.getAccountNumber();
275             key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
276             key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
277             OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
278                     OleSufficientFundCheck.class, key);
279             if (account != null) {
280                 notificationOption = account.getNotificationOption();
281             }
282             if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) {
283                 sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine);
284                 if (sufficientFundCheck) {
285                     GlobalVariables.getMessageMap().putError(
286                             OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM,
287                             OLEConstants.SufficientFundCheck.INSUFF_FUND_POA + accLine.getAccountNumber());
288                 }
289             }
290         }
291 
292         // End
293 
294         // formBase.setCalculated(true);
295         if (LOG.isDebugEnabled()) {
296             LOG.debug("Inside the OlePurchaseOrderAction class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice());
297         }
298         return forward;
299     }
300 
301     /**
302      * @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)
303      */
304     @Override
305     public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
306 
307         LOG.debug("###########Inside AddItem in olePurchaseOrderAction ###########");
308         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
309         OlePurchaseOrderItem purchaseOrderItem = (OlePurchaseOrderItem) purchasingForm.getNewPurchasingItemLine();
310         purchaseOrderItem.getNewSourceLine().setAccountLinePercent(new BigDecimal(100));
311         //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() : ""));
312         PurchaseOrderDocument document = (PurchaseOrderDocument) purchasingForm.getDocument();
313 
314         // changes done for BibEditor starts
315 
316         OlePurchaseOrderForm oleForm = (OlePurchaseOrderForm) form;
317         PurchaseOrderDocument doc = (PurchaseOrderDocument) oleForm.getDocument();
318         Iterator itemIterator = doc.getItems().iterator();
319         int itemCounter = 0;
320         while (itemIterator.hasNext()) {
321             OlePurchaseOrderItem tempItem = (OlePurchaseOrderItem) itemIterator.next();
322             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
323                 itemCounter++;
324             }
325         }
326         String itemNo = String.valueOf(itemCounter);
327         //String itemNo = String.valueOf(doc.getItems().size() - 4);
328         HashMap<String, String> dataMap = new HashMap<String, String>();
329         BibInfoBean xmlBibInfoBean = new BibInfoBean();
330         if (purchaseOrderItem.getBibInfoBean() == null) {
331             purchaseOrderItem.setBibInfoBean(xmlBibInfoBean);
332             if (purchaseOrderItem.getBibInfoBean().getDocStoreOperation() == null) {
333                 purchaseOrderItem.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
334             }
335         }
336         String fileName = document.getDocumentNumber() + "_" + itemNo;
337 
338         // Modified for jira OLE - 2437 starts
339 
340         setItemDescription(purchaseOrderItem, fileName);
341         //    purchaseOrderItem.setStartingCopyNumber(new KualiInteger(1));
342 
343         // Modified for jira OLE - 2437 ends
344 
345        /* dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation());
346         dataMap.put(OleSelectConstant.FILENAME, fileName);
347         if (fileProcessingService.isCreateFileExist(dataMap)) {
348             isBibFileExist = true;
349         }
350         if (isBibFileExist) {
351             titleId = docStore.getTitleIdByMarcXMLFileProcessing(purchaseOrderItem.getBibInfoBean(), dataMap);
352             purchaseOrderItem.setItemTitleId(titleId);
353             dataMap.put(OleSelectConstant.TITLE_ID, titleId);
354             dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
355             xmlBibInfoBean = docStore.getBibInfo(dataMap);
356             purchaseOrderItem.setBibInfoBean(xmlBibInfoBean);
357             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() : ""));
358 
359             HashMap<String,String> queryMap = new HashMap<String,String>();
360             queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, purchaseOrderItem.getItemTitleId());
361             List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
362             Iterator bibIdIterator = docStoreResult.iterator();
363             if(bibIdIterator.hasNext()){
364                 DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next();
365                 purchaseOrderItem.setBibUUID(docInfoBean.getUniqueId());
366             }
367         }*/
368         // changes done for BibEditor ends
369         if (document.getVendorDetail().getCurrencyType()!=null){
370             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
371                 currencyTypeIndicator=true;
372             }
373             else{
374                 currencyTypeIndicator=false;
375             }
376         }
377         boolean ruleFlag = getKualiRuleService().applyRules(new OlePurchaseOrderDescEvent(document, purchaseOrderItem));
378         if (ruleFlag) {
379             if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && currencyTypeIndicator)) {
380                 boolean rulePassed = getKualiRuleService().applyRules(new DiscountPurchaseOrderEvent(document, purchaseOrderItem));
381                 if (rulePassed) {
382                     purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(purchaseOrderItem).setScale(2, BigDecimal.ROUND_HALF_UP));
383                     super.addItem(mapping, purchasingForm, request, response);
384                 }
385             } else {
386                 boolean rulePassed = getKualiRuleService().applyRules(new ForeignCurrencyPOEvent(document, purchaseOrderItem));
387                 if (rulePassed) {
388                     LOG.debug("###########Foreign Currency Field additem for purchase Order ###########");
389                     SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(purchaseOrderItem);
390                     Long id = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
391                     Map documentNumberMap = new HashMap();
392                     documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
393                     BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
394                     List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
395                     Iterator iterator = exchangeRateList.iterator();
396                     if (iterator.hasNext()) {
397                         OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
398                         purchaseOrderItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
399                     }
400                     if (purchaseOrderItem.getItemExchangeRate() != null && purchaseOrderItem.getItemForeignUnitCost() != null) {
401                         purchaseOrderItem.setItemUnitCostUSD(new KualiDecimal(purchaseOrderItem.getItemForeignUnitCost().bigDecimalValue().divide(purchaseOrderItem.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
402                         purchaseOrderItem.setItemUnitPrice(purchaseOrderItem.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
403                         purchaseOrderItem.setItemListPrice(purchaseOrderItem.getItemUnitCostUSD());
404                     }
405                     super.addItem(mapping, purchasingForm, request, response);
406                 }
407             }
408         }
409         if(purchaseOrderItem.getClaimDate()==null){
410             VendorDetail vendorDetail =document.getVendorDetail();
411             if( vendorDetail!=null ){
412                 String claimInterval = vendorDetail.getClaimInterval();
413                 if (StringUtils.isNotBlank(claimInterval)) {
414                     Integer actIntvl = Integer.parseInt(claimInterval);
415                     purchaseOrderItem.setClaimDate(new java.sql.Date(DateUtils.addDays(new java.util.Date(), actIntvl).getTime()));
416                 }
417             }
418         }
419         return mapping.findForward(OLEConstants.MAPPING_BASIC);
420     }
421 
422     /**
423      * Add Note for the selected PurchaseOrderItem
424      *
425      * @param mapping
426      * @param form
427      * @param request
428      * @param response
429      * @return An ActionForward
430      * @throws Exception
431      */
432 
433     public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
434         LOG.debug("Inside addNote Method of PurchaseOrderAction");
435         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
436         int line = this.getSelectedLine(request);
437         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
438         OlePurchaseOrderNotes note = new OlePurchaseOrderNotes();
439         note.setNote(item.getNote());
440         note.setNoteTypeId(item.getNoteTypeId());
441         item.getNotes().add(note);
442         LOG.debug("Adding Note to PurchaseOrderItem");
443         item.setNote(null);
444         item.setNoteTypeId(null);
445         LOG.debug("Leaving addNote Method of PurchaseOrderAction");
446         return mapping.findForward(OLEConstants.MAPPING_BASIC);
447     }
448 
449     /**
450      * deletes the selected Note for the selected POItem
451      *
452      * @param mapping
453      * @param form
454      * @param request
455      * @param response
456      * @return An ActionForward
457      * @throws Exception
458      */
459     public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
460         LOG.debug("Inside deleteNote Method of PurchaseOrderAction");
461         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
462         String[] indexes = getSelectedLineForAccounts(request);
463         int itemIndex = Integer.parseInt(indexes[0]);
464         int noteIndex = Integer.parseInt(indexes[1]);
465         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
466         item.getNotes().remove(noteIndex);
467         LOG.debug("Note deleted for the selected Item");
468         LOG.debug("Leaving deleteNote Method of PurchaseOrderAction");
469         return mapping.findForward(OLEConstants.MAPPING_BASIC);
470     }
471 
472     /**
473      * This method is overridden to change receivingitem url with respect to OLE
474      *
475      * @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)
476      */
477     @Override
478     public ActionForward createReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
479         LOG.debug("Inside createReceivingLine Method of OlePurchaseOrderAction");
480         PurchaseOrderForm poForm = (PurchaseOrderForm) form;
481         PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
482 
483         String basePath = getApplicationBaseUrl();
484         String methodToCallDocHandler = "continueReceivingLine";
485         String methodToCallReceivingLine = "initiate";
486 
487         //set parameters
488         Properties parameters = new Properties();
489         parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
490         parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingLine);
491         parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVL");
492         parameters.put("purchaseOrderId", document.getPurapDocumentIdentifier().toString());
493 
494         //create url
495         // Changed receivingUrl to point to the OLE receiving URL (OLE-2057)
496         String receivingUrl = UrlFactory.parameterizeUrl(basePath + "/" + "selectOleLineItemReceiving.do", parameters);
497 
498         //create forward
499         ActionForward forward = new ActionForward(receivingUrl, true);
500         LOG.debug("Leaving createReceivingLine Method of OlePurchaseOrderAction");
501         return forward;
502     }
503 
504     /**
505      * Creates a URL to be used in printing the purchase order.
506      *
507      * @param basePath     String: The base path of the current URL
508      * @param docId        String: The document ID of the document to be printed
509      * @param methodToCall String: The name of the method that will be invoked to do this particular print
510      * @return The URL
511      */
512     @Override
513     protected String getUrlForPrintPO(String basePath, String docId, String methodToCall) {
514         StringBuffer result = new StringBuffer(basePath);
515         result.append("/purapOlePurchaseOrder.do?methodToCall=");
516         result.append(methodToCall);
517         result.append("&docId=");
518         result.append(docId);
519         result.append("&command=displayDocSearchView");
520 
521         return result.toString();
522     }
523 
524     @Override
525     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
526         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
527         PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
528         if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
529             //   setDocstoreDataForCopies((OlePurchaseOrderAmendmentDocument) purDoc);
530         }
531         // if form is not yet calculated, return and prompt user to calculate
532         if (requiresCalculate(purchasingForm)) {
533             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
534 
535             return mapping.findForward(OLEConstants.MAPPING_BASIC);
536         }
537 
538         // call prorateDiscountTradeIn
539         SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
540         this.calculate(mapping, purchasingForm, request, response);
541         PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) purchasingForm.getDocument();
542         List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems();
543         for (int i = OLEConstants.ZERO; purDoc.getItems().size() > i; i++) {
544             OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i);
545             if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
546                 if (item.getCopyList().size()==OLEConstants.ZERO && item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
547                         && !item.getItemNoOfParts().isGreaterThan(OLEConstants.ONE) ) {
548                     OleCopy oleCopy = new OleCopy();
549                     oleCopy.setLocation(item.getItemLocation());
550                     oleCopy.setBibId(item.getItemTitleId());
551                     oleCopy.setCopyNumber(item.getSingleCopyNumber()!=null && !item.getSingleCopyNumber().isEmpty()?item.getSingleCopyNumber():null);
552                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
553                     if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
554                         oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
555                     }
556                     List<OleCopy> copyList = new ArrayList<>();
557                     copyList.add(oleCopy);
558                     item.setCopyList(copyList);
559                 }
560             }
561             if (item.getItemIdentifier() != null && item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
562                     && !item.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)) {
563                 Map<String, String> map = new HashMap<>();
564                 map.put(OLEConstants.PO_ID, item.getItemIdentifier().toString());
565                 List<OleCopy> oleCopyList = (List<OleCopy>) SpringContext.getBean(BusinessObjectService.class).findMatching(OleCopy.class, map);
566                 if (oleCopyList.size() == 1) {
567                     item.getCopyList().get(0).setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
568                 }
569             }
570             if (item.getItemIdentifier() != null) {
571                 Map map = new HashMap();
572                 map.put(OLEConstants.PO_ID, item.getItemIdentifier().toString());
573                 List<OLELinkPurapDonor> linkPurapDonors = (List<OLELinkPurapDonor>) getBusinessObjectService().findMatching(OLELinkPurapDonor.class, map);
574                 if (linkPurapDonors != null && linkPurapDonors.size() > 0) {
575                     getBusinessObjectService().delete(linkPurapDonors);
576                 }
577             }
578         }
579         return super.route(mapping, form, request, response);
580 
581     }
582 
583 //    public void setDocstoreDataForCopies(OlePurchaseOrderAmendmentDocument purDoc) throws Exception {
584 //        List<OlePurchaseOrderItem> items = new ArrayList<OlePurchaseOrderItem>();
585 //        items = purDoc.getItems();
586 //        Iterator iterator = items.iterator();
587 //        while (iterator.hasNext()) {
588 //            Object object = iterator.next();
589 //            if (object instanceof OlePurchaseOrderItem) {
590 //                OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
591 //                List<String> itemTitleIdsList = new ArrayList<String>();
592 //                List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
593 //                // for (OlePurchaseOrderItem itemTitleId : items) {
594 //                if (null != singleItem.getItemTitleId()) {
595 //                    if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
596 //                            || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
597 //                        itemTitleIdsList.add(singleItem.getItemTitleId());
598 //                        workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
599 //                        for (WorkBibDocument workBibDocument : workBibDocuments) {
600 //
601 //
602 //                        }
603 //                    }
604 //                }
605 //                // }
606 //                // setEnumerationToCopies(singleItem);
607 //                /*
608 //                 * if (null != singleItem.getItemTitleId() && workBibDocuments.size() > 0) { }
609 //                 */
610 //            }
611 //        }
612 //    }
613 
614     public void setEnumerationToCopies(List<OlePurchaseOrderItem> purItem) {
615         String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
616                 OLEConstants.PART_ENUMERATION_COPY);
617         String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
618                 OLEConstants.PART_ENUMERATION_VOLUME);
619         for (int singleItem = 0; purItem.size() > singleItem; singleItem++) {
620             List<OleCopies> purItemCopies = purItem.get(singleItem).getCopies();
621             for (int copies = 0; copies < purItemCopies.size(); copies++) {
622                 purItemCopies.get(copies).setParts(purItem.get(singleItem).getItemNoOfParts());
623                 int startingCopyNumber = purItemCopies.get(copies).getStartingCopyNumber().intValue();
624                 StringBuffer enumeration = new StringBuffer();
625                 for (int noOfCopies = 0; noOfCopies < purItemCopies.get(copies).getItemCopies().intValue(); noOfCopies++) {
626                     for (int noOfParts = 0; noOfParts < purItemCopies.get(copies).getParts().intValue(); noOfParts++) {
627                         int newNoOfCopies = startingCopyNumber + noOfCopies;
628                         int newNoOfParts = noOfParts + 1;
629                         if (noOfCopies + 1 == purItemCopies.get(copies).getItemCopies().intValue()
630                                 && newNoOfParts == purItemCopies.get(copies).getParts().intValue()) {
631                             enumeration = enumeration.append(
632                                     partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
633                                     partEnumerationVolume + newNoOfParts);
634                         } else {
635                             enumeration = enumeration.append(
636                                     partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
637                                     partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
638                         }
639                     }
640                 }
641                 purItemCopies.get(copies).setPartEnumeration(enumeration.toString());
642             }
643         }
644     }
645 
646 
647     /**
648      * For use with a specific set of methods of this class that create new purchase order-derived document types in response to
649      * user actions, including <code>closePo</code>, <code>reopenPo</code>, <code>paymentHoldPo</code>, <code>removeHoldPo</code>,
650      * <code>splitPo</code>, <code>amendPo</code>, and <code>voidPo</code>. It employs the question framework to ask
651      * the user for a response before creating and routing the new document. The response should consist of a note detailing a
652      * 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
653      * question framework); when each question is originally asked, and again when the yes/no response is processed, for
654      * confirmation.
655      *
656      * @param mapping      These are boiler-plate.
657      * @param form         "
658      * @param request      "
659      * @param response     "
660      * @param questionType A string identifying the type of question being asked.
661      * @param confirmType  A string identifying which type of question is being confirmed.
662      * @param documentType A string, the type of document to create
663      * @param notePrefix   A string to appear before the note in the BO Notes tab
664      * @param messageType  A string to appear on the PO once the question framework is done, describing the action taken
665      * @param operation    A string, the verb to insert in the original question describing the action to be taken
666      * @return An ActionForward
667      * @throws Exception
668      */
669     @Override
670     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 {
671         LOG.debug("askQuestionsAndPerformDocumentAction started.");
672         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
673         PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
674         Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
675         String reason = request.getParameter(OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME);
676         String noteText = "";
677         String noteOne = "";
678         String noteTwo = "";
679 
680         try {
681             ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
682             String[] reasons = null;
683             // Start in logic for confirming the proposed operation.
684             if (ObjectUtils.isNull(question)) {
685                 String message = "";
686                 if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
687                     message = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_SPLIT_QUESTION_TEXT);
688                 } else {
689                     String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
690                     message = StringUtils.replace(key, "{0}", operation);
691                 }
692                 // Ask question if not already asked.
693                 return this.performQuestionWithInput(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "");
694             } else {
695                 Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
696                 if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
697 
698                     // If 'No' is the button clicked, just reload the doc
699                     return returnToPreviousPage(mapping, kualiDocumentFormBase);
700                 } else if (question.equals(confirmType) && buttonClicked.equals(SingleConfirmationQuestion.OK)) {
701 
702                     // This is the case when the user clicks on "OK" in the end.
703                     // After we inform the user that the close has been rerouted, we'll redirect to the portal page.
704                     return mapping.findForward(OLEConstants.MAPPING_PORTAL);
705                 } else {
706                     // Have to check length on value entered.
707                     String introNoteMessage = notePrefix + OLEConstants.BLANK_SPACE;
708                     int noteTextLength = 0;
709                     // Build out full message.
710                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
711                         if (StringUtils.isNotBlank(reason)) {
712                             reasons = reason.split("/");
713                             noteOne = introNoteMessage + reasons[0];
714                             if (!reasons[1].equalsIgnoreCase(null)) {
715                                 noteTwo = introNoteMessage + reasons[1];
716                                 noteTextLength = noteTwo.length();
717                             }
718 
719                         }
720                     } else {
721                     noteText = introNoteMessage + reason;
722                         noteTextLength = noteText.length();
723                     }
724 
725                     // Get note text max length from DD.
726                     int noteTextMaxLength = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getAttributeMaxLength(Note.class, OLEConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
727 
728                     String message = "";
729                     String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
730                     message = StringUtils.replace(key, "{0}", operation);
731 
732                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT))  {
733                         if (reasons == null || reasons[0].trim().equalsIgnoreCase("null")) {
734                             reason = "";
735                             return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "", reason, OLEConstants.ERROR_CANCELLATION_REASON_REQUIRED, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, "");
736                         } else if (!reasons[1].equalsIgnoreCase(null) && (noteTextLength > noteTextMaxLength)) {
737                             reason = "";
738                             return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "", reason, OLEConstants.ERROR_REASON, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(noteTextMaxLength - noteTextLength).toString());
739                         }
740                     }
741 
742                     if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
743                         // Figure out exact number of characters that the user can enter.
744                         int reasonLimit = noteTextMaxLength - noteTextLength;
745 
746                         if (ObjectUtils.isNull(reason)) {
747                             // Prevent a NPE by setting the reason to a blank string.
748                             reason = "";
749                         }
750 
751                         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());
752                     }
753                 }
754             }
755             // Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
756             ActionForward returnActionForward = null;
757             if (!po.isPendingActionIndicator()) {
758                 /*
759                  * Below if-else code block calls PurchaseOrderService methods that will throw ValidationException objects if errors
760                  * occur during any process in the attempt to perform its actions. Assume, if these return successfully, that the
761                  * PurchaseOrderDocument object returned from each is the newly created document and that all actions in the method
762                  * were run correctly. NOTE: IF BELOW IF-ELSE IS EDITED THE NEW METHODS CALLED MUST THROW ValidationException OBJECT
763                  * IF AN ERROR IS ADDED TO THE GlobalVariables
764                  */
765                 if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
766                     po.setPendingSplit(true);
767                     // Save adding the note for after the items are picked.
768                     ((PurchaseOrderForm) kualiDocumentFormBase).setSplitNoteText(noteText);
769                     returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
770                 } else {
771                     String newStatus = null;
772                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
773 
774                         newStatus = PurchaseOrderStatuses.APPDOC_AMENDMENT;
775                         po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
776                         returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
777                     } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
778                         newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REOPEN;
779                         po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
780                     } else {
781                         if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT)) {
782                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_CLOSE;
783                         }
784                         /*else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
785                             newStatus = PurchaseOrderStatuses.PENDING_REOPEN;
786                         }*/
787                         else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
788                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_VOID;
789                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)) {
790                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_PAYMENT_HOLD;
791                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT)) {
792                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REMOVE_HOLD;
793                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT)) {
794                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_RETRANSMIT;
795                         }
796                         po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), newStatus);
797                     }
798                     if (!GlobalVariables.getMessageMap().hasNoErrors()) {
799                         throw new ValidationException("errors occurred during new PO creation");
800                     }
801 
802                     String previousDocumentId = kualiDocumentFormBase.getDocId();
803                     // Assume at this point document was created properly and 'po' variable is new PurchaseOrderDocument created
804                     kualiDocumentFormBase.setDocument(po);
805                     kualiDocumentFormBase.setDocId(po.getDocumentNumber());
806                     kualiDocumentFormBase.setDocTypeName(po.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
807                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
808                         Note noteObjOne = new Note();
809                         noteObjOne.setNoteText(noteOne);
810                         noteObjOne.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
811                         kualiDocumentFormBase.setNewNote(noteObjOne);
812 
813                         kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
814 
815                         insertBONote(mapping, kualiDocumentFormBase, request, response);
816 
817                         if (!reasons[1].trim().equalsIgnoreCase("null")) {
818                             Note noteObjTwo = new Note();
819                             noteObjTwo.setNoteText(noteTwo);
820                             noteObjTwo.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
821                             kualiDocumentFormBase.setNewNote(noteObjTwo);
822 
823                             kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
824 
825                             insertBONote(mapping, kualiDocumentFormBase, request, response);
826                         }
827                     } else {
828                     Note newNote = new Note();
829                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
830                         noteText = noteText + " (Previous Document Id is " + previousDocumentId + ")";
831                     }
832                     newNote.setNoteText(noteText);
833                     newNote.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
834                     kualiDocumentFormBase.setNewNote(newNote);
835                     kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
836                     insertBONote(mapping, kualiDocumentFormBase, request, response);
837                 }
838              }
839                 if (StringUtils.isNotEmpty(messageType)) {
840                     KNSGlobalVariables.getMessageList().add(messageType);
841                 }
842             }
843             if (ObjectUtils.isNotNull(returnActionForward)) {
844                 return returnActionForward;
845             } else {
846 
847                 return this.performQuestionWithoutInput(mapping, form, request, response, confirmType, kualiConfiguration.getPropertyValueAsString(messageType), PODocumentsStrings.SINGLE_CONFIRMATION_QUESTION, questionType, "");
848             }
849         } catch (ValidationException ve) {
850             throw ve;
851         }
852     }
853 
854     @Override
855     public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
856         LOG.debug("<<<---------Inside OlePurchaseOrderAction Refresh------>>>");
857         ActionForward forward = super.refresh(mapping, form, request, response);
858         OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
859         PurchaseOrderDocument document = (PurchaseOrderDocument) rqForm.getDocument();
860         OlePurchaseOrderItem item = (OlePurchaseOrderItem) rqForm.getNewPurchasingItemLine();
861 
862         if (document.getVendorDetail().getCurrencyType()!=null){
863             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
864                 currencyTypeIndicator=true;
865             }
866             else{
867                 currencyTypeIndicator=false;
868             }
869         }
870         // To set PurchaseOrderTransmissionMethod depend on vendor transmission format
871         if (document.getVendorDetail() != null) {
872             if (document.getVendorDetail().getVendorTransmissionFormat().size() > 0) {
873                 List<VendorTransmissionFormatDetail> vendorTransmissionFormat = document.getVendorDetail().getVendorTransmissionFormat();
874                 for (VendorTransmissionFormatDetail iter : vendorTransmissionFormat) {
875                     if (iter.isVendorPreferredTransmissionFormat()) {
876                         if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat() != null) {
877                             if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat().equalsIgnoreCase(OleSelectConstant.VENDOR_TRANSMISSION_FORMAT_EDI)) {
878                                 document.setPurchaseOrderTransmissionMethodCode(OleSelectConstant.METHOD_OF_PO_TRANSMISSION_NOPR);
879                             } else {
880                                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
881                             }
882                         }
883                     }
884                 }
885             } else {
886                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
887             }
888             if ( (!currencyTypeIndicator) && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
889                 Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
890                 Map documentNumberMap = new HashMap();
891                 documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
892                 BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
893                 List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
894                 Iterator iterator = exchangeRateList.iterator();
895                 if (iterator.hasNext()) {
896                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
897                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
898                 }
899             }
900         }
901         return forward;
902     }
903 
904     @Override
905     public ActionForward amendPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
906         // TODO Auto-generated method stub
907         ActionForward findForward = super.amendPo(mapping, form, request, response);
908         OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
909         OlePurchaseOrderAmendmentDocument olePurchaseOrderAmendmentDocument = new OlePurchaseOrderAmendmentDocument();
910         if ((rqForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
911             rqForm.getAndResetNewPurchasingItemLine();
912         }
913         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
914         Document document = kualiDocumentFormBase.getDocument();
915         // prepare for the reload action - set doc id and command
916         kualiDocumentFormBase.setDocId(document.getDocumentNumber());
917         kualiDocumentFormBase.setCommand(DOCUMENT_LOAD_COMMANDS[1]);
918         // forward off to the doc handler
919         docHandler(mapping, form, request, response);
920 
921         return findForward;
922     }
923 
924     /**
925      * Is executed when the user clicks on the "print" button on a Purchase Order Print Document page. On a non
926      * javascript enabled browser, it will display a page with 2 buttons. One is to display the PDF, the other is to view the PO
927      * tabbed page where the PO document statuses, buttons, etc have already been updated (the updates of those occurred while the
928      * <code>performPurchaseOrderFirstTransmitViaPrinting</code> method is invoked. On a javascript enabled browser, it will
929      * display both the PO tabbed page containing the updated PO document info and the pdf on the next window/tab of the browser.
930      *
931      * @param mapping  An ActionMapping
932      * @param form     An ActionForm
933      * @param request  The HttpServletRequest
934      * @param response The HttpServletResponse
935      * @return An ActionForward
936      * @throws Exception
937      */
938     @Override
939     public ActionForward firstTransmitPrintPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
940         PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
941         String poDocId = ((PurchaseOrderForm) form).getDocId();
942         ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
943         try {
944             SpringContext.getBean(OlePurchaseOrderService.class).performPurchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
945         } finally {
946             if (baosPDF != null) {
947                 baosPDF.reset();
948             }
949         }
950         String basePath = getApplicationBaseUrl();
951         String docId = ((PurchaseOrderForm) form).getDocId();
952         String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
953         String methodToCallDocHandler = "docHandler";
954         String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
955         String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
956         request.setAttribute("printPOPDFUrl", printPOPDFUrl);
957         request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
958         String label = "";
959         if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
960             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
961         } else {
962             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
963         }
964         request.setAttribute("purchaseOrderLabel", label);
965 
966         return mapping.findForward("printPurchaseOrderPDF");
967     }
968 
969     public ActionForward printPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
970         PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
971         String poDocId = ((PurchaseOrderForm) form).getDocId();
972         ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
973         try {
974             SpringContext.getBean(OlePurchaseOrderService.class).purchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
975         } finally {
976             if (baosPDF != null) {
977                 baosPDF.reset();
978             }
979         }
980         String basePath = getApplicationBaseUrl();
981         String docId = ((PurchaseOrderForm) form).getDocId();
982         String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
983         String methodToCallDocHandler = "docHandler";
984         String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
985         String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
986         request.setAttribute("printPOPDFUrl", printPOPDFUrl);
987         request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
988         String label = "";
989         if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
990             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
991         } else {
992             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
993         }
994         request.setAttribute("purchaseOrderLabel", label);
995 
996         return mapping.findForward("printPurchaseOrderPDF");
997     }
998 
999     /**
1000      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
1001      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1002      */
1003     @Override
1004     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1005         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
1006         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
1007 
1008         // index of item selected
1009         int itemIndex = getSelectedLine(request);
1010         PurApItem item = null;
1011 
1012         // if custom processing of an accounting line is not done then insert a line generically.
1013         if (processCustomInsertAccountingLine(purapForm, request) == false) {
1014             String errorPrefix = null;
1015             PurApAccountingLine line = null;
1016 
1017             boolean rulePassed = false;
1018             if (itemIndex >= 0) {
1019                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
1020                 //Calculating the dollar amount for the accounting Line.
1021                 PurApAccountingLine lineItem = item.getNewSourceLine();
1022                 if (lineItem.getAccountLinePercent() != null) {
1023                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1024                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1025                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
1026                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1027                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
1028                     lineItem.setAccountLinePercent(dollarToPercent);
1029                 }
1030                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
1031                 //end
1032                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
1033                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
1034                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
1035             } else if (itemIndex == -2) {
1036                 //corrected: itemIndex == -2 is the only case for distribute account
1037                 //This is the case when we're inserting an accounting line for distribute account.
1038                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
1039                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
1040                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
1041                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
1042             }
1043             AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
1044             if (accountingLineBase != null) {
1045                 String accountNumber = accountingLineBase.getAccountNumber();
1046                 String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
1047                 Map<String, String> criteria = new HashMap<String, String>();
1048                 criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1049                 criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1050                 Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
1051                         criteria);
1052                 rulePassed = checkForValidAccount(account);
1053             }
1054             if (rulePassed) {
1055                 // add accountingLine
1056                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
1057 
1058                 PurApAccountingLine newSourceLine = item.getNewSourceLine();
1059                 List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();
1060 
1061                 BigDecimal initialValue = new BigDecimal(0);
1062 
1063                 for (PurApAccountingLine accountLine : existingSourceLine) {
1064                     initialValue = initialValue.add(accountLine.getAccountLinePercent());
1065                 }
1066                 if (itemIndex >= 0) {
1067 
1068                     if ((newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
1069                         if (OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue() != OleSelectConstant.ZERO) {
1070                             insertAccountingLine(purapForm, item, line);
1071                         }
1072                     }else {
1073                         checkAccountingLinePercent(newSourceLine);
1074 
1075                     }
1076                     for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
1077                         if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
1078                             ((OlePurchaseOrderAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
1079                         }
1080                     }
1081                     List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
1082                     BigDecimal totalPercent = new BigDecimal(100);
1083                     BigDecimal initialPercent = new BigDecimal(0);
1084                     for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
1085                         initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
1086 
1087                     }
1088                     initialPercent = totalPercent.subtract(initialPercent);
1089                     BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
1090                     if (maxPercent.intValue() == OleSelectConstant.ZERO) {
1091                         item.resetAccount(OleSelectConstant.ZERO_PERCENT);
1092 
1093                     } else {
1094                         item.resetAccount(initialPercent);
1095 
1096                     }
1097                 } else if (itemIndex == -2) {
1098                     //this is the case for distribute account
1099                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
1100                 }
1101             }
1102         }
1103 
1104         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1105     }
1106 
1107     private void checkAccountingLinePercent(PurApAccountingLine newSourceLine) {
1108         if (newSourceLine.getAccountLinePercent().intValue() >= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED) {
1109             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1110                     OleSelectPropertyConstants.ERROR_PERCENT_SHOULD_GREATER, OleSelectConstant.PERCENT);
1111         } else if (newSourceLine.getAccountLinePercent().intValue() == OleSelectConstant.ZERO) {
1112             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1113                     OleSelectPropertyConstants.ERROR_PERCENT_ZERO, OleSelectConstant.PERCENT);
1114         } else {
1115 
1116         }
1117 
1118     }
1119 
1120     private boolean checkForValidAccount(Account account) {
1121         boolean result = true;
1122         if (account != null) {
1123             String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
1124                     OleSelectConstant.SUB_FUND_GRP_CD);
1125             if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
1126                 GlobalVariables.getMessageMap()
1127                         .putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1128                                 OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
1129                                 new String[]{OleSelectConstant.PURCHASE_ORDER});
1130                 result = false;
1131             }
1132         }
1133         return result;
1134     }
1135 
1136     private void setItemDescription(OlePurchaseOrderItem item, String fileName) throws Exception{
1137         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
1138             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
1139             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
1140             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
1141             bib = (Bib) bib.deserializeContent(bib);
1142             if (bib != null) {
1143                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
1144                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
1145                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
1146                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
1147                 String description = title + author + publisher + isbn;
1148                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId().toString()));
1149                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
1150             }
1151             if (bib != null) {
1152                 item.setBibUUID(bib.getId());
1153                 item.setItemTitleId(bib.getId());
1154                 item.setLinkToOrderOption(oleEditorResponse.getLinkToOrderOption());
1155             }
1156             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
1157         }
1158     }
1159 
1160     // Added for Jira OLE-1900 Starts
1161 
1162     public ActionForward addCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1163                                  HttpServletResponse response) throws Exception {
1164         LOG.debug("Inside addCopy Method of OleRequisitionAction");
1165         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1166         OlePurchaseOrderAmendmentDocument purDocument = (OlePurchaseOrderAmendmentDocument) purchasingForm
1167                 .getDocument();
1168         int line = this.getSelectedLine(request);
1169         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1170                 .getDocument()).getItem(line);
1171         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1172         OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
1173         boolean isValid = true;
1174         List<String> volChar = new ArrayList<>();
1175         String[] volNumbers = item.getVolumeNumber() != null ? item.getVolumeNumber().split(",") : new String[0];
1176         for (String volStr : volNumbers) {
1177             volChar.add(volStr);
1178         }
1179         Integer itemCount = volChar.size();
1180         isValid = oleCopyHelperService.checkCopyEntry(
1181                 item.getItemCopies(), item.getLocationCopies(), itemCount, item.getItemQuantity(), item.getItemNoOfParts(), item.getCopies(), item.getVolumeNumber(), false);
1182         if (isValid) {
1183             itemCopy.setItemCopies(item.getItemCopies());
1184             itemCopy.setLocationCopies(item.getLocationCopies());
1185             itemCopy.setParts(item.getItemNoOfParts());
1186             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1187             itemCopy.setCaption(item.getCaption());
1188             itemCopy.setVolumeNumber(item.getVolumeNumber());
1189             List<OleCopy> copyList = oleCopyHelperService.setCopyValues(itemCopy, item.getItemTitleId(), volChar);
1190             // Whenever there is a single copy, the first copy in the copies table is deleted and replaced with the newly added copy from the copies subsection.
1191             if (StringUtils.isNotEmpty(item.getItemLocation())) {
1192                 if (!item.getItemLocation().equalsIgnoreCase(item.getLocationCopies()) && !item.isLocationFlag() && item.getCopyList().size()==1) {
1193                     KRADServiceLocator.getBusinessObjectService().delete(item.getCopyList().get(0));
1194                     item.getCopyList().clear();
1195                     item.getCopyList().addAll(copyList);
1196                     item.setLocationFlag(true);
1197                 }
1198                 else {
1199                     if (item.getCopyList().size() == 1) {
1200                         KRADServiceLocator.getBusinessObjectService().delete(item.getCopyList().get(0));
1201                         item.getCopyList().clear();
1202                     }
1203                     item.getCopyList().addAll(copyList);
1204                 }
1205             }
1206             else {// For Multiple copies, the copy gets added.
1207                 item.getCopyList().addAll(copyList);
1208             }
1209             item.getCopies().add(itemCopy);
1210             item.setParts(null);
1211             item.setItemCopies(null);
1212             item.setPartEnumeration(null);
1213             item.setLocationCopies(null);
1214             item.setCaption(null);
1215             item.setVolumeNumber(null);
1216            /* if (item.getCopies().size() > 0) {
1217                 int startingCopies = 1;
1218                 for (int copy = 0; copy < item.getCopies().size(); copy++) {
1219                     startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1220                 }
1221                 item.setStartingCopyNumber(new KualiInteger(startingCopies));
1222             }*/
1223         }
1224 
1225         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1226     }
1227 
1228     public boolean checkForCopiesAndLocation(OlePurchaseOrderItem item) {
1229         boolean isValid = true;
1230         if (null == item.getItemCopies() || null == item.getLocationCopies()) {
1231             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1232                     OLEConstants.ITEM_ITEMCOPIES_OR_LOCATIONCOPIES_SHOULDNOT_BE_NULL, new String[]{});
1233             isValid = false;
1234         }
1235         return isValid;
1236     }
1237 
1238     public boolean checkForItemCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1239         boolean isValid = true;
1240         if (item.getItemCopies().isGreaterThan(item.getItemQuantity())) {
1241             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1242                     OLEConstants.ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1243             isValid = false;
1244         }
1245         return isValid;
1246     }
1247 
1248     public boolean checkForTotalCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1249         boolean isValid = true;
1250         int copies = 0;
1251         if (item.getCopies().size() > 0) {
1252             for (int itemCopies = 0; itemCopies < item.getCopies().size(); itemCopies++) {
1253                 copies = copies + item.getCopies().get(itemCopies).getItemCopies().intValue();
1254             }
1255             if (item.getItemQuantity().isLessThan(item.getItemCopies().add(new KualiDecimal(copies)))) {
1256                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1257                         OLEConstants.TOTAL_OF_ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1258                 isValid = false;
1259             }
1260         }
1261         return isValid;
1262     }
1263 
1264     /**
1265      * This method takes purchaseorderItem as parameter, it will calculate and set partEnumerations and startingCopyNumber for each
1266      * lineItem
1267      *
1268      * @param item
1269      * @return OleRequisitionCopies
1270      */
1271     public OleRequisitionCopies setCopyValues(OlePurchaseOrderItem item) {
1272         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1273         itemCopy.setParts(item.getItemNoOfParts());
1274         itemCopy.setItemCopies(item.getItemCopies());
1275         StringBuffer enumeration = new StringBuffer();
1276         if (item.getStartingCopyNumber() != null && item.getStartingCopyNumber().isNonZero()) {
1277             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1278         } else {
1279             int startingCopies = 1;
1280             for (int copy = 0; copy < item.getCopies().size(); copy++) {
1281                 startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1282             }
1283             itemCopy.setStartingCopyNumber(new KualiInteger(startingCopies));
1284         }
1285         String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
1286                 OLEConstants.PART_ENUMERATION_COPY);
1287         String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
1288                 OLEConstants.PART_ENUMERATION_VOLUME);
1289         int startingCopyNumber = itemCopy.getStartingCopyNumber().intValue();
1290         for (int noOfCopies = 0; noOfCopies < item.getItemCopies().intValue(); noOfCopies++) {
1291             for (int noOfParts = 0; noOfParts < item.getItemNoOfParts().intValue(); noOfParts++) {
1292                 int newNoOfCopies = startingCopyNumber + noOfCopies;
1293                 int newNoOfParts = noOfParts + 1;
1294                 if (noOfCopies + 1 == item.getItemCopies().intValue()
1295                         && newNoOfParts == item.getItemNoOfParts().intValue()) {
1296                     enumeration = enumeration.append(
1297                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1298                             partEnumerationVolume + newNoOfParts);
1299                 } else {
1300                     enumeration = enumeration.append(
1301                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1302                             partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
1303                 }
1304             }
1305         }
1306         itemCopy.setPartEnumeration(enumeration.toString());
1307         itemCopy.setLocationCopies(item.getLocationCopies());
1308         return itemCopy;
1309     }
1310 
1311     /**
1312      * Remove a Copy for the selected Item .
1313      *
1314      * @param mapping  An ActionMapping
1315      * @param form     An ActionForm
1316      * @param request  The HttpServletRequest
1317      * @param response The HttpServletResponse
1318      * @return An ActionForward
1319      * @throws Exception
1320      */
1321     public ActionForward deleteCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1322                                     HttpServletResponse response) throws Exception {
1323         LOG.debug("Inside deleteCopy Method of OleRequisitionAction");
1324         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1325         String[] indexes = getSelectedLineForAccounts(request);
1326         int itemIndex = Integer.parseInt(indexes[0]);
1327         int copyIndex = Integer.parseInt(indexes[1]);
1328         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1329                 .getDocument()).getItem((itemIndex));
1330         List<OleCopy> copyList = new ArrayList<>();
1331         for(int i=0;i<item.getCopyList().size();i++){
1332             OleCopy oleCopy = item.getCopyList().get(i);
1333             if(item.getCopies().get(copyIndex).getLocationCopies().equalsIgnoreCase(oleCopy.getLocation())){
1334                 copyList.add(oleCopy);
1335             }
1336         }
1337         for(OleCopy copy : copyList){
1338             item.getCopyList().remove(copy);
1339             item.getDeletedCopiesList().add(copy);
1340         }
1341         item.getCopies().remove(copyIndex);
1342         LOG.debug("Selected Copy is Remove");
1343         LOG.debug("Leaving deleteCopy Method of OleRequisitionAction");
1344         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1345     }
1346 
1347     /**
1348      * Add a Payment History for selected Item.
1349      *
1350      * @param mapping  An ActionMapping
1351      * @param form     An ActionForm
1352      * @param request  The HttpServletRequest
1353      * @param response The HttpServletResponse
1354      * @return An ActionForward
1355      * @throws Exception
1356      */
1357     public ActionForward addPaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1358                                            HttpServletResponse response) throws Exception {
1359         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1360         int line = this.getSelectedLine(request);
1361         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1362                 .getDocument()).getItem(line);
1363         OleRequisitionPaymentHistory paymentHistory = new OleRequisitionPaymentHistory();
1364         paymentHistory.setPaymentHistory("");
1365         item.getRequisitionPaymentHistory().add(paymentHistory);
1366         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1367     }
1368 
1369     /**
1370      * Remove a Payment History for selected Item
1371      *
1372      * @param mapping
1373      * @param form
1374      * @param request
1375      * @param response
1376      * @return
1377      * @throws Exception
1378      */
1379     public ActionForward deletePaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1380                                               HttpServletResponse response) throws Exception {
1381 
1382         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1383         String[] indexes = getSelectedLineForAccounts(request);
1384         int itemIndex = Integer.parseInt(indexes[0]);
1385         int copyIndex = Integer.parseInt(indexes[1]);
1386         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1387                 .getDocument()).getItem((itemIndex));
1388         item.getRequisitionPaymentHistory().remove(copyIndex);
1389         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1390     }
1391 
1392     public static ConfigurationService getConfigurationService() {
1393         if (kualiConfigurationService == null) {
1394             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
1395         }
1396         return kualiConfigurationService;
1397     }
1398 
1399     /**
1400      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
1401      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
1402      *
1403      * @param instanceIdsList
1404      * @return List<WorkBibDocument>
1405      */
1406 //    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
1407 //        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
1408 //        for (String instanceId : instanceIdsList) {
1409 //            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
1410 //            instanceIdMap.put(DocType.INSTANCE.getDescription(), instanceId);
1411 //            instanceIdMapList.add(instanceIdMap);
1412 //        }
1413 //
1414 //        QueryService queryService = QueryServiceImpl.getInstance();
1415 //        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
1416 //        try {
1417 //            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
1418 //        } catch (Exception ex) {
1419 //            // TODO Auto-generated catch block
1420 //            ex.printStackTrace();
1421 //        }
1422 //        return workBibDocuments;
1423 //    }
1424 
1425     // Added for Jira OLE-1900 Ends
1426 
1427     @Override
1428     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1429                                         HttpServletResponse response) throws Exception {
1430         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1431         PurchasingDocument document = (PurchasingDocument) ((PurchasingFormBase) form).getDocument();
1432         this.calculate(mapping, purchasingForm, request, response);
1433         Iterator itemIterator = document.getItems().iterator();
1434         boolean rulePassed = true;
1435         while (itemIterator.hasNext()) {
1436             OlePurchaseOrderItem tempItem = (OlePurchaseOrderItem) itemIterator.next();
1437             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
1438                 if (tempItem.getCopyList().size()==OLEConstants.ZERO && tempItem.getItemQuantity() != null && tempItem.getItemNoOfParts() != null && !tempItem.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
1439                         && !tempItem.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)) {
1440                     OleCopy oleCopy = new OleCopy();
1441                     oleCopy.setLocation(tempItem.getItemLocation());
1442                     oleCopy.setBibId(tempItem.getItemTitleId());
1443                     if (StringUtils.isNotBlank(tempItem.getLinkToOrderOption()) && (tempItem.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || tempItem.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
1444                         oleCopy.setCopyNumber(tempItem.getSingleCopyNumber() != null && !tempItem.getSingleCopyNumber().isEmpty() ? tempItem.getSingleCopyNumber() : null);
1445                     }
1446                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1447                     List<OleCopy> copyList = new ArrayList<>();
1448                     copyList.add(oleCopy);
1449                     tempItem.setCopyList(copyList);
1450                 }
1451                 if(tempItem.getItemIdentifier()!=null && tempItem.getItemQuantity() != null && tempItem.getItemNoOfParts() != null && !tempItem.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
1452                         && !tempItem.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)){
1453                     Map<String,String> map=new HashMap<>();
1454                     map.put(OLEConstants.PO_ID,tempItem.getItemIdentifier().toString());
1455                     List<OleCopy> oleCopyList =(List<OleCopy>)SpringContext.getBean(BusinessObjectService.class).findMatching(OleCopy.class, map);
1456                     if(oleCopyList.size()==1){
1457                         tempItem.getCopyList().get(0).setCopyNumber(tempItem.getSingleCopyNumber()!=null && !tempItem.getSingleCopyNumber().isEmpty()?tempItem.getSingleCopyNumber():null);
1458                     }
1459                 }
1460                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
1461                 if (accountingLineBase != null) {
1462                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
1463                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
1464                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
1465                         Map<String, String> criteria = new HashMap<String, String>();
1466                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1467                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1468                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1469                                 Account.class, criteria);
1470                         rulePassed = checkForValidAccount(account);
1471                         if (!rulePassed) {
1472                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1473                         }
1474                     }
1475                 }
1476             }
1477             if (tempItem.getItemIdentifier() != null) {
1478                 Map map = new HashMap();
1479                 map.put(OLEConstants.PO_ID, tempItem.getItemIdentifier().toString());
1480                 List<OLELinkPurapDonor> linkPurapDonors = (List<OLELinkPurapDonor>) getBusinessObjectService().findMatching(OLELinkPurapDonor.class, map);
1481                 if (linkPurapDonors != null && linkPurapDonors.size() > 0) {
1482                     getBusinessObjectService().delete(linkPurapDonors);
1483                 }
1484             }
1485         }
1486         return super.blanketApprove(mapping, form, request, response);
1487     }
1488 
1489     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1490         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1491         OlePurchaseOrderAmendmentDocument document = (OlePurchaseOrderAmendmentDocument) purchasingForm.getDocument();
1492         if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
1493             if (document.getVendorAliasName() != null && document.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
1494             /* Getting matching vendor for the given vendor alias name */
1495                 Map vendorAliasMap = new HashMap();
1496                 vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, document.getVendorAliasName());
1497                 org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
1498                 List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
1499                 if (vendorAliasList != null && vendorAliasList.size() > 0) {  /* if there matching vendor found for the given vendor alias name */
1500                     Map vendorDetailMap = new HashMap();
1501                     vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1502                     vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1503                     VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
1504                     document.setVendorDetail(vendorDetail);
1505                     document.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1506                     document.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1507                     refreshVendor(mapping, form, request, response);
1508                 } else {     /* If there is no matching vendor found*/
1509                     GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
1510                 }
1511             }
1512         }
1513         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1514     }
1515 
1516     public ActionForward refreshVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1517         PurchasingAccountsPayableFormBase baseForm = (PurchasingAccountsPayableFormBase) form;
1518         PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
1519         if (StringUtils.equals(OLEConstants.REFRESH_VENDOR_CALLER, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && document.getVendorDetailAssignedIdentifier() != null && document.getVendorHeaderGeneratedIdentifier() != null) {
1520             document.setVendorContractGeneratedIdentifier(null);
1521             document.refreshReferenceObject(OLEConstants.VENDOR_CONTRACT);
1522 
1523             // retrieve vendor based on selection from vendor lookup
1524             document.refreshReferenceObject(OLEConstants.VENDOR_DETAILS);
1525             document.templateVendorDetail(document.getVendorDetail());
1526 
1527             // populate default address based on selected vendor
1528             VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), document.getDeliveryCampusCode());
1529             document.templateVendorAddress(defaultAddress);
1530         }
1531         return super.refresh(mapping, form, request, response);
1532     }
1533 
1534     private LookupService getLookupService() {
1535         return KRADServiceLocatorWeb.getLookupService();
1536     }
1537 
1538     @Override
1539     public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1540         Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
1541         // this should probably be moved into a protected instance variable
1542         ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
1543 
1544         // logic for cancel question
1545         if (question == null) {
1546 
1547             // ask question if not already asked
1548             return this.performQuestionWithoutInput(mapping, form, request, response, OLEConstants.DOCUMENT_CANCEL_QUESTION, kualiConfiguration.getPropertyValueAsString("document.question.cancel.text"), OLEConstants.CONFIRMATION_QUESTION, OLEConstants.MAPPING_CANCEL, "");
1549         } else {
1550             Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
1551             if ((OLEConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
1552 
1553                 // if no button clicked just reload the doc
1554                 return mapping.findForward(OLEConstants.MAPPING_BASIC);
1555             }
1556             // else go to cancel logic below
1557         }
1558         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1559         OlePurchaseOrderForm purchaseOrderForm = (OlePurchaseOrderForm) form;
1560         if ((purchaseOrderForm.getDocTypeName()).equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT)) {
1561             List<Note> noteList = new ArrayList<Note>();
1562 
1563             if (kualiDocumentFormBase.getDocument().getNotes().size() > 0) {
1564                 for (Note note : (List<Note>) kualiDocumentFormBase.getDocument().getNotes()) {
1565                     noteList.add(note);
1566                     getBusinessObjectService().delete(note);
1567                 }
1568             }
1569             SpringContext.getBean(DocumentService.class).cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
1570             if (noteList.size() > 0) {
1571                 getBusinessObjectService().save(noteList);
1572             }
1573 
1574             return returnToSender(request, mapping, kualiDocumentFormBase);
1575         }
1576         return returnToSender(request, mapping, kualiDocumentFormBase);
1577     }
1578 
1579     public ActionForward addDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1580         boolean flag = true;
1581         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
1582         int line = this.getSelectedLine(request);
1583         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
1584         Map map = new HashMap();
1585         if (item.getDonorCode() != null) {
1586             map.put(OLEConstants.DONOR_CODE, item.getDonorCode());
1587             List<OLEDonor> oleDonorList = (List<OLEDonor>) getLookupService().findCollectionBySearch(OLEDonor.class, map);
1588             if (oleDonorList != null && oleDonorList.size() > 0) {
1589                 OLEDonor oleDonor = oleDonorList.get(0);
1590                 if (oleDonor != null) {
1591                     for (OLELinkPurapDonor oleLinkPurapDonor : item.getOleDonors()) {
1592                         if (oleLinkPurapDonor.getDonorCode().equalsIgnoreCase(item.getDonorCode())) {
1593                             flag = false;
1594                             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1595                                     OLEConstants.DONOR_CODE_EXISTS, new String[]{});
1596                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1597                         }
1598                     }
1599                     if (flag) {
1600                         OLELinkPurapDonor donor = new OLELinkPurapDonor();
1601                         donor.setDonorId(oleDonor.getDonorId());
1602                         donor.setDonorCode(oleDonor.getDonorCode());
1603                         item.getOleDonors().add(donor);
1604                         item.setDonorCode(null);
1605                     }
1606                 }
1607             } else {
1608                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1609                         OLEConstants.ERROR_DONOR_CODE, new String[]{});
1610             }
1611         }
1612         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1613     }
1614 
1615     public ActionForward deleteDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1616                                      HttpServletResponse response) throws Exception {
1617         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
1618         String[] indexes = getSelectedLineForAccounts(request);
1619         int itemIndex = Integer.parseInt(indexes[0]);
1620         int donorIndex = Integer.parseInt(indexes[1]);
1621         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
1622         item.getOleDonors().remove(donorIndex);
1623         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1624     }
1625 
1626     @Override
1627     protected ActionForward performQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String questionText, String questionType, String caller, String context) throws Exception {
1628         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, "", "", "", "");
1629     }
1630 
1631 
1632     private ActionForward performQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String questionText, String questionType, String caller, String context, boolean showReasonField, String reason, String errorKey, String errorPropertyName, String errorParameter) throws Exception {
1633         Properties parameters = new Properties();
1634 
1635         parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, "start");
1636         parameters.put(KRADConstants.DOC_FORM_KEY, GlobalVariables.getUserSession().addObjectWithGeneratedKey(form));
1637         parameters.put(KRADConstants.CALLING_METHOD, caller);
1638         parameters.put(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME, questionId);
1639         parameters.put(KRADConstants.QUESTION_IMPL_ATTRIBUTE_NAME, questionType);
1640         //parameters.put(KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME, questionText);
1641         parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, getReturnLocation(request, mapping));
1642         parameters.put(KRADConstants.QUESTION_CONTEXT, context);
1643         parameters.put(KRADConstants.QUESTION_SHOW_REASON_FIELD, Boolean.toString(showReasonField));
1644         parameters.put(KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, reason);
1645         parameters.put(KRADConstants.QUESTION_ERROR_KEY, errorKey);
1646         parameters.put(KRADConstants.QUESTION_ERROR_PROPERTY_NAME, errorPropertyName);
1647         parameters.put(KRADConstants.QUESTION_ERROR_PARAMETER, errorParameter);
1648         parameters.put(KRADConstants.QUESTION_ANCHOR, form instanceof KualiForm ? org.apache.commons.lang.ObjectUtils.toString(((KualiForm) form).getAnchor()) : "");
1649         Object methodToCallAttribute = request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
1650         if (methodToCallAttribute != null) {
1651             parameters.put(KRADConstants.METHOD_TO_CALL_PATH, methodToCallAttribute);
1652             ((PojoForm) form).registerEditableProperty(String.valueOf(methodToCallAttribute));
1653         }
1654 
1655         if (form instanceof KualiDocumentFormBase) {
1656             String docNum = ((KualiDocumentFormBase) form).getDocument().getDocumentNumber();
1657             if(docNum != null){
1658                 parameters.put(KRADConstants.DOC_NUM, ((KualiDocumentFormBase) form)
1659                         .getDocument().getDocumentNumber());
1660             }
1661         }
1662 
1663         // KULRICE-8077: PO Quote Limitation of Only 9 Vendors
1664         String questionTextAttributeName = KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME + questionId;
1665         GlobalVariables.getUserSession().addObject(questionTextAttributeName, (Object)questionText);
1666         String questionUrl = null;
1667         if (questionId.equalsIgnoreCase(PODocumentsStrings.VOID_QUESTION)) {
1668             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + OLEConstants.QUESTION_ACTION , parameters);
1669         } else {
1670             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + "/kr/" + KRADConstants.QUESTION_ACTION, parameters);
1671         }
1672 
1673         return new ActionForward(questionUrl, true);
1674     }
1675 
1676     @Override
1677     protected ActionForward performQuestionWithInputAgainBecauseOfErrors(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String questionText, String questionType, String caller, String context, String reason, String errorKey, String errorPropertyName, String errorParameter) throws Exception {
1678         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, reason, errorKey, errorPropertyName, errorParameter);
1679     }
1680 
1681 }
1682 
1683