• DheerajKumar@Salesforce
  • NEWBIE
  • 64 Points
  • Member since 2019

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 17
    Replies
Hi,
I have created a schedule class to RUN every 1 hour but It is not checking the newly created record and inserting. Kindly review my code and let me know what changes need to be done.

My Requirement:
I want to write a schedule class on custom object to check newly created custom object record is created in Opportunity Line Items.
I have a field common to find custom obj and opportunity which is used to find opplineitems.
 
global class orderItems Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
        
        List<OrderItems__c> lstOpty = [SELECT Id, Name, OrderId__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c,
                                              Qty_Backordered__c, Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                                          FROM OrderItems__c WHERE CreatedDate > TODAY];
        
        Set<Decimal> orderIds = new Set<Decimal>();

        for(OrderItems__c oi : lstOpty) {
            orderIds.add(oi.OrderId__c);
            System.debug('--- Getting Custom Obj Id: ---' + orderIds);
        }
        
        Map<Decimal, List<Opportunity>> oppMap = new Map<Decimal, List<Opportunity>>();
        
        if(!orderIds.isEmpty()){
            System.debug('--- Checking Order ID: ---');
            for(Opportunity opp : [SELECT Id, Name, OrderItem__c FROM Opportunity WHERE OrderItem__c IN: orderIds]) {
                if(!oppMap.containsKey(opp.OrderItem__c)) {
                    oppMap.put(opp.OrderItem__c, new List<Opportunity> {opp});
                    System.debug('--- Opportunity Map ---' + oppMap);
                }            
            } 
        }
  
        List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];
    
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
        
        for(OrderItems__c oi : lstOpty){
            System.debug('--- Order Items: ---' + oi);
            if(oppMap.containsKey(oi.OrderId__c)){
                for(Opportunity opp : oppMap.get(oi.OrderId__c)) {
                    System.debug('--- Inside Opportunity ---');
                    OpportunityLineItem oli = new OpportunityLineItem();                
                    oli.OpportunityId = opp.Id;
                    oli.PricebookEntryId = priceBookList[0].Id; 
                    oli.Quantity = oi.Qty_Ordered__c;
                    oli.TotalPrice = oi.Price__c;                
                    oli.item_id__c = oi.Name;
                    oli.Name__c = oi.Name__c;
                    oli.product_id__c = oi.product_id__c;
                    oli.Due_Date__c = oi.Due_Date__c;
                    oli.product_type__c = oi.product_type__c;
                    oli.qty_backordered__c = oi.qty_backordered__c;
                    oli.qty_canceled__c = oi.qty_canceled__c;
                    oli.qty_invoiced__c = oi.qty_invoiced__c;
                    oli.qty_ordered__c = oi.qty_ordered__c;
                    oli.qty_refunded__c = oi.qty_refunded__c;
                    oli.qty_returned__c = oi.qty_returned__c;
                    oli.qty_shipped__c = oi.qty_shipped__c;
                    oli.Sku__c = oi.Sku__c; 
                    oliList.add(oli);
                    System.debug('--- Inside Opportunity' + opp);
                    System.debug('--- Oli List: ---');
                }
            }
        }
        try {
            if(oliList.size()>0) {
                insert oliList;
                System.debug('--- Inserted Opp Line Items: ---');
                System.debug('--- Inserted Opp Line Items: ---' + olilist.size()); 
            }
        }
        catch(Exception e){
            System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
        }
    }
}

Need assistance to complete this code.

Thanks.

 Hi All,
        i have a batch in which i am creating a parent child account hierarchy.  at this time when i am executing the batch for opportunity with exact same name its creating two Accounts with the same name but i want that opportunity with same name should go to the account which is first created .it should not created duplicate records of Account for opportunity with same name.
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> scope){
         executeHelper( scope );
    }
    //Helper method to create  respective Accounts of opportunities
    public static void executeHelper( List<Opportunity> scope ) {
        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
        for(Opportunity Oppty : scope) {
             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;
                }
            }
            //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;
        }
         // Update Oppty List with newAccountId
        for(Account acc : accList) {
            for(Opportunity oppty : scope) {
               if(oppty.AccountId == acc.ParentId) {
                    oppty.AccountId = acc.Id;
                    opptyListToBeUpdated.add(oppty);
                 }
            }
        }
        if(opptyListToBeUpdated.size()>0) {
            update opptyListToBeUpdated;
        }
    }
    public void finish(Database.BatchableContext BC){
    }
}
         right now its creating duplicate account records with opportunity which has same name.i want to prevent duplicate account creation and simply want that the opportunity should attach with the account which is created already first with the batch.
