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