• salesforce_hoonigan
  • NEWBIE
  • 70 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 21
    Questions
  • 25
    Replies
Hi Experts,

I am somewhat apex newb, I need a second eye with my test class and codes. As I am only getting 72% code coverage and I am not sure if I wrote it correctly.

Goal: Redirect the page layout to VF (Displaying 4 fields only) IF the Lead Owner is not equal to Current Running User

VF 1: 
<apex:page standardController="Lead" extensions="LeadViewRestriction" 
    action="{!nullValue(redir.url, urlFor($Action.Lead.View, Lead.id, null, true))}">
</apex:page>

VF 2:
<apex:page standardController="Lead"> 
    <apex:sectionheader title="{!$ObjectType.Lead.label} Detail" subtitle="{!Lead.Company}"/>
        <apex:pageblock mode="maindetail" title="{!$ObjectType.Lead.label} Detail">
            <apex:pageBlockSection title="Lead Information" columns="1"> 
                <apex:outputField title="Lead Owner" value="{!Lead.OwnerId}"/> 
                <apex:outputField title="Company Name" value="{!Lead.Company}"/> 
                <apex:outputField title="Status" value="{!Lead.Lead_Status_NEW__c}"/> <BR></BR>
            </apex:pageBlockSection> 
        </apex:pageBlock> 
</apex:page>

Controller:
public class LeadViewRestriction {

    public LeadViewRestriction (ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public PageReference getRedir() {
        Lead l = [Select id, OwnerId From Lead Where Id =: ApexPages.currentPage().getParameters().get('id')];
        User u = [Select Id, Profile.Name from User where Id =: UserInfo.getUserId()];
        
        PageReference newPage;

        if (u.Profile.Name == 'VL - Sales Agent' && l.OwnerId != u.Id) {
            newPage = Page.LeadBasicView;
        } else {
            return null;
        }


        newPage.getParameters().put('id', l.Id);
        return newPage.setRedirect(true);

    }

    private final ApexPages.StandardController controller;

}

TEST CLASS:
 
@isTest
private class TestLeadViewRestriction {
@isTest static void testsLeadView(){
    Lead l = new Lead();
    l.Company= 'Test';
    l.LastName = 'Doe';
    l.Lead_Status_NEW__c = 'New';
    insert l;

    Test.setCurrentPageReference(new PageReference('Page.LeadBasicView'));
    System.currentPageReference().getParameters().put('Id', l.Id);

    ApexPages.StandardController sc = new ApexPages.standardController(l);
    LeadViewRestriction controller = new LeadViewRestriction (sc);       

    controller.getRedir();


}
}

Any assistance with arranging the framework is greatly appreciated.

Thank you.

 
Hi,

I am currently building an Task Counter and I was able to achieve this by counting the Activity History and Open Activity using the current code. My new requirement is to count the number of Activities whether an Activity is a Call or an Email, I will base the criteria by Task Type (ex. Emai, Call - Connected, Call - Not Connected). So basically, I will have a total of 4 fields. 
1. Completed Activities - Call, 
2. Open Activities - Call, 
3. Completed Activities - Email, 
4. Open Activities - Email

I hope you could assist me on modifying my code please.

Class: 
public class ActivityUtils {
     
    //config
     
    String fieldToUpdate = 'Activity_Logs__c'; //this field must be added to each object we're updating
    String fieldOpenToUpdate = 'Open_Activities__c'; //this field must be added to each object we're updating
     
    //state
    set<id> leadIds;
     
    public ActivityUtils(sObject[] records) {
        leadIds = new set<id>();
        captureWhatAndWhoIds(records);
    }
     
    public void updateLeadActivityCount() {
        if(leadIds.size() == 0) return;
        updateActivityCount('Lead','WhoId', getStringFromIdSet(leadIds));
                updateActivityHistory('Lead','WhoId', getStringFromIdSet(leadIds));
 
    }

    private void updateActivityCount(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM OpenActivities) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            OpenActivity[] oActivities = so.getSObjects('OpenActivities');
            Integer openActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldOpenToUpdate, openActivityCount);
            sobjects.add(obj);
            system.debug('openActivityCount: ' + openActivityCount);
        }
        update sobjects;
    }
      
    private void updateActivityHistory(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM ActivityHistories) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';       
