• Rameshwar gaur
  • NEWBIE
  • 90 Points
  • Member since 2018


  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 20
    Replies
I am new to salesforce and getting below mentioned exception in one of the query :-

public static void buildPartnerTeam (list<SObject> objects)
    {
        FINAL list<String> roleNames = new list<String>
        {
            'Account Partner',
            'Account Partner Parent',
            'Account Partner Manager To Self',
            'Account Partner User To Self',
            'Account Partner Manager',  
            'Account Master Agent',  //  jul 17
            'Account- Sub Agent Super User Access Customer (Authorized)',  //  jul 17
            'Account- Sub Agent Super User Access to Prospect or Customer (Unauthorized)', //  jul 17
            'Account Related Partner Contact' //  MO-66
        };

        list<Partner_Team_Member__c> ptmsToInsert = new list<Partner_Team_Member__c>{};
        map<Id,Account> partnerAccountsMap = new map<Id,Account>{};
        list<Id> partnerAccountIds = new list<Id>{};

        list<Partner_Team_Role__c> partnerTeamRoles = TransactionSupport.getPartnerTeamRoles (roleNames);

//        list<Partner_Team_Role__c> partnerTeamRoles = [SELECT Id, Unique_Name__c FROM Partner_Team_Role__c WHERE Unique_Name__c IN :roleNames];

        list<Id> accountIds = new list<Id>{};

        for (SObject o : objects)
        {
            if (o.get('Partner_Account__c') != null) partnerAccountIds.add ((Id) o.get('Partner_Account__c'));
            if (o.get('CSD_MA__c') != null) partnerAccountIds.add ((Id) o.get('CSD_MA__c'));
            if (o.get('Partner_Of_Record_Cloud__c') != null) partnerAccountIds.add ((Id) o.get('Partner_Of_Record_Cloud__c'));
            accountids.add (o.Id);
        }

        // MO-66: get AccountContactRelations
        map<Id,Account> accountsWithACRsMap = new map<Id,Account>([SELECT Id,(SELECT Id, ContactId, AccountId FROM AccountContactRelations)
                                FROM Account WHERE Id IN :accountIds]);  //This is line where I am getting this error 

       // system.debug('&&&'+accountsWithACRsMap);
        map<Id,Id> contactToUserIdsMap = new map<Id,Id>{};
        set<Id> contactIds = new set<Id>{};
           // list<Account> acc = [SELECT Id,(SELECT Id, ContactId, AccountId FROM AccountContactRelations)
                               // FROM Account WHERE Id IN :accountIds];
           //  accId = accountsWithACRsMap.values();
           
        /*   for(Account acct : acc) {
                                    system.debug('&&&'+acct);
               
                                    integer count=0;
                                    for (AccountContactRelation acr : acct.AccountContactRelations)
            {
                count++;
                if (acr.AccountId != acct.Id) contactIds.add (acr.ContactId);
            }
                                    
                                }  */
            
        for (Account a : accountsWithACRsMap.values())
        {
            for (AccountContactRelation acr : a.AccountContactRelations)
            {
                if (acr.AccountId != a.Id) contactIds.add (acr.ContactId);
            }
        } 
        
      /*  for (Account a : acc)
        {
            
            for (AccountContactRelation acr : a.AccountContactRelations)
            {
                if (acr.AccountId != a.Id) contactIds.add (acr.ContactId);
            }
        } */

        //  MO-66: build map for Contact Id to User Id, for all AccountContactRelation records 

        for (User u : [SELECT Id, ContactId FROM User WHERE ContactId IN :contactIds])
        {
            contactToUserIdsMap.put (u.ContactId, u.Id);
        }

        //  now add partner team members

        for (Account a : [SELECT Id, Type, Partner_Account__c, ParentId, Partner_Type__c,
                            Sub_Agent_Authorized_to_access_cases__c 
                            FROM Account 
                            WHERE Id IN :partnerAccountIds])
        {
            partnerAccountsMap.put (a.Id, a);
        }
        
        for (SObject o : objects)
        {
            for (Partner_Team_Role__c ptr : partnerTeamRoles)
            {
                if (ptr.Unique_Name__c == roleNames[0] ||    //  'Account Partner'
                        ptr.Unique_Name__c == roleNames[4])  //  'Account Partner Manager'
                {
                    Id lookupId = (Id) o.get ('Partner_Account__c');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }

                    lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c != 'Sub-Agent')  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }

                if (ptr.Unique_Name__c == roleNames[1])  // 'Account Partner Parent'
                {
                    Account a = partnerAccountsMap.get ((Id) o.get ('Partner_Account__c'));
          
                    if (a != null)
                    {
                        if (a.Partner_Account__c != null)
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                          Partner_Account__c = a.Partner_Account__c,
                                          Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }

                        if (a.ParentId != null)
                        {   
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                          Partner_Account__c = a.ParentId,
                                          Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }

                    Id lookupId = (Id) o.get ('ParentId');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }
                }

                // 'Account Partner Manager To Self' or 'Account Partner User To Self'

                if ((String) o.get('Type') == 'Partner' && (ptr.Unique_Name__c == roleNames[2] || ptr.Unique_Name__c == roleNames[3]))  
                {
                    Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = o.Id,
                                        Reason__c = 'Automatic');
                    ptm.put ('Account__c', o.Id);
                    ptmsToInsert.add (ptm);            
                }

                if (ptr.Unique_Name__c == roleNames[5])   //  'Account Master Agent'  //  Jul 17
                {
                    Id lookupId = (Id) o.get ('CSD_MA__c');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }
                }

                if (ptr.Unique_Name__c == roleNames[6])   //  'Account- Sub Agent Super User Access Customer (Authorized)'  // Jul 17
                {
                    Id lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c == 'Sub-Agent' && 
                                partnerAccount.Sub_Agent_Authorized_to_access_cases__c == true)  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }

                }

                if (ptr.Unique_Name__c == roleNames[7])   //  'Account- Sub Agent Super User Access to Prospect or Customer (Unauthorized)' //  jul 17
                {
                    Id lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c == 'Sub-Agent' && 
                                partnerAccount.Sub_Agent_Authorized_to_access_cases__c == false)  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }

                //  MO-66: Add PTMs for all Related Contacts

                if (ptr.Unique_Name__c == roleNames[8])   //  'Account Related Partner Contact'
                                {
                     Account accountWithACRs = accountsWithACRsMap.get (o.Id);
                   // Account accountWithACRs = acc.Id;

                    for (AccountContactRelation acr : accountWithACRs.AccountContactRelations)
                    {
                        Id userId = contactToUserIdsMap.get (acr.ContactId);

                        if (userId != null)
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_User__c = userId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }
            }
        }
        insert ptmsToInsert;
    }


Any help would be appreciated 
 
