• Padmini S 26
  • NEWBIE
  • 45 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 42
    Replies
Hi All,

I have 4 objects Forecast__c, ForeCast_Details__C, Opportunity and Opportunity_Forecast__c.  Opportunity object contains multiple Opportunity_Forecast__c. Forecast__c has looup to Opportunity Object. Now i have to write batch apex class with upsert the ForeCast_Details__C  object records with value of Opportunity_Forecast__c.Could anyone please help on this.

Thanks in Advance.
Hi,
Below is the apex class and test class. i need to increase code coverage. Please help me to increase code coverage.
@RestResource(urlMapping='/Branch/*')
global class BranchMaster {

    @HttpPost
    global static void CreateBranch() {
     Map<String,String> mapResponse = new Map<String,String>();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
     try{
        List<Branch__c> createBranchList = new List<Branch__c>();
        List<Branch__c> updateBranchList = new List<Branch__c>();
         BranchData bdata = new BranchData();
         bdata = (BranchData)JSON.deserialize(req.requestBody.toString(),BranchData.class);
               
         List<Branch__c> beList = [select Id, Active__c, Branch_Address__c, Branch_Code__c, Catchment_Cities__c, Channel__c, City_ID__c, Name, Region_ID__c from Branch__c where Branch_Code__c =: bdata.Branch_Code];
     
         if(beList.size()>0)
        {
           Branch__c branchList = beList[0];
           if(bdata.Name!='')
                branchList.Name = bdata.Name;
            branchList.Active__c = Boolean.valueOf(bdata.Active);
            branchList.Branch_Address__c = bdata.Branch_Address;
            branchList.Channel__c = bdata.Channel;
            if(bdata.Catchment_Cities!='')
                branchList.Catchment_Cities__c = bdata.Catchment_Cities;
            if(bdata.City_ID!='')
            {           
                City__c c = new City__c();
                c.CityID__c = bdata.City_ID;
                branchList.City__r = c;
            }
            if(bdata.Region_ID!='')
            {            
                Region__c r = new Region__c();
                r.Region_ID__c = bdata.Region_ID;
                branchList.Region__r = r;
            }
            if(bdata.Zone_ID!='')
            {            
                 Zone__c z = new Zone__c();
                z.Zone_ID__c = bdata.Zone_ID;
                branchList.Zone__r = z;
            }
              if(bdata.Branch_Head!='')
            {            
                 Branch_Employee__c bh = new Branch_Employee__c();
                bh.Payrole_ID__c = bdata.Branch_Head;
                branchList.Branch_Head__r = bh;
            }
            if(bdata.CSO_Channel_Head!='')
            {            
                 Branch_Employee__c ch = new Branch_Employee__c();
                ch.Payrole_ID__c = bdata.CSO_Channel_Head;
                branchList.CSO_Channel_Head__r = ch;
            }
             if(bdata.Zonal_Head!='')
            {            
                Branch_Employee__c zh = new Branch_Employee__c();
                zh.Payrole_ID__c = bdata.Zonal_Head;
                branchList.Zonal_Head__r = zh;
            }
            if(bdata.RM_Channel_Head!='')
            {            
                Branch_Employee__c rmch = new Branch_Employee__c();
                rmch.Payrole_ID__c = bdata.RM_Channel_Head;
                branchList.RM_Channel_Head__r = rmch;
            }
            updateBranchList.add(branchList);
            if(updateBranchList.size()>0)
            {
                update updateBranchList;
                 mapResponse.put('success', '1');
                mapResponse.put('error', '0');
                mapResponse.put('Branch_Code', bdata.Branch_Code);
                mapResponse.put('errorCode', '');
                mapResponse.put('successCode', 'Branch updated successfully');
                res.responseBody = Blob.valueOf(JSON.serialize(mapResponse));                    
            }                        
        }
        else
        {                                 
            Branch__c branch = new Branch__c();
             branch.Name = bdata.Name;
            branch.Branch_Code__c = bdata.Branch_Code;
            branch.Active__c = Boolean.valueOf(bdata.Active);
            branch.Branch_Address__c = bdata.Branch_Address;
            branch.Channel__c = bdata.Channel;
            branch.Catchment_Cities__c = bdata.Catchment_Cities;
            if(bdata.City_ID!='')
            {
                City__c c = new City__c();
                c.CityID__c = bdata.City_ID;
                branch.City__r = c;
            }
             if(bdata.Region_ID!='')
            {          
                Region__c r = new Region__c();
                r.Region_ID__c = bdata.Region_ID;
                branch.Region__r = r;
            }
             if(bdata.Zone_ID!='')
            {            
                Zone__c z = new Zone__c();
                z.Zone_ID__c = bdata.Zone_ID;
                branch.Zone__r = z;
            }
             if(bdata.Branch_Head!='')
            {
              Branch_Employee__c bh = new Branch_Employee__c();
                bh.Payrole_ID__c = bdata.Branch_Head;
                branch.Branch_Head__r = bh;
            }
            if(bdata.CSO_Channel_Head!='')
            {
                Branch_Employee__c ch = new Branch_Employee__c();
                ch.Payrole_ID__c = bdata.CSO_Channel_Head;
                branch.CSO_Channel_Head__r = ch;
            }
             if(bdata.Zonal_Head!='')
            {            
                Branch_Employee__c zh = new Branch_Employee__c();
                zh.Payrole_ID__c = bdata.Zonal_Head;
                branch.Zonal_Head__r = zh;
            }
            if(bdata.RM_Channel_Head!='')
            {            
                Branch_Employee__c rmch = new Branch_Employee__c();
                rmch.Payrole_ID__c = bdata.RM_Channel_Head;
                branch.RM_Channel_Head__r = rmch;
            }
             createBranchList.add(branch);
            if(createBranchList.size()>0)
            {
                insert createBranchList;
                mapResponse.put('success', '1');
                mapResponse.put('error', '0');
                mapResponse.put('Brach_Code', bdata.Branch_Code);
                mapResponse.put('errorCode', '');
                mapResponse.put('successCode', 'Branch inserted successfully');
                res.responseBody = Blob.valueOf(JSON.serialize(mapResponse));
            }
         }
      } 
      catch(Exception e)
      {
          mapResponse.put('success', '0');
          mapResponse.put('error', '1');
          mapResponse.put('Branch_Code', '');
          mapResponse.put('errorCode', e.getMessage());
          mapResponse.put('successCode', '');
          res.responseBody = Blob.valueOf(JSON.serialize(mapResponse));          
      } // catch block
    }
        
    global class BranchData {
        public String Name{get;set;}
        public String Branch_Code{get;set;}
        public String Active{get;set;}
        public String Branch_Address{get;set;}
        public String Channel{get;set;}
        public String Catchment_Cities{get;set;}
        public String City_ID{get;set;}
        public String Region_ID{get;set;}
        public String Zone_ID{get;set;}
        public String Branch_Head{get;set;}
        public String CSO_Channel_Head{get;set;}
        public String Zonal_Head{get;set;}
        public String RM_Channel_Head{get;set;}
    }
    
}
@isTest
public class TestBranchMaster 
{
    @isTest
  public static void testMethodBranchMaster()
    { 
      BranchMaster.BranchData bd = new BranchMaster.BranchData(); 
         bd.Name = 'branch';
         bd.Branch_Code='A112';
         bd.Active = 'true';
         bd.Branch_Address = '9 GROUND FLOOR RAJENDRA BHAWAN';
         bd.Channel = 'Retail'; 
         bd.Catchment_Cities= 'nasik';
         bd.City_ID = objCity.CityID__c;
         bd.Region_ID = objRegion.Region_ID__c;
         bd.Zone_ID = objZone.Zone_ID__c;
         bd.Branch_Head = '';
         bd.CSO_Channel_Head = '';
         bd.Zonal_Head = '';
         bd.RM_Channel_Head = '';
       objCity.CityID__c=  bd.City_ID;        
        update objCity;
         try
       {
         Test.StartTest();
         Test.setMock(HttpCalloutMock.class, new TestCalloutMock());
          List<Branch__c> beList = [select Id, Active__c, Branch_Address__c, Branch_Code__c, Catchment_Cities__c, Channel__c, City_ID__c, Name, Region_ID__c from Branch__c];
         Branch__c b3 = new Branch__c( Name='Delhi Branch_Retail',Branch_Mobile__c = '9811352726', Branch_Phone__c = '011-64640938,25734989,41538597',
Branch_Address__c = '9 GROUND FLOOR RAJENDRA BHAWAN', Active__c = true,                          
Channel__c='Retail', Branch_Code__c='A101',Catchment_Cities__c='nasik', Catchment_Pincode__c='110015,110016'
                                    );
       Branch__c b4 = new Branch__c( Name='Delhi Branch_Retail',Branch_Mobile__c = '9811352726',Branch_Phone__c = '011-64640938,25734989,41538597',
Branch_Address__c = '9 GROUND FLOOR RAJENDRA BHAWAN',Active__c = true,
 Channel__c='Retail', Branch_Code__c='A101', Catchment_Cities__c='nasik', Catchment_Pincode__c='110015,110016'
                                    );  
        
           list<Branch__c> bList = new list<Branch__c>();
                 bList.add(b3);
                 bList.add(b4);
                 insert bList;  
           BranchMaster bm = new BranchMaster();
           BranchMaster.CreateBranch();
           system.assertequals(bList.size(),2);      
            delete bList;
          BranchMaster.CreateBranch();
           system.assertequals(bList.size(),0);  
           Test.StopTest();
        }
        Catch( Exception e)
        {
        
        } }}
Thanks in Advance.

 
Hi,

I have written test class for below apex class. Code coverage is 25% only.
public class OpportunityTriggerHelper_AOPLine{