How can i modify this batch to prevent duplicate accounts creations?
Any suggestions?
trigger ProductDetail on Design_Selected_Junction__c (After insert) {
    if(Trigger.isInsert){
        Set<Id> designTemplateSet = new Set<Id>();
        Set<Id> oppSet = new Set<Id>();
        for(Design_Selected_Junction__c desiSele : trigger.new){
            designTemplateSet.add(desiSele.Design_Template__c);  
            oppSet.add(desiSele.Opportunity__c);  
            //System.debug('ID --->' +designTemplateSet);
            //System.debug('ID --->' +oppSet);
        }
        // sObject types to describe
        Map<String, Schema.SObjectField> fields = Schema.getGlobalDescribe().get('Design_Item__c').getDescribe().fields.getMap();
        List<String> listFields = new List<String>();
        for(Schema.SObjectField fieldRef : fields.values()){
            Schema.DescribeFieldResult parentfieldResult = fieldRef.getDescribe();
            if(parentfieldResult.isUpdateable()) {
                listFields.add(parentfieldResult.getName());
            }
        }
        String query = '';
        query =  'Select Id,' + String.join(listFields,',') + ',';
        System.debug('Query --->' +query);  
        String dynamicQuery = '';
        List<String> fieldNames;
        Set<String> childString = new Set<String>{
        'Handles__r','Prints__r','Linings__r','Closures__r','Inserts__r','Patches__r','Insulation_Padding__r','Tags__r'
        };
        String childStringQuery = '';
        String finalQuery = '';
        for(ChildRelationship childRel : Schema.getGlobalDescribe().get('Design_Item__c').getDescribe().getChildRelationships()){                       
            if(childString.contains(childRel.getRelationshipName())){
                DescribeSObjectResult describeResult = childRel.getChildSObject().getDescribe();
                System.debug('Child Relationship Name --->' +childRel.getRelationshipName());
                Map <String, Schema.SObjectField> fieldsMap = describeResult.fields.getMap();
                fieldNames = new List<String>();
                for(Schema.SObjectField sObjectField : fieldsMap.values()){
                    Schema.DescribeFieldResult fieldResult = sObjectField.getDescribe();                    if(fieldResult.isUpdateable()){
                        fieldNames.add(fieldResult.getName());
                    }
                    dynamicQuery +='(select Id,' + String.join(fieldNames, ',')
                     + ' from ' + String.valueOf(childRel.getRelationshipName())+'),'; 
                }
            }
        }
        dynamicQuery = dynamicQuery.removeEnd(',');
        childStringQuery += dynamicQuery;
        System.debug('Check dynamic ---> '+childStringQuery);
        String condition = 'Where Parent_template__c In:designTemplateSet'; 
        query += query + childStringQuery+' FROM Design_Item__c '+ condition;    
        //String finalQuery = query +','+ dynamicQuery +' from  Design_Item__c '+ condition;
        System.debug('Check final ---> '+query);
        List<Design_Item__c> designRecords = Database.query(finalQuery);
        System.debug('Check List ---> '+designRecords);
    }
}
Hi everyone!
              Need help, to capture failed records in batch class.Below  is my code, i am able to capture sucessfull records but unable to capture failed records.
