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) KRADServiceLocatorWeb.getLegacyDataAdapter().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) KRADServiceLocatorWeb.getLegacyDataAdapter().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         SpringContext.getBean(OlePurapService.class).getInitialCollapseSections(document);
271         List<OleCreditMemoItem> items = document.getItems();
272         OleCreditMemoItem newLineItem = (OleCreditMemoItem) rqForm.getNewPurchasingItemLine();
273         document.setProrateQty(true);
274         document.setProrateBy(document.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : document.isProrateManual() ? OLEConstants.MANUAL_PRORATE : document.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR :
275                  document.isNoProrate() ? OLEConstants.NO_PRORATE : null);
276         if (document.getVendorDetail().getCurrencyType()!=null){
277             if(document.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
278                 currencyTypeIndicator=true;
279             }
280             else{
281                 currencyTypeIndicator=false;
282             }
283         }
284 
285         if (document.getVendorDetail() != null && (!currencyTypeIndicator)) {
286             Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
287             Map documentNumberMap = new HashMap();
288             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
289             BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
290             List<OleExchangeRate> exchangeRateList = (List) KRADServiceLocatorWeb.getLegacyDataAdapter().findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
291             Iterator iterator = exchangeRateList.iterator();
292             for (OleCreditMemoItem item : items) {
293                 iterator = exchangeRateList.iterator();
294                 if (iterator.hasNext()) {
295                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
296                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
297                 }
298             }
299             iterator = exchangeRateList.iterator();
300             if (iterator.hasNext()) {
301                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
302                 newLineItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
303             }
304         }
305         rqForm.getAndResetNewPurchasingItemLine();
306 
307         return forward;
308     }
309 
310     @Override
311     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
312         ActionForward forward = super.route(mapping, form, request, response);
313         this.calculate(mapping, form, request, response);
314         return forward;
315     }
316 
317 
318     /**
319      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
320      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
321      */
322     @Override
323     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
324         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
325         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
326 
327         // index of item selected
328         int itemIndex = getSelectedLine(request);
329         PurApItem item = null;
330 
331         // if custom processing of an accounting line is not done then insert a line generically.
332         if (processCustomInsertAccountingLine(purapForm, request) == false) {
333             String errorPrefix = null;
334             PurApAccountingLine line = null;
335 
336             boolean rulePassed = false;
337             if (itemIndex >= 0) {
338                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
339                 //Calculating the dollar amount for the accounting Line.
340                 PurApAccountingLine lineItem = item.getNewSourceLine();
341                 if (lineItem.getAccountLinePercent() != null) {
342                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
343                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
344                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
345                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
346                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
347                     lineItem.setAccountLinePercent(dollarToPercent);
348                 }
349                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
350                 //end
351                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
352                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
353                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
354             } else if (itemIndex == -2) {
355                 //corrected: itemIndex == -2 is the only case for distribute account
356                 //This is the case when we're inserting an accounting line for distribute account.
357                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
358                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
359                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
360                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
361             }
362 
363             if (rulePassed) {
364                 // add accountingLine
365                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
366                 if (itemIndex >= 0) {
367                     insertAccountingLine(purapForm, item, line);
368                     // clear the temp account
369                     item.resetAccount();
370                 } else if (itemIndex == -2) {
371                     //this is the case for distribute account
372                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
373                 }
374             }
375         }
376 
377         return mapping.findForward(OLEConstants.MAPPING_BASIC);
378     }
379 
380     private OleCreditMemoService getOleCreditMemoService() {
381         return SpringContext.getBean(OleCreditMemoService.class);
382     }
383 
384 
385     private void setItemDescription(OleCreditMemoItem item, String fileName) {
386         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
387             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
388             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
389             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
390             bib = (Bib) bib.deserializeContent(bib);
391             if (bib != null) {
392                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
393                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
394                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
395                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
396                 String description = title + author + publisher + isbn;
397                 item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(bib.getId()));
398                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
399             }
400             if (bib != null) {
401                 item.setBibUUID(bib.getId());
402                 item.setItemTitleId(bib.getId());
403             }
404             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
405         }
406     }
407 
408     /**
409      * Calls methods to perform credit allowed calculation and total credit memo amount.
410      *
411      * @param apDoc An AccountsPayableDocument
412      */
413     @Override
414     protected void customCalculate(PurchasingAccountsPayableDocument apDoc) {
415         OleVendorCreditMemoDocument cmDocument = (OleVendorCreditMemoDocument) apDoc;
416 
417         // call service method to finish up calculation
418         SpringContext.getBean(OleCreditMemoService.class).calculateCreditMemo(cmDocument);
419 
420         // notice we're ignoring the boolean because these are just warnings they shouldn't halt anything
421         SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(cmDocument));
422         // }
423     }
424 
425     /**
426      * This method refreshs the Accounting Line for the below line Items based on the Prorations option selected
427      */
428     public ActionForward proratedSurchargeRefresh(ActionMapping mapping, ActionForm form,
429                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
430         OleVendorCreditMemoForm vendorCreditMemoForm = (OleVendorCreditMemoForm) form;
431         OleVendorCreditMemoDocument creditMemoDocument = (OleVendorCreditMemoDocument) vendorCreditMemoForm.getDocument();
432         for (OleCreditMemoItem item : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
433             if (item.getItemType().isAdditionalChargeIndicator()) {
434                 List<PurApItem> items = new ArrayList<>();
435 
436                 /*for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
437                     for (OlePurchaseOrderItem purItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
438                         if (purItem.isItemForInvoice()) {
439                             items.add(purItem);
440                         }
441                     }
442                 }*/
443                 if (items.size() == 0) {
444                     for (OleCreditMemoItem invoiceItem : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
445                         items.add(invoiceItem);
446                     }
447                 }
448                 else {
449                     for (OleCreditMemoItem invoiceItem : (List<OleCreditMemoItem>) creditMemoDocument.getItems()) {
450                         if (!(invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
451                             items.add(invoiceItem);
452                         }
453                     }
454                 }
455                 List<PurApAccountingLine> distributedAccounts = null;
456                 List<SourceAccountingLine> summaryAccounts = null;
457                 summaryAccounts = getOlePurapAccountingService().generateSummaryForManual(items);
458                 distributedAccounts = getOlePurapAccountingService().generateAccountDistributionForProrationByManual(summaryAccounts,CreditMemoAccount.class);
459                 if (CollectionUtils.isNotEmpty(distributedAccounts)) {
460                     item.setSourceAccountingLines(distributedAccounts);
461                 }
462                 if(creditMemoDocument.isNoProrate() && item.getItemType().isAdditionalChargeIndicator()){
463                     item.setSourceAccountingLines(new ArrayList<PurApAccountingLine>());
464                 }
465                 else if (creditMemoDocument.isProrateDollar() || creditMemoDocument.isProrateQty()) {
466                     calculate(mapping, vendorCreditMemoForm, request, response);
467                 }
468             }
469 
470         }
471         return mapping.findForward(OLEConstants.MAPPING_BASIC);
472     }
473 
474     public static OlePurapAccountingService getOlePurapAccountingService() {
475         if (olePurapAccountingService == null) {
476             olePurapAccountingService = SpringContext.getBean(OlePurapAccountingService.class);
477         }
478         return olePurapAccountingService;
479     }
480 
481     public ActionForward selectVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
482         //ActionForward forward = super.clearVendor(mapping, form, request, response);
483         OleVendorCreditMemoForm vendorCreditMemoForm = (OleVendorCreditMemoForm) form;
484         OleVendorCreditMemoDocument creditMemoDocument = (OleVendorCreditMemoDocument) vendorCreditMemoForm.getDocument();
485         if (creditMemoDocument.getVendorAliasName() != null && creditMemoDocument.getVendorAliasName().length() > 0) { /* Checks Vendor name is not equal to null  */
486             /* Getting matching vendor for the given vendor alias name */
487             Map vendorAliasMap = new HashMap();
488             vendorAliasMap.put(OLEConstants.VENDOR_ALIAS_NAME, creditMemoDocument.getVendorAliasName());
489             org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
490             List<VendorAlias> vendorAliasList = (List<VendorAlias>) getLookupService().findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
491             if (vendorAliasList != null && vendorAliasList.size() > 0 && vendorAliasList.get(0) != null) {  /* if there matching vendor found for the given vendor alias name */
492                 Map vendorDetailMap = new HashMap();
493                 vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
494                 vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
495                 VendorDetail vendorDetail = KRADServiceLocatorWeb.getLegacyDataAdapter().findByPrimaryKey(VendorDetail.class, vendorDetailMap);
496                 creditMemoDocument.setVendorDetail(vendorDetail);
497                 creditMemoDocument.setVendorHeaderGeneratedIdentifier(vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier());
498                 creditMemoDocument.setVendorDetailAssignedIdentifier(vendorAliasList.get(0).getVendorDetailAssignedIdentifier());
499                 creditMemoDocument.setVendorName(vendorDetail.getVendorName());
500                 VendorAddress vendorAddress = KRADServiceLocatorWeb.getLegacyDataAdapter().findByPrimaryKey(VendorAddress.class, vendorDetailMap);
501                 if (vendorAddress != null) {
502                     creditMemoDocument.setVendorLine1Address(vendorAddress.getVendorLine1Address());
503                     creditMemoDocument.setVendorLine2Address(vendorAddress.getVendorLine2Address());
504                     creditMemoDocument.setVendorCityName(vendorAddress.getVendorCityName());
505                     creditMemoDocument.setVendorStateCode(vendorAddress.getVendorStateCode());
506                     creditMemoDocument.setVendorPostalCode(vendorAddress.getVendorZipCode());
507                     creditMemoDocument.setVendorCountryCode(vendorAddress.getVendorCountryCode());
508                     creditMemoDocument.setVendorAddressInternationalProvinceName(vendorAddress.getVendorAddressInternationalProvinceName());
509                 }
510                 refresh(mapping, form, request, response);
511             } else {     /* If there is no matching vendor found*/
512                 GlobalVariables.getMessageMap().putError(PurapConstants.VENDOR_ERRORS, OLEConstants.VENDOR_NOT_FOUND);
513             }
514         }
515         return mapping.findForward(OLEConstants.MAPPING_BASIC);
516     }
517 
518     private LookupService getLookupService() {
519         return KRADServiceLocatorWeb.getLookupService();
520     }
521 }