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