Help to solve this please: Illegal assignment from Decimal to String at line 34 column 4 in the test class
public with sharing class InventorySearchController { 
public list <Articles_Containers__c> inventoryItem {get;set;} 
public string searchstring {get;set;} 
public InventorySearchController( ) { 
} 
public void search(){ 
string searchquery= 'select Name , FFP_Centers__c,Prod__c, UM__c, Container__c, Number__c, On_Hand__c,  Pending__c,  Available__c, Purpose__c, Condition__c, Age__c, Comments__c FROM Articles_Containers__c  WHERE Prod__c like \'%'+searchstring+'%\'  AND On_Hand__c >0  AND IsOpened__c = 1  ORDER BY FFP_Centers__c, Prod__c,UM__c Number__c Limi 1000';
     
      inventoryItem= Database.query(searchquery); 

}
public void clear(){ 
inventoryItem.clear(); 
} 
}


@isTest
private class InventorySearchController_Test{
  @testSetup
  static void setupTestData(){
     test.startTest();
    Account pa = new Account(Name ='test Account parent', Representant__c ='hkjlhjd', 
    Distribution_Center__c='CRD Cayes', Class__c = 'Clinic', Type = 'CLINICS', 
    Departement__c = 'NORD', Address__c ='Test Address');
    insert pa;
    
          Product2 p = new Product2(Name ='TestProduct'); 
          insert p;
          Container_Shipper__c cs =new Container_Shipper__c(Name = 'Test Shipper');
          insert cs;
    Container__c container_Obj = new Container__c(Provenance__c = 'FFP FLORIDA', Distribution_Center__c= pa.id, Statut__c = 'Open',  FFP_Centers__c = 'FFP Caracole', 
     RecordTypeId='0126A000000nMlU',  Shipper__c=cs.Id );
    Insert container_Obj; 
    Articles_Containers__c articles_containers_Obj = new Articles_Containers__c(Container__c = container_Obj.id, Number__c = 17, UM__c = 'BAG(S)' ,  Local_ID__c = 7888, Product__c=p.ID,
            Comments__c = 'UNIT(S)',
           Purpose__c='Consignment',
            Condition__c= 'New',
           FFP_Centers__c = 'FFP Caracole'
            );
    Insert articles_containers_Obj; 
    test.stopTest();
  }
  static testMethod void test_search_UseCase1(){
    List<Container__c> container_Obj  =  [SELECT Provenance__c,Statut__c,Is_Reported__c,FFP_Centers__c  from Container__c];
    System.assertEquals(true,container_Obj.size()>0);
    List<Articles_Containers__c> articles_containers_Obj  =  [SELECT Container__c,Number__c,UM__c from Articles_Containers__c];
    System.assertEquals(true,articles_containers_Obj.size()>0);
    InventorySearchController obj01 = new InventorySearchController();
    obj01.inventoryItem = articles_containers_Obj;
 //Illegal assignment from Decimal to String at line 34 column 4      
obj01.searchstring =  articles_containers_Obj[0].Number__c;
    obj01.search();
  }
  static testMethod void test_clear_UseCase1(){
    List<Container__c> container_Obj  =  [SELECT Provenance__c,Statut__c,Is_Reported__c,FFP_Centers__c from Container__c];
    System.assertEquals(true,container_Obj.size()>0);
    List<Articles_Containers__c> articles_containers_Obj  =  [SELECT Container__c,Number__c,UM__c from Articles_Containers__c];
    System.assertEquals(true,articles_containers_Obj.size()>0);
    InventorySearchController obj01 = new InventorySearchController();
    obj01.inventoryItem = articles_containers_Obj;
   // obj01.searchstring = articles_containers_Obj[0].Number__c;
    obj01.clear();
  }
}

 
Hello, I'm trying to create a test class for inserting/updating quote products. When I try to run a test class I get the error: System.NullPointerException: Attempt to de-reference a null object. The stack trace is Class.QuoteRollupPFBU.updateQuote: line 17, column 1
Class.QLITest.RollUpQLI: line 63, column 1. I thought I initalized all of the variables, but feel free to let me know if you see any errors in my code. Thank you. 
 
Class 

public class QuoteRollupPFBU {
    
       public QuoteRollupPFBU(){
      List<Quote> quotesToUpdate = new List<Quote>();
      List<QuoteLineItem> quoteLineItemToUpdate;
      quoteLineItemToUpdate = new List<QuoteLineItem>();
    }
        public static void updateQuote(List<SObject> quoteLineItemToUpdate){
            List<Quote> quotesToUpdate = new List<Quote>();
            Set<String> setQuoteProdsToRemove = new  Set<String>();
            List<String> listQuoteProdsToRemove = new List<String>();
            Set<Id> ParentIds = new Set<Id>();
            for(QuoteLineItem qProduct: (List<QuoteLineItem>)quoteLineItemToUpdate){
                System.debug( 'value :' + quoteLineItemToUpdate);
                ParentIds.add(qProduct.QuoteId); 
            }                                            
            Map<Id, Quote> mapQuote = new Map<Id, Quote>([Select Id, ProductBusinessUnits__c, RollupofProductFamilies__c,  (Select Id, QuoteId, ProductFamily__c, Product2Id, LineNumber, BusinessUnit__c from QuoteLineItems Where  (LineNumber != null) ) From Quote Where Id In: ParentIds]); 

           if(Trigger.isInsert || Trigger.isUpdate ){ 
               for(Quote q : mapQuote.values()){
  
                   List<String> quoteLineItemProductFamList = new List<String>();
                   List<String> quoteLineItemBUList = new List<String>();
                   Set<String> qliProdFamSet = new Set<String>();
                   Set<String> qliBUSet = new Set<String>();
                   
                   for(QuoteLineItem qli: q.quotelineitems){
                       if(qli.LineNumber != null  ){
                       qliProdFamSet.add(qli.ProductFamily__c);
                       qliBUSet.add(qli.BusinessUnit__c);   
                       }
                        else if(qli.LineNumber == null ){
                          qliBUSet.remove(qli.BusinessUnit__c);
                          qliProdFamSet.remove(qli.ProductFamily__c);
                           }
                           
                   }
                       
                   
                   quoteLineItemProductFamList.addAll(qliProdFamSet);
                   quoteLineItemProductFamList.sort();
                   String productFamily = string.join(quoteLineItemProductFamList,', ' );
                   
                   quoteLineItemBUList.addAll(qliBUSet);
                   quoteLineItemBUList.sort();
                   String businessUnit = string.join(quoteLineItemBUList,', ' );
                   
                   if(q.RollupofProductFamilies__c != productFamily &&  q.ProductBusinessUnits__c != businessUnit ){
                       q.RollupofProductFamilies__c = productFamily;
                        q.ProductBusinessUnits__c = businessUnit;
                   quotesToUpdate.add(q);
                   }
                                     
               }
              //End of for loop above
               
               if(!quotesToUpdate.isEmpty()){
                   upsert quotesToUpdate;
               }
           }
         
                       }
  
            }




Test Class 

@isTest(SeeAllData = true)
public class QLITest {
    