System.debug(strQuery);
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            ActivityHistory[] oActivities = so.getSObjects('ActivityHistories');
            Integer closedActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldToUpdate, closedActivityCount);
            sobjects.add(obj);
            system.debug('ActivityHistoryCount: ' + closedActivityCount);
        }
        update sobjects;
    }
     
    private void captureWhatAndWhoIds(sObject[] objects) {
        for(sObject o : objects) {
            Id whoId = (Id)o.get('WhoId');
            if(whoId != null) {
                String objectName = getObjectNameFromId(whoId);
                if(objectName == 'lead') leadIds.add(whoId);
            }
        }
    }
     
    private String getObjectNameFromId(Id objId) {
        String preFix = String.valueOf(objId).left(3).toLowercase();
        if(prefix == '00q') return 'lead';
        return '';
    }
     
    private String getStringFromIdSet(set<id> idSet) {
        string idString = '';
        for(Id i : idSet) idString+= '\'' + i + '\',';
        return idString == '' ? idString : idString.left(idString.length()-1); //If idString contains some ids we want to ensure we strip out the last comma
    }
     
    //The main part of the method below was taken from //Taken from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm
    //However we've modified this to accept an object id
    private sObject createObject(String typeName, Id objId) {
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
        if (targetType == null) {
            // throw an exception
        }
         
        // Instantiate an sObject with the type passed in as an argument
        //  at run time.
        return targetType.newSObject(objId);
    }
     
}

Trigger:
trigger ActivityCounterTrigger on Task (after insert, after update, after delete, after undelete) {
     
    sObject[] triggerRecords;
    if(!trigger.isDelete) triggerRecords = trigger.new;
    else triggerRecords = trigger.old;
     
    //Update Open Activity Count
    ActivityUtils au = new ActivityUtils(triggerRecords);
    au.updateLeadActivityCount();

}




 
Hi Experts,

I'm still total newb in apex. I hope you could assist me on this.

Criteria:
Uncheck Textbox1__c (Lead - Parent) if Lookup__c (Document__r - child) was changed to blank.

I would appreciate any help coming from the experts.

Thank you.
Hi Experts,

I need your assistance updating TIN_Uploaded__c (Checkbox) on Lead if the Attachment (Notes and Attachment) Name starts with "TIN". This box should be unchecked if the Attachment is deleted. Also I have another box that will do the same behavior SLA_Uploaded__c but I don't know how to nest them in the code. I've tried building the code but I'm getting error "Variable does not exist: attach.Name" in Line 14.
 
trigger TestAttachmentCheck on Attachment (after insert, after update, after delete, after undelete) {
    List <Lead> LeadList = new List<Lead>();
    Set <Id> LeadIds = new Set <Id>();
    
    for(Attachment attach : trigger.New){
         //Check if added attachment is related to Lead or not
         if(attach.ParentId.getSobjectType() == Lead.SobjectType){
              LeadIds.add(attach.ParentId);
         }
    }
    LeadList = [select id, CIN_Uploaded__c from Lead where id in : LeadIds];
   	for(Lead lead : LeadList){    
    	if((string.valueOf(attach.Name)).startswith('.xls')){
            lead.CIN_Uploaded__c  = true;
        }
        else{
            lead.CIN_Uploaded__c = false;
        }
    }
        update LeadList;
}
I would appreciate any help.

Thanks.
 
Hi Experts,

I hope you could assist me creating a code to auto populate a Lookup field based on a Text field. This text field will always contain the ID of a Lead. The custom Object and Lead doesn't have a direct relationship. The text field will be populated manually

Details:
Object: Cloud File (Custom)
Text Field: Text__c (Residing in Cloud File)
Lookup Field: Lead__c

Any assistance is greatly appreciated.
Hi All,

I am a newb on Apex and I am not sure if I built my test class correctly. I am only getting 63% code coverage. Any help is gladly appreciated.

Trigger:  (I am getting red marks on 14,15,18 and 21)
trigger TotalBusinessHrs on Predecessor_Task__c (before insert, before update) {

    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    Decimal Diff1;

for (Predecessor_Task__c pt1: trigger.new)
{
   
    DateTime d1 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    DateTime d2 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    
    if((pt1.Actual_Start_Date_Time__c!=null) && (pt1.Actual_Completion_Date_Time__c!=null)) {
        
    d1=pt1.Actual_Start_Date_Time__c;
    d2=pt1.Actual_Completion_Date_Time__c;
    
    
    Diff1=BusinessHours.diff(stdBusinessHours.id,d1,d2);
    
    
    pt1.Actual_of_Hours_of_Completion__c=(Diff1/(1*60*60*1000));
    
    }
  }
}
Test Class:
 
@isTest
private class testTotalBusinessHrs{