    // this function use for update aop line record called when opprtunity status closed .
    public void updateAOPLineOnOppClosed(){
        List<Opportunity> newOpportunities = (List<Opportunity>)trigger.new;
        Map<Id,Opportunity> oldMapOpportunities = (Map<Id,Opportunity>)trigger.oldMap;
        Map<Id,Opportunity> newMapOpportunities =(Map<Id,Opportunity>)trigger.newMap;
        
        List<Id> oppIds = new List<Id>();
 for(Opportunity opp : newOpportunities ){
            if(oldMapOpportunities.get(opp.Id).StageName != opp.StageName && opp.StageName == 'Closed' && opp.Month_sap__c != null && opp.Month__c != null && opp.Financial_Year__c!= null)
                oppIds.add(opp.Id);            
        }  
        if(oppIds.size() > 0){
            Set<Id> useridSet = new Set<Id>();
            Set<String> oppMonths = new Set<String>();
            Set<String> oppYears = new Set<String>();
            List<Opportunity> oppList = [SELECT Id,Account.Category__c,MTD_Volume__c,MTD_Focussed_Volume__c,MTD_GP__c,Month__c,Year__c,Financial_Year__c,OwnerId,Owner.ManagerId,Owner.Manager.ManagerId,(SELECT Id, UserId,User.ManagerId,User.Manager.ManagerId,TeamMemberRole 
 FROM OpportunityTeamMembers WHERE TeamMemberRole != null AND UserId != null)  FROM Opportunity WHERE Id IN:oppIds];
            for(Opportunity opp : oppList){
                oppMonths.add(opp.Month__c);
                oppYears.add(opp.Financial_Year__c);
                if(opp.OwnerId != null)
                    useridSet.add(opp.OwnerId);
                 if(opp.Owner.ManagerId != null)
                    useridSet.add(opp.Owner.ManagerId);
              for(OpportunityTeamMember oppTemMember : opp.OpportunityTeamMembers){
                    useridSet.add(oppTemMember.UserId);
                     if(oppTemMember.User.ManagerId != null)
                        useridSet.add(oppTemMember.User.ManagerId);
                     if(oppTemMember.User.Manager.ManagerId != null)
                        useridSet.add(oppTemMember.User.Manager.ManagerId);
                }
           }
           
           if(useridSet.size() > 0 && oppMonths.size() >0 && oppYears.size() >0){
                Map<Id,User> userMap = new Map<Id,User>([SELECT Id,Profile.Name FROM User WHERE Id IN: useridSet]);
              Map<String,Id> aopLnMap = new Map<String,Id>();
                for(AOP_Line__c aopLn : [SELECT Id,Month__c,MTD_Regional_Vol_in_kL__c, MTD_National_Vol_in_kL__c,MTD_Focus_Vol_in_kL__c, MTD_Regional_GP__c, MTD_National_GP__c,                                            MTD_New_Win_in_kL__c,Valvoline_Financial_Year__c,AOP_Plan_User__c FROM AOP_Line__c WHERE  AOP_Plan_User__c IN : useridSet AND Month__c IN : oppMonths AND Valvoline_Financial_Year__c IN : oppYears]){
                  String keyMap = aopLn.Month__c.toUpperCase() +'#'+aopLn.Valvoline_Financial_Year__c+'#'+aopLn.AOP_Plan_User__c;   
                    aopLnMap.put(keyMap,aopLn.Id);
               }
               
               if(aopLnMap.size() > 0){
                   List<Monthly_line_Logs__c> inserMonthLn = new List<Monthly_line_Logs__c>();
                   for(Opportunity opp : oppList){
opp.MTD_Volume__c = opp.MTD_Volume__c != null ?opp.MTD_Volume__c : 0;
opp.MTD_GP__c = opp.MTD_GP__c != null ? opp.MTD_GP__c : 0;
opp.MTD_Focussed_Volume__c = opp.MTD_Focussed_Volume__c != null ? opp.MTD_Focussed_Volume__c : 0;
String keyMap = opp.Month__c.toUpperCase() +'#'+opp.Financial_Year__c;
        if(opp.OwnerId != null){
                            if(aopLnMap.containsKey(keyMap+'#'+opp.OwnerId)){
                             Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
   mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+opp.OwnerId);
          mnthAopLn.MTD_Regional_Vol_in_kL__c = opp.MTD_Volume__c;
           mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;                         
                                mnthAopLn.MTD_Regional_GP__c = opp.MTD_GP__c;
                    if(opp.Account.Category__c== 'New')
            mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
              inserMonthLn.add(mnthAopLn);
                            }
                        }
                        //M1 : TBM's Manager
                        if(opp.Owner.ManagerId != null){
                            if(aopLnMap.containsKey(keyMap+'#'+opp.Owner.ManagerId)){
                                if(userMap.get(opp.Owner.ManagerId).profile.name.equalsIgnoreCase('ZM')){
   Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+opp.Owner.ManagerId);
  mnthAopLn.MTD_Regional_Vol_in_kL__c = opp.MTD_Volume__c;
 mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;                         
                                    mnthAopLn.MTD_Regional_GP__c = opp.MTD_GP__c;
                                    if(opp.Account.Category__c== 'New')
          mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                inserMonthLn.add(mnthAopLn); 
                                }else if(userMap.get(opp.Owner.ManagerId).profile.name.equalsIgnoreCase('NSH')){
Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
       mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+opp.Owner.ManagerId);
                                  mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
                    mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;                         
                                    mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
                                    if(opp.Account.Category__c== 'New')
                                   mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                    inserMonthLn.add(mnthAopLn); 
                                }                                  
                            }
                        }
                    
                        if(opp.Owner.Manager.ManagerId != null){
                        if(aopLnMap.containsKey(keyMap+'#'+opp.Owner.Manager.ManagerId)){                                                                if(userMap.get(opp.Owner.Manager.ManagerId).profile.name.equalsIgnoreCase('NSH')){
 Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+opp.Owner.Manager.ManagerId);
mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;                         
                                    mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
                                   if(opp.Account.Category__c== 'New')
 mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                  inserMonthLn.add(mnthAopLn); 
                                }                             
                            }
                        }
                        
 for(OpportunityTeamMember oppTemMember : opp.OpportunityTeamMembers){
                            if(oppTemMember.TeamMemberRole.EqualsIgnoreCase('RKAM')){       
                                if(aopLnMap.containsKey(keyMap+'#'+oppTemMember.UserId)){
Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+oppTemMember.UserId);
mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;
 if(opp.Account.Category__c== 'New')
mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
  inserMonthLn.add(mnthAopLn);                           
                                }
   if(oppTemMember.User.ManagerId != null && oppTemMember.User.ManagerId != opp.Owner.ManagerId){                                   if(aopLnMap.containsKey(keyMap+'#'+oppTemMember.User.ManagerId)){                                      if(userMap.get(oppTemMember.User.ManagerId).profile.name.equalsIgnoreCase('ZM')){
 Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+oppTemMember.User.ManagerId);
       mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
          mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
           mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;             
          if(opp.Account.Category__c== 'New')
          mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                            inserMonthLn.add(mnthAopLn);
                                        }   
                                    }                    
                                } 
                            }else if(oppTemMember.TeamMemberRole.EqualsIgnoreCase('NKAM')){
                                if(aopLnMap.containsKey(keyMap+'#'+oppTemMember.UserId)){                                     Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+oppTemMember.UserId);
 mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
  mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;
 mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
      if(opp.Account.Category__c== 'New')
 mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                    inserMonthLn.add(mnthAopLn);                             
                                } 
                            }else if(oppTemMember.TeamMemberRole.EqualsIgnoreCase('Segment Manager')){
                                if(aopLnMap.containsKey(keyMap+'#'+oppTemMember.UserId)){
 Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+oppTemMember.UserId);
mnthAopLn.MTD_National_Vol_in_kL__c = opp.MTD_Volume__c;
mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;
                                    mnthAopLn.MTD_National_GP__c = opp.MTD_GP__c;
                                    
                                    if(opp.Account.Category__c== 'New')
        mnthAopLn.MTD_New_Win_in_kL__c = opp.MTD_Volume__c;
                                    inserMonthLn.add(mnthAopLn);                              
                                } 
                            }else if(oppTemMember.TeamMemberRole.EqualsIgnoreCase('Product Manager')){
                                if(aopLnMap.containsKey(keyMap+'#'+oppTemMember.UserId)){
Monthly_line_Logs__c mnthAopLn = new Monthly_line_Logs__c(Monthly_Opportunity__c = opp.Id); 
  mnthAopLn.Monthly_line__c = aopLnMap.get(keyMap+'#'+oppTemMember.UserId);
  mnthAopLn.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;
                           inserMonthLn.add(mnthAopLn);                     
                                }  }  } }
 if(inserMonthLn.size() > 0)
                       insert inserMonthLn;
               }
             }} }}
Test Class:
==========
@isTest
public class OpportunityTriggerHelper_AOPLineTest1 {
     static testMethod void AOPTest1(){        
        List<Opportunity> oppLst= new List<Opportunity>();        
        profile p1 = [SELECT Id FROM Profile WHERE Name='NSH']; 
        User u= new User();
            u.FirstName ='Sagar';
            u.Username='Sagar3443@acme.com';
            u.LastName='Sagar';
            u.Email='Sagar343@abc.com';
            u.Alias='Sagar34';
            u.CommunityNickname='Sagar';
            u.TimeZoneSidKey='America/Los_Angeles';
            u.LocaleSidKey='en_US';
            u.EmailEncodingKey='UTF-8';
            u.ProfileId = p1.Id;
            u.LanguageLocaleKey='en_US';
           insert u;
         profile p3 = [SELECT Id FROM Profile WHERE Name='ZM']; 
        User uzm= new User();
            uzm.FirstName ='Sagar243';
            uzm.Username='Sagar23@acme.com';
            uzm.LastName='Saga3r';
            uzm.Email='Sagar34342@abc.com';
            uzm.Alias='Sagar234';
            uzm.CommunityNickname='Sagar23';
            uzm.TimeZoneSidKey='America/Los_Angeles';
            uzm.LocaleSidKey='en_US';
            uzm.EmailEncodingKey='UTF-8';
            uzm.ProfileId = p3.Id;
            uzm.LanguageLocaleKey='en_US';
            insert uzm;
        profile p2 = [SELECT Id FROM Profile WHERE Name='TBM']; 
        User ut= new User();
            ut.FirstName ='Sagar243';
            ut.Username='Sagar23434@acme.com';
            ut.LastName='Saga334r';
            ut.Email='Sagar34342@abc.com';
            ut.Alias='Sagar234';
            ut.CommunityNickname='Sagar2';
            ut.TimeZoneSidKey='America/Los_Angeles';
            ut.LocaleSidKey='en_US';
            ut.EmailEncodingKey='UTF-8';
            ut.ProfileId = p2.Id;
            ut.LanguageLocaleKey='en_US';
            ut.ManagerId=uzm.Id;
            insert ut;
List<Account> accLst= new List<Account>();
String recordTypeSAP  = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SAP Order').getRecordTypeId();
        Account acc= new Account();
         acc.Name='Testclass acc1';
        acc.Is_Parent__c='N';
        acc.Type='Factory Fill';
        acc.Indutry_Segment__c='On-Highway';
        acc.Market_Segment__c='PowerGen';
        acc.Quote_allowed__c='Yes';
        acc.BU_Name__c='OEM';
        acc.Category__c='New';
         acc.Account_Type__c='Factory Fill';
        accLst.add(acc);
         insert accLst;
         Opportunity opp = new Opportunity();
        opp.RecordTypeId = recordTypeSAP;
        opp.AccountId=acc.Id;
        opp.Name='Testclass Opp SAP';
        opp.StageName='Open';   
        opp.Month__c='OCT';
        opp.Year__c='2017';
        opp.Financial_Year__c='2017';
        opp.Month_sap__c='OCT';
        opp.Calendar_Year__c ='2017';
        opp.closeDate = System.today();
        opp.ownerId = ut.Id;
       // opp.Owner.Manager.ManagerId = ut.ManagerId;
        opp.MTD_Volume__c = 100;
        opp.MTD_GP__c = 50;
        opp.MTD_Focussed_Volume__c = 100;
         insert opp;
     
    List<OpportunityTeamMember> oppTMLst= new List<OpportunityTeamMember>();    
        OpportunityTeamMember ptm= new OpportunityTeamMember();
        ptm.TeamMemberRole = 'Zonal Manager';
        ptm.OpportunityId = opp.Id;
        ptm.OpportunityAccessLevel = 'Edit';
        ptm.UserId=uzm.Id;
        oppTMLst.add(ptm);
        
         OpportunityTeamMember ptm2= new OpportunityTeamMember();
        ptm2.TeamMemberRole = 'NSH';
        ptm2.OpportunityId = opp.Id;
        ptm2.OpportunityAccessLevel = 'Edit';
        ptm2.UserId=u.Id;
        oppTMLst.add(ptm2);
        
        OpportunityTeamMember ptm3= new OpportunityTeamMember();
        ptm3.TeamMemberRole = 'TBM';
        ptm3.OpportunityId = opp.Id;
        ptm3.OpportunityAccessLevel = 'Edit';
        ptm3.UserId=uzm.Id;
        oppTMLst.add(ptm3);
        insert oppTMLst;
       List<AOP__c> aopList = new List<AOP__c>();
        AOP__c aop = new AOP__c();
        aop.AOP_DSO__c = 52.00;
        aop.Valvoline_Financial_Year__c = '2017';
        aop.AOP_Regional_Vol_in_kL__c = 1.00;
        aop.AOP_National_Vol_in_kL__c = 2.00;
        aop.AOP_Focus_Vol_in_kL__c = 1.00;
        aop.AOP_Regional_GP__c = 1;
        aop.AOP_Forecast_Accuracy__c =10;
        aop.AOP_New_Win_in_kL__c = 3.00;
        aop.AOP_National_GP__c = 1.00;    
        aopList.add(aop);
         insert aopList;
         List<AOP_Line__c> AopLineList = new List<AOP_Line__c>();
        AOP_Line__c aopLine3 = new AOP_Line__c();
       aopLine3.AOP__c = aop.Id;
       aopLine3.AOP_Plan_User__c=uzm.Id;
       aopLine3.AOP_Regional_Vol_in_kL__c = aop.AOP_Regional_Vol_in_kL__c;
       aopLine3.AOP_New_Win_in_kL__c = aop.AOP_New_Win_in_kL__c;
       aopLine3.AOP_DSO__c = aop.AOP_DSO__c;
       aopLine3.AOP_Forecast_Accuracy__c = aop.AOP_Forecast_Accuracy__c;
       aopLine3.AOP_National_Vol_in_kL__c = aop.AOP_National_Vol_in_kL__c;
       aopLine3.AOP_Regional_GP__c = aop.AOP_Regional_GP__c;
       aopLine3.AOP_National_GP__c = aop.AOP_National_GP__c;
       aopLine3.AOP_Focus_Vol_in_kL__c = aop.AOP_Focus_Vol_in_kL__c;
       aopLine3.Month__c = 'Oct';
       AopLineList.add(aopLine3);
       List<Monthly_Line_Logs__c> molList = new List<Monthly_Line_Logs__c>();
       Monthly_line_Logs__c mon1 = new Monthly_line_Logs__c();
                mon1.Monthly_line__c= opp.OwnerId;
                mon1.Monthly_Opportunity__c= opp.Id;
                mon1.MTD_Regional_Vol_in_kL__c = opp.MTD_Volume__c;
                mon1.MTD_Focus_Vol_in_kL__c = opp.MTD_Focussed_Volume__c;
                mon1.MTD_Regional_GP__c = opp.MTD_GP__c;
                mon1.MTD_New_Win_in_kL__c = opp.MTD_Volume__c ; 
                molList.add(mon1); 
                test.startTest();
       try{
               
             insert AopLineList;    
              insert molList;   
                
          }
       catch(Exception E){}
     
           opp.StageName='Closed';
           update opp;       
       test.stopTest();
    }}