          @isTest static void RollUpQLI(){
       List<QuoteLineItem> listQLI = new List<QuoteLineItem>();
       List<Quote> quotesToUpdate = new List<Quote>();
       Set<Id> ParentIds = new Set<Id>();
      
      
       //Insert product
       Product2 p = new Product2(Name = 'Test Name', BusinessUnit__c = 'CDS', ProductFamily__c = 'Communication Director');   
       insert p;
       //Insert pricebook
       Pricebook2 standardPricebook = new Pricebook2(Id = Test.getStandardPricebookId(), IsActive = true);
       update standardPricebook;
      // Id pricebookId = Test.getStandardPricebookId();
       
       PricebookEntry pbe1 = new PricebookEntry(Pricebook2id = standardPricebook.Id, Product2id=p.Id, isActive = true, unitPrice=100);
       insert pbe1;
              
        Opportunity o = new Opportunity(Pricebook2id = Test.getStandardPricebookId(), Name = 'Test Opp1', RollupofProductFamilies__c = 'Test', ProductBusinessUnits__c = 'Bed Stat', StageName ='Test Stage', CloseDate = date.today());
        insert o;  
        Quote q = new Quote(OpportunityId = o.Id, Name = 'Test Quote', Pricebook2Id = standardPricebook.Id);   
        insert q;
              
       QuoteLineItem oli = new QuoteLineItem(PricebookEntryid = pbe1.Id, ProductFamily__c = 'Bed Stat', QuoteId = q.Id, Product2Id = p.Id, Quantity = 1, UnitPrice = 1); 
       insert oli;
        listQLI.add(oli);
        upsert listQLI;
        ParentIds.add(oli.QuoteId);
        Map<Id, Quote> mapQuote = new Map<Id, Quote>([Select Id, BusinessUnit__c, ProductBusinessUnits__c, RollupofProductFamilies__c, (Select Id, QuoteId, Product2Id, LineNumber, ProductFamily__c,  BusinessUnit__c from QuoteLineItems ) From Quote Where Id In: ParentIds]);                                                   

        for(Quote quote: mapQuote.values()){
             List<String> qliProdFamList = new List<String>();
             Set<String> qlitProdFamSet = new Set<String>();
             Set<String> qlitBUset = new Set<String>();
             List<String> qliBUList = new List<String>();
              for(QuoteLineItem ql: quote.QuoteLineItems){
                       
                       qlitProdFamSet.add(ql.ProductFamily__c);
                       qlitBUset.add(ql.BusinessUnit__c);

                   }
                   qliProdFamList.addAll(qlitProdFamSet);
                   qliProdFamList.sort();
                   String productFamily = string.join(qliProdFamList,', ' );
            
                   qliBUList.addAll(qlitBUset);
                   qliBUList.sort();
                   String bizUnit = string.join(qliBUList,', ' );
            if(quote.RollupofProductFamilies__c != productFamily && quote.BusinessUnit__c != bizUnit){
                 quote.RollupofProductFamilies__c = productFamily;
                 quote.ProductBusinessUnits__c = bizUnit;
                   quotesToUpdate.add(quote);
                   }
        }
        upsert quotesToUpdate;
             
        
        test.startTest();
    //    if(quotesToUpdate.size()>0 && listQLI.size()>0){
         
         QuoteRollupPFBU.updateQuote(listQLI);
  //      }
        test.stopTest();
       
    }
    
    


}


Trigger

trigger PrimaryQliTrigger on QuoteLineItem (before insert, before update, after insert, after update, before delete, after delete) {
    
        if(Trigger.isBefore){
        if(Trigger.isInsert){   
        }
        if(Trigger.isUpdate){
                    }
        if(Trigger.isDelete){
                    }
    }
    
 if(Trigger.isAfter){
        if(Trigger.isInsert){ 
             QuoteRollupPFBU.updateQuote(trigger.new);
        }
       if(Trigger.isUpdate || Trigger.isInsert ){
       //    QuoteRollupPFBU.updateQuote(trigger.new);
                    }
        if(Trigger.isDelete){
                    }
    }    


    
    

}

 
  • May 22, 2019
  • Like
  • 0
i get that error on automated record creation

Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one.


This is trigger code
trigger MaintenanceRequest on Case (before update, after update) {
    // call MaintenanceRequestHelper.updateWorkOrders  
    if(Trigger.isUpdate)
    {
       MaintenanceRequestHelper.updateWorkOrders(trigger.new , trigger.oldmap); 
    }
    
}

And trigger helper class
 
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(list<case> triggerlist,map<id,case> triggermap){
        // update workorders
        list<case> FutureMaintenanceList = new list<case>();
        list<product2> prdlst = new list<product2>();
         try
         {
            prdlst =new list<product2>([SELECT Cost__c,Id,IsActive,Lifespan_Months__c,Maintenance_Cycle__c,Name,ProductCode,Replacement_Part__c FROM Product2]);
        	}
        catch(exception e)
        {
            System.debug('Error Caught !!! '+e.getMessage());
        }
        map<id,product2>  equipment = new map<id,product2>(prdlst);
        
        for(case cs:triggerlist)
        {
            if(triggermap.get(cs.id).status != 'closed' && cs.Status == 'closed')
            {
                    case NewMaintenance = new case();
                    date Todaydate = date.today();
             	    NewMaintenance.AccountId = cs.AccountId;
              	    NewMaintenance.ContactId = cs.ContactId;
              	    NewMaintenance.AssetId = cs.AssetId;
                    NewMaintenance.Subject ='Vehicle '+cs.Vehicle__c+' future Maintenance ';
                    NewMaintenance.Vehicle__c=cs.Vehicle__c;
                 	NewMaintenance.Date_Reported__c= Todaydate ;
                 	NewMaintenance.Equipment__c = cs.Equipment__c;
                    NewMaintenance.Type = 'Routine Maintenance';
                    NewMaintenance.Status = 'New';
                    NewMaintenance.Origin =cs.Origin;
                    NewMaintenance.Date_Due__c=Todaydate.adddays(integer.valueOf(math.round(equipment.get(cs.Equipment__c).Maintenance_Cycle__c)));
                    FutureMaintenanceList.add(NewMaintenance);
                integer x =integer.valueOf(math.round(equipment.get(cs.Equipment__c).Maintenance_Cycle__c));
                system.debug('value--'+x);
            }
        }
        system.debug('FutureMaintenanceList--'+FutureMaintenanceList);
        if(FutureMaintenanceList.size() >0)
        {
          insert FutureMaintenanceList;  
        }
       
    }        
    
}
Can any one tell me what i doing wrong.
Thank You

​​​​​​​
I am new to salesforce and getting below mentioned exception in one of the query :-

