View Javadoc
1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.document.web.struts;
17  
18  import org.apache.struts.action.ActionForm;
19  import org.apache.struts.action.ActionForward;
20  import org.apache.struts.action.ActionMapping;
21  import org.kuali.ole.coa.businessobject.Account;
22  import org.kuali.ole.coa.businessobject.Chart;
23  import org.kuali.ole.coa.businessobject.ObjectCode;
24  import org.kuali.ole.gl.businessobject.Balance;
25  import org.kuali.ole.gl.businessobject.Entry;
26  import org.kuali.ole.module.purap.businessobject.PaymentRequestAccount;
27  import org.kuali.ole.select.businessobject.*;
28  import org.kuali.ole.select.document.OleFundLookupDocument;
29  import org.kuali.ole.select.document.OlePaymentRequestDocument;
30  import org.kuali.ole.sys.OLEConstants;
31  import org.kuali.ole.sys.OLEKeyConstants;
32  import org.kuali.ole.sys.businessobject.FinancialSystemDocumentHeader;
33  import org.kuali.ole.sys.businessobject.GeneralLedgerPendingEntry;
34  import org.kuali.ole.sys.context.SpringContext;
35  import org.kuali.ole.sys.service.UniversityDateService;
36  import org.kuali.rice.core.api.util.RiceConstants;
37  import org.kuali.rice.core.api.util.type.KualiDecimal;
38  import org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase;
39  import org.kuali.rice.krad.service.BusinessObjectService;
40  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
41  import org.kuali.rice.krad.service.LookupService;
42  import org.kuali.rice.krad.util.GlobalVariables;
43  
44  import javax.servlet.http.HttpServletRequest;
45  import javax.servlet.http.HttpServletResponse;
46  import java.util.*;
47  
48  /**
49   * This class is the Action Class for OleFundLookup
50   */
51  public class OleFundLookupAction extends KualiTransactionalDocumentActionBase {
52  
53      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleFundLookupAction.class);
54      List<OleFundLookup> searchResult = new ArrayList<OleFundLookup>();
55      List<OleFundLookup> searchPendingList = new ArrayList<OleFundLookup>();
56      List<OleFundLookup> searchEntryList = new ArrayList<OleFundLookup>();
57      List<OleFundLookup> searchMergedPendingList = new ArrayList<OleFundLookup>();
58      List<OleFundLookup> finalSearchResult = new ArrayList<OleFundLookup>();
59  
60      public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request,
61                                 HttpServletResponse response) throws Exception {
62          return mapping.findForward(OLEConstants.MAPPING_BASIC);
63      }
64  
65      /**
66       * This method returns the list of values that satisfy the search criteria input from OleFundLookup page.
67       *
68       * @param mapping
69       * @param form
70       * @param request
71       * @param response
72       * @return
73       * @throws Exception
74       */
75      public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request,
76                                  HttpServletResponse response) throws Exception {
77  
78          List<Balance> balanceList = null;
79          List<GeneralLedgerPendingEntry> pendingList = null;
80          List<Entry> entryList = null;
81          finalSearchResult.clear();
82          searchResult.clear();
83          searchPendingList.clear();
84          searchMergedPendingList.clear();
85          searchEntryList.clear();
86          LOG.debug("Inside searchRequisitions of OleFundLookupAction");
87          OleFundLookupForm oleFundLookupForm = (OleFundLookupForm) form;
88          OleFundLookupDocument oleFundDocument = oleFundLookupForm.getOleFundLookupDocument();
89          if(oleFundDocument.getKeyword() != null){
90              oleFundDocument.setKeyword(oleFundDocument.getKeyword().toUpperCase());
91          }
92          if(oleFundDocument.getAccountNumber() != null){
93              oleFundDocument.setAccountNumber(oleFundDocument.getAccountNumber().toUpperCase());
94          }
95          if(oleFundDocument.getChartOfAccountsCode() != null){
96              oleFundDocument.setChartOfAccountsCode(oleFundDocument.getChartOfAccountsCode().toUpperCase());
97          }
98          if(oleFundDocument.getOrganizationCode() != null){
99              oleFundDocument.setOrganizationCode(oleFundDocument.getOrganizationCode().toUpperCase());
100         }
101         if(oleFundDocument.getObjectCode() != null){
102             oleFundDocument.setObjectCode(oleFundDocument.getObjectCode().toUpperCase());
103         }
104         if (oleFundDocument.getChartOfAccountsCode() == null) {
105             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
106                     OLEKeyConstants.CHART_CODE_REQUIRED);
107             return mapping.findForward(RiceConstants.MAPPING_BASIC);
108         } else if (oleFundDocument.getAccountNumber() == null) {
109             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
110                     OLEKeyConstants.ACC_NO_IS_REQUIRED);
111             return mapping.findForward(RiceConstants.MAPPING_BASIC);
112         } else if (oleFundDocument.getObjectCode() == null) {
113             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
114                     OLEKeyConstants.OBJ_CODE_REQUIRED);
115             return mapping.findForward(RiceConstants.MAPPING_BASIC);
116         } else if (oleFundDocument.getUniversityFiscalYear() == null) {
117             return mapping.findForward(RiceConstants.MAPPING_BASIC);
118         }
119 
120 
121         if(!validateChartCode(oleFundDocument.getChartOfAccountsCode())){
122             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.CHART_CODE_NOT_FOUND});
123             return mapping.findForward(RiceConstants.MAPPING_BASIC);
124         }
125         if(!validateAccountNumber(oleFundDocument.getAccountNumber())){
126             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.ACC_NO_NOT_FOUND});
127             return mapping.findForward(RiceConstants.MAPPING_BASIC);
128         }
129         if(!validateObjectCode(oleFundDocument.getObjectCode())){
130             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.OBJ_CODE_NOT_FOUND});
131             return mapping.findForward(RiceConstants.MAPPING_BASIC);
132         }
133         if(oleFundDocument.getUniversityFiscalYear() != null){
134             UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
135             if(!universityDateService.getCurrentFiscalYear().equals(oleFundDocument.getUniversityFiscalYear())){
136                 GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.UNIV_FIS_YR_FOUND});
137                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
138             }
139         }
140 
141 
142         if(oleFundDocument.getOrganizationCode() != null || oleFundDocument.getKeyword() != null){
143             Map searchCriteria = new HashMap();
144             if(oleFundDocument.getOrganizationCode() != null){
145                 searchCriteria.put(OLEConstants.OleFundLookupDocument.ORG_CODE,oleFundDocument.getOrganizationCode().toUpperCase());
146             }
147             if(oleFundDocument.getKeyword() != null) {
148                 searchCriteria.put(OLEConstants.OleFundLookupDocument.ACC_NAME, oleFundDocument.getKeyword().toUpperCase());
149             }
150             if(oleFundDocument.getChartOfAccountsCode() != null){
151                 searchCriteria.put(OLEConstants.OleFundLookupDocument.CHART_CODE, oleFundDocument.getChartOfAccountsCode().toUpperCase());
152             }
153             if(oleFundDocument.getAccountNumber() != null){
154                 searchCriteria.put(OLEConstants.OleFundLookupDocument.ACC_NO, oleFundDocument.getAccountNumber().toUpperCase());
155             }
156 
157             if(searchCriteria != null){
158                 String accountNumber = oleFundDocument.getAccountNumber();
159                 List<Account> accounts = (List) getLookupService().findCollectionBySearchHelper(Account.class, searchCriteria, true);
160                 searchCriteria.clear();
161                 List<Account> orgAccounts;
162                 List<Account> keywordList;
163                 List<String> organizationCodeList = new ArrayList<String>();
164                 List<String> accountNameList = new ArrayList<String>();
165                 if(oleFundDocument.getOrganizationCode() != null){
166                     searchCriteria.clear();
167                     searchCriteria.put(OLEConstants.OleFundLookupDocument.ORG_CODE,oleFundDocument.getOrganizationCode().toUpperCase());
168                     orgAccounts = (List)getLookupService().findCollectionBySearchHelper(Account.class, searchCriteria, true);
169                     if(orgAccounts.size() >0){
170                     for(Account account : orgAccounts){
171                         organizationCodeList.add(account.getOrganizationCode());
172                     }
173                     }
174                 }
175                 if(oleFundDocument.getKeyword() != null){
176                     searchCriteria.clear();
177                     searchCriteria.put(OLEConstants.OleFundLookupDocument.ACC_NAME,oleFundDocument.getKeyword());
178                     keywordList = (List)getLookupService().findCollectionBySearchHelper(Account.class, searchCriteria, true);
179                     if(keywordList.size() >0){
180                         for(Account account : keywordList){
181                             accountNameList.add(account.getAccountName());
182                         }
183                     }
184                 }
185 
186                 //List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class,searchCriteria);
187                 if(accounts.size() > 0){
188                     for(Account account : accounts){
189                         if(oleFundDocument.getOrganizationCode() == null || organizationCodeList.contains(account.getOrganizationCode()) && (oleFundDocument.getKeyword() == null || accountNameList.contains(account.getAccountName()))){
190                             //if(oleFundDocument.getKeyword() == null || accountNameList.contains(account.getAccountName())){
191                         oleFundDocument.setAccountNumber(account.getAccountNumber());
192                         balanceList = getBalanceEntries(oleFundDocument);
193                         pendingList = getGLPendingEntries(oleFundDocument);
194                         entryList = getEntries(oleFundDocument);
195                         Map<String,String> searchResultMap = new HashMap<String,String>();
196                         if(balanceList.size() > 0){
197                             for(Balance balance : balanceList){
198                                 String value =  balance.getChartOfAccountsCode()+"-"+balance.getAccountNumber()+"-"+balance.getObjectCode()+"-"+balance.getUniversityFiscalYear();
199                                 searchResultMap.put(value,value);
200                             }
201                         }
202                         if(pendingList.size() > 0){
203                             for(GeneralLedgerPendingEntry glPendingEntry : pendingList){
204                                 String value = glPendingEntry.getChartOfAccountsCode()+"-"+glPendingEntry.getAccountNumber()+"-"+glPendingEntry.getFinancialObjectCode()+"-"+glPendingEntry.getUniversityFiscalYear();
205                                 searchResultMap.put(value,value);
206                             }
207                         }
208                         if(entryList.size() > 0){
209                             for(Entry entry : entryList){
210                                 String value = entry.getChartOfAccountsCode()+"-"+entry.getAccountNumber()+"-"+entry.getFinancialObjectCode()+"-"+entry.getUniversityFiscalYear();
211                                 searchResultMap.put(value,value);
212                             }
213                         }
214 
215                         if(balanceList.size()<= 0 && pendingList.size()<= 0 && entryList.size() <= 0){
216                             boolean valid = checkAccountEntry(account.getAccountNumber(), account.getChartOfAccountsCode(),oleFundDocument.getKeyword());
217                             if(!valid){
218                                 GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
219                                         OLEKeyConstants.ERROR_NO_RESULTS_FOUND);
220                             }else{
221                                 OleFundLookup oleFundLookup = new OleFundLookup();
222                                 oleFundLookup.setChartOfAccountsCode(account.getChartOfAccountsCode());
223                                 oleFundLookup.setAccountName(getAccountName(account.getAccountNumber()));
224                                 oleFundLookup.setAccountNumber(account.getAccountNumber());
225                                 if(oleFundDocument.getObjectCode().equals(OLEConstants.ALL))     {
226                                     oleFundLookup.setObjectCode(OLEConstants.ALL_OBJ_CD);
227                                 } else{
228                                     oleFundLookup.setObjectCode(oleFundDocument.getObjectCode());
229                                 }
230                                 oleFundLookup.setOrganizationCode(getOrganizationCode(account.getAccountNumber()));
231                                 oleFundLookup.setCashBalance(KualiDecimal.ZERO.toString());
232                                 oleFundLookup.setFreeBalance(KualiDecimal.ZERO.toString());
233                                 oleFundLookup.setIntialBudgetAllocation(KualiDecimal.ZERO.toString());
234                                 oleFundLookup.setNetAllocation(KualiDecimal.ZERO.toString());
235                                 oleFundLookup.setEncumbrances(KualiDecimal.ZERO.toString());
236                                 oleFundLookup.setSumPaidInvoice(KualiDecimal.ZERO.toString());
237                                 oleFundLookup.setSumUnpaidInvoice(KualiDecimal.ZERO.toString());
238                                 oleFundLookup.setExpendedPercentage(KualiDecimal.ZERO.toString());
239                                 oleFundLookup.setExpenEncumPercentage(KualiDecimal.ZERO.toString());
240                                 searchResult.add(oleFundLookup);
241                             }
242                         }
243 
244                         List searchList = new ArrayList();
245                         searchList.addAll(searchResultMap.values());
246                         finalSearchResult.clear();
247                         finalSearchResult.addAll(updateSearchResults(searchList));
248                         finalSearchResult.addAll(searchResult);
249                     }else{
250                                 GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
251                                         OLEKeyConstants.ERROR_NO_RESULTS_FOUND);
252 
253                         }
254                 }
255                     oleFundDocument.setAccountNumber(accountNumber);
256 
257                 }else{
258                     GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
259                             OLEKeyConstants.ERROR_NO_RESULTS_FOUND);
260                 }
261             }
262         }else{
263             balanceList = getBalanceEntries(oleFundDocument);
264             pendingList = getGLPendingEntries(oleFundDocument);
265             entryList = getEntries(oleFundDocument);
266             Map<String,String> searchResultMap = new HashMap<String,String>();
267             if(balanceList.size() > 0){
268                 for(Balance balance : balanceList){
269                     String value =  balance.getChartOfAccountsCode()+"-"+balance.getAccountNumber()+"-"+balance.getObjectCode()+"-"+balance.getUniversityFiscalYear();
270                     searchResultMap.put(value,value);
271                 }
272             }
273             if(pendingList.size() > 0){
274                 for(GeneralLedgerPendingEntry glPendingEntry : pendingList){
275                     String value = glPendingEntry.getChartOfAccountsCode()+"-"+glPendingEntry.getAccountNumber()+"-"+glPendingEntry.getFinancialObjectCode()+"-"+glPendingEntry.getUniversityFiscalYear();
276                     searchResultMap.put(value,value);
277                 }
278             }
279             if(entryList.size() > 0){
280                 for(Entry entry : entryList){
281                     String value = entry.getChartOfAccountsCode()+"-"+entry.getAccountNumber()+"-"+entry.getFinancialObjectCode()+"-"+entry.getUniversityFiscalYear();
282                     searchResultMap.put(value,value);
283                 }
284             }
285 
286             if(balanceList.size()<= 0 && pendingList.size()<= 0 && entryList.size() <= 0){
287                 List<Account> accountList = getAccountList(oleFundDocument.getAccountNumber(), oleFundDocument.getChartOfAccountsCode());
288 
289                 if (accountList.size() > 0) {
290                     for (Iterator<Account> accountIterator = accountList.iterator(); accountIterator.hasNext(); ) {
291                     Account account = accountIterator.next();
292                     OleFundLookup oleFundLookup = new OleFundLookup();
293                     oleFundLookup.setChartOfAccountsCode(account.getChartOfAccountsCode());
294                     oleFundLookup.setAccountName(getAccountName(account.getAccountNumber()));
295                     oleFundLookup.setAccountNumber(account.getAccountNumber());
296                         if(oleFundDocument.getObjectCode().equals(OLEConstants.ALL))     {
297                             oleFundLookup.setObjectCode(OLEConstants.ALL_OBJ_CD);
298                         } else{
299                             oleFundLookup.setObjectCode(oleFundDocument.getObjectCode());
300                         }
301                     oleFundLookup.setOrganizationCode(getOrganizationCode(account.getAccountNumber()));
302                     oleFundLookup.setCashBalance(KualiDecimal.ZERO.toString());
303                     oleFundLookup.setFreeBalance(KualiDecimal.ZERO.toString());
304                     oleFundLookup.setIntialBudgetAllocation(KualiDecimal.ZERO.toString());
305                     oleFundLookup.setNetAllocation(KualiDecimal.ZERO.toString());
306                     oleFundLookup.setEncumbrances(KualiDecimal.ZERO.toString());
307                     oleFundLookup.setSumPaidInvoice(KualiDecimal.ZERO.toString());
308                     oleFundLookup.setSumUnpaidInvoice(KualiDecimal.ZERO.toString());
309                     oleFundLookup.setExpendedPercentage(KualiDecimal.ZERO.toString());
310                     oleFundLookup.setExpenEncumPercentage(KualiDecimal.ZERO.toString());
311                     searchResult.add(oleFundLookup);
312 
313                 }
314             }
315         }
316             List searchList = new ArrayList();
317             searchList.addAll(searchResultMap.values());
318             finalSearchResult.addAll(updateSearchResults(searchList));
319             finalSearchResult.addAll(searchResult);
320         }
321 
322 
323         Collections.sort(finalSearchResult, new Comparator<OleFundLookup>() {
324             public int compare(OleFundLookup fundLookup1, OleFundLookup fundLookup2) {
325                 String firstString = fundLookup1.getAccountNumber();
326                 String secondString = fundLookup2.getAccountNumber();
327                 if (secondString == null || firstString == null) {
328                     return 0;
329                 }
330                 int lengthFirstStr = firstString.length();
331                 int lengthSecondStr = secondString.length();
332                 int index1 = 0;
333                 int index2 = 0;
334                 while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
335                     char ch1 = firstString.charAt(index1);
336                     char ch2 = secondString.charAt(index2);
337 
338                     char[] space1 = new char[lengthFirstStr];
339                     char[] space2 = new char[lengthSecondStr];
340 
341                     int loc1 = 0;
342                     int loc2 = 0;
343 
344                     do {
345                         space1[loc1++] = ch1;
346                         index1++;
347 
348                         if (index1 < lengthFirstStr) {
349                             ch1 = firstString.charAt(index1);
350                         } else {
351                             break;
352                         }
353                     } while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
354 
355                     do {
356                         space2[loc2++] = ch2;
357                         index2++;
358 
359                         if (index2 < lengthSecondStr) {
360                             ch2 = secondString.charAt(index2);
361                         } else {
362                             break;
363                         }
364                     } while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
365 
366                     String str1 = new String(space1);
367                     String str2 = new String(space2);
368 
369                     int result;
370 
371                     if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
372                         Integer firstNumberToCompare = new Integer(Integer
373                                 .parseInt(str1.trim()));
374                         Integer secondNumberToCompare = new Integer(Integer
375                                 .parseInt(str2.trim()));
376                         result = firstNumberToCompare.compareTo(secondNumberToCompare);
377                     } else {
378                         result = str1.compareTo(str2);
379                     }
380 
381                     if (result != 0) {
382                         return result;
383                     }
384                 }
385                 return lengthFirstStr - lengthSecondStr;
386             }
387         });
388 
389 
390         Collections.sort(finalSearchResult, new Comparator<OleFundLookup>() {
391             public int compare(OleFundLookup fundLookup1, OleFundLookup fundLookup2) {
392                 String firstString = fundLookup1.getObjectCode();
393                 String secondString = fundLookup2.getObjectCode();
394                 if (secondString == null || firstString == null) {
395                     return 0;
396                 }
397                 int lengthFirstStr = firstString.length();
398                 int lengthSecondStr = secondString.length();
399                 int index1 = 0;
400                 int index2 = 0;
401                 while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
402                     char ch1 = firstString.charAt(index1);
403                     char ch2 = secondString.charAt(index2);
404 
405                     char[] space1 = new char[lengthFirstStr];
406                     char[] space2 = new char[lengthSecondStr];
407 
408                     int loc1 = 0;
409                     int loc2 = 0;
410 
411                     do {
412                         space1[loc1++] = ch1;
413                         index1++;
414 
415                         if (index1 < lengthFirstStr) {
416                             ch1 = firstString.charAt(index1);
417                         } else {
418                             break;
419                         }
420                     } while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
421 
422                     do {
423                         space2[loc2++] = ch2;
424                         index2++;
425 
426                         if (index2 < lengthSecondStr) {
427                             ch2 = secondString.charAt(index2);
428                         } else {
429                             break;
430                         }
431                     } while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
432 
433                     String str1 = new String(space1);
434                     String str2 = new String(space2);
435 
436                     int result;
437 
438                     if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
439                         Integer firstNumberToCompare = new Integer(Integer
440                                 .parseInt(str1.trim()));
441                         Integer secondNumberToCompare = new Integer(Integer
442                                 .parseInt(str2.trim()));
443                         result = firstNumberToCompare.compareTo(secondNumberToCompare);
444                     } else {
445                         result = str1.compareTo(str2);
446                     }
447 
448                     if (result != 0) {
449                         return result;
450                     }
451                 }
452                 return lengthFirstStr - lengthSecondStr;
453             }
454         });
455         oleFundDocument.setFinalResults(finalSearchResult);
456         return mapping.findForward(RiceConstants.MAPPING_BASIC);
457     }
458 
459 
460     public List<OleFundLookup> updateSearchResults(List<String> entryList) {
461         for (int i=0; i< entryList.size();i++) {
462             OleFundLookup oleFundLookup = new OleFundLookup();
463             String[] searchString = entryList.get(i).split("-");
464             String chartCode =  searchString[0];
465             String accountNumber = searchString[1];
466             String objectCode = searchString[2];
467             int fiscalYear = Integer.parseInt(searchString[3]);
468             KualiDecimal encumbranceAmount = getEncumbrance(chartCode, accountNumber,objectCode, fiscalYear);
469             KualiDecimal sumPaidInvoice = getSumPaidInvoices(chartCode, accountNumber,objectCode, fiscalYear);
470             KualiDecimal sumUnpaidInvoice = getSumUnpaidInvoices(chartCode, accountNumber, objectCode);
471             KualiDecimal budgetIncrease = getBudgetIncrease(fiscalYear,chartCode, accountNumber, objectCode);
472             KualiDecimal budgetDecrease = getBudgetDecrease(fiscalYear,chartCode, accountNumber, objectCode);
473             KualiDecimal initialBudgetAllocation = getInitialBudgetAllocation(chartCode,accountNumber,objectCode,fiscalYear);
474             KualiDecimal netAllocation = (initialBudgetAllocation.add(budgetIncrease)).subtract(budgetDecrease);
475             KualiDecimal encumExpPercentage = ((sumPaidInvoice.add(encumbranceAmount)).multiply(new KualiDecimal(100)));
476             if(!encumExpPercentage.isZero() && netAllocation.isGreaterThan(KualiDecimal.ZERO)){
477                 encumExpPercentage = encumExpPercentage.divide(netAllocation);
478             }else{
479                 encumExpPercentage = KualiDecimal.ZERO;
480             }
481             KualiDecimal expenPercentage = sumPaidInvoice.multiply(new KualiDecimal(100));
482             if(!expenPercentage.isZero() && netAllocation.isGreaterThan(KualiDecimal.ZERO)){
483                 expenPercentage = expenPercentage.divide(netAllocation);
484             }else{
485                 expenPercentage = KualiDecimal.ZERO;
486             }
487             oleFundLookup.setChartOfAccountsCode(chartCode);
488             oleFundLookup.setAccountNumber(accountNumber);
489             oleFundLookup.setAccountName(getAccountName(accountNumber));
490             oleFundLookup.setOrganizationCode(getOrganizationCode(accountNumber));
491             oleFundLookup.setObjectCode(objectCode);
492             oleFundLookup.setCashBalance(convertNegativeSign(netAllocation.subtract(sumPaidInvoice)));
493             oleFundLookup.setFreeBalance(convertNegativeSign((netAllocation.subtract(sumPaidInvoice)).subtract(encumbranceAmount)));
494             oleFundLookup.setIntialBudgetAllocation(initialBudgetAllocation.toString());
495             oleFundLookup.setNetAllocation(convertNegativeSign(netAllocation));
496             oleFundLookup.setEncumbrances(convertNegativeSign(encumbranceAmount));
497             oleFundLookup.setSumPaidInvoice(convertNegativeSign(sumPaidInvoice));
498             oleFundLookup.setSumUnpaidInvoice(convertNegativeSign(sumUnpaidInvoice));
499             oleFundLookup.setExpendedPercentage(convertNegativeSign(expenPercentage));
500             oleFundLookup.setExpenEncumPercentage(convertNegativeSign(encumExpPercentage));
501             searchEntryList.add(oleFundLookup);
502         }
503         return searchEntryList;
504 
505     }
506 
507     public List<Entry> getEntries(OleFundLookupDocument oleFundDocument) {
508         Map searchMap = new HashMap();
509         searchMap.put("accountNumber", oleFundDocument.getAccountNumber());
510         searchMap.put("chartOfAccountsCode", oleFundDocument.getChartOfAccountsCode());
511         searchMap.put("financialObjectCode", oleFundDocument.getObjectCode());
512         searchMap.put("universityFiscalYear", oleFundDocument.getUniversityFiscalYear());
513         List<Entry> list = new ArrayList<Entry>();
514         List<Entry> entryList = (List) SpringContext.getBean(BusinessObjectService.class).
515                 findMatching(Entry.class, searchMap);
516         for(Entry entry : entryList){
517             if(!entry.getTransactionLedgerEntryDescription().equals("TP Generated Offset") && !entry.getTransactionLedgerEntryDescription().equals("GENERATED OFFSET")){
518                 list.add(entry);
519             }
520         }
521         return list;
522     }
523 
524     public List<Balance> getBalanceEntries(OleFundLookupDocument oleFundDocument) {
525         Map searchMap = new HashMap();
526         searchMap.put("accountNumber", oleFundDocument.getAccountNumber());
527         searchMap.put("chartOfAccountsCode", oleFundDocument.getChartOfAccountsCode());
528         searchMap.put("objectCode", oleFundDocument.getObjectCode());
529         searchMap.put("universityFiscalYear", oleFundDocument.getUniversityFiscalYear());
530         searchMap.put("balanceTypeCode","CB");
531         List<Balance> balanceList = new ArrayList<Balance>();
532         balanceList = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Balance.class, searchMap);
533         return balanceList;
534     }
535 
536     public List<GeneralLedgerPendingEntry> getGLPendingEntries(OleFundLookupDocument oleFundDocument) {
537         Map searchMap = new HashMap();
538         searchMap.put("accountNumber", oleFundDocument.getAccountNumber());
539         searchMap.put("chartOfAccountsCode", oleFundDocument.getChartOfAccountsCode());
540         searchMap.put("financialObjectCode", oleFundDocument.getObjectCode());
541         searchMap.put("universityFiscalYear", oleFundDocument.getUniversityFiscalYear());
542         searchMap.put("transactionEntryOffsetIndicator","N");
543         List<GeneralLedgerPendingEntry> pendingEntryList = new ArrayList<GeneralLedgerPendingEntry>();
544         pendingEntryList = (List) SpringContext.getBean(BusinessObjectService.class).
545                 findMatching(GeneralLedgerPendingEntry.class, searchMap);
546         return pendingEntryList;
547     }
548 
549 
550     public KualiDecimal getInitialBudgetAllocation(String chartCode,String accountNumber,String financialObjectCode,int fiscalYear){
551         KualiDecimal initialBUdgetAllocation = KualiDecimal.ZERO;
552         Map searchMap = new HashMap();
553         searchMap.put("accountNumber", accountNumber);
554         searchMap.put("chartOfAccountsCode", chartCode);
555         searchMap.put("objectCode", financialObjectCode);
556         searchMap.put("balanceTypeCode", "CB");
557         searchMap.put("universityFiscalYear",fiscalYear);
558         List<Balance> balances = (List) SpringContext.getBean(BusinessObjectService.class).
559                 findMatching(Balance.class, searchMap);
560         if (balances.size() > 0) {
561             for (Balance balance : balances) {
562                 if (balance.getAccountLineAnnualBalanceAmount().isGreaterThan(KualiDecimal.ZERO)) {
563                     initialBUdgetAllocation = initialBUdgetAllocation.add(balance.getAccountLineAnnualBalanceAmount());
564                 }
565             }
566         }
567         return initialBUdgetAllocation;
568     }
569 
570     public String getAccountName(String accountNumber) {
571         Map searchMap = new HashMap();
572         String accountName = "";
573         searchMap.put("accountNumber", accountNumber);
574         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
575         if (accounts.size() > 0) {
576             return accounts.get(0).getAccountName();
577         }
578         return accountName;
579     }
580 
581     public String getOrganizationCode(String accountNumber) {
582         Map searchMap = new HashMap();
583         String organizationCode = "";
584         searchMap.put("accountNumber", accountNumber);
585         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
586         if (accounts.size() > 0) {
587             return accounts.get(0).getOrganizationCode();
588         }
589         return organizationCode;
590     }
591 
592     public KualiDecimal getEncumbrance(String chartCode, String accountNumber, String objectCode, Integer fiscalYear) {
593 
594         Map searchMap = new HashMap();
595         KualiDecimal encumbranceAmount = KualiDecimal.ZERO;
596         KualiDecimal creditAmount = KualiDecimal.ZERO;
597         KualiDecimal debitAmount = KualiDecimal.ZERO;
598         searchMap.put("accountNumber", accountNumber);
599         searchMap.put("chartOfAccountsCode", chartCode);
600         searchMap.put("financialObjectCode", objectCode);
601         searchMap.put("universityFiscalYear", fiscalYear);
602         searchMap.put("financialBalanceTypeCode", "EX");
603         searchMap.put("financialDocumentApprovedCode", "A");
604         List<GeneralLedgerPendingEntry> poPendingEntry = (List) SpringContext.getBean(BusinessObjectService.class).
605                 findMatching(GeneralLedgerPendingEntry.class, searchMap);
606         if (poPendingEntry.size() > 0) {
607             for (GeneralLedgerPendingEntry generalLedgerPendingEntry : poPendingEntry) {
608                 if (generalLedgerPendingEntry.getTransactionDebitCreditCode().equals("D")) {
609                     debitAmount = debitAmount.add(generalLedgerPendingEntry.getTransactionLedgerEntryAmount());
610                 } else if (generalLedgerPendingEntry.getTransactionDebitCreditCode().equals("C")) {
611                     if(!generalLedgerPendingEntry.getFinancialDocumentTypeCode().equals("OLE_POR")) {
612                         creditAmount = creditAmount.add(generalLedgerPendingEntry.getTransactionLedgerEntryAmount());
613                     }
614                 }
615             }
616         }
617 
618         searchMap.clear();
619         searchMap.put("accountNumber", accountNumber);
620         searchMap.put("chartOfAccountsCode", chartCode);
621         searchMap.put("financialObjectCode", objectCode);
622         searchMap.put("universityFiscalYear", fiscalYear);
623         searchMap.put("financialBalanceTypeCode", "EX");
624 
625         List<Entry> poEntry = (List) SpringContext.getBean(BusinessObjectService.class).
626                 findMatching(Entry.class, searchMap);
627         if (poEntry.size() > 0) {
628             for (Entry entry : poEntry) {
629                 if (entry.getTransactionDebitCreditCode().equals("D")) {
630                     debitAmount = debitAmount.add(entry.getTransactionLedgerEntryAmount());
631                 } else if (entry.getTransactionDebitCreditCode().equals("C")) {
632                     if(!entry.getFinancialDocumentTypeCode().equals("OLE_POR")){
633                         creditAmount = creditAmount.add(entry.getTransactionLedgerEntryAmount());
634                     }
635                 }
636             }
637         }
638         encumbranceAmount = debitAmount.subtract(creditAmount);
639         return encumbranceAmount;
640 
641     }
642 
643 
644     public KualiDecimal getSumPaidInvoices (String chartCode, String accountNumber, String objectCode, Integer
645             fiscalYear){
646 
647         KualiDecimal paidInvoice = KualiDecimal.ZERO;
648         KualiDecimal credit = KualiDecimal.ZERO;
649         KualiDecimal debit = KualiDecimal.ZERO;
650 
651         Map searchMap = new HashMap();
652         searchMap.put("accountNumber", accountNumber);
653         searchMap.put("chartOfAccountsCode", chartCode);
654         searchMap.put("financialObjectCode", objectCode);
655         searchMap.put("universityFiscalYear", fiscalYear);
656         searchMap.put("financialBalanceTypeCode", "AC");
657         searchMap.put("financialDocumentApprovedCode", "A");
658         List<GeneralLedgerPendingEntry> preqPendingEntry = (List) SpringContext.getBean(BusinessObjectService.class).
659                 findMatching(GeneralLedgerPendingEntry.class, searchMap);
660         if (preqPendingEntry.size() > 0) {
661             for (GeneralLedgerPendingEntry generalLedgerPendingEntry : preqPendingEntry) {
662                 if (generalLedgerPendingEntry.getTransactionDebitCreditCode().equals("D")) {
663                     debit = debit.add(generalLedgerPendingEntry.getTransactionLedgerEntryAmount());
664                 } else if (generalLedgerPendingEntry.getTransactionDebitCreditCode().equals("C")) {
665                     credit = credit.add(generalLedgerPendingEntry.getTransactionLedgerEntryAmount());
666                 }
667 
668             }
669         }
670 
671 
672         searchMap.clear();
673         searchMap.put("accountNumber", accountNumber);
674         searchMap.put("chartOfAccountsCode", chartCode);
675         searchMap.put("financialObjectCode", objectCode);
676         searchMap.put("universityFiscalYear", fiscalYear);
677         searchMap.put("financialBalanceTypeCode", "AC");
678         searchMap.put("financialDocumentTypeCode", "OLE_PREQ");
679         List<Entry> entryList = (List) SpringContext.getBean(BusinessObjectService.class).
680                 findMatching(Entry.class, searchMap);
681         if (entryList.size() > 0) {
682             for (Entry entry : entryList) {
683                 if (entry.getTransactionDebitCreditCode().equals("D")) {
684                     debit = debit.add(entry.getTransactionLedgerEntryAmount());
685                 } else if (entry.getTransactionDebitCreditCode().equals("C")) {
686                     credit = credit.add(entry.getTransactionLedgerEntryAmount());
687                 }
688             }
689         }
690         if(debit.isGreaterThan(credit)){
691             if(credit.isLessEqual(KualiDecimal.ZERO)){
692                 credit = credit.negated();
693             }
694             paidInvoice = debit.subtract(credit);
695         } else{
696             paidInvoice = credit.subtract(debit);
697         }
698         return paidInvoice;
699     }
700 
701     public KualiDecimal getBudgetIncrease (Integer fiscalYear, String chartCode, String accountNo,
702                                            String objectCode){
703         Map searchMap = new HashMap();
704         searchMap.put("universityFiscalYear", fiscalYear);
705         searchMap.put("chartOfAccountsCode", chartCode);
706         searchMap.put("accountNumber", accountNo);
707         searchMap.put("financialObjectCode", objectCode);
708         searchMap.put("financialDocumentTypeCode", OLEConstants.DOC_TYP_CD);
709         searchMap.put("financialBalanceTypeCode", OLEConstants.BAL_TYP_CD);
710         searchMap.put("financialDocumentApprovedCode", OLEConstants.FDOC_APPR_CD);
711         List<GeneralLedgerPendingEntry> generalLedgerPendingEntryList = (List<GeneralLedgerPendingEntry>) SpringContext.getBean(
712                 BusinessObjectService.class).findMatching(GeneralLedgerPendingEntry.class, searchMap);
713         KualiDecimal budgetIncrease = KualiDecimal.ZERO;
714         if (generalLedgerPendingEntryList.size() > 0) {
715             for (GeneralLedgerPendingEntry entry : generalLedgerPendingEntryList) {
716                 if (entry.getTransactionLedgerEntryAmount().isGreaterThan(KualiDecimal.ZERO)) {
717                     budgetIncrease = budgetIncrease.add(entry.getTransactionLedgerEntryAmount());
718                 }
719             }
720         }
721 
722         return budgetIncrease;
723     }
724 
725     public KualiDecimal getBudgetDecrease (Integer fiscalYear, String chartCode, String accountNo,
726                                            String objectCode){
727         Map searchMap = new HashMap();
728         searchMap.put("universityFiscalYear", fiscalYear);
729         searchMap.put("chartOfAccountsCode", chartCode);
730         searchMap.put("accountNumber", accountNo);
731         searchMap.put("financialObjectCode", objectCode);
732         searchMap.put("financialDocumentTypeCode", OLEConstants.DOC_TYP_CD);
733         searchMap.put("financialBalanceTypeCode", OLEConstants.BAL_TYP_CD);
734         searchMap.put("financialDocumentApprovedCode", OLEConstants.FDOC_APPR_CD);
735         List<GeneralLedgerPendingEntry> generalLedgerPendingEntryList = (List<GeneralLedgerPendingEntry>) SpringContext.getBean(
736                 BusinessObjectService.class).findMatching(GeneralLedgerPendingEntry.class, searchMap);
737         KualiDecimal budgetDecrease = KualiDecimal.ZERO;
738         if (generalLedgerPendingEntryList.size() > 0) {
739             for (GeneralLedgerPendingEntry entry : generalLedgerPendingEntryList) {
740                 if (entry.getTransactionLedgerEntryAmount().isNegative()) {
741                     budgetDecrease = budgetDecrease.add(entry.getTransactionLedgerEntryAmount().multiply(new KualiDecimal(-1)));
742                 }
743             }
744         }
745         return budgetDecrease;
746     }
747 
748     public KualiDecimal getSumUnpaidInvoices (String chartCode, String accountNo, String objectCode){
749         Map payMap = new HashMap();
750         payMap.put("chartOfAccountsCode", chartCode);
751         payMap.put("accountNumber", accountNo);
752         payMap.put("financialObjectCode", objectCode);
753         Map docMap = new HashMap();
754         docMap.put("financialDocumentStatusCode", OLEConstants.FIN_DOC_STS_CD);
755         KualiDecimal amount = KualiDecimal.ZERO;
756         List<FinancialSystemDocumentHeader> docList = (List<FinancialSystemDocumentHeader>) SpringContext.getBean(
757                 BusinessObjectService.class).findMatching(FinancialSystemDocumentHeader.class, docMap);
758         if (docList.size() > 0) {
759             for (FinancialSystemDocumentHeader financialSystemDocumentHeader : docList) {
760                 String fdocNo = financialSystemDocumentHeader.getDocumentNumber();
761                 Map reqMap = new HashMap();
762                 reqMap.put("documentNumber", fdocNo);
763                 List<OlePaymentRequestDocument> reqList = (List<OlePaymentRequestDocument>) SpringContext.getBean(
764                         BusinessObjectService.class).findMatching(OlePaymentRequestDocument.class, reqMap);
765                 if (reqList.size() > 0) {
766                     for (OlePaymentRequestDocument oleRequestDocument : reqList) {
767                         Integer payReqItmId = oleRequestDocument.getPurapDocumentIdentifier();
768                         Map itmMap = new HashMap();
769                         itmMap.put("purapDocumentIdentifier", payReqItmId);
770                         List<OlePaymentRequestItem> itemList = (List<OlePaymentRequestItem>) SpringContext.getBean(
771                                 BusinessObjectService.class).findMatching(OlePaymentRequestItem.class, itmMap);
772                         if (itemList.size() > 0) {
773                             for (OlePaymentRequestItem olePaymentRequestItem : itemList) {
774                                 Integer itemIdentifier = olePaymentRequestItem.getItemIdentifier();
775                                 Map itemMap = new HashMap();
776                                 itemMap.put("itemIdentifier", itemIdentifier);
777                                 itemMap.put("chartOfAccountsCode", chartCode);
778                                 itemMap.put("accountNumber", accountNo);
779                                 itemMap.put("financialObjectCode", objectCode);
780                                 List<PaymentRequestAccount> payReqList = (List<PaymentRequestAccount>) SpringContext
781                                         .getBean(BusinessObjectService.class).findMatching(PaymentRequestAccount.class,
782                                                 itemMap);
783                                 if (payReqList.size() > 0) {
784                                     for (PaymentRequestAccount paymentRequestAccount : payReqList) {
785                                         amount = amount.add(paymentRequestAccount.getAmount());
786 
787                                     }
788                                 }
789                             }
790                         }
791                     }
792                 }
793             }
794         }
795         return amount;
796     }
797 
798     @Override
799     public ActionForward cancel (ActionMapping mapping, ActionForm form, HttpServletRequest request,
800                                  HttpServletResponse response)throws Exception {
801         OleFundLookupForm lookupForm = (OleFundLookupForm) form;
802         return returnToSender(request, mapping, lookupForm);
803     }
804 
805 
806     @Override
807     public ActionForward refresh (ActionMapping mapping, ActionForm form, HttpServletRequest request,
808                                   HttpServletResponse response)throws Exception {
809         return super.refresh(mapping, form, request, response);
810     }
811 
812 
813     /**
814      * This method clears the search criteria's that is on the FundLookup Search Page
815      *
816      * @param mapping
817      * @param form
818      * @param request
819      * @param response
820      * @return
821      * @throws Exception
822      */
823     public ActionForward clear (ActionMapping mapping, ActionForm form, HttpServletRequest request,
824                                 HttpServletResponse response)throws Exception {
825         OleFundLookupForm oleFundLookupForm = (OleFundLookupForm) form;
826         OleFundLookupDocument oleFundLookDocument = (OleFundLookupDocument) oleFundLookupForm.getDocument();
827         oleFundLookDocument.setAccountNumber(null);
828         oleFundLookDocument.setKeyword(null);
829         oleFundLookDocument.setChartOfAccountsCode(null);
830         oleFundLookDocument.setObjectCode(null);
831         oleFundLookDocument.setOrganizationCode(null);
832         oleFundLookDocument.setUniversityFiscalYear(null);
833         oleFundLookupForm.setOleFundLookupDocument(null);
834         return mapping.findForward(RiceConstants.MAPPING_BASIC);
835     }
836 
837     public String convertNegativeSign (KualiDecimal convertTo){
838         if (convertTo.isLessThan(KualiDecimal.ZERO)) {
839             String converted = convertTo.toString().replace("-", "");
840             return "(" + converted + ")";
841         }
842         return convertTo.toString();
843     }
844 
845     public boolean validateChartCode(String chartCode) {
846         Map searchMap = new HashMap();
847         searchMap.put(OLEConstants.CHART_CODE, chartCode);
848         Chart chart = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Chart.class, searchMap);
849         if (chart != null) {
850             return true;
851         }
852         return false;
853     }
854 
855     public boolean validateAccountNumber(String accountNumber) {
856         Map searchMap = new HashMap();
857         searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
858         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class, searchMap);
859         if (account != null) {
860             return true;
861         }
862         return false;
863     }
864 
865     public boolean validateObjectCode(String objectCode) {
866         Map searchMap = new HashMap();
867         searchMap.put(OLEConstants.FINANCIAL_OBJECT_CODE_PROPERTY_NAME, objectCode);
868         ObjectCode code = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(ObjectCode.class, searchMap);
869         if (code != null) {
870             return true;
871         }
872         return false;
873     }
874 
875     public boolean checkAccountEntry(String accountNumber,String chartCode,String accountName) {
876         Map searchMap = new HashMap();
877         searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
878         searchMap.put(OLEConstants.CHART_CODE,chartCode);
879         Account account =  SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class, searchMap);
880         if (account != null && accountName != null) {
881              searchMap.clear();
882             searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
883             searchMap.put(OLEConstants.OleFundLookupDocument.ACC_NAME,accountName);
884             List<Account> accountList = (List) getLookupService().findCollectionBySearchHelper(Account.class, searchMap, true);
885             if(accountList.size() > 0){
886                 if(account.getAccountName().equals(accountList.get(0).getAccountName())){
887                     return true;
888                 }else{
889                     return false;
890                 }
891             }
892         }
893         else if (account != null){
894             return true;
895         }
896         return false;
897     }
898 
899 
900     public List<Account> getAccountList(String accountNumber,String chartCode) {
901         Map searchMap = new HashMap();
902         searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
903         searchMap.put(OLEConstants.CHART_CODE,chartCode);
904         List<Account> accountList = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
905         return accountList;
906     }
907 
908     private LookupService getLookupService() {
909         return KRADServiceLocatorWeb.getLookupService();
910     }
911 
912 
913 }