View Javadoc
1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.document.web.struts;
17  
18  
19  import org.apache.commons.lang.StringEscapeUtils;
20  import org.apache.commons.lang.StringUtils;
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.document.Bib;
27  import org.kuali.ole.module.purap.PurapConstants;
28  import org.kuali.ole.module.purap.PurapConstants.PaymentRequestStatuses;
29  import org.kuali.ole.module.purap.PurapPropertyConstants;
30  import org.kuali.ole.module.purap.businessobject.PaymentRequestAccount;
31  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
32  import org.kuali.ole.module.purap.businessobject.PurApItem;
33  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
34  import org.kuali.ole.module.purap.document.service.OlePurapService;
35  import org.kuali.ole.module.purap.document.service.PaymentRequestService;
36  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
37  import org.kuali.ole.module.purap.document.validation.event.AttributedContinuePurapEvent;
38  import org.kuali.ole.module.purap.document.web.struts.PaymentRequestAction;
39  import org.kuali.ole.module.purap.document.web.struts.PurchasingAccountsPayableFormBase;
40  import org.kuali.ole.module.purap.document.web.struts.PurchasingFormBase;
41  import org.kuali.ole.pojo.OleBibRecord;
42  import org.kuali.ole.pojo.OleEditorResponse;
43  import org.kuali.ole.select.OleSelectConstant;
44  import org.kuali.ole.select.bo.OLEDonor;
45  import org.kuali.ole.select.bo.OLEEditorResponse;
46  import org.kuali.ole.select.businessobject.*;
47  import org.kuali.ole.select.constants.OleSelectPropertyConstants;
48  import org.kuali.ole.select.document.OleInvoiceDocument;
49  import org.kuali.ole.select.document.OlePaymentRequestDocument;
50  import org.kuali.ole.select.document.service.OlePaymentRequestService;
51  import org.kuali.ole.select.document.validation.event.OleDiscountPaymentRequestEvent;
52  import org.kuali.ole.select.document.validation.event.OleForeignCurrencyPaymentRequestEvent;
53  import org.kuali.ole.select.document.validation.event.OlePaymentRequestDescEvent;
54  import org.kuali.ole.select.service.BibInfoWrapperService;
55  import org.kuali.ole.select.service.FileProcessingService;
56  import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
57  import org.kuali.ole.sys.OLEConstants;
58  import org.kuali.ole.sys.OLEPropertyConstants;
59  import org.kuali.ole.sys.businessobject.AccountingLineBase;
60  import org.kuali.ole.sys.context.SpringContext;
61  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
62  import org.kuali.ole.vnd.businessobject.OleExchangeRate;
63  import org.kuali.ole.vnd.businessobject.VendorAddress;
64  import org.kuali.ole.vnd.businessobject.VendorAlias;
65  import org.kuali.ole.vnd.businessobject.VendorDetail;
66  import org.kuali.rice.core.api.util.type.KualiDecimal;
67  import org.kuali.rice.krad.service.*;
68  import org.kuali.rice.krad.util.GlobalVariables;
69  import org.kuali.rice.krad.util.ObjectUtils;
70  
71  import javax.servlet.http.HttpServletRequest;
72  import javax.servlet.http.HttpServletResponse;
73  import java.math.BigDecimal;
74  import java.math.RoundingMode;
75  import java.util.*;
76  
77  
78  /**
79   * This class is the KualiForm class for Ole Payment Request Action
80   */
81  public class OlePaymentRequestAction extends PaymentRequestAction {
82  
83      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePaymentRequestAction.class);
84  
85      private boolean currencyTypeIndicator = true;
86  
87      /**
88       * @see org.kuali.ole.module.purap.document.web.struts.AccountsPayableActionBase#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
89       */
90      @Override
91      public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
92          /*ActionForward forward = super.calculate(mapping, form, request, response);*/
93          /* calculateCurrency(mapping, form, request, response); */
94          PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
95          List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems();
96          for(PurApItem purApItem:purApItems){
97              List<KualiDecimal> existingAmount=new ArrayList<>();
98              for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
99                  if(oldSourceAccountingLine instanceof PaymentRequestAccount) {
100                     if(((PaymentRequestAccount)oldSourceAccountingLine).getExistingAmount()!=null){
101                         existingAmount.add(((PaymentRequestAccount)oldSourceAccountingLine).getExistingAmount());
102                     }
103                 }
104             }
105             int count=0;
106             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
107 
108                 if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) {
109                     if (account.getAmount()!=null&&count<existingAmount.size()&&existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) {
110                         KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString());
111                         account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE,BigDecimal.ROUND_CEILING));
112                     }
113 
114                     else {
115                         if(account.getAccountLinePercent().intValue()==100&&(account.getAmount()==null||account.getAccount()!=null)){
116                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
117                             account.setAmount(calculatedAmount);
118                         }
119                         else{
120                             KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
121                             account.setAmount(calculatedAmount);
122                         }
123                     }
124                 }
125                 count++;
126             }
127             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
128                 if(oldSourceAccountingLine instanceof PaymentRequestAccount) {
129                     ((PaymentRequestAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
130                 }
131             }
132         }
133         OlePaymentRequestForm paymentForm = (OlePaymentRequestForm) form;
134         OlePaymentRequestDocument payDoc = (OlePaymentRequestDocument) paymentForm.getDocument();
135         Map invMap = new HashMap();
136         if (payDoc.getInvoiceIdentifier() != null) {
137             invMap.put(PurapConstants.PRQSDocumentsStrings.INV_ID, payDoc.getInvoiceIdentifier());
138             payDoc.getInvoiceIdentifier();
139             OleInvoiceDocument oleInvoice = SpringContext
140                     .getBean(org.kuali.rice.krad.service.BusinessObjectService.class).findByPrimaryKey(OleInvoiceDocument.class, invMap);
141             payDoc.setProrateBy(oleInvoice.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : oleInvoice.isProrateManual() ? OLEConstants.MANUAL_PRORATE :
142                     oleInvoice.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : oleInvoice.isNoProrate() ? OLEConstants.NO_PRORATE :
143                             OLEConstants.DEFAULT_PRORATE_BY_INVOICE);
144 
145             List<OleInvoiceItem> item = oleInvoice.getItems();
146             for (int i = 0; item.size() > i; i++) {
147                 OleInvoiceItem items = (OleInvoiceItem) oleInvoice.getItem(i);
148                 if (items.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_FREIGHT_CODE) && LOG.isDebugEnabled()) {
149                     LOG.debug("Item Type Code >>>>>>>>>>>" + items.getItemTypeCode());
150                     LOG.debug("items.getItemUnitPrice() >>>>>>>>>" + items.getItemUnitPrice());
151                     LOG.debug("items.getTotalAmount() >>>>>>>>" + items.getTotalAmount());
152 
153                 }
154             }
155 
156         } else {
157             payDoc.setProrateBy(payDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : payDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE :
158                     payDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : payDoc.isNoProrate() ? OLEConstants.NO_PRORATE : null);
159         }
160         boolean manualProrateValidFlag = true;
161         if ((payDoc.getProrateBy() != null) && (payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
162             if (payDoc.getProrateBy() != null && payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
163                 // Validates the prorate surchanges if prorate by manual
164                 manualProrateValidFlag = getOlePaymentRequestService().validateProratedSurcharge(payDoc);
165             }
166             if (manualProrateValidFlag) {
167 
168                 List<OlePaymentRequestItem> item = payDoc.getItems();
169                 if (payDoc.getVendorDetail().getCurrencyType()!=null){
170                     if(payDoc.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
171                         currencyTypeIndicator=true;
172                     }
173                     else{
174                         currencyTypeIndicator=false;
175                     }
176                 }
177                 if (payDoc.getVendorDetail() == null || (payDoc.getVendorDetail() != null && currencyTypeIndicator)) {
178                     for (int i = 0; item.size() > i; i++) {
179                         OlePaymentRequestItem items = (OlePaymentRequestItem) payDoc.getItem(i);
180                         if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
181                             boolean rulePassed = getKualiRuleService().applyRules(
182                                     new OleDiscountPaymentRequestEvent(payDoc, items));
183                             if (rulePassed) {
184                                 items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(items).setScale(2, BigDecimal.ROUND_HALF_UP));
185                             }
186                         }
187                     }
188                 } else {
189 
190                     LOG.debug("###########Foreign Currency Field Calculation###########");
191                     for (int i = 0; item.size() > i; i++) {
192                         OlePaymentRequestItem items = (OlePaymentRequestItem) payDoc.getItem(i);
193                         Long id = payDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
194                         Map documentNumberMap = new HashMap();
195                         documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
196                         org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext
197                                 .getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
198                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(
199                                 OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
200                         Iterator iterator = exchangeRateList.iterator();
201                         if (iterator.hasNext()) {
202                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
203                             items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
204                             payDoc.setForeignVendorInvoiceAmount(payDoc.getVendorInvoiceAmount().bigDecimalValue()
205                                     .multiply(tempOleExchangeRate.getExchangeRate()));
206                         }
207                         if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
208                             boolean rulePassed = getKualiRuleService().applyRules(
209                                     new OleForeignCurrencyPaymentRequestEvent(payDoc, items));
210                             if (rulePassed) {
211                                 SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
212                                 if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
213                                     items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
214                                     items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
215                                     items.setItemListPrice(items.getItemUnitCostUSD());
216                                     //items.setPurchaseOrderItemUnitPrice(items.getItemUnitPrice());
217                                 }
218                             }
219 
220                         } else {
221                             if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) {
222                                 // added for jira - OLE-2203
223                                 if (items.isAdditionalChargeUsd()) {
224                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
225                                 } else {
226                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP));
227                                 }
228                             }
229                         }
230                     }
231                 }
232                 getOlePaymentRequestService().calculateProrateItemSurcharge(payDoc);
233             }
234         }
235 
236         if (payDoc.getProrateBy() == null && manualProrateValidFlag) {
237             getOlePaymentRequestService().calculateWithoutProrates(payDoc);
238         }
239         List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItems();
240         for(PurApItem purApItem:newpurApItems){
241             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
242                 KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()).divide(new BigDecimal(100)).toString());
243                 account.setAmount(calculatedAmount);
244             }
245         }
246         return super.calculate(mapping, form, request, response);
247     }
248 
249     /**
250      * Add a new Note to the selected PaymentRequestItem.
251      *
252      * @param mapping  An ActionMapping
253      * @param form     An ActionForm
254      * @param request  The HttpServletRequest
255      * @param response The HttpServletResponse
256      * @return An ActionForward
257      * @throws Exception
258      */
259 
260     public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
261         LOG.debug("Inside addNote Method of OlePaymentRequestAction");
262         OlePaymentRequestForm paymentForm = (OlePaymentRequestForm) form;
263         OlePaymentRequestDocument paymentDocument = (OlePaymentRequestDocument) paymentForm.getDocument();
264         int line = this.getSelectedLine(request);
265         OlePaymentRequestItem item = (OlePaymentRequestItem) ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItem(line);
266         OlePaymentRequestNote note = new OlePaymentRequestNote();
267         note.setNote(item.getNote());
268 //        boolean rulePassed = getKualiRuleService().applyRules(new OleNoteTypeEvent(purDocument,note));
269 //        if(rulePassed){
270         item.getNotes().add(note);
271         LOG.debug("Adding InvoiceNote to the PaymentRequestItem");
272         item.setNote(null);
273         LOG.debug("Leaving addNote Method of OlePaymentRequestAction");
274 //        }
275         return mapping.findForward(OLEConstants.MAPPING_BASIC);
276     }
277 
278     /**
279      * deletes the selected InvoiceNote for the selected PaymentRequestItem
280      *
281      * @param mapping
282      * @param form
283      * @param request
284      * @param response
285      * @return An ActionForward
286      * @throws Exception
287      */
288     public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
289         LOG.debug("Inside deleteNote Method of OlePaymentRequestAction");
290         OlePaymentRequestForm paymentForm = (OlePaymentRequestForm) form;
291 
292         String[] indexes = getSelectedLineForAccounts(request);
293         int itemIndex = Integer.parseInt(indexes[0]);
294         int noteIndex = Integer.parseInt(indexes[1]);
295         OlePaymentRequestItem item = (OlePaymentRequestItem) ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItem((itemIndex));
296         item.getNotes().remove(noteIndex);
297         LOG.debug("Note deleted for the selected Item");
298         LOG.debug("Leaving deleteNote Method of OlePaymentRequestAction");
299         return mapping.findForward(OLEConstants.MAPPING_BASIC);
300     }
301 
302     /**
303      * Add a new item to the document.
304      *
305      * @param mapping  An ActionMapping
306      * @param form     An ActionForm
307      * @param request  The HttpServletRequest
308      * @param response The HttpServletResponse
309      * @return An ActionForward
310      * @throws Exception
311      */
312     public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
313         OlePaymentRequestForm purchasingForm = (OlePaymentRequestForm) form;
314         OlePaymentRequestItem item = (OlePaymentRequestItem) purchasingForm.getNewPurchasingItemLine();
315         item.getNewSourceLine().setAccountLinePercent(new BigDecimal(100));
316         // purchasingForm.getNewPurchasingItemLine().setItemDescription((item.getBibInfoBean().getTitle() != null ?
317         // item.getBibInfoBean().getTitle() : "") + (item.getBibInfoBean().getAuthor() != null ? "," +
318         // item.getBibInfoBean().getAuthor() : "") + (item.getBibInfoBean().getPublisher() != null ? "," +
319         // item.getBibInfoBean().getPublisher() : "") + (item.getBibInfoBean().getIsbn() != null ? "," +
320         // item.getBibInfoBean().getIsbn() : ""));
321         OlePaymentRequestDocument document = (OlePaymentRequestDocument) purchasingForm.getDocument();
322         BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
323         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
324         String titleId = null;
325         boolean isBibFileExist = false;
326         Iterator itemIterator = document.getItems().iterator();
327         int itemCounter = 0;
328         while (itemIterator.hasNext()) {
329             OlePaymentRequestItem tempItem = (OlePaymentRequestItem) itemIterator.next();
330             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
331                 itemCounter++;
332             }
333         }
334         String itemNo = String.valueOf(itemCounter);
335         //String itemNo = String.valueOf(document.getItems().size() - 8);
336         HashMap<String, String> dataMap = new HashMap<String, String>();
337         item.setBibInfoBean(new BibInfoBean());
338         if (item.getBibInfoBean().getDocStoreOperation() == null) {
339             item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
340         }
341         String tokenId = document.getDocumentNumber() + "_" + itemNo;
342 
343         setItemDescription(item, tokenId);
344 
345         /*dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation());
346         dataMap.put(OleSelectConstant.FILENAME, fileName);
347         if (fileProcessingService.isCreateFileExist(dataMap)) {
348             isBibFileExist = true;
349         }
350         if (isBibFileExist) {
351             titleId = docStore.getTitleIdByMarcXMLFileProcessing(item.getBibInfoBean(), dataMap);
352             item.setItemTitleId(titleId);
353             BibInfoBean xmlBibInfoBean = new BibInfoBean();
354             dataMap.put(OleSelectConstant.TITLE_ID, titleId);
355             dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
356             xmlBibInfoBean = docStore.getBibInfo(dataMap);
357             item.setBibInfoBean(xmlBibInfoBean);
358             purchasingForm.getNewPurchasingItemLine().setItemDescription((item.getBibInfoBean().getTitle() != null ? item.getBibInfoBean().getTitle() : "") + (item.getBibInfoBean().getAuthor() != null ? "," + item.getBibInfoBean().getAuthor() : "") + (item.getBibInfoBean().getPublisher() != null ? "," + item.getBibInfoBean().getPublisher() : "") + (item.getBibInfoBean().getIsbn() != null ? "," + item.getBibInfoBean().getIsbn() : ""));
359 
360             HashMap<String,String> queryMap = new HashMap<String,String>();
361             queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, item.getItemTitleId());
362             List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
363             Iterator bibIdIterator = docStoreResult.iterator();
364             if(bibIdIterator.hasNext()){
365                 DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next();
366                 item.setBibUUID(docInfoBean.getUniqueId());
367             }
368         }*/
369         boolean ruleFlag = getKualiRuleService().applyRules(new OlePaymentRequestDescEvent(document, item));
370         if (ruleFlag) {
371             if (document.getVendorDetail().getCurrencyType()!=null){
372                 if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
373                     currencyTypeIndicator=true;
374                 }
375                 else{
376                     currencyTypeIndicator=false;
377                 }
378             }
379             if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && currencyTypeIndicator)) {
380                 boolean rulePassed = getKualiRuleService().applyRules(new OleDiscountPaymentRequestEvent(document, item));
381                 if (rulePassed) {
382                     purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item).setScale(2, BigDecimal.ROUND_HALF_UP));
383                     item = (OlePaymentRequestItem) purchasingForm.getAndResetNewPurchasingItemLine();
384                     document.addItem(item);
385                 }
386             } else {
387                 boolean rulePassed = getKualiRuleService().applyRules(new OleForeignCurrencyPaymentRequestEvent(document, item));
388                 if (rulePassed) {
389                     LOG.debug("###########Foreign Currency Field Calculation for Payment Request ###########");
390                     SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(item);
391                     Long id = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
392                     Map documentNumberMap = new HashMap();
393                     documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
394                     org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
395                     List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
396                     Iterator iterator = exchangeRateList.iterator();
397                     if (iterator.hasNext()) {
398                         OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
399                         item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
400                     }
401                     if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
402                         item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
403                         item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
404                         item.setItemListPrice(item.getItemUnitCostUSD());
405                     }
406                     item = (OlePaymentRequestItem) purchasingForm.getAndResetNewPurchasingItemLine();
407                     document.addItem(item);
408                 }
409             }
410         }
411         /*if(item.getDonorCode() == null){
412             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectPropertyConstants.ERROR_DONOR_CODE,"donorCode");
413         }*/
414         return mapping.findForward(OLEConstants.MAPPING_BASIC);
415     }
416 
417     /**
418      * Delete an item from the document.
419      *
420      * @param mapping  An ActionMapping
421      * @param form     An ActionForm
422      * @param request  The HttpServletRequest
423      * @param response The HttpServletResponse
424      * @return An ActionForward
425      * @throws Exception
426      */
427     public ActionForward deleteItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
428         OlePaymentRequestForm purchasingForm = (OlePaymentRequestForm) form;
429         OlePaymentRequestDocument purDocument = (OlePaymentRequestDocument) purchasingForm.getDocument();
430         purDocument.deleteItem(getSelectedLine(request));
431         return mapping.findForward(OLEConstants.MAPPING_BASIC);
432     }
433 
434     @Override
435     public ActionForward continuePREQ(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
436         OlePaymentRequestForm rqForm = (OlePaymentRequestForm) form;
437         OlePaymentRequestDocument document = (OlePaymentRequestDocument) rqForm.getDocument();
438         boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedContinuePurapEvent(document));
439         if (!rulePassed) {
440             return super.continuePREQ(mapping, form, request, response);
441         }
442         ActionForward forward = super.continuePREQ(mapping, form, request, response);
443         SpringContext.getBean(OlePurapService.class).getInitialCollapseSections(document);
444         List<OlePaymentRequestItem> items = document.getItems();
445         OlePaymentRequestItem newLineItem = (OlePaymentRequestItem) rqForm.getNewPurchasingItemLine();
446         if (document.getVendorDetail().getCurrencyType()!=null){
447             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
448                 currencyTypeIndicator=true;
449             }
450             else{
451                 currencyTypeIndicator=false;
452             }
453         }
454         if (document.getVendorDetail() != null && (!currencyTypeIndicator)) {
455             Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
456             Map documentNumberMap = new HashMap();
457             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
458             org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
459             List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
460             Iterator iterator = exchangeRateList.iterator();
461             for (OlePaymentRequestItem item : items) {
462                 iterator = exchangeRateList.iterator();
463                 if (iterator.hasNext()) {
464                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
465                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
466                 }
467             }
468             iterator = exchangeRateList.iterator();
469             if (iterator.hasNext()) {
470                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
471                 newLineItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
472             }
473         }
474         rqForm.getAndResetNewPurchasingItemLine();
475 
476         return forward;
477     }
478 
479     @Override
480     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
481         this.calculate(mapping, form, request, response);
482         ActionForward forward = super.route(mapping, form, request, response);
483         OlePaymentRequestDocument document = (OlePaymentRequestDocument) ((OlePaymentRequestForm) form).getDocument();
484         Iterator itemIterator = document.getItems().iterator();
485         int itemCounter = 0;
486         boolean rulePassed = true;
487         while (itemIterator.hasNext()) {
488             OlePaymentRequestItem tempItem = (OlePaymentRequestItem) itemIterator.next();
489             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)
490                     || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
491                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
492                 if (accountingLineBase != null) {
493                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
494                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
495                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
496                         Map<String, String> criteria = new HashMap<String, String>();
497                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
498                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
499                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
500                                 Account.class, criteria);
501                         rulePassed = checkForValidAccount(account);
502                         if (!rulePassed) {
503                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
504                         }
505                     }
506                 }
507             }
508         }
509        /* if (rulePassed) {
510             this.calculate(mapping, form, request, response);
511         }*/
512         return forward;
513     }
514 
515     /**
516      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
517      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
518      */
519     @Override
520     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
521         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
522         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
523 
524         // index of item selected
525         int itemIndex = getSelectedLine(request);
526         PurApItem item = null;
527 
528         // if custom processing of an accounting line is not done then insert a line generically.
529         if (processCustomInsertAccountingLine(purapForm, request) == false) {
530             String errorPrefix = null;
531             PurApAccountingLine line = null;
532 
533             boolean rulePassed = false;
534             if (itemIndex >= 0) {
535                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
536                 //Calculating the dollar amount for the accounting Line.
537                 PurApAccountingLine lineItem = item.getNewSourceLine();
538                 if (lineItem.getAccountLinePercent() != null) {
539                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
540                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
541                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
542                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
543                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
544                     lineItem.setAccountLinePercent(dollarToPercent);
545                 }
546                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
547                 //end
548                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
549                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
550                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
551             } else if (itemIndex == -2) {
552                 //corrected: itemIndex == -2 is the only case for distribute account
553                 //This is the case when we're inserting an accounting line for distribute account.
554                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
555                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
556                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
557                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
558             }
559             AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
560             if (accountingLineBase != null) {
561                 String accountNumber = accountingLineBase.getAccountNumber();
562                 String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
563                 Map<String, String> criteria = new HashMap<String, String>();
564                 criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
565                 criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
566                 Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
567                         criteria);
568                 rulePassed = checkForValidAccount(account);
569             }
570 
571           /*  if (rulePassed) {
572                 // add accountingLine
573                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
574                 if (itemIndex >=0) {
575                     insertAccountingLine(purapForm, item, line);
576                     // clear the temp account
577                     item.resetAccount();
578                 }
579                 else if (itemIndex == -2) {
580                     //this is the case for distribute account
581                     ((PurchasingFormBase)purapForm).addAccountDistributionsourceAccountingLine(line);
582                 }
583             }*/
584             if (rulePassed) {
585                 // add accountingLine
586                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
587 
588                 PurApAccountingLine newSourceLine = item.getNewSourceLine();
589                 List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();
590 
591                 BigDecimal initialValue = new BigDecimal(0);
592 
593                 for (PurApAccountingLine accountLine : existingSourceLine) {
594                     initialValue = initialValue.add(accountLine.getAccountLinePercent());
595                 }
596                 if (itemIndex >= 0) {
597 
598                     if ((newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
599                         if (OleSelectConstant.MAX_PERCENT.subtract(initialValue).intValue() != OleSelectConstant.ZERO) {
600                             insertAccountingLine(purapForm, item, line);
601                         }
602                     }else {
603                         checkAccountingLinePercent(newSourceLine);
604 
605                     }
606                     for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
607                         if(oldSourceAccountingLine instanceof PaymentRequestAccount) {
608                             ((PaymentRequestAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
609                         }
610                     }
611                     List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
612                     BigDecimal totalPercent = new BigDecimal(100);
613                     BigDecimal initialPercent = new BigDecimal(0);
614                     for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
615                         initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());
616 
617                     }
618                     initialPercent = totalPercent.subtract(initialPercent);
619                     BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
620                     if (maxPercent.intValue() == OleSelectConstant.ZERO) {
621                         item.resetAccount(OleSelectConstant.ZERO_PERCENT);
622 
623                     } else {
624                         item.resetAccount(initialPercent);
625 
626                     }
627                 } else if (itemIndex == -2) {
628                     //this is the case for distribute account
629                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
630                 }
631             }
632         }
633 
634 
635         return mapping.findForward(OLEConstants.MAPPING_BASIC);
636     }
637 
638     private void checkAccountingLinePercent(PurApAccountingLine newSourceLine) {
639         if (newSourceLine.getAccountLinePercent().intValue() >= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED) {
640             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
641                     OleSelectPropertyConstants.ERROR_PERCENT_SHOULD_GREATER, OleSelectConstant.PERCENT);
642         } else if (newSourceLine.getAccountLinePercent().intValue() == OleSelectConstant.ZERO) {
643             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
644                     OleSelectPropertyConstants.ERROR_PERCENT_ZERO, OleSelectConstant.PERCENT);
645         } else {
646 
647         }
648 
649     }
650 
651     private boolean checkForValidAccount(Account account) {
652         boolean result = true;
653         if (account != null) {
654             String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
655                     OleSelectConstant.SUB_FUND_GRP_CD);
656             if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
657                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
658                         OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
659                         new String[]{OleSelectConstant.PAYMENT_REQUEST});
660                 result = false;
661             }
662         }
663         return result;
664     }
665 
666     private void setItemDescription(OlePaymentRequestItem item, String tokenId) {
667         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
668             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
669             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(tokenId);
670             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
671             bib = (Bib) bib.deserializeContent(bib);
672             if (bib != null) {
673                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
674                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
675                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
676                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
677                 String description = title + author + publisher + isbn;
678                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId()));
679                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
680             }
681             if (bib != null) {
682                 item.setBibUUID(bib.getId());
683                 item.setItemTitleId(bib.getId());
684             }
685             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
686         }
687     }
688 
689     private OlePaymentRequestService getOlePaymentRequestService() {
690         return SpringContext.getBean(OlePaymentRequestService.class);
691     }
692 
693     @Override
694     protected void customCalculate(PurchasingAccountsPayableDocument apDoc) {
695         OlePaymentRequestDocument preqDoc = (OlePaymentRequestDocument) apDoc;
696         if ((preqDoc.getProrateBy() != null) && (preqDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || preqDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || preqDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
697             // set amounts on any empty
698             preqDoc.updateExtendedPriceOnItems();
699 
700             // calculation just for the tax area, only at tax review stage
701             // by now, the general calculation shall have been done.
702             if (preqDoc.getApplicationDocumentStatus().equals(PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
703                 SpringContext.getBean(PaymentRequestService.class).calculateTaxArea(preqDoc);
704                 return;
705             }
706 
707             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
708             // Calculate Payment request before rules since the rule check totalAmount.
709             SpringContext.getBean(OlePaymentRequestService.class).calculatePaymentRequest(preqDoc, true);
710             SpringContext.getBean(KualiRuleService.class).applyRules(
711                     new AttributedCalculateAccountsPayableEvent(preqDoc));
712         } else {
713             super.customCalculate(preqDoc);
714         }
715     }
716 
717     @Override
718     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
719                                         HttpServletResponse response) throws Exception {
720         this.calculate(mapping, form, request, response);
721         ActionForward forward = super.blanketApprove(mapping, form, request, response);
722         OlePaymentRequestDocument document = (OlePaymentRequestDocument) ((OlePaymentRequestForm) form).getDocument();
723         Iterator itemIterator = document.getItems().iterator();
724         int itemCounter = 0;
725         boolean rulePassed = true;
726         while (itemIterator.hasNext()) {
727             OlePaymentRequestItem tempItem = (OlePaymentRequestItem) itemIterator.next();
728             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)
729                     || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
730                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
731                 if (accountingLineBase != null) {
732                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
733                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
734                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
735                         Map<String, String> criteria = new HashMap<String, String>();
736                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
737                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
738                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
739                                 Account.class, criteria);
740                         rulePassed = checkForValidAccount(account);
741                         if (!rulePassed) {
742                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
743                         }
744                     }
745                 }
746             }
747         }
748         return forward;
749     }
750 
751     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
752         //ActionForward forward = super.clearVendor(mapping, form, request, response);
753         OlePaymentRequestForm preqForm = (OlePaymentRequestForm) form;
754         OlePaymentRequestDocument document = (OlePaymentRequestDocument) preqForm.getDocument();
755         if (document.getVendorAliasName() != null && document.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
756             /* Getting matching vendor for the given vendor alias name */
757             Map vendorAliasMap = new HashMap();
758             vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, document.getVendorAliasName());
759             org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
760             List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
761             if (vendorAliasList != null && vendorAliasList.size() > 0 && vendorAliasList.get(0) != null) {  /* if there matching vendor found for the given vendor alias name */
762                 Map vendorDetailMap = new HashMap();
763                 vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
764                 vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
765                 VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
766                 document.setVendorDetail(vendorDetail);
767                 document.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
768                 document.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
769                 document.setVendorName(vendorDetail.getVendorName());
770                 VendorAddress vendorAddress = businessObject.findByPrimaryKey(VendorAddress.class, vendorDetailMap);
771                 if (vendorAddress != null) {
772                     document.setVendorLine1Address(vendorAddress.getVendorLine1Address());
773                     document.setVendorLine2Address(vendorAddress.getVendorLine2Address());
774                     document.setVendorCityName(vendorAddress.getVendorCityName());
775                     document.setVendorStateCode(vendorAddress.getVendorStateCode());
776                     document.setVendorPostalCode(vendorAddress.getVendorZipCode());
777                     document.setVendorCountryCode(vendorAddress.getVendorCountryCode());
778                     document.setVendorAddressInternationalProvinceName(vendorAddress.getVendorAddressInternationalProvinceName());
779                 }
780                 refresh(mapping, form, request, response);
781             } else {     /* If there is no matching vendor found*/
782                 GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
783             }
784         }
785         return mapping.findForward(OLEConstants.MAPPING_BASIC);
786     }
787 
788     private LookupService getLookupService() {
789         return KRADServiceLocatorWeb.getLookupService();
790     }
791 
792     public ActionForward relinkPO(ActionMapping mapping, ActionForm form, HttpServletRequest request,
793                                         HttpServletResponse response) throws Exception {
794         OlePaymentRequestForm preqForm = (OlePaymentRequestForm) form;
795         OlePaymentRequestDocument document = (OlePaymentRequestDocument) preqForm.getDocument();
796         int itemIndex = getSelectedLine(request);
797         OlePaymentRequestItem item = (OlePaymentRequestItem) ((PurchasingAccountsPayableDocument)document).getItem((itemIndex));
798         Map<String,String> criteriaMap = new HashMap<String,String>();
799         criteriaMap.put("itemIdentifier",item.getPoItemIdentifier().toString());
800         OleInvoiceItem invoiceItem = getBusinessObjectService().findByPrimaryKey(OleInvoiceItem.class,criteriaMap);
801         invoiceItem.setPoItemIdentifier(Integer.valueOf(item.getPurchaseOrderItemID()));
802         invoiceItem.setItemTitleId(item.getItemTitleId());
803         invoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier(document.getAccountsPayablePurchasingDocumentLinkIdentifier());
804         if(invoiceItem.getInvoiceDocument()!=null && invoiceItem.getInvoiceDocument().getDocumentNumber()!=null ){
805             invoiceItem.getInvoiceDocument().setDocumentHeader((SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(invoiceItem.getInvoiceDocument().getDocumentNumber())));
806             getBusinessObjectService().save(invoiceItem.getInvoiceDocument());
807         }
808         getBusinessObjectService().save(document);
809         return mapping.findForward(OLEConstants.MAPPING_BASIC);
810     }
811 
812 }