public static void buildPartnerTeam (list<SObject> objects)
    {
        FINAL list<String> roleNames = new list<String>
        {
            'Account Partner',
            'Account Partner Parent',
            'Account Partner Manager To Self',
            'Account Partner User To Self',
            'Account Partner Manager',  
            'Account Master Agent',  //  jul 17
            'Account- Sub Agent Super User Access Customer (Authorized)',  //  jul 17
            'Account- Sub Agent Super User Access to Prospect or Customer (Unauthorized)', //  jul 17
            'Account Related Partner Contact' //  MO-66
        };

        list<Partner_Team_Member__c> ptmsToInsert = new list<Partner_Team_Member__c>{};
        map<Id,Account> partnerAccountsMap = new map<Id,Account>{};
        list<Id> partnerAccountIds = new list<Id>{};

        list<Partner_Team_Role__c> partnerTeamRoles = TransactionSupport.getPartnerTeamRoles (roleNames);

//        list<Partner_Team_Role__c> partnerTeamRoles = [SELECT Id, Unique_Name__c FROM Partner_Team_Role__c WHERE Unique_Name__c IN :roleNames];

        list<Id> accountIds = new list<Id>{};

        for (SObject o : objects)
        {
            if (o.get('Partner_Account__c') != null) partnerAccountIds.add ((Id) o.get('Partner_Account__c'));
            if (o.get('CSD_MA__c') != null) partnerAccountIds.add ((Id) o.get('CSD_MA__c'));
            if (o.get('Partner_Of_Record_Cloud__c') != null) partnerAccountIds.add ((Id) o.get('Partner_Of_Record_Cloud__c'));
            accountids.add (o.Id);
        }

        // MO-66: get AccountContactRelations
        map<Id,Account> accountsWithACRsMap = new map<Id,Account>([SELECT Id,(SELECT Id, ContactId, AccountId FROM AccountContactRelations)
                                FROM Account WHERE Id IN :accountIds]);  //This is line where I am getting this error 

       // system.debug('&&&'+accountsWithACRsMap);
        map<Id,Id> contactToUserIdsMap = new map<Id,Id>{};
        set<Id> contactIds = new set<Id>{};
           // list<Account> acc = [SELECT Id,(SELECT Id, ContactId, AccountId FROM AccountContactRelations)
                               // FROM Account WHERE Id IN :accountIds];
           //  accId = accountsWithACRsMap.values();
           
        /*   for(Account acct : acc) {
                                    system.debug('&&&'+acct);
               
                                    integer count=0;
                                    for (AccountContactRelation acr : acct.AccountContactRelations)
            {
                count++;
                if (acr.AccountId != acct.Id) contactIds.add (acr.ContactId);
            }
                                    
                                }  */
            
        for (Account a : accountsWithACRsMap.values())
        {
            for (AccountContactRelation acr : a.AccountContactRelations)
            {
                if (acr.AccountId != a.Id) contactIds.add (acr.ContactId);
            }
        } 
        
      /*  for (Account a : acc)
        {
            
            for (AccountContactRelation acr : a.AccountContactRelations)
            {
                if (acr.AccountId != a.Id) contactIds.add (acr.ContactId);
            }
        } */

        //  MO-66: build map for Contact Id to User Id, for all AccountContactRelation records 

        for (User u : [SELECT Id, ContactId FROM User WHERE ContactId IN :contactIds])
        {
            contactToUserIdsMap.put (u.ContactId, u.Id);
        }

        //  now add partner team members

        for (Account a : [SELECT Id, Type, Partner_Account__c, ParentId, Partner_Type__c,
                            Sub_Agent_Authorized_to_access_cases__c 
                            FROM Account 
                            WHERE Id IN :partnerAccountIds])
        {
            partnerAccountsMap.put (a.Id, a);
        }
        
        for (SObject o : objects)
        {
            for (Partner_Team_Role__c ptr : partnerTeamRoles)
            {
                if (ptr.Unique_Name__c == roleNames[0] ||    //  'Account Partner'
                        ptr.Unique_Name__c == roleNames[4])  //  'Account Partner Manager'
                {
                    Id lookupId = (Id) o.get ('Partner_Account__c');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }

                    lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c != 'Sub-Agent')  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }

                if (ptr.Unique_Name__c == roleNames[1])  // 'Account Partner Parent'
                {
                    Account a = partnerAccountsMap.get ((Id) o.get ('Partner_Account__c'));
          
                    if (a != null)
                    {
                        if (a.Partner_Account__c != null)
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                          Partner_Account__c = a.Partner_Account__c,
                                          Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }

                        if (a.ParentId != null)
                        {   
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                          Partner_Account__c = a.ParentId,
                                          Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }

                    Id lookupId = (Id) o.get ('ParentId');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }
                }

                // 'Account Partner Manager To Self' or 'Account Partner User To Self'

                if ((String) o.get('Type') == 'Partner' && (ptr.Unique_Name__c == roleNames[2] || ptr.Unique_Name__c == roleNames[3]))  
                {
                    Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = o.Id,
                                        Reason__c = 'Automatic');
                    ptm.put ('Account__c', o.Id);
                    ptmsToInsert.add (ptm);            
                }

                if (ptr.Unique_Name__c == roleNames[5])   //  'Account Master Agent'  //  Jul 17
                {
                    Id lookupId = (Id) o.get ('CSD_MA__c');
          
                    if (lookupId != null)
                    {
                        Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                        Partner_Account__c = lookupId,
                                        Reason__c = 'Automatic');
                        ptm.put ('Account__c', o.Id);
                        ptmsToInsert.add (ptm);
                    }
                }

                if (ptr.Unique_Name__c == roleNames[6])   //  'Account- Sub Agent Super User Access Customer (Authorized)'  // Jul 17
                {
                    Id lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c == 'Sub-Agent' && 
                                partnerAccount.Sub_Agent_Authorized_to_access_cases__c == true)  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }

                }

                if (ptr.Unique_Name__c == roleNames[7])   //  'Account- Sub Agent Super User Access to Prospect or Customer (Unauthorized)' //  jul 17
                {
                    Id lookupId = (Id) o.get ('Partner_Of_Record_Cloud__c');
          
                    if (lookupId != null)
                    {
                        Account partnerAccount = partnerAccountsMap.get (lookupId);

                        if (partnerAccount.Partner_Type__c == 'Sub-Agent' && 
                                partnerAccount.Sub_Agent_Authorized_to_access_cases__c == false)  //  jul 17
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_Account__c = lookupId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }

                //  MO-66: Add PTMs for all Related Contacts

                if (ptr.Unique_Name__c == roleNames[8])   //  'Account Related Partner Contact'
                                {
                     Account accountWithACRs = accountsWithACRsMap.get (o.Id);
                   // Account accountWithACRs = acc.Id;

                    for (AccountContactRelation acr : accountWithACRs.AccountContactRelations)
                    {
                        Id userId = contactToUserIdsMap.get (acr.ContactId);

                        if (userId != null)
                        {
                            Partner_Team_Member__c ptm = new Partner_Team_Member__c (Partner_Team_Role__c = ptr.Id,
                                            Partner_User__c = userId,
                                            Reason__c = 'Automatic');
                            ptm.put ('Account__c', o.Id);
                            ptmsToInsert.add (ptm);
                        }
                    }
                }
            }
        }
        insert ptmsToInsert;
    }


