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