global class updateOppSendPIQReport implements Database.Batchable<SObject>{
    
    global Set<Id> failureIdsSet;

    
    global Database.QueryLocator start(Database.BatchableContext BC)
    { 
        //Fetch records after opportunity stage is set to PIQ Complete
        return Database.getQueryLocator('SELECT ID, StageName__c, SendPIQReport__c, Opportunity__r.id FROM PIQ_Response__c where StageName__c = \'PIQ Complete\' or StageName__c = \'50-PIQ Complete\' ');
              
    }
    
    global void execute(Database.BatchableContext BC, List<PIQ_Response__c> scope){
        
        failureIdsSet = new Set<Id>();

        List<PIQ_Response__c> updatepiq = new List<PIQ_Response__c>();
        for(PIQ_Response__c piq :  scope){
            if(piq.SendPIQReport__c == False && piq.StageName__c == 'PIQ Complete'){
                
                String [] emailList = new List<String>();
                Set<Id> opId = new Set<Id>();
                
                opId.add(piq.Opportunity__r.id);
                //Fetch Opportunity Record
                Opportunity op = [select id, name, AccountID from Opportunity where Id=:opId];
                
                // DML statement
                Database.SaveResult[] srList = Database.update(scope, false);
                
                // Iterate through each returned result
                for (Database.SaveResult sr : srList) {
                    if (sr.isSuccess()) {
                        // Operation was successful, so get the ID of the record that was processed
                        System.debug('Successfull records****************************: ' + sr.getId());
                    }
                    else {
                        // Operation failed, so get all errors                
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                    
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('failed records**************************: ' + err.getFields());
                        }
                    }
                }
                //Fetch Email id of Account Manager
                List<AccountTeamMember> teamList = [ SELECT ID, TeamMemberRole,
                                                    User.Email
                                                    FROM AccountTeamMember
                                                    WHERE AccountID = :op.AccountID 
                                                    AND TeamMemberRole = 'Account Manager'];
                for(AccountTeamMember a1: teamList){
                    emailList.add(a1.User.Email);
                }
                //Fetch Email id of Sales Coordinator
                List<AccountTeamMember> teamList2 = [ SELECT ID, TeamMemberRole,
                                                     User.Email
                                                     FROM AccountTeamMember
                                                     WHERE AccountID = :op.AccountID 
                                                     AND TeamMemberRole = 'Sales Coordinator'];
                for(AccountTeamMember a2: teamList2){
                    emailList.add(a2.User.Email);
                }  
                 List<CustomUsers__c> cu1 = [select UserEmails__c from CustomUsers__c];
                
               
                for(CustomUsers__c u1:cu1){
                     list<string> templist = u1.UserEmails__c.split(',');
                    emailList.addAll(templist);
                     //emailList.add(u1.UserEmails__c); 
                                         system.debug('EmailList'+emailList);
                                     }
                
                String [] emailList2 = new List<String>();
                for (Integer i = 0; i<emailList.size(); i++) {
                    emailList2.add(emailList[i]);
                     system.debug('EmailList**'+emailList2);
                } 
                PIQCOntroller.sendPDf(piq.Id, emailList2);
                piq.SendPIQReport__c = True;
                updatepiq.add(piq);
            } 
        }
        update updatepiq;
        system.debug('updatepiq*******************'+updatepiq);
    }
    
    global void finish(Database.BatchableContext BC)
    {
    }
}
  • May 28, 2019
  • Like
  • 0
This is my class
public with sharing class costsheet {

    

 
 public List<Order> ordwrap {get;set;}
 public List<Opportunity> oppwrap {get;set;}
  public List<SOWrapper> wrapper {get;set;}
 
 
 
 public costsheet()
 {
  ordwrap=[Select id from Order limit 5];
  oppwrap=[select Id,name,Account.Name from opportunity limit 5];
  wrapper = new List<SOWrapper>() ;
        for(Integer i=0 ; i < 5 ; i++)
            wrapper.add(new SOWrapper(ordwrap[i] , oppwrap[i])) ;
  
 }

  
        public class SOWrapper{
        public Order order{get;set;}
        public Opportunity opportunity{get;set;}
        //public Cost_Price__c costprice{get;set;}
        
        public SOWrapper(Order ord, Opportunity opp){
            order= ord;
            opportunity = opp;
            //costprice = cp;
        }
    }
    
}
Actually this is the controller class and the help I need is how to write the test class for the below code.

