function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sfg1sfg1 

Sorting date field and displaying Latest and old date

I have muliple records in dxCodes. I am trying to display output format,  based on dxCodes.I have a custom field  "DOS__c" i need to display latest date in "DOS__c". And  for "DOS_End__c" i need to display old date. Somoe one please guide me in this. thanks.
 
        // Get charts and dxcodes to work on        
        List<MC_Chart__c> charts = (List<MC_Chart__c>) scope;         Map<Id, List<mc_Chart_DxCode__c>> chartIdToDxCodeMap = buildChartIdToDxcodeMap(charts);         // Get project details         Project2__c theProject = [SELECT Name FROM Project2__c WHERE Name = :projectKey Limit 1];         // Get mcMember details details         Set<Id> members = new Set<Id>();        
       for(MC_Chart__c c : charts) {          
          members.add(c.Member__c);         }    
      Map<ID, mc_Member__c> theMembers = new Map<ID, mc_Member__c([SELECT Id, Name, Recapture_V12__c FROM mc_Member__c 
  WHERE Id IN :members]);       
  // Build Output
  // For each chart   
      for(MC_Chart__c c : charts) {           
  // Get the list of DxCodes for this Chart from our map         
    List<mc_Chart_DxCode__c> dxCodes = new List<mc_Chart_DxCode__c>();        
     if(chartIdToDxCodeMap.containsKey(c.Id)) { // It's possible for a chart to have no DxCodes                 dxCodes = chartIdToDxCodeMap.get(c.Id);                 // the Dx Codes need to be grouped on DOS_Start / DOS_End for this format                 Map<String, List<MC_Chart_DxCode__c>> dxGroupMap = new Map<String, List<MC_Chart_DxCode__c>>();
 for(mc_Chart_DxCode__c dx : dxCodes) {

                    String providerFirstName = '';
                    String providerLastName = '';
                   
                     String dob = '';
                     String dos = '';
                 
                     if (dx.DOS__c != null){
                       dos = GetFormat(dx.DOS__c, 'MM/dd/yyyy');
                       }
                    String dosTo = '';
                    if (dx.DOS_End__c != null) {
                        dosTo = GetFormat(dx.DOS_End__c, 'MM/dd/yyyy');
                    }    
Asif Ali MAsif Ali M
Please try the below logic.
Date[] dl1 = new List<Date>();
Date[] dl2 = new List<Date>();

// Get the Dates into List
for (Sobject dx : dxCodes) {

    dl1.add(Date.valueOf(dx.get('DOS__c')));
    dl2.add(Date.valueOf(dx.get('DOS_End__c')));

}
// Sort the Dates List
dl1.sort();
dl2.sort();

// Now get the MIN/MAX based on your need.
// Min is at first Index and MAX is at last index.
Integer i = dl1.size();
String Dos__c = (i > 0) ? dl1[i - 1] : '';
String DOS_End__c = (dl2.size() > 0) ? dl2[0] : '';
sfg1sfg1
Thanks for your reply Asif. I have used below code. It is working fine for few records. For if few records it is not working as per logic(Picking latest ans old date). Please guide me.
                 string dos='';
                 Date[] dl1 = new List<Date>();
                 Date[] dl2 = new List<Date>();
                 dl1.add(Date.valueOf(dx.get('DOS__c')));
                 dl2.add(Date.valueOf(dx.get('DOS_End__c')));
                 dl1.sort();
                 dl2.sort();
                 
                        if (dx.DOS__c != null) {
                        dos = GetFormat(dl1[0], 'MM/dd/yyyy');
                        System.debug('The dos is: ' + dos);
                         } 
                  
                    String dosTo = '';
                    if (dx.DOS_End__c != null) {
                        dosTo = GetFormat(dl2[dl2.size() - 1], 'MM/dd/yyyy');
                        System.debug('The dosTodate is: ' + dosTo);
                    }  
Asif Ali MAsif Ali M
Below 2 lines should only be in for loop. Sorting statements and other remaining code should be outside the for loop. Share me your full for block to understand the it better.
dl1.add(Date.valueOf(dx.get('DOS__c')));
dl2.add(Date.valueOf(dx.get('DOS_End__c')));


 
sfg1sfg1
global class MC_AsyncOutputFile_AetnaMedicareMetadata extends MC_AsyncOutputFile_base {

    protected integer detailRowCount = 0; //Since >1 Dx's can be on one line, the rowcount needs to be kept separate
    protected String fileCreateDate = '';
    protected String fileId = '';
    protected String aetOrCVTY = '';

    //
    // Constructor
    //

    global MC_AsyncOutputFile_AetnaMedicareMetadata(MC_AsyncOutputFile__c outputFileParam, string projectKeyParam, date fromDateParam, date toDateParam) {
        asyncOutput = outputFileParam;
        projectKey = projectKeyParam;
        fromTimeStamp = Datetime.newInstance(fromDateParam.year(), fromDateParam.month(), fromDateParam.day());
        toTimeStamp = Datetime.newInstance(toDateParam.year(), toDateParam.month(), toDateParam.day() + 1);
    }


    //
    // Override Methods
    //

    protected override String BuildQueryString(){
        query = 'Select Id, Name, Status__c, Member__r.Name, Member__r.DOB__c,Chart_Url__c, Member__r.Last_Name__c, Member__r.First_Name__c, ';
        query += 'Member__r.Gender__c, Flex_Field_1__c, Flex_Field_2__c, Flex_Field_3__c, Flex_Field_4__c, Flex_Field_5__c, Flex_Field_6__c, Flex_Field_7__c, Flex_Field_8__c, ';
        query += 'Member__r.HICN__c, L1_Finish_TimeStamp__c ';
        query += 'From MC_Chart__c Where Status__c = \'' + MC_CMN.DELIVERED + '\' ';
        query += 'And Project__r.Name = \'' + projectKey + '\' ';
        query += 'And Delivered_TimeStamp__c >= ' + fromTimeStamp.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\' ', 'GMT');
        query += 'And Delivered_TimeStamp__c <= ' + toTimeStamp.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'', 'GMT');

        fileCreateDate = DateTime.now().format('YYYYMMddHHmmss');
        fileId = 'Episource' + fileCreateDate;

        if (projectKey == '2001170536' || projectKey == '2001170534' || projectKey == '2001170533' || projectKey == '2001170535' || projectKey == '2001170685' || projectKey == '2001170684' || projectKey == '2001170684' || projectkey == '2001170672' || projectkey == '2001170673') {
            aetOrCVTY = 'AET';
        } 
        /*   else if (projectKey == '2001170534' || projectKey == '2001170536' || projectKey == '2001150576' || projectKey == '2001151033' || projectKey == '2001150575' || projectKey == '2001151032') {
            aetOrCVTY = 'CVTY';
        }*/
         if (Utils.writeDebugLog(Utils.DEBUG_LEVEL_DEBUG)) { System.debug(LoggingLevel.DEBUG, '[MC_AsyncOutputFile_AetnaMedicareCode2017] query string constructed: ' + query); }
        return query;
    }


    protected override String buildFileName() {
        // Format: EPISOURCE-AET.GPS.OFFSHORE.MMDDYYYY.TXT
        return 'Epi MetaData_' + System.now().format('dd.MM.YYYY') + '.TXT';
    }


    protected override String buildHeaderRow(){
        List<String> headerRow = new List<String>();

       
        headerRow.add('MemberID');     
        headerRow.add('MemberGender'); 
        headerRow.add('MemberDOB');
        headerRow.add('ChartRequestID');       
        headerRow.add('DOSStartDt');
        headerRow.add('DOSEndDt');       
        headerRow.add('ChartFileName');
        

        String result = buildContentRowFromList(headerRow, delimiter);
        return result;
    }

    protected override String buildFooterRow(){
        return '';
    }

    protected override void Process(List<sObject> scope) {
         if (Utils.writeDebugLog(Utils.DEBUG_LEVEL_DEBUG)) { System.debug(LoggingLevel.DEBUG, '[MC_AsyncOutputFile_AetnaMedicareMetadata] Process Begin'); }

        // Get charts and dxcodes to work on
        List<MC_Chart__c> charts = (List<MC_Chart__c>) scope;
        Map<Id, List<mc_Chart_DxCode__c>> chartIdToDxCodeMap = buildChartIdToDxcodeMap(charts);

        // Get project details
        Project2__c theProject = [SELECT Name FROM Project2__c WHERE Name = :projectKey Limit 1];

        // Get mcMember details details
        Set<Id> members = new Set<Id>();
        for(MC_Chart__c c : charts) {
            members.add(c.Member__c);
        }
        Map<ID, mc_Member__c> theMembers = new Map<ID, mc_Member__c>([SELECT Id, Name, Recapture_V12__c FROM mc_Member__c WHERE Id IN :members]);

        // Build Output
        // For each chart
        for(MC_Chart__c c : charts) {
            // Get the list of DxCodes for this Chart from our map
            List<mc_Chart_DxCode__c> dxCodes = new List<mc_Chart_DxCode__c>();
            if(chartIdToDxCodeMap.containsKey(c.Id)) { // It's possible for a chart to have no DxCodes
                dxCodes = chartIdToDxCodeMap.get(c.Id);

                // the Dx Codes need to be grouped on DOS_Start / DOS_End for this format
                Map<String, List<MC_Chart_DxCode__c>> dxGroupMap = new Map<String, List<MC_Chart_DxCode__c>>();

                for(mc_Chart_DxCode__c dx : dxCodes) {

                //   if (!isDeletedCode(dx) && dx.CDV_Result__c != 'Exclude' && dx.Name != 'No HCC Codes'  ) {

                   // String dosEndDate = GetFormat(dx.DOS_END__c,'yyyy-MM-dd');
                   // Date dosEndDate2 = date.valueOf(dosEndDate);
                   // Date icd10Date = date.valueOf('2015-10-01');

                    String providerFirstName = '';
                    String providerLastName = '';
                    String providerPlanProviderID = '';
                    String providerName = '';
                    String providerType = '';
               /*     if(!String.isBlank(dx.Provider_Name__c) && String.isBlank(providerName)) {
                        providerName = dx.Provider_Name__c;
                    }
                    if(!String.isBlank(dx.Flex_Field__c) && String.isBlank(providerType)) {
                        providerType = dx.Flex_Field__c;

                    }*/

                    if (providerName.isNumeric()) {
                        providerPlanProviderID = providerName;
                    }
                    else {
                        providerName = c.Flex_Field_4__c;
                        providerPlanProviderID = providerName;
                    }

                     string chartflex1;
                    if (c.Flex_Field_1__c != null) {
                    chartflex1 = c.Flex_Field_1__c;
                    }
                   
                     String dob = '';
                     string dos='';
                 Date[] dl1 = new List<Date>();
                 Date[] dl2 = new List<Date>();
                 dl1.add(Date.valueOf(dx.get('DOS__c')));
                 dl2.add(Date.valueOf(dx.get('DOS_End__c')));
                 dl1.sort();
                 dl2.sort();
                 
                       if (dx.DOS__c != null) {
                        dos = GetFormat(dl1[0], 'MM/dd/yyyy');
                        System.debug('The dos is: ' + dos);
                    
                            System.debug('The dosdate is: ' + dos);
                       } 
                  
                    String dosTo = '';
                    if (dx.DOS_End__c != null) {
                        dosTo = GetFormat(dl2[dl2.size() - 1], 'MM/dd/yyyy');
                        System.debug('The dosTodate is: ' + dosTo);
                    }    
                    
                    
                    
                        
                    if (c.Member__r != null && c.Member__r.DOB__c != null)
                        dob = GetFormat(c.Member__r.DOB__c, 'MM/dd/yyyy');
                  //  String gender = c.Member__r.Gender__c;
               //  dos = GetFormat(dx.DOS__c, 'MM/dd/yyyy');
                  // if(c.mc_Chart_DxCode__r !=Null && c.mc_Chart_DxCode__r.DOS__c != null)
                      //  dos = GetFormat(mc_Chart_DxCode__c.DOS__c, 'MM/dd/yyyy');
                  //  String dosTo = GetFormat(dx.DOS_End__c, 'MM/dd/yyyy');
                    
                    String icdIndicator = '';
                   // String dosDate = GetFormat(dx.DOS__c,'yyyy-MM-dd');
                 //   Date dosDate2 = date.valueOf(dosDate);
                    Date icd10 = date.valueOf('2015-10-01');
                  //  if(dosDate2 >= icd10) {
                      //  icdIndicator = 'ABF';
                  //  } else {
                     //   icdIndicator = 'BF';
                   // }

                    numOfCodes += 1;

                    
                    List<String> outputRow = new List<String>();
                    outputRow.add(c.Member__r.id);
                    outputRow.add(c.Member__r.Gender__c );
                    outputRow.add(dob);
                    outputRow.add(Chartflex1);
                    outputRow.add(dos);
                    outputRow.add(dosTo);
                    outputRow.add(c.Flex_Field_1__c + ' ' + c.Flex_Field_6__c + '' + c.Flex_Field_8__c +'.pdf');
                     // Save row to Output
                    outputFileContent += buildContentRowFromList(outputRow, delimiter);

                    // If current output string is too large, save it off and start a new "piece"
                    if(outputFileContent.length() >= maxCharsBeforeSave) {
                        SaveCurrentContent();
                    }

                    
                   // }
             //   } // End calulated chart loop
            }
        } // End chart loop
    }


    // *** Overridden to filter out codes that are not "ADD"
    // Builds a ChartID to List<DxCode> map out of a list of charts.
 //   protected override Map<Id, List<mc_Chart_DxCode__c>> buildChartIdToDxcodeMap(List<MC_Chart__c> charts){
        // Note: Used because Parent/Child queries used in batch jobs can sometimes
        // experience a cursor error when traversing the child records. Best practice
        // is to query for the parent objects only (charts), and then query for the required
        // child objects (dx codes) on each iteration of the batch. To avoid using SOQL in a
        // loop this function is used to retreive all dx codes for a group of charts at the
        // beginning of each batch iteration.

        Set<Id> chartIds = new Set<Id>();
        for(MC_Chart__c c : charts)
            chartIds.add(c.Id);

        List<mc_Chart_DxCode__c> codes =
            [Select Id,
                    Name,
                    L1_Primary_Comment__c,
                    L1_Secondary_Comment__c,
                    L2_Primary_Comment__c,
                    L2_Secondary_Comment__c,
                    Master_Audit_Primary_Comment__c,
                    Master_Audit_Secondary_Comment__c,
                    DOS__c,
                    DOS_End__c,
                    DOS_Year__c,
                    Provider_Name__c,
                    HCC_Category__c,
                    PDF_Page__c,
                    Flex_Field__c,
                    Flex_Field_2__c,
                    CDV_Result__c,
                    CDV_Comment__c,
                    CDV_Sec_Comment__c,
                    CDV_Claim_Number__c,
                    MC_Chart__r.Id
            From mc_Chart_DxCode__c
            Where MC_Chart__r.Id In :chartIds ];
            // And L1_Primary_Comment__c NOT IN ('Delete','Incorrect - Delete') and Master_Audit_Primary_Comment__c NOT IN ('Delete','Incorrect - Delete'


  //      Map<Id, List<mc_Chart_DxCode__c>> chartIdToDxCodeMap = new Map<Id, List<mc_Chart_DxCode__c>>();
        for(mc_Chart_DxCode__c code : codes){
            if(chartIdToDxCodeMap.containsKey(code.MC_Chart__r.Id))
                chartIdToDxCodeMap.get(code.MC_Chart__r.Id).add(code);
            else {
                List<mc_Chart_DxCode__c> newList = new List<mc_Chart_DxCode__c>();
                newList.add(code);
                chartIdToDxCodeMap.put(code.MC_Chart__r.Id, newList);
            }
        }
        codes = null;
      //  return chartIdToDxCodeMap;
    }

    // *** Overridden from base to remove quotes "" from automatically being placed around all values as is std SFDC practice
    // Builds a delimited string representing a single row of a delimited document
    protected override String buildContentRowFromList(List<String> content, String delimiter) {
        String result = '';
        Boolean isFirst = true;
        for(String s : content) {
            if(String.isBlank(s)) //IsNull style guard clause
                s = '';

            if(isFirst) {
                result = String.format('{0}', new String[]{s});
                isFirst = false;
            }
            else {
                result += String.format(delimiter + '{0}', new String[]{s});
            }
        }
        return result + '\r\n';
    }
}