• SFDC Noob 1
  • NEWBIE
  • 0 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 6
    Replies
I have this batch apex sharing recalculation i created with the help of the apex workbook, How can i create a test class for this? The example in the workbook doesn't help me with my situation.
global class PartnerSharingClass implements Database.Batchable<sObject> {
    
    static String emailAddress = 'test@test.com';
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Partner__c FROM Opportunity]);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>((List<Opportunity>)scope);
        List<opportunityshare> newOppShare = new List<OpportunityShare>();
        
        List<OpportunityShare> oldOppShare = [SELECT Id FROM OpportunityShare WHERE Id IN :oppMap.keyset()];
        
        for(Opportunity o : oppMap.Values()){
            OpportunityShare pShare = new OpportunityShare();
            
            pshare.UserOrGroupId = o.Partner__c;
            pshare.OpportunityAccessLevel = 'Read';
            pshare.OpportunityId = o.Id;
            
            newOppShare.add(pshare);
        }
        try {
            Delete oldOppShare;
            Database.SaveResult[] lsr = Database.insert(newOppShare,false);
            
            for(Database.Saveresult sr : lsr) {
                if(!sr.isSuccess()){
                    Database.Error err = sr.getErrors()[0];
                    
                 if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
                      && err.getMessage().contains('AccessLevel'))){
                          
                          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                          String[] toAddresses = new String[] {emailAddress};
                          mail.setToAddresses(toAddresses);
                          mail.setSubject('Apex Sharing Recalculation Exception');
                          mail.setPlainTextBOdy(
                          'The Apex Sharing recalculation threw the following exception: ' + err.getMessage());
                          Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                      } 
                }
            }
        }catch(DMLException e) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {emailAddress};
            mail.setToAddresses(toAddresses);
            mail.setSubject('APex Sharing Recalculation Exception');
            mail.setPlainTextBody( 'The APex sharing recalculation threw the following exception: ' + e.getMessage());
            
        }
                
    }           global void finish(Database.BatchableContext BC) {
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    String[] toAddresses = new String[] {emailAddress};
                    mail.setToAddresses(toAddresses);
                    mail.setSubject('Apex Sharing Recalculation Completed.');
                    mail.setPlainTextBody('The Apex sharing recalculation finished processing');
                    
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail} );
          }
}

thanks
I have a partner__c user lookup field on Opportunity. I created a trigger that gives View access to the opportunities to the User that is in the Partner__c field, but this only works on the new opportunities being created.

I have thousands of Opps that don't have a populated Partner__c yet and some that alread did. How can i give those users View access once i get the Parter__c populated and to the older opportunities?
I am trying to get this trigger working to update lead owner based on another field but i am getting this error: 
Initial term of field expression must be a concrete SObject: List<User>

I have bolded the line getting the error in the code.
trigger leadassign on Lead (after insert) {
	
	for (Lead newLead : Trigger.new) {
	
	List <User> csm = [SELECT Id FROM User WHERE name =: newLead.Channel_Sales_manager__c Limit 1];

    IF(newlead.channel_sales_manager__C == 'Unknown'){
            Group csmqueue = [SELECT Id FROM Group
                              WHERE name = 'Channel Sales Managers'
                              AND type = 'Queue' LIMIT 1];
        		newlead.ownerID = csmqueue.Id;
        }
        IF(newlead.channel_sales_manager__c == csm.name){
            newlead.ownerId = csm.Id;
        }
      update newLead;
    }
    
}

 
I have a previous trigger in my org that i am trying to add another part to.
Here is my trigger to change lead owner based on a lookupfield and i am trying to add it to the longer trigger pasted after. But i am getting maxium trigger depth exceeded error when i try to add it. 
 
IF (trigger.isAfter){
         list<Lead> LeadList = [select id,channel_sales_manager__c,ownerid from Lead where id in: trigger.newmap.keyset()]; 
          for(Lead ld : LeadList){
              if(ld.channel_sales_manager__c != null){
                  ld.ownerid = ld.channel_sales_manager__c;
              }
              IF(ld.channel_sales_manager__c == null){
                  Group csmqueue = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1];
                  ld.ownerid = csmqueue.Id;
              }
          }
          update LeadList ;
}