Can anyone help on this how to increase the code coverage and where i am missing.

Thanks in Advance.  
Hi,

Below is the apex trigger which i have written. But i got only 64% code coverage. I am not getting how to increase code coverage. Please help me how to increase code coverage.
trigger LeadTrigger on Lead (before insert,before update, after update) 
{
    Map<String, String> dispositionMap = new Map<String, String>();
    Map<String, DateTime> dispositionDateTimeMap = new Map<String, DateTime>();
    List<Id> leadIds = new List<Id>();
    if(Trigger.isInsert)
    {
        leadCategorizationClass.leadCategorization(Trigger.new,Trigger.oldMap);       //Lead Categorization
        LeadHelperClass.AddNewLead(Trigger.New);         //NEW LEAD
        leadAllocationClass.leadAllocation(Trigger.New); //GO TO CSO
        leadReAllocationClass.setRMLeadOpptyInfo(Trigger.New, Trigger.oldMap);        //When RM is Assigned
    }
    else if(Trigger.isUpdate && Trigger.isBefore)
    {
       leadCategorizationClass.leadCategorization(Trigger.new,Trigger.oldMap);       //Lead Categorization
        if(stopRecClass.stopRec==false){
            leadReAllocationClass.leadAllocationFromQueue(Trigger.New,Trigger.oldMap);//CSO allocation for Queue.
            leadReAllocationClass.setRMLeadOpptyInfo(Trigger.New, Trigger.oldMap);    //When RM is Assigned
            stopRecClass.stopRec=true;
        }
        
        for(lead ld: trigger.new)
        {
            if((ld.Dispositions__c!=trigger.oldMap.get(ld.id).Dispositions__c) 
                && (ld.Dispositions__c=='Appointment Fixed' || 
                    ld.Dispositions__c=='Follow Up' || 
                        ld.Dispositions__c=='Engaged' || ld.Dispositions__c=='Number was busy' || 
                        ld.Dispositions__c=='Ringing Not Responding' || ld.Dispositions__c=='Not available'))
            {
               if(dispositionMap.containsKey(ld.Dispositions__c))         
                   dispositionMap.put(ld.Dispositions__c,dispositionMAP.get(ld.Dispositions__c)+',91'+ld.Mobile_Number__c); 
                else
                   dispositionMap.put(ld.Dispositions__c,'91'+ld.Mobile_Number__c);         
                
                if(ld.Dispositions__c=='Appointment Fixed')
                {
                    dispositionDateTimeMap.put(ld.Dispositions__c, ld.Appointment_Creation_Date__c);
                }
                else if(ld.Dispositions__c=='Follow Up')
                {
                    dispositionDateTimeMap.put(ld.Dispositions__c, ld.Prefered_Date_Time__c);
                }
            }
           ld.Email_Internal__c = ld.Email;
}
        if(!dispositionMap.IsEmpty()){
            // call method helper class
            LeadHelperClass.sendingSMS(dispositionMap, dispositionDateTimeMap);
        }
    }
    else if(Trigger.isUpdate && Trigger.isAfter)
    {
        // for FarEye Integration //
        system.debug('After Update Trigger Fired');
        for(lead ld: Trigger.New)
        {
            if(((ld.Dispositions__c!=trigger.oldMap.get(ld.id).Dispositions__c) && (ld.Dispositions__c=='Appointment Fixed') && 
               (ld.RM__c!=null)) || (ld.Resend_To_FarEye__c==true)    
            )
            {
                system.debug('Class Calling');
                leadIds.add(ld.Id);
                //system.debug('Class End of Calling');
            }
        }
        system.debug('IDS: '+leadIds.size());
        if(leadIds.size()>0)
        {
            // call batch class here
            system.debug('<<<<<<<<<< Batch Called After Update');
            Database.executeBatch(new BatchClassFarEyeIntegrationLead(leadIds)) ;
        }}}

Below is the test class.
@isTest
public class TestLeadHelperClass {
 Public static testmethod void testLeadHelper()
 {
    
     Campaign cp = new Campaign(Name='test', IsActive=true, Interested_Product__c='LI', Channel__c='Retail');
     insert cp;
     
     Lead L1 = new Lead(FirstName='Harsh',LastName='Test',Email= 'sachin@gmail.com', Status='CSOAllocated',Company = 'Test Name', Remarks__c= 'good',Client_Type__c='NRI',Postal_Code__c='474001',Tax_Bracket__c='5%',Disposition_Category__c='General', Dispositions__c='Appointment Fixed', Interested_Product__c='Mutual Fund',Mobile_Number__c='9669259232', Appointment_Creation_Date__c = System.Today(), Campaigns__c= cp.id);
     insert L1;
     List<Lead> LT = new List<Lead>();
     LT.add(L1);
     Lead l = [SELECT Id, FirstName,LastName,Email,Status,Company ,Remarks__c,Client_Type__c,Postal_Code__c,Tax_Bracket__c,Disposition_Category__c,Dispositions__c,Interested_Product__c,Mobile_Number__c,Campaigns__c FROM Lead WHERE Id = :LT[0].Id];

     l.FirstName= 'Test Account 2';
     update l;
     Account acc = new Account(Name ='Testing', Client_Code_KYC__c='newsourcecode');
     insert acc;
     Opportunity opp1 = new Opportunity( Name = 'mAWS Usage', StageName = 'Negotiations', CloseDate = System.today(),Email__c='abc@gmail.com', Client_Type__c='Individual', AccountId=acc.Id);
     insert opp1;
     Task t = new task(WhatID = opp1.id,Subject='Donni',Status='New',Priority='Normal');
     insert t;
     
      SMSSetings__c sms = new SMSSetings__c(Disposition_Name__c = 'testsms',SMS_Content__c = 'testsms content' );
     Map<String, String> dispositionMap = new  Map<String, String>{'test'=>'test1'};
      DateTime dat = datetime.newInstance(2014, 9, 15, 12, 30, 0);
     Map<String, DateTime> dispositionDateTimeMap= new  Map<String, DateTime>{'test'=>dat};  
     LeadHelperClass lc = new LeadHelperClass();
     LeadHelperClass.AddNewLead(LT);
 }
}
Thanks in Advance.
 
Hi All,

We have two roles that Marketing Manager and Marketing Executive. Campaign OWD is Private. We have Parent campaign and sub campaign. Parent campaign owner always should be marketing manager. Sub campaign owner is marketing executive. But sub campaign has lookup to parent campaign. If i won't give parent campaign read permission to marketing executive then marketing executive can not save the sub campaign. Marketing executive will get error as insufficient privileges. I have created sharing rule that marketing executive can see marketing manager records with read only permission then only marketing executive can able to save the record or else marketing executive cannot save the record. But Actual requirement is Marketing executive not to see the parent campaign record, he can able to see only sub campaign. Could anyone help on this issue how to solve.

Thanks in Advance.
Hi All,

I have written below trigger.
trigger D2R_DFA_InventoryTrigger on DFA_Inventory__c (before insert, before update) {
    if(trigger.isBefore) {
        if(trigger.isInsert || trigger.isUpdate) {
              for(DFA_Inventory__c inv : trigger.new) {
                 if(inv.Add_Quantity__c != null) {
                    if(inv.Available_Quanity__c == null)
                        inv.Available_Quanity__c = 0;
                    inv.Available_Quanity__c = inv.Add_Quantity__c + inv.Available_Quanity__c;
                    inv.Add_Quantity__c = null;
                }
            }
        }
        
        if(trigger.isInsert) {
           Map<Id, List<DFA_Inventory__c>> mapInvByDFA_Id = new Map<Id, List<DFA_Inventory__c>>();
           for(DFA_Inventory__c inv : trigger.new) {
              mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
            }
            List<DFA_Inventory__c> lstExistingInvs = [SELECT Id, DFA__c, Product__c FROM DFA_Inventory__c
                                                      WHERE DFA__c=:mapInvByDFA_Id.keySet() ];
            
            for( DFA_Inventory__c inv : lstExistingInvs) {
                 if(!mapInvByDFA_Id.containsKey(inv.DFA__c)) {
                    mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
                }
                mapInvByDFA_Id.get(inv.DFA__c).add(inv);
            }
            
            for(DFA_Inventory__c inv : trigger.new) {
                if(mapInvByDFA_Id.containsKey(inv.DFA__c) && mapInvByDFA_Id.get(inv.DFA__c).size() > 0 ) {
                    for(DFA_Inventory__c existingInv : mapInvByDFA_Id.get(inv.DFA__c)) {
                        if(inv.Product__c == existingInv.Product__c) {
                         inv.Product__c.addError('Product already exists in DFA Inventory, Update existing Inventory.');
                        }
                    }
                }
            }
          }
    }
}
Below is the test class
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
         product2 prod = new product2();
        prod.Name = 'Test Product';
       insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

I am getting only 69% code coverage for trigger. I am not able to cover the add error message in test class.could anyone help on this. 

Thanks in Advance.
 
Hi All,

I am getting System.NullPointerException: Attempt to de-reference a null object error in salesforce test class.

