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.struts.action.ActionForm;
21  import org.apache.struts.action.ActionForward;
22  import org.apache.struts.action.ActionMapping;
23  import org.kuali.ole.coa.businessobject.Account;
24  import org.kuali.ole.docstore.common.document.Bib;
25  import org.kuali.ole.module.purap.PurapConstants;
26  import org.kuali.ole.module.purap.PurapConstants.InvoiceStatuses;
27  import org.kuali.ole.module.purap.PurapPropertyConstants;
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.InvoiceService;
32  import org.kuali.ole.module.purap.document.service.OlePurapService;
33  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
34  import org.kuali.ole.module.purap.document.validation.event.AttributedContinuePurapEvent;
35  import org.kuali.ole.module.purap.document.web.struts.InvoiceAction;
36  import org.kuali.ole.module.purap.document.web.struts.PurchasingAccountsPayableFormBase;
37  import org.kuali.ole.module.purap.document.web.struts.PurchasingFormBase;
38  import org.kuali.ole.pojo.OleBibRecord;
39  import org.kuali.ole.pojo.OleEditorResponse;
40  import org.kuali.ole.select.OleSelectConstant;
41  import org.kuali.ole.select.bo.OLEEditorResponse;
42  import org.kuali.ole.select.businessobject.BibInfoBean;
43  import org.kuali.ole.select.businessobject.OleDocstoreResponse;
44  import org.kuali.ole.select.businessobject.OleInvoiceItem;
45  import org.kuali.ole.select.businessobject.OleInvoiceNote;
46  import org.kuali.ole.select.constants.OleSelectPropertyConstants;
47  import org.kuali.ole.select.document.OleInvoiceDocument;
48  import org.kuali.ole.select.document.service.OleInvoiceService;
49  import org.kuali.ole.select.document.validation.event.OleDiscountInvoiceEvent;
50  import org.kuali.ole.select.document.validation.event.OleForeignCurrencyInvoiceEvent;
51  import org.kuali.ole.select.document.validation.event.OleInvoiceDescEvent;
52  import org.kuali.ole.select.service.BibInfoWrapperService;
53  import org.kuali.ole.select.service.FileProcessingService;
54  import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
55  import org.kuali.ole.sys.OLEConstants;
56  import org.kuali.ole.sys.OLEPropertyConstants;
57  import org.kuali.ole.sys.businessobject.AccountingLineBase;
58  import org.kuali.ole.sys.context.SpringContext;
59  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
60  import org.kuali.ole.vnd.businessobject.OleExchangeRate;
61  import org.kuali.rice.core.api.util.type.KualiDecimal;
62  import org.kuali.rice.krad.service.BusinessObjectService;
63  import org.kuali.rice.krad.service.KualiRuleService;
64  import org.kuali.rice.krad.service.PersistenceService;
65  import org.kuali.rice.krad.util.GlobalVariables;
66  import org.kuali.rice.krad.util.ObjectUtils;
67  
68  import javax.servlet.http.HttpServletRequest;
69  import javax.servlet.http.HttpServletResponse;
70  import java.math.BigDecimal;
71  import java.math.RoundingMode;
72  import java.util.HashMap;
73  import java.util.Iterator;
74  import java.util.List;
75  import java.util.Map;
76  
77  
78  /**
79   * This class is the KualiForm class for Ole Invoice Action
80   */
81  public class OleInvoiceAction extends InvoiceAction {
82  
83      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleInvoiceAction.class);
84  
85      /**
86       * @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)
87       */
88      @Override
89      public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
90          // ActionForward forward = super.calculate(mapping, form, request, response);
91          /* calculateCurrency(mapping, form, request, response); */
92          OleInvoiceForm paymentForm = (OleInvoiceForm) form;
93          OleInvoiceDocument payDoc = (OleInvoiceDocument) paymentForm.getDocument();
94          payDoc.setProrateBy(payDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : payDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE : payDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : null);
95          boolean manualProrateValidFlag = true;
96          if ((payDoc.getProrateBy() != null) && (payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
97              if (payDoc.getProrateBy() != null && payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
98                  // Validates the prorate surchanges if prorate by manual
99                  manualProrateValidFlag = getOleInvoiceService().validateProratedSurcharge(payDoc);
100             }
101             if (manualProrateValidFlag) {
102 
103                 List<OleInvoiceItem> item = payDoc.getItems();
104                 if (payDoc.getVendorDetail() == null || (payDoc.getVendorDetail() != null && payDoc.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != true)) {
105                     for (int i = 0; item.size() > i; i++) {
106                         OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
107                         if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
108                             boolean rulePassed = getKualiRuleService().applyRules(
109                                     new OleDiscountInvoiceEvent(payDoc, items));
110                             if (rulePassed) {
111                                 items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(items));
112                             }
113                         }
114                     }
115                 } else {
116 
117                     LOG.debug("###########Foreign Currency Field Calculation###########");
118                     for (int i = 0; item.size() > i; i++) {
119                         OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
120                         Long id = payDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
121                         Map documentNumberMap = new HashMap();
122                         documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
123                         BusinessObjectService businessObjectService = SpringContext
124                                 .getBean(BusinessObjectService.class);
125                         List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(
126                                 OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
127                         Iterator iterator = exchangeRateList.iterator();
128                         if (iterator.hasNext()) {
129                             OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
130                             items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
131                             payDoc.setForeignVendorInvoiceAmount(payDoc.getVendorInvoiceAmount().bigDecimalValue()
132                                     .multiply(tempOleExchangeRate.getExchangeRate()));
133                         }
134                         if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
135                             boolean rulePassed = getKualiRuleService().applyRules(
136                                     new OleForeignCurrencyInvoiceEvent(payDoc, items));
137                             if (rulePassed) {
138                                 SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
139                                 if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
140                                     items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
141                                     items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue());
142                                     items.setItemListPrice(items.getItemUnitCostUSD());
143                                     items.setPurchaseOrderItemUnitPrice(items.getItemUnitPrice());
144                                 }
145                             }
146 
147                         } else {
148                             if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) {
149                                 // added for jira - OLE-2203
150                                 if (items.isAdditionalChargeUsd()) {
151                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue());
152                                 } else {
153                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP));
154                                 }
155                             }
156                         }
157                     }
158                 }
159                 getOleInvoiceService().calculateProrateItemSurcharge(payDoc);
160             }
161         }
162 
163         if (payDoc.getProrateBy() == null && manualProrateValidFlag) {
164             getOleInvoiceService().calculateWithoutProrates(payDoc);
165         }
166 
167         return super.calculate(mapping, form, request, response);
168     }
169 
170     /**
171      * Add a new Note to the selected InvoiceItem.
172      *
173      * @param mapping  An ActionMapping
174      * @param form     An ActionForm
175      * @param request  The HttpServletRequest
176      * @param response The HttpServletResponse
177      * @return An ActionForward
178      * @throws Exception
179      */
180 
181     public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
182         LOG.debug("Inside addNote Method of OleInvoiceAction");
183         OleInvoiceForm paymentForm = (OleInvoiceForm) form;
184         OleInvoiceDocument paymentDocument = (OleInvoiceDocument) paymentForm.getDocument();
185         int line = this.getSelectedLine(request);
186         OleInvoiceItem item = (OleInvoiceItem) ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItem(line);
187         OleInvoiceNote note = new OleInvoiceNote();
188         note.setNote(item.getNote());
189 //        boolean rulePassed = getKualiRuleService().applyRules(new OleNoteTypeEvent(purDocument,note));
190 //        if(rulePassed){
191         item.getNotes().add(note);
192         LOG.debug("Adding InvoiceNote to the InvoiceItem");
193         item.setNote(null);
194         LOG.debug("Leaving addNote Method of OleInvoiceAction");
195 //        }
196         return mapping.findForward(OLEConstants.MAPPING_BASIC);
197     }
198 
199     /**
200      * deletes the selected InvoiceNote for the selected InvoiceItem
201      *
202      * @param mapping
203      * @param form
204      * @param request
205      * @param response
206      * @return An ActionForward
207      * @throws Exception
208      */
209     public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
210         LOG.debug("Inside deleteNote Method of OleInvoiceAction");
211         OleInvoiceForm paymentForm = (OleInvoiceForm) form;
212 
213         String[] indexes = getSelectedLineForAccounts(request);
214         int itemIndex = Integer.parseInt(indexes[0]);
215         int noteIndex = Integer.parseInt(indexes[1]);
216         OleInvoiceItem item = (OleInvoiceItem) ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItem((itemIndex));
217         item.getNotes().remove(noteIndex);
218         LOG.debug("Note deleted for the selected Item");
219         LOG.debug("Leaving deleteNote Method of OleInvoiceAction");
220         return mapping.findForward(OLEConstants.MAPPING_BASIC);
221     }
222 
223     /**
224      * Add a new item to the document.
225      *
226      * @param mapping  An ActionMapping
227      * @param form     An ActionForm
228      * @param request  The HttpServletRequest
229      * @param response The HttpServletResponse
230      * @return An ActionForward
231      * @throws Exception
232      */
233     public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
234         OleInvoiceForm purchasingForm = (OleInvoiceForm) form;
235         OleInvoiceItem item = (OleInvoiceItem) purchasingForm.getNewPurchasingItemLine();
236         // purchasingForm.getNewPurchasingItemLine().setItemDescription((item.getBibInfoBean().getTitle() != null ?
237         // item.getBibInfoBean().getTitle() : "") + (item.getBibInfoBean().getAuthor() != null ? "," +
238         // item.getBibInfoBean().getAuthor() : "") + (item.getBibInfoBean().getPublisher() != null ? "," +
239         // item.getBibInfoBean().getPublisher() : "") + (item.getBibInfoBean().getIsbn() != null ? "," +
240         // item.getBibInfoBean().getIsbn() : ""));
241         OleInvoiceDocument document = (OleInvoiceDocument) purchasingForm.getDocument();
242         BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
243         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
244         String titleId = null;
245         boolean isBibFileExist = false;
246         Iterator itemIterator = document.getItems().iterator();
247         int itemCounter = 0;
248         while (itemIterator.hasNext()) {
249             OleInvoiceItem tempItem = (OleInvoiceItem) itemIterator.next();
250             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
251                 itemCounter++;
252             }
253         }
254         String itemNo = String.valueOf(itemCounter);
255         //String itemNo = String.valueOf(document.getItems().size() - 8);
256         HashMap<String, String> dataMap = new HashMap<String, String>();
257         item.setBibInfoBean(new BibInfoBean());
258         if (item.getBibInfoBean().getDocStoreOperation() == null) {
259             item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
260         }
261         String fileName = document.getDocumentNumber() + "_" + itemNo;
262 
263         setItemDescription(item, fileName);
264 
265         /*dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation());
266         dataMap.put(OleSelectConstant.FILENAME, fileName);
267         if (fileProcessingService.isCreateFileExist(dataMap)) {
268             isBibFileExist = true;
269         }
270         if (isBibFileExist) {
271             titleId = docStore.getTitleIdByMarcXMLFileProcessing(item.getBibInfoBean(), dataMap);
272             item.setItemTitleId(titleId);
273             BibInfoBean xmlBibInfoBean = new BibInfoBean();
274             dataMap.put(OleSelectConstant.TITLE_ID, titleId);
275             dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
276             xmlBibInfoBean = docStore.getBibInfo(dataMap);
277             item.setBibInfoBean(xmlBibInfoBean);
278             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() : ""));
279 
280             HashMap<String,String> queryMap = new HashMap<String,String>();
281             queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, item.getItemTitleId());
282             List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
283             Iterator bibIdIterator = docStoreResult.iterator();
284             if(bibIdIterator.hasNext()){
285                 DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next();
286                 item.setBibUUID(docInfoBean.getUniqueId());
287             }
288         }*/
289         boolean ruleFlag = getKualiRuleService().applyRules(new OleInvoiceDescEvent(document, item));
290         if (ruleFlag) {
291             if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null && !document.getVendorDetail().getVendorHeader().getVendorForeignIndicator())) {
292                 boolean rulePassed = getKualiRuleService().applyRules(new OleDiscountInvoiceEvent(document, item));
293                 if (rulePassed) {
294                     purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item));
295                     item = (OleInvoiceItem) purchasingForm.getAndResetNewPurchasingItemLine();
296                     document.addItem(item);
297                 }
298             } else {
299                 boolean rulePassed = getKualiRuleService().applyRules(new OleForeignCurrencyInvoiceEvent(document, item));
300                 if (rulePassed) {
301                     LOG.debug("###########Foreign Currency Field Calculation for Invoice ###########");
302                     SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(item);
303                     Long id = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
304                     Map documentNumberMap = new HashMap();
305                     documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
306                     BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
307                     List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
308                     Iterator iterator = exchangeRateList.iterator();
309                     if (iterator.hasNext()) {
310                         OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
311                         item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
312                     }
313                     if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
314                         item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
315                         item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue());
316                         item.setItemListPrice(item.getItemUnitCostUSD());
317                     }
318                     item = (OleInvoiceItem) purchasingForm.getAndResetNewPurchasingItemLine();
319                     document.addItem(item);
320                 }
321             }
322         }
323         return mapping.findForward(OLEConstants.MAPPING_BASIC);
324     }
325 
326     /**
327      * Delete an item from the document.
328      *
329      * @param mapping  An ActionMapping
330      * @param form     An ActionForm
331      * @param request  The HttpServletRequest
332      * @param response The HttpServletResponse
333      * @return An ActionForward
334      * @throws Exception
335      */
336     public ActionForward deleteItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
337         OleInvoiceForm purchasingForm = (OleInvoiceForm) form;
338         OleInvoiceDocument purDocument = (OleInvoiceDocument) purchasingForm.getDocument();
339         purDocument.deleteItem(getSelectedLine(request));
340         return mapping.findForward(OLEConstants.MAPPING_BASIC);
341     }
342 
343     @Override
344     public ActionForward continuePRQS(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
345         OleInvoiceForm rqForm = (OleInvoiceForm) form;
346         OleInvoiceDocument document = (OleInvoiceDocument) rqForm.getDocument();
347         boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedContinuePurapEvent(document));
348         if (!rulePassed) {
349             return super.continuePRQS(mapping, form, request, response);
350         }
351         ActionForward forward = super.continuePRQS(mapping, form, request, response);
352         List<OleInvoiceItem> items = document.getItems();
353         OleInvoiceItem newLineItem = (OleInvoiceItem) rqForm.getNewPurchasingItemLine();
354         if (document.getVendorDetail() != null && document.getVendorDetail().getVendorHeader().getVendorForeignIndicator()) {
355             Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
356             Map documentNumberMap = new HashMap();
357             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
358             BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
359             List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
360             Iterator iterator = exchangeRateList.iterator();
361             for (OleInvoiceItem item : items) {
362                 iterator = exchangeRateList.iterator();
363                 if (iterator.hasNext()) {
364                     OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
365                     item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
366                 }
367             }
368             iterator = exchangeRateList.iterator();
369             if (iterator.hasNext()) {
370                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
371                 newLineItem.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
372             }
373         }
374         rqForm.getAndResetNewPurchasingItemLine();
375 
376         return forward;
377     }
378 
379     @Override
380     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
381         ActionForward forward = super.route(mapping, form, request, response);
382         OleInvoiceDocument document = (OleInvoiceDocument) ((OleInvoiceForm) form).getDocument();
383         Iterator itemIterator = document.getItems().iterator();
384         int itemCounter = 0;
385         boolean rulePassed = true;
386         while (itemIterator.hasNext()) {
387             OleInvoiceItem tempItem = (OleInvoiceItem) itemIterator.next();
388             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)
389                     || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
390                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
391                 if (accountingLineBase != null) {
392                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
393                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
394                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
395                         Map<String, String> criteria = new HashMap<String, String>();
396                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
397                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
398                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
399                                 Account.class, criteria);
400                         rulePassed = checkForValidAccount(account);
401                         if (!rulePassed) {
402                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
403                         }
404                     }
405                 }
406             }
407         }
408         if (rulePassed) {
409             this.calculate(mapping, form, request, response);
410         }
411         return forward;
412     }
413 
414     /**
415      * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
416      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
417      */
418     @Override
419     public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
420         // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
421         PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;
422 
423         // index of item selected
424         int itemIndex = getSelectedLine(request);
425         PurApItem item = null;
426 
427         // if custom processing of an accounting line is not done then insert a line generically.
428         if (processCustomInsertAccountingLine(purapForm, request) == false) {
429             String errorPrefix = null;
430             PurApAccountingLine line = null;
431 
432             boolean rulePassed = false;
433             if (itemIndex >= 0) {
434                 item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
435                 //Calculating the dollar amount for the accounting Line.
436                 PurApAccountingLine lineItem = item.getNewSourceLine();
437                 if (lineItem.getAccountLinePercent() != null) {
438                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
439                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
440                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
441                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
442                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
443                     lineItem.setAccountLinePercent(dollarToPercent);
444                 }
445                 line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
446                 //end
447                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
448                 errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
449                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
450             } else if (itemIndex == -2) {
451                 //corrected: itemIndex == -2 is the only case for distribute account
452                 //This is the case when we're inserting an accounting line for distribute account.
453                 line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
454                 //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
455                 errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
456                 rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
457             }
458             AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
459             if (accountingLineBase != null) {
460                 String accountNumber = accountingLineBase.getAccountNumber();
461                 String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
462                 Map<String, String> criteria = new HashMap<String, String>();
463                 criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
464                 criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
465                 Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
466                         criteria);
467                 rulePassed = checkForValidAccount(account);
468             }
469 
470             if (rulePassed) {
471                 // add accountingLine
472                 SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
473                 if (itemIndex >= 0) {
474                     insertAccountingLine(purapForm, item, line);
475                     // clear the temp account
476                     item.resetAccount();
477                 } else if (itemIndex == -2) {
478                     //this is the case for distribute account
479                     ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
480                 }
481             }
482         }
483 
484         return mapping.findForward(OLEConstants.MAPPING_BASIC);
485     }
486 
487     private boolean checkForValidAccount(Account account) {
488         boolean result = true;
489         if (account != null) {
490             String subFundGroupParameter = getParameterService().getParameterValueAsString(Account.class,
491                     OleSelectConstant.SUB_FUND_GRP_CD);
492             if (account.getSubFundGroupCode().equalsIgnoreCase(subFundGroupParameter)) {
493                 GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
494                         OleSelectPropertyConstants.ERROR_ACCOUNT_NUMBER,
495                         new String[]{OleSelectConstant.PAYMENT_REQUEST});
496                 result = false;
497             }
498         }
499         return result;
500     }
501 
502     private void setItemDescription(OleInvoiceItem item, String fileName) {
503         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
504             Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
505             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName);
506             Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null;
507             bib = (Bib) bib.deserializeContent(bib);
508             if (bib != null) {
509                 String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : "";
510                 String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : "";
511                 String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : "";
512                 String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : "";
513                 String description = title + author + publisher + isbn;
514                 item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
515             }
516             if (bib != null) {
517                 item.setBibUUID(bib.getId());
518                 item.setItemTitleId(bib.getId());
519             }
520             OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse);
521         }
522     }
523 
524     private OleInvoiceService getOleInvoiceService() {
525         return SpringContext.getBean(OleInvoiceService.class);
526     }
527 
528     @Override
529     protected void customCalculate(PurchasingAccountsPayableDocument apDoc) {
530         OleInvoiceDocument preqDoc = (OleInvoiceDocument) apDoc;
531         if ((preqDoc.getProrateBy() != null) && (preqDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || preqDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || preqDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
532             // set amounts on any empty
533             preqDoc.updateExtendedPriceOnItems();
534 
535             // calculation just for the tax area, only at tax review stage
536             // by now, the general calculation shall have been done.
537             if (preqDoc.getApplicationDocumentStatus().equals(InvoiceStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
538                 SpringContext.getBean(InvoiceService.class).calculateTaxArea(preqDoc);
539                 return;
540             }
541 
542             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
543             // Calculate Payment request before rules since the rule check totalAmount.
544             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(preqDoc, true);
545             SpringContext.getBean(KualiRuleService.class).applyRules(
546                     new AttributedCalculateAccountsPayableEvent(preqDoc));
547         } else {
548             super.customCalculate(preqDoc);
549         }
550     }
551 
552     @Override
553     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
554                                         HttpServletResponse response) throws Exception {
555         this.calculate(mapping, form, request, response);
556         ActionForward forward = super.blanketApprove(mapping, form, request, response);
557         OleInvoiceDocument document = (OleInvoiceDocument) ((OleInvoiceForm) form).getDocument();
558         Iterator itemIterator = document.getItems().iterator();
559         int itemCounter = 0;
560         boolean rulePassed = true;
561         while (itemIterator.hasNext()) {
562             OleInvoiceItem tempItem = (OleInvoiceItem) itemIterator.next();
563             if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)
564                     || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) {
565                 List<PurApAccountingLine> accountingLineBase = tempItem.getSourceAccountingLines();
566                 if (accountingLineBase != null) {
567                     for (int accountingLine = 0; accountingLine < accountingLineBase.size(); accountingLine++) {
568                         String accountNumber = accountingLineBase.get(accountingLine).getAccountNumber();
569                         String chartOfAccountsCode = accountingLineBase.get(accountingLine).getChartOfAccountsCode();
570                         Map<String, String> criteria = new HashMap<String, String>();
571                         criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
572                         criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
573                         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
574                                 Account.class, criteria);
575                         rulePassed = checkForValidAccount(account);
576                         if (!rulePassed) {
577                             return mapping.findForward(OLEConstants.MAPPING_BASIC);
578                         }
579                     }
580                 }
581             }
582         }
583         return forward;
584     }
585 }