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
sumit dsumit d 

Prevent duplicate account in batch of opportunity

Hi All,
Hi All,
        i have a batch in which i am creating a parent child account hierarchy. i created new Accounts for each opportunity  And Opportunity has parent Account as the new Account which is just created and the newAccount has the Old Account as a parent.now at this time when i am executing the batch for opportunity with exact same name its creating two Accounts for each opportunity but i want that opportunity with same name should go to the account which is first created . and Opportunity should not create two Accounts .it should not created duplicate records of Account for opportunity with same name.
and if opportunity name does not contains ':'(Coloun) and '-'(Hyphen) than a checkbox Called not Processed should be true
My batch is given below:-
public class BatchResellerPartnerToResellerCustomer implements Database.Batchable<sObject>{
    //Run method to check the Batch on one record
    public static void run( Set<Id> OppIds ) {
         List<Opportunity> OppRecords =  [SELECT Name, AccountId, 
                                         Account.Name, Account.OwnerId,
                                         Account.RecordTypeId, Account.RecordType.Name  
                                         FROM Opportunity 
                                         WHERE AccountId != null 
                                         AND Account.RecordType.Name = 'Time Rack'
                                         AND Account.Customer_Type__c = 'Reseller'
                                         AND Id IN:  OppIds ];
        
        executeHelper( OppRecords );                  
    }
    public Database.querylocator start(Database.BatchableContext BC){
        String query = 'SELECT Name, Account.Name, Account.OwnerId, AccountId, '+
            'Account.RecordTypeId, Account.RecordType.Name '+
            'FROM Opportunity '+
            'WHERE AccountId != null '+
            'AND Account.RecordType.Name = \'Time Rack\''+
            'AND Account.Customer_Type__c = \'Reseller\'';
        return Database.getQueryLocator(query);            
    }
    public void execute(Database.BatchableContext BC, List<Opportunity> opportunities ){
         executeHelper( opportunities );
    }
    //Helper method to create  respective Accounts of opportunities
    public static void executeHelper( List<Opportunity> opportunities ) {
        List<Account> accList = new List<Account>();
        List<Opportunity> opptyListToBeUpdated = new List<Opportunity>();
        //Create Accounts with Opportunity's EndUser Name and ParentId with Opp's accountId
       /* Map<String,Opportunity> mapOppNameToOpportunity = new Map<String,Opportunity>();
        for( Opportunity opp : opportunities ){
            mapOppNameToOpportunity.put(opp.Name, opp);
         }*/
         for(Opportunity Oppty :opportunities  ) {
             String oppName = '';
             //Condition to get the end user name from opp name and give it to the new Account
            if(Oppty.Name.startsWith(Oppty.Account.Name)){
                oppName = Oppty.Name.removeStart(Oppty.Account.Name);
                oppName = oppName.trim();
                 if(oppName.startsWith(':') ){
                    oppName = oppName.substringAfter(':');
                    oppName = oppName.trim();
                }
                else if( oppName.startsWith('-') ){
                    oppName = oppName.substringAfter('-');
                    oppName = oppName.trim();
                }
                else{
                    oppName = Oppty.Name;
                }
                if (Oppty.Name.containsNone(':')||oppName.containsNone('-')){
                   Oppty.Not_Processed__c = True;
                }
            }
            //Condition to check opportunity has account with record type
            if(oppName != '' 
               && Oppty.AccountId != Null
               && Oppty.Account.RecordTypeId != Null){
                   //create new Account for each opportunity with customerType -'End user'
                 Account acc = new Account(Parentid = Oppty.AccountId,
                                            Customer_Type__c = 'End User',
                                            RecordTypeId = Oppty.Account.RecordTypeId,
                                            OwnerId = Oppty.Account.OwnerId,
                                            Name = oppName );
                accList.add(acc);
            }
            
         }
        if(accList.size() >0) {
            insert accList;
        }
       /* Map<String,Account> mapAccountNameToAccount = new Map<String,Account>();
        for(Account acc :accList){
            mapAccountNameToAccount.put(acc.Name, acc);
        }*/
         // Update Oppty List with newAccountId
        for(Account acc : accList) {
            for(Opportunity oppty : opportunities ) {
                /*if(mapAccountNameToAccount.containsKey(acc.Name)){
                    oppty.AccountId = mapAccountNameToAccount.get(acc.Name).id;
                }*/
               if(oppty.AccountId == acc.ParentId) {
                    oppty.AccountId = acc.Id;
                    opptyListToBeUpdated.add(oppty);
                 }
            }
        }
        if(opptyListToBeUpdated.size()>0) {
            update opptyListToBeUpdated;
        }
    }
    public void finish(Database.BatchableContext BC){
    }
}
how to prevent duplicate accounts.
Any suggestions?
Best Answer chosen by sumit d
Santosh Reddy MaddhuriSantosh Reddy Maddhuri

Hi Sumit.

Change this line of code to following and it should work.

FROM :

   if(accList.size() >0) {
            insert accList;
        }

TO :

   if(accList.size() >0) {
            upsert accList;
     }


If this helps.mark this as best answer so other can benefit too!

Regards,

Santosh.