Apex Class:
global class planvisitcontroller {
 public String RequestorEmployee { get; set; }
    public id leadid{get;set;}
    public string userid{get;set;}
    public string SelectedProduct{get;set;}
    public boolean showReqPopup { get; set; }
    public list<lead> leadlist{get;set;}
    
    public boolean serachdone{get;set;}
    public list<user> userList{get;set;}
    public String routeAccMap { get; set; }
    
    public String taskSubject{get;set;}
    public DateTime startDateTime {get;set;}
    public DateTime endDateTime {get;set;}
    public String errorMessage {get;set;}
    
     public list<Account> lstAccount {get;set;} 
    public boolean isError { get; set; }
    public List<WrapperLead> wrappers {get; set;} 
    public List<String> selectedDays {get;set;}
    public String recordName { get; set; }
    
    public List<SelectOption> days { get; set; }
    public Set<String> plannedDays;
    public String currentMonth { get; set; }

   public planvisitcontroller () {
        showReqPopup = false;
        wrappers = new List<WrapperLead>();
        SelectedDays = new List<String>();
        days = new List<SelectOption>();
       mapUsersByID = new Map<Id, User>([SELECT Id, Name From User 
                                         WHERE Manager.Id=:UserInfo.getUserId() AND UserRole.Name='Sales Executive']);
        
        leadlist=[select id, name, Status, Requested_Visit_Time__c,OwnerId,Sales_Executive__c,Address,city 
                 from lead WHERE OwnerID=:mapUsersByID.keySet()  and isConverted=false and Sales_Executive__c!=null 
                 order by Requested_Visit_Time__c];
         
        for(Lead l : leadlist){
            wrappers.add(new WrapperLead(l, new List<Integer>{1,2})); 
        } 
            
        lstAccount = [SELECT Id, Name, Onboarding_Status__c, BillingCity, OwnerId,Sales_Executive__c From Account 
                      WHERE Sales_Executive__c=:mapUsersByID.keySet()];
    }
    
    
    public PageReference closetable() {
        showReqPopup=false;
        return null;
    }


    public PageReference SelectedEmployee() {
        return null;
    }
    
    
    public PageReference closePopup() {
        PageReference ref = new PageReference('/apex/D2R_PlanVisit');
        ref.setRedirect(true);    
        return ref;      
    }
    
    public void FilterEmployee() {
        userList=mapUsersByID.values();
        serachdone=true; 
        openpopup();   
        //return null;
    }
    
    
    public PageReference CloseWindow() {
        showReqPopup=false;
        selectedDays = new List<String>();
        plannedDays = new Set<String>();
        taskSubject = '';
        
        return null;
    }


    public PageReference openpopup() {
         showReqPopup=true;
        String recordId = leadid;
        List<Task> existingTasks = new List<Task>();
        plannedDays = new Set<String>();
       
        if(recordId.startsWith('00Q')) {
            Lead l = [SELECT Sales_Executive__r.name FROM Lead WHERE Id=:recordId];
            
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee = l.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhoId=:recordId AND Type='Visit'];
            
        }else {
            Account a = [Select Sales_Executive__r.name From Account Where id=:recordId];
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee  = a.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhatId=:recordId AND Type='Visit'];
        }
       
        days = getDaysOfCurrentMonth();
        
        for (Task t : existingTasks){
            String taskDay = String.valueOf(t.ActivityDate);
        }
       
        selectedDays = new List<String>();
        
        for (Task t : existingTasks){
            
            String taskDay = String.valueOf(t.ActivityDate);
            System.debug('!!: ' + taskDay);
            
            if(String.isNotBlank(taskDay) ){
                List<String> i = taskDay.split('-');
                
                if(Date.Today().Year() == Integer.valueOf(i[0]) &&  Date.Today().Month() == Integer.valueOf(i[1]))
                    if(!plannedDays.contains(''+i[2])) {
                        selectedDays.add(''+Integer.valueOf(i[2]));
                        plannedDays.add(''+Integer.valueOf(i[2]));
                    }
            }
            
        }   
         System.debug(' selectedDays !!: ' + selectedDays);
         System.debug('plannedDays !!: ' + plannedDays);
        
        return null;
    }


    public PageReference saveplaning() {
        
        showReqPopup=false;
        String recordId = leadid;
        Lead leadplan = new Lead();
        Account acc = new Account();
        List<Task> tasksToInsert = new List<Task>();
        
        System.debug('selected Days: ' + selectedDays );
        
        if(recordId.startsWith('00Q')){
            leadplan = [select id, Requested_Visit_Time__c, Plan__c, Name, OwnerId, Sales_Executive__c from Lead where id = :recordId ];
        
        } else {
            acc = [SELECT Id, Name, BillingCity, OwnerId,Sales_Executive__c From Account 
                   WHERE Id=:recordId];
        }
        
       
        for(String str : selectedDays) {
        
            system.debug('Loop for : ' + str);
            Id visitRT = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Plan-Visit Task').getRecordTypeId();
            
            if(!plannedDays.contains(str)) {
            
                system.debug('task to be inserted for : ' + str);
                Integer day = Integer.valueOf(str);
                Date dueDate = date.newInstance(Date.Today().Year(), Date.Today().Month(), day);
                
                Task task = new Task();
                task.subject = taskSubject;
                
                if(String.isNotBlank(userid)){
                     task.OwnerId = userid;
                } else {
                    if(recordId.startsWith('00Q'))
                        task.OwnerId = leadplan.Sales_Executive__c;
                    else
                        task.OwnerId = acc.Sales_Executive__c;
                }
                              
                if(recordId.startsWith('00Q')) {
                    task.whoId = recordId;
                } else {
                    task.whatId = recordId;    
                }
                
                task.ActivityDate = dueDate;
                task.RecordTypeId = visitRT;
                task.Type = 'Visit';
                
                tasksToInsert.add(task);
              }
          }
          
          if(tasksToInsert.size()>0) {
              insert tasksToInsert;
          }
          
          PageReference ref = new PageReference('/apex/D2R_PlanVisit');
          ref.setRedirect(true);
        
          return ref;      
    }
    
     public List<SelectOption> getDaysOfCurrentMonth() {
    
          Map<Integer,String> mapMonthsByIndex = new Map<Integer,String>{ 1 => 'January', 2 => 'February'};
        currentMonth = mapMonthsByIndex.get(Date.Today().Month()) + ' , ' + Date.Today().Year();
        
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
        
        System.debug('!!!!: ' + lastDayOfMonth);
        List<String> days = new List<String>();
        
        for(Integer i=1; i<=lastDayOfMonth.day() ; i++ ){
            days.add('' + i);
            System.debug('!!!!: ' +i);
        }
            
        List<SelectOption> Options = new List<SelectOption>();
        
        for(String str : days){
            Options.add(new SelectOption(str,str));
        }
        
        return Options;
    }
    }

Test Class
@isTest
private class planvisitcontrollerTest
{

    @testSetup 
 static void setup() 
 {
      Profile p = [SELECT Id FROM Profile WHERE Name='Sales Executive'];
      User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
      insert u2;
        
      Lead l = new Lead();
      l.LastName = 'Salesforce.com';
      l.Company = 'KPMG';
      l.Status = 'New';
      l.Email = 'abc@gmail.com';
      l.Phone = '8938493';
      l.Industry = 'Web';
      l.City=' bangalore';
      l.PostalCode ='788889';
      l.State = 'Karnataka';
      l.Country = 'India';
      insert l;
      
      Task t = new Task();
      t.Subject= 'test task';
      t.ActivityDate = System.Today();
      t.WhoId = l.Id;
      t.Type = 'Visit';
      insert t;
  
       l = [SELECT Id FROM Lead WHERE Id = :l.Id];
 }

     @isTest 
 static void testMethod1() 
 {
 
    
     planvisitcontroller pc = new planvisitcontroller();
      Test.startTest();
      pc.SelectedEmployee();
      pc.closePopup();
    
       pc.FilterEmployee();
      pc.CloseWindow();
      
      pc.saveplaning();
      pc.getDaysOfCurrentMonth();
      Test.stopTest();
   
      System.assertNotEquals(null,    pc.openpopup());

     
      
 }

}

Getting error in openpopup() method in Apex class. Because passing the recordId.startsWith('00Q') in openpopup. Not getting how to pass in Test class. Could any one help on this. 

Thanks in Advance.
Hi All,

We have two profiles in our organization. One is Maketing Manager and Maketing Executive. Set the Campaign OWD as Private. For Marketing Executive Profile given the Read and Edit Permission. Marketing User checkbox has checked on User record. But Marketing Executive edits the Campaign and clicked on save button then getting error as "Insufficient Privileges for the user". I am not getting what mistake i have done. Could any one help on this issue.
I have 3 objects Booking, Products and Collections. Booking object has two related lists that is Products and Collections. After creating the booking record then automatically collection records are created depend on field payment duration on Booking. For this i have implemented the Apex Trigger. It is inserting the child collection records fine only but problem is when i will update the booking payment duration field as 2 again 2 more recods are inserting under collection object. It is inserting collection records again. If i will remove the after update event then child collections records are inserting the payment amount as 0.Below is the trigger.
trigger createCollections on Order ( after insert, after update) {

List<Collection__c> coll = new List<Collection__c>();
for(Order o : trigger.new)
{
 if(createcollectionclass.runonce()){
if(o.Payment_Duration__c != null  && o.Type == 'Periodic' )
{
for(integer i = 0; i< integer.valueOf(o.Payment_Duration__c); i++){

                Collection__c c= new Collection__c();
                c.Order__c = o.id;
                c.Payment_Amount__c = ( o.Total_Due__c/o.Payment_Duration__c);
                coll.add(c);
            }
}
}
}
if(!coll.isEmpty()){
    insert coll;
    }       
}
Kindly help on this issue.

 
Hi,
I have written the below visualforce page and Apex class for creating the Opportunity Product. It is working fine in salesforce . When I opened in salesforce Community , I am not able to create opportunity product and not able to redirect to another visualforce page. I have given visualforce page and apex class access to community user profile. But it is redirects to Error occurred while loading a Visualforce page.
 
Visualforce page:
<apex:page standardController="Pricebookentry"  extensions="productcontroller" sidebar="false" showHeader="false" applyBodyTag="false">
<html lang="en">
<head>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" ></script>
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
        <script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
       <apex:stylesheet value="{!URLFOR($Resource.BootCss)}" />
         <apex:includeScript value="{!URLFOR($Resource.Chart1)}"/>   
  <apex:includeScript value="{!URLFOR($Resource.JS)}" /> 
        <apex:includeScript value="{!URLFOR($Resource.bootJs)}" /> 
<script>
    function alertSample()
    {   
        alert("You have booked Successfully");
     }
</script> 
<style>
            .container-fluid {
            margin-top: 10px;
            }
            
              #chartdiv {
    width       : 400px;
    height      : 200px;
    font-size   : 11px;
}       

 </style>              
 </head>
<body>    
<apex:form >
<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
  </ol>
 <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src='{!URLFOR($Resource.Header)}' alt="New York"/>
      <div class="carousel-caption">
        <h3>New York</h3>
        <p>The atmosphere in New York is lorem ipsum.</p>
      </div> 
    </div>

    <div class="item">
      <img src='{!URLFOR($Resource.Header)}' alt="Chicago"/>
      <div class="carousel-caption">
        <h3>Chicago</h3>
        <p>Thank you, Chicago - A night we won't forget.</p>
      </div> 
    </div>

    <div class="item">
      <img src='{!URLFOR($Resource.Header)}' alt="Los Angeles"/>
      <div class="carousel-caption">
        <h3>LA</h3>
        <p>Even though the traffic was a mess, we had the best time.</p>
      </div> 
    </div>
  </div>

 </div>

<div class="container-fluid">
<div id="header"></div>
                <div class="panel panel-default">
                <div class = "panel-table" style="float: left;width: 900px;">
                    <div class="panel-body" >
                        <div class="panel panel-success">
                            <div class="panel-heading">Prodcut Search</div>
                             <div class="panel-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group"> 
                                        <label for="aName">Products Category</label> &nbsp;
                             <apex:selectList value="{!selectedCategory}" multiselect="false" size="1">
                                            <apex:selectOptions value="{!productOptions}"/>
                                            </apex:selectList> &nbsp;
                              <apex:commandButton value="Search Product" action="{!SearchProduct}" />
                                        </div>
                                    </div>
                              </div>
                           </div>
                        </div>
                        <div class="panel panel-info">
                            <div class="panel-heading"><div>
                                Products Information
    <apex:commandButton value="Book" action="{!Book}"  onclick="alertSample();" style="float: right;"/>
                                </div>
     <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header"> 
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                                                </button> 
                   </div>
            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="panel-body">
                                <apex:outputPanel id="productTable">
                                    <table class="table table-condensed">
                                        <tr>
                                            <th>Select</th>
                                            <th>Product name</th>
                                            <th>Product Category</th>
                                            <th>Product Price</th>
                                             <th> Quantity</th>
                                            <th>Image</th>
                                          
                                        </tr>
                   <apex:outputpanel rendered="{!IF((selectedCategory == NULL) , true,false)}">
                                         <apex:repeat value="{!productlist1}" var="prod1" >
                                            <tr>
                                                <td> </td>
                                                <td>
                                                   <apex:outputField value="{!prod1.Product2.Name}" />
                                                </td>
                                                <td>
                                                    <apex:outputField value="{!prod1.Product2.Family}" />
                                                </td>
                                                <td>
                                                   <apex:outputField value="{!prod1.UnitPrice}" />
                                                </td>
                                                <td>
           <apex:inputField value="{!prod1.Product2.Quantity__c}" />
                                                </td>
                                                 <td>
     <apex:outputField value="{!prod1.Product2.ProductPicture__c}" />
                                                </td>
                                            </tr>
                                        </apex:repeat> 
                                        </apex:outputpanel>
          <apex:outputpanel rendered="{!IF((selectedCategory!= NULL) , true,false)}" id="pageblock1"> 
                                        <apex:repeat value="{!productlist}" var="prod" >
                                            <tr>
                                                <td>
                                                  <apex:outputPanel id="counter2">
				 <input type="radio" name="sel"  />
                 <apex:actionsupport action="{!process}" event="onchange" rerender="abc">
               <apex:param name="select"  value="{!prod.Product2.Id}"  assignTo="{!str}"/>
                                                    </apex:actionsupport>
                                                    </apex:outputPanel>
                                               </td>
                                                <td>
                                                   <apex:outputField value="{!prod.Product2.Name}" />
                                                </td>
                                                <td>
                                                    <apex:outputField value="{!prod.Product2.Family}" />
                                                </td>
                                                <td>
                                                   <apex:outputField value="{!prod.UnitPrice}" />
                                                </td>
                                                <td>
               <apex:inputText value="{!prod.Product2.Quantity__c }" />
                                                </td>
                                                 <td >
         <apex:outputField value="{!prod.Product2.ProductPicture__c}" />
                                                </td>
                                            </tr>
                                        </apex:repeat> 
                                         </apex:outputpanel>
                                    </table>
                                </apex:outputPanel>
                            </div>
                        </div>
                    </div>
                </div>
                         </div>
            </div>
            
      </apex:form>
    </body>
    </html> 
</apex:page>