    public static testMethod void BusinessHrs() {
    
    Decimal Diff1;
    
    // Setup test data
    Project_and_Task__c Proj = new Project_and_Task__c (
    Name = 'Test1');
    insert Proj;
    
    Predecessor_Task__c pt = new Predecessor_Task__c (
    Project_and_Task__c=Proj.Id,
    Activity_Name__c='Test123', 
    Actual_Start_Date_Time__c=System.now(), 
    Alloted_Hours__c=2.00);
    insert pt;
    
    System.debug('Inserting PT with valid Actual_of_Hours_of_Completion__c Num value');
    
    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    
    Proj = [select Id, Name from Project_and_Task__c where Name= 'Test1'];
   
    pt = [select Id, Activity_Name__c, Actual_Start_Date_Time__c, Alloted_Hours__c, Actual_of_Hours_of_Completion__c from Predecessor_Task__c 
            where Activity_Name__c= 'Test123'];
                        
    System.assert (pt.Alloted_Hours__c != NULL); 
    System.assert (pt.Actual_Start_Date_Time__c!= NULL); 
    System.assertequals(pt.Actual_of_Hours_of_Completion__c, pt.Actual_of_Hours_of_Completion__c);
    }
}


 
Hi All,

Please bear with me since I am a complete newbie with Apex. I currently have a code and I can't get it to work. Need help.

Requirement: Add Number field and Date/Field respecting the Business Hours/Day and decimals in number field

Detail: 
Business Hours: 7:00 AM - 5:00 PM   ---- Total of 10 hrs.
Actual_Time__c (Date/Time) 
Hours__c (Number field with two decimal places)
Target_Date_Time__c (Date/Time) 

Ex. 1
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 7:00 AM + 2.00 = 01/10/2015 9:00 AM

Ex. 2 (respecting Business Hours/Day)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:00 PM + 2.00 = 02/10/2015 8:00 AM

Ex. 2 (respecting Business Hours/Day with decimal)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:30 PM + 2.00 = 02/10/2015 8:30 AM

CODE:
trigger TargetCompletionTime on Predecessor_Task__c (before insert, before update) {
    
    for(Predecessor_Task__c pt : trigger.new)
        {
            BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
            DateTime d1 = pt.Actual_Time__c ;
            
            if((pt.Actual_Time__c !=null) && (pt.Hours__c !=null)) {
            
            pt.Target_Date_Time__c  = d1.addHours(integer.valueOf(pt.Hours__c));
   }
}
}





 
Hi All,

I'm newb on Test Classes. Any assistance is gladly appreciated. I am having errors when trying to Run the Test Class I've created, it is showing 100% code coverage but has an error on Test Class. It is showing "System.DmlException: Update failed. First exception on row 0 with id a1gJ0000001GZsCIAW; first error: TRANSFER_REQUIRES_READ, The new owner must have read permission: []

Apex Class:
 
trigger SyncOwner on Project_and_Task__c (before insert, before update) {

  for(Project_and_Task__c pt:Trigger.new)                    // For each record
    if(Trigger.isInsert)                                     // If we're inserting
      pt.OwnerId = pt.Assigned_To_Owner__c;                  // Assign ownership from Assigned__c
    else                                                     // Otherwise (an update)
      if(pt.OwnerId != Trigger.oldMap.get(pt.id).OwnerId)       // If ownership has changed
        pt.Assigned_To_Owner__c = pt.OwnerId;                // Place the new owner is assigned
      else                                                   // Otherwise (owner not changed, is an update)
        if(pt.Assigned_To_Owner__c != Trigger.oldMap.get(pt.id).Assigned_To_Owner__c)     // If the Assigned__c field changed
          pt.OwnerId = pt.Assigned_To_Owner__c;             // Assigned ownership from Assigned__c
}
Test Class
@isTest
private class TestSyncOwner {
  static testMethod void test() {
    List<User> testUsers = [select id from user where isactive = true limit 2];
        
    List<Project_and_Task__c> pt= new List<Project_and_Task__c>();
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[0].Id));
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[1].Id));
    insert pt;

    Map<Id, Project_and_Task__c> refMap = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);

    system.assertEquals(refMap.get(pt[0].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c;
    system.assertEquals(refMap.get(pt[1].Id).OwnerId,testUsers[1].Id); // OwnerId should equal Assigned_To_Owner__c;
    pt[0].OwnerId = testUsers[1].Id;
    pt[1].Assigned_To_Owner__c = testUsers[0].Id;
    update pt;
    
    Map<Id, Project_and_Task__c> refMap2 = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);
    
    system.assertEquals(refMap2.get(pt[0].Id).Assigned_To_Owner__c,testUsers[1].Id); // Assigned_To_Owner__c should equal OwnerId now
    system.assertEquals(refMap2.get(pt[1].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c now
  }  
}
I will appreciate any help