Any help would be appreciated 
 
Hi,

I am having a massive confusion,

We have a database of 400,000 records.. which calls for duplication.

I want to check if alternate phone number of any of the account matches with the Primary phone number of any of the account, If it does, there is a checkbox  called "Marked For deletion"  m that checkbox should get selected and primary phone number of that account should become the alternate phone number of the acount against which it has matched 

So lets say ,

Accoount : A  Primary No : 1234  Secondary No : 5678

Accoount : B  Primary No : 9241  Secondary No : 1234 

Accoount : C  Primary No : 9241  Secondary No :  1234

Account B and Account C should have marked for deletion checked.
and Account B's primary phone number should become Secondary phone number of Account A. 

Please help me in achieving this 
 
trigger updateborrowerinbucket1 on Account (after insert, after update) {

set<id> setid = new set<id>();
list<bucket1__C> bucketlist = new list<bucket1__C>();

for(Account a : trigger.new){
setid.add(a.Bucket_1__c);

}

for(bucket1__c bb : [select id,Borrower_Name__c,(select id, name, Mobile_Number__c from Accounts__r)from bucket1__C]){

for(bucket1__C bb5 : bb.Accounts__r){
bucket1__C bb2 = new bucket1__C();
bb2.id=bb.id;
bb2.count_of_patients__c=bb.Accounts__r.size();
bb2.Borrower_Name__c=bb.Name;

bucketlist.add(bb2);
}
}

update bucketlist;
}
  • May 25, 2019
  • Like
  • 0
Help to solve this please: Illegal assignment from Decimal to String at line 34 column 4 in the test class
public with sharing class InventorySearchController { 
public list <Articles_Containers__c> inventoryItem {get;set;} 
public string searchstring {get;set;} 
public InventorySearchController( ) { 
} 
public void search(){ 
string searchquery= 'select Name , FFP_Centers__c,Prod__c, UM__c, Container__c, Number__c, On_Hand__c,  Pending__c,  Available__c, Purpose__c, Condition__c, Age__c, Comments__c FROM Articles_Containers__c  WHERE Prod__c like \'%'+searchstring+'%\'  AND On_Hand__c >0  AND IsOpened__c = 1  ORDER BY FFP_Centers__c, Prod__c,UM__c Number__c Limi 1000';
     
      inventoryItem= Database.query(searchquery); 

}
public void clear(){ 
inventoryItem.clear(); 
} 
}