trigger PartnerPortalTrigger on Lead (before insert, after insert, after update) {

    if(Trigger.isInsert && Trigger.isBefore) {
        
      Id queueId = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1].id;
      Id currentProfileId = userinfo.getProfileId();
      List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
    
      for(Integer i = 0; i < Trigger.New.size(); i++){
          if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
              Trigger.new[i].OwnerId = queueId;
              Trigger.new[i].Status = 'Channel Submitted';
          }
      }
    }
    if(Trigger.isInsert && Trigger.isAfter) {
        
        List<LeadShare> sharesToInsert = new List<LeadShare>();

        Id currentProfileId = userinfo.getProfileId();
        List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
        
        List<Lead> toUpdate = new List<Lead>();
        toUpdate = [SELECT Id, CreatedById, Partner__c FROM Lead WHERE Id IN :Trigger.New];
        List<Lead> newLeads = new List<Lead>();
        
        for(Integer i = 0; i < Trigger.New.size(); i++){
            
            if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
                          
                LeadShare leadShare = new LeadShare();
                leadShare.LeadId = Trigger.new[i].Id;
                leadShare.UserOrGroupId = Trigger.new[i].CreatedById;
                leadShare.LeadAccessLevel = 'Read';
                sharesToInsert.add(leadShare);

            }
        }
        
        insert sharesToInsert;
        
        for(Lead l : toUpdate) {
            if(l.Partner__c == null) {
                l.Partner__c = l.CreatedById;
                newLeads.add(l);
            }    
        }
        update newLeads;
        
    }
    
    
    if(Trigger.isUpdate) {
        //When a lead status is updated to "Channel Registered," this will
        //update the status on the corresponding Campaign Member record
         
        List<Lead> updatedLeads = new List<Lead>();
        Map<Id, CampaignMember> members = new Map<Id, CampaignMember>([SELECT Id, LeadId, CampaignId FROM CampaignMember WHERE LeadId IN :Trigger.New]);        
        List<CampaignMember> membersToUpdate = new List<CampaignMember>();
        Map<Id, CampaignMember> leadIds = new Map<Id, CampaignMember>();

        List<String> companies = new List<String>();
        List<String> domains = new List<String>();
        String nameToMatch1;
        String nameToMatch2;
        List<Lead> sameCompanyLeads = new List<Lead>();
        List<Lead> newLeadsToUpdate = new List<Lead>();
            
        for(Lead thisLead : Trigger.New) {
            Lead oldLead = Trigger.oldMap.get(thisLead.Id);
            
            Boolean oldLeadIsRegistered = oldLead.Status.equals('Channel Registered');
            Boolean newLeadIsRegistered = thisLead.Status.equals('Channel Registered');
            
            if(!oldLeadIsRegistered && newLeadIsRegistered) {
                updatedLeads.add(thisLead);
                
                nameToMatch1 = thisLead.Company;
                
                if (nameToMatch1 != null) {
                    nameToMatch1 = nameToMatch1.remove(',');
                    nameToMatch1 = nameToMatch1.remove('.');
                    nameToMatch1 = nameToMatch1.remove('Inc');
                    nameToMatch1 = nameToMatch1.remove('LLC');
                    nameToMatch1 = nameToMatch1.remove('Credit Union');
                    nameToMatch1 = nameToMatch1.remove('Company');
                    nameToMatch1 = nameToMatch1.remove('/');
                    nameToMatch1 = nameToMatch1.remove('&');
                    nameToMatch1 = nameToMatch1.remove('\'');
                    nameToMatch1 = nameToMatch1.replaceAll('[\\s]', '%');
                    
                    if (!nameToMatch1.endsWith('%')) {
                        nameToMatch1 += '%';
                    }
                    
                }
    
                nameToMatch2 = nameToMatch1.remove('Corp');
                nameToMatch2 = nameToMatch2.remove('FCU');
                nameToMatch2 = nameToMatch2.remove('CU');
                
                companies.add(nameToMatch1);
                companies.add(nameToMatch2);
                
                if(thisLead.Email_Domain__c != 'yahoo.com' && thisLead.Email_Domain__c != 'gmail.com' && 
                    thisLead.Email_Domain__c != 'hotmail.com' && thisLead.Email_Domain__c != 'zoho.com' &&
                    thisLead.Email_Domain__c != 'outlook.com') {
                    domains.add(thisLead.Email_Domain__c);
                }
            }
        }
        
        //If we find another lead in the Channel Submitted status with the same email domain OR the same company, 
        //we update the status as Channel Registered
        sameCompanyLeads = [SELECT Id, Email_Domain__c, Company, Status FROM Lead WHERE Owner.Name = 'Channel Sales Managers' AND Status IN('Channel Submitted') AND Id NOT IN :updatedLeads AND (Email_Domain__c IN :domains OR Company IN :companies)];
    
         //AND (Email_Domain__c IN :domains OR Company IN :companies)
        for(Lead thisLead : sameCompanyLeads) {
            thisLead.Status = 'Channel Registered (Affiliated)';
            newLeadsToUpdate.add(thisLead);    
        }
        
        for(CampaignMember thisCM : members.values()) {
            CampaignMember thisMember = members.get(thisCM.Id);
            leadIds.put(thisCM.LeadId, thisMember);
        }
        
        for(Lead thisLead : updatedLeads) {
           if(leadIds.containsKey(thisLead.Id)) {
               CampaignMember thisMember = leadIds.get(thisLead.Id);
               thisMember.Status = 'Channel Registered';
               membersToUpdate.add(thisMember);
           }
        } 
        
        try {
            Database.update( membersToUpdate );
            Database.update( newLeadsToUpdate );
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }
}

 
I need to set the Partner Users on previous Opportunities registered by that partner user. Only designation i have to connect the two is the LeadSource field on Opportunities that lists "Partner-XXXX", xxxx is the company name. There are over 10000 records that don't have a partner listed. What would be the best of doing this?
We have a lead registration form in our partner portal and currently all leads get assigned to the queue via a workflow rule. 
We recently added a Sales manager picklist on our lead registration form and want the future leads to be assigned to the Sales manager that was selected by the partner in the picklist field. IF noone is selected then we assign the lead to the queue again.
I am having a hard time getting this going even though it doesnt sound very complicated. Any tips would be greatly appreciated.
I have this batch apex sharing recalculation i created with the help of the apex workbook, How can i create a test class for this? The example in the workbook doesn't help me with my situation.
global class PartnerSharingClass implements Database.Batchable<sObject> {
    
    static String emailAddress = 'test@test.com';
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Partner__c FROM Opportunity]);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>((List<Opportunity>)scope);
        List<opportunityshare> newOppShare = new List<OpportunityShare>();
        
        List<OpportunityShare> oldOppShare = [SELECT Id FROM OpportunityShare WHERE Id IN :oppMap.keyset()];
        
        for(Opportunity o : oppMap.Values()){
            OpportunityShare pShare = new OpportunityShare();
            
            pshare.UserOrGroupId = o.Partner__c;
            pshare.OpportunityAccessLevel = 'Read';
            pshare.OpportunityId = o.Id;
            
            newOppShare.add(pshare);
        }
        try {
            Delete oldOppShare;
            Database.SaveResult[] lsr = Database.insert(newOppShare,false);
            
            for(Database.Saveresult sr : lsr) {
                if(!sr.isSuccess()){
                    Database.Error err = sr.getErrors()[0];
                    
                 if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
                      && err.getMessage().contains('AccessLevel'))){
                          
                          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                          String[] toAddresses = new String[] {emailAddress};
                          mail.setToAddresses(toAddresses);
                          mail.setSubject('Apex Sharing Recalculation Exception');
                          mail.setPlainTextBOdy(
                          'The Apex Sharing recalculation threw the following exception: ' + err.getMessage());
                          Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                      } 
                }
            }
        }catch(DMLException e) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {emailAddress};
            mail.setToAddresses(toAddresses);
            mail.setSubject('APex Sharing Recalculation Exception');
            mail.setPlainTextBody( 'The APex sharing recalculation threw the following exception: ' + e.getMessage());
            
        }
                
    }           global void finish(Database.BatchableContext BC) {
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    String[] toAddresses = new String[] {emailAddress};
                    mail.setToAddresses(toAddresses);
                    mail.setSubject('Apex Sharing Recalculation Completed.');
                    mail.setPlainTextBody('The Apex sharing recalculation finished processing');
                    
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail} );
          }
}