Apex Class:
public without sharing class productcontroller {

    public Product2 pro{get;set;}
    public Pricebookentry productlist{get;set;}
    public OpportunityLineItem oppLineItem{get;set;}
    Public Boolean flag {get;set;}
    Public string str {get;set;}
    Public Product2 records {get;set;}
    public List<Pricebookentry> productlist1{get;set;}
    public string selectedAsset {get;set;}
    public string selected{get;set;}
    public String selectedCategory{get;set;}
 
     public productcontroller(ApexPages.StandardController controller) {
     pro = new Product2();
     productlist1 = [SELECT Id,Name,Product2.Id,Product2.Name,Product2.Family,Product2.Quantity__c ,Product2.Product_Category__c,Product2.ProductPicture__c,Product2.ProductCode,UnitPrice FROM Pricebookentry LIMIT 2];
  
   }
    public void SearchProduct()
    {
       productlist = [SELECT Id,Name,Product2.Id,Product2.Name,Product2.Family,Product2.Quantity__c ,Product2.ProductPicture__c,Product2.ProductCode,UnitPrice FROM Pricebookentry where PriceBook2.IsStandard=true AND Product2.Family =:selectedCategory];
       system.debug('**********' + pro.Family);
    }
   
     public PageReference process()
     {
        flag = false;
        return null;
     }

    public PageReference Book()
    {
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opportunity';
        opp.CloseDate= System.Today();
        opp.StageName='Open';
        insert opp;
       
          system.debug('str****************' + str); 
             oppLineItem = new OpportunityLineItem();
       
       if ( str != null)
       {
         
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = productlist.Id;
       // oppLineItem.Product2.Id = str;
        oppLineItem.UnitPrice = productlist.UnitPrice;
       
        oppLineItem.Quantity = productlist.Product2.Quantity__c;
        oppLineItem.Status__c = 'Open';
        oppLineItem.Sub_Status__c = 'Order Received';
        insert oppLineItem;
       
          return null;
      
       
        } 
       
        PageReference ref = Page.oppproddetailpage;
        ref.getParameters().put('selectedAsset', oppLineItem.Id);
        ref.setRedirect(true);
        return ref;
      }
   }
    public List<SelectOption> getproductOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('Vibration Speakers','Vibration Speakers'));
        countryOptions.add(new SelectOption('LED H Series','LED H Series'));
      
        return countryOptions;
    }  
}
Could please help on this issue. Thanks in Advance.
 
Hi All,
Below are Apex Class and Test Class.
Apex Class:
public  class UnvalidatedMum {
      id currentUserid;
      public list<Mum_Information__c> UnvalidatedMumList{get;set;}
    public UnvalidatedMum () {
        currentUserid=UserInfo.getUserId();
        Educator__c edu=[select id from Educator__c where user__c =:currentUserid limit 1];
        UnvalidatedMumList=[SELECT Id, Name, Mobile_No__c,  EduMum__c, 
                            First_Name__c,  Validation_Stage__c, Current_week__c FROM Mum_Information__c
                            where EduMum__c =:edu.id and Validation_Stage__c='Unvalidated' order by CreatedDate desc limit 10000 ];
        
    }
}
Test class:
-----------
@istest
private class UnvalidatedMumExtTest
{
  
    private static testmethod void fetchUnValidatedMum(){
         list<Mum_Information__c> mumList = new list<Mum_Information__c>();
          user u =[select id from user limit 1];
         Educator__c edu = new Educator__c();
        edu.Educator_Phone_No__c='7451245759';
        edu.user__c = u.id;
        insert edu;
       City__c c = new City__c(Name='cityname',Estimated_Target__c=6);
        insert c;
        Message_Table__c  m = new Message_Table__c (Persona__c=1,Week__c=12);
        insert m;
        Hospital__c h = new Hospital__c(name='hospital',Hospital_Type__c='Govt',City_Name__c=c.id);
        insert h;
        Mum_Information__c info = new Mum_Information__c(Mum_Hospital__c=h.id,Whatsapp_Presence__c='yes',Validation_Stage__c='validated',Pregnancy_Type__c='First',Lifestage_Months__c='3rd trimester',Family_Type__c='Joint',Facebook_Presence__c='no',First_Name__c = 'Test',edumum__c=edu.id,edd__c=date.today(),MObile_no__c='7094346807', address__c='hyd',pincode__c=121312,Landline_Number__c=0402303433,otp__c=123,Preferred_language__c='English',Do_you_own_this_phone__c='yes',ConsentID__c = decimal.valueof('12345678912')); 
        insert info;
 UnvalidatedMum un = new UnvalidatedMum();
  }
}

I am getting only 50% code coverage. I am not able to cover the Bold lines in apex class. Anyone please help on this.

Thanks in Advance.


 
Hi All,
I have written the test class for apex class code coverage. But i am getting only 56% code coverage for the class. Below are the apex class and test class.
 
Apex class:

@RestResource(urlMapping='/portalUserAuthentication/*')
global with sharing class portalUserAuthenticationService
{
 @HttpPost
    global static String checkPortalUser(){
   RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        String Endpoint=req.requestURI;
        string userName=endpoint.substring(endpoint.lastIndexOf('/')+1);
        system.debug('**userName**'+userName);
         if(userName!='' || userName!=null){
            system.debug('**inside userName**'+userName);
            List<User> users=[select id,contactId from User where (email=:userName OR username =:userName) and IsActive=true];
            if(users.size()>0){
                system.debug('**users**'+users);
                List<Account> acc = [Select Id,Status__c,Account_Type__c From Account where PersonContactid=:users[0].contactId and IsPersonAccount=true];
                if(acc.size()>0){
                    system.debug('**acc**'+acc);  
                    if(acc[0].Account_Type__c=='Member' && acc[0].Membership_Status__c=='Approved'){
                        system.debug('**true acc type**'+acc[0].Account_Type__c+'**mem status**'+acc[0].Membership_Status__c);
                        return 'true';
                    }
                    else
                        return 'false';  
                }
                else
                    return 'false';
            }
            else
                return 'false';
        }
        else
            return 'false';
  }
}
 
Test Class:
@isTest
private class TestportalUserAuthenticationService
{
    public static testmethod void testportaluser() {
     Account acc1 = new Account();
    acc1.Name = 'newAcc1';
    insert acc1;
    Contact con = new Contact();
    con.AccountId = acc1.id;
    con.LastName = 'portalTestUser';
    insert con;
     User u = new User();
    u.username = 'newUser@yahoo.com'; 
    u.email = 'pb@ff.com';
    u.emailencodingkey = 'UTF-8'; 
    u.localesidkey = 'en_US'; 
    u.languagelocalekey = 'en_US';
    u.timezonesidkey = 'America/Los_Angeles'; 
    u.alias='nuser';
    u.lastname='lastname'; 
    u.contactId = con.id;
    insert u;
    System.RestContext.request = new RestRequest();
    RestContext.request.requestURI = '/portalUserAuthentication/*';
     String portalu = portalUserAuthenticationService.checkPortalUser(); 
    List<Account> accdetails = [Select Id,Status__c,Account_Type__c From Account where PersonContactid=:u.contactId and IsPersonAccount=true];
   System.assert(accdetails.size()==0);
 }
}

I am not getting how to increase the code coverage for this class.Kindly help how to increase code coverage.

Thanks in Advance.


 
Hi All,

I am getting the error in test class as System.StringException: Unrecognized base64 character: *. I am not getting how to resolve the issue. Could anyone help on this issue.
 
@isTest
private class TestUpdateCourseCompletionStatusService 
{
    public static testmethod void testupdate() {
     LMS__c lmsc = new LMS__c ();
    lmsc.Prod_CryptoKey__c = 'prod crypto';
    lmsc.Test_CryptoKey__c = 'test crypto';
    lmsc.Prod_IV__c = 'prod iv';
    lmsc.Test_IV__c = 'test iv';
    insert lmsc;
    
    Registration__c coursereg = new Registration__c();
    coursereg.Name__c = 'testcourse';
    coursereg.ID_Number__c = '1234';
    coursereg.LMS_Status__c ='Completed';
    insert coursereg;
    
     System.RestContext.request = new RestRequest();
     RestContext.request.requestURI = '/UpdateCourseCompletionStatus/*';
     RestContext.request.addHeader('decodedB64 ', '12345');
     
    UpdateCourseCompletionStatusService.updateCourseRegistration();
  
}
}

Thanks in Advance.


 
Hi All,

I am getting the System.StringException: Unrecognized base64 character: in Test Class.