@isTest
private class InventorySearchController_Test{
  @testSetup
  static void setupTestData(){
     test.startTest();
    Account pa = new Account(Name ='test Account parent', Representant__c ='hkjlhjd', 
    Distribution_Center__c='CRD Cayes', Class__c = 'Clinic', Type = 'CLINICS', 
    Departement__c = 'NORD', Address__c ='Test Address');
    insert pa;
    
          Product2 p = new Product2(Name ='TestProduct'); 
          insert p;
          Container_Shipper__c cs =new Container_Shipper__c(Name = 'Test Shipper');
          insert cs;
    Container__c container_Obj = new Container__c(Provenance__c = 'FFP FLORIDA', Distribution_Center__c= pa.id, Statut__c = 'Open',  FFP_Centers__c = 'FFP Caracole', 
     RecordTypeId='0126A000000nMlU',  Shipper__c=cs.Id );
    Insert container_Obj; 
    Articles_Containers__c articles_containers_Obj = new Articles_Containers__c(Container__c = container_Obj.id, Number__c = 17, UM__c = 'BAG(S)' ,  Local_ID__c = 7888, Product__c=p.ID,
            Comments__c = 'UNIT(S)',
           Purpose__c='Consignment',
            Condition__c= 'New',
           FFP_Centers__c = 'FFP Caracole'
            );
    Insert articles_containers_Obj; 
    test.stopTest();
  }
  static testMethod void test_search_UseCase1(){
    List<Container__c> container_Obj  =  [SELECT Provenance__c,Statut__c,Is_Reported__c,FFP_Centers__c  from Container__c];
    System.assertEquals(true,container_Obj.size()>0);
    List<Articles_Containers__c> articles_containers_Obj  =  [SELECT Container__c,Number__c,UM__c from Articles_Containers__c];
    System.assertEquals(true,articles_containers_Obj.size()>0);
    InventorySearchController obj01 = new InventorySearchController();
    obj01.inventoryItem = articles_containers_Obj;
 //Illegal assignment from Decimal to String at line 34 column 4      
obj01.searchstring =  articles_containers_Obj[0].Number__c;
    obj01.search();
  }
  static testMethod void test_clear_UseCase1(){
    List<Container__c> container_Obj  =  [SELECT Provenance__c,Statut__c,Is_Reported__c,FFP_Centers__c from Container__c];
    System.assertEquals(true,container_Obj.size()>0);
    List<Articles_Containers__c> articles_containers_Obj  =  [SELECT Container__c,Number__c,UM__c from Articles_Containers__c];
    System.assertEquals(true,articles_containers_Obj.size()>0);
    InventorySearchController obj01 = new InventorySearchController();
    obj01.inventoryItem = articles_containers_Obj;
   // obj01.searchstring = articles_containers_Obj[0].Number__c;
    obj01.clear();
  }
}

 
I followed the tutorial here (https://trailhead.salesforce.com/content/learn/modules/api_basics/api_basics_bulk?trail_id=force_com_dev_intermediate) but couldnt pass because I can only inject 100 users a time. I checked the failedResult User-added image
looks like it use SOQL for each individual record, I must did something wrong?
I am trying to build a custom component using <aura:iteration>  and add the rowaction "Add" and "View" ,which will take the user to "Add New Campaign member" and 'View related Campaign Member " respectively for each campaign record. Something like this -

User-added image
Server Side Controller :-

public class MarketingCampaignController {
    @AuraEnabled
    public static List<Campaign> CampaignsSOQL(string searchString) {
        String queryString = 'Select id, name,type,status from Campaign ';
        if(searchString!=null && searchString!=''){
            searchString = '%'+string.escapeSingleQuotes(searchString)+'%'; 
            queryString = queryString+ 'where Name Like:searchString';
        }
        queryString = queryString + ' Limit 10000';
        List<Campaign> campList = database.query(queryString);
        
        return campList;
    }
}

Component :-

<aura:component controller="MarketingCampaignController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name="campList" type="Object"/>
     <aura:attribute name="accSearchValue" type="String" default=""/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <div class="slds-card">
        <div class="slds-card__header slds-grid">
            <header class="slds-media slds-media_center slds-has-flexi-truncate">
                <div class="slds-media__figure">
                    <lightning:Icon iconName="standard:account"  size="Medium" 
                             class="slds-icon slds-input__icon slds-input__icon_right " />
                </div>
                <div class="slds-media__body">
                    <h2><span class="slds-text-heading_medium">Marketing Campaigns</span></h2>
                </div>
            </header>
            <div class="slds-no-flex">
                <div class="slds-form-element__control slds-input-has-icon slds-input-has-icon_right">
                    <lightning:input value="{!v.accSearchValue}" placeholder="Search" type="text" label="" name="Campaign Search" onchange="{!c.doInit}"/>
                </div>        
            </div>
        </div>
        
        <table class="slds-table slds-table_bordered slds-table_cell-buffer">       
    <thead>
        <tr class="slds-text-title_caps"> 
            <th scope="col">
                <div class="slds-truncate" title="Name"></div>
            </th>
            <th scope="col">
                <div class="slds-truncate" title="Name"></div>
            </th>           
           <th scope="col">
                <div class="slds-truncate" title="Name">Name</div>
            </th>       
            <th scope="col">
                <div class="slds-truncate" title="Approver">Type</div>
            </th>
            <th scope="col">
                <div class="slds-truncate" title="Approver">StartDate</div>
            </th>
            <th scope="col">
                <div class="slds-truncate" title="Approver">Status</div>
            </th>   
        </tr>
    </thead>
    <tbody> 
        <!--### display all records of searchResult attribute by aura:iteration ###-->
        <aura:iteration items="{!v.campList}" var="camp" indexVar="count" >
            <tr>
                <td>
            {!count + 1}
        </td>       
           <td>
                 <div class="slds-align_absolute-center slds-p-top_small">
                <lightning:button variant="success"  label="View" title="Brand action" onclick="{!c.view}" />
            &nbsp;&nbsp;<lightning:button variant="success" label="Add" title="Brand action" onclick="{!c.Add}" />
            </div>
                </td>
               <td >
                    <div class="slds-truncate">{!camp.Name}</div>
                </td>
                
                <td>
                    <div class="slds-truncate">{!camp.Type}</div>
                </td>
                <td >
                    <div class="slds-truncate">{!camp.StartDate}</div>
                </td>
                <td>
                    <div class="slds-truncate">{!camp.Status}</div>
                </td> 
            </tr>
        </aura:iteration>     
    </tbody>
</table>
        </div>
        <footer class="slds-card__footer"></footer>              
</aura:component>


How to implement those Rowaction buttons ? Kindly help.
Hello,
My trigger :

trigger stopTaskDelete on Task (before delete) {
    Id profileid = Userinfo.getProfileId();
    profile profilename = [select Name from Profile where id=:profileid];
    for(Task T1:Trigger.old){
        if(profilename.Name != 'System Administrator'){
            T1.adderror('You can not delete task');
        }
    }
}

How can I make this trigger work via Handler class? and how do I write test class for this?
i get that error on automated record creation

Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one.


This is trigger code
trigger MaintenanceRequest on Case (before update, after update) {
    // call MaintenanceRequestHelper.updateWorkOrders  
    if(Trigger.isUpdate)
    {
       MaintenanceRequestHelper.updateWorkOrders(trigger.new , trigger.oldmap); 
    }
    
}

And trigger helper class
 
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(list<case> triggerlist,map<id,case> triggermap){
        // update workorders
        list<case> FutureMaintenanceList = new list<case>();
        list<product2> prdlst = new list<product2>();
         try
         {
            prdlst =new list<product2>([SELECT Cost__c,Id,IsActive,Lifespan_Months__c,Maintenance_Cycle__c,Name,ProductCode,Replacement_Part__c FROM Product2]);
        	}
        catch(exception e)
        {
            System.debug('Error Caught !!! '+e.getMessage());
        }
        map<id,product2>  equipment = new map<id,product2>(prdlst);
        
        for(case cs:triggerlist)
        {
            if(triggermap.get(cs.id).status != 'closed' && cs.Status == 'closed')
            {
                    case NewMaintenance = new case();
                    date Todaydate = date.today();
             	    NewMaintenance.AccountId = cs.AccountId;
              	    NewMaintenance.ContactId = cs.ContactId;
              	    NewMaintenance.AssetId = cs.AssetId;
                    NewMaintenance.Subject ='Vehicle '+cs.Vehicle__c+' future Maintenance ';
                    NewMaintenance.Vehicle__c=cs.Vehicle__c;
                 	NewMaintenance.Date_Reported__c= Todaydate ;
                 	NewMaintenance.Equipment__c = cs.Equipment__c;
                    NewMaintenance.Type = 'Routine Maintenance';
                    NewMaintenance.Status = 'New';
                    NewMaintenance.Origin =cs.Origin;
                    NewMaintenance.Date_Due__c=Todaydate.adddays(integer.valueOf(math.round(equipment.get(cs.Equipment__c).Maintenance_Cycle__c)));
                    FutureMaintenanceList.add(NewMaintenance);
                integer x =integer.valueOf(math.round(equipment.get(cs.Equipment__c).Maintenance_Cycle__c));
                system.debug('value--'+x);
            }
        }
        system.debug('FutureMaintenanceList--'+FutureMaintenanceList);
        if(FutureMaintenanceList.size() >0)
        {
          insert FutureMaintenanceList;  
        }
       
    }        
    
}
Can any one tell me what i doing wrong.
Thank You

​​​​​​​
Hi,
We have one bulkified trigger on custom object.
i want to use that same trigger to update all the records in the system, how can i execute the trigger which will update 1000 records in the system.
Thanks. 
I have the following code where you are sending the payments of the invoices to all contacts associated with the account, is there any way to bring the contact that is associated with the invoice ???


                List<Contact> listofContacts = [SELECT Email FROM Contact where AccountId = :accId and Email != null];
                String[] toRecipients = new List<String> ();

                Integer count = 0;
                for (Contact oneContact : listofContacts)
                {
                    if (count > 0)
                    toRecipients.add(oneContact.Email);
                    count++;
                }

                Id orgWide = [SELECT Id FROM OrgWideEmailAddress limit 1].id;
When a user is passing 2 character in search box, if he types 2 characters in the field , The user display result should be Exact match (Starts with 2 characters) and after that the value of other values that can match(Contains with 2 characters).
 
Hello, I'm trying to create a test class for inserting/updating quote products. When I try to run a test class I get the error: System.NullPointerException: Attempt to de-reference a null object. The stack trace is Class.QuoteRollupPFBU.updateQuote: line 17, column 1
Class.QLITest.RollUpQLI: line 63, column 1. I thought I initalized all of the variables, but feel free to let me know if you see any errors in my code. Thank you. 
 
Class 

public class QuoteRollupPFBU {
    
