View Javadoc
1   /*
2    * Copyright 2013 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 1.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl1.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.document.web.struts;
17  
18  import org.apache.commons.collections.CollectionUtils;
19  import org.apache.commons.lang.StringEscapeUtils;
20  import org.apache.struts.action.ActionForm;
21  import org.apache.struts.action.ActionForward;
22  import org.apache.struts.action.ActionMapping;
23  import org.kuali.ole.DocumentUniqueIDPrefix;
24  import org.kuali.ole.docstore.common.document.Bib;
25  import org.kuali.ole.module.purap.PurapConstants;
26  import org.kuali.ole.module.purap.PurapPropertyConstants;
27  import org.kuali.ole.module.purap.businessobject.CreditMemoAccount;
28  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
29  import org.kuali.ole.module.purap.businessobject.PurApItem;
30  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
31  import org.kuali.ole.module.purap.document.service.OlePurapService;
32  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
33  import org.kuali.ole.module.purap.document.validation.event.AttributedContinuePurapEvent;
34  import org.kuali.ole.module.purap.document.web.struts.PurchasingAccountsPayableFormBase;
35  import org.kuali.ole.module.purap.document.web.struts.PurchasingFormBase;
36  import org.kuali.ole.module.purap.document.web.struts.VendorCreditMemoAction;
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.OLEEditorResponse;
41  import org.kuali.ole.select.businessobject.BibInfoBean;
42  import org.kuali.ole.select.businessobject.OleCreditMemoItem;
43  import org.kuali.ole.select.businessobject.OleDocstoreResponse;
44  import org.kuali.ole.select.document.OleVendorCreditMemoDocument;
45  import org.kuali.ole.select.document.service.OleCreditMemoService;
46  import org.kuali.ole.select.document.service.OlePurapAccountingService;
47  import org.kuali.ole.select.document.validation.event.OleCreditMemoDescEvent;
48  import org.kuali.ole.select.document.validation.event.OleForeignCurrencyCreditMemoEvent;
49  import org.kuali.ole.select.service.BibInfoWrapperService;
50  import org.kuali.ole.select.service.FileProcessingService;
51  import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
52  import org.kuali.ole.sys.OLEConstants;
53  import org.kuali.ole.sys.OLEPropertyConstants;
54  import org.kuali.ole.sys.businessobject.SourceAccountingLine;
55  import org.kuali.ole.sys.context.SpringContext;
56  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
57  import org.kuali.ole.vnd.businessobject.OleExchangeRate;
58  import org.kuali.ole.vnd.businessobject.VendorAddress;
59  import org.kuali.ole.vnd.businessobject.VendorAlias;
60  import org.kuali.ole.vnd.businessobject.VendorDetail;
61  import org.kuali.rice.core.api.util.type.KualiDecimal;
62  import org.kuali.rice.krad.service.*;
63  import org.kuali.rice.krad.util.GlobalVariables;
64  import org.kuali.rice.krad.util.ObjectUtils;
65  
66  import javax.servlet.http.HttpServletRequest;
67  import javax.servlet.http.HttpServletResponse;
68  import java.math.BigDecimal;
69  import java.math.RoundingMode;
70  import java.util.*;
71  
72  
73  public class OleVendorCreditMemoAction extends VendorCreditMemoAction {
74  
75      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleVendorCreditMemoAction.class);
76      private static transient OlePurapAccountingService olePurapAccountingService;
77  
78      private boolean currencyTypeIndicator = true;
79      /**
80       * @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)
81       */
82      @Override
83      public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
84  
85          OleVendorCreditMemoForm creditForm = (OleVendorCreditMemoForm) form;
86          OleVendorCreditMemoDocument creditDoc = (OleVendorCreditMemoDocument) creditForm.getDocument();
87          if (creditDoc.getVendorDetail().getCurrencyType()!=null){
88              if(creditDoc.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
89                  currencyTypeIndicator=true;
90              }
91              else{
92                  currencyTypeIndicator=false;
93              }
94          }
95          List<OleCreditMemoItem> item = creditDoc.getItems();
96  
97          if (!(creditDoc.getVendorDetail() == null || (creditDoc.getVendorDetail() != null &&
98                  currencyTypeIndicator))) {
99  
100             LOG.debug("###########Foreign Currency Field Calculation###########");
101             for (int i = 0; item.size() > i; i++) {
102                 OleCreditMemoItem items = (OleCreditMemoItem) creditDoc.getItem(i);
103                 Long id = creditDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
104                 Map documentNumberMap = new HashMap();
105                 documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
106                 BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
107                 List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
108                 Iterator iterator = exchangeRateList.iterator();
109                 if (iterator.hasNext()) {
110                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
111                     items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
112                     //creditDoc.setForeignVendorInvoiceAmount(creditDoc.getVendorInvoiceAmount().bigDecimalValue().multiply(tempOleExchangeRate.getExchangeRate()));
113                 }
114                 if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
115                     boolean rulePassed = getKualiRuleService().applyRules(new OleForeignCurrencyCreditMemoEvent(creditDoc, items));
116                     if (rulePassed) {
117                         SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
118                         if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
119                             items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
120                             items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue());
121                         }
122                     }
123                 } else {
124                     if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) {
125 
126                         if (items.isAdditionalChargeUsd()) {
127                             items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue());
128                         } else {
129                             items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP));
130 
131                         }
132                     }
133                 }
134             }
135         }
136         creditDoc.setProrateBy(creditDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : creditDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE :
137                 creditDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : creditDoc.isNoProrate() ? OLEConstants.NO_PRORATE : null);
138         if ((creditDoc.getProrateBy() != null) && (creditDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || creditDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || creditDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
139             LOG.debug("Calculation for ProrateItemSurcharge");
140             getOleCreditMemoService().calculateCreditMemo(creditDoc);
141         } else {
142             for (OleCreditMemoItem items : item) {
143                 if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
144                     items.setItemSurcharge(BigDecimal.ZERO);
145                 }
146             }
147         }
148 
149         return super.calculate(mapping, form, request, response);
150     }
151 
152     /**
153      * Add a new item to the document.
154      *
155      * @param mapping  An ActionMapping
156      * @param form     An ActionForm
157      * @param request  The HttpServletRequest
158      * @param response The HttpServletResponse
159      * @return An ActionForward
160      * @throws Exception
161      */
162     public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
163         OleVendorCreditMemoForm purchasingForm = (OleVendorCreditMemoForm) form;
164         OleCreditMemoItem item = (OleCreditMemoItem) purchasingForm.getNewPurchasingItemLine();
165 
166         OleVendorCreditMemoDocument document = (OleVendorCreditMemoDocument) purchasingForm.getDocument();
167         BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
168         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
169         String titleId = null;
170         boolean isBibFileExist = false;
171         Iterator itemIterator = document.getItems().iterator();
172         int itemCounter = 0;
173         while (itemIterator.hasNext()) {
174             OleCreditMemoItem tempItem = (OleCreditMemoItem) itemIterator.next();
175             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
176                 itemCounter++;
177             }
178         }
179         String itemNo = String.valueOf(itemCounter);
180 
181         HashMap<String, String> dataMap = new HashMap<String, String>();
182         item.setBibInfoBean(new BibInfoBean());
183         if (item.getBibInfoBean().getDocStoreOperation() == null) {
184             item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
185         }
186         String fileName = document.getDocumentNumber() + "_" + itemNo;
187 
188         setItemDescription(item, fileName);
189 
190 
191         boolean ruleFlag = getKualiRuleService().applyRules(new OleCreditMemoDescEvent(document, item));
192 
193         if (ruleFlag) {
194             if (item.getItemDescription() == null || item.getItemDescription().isEmpty()) {
195                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_REQUIRED, new String[]{"Line Item"});
196             } else if (item.getPoUnitPrice() == null || item.getPoUnitPrice().equals(BigDecimal.ZERO)) {
197                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_UNIT_PRICE_REQUIRED);
198             } else {
199                 if (document.getVendorDetail().getCurrencyType()!=null){
200                     if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
201                         currencyTypeIndicator=true;
202                     }
203                     else{
204                         currencyTypeIndicator=false;
205                     }
206                 }
207 
208                 if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && currencyTypeIndicator)) {
209 
210                     item = (OleCreditMemoItem) purchasingForm.getAndResetNewPurchasingItemLine();
211                     document.creditMemoCalculation(item);
212                     document.addItem(item);
213                 } else {
214                     boolean rulePassed = getKualiRuleService().applyRules(new OleForeignCurrencyCreditMemoEvent(document, item));
215                     if (rulePassed) {
216                         LOG.debug("###########Foreign Currency Field Calculation for Payment Request ###########");
217 
218                         Long id = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
219                         Map documentNumberMap = new HashMap();
220                         documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
221                         BusinessObjectService businessObjectService = SpringContext
222                                 .getBean(BusinessObjectService.class);
223                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
224                         Iterator iterator = exchangeRateList.iterator();
225                         if (iterator.hasNext()) {
226                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
227                             item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
228                         }
229                         if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
230                             item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
231                             item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue());
232 
233                         }
234                         item = (OleCreditMemoItem) purchasingForm.getAndResetNewPurchasingItemLine();
235                         document.addItem(item);
236                     }
237                 }
238             }
239         }
240         return mapping.findForward(OLEConstants.MAPPING_BASIC);
241     }
242 
243 
244     /**
245      * Delete an item from the document.
246      *
247      * @param mapping  An ActionMapping
248      * @param form     An ActionForm
249      * @param request  The HttpServletRequest
250      * @param response The HttpServletResponse
251      * @return An ActionForward
252      * @throws Exception
253      */
254     public ActionForward deleteItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
255         OleVendorCreditMemoForm creditMemoForm = (OleVendorCreditMemoForm) form;
256         OleVendorCreditMemoDocument creditMemoDocument = (OleVendorCreditMemoDocument) creditMemoForm.getDocument();
257         creditMemoDocument.deleteItem(getSelectedLine(request));
258         return mapping.findForward(OLEConstants.MAPPING_BASIC);
259     }
260 
261     @Override
262     public ActionForward continueCreditMemo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
263         OleVendorCreditMemoForm rqForm = (OleVendorCreditMemoForm) form;
264         OleVendorCreditMemoDocument document = (OleVendorCreditMemoDocument) rqForm.getDocument();
265         boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedContinuePurapEvent(document));
266         if (!rulePassed) {
267             return super.continueCreditMemo(mapping, form, request, response);
268         }
269         ActionForward forward = super.continueCreditMemo(mapping, form, request, response);
270         if(forward != null){
271             return forward;
272         }
273         SpringContext.getBean(OlePurapService.class).getInitialCollapseSections(document);
274         List<OleCreditMemoItem> items = document.getItems();
275         OleCreditMemoItem newLineItem = (OleCreditMemoItem) rqForm.getNewPurchasingItemLine();
276         document.setProrateQty(true);
277         document.setProrateBy(document.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : document.isProrateManual() ? OLEConstants.MANUAL_PRORATE : document.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR :
278                  document.isNoProrate() ? OLEConstants.NO_PRORATE : null);
279         if (document.getVendorDetail().getCurrencyType()!=null){
280             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
281                 currencyTypeIndicator=true;
282             }
283             else{
284                 currencyTypeIndicator=false;
285             }
286         }
287 
288         if (document.getVendorDetail() != null && (!currencyTypeIndicator)) {
289             Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
290             Map documentNumberMap = new HashMap();
291             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
292             BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
293             List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
294             Iterator iterator = exchangeRateList.iterator();
295             for (OleCreditMemoItem item : items) {
296                 iterator = exchangeRateList.iterator();
297                 if (iterator.hasNext()) {
298                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
299                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
300                 }
301             }
302             iterator = exchangeRateList.iterator();
303             if (iterator.hasNext()) {
304                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
305                 newLineItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
306             }
307         }
308         rqForm.getAndResetNewPurchasingItemLine();
309 
310         return forward;
311     }
312 
313     @Override
314     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
315         ActionForward forward = super.route(mapping, form, request, response);
316         this.calculate(mapping, form, request, response);
317         return forward;
318     }
319 
320 
321     /**
322      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
323      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
324      */
325     @Override
326     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
327         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
328         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
329 
330         // index of item selected
331         int itemIndex = getSelectedLine(request);
332         PurApItem item = null;
333 
334         // if custom processing of an accounting line is not done then insert a line generically.
335         if (processCustomInsertAccountingLine(purapForm, request) == false) {
336             String errorPrefix = null;
337             PurApAccountingLine line = null;
338 
339             boolean rulePassed = false;
340             if (itemIndex >= 0) {
341                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
342                 //Calculating the dollar amount for the accounting Line.
343                 PurApAccountingLine lineItem = item.getNewSourceLine();
344                 if (lineItem.getAccountLinePercent() != null) {
345                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
346                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
347                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
348                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
349                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
350                     lineItem.setAccountLinePercent(dollarToPercent);
351                 }
352                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
353                 //end
354                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
355                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
356                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
357             } else if (itemIndex == -2) {
358                 //corrected: itemIndex == -2 is the only case for distribute account
359                 //This is the case when we're inserting an accounting line for distribute account.
360                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
361                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
362                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
363                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
364             }
365 
366             if (rulePassed) {
367                 // add accountingLine
368                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
369                 if (itemIndex >= 0) {
370                     insertAccountingLine(purapForm, item, line);
371                     // clear the temp account
372                     item.resetAccount();
373                 } else if (itemIndex == -2) {
374                     //this is the case for distribute account
375                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
376                 }
377             }
378         }
379 
380         return mapping.findForward(OLEConstants.MAPPING_BASIC);
381     }
382 
383     private OleCreditMemoService getOleCreditMemoService() {
384         return SpringContext.getBean(OleCreditMemoService.class);
385     }
386 
387 
388     private void setItemDescription(OleCreditMemoItem item, String fileName) {
389         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
390             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
391             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
392             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
393             bib = (Bib) bib.deserializeContent(bib);
394             if (bib != null) {
395                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
396                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
397                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
398                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
399                 String description = title + author + publisher + isbn;
400                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId()));
401                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
402             }
403             if (bib != null) {
404                 item.setBibUUID(bib.getId());
405                 item.setItemTitleId(bib.getId());
406             }
407             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
408         }
409     }
410 
411     /**
412      * Calls methods to perform credit allowed calculation and total credit memo amount.
413      *
414      * @param apDoc An AccountsPayableDocument
415      */
416     @Override
417     protected void customCalculate(PurchasingAccountsPayableDocument apDoc) {
418         OleVendorCreditMemoDocument cmDocument = (OleVendorCreditMemoDocument) apDoc;
419 
420         // call service method to finish up calculation
421         SpringContext.getBean(OleCreditMemoService.class).calculateCreditMemo(cmDocument);
422 
423         // notice we're ignoring the boolean because these are just warnings they shouldn't halt anything
424         SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(cmDocument));
425         // }
426     }
427 
428     /**
429      * This method refreshs the Accounting Line for the below line Items based on the Prorations option selected
430      */
431     public ActionForward proratedSurchargeRefresh(ActionMapping mapping, ActionForm form,
432                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
433         OleVendorCreditMemoForm vendorCreditMemoForm = (OleVendorCreditMemoForm) form;
434         OleVendorCreditMemoDocument creditMemoDocument = (OleVendorCreditMemoDocument) vendorCreditMemoForm.getDocument();
435         for (OleCreditMemoItem item : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
436             if (item.getItemType().isAdditionalChargeIndicator()) {
437                 List<PurApItem> items = new ArrayList<>();
438 
439                 /*for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
440                     for (OlePurchaseOrderItem purItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
441                         if (purItem.isItemForInvoice()) {
442                             items.add(purItem);
443                         }
444                     }
445                 }*/
446                 if (items.size() == 0) {
447                     for (OleCreditMemoItem invoiceItem : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
448                         items.add(invoiceItem);
449                     }
450                 }
451                 else {
452                     for (OleCreditMemoItem invoiceItem : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
453                         if (!(invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
454                             items.add(invoiceItem);
455                         }
456                     }
457                 }
458                 List<PurApAccountingLine> distributedAccounts = null;
459                 List<SourceAccountingLine> summaryAccounts = null;
460                 summaryAccounts = getOlePurapAccountingService().generateSummaryForManual(items);
461                 distributedAccounts = getOlePurapAccountingService().generateAccountDistributionForProrationByManual(summaryAccounts,CreditMemoAccount.class);
462                 if (CollectionUtils.isNotEmpty(distributedAccounts)) {
463                     item.setSourceAccountingLines(distributedAccounts);
464                 }
465                 if(creditMemoDocument.isNoProrate() && item.getItemType().isAdditionalChargeIndicator()){
466                     item.setSourceAccountingLines(new ArrayList<PurApAccountingLine>());
467                 }
468                 else if (creditMemoDocument.isProrateDollar() || creditMemoDocument.isProrateQty()) {
469                     calculate(mapping, vendorCreditMemoForm, request, response);
470                 }
471             }
472 
473         }
474         return mapping.findForward(OLEConstants.MAPPING_BASIC);
475     }
476 
477     public static OlePurapAccountingService getOlePurapAccountingService() {
478         if (olePurapAccountingService == null) {
479             olePurapAccountingService = SpringContext.getBean(OlePurapAccountingService.class);
480         }
481         return olePurapAccountingService;
482     }
483 
484     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
485         //ActionForward forward = super.clearVendor(mapping, form, request, response);
486         OleVendorCreditMemoForm vendorCreditMemoForm = (OleVendorCreditMemoForm) form;
487         OleVendorCreditMemoDocument creditMemoDocument = (OleVendorCreditMemoDocument) vendorCreditMemoForm.getDocument();
488         if (creditMemoDocument.getVendorAliasName() != null && creditMemoDocument.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
489             /* Getting matching vendor for the given vendor alias name */
490             Map vendorAliasMap = new HashMap();
491             vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, creditMemoDocument.getVendorAliasName());
492             org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
493             List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
494             if (vendorAliasList != null && vendorAliasList.size() > 0 && vendorAliasList.get(0) != null) {  /* if there matching vendor found for the given vendor alias name */
495                 Map vendorDetailMap = new HashMap();
496                 vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
497                 vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
498                 VendorDetail vendorDetail = businessObject.findByPrimaryKey(VendorDetail.class, vendorDetailMap);
499                 creditMemoDocument.setVendorDetail(vendorDetail);
500                 creditMemoDocument.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
501                 creditMemoDocument.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
502                 creditMemoDocument.setVendorName(vendorDetail.getVendorName());
503                 VendorAddress vendorAddress = businessObject.findByPrimaryKey(VendorAddress.class, vendorDetailMap);
504                 if (vendorAddress != null) {
505                     creditMemoDocument.setVendorLine1Address(vendorAddress.getVendorLine1Address());
506                     creditMemoDocument.setVendorLine2Address(vendorAddress.getVendorLine2Address());
507                     creditMemoDocument.setVendorCityName(vendorAddress.getVendorCityName());
508                     creditMemoDocument.setVendorStateCode(vendorAddress.getVendorStateCode());
509                     creditMemoDocument.setVendorPostalCode(vendorAddress.getVendorZipCode());
510                     creditMemoDocument.setVendorCountryCode(vendorAddress.getVendorCountryCode());
511                     creditMemoDocument.setVendorAddressInternationalProvinceName(vendorAddress.getVendorAddressInternationalProvinceName());
512                 }
513                 refresh(mapping, form, request, response);
514             } else {     /* If there is no matching vendor found*/
515                 GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
516             }
517         }
518         return mapping.findForward(OLEConstants.MAPPING_BASIC);
519     }
520 
521     private LookupService getLookupService() {
522         return KRADServiceLocatorWeb.getLookupService();
523     }
524 }