I have written the below Apex Code to update the Course Registration Details.
 global static String updateCourseRegistration(){
   RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        String Endpoint=req.requestURI;
        
        string enrCourseComDate=endpoint.substring(endpoint.lastIndexOf('/')+1);
        String enrCourseComDateUTF= EncodingUtil.urlDecode(enrCourseComDate,'UTF-8');
        enrCourseComDateUTF= EncodingUtil.urlDecode(enrCourseComDateUTF,'UTF-8');
        Blob decodedB64 = EncodingUtil.base64Decode(enrCourseComDateUTF);
        Blob decryptedBlob = Crypto.decrypt('AES256', blob.valueof(cryptoKey),blob.valueof(IV), decodedB64);
        string CourseComDate=decryptedBlob.toString();
         if(courseComDate.length()==8){
            endpoint=endpoint.removeEnd('/'+enrCourseComDate);
            String encEnCourseId= endpoint.substring(endpoint.lastIndexOf('/')+1);
            encEnCourseId= EncodingUtil.urlDecode(encEnCourseId,'UTF-8');
            encEnCourseId= EncodingUtil.urlDecode(encEnCourseId,'UTF-8');
            Blob decodedB641 = EncodingUtil.base64Decode(encEnCourseId);
            Blob decryptedBlob1 = Crypto.decrypt('AES256', blob.valueof(cryptoKey),blob.valueof(IV), decodedB641);
            string enCourseId=decryptedBlob1.toString();
            if(enCourseId.length()==5){
                List<Course_Registration__c> cr=[select id,name,Course_Instance_LMS_Mode__c,LMS1_Enrcourse_ID__c,Registration_Date__c,Course_completion_Date__c from Course_Registration__c where
                                                    LMS1_Enrcourse_ID__c=:enCourseId];
                if(cr.size()>0){                                    
                    if(cr[0].Course_Instance_LMS_Mode__c!='Blended')
                        cr[0].LMS_Status__c='Completed';
                    else
                        cr[0].LMS_Status__c='Blended course completed';
                    update cr;
                  return '2000-Successful';
                }

Test Class:

@isTest
private class TestUpdateCourseCompletionStatusService 
{
    public static testmethod void testupdate() {
     LMSCredentials__c lmsc = new LMSCredentials__c ();
    lmsc.Prod_CryptoKey__c = 'prod crypto';
    lmsc.Test_CryptoKey__c = 'test crypto';
    lmsc.Prod_IV__c = 'prod iv';
    lmsc.Test_IV__c = 'test iv';
    insert lmsc;
    Course_Registration__c coursereg = new Course_Registration__c();
    coursereg.Name__c = 'testcourse';
    coursereg.ID_Number__c = '1234';
    coursereg.LMS_Status__c ='Completed';
    insert coursereg;
   System.RestContext.request = new RestRequest();
     RestContext.request.requestURI = '/UpdateCourseCompletionStatus/*';
     RestContext.request.addHeader('decodedB641 ', '12345');
     UpdateCourseCompletionStatusService.updateCourseRegistration();
}
}

I am getting the error as "System.StringException: Unrecognized base64 character: " and stack trace as Class.System.EncodingUtil.base64Decode: line 5, column 1
Class.UpdateCourseCompletionStatusService.updateCourseRegistration: line 28, column 1
Class.TestUpdateCourseCompletionStatusService.testupdate: line 30, column 1.

Thanks in Advance.
Hi All,

I am writing the Test class for one batch Apex class. Below is the code of Test Class and Batch Apex Class.

@istest
public class BatchBulkMembershipRenewalsTest
{
static testmethod void BulkMembershipTestMethod(){
 BulkRenewals__c testRenewal = new BulkRenewals__c (ID_Number__c = '12345',ID_Type__c = 'Pink NRIC');
 insert testRenewal;
 testRenewal = [select id,Name,ID_Number__c,ID_Type__c from BulkRenewals__c where id = :testRenewal.Id ];
 String RecTypeId= [select Id from RecordType where (Name='Person Account') and (SobjectType='Account')].Id;
 Account newAccount = new Account(RecordTypeID=RecTypeId, FirstName='Test FName', LastName='Test LName', Membership_Status__c = 'Approved', Member_Class__c = 'Associate', Renewal_Year__c = '2016', ID_Type__c = testRenewal.ID_Type__c , ID_Number__c = testRenewal.ID_Number__c );
 insert newAccount;
 Application__c application = new Application__c (Application_Status__c = 'Created',Account__c = newAccount.Id);
  insert application;
 application = [select id,Name from Application__c where id = :application.Id];
 String RecTypeId2= [select Id from RecordType where (Name='Business Account') and (SobjectType='Account')].Id;
 Account businessAccount = new Account(RecordTypeID=RecTypeId2, Name='Test FName1', ID_Type__c = testRenewal.ID_Type__c , ID_Number__c = testRenewal.ID_Number__c );
   insert businessAccount;
 BatchBulkMembershipRenewals  bbmr = new BatchBulkMembershipRenewals ('select id from BulkRenewals__c'  );
  Test.StartTest();
   Database.executeBatch(bbmr,200);
  Test.StopTest();  
}}

Batch Apex Class:
------------------------
 global Database.QueryLocator start(Database.BatchableContext BC){
        List<String> recordIdList=new List<String>();
        system.debug('**recordIdString**'+recordIdString);
        //recordIdList=recordIdString.split(',');
        recordIdList = (List<String>)System.JSON.deserialize(recordIdString, List<String>.class);
        system.debug('**recordIdList**'+recordIdList);
        string query='SELECT id,name,Person_Account_Name__c,ID_Type__c,ID_Number__c,Failed_Reasons__c,Corporate_Account__c,Renewal_Process_Status__c,Consent_to_ISCA_PDP_Policy__c, Disciplinary_Proceedings__c,Accounting_Qualification__c,Acknowledge_Non_Refundable_Admission_Fee__c,Accuracy_and_Completeness_of_Information__c,Eligibility_of_MIR__c,Acknowledgement_Transitional_Arrangement__c,Ethics_Declaration__c,Reason_For_Non_Compliance__c,CPE_Compliance_Declaration__c from BulkRenewals__c where id IN :recordIdList';
        system.debug('**query**'+query);
        return Database.getQueryLocator(query);
    }
    
I am getting the error like "System.JSONException: Unexpected character ('s' (code 115)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]".

Please help me on this isse. Thanks in Advance.
 
Hi ,

I have implemented the below code. But problem is when i am deleting the child record (Patient Record )then i am getting the error.

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger UpdateDoctor caused an unexpected exception, contact your administrator: UpdateDoctor: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Class.UpdatedoctorInfo.updatedoctor: line 10, column 1". 

Apex Class:
-----------------
public Class UpdatedoctorInfo
{
  public void updatedoctor (List<Patient__C> patients)
     {
     Map<String, Patient__C> patientcodeMap= new Map<String, Patient__C>();
     for(Patient__c p: patients)
        {
             if (p.Doctor_Code__C != Null )
            {
            patientcodeMap.put(p.Doctor_Code__C ,p);
            }
              }
     List<Doctor__C> doctorToUpdate= new List<Doctor__C>();
     List<Doctor__C> doctorList = new List<Doctor__C>([SELECT id,Doctor_Code__C  FROM Doctor__C WHERE Doctor_Code__C IN :patientcodeMap.KeySet()]);
     System.debug('***********' +doctorList);
     for(Doctor__C c: doctorList )
        {
            Patient__C obj = patientcodeMap.get(c.Doctor_Code__C );
             if(obj.Doctor__C == NULL)
            {
            system.debug('doctor id' +obj.Id);
            obj.Doctor__C = c.Id;
            }
          else
            {
              
            }
            doctorToUpdate.add(c);
            update doctorToUpdate;
        }
     Map<Id, Doctor__c> opportunityMap = new Map<Id, Doctor__c>();
         for (Patient__C ps : patients)
        {
            Doctor__c opp = new Doctor__c(Id = ps.Doctor__C);
            opp.Jan_Revenue_Value__c = 0;
            opp.Feb_Revenue__c = 0;
            opp.Mar_Revenue__c = 0;
            opp.May_Revenue__c = 0;
            opp.Apr_Revenue__c = 0;
            opp.Jun_Revenue__c = 0;
            opp.Jul_Revenue__c = 0;
            opp.Aug_Revenue__c = 0;
            opp.Sep_Revenue__c = 0;
            opp.Oct_Revenue__c = 0;
            opp.Nov_Revenue__c = 0;
            opp.Dec_Revenue__c = 0;
             opportunityMap.put(ps.Doctor__C, opp);
        }
         List<Patient__c> pat =  [select id,Doctor__C ,Patient_Revenue__c,CreatedDate from Patient__C where Doctor__C in :opportunityMap.keySet()];
         for (Patient__C ps : pat)
        {
            Doctor__c opp = opportunityMap.get(ps.Doctor__c);
            if(ps.CreatedDate.month() == 1)
             {
           if (ps.Patient_Revenue__c != null )
             {
              opp.Jan_Revenue_Value__c += ps.Patient_Revenue__c;
             }
             }
             if(ps.CreatedDate.month() == 2)
             {
           if (ps.Patient_Revenue__c != null )
             {
              opp.Feb_Revenue__c += ps.Patient_Revenue__c;
             }
             }
              if(ps.CreatedDate.month() == 3)
             {
           if (ps.Patient_Revenue__c != null )
             {
              opp.Mar_Revenue__c += ps.Patient_Revenue__c;
             }
             }
              if(ps.CreatedDate.month() == 4)
             {
            if (ps.Patient_Revenue__c != null )
             {
              opp.Apr_Revenue__c += ps.Patient_Revenue__c;
             }
             }
              if(ps.CreatedDate.month() == 5)
             {
          if (ps.Patient_Revenue__c != null )
             {
              opp.May_Revenue__c += ps.Patient_Revenue__c;
             }
             }
             if(ps.CreatedDate.month() == 6)
             {
           if (ps.Patient_Revenue__c != null )
             {
              opp.Jun_Revenue__c += ps.Patient_Revenue__c;
             }
             }
             if(ps.CreatedDate.month() == 7)
             {
            if (ps.Patient_Revenue__c != null )
             {
              opp.Jul_Revenue__c += ps.Patient_Revenue__c;
             }
             }
         if(ps.CreatedDate.month() == 8)
             {
         if (ps.Patient_Revenue__c != null )
             {
              opp.Aug_Revenue__c += ps.Patient_Revenue__c;
             }
             }
          if(ps.CreatedDate.month() == 9)
             {
          if (ps.Patient_Revenue__c != null )
             {
              opp.Sep_Revenue__c += ps.Patient_Revenue__c;
             }
             }
           if(ps.CreatedDate.month() == 10)
             {
           if (ps.Patient_Revenue__c != null )
             {
              opp.Oct_Revenue__c += ps.Patient_Revenue__c;
             }
             }
             if(ps.CreatedDate.month() == 11)
             {
             if (ps.Patient_Revenue__c != null )
             {
              opp.Nov_Revenue__c += ps.Patient_Revenue__c;
             }
             }
             if(ps.CreatedDate.month() == 12)
             {
              if (ps.Patient_Revenue__c != null )
             {
              opp.Dec_Revenue__c += ps.Patient_Revenue__c;
             }
             } }
  update opportunityMap.values();
   }}

Apex Trigger:
--------------------------
trigger UpdateDoctor  on Patient__c (before insert, before update, after insert, before delete,after update, after delete, after undelete ) {
    list<Patient__C> patients = trigger.new;
    UpdatedoctorInfo my = new UpdatedoctorInfo();
    my.updatedoctor(patients); }

Thanks for your help!
 
Hi All,

I am new to salesforce triggers.  I have two object Doctor__c and Patient__c objects. One custom field Doctor_Code__c on Docor__c object and another custom field on Patient__C object. Patient object has lookup field Doctor__c. If Patient Doctor_Code__c equal to Doctors Doctor_Code__c then Doctor__C field should populate with Doctor Name on Patient Object. For this I have written the Apex class and calling the Apex Class in trigger. But I am not getting any field Update. Below is the Code.

Apex Class:
------------------
public Class UpdateDoctor
{
  public void updatedoctor1 (List<Doctor__C> doctors)
     {
         map<string, Doctor__C> ObjMap = new map<string, Doctor__C>();
         for(Doctor__C obj: doctors)
         {
              if (obj.Doctor_Code__C!= Null)
        {
            ObjMap.put(obj.Doctor_Code__C, obj);
        }
    }
      List<Patient__c> cases = [SELECT Id, Doctor_Code__c, Doctor__c FROM Patient__c WHERE Doctor_Code__c IN :ObjMap.KeySet()];
    List<Patient__c> caseUpdateList = new List<Patient__c>();
     for(Patient__c c: cases)
    {
        Doctor__C  obj = ObjMap.get(c.Doctor_Code__c);
        c.Doctor__C= obj.Id;
         caseUpdateList.add(c);
    }
     }
}

Trigger
----------
trigger UpdateDoctortrigger  on Doctor__c( before insert,before update) {
    list<Doctor__c> doctors = trigger.new;
    UpdateDoctor my = new UpdateDoctor();
    my.updatedoctor1 (doctors);
  }

Please help on this issue.

Thanks in Advance.
Hi All,

I have implemented one Visualforce Page which display all the user with certain below condition.

User event startdate should not match with WorkOrder startdate. I am able to get list of user but not depend on criteria.

I wrote  query for getting the user list :  select Name, firstname,lastname, Skill__C, Technician_Location__c,Technician_Location__Latitude__s,Technician_Location__Longitude__s from User where Skill__C = :wo.Problem__c 

I have written the query to get the all the task : select Id, Subject, isAllDayEvent, StartDateTime, EndDateTime from Event

I have retrieved the current record workorder by using the below query :SELECT Skill_Comparision__c ,Problem__c, Distance__c,Contact.Customer_Location__c,Contact.Customer_Location__Latitude__s,Contact.Customer_Location__Longitude__s,StartDate,EndDate FROM WorkOrder WHERE ID =: controller.getId()

Now I am not getting how to compare the WorkOrder startdate to Event Startdate. Please help on this issue.

Thanks in Advance.

 
I am trying to display the Some fields from WorkOrder and some fields from User objects. Kindly help me how to write the SOQL query on this objects. I have tried with below query.

Select id, Name , ( Select WorkOrderNumber from WorkOrder) from User. 

It is throwing the error. Kindly help me on this issue.

Thanks in Advance.
I am not able to pass the parameter in Apex Controller. Below is the my Code.

public assigntechniciancontroller(ApexPages.StandardController controller) { 
    accID =  ApexPages.currentPage().getParameters().get('Id');
    skill =  ApexPages.currentPage().getParameters().get('Problem__c');
    system.debug ('@@@@@@@@@@@' +skill);
}

Problem__c is the picklist field on Standard WorkOrder Object. I am getting the null in Problem__c field. Kindly help me on this.

Thanks in Advance.
Hi All,

I have 4 objects Forecast__c, ForeCast_Details__C, Opportunity and Opportunity_Forecast__c.  Opportunity object contains multiple Opportunity_Forecast__c. Forecast__c has looup to Opportunity Object. Now i have to write batch apex class with upsert the ForeCast_Details__C  object records with value of Opportunity_Forecast__c.Could anyone please help on this.

Thanks in Advance.
Hi All,

We have two roles that Marketing Manager and Marketing Executive. Campaign OWD is Private. We have Parent campaign and sub campaign. Parent campaign owner always should be marketing manager. Sub campaign owner is marketing executive. But sub campaign has lookup to parent campaign. If i won't give parent campaign read permission to marketing executive then marketing executive can not save the sub campaign. Marketing executive will get error as insufficient privileges. I have created sharing rule that marketing executive can see marketing manager records with read only permission then only marketing executive can able to save the record or else marketing executive cannot save the record. But Actual requirement is Marketing executive not to see the parent campaign record, he can able to see only sub campaign. Could anyone help on this issue how to solve.

Thanks in Advance.
Hi All,

I have written below trigger.
trigger D2R_DFA_InventoryTrigger on DFA_Inventory__c (before insert, before update) {
    if(trigger.isBefore) {
        if(trigger.isInsert || trigger.isUpdate) {
              for(DFA_Inventory__c inv : trigger.new) {
                 if(inv.Add_Quantity__c != null) {
                    if(inv.Available_Quanity__c == null)
                        inv.Available_Quanity__c = 0;
                    inv.Available_Quanity__c = inv.Add_Quantity__c + inv.Available_Quanity__c;
                    inv.Add_Quantity__c = null;
                }
            }
        }
        
        if(trigger.isInsert) {
           Map<Id, List<DFA_Inventory__c>> mapInvByDFA_Id = new Map<Id, List<DFA_Inventory__c>>();
           for(DFA_Inventory__c inv : trigger.new) {
              mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
            }
            List<DFA_Inventory__c> lstExistingInvs = [SELECT Id, DFA__c, Product__c FROM DFA_Inventory__c
                                                      WHERE DFA__c=:mapInvByDFA_Id.keySet() ];
            
            for( DFA_Inventory__c inv : lstExistingInvs) {
                 if(!mapInvByDFA_Id.containsKey(inv.DFA__c)) {
                    mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
                }
                mapInvByDFA_Id.get(inv.DFA__c).add(inv);
            }
            
            for(DFA_Inventory__c inv : trigger.new) {
                if(mapInvByDFA_Id.containsKey(inv.DFA__c) && mapInvByDFA_Id.get(inv.DFA__c).size() > 0 ) {
                    for(DFA_Inventory__c existingInv : mapInvByDFA_Id.get(inv.DFA__c)) {
                        if(inv.Product__c == existingInv.Product__c) {
                         inv.Product__c.addError('Product already exists in DFA Inventory, Update existing Inventory.');
                        }
                    }
                }
            }
          }
    }
}
Below is the test class
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
         product2 prod = new product2();
        prod.Name = 'Test Product';
       insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

I am getting only 69% code coverage for trigger. I am not able to cover the add error message in test class.could anyone help on this. 

Thanks in Advance.
 
Hi All,

I am getting System.NullPointerException: Attempt to de-reference a null object error in salesforce test class.

Apex Class:
global class planvisitcontroller {
 public String RequestorEmployee { get; set; }
    public id leadid{get;set;}
    public string userid{get;set;}
    public string SelectedProduct{get;set;}
    public boolean showReqPopup { get; set; }
    public list<lead> leadlist{get;set;}
    
    public boolean serachdone{get;set;}
    public list<user> userList{get;set;}
    public String routeAccMap { get; set; }
    
    public String taskSubject{get;set;}
    public DateTime startDateTime {get;set;}
    public DateTime endDateTime {get;set;}
    public String errorMessage {get;set;}
    
     public list<Account> lstAccount {get;set;} 
    public boolean isError { get; set; }
    public List<WrapperLead> wrappers {get; set;} 
    public List<String> selectedDays {get;set;}
    public String recordName { get; set; }
    
    public List<SelectOption> days { get; set; }
    public Set<String> plannedDays;
    public String currentMonth { get; set; }

   public planvisitcontroller () {
        showReqPopup = false;
        wrappers = new List<WrapperLead>();
        SelectedDays = new List<String>();
        days = new List<SelectOption>();
       mapUsersByID = new Map<Id, User>([SELECT Id, Name From User 
                                         WHERE Manager.Id=:UserInfo.getUserId() AND UserRole.Name='Sales Executive']);
        
        leadlist=[select id, name, Status, Requested_Visit_Time__c,OwnerId,Sales_Executive__c,Address,city 
                 from lead WHERE OwnerID=:mapUsersByID.keySet()  and isConverted=false and Sales_Executive__c!=null 
                 order by Requested_Visit_Time__c];
         
        for(Lead l : leadlist){
            wrappers.add(new WrapperLead(l, new List<Integer>{1,2})); 
        } 
            
        lstAccount = [SELECT Id, Name, Onboarding_Status__c, BillingCity, OwnerId,Sales_Executive__c From Account 
                      WHERE Sales_Executive__c=:mapUsersByID.keySet()];
    }
    
    
    public PageReference closetable() {
        showReqPopup=false;
        return null;
    }


    public PageReference SelectedEmployee() {
        return null;
    }
    
    
    public PageReference closePopup() {
        PageReference ref = new PageReference('/apex/D2R_PlanVisit');
        ref.setRedirect(true);    
        return ref;      
    }
    
    public void FilterEmployee() {
        userList=mapUsersByID.values();
        serachdone=true; 
        openpopup();   
        //return null;
    }
    
    
    public PageReference CloseWindow() {
        showReqPopup=false;
        selectedDays = new List<String>();
        plannedDays = new Set<String>();
        taskSubject = '';
        
        return null;
    }


    public PageReference openpopup() {
         showReqPopup=true;
        String recordId = leadid;
        List<Task> existingTasks = new List<Task>();
        plannedDays = new Set<String>();
       
        if(recordId.startsWith('00Q')) {
            Lead l = [SELECT Sales_Executive__r.name FROM Lead WHERE Id=:recordId];
            
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee = l.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhoId=:recordId AND Type='Visit'];
            
        }else {
            Account a = [Select Sales_Executive__r.name From Account Where id=:recordId];
            if(RequestorEmployee=='' || RequestorEmployee == null)
                RequestorEmployee  = a.Sales_Executive__r.name;
            
            existingTasks = [Select Id, subject, ActivityDate from Task Where WhatId=:recordId AND Type='Visit'];
        }
       
        days = getDaysOfCurrentMonth();
        
        for (Task t : existingTasks){
            String taskDay = String.valueOf(t.ActivityDate);
        }
       
        selectedDays = new List<String>();
        
        for (Task t : existingTasks){
            
            String taskDay = String.valueOf(t.ActivityDate);
            System.debug('!!: ' + taskDay);
            
            if(String.isNotBlank(taskDay) ){
                List<String> i = taskDay.split('-');
                
                if(Date.Today().Year() == Integer.valueOf(i[0]) &&  Date.Today().Month() == Integer.valueOf(i[1]))
                    if(!plannedDays.contains(''+i[2])) {
                        selectedDays.add(''+Integer.valueOf(i[2]));
                        plannedDays.add(''+Integer.valueOf(i[2]));
                    }
            }
            
        }   
         System.debug(' selectedDays !!: ' + selectedDays);
         System.debug('plannedDays !!: ' + plannedDays);
        
        return null;
    }


    public PageReference saveplaning() {
        
        showReqPopup=false;
        String recordId = leadid;
        Lead leadplan = new Lead();
        Account acc = new Account();
        List<Task> tasksToInsert = new List<Task>();
        
        System.debug('selected Days: ' + selectedDays );
        
        if(recordId.startsWith('00Q')){
            leadplan = [select id, Requested_Visit_Time__c, Plan__c, Name, OwnerId, Sales_Executive__c from Lead where id = :recordId ];
        
        } else {
            acc = [SELECT Id, Name, BillingCity, OwnerId,Sales_Executive__c From Account 
                   WHERE Id=:recordId];
        }
        
       
        for(String str : selectedDays) {
        
            system.debug('Loop for : ' + str);
            Id visitRT = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Plan-Visit Task').getRecordTypeId();
            
            if(!plannedDays.contains(str)) {
            
                system.debug('task to be inserted for : ' + str);
                Integer day = Integer.valueOf(str);
                Date dueDate = date.newInstance(Date.Today().Year(), Date.Today().Month(), day);
                
                Task task = new Task();
                task.subject = taskSubject;
                
                if(String.isNotBlank(userid)){
                     task.OwnerId = userid;
                } else {
                    if(recordId.startsWith('00Q'))
                        task.OwnerId = leadplan.Sales_Executive__c;
                    else
                        task.OwnerId = acc.Sales_Executive__c;
                }
                              
                if(recordId.startsWith('00Q')) {
                    task.whoId = recordId;
                } else {
                    task.whatId = recordId;    
                }
                
                task.ActivityDate = dueDate;
                task.RecordTypeId = visitRT;
                task.Type = 'Visit';
                
                tasksToInsert.add(task);
              }
          }
          
          if(tasksToInsert.size()>0) {
              insert tasksToInsert;
          }
          
          PageReference ref = new PageReference('/apex/D2R_PlanVisit');
          ref.setRedirect(true);
        
          return ref;      
    }
    
     public List<SelectOption> getDaysOfCurrentMonth() {
    
          Map<Integer,String> mapMonthsByIndex = new Map<Integer,String>{ 1 => 'January', 2 => 'February'};
        currentMonth = mapMonthsByIndex.get(Date.Today().Month()) + ' , ' + Date.Today().Year();
        
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
        
        System.debug('!!!!: ' + lastDayOfMonth);
        List<String> days = new List<String>();
        
        for(Integer i=1; i<=lastDayOfMonth.day() ; i++ ){
            days.add('' + i);
            System.debug('!!!!: ' +i);
        }
            
        List<SelectOption> Options = new List<SelectOption>();
        
        for(String str : days){
            Options.add(new SelectOption(str,str));
        }
        
        return Options;
    }
    }

Test Class
@isTest
private class planvisitcontrollerTest
{

    @testSetup 
 static void setup() 
 {
      Profile p = [SELECT Id FROM Profile WHERE Name='Sales Executive'];
      User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
      insert u2;
        
      Lead l = new Lead();
      l.LastName = 'Salesforce.com';
      l.Company = 'KPMG';
      l.Status = 'New';
      l.Email = 'abc@gmail.com';
      l.Phone = '8938493';
      l.Industry = 'Web';
      l.City=' bangalore';
      l.PostalCode ='788889';
      l.State = 'Karnataka';
      l.Country = 'India';
      insert l;
      
      Task t = new Task();
      t.Subject= 'test task';
      t.ActivityDate = System.Today();
      t.WhoId = l.Id;
      t.Type = 'Visit';
      insert t;
  
       l = [SELECT Id FROM Lead WHERE Id = :l.Id];
 }

     @isTest 
 static void testMethod1() 
 {
 
    
     planvisitcontroller pc = new planvisitcontroller();
      Test.startTest();
      pc.SelectedEmployee();
      pc.closePopup();
    
       pc.FilterEmployee();
      pc.CloseWindow();
      
      pc.saveplaning();
      pc.getDaysOfCurrentMonth();
      Test.stopTest();
   
      System.assertNotEquals(null,    pc.openpopup());

     
      
 }

}

Getting error in openpopup() method in Apex class. Because passing the recordId.startsWith('00Q') in openpopup. Not getting how to pass in Test class. Could any one help on this. 

Thanks in Advance.
I have 3 objects Booking, Products and Collections. Booking object has two related lists that is Products and Collections. After creating the booking record then automatically collection records are created depend on field payment duration on Booking. For this i have implemented the Apex Trigger. It is inserting the child collection records fine only but problem is when i will update the booking payment duration field as 2 again 2 more recods are inserting under collection object. It is inserting collection records again. If i will remove the after update event then child collections records are inserting the payment amount as 0.Below is the trigger.
trigger createCollections on Order ( after insert, after update) {

List<Collection__c> coll = new List<Collection__c>();
for(Order o : trigger.new)
{
 if(createcollectionclass.runonce()){
if(o.Payment_Duration__c != null  && o.Type == 'Periodic' )
{
for(integer i = 0; i< integer.valueOf(o.Payment_Duration__c); i++){

                Collection__c c= new Collection__c();
                c.Order__c = o.id;
                c.Payment_Amount__c = ( o.Total_Due__c/o.Payment_Duration__c);
                coll.add(c);
            }
}
}
}
if(!coll.isEmpty()){
    insert coll;
    }       
}
Kindly help on this issue.

 
Hi,
I have written the below visualforce page and Apex class for creating the Opportunity Product. It is working fine in salesforce . When I opened in salesforce Community , I am not able to create opportunity product and not able to redirect to another visualforce page. I have given visualforce page and apex class access to community user profile. But it is redirects to Error occurred while loading a Visualforce page.
 
Visualforce page:
<apex:page standardController="Pricebookentry"  extensions="productcontroller" sidebar="false" showHeader="false" applyBodyTag="false">
<html lang="en">
<head>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" ></script>
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
        <script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
       <apex:stylesheet value="{!URLFOR($Resource.BootCss)}" />
         <apex:includeScript value="{!URLFOR($Resource.Chart1)}"/>   
  <apex:includeScript value="{!URLFOR($Resource.JS)}" /> 
        <apex:includeScript value="{!URLFOR($Resource.bootJs)}" /> 
<script>
    function alertSample()
    {   
        alert("You have booked Successfully");
     }
</script> 
<style>
            .container-fluid {
            margin-top: 10px;
            }
            
              #chartdiv {
    width       : 400px;
    height      : 200px;
    font-size   : 11px;
}       

 </style>              
 </head>
<body>    
<apex:form >
<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
  </ol>
 <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src='{!URLFOR($Resource.Header)}' alt="New York"/>
      <div class="carousel-caption">
        <h3>New York</h3>
        <p>The atmosphere in New York is lorem ipsum.</p>
      </div> 
    </div>

    <div class="item">
      <img src='{!URLFOR($Resource.Header)}' alt="Chicago"/>
      <div class="carousel-caption">
        <h3>Chicago</h3>
        <p>Thank you, Chicago - A night we won't forget.</p>
      </div> 
    </div>

    <div class="item">
      <img src='{!URLFOR($Resource.Header)}' alt="Los Angeles"/>
      <div class="carousel-caption">
        <h3>LA</h3>
        <p>Even though the traffic was a mess, we had the best time.</p>
      </div> 
    </div>
  </div>

 </div>

<div class="container-fluid">
<div id="header"></div>
                <div class="panel panel-default">
                <div class = "panel-table" style="float: left;width: 900px;">
                    <div class="panel-body" >
                        <div class="panel panel-success">
                            <div class="panel-heading">Prodcut Search</div>
                             <div class="panel-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group"> 
                                        <label for="aName">Products Category</label> &nbsp;
                             <apex:selectList value="{!selectedCategory}" multiselect="false" size="1">
                                            <apex:selectOptions value="{!productOptions}"/>
                                            </apex:selectList> &nbsp;
                              <apex:commandButton value="Search Product" action="{!SearchProduct}" />
                                        </div>
                                    </div>
                              </div>
                           </div>
                        </div>
                        <div class="panel panel-info">
                            <div class="panel-heading"><div>
                                Products Information
    <apex:commandButton value="Book" action="{!Book}"  onclick="alertSample();" style="float: right;"/>
                                </div>
     <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header"> 
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                                                </button> 
                   </div>
            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="panel-body">
                                <apex:outputPanel id="productTable">
                                    <table class="table table-condensed">
                                        <tr>
                                            <th>Select</th>
                                            <th>Product name</th>
                                            <th>Product Category</th>
                                            <th>Product Price</th>
                                             <th> Quantity</th>
                                            <th>Image</th>
                                          
                                        </tr>
                   <apex:outputpanel rendered="{!IF((selectedCategory == NULL) , true,false)}">
                                         <apex:repeat value="{!productlist1}" var="prod1" >
                                            <tr>
                                                <td> </td>
                                                <td>
                                                   <apex:outputField value="{!prod1.Product2.Name}" />
                                                </td>
                                                <td>
                                                    <apex:outputField value="{!prod1.Product2.Family}" />
                                                </td>
                                                <td>
                                                   <apex:outputField value="{!prod1.UnitPrice}" />
                                                </td>
                                                <td>
           <apex:inputField value="{!prod1.Product2.Quantity__c}" />
                                                </td>
                                                 <td>
     <apex:outputField value="{!prod1.Product2.ProductPicture__c}" />
                                                </td>
                                            </tr>
                                        </apex:repeat> 
                                        </apex:outputpanel>
          <apex:outputpanel rendered="{!IF((selectedCategory!= NULL) , true,false)}" id="pageblock1"> 
                                        <apex:repeat value="{!productlist}" var="prod" >
                                            <tr>
                                                <td>
                                                  <apex:outputPanel id="counter2">
				 <input type="radio" name="sel"  />
                 <apex:actionsupport action="{!process}" event="onchange" rerender="abc">
               <apex:param name="select"  value="{!prod.Product2.Id}"  assignTo="{!str}"/>
                                                    </apex:actionsupport>
                                                    </apex:outputPanel>
                                               </td>
                                                <td>
                                                   <apex:outputField value="{!prod.Product2.Name}" />
                                                </td>
                                                <td>
                                                    <apex:outputField value="{!prod.Product2.Family}" />
                                                </td>
                                                <td>
                                                   <apex:outputField value="{!prod.UnitPrice}" />
                                                </td>
                                                <td>
               <apex:inputText value="{!prod.Product2.Quantity__c }" />
                                                </td>
                                                 <td >
         <apex:outputField value="{!prod.Product2.ProductPicture__c}" />
                                                </td>
                                            </tr>
                                        </apex:repeat> 
                                         </apex:outputpanel>
                                    </table>
                                </apex:outputPanel>
                            </div>
                        </div>
                    </div>
                </div>
                         </div>
            </div>
            
      </apex:form>
    </body>
    </html> 
</apex:page>

Apex Class:
public without sharing class productcontroller {

    public Product2 pro{get;set;}
    public Pricebookentry productlist{get;set;}
    public OpportunityLineItem oppLineItem{get;set;}
    Public Boolean flag {get;set;}
    Public string str {get;set;}
    Public Product2 records {get;set;}
    public List<Pricebookentry> productlist1{get;set;}
    public string selectedAsset {get;set;}
    public string selected{get;set;}
    public String selectedCategory{get;set;}
 
     public productcontroller(ApexPages.StandardController controller) {
     pro = new Product2();
     productlist1 = [SELECT Id,Name,Product2.Id,Product2.Name,Product2.Family,Product2.Quantity__c ,Product2.Product_Category__c,Product2.ProductPicture__c,Product2.ProductCode,UnitPrice FROM Pricebookentry LIMIT 2];
  
   }
    public void SearchProduct()
    {
       productlist = [SELECT Id,Name,Product2.Id,Product2.Name,Product2.Family,Product2.Quantity__c ,Product2.ProductPicture__c,Product2.ProductCode,UnitPrice FROM Pricebookentry where PriceBook2.IsStandard=true AND Product2.Family =:selectedCategory];
       system.debug('**********' + pro.Family);
    }
   
     public PageReference process()
     {
        flag = false;
        return null;
     }

    public PageReference Book()
    {
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opportunity';
        opp.CloseDate= System.Today();
        opp.StageName='Open';
        insert opp;
       
          system.debug('str****************' + str); 
             oppLineItem = new OpportunityLineItem();
       
       if ( str != null)
       {
         
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = productlist.Id;
       // oppLineItem.Product2.Id = str;
        oppLineItem.UnitPrice = productlist.UnitPrice;
       
        oppLineItem.Quantity = productlist.Product2.Quantity__c;
        oppLineItem.Status__c = 'Open';
        oppLineItem.Sub_Status__c = 'Order Received';
        insert oppLineItem;
       
          return null;
      
       
        } 
       
        PageReference ref = Page.oppproddetailpage;
        ref.getParameters().put('selectedAsset', oppLineItem.Id);
        ref.setRedirect(true);
        return ref;
      }
   }
    public List<SelectOption> getproductOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('Vibration Speakers','Vibration Speakers'));
        countryOptions.add(new SelectOption('LED H Series','LED H Series'));
      
        return countryOptions;
    }  
}
Could please help on this issue. Thanks in Advance.
 