       public QuoteRollupPFBU(){
      List<Quote> quotesToUpdate = new List<Quote>();
      List<QuoteLineItem> quoteLineItemToUpdate;
      quoteLineItemToUpdate = new List<QuoteLineItem>();
    }
        public static void updateQuote(List<SObject> quoteLineItemToUpdate){
            List<Quote> quotesToUpdate = new List<Quote>();
            Set<String> setQuoteProdsToRemove = new  Set<String>();
            List<String> listQuoteProdsToRemove = new List<String>();
            Set<Id> ParentIds = new Set<Id>();
            for(QuoteLineItem qProduct: (List<QuoteLineItem>)quoteLineItemToUpdate){
                System.debug( 'value :' + quoteLineItemToUpdate);
                ParentIds.add(qProduct.QuoteId); 
            }                                            
            Map<Id, Quote> mapQuote = new Map<Id, Quote>([Select Id, ProductBusinessUnits__c, RollupofProductFamilies__c,  (Select Id, QuoteId, ProductFamily__c, Product2Id, LineNumber, BusinessUnit__c from QuoteLineItems Where  (LineNumber != null) ) From Quote Where Id In: ParentIds]); 

           if(Trigger.isInsert || Trigger.isUpdate ){ 
               for(Quote q : mapQuote.values()){
  
                   List<String> quoteLineItemProductFamList = new List<String>();
                   List<String> quoteLineItemBUList = new List<String>();
                   Set<String> qliProdFamSet = new Set<String>();
                   Set<String> qliBUSet = new Set<String>();
                   
                   for(QuoteLineItem qli: q.quotelineitems){
                       if(qli.LineNumber != null  ){
                       qliProdFamSet.add(qli.ProductFamily__c);
                       qliBUSet.add(qli.BusinessUnit__c);   
                       }
                        else if(qli.LineNumber == null ){
                          qliBUSet.remove(qli.BusinessUnit__c);
                          qliProdFamSet.remove(qli.ProductFamily__c);
                           }
                           
                   }
                       
                   
                   quoteLineItemProductFamList.addAll(qliProdFamSet);
                   quoteLineItemProductFamList.sort();
                   String productFamily = string.join(quoteLineItemProductFamList,', ' );
                   
                   quoteLineItemBUList.addAll(qliBUSet);
                   quoteLineItemBUList.sort();
                   String businessUnit = string.join(quoteLineItemBUList,', ' );
                   
                   if(q.RollupofProductFamilies__c != productFamily &&  q.ProductBusinessUnits__c != businessUnit ){
                       q.RollupofProductFamilies__c = productFamily;
                        q.ProductBusinessUnits__c = businessUnit;
                   quotesToUpdate.add(q);
                   }
                                     
               }
              //End of for loop above
               
               if(!quotesToUpdate.isEmpty()){
                   upsert quotesToUpdate;
               }
           }
         
                       }
  
            }




Test Class 

@isTest(SeeAllData = true)
public class QLITest {
    
          @isTest static void RollUpQLI(){
       List<QuoteLineItem> listQLI = new List<QuoteLineItem>();
       List<Quote> quotesToUpdate = new List<Quote>();
       Set<Id> ParentIds = new Set<Id>();
      
      
       //Insert product
       Product2 p = new Product2(Name = 'Test Name', BusinessUnit__c = 'CDS', ProductFamily__c = 'Communication Director');   
       insert p;
       //Insert pricebook
       Pricebook2 standardPricebook = new Pricebook2(Id = Test.getStandardPricebookId(), IsActive = true);
       update standardPricebook;
      // Id pricebookId = Test.getStandardPricebookId();
       
       PricebookEntry pbe1 = new PricebookEntry(Pricebook2id = standardPricebook.Id, Product2id=p.Id, isActive = true, unitPrice=100);
       insert pbe1;
              
        Opportunity o = new Opportunity(Pricebook2id = Test.getStandardPricebookId(), Name = 'Test Opp1', RollupofProductFamilies__c = 'Test', ProductBusinessUnits__c = 'Bed Stat', StageName ='Test Stage', CloseDate = date.today());
        insert o;  
        Quote q = new Quote(OpportunityId = o.Id, Name = 'Test Quote', Pricebook2Id = standardPricebook.Id);   
        insert q;
              
       QuoteLineItem oli = new QuoteLineItem(PricebookEntryid = pbe1.Id, ProductFamily__c = 'Bed Stat', QuoteId = q.Id, Product2Id = p.Id, Quantity = 1, UnitPrice = 1); 
       insert oli;
        listQLI.add(oli);
        upsert listQLI;
        ParentIds.add(oli.QuoteId);
        Map<Id, Quote> mapQuote = new Map<Id, Quote>([Select Id, BusinessUnit__c, ProductBusinessUnits__c, RollupofProductFamilies__c, (Select Id, QuoteId, Product2Id, LineNumber, ProductFamily__c,  BusinessUnit__c from QuoteLineItems ) From Quote Where Id In: ParentIds]);                                                   

        for(Quote quote: mapQuote.values()){
             List<String> qliProdFamList = new List<String>();
             Set<String> qlitProdFamSet = new Set<String>();
             Set<String> qlitBUset = new Set<String>();
             List<String> qliBUList = new List<String>();
              for(QuoteLineItem ql: quote.QuoteLineItems){
                       
                       qlitProdFamSet.add(ql.ProductFamily__c);
                       qlitBUset.add(ql.BusinessUnit__c);

                   }
                   qliProdFamList.addAll(qlitProdFamSet);
                   qliProdFamList.sort();
                   String productFamily = string.join(qliProdFamList,', ' );
            
                   qliBUList.addAll(qlitBUset);
                   qliBUList.sort();
                   String bizUnit = string.join(qliBUList,', ' );
            if(quote.RollupofProductFamilies__c != productFamily && quote.BusinessUnit__c != bizUnit){
                 quote.RollupofProductFamilies__c = productFamily;
                 quote.ProductBusinessUnits__c = bizUnit;
                   quotesToUpdate.add(quote);
                   }
        }
        upsert quotesToUpdate;
             
        
        test.startTest();
    //    if(quotesToUpdate.size()>0 && listQLI.size()>0){
         
         QuoteRollupPFBU.updateQuote(listQLI);
  //      }
        test.stopTest();
       
    }
    
    


}


Trigger

trigger PrimaryQliTrigger on QuoteLineItem (before insert, before update, after insert, after update, before delete, after delete) {
    
        if(Trigger.isBefore){
        if(Trigger.isInsert){   
        }
        if(Trigger.isUpdate){
                    }
        if(Trigger.isDelete){
                    }
    }
    
 if(Trigger.isAfter){
        if(Trigger.isInsert){ 
             QuoteRollupPFBU.updateQuote(trigger.new);
        }
       if(Trigger.isUpdate || Trigger.isInsert ){
       //    QuoteRollupPFBU.updateQuote(trigger.new);
                    }
        if(Trigger.isDelete){
                    }
    }    


    
    

}

 
  • May 22, 2019
  • Like
  • 0
The System.AssertEqual (); is not returning a PASS in my Apex Test Class.
This is because, the field EmailMessage.HasAttachment (standard field) is not being updated to True by Salesforce (this is a protected Read-Only field of Salesforce).

