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         /*if (GlobalVariables.getMessageMap().getErrorCount() == 0) {
420             setDefaultItemStatusAndLocation(document, (OlePurchaseOrderItem) purchasingForm.getNewPurchasingItemLine());
421         }*/
422         return mapping.findForward(OLEConstants.MAPPING_BASIC);
423     }
424 
425     /**
426      * Add Note for the selected PurchaseOrderItem
427      *
428      * @param mapping
429      * @param form
430      * @param request
431      * @param response
432      * @return An ActionForward
433      * @throws Exception
434      */
435 
436     public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
437         LOG.debug("Inside addNote Method of PurchaseOrderAction");
438         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
439         int line = this.getSelectedLine(request);
440         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
441         OlePurchaseOrderNotes note = new OlePurchaseOrderNotes();
442         note.setNote(item.getNote());
443         note.setNoteTypeId(item.getNoteTypeId());
444         item.getNotes().add(note);
445         LOG.debug("Adding Note to PurchaseOrderItem");
446         item.setNote(null);
447         item.setNoteTypeId(null);
448         LOG.debug("Leaving addNote Method of PurchaseOrderAction");
449         return mapping.findForward(OLEConstants.MAPPING_BASIC);
450     }
451 
452     /**
453      * deletes the selected Note for the selected POItem
454      *
455      * @param mapping
456      * @param form
457      * @param request
458      * @param response
459      * @return An ActionForward
460      * @throws Exception
461      */
462     public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
463         LOG.debug("Inside deleteNote Method of PurchaseOrderAction");
464         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
465         String[] indexes = getSelectedLineForAccounts(request);
466         int itemIndex = Integer.parseInt(indexes[0]);
467         int noteIndex = Integer.parseInt(indexes[1]);
468         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
469         item.getNotes().remove(noteIndex);
470         LOG.debug("Note deleted for the selected Item");
471         LOG.debug("Leaving deleteNote Method of PurchaseOrderAction");
472         return mapping.findForward(OLEConstants.MAPPING_BASIC);
473     }
474 
475     /**
476      * This method is overridden to change receivingitem url with respect to OLE
477      *
478      * @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)
479      */
480     @Override
481     public ActionForward createReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
482         LOG.debug("Inside createReceivingLine Method of OlePurchaseOrderAction");
483         PurchaseOrderForm poForm = (PurchaseOrderForm) form;
484         PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
485 
486         String basePath = getApplicationBaseUrl();
487         String methodToCallDocHandler = "continueReceivingLine";
488         String methodToCallReceivingLine = "initiate";
489 
490         //set parameters
491         Properties parameters = new Properties();
492         parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
493         parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingLine);
494         parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVL");
495         parameters.put("purchaseOrderId", document.getPurapDocumentIdentifier().toString());
496 
497         //create url
498         // Changed receivingUrl to point to the OLE receiving URL (OLE-2057)
499         String receivingUrl = UrlFactory.parameterizeUrl(basePath + "/" + "selectOleLineItemReceiving.do", parameters);
500 
501         //create forward
502         ActionForward forward = new ActionForward(receivingUrl, true);
503         LOG.debug("Leaving createReceivingLine Method of OlePurchaseOrderAction");
504         return forward;
505     }
506 
507     /**
508      * Creates a URL to be used in printing the purchase order.
509      *
510      * @param basePath     String: The base path of the current URL
511      * @param docId        String: The document ID of the document to be printed
512      * @param methodToCall String: The name of the method that will be invoked to do this particular print
513      * @return The URL
514      */
515     @Override
516     protected String getUrlForPrintPO(String basePath, String docId, String methodToCall) {
517         StringBuffer result = new StringBuffer(basePath);
518         result.append("/purapOlePurchaseOrder.do?methodToCall=");
519         result.append(methodToCall);
520         result.append("&docId=");
521         result.append(docId);
522         result.append("&command=displayDocSearchView");
523 
524         return result.toString();
525     }
526 
527     @Override
528     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
529         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
530         PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
531         if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
532             //   setDocstoreDataForCopies((OlePurchaseOrderAmendmentDocument) purDoc);
533         }
534         // if form is not yet calculated, return and prompt user to calculate
535         if (requiresCalculate(purchasingForm)) {
536             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
537 
538             return mapping.findForward(OLEConstants.MAPPING_BASIC);
539         }
540 
541         // call prorateDiscountTradeIn
542         SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
543         this.calculate(mapping, purchasingForm, request, response);
544         PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) purchasingForm.getDocument();
545         List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems();
546         for (int i = OLEConstants.ZERO; purDoc.getItems().size() > i; i++) {
547             OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i);
548             if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
549                 if (item.getCopyList().size()==OLEConstants.ZERO && item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
550                         && !item.getItemNoOfParts().isGreaterThan(OLEConstants.ONE) ) {
551                     OleCopy oleCopy = new OleCopy();
552                     oleCopy.setLocation(item.getItemLocation());
553                     oleCopy.setBibId(item.getItemTitleId());
554                     oleCopy.setCopyNumber(item.getSingleCopyNumber()!=null && !item.getSingleCopyNumber().isEmpty()?item.getSingleCopyNumber():null);
555                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
556                     if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
557                         oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
558                     }
559                     List<OleCopy> copyList = new ArrayList<>();
560                     copyList.add(oleCopy);
561                     item.setCopyList(copyList);
562                 }
563             }
564             if (item.getItemIdentifier() != null && item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
565                     && !item.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)) {
566                 Map<String, String> map = new HashMap<>();
567                 map.put(OLEConstants.PO_ID, item.getItemIdentifier().toString());
568                 List<OleCopy> oleCopyList = (List<OleCopy>) SpringContext.getBean(BusinessObjectService.class).findMatching(OleCopy.class, map);
569                 if (oleCopyList.size() == 1) {
570                     item.getCopyList().get(0).setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
571                 }
572             }
573             if (item.getItemIdentifier() != null) {
574                 Map map = new HashMap();
575                 map.put(OLEConstants.PO_ID, item.getItemIdentifier().toString());
576                 List<OLELinkPurapDonor> linkPurapDonors = (List<OLELinkPurapDonor>) getBusinessObjectService().findMatching(OLELinkPurapDonor.class, map);
577                 if (linkPurapDonors != null && linkPurapDonors.size() > 0) {
578                     getBusinessObjectService().delete(linkPurapDonors);
579                 }
580             }
581         }
582         return super.route(mapping, form, request, response);
583 
584     }
585 
586 //    public void setDocstoreDataForCopies(OlePurchaseOrderAmendmentDocument purDoc) throws Exception {
587 //        List<OlePurchaseOrderItem> items = new ArrayList<OlePurchaseOrderItem>();
588 //        items = purDoc.getItems();
589 //        Iterator iterator = items.iterator();
590 //        while (iterator.hasNext()) {
591 //            Object object = iterator.next();
592 //            if (object instanceof OlePurchaseOrderItem) {
593 //                OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
594 //                List<String> itemTitleIdsList = new ArrayList<String>();
595 //                List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
596 //                // for (OlePurchaseOrderItem itemTitleId : items) {
597 //                if (null != singleItem.getItemTitleId()) {
598 //                    if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
599 //                            || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
600 //                        itemTitleIdsList.add(singleItem.getItemTitleId());
601 //                        workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
602 //                        for (WorkBibDocument workBibDocument : workBibDocuments) {
603 //
604 //
605 //                        }
606 //                    }
607 //                }
608 //                // }
609 //                // setEnumerationToCopies(singleItem);
610 //                /*
611 //                 * if (null != singleItem.getItemTitleId() && workBibDocuments.size() > 0) { }
612 //                 */
613 //            }
614 //        }
615 //    }
616 
617     public void setEnumerationToCopies(List<OlePurchaseOrderItem> purItem) {
618         String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
619                 OLEConstants.PART_ENUMERATION_COPY);
620         String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
621                 OLEConstants.PART_ENUMERATION_VOLUME);
622         for (int singleItem = 0; purItem.size() > singleItem; singleItem++) {
623             List<OleCopies> purItemCopies = purItem.get(singleItem).getCopies();
624             for (int copies = 0; copies < purItemCopies.size(); copies++) {
625                 purItemCopies.get(copies).setParts(purItem.get(singleItem).getItemNoOfParts());
626                 int startingCopyNumber = purItemCopies.get(copies).getStartingCopyNumber().intValue();
627                 StringBuffer enumeration = new StringBuffer();
628                 for (int noOfCopies = 0; noOfCopies < purItemCopies.get(copies).getItemCopies().intValue(); noOfCopies++) {
629                     for (int noOfParts = 0; noOfParts < purItemCopies.get(copies).getParts().intValue(); noOfParts++) {
630                         int newNoOfCopies = startingCopyNumber + noOfCopies;
631                         int newNoOfParts = noOfParts + 1;
632                         if (noOfCopies + 1 == purItemCopies.get(copies).getItemCopies().intValue()
633                                 && newNoOfParts == purItemCopies.get(copies).getParts().intValue()) {
634                             enumeration = enumeration.append(
635                                     partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
636                                     partEnumerationVolume + newNoOfParts);
637                         } else {
638                             enumeration = enumeration.append(
639                                     partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
640                                     partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
641                         }
642                     }
643                 }
644                 purItemCopies.get(copies).setPartEnumeration(enumeration.toString());
645             }
646         }
647     }
648 
649 
650     /**
651      * For use with a specific set of methods of this class that create new purchase order-derived document types in response to
652      * user actions, including <code>closePo</code>, <code>reopenPo</code>, <code>paymentHoldPo</code>, <code>removeHoldPo</code>,
653      * <code>splitPo</code>, <code>amendPo</code>, and <code>voidPo</code>. It employs the question framework to ask
654      * the user for a response before creating and routing the new document. The response should consist of a note detailing a
655      * 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
656      * question framework); when each question is originally asked, and again when the yes/no response is processed, for
657      * confirmation.
658      *
659      * @param mapping      These are boiler-plate.
660      * @param form         "
661      * @param request      "
662      * @param response     "
663      * @param questionType A string identifying the type of question being asked.
664      * @param confirmType  A string identifying which type of question is being confirmed.
665      * @param documentType A string, the type of document to create
666      * @param notePrefix   A string to appear before the note in the BO Notes tab
667      * @param messageType  A string to appear on the PO once the question framework is done, describing the action taken
668      * @param operation    A string, the verb to insert in the original question describing the action to be taken
669      * @return An ActionForward
670      * @throws Exception
671      */
672     @Override
673     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 {
674         LOG.debug("askQuestionsAndPerformDocumentAction started.");
675         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
676         PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
677         Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
678         String reason = request.getParameter(OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME);
679         String noteText = "";
680         String noteOne = "";
681         String noteTwo = "";
682 
683         try {
684             ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
685             String[] reasons = null;
686             // Start in logic for confirming the proposed operation.
687             if (ObjectUtils.isNull(question)) {
688                 String message = "";
689                 if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
690                     message = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_SPLIT_QUESTION_TEXT);
691                 } else {
692                     String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
693                     message = StringUtils.replace(key, "{0}", operation);
694                 }
695                 // Ask question if not already asked.
696                 return this.performQuestionWithInput(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "");
697             } else {
698                 Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
699                 if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
700 
701                     // If 'No' is the button clicked, just reload the doc
702                     return returnToPreviousPage(mapping, kualiDocumentFormBase);
703                 } else if (question.equals(confirmType) && buttonClicked.equals(SingleConfirmationQuestion.OK)) {
704 
705                     // This is the case when the user clicks on "OK" in the end.
706                     // After we inform the user that the close has been rerouted, we'll redirect to the portal page.
707                     return mapping.findForward(OLEConstants.MAPPING_PORTAL);
708                 } else {
709                     // Have to check length on value entered.
710                     String introNoteMessage = notePrefix + OLEConstants.BLANK_SPACE;
711                     int noteTextLength = 0;
712                     // Build out full message.
713                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
714                         if (StringUtils.isNotBlank(reason)) {
715                             reasons = reason.split("/");
716                             noteOne = introNoteMessage + reasons[0];
717                             if (!reasons[1].equalsIgnoreCase(null)) {
718                                 noteTwo = introNoteMessage + reasons[1];
719                                 noteTextLength = noteTwo.length();
720                             }
721 
722                         }
723                     } else {
724                     noteText = introNoteMessage + reason;
725                         noteTextLength = noteText.length();
726                     }
727 
728                     // Get note text max length from DD.
729                     int noteTextMaxLength = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getAttributeMaxLength(Note.class, OLEConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
730 
731                     String message = "";
732                     String key = kualiConfiguration.getPropertyValueAsString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
733                     message = StringUtils.replace(key, "{0}", operation);
734 
735                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT))  {
736                         if (reasons == null || reasons[0].trim().equalsIgnoreCase("null")) {
737                             reason = "";
738                             return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, message, OLEConstants.CONFIRMATION_QUESTION, questionType, "", reason, OLEConstants.ERROR_CANCELLATION_REASON_REQUIRED, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, "");
739                         } else if (!reasons[1].equalsIgnoreCase(null) && (noteTextLength > noteTextMaxLength)) {
740                             reason = "";
741                             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());
742                         }
743                     }
744 
745                     if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
746                         // Figure out exact number of characters that the user can enter.
747                         int reasonLimit = noteTextMaxLength - noteTextLength;
748 
749                         if (ObjectUtils.isNull(reason)) {
750                             // Prevent a NPE by setting the reason to a blank string.
751                             reason = "";
752                         }
753 
754                         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());
755                     }
756                 }
757             }
758             // Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
759             ActionForward returnActionForward = null;
760             if (!po.isPendingActionIndicator()) {
761                 /*
762                  * Below if-else code block calls PurchaseOrderService methods that will throw ValidationException objects if errors
763                  * occur during any process in the attempt to perform its actions. Assume, if these return successfully, that the
764                  * PurchaseOrderDocument object returned from each is the newly created document and that all actions in the method
765                  * were run correctly. NOTE: IF BELOW IF-ELSE IS EDITED THE NEW METHODS CALLED MUST THROW ValidationException OBJECT
766                  * IF AN ERROR IS ADDED TO THE GlobalVariables
767                  */
768                 if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
769                     po.setPendingSplit(true);
770                     // Save adding the note for after the items are picked.
771                     ((PurchaseOrderForm) kualiDocumentFormBase).setSplitNoteText(noteText);
772                     returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
773                 } else {
774                     String newStatus = null;
775                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
776 
777                         newStatus = PurchaseOrderStatuses.APPDOC_AMENDMENT;
778                         po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
779                         returnActionForward = mapping.findForward(OLEConstants.MAPPING_BASIC);
780                     } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
781                         newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REOPEN;
782                         po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
783                     } else {
784                         if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT)) {
785                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_CLOSE;
786                         }
787                         /*else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
788                             newStatus = PurchaseOrderStatuses.PENDING_REOPEN;
789                         }*/
790                         else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
791                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_VOID;
792                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)) {
793                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_PAYMENT_HOLD;
794                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT)) {
795                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_REMOVE_HOLD;
796                         } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT)) {
797                             newStatus = PurchaseOrderStatuses.APPDOC_PENDING_RETRANSMIT;
798                         }
799                         po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), newStatus);
800                     }
801                     if (!GlobalVariables.getMessageMap().hasNoErrors()) {
802                         throw new ValidationException("errors occurred during new PO creation");
803                     }
804 
805                     String previousDocumentId = kualiDocumentFormBase.getDocId();
806                     // Assume at this point document was created properly and 'po' variable is new PurchaseOrderDocument created
807                     kualiDocumentFormBase.setDocument(po);
808                     kualiDocumentFormBase.setDocId(po.getDocumentNumber());
809                     kualiDocumentFormBase.setDocTypeName(po.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
810                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
811                         Note noteObjOne = new Note();
812                         noteObjOne.setNoteText(noteOne);
813                         noteObjOne.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
814                         kualiDocumentFormBase.setNewNote(noteObjOne);
815 
816                         kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
817 
818                         insertBONote(mapping, kualiDocumentFormBase, request, response);
819 
820                         if (!reasons[1].trim().equalsIgnoreCase("null")) {
821                             Note noteObjTwo = new Note();
822                             noteObjTwo.setNoteText(noteTwo);
823                             noteObjTwo.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
824                             kualiDocumentFormBase.setNewNote(noteObjTwo);
825 
826                             kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
827 
828                             insertBONote(mapping, kualiDocumentFormBase, request, response);
829                         }
830                     } else {
831                     Note newNote = new Note();
832                     if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
833                         noteText = noteText + " (Previous Document Id is " + previousDocumentId + ")";
834                     }
835                     newNote.setNoteText(noteText);
836                     newNote.setNoteTypeCode(OLEConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
837                     kualiDocumentFormBase.setNewNote(newNote);
838                     kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
839                     insertBONote(mapping, kualiDocumentFormBase, request, response);
840                 }
841              }
842                 if (StringUtils.isNotEmpty(messageType)) {
843                     KNSGlobalVariables.getMessageList().add(messageType);
844                 }
845             }
846             if (ObjectUtils.isNotNull(returnActionForward)) {
847                 return returnActionForward;
848             } else {
849 
850                 return this.performQuestionWithoutInput(mapping, form, request, response, confirmType, kualiConfiguration.getPropertyValueAsString(messageType), PODocumentsStrings.SINGLE_CONFIRMATION_QUESTION, questionType, "");
851             }
852         } catch (ValidationException ve) {
853             throw ve;
854         }
855     }
856 
857     @Override
858     public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
859         LOG.debug("<<<---------Inside OlePurchaseOrderAction Refresh------>>>");
860         ActionForward forward = super.refresh(mapping, form, request, response);
861         OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
862         PurchaseOrderDocument document = (PurchaseOrderDocument) rqForm.getDocument();
863         OlePurchaseOrderItem item = (OlePurchaseOrderItem) rqForm.getNewPurchasingItemLine();
864 
865         if (document.getVendorDetail().getCurrencyType()!=null){
866             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
867                 currencyTypeIndicator=true;
868             }
869             else{
870                 currencyTypeIndicator=false;
871             }
872         }
873         // To set PurchaseOrderTransmissionMethod depend on vendor transmission format
874         if (document.getVendorDetail() != null) {
875             if (document.getVendorDetail().getVendorTransmissionFormat().size() > 0) {
876                 List<VendorTransmissionFormatDetail> vendorTransmissionFormat = document.getVendorDetail().getVendorTransmissionFormat();
877                 for (VendorTransmissionFormatDetail iter : vendorTransmissionFormat) {
878                     if (iter.isVendorPreferredTransmissionFormat()) {
879                         if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat() != null) {
880                             if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat().equalsIgnoreCase(OleSelectConstant.VENDOR_TRANSMISSION_FORMAT_EDI)) {
881                                 document.setPurchaseOrderTransmissionMethodCode(OleSelectConstant.METHOD_OF_PO_TRANSMISSION_NOPR);
882                             } else {
883                                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
884                             }
885                         }
886                     }
887                 }
888             } else {
889                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
890             }
891             if ( (!currencyTypeIndicator) && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
892                 Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
893                 Map documentNumberMap = new HashMap();
894                 documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
895                 BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
896                 List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
897                 Iterator iterator = exchangeRateList.iterator();
898                 if (iterator.hasNext()) {
899                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
900                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
901                 }
902             }
903         }
904         return forward;
905     }
906 
907     @Override
908     public ActionForward amendPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
909         // TODO Auto-generated method stub
910         ActionForward findForward = super.amendPo(mapping, form, request, response);
911         OlePurchaseOrderForm rqForm = (OlePurchaseOrderForm) form;
912         OlePurchaseOrderAmendmentDocument olePurchaseOrderAmendmentDocument = new OlePurchaseOrderAmendmentDocument();
913         if ((rqForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
914             rqForm.getAndResetNewPurchasingItemLine();
915         }
916         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
917         Document document = kualiDocumentFormBase.getDocument();
918         // prepare for the reload action - set doc id and command
919         kualiDocumentFormBase.setDocId(document.getDocumentNumber());
920         kualiDocumentFormBase.setCommand(DOCUMENT_LOAD_COMMANDS[1]);
921         // forward off to the doc handler
922         docHandler(mapping, form, request, response);
923 
924         return findForward;
925     }
926 
927     /**
928      * Is executed when the user clicks on the "print" button on a Purchase Order Print Document page. On a non
929      * javascript enabled browser, it will display a page with 2 buttons. One is to display the PDF, the other is to view the PO
930      * tabbed page where the PO document statuses, buttons, etc have already been updated (the updates of those occurred while the
931      * <code>performPurchaseOrderFirstTransmitViaPrinting</code> method is invoked. On a javascript enabled browser, it will
932      * display both the PO tabbed page containing the updated PO document info and the pdf on the next window/tab of the browser.
933      *
934      * @param mapping  An ActionMapping
935      * @param form     An ActionForm
936      * @param request  The HttpServletRequest
937      * @param response The HttpServletResponse
938      * @return An ActionForward
939      * @throws Exception
940      */
941     @Override
942     public ActionForward firstTransmitPrintPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
943         PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
944         String poDocId = ((PurchaseOrderForm) form).getDocId();
945         ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
946         try {
947             SpringContext.getBean(OlePurchaseOrderService.class).performPurchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
948         } finally {
949             if (baosPDF != null) {
950                 baosPDF.reset();
951             }
952         }
953         String basePath = getApplicationBaseUrl();
954         String docId = ((PurchaseOrderForm) form).getDocId();
955         String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
956         String methodToCallDocHandler = "docHandler";
957         String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
958         String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
959         request.setAttribute("printPOPDFUrl", printPOPDFUrl);
960         request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
961         String label = "";
962         if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
963             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
964         } else {
965             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
966         }
967         request.setAttribute("purchaseOrderLabel", label);
968 
969         return mapping.findForward("printPurchaseOrderPDF");
970     }
971 
972     public ActionForward printPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
973         PurchaseOrderDocument poa = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
974         String poDocId = ((PurchaseOrderForm) form).getDocId();
975         ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
976         try {
977             SpringContext.getBean(OlePurchaseOrderService.class).purchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
978         } finally {
979             if (baosPDF != null) {
980                 baosPDF.reset();
981             }
982         }
983         String basePath = getApplicationBaseUrl();
984         String docId = ((PurchaseOrderForm) form).getDocId();
985         String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
986         String methodToCallDocHandler = "docHandler";
987         String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
988         String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
989         request.setAttribute("printPOPDFUrl", printPOPDFUrl);
990         request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
991         String label = "";
992         if (OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT.equalsIgnoreCase(poa.getDocumentHeader().getWorkflowDocument().getDocumentTypeName())) {
993             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT);
994         } else {
995             label = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER);
996         }
997         request.setAttribute("purchaseOrderLabel", label);
998 
999         return mapping.findForward("printPurchaseOrderPDF");
1000     }
1001 
1002     /**
1003      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
1004      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1005      */
1006     @Override
1007     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1008         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
1009         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
1010 
1011         // index of item selected
1012         int itemIndex = getSelectedLine(request);
1013         PurApItem item = null;
1014 
1015         // if custom processing of an accounting line is not done then insert a line generically.
1016         if (processCustomInsertAccountingLine(purapForm, request) == false) {
1017             String errorPrefix = null;
1018             PurApAccountingLine line = null;
1019 
1020             boolean rulePassed = false;
1021             if (itemIndex >= 0) {
1022                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
1023                 //Calculating the dollar amount for the accounting Line.
1024                 PurApAccountingLine lineItem = item.getNewSourceLine();
1025                 if (lineItem.getAccountLinePercent() != null) {
1026                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1027                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1028                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
1029                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1030                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
1031                     lineItem.setAccountLinePercent(dollarToPercent);
1032                 }
1033                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
1034                 //end
1035                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
1036                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
1037                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
1038             } else if (itemIndex == -2) {
1039                 //corrected: itemIndex == -2 is the only case for distribute account
1040                 //This is the case when we're inserting an accounting line for distribute account.
1041                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
1042                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
1043                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
1044                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
1045             }
1046             AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
1047             if (accountingLineBase != null) {
1048                 String accountNumber = accountingLineBase.getAccountNumber();
1049                 String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
1050                 Map<String, String> criteria = new HashMap<String, String>();
1051                 criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1052                 criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1053                 Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
1054                         criteria);
1055                 rulePassed = checkForValidAccount(account);
1056             }
1057             if (rulePassed) {
1058                 // add accountingLine
1059                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
1060 
1061                 PurApAccountingLine newSourceLine = item.getNewSourceLine();
1062                 List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();
1063 
1064                 BigDecimal initialValue = new BigDecimal(0);
1065 
1066                 for (PurApAccountingLine accountLine : existingSourceLine) {
1067                     initialValue = initialValue.add(accountLine.getAccountLinePercent());
1068                 }
1069                 if (itemIndex >= 0) {
1070 
1071                     if ((newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
1072                         if (OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue() != OleSelectConstant.ZERO) {
1073                             insertAccountingLine(purapForm, item, line);
1074                         }
1075                     }else {
1076                         checkAccountingLinePercent(newSourceLine);
1077 
1078                     }
1079                     for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
1080                         if(oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
1081                             ((OlePurchaseOrderAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
1082                         }
1083                     }
1084                     List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
1085                     BigDecimal totalPercent = new BigDecimal(100);
1086                     BigDecimal initialPercent = new BigDecimal(0);
1087                     for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
1088                         initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
1089 
1090                     }
1091                     initialPercent = totalPercent.subtract(initialPercent);
1092                     BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
1093                     if (maxPercent.intValue() == OleSelectConstant.ZERO) {
1094                         item.resetAccount(OleSelectConstant.ZERO_PERCENT);
1095 
1096                     } else {
1097                         item.resetAccount(initialPercent);
1098 
1099                     }
1100                 } else if (itemIndex == -2) {
1101                     //this is the case for distribute account
1102                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
1103                 }
1104             }
1105         }
1106 
1107         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1108     }
1109 
1110     private void checkAccountingLinePercent(PurApAccountingLine newSourceLine) {
1111         if (newSourceLine.getAccountLinePercent().intValue() >= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED) {
1112             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1113                     OleSelectPropertyConstants.ERROR_PERCENT_SHOULD_GREATER, OleSelectConstant.PERCENT);
1114         } else if (newSourceLine.getAccountLinePercent().intValue() == OleSelectConstant.ZERO) {
1115             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1116                     OleSelectPropertyConstants.ERROR_PERCENT_ZERO, OleSelectConstant.PERCENT);
1117         } else {
1118 
1119         }
1120 
1121     }
1122 
1123     private boolean checkForValidAccount(Account account) {
1124         boolean result = true;
1125         if (account != null) {
1126             String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
1127                     OleSelectConstant.SUB_FUND_GRP_CD);
1128             if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
1129                 GlobalVariables.getMessageMap()
1130                         .putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1131                                 OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
1132                                 new String[]{OleSelectConstant.PURCHASE_ORDER});
1133                 result = false;
1134             }
1135         }
1136         return result;
1137     }
1138 
1139     private void setItemDescription(OlePurchaseOrderItem item, String fileName) throws Exception{
1140         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
1141             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
1142             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
1143             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
1144             bib = (Bib) bib.deserializeContent(bib);
1145             if (bib != null) {
1146                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
1147                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
1148                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
1149                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
1150                 String description = title + author + publisher + isbn;
1151                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId().toString()));
1152                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
1153             }
1154             if (bib != null) {
1155                 item.setBibUUID(bib.getId());
1156                 item.setItemTitleId(bib.getId());
1157                 item.setLinkToOrderOption(oleEditorResponse.getLinkToOrderOption());
1158             }
1159             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
1160         }
1161     }
1162 
1163     // Added for Jira OLE-1900 Starts
1164 
1165     public ActionForward addCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1166                                  HttpServletResponse response) throws Exception {
1167         LOG.debug("Inside addCopy Method of OleRequisitionAction");
1168         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1169         OlePurchaseOrderAmendmentDocument purDocument = (OlePurchaseOrderAmendmentDocument) purchasingForm
1170                 .getDocument();
1171         int line = this.getSelectedLine(request);
1172         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1173                 .getDocument()).getItem(line);
1174         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1175         OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
1176         boolean isValid = true;
1177         List<String> volChar = new ArrayList<>();
1178         String[] volNumbers = item.getVolumeNumber() != null ? item.getVolumeNumber().split(",") : new String[0];
1179         for (String volStr : volNumbers) {
1180             volChar.add(volStr);
1181         }
1182         Integer itemCount = volChar.size();
1183         isValid = oleCopyHelperService.checkCopyEntry(
1184                 item.getItemCopies(), item.getLocationCopies(), itemCount, item.getItemQuantity(), item.getItemNoOfParts(), item.getCopies(), item.getVolumeNumber(), false);
1185         if (isValid) {
1186             itemCopy.setItemCopies(item.getItemCopies());
1187             itemCopy.setLocationCopies(item.getLocationCopies());
1188             itemCopy.setParts(item.getItemNoOfParts());
1189             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1190             itemCopy.setCaption(item.getCaption());
1191             itemCopy.setVolumeNumber(item.getVolumeNumber());
1192             List<OleCopy> copyList = oleCopyHelperService.setCopyValues(itemCopy, item.getItemTitleId(), volChar);
1193             // 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.
1194             if (StringUtils.isNotEmpty(item.getItemLocation())) {
1195                 if (!item.getItemLocation().equalsIgnoreCase(item.getLocationCopies()) && !item.isLocationFlag() && item.getCopyList().size()==1) {
1196                     KRADServiceLocator.getBusinessObjectService().delete(item.getCopyList().get(0));
1197                     item.getCopyList().clear();
1198                     item.getCopyList().addAll(copyList);
1199                     item.setLocationFlag(true);
1200                 }
1201                 else {
1202                     if (item.getCopyList().size() == 1) {
1203                         KRADServiceLocator.getBusinessObjectService().delete(item.getCopyList().get(0));
1204                         item.getCopyList().clear();
1205                     }
1206                     item.getCopyList().addAll(copyList);
1207                 }
1208             }
1209             else {// For Multiple copies, the copy gets added.
1210                 item.getCopyList().addAll(copyList);
1211             }
1212             item.getCopies().add(itemCopy);
1213             item.setParts(null);
1214             item.setItemCopies(null);
1215             item.setPartEnumeration(null);
1216             item.setLocationCopies(null);
1217             item.setCaption(null);
1218             item.setVolumeNumber(null);
1219            /* if (item.getCopies().size() > 0) {
1220                 int startingCopies = 1;
1221                 for (int copy = 0; copy < item.getCopies().size(); copy++) {
1222                     startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1223                 }
1224                 item.setStartingCopyNumber(new KualiInteger(startingCopies));
1225             }*/
1226         }
1227 
1228         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1229     }
1230 
1231     public boolean checkForCopiesAndLocation(OlePurchaseOrderItem item) {
1232         boolean isValid = true;
1233         if (null == item.getItemCopies() || null == item.getLocationCopies()) {
1234             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1235                     OLEConstants.ITEM_ITEMCOPIES_OR_LOCATIONCOPIES_SHOULDNOT_BE_NULL, new String[]{});
1236             isValid = false;
1237         }
1238         return isValid;
1239     }
1240 
1241     public boolean checkForItemCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1242         boolean isValid = true;
1243         if (item.getItemCopies().isGreaterThan(item.getItemQuantity())) {
1244             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1245                     OLEConstants.ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1246             isValid = false;
1247         }
1248         return isValid;
1249     }
1250 
1251     public boolean checkForTotalCopiesGreaterThanQuantity(OlePurchaseOrderItem item) {
1252         boolean isValid = true;
1253         int copies = 0;
1254         if (item.getCopies().size() > 0) {
1255             for (int itemCopies = 0; itemCopies < item.getCopies().size(); itemCopies++) {
1256                 copies = copies + item.getCopies().get(itemCopies).getItemCopies().intValue();
1257             }
1258             if (item.getItemQuantity().isLessThan(item.getItemCopies().add(new KualiDecimal(copies)))) {
1259                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1260                         OLEConstants.TOTAL_OF_ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
1261                 isValid = false;
1262             }
1263         }
1264         return isValid;
1265     }
1266 
1267     /**
1268      * This method takes purchaseorderItem as parameter, it will calculate and set partEnumerations and startingCopyNumber for each
1269      * lineItem
1270      *
1271      * @param item
1272      * @return OleRequisitionCopies
1273      */
1274     public OleRequisitionCopies setCopyValues(OlePurchaseOrderItem item) {
1275         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
1276         itemCopy.setParts(item.getItemNoOfParts());
1277         itemCopy.setItemCopies(item.getItemCopies());
1278         StringBuffer enumeration = new StringBuffer();
1279         if (item.getStartingCopyNumber() != null && item.getStartingCopyNumber().isNonZero()) {
1280             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
1281         } else {
1282             int startingCopies = 1;
1283             for (int copy = 0; copy < item.getCopies().size(); copy++) {
1284                 startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
1285             }
1286             itemCopy.setStartingCopyNumber(new KualiInteger(startingCopies));
1287         }
1288         String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
1289                 OLEConstants.PART_ENUMERATION_COPY);
1290         String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
1291                 OLEConstants.PART_ENUMERATION_VOLUME);
1292         int startingCopyNumber = itemCopy.getStartingCopyNumber().intValue();
1293         for (int noOfCopies = 0; noOfCopies < item.getItemCopies().intValue(); noOfCopies++) {
1294             for (int noOfParts = 0; noOfParts < item.getItemNoOfParts().intValue(); noOfParts++) {
1295                 int newNoOfCopies = startingCopyNumber + noOfCopies;
1296                 int newNoOfParts = noOfParts + 1;
1297                 if (noOfCopies + 1 == item.getItemCopies().intValue()
1298                         && newNoOfParts == item.getItemNoOfParts().intValue()) {
1299                     enumeration = enumeration.append(
1300                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1301                             partEnumerationVolume + newNoOfParts);
1302                 } else {
1303                     enumeration = enumeration.append(
1304                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
1305                             partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
1306                 }
1307             }
1308         }
1309         itemCopy.setPartEnumeration(enumeration.toString());
1310         itemCopy.setLocationCopies(item.getLocationCopies());
1311         return itemCopy;
1312     }
1313 
1314     /**
1315      * Remove a Copy for the selected Item .
1316      *
1317      * @param mapping  An ActionMapping
1318      * @param form     An ActionForm
1319      * @param request  The HttpServletRequest
1320      * @param response The HttpServletResponse
1321      * @return An ActionForward
1322      * @throws Exception
1323      */
1324     public ActionForward deleteCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1325                                     HttpServletResponse response) throws Exception {
1326         LOG.debug("Inside deleteCopy Method of OleRequisitionAction");
1327         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1328         String[] indexes = getSelectedLineForAccounts(request);
1329         int itemIndex = Integer.parseInt(indexes[0]);
1330         int copyIndex = Integer.parseInt(indexes[1]);
1331         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1332                 .getDocument()).getItem((itemIndex));
1333         List<OleCopy> copyList = new ArrayList<>();
1334         for(int i=0;i<item.getCopyList().size();i++){
1335             OleCopy oleCopy = item.getCopyList().get(i);
1336             if(item.getCopies().get(copyIndex).getLocationCopies().equalsIgnoreCase(oleCopy.getLocation())){
1337                 copyList.add(oleCopy);
1338             }
1339         }
1340         for(OleCopy copy : copyList){
1341             item.getCopyList().remove(copy);
1342             item.getDeletedCopiesList().add(copy);
1343         }
1344         item.getCopies().remove(copyIndex);
1345         LOG.debug("Selected Copy is Remove");
1346         LOG.debug("Leaving deleteCopy Method of OleRequisitionAction");
1347         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1348     }
1349 
1350     /**
1351      * Add a Payment History for selected Item.
1352      *
1353      * @param mapping  An ActionMapping
1354      * @param form     An ActionForm
1355      * @param request  The HttpServletRequest
1356      * @param response The HttpServletResponse
1357      * @return An ActionForward
1358      * @throws Exception
1359      */
1360     public ActionForward addPaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1361                                            HttpServletResponse response) throws Exception {
1362         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1363         int line = this.getSelectedLine(request);
1364         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1365                 .getDocument()).getItem(line);
1366         OleRequisitionPaymentHistory paymentHistory = new OleRequisitionPaymentHistory();
1367         paymentHistory.setPaymentHistory("");
1368         item.getRequisitionPaymentHistory().add(paymentHistory);
1369         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1370     }
1371 
1372     /**
1373      * Remove a Payment History for selected Item
1374      *
1375      * @param mapping
1376      * @param form
1377      * @param request
1378      * @param response
1379      * @return
1380      * @throws Exception
1381      */
1382     public ActionForward deletePaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1383                                               HttpServletResponse response) throws Exception {
1384 
1385         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1386         String[] indexes = getSelectedLineForAccounts(request);
1387         int itemIndex = Integer.parseInt(indexes[0]);
1388         int copyIndex = Integer.parseInt(indexes[1]);
1389         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm
1390                 .getDocument()).getItem((itemIndex));
1391         item.getRequisitionPaymentHistory().remove(copyIndex);
1392         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1393     }
1394 
1395     public static ConfigurationService getConfigurationService() {
1396         if (kualiConfigurationService == null) {
1397             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
1398         }
1399         return kualiConfigurationService;
1400     }
1401 
1402     /**
1403      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
1404      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
1405      *
1406      * @param instanceIdsList
1407      * @return List<WorkBibDocument>
1408      */
1409 //    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
1410 //        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
1411 //        for (String instanceId : instanceIdsList) {
1412 //            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
1413 //            instanceIdMap.put(DocType.INSTANCE.getDescription(), instanceId);
1414 //            instanceIdMapList.add(instanceIdMap);
1415 //        }
1416 //
1417 //        QueryService queryService = QueryServiceImpl.getInstance();
1418 //        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
1419 //        try {
1420 //            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
1421 //        } catch (Exception ex) {
1422 //            // TODO Auto-generated catch block
1423 //            ex.printStackTrace();
1424 //        }
1425 //        return workBibDocuments;
1426 //    }
1427 
1428     // Added for Jira OLE-1900 Ends
1429 
1430     @Override
1431     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1432                                         HttpServletResponse response) throws Exception {
1433         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1434         PurchasingDocument document = (PurchasingDocument) ((PurchasingFormBase) form).getDocument();
1435         this.calculate(mapping, purchasingForm, request, response);
1436         Iterator itemIterator = document.getItems().iterator();
1437         boolean rulePassed = true;
1438         while (itemIterator.hasNext()) {
1439             OlePurchaseOrderItem tempItem = (OlePurchaseOrderItem) itemIterator.next();
1440             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
1441                 if (tempItem.getCopyList().size()==OLEConstants.ZERO && tempItem.getItemQuantity() != null && tempItem.getItemNoOfParts() != null && !tempItem.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
1442                         && !tempItem.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)) {
1443                     OleCopy oleCopy = new OleCopy();
1444                     oleCopy.setLocation(tempItem.getItemLocation());
1445                     oleCopy.setBibId(tempItem.getItemTitleId());
1446                     if (StringUtils.isNotBlank(tempItem.getLinkToOrderOption()) && (tempItem.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || tempItem.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
1447                         oleCopy.setCopyNumber(tempItem.getSingleCopyNumber() != null && !tempItem.getSingleCopyNumber().isEmpty() ? tempItem.getSingleCopyNumber() : null);
1448                     }
1449                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1450                     List<OleCopy> copyList = new ArrayList<>();
1451                     copyList.add(oleCopy);
1452                     tempItem.setCopyList(copyList);
1453                 }
1454                 if(tempItem.getItemIdentifier()!=null && tempItem.getItemQuantity() != null && tempItem.getItemNoOfParts() != null && !tempItem.getItemQuantity().isGreaterThan(OLEConstants.ONE.kualiDecimalValue())
1455                         && !tempItem.getItemNoOfParts().isGreaterThan(OLEConstants.ONE)){
1456                     Map<String,String> map=new HashMap<>();
1457                     map.put(OLEConstants.PO_ID,tempItem.getItemIdentifier().toString());
1458                     List<OleCopy> oleCopyList =(List<OleCopy>)SpringContext.getBean(BusinessObjectService.class).findMatching(OleCopy.class, map);
1459                     if(oleCopyList.size()==1){
1460                         tempItem.getCopyList().get(0).setCopyNumber(tempItem.getSingleCopyNumber()!=null && !tempItem.getSingleCopyNumber().isEmpty()?tempItem.getSingleCopyNumber():null);
1461                     }
1462                 }
1463                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
1464                 if (accountingLineBase != null) {
1465                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
1466                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
1467                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
1468                         Map<String, String> criteria = new HashMap<String, String>();
1469                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1470                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1471                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1472                                 Account.class, criteria);
1473                         rulePassed = checkForValidAccount(account);
1474                         if (!rulePassed) {
1475                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1476                         }
1477                     }
1478                 }
1479             }
1480             if (tempItem.getItemIdentifier() != null) {
1481                 Map map = new HashMap();
1482                 map.put(OLEConstants.PO_ID, tempItem.getItemIdentifier().toString());
1483                 List<OLELinkPurapDonor> linkPurapDonors = (List<OLELinkPurapDonor>) getBusinessObjectService().findMatching(OLELinkPurapDonor.class, map);
1484                 if (linkPurapDonors != null && linkPurapDonors.size() > 0) {
1485                     getBusinessObjectService().delete(linkPurapDonors);
1486                 }
1487             }
1488         }
1489         return super.blanketApprove(mapping, form, request, response);
1490     }
1491 
1492     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1493         OlePurchaseOrderForm purchasingForm = (OlePurchaseOrderForm) form;
1494         OlePurchaseOrderAmendmentDocument document = (OlePurchaseOrderAmendmentDocument) purchasingForm.getDocument();
1495         if ((purchasingForm.getDocTypeName()).equalsIgnoreCase("OLE_POA")) {
1496             if (document.getVendorAliasName() != null && document.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
1497             /* Getting matching vendor for the given vendor alias name */
1498                 Map vendorAliasMap = new HashMap();
1499                 vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, document.getVendorAliasName());
1500                 org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
1501                 List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
1502                 if (vendorAliasList != null && vendorAliasList.size() > 0) {  /* if there matching vendor found for the given vendor alias name */
1503                     Map vendorDetailMap = new HashMap();
1504                     vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1505                     vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1506                     VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
1507                     document.setVendorDetail(vendorDetail);
1508                     document.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1509                     document.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1510                     refreshVendor(mapping, form, request, response);
1511                 } else {     /* If there is no matching vendor found*/
1512                     GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
1513                 }
1514             }
1515         }
1516         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1517     }
1518 
1519     public ActionForward refreshVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1520         PurchasingAccountsPayableFormBase baseForm = (PurchasingAccountsPayableFormBase) form;
1521         PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
1522         if (StringUtils.equals(OLEConstants.REFRESH_VENDOR_CALLER, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && document.getVendorDetailAssignedIdentifier() != null && document.getVendorHeaderGeneratedIdentifier() != null) {
1523             document.setVendorContractGeneratedIdentifier(null);
1524             document.refreshReferenceObject(OLEConstants.VENDOR_CONTRACT);
1525 
1526             // retrieve vendor based on selection from vendor lookup
1527             document.refreshReferenceObject(OLEConstants.VENDOR_DETAILS);
1528             document.templateVendorDetail(document.getVendorDetail());
1529 
1530             // populate default address based on selected vendor
1531             VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), document.getDeliveryCampusCode());
1532             document.templateVendorAddress(defaultAddress);
1533         }
1534         return super.refresh(mapping, form, request, response);
1535     }
1536 
1537     private LookupService getLookupService() {
1538         return KRADServiceLocatorWeb.getLookupService();
1539     }
1540 
1541     @Override
1542     public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1543         Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
1544         // this should probably be moved into a protected instance variable
1545         ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
1546 
1547         // logic for cancel question
1548         if (question == null) {
1549 
1550             // ask question if not already asked
1551             return this.performQuestionWithoutInput(mapping, form, request, response, OLEConstants.DOCUMENT_CANCEL_QUESTION, kualiConfiguration.getPropertyValueAsString("document.question.cancel.text"), OLEConstants.CONFIRMATION_QUESTION, OLEConstants.MAPPING_CANCEL, "");
1552         } else {
1553             Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
1554             if ((OLEConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
1555 
1556                 // if no button clicked just reload the doc
1557                 return mapping.findForward(OLEConstants.MAPPING_BASIC);
1558             }
1559             // else go to cancel logic below
1560         }
1561         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1562         OlePurchaseOrderForm purchaseOrderForm = (OlePurchaseOrderForm) form;
1563         if ((purchaseOrderForm.getDocTypeName()).equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_AMENDMENT)) {
1564             List<Note> noteList = new ArrayList<Note>();
1565 
1566             if (kualiDocumentFormBase.getDocument().getNotes().size() > 0) {
1567                 for (Note note : (List<Note>) kualiDocumentFormBase.getDocument().getNotes()) {
1568                     noteList.add(note);
1569                     getBusinessObjectService().delete(note);
1570                 }
1571             }
1572             SpringContext.getBean(DocumentService.class).cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
1573             if (noteList.size() > 0) {
1574                 getBusinessObjectService().save(noteList);
1575             }
1576 
1577             return returnToSender(request, mapping, kualiDocumentFormBase);
1578         }
1579         return returnToSender(request, mapping, kualiDocumentFormBase);
1580     }
1581 
1582     public ActionForward addDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1583         boolean flag = true;
1584         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
1585         int line = this.getSelectedLine(request);
1586         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
1587         Map map = new HashMap();
1588         if (item.getDonorCode() != null) {
1589             map.put(OLEConstants.DONOR_CODE, item.getDonorCode());
1590             List<OLEDonor> oleDonorList = (List<OLEDonor>) getLookupService().findCollectionBySearch(OLEDonor.class, map);
1591             if (oleDonorList != null && oleDonorList.size() > 0) {
1592                 OLEDonor oleDonor = oleDonorList.get(0);
1593                 if (oleDonor != null) {
1594                     for (OLELinkPurapDonor oleLinkPurapDonor : item.getOleDonors()) {
1595                         if (oleLinkPurapDonor.getDonorCode().equalsIgnoreCase(item.getDonorCode())) {
1596                             flag = false;
1597                             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1598                                     OLEConstants.DONOR_CODE_EXISTS, new String[]{});
1599                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1600                         }
1601                     }
1602                     if (flag) {
1603                         OLELinkPurapDonor donor = new OLELinkPurapDonor();
1604                         donor.setDonorId(oleDonor.getDonorId());
1605                         donor.setDonorCode(oleDonor.getDonorCode());
1606                         item.getOleDonors().add(donor);
1607                         item.setDonorCode(null);
1608                     }
1609                 }
1610             } else {
1611                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1612                         OLEConstants.ERROR_DONOR_CODE, new String[]{});
1613             }
1614         }
1615         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1616     }
1617 
1618     public ActionForward deleteDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1619                                      HttpServletResponse response) throws Exception {
1620         PurchaseOrderForm purchasingForm = (PurchaseOrderForm) form;
1621         String[] indexes = getSelectedLineForAccounts(request);
1622         int itemIndex = Integer.parseInt(indexes[0]);
1623         int donorIndex = Integer.parseInt(indexes[1]);
1624         OlePurchaseOrderItem item = (OlePurchaseOrderItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
1625         item.getOleDonors().remove(donorIndex);
1626         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1627     }
1628 
1629     @Override
1630     protected ActionForward performQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String questionText, String questionType, String caller, String context) throws Exception {
1631         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, "", "", "", "");
1632     }
1633 
1634 
1635     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 {
1636         Properties parameters = new Properties();
1637 
1638         parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, "start");
1639         parameters.put(KRADConstants.DOC_FORM_KEY, GlobalVariables.getUserSession().addObjectWithGeneratedKey(form));
1640         parameters.put(KRADConstants.CALLING_METHOD, caller);
1641         parameters.put(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME, questionId);
1642         parameters.put(KRADConstants.QUESTION_IMPL_ATTRIBUTE_NAME, questionType);
1643         //parameters.put(KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME, questionText);
1644         parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, getReturnLocation(request, mapping));
1645         parameters.put(KRADConstants.QUESTION_CONTEXT, context);
1646         parameters.put(KRADConstants.QUESTION_SHOW_REASON_FIELD, Boolean.toString(showReasonField));
1647         parameters.put(KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, reason);
1648         parameters.put(KRADConstants.QUESTION_ERROR_KEY, errorKey);
1649         parameters.put(KRADConstants.QUESTION_ERROR_PROPERTY_NAME, errorPropertyName);
1650         parameters.put(KRADConstants.QUESTION_ERROR_PARAMETER, errorParameter);
1651         parameters.put(KRADConstants.QUESTION_ANCHOR, form instanceof KualiForm ? org.apache.commons.lang.ObjectUtils.toString(((KualiForm) form).getAnchor()) : "");
1652         Object methodToCallAttribute = request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
1653         if (methodToCallAttribute != null) {
1654             parameters.put(KRADConstants.METHOD_TO_CALL_PATH, methodToCallAttribute);
1655             ((PojoForm) form).registerEditableProperty(String.valueOf(methodToCallAttribute));
1656         }
1657 
1658         if (form instanceof KualiDocumentFormBase) {
1659             String docNum = ((KualiDocumentFormBase) form).getDocument().getDocumentNumber();
1660             if(docNum != null){
1661                 parameters.put(KRADConstants.DOC_NUM, ((KualiDocumentFormBase) form)
1662                         .getDocument().getDocumentNumber());
1663             }
1664         }
1665 
1666         // KULRICE-8077: PO Quote Limitation of Only 9 Vendors
1667         String questionTextAttributeName = KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME + questionId;
1668         GlobalVariables.getUserSession().addObject(questionTextAttributeName, (Object)questionText);
1669         String questionUrl = null;
1670         if (questionId.equalsIgnoreCase(PODocumentsStrings.VOID_QUESTION)) {
1671             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + OLEConstants.QUESTION_ACTION , parameters);
1672         } else {
1673             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + "/kr/" + KRADConstants.QUESTION_ACTION, parameters);
1674         }
1675 
1676         return new ActionForward(questionUrl, true);
1677     }
1678 
1679     @Override
1680     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 {
1681         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, reason, errorKey, errorPropertyName, errorParameter);
1682     }
1683 
1684 }
1685 
1686