thanks
I am trying to get this trigger working to update lead owner based on another field but i am getting this error: 
Initial term of field expression must be a concrete SObject: List<User>

I have bolded the line getting the error in the code.
trigger leadassign on Lead (after insert) {
	
	for (Lead newLead : Trigger.new) {
	
	List <User> csm = [SELECT Id FROM User WHERE name =: newLead.Channel_Sales_manager__c Limit 1];

    IF(newlead.channel_sales_manager__C == 'Unknown'){
            Group csmqueue = [SELECT Id FROM Group
                              WHERE name = 'Channel Sales Managers'
                              AND type = 'Queue' LIMIT 1];
        		newlead.ownerID = csmqueue.Id;
        }
        IF(newlead.channel_sales_manager__c == csm.name){
            newlead.ownerId = csm.Id;
        }
      update newLead;
    }
    
}

 
I have a previous trigger in my org that i am trying to add another part to.
Here is my trigger to change lead owner based on a lookupfield and i am trying to add it to the longer trigger pasted after. But i am getting maxium trigger depth exceeded error when i try to add it. 
 
IF (trigger.isAfter){
         list<Lead> LeadList = [select id,channel_sales_manager__c,ownerid from Lead where id in: trigger.newmap.keyset()]; 
          for(Lead ld : LeadList){
              if(ld.channel_sales_manager__c != null){
                  ld.ownerid = ld.channel_sales_manager__c;
              }
              IF(ld.channel_sales_manager__c == null){
                  Group csmqueue = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1];
                  ld.ownerid = csmqueue.Id;
              }
          }
          update LeadList ;
}

