View Javadoc
1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 1.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/ecl1.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.StringUtils;
19  import org.apache.struts.action.ActionForm;
20  import org.apache.struts.action.ActionForward;
21  import org.apache.struts.action.ActionMapping;
22  import org.kuali.ole.DocumentUniqueIDPrefix;
23  import org.kuali.ole.coa.businessobject.Account;
24  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
25  import org.kuali.ole.docstore.common.document.Bib;
26  import org.kuali.ole.docstore.common.document.Holdings;
27  import org.kuali.ole.module.purap.PurapConstants;
28  import org.kuali.ole.module.purap.PurapKeyConstants;
29  import org.kuali.ole.module.purap.PurapParameterConstants;
30  import org.kuali.ole.module.purap.PurapPropertyConstants;
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.PurchasingAccountsPayableDocument;
34  import org.kuali.ole.module.purap.document.PurchasingDocument;
35  import org.kuali.ole.module.purap.document.RequisitionDocument;
36  import org.kuali.ole.module.purap.document.service.OlePurapService;
37  import org.kuali.ole.module.purap.document.service.PurapService;
38  import org.kuali.ole.pojo.OleBibRecord;
39  import org.kuali.ole.pojo.OleEditorResponse;
40  import org.kuali.ole.select.OleSelectConstant;
41  import org.kuali.ole.select.bo.OLEDonor;
42  import org.kuali.ole.select.bo.OLELinkPurapDonor;
43  import org.kuali.ole.select.bo.OLEEditorResponse;
44  import org.kuali.ole.select.businessobject.*;
45  import org.kuali.ole.select.constants.OleSelectPropertyConstants;
46  import org.kuali.ole.select.document.OleDefaultValueAssignment;
47  import org.kuali.ole.select.document.OleInvoiceDocument;
48  import org.kuali.ole.select.document.OleRequisitionDocument;
49  import org.kuali.ole.select.document.service.OleCopyHelperService;
50  import org.kuali.ole.select.document.service.OleDocstoreHelperService;
51  import org.kuali.ole.select.document.service.OleRequisitionDocumentService;
52  import org.kuali.ole.select.document.validation.event.CopiesRequisitionEvent;
53  import org.kuali.ole.select.document.validation.event.DiscountRequisitionEvent;
54  import org.kuali.ole.select.document.validation.event.ForeignCurrencyRequisitionEvent;
55  import org.kuali.ole.select.document.web.struts.OleRequisitionForm;
56  import org.kuali.ole.sys.OLEConstants;
57  import org.kuali.ole.sys.OLEPropertyConstants;
58  import org.kuali.ole.sys.businessobject.AccountingLineBase;
59  import org.kuali.ole.sys.businessobject.SourceAccountingLine;
60  import org.kuali.ole.sys.context.SpringContext;
61  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
62  import org.kuali.ole.vnd.VendorConstants;
63  import org.kuali.ole.vnd.businessobject.*;
64  import org.kuali.ole.vnd.document.service.VendorService;
65  import org.kuali.rice.core.api.config.property.ConfigurationService;
66  import org.kuali.rice.core.api.util.RiceKeyConstants;
67  import org.kuali.rice.core.api.util.type.KualiDecimal;
68  import org.kuali.rice.core.api.util.type.KualiInteger;
69  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
70  import org.kuali.rice.kew.api.exception.WorkflowException;
71  import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
72  import org.kuali.rice.krad.service.*;
73  import org.kuali.rice.krad.util.GlobalVariables;
74  import org.kuali.rice.krad.util.KRADConstants;
75  import org.kuali.rice.krad.util.ObjectUtils;
76  
77  import javax.servlet.http.HttpServletRequest;
78  import javax.servlet.http.HttpServletResponse;
79  import java.math.BigDecimal;
80  import java.math.RoundingMode;
81  import java.util.*;
82  
83  public class OleRequisitionAction extends RequisitionAction {
84      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleRequisitionAction.class);
85      private static transient ConfigurationService kualiConfigurationService;
86      private boolean sufficientFundChecklag = true;
87      private DocstoreClientLocator docstoreClientLocator;
88      private static transient OlePurapService olePurapService;
89  
90      public DocstoreClientLocator getDocstoreClientLocator() {
91          if (docstoreClientLocator == null) {
92              docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
93          }
94          return docstoreClientLocator;
95      }
96  
97      public static OlePurapService getOlePurapService() {
98          if (olePurapService == null) {
99              olePurapService = SpringContext.getBean(OlePurapService.class);
100         }
101         return olePurapService;
102     }
103 
104     public static void setOlePurapService(OlePurapService olePurapService) {
105         OleRequisitionAction.olePurapService = olePurapService;
106     }
107     /**
108      * Does initialization for a new requisition.
109      *
110      * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#createDocument(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase)
111      */
112     @Override
113     protected void createDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
114         LOG.debug("Inside the OleRequisitionAction class Create Document");
115         super.createDocument(kualiDocumentFormBase);
116         OleRequisitionForm oleRequisitionForm = (OleRequisitionForm) kualiDocumentFormBase;
117         OleRequisitionItem oleRequisitionItem = (OleRequisitionItem) oleRequisitionForm.getNewPurchasingItemLine();
118         ((RequisitionDocument) kualiDocumentFormBase.getDocument()).initiateDocument();
119         RequisitionDocument requisitionDocument = (RequisitionDocument) kualiDocumentFormBase.getDocument();
120         new OleDefaultValueAssignment(oleRequisitionForm.getDefaultDocumentTypeName(), oleRequisitionItem, requisitionDocument);
121     }
122 
123     /**
124      * Calculate the whole document.
125      *
126      * @param mapping  An ActionMapping
127      * @param form     An ActionForm
128      * @param request  The HttpServletRequest
129      * @param response The HttpServletResponse
130      * @return An ActionForward
131      * @throws Exception
132      */
133 
134     @Override
135     public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
136         LOG.debug("Inside the OleRequisitionAction class Calculate");
137         PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
138         List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
139         for(PurApItem purApItem:purApItems){
140             List<KualiDecimal> existingAmount=new ArrayList<>();
141             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
142                 if(oldSourceAccountingLine instanceof OleRequisitionAccount) {
143                     if(((OleRequisitionAccount)oldSourceAccountingLine).getExistingAmount()!=null){
144                         existingAmount.add(((OleRequisitionAccount)oldSourceAccountingLine).getExistingAmount());
145                     }
146                 }
147             }
148             int count=0;
149             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
150 
151                 if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) {
152                     if (account.getAmount()!=null&&count<existingAmount.size()&&existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) {
153                         KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString());
154                         account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE,BigDecimal.ROUND_CEILING));
155                     }
156                     else {
157                         if(account.getAccountLinePercent().intValue()==100&&(account.getAmount()==null||account.getAccount()!=null)){
158                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
159                             account.setAmount(calculatedAmount);
160                         }
161                         else{
162                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
163                             account.setAmount(calculatedAmount);
164                         }
165                     }
166                 }
167                 count++;
168             }
169             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
170                 if(oldSourceAccountingLine instanceof OleRequisitionAccount) {
171                     ((OleRequisitionAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
172                 }
173             }
174         }
175         ActionForward forward = super.calculate(mapping, form, request, response);
176         purchasingForm = (PurchasingAccountsPayableFormBase) form;
177         PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
178         PurchasingFormBase formBase = (PurchasingFormBase) form;
179         OleRequisitionDocument reqDoc = (OleRequisitionDocument) formBase.getDocument();
180         boolean foreignCurrencyIndicator = false;
181 
182         List<OleRequisitionItem> item = reqDoc.getItems();
183         if (purDoc.getVendorDetail()!=null) {
184             foreignCurrencyIndicator = isForeignCurrency(purDoc.getVendorDetail().getCurrencyType());
185         }
186         if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && (!foreignCurrencyIndicator))) {
187             for (int i = 0; purDoc.getItems().size() > i; i++) {
188                 OleRequisitionItem items = (OleRequisitionItem) purDoc.getItem(i);
189                 if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
190                     boolean rulePassed = getKualiRuleService().applyRules(new DiscountRequisitionEvent(reqDoc, items));
191                     if (rulePassed) {
192                         items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(items).setScale(2, BigDecimal.ROUND_HALF_UP));
193                     }
194                     rulePassed = getKualiRuleService().applyRules(new CopiesRequisitionEvent(reqDoc, items));
195                 }
196 
197             }
198         } else {
199             LOG.debug("###########Foreign Currency Field Calculation###########");
200             for (int i = 0; item.size() > i; i++) {
201                 OleRequisitionItem items = (OleRequisitionItem) reqDoc.getItem(i);
202                 if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
203                     boolean rulePassed = getKualiRuleService().applyRules(new ForeignCurrencyRequisitionEvent(reqDoc, items));
204                     if (rulePassed) {
205                         SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
206                         Long id = reqDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
207                         Map documentNumberMap = new HashMap();
208                         documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
209                         BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
210                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
211                         Iterator iterator = exchangeRateList.iterator();
212                         if (iterator.hasNext()) {
213                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
214                             items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
215                         }
216                         if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
217                             items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
218                             items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
219                             items.setItemListPrice(items.getItemUnitCostUSD());
220                             items.setTotalAmount(items.getTotalAmount());
221                         }
222                     }
223                 }
224             }
225         }
226         purchasingForm = (PurchasingAccountsPayableFormBase) form;
227         List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
228         for(PurApItem purApItem:newpurApItems){
229             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
230                 KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
231                 account.setAmount(calculatedAmount);
232             }
233         }
234         forward = super.calculate(mapping, form, request, response);
235         // formBase.setCalculated(true);
236 
237         // Added for jira OLE-964
238         OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext
239                 .getBean("oleRequisitionDocumentService");
240         List<SourceAccountingLine> sourceAccountingLineList = reqDoc.getSourceAccountingLines();
241         for (SourceAccountingLine accLine : sourceAccountingLineList) {
242             String notificationOption = null;
243             boolean sufficientFundCheck;
244             Map<String, Object> key = new HashMap<String, Object>();
245             String chartCode = accLine.getChartOfAccountsCode();
246             String accNo = accLine.getAccountNumber();
247             key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
248             key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
249             OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
250                     OleSufficientFundCheck.class, key);
251             if (account != null) {
252                 notificationOption = account.getNotificationOption();
253             }
254             if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) {
255                 sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine);
256                 if (sufficientFundCheck) {
257                     GlobalVariables.getMessageMap().putError(
258                             OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM,
259                             OLEConstants.SufficientFundCheck.INSUFF_FUND_REQ + accLine.getAccountNumber());
260                 }
261             }
262         }
263         // End
264         if (LOG.isDebugEnabled()) {
265             LOG.debug("Inside the OleRequisitionAcrion class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice());
266         }
267         return forward;
268     }
269 
270     /**
271      * Add a new item to the document.
272      *
273      * @param mapping  An ActionMapping
274      * @param form     An ActionForm
275      * @param request  The HttpServletRequest
276      * @param response The HttpServletResponse
277      * @return An ActionForward
278      * @throws Exception
279      */
280     @Override
281     public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
282         LOG.debug("###########Inside AddItem in oleRequisitionAction ###########");
283         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
284         OleRequisitionItem item = (OleRequisitionItem) purchasingForm.getNewPurchasingItemLine();
285         OleRequisitionDocument document = (OleRequisitionDocument) purchasingForm.getDocument();
286         OleRequisitionForm oleForm = (OleRequisitionForm) form;
287         OleRequisitionDocument doc = (OleRequisitionDocument) oleForm.getDocument();
288         Iterator itemIterator = doc.getItems().iterator();
289         int itemCounter = 0;
290         while (itemIterator.hasNext()) {
291             OleRequisitionItem tempItem = (OleRequisitionItem) itemIterator.next();
292             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
293                 itemCounter++;
294             }
295         }
296         String itemNo = String.valueOf(itemCounter);
297         BibInfoBean xmlBibInfoBean = new BibInfoBean();
298         if (item.getBibInfoBean() == null) {
299             item.setBibInfoBean(xmlBibInfoBean);
300             if (item.getBibInfoBean().getDocStoreOperation() == null) {
301                 item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
302             }
303         } else {
304             if (item.getBibInfoBean().getDocStoreOperation() == null) {
305                 item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
306             }
307         }
308         String fileName = document.getDocumentNumber() + "_" + itemNo;
309         // Modified for jira OLE - 2437 starts
310 
311         setItemDescription(item, fileName);
312         if (document.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != null) {
313             if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && !document.getVendorDetail().getVendorHeader().getVendorForeignIndicator())) {
314                 purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item).setScale(2, BigDecimal.ROUND_HALF_UP));
315                 super.addItem(mapping, purchasingForm, request, response);
316                 //}
317             } else {
318                 LOG.debug("###########Foreign Currency Field Calculation for requisition###########");
319                 SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(item);
320                 Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
321                 Map documentNumberMap = new HashMap();
322                 documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
323                 BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
324                 List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
325                 Iterator iterator = exchangeRateList.iterator();
326                 if (iterator.hasNext()) {
327                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
328                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
329                 }
330                 if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
331                     item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
332                     item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
333                     item.setItemListPrice(item.getItemUnitCostUSD());
334                 }
335                 super.addItem(mapping, purchasingForm, request, response);
336             }
337         } else {
338             purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item).setScale(2, BigDecimal.ROUND_HALF_UP));
339             super.addItem(mapping, purchasingForm, request, response);
340         }
341         if(item.getClaimDate()==null){
342             getOlePurapService().setClaimDateForReq(item,document.getVendorDetail());
343         }
344         return mapping.findForward(OLEConstants.MAPPING_BASIC);
345     }
346 
347     /**
348      * Takes care of storing the action form in the User session and forwarding to the prlookup action.
349      *
350      * @param mapping
351      * @param form
352      * @param request
353      * @param response
354      * @return
355      * @throws Exception
356      */
357     public ActionForward performPRLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
358         LOG.debug("Inside performPRLookup Method of OleRequisitionAction");
359         ActionForward forward = super.performLookup(mapping, form, request, response);
360         String path = forward.getPath();
361         if (path.contains("kr/" + KRADConstants.LOOKUP_ACTION)) {
362             path = path.replace("kr/" + KRADConstants.LOOKUP_ACTION, OLEConstants.PR_LOOKUP_ACTION);
363             // path = path.replace("kr/lookup.do", "ptrnlookup.do");
364         } else if (path.contains(KRADConstants.LOOKUP_ACTION)) {
365             path = path.replace(KRADConstants.LOOKUP_ACTION, OLEConstants.PR_LOOKUP_ACTION);
366             // path = path.replace("lookup.do", "ptrnlookup.do");
367         }
368         forward.setPath(path);
369         LOG.debug("Leaving performPRLookup Method of OleRequisitionAction");
370         return forward;
371     }
372 
373 
374     /**
375      * Add a new Note to the selected RequisitionItem.
376      *
377      * @param mapping  An ActionMapping
378      * @param form     An ActionForm
379      * @param request  The HttpServletRequest
380      * @param response The HttpServletResponse
381      * @return An ActionForward
382      * @throws Exception
383      */
384 
385     public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
386         LOG.debug("Inside addNote Method of OleRequisitionAction");
387         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
388         int line = this.getSelectedLine(request);
389         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
390         OleRequisitionNotes note = new OleRequisitionNotes();
391         note.setNoteTypeId(item.getNoteTypeId());
392         note.setNote(item.getNote());
393         item.getNotes().add(note);
394         LOG.debug("Adding Note to the RequisitionItem");
395         item.setNoteTypeId(null);
396         item.setNote(null);
397         LOG.debug("Leaving addNote Method of OleRequisitionAction");
398         return mapping.findForward(OLEConstants.MAPPING_BASIC);
399     }
400 
401     /**
402      * Remove a note for the selected Item .
403      *
404      * @param mapping  An ActionMapping
405      * @param form     An ActionForm
406      * @param request  The HttpServletRequest
407      * @param response The HttpServletResponse
408      * @return An ActionForward
409      * @throws Exception
410      */
411     public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
412         LOG.debug("Inside deleteNote Method of OleRequisitionAction");
413         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
414         String[] indexes = getSelectedLineForAccounts(request);
415         int itemIndex = Integer.parseInt(indexes[0]);
416         int noteIndex = Integer.parseInt(indexes[1]);
417         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
418         item.getNotes().remove(noteIndex);
419         LOG.debug("Selected Note is Remove");
420         LOG.debug("Leaving deleteNote Method of OleRequisitionAction");
421         return mapping.findForward(OLEConstants.MAPPING_BASIC);
422     }
423 
424     @Override
425     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
426         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
427         PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
428         PurchasingFormBase formBase = (PurchasingFormBase) form;
429         OleRequisitionDocument reqDoc = (OleRequisitionDocument) formBase.getDocument();
430         List<OleRequisitionItem> items = reqDoc.getItems();
431         // if form is not yet calculated, return and prompt user to calculate
432         if (requiresCalculate(purchasingForm)) {
433             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
434             return mapping.findForward(OLEConstants.MAPPING_BASIC);
435         }
436         // call prorateDiscountTradeIn
437         SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
438         this.calculate(mapping, purchasingForm, request, response);
439         for (OleRequisitionItem item : items) {
440             if (null != item.getItemType() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
441                 if (item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(new KualiDecimal(1))
442                         && !item.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
443                     OleCopy oleCopy = new OleCopy();
444                     oleCopy.setLocation(item.getItemLocation());
445                     oleCopy.setBibId(item.getItemTitleId());
446                     if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
447                         oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
448                     }
449                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
450                     List<OleCopy> copyList = new ArrayList<>();
451                     copyList.add(oleCopy);
452                     item.setCopyList(copyList);
453                 }
454             }
455         }
456         if (sufficientFundChecklag) {
457             return super.route(mapping, form, request, response);
458         }
459         return mapping.findForward(OLEConstants.MAPPING_BASIC);
460     }
461 
462     // changes for jira OLE-2177.
463 
464     /**
465      * @see org.kuali.rice.kns.web.struts.action.KualiAction#refresh(org.apache.struts.action.ActionMapping,
466      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
467      */
468     @Override
469     public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
470         LOG.debug("<<<---------Inside OleRequisitionAction Refresh------>>>");
471         ActionForward forward = super.refresh(mapping, form, request, response);
472         OleRequisitionForm rqForm = (OleRequisitionForm) form;
473         OleRequisitionDocument document = (OleRequisitionDocument) rqForm.getDocument();
474         OleRequisitionItem item = (OleRequisitionItem) rqForm.getNewPurchasingItemLine();
475         // super.refresh() must occur before this line to get the correct APO limit
476         document.setOrganizationAutomaticPurchaseOrderLimit(SpringContext.getBean(PurapService.class).getApoLimit(document.getVendorContractGeneratedIdentifier(), document.getChartOfAccountsCode(), document.getOrganizationCode()));
477         // To set PurchaseOrderTransmissionMethod depend on vendor transmission format
478         if (LOG.isInfoEnabled()) {
479             LOG.info("Currency Type on Requisition :" + document.getVendorDetail().getCurrencyType());
480         }
481         if (document.getVendorDetail() != null) {
482             if (document.getVendorDetail().getVendorTransmissionFormat().size() > 0) {
483                 List<VendorTransmissionFormatDetail> vendorTransmissionFormat = document.getVendorDetail().getVendorTransmissionFormat();
484                 for (VendorTransmissionFormatDetail iter : vendorTransmissionFormat) {
485                     if (iter.isVendorPreferredTransmissionFormat()) {
486                         if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat() != null) {
487                             if (iter.getVendorTransmissionFormat().getVendorTransmissionFormat().equalsIgnoreCase(OleSelectConstant.VENDOR_TRANSMISSION_FORMAT_EDI) ||
488                                     iter.getVendorTransmissionFormat().getVendorTransmissionFormat().equalsIgnoreCase(OleSelectConstant.VENDOR_TRANSMISSION_FORMAT_PDF)) {
489                                 document.setPurchaseOrderTransmissionMethodCode(OleSelectConstant.METHOD_OF_PO_TRANSMISSION_NOPR);
490                             } else {
491                                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
492                             }
493                         }
494                     }
495                 }
496             } else {
497                 document.setPurchaseOrderTransmissionMethodCode(SpringContext.getBean(ParameterService.class).getParameterValueAsString(RequisitionDocument.class, PurapParameterConstants.PURAP_DEFAULT_PO_TRANSMISSION_CODE));
498             }
499             boolean foreignCurrencyIndicator = isForeignCurrency(document.getVendorDetail().getCurrencyType());
500           //  if (document.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != null) {
501                 if ((!foreignCurrencyIndicator) && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
502                     if (document.getVendorDetail().getCurrencyType() != null) {
503                         Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
504                         Map documentNumberMap = new HashMap();
505                         documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
506                         BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
507                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
508                         Iterator iterator = exchangeRateList.iterator();
509                         if (iterator.hasNext()) {
510                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
511                             item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
512                         }
513                     }
514                 }
515             //}
516         }
517         return forward;
518     }
519 
520     private boolean isForeignCurrency(OleCurrencyType oleCurrencyType){
521         boolean foreignCurrencyIndicator = false;
522         if(oleCurrencyType!=null){
523             if(!oleCurrencyType.getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
524                 foreignCurrencyIndicator = true;
525             }
526         }
527         return foreignCurrencyIndicator;
528     }
529 
530     /**
531      * @see org.kuali.ole.module.purap.document.web.struts.RequisitionAction#clearVendor(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
532      */
533     @Override
534     public ActionForward clearVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
535 
536         ActionForward forward = super.clearVendor(mapping, form, request, response);
537         OleRequisitionForm rqForm = (OleRequisitionForm) form;
538         OleRequisitionDocument document = (OleRequisitionDocument) rqForm.getDocument();
539         document.setPurchaseOrderTransmissionMethodCode(OleSelectConstant.METHOD_OF_PO_TRANSMISSION_NOPR);
540         return forward;
541     }
542     // end for jira OLE-2177.
543     // added for jira OLE-2112
544 
545     /**
546      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
547      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
548      */
549     @Override
550     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
551         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
552         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
553 
554 
555         // index of item selected
556         int itemIndex = getSelectedLine(request);
557         PurApItem item = null;
558 
559 
560         // if custom processing of an accounting line is not done then insert a line generically.
561         if (processCustomInsertAccountingLine(purapForm, request) == false) {
562             String errorPrefix = null;
563             PurApAccountingLine line = null;
564 
565             boolean rulePassed = false;
566             if (itemIndex >= 0) {
567                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
568                 // calculating the dollar amount for the accounting Line.
569                 PurApAccountingLine lineItem = item.getNewSourceLine();
570                 if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
571                     if (lineItem.getAccountLinePercent() != null && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
572                         BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
573                         lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
574                     } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero() && lineItem.getAccountLinePercent() == null) {
575                         KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
576                         BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
577                         lineItem.setAccountLinePercent(dollarToPercent);
578                     } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero() && lineItem.getAccountLinePercent() == null) {
579                         lineItem.setAccountLinePercent(new BigDecimal(0));
580                     }
581                     else if(lineItem.getAmount()!=null&& lineItem.getAccountLinePercent().intValue()== 100){
582                         KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
583                         BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()),0,RoundingMode.FLOOR);
584                         lineItem.setAccountLinePercent(dollarToPercent);
585                     }
586                     else if(lineItem.getAmount()!=null&&lineItem.getAccountLinePercent() != null){
587                         BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
588                         lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
589                     }
590                 } else {
591                     lineItem.setAmount(new KualiDecimal(0));
592                 }
593                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
594                 //end
595                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
596                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
597                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
598             } else if (itemIndex == -2) {
599                 //corrected: itemIndex == -2 is the only case for distribute account
600                 //This is the case when we're inserting an accounting line for distribute account.
601                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
602                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
603                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
604                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
605             }
606             if (rulePassed) {
607                 AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
608                 if (accountingLineBase != null) {
609                     String accountNumber = accountingLineBase.getAccountNumber();
610                     String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
611                     Map<String, String> criteria = new HashMap<String, String>();
612                     criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
613                     criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
614                     Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,criteria);
615                     rulePassed = checkForValidAccount(account);
616                 }
617             }
618             if (rulePassed) {
619                 // add accountingLine
620                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
621                 PurApAccountingLine newSourceLine = item.getNewSourceLine();
622                 List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();
623 
624                 BigDecimal initialValue = OleSelectConstant.ZERO_PERCENT;
625 
626                 for (PurApAccountingLine accountLine : existingSourceLine) {
627                     initialValue = initialValue.add(accountLine.getAccountLinePercent());
628 
629                 }
630                 if (itemIndex >= 0) {
631 
632                     if ((newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
633                         if (OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue() != OleSelectConstant.ZERO) {
634                             insertAccountingLine(purapForm, item, line);
635                         }
636                     } else {
637                         checkAccountingLinePercent(newSourceLine);
638 
639                     }
640                     for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
641                         if(oldSourceAccountingLine instanceof OleRequisitionAccount) {
642                             ((OleRequisitionAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
643                         }
644                     }
645                     List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
646                     BigDecimal totalPercent = new BigDecimal(100);
647                     BigDecimal initialPercent = new BigDecimal(0);
648                     for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
649                         initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
650 
651                     }
652                     initialPercent = totalPercent.subtract(initialPercent);
653                     BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
654                     if (maxPercent.intValue() == OleSelectConstant.ZERO) {
655                         item.resetAccount(OleSelectConstant.ZERO_PERCENT);
656 
657                     } else {
658                         item.resetAccount(initialPercent);
659 
660                     }
661                 } else if (itemIndex == -2) {
662                     //this is the case for distribute account
663                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
664                 }
665             }
666         }
667 
668         return mapping.findForward(OLEConstants.MAPPING_BASIC);
669     }
670 
671     private void checkAccountingLinePercent(PurApAccountingLine newSourceLine) {
672         if (newSourceLine.getAccountLinePercent().intValue() >= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED) {
673             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
674                     OleSelectPropertyConstants.ERROR_PERCENT_SHOULD_GREATER, OleSelectConstant.PERCENT);
675         } else if (newSourceLine.getAccountLinePercent().intValue() == OleSelectConstant.ZERO) {
676             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
677                     OleSelectPropertyConstants.ERROR_PERCENT_ZERO, OleSelectConstant.PERCENT);
678         } else {
679 
680         }
681 
682     }
683 
684     private boolean checkForValidAccount(Account account) {
685         boolean result = true;
686         if (account != null) {
687             String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
688                     OleSelectConstant.SUB_FUND_GRP_CD);
689             if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
690                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
691                         OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
692                         new String[]{OleSelectConstant.REQUISITION});
693                 result = false;
694             }
695         }
696         return result;
697     }
698 
699     private void setItemDescription(OleRequisitionItem item, String fileName) throws Exception{
700 
701         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
702             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
703             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
704             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
705             if (bib != null) {
706                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
707                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
708                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
709                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
710                 String description = title + author + publisher + isbn;
711                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId().toString()));
712                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
713             }
714             if (bib != null) {
715                 item.setBibUUID(bib.getId());
716                 item.setItemTitleId(bib.getId());
717                 item.setLinkToOrderOption(oleEditorResponse.getLinkToOrderOption());
718             }
719             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
720         }
721 
722     }
723 
724     public ActionForward addCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
725                                  HttpServletResponse response) throws Exception {
726         LOG.debug("Inside addCopy Method of OleRequisitionAction");
727         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
728         int line = this.getSelectedLine(request);
729         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm
730                 .getDocument()).getItem(line);
731         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
732         OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
733         boolean isValid = true;
734         List<String> volChar = new ArrayList<>();
735         String[] volNumbers = item.getVolumeNumber() != null ? item.getVolumeNumber().split(",") : new String[0];
736         for (String volStr : volNumbers) {
737             volChar.add(volStr);
738         }
739         Integer itemCount = volChar.size();
740         isValid = oleCopyHelperService.checkCopyEntry(
741                 item.getItemCopies(), item.getLocationCopies(), itemCount, item.getItemQuantity(), item.getItemNoOfParts(), item.getCopies(), item.getVolumeNumber(), false);
742         if (isValid) {
743             itemCopy.setItemCopies(item.getItemCopies());
744             itemCopy.setLocationCopies(item.getLocationCopies());
745             itemCopy.setParts(item.getItemNoOfParts());
746             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
747             itemCopy.setCaption(item.getCaption());
748             itemCopy.setVolumeNumber(item.getVolumeNumber());
749             item.setOleRequisitionCopy(itemCopy);
750             List<OleCopy> copyList = oleCopyHelperService.setCopyValues(item.getOleRequisitionCopy(), item.getItemTitleId(), volChar);
751             item.getCopyList().addAll(copyList);
752             item.getCopies().add(itemCopy);
753             item.setParts(null);
754             item.setItemCopies(null);
755             item.setPartEnumeration(null);
756             item.setLocationCopies(null);
757             item.setCaption(null);
758             item.setVolumeNumber(null);
759         }
760         return mapping.findForward(OLEConstants.MAPPING_BASIC);
761     }
762 
763     public boolean checkForCopiesAndLocation(OleRequisitionItem item) {
764         boolean isValid = true;
765         if (null == item.getItemCopies() || null == item.getLocationCopies()) {
766             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
767                     OLEConstants.ITEM_ITEMCOPIES_OR_LOCATIONCOPIES_SHOULDNOT_BE_NULL, new String[]{});
768             isValid = false;
769         }
770         return isValid;
771     }
772 
773     public boolean checkForItemCopiesGreaterThanQuantity(OleRequisitionItem item) {
774         boolean isValid = true;
775         if (item.getItemCopies().isGreaterThan(item.getItemQuantity())) {
776             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
777                     OLEConstants.ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
778             isValid = false;
779         }
780         return isValid;
781     }
782 
783     public boolean checkForTotalCopiesGreaterThanQuantity(OleRequisitionItem item) {
784         boolean isValid = true;
785         int copies = 0;
786         if (item.getCopies().size() > 0) {
787             for (int itemCopies = 0; itemCopies < item.getCopies().size(); itemCopies++) {
788                 copies = copies + item.getCopies().get(itemCopies).getItemCopies().intValue();
789             }
790             if (item.getItemQuantity().isLessThan(item.getItemCopies().add(new KualiDecimal(copies)))) {
791                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
792                         OLEConstants.TOTAL_OF_ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{});
793                 isValid = false;
794             }
795         }
796         return isValid;
797     }
798 
799 
800     /**
801      * This method takes RequisitionItem as parameter, it will calculate and set partEnumerations and startingCopyNumber for each
802      * lineItem
803      *
804      * @param item
805      * @return OleRequisitionCopies
806      */
807     public OleRequisitionCopies setCopyValues(OleRequisitionItem item) {
808         OleRequisitionCopies itemCopy = new OleRequisitionCopies();
809         itemCopy.setParts(item.getItemNoOfParts());
810         itemCopy.setItemCopies(item.getItemCopies());
811         StringBuffer enumeration = new StringBuffer();
812         if (item.getStartingCopyNumber() != null && item.getStartingCopyNumber().isNonZero()) {
813             itemCopy.setStartingCopyNumber(item.getStartingCopyNumber());
814         } else {
815             int startingCopies = 1;
816             for (int copy = 0; copy < item.getCopies().size(); copy++) {
817                 startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue();
818             }
819             itemCopy.setStartingCopyNumber(new KualiInteger(startingCopies));
820         }
821 
822         String partEnumerationCopy = getConfigurationService().getPropertyValueAsString(
823                 OLEConstants.PART_ENUMERATION_COPY);
824         String partEnumerationVolume = getConfigurationService().getPropertyValueAsString(
825                 OLEConstants.PART_ENUMERATION_VOLUME);
826         int startingCopyNumber = itemCopy.getStartingCopyNumber().intValue();
827         for (int noOfCopies = 0; noOfCopies < item.getItemCopies().intValue(); noOfCopies++) {
828             for (int noOfParts = 0; noOfParts < item.getItemNoOfParts().intValue(); noOfParts++) {
829                 int newNoOfCopies = startingCopyNumber + noOfCopies;
830                 int newNoOfParts = noOfParts + 1;
831                 if (noOfCopies + 1 == item.getItemCopies().intValue()
832                         && newNoOfParts == item.getItemNoOfParts().intValue()) {
833                     enumeration = enumeration.append(
834                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
835                             partEnumerationVolume + newNoOfParts);
836                 } else {
837                     enumeration = enumeration.append(
838                             partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append(
839                             partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION);
840                 }
841             }
842         }
843         itemCopy.setPartEnumeration(enumeration.toString());
844         itemCopy.setLocationCopies(item.getLocationCopies());
845         return itemCopy;
846     }
847 
848     /**
849      * Remove a Copy for the selected Item .
850      *
851      * @param mapping  An ActionMapping
852      * @param form     An ActionForm
853      * @param request  The HttpServletRequest
854      * @param response The HttpServletResponse
855      * @return An ActionForward
856      * @throws Exception
857      */
858     public ActionForward deleteCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
859                                     HttpServletResponse response) throws Exception {
860         LOG.debug("Inside deleteCopy Method of OleRequisitionAction");
861         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
862         String[] indexes = getSelectedLineForAccounts(request);
863         int itemIndex = Integer.parseInt(indexes[0]);
864         int copyIndex = Integer.parseInt(indexes[1]);
865         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm
866                 .getDocument()).getItem((itemIndex));
867         List<OleCopy> copyList = new ArrayList<>();
868         for(int i=0;i<item.getCopyList().size();i++){
869             OleCopy oleCopy = item.getCopyList().get(i);
870             if(item.getCopies().get(copyIndex).getLocationCopies().equalsIgnoreCase(oleCopy.getLocation())){
871                 copyList.add(oleCopy);
872             }
873         }
874         for(OleCopy copy : copyList){
875             item.getCopyList().remove(copy);
876             item.getDeletedCopiesList().add(copy);
877         }
878         item.getCopies().remove(copyIndex);
879         LOG.debug("Selected Copy is Remove");
880         LOG.debug("Leaving deleteCopy Method of OleRequisitionAction");
881         return mapping.findForward(OLEConstants.MAPPING_BASIC);
882     }
883 
884     /**
885      * Add a Payment History for selected Item.
886      *
887      * @param mapping  An ActionMapping
888      * @param form     An ActionForm
889      * @param request  The HttpServletRequest
890      * @param response The HttpServletResponse
891      * @return An ActionForward
892      * @throws Exception
893      */
894     public ActionForward addPaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
895                                            HttpServletResponse response) throws Exception {
896         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
897         int line = this.getSelectedLine(request);
898         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm
899                 .getDocument()).getItem(line);
900         OleRequisitionPaymentHistory paymentHistory = new OleRequisitionPaymentHistory();
901         paymentHistory.setPaymentHistory("");
902         item.getRequisitionPaymentHistory().add(paymentHistory);
903         return mapping.findForward(OLEConstants.MAPPING_BASIC);
904     }
905 
906     /**
907      * Remove a Payment History for selected Item
908      *
909      * @param mapping
910      * @param form
911      * @param request
912      * @param response
913      * @return
914      * @throws Exception
915      */
916     public ActionForward deletePaymentHistory(ActionMapping mapping, ActionForm form, HttpServletRequest request,
917                                               HttpServletResponse response) throws Exception {
918 
919         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
920         String[] indexes = getSelectedLineForAccounts(request);
921         int itemIndex = Integer.parseInt(indexes[0]);
922         int copyIndex = Integer.parseInt(indexes[1]);
923         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm
924                 .getDocument()).getItem((itemIndex));
925         item.getRequisitionPaymentHistory().remove(copyIndex);
926         return mapping.findForward(OLEConstants.MAPPING_BASIC);
927     }
928 
929     public static ConfigurationService getConfigurationService() {
930         if (kualiConfigurationService == null) {
931             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
932         }
933         return kualiConfigurationService;
934     }
935 
936     @Override
937     public ActionForward copy(ActionMapping mapping, ActionForm form, HttpServletRequest request,
938                               HttpServletResponse response) throws Exception {
939         ActionForward actionForward = super.copy(mapping, form, request, response);
940 
941         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
942         PurchasingAccountsPayableDocument purapDocument = (PurchasingAccountsPayableDocument) kualiDocumentFormBase
943                 .getDocument();
944         if(purapDocument.getIsReqsDoc()) {
945             OleRequisitionDocument oleRequisitionDocument = (OleRequisitionDocument)purapDocument;
946             if(oleRequisitionDocument.getRequisitionSource().getRequisitionSourceCode().equalsIgnoreCase(OleSelectConstant.REQUISITON_SRC_TYPE_AUTOINGEST)) {
947                 ((OleRequisitionDocument) purapDocument).setRequisitionSourceCode(null);
948             }
949         }
950 
951         // refresh accounts in each item....
952         List<PurApItem> items = purapDocument.getItems();
953 
954         for (PurApItem item : items) {
955             OleRequisitionItem oleRequisitionItem = (OleRequisitionItem) item;
956             oleRequisitionItem.setInvoiceDocuments(new ArrayList<OleInvoiceDocument>());
957             oleRequisitionItem.setNoOfCopiesReceived("");
958             oleRequisitionItem.setNoOfPartsReceived("");
959             oleRequisitionItem.setReceiptStatusId(null);
960             for (OleCopy oleCopy : ((OleRequisitionItem) item).getCopyList()) {
961                 oleCopy.setCopyId(null);
962                 oleCopy.setReqItemId(null);
963                 oleCopy.setPoDocNum(null);
964                 oleCopy.setPoItemId(null);
965                 oleCopy.setReceivingItemId(null);
966                 oleCopy.setCorrectionItemId(null);
967                 oleCopy.setSerialReceivingIdentifier(null);
968                 oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
969             }
970             for (OLELinkPurapDonor oleLinkPurapDonor : ((OleRequisitionItem) item).getOleDonors()) {
971                 oleLinkPurapDonor.setLinkPurapDonorId(null);
972                 oleLinkPurapDonor.setCorrectionItemId(null);
973                 oleLinkPurapDonor.setReceivingItemId(null);
974                 oleLinkPurapDonor.setReqItemId(null);
975                 oleLinkPurapDonor.setPoDocNum(null);
976                 oleLinkPurapDonor.setPoItemId(null);
977             }
978             if(oleRequisitionItem.getItemQuantity().equals(new KualiDecimal("1")) && oleRequisitionItem.getItemNoOfParts().equals(new KualiInteger("1"))){
979                 oleRequisitionItem.setCopyList(new ArrayList<OleCopy>());
980                 oleRequisitionItem.setCopies(new ArrayList<OleCopies>());
981             }
982         }
983 
984         return actionForward;
985     }
986 
987     @Override
988     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
989                                         HttpServletResponse response) throws Exception {
990         OleRequisitionDocument document = (OleRequisitionDocument) ((PurchasingFormBase) form).getDocument();
991         boolean budgetReviewRequired = isBudgetReviewRequired(document);
992         if(budgetReviewRequired){
993             route(mapping, form, request, response);
994             return mapping.findForward(OLEConstants.MAPPING_BASIC);
995         }
996         Iterator itemIterator = document.getItems().iterator();
997         PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
998         OleRequisitionDocument reqDoc = (OleRequisitionDocument) purchasingForm.getDocument();
999         List<OleRequisitionItem> items = reqDoc.getItems();
1000         boolean rulePassed = true;
1001         while (itemIterator.hasNext()) {
1002             OleRequisitionItem tempItem = (OleRequisitionItem) itemIterator.next();
1003             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
1004                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
1005                 if (accountingLineBase != null) {
1006                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
1007                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
1008                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
1009                         Map<String, String> criteria = new HashMap<String, String>();
1010                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
1011                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
1012                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1013                                 Account.class, criteria);
1014                         rulePassed = checkForValidAccount(account);
1015                         if (!rulePassed) {
1016                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1017                         }
1018                     }
1019                 }
1020             }
1021         }
1022         if (requiresCalculate(purchasingForm)) {
1023             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS,
1024                     PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
1025             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1026         }
1027         // call prorateDiscountTradeIn
1028         SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(document);
1029         this.calculate(mapping, purchasingForm, request, response);
1030         for (OleRequisitionItem item : items) {
1031             if (null != item.getItemType() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
1032                 if (item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(new KualiDecimal(1))
1033                         && !item.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
1034                     OleCopy oleCopy = new OleCopy();
1035                     oleCopy.setLocation(item.getItemLocation());
1036                     oleCopy.setBibId(item.getItemTitleId());
1037                     if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
1038                         oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : OLEConstants.ONE.toString());
1039                     }
1040                     oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1041                     List<OleCopy> copyList = new ArrayList<>();
1042                     copyList.add(oleCopy);
1043                     item.setCopyList(copyList);
1044                 }
1045             }
1046         }
1047         if (sufficientFundChecklag) {
1048             return super.blanketApprove(mapping, form, request, response);
1049         }
1050         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1051     }
1052 
1053     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1054         OleRequisitionForm rqForm = (OleRequisitionForm) form;
1055         OleRequisitionDocument document = (OleRequisitionDocument) rqForm.getDocument();
1056         if (document.getVendorAliasName() != null && document.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
1057             /* Getting matching vendor for the given vendor alias name */
1058             Map vendorAliasMap = new HashMap();
1059             vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, document.getVendorAliasName());
1060             org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
1061             List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
1062             if (vendorAliasList != null && vendorAliasList.size() > 0) {
1063                 Map vendorDetailMap = new HashMap();
1064                 vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1065                 vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1066                 VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
1067                 document.setVendorDetail(vendorDetail);
1068                 document.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
1069                 document.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
1070                 refreshVendor(mapping, form, request, response);
1071             } else {
1072                 GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
1073             }
1074         }
1075         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1076     }
1077 
1078 
1079     public ActionForward refreshVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1080         PurchasingAccountsPayableFormBase baseForm = (PurchasingAccountsPayableFormBase) form;
1081 
1082         PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
1083         if (StringUtils.equals(OLEConstants.REFRESH_VENDOR_CALLER, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && document.getVendorDetailAssignedIdentifier() != null && document.getVendorHeaderGeneratedIdentifier() != null) {
1084             document.setVendorContractGeneratedIdentifier(null);
1085             document.refreshReferenceObject(OLEConstants.VENDOR_CONTRACT);
1086 
1087             // retrieve vendor based on selection from vendor lookup
1088             document.refreshReferenceObject(OLEConstants.VENDOR_DETAILS);
1089             document.templateVendorDetail(document.getVendorDetail());
1090 
1091             // populate default address based on selected vendor
1092             VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), document.getDeliveryCampusCode());
1093             document.templateVendorAddress(defaultAddress);
1094         }
1095         return refresh(mapping, form, request, response);
1096     }
1097 
1098     private LookupService getLookupService() {
1099         return KRADServiceLocatorWeb.getLookupService();
1100     }
1101 
1102     public boolean isBudgetReviewRequired(OleRequisitionDocument document) {
1103         OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext
1104                 .getBean("oleRequisitionDocumentService");
1105         List<SourceAccountingLine> sourceAccountingLineList = document.getSourceAccountingLines();
1106         boolean sufficientFundCheck = false;
1107         for (SourceAccountingLine accLine : sourceAccountingLineList) {
1108             String notificationOption = null;
1109             Map<String, Object> key = new HashMap<String, Object>();
1110             String chartCode = accLine.getChartOfAccountsCode();
1111             String accNo = accLine.getAccountNumber();
1112             key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
1113             key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
1114             OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1115                     OleSufficientFundCheck.class, key);
1116             if (account != null) {
1117                 notificationOption = account.getNotificationOption();
1118             }
1119             if (notificationOption != null
1120                     && (notificationOption.equals(OLEPropertyConstants.BUD_REVIEW))) {
1121                 sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnBlanketApproveRequisition(accLine);
1122                 if (sufficientFundCheck) {
1123                     return sufficientFundCheck;
1124                 }
1125 
1126             }
1127         }
1128         return sufficientFundCheck;
1129     }
1130     public ActionForward addDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1131         boolean flag = true;
1132         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
1133         int line = this.getSelectedLine(request);
1134         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem(line);
1135         Map map = new HashMap();
1136         if (item.getDonorCode() != null) {
1137             map.put(OLEConstants.DONOR_CODE, item.getDonorCode());
1138             List<OLEDonor> oleDonorList = (List<OLEDonor>) getLookupService().findCollectionBySearch(OLEDonor.class, map);
1139             if (oleDonorList != null && oleDonorList.size() > 0) {
1140                 OLEDonor oleDonor = oleDonorList.get(0);
1141                 if (oleDonor != null) {
1142                     for (OLELinkPurapDonor oleLinkPurapDonor : item.getOleDonors()) {
1143                         if (oleLinkPurapDonor.getDonorCode().equalsIgnoreCase(item.getDonorCode())) {
1144                             flag = false;
1145                             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1146                                     OLEConstants.DONOR_CODE_EXISTS, new String[]{});
1147                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
1148                         }
1149                     }
1150                     if (flag) {
1151                         OLELinkPurapDonor donor = new OLELinkPurapDonor();
1152                         donor.setDonorId(oleDonor.getDonorId());
1153                         donor.setDonorCode(oleDonor.getDonorCode());
1154                         item.getOleDonors().add(donor);
1155                         item.setDonorCode(null);
1156                     }
1157                 }
1158             } else {
1159                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
1160                         OLEConstants.ERROR_DONOR_CODE, new String[]{});
1161             }
1162         }
1163         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1164     }
1165 
1166     public ActionForward deleteDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request,
1167                                      HttpServletResponse response) throws Exception {
1168         LOG.debug("Inside deleteDonor Method of OleRequisitionAction");
1169         OleRequisitionForm purchasingForm = (OleRequisitionForm) form;
1170         String[] indexes = getSelectedLineForAccounts(request);
1171         int itemIndex = Integer.parseInt(indexes[0]);
1172         int donorIndex = Integer.parseInt(indexes[1]);
1173         OleRequisitionItem item = (OleRequisitionItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
1174         item.getOleDonors().remove(donorIndex);
1175         LOG.debug("Selected Donor is Remove");
1176         LOG.debug("Leaving deleteDonor Method of OleRequisitionAction");
1177         return mapping.findForward(OLEConstants.MAPPING_BASIC);
1178     }
1179 
1180     /*@Override
1181     public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1182         PurchasingFormBase formBase = (PurchasingFormBase) form;
1183         OleRequisitionDocument reqDoc = (OleRequisitionDocument) formBase.getDocument();
1184         OleDocstoreHelperService oleDocstoreHelperService = SpringContext
1185                 .getBean(OleDocstoreHelperService.class);
1186         Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
1187         String reason = request.getParameter(OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME);
1188         String noteOne = "";
1189         String noteTwo = "";
1190         ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
1191         String[] reasons = null;
1192         // this should probably be moved into a private instance variable
1193         // logic for cancel question
1194         if (question == null) {
1195             // ask question if not already asked
1196             return this.performQuestionWithInput(mapping, form, request, response, KRADConstants.DOCUMENT_CANCEL_QUESTION, getKualiConfigurationService().getPropertyValueAsString(
1197                     OLEConstants.CANCEL_TEXT), KRADConstants.CONFIRMATION_QUESTION, KRADConstants.MAPPING_CANCEL, "");
1198         } else {
1199             Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
1200             if ((KRADConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
1201                 // if no button clicked just reload the doc
1202                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
1203             }
1204             else {
1205                 // Have to check length on value entered.
1206                 String introNoteMessage = OLEConstants.REQUISITION_CANCEL_NOTE_PREFIX + OLEConstants.BLANK_SPACE;
1207                 int noteTextLength = 0;
1208 
1209                 // Build out full message.
1210                 if (StringUtils.isNotBlank(reason)) {
1211                     reasons = reason.split("/");
1212                     noteOne = introNoteMessage + reasons[0];
1213                     if (!reasons[1].equalsIgnoreCase(null)) {
1214                         noteTwo = introNoteMessage + reasons[1];
1215                         noteTextLength = noteTwo.length();
1216                     }
1217 
1218                 }
1219 
1220                 // Get note text max length from DD.
1221                 int noteTextMaxLength = SpringContext.getBean(org.kuali.rice.krad.service.DataDictionaryService.class).getAttributeMaxLength(Note.class, OLEConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
1222                 String message = getKualiConfigurationService().getPropertyValueAsString(OLEConstants.CANCEL_TEXT);
1223 
1224                 if (reasons == null || reasons[0].trim().equalsIgnoreCase(OLEConstants.NULL)) {
1225                     reason = "";
1226                     return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, KRADConstants.DOCUMENT_CANCEL_QUESTION, message, OLEConstants.CONFIRMATION_QUESTION, KRADConstants.DOCUMENT_CANCEL_QUESTION, "", reason, OLEConstants.ERROR_CANCELLATION_REASON_REQUIRED, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, "");
1227                 } else if (!reasons[1].equalsIgnoreCase(null) && (noteTextLength > noteTextMaxLength)) {
1228                     reason = "";
1229                     return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, KRADConstants.DOCUMENT_CANCEL_QUESTION, message, OLEConstants.CONFIRMATION_QUESTION, KRADConstants.DOCUMENT_CANCEL_QUESTION, "", reason, OLEConstants.ERROR_REASON, OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(noteTextMaxLength - noteTextLength).toString());
1230                 }
1231                 // else go to cancel logic below
1232             }
1233         }
1234         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1235         doProcessingAfterPost(kualiDocumentFormBase, request);
1236         // KULRICE-4447 Call cancelDocument() only if the document exists
1237         if (getDocumentService().documentExists(kualiDocumentFormBase.getDocId())) {
1238             getDocumentService().cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
1239         }
1240 
1241         DocumentService documentService = SpringContext.getBean(DocumentService.class);
1242         Note apoNoteOne = documentService.createNoteFromDocument(kualiDocumentFormBase.getDocument(), noteOne);
1243         kualiDocumentFormBase.getDocument().addNote(apoNoteOne);
1244         if (!reasons[1].trim().equalsIgnoreCase(OLEConstants.NULL)) {
1245             Note apoNoteTwo = documentService.createNoteFromDocument(kualiDocumentFormBase.getDocument(), noteTwo);
1246             kualiDocumentFormBase.getDocument().addNote(apoNoteTwo);
1247         }
1248         documentService.saveDocumentNotes(kualiDocumentFormBase.getDocument());
1249         List<OleRequisitionItem> item = reqDoc.getItems();
1250 
1251         for (int i = 0; item.size() > i; i++) {
1252             OleRequisitionItem items = (OleRequisitionItem) reqDoc.getItem(i);
1253             if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
1254                 oleDocstoreHelperService.updateItemNote(items,reasons[0]);
1255             }
1256         }
1257         return returnToSender(request, mapping, kualiDocumentFormBase);
1258     }
1259 
1260     @Override
1261     protected ActionForward performQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String questionText, String questionType, String caller, String context) throws Exception {
1262         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, "", "", "", "");
1263     }
1264 
1265     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 {
1266         Properties parameters = new Properties();
1267 
1268         parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, "start");
1269         parameters.put(KRADConstants.DOC_FORM_KEY, GlobalVariables.getUserSession().addObjectWithGeneratedKey(form));
1270         parameters.put(KRADConstants.CALLING_METHOD, caller);
1271         parameters.put(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME, questionId);
1272         parameters.put(KRADConstants.QUESTION_IMPL_ATTRIBUTE_NAME, questionType);
1273         //parameters.put(KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME, questionText);
1274         parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, getReturnLocation(request, mapping));
1275         parameters.put(KRADConstants.QUESTION_CONTEXT, context);
1276         parameters.put(KRADConstants.QUESTION_SHOW_REASON_FIELD, Boolean.toString(showReasonField));
1277         parameters.put(KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, reason);
1278         parameters.put(KRADConstants.QUESTION_ERROR_KEY, errorKey);
1279         parameters.put(KRADConstants.QUESTION_ERROR_PROPERTY_NAME, errorPropertyName);
1280         parameters.put(KRADConstants.QUESTION_ERROR_PARAMETER, errorParameter);
1281         parameters.put(KRADConstants.QUESTION_ANCHOR, form instanceof KualiForm ? org.apache.commons.lang.ObjectUtils.toString(((KualiForm) form).getAnchor()) : "");
1282         Object methodToCallAttribute = request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
1283         if (methodToCallAttribute != null) {
1284             parameters.put(KRADConstants.METHOD_TO_CALL_PATH, methodToCallAttribute);
1285             ((PojoForm) form).registerEditableProperty(String.valueOf(methodToCallAttribute));
1286         }
1287 
1288         if (form instanceof KualiDocumentFormBase) {
1289             String docNum = ((KualiDocumentFormBase) form).getDocument().getDocumentNumber();
1290             if(docNum != null){
1291                 parameters.put(KRADConstants.DOC_NUM, ((KualiDocumentFormBase) form)
1292                         .getDocument().getDocumentNumber());
1293             }
1294         }
1295 
1296         // KULRICE-8077: PO Quote Limitation of Only 9 Vendors
1297         String questionTextAttributeName = KRADConstants.QUESTION_TEXT_ATTRIBUTE_NAME + questionId;
1298         GlobalVariables.getUserSession().addObject(questionTextAttributeName, (Object)questionText);
1299         String questionUrl;
1300         if (questionId.equalsIgnoreCase(KRADConstants.DOCUMENT_CANCEL_QUESTION)) {
1301             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + OLEConstants.QUESTION_ACTION, parameters);
1302         } else {
1303             questionUrl = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + "/kr/" + KRADConstants.QUESTION_ACTION, parameters);
1304         }
1305 
1306         return new ActionForward(questionUrl, true);
1307     }
1308 
1309     @Override
1310     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 {
1311         return performQuestion(mapping, form, request, response, questionId, questionText, questionType, caller, context, true, reason, errorKey, errorPropertyName, errorParameter);
1312     }*/
1313 
1314 }