Orginal Apex controller code:
--------------------------------------
private String addressValidation(Contact con, boolean showApexErroMsg){
            boolean errorExist = false;
            String addrs_Error_Message = '';
            String errorMsgFullString = '';
   
            if (!AddressService.isValidationResultValid(con.Other_Address_Validation_Status__c, con.Other_Address_Validation_Timestamp__c))
            {
                addrs_Error_Message += ' Ship To Address, ';
                errorExist = true;
            }

        if (!AddressService.isValidationResultValid(con.Mailing_Address_Validation_Status__c, con.Mailing_Address_Validation_Timestamp__c))
        {
            addrs_Error_Message += ' Sold To Address, ';
            errorExist = true;
        }

        if (!AddressService.isValidationResultValid(con.Other_Address2_Validation_Status__c, con.Other_Address2_Validation_Timestamp__c))
        {
            addrs_Error_Message += ' Bill To Address ';
            errorExist = true;
        }

        if(String.isNotBlank(addrs_Error_Message)){
            errorMsgFullString = con.name+' has an non-validated '+addrs_Error_Message+'. Please go to the Contact page for '+con.name +' and validate the address.';
            if(showApexErroMsg)
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,errorMsgFullString));

        }
        system.debug('----addressValidation Result ----'+errorExist);
        return errorMsgFullString;
    }

Need test class for the above code.
Please do the needful. Thanks in advance
Hi All,

I created a new field in user with the data type number am trying to update the field called Total License from user license object .

to acomplish this i wrote a bacth class.But its not updating this field.

Kindly let mw know ,Where i do changes
Batch Class:
global class totallicensecount implements Database.Batchable<SObject>{
Map<ID,String> License= New Map<ID,String>();
Map<string,Integer> License1= New Map<string,Integer>();
list<user> query1=new list<user>();
set<string> setuserlicense=new set<string>();
list<user> listofuser=new list<user>();

        
        global Database.QueryLocator start(Database.BatchableContext bc){
                string query='select Id,name,TotalLicenses from Userlicense'; 
                query+='limit 1';       
                return Database.getQueryLocator(query);
        
        }
        

        global void execute(Database.BatchableContext bc,list<Userlicense> scope){
        
                for(Userlicense us:scope){
                License1.put(Us.Name,us.TotalLicenses);
                setuserlicense.add(us.name);
                }
            
                    query1=[select Id,name,profile.Userlicense.name,Profile.UserLicense.TotalLicenses,Type__C,Total_license_count__c from user where profile.Userlicense.name in :setuserlicense];
                    for(user us1:query1){
                    us1.Total_license_count__c=License1.get(us1.profile.Userlicense.name);
                    listofuser.add(us1);                   
                   
                }
            
        IF(listofuser.size()>0){
        
        update listofuser;
        
        }
}



global void finish (Database.BatchableContext bc){
}



}


 
Hi Every one,

I wrote program using Extension concpt

Apex program
public class Quick_quote {
    public Account acc      {set;get;}
    public contact con      {set;get;}
    public opportunity opt  {set;get;}
    public string quotename {set;get;}
    
    public Quick_quote(Apexpages.StandardController controller){
        List<string> fields = new List<string>{'name','phone','industry','rating'};
            controller.addfields(fields);
           con=new contact();
           opt= new opportunity();
        acc=(account)controller.getRecord();
    } 
    }
Visual force program

<apex:page standardController="Account" extensions="Quick_quote">
   <apex:sectionHeader title="Quick quote" subtitle="new quick quote"/> 
    <apex:form>
        <apex:pageblock>
    <apex:pageBlockSection title="Account" collapsible="false">
        <apex:inputField value="{!Account.name}"/>
        <apex:inputField value="{!account.phone}"/>
        <apex:inputField value="{!account.industry}"/>
        <apex:inputField value="{!account.rating}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection title="Contact" collapsible="false">
            <apex:inputText value="{!con.firstname}"/>
            <apex:inputText value="{!con.lastname}"/>
            <apex:inputText value="{!con.phone}"/>
            <apex:inputText value="{!con.Email}"/>
        </apex:pageBlockSection>
            <apex:pageBlockSection title="opportunty" collapsible="false">
                <apex:inputText value="{!quotename}"/>
                </apex:pageBlockSection>
            </apex:pageblock>
    </apex:form>
    </apex:page>