trigger PartnerPortalTrigger on Lead (before insert, after insert, after update) {

    if(Trigger.isInsert && Trigger.isBefore) {
        
      Id queueId = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1].id;
      Id currentProfileId = userinfo.getProfileId();
      List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
    
      for(Integer i = 0; i < Trigger.New.size(); i++){
          if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
              Trigger.new[i].OwnerId = queueId;
              Trigger.new[i].Status = 'Channel Submitted';
          }
      }
    }
    if(Trigger.isInsert && Trigger.isAfter) {
        
        List<LeadShare> sharesToInsert = new List<LeadShare>();

        Id currentProfileId = userinfo.getProfileId();
        List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
        
        List<Lead> toUpdate = new List<Lead>();
        toUpdate = [SELECT Id, CreatedById, Partner__c FROM Lead WHERE Id IN :Trigger.New];
        List<Lead> newLeads = new List<Lead>();
        
        for(Integer i = 0; i < Trigger.New.size(); i++){
            
            if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
                          
                LeadShare leadShare = new LeadShare();
                leadShare.LeadId = Trigger.new[i].Id;
                leadShare.UserOrGroupId = Trigger.new[i].CreatedById;
                leadShare.LeadAccessLevel = 'Read';
                sharesToInsert.add(leadShare);

            }
        }
        
        insert sharesToInsert;
        
        for(Lead l : toUpdate) {
            if(l.Partner__c == null) {
                l.Partner__c = l.CreatedById;
                newLeads.add(l);
            }    
        }
        update newLeads;
        
    }
    
    
    if(Trigger.isUpdate) {
        //When a lead status is updated to "Channel Registered," this will
        //update the status on the corresponding Campaign Member record
         
        List<Lead> updatedLeads = new List<Lead>();
        Map<Id, CampaignMember> members = new Map<Id, CampaignMember>([SELECT Id, LeadId, CampaignId FROM CampaignMember WHERE LeadId IN :Trigger.New]);        
        List<CampaignMember> membersToUpdate = new List<CampaignMember>();
        Map<Id, CampaignMember> leadIds = new Map<Id, CampaignMember>();

        List<String> companies = new List<String>();
        List<String> domains = new List<String>();
        String nameToMatch1;
        String nameToMatch2;
        List<Lead> sameCompanyLeads = new List<Lead>();
        List<Lead> newLeadsToUpdate = new List<Lead>();
            
        for(Lead thisLead : Trigger.New) {
            Lead oldLead = Trigger.oldMap.get(thisLead.Id);
            
            Boolean oldLeadIsRegistered = oldLead.Status.equals('Channel Registered');
            Boolean newLeadIsRegistered = thisLead.Status.equals('Channel Registered');
            
            if(!oldLeadIsRegistered && newLeadIsRegistered) {
                updatedLeads.add(thisLead);
                
                nameToMatch1 = thisLead.Company;
                
                if (nameToMatch1 != null) {
                    nameToMatch1 = nameToMatch1.remove(',');
                    nameToMatch1 = nameToMatch1.remove('.');
                    nameToMatch1 = nameToMatch1.remove('Inc');
                    nameToMatch1 = nameToMatch1.remove('LLC');
                    nameToMatch1 = nameToMatch1.remove('Credit Union');
                    nameToMatch1 = nameToMatch1.remove('Company');
                    nameToMatch1 = nameToMatch1.remove('/');
                    nameToMatch1 = nameToMatch1.remove('&');
                    nameToMatch1 = nameToMatch1.remove('\'');
                    nameToMatch1 = nameToMatch1.replaceAll('[\\s]', '%');
                    
                    if (!nameToMatch1.endsWith('%')) {
                        nameToMatch1 += '%';
                    }
                    
                }
    
                nameToMatch2 = nameToMatch1.remove('Corp');
                nameToMatch2 = nameToMatch2.remove('FCU');
                nameToMatch2 = nameToMatch2.remove('CU');
                
                companies.add(nameToMatch1);
                companies.add(nameToMatch2);
                
                if(thisLead.Email_Domain__c != 'yahoo.com' && thisLead.Email_Domain__c != 'gmail.com' && 
                    thisLead.Email_Domain__c != 'hotmail.com' && thisLead.Email_Domain__c != 'zoho.com' &&
                    thisLead.Email_Domain__c != 'outlook.com') {
                    domains.add(thisLead.Email_Domain__c);
                }
            }
        }
        
        //If we find another lead in the Channel Submitted status with the same email domain OR the same company, 
        //we update the status as Channel Registered
        sameCompanyLeads = [SELECT Id, Email_Domain__c, Company, Status FROM Lead WHERE Owner.Name = 'Channel Sales Managers' AND Status IN('Channel Submitted') AND Id NOT IN :updatedLeads AND (Email_Domain__c IN :domains OR Company IN :companies)];
    
         //AND (Email_Domain__c IN :domains OR Company IN :companies)
        for(Lead thisLead : sameCompanyLeads) {
            thisLead.Status = 'Channel Registered (Affiliated)';
            newLeadsToUpdate.add(thisLead);    
        }
        
        for(CampaignMember thisCM : members.values()) {
            CampaignMember thisMember = members.get(thisCM.Id);
            leadIds.put(thisCM.LeadId, thisMember);
        }
        
        for(Lead thisLead : updatedLeads) {
           if(leadIds.containsKey(thisLead.Id)) {
               CampaignMember thisMember = leadIds.get(thisLead.Id);
               thisMember.Status = 'Channel Registered';
               membersToUpdate.add(thisMember);
           }
        } 
        
        try {
            Database.update( membersToUpdate );
            Database.update( newLeadsToUpdate );
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }
}

 
I need to set the Partner Users on previous Opportunities registered by that partner user. Only designation i have to connect the two is the LeadSource field on Opportunities that lists "Partner-XXXX", xxxx is the company name. There are over 10000 records that don't have a partner listed. What would be the best of doing this?
We have a lead registration form in our partner portal and currently all leads get assigned to the queue via a workflow rule. 
We recently added a Sales manager picklist on our lead registration form and want the future leads to be assigned to the Sales manager that was selected by the partner in the picklist field. IF noone is selected then we assign the lead to the queue again.
I am having a hard time getting this going even though it doesnt sound very complicated. Any tips would be greatly appreciated.