Hi All,
Below are Apex Class and Test Class.
Apex Class:
public  class UnvalidatedMum {
      id currentUserid;
      public list<Mum_Information__c> UnvalidatedMumList{get;set;}
    public UnvalidatedMum () {
        currentUserid=UserInfo.getUserId();
        Educator__c edu=[select id from Educator__c where user__c =:currentUserid limit 1];
        UnvalidatedMumList=[SELECT Id, Name, Mobile_No__c,  EduMum__c, 
                            First_Name__c,  Validation_Stage__c, Current_week__c FROM Mum_Information__c
                            where EduMum__c =:edu.id and Validation_Stage__c='Unvalidated' order by CreatedDate desc limit 10000 ];
        
    }
}
Test class:
-----------
@istest
private class UnvalidatedMumExtTest
{
  
    private static testmethod void fetchUnValidatedMum(){
         list<Mum_Information__c> mumList = new list<Mum_Information__c>();
          user u =[select id from user limit 1];
         Educator__c edu = new Educator__c();
        edu.Educator_Phone_No__c='7451245759';
        edu.user__c = u.id;
        insert edu;
       City__c c = new City__c(Name='cityname',Estimated_Target__c=6);
        insert c;
        Message_Table__c  m = new Message_Table__c (Persona__c=1,Week__c=12);
        insert m;
        Hospital__c h = new Hospital__c(name='hospital',Hospital_Type__c='Govt',City_Name__c=c.id);
        insert h;
        Mum_Information__c info = new Mum_Information__c(Mum_Hospital__c=h.id,Whatsapp_Presence__c='yes',Validation_Stage__c='validated',Pregnancy_Type__c='First',Lifestage_Months__c='3rd trimester',Family_Type__c='Joint',Facebook_Presence__c='no',First_Name__c = 'Test',edumum__c=edu.id,edd__c=date.today(),MObile_no__c='7094346807', address__c='hyd',pincode__c=121312,Landline_Number__c=0402303433,otp__c=123,Preferred_language__c='English',Do_you_own_this_phone__c='yes',ConsentID__c = decimal.valueof('12345678912')); 
        insert info;
 UnvalidatedMum un = new UnvalidatedMum();
  }
}