Here is my apex test class:
@isTest static void insertingEmailMssgWithAttachment() {
        Case c = new Case();
        c.Subject = 'Caso de ejemplo';
        c.Status = 'New';
        c.Origin = 'Phone';
        c.Hidden_Has_Attachment__c = FALSE;
        insert c;
        
        EmailMessage e = new EmailMessage();
        e.Subject = 'Email de ejemplo';
        e.ParentId = c.Id;
        insert e;
        
        Attachment a = new Attachment();
        a.Name = 'Adjunto de ejemplo';
        a.ParentId = e.Id;
        Blob b = blob.valueOf('test');
        a.Body = b;
        insert a;
        
        EmailMessage myEmailMssg = [SELECT Id, HasAttachment FROM EmailMessage];
        System.debug('FROM Test Class HasAttachmentCaseEmail_Test - Display myEmailMssg: '+myEmailMssg);
        System.assertEquals(True, myEmailMssg.HasAttachment, 'Error mssg: The outcome should be True but its not');
        
        Case myCase = [SELECT Id, Hidden_Has_Attachment__c FROM Case];
        System.assertEquals(True, myCase.Hidden_Has_Attachment__c, 'Error mssg: The HiddenHasAttachment field should be True but its not');
    }

The following apex trigger contains an if condition:
if(em.HasAttachment == TRUE) {...code...}

and unfortunately, when running the test class, it is not running the code depending on that if condition.
 
Set<Id> emailIds        = new Set<Id>();
.....

        //==> Verify if EmailMessage has a child Attachment & if its parentId is of Type Case
        for (EmailMessage em : trigger.new){
            System.debug('FROM: EmailMessageTrigger - 2ondtrigerNew: '+trigger.new);
            if(em.ParentId.getSobjectType() == Case.SobjectType) {
                System.debug('FROM: EmailMessageTrigger - ParentId is SobjectType = True?-->Yes!');
                if(em.HasAttachment == TRUE){
                    System.debug('FROM: EmailMessageTrigger - Email HasAttachment field = TRUE? --> Yes!');
                    emailIds.add(em.Id); 
                }
            }
        }
          System.debug('FROM: EmailMessageTrigger - set of all inserted/updated emails: '+emailIds);
When doing manual tests of this functionality (adding an Attachment to the EmailMessage attached to a Case), such manual test works correctly (it passes OK).

Can you possibly help?

Thank you very much.
 
We have to a update child account depending on parent account. We have the same record type for both the accounts. When a checkbox called "entity" is checked, and a look up field called parent account is filled, that account is considered a child account. Whenever a new address is added or edited on the parent account, the same should flow on child account in the same field of address.
We have to write a trigger for the same
class:
global class ICC_ReminderEmails implements Database.Batchable<sObject>{
    
    
     global list<ICCWorkbench__c> start(Database.BatchableContext BC){
        return [select id,name,Organization_ID__c,Vendor_Name__r.name,Vendor_Name__r.Email__c,Vendor_Name__r.Email1__c,Vendor_Name__r.Email2__c,Vendor_Name__r.Group_Email__c,MppsubmittDate__c,CreatedDate from ICCWorkbench__c where Supplier_Status__c ='Submitted To Supplier' AND MppsubmittDate__c=Last_n_days:1];
   }

     global void execute(Database.BatchableContext BC, List<ICCWorkbench__c> scope){
        system.debug('Scope -->' + scope);
        List < Messaging.SingleEmailMessage > emails = new List < Messaging.SingleEmailMessage > ();
           
        for(ICCWorkbench__c wcb : scope){
                
                               List<String> emailAddress  = wcb.Vendor_Name__r.Group_Email__c.split(';'); 
                               System.debug(emailAddress);
                               if(wcb.Vendor_Name__r.Email__c != null)
                                emailAddress.add(wcb.Vendor_Name__r.Email__c);
                               if(wcb.Vendor_Name__r.Email1__c != null)
                                emailAddress.add(wcb.Vendor_Name__r.Email1__c);
                               if(wcb.Vendor_Name__r.Email2__c != null)
                                emailAddress.add(wcb.Vendor_Name__r.Email2__c);
                               Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                               email.setToAddresses(emailAddress);
                               email.setSubject('Reminder For Pending Po Acknowledge '); 
                               email.setPlainTextBody('Dear User,' +' '+
                                                                'Your PO Number '+' '+wcb.Name +' ' + 'Pending For Acknowledge if Already Acknowledge then Ignore  this Mail otherwise Submit it immedietly.');
                                                      
                               emails.add(email);
                               system.debug('List Of Emails -->' + emails);
            
           
          }
       Messaging.sendEmail(emails);
      }
    
    global void finish(Database.BatchableContext BC){
   }
}

test class:

@isTest
Public class TestICC_ReminderEmails {  
public static testMethod void TestRemindermails(){   

//LisT<ICCWorkbench__c>  query = [select id,name,Vendor_Name__c ,Organization_ID__c,Vendor_Name__r.name,Vendor_Name__r.Email__c,Vendor_Name__r.Email1__c,Vendor_Name__r.Email2__c,Vendor_Name__r.Group_Email__c,MppsubmittDate__c,CreatedDate from ICCWorkbench__c where Supplier_Status__c ='Submitted To Supplier' AND MppsubmittDate__c=Last_n_days:1];
RecordType rtvnd = [select id,Name from RecordType where Name='Vender'];
ICCOrganization__c org = new ICCOrganization__c();
org.RecordTypeID = rtvnd.id;
org.Name ='test3';
//org.CurrencyIsoCode='';
org.Email__c = 'surajdem@gmail.com';     
org.Email1__c='surajdem@gmail.com';
org.Email2__c ='harshard.pansare@zamilindustrial.com'; 
org.Group_Email__c='surajdem@gmail.com;harshad.pansare@zamilindustrial.com';
insert org;
System.debug(org);

RecordType rtvnd1 = [select id,Name from RecordType where Name ='Manual FPO'];    
ICCWorkbench__c wcb = new ICCWorkbench__c();
wcb.RecordTypeID = rtvnd1.id;
wcb.Vendor_Name__c=org.id;
wcb.Name='hchchchchchc2';
wcb.MppsubmittDate__c= Date.newInstance(2014,1,21);
wcb.Organization_ID__c= '82';
wcb.Supplier_Status__c = 'Submitted To Supplier';
//wcb.Vendor_Name__r.Email__c  = org.Email__c;
//wcb.Vendor_Name__r.Email1__c= org.Email1__c;
//wcb.Vendor_Name__r.Email2__c = org.Email2__c;
//wcb.Vendor_Name__r.Group_Email__c=org.Group_Email__c;

//wcb.CurrencyIsoCode = 'EUR-Euro';

insert wcb;
System.debug(wcb);

test.startTest();  

//initiating an instance of the batch job   
ICC_ReminderEmails b = new ICC_ReminderEmails();
Database.executeBatch(b);

test.stopTest();  


}
}