When i am executig this program i am getting error 
Error-
Maximum stack depth reached: 1001 

Thank you
surender reddy

 
Hi,
I have created a schedule class to RUN every 1 hour but It is not checking the newly created record and inserting. Kindly review my code and let me know what changes need to be done.

My Requirement:
I want to write a schedule class on custom object to check newly created custom object record is created in Opportunity Line Items.
I have a field common to find custom obj and opportunity which is used to find opplineitems.
 
global class orderItems Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
        
        List<OrderItems__c> lstOpty = [SELECT Id, Name, OrderId__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c,
                                              Qty_Backordered__c, Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                                          FROM OrderItems__c WHERE CreatedDate > TODAY];
        
        Set<Decimal> orderIds = new Set<Decimal>();

        for(OrderItems__c oi : lstOpty) {
            orderIds.add(oi.OrderId__c);
            System.debug('--- Getting Custom Obj Id: ---' + orderIds);
        }
        
        Map<Decimal, List<Opportunity>> oppMap = new Map<Decimal, List<Opportunity>>();
        
        if(!orderIds.isEmpty()){
            System.debug('--- Checking Order ID: ---');
            for(Opportunity opp : [SELECT Id, Name, OrderItem__c FROM Opportunity WHERE OrderItem__c IN: orderIds]) {
                if(!oppMap.containsKey(opp.OrderItem__c)) {
                    oppMap.put(opp.OrderItem__c, new List<Opportunity> {opp});
                    System.debug('--- Opportunity Map ---' + oppMap);
                }            
            } 
        }
  
        List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];
    
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
        
        for(OrderItems__c oi : lstOpty){
            System.debug('--- Order Items: ---' + oi);
            if(oppMap.containsKey(oi.OrderId__c)){
                for(Opportunity opp : oppMap.get(oi.OrderId__c)) {
                    System.debug('--- Inside Opportunity ---');
                    OpportunityLineItem oli = new OpportunityLineItem();                
                    oli.OpportunityId = opp.Id;
                    oli.PricebookEntryId = priceBookList[0].Id; 
                    oli.Quantity = oi.Qty_Ordered__c;
                    oli.TotalPrice = oi.Price__c;                
                    oli.item_id__c = oi.Name;
                    oli.Name__c = oi.Name__c;
                    oli.product_id__c = oi.product_id__c;
                    oli.Due_Date__c = oi.Due_Date__c;
                    oli.product_type__c = oi.product_type__c;
                    oli.qty_backordered__c = oi.qty_backordered__c;
                    oli.qty_canceled__c = oi.qty_canceled__c;
                    oli.qty_invoiced__c = oi.qty_invoiced__c;
                    oli.qty_ordered__c = oi.qty_ordered__c;
                    oli.qty_refunded__c = oi.qty_refunded__c;
                    oli.qty_returned__c = oi.qty_returned__c;
                    oli.qty_shipped__c = oi.qty_shipped__c;
                    oli.Sku__c = oi.Sku__c; 
                    oliList.add(oli);
                    System.debug('--- Inside Opportunity' + opp);
                    System.debug('--- Oli List: ---');
                }
            }
        }
        try {
            if(oliList.size()>0) {
                insert oliList;
                System.debug('--- Inserted Opp Line Items: ---');
                System.debug('--- Inserted Opp Line Items: ---' + olilist.size()); 
            }
        }
        catch(Exception e){
            System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
        }
    }
}

Need assistance to complete this code.

Thanks.
Hi, 

  In below code I am hard coding RW: and FW: in the loop to compare and replace please suggest me how to  user keywords. 
