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