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.commons.lang.ArrayUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.struts.action.ActionForm;
21  import org.apache.struts.action.ActionForward;
22  import org.apache.struts.action.ActionMapping;
23  import org.kuali.ole.coa.businessobject.Account;
24  import org.kuali.ole.coa.businessobject.Chart;
25  import org.kuali.ole.coa.businessobject.ObjectCode;
26  import org.kuali.ole.gl.Constant;
27  import org.kuali.ole.gl.GeneralLedgerConstants;
28  import org.kuali.ole.gl.OJBUtility;
29  import org.kuali.ole.gl.batch.service.AccountBalanceCalculator;
30  import org.kuali.ole.gl.businessobject.AccountBalance;
31  import org.kuali.ole.gl.businessobject.Balance;
32  import org.kuali.ole.gl.businessobject.Entry;
33  import org.kuali.ole.gl.businessobject.TransientBalanceInquiryAttributes;
34  import org.kuali.ole.gl.businessobject.lookup.AccountBalanceLookupableHelperServiceImpl;
35  import org.kuali.ole.gl.businessobject.lookup.BusinessObjectFieldConverter;
36  import org.kuali.ole.gl.service.AccountBalanceService;
37  import org.kuali.ole.module.purap.businessobject.PaymentRequestAccount;
38  import org.kuali.ole.select.businessobject.*;
39  import org.kuali.ole.select.document.OleFundLookupDocument;
40  import org.kuali.ole.select.document.OlePaymentRequestDocument;
41  import org.kuali.ole.sys.OLEConstants;
42  import org.kuali.ole.sys.OLEKeyConstants;
43  import org.kuali.ole.sys.OLEPropertyConstants;
44  import org.kuali.ole.sys.businessobject.FinancialSystemDocumentHeader;
45  import org.kuali.ole.sys.businessobject.GeneralLedgerPendingEntry;
46  import org.kuali.ole.sys.businessobject.SystemOptions;
47  import org.kuali.ole.sys.context.SpringContext;
48  import org.kuali.ole.sys.service.GeneralLedgerPendingEntryService;
49  import org.kuali.ole.sys.service.OptionsService;
50  import org.kuali.ole.sys.service.UniversityDateService;
51  import org.kuali.rice.core.api.util.RiceConstants;
52  import org.kuali.rice.core.api.util.type.KualiDecimal;
53  import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
54  import org.kuali.rice.kns.service.KNSServiceLocator;
55  import org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase;
56  import org.kuali.rice.krad.lookup.CollectionIncomplete;
57  import org.kuali.rice.krad.service.BusinessObjectService;
58  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
59  import org.kuali.rice.krad.service.LookupService;
60  import org.kuali.rice.krad.util.BeanPropertyComparator;
61  import org.kuali.rice.krad.util.GlobalVariables;
62  import org.kuali.rice.krad.util.ObjectUtils;
63  
64  import javax.servlet.http.HttpServletRequest;
65  import javax.servlet.http.HttpServletResponse;
66  import java.util.*;
67  
68  /**
69   * This class is the Action Class for OleFundLookup
70   */
71  public class OleFundLookupAction extends KualiTransactionalDocumentActionBase {
72  
73      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleFundLookupAction.class);
74      List<OleFundLookup> searchResult = new ArrayList<OleFundLookup>();
75      List<OleFundLookup> searchPendingList = new ArrayList<OleFundLookup>();
76      List<OleFundLookup> searchEntryList = new ArrayList<OleFundLookup>();
77      List<OleFundLookup> searchMergedPendingList = new ArrayList<OleFundLookup>();
78      List<OleFundLookup> finalSearchResult = new ArrayList<OleFundLookup>();
79      private AccountBalanceCalculator postAccountBalance;
80      private AccountBalanceService accountBalanceService;
81      private OptionsService optionsService;
82      protected GeneralLedgerPendingEntryService generalLedgerPendingEntryService;
83      public BusinessObjectDictionaryService businessObjectDictionaryService;
84      protected Class businessObjectClass ;
85  
86      public BusinessObjectDictionaryService getBusinessObjectDictionaryService() {
87          return businessObjectDictionaryService != null ? businessObjectDictionaryService : KNSServiceLocator
88                  .getBusinessObjectDictionaryService();
89      }
90  
91      protected GeneralLedgerPendingEntryService getGeneralLedgerPendingEntryService() {
92          return SpringContext.getBean(GeneralLedgerPendingEntryService.class);
93      }
94  
95  
96      public AccountBalanceCalculator getPostAccountBalance() {
97          return SpringContext.getBean(AccountBalanceCalculator.class);
98      }
99  
100     public void setPostAccountBalance(AccountBalanceCalculator postAccountBalance) {
101         this.postAccountBalance = postAccountBalance;
102     }
103 
104     public AccountBalanceService getAccountBalanceService() {
105         return SpringContext.getBean(AccountBalanceService.class);
106     }
107 
108     public void setAccountBalanceService(AccountBalanceService accountBalanceService) {
109         this.accountBalanceService = accountBalanceService;
110     }
111 
112     public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request,
113                                HttpServletResponse response) throws Exception {
114         return mapping.findForward(OLEConstants.MAPPING_BASIC);
115     }
116 
117     public OptionsService getOptionsService() {
118         return SpringContext.getBean(OptionsService.class);
119     }
120 
121     public void setOptionsService(OptionsService optionsService) {
122         this.optionsService = optionsService;
123     }
124 
125     /**
126      * This method returns the list of values that satisfy the search criteria input from OleFundLookup page.
127      *
128      * @param mapping
129      * @param form
130      * @param request
131      * @param response
132      * @return
133      * @throws Exception
134      */
135     public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request,
136                                 HttpServletResponse response) throws Exception {
137 
138         List balanceList = null;
139         List<GeneralLedgerPendingEntry> pendingList = null;
140         List<Entry> entryList = null;
141         finalSearchResult.clear();
142         searchResult.clear();
143         searchPendingList.clear();
144         searchMergedPendingList.clear();
145         searchEntryList.clear();
146         LOG.debug("Inside searchRequisitions of OleFundLookupAction");
147         OleFundLookupForm oleFundLookupForm = (OleFundLookupForm) form;
148         OleFundLookupDocument oleFundDocument = oleFundLookupForm.getOleFundLookupDocument();
149         if(oleFundDocument.getKeyword() != null){
150             oleFundDocument.setKeyword(oleFundDocument.getKeyword().toUpperCase());
151         }
152         if(oleFundDocument.getAccountNumber() != null){
153             oleFundDocument.setAccountNumber(oleFundDocument.getAccountNumber().toUpperCase());
154         }
155         if(oleFundDocument.getChartOfAccountsCode() != null){
156             oleFundDocument.setChartOfAccountsCode(oleFundDocument.getChartOfAccountsCode().toUpperCase());
157         }
158         if(oleFundDocument.getOrganizationCode() != null){
159             oleFundDocument.setOrganizationCode(oleFundDocument.getOrganizationCode().toUpperCase());
160         }
161         if(oleFundDocument.getObjectCode() != null){
162             oleFundDocument.setObjectCode(oleFundDocument.getObjectCode().toUpperCase());
163         }
164         if (oleFundDocument.getChartOfAccountsCode() == null) {
165             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
166                     OLEKeyConstants.CHART_CODE_REQUIRED);
167             return mapping.findForward(RiceConstants.MAPPING_BASIC);
168         } else if (oleFundDocument.getAccountNumber() == null) {
169             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
170                     OLEKeyConstants.ACC_NO_IS_REQUIRED);
171             return mapping.findForward(RiceConstants.MAPPING_BASIC);
172         } else if (oleFundDocument.getObjectCode() == null) {
173             GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
174                     OLEKeyConstants.OBJ_CODE_REQUIRED);
175             return mapping.findForward(RiceConstants.MAPPING_BASIC);
176         } else if (oleFundDocument.getUniversityFiscalYear() == null) {
177             return mapping.findForward(RiceConstants.MAPPING_BASIC);
178         }
179 
180         if(oleFundDocument.getChartOfAccountsCode().equals("*")){
181             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.CHART_CODE_WILDCARD_SEARCH});
182             return mapping.findForward(RiceConstants.MAPPING_BASIC);
183         }
184         if(!validateChartCode(oleFundDocument.getChartOfAccountsCode())){
185             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.CHART_CODE_NOT_FOUND});
186             return mapping.findForward(RiceConstants.MAPPING_BASIC);
187         }
188         if(!validateAccountNumber(oleFundDocument.getAccountNumber())){
189             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.ACC_NO_NOT_FOUND});
190             return mapping.findForward(RiceConstants.MAPPING_BASIC);
191         }
192         if(!validateObjectCode(oleFundDocument.getObjectCode())){
193             GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.OBJ_CODE_NOT_FOUND});
194             return mapping.findForward(RiceConstants.MAPPING_BASIC);
195         }
196     /*    if(oleFundDocument.getUniversityFiscalYear() != null){
197             UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
198             if(!universityDateService.getCurrentFiscalYear().equals(oleFundDocument.getUniversityFiscalYear())){
199                 GlobalVariables.getMessageMap().putError(OLEConstants.DOCUMENT_ERRORS, OLEKeyConstants.ERROR_CUSTOM, new String[]{OLEConstants.UNIV_FIS_YR_FOUND});
200                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
201             }
202         }
203 */
204 
205         Map map = new HashMap();
206         map.put(OLEConstants.OleFundLookupDocument.CHART_CODE,oleFundDocument.getChartOfAccountsCode().toUpperCase() );
207         map.put(OLEConstants.OleFundLookupDocument.ACC_NO, oleFundDocument.getAccountNumber().toUpperCase());
208         map.put("sunAccountNumber","");
209         map.put("objectCode",oleFundDocument.getObjectCode());
210         map.put("universityFiscalYear",oleFundDocument.getUniversityFiscalYear() );
211         map.put("dummyBusinessObject.pendingEntryOption", "All");
212         map.put("dummyBusinessObject.consolidationOption","Consolidation" );
213         map.put("backLocation", "portal.do");
214         map.put("docFormKey","88888888" );
215         map.put("subObjectCode","" );
216 
217         balanceList = getSearchResults(map);
218         if(balanceList.size() <= 0  && !oleFundDocument.getAccountNumber().equals("*")){
219             boolean accountAvailable = checkAccountEntry(oleFundDocument.getAccountNumber(),oleFundDocument.getChartOfAccountsCode());
220             if(accountAvailable){
221                 AccountBalance accountBalance = new AccountBalance();
222                 accountBalance.setChartOfAccountsCode(oleFundDocument.getChartOfAccountsCode());
223                 accountBalance.setAccountNumber(oleFundDocument.getAccountNumber());
224                 accountBalance.setObjectCode(oleFundDocument.getObjectCode());
225                 accountBalance.setUniversityFiscalYear(Integer.parseInt(oleFundDocument.getUniversityFiscalYear()));
226                 accountBalance.setCurrentBudgetLineBalanceAmount(KualiDecimal.ZERO);
227                 accountBalance.setAccountLineEncumbranceBalanceAmount(KualiDecimal.ZERO);
228                 accountBalance.setAccountLineActualsBalanceAmount(KualiDecimal.ZERO);
229                 balanceList.add(accountBalance);
230             }
231         }
232         //CollectionIncomplete<AccountBalance> fundbBalanceResultList = null;
233         List<AccountBalance> fundbBalanceResultList = new ArrayList<AccountBalance>();
234         CollectionIncomplete<AccountBalance> fundbBalanceList = (CollectionIncomplete<AccountBalance>) balanceList;
235         List<String> accountNameList = new ArrayList<String>();
236         List<String> orgCodeList = new ArrayList<String>();
237         if(oleFundDocument.getKeyword() != null && oleFundDocument.getOrganizationCode() != null){
238             accountNameList  = getKeyword(oleFundDocument.getKeyword());
239             orgCodeList = getOrganizationCd(oleFundDocument.getOrganizationCode());
240             for (AccountBalance balance : fundbBalanceList) {
241                 if((accountNameList.contains(getAccountName(balance.getAccountNumber()))) &&
242                         (orgCodeList.contains(getOrganizationCode(balance.getAccountNumber())))){
243                     fundbBalanceResultList.add(balance);
244 
245                 }
246             }
247         }else if(oleFundDocument.getKeyword() != null){
248             accountNameList  = getKeyword(oleFundDocument.getKeyword());
249             for (AccountBalance balance : fundbBalanceList) {
250                 if((accountNameList.contains(getAccountName(balance.getAccountNumber())))){
251                     fundbBalanceResultList.add(balance);
252 
253                 }
254             }
255         }else if(oleFundDocument.getOrganizationCode() != null){
256             orgCodeList = getOrganizationCd(oleFundDocument.getOrganizationCode());
257             for (AccountBalance balance : fundbBalanceList) {
258                 if(orgCodeList.contains(getOrganizationCode(balance.getAccountNumber()))){
259                     fundbBalanceResultList.add(balance);
260 
261                 }
262             }
263         }else if(oleFundDocument.getKeyword() == null && oleFundDocument.getOrganizationCode() == null){
264             fundbBalanceResultList = fundbBalanceList;
265         }
266         if(fundbBalanceResultList != null){
267             finalSearchResult.addAll(updateSearchResults(fundbBalanceResultList));
268         }
269         if(finalSearchResult.size() > 0){
270         oleFundDocument.setFinalResults(finalSearchResult);
271         }else {
272             GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
273                     OLEKeyConstants.ERROR_NO_RESULTS_FOUND);
274             return mapping.findForward(RiceConstants.MAPPING_BASIC);
275         }
276         return mapping.findForward(RiceConstants.MAPPING_BASIC);
277     }
278 
279     public List updateSearchResults(List<AccountBalance> fundbBalanceList) {
280         for (AccountBalance balance : fundbBalanceList) {
281             OleFundLookup oleFundLookup = new OleFundLookup();
282             String chartCode =  balance.getChartOfAccountsCode();
283             String accountNumber = balance.getAccountNumber();
284             String objectCode = balance.getObjectCode();
285             int fiscalYear = balance.getUniversityFiscalYear();
286             KualiDecimal encumbranceAmount = balance.getAccountLineEncumbranceBalanceAmount();
287             KualiDecimal sumPaidInvoice = balance.getAccountLineActualsBalanceAmount();
288             KualiDecimal sumUnpaidInvoice = KualiDecimal.ZERO;
289             KualiDecimal budgetIncrease = KualiDecimal.ZERO;
290             KualiDecimal budgetDecrease = KualiDecimal.ZERO;
291             KualiDecimal initialBudgetAllocation = balance.getCurrentBudgetLineBalanceAmount();
292             KualiDecimal netAllocation = balance.getCurrentBudgetLineBalanceAmount();
293             KualiDecimal encumExpPercentage = ((sumPaidInvoice.add(encumbranceAmount)).multiply(new KualiDecimal(100)));
294             if(!encumExpPercentage.isZero() && netAllocation.isGreaterThan(KualiDecimal.ZERO)){
295                 encumExpPercentage = encumExpPercentage.divide(netAllocation);
296             }else{
297                 encumExpPercentage = KualiDecimal.ZERO;
298             }
299             KualiDecimal expenPercentage = sumPaidInvoice.multiply(new KualiDecimal(100));
300             if(!expenPercentage.isZero() && netAllocation.isGreaterThan(KualiDecimal.ZERO)){
301                 expenPercentage = expenPercentage.divide(netAllocation);
302             }else{
303                 expenPercentage = KualiDecimal.ZERO;
304             }
305             oleFundLookup.setChartOfAccountsCode(chartCode);
306             oleFundLookup.setAccountNumber(accountNumber);
307             oleFundLookup.setAccountName(getAccountName(accountNumber));
308             oleFundLookup.setOrganizationCode(getOrganizationCode(accountNumber));
309             oleFundLookup.setObjectCode(objectCode);
310             oleFundLookup.setCashBalance(convertNegativeSign(netAllocation.subtract(sumPaidInvoice)));
311             oleFundLookup.setFreeBalance(convertNegativeSign((netAllocation.subtract(sumPaidInvoice)).subtract(encumbranceAmount)));
312             oleFundLookup.setIntialBudgetAllocation(initialBudgetAllocation.toString());
313             oleFundLookup.setNetAllocation(convertNegativeSign(netAllocation));
314             oleFundLookup.setEncumbrances(convertNegativeSign(encumbranceAmount));
315             oleFundLookup.setSumPaidInvoice(convertNegativeSign(sumPaidInvoice));
316             oleFundLookup.setSumUnpaidInvoice(convertNegativeSign(sumUnpaidInvoice));
317             oleFundLookup.setExpendedPercentage(convertNegativeSign(expenPercentage));
318             oleFundLookup.setExpenEncumPercentage(convertNegativeSign(encumExpPercentage));
319             searchEntryList.add(oleFundLookup);
320         }
321         return searchEntryList;
322 
323     }
324 
325 
326 
327     public List getSearchResults(Map fieldValues) {
328 
329 
330         Collection searchResultsCollection = null;
331 
332         // get the pending entry option. This method must be prior to the get search results
333         String pendingEntryOption = this.getSelectedPendingEntryOption(fieldValues);
334 
335         // KFSMI-410: added one more node for consolidationOption
336         String consolidationOption = (String) fieldValues.get(GeneralLedgerConstants.DummyBusinessObject.CONSOLIDATION_OPTION);
337         // test if the consolidation option is selected or not
338         boolean isConsolidated = true;
339 
340 
341         if (isConsolidated) {
342             fieldValues.remove("dummyBusinessObject.consolidationOption");
343             Iterator availableBalanceIterator = getAccountBalanceService().findConsolidatedAvailableAccountBalance(fieldValues);
344             searchResultsCollection = buildConsolidedAvailableBalanceCollection(availableBalanceIterator);
345         }
346 
347 
348         // update search results according to the selected pending entry option
349         updateByPendingLedgerEntry(searchResultsCollection, fieldValues, pendingEntryOption, isConsolidated, false);
350 
351         // Put the search related stuff in the objects
352         for (Iterator iter = searchResultsCollection.iterator(); iter.hasNext();) {
353             AccountBalance ab = (AccountBalance) iter.next();
354             TransientBalanceInquiryAttributes dbo = ab.getDummyBusinessObject();
355             dbo.setConsolidationOption(consolidationOption);
356             dbo.setPendingEntryOption(pendingEntryOption);
357         }
358 
359         // get the actual size of all qualified search results
360         Integer recordCount = getAccountBalanceService().getAvailableAccountBalanceCount(fieldValues, isConsolidated);
361         Long actualSize = OJBUtility.getResultActualSize(searchResultsCollection, recordCount, fieldValues, new AccountBalance());
362         // Get the entry in Account
363   /*      SystemOptions option = getBusinessObjectService().findBySinglePrimaryKey(SystemOptions.class, Integer.parseInt((String)fieldValues.get(OLEConstants.FISCAL_YEAR)));
364         if(option != null){
365             if(searchResultsCollection.size() < 1) {
366                 String accountNumber = fieldValues.get(OLEConstants.ACCOUNT_NUMBER).toString();
367                 String chartCode = fieldValues.get(OLEConstants.CHART_CODE).toString();
368                 List<Account> accountList =  checkAccountEntry(accountNumber,chartCode);
369                 for (Iterator<Account> accountIterator = accountList.iterator(); accountIterator.hasNext(); ) {
370                     Account account = accountIterator.next();
371                     AccountBalance balance = new AccountBalance();
372                     balance.setChartOfAccountsCode(account.getChartOfAccountsCode());
373                     balance.setAccountNumber(account.getAccountNumber());
374                     String fiscalYear = fieldValues.get(OLEConstants.FISCAL_YEAR).toString();
375                     balance.setUniversityFiscalYear(Integer.parseInt(fiscalYear));
376                     balance.setObjectCode(Constant.CONSOLIDATED_OBJECT_TYPE_CODE);
377                     balance.setSubAccountNumber(Constant.CONSOLIDATED_OBJECT_TYPE_CODE);
378                     balance.setSubObjectCode(Constant.CONSOLIDATED_OBJECT_TYPE_CODE);
379                     balance.setCurrentBudgetLineBalanceAmount(KualiDecimal.ZERO);
380                     balance.setAccountLineActualsBalanceAmount(KualiDecimal.ZERO);
381                     balance.setAccountLineEncumbranceBalanceAmount(KualiDecimal.ZERO);
382                     searchResultsCollection.add(balance);
383                 }
384             }
385         }*/
386         return this.buildSearchResultList(searchResultsCollection, actualSize);
387     }
388 
389 
390     protected String getSelectedPendingEntryOption(Map fieldValues) {
391         // truncate the non-property filed
392         String pendingEntryOption = (String) fieldValues.get(Constant.PENDING_ENTRY_OPTION);
393         fieldValues.remove(Constant.PENDING_ENTRY_OPTION);
394 
395         return pendingEntryOption;
396     }
397 
398     private Collection buildConsolidedAvailableBalanceCollection(Iterator iterator) {
399         Collection balanceCollection = new ArrayList();
400 
401         // build available balance collection throught analyzing the input iterator
402         while (iterator.hasNext()) {
403             Object avaiableAccountBalance = iterator.next();
404 
405             if (avaiableAccountBalance.getClass().isArray()) {
406                 int i = 0;
407                 Object[] array = (Object[]) avaiableAccountBalance;
408                 AccountBalance accountBalance = new AccountBalance();
409 
410                 accountBalance.setUniversityFiscalYear(new Integer(array[i++].toString()));
411                 accountBalance.setChartOfAccountsCode(array[i++].toString());
412 
413                 accountBalance.setAccountNumber(array[i++].toString());
414                 accountBalance.setSubAccountNumber(Constant.CONSOLIDATED_SUB_ACCOUNT_NUMBER);
415 
416                 accountBalance.setObjectCode(array[i++].toString());
417                 accountBalance.setSubObjectCode(Constant.CONSOLIDATED_SUB_OBJECT_CODE);
418 
419                 String objectTypeCode = array[i++].toString();
420                 accountBalance.getFinancialObject().setFinancialObjectTypeCode(objectTypeCode);
421 
422                 KualiDecimal budgetAmount = new KualiDecimal(array[i++].toString());
423                 accountBalance.setCurrentBudgetLineBalanceAmount(budgetAmount);
424 
425                 KualiDecimal actualsAmount = new KualiDecimal(array[i++].toString());
426                 accountBalance.setAccountLineActualsBalanceAmount(actualsAmount);
427 
428                 KualiDecimal encumbranceAmount = new KualiDecimal(array[i].toString());
429                 accountBalance.setAccountLineEncumbranceBalanceAmount(encumbranceAmount);
430 
431                 KualiDecimal variance = calculateVariance(accountBalance);
432                 accountBalance.getDummyBusinessObject().setGenericAmount(variance);
433 
434                 balanceCollection.add(accountBalance);
435             }
436         }
437         return balanceCollection;
438     }
439 
440     private KualiDecimal calculateVariance(AccountBalance balance) {
441 
442         KualiDecimal variance = new KualiDecimal(0.0);
443         KualiDecimal budgetAmount = balance.getCurrentBudgetLineBalanceAmount();
444         KualiDecimal actualsAmount = balance.getAccountLineActualsBalanceAmount();
445         KualiDecimal encumbranceAmount = balance.getAccountLineEncumbranceBalanceAmount();
446 
447         // determine if the object type code is one of the given codes
448         if (ObjectUtils.isNull(balance.getFinancialObject()) || StringUtils.isBlank(balance.getFinancialObject().getFinancialObjectTypeCode())) {
449             balance.refreshReferenceObject("financialObject"); // refresh if we need to...
450         }
451         ObjectCode financialObject = balance.getFinancialObject();
452         String objectTypeCode = (financialObject == null) ? Constant.EMPTY_STRING : financialObject.getFinancialObjectTypeCode();
453 
454         SystemOptions options = getOptionsService().getOptions(balance.getUniversityFiscalYear());
455         if (ObjectUtils.isNull(options)) {
456             options = getOptionsService().getCurrentYearOptions();
457         }
458         String[] objectTypeCodeList = new String[3];
459         objectTypeCodeList[0] = options.getFinObjTypeExpendNotExpCode();
460         objectTypeCodeList[1] = options.getFinObjTypeExpNotExpendCode();
461         objectTypeCodeList[2] = options.getFinObjTypeExpenditureexpCd();
462 
463         boolean isObjectTypeCodeInList = ArrayUtils.contains(objectTypeCodeList, objectTypeCode);
464 
465         // calculate the variance based on the object type code of the balance
466         if (isObjectTypeCodeInList) {
467             variance = budgetAmount.subtract(actualsAmount);
468             variance = variance.subtract(encumbranceAmount);
469         }
470         else {
471             variance = actualsAmount.subtract(budgetAmount);
472         }
473         return variance;
474     }
475 
476     protected void updateByPendingLedgerEntry(Collection entryCollection, Map fieldValues, String pendingEntryOption, boolean isConsolidated, boolean isCostShareInclusive) {
477 
478 
479         updateEntryCollection(entryCollection, fieldValues, false, isConsolidated, isCostShareInclusive);
480 
481     }
482 
483     protected void updateEntryCollection(Collection entryCollection, Map fieldValues, boolean isApproved, boolean isConsolidated, boolean isCostShareExcluded) {
484 
485         // convert the field names of balance object into corresponding ones of pending entry object
486         Map pendingEntryFieldValues = BusinessObjectFieldConverter.convertToTransactionFieldValues(fieldValues);
487 
488         // go through the pending entries to update the balance collection
489         Iterator pendingEntryIterator = getGeneralLedgerPendingEntryService().findPendingLedgerEntriesForAccountBalance(pendingEntryFieldValues, isApproved);
490         while (pendingEntryIterator.hasNext()) {
491             GeneralLedgerPendingEntry pendingEntry = (GeneralLedgerPendingEntry) pendingEntryIterator.next();
492 
493             if (isCostShareExcluded) {
494                 if (ObjectUtils.isNotNull(pendingEntry.getSubAccount()) && ObjectUtils.isNotNull(pendingEntry.getSubAccount().getA21SubAccount())) {
495                     if (OLEConstants.SubAccountType.COST_SHARE.equals(pendingEntry.getSubAccount().getA21SubAccount().getSubAccountTypeCode())) {
496                         // Don't process this one
497                         continue;
498                     }
499                 }
500             }
501 
502             // if consolidated, change the following fields into the default values for consolidation
503             if (isConsolidated) {
504                 pendingEntry.setSubAccountNumber(Constant.CONSOLIDATED_SUB_ACCOUNT_NUMBER);
505                 pendingEntry.setFinancialSubObjectCode(Constant.CONSOLIDATED_SUB_OBJECT_CODE);
506                 pendingEntry.setFinancialObjectTypeCode(Constant.CONSOLIDATED_OBJECT_TYPE_CODE);
507             }
508 
509             AccountBalance accountBalance = getPostAccountBalance().findAccountBalance(entryCollection, pendingEntry);
510             getPostAccountBalance().updateAccountBalance(pendingEntry, accountBalance);
511 
512             // recalculate the variance after pending entries are combined into account balances
513             if (accountBalance.getDummyBusinessObject() == null) {
514                 accountBalance.setDummyBusinessObject(new TransientBalanceInquiryAttributes());
515             }
516             KualiDecimal variance = calculateVariance(accountBalance);
517             accountBalance.getDummyBusinessObject().setGenericAmount(variance);
518         }
519     }
520 
521     public boolean checkAccountEntry(String accountNumber,String chartCode) {
522         boolean exists = false;
523         Map searchMap = new HashMap();
524         searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
525         searchMap.put(OLEConstants.CHART_CODE,chartCode);
526         List<Account> accountList = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
527         if(accountList.size() > 0){
528             return true;
529         }
530         return false;
531     }
532 
533     protected List buildSearchResultList(Collection searchResultsCollection, Long actualSize) {
534         CollectionIncomplete results = new CollectionIncomplete(searchResultsCollection, actualSize);
535 
536         // sort list if default sort column given
537         List searchResults = results;
538         List defaultSortColumns = getDefaultSortColumns();
539         if (defaultSortColumns.size() > 0) {
540             Collections.sort(results, new BeanPropertyComparator(defaultSortColumns, true));
541         }
542         return searchResults;
543     }
544 
545     public List<String> getDefaultSortColumns() {
546         return getBusinessObjectDictionaryService().getLookupDefaultSortFieldNames(getBusinessObjectClass());
547     }
548 
549     public Class getBusinessObjectClass() {
550         return OleFundLookup.class;
551     }
552 
553     public boolean validateChartCode(String chartCode) {
554         Map searchMap = new HashMap();
555         searchMap.put(OLEConstants.CHART_CODE, chartCode);
556         Chart chart = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Chart.class, searchMap);
557         if (chart != null) {
558             return true;
559         }
560         return false;
561     }
562 
563     public boolean validateAccountNumber(String accountNumber) {
564         Map searchMap = new HashMap();
565         searchMap.put(OLEConstants.ACCOUNT_NUMBER, accountNumber);
566         Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class, searchMap);
567         if (account != null) {
568             return true;
569         }
570         return false;
571     }
572 
573     public boolean validateObjectCode(String objectCode) {
574         Map searchMap = new HashMap();
575         searchMap.put(OLEConstants.FINANCIAL_OBJECT_CODE_PROPERTY_NAME, objectCode);
576         ObjectCode code = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(ObjectCode.class, searchMap);
577         if (code != null) {
578             return true;
579         }
580         return false;
581     }
582 
583     public ActionForward clear (ActionMapping mapping, ActionForm form, HttpServletRequest request,
584                                 HttpServletResponse response)throws Exception {
585         OleFundLookupForm oleFundLookupForm = (OleFundLookupForm) form;
586         OleFundLookupDocument oleFundLookDocument = (OleFundLookupDocument) oleFundLookupForm.getDocument();
587         oleFundLookDocument.setAccountNumber(null);
588         oleFundLookDocument.setKeyword(null);
589         oleFundLookDocument.setChartOfAccountsCode(null);
590         oleFundLookDocument.setObjectCode(null);
591         oleFundLookDocument.setOrganizationCode(null);
592         oleFundLookDocument.setUniversityFiscalYear(null);
593         oleFundLookupForm.setOleFundLookupDocument(null);
594         return mapping.findForward(RiceConstants.MAPPING_BASIC);
595     }
596 
597 
598     @Override
599     public ActionForward cancel (ActionMapping mapping, ActionForm form, HttpServletRequest request,
600                                  HttpServletResponse response)throws Exception {
601         OleFundLookupForm lookupForm = (OleFundLookupForm) form;
602         return returnToSender(request, mapping, lookupForm);
603     }
604 
605     public String getAccountName(String accountNumber) {
606         Map searchMap = new HashMap();
607         String accountName = "";
608         searchMap.put("accountNumber", accountNumber);
609         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
610         if (accounts.size() > 0) {
611             return accounts.get(0).getAccountName();
612         }
613         return accountName;
614     }
615 
616     public String getOrganizationCode(String accountNumber) {
617         Map searchMap = new HashMap();
618         String organizationCode = "";
619         searchMap.put("accountNumber", accountNumber);
620         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
621         if (accounts.size() > 0) {
622             return accounts.get(0).getOrganizationCode();
623         }
624         return organizationCode;
625     }
626 
627     public String convertNegativeSign (KualiDecimal convertTo){
628         if (convertTo.isLessThan(KualiDecimal.ZERO)) {
629             String converted = convertTo.toString().replace("-", "");
630             return "(" + converted + ")";
631         }
632         return convertTo.toString();
633     }
634 
635     public List<String> getKeyword(String accountName){
636         Map searchMap = new HashMap();
637         List<String> accountNameList = new ArrayList<String>();
638         searchMap.put("accountName", accountName);
639         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
640         if (accounts.size() > 0) {
641             for(Account account : accounts){
642                 accountNameList.add(account.getAccountName());
643             }
644         }
645         return accountNameList;
646     }
647 
648     public List<String> getOrganizationCd(String orgCd){
649         Map searchMap = new HashMap();
650         List<String> orgCdList = new ArrayList<String>();
651         searchMap.put("organizationCode", orgCd);
652         List<Account> accounts = (List) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, searchMap);
653         if (accounts.size() > 0) {
654             for(Account account : accounts){
655                 orgCdList.add(account.getOrganizationCode());
656             }
657         }
658         return orgCdList;
659     }
660 
661 
662 }
663 
664 
665