public static void processUpdate(list<Case> cseLst) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst = new list<Case>();
       
        for (Case c : cseLst) {       
            if(c.subject <> null){     
                // Remove FW and RW from case subject to get exact string
                if(c.subject.Contains('FW:')){
                    FWSubject = c.subject.replaceAll('FW:','');
                    System.debug('FQ Trim String :' + FWSubject);
                    CaseSubject = FWSubject;     
                } else if(c.subject.Contains('RW:')){ 
                    RWSubject = c.subject.replaceAll('RW:','');
                    System.debug('RW Trim String :' + RWSubject);   
                    CaseSubject = RWSubject;

   }
}

Thanks
GMASJ
  • February 28, 2019
  • Like
  • 2

 Hi All,
        i have a batch in which i am creating a parent child account hierarchy.  at this time when i am executing the batch for opportunity with exact same name its creating two Accounts with the same name but i want that opportunity with same name should go to the account which is first created .it should not created duplicate records of Account for opportunity with same name.
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> scope){
         executeHelper( scope );
    }
    //Helper method to create  respective Accounts of opportunities
    public static void executeHelper( List<Opportunity> scope ) {
        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
        for(Opportunity Oppty : scope) {
             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;
                }
            }
            //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;
        }
         // Update Oppty List with newAccountId
        for(Account acc : accList) {
            for(Opportunity oppty : scope) {
               if(oppty.AccountId == acc.ParentId) {
                    oppty.AccountId = acc.Id;
                    opptyListToBeUpdated.add(oppty);
                 }
            }
        }
        if(opptyListToBeUpdated.size()>0) {
            update opptyListToBeUpdated;
        }
    }
    public void finish(Database.BatchableContext BC){
    }
}
         right now its creating duplicate account records with opportunity which has same name.i want to prevent duplicate account creation and simply want that the opportunity should attach with the account which is created already first with the batch.
How can i modify this batch to prevent duplicate accounts creations?
Any suggestions?

The problem i have is with vf page. What i need to do is get two values which are Date type from user and after he click button based on those values gatther data from SF and show them in correct way.

 

I am at very begining of the road and I am blocked with that my variables do not get updated after button click. So i can't really sue them in my controller and what is more i can rerender content of page with other variable cause it is not changing for page as well...

 

Code page:
 

<apex:page controller="pageGenerator" docType="html-5.0">
    <apex:form>
         <script>
            function sideSetter()
            {
                dataSetter();
                document.getElementById('{!$Component.mainform.mainBlock.mainDisplay}').innerHTML = '{!mainTableArea}';
            }
        </script>
        <apex:actionFunction name="dataSetter" action="{!dataSetter}" rerender="mainform.mainDisplay"/>
    </apex:form>
    <apex:form id="mainform">
        <apex:pageBlock title="dynamictest" id="mainBlock">
            <apex:pageBlockSection title="Filters" id="mainWork" columns="1">
                <apex:input title="Start date" label="Start date" type='date' value="{!startDate}"/>
                <apex:input title="End date" label="End date" type="date" value="{!endDate}"/>
                <apex:commandButton value="Generate" onclick="sideSetter();" rerender="mainform.mainDisplay"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="renderedpart" id="mainDisplay">
                Nothing yet....
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>    
</apex:page>

Code controller:

public class pageGenerator
{
    
    public String mainTableArea {get;set;}
    public Date startDate {get;set;}
    public Date endDate {get;set;}
    
    
    private void setMainTableArea( String theString )
    {
        this.mainTableArea = theString;
    }
    
    public pageGenerator()
    {
        mainTableArea = 'nicnicnic';
        startDate = Date.today();
        endDate = Date.today().addMonths(1);
    }
    
    public PageReference dataSetter()
    {
        setMainTableArea( String.valueOf(startDate) + ' ' + String.valueOf(endDate) );
        system.debug( MainTableArea + ' ' + String.valueOf(startDate) + ' ' + String.valueOf(endDate) );
        
        return null;
    }
    
}

Can any one tell me what i do wrong. After clicking the button some times endDate get updated but never startDate and the mainTableArea varaible never get's updated when the dataSetter methods is being triggered.

 

 

By the way if you think this is bad way of doing what i want and i should use other technology let me know ;) we use only classic.