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
Maria22Maria22 

Update most recent (newest) Opportunity Created Date stage to Closed Won

I am working on a requirement which goes like something bleow: We have Accounts and Opportunities. Opportunities has a record type as Surgery. 1. If the account has more then one suregery opportunity, Surgery Opportunity with most recent (newest) Opportunity Created Date should remain Closed Won
2. If the account has more then one suregery opportunity, Surgery Opportunity/ies with older Opportunity Created Date should be changed to Closed Lost
3. If the Opportunity is in Closed Lost DONT DO ANYTHING.

I have written below code but it seems not working as expectation.Currently all of the surgery opportunity is changing to Closed/Won
global with sharing class OpportunityWithSurgeryBatch extends BasicJob  {


    global OpportunityWithSurgeryBatch() {
        super(200);
    }

    global OpportunityWithSurgeryBatch(Integer batchSize) {
        super(batchSize, null);
    }

   /*
    Fetch all potential accounts to close the opportunities.
   */

    global List<Application_Log__c> logRec2insert = new List<Application_Log__c>();

    global override Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([
                    SELECT 
                    (
                        SELECT Surgery_Date__c 
                        FROM Install_Base__r 
                        WHERE Surgery_Date__c <> NULL 
                        ORDER BY Surgery_Date__c DESC
                    ), 
                    Candidate_Creation_Date__c, 
                    Lead_Status__pc, 
                    ID,
                    (
                        SELECT ID, stageName, Surgery_Date__c,CreatedDate,Probability
                        FROM Opportunities 
                        WHERE RecordType.name  = 'Surgery' 
                        AND stageName <> 'Surgery Complete'
                         ORDER BY CreatedDate DESC LIMIT 1
                    ) 
                    FROM Account 
                    WHERE RecordType.name = 'Recipient'
                    
                    AND First_Surgery_Date__c <> NULL
                ]);
    }

    /*
        Process all the records
    */
    global override void execute(Database.BatchableContext BC, List<sObject> scope){

        String myLogMessage;
        Integer processedRecordsNumber;
        Map<Id,String> accIdLogMessageMap=new Map<Id,String>();
        //create list of opportunities to update
        List<Opportunity> opportunities2update = new List<Opportunity>();         
        List<Account> accounts2update = new List<Account>();         
        //check update conditions
        processedRecordsNumber = 0;
        try{            
            for(Account acc : (List<Account>)scope) {

                if (acc.Install_Base__r.size() > 0) {                   
                    Install_Base__c equipment = acc.Install_Base__r[0];


                        //set opportunity to update
                        list<Opportunity> opp = acc.Opportunities;

                        for (Opportunity op :opp) {
                            //Below conditions compare Oppty Creation Date less than Surgery Date 
                            if(Op.CreatedDate < equipment.Surgery_Date__c) {
                                myLogMessage = ''; 
                                op.stageName = 'Surgery Complete';
                                op.Surgery_Date__c = equipment.Surgery_Date__c;
                                op.Probability = 100;
                                opportunities2update.add(op);
                                myLogMessage = myLogMessage  + 'opportunity ID =(' + op.ID + '), ';
                        }

                        if (myLogMessage <> ''){
                            ++processedRecordsNumber;
                            myLogMessage   = 'Record number in the batch (' + processedRecordsNumber + '), ' 
                                + myLogMessage; 
                            accIdLogMessageMap.put(acc.ID,myLogMessage );                            
                        }
                        else{
                            accIdLogMessageMap.put(acc.ID,'' );
                        }
                    }
                }
            }


        update opportunities2update;

        for(Id accId:accIdLogMessageMap.keySet()){          
            // set account for update  
            Account acc=new Account(id=accId);
            acc.Lead_Status__pc = 'Surgery Complete';
            accounts2update.add(acc);
            if(accIdLogMessageMap.get(accId)!=''){
                //set log to insert
                Application_Log__c myLog       = new Application_Log__c();
                myLog.Source__c = 'OpportunityWithSurgery';
                myLog.Source_Function__c = 'close';
                myLog.Reference_Id__c = acc.ID;
                myLog.Reference_Info__c = 'MasterAccountId';
                myLog.Status__c  = 'Completed';
                myLog.Message__c   = accIdLogMessageMap.get(accId);
                logRec2insert.add(myLog);
            }
        }

        update accounts2update;       


        }catch (Exception ex){
            ApplicationLog.logMessage('Opportunity update Fail', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                   null, null, ex);
        }
        finally {   
            ApplicationLog.logMessage('Completed', 'OpportunityWithSurgery', 'close', 'EXCEPTION', null, 
                                      ' Total SQL: ' +  Limits.getLimitQueries() + ' Used SQL:' + Limits.getQueries(), null, null);

        }    

    }

   global override void finish(Database.BatchableContext BC){
    insert logRec2insert;
   }
}

Kindly note we are using Surgery Complete as Closed/Won for our Surgery Oppty.
Kindly advise/suggests what I am doing wrong here and what I am missing on same
Many thanks in advance