View Javadoc
1   package org.kuali.ole.select.controller;
2   
3   
4   import org.apache.commons.collections.CollectionUtils;
5   import org.apache.commons.lang.ArrayUtils;
6   import org.apache.commons.lang.StringUtils;
7   import org.kuali.ole.coa.businessobject.OleFundCode;
8   import org.kuali.ole.coa.businessobject.OleFundCodeAccountingLine;
9   import org.kuali.ole.module.purap.PurapConstants;
10  import org.kuali.ole.module.purap.PurapKeyConstants;
11  import org.kuali.ole.module.purap.PurapPropertyConstants;
12  import org.kuali.ole.module.purap.businessobject.*;
13  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
14  import org.kuali.ole.module.purap.document.service.OlePurapService;
15  import org.kuali.ole.module.purap.document.service.PurapService;
16  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
17  import org.kuali.ole.module.purap.service.PurapAccountingService;
18  import org.kuali.ole.module.purap.util.PurApObjectUtils;
19  import org.kuali.ole.module.purap.util.PurApRelatedViews;
20  import org.kuali.ole.select.OleSelectConstant;
21  import org.kuali.ole.select.businessobject.*;
22  import org.kuali.ole.select.document.OleInvoiceDocument;
23  import org.kuali.ole.select.document.OlePurchaseOrderDocument;
24  import org.kuali.ole.select.document.service.OleInvoiceFundCheckService;
25  import org.kuali.ole.select.document.service.OleInvoiceItemService;
26  import org.kuali.ole.select.document.service.OleInvoiceService;
27  import org.kuali.ole.select.document.service.OlePurapAccountingService;
28  import org.kuali.ole.select.document.service.impl.OlePurapAccountingServiceImpl;
29  import org.kuali.ole.select.document.validation.event.OLEInvoiceSubscriptionOverlayValidationEvent;
30  import org.kuali.ole.select.document.validation.event.OleDiscountInvoiceEvent;
31  import org.kuali.ole.select.document.validation.event.OleForeignCurrencyInvoiceEvent;
32  import org.kuali.ole.select.form.OLEInvoiceForm;
33  import org.kuali.ole.select.service.impl.OLEInvoiceDaoOjb;
34  import org.kuali.ole.sys.OLEConstants;
35  import org.kuali.ole.sys.OLEKeyConstants;
36  import org.kuali.ole.sys.OLEPropertyConstants;
37  import org.kuali.ole.sys.businessobject.AccountingLine;
38  import org.kuali.ole.sys.businessobject.AccountingLineBase;
39  import org.kuali.ole.sys.businessobject.SourceAccountingLine;
40  import org.kuali.ole.sys.context.SpringContext;
41  import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent;
42  import org.kuali.ole.vnd.businessobject.VendorAddress;
43  import org.kuali.ole.vnd.businessobject.VendorDetail;
44  import org.kuali.rice.core.api.config.property.ConfigContext;
45  import org.kuali.rice.core.api.exception.RiceRuntimeException;
46  import org.kuali.rice.core.api.util.RiceKeyConstants;
47  import org.kuali.rice.core.api.util.type.AbstractKualiDecimal;
48  import org.kuali.rice.core.api.util.type.KualiDecimal;
49  import org.kuali.rice.core.api.util.type.KualiInteger;
50  import org.kuali.rice.kew.api.KewApiConstants;
51  import org.kuali.rice.kew.api.exception.WorkflowException;
52  import org.kuali.rice.krad.bo.Note;
53  import org.kuali.rice.krad.bo.PersistableBusinessObject;
54  import org.kuali.rice.krad.document.Document;
55  import org.kuali.rice.krad.exception.ValidationException;
56  import org.kuali.rice.krad.service.*;
57  import org.kuali.rice.krad.uif.UifConstants;
58  import org.kuali.rice.krad.uif.UifParameters;
59  import org.kuali.rice.krad.uif.container.CollectionGroup;
60  import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
61  import org.kuali.rice.krad.uif.view.View;
62  import org.kuali.rice.krad.util.GlobalVariables;
63  import org.kuali.rice.krad.util.KRADConstants;
64  import org.kuali.rice.krad.util.ObjectUtils;
65  import org.kuali.rice.krad.web.controller.TransactionalDocumentControllerBase;
66  import org.kuali.rice.krad.web.form.DocumentFormBase;
67  import org.kuali.rice.krad.web.form.UifFormBase;
68  import org.springframework.stereotype.Controller;
69  import org.springframework.validation.BindingResult;
70  import org.springframework.web.bind.annotation.ModelAttribute;
71  import org.springframework.web.bind.annotation.RequestMapping;
72  import org.springframework.web.bind.annotation.RequestMethod;
73  import org.springframework.web.servlet.ModelAndView;
74  
75  import javax.servlet.http.HttpServletRequest;
76  import javax.servlet.http.HttpServletResponse;
77  import java.math.BigDecimal;
78  import java.math.RoundingMode;
79  import java.text.NumberFormat;
80  import java.text.ParsePosition;
81  import java.util.*;
82  
83  /**
84   * Created with IntelliJ IDEA.
85   * User: anithaa
86   * Date: 7/8/13
87   * Time: 7:27 PM
88   * To change this template use File | Settings | File Templates.
89   */
90  
91  
92  @Controller
93  @RequestMapping(value = "/OLEInvoice")
94  public class OLEInvoiceController extends TransactionalDocumentControllerBase {
95  
96      private static transient OleInvoiceService invoiceService;
97      private KualiRuleService kualiRuleService;
98  
99      @Override
100     protected OLEInvoiceForm createInitialForm(HttpServletRequest request) {
101         OLEInvoiceForm oleInvoiceForm = new OLEInvoiceForm();
102         return oleInvoiceForm;
103     }
104 
105     /**
106      * Creates a new document of the type specified by the docTypeName property of the given form.
107      * This has been abstracted out so that it can be overridden in children if the need arises.
108      *
109      * @param form - form instance that contains the doc type parameter and where
110      *             the new document instance should be set
111      */
112     @Override
113     protected void createDocument(DocumentFormBase form) throws WorkflowException {
114         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
115         super.createDocument(oleInvoiceForm);
116         ((OleInvoiceDocument) oleInvoiceForm.getDocument()).initiateDocument();
117 
118     }
119 
120     @RequestMapping(params = "methodToCall=docHandler")
121     public ModelAndView docHandler(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
122                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
123         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
124         String itemLimit = getInvoiceService().getParameter(org.kuali.ole.OLEConstants.SERIAL_SINGLE_SEC_LIMIT);
125         oleInvoiceForm.setItemLimit(itemLimit!=null?itemLimit:"0");
126         ModelAndView mv = super.docHandler(oleInvoiceForm, result, request, response);
127         String command = form.getCommand();
128         String[] DOCUMENT_LOAD_COMMANDS =
129                 {KewApiConstants.ACTIONLIST_COMMAND, KewApiConstants.DOCSEARCH_COMMAND, KewApiConstants.SUPERUSER_COMMAND,
130                         KewApiConstants.HELPDESK_ACTIONLIST_COMMAND};
131         if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, command) && form.getDocId() != null) {
132             OleInvoiceDocument  oleInvoiceDocument = (OleInvoiceDocument) form.getDocument();
133             oleInvoiceDocument.loadInvoiceDocument();
134         }
135         return mv;
136     }
137     @RequestMapping(params = "methodToCall=addProcessItem")
138     public ModelAndView addItem(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
139                                 HttpServletRequest request, HttpServletResponse response) {
140         LOG.debug("Inside the add process item method");
141         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
142         OleInvoiceDocument invoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
143         invoiceDocument.setDbRetrieval(false);
144         Map<String, String> searchCriteria = new HashMap<String, String>();
145 
146         String poId = invoiceDocument.getPoId();
147         OleInvoiceItemService oleInvoiceItemService = (OleInvoiceItemService) SpringContext
148                 .getBean("oleInvoiceItemService");
149         //getInvoiceService().convertPOItemToInvoiceItem(invoiceDocument);
150         //GlobalVariables.getMessageMap().clearErrorMessages();
151         if(invoiceDocument.getPurchaseOrderDocuments().size() > 0) {
152             GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
153                     PurapKeyConstants.ERROR_PO_ADD);
154         }
155         else {
156             invoiceDocument.setPurchaseOrderDocuments(new ArrayList<OlePurchaseOrderDocument>());
157             if (!poId.isEmpty() && isNumeric(poId) && isValidInteger(poId)) {
158                 searchCriteria.put(OLEConstants.InvoiceDocument.INVOICE_PURAP_DOCUMENT_IDENTIFIER, poId);
159                 //OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, searchCriteria);
160                 OlePurchaseOrderDocument olePurchaseOrderDocument=null;
161                 List<OlePurchaseOrderDocument> purchaseOrderDocumentList =(List<OlePurchaseOrderDocument>) getBusinessObjectService().findMatching(OlePurchaseOrderDocument.class, searchCriteria);
162                 if(purchaseOrderDocumentList.size()>0){
163                     for(OlePurchaseOrderDocument purchaseOrderDocument:purchaseOrderDocumentList){
164                         if(purchaseOrderDocument.getPurchaseOrderCurrentIndicatorForSearching()){
165                             olePurchaseOrderDocument=purchaseOrderDocument;
166                         }
167                     }
168                 }
169                 if (olePurchaseOrderDocument != null && (olePurchaseOrderDocument.getApplicationDocumentStatus().equalsIgnoreCase("OPEN"))) {
170                     if (invoiceDocument.getVendorHeaderGeneratedIdentifier() != null && invoiceDocument.getVendorDetailAssignedIdentifier() != null &&
171                             (olePurchaseOrderDocument.getVendorDetailAssignedIdentifier().compareTo(invoiceDocument.getVendorDetailAssignedIdentifier()) == 0) &&
172                             olePurchaseOrderDocument.getVendorHeaderGeneratedIdentifier().compareTo(invoiceDocument.getVendorHeaderGeneratedIdentifier()) == 0) {
173                         List<OlePurchaseOrderItem> items = (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems();
174                         List<OlePurchaseOrderItem> finalItem = new ArrayList<OlePurchaseOrderItem>();
175                         olePurchaseOrderDocument.setItems(finalItem);
176                         Integer active_item_count = 0;
177                         for (OlePurchaseOrderItem item : items) {
178                             if (item.isItemActiveIndicator() &&
179                                     item.getItemType().isQuantityBasedGeneralLedgerIndicator() &&
180                                     item.getItemType().isLineItemIndicator()) {
181                                 active_item_count = active_item_count + 1;
182 
183                             }
184                             }
185                         if(active_item_count == 0) {
186                             GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID, OLEKeyConstants.NO_ACTIVE_ITEMS, invoiceDocument.getPoId());
187                             return getUIFModelAndView(oleInvoiceForm);
188 
189                         }
190                         else {
191                         for (OlePurchaseOrderItem item : items) {
192                             if (item.isItemActiveIndicator() &&
193                                     item.getItemType().isQuantityBasedGeneralLedgerIndicator() &&
194                                     item.getItemType().isLineItemIndicator()) {
195                                 if (item.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
196                                     item.setPoOutstandingQuantity(item.getItemQuantity().subtract(item.getItemInvoicedTotalQuantity()));
197                                     item.setNoOfCopiesInvoiced(new KualiInteger(item.getItemQuantity().bigDecimalValue()));
198                                     item.setNoOfPartsInvoiced(item.getItemNoOfParts());
199                                     item.setInvoiceItemListPrice(item.getItemListPrice().toString());
200                                     if (StringUtils.isNotBlank(invoiceDocument.getInvoiceCurrencyType())) {
201                                         invoiceDocument.setInvoiceCurrencyTypeId(new Long(invoiceDocument.getInvoiceCurrencyType()));
202                                         String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
203                                         if (StringUtils.isNotBlank(currencyType)) {
204                                             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
205                                                 item.setInvoiceForeignCurrency(currencyType);
206                                                 invoiceDocument.setForeignCurrencyFlag(true);
207                                                 item.setItemDiscount(new KualiDecimal(0.0));
208                                                 if (StringUtils.isBlank(invoiceDocument.getInvoiceCurrencyExchangeRate())) {
209                                                 /*BigDecimal exchangeRate = getInvoiceService().getExchangeRate(invoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
210                                                 invoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
211                                                 item.setInvoiceExchangeRate(exchangeRate.toString());*/
212                                                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
213                                                     return getUIFModelAndView(oleInvoiceForm);
214                                                 } else {
215                                                     try {
216                                                         Double.parseDouble(invoiceDocument.getInvoiceCurrencyExchangeRate());
217                                                         BigDecimal exchangeRate = new BigDecimal(invoiceDocument.getInvoiceCurrencyExchangeRate());
218                                                         if (new KualiDecimal(exchangeRate).isZero()) {
219                                                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
220                                                             return getUIFModelAndView(oleInvoiceForm);
221                                                         }
222                                                         item.setInvoiceExchangeRate(exchangeRate.toString());
223                                                     } catch (NumberFormatException nfe) {
224                                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
225                                                         return getUIFModelAndView(oleInvoiceForm);
226                                                     }
227                                                 }
228 
229                                                 // if the PO has Foreign Currency
230                                                 if (item.getItemForeignListPrice() != null) {
231                                                     item.setInvoiceForeignItemListPrice(item.getItemForeignListPrice().toString());
232                                                     item.setInvoiceForeignDiscount(item.getItemForeignDiscount() != null ? item.getItemForeignDiscount().toString() : new KualiDecimal("0.0").toString());
233                                                     item.setInvoiceForeignUnitCost(item.getItemForeignUnitCost().toString());
234                                                     item.setInvoiceForeignCurrency(currencyType);
235 
236                                                     if (item.getInvoiceExchangeRate() != null && item.getInvoiceForeignUnitCost() != null) {
237                                                         item.setItemUnitCostUSD(new KualiDecimal(new BigDecimal(item.getInvoiceForeignUnitCost()).divide(new BigDecimal(item.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP)));
238                                                         item.setItemUnitPrice(new BigDecimal(item.getInvoiceForeignUnitCost()).divide(new BigDecimal(item.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP));
239                                                         item.setItemListPrice(item.getItemUnitCostUSD());
240                                                         item.setInvoiceItemListPrice(item.getItemListPrice().toString());
241                                                     }
242                                                 } else {
243                                                     item.setItemForeignUnitCost(new KualiDecimal(item.getItemUnitPrice().multiply(new BigDecimal(item.getInvoiceExchangeRate()))));
244                                                     item.setItemForeignListPrice(item.getItemForeignUnitCost());
245                                                     item.setInvoiceForeignItemListPrice(item.getItemForeignListPrice().toString());
246                                                     item.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
247                                                     item.setInvoiceForeignUnitCost(item.getItemForeignUnitCost().toString());
248                                                 }
249                                                 getInvoiceService().calculateAccount(item);
250 
251                                             } else {
252                                                 invoiceDocument.setForeignCurrencyFlag(false);
253                                                 invoiceDocument.setInvoiceCurrencyExchangeRate(null);
254                                                 item.setItemDiscount(item.getItemDiscount() != null ? item.getItemDiscount() : new KualiDecimal(0.0));
255                                             }
256                                         }
257                                     } else {
258                                         invoiceDocument.setForeignCurrencyFlag(false);
259                                         invoiceDocument.setInvoiceCurrencyType(invoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId().toString());
260                                         invoiceDocument.setInvoiceCurrencyTypeId(invoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId());
261                                         invoiceDocument.setInvoiceCurrencyExchangeRate(null);
262                                         item.setInvoiceExchangeRate(null);
263                                         item.setItemExchangeRate(null);
264                                     }
265                                     if (item.getItemTitleId() != null) {
266                                         item.setItemDescription(SpringContext.getBean(OlePurapService.class).getItemDescription(item));
267                                         // item.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(item.getItemTitleId()));
268                                     }
269                                     olePurchaseOrderDocument.getItems().add(item);
270                                 }
271                             }
272                         }
273                         }
274                     //    List<Note> note = olePurchaseOrderDocument.getNotes();
275                         if ((olePurchaseOrderDocument.getPurchaseOrderEndDate() != null)) {
276                             olePurchaseOrderDocument.setPoEndDate(olePurchaseOrderDocument.getPurchaseOrderEndDate());
277                         }
278                         List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = oleInvoiceItemService.getOlePurchaseOrderLineForInvoiceForAddItem(olePurchaseOrderDocument);
279                         olePurchaseOrderDocument.setOlePurchaseOrderLineForInvoiceList(olePurchaseOrderLineForInvoiceList);
280                         List<OlePurchaseOrderTotal> olePurchaseOrderTotalList = oleInvoiceItemService.getOlePurchaseOrderTotalForAddItem(olePurchaseOrderDocument);
281                         olePurchaseOrderDocument.setPurchaseOrderTotalList(olePurchaseOrderTotalList);
282                         // invoiceDocument.setPurchaseOrderNotes("Test");
283                         invoiceDocument.setPoId("");
284                         String[] collapseSections = getInvoiceService().getCollapseSections();
285                         invoiceDocument.getPurchaseOrderDocuments().add(olePurchaseOrderDocument);
286                         invoiceDocument.setOverviewFlag(getInvoiceService().canCollapse(OLEConstants.OVERVIEW_SECTION,collapseSections));
287                         invoiceDocument.setVendorInfoFlag(getInvoiceService().canCollapse(OLEConstants.VENDOR_INFO_SECTION,collapseSections));
288                         invoiceDocument.setInvoiceInfoFlag(getInvoiceService().canCollapse(OLEConstants.INVOICE_INFO_SECTION,collapseSections));
289                         invoiceDocument.setProcessTitlesFlag(getInvoiceService().canCollapse(OLEConstants.PROCESS_TITLES_SECTION,collapseSections));
290                         invoiceDocument.setCurrentItemsFlag(getInvoiceService().canCollapse(OLEConstants.CURRENT_ITEM_SECTION,collapseSections));
291                         invoiceDocument.setAdditionalChargesFlag(getInvoiceService().canCollapse(OLEConstants.ADDITIONAL_CHARGES_SECTION,collapseSections));
292                         invoiceDocument.setAccountSummaryFlag(getInvoiceService().canCollapse(OLEConstants.ACCOUNT_SUMMARY_SECTION,collapseSections));
293                         invoiceDocument.setAdHocRecipientsFlag(getInvoiceService().canCollapse(OLEConstants.ADHOC_RECIPIENT_SECTION,collapseSections));
294                         invoiceDocument.setRouteLogFlag(getInvoiceService().canCollapse(OLEConstants.ROUTE_LOG_SECTION,collapseSections));
295                         invoiceDocument.setNotesAndAttachmentFlag(getInvoiceService().canCollapse(OLEConstants.NOTES_AND_ATTACH_SECTION,collapseSections));
296 
297                     }
298 
299                         else if(invoiceDocument.getVendorHeaderGeneratedIdentifier() == null && invoiceDocument.getVendorDetailAssignedIdentifier() == null && invoiceDocument.getPoId() != null && invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId()) != null) {
300                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID, OLEKeyConstants.ERROR_NO_MATCHING_PO_VND_NM, new String[]{invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId())});
301                     }
302                     else {
303                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID, OLEKeyConstants.ERROR_NO_MATCHING_PO_VND);
304                     }
305                 } else if (olePurchaseOrderDocument != null && olePurchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isFinal() && (olePurchaseOrderDocument.getApplicationDocumentStatus().equalsIgnoreCase("VOID"))) {
306                     if (invoiceDocument.getVendorHeaderGeneratedIdentifier() == null && invoiceDocument.getVendorDetailAssignedIdentifier() == null && invoiceDocument.getPoId() != null && invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId()) != null) {
307                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
308                                 PurapKeyConstants.ERROR_PURCHASE_ORDER_FINAL_VOID);
309                     } else if (invoiceDocument.getVendorName().equalsIgnoreCase(invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId()))) {
310                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
311                                 PurapKeyConstants.ERROR_PURCHASE_ORDER_FINAL_VOID);
312                     } else {
313                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID, OLEKeyConstants.ERROR_NO_MATCHING_PO_VND);
314                     }
315                 } else if (olePurchaseOrderDocument != null && olePurchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isFinal() && (olePurchaseOrderDocument.getApplicationDocumentStatus().equalsIgnoreCase("PENDING PRINT"))) {
316                     if (invoiceDocument.getVendorHeaderGeneratedIdentifier() == null && invoiceDocument.getVendorDetailAssignedIdentifier() == null && invoiceDocument.getPoId() != null && invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId()) != null) {
317                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
318                                 PurapKeyConstants.ERROR_PURCHASE_ORDER_PENDING_PRINT);
319                     } else if (invoiceDocument.getVendorName().equalsIgnoreCase(invoiceService.getPurchaseOrderVendor(invoiceDocument.getPoId()))) {
320                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
321                                 PurapKeyConstants.ERROR_PURCHASE_ORDER_PENDING_PRINT);
322                     } else {
323                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID, OLEKeyConstants.ERROR_NO_MATCHING_PO_VND);
324                     }
325 
326                 } else {
327                     GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
328                             PurapKeyConstants.ERROR_PURCHASE_ORDER_NOT_OPEN);
329                 }
330             }
331             else {
332                 GlobalVariables.getMessageMap().putError(OleSelectConstant.PO_ITEM_SECTION_ID,
333                         OLEKeyConstants.ERROR_NO_PO_EXIST);
334             }
335         }
336         return getUIFModelAndView(oleInvoiceForm);
337     }
338 
339     @RequestMapping(params = "methodToCall=searchVendor")
340     public ModelAndView searchVendor(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
341                                      HttpServletRequest request, HttpServletResponse response) {
342         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
343         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
344         Map<String, String> criteria = new HashMap<String, String>();
345         VendorDetail vendorDetail = null;
346         String[] vendorIds = oleInvoiceDocument.getVendorId().split("-");
347         if (vendorIds.length > 1) {
348             criteria.put(OLEConstants.InvoiceDocument.VENDOR_HEADER_IDENTIFIER, vendorIds[0]);
349             criteria.put(OLEConstants.InvoiceDocument.VENDOR_DETAIL_IDENTIFIER, vendorIds[1]);
350             vendorDetail = (VendorDetail) getBusinessObjectService().findByPrimaryKey(VendorDetail.class, criteria);
351         }
352         if (vendorDetail != null) {
353             oleInvoiceDocument.setVendorDetail(vendorDetail);
354             oleInvoiceDocument.setVendorName(vendorDetail.getVendorName());
355             oleInvoiceDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
356             oleInvoiceDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
357             oleInvoiceDocument.setVendorNumber(vendorDetail.getVendorNumber());
358             oleInvoiceDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
359             oleInvoiceDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
360             oleInvoiceDocument.setVendorFaxNumber(vendorDetail.getDefaultFaxNumber());
361             //oleInvoiceDocument.
362             if (vendorDetail.getVendorPaymentTerms() != null) {
363                 oleInvoiceDocument.setVendorPaymentTerms(vendorDetail.getVendorPaymentTerms());
364                 oleInvoiceDocument.setVendorPaymentTermsCode(vendorDetail.getVendorPaymentTerms().getVendorPaymentTermsCode());
365             }
366             if (vendorDetail.getVendorShippingTitle() != null) {
367                 oleInvoiceDocument.setVendorShippingTitleCode(vendorDetail.getVendorShippingTitle().getVendorShippingTitleCode());
368             }
369             if (vendorDetail.getVendorShippingPaymentTerms() != null) {
370                 oleInvoiceDocument.setVendorShippingPaymentTerms(vendorDetail.getVendorShippingPaymentTerms());
371             }
372             if (vendorDetail.getPaymentMethodId() != null) {
373                 oleInvoiceDocument.setPaymentMethodIdentifier(vendorDetail.getPaymentMethodId().toString());
374             }
375             if (oleInvoiceDocument.getVendorDetail() != null ) {
376                 if (oleInvoiceDocument.getVendorDetail().getCurrencyType() != null) {
377                     oleInvoiceDocument.setInvoiceCurrencyType(vendorDetail.getCurrencyType().getCurrencyTypeId().toString());
378                     oleInvoiceDocument.setInvoiceCurrencyTypeId(vendorDetail.getCurrencyType().getCurrencyTypeId());
379                     if (vendorDetail.getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
380                         oleInvoiceDocument.setForeignCurrencyFlag(false);
381                         oleInvoiceDocument.setForeignInvoiceAmount(null);
382                         oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
383                     } else {
384                         oleInvoiceDocument.setForeignCurrencyFlag(true);
385                         oleInvoiceDocument.setInvoiceAmount(null);
386                         BigDecimal exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
387                         oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
388                     }
389                 }
390             }
391             else {
392                 oleInvoiceDocument.setPaymentMethodIdentifier("");
393             }
394 
395 
396             for (VendorAddress vendorAddress : vendorDetail.getVendorAddresses()) {
397                 if (vendorAddress.isVendorDefaultAddressIndicator()) {
398                     oleInvoiceDocument.setVendorCityName(vendorAddress.getVendorCityName());
399                     oleInvoiceDocument.setVendorLine1Address(vendorAddress.getVendorLine1Address());
400                     oleInvoiceDocument.setVendorLine2Address(vendorAddress.getVendorLine2Address());
401                     oleInvoiceDocument.setVendorAttentionName(vendorAddress.getVendorAttentionName());
402                     oleInvoiceDocument.setVendorPostalCode(vendorAddress.getVendorZipCode());
403                     oleInvoiceDocument.setVendorStateCode(vendorAddress.getVendorStateCode());
404                     oleInvoiceDocument.setVendorAttentionName(vendorAddress.getVendorAttentionName());
405                     oleInvoiceDocument.setVendorAddressInternationalProvinceName(vendorAddress.getVendorAddressInternationalProvinceName());
406                     oleInvoiceDocument.setVendorCountryCode(vendorAddress.getVendorCountryCode());
407                     oleInvoiceDocument.setVendorCountry(vendorAddress.getVendorCountry());
408                     //oleInvoiceDocument.setNoteLine1Text(vendorAddress.getNoteLine2Text
409                 }
410             }
411         }
412         else {
413             vendorDetail = new VendorDetail();
414             oleInvoiceDocument.setVendorDetail(vendorDetail);
415             oleInvoiceDocument.setVendorName(vendorDetail.getVendorName());
416             oleInvoiceDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
417             oleInvoiceDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
418             oleInvoiceDocument.setVendorNumber(vendorDetail.getVendorNumber());
419             oleInvoiceDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
420             oleInvoiceDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
421             oleInvoiceDocument.setVendorFaxNumber(vendorDetail.getDefaultFaxNumber());
422             oleInvoiceDocument.setVendorPaymentTerms(vendorDetail.getVendorPaymentTerms());
423             oleInvoiceDocument.setVendorPaymentTermsCode("");
424             oleInvoiceDocument.setVendorShippingPaymentTerms(vendorDetail.getVendorShippingPaymentTerms());
425             oleInvoiceDocument.setPaymentMethodIdentifier("");
426             oleInvoiceDocument.setVendorCityName("");
427             oleInvoiceDocument.setVendorLine1Address("");
428             oleInvoiceDocument.setVendorLine2Address("");
429             oleInvoiceDocument.setVendorAttentionName("");
430             oleInvoiceDocument.setVendorPostalCode("");
431             oleInvoiceDocument.setVendorStateCode("");
432             oleInvoiceDocument.setVendorAttentionName("");
433             oleInvoiceDocument.setVendorAddressInternationalProvinceName("");
434             oleInvoiceDocument.setVendorCountryCode("");
435         }
436         return getUIFModelAndView(oleInvoiceForm);
437     }
438 
439     @RequestMapping(params = {"methodToCall=calculate"})
440     public ModelAndView calculate(@ModelAttribute("KualiForm") org.kuali.rice.krad.web.form.DocumentFormBase form,
441                                   BindingResult result, HttpServletRequest request, HttpServletResponse response)
442             throws Exception {
443         // ActionForward forward = super.calculate(mapping, form, request, response);
444         /* calculateCurrency(mapping, form, request, response); */
445         OLEInvoiceForm paymentForm = (OLEInvoiceForm) form;
446         OleInvoiceDocument payDoc = (OleInvoiceDocument) paymentForm.getDocument();
447 
448         List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) payDoc).getItems();
449         for(PurApItem purApItem:purApItems){
450             List<KualiDecimal> existingAmount=new ArrayList<>();
451             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
452                 if(oldSourceAccountingLine instanceof InvoiceAccount) {
453                     if(((InvoiceAccount)oldSourceAccountingLine).getExistingAmount()!=null){
454                         existingAmount.add(((InvoiceAccount)oldSourceAccountingLine).getExistingAmount());
455                     }
456                 }
457             }
458             int count=0;
459             for(PurApAccountingLine account:purApItem.getSourceAccountingLines()){
460                 OleInvoiceItem oleInvoiceItem = (OleInvoiceItem)purApItem;
461                 KualiDecimal totalAmount = KualiDecimal.ZERO;
462                 BigDecimal discount = BigDecimal.ZERO;
463                 if(oleInvoiceItem.getItemDiscount() != null) {
464                     if((oleInvoiceItem.getItemDiscountType() != null && oleInvoiceItem.getItemDiscountType().equals("%")) || (oleInvoiceItem.getItemForeignDiscountType() != null && oleInvoiceItem.getItemForeignDiscountType().equals("%"))) {
465                         discount = ((oleInvoiceItem.getItemListPrice().bigDecimalValue().multiply(oleInvoiceItem.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
466                         totalAmount = new KualiDecimal(purApItem.getItemQuantity().bigDecimalValue().multiply(oleInvoiceItem.getItemListPrice().bigDecimalValue().subtract(discount)));
467                     }  else {
468                         discount = ((oleInvoiceItem.getItemListPrice().bigDecimalValue().subtract(oleInvoiceItem.getItemDiscount().bigDecimalValue())));
469                         totalAmount = new KualiDecimal(purApItem.getItemQuantity().bigDecimalValue().multiply(oleInvoiceItem.getItemListPrice().bigDecimalValue().subtract(discount)));
470                     }
471 
472                 }
473                 else{
474                     totalAmount = new KualiDecimal(purApItem.getItemQuantity().bigDecimalValue().multiply(oleInvoiceItem.getItemListPrice().bigDecimalValue()));
475                 }
476                 if (purApItem != null && purApItem.getExtendedPrice() != null && purApItem.getExtendedPrice().isZero()) {
477                     account.setAmount(KualiDecimal.ZERO);
478                 }
479                 else if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) {
480                     if (account.getAmount()!=null&&count<existingAmount.size()&&existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) {
481                         KualiDecimal calculatedPercent = totalAmount.isGreaterThan(AbstractKualiDecimal.ZERO) ? new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(totalAmount).toString()) : KualiDecimal.ZERO;
482                         account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE,BigDecimal.ROUND_CEILING));
483                     }
484                     else {
485                         KualiDecimal calculatedAmount = new KualiDecimal((account.getAccountLinePercent().multiply(purApItem.getItemQuantity().bigDecimalValue().multiply(oleInvoiceItem.getItemListPrice().bigDecimalValue().subtract(discount))).divide(new BigDecimal(100))).toString());
486                         account.setAmount(calculatedAmount);
487                         KualiDecimal calculatedPercent = totalAmount.isGreaterThan(AbstractKualiDecimal.ZERO) ? new KualiDecimal(account.getAmount().multiply(new KualiDecimal(100)).divide(totalAmount).toString()) : KualiDecimal.ZERO;
488                             account.setAccountLinePercent(calculatedPercent.bigDecimalValue().setScale(OLEConstants.BIG_DECIMAL_SCALE,BigDecimal.ROUND_CEILING));
489                         }
490                 }
491                 count++;
492             }
493             for(PurApAccountingLine oldSourceAccountingLine:purApItem.getSourceAccountingLines()) {
494                 if(oldSourceAccountingLine instanceof InvoiceAccount) {
495                     ((InvoiceAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
496                 }
497             }
498         }
499 
500         payDoc.setProrateBy(payDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : payDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE : payDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : payDoc.isNoProrate() ? OLEConstants.NO_PRORATE : null);
501 
502         if ( StringUtils.isNotBlank(payDoc.getInvoiceCurrencyType()) ) {
503             List<OleInvoiceItem> item = payDoc.getItems();
504             String currencyType = getInvoiceService().getCurrencyType(payDoc.getInvoiceCurrencyType());
505             if (StringUtils.isNotBlank(currencyType)) {
506                 if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
507                     payDoc.setInvoiceCurrencyExchangeRate(null);
508                     payDoc.setForeignCurrencyFlag(false);
509                     payDoc.setForeignVendorInvoiceAmount(null);
510                     for (int i = 0; item.size() > i; i++) {
511                         OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
512                         if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
513                             boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(
514                                     new OleDiscountInvoiceEvent(payDoc, items));
515                             if (rulePassed) {
516                                 items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(items).setScale(4, BigDecimal.ROUND_HALF_UP));
517                             }
518                         }
519                     }
520                 } else {
521                     LOG.debug("###########Foreign Currency Field Calculation###########");
522                     for (int i = 0; item.size() > i; i++) {
523                         OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
524                         BigDecimal exchangeRate = null;
525                         if (StringUtils.isNotBlank(payDoc.getInvoiceCurrencyExchangeRate())) {
526                             try {
527                                 Double.parseDouble(payDoc.getInvoiceCurrencyExchangeRate());
528                                 exchangeRate = new BigDecimal(payDoc.getInvoiceCurrencyExchangeRate());
529                                 if (new KualiDecimal(exchangeRate).isZero() ) {
530                                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
531                                     return getUIFModelAndView(paymentForm);
532                                 }
533                                 items.setItemExchangeRate(new KualiDecimal(exchangeRate));
534                                 items.setExchangeRate(exchangeRate.toString());
535                             }
536                             catch (NumberFormatException nfe) {
537                                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
538                                 return getUIFModelAndView(paymentForm);
539                             }
540                         } else {
541                                 /*exchangeRate = new KualiDecimal(getInvoiceService().getExchangeRate(payDoc.getInvoiceCurrencyType()).getExchangeRate());
542                                 items.setItemExchangeRate(exchangeRate);
543                                 items.setExchangeRate(exchangeRate.toString());
544                                 payDoc.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
545                                 payDoc.setForeignCurrencyFlag(true);*/
546                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
547                             return getUIFModelAndView(paymentForm);
548                         }
549                             /*payDoc.setForeignVendorInvoiceAmount(payDoc.getVendorInvoiceAmount()!=null ? payDoc.getVendorInvoiceAmount().bigDecimalValue()
550                                     .multiply(tempOleExchangeRate.getExchangeRate()) : payDoc.getForeignVendorInvoiceAmount());*/
551 
552                         if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
553                             boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(
554                                     new OleForeignCurrencyInvoiceEvent(payDoc, items));
555                             if (rulePassed) {
556                                 SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
557                                 if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
558                                     items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost().bigDecimalValue().divide(exchangeRate, 4, BigDecimal.ROUND_HALF_UP)));
559                                     items.setItemUnitPrice(items.getItemForeignUnitCost().bigDecimalValue().divide(exchangeRate, 4, BigDecimal.ROUND_HALF_UP));
560                                     items.setItemListPrice(items.getItemUnitCostUSD());
561                                     if (!items.isDebitItem()) {
562                                         items.setListPrice("-" + items.getItemListPrice().toString());
563                                     } else {
564                                         items.setListPrice(items.getItemListPrice().toString());
565                                     }
566                                     items.setItemDiscount(new KualiDecimal(0.0));
567                                     items.setDiscountItem(new KualiDecimal(0.0).toString());
568                                 }
569                                 getInvoiceService().calculateAccount(items);
570                             }
571 
572                         } else {
573                             if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) {
574                                 // added for jira - OLE-2203
575                                 if (items.isAdditionalChargeUsd()) {
576                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue());
577                                 } else {
578                                     items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().divide(exchangeRate, 4, RoundingMode.HALF_UP));
579                                 }
580                             }
581                         }
582                     }
583                 }
584             }
585         }
586         else{
587             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, org.kuali.ole.OLEConstants.NO_CURENCYTYPE_FOUND);
588         }
589 
590         //   SpringContext.getBean(OleInvoiceService.class).populateInvoiceFromPurchaseOrders(payDoc,null);
591         SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(payDoc);
592 
593         if ((payDoc.getProrateBy() != null) && (payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
594             // set amounts on any empty
595             payDoc.updateExtendedPriceOnItems();
596 
597             // calculation just for the tax area, only at tax review stage
598             // by now, the general calculation shall have been done.
599             if (payDoc.getApplicationDocumentStatus().equals(PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
600                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(payDoc);
601             }
602 
603             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
604             // Calculate Payment request before rules since the rule check totalAmount.
605             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(payDoc, true);
606             SpringContext.getBean(KualiRuleService.class).applyRules(
607                     new AttributedCalculateAccountsPayableEvent(payDoc));
608         } else {
609             // set amounts on any empty
610             payDoc.updateExtendedPriceOnItems();
611 
612             // calculation just for the tax area, only at tax review stage
613             // by now, the general calculation shall have been done.
614             if (StringUtils.equals(payDoc.getApplicationDocumentStatus(), PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
615                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(payDoc);
616 
617             }
618 
619             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
620             //Calculate Payment request before rules since the rule check totalAmount.
621             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(payDoc, true);
622             SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(payDoc));
623         }
624 
625         payDoc.setCalculated(true);
626 
627         try {
628             SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(payDoc);
629             payDoc.refreshAccountSummmary();
630         } catch (Exception e) {
631             LOG.error("Exception while refreshing the document"+e);
632             throw new RuntimeException(e);
633         }
634         calculateProrateForPOLevel(payDoc);
635 
636 
637         //return mapping.findForward(OLEConstants.MAPPING_BASIC);
638         //AccountsPayableActionBase accountsPayableActionBase = new AccountsPayableActionBase();
639         //return calculate(mapping, form, request, response);
640         return getUIFModelAndView(paymentForm);
641     }
642 
643     public void  calculateProrateForPOLevel(OleInvoiceDocument inv) {
644         List<Integer> poIdList = new ArrayList<>();
645         int noOfCopies = 0;
646         for(OleInvoiceItem item : (List<OleInvoiceItem>)inv.getItems()){
647             if(item.getItemTypeCode().equals(OLEConstants.ITEM)){
648                 poIdList.add(item.getPurchaseOrderIdentifier());
649                 noOfCopies += Integer.parseInt(item.getOleCopiesOrdered());
650             }
651         }
652         List<OleInvoiceItem> removeFromInvoiceItemList = new ArrayList<OleInvoiceItem>();
653         List<OleInvoiceItem> addToInvoiceItemList = new ArrayList<OleInvoiceItem>();
654         int invoiceItemsize = poIdList.size();
655         for(OleInvoiceItem item : (List<OleInvoiceItem>)inv.getItems()){
656             if(!item.getItemTypeCode().equals(OLEConstants.ITEM) && item.getItemUnitPrice() != null) {
657                 BigDecimal itemUnitPrice = item.getItemUnitPrice();
658                 if(inv.isProrateQty()) {
659                     itemUnitPrice = (itemUnitPrice.divide(new BigDecimal(noOfCopies), 2, RoundingMode.HALF_UP));
660                     for (int i = 0; i < invoiceItemsize; i++) {
661                         OleInvoiceItem oleInvoiceItem = (OleInvoiceItem) ObjectUtils.deepCopy(item);
662                         int copies = Integer.parseInt((String) ((OleInvoiceItem) inv.getItems().get(i)).getOleCopiesOrdered());
663                         oleInvoiceItem.setItemUnitPrice(itemUnitPrice.multiply(new BigDecimal(copies)));
664                         oleInvoiceItem.setPurchaseOrderIdentifier(poIdList.get(i));
665                         List<SourceAccountingLine> sourceAccountingLines = (List) ((OleInvoiceItem) inv.getItems().get(i)).getSourceAccountingLines();
666                         List<PurApAccountingLine> sourceAccountingLineList = updateAccountingLinesForProrate(sourceAccountingLines, itemUnitPrice, InvoiceAccount.class);
667                         oleInvoiceItem.setSourceAccountingLines(sourceAccountingLineList);
668                         addToInvoiceItemList.add(oleInvoiceItem);
669                     }
670                     removeFromInvoiceItemList.add(item);
671                 } else if(inv.isProrateDollar()) {
672                     for (int i = 0; i < invoiceItemsize; i++) {
673                         OleInvoiceItem oleInvoiceItem = (OleInvoiceItem) ObjectUtils.deepCopy(item);
674                         KualiDecimal totalAmount = ((OleInvoiceItem) inv.getItems().get(i)).getTotalAmount();
675                         String listPrice = (String)((OleInvoiceItem) inv.getItems().get(i)).getListPrice();
676                         itemUnitPrice = (new BigDecimal(listPrice).multiply(item.getItemUnitPrice())).divide(new BigDecimal(inv.getItemTotal()));
677                         oleInvoiceItem.setItemUnitPrice(itemUnitPrice);
678                         oleInvoiceItem.setPurchaseOrderIdentifier(poIdList.get(i));
679                         List<SourceAccountingLine> sourceAccountingLines = (List) ((OleInvoiceItem) inv.getItems().get(i)).getSourceAccountingLines();
680                         List<PurApAccountingLine> sourceAccountingLineList = updateAccountingLinesForProrate(sourceAccountingLines, itemUnitPrice, InvoiceAccount.class);
681                         oleInvoiceItem.setSourceAccountingLines(sourceAccountingLineList);
682                         addToInvoiceItemList.add(oleInvoiceItem);
683                     }
684                     removeFromInvoiceItemList.add(item);
685 
686                 } else if(inv.isProrateManual()) {
687                     itemUnitPrice = itemUnitPrice.divide(new BigDecimal(poIdList.size()), 2, RoundingMode.HALF_UP);
688                     for (int i = 0; i < invoiceItemsize; i++) {
689                         OleInvoiceItem oleInvoiceItem = (OleInvoiceItem) ObjectUtils.deepCopy(item);
690                         oleInvoiceItem.setItemUnitPrice(itemUnitPrice);
691                         oleInvoiceItem.setPurchaseOrderIdentifier(poIdList.get(i));
692                         List<PurApAccountingLine> sourceAccountingLines = oleInvoiceItem.getSourceAccountingLines();
693                         List<PurApAccountingLine> soucrceAccountingLineList = updateAccountingLinesForManualProrate(sourceAccountingLines, itemUnitPrice, InvoiceAccount.class);
694                         oleInvoiceItem.setSourceAccountingLines(soucrceAccountingLineList);
695                         addToInvoiceItemList.add(oleInvoiceItem);
696                     }
697                     removeFromInvoiceItemList.add(item);
698                 }
699             }
700         }
701         inv.getItems().removeAll(removeFromInvoiceItemList);
702         inv.getItems().addAll(addToInvoiceItemList);
703     }
704 
705     public List<PurApAccountingLine> updateAccountingLinesForProrate(List<SourceAccountingLine> accounts, BigDecimal itemUnitPrice, Class clazz) {
706 
707         List<PurApAccountingLine> newAccounts = new ArrayList();
708         BigDecimal percent = new BigDecimal(0);
709         if (accounts.size() > 0) {
710             percent = new BigDecimal(100).divide(new BigDecimal(accounts.size()), 2, RoundingMode.HALF_UP);
711             itemUnitPrice = itemUnitPrice.multiply(percent.divide(new BigDecimal(100)));
712         }
713         for (SourceAccountingLine accountingLine : accounts) {
714             PurApAccountingLine newAccountingLine;
715             newAccountingLine = null;
716             try {
717                 newAccountingLine = (PurApAccountingLine) clazz.newInstance();
718             } catch (InstantiationException e) {
719                 e.printStackTrace();
720             } catch (IllegalAccessException e) {
721                 e.printStackTrace();
722             }
723             PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine);
724             newAccountingLine.setAccountLinePercent(percent);
725             newAccountingLine.setAmount(new KualiDecimal(itemUnitPrice));
726             newAccounts.add(newAccountingLine);
727 
728 
729         }
730 
731         return newAccounts;
732 
733     }
734 
735 
736     public List<PurApAccountingLine> updateAccountingLinesForManualProrate(List<PurApAccountingLine> accounts, BigDecimal itemUnitPrice, Class clazz) {
737 
738         List<PurApAccountingLine> newAccounts = new ArrayList();
739         BigDecimal percent = new BigDecimal(0);
740         if (accounts.size() > 0) {
741             percent = new BigDecimal(100).divide(new BigDecimal(accounts.size()), 2, RoundingMode.HALF_UP);
742             itemUnitPrice = itemUnitPrice.multiply(percent.divide(new BigDecimal(100)));
743         }
744         for (PurApAccountingLine accountingLine : accounts) {
745             PurApAccountingLine newAccountingLine;
746             newAccountingLine = null;
747             try {
748                 newAccountingLine = (PurApAccountingLine) clazz.newInstance();
749             } catch (InstantiationException e) {
750                 e.printStackTrace();
751             } catch (IllegalAccessException e) {
752                 e.printStackTrace();
753             }
754             PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine);
755             newAccountingLine.setAccountLinePercent(percent);
756             newAccountingLine.setAmount(new KualiDecimal(itemUnitPrice));
757             newAccounts.add(newAccountingLine);
758 
759 
760         }
761 
762         return newAccounts;
763 
764     }
765 
766 
767     /*@RequestMapping(params = "methodToCall=view")
768     public ModelAndView view(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
769                              HttpServletRequest request, HttpServletResponse response) {
770 
771         String ckecking;
772         OLEInvoiceForm  invform = (OLEInvoiceForm) form;
773         InvoiceDocument invoiceDoc = (InvoiceDocument)invform.getDocument();
774         List<InvoiceAccount> l=new ArrayList<InvoiceAccount>();
775         //l= invoiceDoc.getInvoiceAccount();
776         if (l.isEmpty())
777         {
778             ckecking=new String("SELECT THE ACCOUNT NUMBER");
779         }
780         else
781         {
782            // invoiceDoc.setAccountSummary(l);
783         }
784         Integer c=l.size();
785         //invoiceDoc.setValue2(c.toString());
786         //invoiceDoc.setValue1("   ");
787         return  getUIFModelAndView(invform);
788     }*/
789 
790     /**
791      * Saves the document instance contained on the form
792      *
793      * @param form - document form base containing the document instance that will be saved
794      * @return ModelAndView
795      */
796     @RequestMapping(params = "methodToCall=save")
797     public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
798                              HttpServletRequest request, HttpServletResponse response) throws Exception {
799 
800         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
801         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
802         oleInvoiceDocument.setDbRetrieval(false);
803         OleInvoiceItemService oleInvoiceItemService = (OleInvoiceItemService) SpringContext
804                 .getBean("oleInvoiceItemService");
805         OleInvoiceFundCheckService oleInvoiceFundCheckService = (OleInvoiceFundCheckService) SpringContext
806                 .getBean("oleInvoiceFundCheckService");
807         oleInvoiceDocument.setNoteLine1Text(oleInvoiceDocument.getInvoiceNumber());
808         boolean fundCheckFlag = false;
809         if (!validateRequiredFields(oleInvoiceDocument,false)) {
810             return getUIFModelAndView(oleInvoiceForm);
811         }
812         if(oleInvoiceDocument.getItems().size() > 4) {
813             try {
814                 calculate(oleInvoiceForm, result, request, response);
815             }
816             catch (Exception e) {
817                 LOG.error("Exception while calculating the document"+e);
818                 throw new RuntimeException(e);
819             }
820         }
821         if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
822             fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
823             if (fundCheckFlag) {
824                 return getUIFModelAndView(form);
825             }
826         }
827         List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = oleInvoiceDocument.getPurchaseOrderDocuments();
828         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) {
829             List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = oleInvoiceItemService.getOlePurchaseOrderLineForInvoice(olePurchaseOrderDocument);
830             olePurchaseOrderDocument.setOlePurchaseOrderLineForInvoiceList(olePurchaseOrderLineForInvoiceList);
831             List<OlePurchaseOrderTotal> olePurchaseOrderTotalList = oleInvoiceItemService.getOlePurchaseOrderTotal(olePurchaseOrderDocument);
832             olePurchaseOrderDocument.setPurchaseOrderTotalList(olePurchaseOrderTotalList);
833         }
834         Long nextLinkIdentifier = SpringContext.getBean(SequenceAccessorService.class).getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID");
835         oleInvoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(nextLinkIdentifier.intValue());
836         SpringContext.getBean(OleInvoiceService.class).populateInvoiceDocument(oleInvoiceDocument);
837         //oleInvoiceDocument = getInvoiceService().populateInvoiceFromPurchaseOrders(oleInvoiceDocument, null);
838         //oleInvoiceForm.setDocument(oleInvoiceDocument);
839         boolean duplicationExists = false;
840         duplicationExists = getInvoiceService().isDuplicationExists(oleInvoiceDocument,oleInvoiceForm,false);
841         if (duplicationExists) {
842             oleInvoiceDocument.setDuplicateSaveFlag(true);
843             return getUIFModelAndView(form);
844         }
845         oleInvoiceDocument.setDuplicateSaveFlag(false);
846         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
847         ModelAndView mv = super.save(form, result, request, response);
848         oleInvoiceDocument.loadInvoiceDocument();
849         return mv;
850     }
851 
852     @RequestMapping(params = "methodToCall=continueSave")
853     public ModelAndView continueSave(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
854                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
855 
856         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
857         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
858         oleInvoiceDocument.setDuplicateSaveFlag(false);
859         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
860         ModelAndView mv = super.save(form, result, request, response);
861         oleInvoiceDocument.loadInvoiceDocument();
862         return mv;
863     }
864 
865 
866     /**
867      * Routes the document instance contained on the form
868      *
869      * @param form - document form base containing the document instance that will be routed
870      * @return ModelAndView
871      */
872     @RequestMapping(params = "methodToCall=route")
873     public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
874                               HttpServletRequest request, HttpServletResponse response)  {
875         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
876         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
877         oleInvoiceDocument.setDbRetrieval(false);
878         oleInvoiceDocument.setValidationFlag(false);
879         List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = oleInvoiceDocument.getPurchaseOrderDocuments();
880         OleInvoiceItemService oleInvoiceItemService = (OleInvoiceItemService) SpringContext
881                 .getBean("oleInvoiceItemService");
882         OleInvoiceFundCheckService oleInvoiceFundCheckService = (OleInvoiceFundCheckService) SpringContext
883                 .getBean("oleInvoiceFundCheckService");
884         if(!(SpringContext.getBean(OleInvoiceService.class).validateDepositAccount(oleInvoiceDocument))){
885             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID,
886                     PurapKeyConstants.ERROR_INVALID_DEPOSIT_ACCT);
887             return getUIFModelAndView(oleInvoiceForm);
888         }
889 
890         if(! (oleInvoiceDocument.getItems().size() > 0 )){
891             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_ATLEAST_ONE_ITEM_QTY_REQUIRED);
892             return getUIFModelAndView(oleInvoiceForm);
893         }
894         /*if(olePurchaseOrderDocumentList.size()==0){
895             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_ATLEAST_ONE_ITEM_QTY_REQUIRED);
896             return getUIFModelAndView(oleInvoiceForm);
897         }*/
898         /*if(oleInvoiceDocument.getPoId().equalsIgnoreCase(null)){
899             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_ATLEAST_ONE_ITEM_QTY_REQUIRED);
900             return getUIFModelAndView(oleInvoiceForm);
901         }*/
902        /* for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
903              if (invoiceItem == null ){
904                     GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_ATLEAST_ONE_ITEM_QTY_REQUIRED);
905                     return getUIFModelAndView(oleInvoiceForm);
906              }
907         }*/
908         boolean fundCheckFlag = false;
909         if (!validateRequiredFields(oleInvoiceDocument,true)) {
910             return getUIFModelAndView(oleInvoiceForm);
911         }
912         try {
913             SpringContext.getBean(OleInvoiceService.class).populateInvoiceDocument(oleInvoiceDocument);
914             calculate(oleInvoiceForm, result, request, response);
915         } catch (Exception e) {
916             LOG.error("Exception while calculating the document"+e);
917             throw new RuntimeException(e);
918         }
919         oleInvoiceDocument.setNoteLine1Text(oleInvoiceDocument.getInvoiceNumber());
920 
921         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) {
922             List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = oleInvoiceItemService.getOlePurchaseOrderLineForInvoice(olePurchaseOrderDocument);
923             olePurchaseOrderDocument.setOlePurchaseOrderLineForInvoiceList(olePurchaseOrderLineForInvoiceList);
924             List<OlePurchaseOrderTotal> olePurchaseOrderTotalList = oleInvoiceItemService.getOlePurchaseOrderTotal(olePurchaseOrderDocument);
925             olePurchaseOrderDocument.setPurchaseOrderTotalList(olePurchaseOrderTotalList);
926            /* Added for Grand total*/
927             oleInvoiceDocument.setGrandTotal(oleInvoiceDocument.getGrandTotal());
928         }
929         if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
930             fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
931             if (fundCheckFlag) {
932                 return getUIFModelAndView(form);
933             }
934         }
935             String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(oleInvoiceDocument);
936             if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
937                 oleInvoiceForm.setSubscriptionDateValidationMessage(subscriptionValidationMessage);
938                 oleInvoiceDocument.setSubscriptionDateValidationFlag(true);
939             }
940 
941         if (oleInvoiceDocument.getItems() != null && oleInvoiceDocument.getItems().size() > 4 ) {
942             String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
943             if (!validationMessage.isEmpty() && validationMessage != null){
944                 oleInvoiceForm.setValidationMessage(validationMessage);
945                 oleInvoiceDocument.setValidationFlag(true);
946             }
947         }
948         if(oleInvoiceDocument.getSourceAccountingLines().size() > 0){
949             List<SourceAccountingLine> sourceAccountingLineList = oleInvoiceDocument.getSourceAccountingLines();
950             for (SourceAccountingLine accLine : sourceAccountingLineList) {
951                 Map searchMap = new HashMap();
952                 String notificationOption = null;
953                 boolean sufficientFundCheck;
954                 Map<String, Object> key = new HashMap<String, Object>();
955                 String chartCode = accLine.getChartOfAccountsCode();
956                 String accNo = accLine.getAccountNumber();
957                 String objectCd = accLine.getFinancialObjectCode();
958                 key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
959                 key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
960                 OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
961                         OleSufficientFundCheck.class, key);
962                 if (account != null) {
963                     notificationOption = account.getNotificationOption();
964                 }
965                 if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.WARNING_MSG)) {
966                     if(oleInvoiceDocument.getPaymentMethodIdentifier() != null && (SpringContext.getBean(OleInvoiceService.class).getPaymentMethodType(oleInvoiceDocument.getPaymentMethodIdentifier())).equals(OLEConstants.DEPOSIT)) {
967                         sufficientFundCheck = false;
968                     }else{
969                         sufficientFundCheck = oleInvoiceFundCheckService.hasSufficientFundCheckRequired(accLine);
970                     }
971                     oleInvoiceDocument.setSfcFlag(sufficientFundCheck);
972                     if (sufficientFundCheck) {
973                         oleInvoiceForm.setSubscriptionDateValidationMessage(null);
974                         oleInvoiceDocument.setSubscriptionDateValidationFlag(false);
975                         oleInvoiceDocument.setSfcFlag(sufficientFundCheck);
976                         oleInvoiceForm.setSfcFailRouteMsg(OLEConstants.INV_INSUFF_FUND +accLine.getAccountNumber());
977                         return getUIFModelAndView(oleInvoiceForm);
978                     }
979                 }
980             }
981         }
982         boolean duplicationExists = false;
983         duplicationExists = getInvoiceService().isDuplicationExists(oleInvoiceDocument,oleInvoiceForm,false);
984         if (duplicationExists) {
985             oleInvoiceDocument.setDuplicateRouteFlag(true);
986             return getUIFModelAndView(form);
987         }
988         oleInvoiceDocument.setDuplicateRouteFlag(false);
989         if(oleInvoiceDocument.isValidationFlag() || oleInvoiceDocument.isSubscriptionDateValidationFlag()){
990             return getUIFModelAndView(oleInvoiceForm);
991         }
992 
993         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
994         ModelAndView mv =  super.route(oleInvoiceForm,result,request,response);
995         oleInvoiceDocument.loadInvoiceDocument();
996         if(GlobalVariables.getMessageMap().getErrorMessages().size() > 0){
997             return  mv;
998         }
999         return closeDocument(oleInvoiceForm,result,request,response);
1000 
1001         /*
1002         if (oleInvoiceDocument.getDocumentHeader() != null && oleInvoiceDocument.getDocumentHeader().getWorkflowDocument() != null &&
1003                 oleInvoiceDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
1004             if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
1005                 fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
1006                 if (fundCheckFlag) {
1007                     return getUIFModelAndView(form);
1008                 }
1009             }
1010             performWorkflowAction(form, UifConstants.WorkflowAction.ROUTE, true);
1011             return getUIFModelAndView(oleInvoiceForm);
1012         } else {
1013             SpringContext.getBean(OleInvoiceService.class).populateInvoiceFromPurchaseOrders(oleInvoiceDocument, null);
1014             if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
1015                 fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
1016                 if (fundCheckFlag) {
1017                     return getUIFModelAndView(form);
1018                 }
1019             }
1020             performWorkflowAction(form, UifConstants.WorkflowAction.ROUTE, true);
1021         }
1022         return getUIFModelAndView(oleInvoiceForm);*/
1023     }
1024 
1025 
1026     @RequestMapping(params = "methodToCall=continueDuplicateRoute")
1027     public ModelAndView continueDuplicateRoute(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1028                                                HttpServletRequest request, HttpServletResponse response) throws Exception {
1029         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1030         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1031         oleInvoiceForm.setDuplicationMessage(null);
1032         oleInvoiceDocument.setDuplicateRouteFlag(false);
1033         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1034         ModelAndView mv = super.route(oleInvoiceForm, result, request, response);
1035         oleInvoiceDocument.loadInvoiceDocument();
1036         if(GlobalVariables.getMessageMap().getErrorMessages().size() > 0){
1037             return  mv;
1038         }
1039         return closeDocument(oleInvoiceForm, result, request, response);
1040     }
1041 
1042     @RequestMapping(params = "methodToCall=continueRoute")
1043     public ModelAndView continueRoute(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1044                                       HttpServletRequest request, HttpServletResponse response) {
1045         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1046         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1047         oleInvoiceDocument.setSfcFlag(false);
1048         oleInvoiceForm.setValidationMessage(null);
1049         oleInvoiceDocument.setValidationFlag(false);
1050         String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(oleInvoiceDocument);
1051         if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
1052             oleInvoiceForm.setSubscriptionDateValidationMessage(subscriptionValidationMessage);
1053             oleInvoiceDocument.setSubscriptionDateValidationFlag(true);
1054         }
1055         if(oleInvoiceDocument.isSubscriptionDateValidationFlag()) {
1056             return getUIFModelAndView(form);
1057         }
1058         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
1059         if (!validationMessage.isEmpty() && validationMessage != null){
1060             oleInvoiceForm.setValidationMessage(validationMessage);
1061             oleInvoiceDocument.setValidationFlag(true);
1062         }
1063         else {
1064             oleInvoiceDocument.setValidationFlag(false);
1065             performWorkflowAction(form, UifConstants.WorkflowAction.ROUTE, true);
1066         }
1067         if(GlobalVariables.getMessageMap().getErrorMessages().size() > 0){
1068             return getUIFModelAndView(form);
1069         }
1070         return closeDocument(oleInvoiceForm, result, request, response);
1071     }
1072 
1073     @RequestMapping(params = "methodToCall=cancelRoute")
1074     public ModelAndView cancelRoute(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1075                                     HttpServletRequest request, HttpServletResponse response) {
1076         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1077         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1078         oleInvoiceDocument.setSfcFlag(false);
1079         oleInvoiceForm.setSfcFailRouteMsg(null);
1080         return getUIFModelAndView(form);
1081     }
1082 
1083 
1084     public static OleInvoiceService getInvoiceService() {
1085         if (invoiceService == null) {
1086             invoiceService = SpringContext.getBean(OleInvoiceService.class);
1087         }
1088         return invoiceService;
1089     }
1090 
1091     /**
1092      * Performs the blanket approve workflow action on the form document instance
1093      *
1094      * @param form - document form base containing the document instance that will be blanket approved
1095      * @return ModelAndView
1096      */
1097     @RequestMapping(params = "methodToCall=blanketApprove")
1098     public ModelAndView blanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1099                                        HttpServletRequest request, HttpServletResponse response) throws Exception {
1100         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1101 
1102         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1103         oleInvoiceDocument.setBlanketApproveValidationFlag(false);
1104         oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(false);
1105         oleInvoiceDocument.setDbRetrieval(false);
1106         OleInvoiceItemService oleInvoiceItemService = (OleInvoiceItemService) SpringContext
1107                 .getBean("oleInvoiceItemService");
1108         OleInvoiceFundCheckService oleInvoiceFundCheckService = (OleInvoiceFundCheckService) SpringContext
1109                 .getBean("oleInvoiceFundCheckService");
1110         if(!(SpringContext.getBean(OleInvoiceService.class).validateDepositAccount(oleInvoiceDocument))){
1111             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID,
1112                     PurapKeyConstants.ERROR_INVALID_DEPOSIT_ACCT);
1113             return getUIFModelAndView(oleInvoiceForm);
1114         }
1115         if(! (oleInvoiceDocument.getItems().size() > 0 )){
1116             GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OleSelectConstant.ERROR_ATLEAST_ONE_ITEM_QTY_REQUIRED);
1117             return getUIFModelAndView(oleInvoiceForm);
1118         }
1119         if (!validateRequiredFields(oleInvoiceDocument,true)) {
1120             return getUIFModelAndView(oleInvoiceForm);
1121         }
1122         try {
1123             SpringContext.getBean(OleInvoiceService.class).populateInvoiceDocument(oleInvoiceDocument);
1124             calculate(oleInvoiceForm, result, request, response);
1125         } catch (Exception e) {
1126             LOG.error("Exception while calculating the document"+e);
1127             throw new RuntimeException(e);
1128         }
1129         oleInvoiceDocument.setNoteLine1Text(oleInvoiceDocument.getInvoiceNumber());
1130         List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = oleInvoiceDocument.getPurchaseOrderDocuments();
1131         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) {
1132             List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = oleInvoiceItemService.getOlePurchaseOrderLineForInvoice(olePurchaseOrderDocument);
1133             olePurchaseOrderDocument.setOlePurchaseOrderLineForInvoiceList(olePurchaseOrderLineForInvoiceList);
1134             List<OlePurchaseOrderTotal> olePurchaseOrderTotalList = oleInvoiceItemService.getOlePurchaseOrderTotal(olePurchaseOrderDocument);
1135             olePurchaseOrderDocument.setPurchaseOrderTotalList(olePurchaseOrderTotalList);
1136         }
1137         boolean duplicationExists = false;
1138         duplicationExists = getInvoiceService().isDuplicationExists(oleInvoiceDocument,oleInvoiceForm,true);
1139         if (duplicationExists) {
1140             oleInvoiceDocument.setDuplicateApproveFlag(true);
1141             return getUIFModelAndView(form);
1142         }
1143         oleInvoiceDocument.setDuplicateApproveFlag(false);
1144         boolean amountExceedsForBlanketApprove = false;
1145         amountExceedsForBlanketApprove = getInvoiceService().isNotificationRequired(oleInvoiceDocument);
1146         if (amountExceedsForBlanketApprove) {
1147             oleInvoiceForm.setAmountExceedsMesgForBlankApp(getInvoiceService().createInvoiceAmountExceedsThresholdText(oleInvoiceDocument));
1148             oleInvoiceDocument.setAmountExceedsForBlanketApprove(true);
1149             return getUIFModelAndView(form);
1150         }
1151         boolean fundCheckFlag = false;
1152         if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
1153             fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
1154             if (fundCheckFlag || oleInvoiceDocument.isBlanketApproveValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()) {
1155                 return getUIFModelAndView(form);
1156             }
1157         }
1158             String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(oleInvoiceDocument);
1159             if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
1160                 oleInvoiceForm.setSubscriptionValidationMessage(subscriptionValidationMessage);
1161                 oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(true);
1162             }
1163         if (oleInvoiceDocument.getItems() != null && oleInvoiceDocument.getItems().size() > 4 ) {
1164             String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
1165             if (!validationMessage.isEmpty() && validationMessage != null){
1166                 oleInvoiceForm.setValidationMessage(validationMessage);
1167                 oleInvoiceDocument.setBlanketApproveValidationFlag(true);
1168             }
1169         }
1170         if(oleInvoiceDocument.getSourceAccountingLines().size() > 0){
1171             List<SourceAccountingLine> sourceAccountingLineList = oleInvoiceDocument.getSourceAccountingLines();
1172             for (SourceAccountingLine accLine : sourceAccountingLineList) {
1173                 Map searchMap = new HashMap();
1174                 String notificationOption = null;
1175                 boolean sufficientFundCheck;
1176                 Map<String, Object> key = new HashMap<String, Object>();
1177                 String chartCode = accLine.getChartOfAccountsCode();
1178                 String accNo = accLine.getAccountNumber();
1179                 String objectCd = accLine.getFinancialObjectCode();
1180                 key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
1181                 key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
1182                 OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
1183                         OleSufficientFundCheck.class, key);
1184                 if (account != null) {
1185                     notificationOption = account.getNotificationOption();
1186                 }
1187                 if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.WARNING_MSG)) {
1188                     if(oleInvoiceDocument.getPaymentMethodIdentifier() != null && (SpringContext.getBean(OleInvoiceService.class).getPaymentMethodType(oleInvoiceDocument.getPaymentMethodIdentifier())).equals(OLEConstants.DEPOSIT)) {
1189                         sufficientFundCheck = false;
1190                     }else{
1191                         sufficientFundCheck = oleInvoiceFundCheckService.hasSufficientFundCheckRequired(accLine);
1192                     }
1193                     if (sufficientFundCheck) {
1194                         oleInvoiceDocument.setBaSfcFlag(sufficientFundCheck);
1195                         oleInvoiceForm.setSfcFailApproveMsg(OLEConstants.INV_INSUFF_FUND+accLine.getAccountNumber());
1196                         return getUIFModelAndView(oleInvoiceForm);
1197                     }
1198                 }
1199             }
1200         }
1201 
1202         /*if (oleInvoiceDocument.getDocumentHeader() != null && oleInvoiceDocument.getDocumentHeader().getWorkflowDocument() != null &&
1203                 !oleInvoiceDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
1204             SpringContext.getBean(OleInvoiceService.class).populateInvoiceFromPurchaseOrders(oleInvoiceDocument, null);
1205 
1206             boolean fundCheckFlag = false;
1207             if (oleInvoiceDocument.getSourceAccountingLines().size() > 0) {
1208                 fundCheckFlag = oleInvoiceFundCheckService.isBudgetReviewRequired(oleInvoiceDocument);
1209                 if (fundCheckFlag) {
1210                     return getUIFModelAndView(form);
1211                 }
1212             }
1213         }*/
1214 
1215 
1216 
1217         if(oleInvoiceDocument.isBlanketApproveValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()){
1218             return getUIFModelAndView(oleInvoiceForm);
1219         }
1220 
1221        /* try {
1222             calculate(oleInvoiceForm,result,request,response);
1223         }   catch(Exception e) {
1224             LOG.error("Error while calculating Invoice Document");
1225             throw new RuntimeException(e);
1226         }*/
1227         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1228         super.blanketApprove(oleInvoiceForm, result, request, response);
1229         oleInvoiceDocument.loadInvoiceDocument();
1230         if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
1231             oleInvoiceDocument.setUnsaved(false);
1232             return getUIFModelAndView(oleInvoiceForm);
1233         }
1234         GlobalVariables.getMessageMap().clearErrorMessages();
1235         oleInvoiceDocument.setUnsaved(false);
1236         //return getUIFModelAndView(oleInvoiceForm);
1237         return closeDocument(oleInvoiceForm,result,request,response);
1238     }
1239 
1240 
1241     @RequestMapping(params = "methodToCall=continueBlanketApprove")
1242     public ModelAndView continueBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1243                                                HttpServletRequest request, HttpServletResponse response)  throws Exception{
1244         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1245         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1246         oleInvoiceDocument.setDuplicateApproveFlag(false);
1247         oleInvoiceDocument.setBaSfcFlag(false);
1248         oleInvoiceDocument.setBlanketApproveValidationFlag(false);
1249         String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(oleInvoiceDocument);
1250         if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
1251             oleInvoiceForm.setSubscriptionValidationMessage(subscriptionValidationMessage);
1252             oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(true);
1253         }
1254         if(oleInvoiceDocument.isValidationFlag() || oleInvoiceDocument.isBlanketApproveValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()){
1255             return getUIFModelAndView(oleInvoiceForm);
1256         }
1257        String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
1258         if (!validationMessage.isEmpty() && validationMessage != null){
1259             oleInvoiceForm.setValidationMessage(validationMessage);
1260             oleInvoiceDocument.setBlanketApproveValidationFlag(true);
1261         }
1262         else {
1263             oleInvoiceDocument.setBlanketApproveValidationFlag(false);
1264             getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1265             super.blanketApprove(oleInvoiceForm, result, request, response);
1266             if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
1267                 return getUIFModelAndView(oleInvoiceForm);
1268             }
1269             oleInvoiceDocument.setUnsaved(false);
1270             //GlobalVariables.getMessageMap().clearErrorMessages();
1271             return closeDocument(form,result,request,response);
1272         }
1273         if(oleInvoiceDocument.isValidationFlag() || oleInvoiceDocument.isBlanketApproveValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()){
1274             return getUIFModelAndView(oleInvoiceForm);
1275         }
1276         return closeDocument(oleInvoiceForm, result, request, response);
1277     }
1278 
1279     @RequestMapping(params = "methodToCall=cancelBlanketApprove")
1280     public ModelAndView cancelBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1281                                              HttpServletRequest request, HttpServletResponse response) {
1282         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1283         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1284         oleInvoiceDocument.setBaSfcFlag(false);
1285         oleInvoiceForm.setSfcFailApproveMsg(null);
1286         return getUIFModelAndView(form);
1287     }
1288 
1289     @RequestMapping(params = "methodToCall=continueInvoiceRoute")
1290     public ModelAndView continueInvoiceRoute(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1291                                              HttpServletRequest request, HttpServletResponse response)  throws Exception{
1292         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1293         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1294         oleInvoiceDocument.setValidationFlag(false);
1295         boolean duplicationExists =  getInvoiceService().isDuplicationExists(oleInvoiceDocument,oleInvoiceForm,true);
1296         if (duplicationExists){
1297             oleInvoiceDocument.setDuplicateRouteFlag(true);
1298         }
1299         else {
1300             oleInvoiceDocument.setValidationFlag(false);
1301             performWorkflowAction(form, UifConstants.WorkflowAction.ROUTE, true);
1302         }
1303         if(GlobalVariables.getMessageMap().getErrorMessages().size() > 0){
1304             return getUIFModelAndView(form);
1305         }
1306         return closeDocument(oleInvoiceForm, result, request, response);
1307     }
1308 
1309     @RequestMapping(params = "methodToCall=cancelInvoiceRoute")
1310     public ModelAndView cancelInvoiceRoute(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1311                                            HttpServletRequest request, HttpServletResponse response) {
1312         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1313         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1314         oleInvoiceDocument.setValidationFlag(false);
1315         oleInvoiceForm.setValidationMessage(null);
1316         oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(false);
1317         oleInvoiceForm.setSubscriptionValidationMessage(null);
1318 
1319         return getUIFModelAndView(form);
1320     }
1321 
1322     @RequestMapping(params = "methodToCall=continueInvoiceSubscriptionApprove")
1323     public ModelAndView continueInvoiceSubscriptionApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1324                                       HttpServletRequest request, HttpServletResponse response) {
1325         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1326         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1327         oleInvoiceDocument.setSfcFlag(false);
1328         oleInvoiceDocument.setSubscriptionDateValidationFlag(false);
1329 
1330         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
1331         if (!validationMessage.isEmpty() && validationMessage != null){
1332             oleInvoiceForm.setValidationMessage(validationMessage);
1333             oleInvoiceDocument.setValidationFlag(true);
1334         }
1335         else {
1336             oleInvoiceDocument.setValidationFlag(false);
1337             performWorkflowAction(form, UifConstants.WorkflowAction.ROUTE, true);
1338         }
1339         return getUIFModelAndView(form);
1340     }
1341 
1342     @RequestMapping(params = "methodToCall=cancelInvoiceSubscriptionApprove")
1343     public ModelAndView cancelInvoiceSubscriptionApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1344                                     HttpServletRequest request, HttpServletResponse response) {
1345         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1346         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1347         oleInvoiceDocument.setSfcFlag(false);
1348         oleInvoiceForm.setSfcFailRouteMsg(null);
1349         return getUIFModelAndView(form);
1350     }
1351 
1352 
1353     @RequestMapping(params = "methodToCall=continueInvoiceBlanketApprove")
1354     public ModelAndView continueInvoiceBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1355                                                       HttpServletRequest request, HttpServletResponse response)  throws Exception{
1356         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1357         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1358         oleInvoiceDocument.setValidationFlag(false);
1359         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1360         super.blanketApprove(oleInvoiceForm, result, request, response);
1361         if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
1362             return getUIFModelAndView(oleInvoiceForm);
1363         }
1364         GlobalVariables.getMessageMap().clearErrorMessages();
1365         return closeDocument(oleInvoiceForm, result, request, response);
1366     }
1367 
1368     @RequestMapping(params = "methodToCall=cancelInvoiceBlanketApprove")
1369     public ModelAndView cancelInvoiceBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1370                                                     HttpServletRequest request, HttpServletResponse response) {
1371         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1372         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1373         oleInvoiceDocument.setValidationFlag(false);
1374         oleInvoiceForm.setValidationMessage(null);
1375         return getUIFModelAndView(form);
1376     }
1377 
1378     @RequestMapping(params = "methodToCall=continueInvoiceSubscriptionBlanketApprove")
1379     public ModelAndView continueInvoiceSubscriptionBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1380                                                       HttpServletRequest request, HttpServletResponse response)  throws Exception{
1381         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1382         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1383         oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(false);
1384         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
1385         if (!validationMessage.isEmpty() && validationMessage != null){
1386             oleInvoiceForm.setValidationMessage(validationMessage);
1387             oleInvoiceDocument.setValidationFlag(true);
1388             oleInvoiceDocument.setBlanketApproveValidationFlag(true);
1389         }
1390         else {
1391             oleInvoiceDocument.setBlanketApproveValidationFlag(false);
1392             getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1393             super.blanketApprove(oleInvoiceForm, result, request, response);
1394             if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
1395                 return getUIFModelAndView(oleInvoiceForm);
1396             }
1397             oleInvoiceDocument.setUnsaved(false);
1398             //GlobalVariables.getMessageMap().clearErrorMessages();
1399             return closeDocument(form,result,request,response);
1400         }
1401         if(oleInvoiceDocument.isValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()){
1402             return getUIFModelAndView(oleInvoiceForm);
1403         }
1404         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
1405         super.blanketApprove(oleInvoiceForm, result, request, response);
1406         if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
1407             oleInvoiceDocument.setUnsaved(false);
1408             return getUIFModelAndView(oleInvoiceForm);
1409         }
1410         GlobalVariables.getMessageMap().clearErrorMessages();
1411         oleInvoiceDocument.setUnsaved(false);
1412         return closeDocument(oleInvoiceForm,result,request,response);
1413     }
1414 
1415     @RequestMapping(params = "methodToCall=cancelInvoiceSubscriptionBlanketApprove")
1416     public ModelAndView cancelInvoiceSubscriptionBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1417                                                     HttpServletRequest request, HttpServletResponse response) {
1418         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1419         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1420         oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(false);
1421         oleInvoiceForm.setSubscriptionValidationMessage(null);
1422         return getUIFModelAndView(form);
1423     }
1424 
1425     /**
1426      * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#loadDocument(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase)
1427      */
1428     @Override
1429     protected void loadDocument(DocumentFormBase formBase) throws WorkflowException {
1430         OLEInvoiceForm invoiceForm = (OLEInvoiceForm) formBase;
1431         super.loadDocument(invoiceForm);
1432         OleInvoiceDocument invoiceDocument = (OleInvoiceDocument) invoiceForm.getDocument();
1433         //invoiceDocument.setItems(new ArrayList());
1434         OLEInvoiceDaoOjb oleInvoiceDaoOjb = (OLEInvoiceDaoOjb)SpringContext.getBean("oleInvoiceDao");
1435         invoiceDocument.setDbRetrieval(true);
1436         invoiceDocument.setGrantTotal(oleInvoiceDaoOjb.getInvoiceTotal(invoiceDocument.getPurapDocumentIdentifier(),null ).toString());
1437         invoiceDocument.setItemTotal(oleInvoiceDaoOjb.getInvoiceTotal(invoiceDocument.getPurapDocumentIdentifier(), "ITEM").toString());
1438         if (invoiceDocument.getInvoiceCurrencyTypeId()!=null) {
1439             String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyTypeId().toString());
1440             if (StringUtils.isNotBlank(currencyType)) {
1441                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1442                     invoiceDocument.setForeignGrandTotal(oleInvoiceDaoOjb.getForeignInvoiceTotal(invoiceDocument.getPurapDocumentIdentifier(),null ).toString());
1443                     invoiceDocument.setForeignItemTotal(oleInvoiceDaoOjb.getForeignInvoiceTotal(invoiceDocument.getPurapDocumentIdentifier(), "ITEM").toString());
1444                 }   else {
1445                     invoiceDocument.setForeignGrandTotal(OLEConstants.EMPTY_STRING);
1446                     invoiceDocument.setForeignItemTotal(OLEConstants.EMPTY_STRING);
1447                 }
1448             }
1449         }
1450         invoiceDocument.setDocumentTotalAmount(invoiceDocument.getGrantTotal());
1451         // refresh the account summary (note this also updates the account amounts)
1452         invoiceDocument.refreshAccountSummmary();
1453 
1454         // Sorting the purchase order item base on item identifier. Modified for Jira OLE-5297
1455         Collections.sort(invoiceDocument.getItems(),new Comparator<OleInvoiceItem>(){
1456             public int compare(OleInvoiceItem item1,OleInvoiceItem item2){
1457                 if(item1.getSequenceNumber() != null && item2.getSequenceNumber() != null) {
1458                     return item1.getSequenceNumber().compareTo(item2.getSequenceNumber());
1459                 }
1460                 return 0;
1461             }
1462         });
1463 
1464 
1465         for (org.kuali.rice.krad.bo.Note note : (java.util.List<org.kuali.rice.krad.bo.Note>) invoiceDocument.getNotes()) {
1466             note.refreshReferenceObject("attachment");
1467         }
1468 
1469         // sort the below the line
1470         SpringContext.getBean(PurapService.class).sortBelowTheLine(invoiceDocument);
1471     }
1472 
1473     /**
1474      * This method to refresh the account summary.
1475      */
1476     @RequestMapping(params = "methodToCall=refreshAccountSummary")
1477     public ModelAndView refreshAccountSummary(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1478                                               HttpServletRequest request, HttpServletResponse response) throws Exception {
1479         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1480         OleInvoiceDocument document = (OleInvoiceDocument) form.getDocument();
1481         SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(document);
1482         document.refreshAccountSummmary();
1483         document.setUnsaved(false);
1484         return getUIFModelAndView(form);
1485     }
1486 
1487     @RequestMapping(params = "methodToCall=proratedSurchargeRefresh")
1488     public ModelAndView proratedSurchargeRefresh(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1489                                                  HttpServletRequest request, HttpServletResponse response) {
1490         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1491         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1492         oleInvoiceDocument.setDbRetrieval(false);
1493         OlePurapAccountingService olePurapAccountingService = new OlePurapAccountingServiceImpl();
1494         boolean canProrate = false;
1495         KualiDecimal totalAmt = oleInvoiceDocument.getInvoicedItemTotal() != null ?
1496                 new KualiDecimal(oleInvoiceDocument.getInvoicedItemTotal()) : KualiDecimal.ZERO;
1497         if(SpringContext.getBean(OleInvoiceService.class).getPaymentMethodType(oleInvoiceDocument.getPaymentMethodIdentifier()).equals(OLEConstants.DEPOSIT))       {
1498             for(OleInvoiceItem item : (List<OleInvoiceItem>)oleInvoiceDocument.getItems()){
1499                 if(item.getItemTypeCode().equals("ITEM")){
1500                     if(item.getSourceAccountingLineList().size() <=0){
1501                         GlobalVariables.getMessageMap().putError(PurapPropertyConstants.OFFSET_ACCT_LINE, OLEKeyConstants.ERROR_REQUIRED, PurapConstants.PRQSDocumentsStrings.OFFSET_ACCT_LINE);
1502                         return getUIFModelAndView(oleInvoiceForm);
1503                     }
1504 
1505                 }
1506             }
1507         }
1508         for (InvoiceItem item : (List<InvoiceItem>) oleInvoiceDocument.getItems()) {
1509             if (item.getItemType().isAdditionalChargeIndicator()) {
1510                 List<PurApItem> items = new ArrayList<>();
1511                 BigDecimal exchangeRate;
1512                 if (items.size() == 0) {
1513                     for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
1514                         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
1515                             String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
1516                             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1517                                 if (StringUtils.isNotBlank(invoiceItem.getAdditionalForeignUnitCost()) && invoiceItem.getItemType().isAdditionalChargeIndicator()) {
1518                                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
1519                                         try {
1520                                             Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1521                                             exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1522                                             if (new KualiDecimal(exchangeRate).isZero()) {
1523                                                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1524                                                 return getUIFModelAndView(oleInvoiceForm);
1525                                             }
1526                                             oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
1527                                         }
1528                                         catch (NumberFormatException nfe) {
1529                                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1530                                             return getUIFModelAndView(oleInvoiceForm);
1531                                         }
1532                                     }  else {
1533                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
1534                                         return getUIFModelAndView(oleInvoiceForm);
1535                                     }
1536                                     KualiDecimal itemUnitPrice = new KualiDecimal((new BigDecimal(invoiceItem.getAdditionalForeignUnitCost()).
1537                                             divide(new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate()), 4, RoundingMode.HALF_UP)));
1538                                     if (!itemUnitPrice.bigDecimalValue().equals(invoiceItem.getItemUnitPrice())) {
1539                                         invoiceItem.setItemUnitPrice((new BigDecimal(invoiceItem.getAdditionalForeignUnitCost()).
1540                                                 divide(new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate()), 4, RoundingMode.HALF_UP)).abs());
1541                                     }
1542                                 }   else if (StringUtils.isBlank(invoiceItem.getAdditionalForeignUnitCost()) && invoiceItem.getItemType().isAdditionalChargeIndicator()) {
1543                                     invoiceItem.setItemUnitPrice(null);
1544                                 }
1545                             }
1546                         }
1547                         if (invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator() && invoiceItem.getItemUnitPrice().compareTo(BigDecimal.ZERO) != 0 ) {
1548                             canProrate = true;
1549                         }
1550                         items.add(invoiceItem);
1551                     }
1552                 }
1553                 else {
1554                     for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
1555                         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
1556                             String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
1557                             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1558                                 if (StringUtils.isNotBlank(invoiceItem.getAdditionalForeignUnitCost()) && invoiceItem.getItemType().isAdditionalChargeIndicator()) {
1559                                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
1560                                         try {
1561                                             Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1562                                             exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1563                                             if (new KualiDecimal(exchangeRate).isZero()) {
1564                                                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1565                                                 return getUIFModelAndView(oleInvoiceForm);
1566                                             }
1567                                             oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
1568                                         }
1569                                         catch (NumberFormatException nfe) {
1570                                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1571                                             return getUIFModelAndView(oleInvoiceForm);
1572                                         }
1573                                     }  else {
1574                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
1575                                         return getUIFModelAndView(oleInvoiceForm);
1576                                     }
1577                                     invoiceItem.setItemUnitPrice(invoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(exchangeRate.setScale(2, RoundingMode.HALF_UP)));
1578 
1579                                 }
1580                             }
1581                         }
1582                         if (!(invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator()) && invoiceItem.getItemUnitPrice().compareTo(BigDecimal.ZERO) != 0 ) {
1583                             canProrate = true;
1584                             items.add(invoiceItem);
1585                         }
1586                     }
1587                 }
1588                 if ((totalAmt.isZero() || !canProrate)&& oleInvoiceDocument.isProrateDollar() ) {
1589                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ADDITIONAL_CHARGE_SECTION_ID,
1590                             OLEKeyConstants.ERROR_PRORATE_DOLLAR_ZERO_ITEM_TOTAL);
1591                     oleInvoiceDocument.setProrateDollar(false);
1592                     oleInvoiceDocument.setProrateManual(false);
1593                     oleInvoiceDocument.setProrateQty(false);
1594                     oleInvoiceDocument.setNoProrate(false);
1595                     oleInvoiceDocument.setProrateBy(null);
1596                     for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
1597                         if (invoiceItem.getItemType().isAdditionalChargeIndicator()) {
1598                             invoiceItem.setSourceAccountingLines(new ArrayList<PurApAccountingLine>());
1599                         }
1600                     }
1601                     return getUIFModelAndView(oleInvoiceForm);
1602                 }
1603                 List<PurApAccountingLine> distributedAccounts = null;
1604                 List<SourceAccountingLine> summaryAccounts = null;
1605                 summaryAccounts = olePurapAccountingService.generateSummaryForManual(items);
1606                 distributedAccounts = olePurapAccountingService.generateAccountDistributionForProrationByManual(summaryAccounts,InvoiceAccount.class);
1607                 if (CollectionUtils.isNotEmpty(distributedAccounts)) {
1608                     item.setSourceAccountingLines(distributedAccounts);
1609                 }
1610                 if(oleInvoiceDocument.isNoProrate() && item.getItemType().isAdditionalChargeIndicator()){
1611                     item.setSourceAccountingLines(new ArrayList<PurApAccountingLine>());
1612                 }
1613                 else if (oleInvoiceDocument.isProrateDollar() || oleInvoiceDocument.isProrateQty()) {
1614                     SpringContext.getBean(OleInvoiceService.class).calculateInvoice(oleInvoiceDocument, true);
1615                 }
1616                 for(PurApAccountingLine oldSourceAccountingLine:item.getSourceAccountingLines()) {
1617                     if(oldSourceAccountingLine instanceof InvoiceAccount) {
1618                         ((InvoiceAccount)oldSourceAccountingLine).setExistingAmount(oldSourceAccountingLine.getAmount());
1619                     }
1620                 }
1621             }
1622 
1623         }
1624         return getUIFModelAndView(oleInvoiceForm);   /*,"OLEInvoiceView-MainPage"*/
1625     }
1626 
1627     @RequestMapping(params = "methodToCall=deletePO")
1628     public ModelAndView deletePurchaseOrder(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1629                                             HttpServletRequest request, HttpServletResponse response) {
1630         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1631         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1632         oleInvoiceDocument.setDbRetrieval(false);
1633         String focusId = oleInvoiceForm.getFocusId();
1634         String s = focusId.substring(focusId.length() - 1, focusId.length());
1635         int deleteDocument = Integer.parseInt(s);
1636         List<OlePurchaseOrderDocument> olePurchaseOrderDocument = oleInvoiceDocument.getPurchaseOrderDocuments();
1637         olePurchaseOrderDocument.remove(deleteDocument);
1638         oleInvoiceDocument.setPurchaseOrderDocuments(olePurchaseOrderDocument);
1639         return getUIFModelAndView(oleInvoiceForm);
1640     }
1641 
1642 
1643     @RequestMapping(params = "methodToCall=fillInvoiceNumber")
1644     public ModelAndView fillInvoiceNumber(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1645                                           HttpServletRequest request, HttpServletResponse response) {
1646         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1647         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1648         oleInvoiceDocument.setNoteLine1Text(oleInvoiceDocument.getInvoiceNumber());
1649         return getUIFModelAndView(oleInvoiceForm);
1650     }
1651 
1652     @RequestMapping(params = "methodToCall=refreshCurrentItem")
1653     public ModelAndView refreshCurrentItem(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1654                                            HttpServletRequest request, HttpServletResponse response) throws Exception {
1655         return navigate(form, result, request, response);
1656     }
1657 
1658 
1659     /**
1660      * Called by the add line action for a new collection line. Method
1661      * determines which collection the add action was selected for and invokes
1662      * the view helper service to add the line
1663      */
1664     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addSourceAccountingLine")
1665     public ModelAndView addSourceAccountingLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
1666                                                 HttpServletRequest request, HttpServletResponse response) {
1667         LOG.debug("Inside addSourceAccountingLine()");
1668         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
1669         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1670         boolean rulePassed = true;
1671         boolean flag = false;
1672         PurApItem item = null;
1673         String errorPrefix = null;
1674         String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1675         if (StringUtils.isBlank(selectedCollectionPath)) {
1676             throw new RuntimeException("Selected collection was not set for add line action, cannot add new line");
1677         }
1678         CollectionGroup collectionGroup = oleInvoiceForm.getPostedView().getViewIndex().getCollectionGroupByPath(
1679                 selectedCollectionPath);
1680         String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
1681         Object eventObject = ObjectPropertyUtils.getPropertyValue(oleInvoiceForm, addLinePath);
1682         InvoiceAccount invoiceAccount = (InvoiceAccount)eventObject;
1683         if (StringUtils.isEmpty(invoiceAccount.getChartOfAccountsCode())) {
1684             flag = true;
1685         }
1686         if (StringUtils.isEmpty(invoiceAccount.getAccountNumber())) {
1687             flag = true;
1688         }
1689         if (StringUtils.isEmpty(invoiceAccount.getFinancialObjectCode())) {
1690             flag = true;
1691         }
1692         int selectedLine = 0;
1693         if (StringUtils.isNotBlank(selectedCollectionPath)) {
1694             String lineNumber = StringUtils.substringBetween(selectedCollectionPath, ".items[", ".");
1695             String itemIndex = StringUtils.substringBefore(lineNumber,"]");
1696             if (!StringUtils.isEmpty(lineNumber)) {
1697                 selectedLine = Integer.parseInt(itemIndex);
1698             }
1699             errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(selectedLine) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
1700         }
1701         rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, oleInvoiceDocument, (AccountingLine)eventObject));
1702         if (!rulePassed || flag) {
1703             return getUIFModelAndView(uifForm);
1704         }
1705         View view = uifForm.getPostedView();
1706         view.getViewHelperService().processCollectionAddLine(view, uifForm, selectedCollectionPath);
1707         if (rulePassed) {
1708             item = oleInvoiceDocument.getItem((selectedLine));
1709             PurApAccountingLine lineItem = invoiceAccount;
1710             if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
1711                 if (lineItem.getAccountLinePercent() != null && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
1712                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1713                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1714                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero() && lineItem.getAccountLinePercent() == null) {
1715                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1716                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
1717                     lineItem.setAccountLinePercent(dollarToPercent);
1718                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero() && lineItem.getAccountLinePercent() == null) {
1719                     lineItem.setAccountLinePercent(new BigDecimal(0));
1720                 }
1721                 else if(lineItem.getAmount()!=null&& lineItem.getAccountLinePercent().intValue()== 100){
1722                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1723                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()),0,RoundingMode.FLOOR);
1724                     lineItem.setAccountLinePercent(dollarToPercent);
1725                 }
1726                 else if(lineItem.getAmount()!=null&&lineItem.getAccountLinePercent() != null){
1727                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1728                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1729                 }
1730             } else {
1731                 lineItem.setAmount(new KualiDecimal(0));
1732             }
1733             if(item.getItemType().isAdditionalChargeIndicator()) {
1734                 oleInvoiceDocument.setProrateBy(OLEConstants.NO_PRORATE);
1735                 oleInvoiceDocument.setNoProrate(true);
1736             }
1737 
1738         }
1739         LOG.debug("Leaving addSourceAccountingLine()");
1740         return getUIFModelAndView(uifForm);
1741     }
1742 
1743     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addPOAccountingLine")
1744     public ModelAndView addPOAccountingLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
1745                                             HttpServletRequest request, HttpServletResponse response) {
1746         LOG.debug("Inside addPOAccountingLine()");
1747         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
1748         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1749         boolean rulePassed = true;
1750         boolean flag = false;
1751         PurApItem item = null;
1752         String errorPrefix = null;
1753         String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1754         if (StringUtils.isBlank(selectedCollectionPath)) {
1755             throw new RuntimeException("Selected collection was not set for add line action, cannot add new line");
1756         }
1757         CollectionGroup collectionGroup = oleInvoiceForm.getPostedView().getViewIndex().getCollectionGroupByPath(
1758                 selectedCollectionPath);
1759         String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
1760         Object eventObject = ObjectPropertyUtils.getPropertyValue(oleInvoiceForm, addLinePath);
1761         OlePurchaseOrderAccount purchaseOrderAccount = (OlePurchaseOrderAccount) eventObject;
1762         if (StringUtils.isEmpty(purchaseOrderAccount.getChartOfAccountsCode())) {
1763             GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEInvoiceView_ProcessItems_AccountingLines, OLEConstants.ERROR_CHART_CODE_REQ,OLEConstants.OrderQueue.CHART_CODE);
1764             flag = true;
1765         }
1766         if (StringUtils.isEmpty(purchaseOrderAccount.getAccountNumber())) {
1767             GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEInvoiceView_ProcessItems_AccountingLines, OLEConstants.ERROR_ACC_NUMB_REQ,OLEConstants.ACC_NUM);
1768             flag = true;
1769         }
1770         if (StringUtils.isEmpty(purchaseOrderAccount.getFinancialObjectCode())) {
1771             GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEInvoiceView_ProcessItems_AccountingLines, OLEConstants.ERROR_OBJECT_CODE_REQ,OLEConstants.OrderQueue.OBJECT_CODE);
1772             flag = true;
1773         }
1774         int selectedLine = 0;
1775         if (StringUtils.isNotBlank(selectedCollectionPath)) {
1776             String lineNumber = StringUtils.substringBetween(selectedCollectionPath, ".items[", ".");
1777             String itemIndex = StringUtils.substringBefore(lineNumber, "]");
1778             if (!StringUtils.isEmpty(lineNumber)) {
1779                 selectedLine = Integer.parseInt(itemIndex);
1780             }
1781             errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(selectedLine) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
1782         }
1783         rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, oleInvoiceDocument, (AccountingLine) eventObject));
1784         if (!rulePassed || flag) {
1785             return getUIFModelAndView(uifForm);
1786         }
1787         View view = uifForm.getPostedView();
1788         view.getViewHelperService().processCollectionAddLine(view, uifForm, selectedCollectionPath);
1789         if (rulePassed) {
1790             item = oleInvoiceDocument.getItem((selectedLine));
1791             PurApAccountingLine lineItem = purchaseOrderAccount;
1792             if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
1793                 if (lineItem.getAccountLinePercent() != null && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
1794                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1795                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1796                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero() && lineItem.getAccountLinePercent() == null) {
1797                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1798                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
1799                     lineItem.setAccountLinePercent(dollarToPercent);
1800                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero() && lineItem.getAccountLinePercent() == null) {
1801                     lineItem.setAccountLinePercent(new BigDecimal(0));
1802                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent().intValue() == 100) {
1803                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
1804                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
1805                     lineItem.setAccountLinePercent(dollarToPercent);
1806                 } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() != null) {
1807                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
1808                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
1809                 }
1810             } else {
1811                 lineItem.setAmount(new KualiDecimal(0));
1812             }
1813             oleInvoiceDocument.setProrateBy(OLEConstants.NO_PRORATE);
1814             oleInvoiceDocument.setNoProrate(true);
1815         }
1816         LOG.debug("Leaving addPOAccountingLine()");
1817         return getUIFModelAndView(uifForm);
1818     }
1819 
1820     /**
1821      * Performs the disapprove workflow action on the form document instance
1822      *
1823      * @param form - document form base containing the document instance that will be disapproved
1824      * @return ModelAndView
1825      */
1826     @RequestMapping(params = "methodToCall=disapprove")
1827     public ModelAndView disapprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1828                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
1829         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1830         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1831 
1832         Note noteObj = getDocumentService().createNoteFromDocument(oleInvoiceDocument, "Dispproved at Budget Node By : " + GlobalVariables.getUserSession().getPerson().getName());
1833         PersistableBusinessObject noteParent = oleInvoiceDocument.getNoteTarget();
1834         List<Note> noteList = getNoteService().getByRemoteObjectId(noteParent.getObjectId());
1835         noteList.add(noteObj);
1836         getNoteService().saveNoteList(noteList);
1837         getNoteService().save(noteObj);
1838         oleInvoiceDocument.setNotes(noteList);
1839         getDocumentService().saveDocument(oleInvoiceDocument);
1840 
1841         performWorkflowAction(oleInvoiceForm, UifConstants.WorkflowAction.DISAPPROVE, true);
1842         return returnToPrevious(oleInvoiceForm);
1843 
1844     }
1845 
1846 
1847     /**
1848      * Called by the add line action for a new collection line. Method
1849      * determines which collection the add action was selected for and invokes
1850      * the view helper service to add the line
1851      */
1852     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addPoItems")
1853     public ModelAndView addPoItems(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
1854                                    HttpServletRequest request, HttpServletResponse response) {
1855         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
1856         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1857         oleInvoiceDocument.setCurrentItemsFlag(true);
1858         if(oleInvoiceDocument.getPaymentMethodIdentifier().equals("")){
1859             GlobalVariables.getMessageMap().putError(OleSelectConstant.PROCESS_ITEM_SECTION_ID, OLEKeyConstants.ERROR_NO_PAYMENT_MTHD);
1860             return getUIFModelAndView(oleInvoiceForm);
1861         }
1862         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
1863             String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
1864             BigDecimal exchangeRate = null;
1865             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1866                 if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
1867                     try {
1868                         Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1869                         exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1870                         if (new KualiDecimal(exchangeRate).isZero()) {
1871                             GlobalVariables.getMessageMap().putError(OleSelectConstant.PROCESS_ITEM_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1872                             return getUIFModelAndView(oleInvoiceForm);
1873                         }
1874                     }
1875                     catch (NumberFormatException nfe) {
1876                         GlobalVariables.getMessageMap().putError(OleSelectConstant.PROCESS_ITEM_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1877                         return getUIFModelAndView(oleInvoiceForm);
1878                     }
1879                 } else {
1880                     GlobalVariables.getMessageMap().putError(OleSelectConstant.PROCESS_ITEM_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
1881                     return getUIFModelAndView(oleInvoiceForm);
1882                 }
1883             }  else {
1884                 oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
1885                 oleInvoiceDocument.setForeignCurrencyFlag(false);
1886                 oleInvoiceDocument.setForeignVendorInvoiceAmount(null);
1887             }
1888         }
1889         getInvoiceService().convertPOItemToInvoiceItem(oleInvoiceDocument);
1890         try {
1891              calculate(oleInvoiceForm, result, request, response);
1892         } catch (Exception e) {
1893             LOG.error("Exception while calculating the document" + e);
1894             throw new RuntimeException(e);
1895         }
1896         if (oleInvoiceDocument.isProrateDollar() || oleInvoiceDocument.isProrateQty()) {
1897             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(oleInvoiceDocument, true);
1898         }
1899         List<OleInvoiceItem> oleInvoiceItems=new ArrayList<OleInvoiceItem>();
1900         List<OleInvoiceItem> oleInvoiceAdditionalItems=new ArrayList<OleInvoiceItem>();
1901         for(OleInvoiceItem oleInvoiceItem:(List<OleInvoiceItem>)oleInvoiceDocument.getItems()){
1902             if(oleInvoiceItem.getItemLineNumber()!=null){
1903                 if(oleInvoiceItem.getSequenceNumber() == null || oleInvoiceItem.getSequenceNumber() == 0){
1904                     int sequenceNumber = oleInvoiceDocument.getLineOrderSequenceNumber();
1905                     oleInvoiceDocument.setLineOrderSequenceNumber(++sequenceNumber);
1906                     oleInvoiceItem.setSequenceNumber(sequenceNumber);
1907                 }
1908                 oleInvoiceItems.add(oleInvoiceItem);
1909             } else {
1910                 oleInvoiceAdditionalItems.add(oleInvoiceItem);
1911               //  oleInvoiceItem.setAdditionalUnitPrice(oleInvoiceItem.getExtendedPrice() != null ? oleInvoiceItem.getExtendedPrice().toString() : "");
1912             }
1913         }
1914         oleInvoiceItems.addAll(oleInvoiceAdditionalItems);
1915         oleInvoiceDocument.setItems(oleInvoiceItems);
1916         OLEInvoiceOffsetAccountingLineVendor vendor = new OLEInvoiceOffsetAccountingLineVendor();
1917         vendor.setVendorName(oleInvoiceDocument.getVendorName());
1918         oleInvoiceDocument.setPoId("");
1919         return getUIFModelAndView(oleInvoiceForm);
1920     }
1921 
1922 
1923     public static boolean isNumeric(String value) {
1924         NumberFormat formatter = NumberFormat.getInstance();
1925         ParsePosition pos = new ParsePosition(0);
1926         formatter.parse(value, pos);
1927         return value.length() == pos.getIndex();
1928     }
1929 
1930     private static boolean isValidInteger(String value){
1931         try{
1932             Integer.parseInt(value);
1933         }catch(Exception e){
1934             return false;
1935         }
1936         return true;
1937     }
1938 
1939     @RequestMapping(params = "methodToCall=acknowledge")
1940     public ModelAndView acknowledge(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
1941                                     HttpServletRequest request, HttpServletResponse response) throws Exception {
1942         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
1943         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1944         Note noteObj = getDocumentService().createNoteFromDocument(oleInvoiceDocument, "Acknowledged at Budget Node By : " + GlobalVariables.getUserSession().getPerson().getName());
1945         PersistableBusinessObject noteParent = oleInvoiceDocument.getNoteTarget();
1946         List<Note> noteList = getNoteService().getByRemoteObjectId(noteParent.getObjectId());
1947         noteList.add(noteObj);
1948         getNoteService().saveNoteList(noteList);
1949         getNoteService().save(noteObj);
1950         oleInvoiceDocument.setNotes(noteList);
1951         getDocumentService().saveDocument(oleInvoiceDocument);
1952         performWorkflowAction(oleInvoiceForm, UifConstants.WorkflowAction.ACKNOWLEDGE, true);
1953         return returnToPrevious(oleInvoiceForm);
1954     }
1955 
1956     /**
1957      * This method updates the Invoice account based on the Invoice Price on the Item.
1958      */
1959     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=updatePrice")
1960     public ModelAndView updatePrice(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
1961                                     HttpServletRequest request, HttpServletResponse response) {
1962         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
1963         //boolean invoicePriceFlag = false;
1964         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
1965         for (OleInvoiceItem item : (List<OleInvoiceItem>)oleInvoiceDocument.getItems()) {
1966             /*if(new KualiDecimal(item.getInvoiceListPrice()).isLessThan(KualiDecimal.ZERO)){
1967                 invoicePriceFlag = true;
1968             }*/
1969             if (item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
1970                 if(StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())){
1971                     String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
1972                     if (StringUtils.isNotBlank(currencyType)) {
1973                         if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1974                             if (item.getItemDiscount() != null && item.getItemDiscountType() != null) {
1975                                 if(item.getItemDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)){
1976                                     BigDecimal discount = ((item.getItemListPrice().bigDecimalValue().multiply(item.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
1977                                     item.setItemUnitPrice(item.getItemListPrice().bigDecimalValue().subtract(discount));
1978                                 }else{
1979                                     item.setItemUnitPrice(((OleInvoiceItem)item).getItemListPrice().bigDecimalValue().subtract(item.getItemDiscount().bigDecimalValue()));
1980                                 }
1981                             }
1982                             else {
1983                                 item.setItemUnitPrice(((OleInvoiceItem)item).getItemListPrice().bigDecimalValue());
1984                             }
1985                         } else {
1986                             BigDecimal exchangeRate = null;
1987                             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
1988                                 try {
1989                                     Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1990                                     exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
1991                                     if (new KualiDecimal(exchangeRate).isZero()) {
1992                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1993                                         return getUIFModelAndView(oleInvoiceForm);
1994                                     }
1995                                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
1996                                 }
1997                                 catch (NumberFormatException nfe) {
1998                                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
1999                                     return getUIFModelAndView(oleInvoiceForm);
2000                                 }
2001                             }  else {
2002                                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
2003                                 return getUIFModelAndView(oleInvoiceForm);
2004                             }
2005                             if (item.getForeignDiscount() != null) {
2006                                 if(item.getItemForeignDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)){
2007                                     item.setItemForeignDiscount(new KualiDecimal(item.getForeignDiscount()));
2008                                     //item.setItemForeignListPrice(new KualiDecimal(new BigDecimal(item.getForeignListPrice())));
2009                                     BigDecimal discount = ((item.getItemForeignListPrice().bigDecimalValue().multiply(new BigDecimal(item.getForeignDiscount())))).divide(new BigDecimal(100));
2010                                     item.setItemForeignUnitCost(new KualiDecimal(item.getItemForeignListPrice().bigDecimalValue().subtract(discount)));
2011                                     item.setForeignUnitCost(item.getItemForeignUnitCost().toString());
2012                                 }else{
2013                                     item.setItemForeignDiscount(new KualiDecimal(item.getForeignDiscount()));
2014                                     item.setItemForeignListPrice(new KualiDecimal(item.getForeignListPrice()));
2015                                     item.setItemForeignUnitCost(new KualiDecimal(((OleInvoiceItem) item).getItemForeignListPrice().bigDecimalValue().subtract(item.getItemForeignDiscount().bigDecimalValue())));
2016                                     item.setForeignUnitCost(item.getItemForeignUnitCost().toString());
2017                                 }
2018                             }
2019                             else {
2020                                 item.setItemForeignListPrice(new KualiDecimal(item.getForeignListPrice()));
2021                                 item.setItemForeignUnitCost(new KualiDecimal(item.getItemForeignListPrice().bigDecimalValue()));
2022                             }
2023                         }
2024                     }
2025                 }
2026                 getInvoiceService().calculateAccount(item);
2027             }
2028         }
2029 
2030         try {
2031             calculate(oleInvoiceForm,result,request,response);
2032             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
2033                 String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
2034                 if (StringUtils.isNotBlank(currencyType)) {
2035                   //  if(invoicePriceFlag){
2036                         oleInvoiceDocument.setDbRetrieval(false);
2037                         oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
2038                         oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
2039                         if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2040                             oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
2041                             oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
2042                         }
2043                    /* }else{
2044                         oleInvoiceDocument.setDbRetrieval(false);
2045                         oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
2046                         oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
2047                         if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2048                             oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
2049                             oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
2050                         }
2051                         oleInvoiceDocument.setItemSign(true);
2052                     }*/
2053                 }
2054             }
2055         }
2056         catch (Exception e) {
2057             LOG.error("Exception while updating price"+e);
2058             throw new RuntimeException(e);
2059         }
2060         return getUIFModelAndView(oleInvoiceForm);
2061     }
2062 
2063 
2064     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=updatePOPrice")
2065     public ModelAndView updatePOPrice(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
2066                                     HttpServletRequest request, HttpServletResponse response) {
2067         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
2068         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2069         for (OlePurchaseOrderItem item : (List<OlePurchaseOrderItem>) oleInvoiceDocument.getPurchaseOrderDocuments().get(0).getItems()) {
2070             if (item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
2071                 if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
2072                     String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
2073                     if (StringUtils.isNotBlank(currencyType)) {
2074                         if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2075                             if (item.getItemDiscount() != null && item.getItemDiscountType() != null) {
2076                                 if (item.getItemDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
2077                                     BigDecimal discount = ((new BigDecimal(item.getInvoiceItemListPrice()).multiply(item.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
2078                                     item.setItemUnitPrice(new BigDecimal(item.getInvoiceItemListPrice()).subtract(discount));
2079                                 } else {
2080                                     item.setInvoiceItemListPrice(item.getInvoiceItemListPrice());
2081                                     item.setItemUnitPrice(new BigDecimal(((OlePurchaseOrderItem) item).getInvoiceItemListPrice()).subtract(item.getItemDiscount().bigDecimalValue()));
2082                                 }
2083                             } else {
2084                                 item.setItemUnitPrice(new BigDecimal(((OlePurchaseOrderItem) item).getInvoiceItemListPrice()));
2085                             }
2086                         } else {
2087                             BigDecimal exchangeRate = null;
2088                             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
2089                                 try {
2090                                     Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
2091                                     exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
2092                                     if (new KualiDecimal(exchangeRate).isZero()) {
2093                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
2094                                         return getUIFModelAndView(oleInvoiceForm);
2095                                     }
2096                                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
2097                                 } catch (NumberFormatException nfe) {
2098                                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
2099                                     return getUIFModelAndView(oleInvoiceForm);
2100                                 }
2101                             } else {
2102                                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
2103                                 return getUIFModelAndView(oleInvoiceForm);
2104                             }
2105                             if (item.getInvoiceForeignDiscount() != null && !item.getInvoiceForeignDiscount().equals("0.00")) {
2106                                 if (item.getInvoiceForeignDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
2107                                     item.setInvoiceForeignDiscount((item.getInvoiceForeignDiscount()));
2108                                     BigDecimal discount = (new BigDecimal(((OlePurchaseOrderItem) item).getInvoiceForeignItemListPrice())).multiply((new BigDecimal(item.getInvoiceForeignDiscount()))).divide(new BigDecimal(100));
2109                                     item.setInvoiceForeignUnitCost(new BigDecimal(item.getInvoiceForeignItemListPrice()).subtract(discount).toString());
2110                                     BigDecimal listPrice = new BigDecimal(item.getInvoiceForeignItemListPrice()).divide(exchangeRate, 2, RoundingMode.HALF_UP);
2111                                     item.setInvoiceItemListPrice(listPrice.subtract(listPrice.multiply(new BigDecimal(item.getInvoiceForeignDiscount()).divide(new BigDecimal(100)))).toString());
2112                                     item.setItemUnitPrice(new BigDecimal(item.getInvoiceItemListPrice()));
2113 
2114                                 } else {
2115                                     item.setInvoiceForeignDiscount((item.getInvoiceForeignDiscount()));
2116                                     BigDecimal discount = new BigDecimal(item.getInvoiceForeignDiscount());
2117                                     item.setInvoiceForeignUnitCost(new BigDecimal(item.getInvoiceForeignItemListPrice()).subtract(discount).toString());
2118                                     BigDecimal listPrice = new BigDecimal(item.getInvoiceForeignItemListPrice()).subtract(discount).divide(exchangeRate, 2, RoundingMode.HALF_UP);
2119                                     item.setInvoiceItemListPrice(listPrice.toString());
2120                                     item.setItemUnitPrice(listPrice);
2121                                 }
2122                             } else {
2123                                 item.setInvoiceForeignUnitCost((item.getInvoiceForeignItemListPrice()));
2124                                 BigDecimal listPrice = new BigDecimal(item.getInvoiceForeignItemListPrice()).divide(exchangeRate, 2, RoundingMode.HALF_UP);
2125                                 item.setInvoiceItemListPrice(listPrice.toString());
2126                                 item.setItemUnitPrice(listPrice);
2127                             }
2128                         }
2129                     }
2130                 }
2131                 getInvoiceService().calculateAccount(item);
2132             }
2133         }
2134 
2135         return getUIFModelAndView(oleInvoiceForm);
2136     }
2137 
2138     /**
2139      * To refresh POItems after lookup.
2140      *
2141      * @param form
2142      * @param result
2143      * @param request
2144      * @param response
2145      * @return
2146      * @throws Exception
2147      */
2148     @Override
2149     @RequestMapping(params = "methodToCall=refresh")
2150     public ModelAndView refresh(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2151                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
2152         OLEInvoiceForm invoiceForm = (OLEInvoiceForm) form;
2153         OleInvoiceDocument invoiceDocument = (OleInvoiceDocument)invoiceForm.getDocument();
2154 
2155        for(OleInvoiceItem item :( List<OleInvoiceItem>)invoiceDocument.getItems()){
2156            if(item.getTempItemIdentifier()!=null){
2157                Integer id = item.getTempItemIdentifier();
2158                Map map = new HashMap();
2159                map.put("itemIdentifier", id);
2160                List<OlePurchaseOrderAccount> list  = (List<OlePurchaseOrderAccount> )getBusinessObjectService().findMatching(OlePurchaseOrderAccount.class, map);
2161                List<InvoiceAccount> newList = new ArrayList<>();
2162                for(OlePurchaseOrderAccount olePurchaseOrderAccount : list){
2163                    InvoiceAccount invoiceAccount = new InvoiceAccount(item, olePurchaseOrderAccount) ;
2164                    newList.add(invoiceAccount);
2165                }
2166                item.setSourceAccountingLines((List)newList);
2167                item.setTempItemIdentifier(null);
2168            }
2169        }
2170         if (invoiceDocument.getPoId() != null && StringUtils.isNotBlank(invoiceDocument.getPoId().toString())) {
2171             super.refresh(invoiceForm, result, request, response);
2172             invoiceDocument.setUnsaved(true);
2173             return addItem(invoiceForm, result, request, response);
2174         }
2175         return super.refresh(invoiceForm, result, request, response);
2176     }
2177 
2178     /**
2179      * This method validates the Invoice Amount.
2180      *
2181      * @param form
2182      * @param result
2183      * @param request
2184      * @param response
2185      * @return
2186      * @throws Exception
2187      */
2188     @RequestMapping(params = "methodToCall=validateInvoiceAmount")
2189     public ModelAndView validateInvoiceAmount(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2190                                               HttpServletRequest request, HttpServletResponse response) throws Exception {
2191         OLEInvoiceForm invoiceForm = (OLEInvoiceForm) form;
2192         OleInvoiceDocument invoiceDocument = (OleInvoiceDocument)invoiceForm.getDocument();
2193         String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(invoiceDocument);
2194         if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
2195             invoiceForm.setSubscriptionValidationMessage(subscriptionValidationMessage);
2196             invoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(true);
2197         }
2198         else {
2199             invoiceDocument.setValidationFlag(false);
2200         }
2201 
2202         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(invoiceDocument);
2203         if (!validationMessage.isEmpty() && validationMessage != null){
2204             invoiceForm.setValidationMessage(validationMessage);
2205             invoiceDocument.setValidationFlag(true);
2206         }
2207         else {
2208             invoiceDocument.setValidationFlag(false);
2209         }
2210         return getUIFModelAndView(invoiceForm);
2211     }
2212 
2213     @RequestMapping(params = "methodToCall=deleteInvoice")
2214     public ModelAndView deleteInvoice(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2215                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
2216         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2217         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2218         oleInvoiceDocument.setDbRetrieval(false);
2219         String focusId = oleInvoiceForm.getFocusId();
2220         String s = focusId.substring(focusId.indexOf("_line"),focusId.length()).replace("_line","");
2221         int deleteDocument = Integer.parseInt(s);
2222         List<OleInvoiceItem> oleInvoiceItems = oleInvoiceDocument.getItems();
2223         oleInvoiceDocument.getDeletedInvoiceItems().add((OleInvoiceItem) oleInvoiceDocument.getItems().get(deleteDocument));
2224         oleInvoiceItems.remove(deleteDocument);
2225         int sequenceNumber = 0;
2226         for(OleInvoiceItem item : oleInvoiceItems) {
2227             if(item.getItemLineNumber() != null) {
2228                 item.setSequenceNumber(++sequenceNumber);
2229             }
2230         }
2231         oleInvoiceDocument.setItems(oleInvoiceItems);
2232         if (oleInvoiceDocument.isProrateDollar() || oleInvoiceDocument.isProrateQty()) {
2233             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(oleInvoiceDocument, true);
2234         }
2235         return getUIFModelAndView(oleInvoiceForm);
2236     }
2237 
2238     @RequestMapping(params = "methodToCall=unlinkInvoice")
2239     public ModelAndView unlinkInvoice(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2240                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
2241         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2242         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2243         String focusId = oleInvoiceForm.getFocusId();
2244         String s = focusId.substring(focusId.indexOf("_line"),focusId.length()).replace("_line","");
2245         int unlinkDocument = Integer.parseInt(s);
2246         List<OleInvoiceItem> oleInvoiceItems = oleInvoiceDocument.getItems();
2247         OleInvoiceItem oleInvoiceItem = oleInvoiceItems.get(unlinkDocument);
2248         oleInvoiceItem.setItemDescription("Unlinked - previously attached to PO ["+oleInvoiceItem.getPurchaseOrderIdentifier()+"]");
2249         oleInvoiceItem.setPoItemIdentifier(null);
2250         Long nextLinkIdentifier = SpringContext.getBean(SequenceAccessorService.class).getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID");
2251         oleInvoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier(nextLinkIdentifier.intValue());
2252         oleInvoiceItem.setItemTitleId(null);
2253         return getUIFModelAndView(oleInvoiceForm);
2254     }
2255 
2256     private boolean validateRequiredFields(OleInvoiceDocument invoiceDocument, boolean validateVendorInvoiceAmount) {
2257         boolean isValid = true;
2258         for (Object invoiceItem : invoiceDocument.getItems()) {
2259             isValid &= getKualiRuleService().applyRules(new OLEInvoiceSubscriptionOverlayValidationEvent(invoiceDocument, (OleInvoiceItem)invoiceItem));
2260         }
2261         if (invoiceDocument.getInvoiceDate() == null || invoiceDocument.getInvoiceDate().equals("")) {
2262             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_NO_INVOICE_DATE);
2263             isValid &= false;
2264         }
2265         if (StringUtils.isNotBlank(invoiceDocument.getInvoiceCurrencyType())) {
2266             String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
2267             BigDecimal exchangeRate = null;
2268             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2269                 if (StringUtils.isNotBlank(invoiceDocument.getInvoiceCurrencyExchangeRate())) {
2270                     try {
2271                         Double.parseDouble(invoiceDocument.getInvoiceCurrencyExchangeRate());
2272                         exchangeRate = new BigDecimal(invoiceDocument.getInvoiceCurrencyExchangeRate());
2273                         if (new KualiDecimal(exchangeRate).isZero()) {
2274                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
2275                             isValid &= false;
2276                         }
2277                     }
2278                     catch (NumberFormatException nfe) {
2279                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
2280                         isValid &= false;
2281                     }
2282                 }   else {
2283                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
2284                     isValid &= false;
2285                 }
2286             }  else {
2287                 invoiceDocument.setInvoiceCurrencyExchangeRate(null);
2288                 invoiceDocument.setForeignCurrencyFlag(false);
2289                 invoiceDocument.setForeignVendorInvoiceAmount(null);
2290             }
2291         }
2292         if (validateVendorInvoiceAmount) {
2293             if (StringUtils.isNotBlank(invoiceDocument.getInvoiceCurrencyType())) {
2294                 String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
2295                 if (StringUtils.isNotBlank(currencyType)) {
2296                     if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2297                         if (invoiceDocument.getInvoiceAmount() == null || invoiceDocument.getInvoiceAmount().equals("")) {
2298                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_NO_INVOICE_AMOUNT);
2299                             isValid &= false;
2300                         }
2301                     } else {
2302                         if (invoiceDocument.getForeignInvoiceAmount() == null || invoiceDocument.getForeignInvoiceAmount().equals("")) {
2303                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_NO_FOREIGN_INVOICE_AMOUNT);
2304                             isValid &= false;
2305                         }
2306                     }
2307                 }
2308             }
2309             try {
2310                 if (StringUtils.isNotBlank(invoiceDocument.getInvoiceAmount())) {
2311                     Double.parseDouble(invoiceDocument.getInvoiceAmount());
2312                 }
2313             }
2314             catch (NumberFormatException nfe) {
2315                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_VALID_INVOICE_AMOUNT);
2316                 isValid &= false;
2317             }
2318             try {
2319                 if (StringUtils.isNotBlank(invoiceDocument.getForeignInvoiceAmount())) {
2320                     Double.parseDouble(invoiceDocument.getForeignInvoiceAmount());
2321                 }
2322             }
2323             catch (NumberFormatException nfe) {
2324                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_VALID_FOREIGN_INVOICE_AMOUNT);
2325                 isValid &= false;
2326             }
2327         }
2328         if (invoiceDocument.getPaymentMethodIdentifier() == null || invoiceDocument.getPaymentMethodIdentifier().equals("")) {
2329             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_NO_PAYMENT_MTHD);
2330             isValid &= false;
2331         }
2332         return isValid;
2333     }
2334 
2335     protected KualiRuleService getKualiRuleService() {
2336         if (kualiRuleService == null) {
2337             kualiRuleService = KRADServiceLocatorWeb.getKualiRuleService();
2338         }
2339         return this.kualiRuleService;
2340     }
2341     @RequestMapping(params = "methodToCall=" + "closeDocument")
2342     public ModelAndView closeDocument(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2343                                       HttpServletRequest request, HttpServletResponse response)  {
2344 
2345         String baseUrl = ConfigContext.getCurrentContextConfig().getProperty(org.kuali.ole.OLEPropertyConstants.OLE_URL_BASE);
2346         String url = baseUrl + "/portal.do";
2347         Properties props = new Properties();
2348         props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.REFRESH);
2349         if (StringUtils.isNotBlank(form.getReturnFormKey())) {
2350             props.put(UifParameters.FORM_KEY, form.getReturnFormKey());
2351         }
2352         GlobalVariables.getUifFormManager().removeSessionForm(form);
2353         return performRedirect(form, url, props);
2354     }
2355 
2356     @RequestMapping(params = "methodToCall=" + "clone")
2357     public ModelAndView clone(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2358                               HttpServletRequest request, HttpServletResponse response) throws Exception {
2359         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2360         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2361         //oleInvoiceDocument.setCloneDebitInvoice("true");
2362         oleInvoiceDocument.setCloneFlag(true);
2363         return getUIFModelAndView(form);
2364     }
2365 
2366     /**
2367      * This method creates the copy of the Invoice Document based on the user input
2368      * on credit or debit Invoice Document.
2369      * @param form
2370      * @param result
2371      * @param request
2372      * @param response
2373      * @return
2374      * @throws Exception
2375      */
2376     @RequestMapping(params = "methodToCall=" + "copyInvoice")
2377     public ModelAndView copyInvoice(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2378                                     HttpServletRequest request, HttpServletResponse response) throws Exception {
2379         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2380         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2381         //oleInvoiceDocument.setCloneFlag(true);
2382         /*for (OleInvoiceItem item : (List<OleInvoiceItem>)oleInvoiceDocument.getItems()) {
2383             OleInvoiceItem invoiceItem = (OleInvoiceItem) item;
2384             invoiceItem.setReceiptStatusId(null);
2385             invoiceItem.setOleReceiptStatus(new OleReceiptStatus());
2386         }*/
2387 
2388         super.copy(oleInvoiceForm,result,request,response);
2389 
2390         return getUIFModelAndView(form);
2391     }
2392 
2393     /**
2394      * Performs the approve workflow action on the form document instance
2395      *
2396      * @param form - document form base containing the document instance that will be approved
2397      * @return ModelAndView
2398      */
2399     @RequestMapping(params = "methodToCall=approveInvoiceDocument")
2400     public ModelAndView approveInvoiceDocument(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2401                                                HttpServletRequest request, HttpServletResponse response) throws Exception {
2402         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2403         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2404         Boolean isAmountExceeds = getInvoiceService().isNotificationRequired(oleInvoiceDocument);
2405         boolean duplicationExists = false;
2406         duplicationExists = getInvoiceService().isDuplicationExists(oleInvoiceDocument,oleInvoiceForm,false);
2407         if (duplicationExists) {
2408             //oleInvoiceForm.setDuplicationMessage(OleSelectConstant.DUPLICATE_INVOICE);
2409             oleInvoiceDocument.setDuplicateFlag(true);
2410         }
2411         else {
2412             if(isAmountExceeds){
2413                 oleInvoiceForm.setAmountExceedsMessage(getInvoiceService().createInvoiceAmountExceedsThresholdText(oleInvoiceDocument));
2414                 oleInvoiceDocument.setAmountExceeds(true);
2415                 return getUIFModelAndView(form);
2416             }
2417             super.approve(oleInvoiceForm,result,request,response);
2418             return closeDocument(oleInvoiceForm,result,request,response);
2419         }
2420         return getUIFModelAndView(form);
2421     }
2422     /**
2423      * close the popup in instance tab
2424      *
2425      * @param form - document form base containing the document instance that will be routed
2426      * @return ModelAndView
2427      */
2428     @RequestMapping(params = "methodToCall=closePopup")
2429     public ModelAndView closePopup(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2430                                    HttpServletRequest request, HttpServletResponse response) {
2431         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2432         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2433         return getUIFModelAndView(form);
2434     }
2435 
2436     /**
2437      * Performs the approve workflow action on the form document instance
2438      *
2439      * @param form - document form base containing the document instance that will be approved
2440      * @return ModelAndView
2441      */
2442     @RequestMapping(params = "methodToCall=continueDuplicateBlanketApprove")
2443     public ModelAndView continueDuplicateBlanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2444                                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
2445         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2446         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2447         oleInvoiceForm.setDuplicationApproveMessage(null);
2448         oleInvoiceDocument.setDuplicateApproveFlag(false);
2449 
2450         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
2451         if (!validationMessage.isEmpty() && validationMessage != null){
2452             oleInvoiceForm.setValidationMessage(validationMessage);
2453             oleInvoiceDocument.setBlanketApproveValidationFlag(true);
2454         }
2455         else {
2456             oleInvoiceDocument.setBlanketApproveValidationFlag(false);
2457             getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
2458             super.blanketApprove(oleInvoiceForm, result, request, response);
2459             if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
2460                 return getUIFModelAndView(oleInvoiceForm);
2461             }
2462             oleInvoiceDocument.setUnsaved(false);
2463             return closeDocument(form,result,request,response);
2464         }
2465         return  getUIFModelAndView(oleInvoiceForm);
2466     }
2467 
2468 
2469 
2470     /**
2471      * Called by the add line action for a new collection line. Method
2472      * determines which collection the add action was selected for and invokes
2473      * the view helper service to add the line
2474      */
2475     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addOffsetSourceAccountingLine")
2476     public ModelAndView addOffsetSourceAccountingLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
2477                                                       HttpServletRequest request, HttpServletResponse response) {
2478         LOG.debug("Inside offset addSourceAccountingLine()");
2479         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
2480         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2481         boolean rulePassed = true;
2482         boolean flag = false;
2483         PurApItem item = null;
2484         String errorPrefix = null;
2485         String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
2486         if (StringUtils.isBlank(selectedCollectionPath)) {
2487             throw new RuntimeException("Selected collection was not set for offset add line action, cannot add new line");
2488         }
2489         CollectionGroup collectionGroup = oleInvoiceForm.getPostedView().getViewIndex().getCollectionGroupByPath(
2490                 selectedCollectionPath);
2491         String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
2492         Object eventObject = ObjectPropertyUtils.getPropertyValue(oleInvoiceForm, addLinePath);
2493         OLEInvoiceOffsetAccountingLine invoiceAccount = (OLEInvoiceOffsetAccountingLine)eventObject;
2494         if (StringUtils.isEmpty(invoiceAccount.getChartOfAccountsCode())) {
2495             flag = true;
2496         }
2497         if (StringUtils.isEmpty(invoiceAccount.getAccountNumber())) {
2498             flag = true;
2499         }
2500         if (StringUtils.isEmpty(invoiceAccount.getFinancialObjectCode())) {
2501             flag = true;
2502         }
2503         int selectedLine = 0;
2504         if (StringUtils.isNotBlank(selectedCollectionPath)) {
2505             String lineNumber = StringUtils.substringBetween(selectedCollectionPath, ".items[", ".");
2506             String itemIndex = StringUtils.substringBefore(lineNumber,"]");
2507             if (!StringUtils.isEmpty(lineNumber)) {
2508                 selectedLine = Integer.parseInt(itemIndex);
2509             }
2510             errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(selectedLine) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
2511         }
2512         rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, oleInvoiceDocument, (AccountingLine)eventObject));
2513         if (!rulePassed || flag) {
2514             return getUIFModelAndView(uifForm);
2515         }
2516         View view = uifForm.getPostedView();
2517         view.getViewHelperService().processCollectionAddLine(view, uifForm, selectedCollectionPath);
2518         if (rulePassed) {
2519             item = oleInvoiceDocument.getItem((selectedLine));
2520             OLEInvoiceOffsetAccountingLine lineItem = invoiceAccount;
2521             if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
2522                 if (lineItem.getAccountLinePercent() != null && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
2523                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
2524                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
2525                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero() && lineItem.getAccountLinePercent() == null) {
2526                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
2527                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
2528                     lineItem.setAccountLinePercent(dollarToPercent);
2529                 } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero() && lineItem.getAccountLinePercent() == null) {
2530                     lineItem.setAccountLinePercent(new BigDecimal(0));
2531                 }
2532                 else if(lineItem.getAmount()!=null&& lineItem.getAccountLinePercent().intValue()== 100){
2533                     KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
2534                     BigDecimal dollarToPercent = dollar.bigDecimalValue().divide((item.getTotalAmount().bigDecimalValue()),0,RoundingMode.FLOOR);
2535                     lineItem.setAccountLinePercent(dollarToPercent);
2536                 }
2537                 else if(lineItem.getAmount()!=null&&lineItem.getAccountLinePercent() != null){
2538                     BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
2539                     lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
2540                 }
2541             } else {
2542                 lineItem.setAmount(null);
2543             }
2544             //oleInvoiceDocument.setProrateBy(OLEConstants.NO_PRORATE);
2545             //oleInvoiceDocument.setNoProrate(true);
2546         }
2547         LOG.debug("Leaving addSourceAccountingLine()");
2548         return getUIFModelAndView(uifForm);
2549     }
2550 
2551     @RequestMapping(params = "methodToCall=refreshBeanId")
2552     public ModelAndView refreshBeanId(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
2553                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
2554         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2555         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2556         String paymentType = SpringContext.getBean(OleInvoiceService.class).getPaymentMethodType(oleInvoiceDocument.getPaymentMethodIdentifier());
2557         if(paymentType.equals(OLEConstants.DEPOSIT)) {
2558             oleInvoiceDocument.setOffsetAccountIndicator(true);
2559         }else{
2560             oleInvoiceDocument.setOffsetAccountIndicator(false);
2561         }
2562         return navigate(form, result, request, response);
2563     }
2564 
2565     @RequestMapping(params = "methodToCall=approveCheckAmountExceeds")
2566     public ModelAndView approveCheckAmountExceeds(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2567                                                   HttpServletRequest request, HttpServletResponse response) throws Exception {
2568         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2569         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2570         Boolean isAmountExceeds = getInvoiceService().isNotificationRequired(oleInvoiceDocument);
2571         if(isAmountExceeds){
2572             oleInvoiceForm.setAmountExceedsMessage(getInvoiceService().createInvoiceAmountExceedsThresholdText(oleInvoiceDocument));
2573             oleInvoiceDocument.setAmountExceeds(true);
2574         }
2575         else {
2576             super.approve(oleInvoiceForm,result,request,response);
2577             return closeDocument(oleInvoiceForm,result,request,response);
2578         }
2579         return getUIFModelAndView(form);
2580     }
2581 
2582     @RequestMapping(params = "methodToCall=continueInvoiceApproval")
2583     public ModelAndView continueInvoiceApproval(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2584                                                 HttpServletRequest request, HttpServletResponse response)  throws Exception{
2585         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2586         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2587         oleInvoiceDocument.setAmountExceeds(false);
2588         return super.approve(oleInvoiceForm, result, request, response);
2589     }
2590 
2591     @RequestMapping(params = "methodToCall=cancelInvoiceApproval")
2592     public ModelAndView cancelInvoiceApproval(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2593                                               HttpServletRequest request, HttpServletResponse response) {
2594         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2595         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2596         oleInvoiceDocument.setAmountExceeds(false);
2597         oleInvoiceForm.setAmountExceedsMessage(null);
2598         return getUIFModelAndView(form);
2599     }
2600 
2601     @RequestMapping(params = "methodToCall=continueInvoiceBlankApproval")
2602     public ModelAndView continueInvoiceBlankApproval(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2603                                                      HttpServletRequest request, HttpServletResponse response)  throws Exception{
2604         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2605         OleInvoiceFundCheckService oleInvoiceFundCheckService = (OleInvoiceFundCheckService) SpringContext
2606                 .getBean("oleInvoiceFundCheckService");
2607         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2608         oleInvoiceDocument.setAmountExceedsForBlanketApprove(false);
2609         oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(false);
2610         oleInvoiceDocument.setValidationFlag(false);
2611         oleInvoiceDocument.setBlanketApproveValidationFlag(false);
2612         if(oleInvoiceDocument.getSourceAccountingLines().size() > 0){
2613             List<SourceAccountingLine> sourceAccountingLineList = oleInvoiceDocument.getSourceAccountingLines();
2614             for (SourceAccountingLine accLine : sourceAccountingLineList) {
2615                 Map searchMap = new HashMap();
2616                 String notificationOption = null;
2617                 boolean sufficientFundCheck;
2618                 Map<String, Object> key = new HashMap<String, Object>();
2619                 String chartCode = accLine.getChartOfAccountsCode();
2620                 String accNo = accLine.getAccountNumber();
2621                 String objectCd = accLine.getFinancialObjectCode();
2622                 key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode);
2623                 key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo);
2624                 OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(
2625                         OleSufficientFundCheck.class, key);
2626                 if (account != null) {
2627                     notificationOption = account.getNotificationOption();
2628                 }
2629                 if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.WARNING_MSG)) {
2630                     sufficientFundCheck = oleInvoiceFundCheckService.hasSufficientFundCheckRequired(accLine);
2631                     if (sufficientFundCheck) {
2632                         oleInvoiceDocument.setBlanketApproveFlag(false);
2633                         oleInvoiceDocument.setBaSfcFlag(sufficientFundCheck);
2634                         oleInvoiceForm.setSfcFailApproveMsg(OLEConstants.INV_INSUFF_FUND+accLine.getAccountNumber());
2635                         return getUIFModelAndView(oleInvoiceForm);
2636                     }
2637                 }
2638             }
2639         }
2640 
2641         String subscriptionValidationMessage = getInvoiceService().createSubscriptionDateOverlapQuestionText(oleInvoiceDocument);
2642         if (!subscriptionValidationMessage.isEmpty() && subscriptionValidationMessage != null){
2643             oleInvoiceForm.setSubscriptionValidationMessage(subscriptionValidationMessage);
2644             oleInvoiceDocument.setBlanketApproveSubscriptionDateValidationFlag(true);
2645             oleInvoiceDocument.setBlanketApproveFlag(false);
2646         }
2647         if(oleInvoiceDocument.isValidationFlag() || oleInvoiceDocument.isBlanketApproveValidationFlag() || oleInvoiceDocument.isBlanketApproveSubscriptionDateValidationFlag()){
2648             return getUIFModelAndView(oleInvoiceForm);
2649         }
2650 
2651         String validationMessage = getInvoiceService().createInvoiceNoMatchQuestionText(oleInvoiceDocument);
2652         if (!validationMessage.isEmpty() && validationMessage != null){
2653             oleInvoiceForm.setValidationMessage(validationMessage);
2654             oleInvoiceDocument.setBlanketApproveValidationFlag(true);
2655             oleInvoiceDocument.setBlanketApproveFlag(false);
2656         }
2657         else {
2658             oleInvoiceDocument.setBlanketApproveValidationFlag(false);
2659             super.blanketApprove(oleInvoiceForm, result, request, response);
2660             if (GlobalVariables.getMessageMap().getErrorCount() > 0) {
2661                 return getUIFModelAndView(oleInvoiceForm);
2662             }
2663             oleInvoiceDocument.setUnsaved(false);
2664             //GlobalVariables.getMessageMap().clearErrorMessages();
2665             return closeDocument(oleInvoiceForm,result,request,response);
2666         }
2667         return  getUIFModelAndView(oleInvoiceForm);
2668     }
2669 
2670     @RequestMapping(params = "methodToCall=cancelInvoiceBlankApproval")
2671     public ModelAndView cancelInvoiceBlankApproval(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2672                                                    HttpServletRequest request, HttpServletResponse response) {
2673         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2674         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2675         oleInvoiceDocument.setAmountExceedsForBlanketApprove(false);
2676         oleInvoiceForm.setAmountExceedsMessage(null);
2677         oleInvoiceDocument.setUnsaved(true);
2678         return getUIFModelAndView(form);
2679     }
2680 
2681     @Override
2682     protected void performWorkflowAction(DocumentFormBase form, UifConstants.WorkflowAction action, boolean checkSensitiveData) {
2683         Document document = form.getDocument();
2684 
2685         LOG.debug("Performing workflow action " + action.name() + "for document: " + document.getDocumentNumber());
2686 
2687         // TODO: need question and prompt framework
2688         if (checkSensitiveData) {
2689             //        String viewName = checkAndWarnAboutSensitiveData(form, request, response,
2690             //                KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "route", "");
2691             //        if (viewName != null) {
2692             //            return new ModelAndView(viewName);
2693             //        }
2694         }
2695 
2696         try {
2697             String successMessageKey = null;
2698             switch (action) {
2699                 case SAVE:
2700                     getDocumentService().saveDocument(document);
2701                     successMessageKey = RiceKeyConstants.MESSAGE_SAVED;
2702                     break;
2703                 case ROUTE:
2704                     getDocumentService().routeDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
2705                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
2706                     break;
2707                 case BLANKETAPPROVE:
2708                     getDocumentService().blanketApproveDocument(document, form.getAnnotation(), combineAdHocRecipients(
2709                             form));
2710                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
2711                     break;
2712                 case APPROVE:
2713                     getDocumentService().approveDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
2714                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_APPROVED;
2715                     break;
2716                 case DISAPPROVE:
2717                     // TODO: need to get disapprove note from user
2718                     String disapprovalNoteText = "";
2719                     getDocumentService().disapproveDocument(document, disapprovalNoteText);
2720                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_DISAPPROVED;
2721                     break;
2722                 case FYI:
2723                     getDocumentService().clearDocumentFyi(document, combineAdHocRecipients(form));
2724                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_FYIED;
2725                     break;
2726                 case ACKNOWLEDGE:
2727                     getDocumentService().acknowledgeDocument(document, form.getAnnotation(), combineAdHocRecipients(
2728                             form));
2729                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_ACKNOWLEDGED;
2730                     break;
2731                 case CANCEL:
2732                     if (getDocumentService().documentExists(document.getDocumentNumber())) {
2733                         getDocumentService().cancelDocument(document, form.getAnnotation());
2734                         successMessageKey = RiceKeyConstants.MESSAGE_CANCELLED;
2735                     }
2736                     break;
2737                 case COMPLETE:
2738                     if (getDocumentService().documentExists(document.getDocumentNumber())) {
2739                         getDocumentService().completeDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
2740                         successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
2741                     }
2742                     break;
2743                 case SENDADHOCREQUESTS:
2744                     getDocumentService().sendAdHocRequests(document, form.getAnnotation(), combineAdHocRecipients(form));
2745                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
2746                     break;
2747             }
2748 
2749             if (successMessageKey != null) {
2750                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_MESSAGES, successMessageKey);
2751             }
2752         } catch (ValidationException e) {
2753             // if errors in map, swallow exception so screen will draw with errors
2754             // if not then throw runtime because something bad happened
2755             if (GlobalVariables.getMessageMap().hasNoErrors()) {
2756                 throw new RiceRuntimeException("Validation Exception with no error message.", e);
2757             }
2758         } catch (Exception e) {
2759             throw new RiceRuntimeException(
2760                     "Exception trying to invoke action " + action.name() + "for document: " + document
2761                             .getDocumentNumber(), e);
2762         }
2763 
2764         form.setAnnotation("");
2765     }
2766 
2767     /**
2768      *  Updates the Currency type of the document.
2769      */
2770 
2771     @RequestMapping(params = "methodToCall=updateCurrencyTypeChange")
2772     public ModelAndView updateCurrencyTypeChange(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
2773                                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
2774         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
2775         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
2776         List<OleInvoiceItem> oleInvoiceItemList = oleInvoiceDocument.getItems();
2777        // boolean invoicePriceFlag = false;
2778         String currencyType = null;
2779         BigDecimal exchangeRate = null;
2780         BigDecimal previousExchangeRate = null;
2781         Long previousCurrencyTypeId = null;
2782         String itemForeignListPrice;
2783         String previousCurrencyType = null;
2784         oleInvoiceDocument.setDbRetrieval(false);
2785         if (oleInvoiceDocument.getInvoiceCurrencyTypeId() != null) {
2786             previousCurrencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyTypeId().toString());
2787             previousCurrencyTypeId = oleInvoiceDocument.getInvoiceCurrencyTypeId();
2788         }
2789         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
2790 
2791             currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
2792 
2793             if (StringUtils.isNotBlank(currencyType)) {
2794                 // local vendor
2795                 if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2796                     oleInvoiceDocument.setForeignCurrencyFlag(false);
2797                     oleInvoiceDocument.setForeignVendorInvoiceAmount(null);
2798                     oleInvoiceDocument.setForeignVendorAmount(OLEConstants.EMPTY_STRING);
2799                     oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
2800                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
2801                     oleInvoiceDocument.setForeignInvoiceAmount(null);
2802                     oleInvoiceDocument.setForeignItemTotal(OLEConstants.EMPTY_STRING);
2803                     oleInvoiceDocument.setForeignGrandTotal(OLEConstants.EMPTY_STRING);
2804 
2805                     if (oleInvoiceDocument.getItems().size()>0 || oleInvoiceDocument.getPurchaseOrderDocuments().size()>0) {
2806                         for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
2807                             for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
2808                                 if (olePurchaseOrderItem.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
2809                                     if (olePurchaseOrderItem.getItemDiscount() != null && olePurchaseOrderItem.getItemDiscountType() != null) {
2810                                         if(olePurchaseOrderItem.getItemDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)){
2811                                             BigDecimal discount = ((olePurchaseOrderItem.getItemListPrice().bigDecimalValue().multiply(olePurchaseOrderItem.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
2812                                             olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemListPrice().bigDecimalValue().subtract(discount));
2813                                             olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getItemListPrice().toString());
2814                                         }else{
2815                                             olePurchaseOrderItem.setItemUnitPrice((olePurchaseOrderItem.getItemListPrice().bigDecimalValue().subtract(olePurchaseOrderItem.getItemDiscount().bigDecimalValue())));
2816                                             olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getItemListPrice().toString());
2817                                         }
2818                                     }   else {
2819                                         olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getItemListPrice().toString());
2820                                         olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemListPrice().bigDecimalValue());
2821                                         olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
2822                                     }
2823                                 }
2824                                 getInvoiceService().calculateAccount(olePurchaseOrderItem);
2825                             }
2826                         }
2827 
2828                         if (oleInvoiceItemList.size()>0) {
2829                             for (OleInvoiceItem oleInvoiceItem : oleInvoiceItemList) {
2830                                 if (oleInvoiceItem.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
2831                                     if (StringUtils.isNotBlank(previousCurrencyType) && previousCurrencyTypeId != null) {
2832                                         if (!previousCurrencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2833                                             previousExchangeRate = getInvoiceService().getExchangeRate(previousCurrencyTypeId.toString()).getExchangeRate();
2834                                             oleInvoiceItem.setItemUnitCostUSD(new KualiDecimal((oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue()).divide(previousExchangeRate, 4, RoundingMode.HALF_UP)));
2835                                             oleInvoiceItem.setItemUnitPrice(oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(previousExchangeRate, 4, RoundingMode.HALF_UP));
2836                                             oleInvoiceItem.setItemListPrice(new KualiDecimal(oleInvoiceItem.getItemUnitPrice()));
2837                                             if (!oleInvoiceItem.isDebitItem()) {
2838                                                 oleInvoiceItem.setListPrice("-" + oleInvoiceItem.getItemListPrice().toString());
2839                                             } else {
2840                                                 oleInvoiceItem.setListPrice(oleInvoiceItem.getItemListPrice().toString());
2841                                             }
2842                                             oleInvoiceItem.setItemDiscount(new KualiDecimal(0.0));
2843                                             oleInvoiceItem.setDiscountItem(new KualiDecimal(0.0).toString());
2844                                         }
2845                                     }
2846                                     oleInvoiceItem.setForeignListPrice(null);
2847                                     oleInvoiceItem.setForeignUnitCost(null);
2848                                     oleInvoiceItem.setForeignDiscount(null);
2849                                 }
2850                                 getInvoiceService().calculateAccount(oleInvoiceItem);
2851                             }
2852                         }
2853                     }
2854                 }
2855                 //foreign currency
2856                 else {
2857                     oleInvoiceDocument.setForeignCurrencyFlag(true);
2858                     oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
2859                     exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
2860                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
2861                     if (StringUtils.isNotBlank(oleInvoiceDocument.getForeignInvoiceAmount()) ) {
2862                         oleInvoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(oleInvoiceDocument.getForeignInvoiceAmount()));
2863                         oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(new BigDecimal(oleInvoiceDocument.getForeignInvoiceAmount()).divide(exchangeRate, 2, RoundingMode.HALF_UP)));
2864                         oleInvoiceDocument.setInvoiceAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
2865                         oleInvoiceDocument.setVendorAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
2866                     }
2867                     else {
2868                         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceAmount())) {
2869                             oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getInvoiceAmount()));
2870                             oleInvoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(oleInvoiceDocument.getInvoiceAmount()).multiply(exchangeRate));
2871                             oleInvoiceDocument.setForeignInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
2872                             oleInvoiceDocument.setForeignVendorAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
2873                         }
2874                     }
2875 
2876                     if (oleInvoiceDocument.getItems().size()>0 || oleInvoiceDocument.getPurchaseOrderDocuments().size()>0) {
2877                         for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
2878                             for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
2879                                 if (olePurchaseOrderItem.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
2880                                     olePurchaseOrderItem.setInvoiceForeignCurrency(currencyType);
2881                                     olePurchaseOrderItem.setInvoiceExchangeRate(exchangeRate.toString());
2882 
2883                                     if (StringUtils.isNotBlank(olePurchaseOrderItem.getInvoiceItemListPrice())) {
2884                                         if (!olePurchaseOrderItem.getItemListPrice().equals(new KualiDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()))) {
2885                                             if (olePurchaseOrderItem.getItemDiscount() != null && olePurchaseOrderItem.getItemDiscountType() != null) {
2886                                                 if(olePurchaseOrderItem.getItemDiscountType().equals(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)){
2887                                                     BigDecimal discount = ((new BigDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()).multiply(olePurchaseOrderItem.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
2888                                                     olePurchaseOrderItem.setItemUnitPrice(new BigDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()).subtract(discount));
2889                                                     olePurchaseOrderItem.setItemListPrice(new KualiDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()));
2890                                                 }else{
2891                                                     olePurchaseOrderItem.setItemUnitPrice(new BigDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()).subtract(olePurchaseOrderItem.getItemDiscount().bigDecimalValue()));
2892                                                     olePurchaseOrderItem.setItemListPrice(new KualiDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()));
2893                                                 }
2894                                             }   else {
2895                                                 olePurchaseOrderItem.setItemListPrice(new KualiDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()));
2896                                                 olePurchaseOrderItem.setItemUnitPrice(new BigDecimal(olePurchaseOrderItem.getInvoiceItemListPrice()));
2897                                             }
2898                                         }
2899                                     }
2900 
2901                                     if (StringUtils.isNotBlank(previousCurrencyType)) {
2902                                         if (!previousCurrencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2903                                             if (olePurchaseOrderItem.getInvoiceForeignDiscount() != null && olePurchaseOrderItem.getInvoiceForeignDiscountType() != null) {
2904                                                 if(olePurchaseOrderItem.getInvoiceForeignDiscountType().equals("%")){
2905                                                     if (new KualiDecimal(olePurchaseOrderItem.getInvoiceForeignDiscount()).isNonZero()) {
2906                                                         BigDecimal discount = ((new BigDecimal(olePurchaseOrderItem.getInvoiceForeignItemListPrice()).multiply(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignDiscount())))).divide(new BigDecimal(100));
2907                                                         olePurchaseOrderItem.setInvoiceForeignUnitCost(new KualiDecimal(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignItemListPrice()).subtract(discount)).toString());
2908                                                     } else {
2909                                                         olePurchaseOrderItem.setInvoiceForeignUnitCost(olePurchaseOrderItem.getInvoiceForeignItemListPrice());
2910                                                     }
2911                                                 }else {
2912                                                     olePurchaseOrderItem.setInvoiceForeignUnitCost(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignItemListPrice()).subtract(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignDiscount())).toString());
2913                                                 }
2914                                                 if (olePurchaseOrderItem.getInvoiceExchangeRate() != null && olePurchaseOrderItem.getInvoiceForeignUnitCost() != null) {
2915                                                     olePurchaseOrderItem.setItemUnitCostUSD(new KualiDecimal(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignUnitCost()).divide(new BigDecimal(olePurchaseOrderItem.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP)));
2916                                                     olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitCostUSD().bigDecimalValue());
2917                                                     olePurchaseOrderItem.setItemListPrice(olePurchaseOrderItem.getItemUnitCostUSD());
2918                                                     olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getItemListPrice().toString());
2919                                                 }
2920                                             }
2921                                         }
2922                                         else {
2923                                             olePurchaseOrderItem.setInvoiceForeignUnitCost(new KualiDecimal((olePurchaseOrderItem.getItemUnitPrice().multiply(new BigDecimal(olePurchaseOrderItem.getInvoiceExchangeRate())))).toString());
2924                                             olePurchaseOrderItem.setInvoiceForeignItemListPrice(olePurchaseOrderItem.getInvoiceForeignUnitCost());
2925                                             olePurchaseOrderItem.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
2926                                             olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
2927                                         }
2928                                     }
2929                                     else {
2930                                         olePurchaseOrderItem.setInvoiceForeignUnitCost(new KualiDecimal((olePurchaseOrderItem.getItemUnitPrice().multiply(new BigDecimal(olePurchaseOrderItem.getInvoiceExchangeRate())))).toString());
2931                                         olePurchaseOrderItem.setInvoiceForeignItemListPrice(olePurchaseOrderItem.getInvoiceForeignUnitCost());
2932                                         olePurchaseOrderItem.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
2933                                         olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
2934                                     }
2935                                     getInvoiceService().calculateAccount(olePurchaseOrderItem);
2936                                 }
2937                             }
2938                         }
2939                         if (oleInvoiceItemList.size()>0) {
2940                             for (OleInvoiceItem oleInvoiceItem : oleInvoiceItemList) {
2941                                /* if(new KualiDecimal(oleInvoiceItem.getInvoiceListPrice()).isLessThan(KualiDecimal.ZERO)){
2942                                     invoicePriceFlag = true;
2943                                 }*/
2944                                 if (oleInvoiceItem.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
2945                                     oleInvoiceItem.setItemCurrencyType(currencyType);
2946                                     oleInvoiceItem.setInvoicedCurrency(currencyType);
2947                                     oleInvoiceItem.setExchangeRate(exchangeRate.toString());
2948                                     oleInvoiceItem.setItemExchangeRate(new KualiDecimal(exchangeRate));
2949 
2950                                     if (StringUtils.isNotBlank(previousCurrencyType)) {
2951                                         if (!previousCurrencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
2952                                             if (oleInvoiceItem.getItemForeignDiscount() != null && oleInvoiceItem.getItemForeignDiscountType() != null) {
2953                                                 if (!oleInvoiceItem.isDebitItem()) {
2954                                                     itemForeignListPrice = oleInvoiceItem.getForeignListPrice().toString().replace("(", "");
2955                                                     itemForeignListPrice = itemForeignListPrice.replace(")","");
2956                                                 } else {
2957                                                     itemForeignListPrice = oleInvoiceItem.getForeignListPrice();
2958                                                 }
2959                                                 if(oleInvoiceItem.getItemForeignDiscountType().equals("%")){
2960                                                     if (new KualiDecimal(oleInvoiceItem.getForeignDiscount()).isNonZero()) {
2961                                                         BigDecimal discount = ((new BigDecimal(itemForeignListPrice).multiply(new BigDecimal(oleInvoiceItem.getForeignDiscount())))).divide(new BigDecimal(100));
2962                                                         oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(new BigDecimal(itemForeignListPrice).subtract(discount)));
2963                                                         oleInvoiceItem.setForeignUnitCost(oleInvoiceItem.getItemForeignUnitCost().toString());
2964                                                         oleInvoiceItem.setItemForeignListPrice(new KualiDecimal(itemForeignListPrice));
2965                                                         oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(oleInvoiceItem.getForeignDiscount()));
2966                                                     } else {
2967                                                         oleInvoiceItem.setItemForeignListPrice(new KualiDecimal(itemForeignListPrice));
2968                                                         oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(0.0));
2969                                                         oleInvoiceItem.setItemForeignUnitCost(oleInvoiceItem.getItemForeignListPrice());
2970                                                         oleInvoiceItem.setForeignUnitCost(oleInvoiceItem.getItemForeignUnitCost().toString());
2971                                                     }
2972                                                 }else {
2973                                                     oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(new BigDecimal(itemForeignListPrice).subtract(new BigDecimal(oleInvoiceItem.getForeignDiscount()))));
2974                                                     oleInvoiceItem.setForeignUnitCost(oleInvoiceItem.getItemForeignUnitCost().toString());
2975                                                     oleInvoiceItem.setItemForeignListPrice(new KualiDecimal(itemForeignListPrice));
2976                                                     oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(oleInvoiceItem.getForeignDiscount()));
2977                                                 }
2978                                                 if (oleInvoiceItem.getExchangeRate() != null && oleInvoiceItem.getItemForeignUnitCost() != null) {
2979                                                     oleInvoiceItem.setItemUnitCostUSD(new KualiDecimal(oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(exchangeRate, 4, RoundingMode.HALF_UP)));
2980                                                     oleInvoiceItem.setItemUnitPrice(oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(exchangeRate, 4, RoundingMode.HALF_UP));
2981                                                     oleInvoiceItem.setItemListPrice(oleInvoiceItem.getItemUnitCostUSD());
2982                                                     if (!oleInvoiceItem.isDebitItem()) {
2983                                                         oleInvoiceItem.setListPrice("-" + oleInvoiceItem.getItemListPrice().toString());
2984                                                     } else {
2985                                                         oleInvoiceItem.setListPrice(oleInvoiceItem.getItemListPrice().toString());
2986                                                     }
2987                                                     oleInvoiceItem.setItemDiscount(new KualiDecimal(0.0));
2988                                                     oleInvoiceItem.setDiscountItem(new KualiDecimal(0.0).toString());
2989                                                 }
2990                                             }
2991                                         }
2992                                         else {
2993                                             oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(oleInvoiceItem.getItemUnitPrice().multiply(exchangeRate)));
2994                                             oleInvoiceItem.setForeignUnitCost(oleInvoiceItem.getItemForeignUnitCost().toString());
2995                                             oleInvoiceItem.setItemForeignListPrice(oleInvoiceItem.getItemForeignUnitCost());
2996                                             //oleInvoiceItem.setForeignListPrice(oleInvoiceItem.getItemForeignListPrice().toString());
2997                                             oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(0.0));
2998                                             oleInvoiceItem.setForeignDiscount(oleInvoiceItem.getItemForeignDiscount().toString());
2999                                             oleInvoiceItem.setItemForeignDiscountType(oleInvoiceItem.getItemDiscountType());
3000                                             oleInvoiceItem.setItemDiscount(new KualiDecimal(0.0));
3001                                         }
3002                                     } else {
3003                                         oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(oleInvoiceItem.getItemUnitPrice().multiply(exchangeRate)));
3004                                         oleInvoiceItem.setForeignUnitCost(oleInvoiceItem.getItemForeignUnitCost().toString());
3005                                         oleInvoiceItem.setItemForeignListPrice(oleInvoiceItem.getItemForeignUnitCost());
3006                                         //oleInvoiceItem.setForeignListPrice(oleInvoiceItem.getItemForeignListPrice().toString());
3007                                         oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(0.0));
3008                                         oleInvoiceItem.setForeignDiscount(oleInvoiceItem.getItemForeignDiscount().toString());
3009                                         oleInvoiceItem.setItemForeignDiscountType(oleInvoiceItem.getItemDiscountType());
3010                                         oleInvoiceItem.setItemDiscount(new KualiDecimal(0.0));
3011                                     }
3012                                 }   else {
3013                                     if (StringUtils.isNotBlank(previousCurrencyType)) {
3014                                         if (previousCurrencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3015                                             if (oleInvoiceItem.getItemUnitPrice() != null) {
3016                                                 oleInvoiceItem.setAdditionalForeignUnitCost(oleInvoiceItem.getItemUnitPrice().multiply(new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())).toString());
3017                                             }
3018                                         }
3019                                     }
3020                                 }
3021                                 getInvoiceService().calculateAccount(oleInvoiceItem);
3022                             }
3023                             proratedSurchargeRefresh(oleInvoiceForm, result, request, response);
3024                         }
3025                     }
3026                 }
3027             }
3028          //   if(invoicePriceFlag){
3029                 oleInvoiceDocument.setDbRetrieval(false);
3030                 oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
3031                 oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
3032                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3033                     oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
3034                     oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
3035                 }
3036           /*  }else{
3037                 oleInvoiceDocument.setDbRetrieval(false);
3038                 oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
3039                 oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
3040                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3041                     oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
3042                     oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
3043                 }
3044                 oleInvoiceDocument.setItemSign(true);
3045             }*/
3046         }
3047         return getUIFModelAndView(form);
3048     }
3049 
3050     /**
3051      * Updates the prices to Zero if Current Currency is Overrided.
3052      */
3053 /*
3054     @RequestMapping(params = "methodToCall=continueCurrencyOverride")
3055     public ModelAndView continueCurrencyOverride(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3056                                                 HttpServletRequest request, HttpServletResponse response)  throws Exception{
3057         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3058         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3059         oleInvoiceDocument.setCurrencyOverrideFlag(false);
3060         oleInvoiceDocument.setGrandTotal(new KualiDecimal(0.0));
3061         oleInvoiceDocument.setItemTotal(new KualiDecimal(0.0).toString());
3062         KualiDecimal exchangeRate = null;
3063         List<OleInvoiceItem> oleInvoiceItems = oleInvoiceDocument.getItems();
3064         for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
3065             //if (oleInvoiceItem.getItemType().getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
3066             oleInvoiceItem.setTotalAmount(new KualiDecimal(0.0));
3067             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
3068                 String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
3069                 if (StringUtils.isNotBlank(currencyType)) {
3070                     oleInvoiceItem.setInvoicedCurrency(currencyType);
3071                     oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
3072                     if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3073                         oleInvoiceDocument.setForeignCurrencyFlag(true);
3074                         exchangeRate = new KualiDecimal(getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate());
3075                         oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
3076                         oleInvoiceItem.setExchangeRate(exchangeRate.toString());
3077                         oleInvoiceItem.setItemExchangeRate(exchangeRate);
3078                     } else {
3079                         oleInvoiceDocument.setForeignCurrencyFlag(false);
3080                         oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
3081                         oleInvoiceItem.setItemExchangeRate(null);
3082                         oleInvoiceItem.setExchangeRate(null);
3083                     }
3084                     oleInvoiceDocument.setVendorAmount(null);
3085                     oleInvoiceDocument.setForeignVendorInvoiceAmount(null);
3086                     oleInvoiceItem.setListPrice(new KualiDecimal(0.0).toString());
3087                     oleInvoiceItem.setDiscountItem(new KualiDecimal(0.0).toString());
3088                     oleInvoiceItem.setItemListPrice(new KualiDecimal(0.0));
3089                     oleInvoiceItem.setItemUnitCostUSD(new KualiDecimal(0.0));
3090                     oleInvoiceItem.setInvoiceListPrice(new KualiDecimal(0.0).toString());
3091                     oleInvoiceItem.setAdditionalUnitPrice(new KualiDecimal(0.0).toString());
3092                     oleInvoiceItem.setItemUnitPrice(new BigDecimal(0));
3093                     oleInvoiceItem.setExtendedPrice(new KualiDecimal(0.0));
3094                     oleInvoiceItem.setItemForeignListPrice(new KualiDecimal(0.0));
3095                     oleInvoiceItem.setForeignListPrice(new KualiDecimal(0.0).toString());
3096                     oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(0.0));
3097                     oleInvoiceItem.setForeignUnitCost(new KualiDecimal(0.0).toString());
3098                     oleInvoiceItem.setItemForeignDiscount(new KualiDecimal(0.0));
3099                     oleInvoiceItem.setForeignDiscount(new KualiDecimal(0.0).toString());
3100                     oleInvoiceItem.setAdditionalForeignUnitCost(new KualiDecimal(0.0).toString());
3101                     oleInvoiceItem.setForeignCurrencyExtendedPrice(new KualiDecimal(0.0));
3102                     oleInvoiceItem.setInvoiceForeignListPrice(new KualiDecimal(0.0).toString());
3103                 }
3104             }
3105             //}
3106             getInvoiceService().calculateAccount(oleInvoiceItem);
3107         }
3108 
3109         if (oleInvoiceDocument.getPurchaseOrderDocuments().size()>0) {
3110             for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
3111                 for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
3112 
3113                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
3114                         String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
3115                         if (StringUtils.isNotBlank(currencyType)) {
3116                             olePurchaseOrderItem.setInvoiceForeignCurrency(currencyType);
3117                             olePurchaseOrderItem.setItemCurrencyType(currencyType);
3118                             oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
3119                             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3120                                 oleInvoiceDocument.setForeignCurrencyFlag(true);
3121                                 exchangeRate = new KualiDecimal(getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate());
3122                                 oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
3123                                 olePurchaseOrderItem.setInvoiceExchangeRate(exchangeRate.toString());
3124                                 olePurchaseOrderItem.setItemExchangeRate(exchangeRate);
3125                             } else {
3126                                 oleInvoiceDocument.setForeignCurrencyFlag(false);
3127                                 olePurchaseOrderItem.setInvoiceExchangeRate(null);
3128                                 olePurchaseOrderItem.setItemExchangeRate(null);
3129                                 oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
3130                             }
3131                             oleInvoiceDocument.setVendorAmount(null);
3132                             oleInvoiceDocument.setForeignVendorInvoiceAmount(null);
3133                             olePurchaseOrderItem.setItemListPrice(new KualiDecimal(0.0));
3134                             olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
3135                             olePurchaseOrderItem.setItemUnitPrice(new BigDecimal(0.0));
3136                             olePurchaseOrderItem.setInvoiceItemListPrice(new KualiDecimal(0.0).toString());
3137                             olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
3138                             olePurchaseOrderItem.setExtendedPrice(new KualiDecimal(0.0));
3139                             olePurchaseOrderItem.setInvoicePrice(new KualiDecimal(0.0));
3140                             olePurchaseOrderItem.setItemForeignListPrice(new KualiDecimal(0.0));
3141                             olePurchaseOrderItem.setInvoiceForeignItemListPrice(new KualiDecimal(0.0).toString());
3142                             olePurchaseOrderItem.setItemForeignDiscount(new KualiDecimal(0.0));
3143                             olePurchaseOrderItem.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
3144                             olePurchaseOrderItem.setItemForeignUnitCost(new KualiDecimal(0.0));
3145                             olePurchaseOrderItem.setInvoiceForeignUnitCost(new KualiDecimal(0.0).toString());
3146                             olePurchaseOrderItem.setItemForiegnExtendedPrice(new KualiDecimal(0.0));
3147                             olePurchaseOrderItem.setItemForeignDiscountAmt(new KualiDecimal(0.0));
3148                         }
3149                     }
3150                     getInvoiceService().calculateAccount(olePurchaseOrderItem);
3151                 }
3152             }
3153         }
3154         return getUIFModelAndView(form);
3155     }
3156 
3157     /**
3158      * Currency type of the document is retained, if Currency Type is not overrided.
3159      */
3160 
3161 /*    @RequestMapping(params = "methodToCall=cancelCurrencyOverride")
3162     public ModelAndView cancelCurrencyOverride(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3163                                                 HttpServletRequest request, HttpServletResponse response)  throws Exception{
3164         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3165         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3166         oleInvoiceDocument.setCurrencyOverrideFlag(false);
3167         oleInvoiceDocument.setInvoiceCurrencyType(oleInvoiceDocument.getInvoiceCurrencyTypeId().toString());
3168         return getUIFModelAndView(form);
3169     }
3170 */
3171     /**
3172      * Exchange rate of the current currency type is overrided and
3173      *
3174      * the prices are re-calculated based on the overrided exchange rate value.
3175      */
3176 
3177     @RequestMapping(params = "methodToCall=updateExchangeRate")
3178     public ModelAndView updateExchangeRate(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3179                                                HttpServletRequest request, HttpServletResponse response)  throws Exception{
3180         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3181         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3182         BigDecimal exchangeRate = null;
3183       //  boolean invoicePriceFlag = false;
3184         oleInvoiceDocument.setDbRetrieval(false);
3185         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
3186             try {
3187                 Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
3188                 exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
3189             }
3190             catch (NumberFormatException nfe) {
3191                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
3192                 return getUIFModelAndView(oleInvoiceForm);
3193             }
3194         }  else {
3195             /*if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
3196                 exchangeRate = new KualiDecimal(getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate());
3197             }*/
3198             String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
3199             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
3200             return getUIFModelAndView(oleInvoiceForm);
3201 
3202         }
3203         if (exchangeRate != null ) {
3204             if (new KualiDecimal(exchangeRate).isZero()) {
3205                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
3206                 return getUIFModelAndView(oleInvoiceForm);
3207             }
3208             oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
3209         } else {
3210             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
3211             return getUIFModelAndView(oleInvoiceForm);
3212         }
3213         if (StringUtils.isNotBlank(oleInvoiceDocument.getForeignInvoiceAmount())) {
3214             oleInvoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(oleInvoiceDocument.getForeignInvoiceAmount()));
3215             oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(new BigDecimal(oleInvoiceDocument.getForeignInvoiceAmount()).divide(exchangeRate, 4, RoundingMode.HALF_UP)));
3216             oleInvoiceDocument.setInvoiceAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
3217             oleInvoiceDocument.setVendorAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
3218         }
3219         else {
3220             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceAmount())) {
3221                 oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getInvoiceAmount()));
3222                 oleInvoiceDocument.setForeignVendorInvoiceAmount(new KualiDecimal(new BigDecimal(oleInvoiceDocument.getInvoiceAmount()).multiply(exchangeRate)).bigDecimalValue());
3223                 oleInvoiceDocument.setForeignInvoiceAmount(oleInvoiceDocument.getForeignVendorInvoiceAmount().toString());
3224                 oleInvoiceDocument.setForeignVendorAmount(oleInvoiceDocument.getForeignVendorInvoiceAmount().toString());
3225             }
3226         }
3227 
3228         if (oleInvoiceDocument.getItems().size()>0) {
3229             for (OleInvoiceItem oleInvoiceItem : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
3230             /*    if(new KualiDecimal(oleInvoiceItem.getInvoiceListPrice()).isLessThan(KualiDecimal.ZERO)){
3231                     invoicePriceFlag = true;
3232                 }*/
3233                 if (oleInvoiceItem.getItemType().getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
3234                         oleInvoiceItem.setExchangeRate(exchangeRate.toString());
3235                         oleInvoiceItem.setItemExchangeRate(new KualiDecimal(exchangeRate));
3236                 }
3237             }
3238             if(oleInvoiceDocument.getItems().size() > 4) {
3239                 calculate(oleInvoiceForm, result, request, response);
3240                 proratedSurchargeRefresh(oleInvoiceForm, result, request, response);
3241             }
3242 
3243             if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
3244                 String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
3245                 if (StringUtils.isNotBlank(currencyType)) {
3246                   //  if(invoicePriceFlag){
3247                         oleInvoiceDocument.setDbRetrieval(false);
3248                         oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
3249                         oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
3250                         if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3251                             oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
3252                             oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
3253                         }
3254                    /* }else{
3255                         oleInvoiceDocument.setDbRetrieval(false);
3256                         oleInvoiceDocument.setInvoicedGrandTotal(oleInvoiceDocument.getInvoicedGrandTotal());
3257                         oleInvoiceDocument.setInvoiceItemTotal(oleInvoiceDocument.getInvoiceItemTotal());
3258                         if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3259                             oleInvoiceDocument.setInvoicedForeignGrandTotal(oleInvoiceDocument.getInvoicedForeignGrandTotal());
3260                             oleInvoiceDocument.setInvoicedForeignItemTotal(oleInvoiceDocument.getInvoicedForeignItemTotal());
3261                         }
3262                         oleInvoiceDocument.setItemSign(true);
3263                     }*/
3264                 }
3265             }
3266         }
3267         if (oleInvoiceDocument.getPurchaseOrderDocuments().size()>0) {
3268             for (OlePurchaseOrderDocument olePurchaseOrderDocument : oleInvoiceDocument.getPurchaseOrderDocuments()) {
3269                 for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
3270 
3271                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
3272                         String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
3273                         if (StringUtils.isNotBlank(currencyType)) {
3274                             if (StringUtils.isNotBlank(currencyType)) {
3275                                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
3276                                     olePurchaseOrderItem.setInvoiceForeignCurrency(currencyType);
3277                                     oleInvoiceDocument.setForeignCurrencyFlag(true);
3278                                     olePurchaseOrderItem.setItemDiscount(new KualiDecimal(0.0));
3279                                     olePurchaseOrderItem.setInvoiceExchangeRate(exchangeRate.toString());
3280 
3281                                     // if the PO has Foreign Currency
3282                                     if (olePurchaseOrderItem.getItemForeignListPrice() != null) {
3283                                         olePurchaseOrderItem.setInvoiceForeignItemListPrice(olePurchaseOrderItem.getItemForeignListPrice().toString());
3284                                         olePurchaseOrderItem.setInvoiceForeignDiscount(olePurchaseOrderItem.getItemForeignDiscount()!=null? olePurchaseOrderItem.getItemForeignDiscount().toString(): new KualiDecimal("0.0").toString());
3285                                         olePurchaseOrderItem.setInvoiceForeignUnitCost(olePurchaseOrderItem.getItemForeignUnitCost().toString());
3286                                         olePurchaseOrderItem.setInvoiceForeignCurrency(currencyType);
3287 
3288                                         if (olePurchaseOrderItem.getInvoiceExchangeRate() != null && olePurchaseOrderItem.getInvoiceForeignUnitCost() != null) {
3289                                             olePurchaseOrderItem.setItemUnitCostUSD(new KualiDecimal(new BigDecimal(olePurchaseOrderItem.getInvoiceForeignUnitCost()).divide(new BigDecimal(olePurchaseOrderItem.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP)));
3290                                             olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitCostUSD().bigDecimalValue());
3291                                             olePurchaseOrderItem.setItemListPrice(olePurchaseOrderItem.getItemUnitCostUSD());
3292                                             olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getItemListPrice().toString());
3293                                             olePurchaseOrderItem.setExtendedPrice(olePurchaseOrderItem.calculateExtendedPrice());
3294                                         }
3295                                     } else {
3296                                         olePurchaseOrderItem.setItemForeignUnitCost(new KualiDecimal(olePurchaseOrderItem.getItemUnitPrice().multiply(new BigDecimal(olePurchaseOrderItem.getInvoiceExchangeRate()))));
3297                                         olePurchaseOrderItem.setItemForeignListPrice(olePurchaseOrderItem.getItemForeignUnitCost());
3298                                         olePurchaseOrderItem.setInvoiceForeignItemListPrice(olePurchaseOrderItem.getItemForeignListPrice().toString());
3299                                         olePurchaseOrderItem.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
3300                                         olePurchaseOrderItem.setInvoiceForeignUnitCost(olePurchaseOrderItem.getItemForeignUnitCost().toString());
3301                                     }
3302                                 }
3303                             }
3304                         }
3305                     }
3306                     getInvoiceService().calculateAccount(olePurchaseOrderItem);
3307                 }
3308             }
3309         }
3310         return getUIFModelAndView(form);
3311     }
3312 
3313     @RequestMapping(params = "methodToCall=relatedViewBtn")
3314     public ModelAndView relatedViewBtn(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3315                                            HttpServletRequest request, HttpServletResponse response)  throws Exception{
3316         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3317         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3318         String focusId = oleInvoiceForm.getFocusId();
3319         String s = focusId.substring(focusId.indexOf("_line"),focusId.length()).replace("_line","");
3320         int unlinkDocument = Integer.parseInt(s);
3321         List<OleInvoiceItem> oleInvoiceItems = oleInvoiceDocument.getItems();
3322         OleInvoiceItem oleInvoiceItem = oleInvoiceItems.get(unlinkDocument);
3323         PurApRelatedViews relatedViews = new PurApRelatedViews(oleInvoiceDocument != null
3324                 ? oleInvoiceDocument.getDocumentNumber() : null,
3325                 oleInvoiceItem.getAccountsPayablePurchasingDocumentLinkIdentifier() != null
3326                         ? oleInvoiceItem.getAccountsPayablePurchasingDocumentLinkIdentifier() : null);
3327         oleInvoiceItem.setRelatedViews(relatedViews);
3328         oleInvoiceItem.getRelatedViews().getRelatedRequisitionViews();
3329         oleInvoiceItem.getRelatedViews().getRelatedLineItemReceivingViews();
3330         oleInvoiceItem.getRelatedViews().getRelatedCorrectionReceivingViews();
3331         oleInvoiceItem.getRelatedViews().getRelatedPaymentRequestViews();
3332         oleInvoiceItem.getRelatedViews().getRelatedCreditMemoViews();
3333         oleInvoiceItem.getRelatedViews().getPaymentHistoryPaymentRequestViews();
3334         oleInvoiceItem.getRelatedViews().getPaymentHistoryCreditMemoViews();
3335         oleInvoiceItem.setEnableDetailsSection(true);
3336         return getUIFModelAndView(form);
3337     }
3338 
3339    /* @RequestMapping(params = "methodToCall=currentItemsBtn")
3340     public ModelAndView currentItemsBtn(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3341                                        HttpServletRequest request, HttpServletResponse response)  throws Exception{
3342         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3343         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3344         oleInvoiceDocument.setEnableCurrentItems(true);
3345         return getUIFModelAndView(form);
3346     }*/
3347 
3348     @RequestMapping(params = "methodToCall=enableRouteLogDisplay")
3349     public ModelAndView enableRouteLogDisplay(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
3350                                        HttpServletRequest request, HttpServletResponse response)  throws Exception{
3351         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3352         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3353         oleInvoiceDocument.setRouteLogDisplayFlag(true);
3354         return getUIFModelAndView(form);
3355     }
3356 
3357 
3358     /**
3359      * Prompts user to confirm the cancel action then if confirmed cancels the document instance
3360      * contained on the form, Overridden to remove session from form.
3361      *
3362      * @param form - document form base containing the document instance that will be cancelled
3363      * @return ModelAndView
3364      */
3365     @RequestMapping(params = "methodToCall=cancel")
3366     @Override
3367     public ModelAndView cancel(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
3368                                HttpServletRequest request, HttpServletResponse response) {
3369 
3370         String baseUrl = ConfigContext.getCurrentContextConfig().getProperty(org.kuali.ole.OLEPropertyConstants.OLE_URL_BASE);
3371         String url = baseUrl + "/portal.do";
3372         Properties props = new Properties();
3373         props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.REFRESH);
3374         if (StringUtils.isNotBlank(form.getReturnFormKey())) {
3375             props.put(UifParameters.FORM_KEY, form.getReturnFormKey());
3376         }
3377         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3378         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3379         oleInvoiceDocument.setDbRetrieval(false);
3380         getInvoiceService().deleteInvoiceItem(oleInvoiceDocument);
3381         super.cancel(form,result,request,response);
3382         GlobalVariables.getUifFormManager().removeSessionForm(form);
3383         return performRedirect(form, url, props);
3384     }
3385 
3386     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=deleteNotes")
3387     public ModelAndView deleteNotes(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
3388                                     HttpServletRequest request, HttpServletResponse response) {
3389         LOG.debug("Inside deleteNotes()");
3390         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) uifForm;
3391         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3392         String focusId = oleInvoiceForm.getFocusId();
3393         String s = focusId.substring(focusId.indexOf("_line"),focusId.length()).replace("_line","");
3394         String lineArray[] = (focusId.substring(focusId.indexOf("_line")).split("_"));
3395         int itemLevel = Integer.parseInt(lineArray[1].replace("line",""));
3396         int noteLevel = Integer.parseInt(lineArray[2].replace("line",""));
3397         List<OleInvoiceItem> oleInvoiceItems = oleInvoiceDocument.getItems();
3398         OleInvoiceItem oleInvoiceItem = oleInvoiceItems.get(itemLevel);
3399         List<OleInvoiceNote> notes = oleInvoiceItem.getNotes();
3400         OleInvoiceNote oleInvoiceNote =  oleInvoiceItem.getNotes().remove(noteLevel);
3401         getBusinessObjectService().delete(oleInvoiceNote);
3402         return getUIFModelAndView(oleInvoiceForm);
3403     }
3404 
3405     @RequestMapping(params = "methodToCall=modifySequenceOrder")
3406     public ModelAndView modifySequenceOrder(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
3407                                 HttpServletRequest request, HttpServletResponse response) {
3408 
3409         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3410         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3411         int sequenceNumber = oleInvoiceDocument.getIndexNumberFromJsonObject(request.getParameter(OLEConstants.SEQ_NBR));
3412         int modifiedSequenceNumber = ((OleInvoiceItem) oleInvoiceDocument.getItems().get(sequenceNumber)).getSequenceNumber();
3413         if (modifiedSequenceNumber < 1) {
3414             String poId = ((OleInvoiceItem) oleInvoiceDocument.getItems().get(sequenceNumber)).getPurchaseOrderIdentifier().toString();
3415             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ITEM_SECTION_ID,
3416                     OLEKeyConstants.INV_SEQ_NBR,poId);
3417             return getUIFModelAndView(oleInvoiceForm);
3418         }
3419         int count = 0;
3420         for(OleInvoiceItem item : (List<OleInvoiceItem>)oleInvoiceDocument.getItems()) {
3421             if(item.getItemLineNumber() != null) {
3422                count++;
3423             }
3424         }
3425         if(modifiedSequenceNumber > count) {
3426             String poId = ((OleInvoiceItem) oleInvoiceDocument.getItems().get(sequenceNumber)).getPurchaseOrderIdentifier().toString();
3427             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ITEM_SECTION_ID,
3428                     OLEKeyConstants.INV_SEQ_NBR_ERR,poId);
3429             return getUIFModelAndView(oleInvoiceForm);
3430         }
3431         if(modifiedSequenceNumber <= sequenceNumber) {
3432             List<OleInvoiceItem> oleInvoiceItemList = new ArrayList<>();
3433             oleInvoiceItemList.addAll(oleInvoiceDocument.getItems());
3434             oleInvoiceItemList.add(modifiedSequenceNumber - 1, oleInvoiceItemList.get(sequenceNumber));
3435             oleInvoiceItemList.remove(sequenceNumber + 1);
3436             oleInvoiceDocument.getItems().clear();
3437             oleInvoiceDocument.getItems().addAll(oleInvoiceItemList);
3438         } else {
3439             List<OleInvoiceItem> oleInvoiceItemList = new ArrayList<>();
3440             oleInvoiceItemList.addAll(oleInvoiceDocument.getItems());
3441             oleInvoiceItemList.add(modifiedSequenceNumber , oleInvoiceItemList.get(sequenceNumber));
3442             oleInvoiceItemList.remove(sequenceNumber);
3443             oleInvoiceDocument.getItems().clear();
3444             oleInvoiceDocument.getItems().addAll(oleInvoiceItemList);
3445 
3446         }
3447         int seqNo = 0;
3448         for (OleInvoiceItem item : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
3449             if (item.getItemLineNumber() != null) {
3450                 item.setSequenceNumber(++seqNo);
3451             }
3452         }
3453         return getUIFModelAndView(oleInvoiceForm);
3454     }
3455 
3456     @RequestMapping(params = "methodToCall=populateAccountingLines")
3457     public ModelAndView populateAccountingLines(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
3458                                                            HttpServletRequest request, HttpServletResponse response) {
3459         OLEInvoiceForm oleInvoiceForm = (OLEInvoiceForm) form;
3460         OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceForm.getDocument();
3461         String accountingLineIndex = request.getParameter("accountingLineIndex");
3462         OleInvoiceItem oleInvoiceItem = (OleInvoiceItem) oleInvoiceDocument.getItem(Integer.parseInt(accountingLineIndex));
3463         Map fundMap = new HashMap();
3464         String fundCode = oleInvoiceItem.getFundCode();
3465         if (!StringUtils.isNotBlank(fundCode) && oleInvoiceDocument.getPurchaseOrderDocuments().size() > 0) {
3466             OlePurchaseOrderItem olePurchaseOrderItem = ((OlePurchaseOrderItem) oleInvoiceDocument.getPurchaseOrderDocuments().get(0).getItem(Integer.parseInt(accountingLineIndex)));
3467             if (olePurchaseOrderItem != null) {
3468                 fundCode = olePurchaseOrderItem.getFundCode();
3469                 if (fundCode != null) {
3470                     fundMap.put(org.kuali.ole.OLEConstants.OLEEResourceRecord.FUND_CODE, fundCode);
3471                     OleFundCode oleFundCode = getBusinessObjectService().findByPrimaryKey(OleFundCode.class, fundMap);
3472                     if (oleFundCode == null) {
3473                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ITEMS_FUNDCODE,
3474                                 OleSelectConstant.ERROR_INVOICE_ITEMS_FUNDCODE_INVALID);
3475                         return getUIFModelAndView(oleInvoiceForm);
3476                     } else {
3477                         if (oleFundCode.getOleFundCodeAccountingLineList() != null) {
3478                             olePurchaseOrderItem.getSourceAccountingLines().clear();
3479                             for (OleFundCodeAccountingLine oleFundCodeAccountingLine : oleFundCode.getOleFundCodeAccountingLineList()) {
3480                                 PurApAccountingLine purApAccountingLine = new OlePurchaseOrderAccount();
3481                                 purApAccountingLine.setChartOfAccountsCode(oleFundCodeAccountingLine.getChartCode());
3482                                 purApAccountingLine.setAccountNumber(oleFundCodeAccountingLine.getAccountNumber());
3483                                 purApAccountingLine.setSubAccountNumber(oleFundCodeAccountingLine.getSubAccount());
3484                                 purApAccountingLine.setFinancialObjectCode(oleFundCodeAccountingLine.getObjectCode());
3485                                 purApAccountingLine.setFinancialSubObjectCode(oleFundCodeAccountingLine.getSubObject());
3486                                 purApAccountingLine.setProjectCode(oleFundCodeAccountingLine.getProject());
3487                                 purApAccountingLine.setOrganizationReferenceId(oleFundCodeAccountingLine.getOrgRefId());
3488                                 purApAccountingLine.setAccountLinePercent(oleFundCodeAccountingLine.getPercentage());
3489                                 olePurchaseOrderItem.getSourceAccountingLines().add(purApAccountingLine);
3490                             }
3491                             olePurchaseOrderItem.setFundCode(null);
3492                         }
3493                     }
3494                 }
3495 
3496             }
3497             return getUIFModelAndView(oleInvoiceForm);
3498         }
3499         if (!StringUtils.isNotBlank(fundCode)) {
3500             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ITEMS_FUNDCODE,
3501                     OleSelectConstant.ERROR_INVOICE_ITEMS_FUNDCODE_REQUIRED);
3502             return getUIFModelAndView(oleInvoiceForm);
3503         } else {
3504             fundMap.clear();
3505             fundMap.put(org.kuali.ole.OLEConstants.OLEEResourceRecord.FUND_CODE, fundCode);
3506             OleFundCode oleFundCode = getBusinessObjectService().findByPrimaryKey(OleFundCode.class, fundMap);
3507             if (oleFundCode == null) {
3508                 GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_ITEMS_FUNDCODE,
3509                         OleSelectConstant.ERROR_INVOICE_ITEMS_FUNDCODE_INVALID);
3510                 return getUIFModelAndView(oleInvoiceForm);
3511             } else {
3512                 if (oleFundCode.getOleFundCodeAccountingLineList() != null) {
3513                     oleInvoiceItem.getSourceAccountingLines().clear();
3514                     for (OleFundCodeAccountingLine oleFundCodeAccountingLine : oleFundCode.getOleFundCodeAccountingLineList()) {
3515                         PurApAccountingLine purApAccountingLine = new InvoiceAccount();
3516                         purApAccountingLine.setChartOfAccountsCode(oleFundCodeAccountingLine.getChartCode());
3517                         purApAccountingLine.setAccountNumber(oleFundCodeAccountingLine.getAccountNumber());
3518                         purApAccountingLine.setSubAccountNumber(oleFundCodeAccountingLine.getSubAccount());
3519                         purApAccountingLine.setFinancialObjectCode(oleFundCodeAccountingLine.getObjectCode());
3520                         purApAccountingLine.setFinancialSubObjectCode(oleFundCodeAccountingLine.getSubObject());
3521                         purApAccountingLine.setProjectCode(oleFundCodeAccountingLine.getProject());
3522                         purApAccountingLine.setOrganizationReferenceId(oleFundCodeAccountingLine.getOrgRefId());
3523                         purApAccountingLine.setAccountLinePercent(oleFundCodeAccountingLine.getPercentage());
3524                         oleInvoiceItem.getSourceAccountingLines().add(purApAccountingLine);
3525                     }
3526                     oleInvoiceItem.setFundCode(null);
3527                 }
3528             }
3529         }
3530         return getUIFModelAndView(oleInvoiceForm);
3531     }
3532 
3533 
3534     /*public Integer getIndexNumberFromJsonObject(String sequenceObject) {
3535         Integer returnValue = null;
3536         try {
3537             JSONObject jsonObject = new JSONObject(sequenceObject);
3538             returnValue = jsonObject.getInt(OLEConstants.INDEX_NBR);
3539         } catch (JSONException e) {
3540             e.printStackTrace();
3541         }
3542         return returnValue;
3543     }*/
3544 
3545 }