Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
87 kB
2
Indexable
Never
/*
* Controller for CapitalCall Visualforce page. Extends Fund__c standard controller.
* Unit tests in CapitalCallControllerTest Apex class.
*
* @author: Luke
* @date: Aug 2012
*/   
public with sharing class CapitalCallController {
    public Fund__c fund { get; set; }
    public Decimal callPercent { get; set; }
    public Boolean isdataLoaded{get;set;}
    public List<Capital_Call__c> capitalCallRecords{get;set;}
    public Id BatchId {get;set;}
    public Boolean alertDisplayed {get;set;}
    public Boolean displayPopUp {get;set;}
    public SelectOption[] leftOptions { get; set; }
    public SelectOption[] rightOptions { get; set; }
    public Boolean updateFieldset {get;set;} // Used to track and display the spinner to update the fieldset.
    public Map<String,Boolean> UpdatefieldsetreturnMap {get;set;} // It holds the response which is returned from MetadataserviceHelper(availablefieldsofFieldset).
    public Integer updateFieldsetcounter {get;set;}
    public Boolean isNullOrZeroCapCommitmentCheckbox {get;set;} // This is for a checkbox Do Not Create Blank Records
    public Map<Id,Boolean> mapOfCapCommWithZeroValues {get;set;} // It holds the Id and boolean value of capital commitment

    public Decimal totalCommitment {
        get {
            // Gets the selected capital commitments and totals their capital
            totalCommitment = 0.0;
            List<Capital_Commitment__c> selected = extractSelected(
                this.mapOfCapitalCommitments
            );
            for (Capital_Commitment__c commitment : selected) {
                totalCommitment += commitment.Capital_Commitment__c;
            }
            return totalCommitment;
        }
        set;
    }
    public Capital_Call__c tempCall { get; set; }
    public Capital_Call_Parent__c parent { get; set; }
    public List<CommitmentWrapper> commitments { get; set; }
    public List<CapitalCallWrapper> newCapitalCalls { get; set; }
    public Set<Integer> listOfPageNoofZeroCapitalCommt {get;set;}
    public list<Integer> listOfPageNumbers {get;set;}
    public Map<String, String> mapOfStyles { get; set; }
    public enum Step {
        COMMITMENT_SELECTION,
            COMMITMENT_CHECK,
            INPUT,
            REVIEW
            }
    public Step currentStep { get; set; }
    public Boolean doCheck0 { get; set; }
    public Boolean isSuccess { get; set; }
    public Blob fileBody { get; set; }
    public List<Schema.FieldSetMember> capCallFieldSetColumns { get; set; }
    public Boolean highCapComtmntsFlag { get; set; } //to differentiate the total capital commitments('> 200' or '< 200')
    public Boolean enableAllocationFeature { get; set; }
    public Integer columnSize { get; set; }
    public String templateUrl {
        get { 
            List<Schema.FieldSetMember> fields = capCallFieldSetColumns;
            final List<String> headers = new List<String>();
            headers.add('Investment Vehicle');
            headers.add('Capital Call Amount');
            for (Schema.FieldSetMember f : fields) {
                if (
                    f.type != Schema.DisplayType.Currency &&
                    f.type != Schema.DisplayType.Double &&
                    f.type != Schema.DisplayType.Integer &&
                    f.type != Schema.DisplayType.PERCENT
                ) {
                    continue;
                }
                headers.add(f.Label);
            }
            final String header = String.join(headers, ',');
            String rows = '';
            Boolean first = true;
            for (Integer pageNum : mapOfCapitalCalls.keySet()) {
                for (CapitalCallWrapper ccw : mapOfCapitalCalls.get(pageNum)) {
                    if (!first) {
                        rows += ',';
                    }
                    rows += '"' + ccw.entityName + '"';
                    first = false;
                }
            }
            final PageReference temp = Page.CSVTemplate;
            temp.getParameters().put('columns', header);
            temp.getParameters().put('rows', rows);
            return temp.getUrl();
        }
        private set;
    }
    public Integer capitalCommitmentPageSize; //Holds the size of each page under capital commitment section(STEP-1)
    public Map<Integer, List<CommitmentWrapper>> mapOfCapitalCommitments {
        get;
        set;
    } //Holds the mapping of page number and records in that sepcific page number under capital commitment section(STEP-1)
    public Integer capitalCommitmentCurrentPageNumber { get; set; } // Holds the current page number that display the records for a particular page under capital commitment section(STEP-1)
    public Integer zerocapitalCommitmentCurrentPageNumber { get; set; }//Holds the current page number that display the records for a particular page under zero capital commitment section(STEP-2)
    public Integer capitalCallPageSize;//Holds the size of capital records that must be displayed under the per page on the (STEP-4)
    public Integer sizeOfCapitalCommitmentsMap {
        get { 
            return mapOfCapitalCommitments.size();
        }  
    }//Holds the total number of pages which display list of capital commitments under (STEP-1)
    public Integer sizeOfzeroCapitalCommitments{
        get{
            return listOfPageNoofZeroCapitalCommt.size();
        }
    }//Holds the total number of pages which display list of zero capital commitments under (STEP-2)
    public Map<Integer,List<Capital_Call__c>> mapOfCapitalCallSuccess{get;set;}//Holds list of capital calls that are successfully inserted as value and respective page number as key under (STEP-4)
    public Integer sizeOfCapitalCallsSuccesssMap {
        get {
            return mapOfCapitalCallSuccess.size();
        }
    }//Holds total number of pages which disply capital calls that are successfully inserted
    public Map<Integer, List<Capital_Commitment__c>> mapOfFailureCapitalCommitments {get;set;}//Holds list of capital commitments for which capital calls were not inserted successfully as value and respective page number as key
    public Integer sizeOfFailureCapitalCommitMap{
        get{
            return mapOfFailureCapitalCommitments.size();
        } 
    }//Holds total number of pages that display list of capital commitments for which capital calls were not inserted successfully
    public Integer failureCapitalCommitCurrentPageNumber {get;set;}//Holds page number of current page that is being displayed on the UI (STEP-4) if there are any capital commitments for which capital call insertion has been failed
    public Map<Integer, List<CapitalCallWrapper>> mapOfCapitalCalls { get; set; }//Holds the list of capital calls as value and respective page number of key
    public Integer capitalCallCurrentPageNumber { get; set; }//Holds the page number of current page that is being displayed on the UI with the list of capital calls under (STEP-4)
    public String batchProcessingRequest {get;set;}//Holds current batch status
    public Integer TotalJobItems {get;set;}//Holds total number of batch jobs created
    public Integer JobItemsProcessed {get;set;}//Holds total number of batch jobs proccessed
    public String BatchJobStatus {get;set;}//Holds current status of batch job
    public Integer BatchNumberOfErrors {get;set;}//Holds number of errors if batch has any
    public String BatchFailureMessage {get;set;}//Holds failure message if batch has any
    public List<Capital_Call__c> capitalCallsSuccess  {get;set;}//Holds list of capital calls that are successfully inserted
    public Integer capitalCallsSuccessPageSize{get;set;}//Holds size of pages which display list of capital calls that are successfully inserted
    public Integer TotalNumberOfCapitalCallsProccessed  {get;set;}//Holds total number of capital calls that are successfully inserted
    public Integer  TotalNumberOfCapitalCallsFailed {get;set;}//Holds total number of capital commitments for which capital calls were not inserted successfully
    public Integer capitalSuccessCurrentPageNumber {get;set;}//Holds page number of the current page which is being displayed on the UI with list of capital calls that are successfully inserted under (STEP-4)
    public List<Capital_Commitment__c> failedCapitalCommId {get;set;}//Holds capital commitments for which capital calls insertion has been failed
    List<Capital_Commitment__c> selectedCapitalCom = new List<Capital_Commitment__c>();//Holds the capital commitments that are selected for capital call insertion
    public Integer capitalCallfailurePageSize{get;set;}//Holds size of pages that display list of capital commitments for which capital call insertion has been failed
    public boolean isBatchRunning{get;set;}
    Map<String, String> fieldSetInfoMap;
    public List<SelectOption> metricsOptions { get;set; }
    public Map<String,List<SelectOption>> metricToMetricOptionsMap {get;set;}
    public string SelectedMetric {set;get;}
    public Map<String,String> metricToFundAllocMap { get;set; }
    public Map<String,String> roundingTypeToAllocMap {get;set;}
    public Boolean defaultProRataFlag {get;set;}
    public List<String> fieldsToWhichFundAllocationParentsMustBeAssigned;
    public List<Fund_Allocation_Parent__c> relFundAllocParents;
    public Boolean changedAnyOfTheAllocationsAssigned {get;set;}
    public Boolean saveAllocationAssigned {get;set;}
    public  Map<String,Allocation_Settings__c> allocSettingOfFund ;
    public CapitalCallController(ApexPages.StandardController sc) {
        fund = [SELECT Name,LP_Commitments__c FROM Fund__c WHERE Id = :sc.getId()];
        capCallFieldSetColumns = SObjectType.Capital_Call__c.FieldSets.Import_Wizard_Fields.getFields();
        capitalCommitmentPageSize = 400;  
        mapOfCapitalCommitments = new Map<Integer, List<CommitmentWrapper>>();
        listOfPageNumbers = new List<Integer>();
        capitalCallCurrentPageNumber = 1;
        capitalCallPageSize = 500;
        mapOfCapitalCalls = new Map<Integer, List<CapitalCallWrapper>>();
        listOfPageNoofZeroCapitalCommt = new Set<Integer>();
        newCapitalCalls = new List<CapitalCallWrapper>();
        currentStep = Step.COMMITMENT_SELECTION;
        isSuccess = false;
        tempCall = new Capital_Call__c();
        mapOfStyles = new Map<String, String>();
        batchProcessingRequest = '';
        capitalCallsSuccess = new List<Capital_Call__c>();
        capitalCallsSuccessPageSize = 500;
        capitalCallfailurePageSize = 500;
        mapOfCapitalCallSuccess = new Map<Integer, List<Capital_Call__c>>();
        failedCapitalCommId = new List<Capital_Commitment__c>();
        mapOfFailureCapitalCommitments = new Map<Integer,List<Capital_Commitment__c>>();
        capitalCallRecords = new List<Capital_Call__c>();
        updateFieldset = false;
        UpdatefieldsetreturnMap = new Map<String,Boolean>();
        updateFieldsetcounter = 0;
        isNullOrZeroCapCommitmentCheckbox = true;
        mapOfCapCommWithZeroValues = new Map<Id,Boolean>();
        //To enable or diable Allocations Feature on ImportWizard
        metricsOptions = new List<SelectOption>();
        metricToFundAllocMap = new Map<String,String>();
        metricToMetricOptionsMap = new Map<String,List<SelectOption>>();
        roundingTypeToAllocMap = new Map<String,String>();
        fieldsToWhichFundAllocationParentsMustBeAssigned = new List<String>();
        for (Schema.FieldSetMember f : capCallFieldSetColumns) {
          //  metricToFundAllocMap.put(f.label,'');
            fieldsToWhichFundAllocationParentsMustBeAssigned.add(f.label);
        }
        fieldsToWhichFundAllocationParentsMustBeAssigned.add('Capital Call Amount');
        //List<Fund_Allocation__c> relFundAllocs = [Select Id, Name, Metrics_to_Allocate_view__c from Fund_Allocation__c where Fund_to_Allocate__c =: fund.Id];
        relFundAllocParents = [Select Id, Name, Metrics_to_Allocate__c,Rounding_Type__c from Fund_Allocation_Parent__c where Fund_to_Allocate__c =: fund.Id];
     //   System.debug('relFundAllocs[0].Metrics_to_Allocate_view__c %%% : '+relFundAllocParents[0].Metrics_to_Allocate__c);
        // for(Fund_Allocation__c fundAlloc : relFundAllocs){
        //     metricsOptions.add(new SelectOption(fundAlloc.Id,fundAlloc.Name));
        // }
        allocSettingOfFund = Allocation_Settings__c.getall();
        initializingFundAllocationParent(relFundAllocParents,fieldsToWhichFundAllocationParentsMustBeAssigned);
      
        system.debug('allocSettingOfFund is '+allocSettingOfFund);
       /*  for(Fund_Allocation_Parent__c fundAllocPrnt : relFundAllocParents){
            metricsOptions.add(new SelectOption(fundAllocPrnt.Id,fundAllocPrnt.Name));
        } */
       /*  for (Schema.FieldSetMember f : capCallFieldSetColumns) {
            metricToFundAllocMap.put(f.label,'');
            List<SelectOption> selOpt = new List<SelectOption>();
            selOpt.add(new SelectOption('Pro-Rata','Pro-Rata'));
            metricToMetricOptionsMap.put(f.label,selOpt); */
            // for(Fund_Allocation__c fa :relFundAllocs){
            //     if(fa.Metrics_to_Allocate_view__c!= null && fa.Metrics_to_Allocate_view__c.contains(f.label)){
            //         List<SelectOption> so = metricToMetricOptionsMap.get(f.label);
            //         so.add(new SelectOption(fa.Id,fa.Name));
            //         metricToMetricOptionsMap.put(f.label,so);
            //     }
            // }
           /*  for(Fund_Allocation_Parent__c fap :relFundAllocParents){
                if(fap.Metrics_to_Allocate__c!= null && fap.Metrics_to_Allocate__c.contains(f.label)){
                    List<SelectOption> so = metricToMetricOptionsMap.get(f.label);
                    so.add(new SelectOption(fap.Id,fap.Name));
                    metricToMetricOptionsMap.put(f.label,so);
                }
            }
        } */
        //for (Schema.FieldSetMember f : capCallFieldSetColumns) {
            /* metricToFundAllocMap.put('Capital Call Amount','');
            List<SelectOption> selOpt = new List<SelectOption>();
            selOpt.add(new SelectOption('Pro-Rata','Pro-Rata'));
            metricToMetricOptionsMap.put('Capital Call Amount',selOpt); */
            // for(Fund_Allocation__c fa :relFundAllocs){
            //     if(fa.Metrics_to_Allocate_view__c != null && fa.Metrics_to_Allocate_view__c.contains('Capital Call Amount')){
            //         List<SelectOption> so = metricToMetricOptionsMap.get('Capital Call Amount');
            //         so.add(new SelectOption(fa.Id,fa.Name));
            //         metricToMetricOptionsMap.put('Capital Call Amount',so);
            //     }
            // }
           /*  for(Fund_Allocation_Parent__c fap :relFundAllocParents){
                if(fap.Metrics_to_Allocate__c != null && fap.Metrics_to_Allocate__c.contains('Capital Call Amount')){
                    List<SelectOption> so = metricToMetricOptionsMap.get('Capital Call Amount');
                    so.add(new SelectOption(fap.Id,fap.Name));
                    metricToMetricOptionsMap.put('Capital Call Amount',so);
                }
            } */
        //}
        mapOfStyles=new Map<String,String>();
      //  changedAnyOfTheAllocationsAssigned = false;
      saveAllocationAssigned = false;
        ImportWizardSettings__c importWizardSettings = ImportWizardSettings__c.getInstance();
        enableAllocationFeature = importWizardSettings.Enable_Allocation_Feature__c;
        if(enableAllocationFeature){
            columnSize = 3;
        }else{
            columnSize = 1;
            defaultProRataFlag = true;
        }
    }
     // SF-209(Manage Available fields button)It sets the available fields and inTheFieldset fields on the coloumns of multiselect picklist.
    public void setFieldsOnMultipicklist(){
        updateFieldsetcounter = updateFieldsetcounter+1;
        capCallFieldSetColumns = SObjectType.Capital_Call__c.FieldSets.Import_Wizard_Fields.getFields();
        try{
            fieldSetInfoMap = MetadataServiceHelper.availablefieldsofFieldset('Import_Wizard_Fields','Capital_Call__c');
        }catch (Exception e) {
            String errorMessage = 'Error retrieving available fields for Capital Call fieldset ' + fieldSetInfoMap.keySet();
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMessage));
        }
        leftOptions = new List<SelectOption>();
        if(fieldSetInfoMap != Null){
            for(string eachApiName : fieldSetInfoMap.keySet()){
                leftOptions.add(new SelectOption(fieldSetInfoMap.get(eachApiName), eachApiName));
            }
        }
        system.debug('leftOptions'+leftOptions);
        rightOptions = new List<SelectOption>();
        for (Schema.FieldSetMember eachfield : capCallFieldSetColumns) {
            rightOptions.add(new SelectOption(eachfield.getFieldPath(), eachfield.getLabel()));
        }
        system.debug('Rightoptions are:'+ rightOptions);
    //Fieldset is set to be updated after one callout.
    //Updatefieldsetcounter is used to track the number of times the setFieldsOnMultipicklist method has been called,rather than every time the actionPoller polls for updates
        if(updateFieldsetcounter>1){
            updateFieldset = false;
        } 
    }

    /**
     * This method provides the end user with multiple fund allocations options to select for a particular field
     */
    public void initializingFundAllocationParent(List<Fund_Allocation_Parent__c> relatedFundAllocParents,List<String> fieldsToWhichFundAllocationParentsMustBeAssigned){
        system.debug('list allocSettingOfFund is *** '+allocSettingOfFund);
        for(String fieldToAssignFundAlloc : fieldsToWhichFundAllocationParentsMustBeAssigned){
            if(allocSettingOfFund.containsKey(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc) && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc) != null && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc).Fund_Id__c == fund.id && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc).Field_Label_Name__c == fieldToAssignFundAlloc && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc).Allocation_Parent_Id__c != null){
                metricToFundAllocMap.put(fieldToAssignFundAlloc, allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc).Allocation_Parent_Id__c);
                //.put(allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+fieldToAssignFundAlloc).Allocation_Parent_Id__c,'');
            }
            else{ 
                metricToFundAllocMap.put(fieldToAssignFundAlloc,'Pro-Rata');
            }
            List<SelectOption> selOpt = new List<SelectOption>();
            selOpt.add(new SelectOption('Pro-Rata','Pro-Rata'));
            for(Fund_Allocation_Parent__c parentToBeAssigned : relatedFundAllocParents){
                if(parentToBeAssigned.Metrics_to_Allocate__c!= null && parentToBeAssigned.Metrics_to_Allocate__c.contains(fieldToAssignFundAlloc)){
                    selOpt.add(new SelectOption(parentToBeAssigned.Id,parentToBeAssigned.Name));
                }
            }
            metricToMetricOptionsMap.put(fieldToAssignFundAlloc,selOpt);
        }
        assignRoundingTypeToFundAllocationParent();
    }
    public void assignRoundingTypeToFundAllocationParent(){
        system.debug(metricToFundAllocMap.values().size());
        if(metricToFundAllocMap.values().size() != 0){
            Map<Id,Fund_Allocation_Parent__c> fundAllocParentsSelected = new Map<Id,Fund_Allocation_Parent__c>([Select Id, Name, Metrics_to_Allocate__c,Rounding_Type__c from Fund_Allocation_Parent__c where Id IN : metricToFundAllocMap.values()]);
            for(String allocatedField : metricToFundAllocMap.keySet()){
                system.debug('allocatedField is '+allocatedField);
                system.debug(metricToFundAllocMap.get(allocatedField));
            //  roundingTypeToAllocMap.put(allocatedField, new Map<String,String>());
                if(metricToFundAllocMap.get(allocatedField)!='Pro-Rata' && fundAllocParentsSelected.get(metricToFundAllocMap.get(allocatedField)) != null){
                //  Map<String,String> allocParentAndRoundingTypeMap = roundingTypeToAllocMap.get(allocatedField);
                    system.debug(roundingTypeToAllocMap.get(allocatedField));
                    system.debug(fundAllocParentsSelected.get(metricToFundAllocMap.get(allocatedField)).Rounding_Type__c);
                //   allocParentAndRoundingTypeMap.put(metricToFundAllocMap.get(allocatedField),fundAllocParentsSelected.get(metricToFundAllocMap.get(allocatedField)).Rounding_Type__c);
                        roundingTypeToAllocMap.put(allocatedField, fundAllocParentsSelected.get(metricToFundAllocMap.get(allocatedField)).Rounding_Type__c);
                }
                else{
                    roundingTypeToAllocMap.put(allocatedField, 'Half Up');
                }
            }
        }
    }

    /*Calls methods that retrieve commitments and checks if there are zero capital commitments*/
    public void callToRetrieveCommitments(){
        isBatchRunning= false;
        fund = [SELECT Name,LP_Commitments__c,Capital_Calls_Update_Status__c FROM Fund__c WHERE Id =: fund.id];
        // This is to display an error message when the user wants to create new fund when existing Batch is InProgress
        if(fund != null){
            if(fund.Capital_Calls_Update_Status__c !=null && fund.Capital_Calls_Update_Status__c != 'Completed'){
                isBatchRunning = true;
                ApexPages.addMessage(
                    new ApexPages.Message(
                        ApexPages.Severity.ERROR,
                        'A batch is already in progress! You cannot create new Capital Calls while the batch is in progress. Please check "Capital Calls Update Status" field to know updated batch status.'
                    )
                );
            }
        }
        alertDisplayed = true;
        retrieveCommitments();
        checkIfZero(); 
    }
    /**
* Retrieves the Capital Commitment records relevant to this fund
* Storing them as CommitmentWrapper instances
* @author Nathan (Trineo)
*/ 
    private void retrieveCommitments() {
        List<Capital_Commitment__c> allCommitments = [
            SELECT
            Name,  
            Capital_Commitment__c,
            LP_Entity__r.Name,
            Fund_Name__c,
            LP_Entity__c,
            Total_Over_Under_Paid__c
            FROM Capital_Commitment__c
            WHERE Fund_Name__c = :fund.Id
            ORDER BY LP_Entity__r.Name
        ];
        this.mapOfCapitalCommitments = wrapCommitments(allCommitments);
    }
    /**
* Checks if we need to ask about capital commitments of 0
* @author Marama (Trineo)
*/
    private void checkIfZero() {
        doCheck0 = false;
        for (Integer pageNum : this.mapOfCapitalCommitments.keySet()) {
            for (CommitmentWrapper cw : this.mapOfCapitalCommitments.get(pageNum)) {
                if (cw.record.Capital_Commitment__c == 0 && cw.checked) {
                    doCheck0 = true;
                }
            }
        }
    }
    // Called when page loads:
    public PageReference init() {
        parent = new Capital_Call_Parent__c();
        parent.Hide_From_Portal__c = true;
        return null;
    }

    public void setDefaultCalculationToMap(){       
        if(defaultProRataFlag){
            for(String key: metricToFundAllocMap.keySet()){
                metricToFundAllocMap.put(key,'Pro-Rata');
            }
            assignRoundingTypeToFundAllocationParent();
        }
        else{
            initializingFundAllocationParent(relFundAllocParents,fieldsToWhichFundAllocationParentsMustBeAssigned);
        }
    }
    
    /**
* Called when the user clicks "Next"
* Progresses the wizard through to its next step
* @author Nathan (Trineo)
*/
    public PageReference next() {
        system.debug('in 286');
        if (currentStep == Step.COMMITMENT_SELECTION) {
             system.debug('in 288');
            // Switch to commitment selection
            if (commitmentsSelected()) {
                checkIfZero();
                if (doCheck0) {
                    currentStep = Step.COMMITMENT_CHECK;
                } else {
                    currentStep = Step.INPUT;
                }
            } else {
                ApexPages.addMessage(
                    new ApexPages.Message(
                        ApexPages.Severity.Error,
                        'Please select at least one capital commitment before continuing'
                    )
                );
            }
        } else if (currentStep == Step.COMMITMENT_CHECK) {
             system.debug('in 306');
            // Switch to input
            currentStep = Step.INPUT;
        } else if (currentStep == Step.INPUT) {
            system.debug('in input step');
            for(String allocatedMetricField : metricToFundAllocMap.keySet()){
                system.debug(allocatedMetricField);
                system.debug(metricToFundAllocMap.get(allocatedMetricField));
                system.debug(roundingTypeToAllocMap.get(allocatedMetricField));
            }
            assignmentCallToAllocationSettings();
            runProrata();
        }
        return null;
    }
    public void assignmentCallToAllocationSettings(){
        system.debug('in assignmentCallToAllocationSettings function');
        system.debug('in changedAnyOfTheAllocationsAssigned '+changedAnyOfTheAllocationsAssigned);
        system.debug('fund id is '+fund.Id);
        system.debug('list allocSettingOfFund is *** '+allocSettingOfFund);
        List<Allocation_Settings__c> listOfAllocationSettingsToInsert = new List<Allocation_Settings__c>();
        for(String key: metricToFundAllocMap.keySet()){
           system.debug('key is '+key);
         //  system.debug('allocation parent id in '+allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key).Allocation_Parent_Id__c);
           system.debug('metricToFundAllocMap.get(key) '+metricToFundAllocMap.get(key));
           if((allocSettingOfFund.containsKey(fund.Name.substring(0, 5)+'_'+key) && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key) != null && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key).Fund_Id__c == fund.id && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key).Field_Label_Name__c == key && allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key).Allocation_Parent_Id__c != metricToFundAllocMap.get(key) && metricToFundAllocMap.get(key) != 'Pro-Rata') ||(!allocSettingOfFund.containsKey(fund.Name.substring(0, 5)+'_'+key) && metricToFundAllocMap.get(key) != 'Pro-Rata')){
            system.debug('in if');
            if(!saveAllocationAssigned){
                changedAnyOfTheAllocationsAssigned = true;
            }
            if(changedAnyOfTheAllocationsAssigned){
                break;  
            }
            Allocation_Settings__c allocationSettingsRec =  allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key);
            if(allocationSettingsRec == null){
                allocationSettingsRec = new Allocation_Settings__c();
                allocationSettingsRec.Name = fund.Name.substring(0, 5)+'_'+key;
                allocationSettingsRec.Fund_Id__c = fund.id;
                allocationSettingsRec.Field_Label_Name__c = key;
            }
           // Allocation_Settings__c allocationSettingsRec =  allocSettingOfFund.get(fund.Name.substring(0, 5)+'_'+key);
            allocationSettingsRec.Allocation_Parent_Id__c = metricToFundAllocMap.get(key);
            listOfAllocationSettingsToInsert.add(allocationSettingsRec);
           }
           /* else if(!allocSettingOfFund.containsKey(fund.Name.substring(0, 5)+'_'+key) && metricToFundAllocMap.get(key) != 'Pro-Rata'){
            system.debug('in else');
            if(!saveAllocationAssigned){
                changedAnyOfTheAllocationsAssigned = true;
            }
            if(changedAnyOfTheAllocationsAssigned){
                break;
            }
            Allocation_Settings__c newAllocationSettingsRec = new Allocation_Settings__c();
            newAllocationSettingsRec.Name = fund.Name.substring(0, 5)+'_'+key;
            newAllocationSettingsRec.Fund_Id__c = fund.id;
            newAllocationSettingsRec.Field_Label_Name__c = key;
            newAllocationSettingsRec.Allocation_Parent_Id__c = metricToFundAllocMap.get(key);
            listOfAllocationSettingsToInsert.add(newAllocationSettingsRec);
           } */
        }
        system.debug('in upsert list'+listOfAllocationSettingsToInsert.size());
        upsert listOfAllocationSettingsToInsert;
        allocSettingOfFund = Allocation_Settings__c.getall();
    }
    public void closeAllocSettPopup() {       
        changedAnyOfTheAllocationsAssigned = false;
        currentStep = Step.REVIEW;
    }
    public void saveSettings(){
        saveAllocationAssigned = true;
        closeAllocSettPopup();
        assignmentCallToAllocationSettings();
        saveAllocationAssigned = false;
    }
    /**
* Runs the prorata logic on the selected commitments
* @author Luke / Nathan / Gareth (Trineo)
*/
    private void runProrata() {
        system.debug('in runProrata');
        //final Set<String> fundIdSet = new Set<String>();
        final List<Capital_Commitment__c> selected = extractSelected(
            this.mapOfCapitalCommitments
        );
        if(defaultProRataFlag){
            system.debug('in 325');
            defaultProRataCalculation(selected);
        }else{
            system.debug('in 327');
            allocationProRataCalculation(selected);
        }
        
        //if (fundIdSet.size() == 1) {
            if (selected.size() <= 200) {
                newCapitalCalls = mapOfCapitalCalls.get(1);
                this.highCapComtmntsFlag = false;
            } else {
                this.highCapComtmntsFlag = true;
            }
            parent.Fund__c = selected[0].Fund_Name__c;
            parent.Due_Date__c = tempCall.Due_Date__c;
        //} else {
        //    System.debug(
        //        'WARNING: Capital Calls dont lookup to the same Fund. Fund lookup on Capital Call Parent not set'
        //    );
            // ApexPages.addMessage(
            //     new ApexPages.Message(
            //         ApexPages.Severity.INFO,
            //         'Unable to retrieve single Fund. Fund lookup on Capital Call Parent not set'
            //     )
            // );
        //}
         if(changedAnyOfTheAllocationsAssigned == false || changedAnyOfTheAllocationsAssigned == null){
            currentStep = Step.REVIEW;
        } 
    }

    public void defaultProRataCalculation(List<Capital_Commitment__c> selected){  
        Boolean isError = false;
        Decimal total = totalCommitment;
        final Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Capital_Call__c.fields.getMap();
        final List<Schema.FieldSetMember> fields = capCallFieldSetColumns;
        List<CapitalCallWrapper> listOfCapitalCallsPerPage = new List<CapitalCallWrapper>();
        Integer totalCapitalCallRecordsProcessed = 0;
        Integer counterForCapitalCallCount = 0;
        Integer pageNumber = 0;
        for (Capital_Commitment__c cc : selected) {
            selectedCapitalCom.add(cc);
            //fundIdSet.add(cc.Fund_Name__c);
            // Calculate cascaded amount. This should be the total call amount multiplied by the percent of this commitment out of the fund total committed:
            Decimal cascadedAmt = null;
            try {
                if (total != 0.0) {
                    system.debug(
                        'cc.Capital_Commitment__c is ' + cc.Capital_Commitment__c
                    );
                    cascadedAmt =
                        (cc.Capital_Commitment__c / total) *
                        tempCall.Capital_Call_Amount__c;
                } else {
                    cascadedAmt = 0.0;
                }
                cascadedAmt = cascadedAmt.setScale(2); // make sure the values are to 2 decimal places
            } catch (Exception e) {
                System.debug(
                    'in 218 error' +
                    e.getMessage() +
                    'is ' +
                    e.getLineNumber()
                );
                isError = true;
                ApexPages.addMessage(
                    new ApexPages.Message(
                        ApexPages.Severity.ERROR,
                        'Something went wrong while trying to calculate Capital Call amount for Capital Commitment with Id: "' +
                        cc.Id +
                        '", and no Capital Calls have been created. Please ensure that the Commitments value on Fund is not blank or equal to zero, or talk to your system administrator (' +
                        e.getMessage() +
                        ')'
                    )
                );
            }
            final Capital_Call__c call = new Capital_Call__c(
                Capital_Commitment__c = cc.Id,
                Due_Date__c = tempCall.Due_Date__c,
                Capital_Call_Amount__c = cascadedAmt,
                LP_Entity__c = cc.LP_Entity__c,
                Fund__c = cc.Fund_Name__c
            );

            for (Schema.FieldSetMember f : fields) {
                try {
                    if (
                        f.type != Schema.DisplayType.Currency &&
                        f.type != Schema.DisplayType.Double &&
                        f.type != Schema.DisplayType.Integer &&
                        f.type != Schema.DisplayType.PERCENT
                    ) {
                        continue;
                    }
                    
                    Decimal valueDivided = (Decimal) tempCall.get(f.fieldPath) == null
                        ? 0.0
                        : (Decimal) tempCall.get(f.fieldPath);
                    
                    if (valueDivided != 0.0) {
                        valueDivided = (cc.Capital_Commitment__c / total) * valueDivided;
                    } else {
                        valueDivided = 0.0;
                    }
                    
                    final Schema.SObjectField field = fieldMap.get(f.fieldPath);
                    final Schema.DescribeFieldResult fd = field.getDescribe();
                    final Integer scale = fd.getScale();
                    
                    if (scale == 0) {
                        valueDivided = valueDivided.setScale(
                            scale,
                            System.RoundingMode.DOWN
                        ); //Round Down but later find the remainder from originalValueOfIntegerColumns - SumOfIntegerColumns
                        call.put(f.fieldPath, (Integer) valueDivided);
                    } else {
                        valueDivided = valueDivided.setScale(scale);
                        call.put(f.fieldPath, valueDivided);
                    }
                } catch (Exception e) {
                    isError = true;
                    ApexPages.addMessage(
                        new ApexPages.Message(
                            ApexPages.Severity.ERROR,
                            'Something went wrong while trying to calculate ' +
                            f.label +
                            ' for Capital Commitment with Id: "' +
                            cc.Id +
                            '"' +
                            ' and no Capital Calls have been created. Please ensure that the Commitments value on Fund is not blank or equal to zero, or talk to your system administrator (' +
                            e.getMessage() +
                            ')'
                        ) 
                    );
                    break;
                }
            }

            if(call != null && cascadedAmt != null){
                decimal expenseOutcomitment = call.Expenses_Outside_of_Commitment__c != null ? call.Expenses_Outside_of_Commitment__c : 0.0;
                decimal lateAdmInterest = call.Late_Admission_Interest__c != null ? call.Late_Admission_Interest__c : 0.0;            
                decimal overUnderPaid = cc.Total_Over_Under_Paid__c != null ? cc.Total_Over_Under_Paid__c : 0.0;            

                call.Amount_Due__c = (cascadedAmt + expenseOutcomitment + lateAdmInterest) <= overUnderPaid 
                        ? cascadedAmt + expenseOutcomitment + lateAdmInterest - overUnderPaid
                        : 0.0;
            }
            // Create the capital call with cascaded amount:
            if (!isError) {//Iterates all the selected capital commitments and creates capital call records for each selected capital commitment and adds 500 capital call records into list and display list of 500 records per page*/
                totalCapitalCallRecordsProcessed++;
                counterForCapitalCallCount++; 
                listOfCapitalCallsPerPage.add(
                    new CapitalCallWrapper(call, cc.LP_Entity__r.Name)
                );
                if (counterForCapitalCallCount == capitalCallPageSize) {
                    pageNumber = pageNumber + 1;
                    mapOfCapitalCalls.put(pageNumber, listOfCapitalCallsPerPage);
                    counterForCapitalCallCount = 0;
                    listOfCapitalCallsPerPage = new List<CapitalCallWrapper>();
                } else if (totalCapitalCallRecordsProcessed == selected.size()) {
                    pageNumber = pageNumber + 1;
                    mapOfCapitalCalls.put(pageNumber, listOfCapitalCallsPerPage);
                }
                //	newCapitalCalls.add(new CapitalCallWrapper(call, cc.LP_Entity__r.Name));
                mapOfStyles.put(cc.LP_Entity__r.Name, 'null');
            }
        }
    }
    
    public void allocationProRataCalculation(List<Capital_Commitment__c> selected){        
        Boolean isError = false;
        Decimal total = totalCommitment;
        // Map<Id,Fund_Allocation__c> fundAlloctoMembrsMap = new Map<Id,Fund_Allocation__c>([Select Id, (Select Id, Name, Capital_Commitment__c, Allocation_Percent__c from Fund_Allocation_Members__r) from Fund_Allocation__c where Id IN : (metricToFundAllocMap.values())]);
        // System.debug('fundAlloctoMembrsMap'+fundAlloctoMembrsMap);
        system.debug('in 487 '+metricToFundAllocMap.values());
        final Map<Id,Map<Id,Fund_Allocation_Member__c>> fundAllocMemPercentAndCapCommMap = new Map<Id,Map<Id,Fund_Allocation_Member__c>>();
        Map<Id,Fund_Allocation_Parent__c> fundAllocParenttoMembrsMap = new Map<Id,Fund_Allocation_Parent__c>([Select Id, (Select Id, Name, Capital_Commitment__c, Allocation_Percent__c from Fund_Allocation_Members__r) from Fund_Allocation_Parent__c where Id IN : (metricToFundAllocMap.values())]);
        for(Fund_Allocation_Parent__c fundAllocPrnt : fundAllocParenttoMembrsMap.values()){
            fundAllocMemPercentAndCapCommMap.put(String.valueOf(fundAllocPrnt.Id),new Map<Id,Fund_Allocation_Member__c>());
            for(Fund_Allocation_Member__c fundAllocMem : fundAllocPrnt.Fund_Allocation_Members__r){
                fundAllocMemPercentAndCapCommMap.get(String.valueOf(fundAllocPrnt.Id)).put(fundAllocMem.Capital_Commitment__c,fundAllocMem);
            }
        }
        System.debug('fundAllocParenttoMembrsMap'+fundAllocParenttoMembrsMap);
        final Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Capital_Call__c.fields.getMap();
        final List<Schema.FieldSetMember> fields = capCallFieldSetColumns;
        List<CapitalCallWrapper> listOfCapitalCallsPerPage = new List<CapitalCallWrapper>();
        Integer totalCapitalCallRecordsProcessed = 0;
        Integer counterForCapitalCallCount = 0;
        Integer pageNumber = 0;
        for (Capital_Commitment__c cc : selected) {
            selectedCapitalCom.add(cc);
            //fundIdSet.add(cc.Fund_Name__c);
            // Calculate cascaded amount. This should be the total call amount multiplied by the percent of this commitment out of the fund total committed:
            Decimal cascadedAmt = null;
            try {
                if (total != 0.0) {
                    system.debug(
                        'cc.Capital_Commitment__c is ' + cc.Capital_Commitment__c
                    );
                    if(metricToFundAllocMap.get('Capital Call Amount') != null && metricToFundAllocMap.get('Capital Call Amount') != 'Pro-Rata'){
                         system.debug('in 521 %%%');
                        Decimal valueDividedForCapitalCallAmount = 0.0; //Value divided or shred for a distribution based on the capital Commitments ratio
                        Decimal valueOriginalForCapitalCallAmount = (Decimal)tempCall.get('Capital_Call_Amount__c') == null ? 0.0 : (Decimal)tempCall.get('Capital_Call_Amount__c'); 
                        system.debug('valueOriginalForCapitalCallAmount is '+valueOriginalForCapitalCallAmount);
                        Decimal calculatedValueFromAllocationPercentForCapitalCallAmount = (valueOriginalForCapitalCallAmount == 0.0 || fundAllocMemPercentAndCapCommMap.get(metricToFundAllocMap.get('Capital Call Amount'))?.get(cc.Id)?.Allocation_Percent__c == null || fundAllocMemPercentAndCapCommMap.get(metricToFundAllocMap.get('Capital Call Amount'))?.get(cc.Id)?.Allocation_Percent__c == 0)  ? 0.0 : valueOriginalForCapitalCallAmount*fundAllocMemPercentAndCapCommMap.get(metricToFundAllocMap.get('Capital Call Amount'))?.get(cc.Id)?.Allocation_Percent__c/100;
                        valueDividedForCapitalCallAmount = calculatedValueFromAllocationPercentForCapitalCallAmount;
                        cascadedAmt = valueDividedForCapitalCallAmount;
                        system.debug('cascadedAmt is '+cascadedAmt);
                    }
                    else{cascadedAmt =
                        (cc.Capital_Commitment__c / total) *
                        tempCall.Capital_Call_Amount__c;
                    }
                } else {
                    cascadedAmt = 0.0;
                }
              //   cascadedAmt = cascadedAmt.setScale(2); // make sure the values are to 2 decimal places
                 system.debug('$$$ Before Rounding'+cascadedAmt);
                if(roundingTypeToAllocMap.get('Capital Call Amount') == 'Half UP'){ //Rounding based on selection of end user on UI
                    system.debug('$$$ in Half Up Rounding');
                    cascadedAmt = cascadedAmt.setScale(2,System.RoundingMode.HALF_UP);
                }
                else{
                    system.debug('$$$ in Half Down Rounding');
                    cascadedAmt = cascadedAmt.setScale(2,System.RoundingMode.HALF_DOWN);
                } 
                system.debug('$$$ After Rounding'+cascadedAmt);
            } catch (Exception e) {
                System.debug(
                    'in 218 error' +
                    e.getMessage() +
                    'is ' +
                    e.getLineNumber()
                );
                isError = true;
                ApexPages.addMessage(
                    new ApexPages.Message(
                        ApexPages.Severity.ERROR,
                        'Something went wrong while trying to calculate Capital Call amount for Capital Commitment with Id: "' +
                        cc.Id +
                        '", and no Capital Calls have been created. Please ensure that the Commitments value on Fund is not blank or equal to zero, or talk to your system administrator (' +
                        e.getMessage() +
                        ')'
                    )
                );
            }
            final Capital_Call__c call = new Capital_Call__c(
                Capital_Commitment__c = cc.Id,
                Due_Date__c = tempCall.Due_Date__c,
                Capital_Call_Amount__c = cascadedAmt,
                LP_Entity__c = cc.LP_Entity__c,
                Fund__c = cc.Fund_Name__c
            );

            for (Schema.FieldSetMember f : fields) {
                try {
                    if (
                        f.type != Schema.DisplayType.Currency &&
                        f.type != Schema.DisplayType.Double &&
                        f.type != Schema.DisplayType.Integer &&
                        f.type != Schema.DisplayType.PERCENT
                    ) {
                        continue;
                    }
                    
                    if(metricToFundAllocMap.get(f.label) == 'Pro-Rata'){
                        Decimal valueDivided = (Decimal) tempCall.get(f.fieldPath) == null
                        ? 0.0
                        : (Decimal) tempCall.get(f.fieldPath);
                    
                        if (valueDivided != 0.0) {
                            valueDivided = (cc.Capital_Commitment__c / total) * valueDivided;
                        } else {
                            valueDivided = 0.0;
                        }

                        final Schema.SObjectField field = fieldMap.get(f.fieldPath);
                        final Schema.DescribeFieldResult fd = field.getDescribe();
                        final Integer scale = fd.getScale();

                        if (scale == 0) {
                            valueDivided = valueDivided.setScale(
                                scale,
                                System.RoundingMode.HALF_UP
                            ); //As it is pro-rata calculation, the default half-up rounding is being applied
                            call.put(f.fieldPath, (Integer) valueDivided);
                        } else {
                            valueDivided = valueDivided.setScale(scale,System.RoundingMode.HALF_UP);
                            call.put(f.fieldPath, valueDivided);
                        }

                    }else{
                        List<Fund_Allocation_Member__c> fundAllocMembList = fundAllocParenttoMembrsMap.get(metricToFundAllocMap.get(f.label)).Fund_Allocation_Members__r;
                        final Schema.SObjectField field = fieldMap.get(f.fieldPath);
					    final Schema.DescribeFieldResult fd = field.getDescribe();
					    final Integer scale = fd.getScale();
                        Integer i = 0;
                        for(Fund_Allocation_Member__c fam: fundAllocMembList){
                            i++;
                            //System.debug('Other Income/Loss: inside for loop : '+ f.label + ' cc.LP_Entity__c : '+cc.LP_Entity__c);
                            if(fam.Capital_Commitment__c == cc.Id){
                                //System.debug('Other Income/Loss: inside inner of for loop : '+f.label + ' cc.LP_Entity__c : '+cc.LP_Entity__c);
                                Decimal calculatedValueFromAllocationPercent = ((Decimal)tempCall.get(f.fieldPath) == null || fam.Allocation_Percent__c == null || fam.Allocation_Percent__c == 0)  ? 0.0 : (Decimal)tempCall.get(f.fieldPath)*fam.Allocation_Percent__c/100;
                                system.debug('## '+f.label);
                                system.debug('## Before'+calculatedValueFromAllocationPercent);
                                system.debug('# Scale is '+scale);
                                //call.put(f.fieldPath, calculatedValueFromAllocationPercent.setScale(scale));
                                if(roundingTypeToAllocMap.get(f.label) == 'Half UP'){
                                    system.debug('# Half UP');
                                    calculatedValueFromAllocationPercent = calculatedValueFromAllocationPercent.setScale(scale,System.RoundingMode.HALF_UP);
                                }
                                else{
                                    system.debug('# Half Down');
                                    calculatedValueFromAllocationPercent = calculatedValueFromAllocationPercent.setScale(scale,System.RoundingMode.HALF_DOWN);
                                }
                                system.debug('## After'+calculatedValueFromAllocationPercent);
                                call.put(f.fieldPath, calculatedValueFromAllocationPercent);
                                break ;
                            }
                            if(i == fundAllocMembList.size()){
                                call.put(f.fieldPath, 0.00);
                            }
                        }
                    }
                    
                } catch (Exception e) {
                    isError = true;
                    ApexPages.addMessage(
                        new ApexPages.Message(
                            ApexPages.Severity.ERROR,
                            'Something went wrong while trying to calculate ' +
                            f.label +
                            ' for Capital Commitment with Id: "' +
                            cc.Id +
                            '"' +
                            ' and no Capital Calls have been created. Please ensure that the Commitments value on Fund is not blank or equal to zero, or talk to your system administrator (' +
                            e.getMessage() +
                            ')'
                        ) 
                    );
                    break;
                }
            }
            if(call != null && cascadedAmt != null){
                decimal expenseOutcomitment = call.Expenses_Outside_of_Commitment__c != null ? call.Expenses_Outside_of_Commitment__c : 0.0;
                decimal lateAdmInterest = call.Late_Admission_Interest__c != null ? call.Late_Admission_Interest__c : 0.0;            
                decimal overUnderPaid = cc.Total_Over_Under_Paid__c != null ? cc.Total_Over_Under_Paid__c : 0.0;            
                call.Amount_Due__c = (cascadedAmt + expenseOutcomitment + lateAdmInterest) <= overUnderPaid 
                        ? cascadedAmt + expenseOutcomitment + lateAdmInterest - overUnderPaid
                        : 0.0;
            }
            // Create the capital call with cascaded amount:
            if (!isError) {//Iterates all the selected capital commitments and creates capital call records for each selected capital commitment and adds 500 capital call records into list and display list of 500 records per page*/
                totalCapitalCallRecordsProcessed++;
                counterForCapitalCallCount++; 
                listOfCapitalCallsPerPage.add(
                    new CapitalCallWrapper(call, cc.LP_Entity__r.Name)
                );
                if (counterForCapitalCallCount == capitalCallPageSize) {
                    pageNumber = pageNumber + 1;
                    mapOfCapitalCalls.put(pageNumber, listOfCapitalCallsPerPage);
                    counterForCapitalCallCount = 0;
                    listOfCapitalCallsPerPage = new List<CapitalCallWrapper>();
                } else if (totalCapitalCallRecordsProcessed == selected.size()) {
                    pageNumber = pageNumber + 1;
                    mapOfCapitalCalls.put(pageNumber, listOfCapitalCallsPerPage);
                }
                //	newCapitalCalls.add(new CapitalCallWrapper(call, cc.LP_Entity__r.Name));
                mapOfStyles.put(cc.LP_Entity__r.Name, 'null');
            }
        }
    }
    
    /**
* Affirms that there are commitments selected for prorata. Used for validation of the commitment selection step.
* @author Nathan (Trineo)
*/
    public Boolean commitmentsSelected() {
        Boolean retVal = false;
        for (Integer pageNum : this.mapOfCapitalCommitments.keySet()) {
            for (
                CommitmentWrapper commitment : this.mapOfCapitalCommitments.get(pageNum)) {
                    if (commitment.checked) {
                        retVal = true;
                        break;
                    }
                }
        }
        return retVal;
    }
    
    // Return to input page from review page:
    public PageReference previous() {
        if (currentStep == Step.REVIEW) {
            currentStep = Step.INPUT;
            //newCapitalCalls = new List<CapitalCallWrapper>();
            mapOfCapitalCalls = new Map<Integer, List<CapitalCallWrapper>>();
        } else if (this.currentStep == Step.COMMITMENT_CHECK) {
            currentStep = Step.COMMITMENT_SELECTION;
        } else if (this.currentStep == Step.INPUT) {
            for(String allocatedMetricField : metricToFundAllocMap.keySet()){
                system.debug(allocatedMetricField);
                system.debug(metricToFundAllocMap.get(allocatedMetricField));
                system.debug(roundingTypeToAllocMap.get(allocatedMetricField));
            }
            if (doCheck0) {
                currentStep = Step.COMMITMENT_CHECK;
            } else {
                currentStep = Step.COMMITMENT_SELECTION;
            }
        }
        return null;
    }
    
    // Called when user clicks "Save" after reviewing the new capital calls:
    public PageReference confirmAndSave() {
        // If the checkbox is checked then it calls validateFieldValues() method.
        if(isNullOrZeroCapCommitmentCheckbox == true){
            validateFieldValues();
        }
        // update the amount due if the call amounts have changed.
        fund.Capital_Calls_Update_Status__c = 'In Progress';
        update fund;
        upsert parent;
        Map<Id, Capital_Commitment__c> selectedMap = extractSelectedMap(
            this.mapOfCapitalCommitments
        );
        if(!TestCapitalCallController.coverBatchStatus){
            for (Integer pageNum : mapOfCapitalCalls.keySet()) {
                for (CapitalCallWrapper wrapped : mapOfCapitalCalls.get(pageNum)) {
                    wrapped.record.Capital_Call_Parent__c = parent.Id;
                    wrapped.record.Capital_Call_Amount__c = wrapped.record.Capital_Call_Amount__c.setScale(
                        2
                    ); // make sure the values are to 2 decimal places
                    if (
                        selectedMap != null &&
                        selectedMap.get(wrapped.record.Capital_Commitment__c) != null
                    ) {
                        decimal expenseOutcomitment = wrapped.record.Expenses_Outside_of_Commitment__c != null ? wrapped.record.Expenses_Outside_of_Commitment__c : 0.0;
                        decimal lateAdmInterest = wrapped.record.Late_Admission_Interest__c != null ? wrapped.record.Late_Admission_Interest__c : 0.0;            

                        wrapped.record.Amount_Due__c = selectedMap.get(wrapped.record.Capital_Commitment__c).Total_Over_Under_Paid__c <= (wrapped.record.Capital_Call_Amount__c + expenseOutcomitment + lateAdmInterest)
                            ? ( wrapped.record.Capital_Call_Amount__c + expenseOutcomitment + lateAdmInterest) - selectedMap.get(wrapped.record.Capital_Commitment__c).Total_Over_Under_Paid__c
                            : 0.0;
                    }
                    // if there are records with zero/null values and the Do not create blank records is checked then these records are not added to capitalCallRecords.
                    if(isNullOrZeroCapCommitmentCheckbox == false || (isNullOrZeroCapCommitmentCheckbox == true && mapOfCapCommWithZeroValues.get(wrapped.record.Capital_Commitment__c) != Null && !mapOfCapCommWithZeroValues.get(wrapped.record.Capital_Commitment__c))){
                       capitalCallRecords.add(wrapped.record);
                    }
                }
            }
        }
        selectedMap = null;
        //newCapitalCalls = null;
        BatchForAsynchronousProcessingOfRecords captialcallsInsrtBatch  = new BatchForAsynchronousProcessingOfRecords((List<SObject>)capitalCallRecords, fund.Id,'Insert', parent.id);
        Integer batchSize = 100;
        ImportWizardSettings__c importWizSettings =  ImportWizardSettings__c.getOrgDefaults();
        if(importWizSettings.Record_Insertion_Batch_Size__c != null && importWizSettings.Record_Insertion_Batch_Size__c != 0){
            batchSize = (Integer)importWizSettings.Record_Insertion_Batch_Size__c;
        }            
        BatchId = Database.executeBatch(captialcallsInsrtBatch,batchSize);
        Integer recCount = capitalCallRecords.size();
        AsyncApexJob jobOfCapitalCallsInsertion = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors ,CreatedDate
                                                   FROM AsyncApexJob WHERE ID =: BatchId ];
        if(BatchId != null){
            batchProcessingRequest = jobOfCapitalCallsInsertion.status;
            parent.Capital_Call_Update_Status__c =  batchProcessingRequest;
        }
        capitalCallRecords.clear();
        mapOfCapitalCalls.clear();
        isSuccess = true; 
        return null;
    }
    // calls when user clicks on confirm and save button and isNullOrZeroCapCommitmentCheckbox is true.
    public void validateFieldValues(){
        List<String> fieldList = new List<String>();
        Boolean checkIfAllColoumnsZero;
        for(Schema.FieldSetMember fieldSetMemberObj : capCallFieldSetColumns){
            fieldList.add(fieldSetMemberObj.getFieldPath());
        }
        fieldList.add(PackageUtils.dynamicReference('Capital_Call_Amount__c'));
        for (Integer pageNum : mapOfCapitalCalls.keySet()) {
            for (CapitalCallWrapper capCallRecord : mapOfCapitalCalls.get(pageNum)) {
                checkIfAllColoumnsZero = true;
                for(String fieldAPIName : fieldList){
                    Object fieldValue = capCallRecord.record.get(fieldAPIName);
                    if((decimal)fieldValue != Null && (decimal)fieldValue != 0){
                        checkIfAllColoumnsZero = false;
                        break;
                    }
                }
                //mapOfCapCommWithZeroValues contains ID of the commitment and boolean value which is set based on the values in the fields
                mapOfCapCommWithZeroValues.put(capCallRecord.record.Capital_Commitment__c, checkIfAllColoumnsZero);
            }
        }
    }
    public List<Id> succeededCapitalCommId ;
    /*Tracks status of the batch and displays the end user different messages depending upon tha batch status and also shows list of successfully created capital call records and list of capital commmitments for which if the capital call records have not been inserted successfully*/
    public PageReference executionStatusOfBatch(){
        List<Capital_Call__c> insertedCapitalCalls = new List<Capital_Call__c>();
        AsyncApexJob  jobOfCapitalCallsInsertion = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors ,CreatedDate,ExtendedStatus
                                                    FROM AsyncApexJob WHERE ID =: BatchId ];
        TotalJobItems =  jobOfCapitalCallsInsertion.TotalJobItems;
        JobItemsProcessed =  jobOfCapitalCallsInsertion.JobItemsProcessed; 
        if(!TestCapitalCallController.coverBatchStatus){   
            BatchJobStatus =  jobOfCapitalCallsInsertion.Status;
        }
        boolean isTheBatchLongRunning = BatchUtil.isBatchLongRunning(jobOfCapitalCallsInsertion);
        if(BatchJobStatus == 'Holding'){   
            batchProcessingRequest = 'Holding';
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Batch has been started execution please wait...'));
        }else if(BatchJobStatus == 'Preparing'){
            batchProcessingRequest = 'Preparing'; 
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Successfully initiated process to create Capital calls. \n Please followup with \'Capital calls Update Status\' & \'Capital calls Last Updated Date\' fields to know the status.'));
        }else if(BatchJobStatus == 'Queued'){
            batchProcessingRequest = 'Queued';
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Batch has been queued please wait for the batch to start execution...'));
        } else if((BatchJobStatus == 'Processing') && (TotalJobItems == 0 || JobItemsProcessed == 0) ){
            batchProcessingRequest = 'Processing Started';
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Batch has started proccessing the records please wait while we show you the capital calls that are successfully created'));
        } else if((BatchJobStatus == 'Processing' && TotalJobItems != 0 && JobItemsProcessed != 0 ) || BatchJobStatus == 'Completed' ){
            if(!TestCapitalCallController.coverBatchStatus){ 
                insertedCapitalCalls = [
                    SELECT Id,Name,LP_Entity__c,LP_Entity__r.Name,Capital_Call_Parent__c,Capital_Commitment__c,Capital_Commitment__r.Name,CreatedDate, Capital_Commitment__r.LP_Entity__c
                    FROM Capital_Call__c where Capital_Call_Parent__c =: parent.Id and  LastModifiedDate >= : jobOfCapitalCallsInsertion.CreatedDate];
            }
            else{
                insertedCapitalCalls = [
                    SELECT Id,Name,LP_Entity__c,LP_Entity__r.Name,Capital_Call_Parent__c,Capital_Commitment__c,Capital_Commitment__r.Name,CreatedDate, Capital_Commitment__r.LP_Entity__c
                    FROM Capital_Call__c where Capital_Call_Parent__c =: parent.Id];
            }
            capitalCallsSuccess = new List<Capital_Call__c>();
            succeededCapitalCommId = new List<Id>();
            for(Capital_Call__c capCall : insertedCapitalCalls){
                capitalCallsSuccess.add(capCall);
                succeededCapitalCommId.add(capCall.Capital_Commitment__c); 
            }
            List<Capital_Call__c> processedSuccessCapitalCalls = new List<Capital_Call__c>();
            Integer totalRecordsProcessed = 0; 
            Integer capitalCallsSuccessCounter = 0;
            Integer capitalCallsSuccessPageNumber = 0;
            for(Capital_Call__c capitalCallRec : capitalCallsSuccess){
                totalRecordsProcessed++;
                capitalCallsSuccessCounter++;
                processedSuccessCapitalCalls.add(capitalCallRec);
                if(capitalCallsSuccessCounter == capitalCallsSuccessPageSize){
                    capitalCallsSuccessPageNumber = capitalCallsSuccessPageNumber + 1;
                    mapOfCapitalCallSuccess.put(capitalCallsSuccessPageNumber, processedSuccessCapitalCalls);
                    capitalCallsSuccessCounter = 0;
                    processedSuccessCapitalCalls = new List<Capital_Call__c>();
                }
                else if(totalRecordsProcessed == capitalCallsSuccess.size()){
                    capitalCallsSuccessPageNumber = capitalCallsSuccessPageNumber + 1;
                    mapOfCapitalCallSuccess.put(capitalCallsSuccessPageNumber, processedSuccessCapitalCalls);
                }   
            }
            TotalNumberOfCapitalCallsProccessed  = totalRecordsProcessed;
            if(mapOfCapitalCallSuccess.size()!=0){
                capitalSuccessCurrentPageNumber  = 1; 
            }
            if(BatchJobStatus == 'Processing'){
                batchProcessingRequest = 'Processing';
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Batch has started proccessing the records please wait while we show you the capital calls that are successfully created'));
            }
            else if(BatchJobStatus == 'Completed'){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Batch has finished creating capital calls successfully'));
                batchProcessingRequest = 'Completed';
                for(Capital_Commitment__c capitalCommSelectedComm : selectedCapitalCom){
                    if((!succeededCapitalCommId.contains(capitalCommSelectedComm.Id) &&  isNullorZeroCapCommitmentcheckbox == false)|| (!succeededCapitalCommId.contains(capitalCommSelectedComm.Id) && isNullorZeroCapCommitmentcheckbox == true && mapOfCapCommWithZeroValues.containsKey(capitalCommSelectedComm.Id) && mapOfCapCommWithZeroValues.get(capitalCommSelectedComm.Id)==false)){
                        failedCapitalCommId.add(capitalCommSelectedComm);
                    }
                }
                Integer totalfailureRecordsProcessed = 0;
                Integer failurecounter = 0;
                Integer pageNumber = 0;
                List<Capital_Commitment__c> listOfFailureCapitalComm = new List<Capital_Commitment__c>();
                for(Capital_Commitment__c failedCapCom : failedCapitalCommId){
                    totalfailureRecordsProcessed++;
                    failurecounter++;
                    listOfFailureCapitalComm.add(failedCapCom);
                    if (failurecounter == capitalCallfailurePageSize) {  
                        pageNumber = pageNumber + 1;
                        mapOfFailureCapitalCommitments.put(pageNumber, listOfFailureCapitalComm);
                        failurecounter = 0;
                        listOfFailureCapitalComm = new List<Capital_Commitment__c>();
                    }
                    else if (totalfailureRecordsProcessed == failedCapitalCommId.size()) {
                        pageNumber = pageNumber + 1;
                        mapOfFailureCapitalCommitments.put(pageNumber, listOfFailureCapitalComm);
                    }
                }
                TotalNumberOfCapitalCallsFailed = totalfailureRecordsProcessed;
                if(mapOfFailureCapitalCommitments.size()>0){
                    failureCapitalCommitCurrentPageNumber = 1;
                }
                // This is to get the Capital Call Parent Name to display in the finish page with hyperlink.
                parent = [select id,name from Capital_Call_Parent__c where id =: parent.id];
            }
        }   
        else if(BatchJobStatus == 'Aborted'){
            batchProcessingRequest = 'Aborted';
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Batch has been aborted'));
        }
        else if(BatchJobStatus == 'Failed'){
            batchProcessingRequest = 'Failed';
            BatchNumberOfErrors =  jobOfCapitalCallsInsertion.NumberOfErrors;
            BatchFailureMessage =  jobOfCapitalCallsInsertion.ExtendedStatus;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Batch has been Failed'));
        }
        //Checks if the batch is in long running and displays an info message
        if((BatchJobStatus == 'Holding' || BatchJobStatus == 'Preparing'|| BatchJobStatus == 'Queued' || BatchJobStatus == 'Processing') && isTheBatchLongRunning){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'The server is experiencing unusually high traffic.This job is in queue and will be completed.'));
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'You may leave this page and monitor the status on the "Funds" page using the "Capital Calls Update Status".'+' This can sometimes take upto 2 hours in extreme situations.'));
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Please wait for this job to finish before creating any new "Funds" for "Capital Call".'));
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'You will be notified by email when this job is finished.'));
            //return null;
        }
        if(batchProcessingRequest == 'Processing'){
            parent.Capital_Call_Update_Status__c = batchProcessingRequest + ' ( '+  jobOfCapitalCallsInsertion.JobItemsProcessed+' of '+ jobOfCapitalCallsInsertion.TotalJobItems +' )'; 
        }
        else{
            parent.Capital_Call_Update_Status__c = batchProcessingRequest;
        }
        if(parent!=null){
          	update parent;
        }
        return null;
    }
    // Return redirect to Fund:
    public PageReference returnToFund() {
        ApexPages.StandardController sc = new ApexPages.StandardController(fund);
        //	mapOfCapitalCommitments.clear();
        return sc.view();
    }
    
    /**
* String representation of the current step
* @author Nathan (Trineo)
*/
    public String getCurrentStepName() {
        return currentStep.name(); 
    }
    public String setCurrentStepName() {
        return currentStep.name();
    } 
    //SF-209(Manage available fields button)
    // To display the Popup
    public void showPopup(){
        displayPopUp = true;
        setFieldsOnMultipicklist();
    }
    //method to close the popup
    public void closePopup(){
        displayPopUp = false;
    }
    public MetadataServiceHelper.FieldsetInfoWrapper fieldsetwrapper = new MetadataServiceHelper.FieldsetInfoWrapper();
    // On click of Update button the fields gets updated in the fieldset.fieldsetwrapper is a wrapper which is sent as a parameter 
    // to the MetadataServiceHelper.FieldsetInfoWrapper method. 
    public PageReference updateFieldsOfFieldset(){
        displayPopUp = false;
        List<String> availableFields = new List<String>(); //Fields on the left side of multiselectPicklist in the pop-up
        List<String> inTheFieldsetFields = new List<String>(); //Fields on the Right side of multiselectPicklist in the pop-up
        for (SelectOption sm : leftOptions){
            availableFields.add(sm.getvalue());
        }
        system.debug('available fields on click of update:'+ availablefields);
        for (SelectOption sm : rightOptions){
            inTheFieldsetFields.add(sm.getValue());
        }
        system.debug('In the field set fields on click of update:'+ inTheFieldsetFields);
        fieldsetwrapper.objectName = 'Capital_Call__c';
        fieldsetwrapper.label = SObjectType.Capital_Call__c.FieldSets.Import_Wizard_Fields.getLabel();
        fieldsetwrapper.fieldsetName = 'Import_Wizard_Fields';
        fieldsetwrapper.description = SObjectType.Capital_Call__c.FieldSets.Import_Wizard_Fields.getDescription();
		fieldsetwrapper.availableFields = availableFields;
        fieldsetwrapper.inTheFieldsetFields = inTheFieldsetFields;
        try{
            UpdatefieldsetreturnMap = MetadataServiceHelper.updatefieldsOnFieldset(fieldsetwrapper);
        }catch (Exception e) {
            String errorMessage = 'Error updating fields for Capital Call fieldset ' + UpdatefieldsetreturnMap.keySet();
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMessage));
            return null;
        }
        if(UpdatefieldsetreturnMap != Null && UpdatefieldsetreturnMap.size()>0 && UpdatefieldsetreturnMap.values()[0] == true){
            updateFieldset = true;
            updateFieldsetcounter = 0;
        }
        else{
            String errorMessage = 'Error: Update fieldset failed due to ' + UpdatefieldsetreturnMap.keySet();
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMessage));
            return null;
        }
        system.debug('issuccess is'+updateFieldset);
        setFieldsOnMultipicklist();
        return null;
    }
    
    /**
* Given a list of Capital Commitments, returns a list of selection wrapped capital commitments
* @author Nathan (Trineo)
* @param List<Capital_Commitment__c> commitments : The commitments to wrap
* @return List<Capital_Commitment__c> the wrapped commitment records
*/
    public Map<Integer, List<CommitmentWrapper>> wrapCommitments(
        List<Capital_Commitment__c> commitments
    ) {
        List<CommitmentWrapper> listOfCapitalCommitmentPerPage = new List<CommitmentWrapper>();
        Integer totalRecordsProcessed = 0;
        Integer counter = 0;
        Integer pageNumber = 0;
        Boolean isZeroPresent = false;
        //Integer remainingRecords = 0;
        for (Capital_Commitment__c commitment : commitments) {
            if(commitment.Capital_Commitment__c == 0 && isZeroPresent == false){
                isZeroPresent = true;
            }
            totalRecordsProcessed++;
            counter++;
            listOfCapitalCommitmentPerPage.add(new CommitmentWrapper(commitment));
            if (counter == capitalCommitmentPageSize) {
                pageNumber = pageNumber + 1;
                if(isZeroPresent == true){
                    listOfPageNoofZeroCapitalCommt.add(pageNumber);
                }
                mapOfCapitalCommitments.put(pageNumber, listOfCapitalCommitmentPerPage);
                counter = 0;
                listOfCapitalCommitmentPerPage = new List<CommitmentWrapper>();
                isZeroPresent = false;
            } else if (totalRecordsProcessed == commitments.size()) {
                pageNumber = pageNumber + 1;
                if(isZeroPresent == true){
                    listOfPageNoofZeroCapitalCommt.add(pageNumber);
                }
                mapOfCapitalCommitments.put(pageNumber, listOfCapitalCommitmentPerPage);
                isZeroPresent = false;
            }
        }
        capitalCommitmentCurrentPageNumber = 1;
        isdataLoaded = true;
        if(listOfPageNoofZeroCapitalCommt.size()!=0){
            for(Integer pageNum:listOfPageNoofZeroCapitalCommt){
                listOfPageNumbers.add(pageNum);
            }
            zerocapitalCommitmentCurrentPageNumber = 0;
        }
        return mapOfCapitalCommitments;
    }
    
    /**
* extractSelected
* @author Nathan (Trineo)
* @param List<CommitmentWrapper> commitments : wrapped commitments to use
* @return List<Capital_Commitment__c> selected : the selected commitments
*/
    public static List<Capital_Commitment__c> extractSelected(
        Map<Integer, List<CommitmentWrapper>> capitalCommitmentsMap
    ) {
        List<Capital_Commitment__c> selected = new List<Capital_Commitment__c>();
        for (Integer pageNum : capitalCommitmentsMap.keySet()) {
            for (CommitmentWrapper commitment : capitalCommitmentsMap.get(pageNum)) {
                if (commitment.checked) {
                    selected.add(commitment.record);
                }
            }
        }
        return selected;
    }
    
    /**
* extractSelectedMap
* @author Sravan M (WAL)
* @param List<CommitmentWrapper> commitments : wrapped commitments to use
* @return Map<Id,Capital_Commitment__c> selected : the selected commitments Map with Id
*/
    public static Map<Id, Capital_Commitment__c> extractSelectedMap(
        Map<Integer, List<CommitmentWrapper>> capitalCommitmentsMap
    ) {
        Map<Id, Capital_Commitment__c> selectedMap = new Map<Id, Capital_Commitment__c>();
        for (Integer pageNum : capitalCommitmentsMap.keySet()) {
            for (CommitmentWrapper commitment : capitalCommitmentsMap.get(pageNum)) {
                if (commitment.checked) {
                    selectedMap.put(commitment.record.Id, commitment.record);
                }
            }
        }
        return selectedMap;
    }
    
    /**
* Class to model Commitments together with a checkbox selection state
* @author Nathan (Trineo)
*/
    public class CommitmentWrapper {
        public Capital_Commitment__c record { get; set; }
        public Boolean checked { get; set; }
        public Boolean isZero { get; set; }
        public CommitmentWrapper(final Capital_Commitment__c commitment) {
            record = commitment;
            checked = true; // Assume checked
            isZero = commitment.Capital_Commitment__c == 0 ? true : false;
        }
    }
    
    public class CapitalCallWrapper {
        public Capital_Call__c record { get; set; }
        public String entityName { get; set; }
        
        public CapitalCallWrapper(
            final Capital_Call__c record,
            final String entityName
        ) {
            this.record = record;
            this.entityName = entityName;
        }
        
        public CapitalCallWrapper(final Capital_Call__c record) {
            this.record = record;
        }
    }
    /**
* Method to process the uploaded CSV file and assign values to Capital Calls and the 4 other cost fields
* @author Gareth (Trineo)
*/
    public void processCSV() {
        Integer countOfInvestmentVehiclesMismatch = 0;
        if (fileBody == null) {
            return;
        }
        final String bodyAsString = fileBody.toString();
        if (String.isBlank(bodyAsString)) {
            ApexPages.addMessage(
                new ApexPages.Message(
                    ApexPages.Severity.ERROR,
                    'The CSV file seems to be empty.'
                )
            ); 
            return; 
        }
        fileBody = null;
        
        // parse the csv and get all the rows
        final Map<String, List<String>> rowsMap = CSVUtil.parseCSVtoMap(
            bodyAsString
        );
        if (rowsMap == null || rowsMap.isEmpty()) {
            ApexPages.addMessage(
                new ApexPages.Message(
                    ApexPages.Severity.ERROR,
                    'Unable to process the CSV file. Remove all commas from numbers prior to processing CSV file.'
                )
            );
            return;
        }
        
        final List<String> headerRow = rowsMap.get('Investment Vehicle');
        Map<String, Integer> rowIdMap = new Map<String, Integer>();
        Integer i = 0;
        for (String col : headerRow) {
            rowIdMap.put(col, i);
            i++;
        }
        for (Integer pageNum : mapOfCapitalCalls.keySet()) {
            for (CapitalCallWrapper ccw : mapOfCapitalCalls.get(pageNum)) {
                List<String> row = rowsMap.get(ccw.entityName);
                Decimal value;
                if (row == null) {
                    countOfInvestmentVehiclesMismatch =
                        countOfInvestmentVehiclesMismatch + 1;
                    mapOfStyles.put(ccw.entityName, 'yellow');
                    continue;
                } else {
                    mapOfStyles.put(ccw.entityName, 'null');
                }
                for (Schema.FieldSetMember f : capCallFieldSetColumns) {
                    Integer indxVal = rowIdMap.get(f.label);
                    if (
                        indxVal == null ||
                        (f.type != Schema.DisplayType.Currency &&
                         f.type != Schema.DisplayType.Double &&
                         f.type != Schema.DisplayType.Integer &&
                         f.type != Schema.DisplayType.PERCENT)
                    ) { 
                        continue; 
                    }
                    if (String.isBlank(row.get(indxVal))) {
                        value = 0.00;
                    } else { 
                        try {
                            value = Decimal.valueOf(row.get(indxVal)).setScale(2); // make sure the values are to 2 decimal places
                        } catch (Exception e) {
                            ApexPages.addMessage(
                                new ApexPages.Message(
                                    ApexPages.Severity.ERROR,
                                    'Unable to process value ' +
                                    row.get(indxVal) +
                                    '. Remove all commas from numbers prior to processing CSV file.'
                                )
                            );
                            return;
                        } 
                    }
                    ccw.record.put(f.fieldPath, value);
                }
                Decimal capCallAmountValue;
                Integer ccaIndexVal = rowIdMap.get('Capital Call Amount');
                if (String.isBlank(row.get(ccaIndexVal))) {
                    capCallAmountValue = 0.00;
                } else {
                    try {
                        capCallAmountValue = Decimal.valueOf(row.get(ccaIndexVal))
                            .setScale(2); // make sure the values are to 2 decimal places
                    } catch (Exception e) {
                        ApexPages.addMessage(
                            new ApexPages.Message(
                                ApexPages.Severity.ERROR,
                                'Unable to process value ' +
                                row.get(ccaIndexVal) +
                                '. Remove all commas from numbers prior to processing CSV file.'
                            )
                        );
                        return;
                    }
                }
                ccw.record.Capital_Call_Amount__c = capCallAmountValue;
            }
        }
        if (countOfInvestmentVehiclesMismatch != 0)
            ApexPages.addMessage(
                new ApexPages.Message(
                    ApexPages.Severity.WARNING,
                    'There were ' +
                    countOfInvestmentVehiclesMismatch +
                    ' Investement vehicles that did not match a row in the processed CSV'
                )
            ); 
    }
    /*Disables and enables the "<" button on the vf page based on the capitalCommitmentCurrentPageNumber on the 1st step*/
    public boolean getprev() {
        if (capitalCommitmentCurrentPageNumber == 1)
            return true;
        else
            return false;
    }
    /*Disables and enables the ">" button on the vf page based on the capitalCommitmentCurrentPageNumber on the 1st step*/
    public boolean getnxt() { 
        if (capitalCommitmentCurrentPageNumber == mapOfCapitalCommitments.size())
            return true; 
        else
            return false; 
    }
    /*Disables and enables the "<" button on the vf page based on the zerocapitalCommitmentCurrentPageNumber on the 2nd step*/
    public boolean getzeroprev() {
        if (zerocapitalCommitmentCurrentPageNumber == 0)
            return true;
        else
            return false;
    }
    /*Disables and enables the ">" button on the vf page based on the zerocapitalCommitmentCurrentPageNumber on the 2nd step*/  
    public boolean getzeronxt() {
        if (zerocapitalCommitmentCurrentPageNumber == sizeOfzeroCapitalCommitments -1)
            return true;
        else
            return false;
    }
    /*Disables and enables the "<" button on the vf page based on the capitalSuccessCurrentPageNumber on the 4th step*/
    public Boolean getcapitalcallsuccessprev(){
        if (capitalSuccessCurrentPageNumber == 1)
            return true;
        else
            return false;
    }
    /*Disables and enables the ">" button on the vf page based on the capitalSuccessCurrentPageNumber on the 4th step*/
    public Boolean getcapitalcallssuccessnxt(){
        if (capitalSuccessCurrentPageNumber == mapOfCapitalCallSuccess.size())
            return true; 
        else
            return false;
    }
    /*Disables and enables the "<" button on the vf page based on the failureCapitalCommitCurrentPageNumber on the 4th step*/
    public Boolean getcapitalcallsfailureprev(){
        if (failureCapitalCommitCurrentPageNumber == 1)
            return true;
        else
            return false;
    }
    /*Disables and enables the ">" button on the vf page based on the failureCapitalCommitCurrentPageNumber on the 4th step*/
    public Boolean getcapitalcallsfailurenxt(){
        if (failureCapitalCommitCurrentPageNumber == mapOfFailureCapitalCommitments.size())
            return true; 
        else
            return false;
    }
    /*Excutes on click of "<" button on the vf page display the previous page if there is any on the 1st step*/
    public void previousCapitalCommitmenttList() {
        capitalCommitmentCurrentPageNumber = capitalCommitmentCurrentPageNumber - 1;
    }
    /*Excutes on click of "<" button on the vf page display the previous page if there is any on the 2nd step*/
    public void previousZeroCapitalCommitmenttList() { 
        zerocapitalCommitmentCurrentPageNumber =  zerocapitalCommitmentCurrentPageNumber-1;
    } 
    /*Excutes on click of ">" button on the vf page display the previous page if there is any on the 2nd step*/
    public void nextzeroCapitalCommitmentList() {
        zerocapitalCommitmentCurrentPageNumber = zerocapitalCommitmentCurrentPageNumber +1;
    }
    /*Excutes on click of ">" button on the vf page display the previous page if there is any on the 1st step*/
    public void nextCapitalCommitmentList() {
        capitalCommitmentCurrentPageNumber = capitalCommitmentCurrentPageNumber + 1;
    }
    /*Excutes on click of "<" button on the vf page display the previous page if there is any on the 4th step*/
    public void previousCapitalCallSuccessList(){  
        capitalSuccessCurrentPageNumber = capitalSuccessCurrentPageNumber - 1;
    }
    /*Excutes on click of ">" button on the vf page display the previous page if there is any on the 4th step*/
    public void nextCapitalCallSuccessList(){
        capitalSuccessCurrentPageNumber = capitalSuccessCurrentPageNumber + 1;
    }
    /*Excutes on click of "<" button on the vf page display the previous page if there is any on the 4th step*/
    public void previoustCapitalCallFailureList(){   
        failureCapitalCommitCurrentPageNumber = failureCapitalCommitCurrentPageNumber - 1;
    }
    /*Excutes on click of ">" button on the vf page display the previous page if there is any on the 4th step*/
    public void nexttCapitalCallFailureList(){
        failureCapitalCommitCurrentPageNumber = failureCapitalCommitCurrentPageNumber + 1;
    }
}