I am getting only 50% code coverage. I am not able to cover the Bold lines in apex class. Anyone please help on this.

Thanks in Advance.


 
Hi All,

I am getting the error in test class as System.StringException: Unrecognized base64 character: *. I am not getting how to resolve the issue. Could anyone help on this issue.
 
@isTest
private class TestUpdateCourseCompletionStatusService 
{
    public static testmethod void testupdate() {
     LMS__c lmsc = new LMS__c ();
    lmsc.Prod_CryptoKey__c = 'prod crypto';
    lmsc.Test_CryptoKey__c = 'test crypto';
    lmsc.Prod_IV__c = 'prod iv';
    lmsc.Test_IV__c = 'test iv';
    insert lmsc;
    
    Registration__c coursereg = new Registration__c();
    coursereg.Name__c = 'testcourse';
    coursereg.ID_Number__c = '1234';
    coursereg.LMS_Status__c ='Completed';
    insert coursereg;
    
     System.RestContext.request = new RestRequest();
     RestContext.request.requestURI = '/UpdateCourseCompletionStatus/*';
     RestContext.request.addHeader('decodedB64 ', '12345');
     
    UpdateCourseCompletionStatusService.updateCourseRegistration();
  
}
}

Thanks in Advance.


 
Hi All,

I am getting the System.StringException: Unrecognized base64 character: in Test Class.

I have written the below Apex Code to update the Course Registration Details.
 global static String updateCourseRegistration(){
   RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        String Endpoint=req.requestURI;
        
        string enrCourseComDate=endpoint.substring(endpoint.lastIndexOf('/')+1);
        String enrCourseComDateUTF= EncodingUtil.urlDecode(enrCourseComDate,'UTF-8');
        enrCourseComDateUTF= EncodingUtil.urlDecode(enrCourseComDateUTF,'UTF-8');
        Blob decodedB64 = EncodingUtil.base64Decode(enrCourseComDateUTF);
        Blob decryptedBlob = Crypto.decrypt('AES256', blob.valueof(cryptoKey),blob.valueof(IV), decodedB64);
        string CourseComDate=decryptedBlob.toString();
         if(courseComDate.length()==8){
            endpoint=endpoint.removeEnd('/'+enrCourseComDate);
            String encEnCourseId= endpoint.substring(endpoint.lastIndexOf('/')+1);
            encEnCourseId= EncodingUtil.urlDecode(encEnCourseId,'UTF-8');
            encEnCourseId= EncodingUtil.urlDecode(encEnCourseId,'UTF-8');
            Blob decodedB641 = EncodingUtil.base64Decode(encEnCourseId);
            Blob decryptedBlob1 = Crypto.decrypt('AES256', blob.valueof(cryptoKey),blob.valueof(IV), decodedB641);
            string enCourseId=decryptedBlob1.toString();
            if(enCourseId.length()==5){
                List<Course_Registration__c> cr=[select id,name,Course_Instance_LMS_Mode__c,LMS1_Enrcourse_ID__c,Registration_Date__c,Course_completion_Date__c from Course_Registration__c where
                                                    LMS1_Enrcourse_ID__c=:enCourseId];
                if(cr.size()>0){                                    
                    if(cr[0].Course_Instance_LMS_Mode__c!='Blended')
                        cr[0].LMS_Status__c='Completed';
                    else
                        cr[0].LMS_Status__c='Blended course completed';
                    update cr;
                  return '2000-Successful';
                }

Test Class:

@isTest
private class TestUpdateCourseCompletionStatusService 
{
    public static testmethod void testupdate() {
     LMSCredentials__c lmsc = new LMSCredentials__c ();
    lmsc.Prod_CryptoKey__c = 'prod crypto';
    lmsc.Test_CryptoKey__c = 'test crypto';
    lmsc.Prod_IV__c = 'prod iv';
    lmsc.Test_IV__c = 'test iv';
    insert lmsc;
    Course_Registration__c coursereg = new Course_Registration__c();
    coursereg.Name__c = 'testcourse';
    coursereg.ID_Number__c = '1234';
    coursereg.LMS_Status__c ='Completed';
    insert coursereg;
   System.RestContext.request = new RestRequest();
     RestContext.request.requestURI = '/UpdateCourseCompletionStatus/*';
     RestContext.request.addHeader('decodedB641 ', '12345');
     UpdateCourseCompletionStatusService.updateCourseRegistration();
}
}

I am getting the error as "System.StringException: Unrecognized base64 character: " and stack trace as Class.System.EncodingUtil.base64Decode: line 5, column 1
Class.UpdateCourseCompletionStatusService.updateCourseRegistration: line 28, column 1
Class.TestUpdateCourseCompletionStatusService.testupdate: line 30, column 1.

Thanks in Advance.
I have enabled Chatter Answers to override the change password page. This is working fine, on click of the link from email it is landing on the change password page.

In the controller of change password page, there is a redirect to another page based on certain conditions, this page redirect is not occuring.

PageReference ref = Page.resetPasswordPage;
return ref;

It seems like the page is stuck on change password page.

Both change and reset pages are added to communities.

Any information on this would be very helpful.
  • April 01, 2015
  • Like
  • 0