• Finney
  • NEWBIE
  • 255 Points
  • Member since 2011

  • Chatter
    Feed
  • 8
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 77
    Questions
  • 112
    Replies
Hi ,

I want to reallocate the account to a different user if the contract has expired and there is no new active contract on the account for 6 weeks starting from the Contract End Date of the recently expired contract. 

If an active contract is added between the 6 week period, for ex. 5 weeks after the contract end date of the recently expired contract, the reallocation should not happen. 

How can we achieve this, please?

Any help will be appreciated.

Thanks
 
  • December 11, 2017
  • Like
  • 0
The error is on line 40, column 1

I've marked the line BOLD.

Trigger SummingUpMonthlyValue On OTC_Contract_Product_Line_Items__c (After Insert, After Update, After Delete, After UnDelete){
    
    List<Id> accountManagerIds = New List<Id>();
    
    DateTime d = datetime.now();
    String monthName = d.format('MMMMM');
    System.debug('Current Month Name ****** ' + monthName);
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
         For(OTC_Contract_Product_Line_Items__c contr : Trigger.New){
             If(contr.Account_Manager__c != null){
                 accountManagerIds.add(contr.Account_Manager__c);
             }
         }   
    }
    
    If(Trigger.IsDelete){
        For(OTC_Contract_Product_Line_Items__c contr : Trigger.Old){
           If(contr.Account_Manager__c != null){
                 accountManagerIds.add(contr.Account_Manager__c);
             }
        }
    }
    
    Map<ID, Double > UserWithTotalInvoicevalue = New Map<ID, Double>();
    System.debug('-------------'+accountManagerIds);
    AggregateResult[] aggRes =  [Select Account_Manager__c,
                                        Sum(OTC_Unit_Price__c) sumac 
                                        FROM OTC_Contract_Product_Line_Items__c where Account_Manager__c = :accountManagerIds and OTC_Status__c = 'Active'
                                            Group by Account_Manager__c];//Invoice_Value_Current_Month__c
    System.debug('-------------------'+ aggRes);
    List<OTC_Contract_Product_Line_Items__c> cpliList = [Select Account_Manager__c,OTC_Unit_Price__c,OTC_Month__c,CreatedDate,OTC_Status__c,Month_Finance_Rev_Rec__c FROM OTC_Contract_Product_Line_Items__c where Account_Manager__c =:accountManagerIds and OTC_Status__c = 'Active'];
    Decimal monthlyAchieved = 0;
    Decimal DoubleUp = 0;
    Set<Id> idToSkip = new Set<Id>();
    Integer Month,Year;
    for(OTC_Contract_Product_Line_Items__c cpli: Trigger.New){
        Month = cpli.CreatedDate.month();
        Year = cpli.CreatedDate.Year();
        if( (cpli.Account_Manager__c != Trigger.oldMap.get(cpli.id).get('Account_Manager__c')) && (cpli.OTC_Status__c == 'Active') ){
            monthlyAchieved = monthlyAchieved + cpli.OTC_Unit_Price__c;
            idToSkip.add(cpli.id);
        }
    }
    for(OTC_Contract_Product_Line_Items__c cpli: cpliList){
        if(!idToSkip.contains(cpli.id)){
            if((cpli.CreatedDate.month() == Month) && (cpli.CreatedDate.year() == Year) && (cpli.OTC_Status__c == 'Active')  ){
                monthlyAchieved = monthlyAchieved + cpli.OTC_Unit_Price__c;
            }
        }
        if((cpli.OTC_Month__c.month() == Month-1) && (cpli.OTC_Status__c == 'Active') && (cpli.Month_Finance_Rev_Rec__c.month() == Month) ){
            DoubleUp = DoubleUp + cpli.OTC_Unit_Price__c;
        }
    }

    
    for(AggregateResult EveryAR : aggRes )
     {
         
         Id accountManagerId         = (Id)EveryAR.get('Account_Manager__c');
         Decimal TotalInvoiceValue   = (decimal)EveryAR.get('sumac');
         UserWithTotalInvoicevalue.put(accountManagerId ,TotalInvoiceValue);
     }    
     system.debug('-------'+ UserWithTotalInvoicevalue);
     List<Monthly_Target__c> targetFinalListToUpdate = New List<Monthly_Target__c>();
     
     For(Monthly_Target__c targ : [Select Id,No_of_Renewals__c, Portfolio_Total_Revenue__c, Active_Amount_Acheived__c, Monthly_Target_User__c, Start_Date__c
                                     FROM Monthly_Target__c WHERE Monthly_Target_User__c =: accountManagerIds LIMIT 1 ])
     {
         if( targ.Start_Date__c.month() == Month){
             targ.Portfolio_Total_Revenue__c = UserWithTotalInvoicevalue.get(targ.Monthly_Target_User__c);
             //targ.No_of_Renewals__c= UserWithTotalInvoicevalue.get(targ.Monthly_Target_User__c );
             targ.Active_Amount_Acheived__c = monthlyAchieved;
             targ.Double_Up_s_Current_Month__c = DoubleUp;
             targetFinalListToUpdate.add(targ);
         }
     }
     
     try{
         If(!targetFinalListToUpdate.IsEmpty()){
             update targetFinalListToUpdate;
         }
     }
     catch(Exception e){
         System.Debug('Thrown Exception for SummingUpInvoiceValue Trigger Is:: ' + e.getMessage());
     } 
     
    
}

Thanks in Advance.
Hi,

I have got a trigger that is as follows
  1. trigger UpdateTargets on Monthly_Target__c (before Insert,before update) {
  2. set<id> AMids=new set<id>();
  3. for(Monthly_Target__c tg:trigger.new)
  4. {
  5. AMids.add(tg.Monthly_Target_User__c);
  6. }
  7. Map<Id,decimal> AMTarget=new Map<Id,decimal>();
  8. aggregateResult[] aggRes=[Select Account_Manager__c,SUM(OTC_Unit_Price__c) sumac from OTC_Contract_Product_Line_Items__c where Account_Manager__c = : AMids AND OTC_Status__c= 'Active' Group by Account_Manager__c];
  9. for(aggregateResult ar:aggRes)
  10. {
  11. Id AM=(Id)ar.get('Account_Manager__c');
  12. double IV=(double)ar.get('sumac');
  13. AMTarget.put(AM,IV);
  14. }
  15. for(Monthly_Target__c tg:trigger.new)
  16. {
  17. tg.Portfolio_Total_Revenue__c=AMTarget.get(tg.Monthly_Target_User__c); 
  18. //tg.Active_Amount_Acheived__c=AMTarget.get(tg.Monthly_Target_User__c); 
  19. //tg.Portfolio_Total_Revenue__c=Integer.valueOf(ar.get('sumac');
  20. }
  21.  
  22. }


I have written a test class but the trigger is still showing 0% coverage.

I am unable to post the class here as it is too long.

Can anyone please help me with the test class?

Thanks
Hi,

I need help with pulling a field value on all contracts of a user to a custom Object.

The 2 objects here are
1) Contract - Standard object
2) Target - Custom Object.

Contract and Target object are not related to each other i.e. there is no lookup field for the Target object on the Contract Object.

There are 2 fields on the Contract object
a) Invoice Value - Currency
b) Account Manager - Lookup field to the user.

There are 2 fields on the Target object
a) Target Account Manager - Lookup field to the user.
b) Total Invoice Value - Should add up Invoice value of all Contracts under the Target Account Manager's name.

Any help would be greatly appreciated.

Thanks in advance.
I am getting an error on the following trigger.Will mark the error line in bold.
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) {

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    
   if((Trigger.isBefore && Trigger.isUpdate) || (Trigger.isBefore && Trigger.isUpdate) ){  
   
    for(Contract cont : Trigger.New){
        accountIds.add(cont.AccountId);
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
   
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_Emirates_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds LIMIT 1]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    if(contactIds.size() > 0) conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contact where Id = :contactIds]);
   
Hi , 

I am getting an error when trying to deploy a class to production.

The error is on line 10 of the trigger

Please find the trigger posted here.

This is the Trigger
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) {

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    for(Contract cont : Trigger.New){
        accountIds.add(cont.AccountId);
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_E_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_E_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    if(contactIds.size() > 0) conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_E_ID_Upload__c from Contact where Id = :contactIds]);
    
    for(Contract cont : Trigger.New){
        if(cont.Key_Contact__c != null && conMap.containsKey(cont.Key_Contact__c)){
            Contact con = conMap.get(cont.Key_Contact__c);
            cont.KeyContact_Email_id__c = con.Email;
            cont.KeyContact_MobileNumber__c = con.MobilePhone;
            cont.OTC_Key_Contact_Name__c = con.FirstName == null ? con.LastName : con.FirstName+' '+con.LastName;
            cont.KeyContact_Office__c = con.Phone;
            cont.E_ID_only_for_Jobs__c = con.OTC_E_ID_Upload__c;
            cont.OTC_Passport_Copy_Person_Signing_Cheque__c = con.Passport__c; 
        } else{
            if(accMap.get(cont.AccountId).IsPersonAccount == true){
                cont.KeyContact_Email_id__c = accMap.get(cont.AccountId).PersonEmail;
                cont.KeyContact_MobileNumber__c = accMap.get(cont.AccountId).PersonMobilePhone; 
                cont.OTC_Key_Contact_Name__c = accMap.get(cont.AccountId).Name;
                cont.KeyContact_Office__c = accMap.get(cont.AccountId).Phone;
                cont.OTC_Passport_Copy_Person_Signing_Cheque__c = accMap.get(cont.AccountId).Passport__pc;
                cont.E_ID_only_for_Jobs__c = accMap.get(cont.AccountId).OTC_E_ID_Upload__pc;
            }else if(accMap.get(cont.AccountId).Contacts.size()>0){
                cont.KeyContact_Email_id__c = accMap.get(cont.AccountId).Contacts[0].Email;
                cont.KeyContact_MobileNumber__c = accMap.get(cont.AccountId).Contacts[0].MobilePhone;
                cont.OTC_Key_Contact_Name__c = accMap.get(cont.AccountId).Contacts[0].FirstName == null ? accMap.get(cont.AccountId).Contacts[0].LastName : accMap.get(cont.AccountId).Contacts[0].FirstName+' '+accMap.get(cont.AccountId).Contacts[0].LastName;
                cont.KeyContact_Office__c = accMap.get(cont.AccountId).Contacts[0].Phone;
                cont.E_ID_only_for_Jobs__c = accMap.get(cont.AccountId).Contacts[0].OTC_E_ID_Upload__c;
                cont.OTC_Passport_Copy_Person_Signing_Cheque__c = accMap.get(cont.AccountId).Contacts[0].Passport__c;
            }
        }
    }

}
I have posted the class as a reply

Thanks
Hi,

I have the follwoing test class but its giving me an error when running a test.

Need your help on fixing it please

The error is 

Class.Test_SelectLineitemController.test_method_1: line 55, column 1


@istest
public class Test_SelectLineitemController {
    @testsetup static void setupData(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
        
        insert Test_cls_DCC_DFPDatafactory.getTestGoogleParametersList();
        
        Account acc = new account(name='testaccname');
        insert acc;
        List<Opportunity> lstopp = new List<Opportunity>();
        lstopp.add(Test_cls_DCC_DFPDatafactory.getTestOpportunity('Booking',100));
        lstopp.add(Test_cls_DCC_DFPDatafactory.getTestOpportunity('Proposal',30));
        lstopp[0].Is_Approved__c = true;
        lstopp[0].accountid = acc.id;
        insert lstopp;
        
         List<OpportunityLineItem> lstItems = new List<OpportunityLineItem>();
        lstItems.add(Test_cls_DCC_DFPDatafactory.getTestOpportunityLineItem(lstopp[0].id,'Test DFP Product',1));
        for(OpportunityLineItem Oli: lstItems){ //loop to the line items
        Oli.DFP_Id__c = string.valueof(system.now()).replaceAll('-', '').replaceAll(':', '').replaceAll(' ', '');
        Oli.DFP_External_Id__c = Oli.DFP_Id__c;
        Oli.Description = 'Test';
        Oli.Start_Date__c = System.Today();
        Oli.End_Date__c = System.Today() + 5;
        insert lstItems;
     }   
        insert Test_cls_DCC_DFPDatafactory.getTestDFPMapping();
        
    }
    
    
    static testMethod void test_method_1(){
        test.startTest();
        {
            SelectLineItemsController obj = null;
            PageReference pageRef = Page.SelectLineItems;
            Test.setCurrentPage(pageRef);
            obj = new SelectLineItemsController();
            pagereference cancel1 = obj.cancel();
            pagereference Sync_DFP1 = obj.Sync_DFP();
            Opportunity opp = [select id,name,(select id,name from opportunitylineitems limit 2) from opportunity where Is_Approved__c = true limit 1 ];
            ApexPages.currentPage().getparameters().put('id',opp.id);
            obj = new SelectLineItemsController();
            cancel1 = obj.cancel();
            
            Sync_DFP1 = obj.Sync_DFP();

            obj.lstwrapper[0].isselected = true;
            
            obj.lstwrapper[1].isselected = true;
            Sync_DFP1 = obj.Sync_DFP();
            
            obj.oppRecord.stagename='Proposal';
            obj.oppRecord.Trafficker_DFP_Id__c = '';
            obj.oppRecord.Targeting_Location__c = '';
            obj.oppRecord.Advertiser_DFP_Id__c = '';
            
            obj.oppRecord.opportunitylineitems[0].Description__c = '';
            obj.oppRecord.opportunitylineitems[0].Start_Date__c = null;
            obj.oppRecord.opportunitylineitems[0].End_Date__c = null;
            obj.oppRecord.opportunitylineitems[0].Product2.Height__c = '';
            obj.oppRecord.opportunitylineitems[0].Product2.Size__c = '';
            obj.oppRecord.opportunitylineitems[0].Description__c = 'Test';
            obj.oppRecord.opportunitylineitems[1].Start_Date__c = system.today().adddays(-2);
            obj.oppRecord.opportunitylineitems[1].End_Date__c = system.today().adddays(-3);
            Sync_DFP1 = obj.Sync_DFP();
            
        }
        test.stopTest();
    }
    
    static testMethod void test_method_2(){
         test.startTest();
        {
            string str = SelectLineItemsController.ValidateOpp(null);
        }
        test.stopTest();
    }
    
}
Dear All,

I have created a trigger for Candidate which on update creates an Employee record.

I am unable to cover the code with the test class I have written.

I am posting both the trigger and the class. Please help me.

TRIGGER

trigger EmployeeCreate on SFDC_Candidate__c (before update) {
  integer i=1;
  for (SFDC_Candidate__c can : trigger.new) {
    SFDC_Employee__c emp = new SFDC_Employee__c();
    SFDC_Candidate__c beforeUpdate = System.Trigger.oldMap.get(can.Id);
    
      system.debug(beforeUpdate.Create_Employee__c+'after----'+can.Create_Employee__c);
     if (beforeUpdate.Create_Employee__c!= can.Create_Employee__c){
    if(can.Create_Employee__c == True){
  
    emp.Candidate__c = can.id;
    emp.OwnerId = '005A0000000dy1y';
    emp.Name = can.SFDC_Candidate_Name__c;
    emp.Email_Address__c = can.SFDC_Candidate_Email__c;
    emp.Emergency_Contact_Phone__c = can.Preferred_Phone__c;
    emp.DOB__c = can.SFDC_Candidate_Birthdate__c;
    emp.Personal_Mobile__c = can.Mobile__c;
    emp.Gender__c = can.Gender__c;
 
   
   
   
    insert emp;
    }
   }
  }
}


TEST CLASS

@isTest
private class UnitTestsEmployeeCreate {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
      
        User u = [select id from user where FirstName = 'Lorenz'];
        Datetime todays= datetime.now();
        SFDC_Candidate__c can = new SFDC_Candidate__c();
        can.OwnerId = u.Id;
        can.SFDC_Candidate_Name__c = 'Test Name';
        can.SFDC_Candidate_Email__c = 'candidate@cansk.com';
        can.Preferred_Phone__c = '4568786588';
        can.Mobile__c = '5454454';
        can.Create_Employee__c = true;
        can.Gender__c = 'Female';
       
       
        insert can;
       
        SFDC_Employee__c emp = new SFDC_Employee__c();
        if(can.Create_Employee__c == true){
        emp.Candidate__c = can.id;
        emp.Name = can.SFDC_Candidate_Name__c;
        emp.Email_Address__c = can.SFDC_Candidate_Email__c;
        emp.Emergency_Contact_Phone__c = can.Preferred_Phone__c;
        emp.Personal_Mobile__c = can.Mobile__c;
        emp.Gender__c = can.Gender__c;
        emp.Personal_Mobile__c = can.Mobile__c;
 
       }
       
        insert emp;
       
          }
}

Thanks,

Finney
  • August 06, 2014
  • Like
  • 0
Dear All,

I have written a apex trigger to create a child object record when there is an update on the parent object.

The parent is account and child is account status note.

I am unable to cover the code on the trigger with the test class written.

I am posting both the trigger and class here. Please help me.

Trigger - 

trigger MissCallStatusNote on Account (after update) {
  if(recursivecheckBankingExsLease.runOnce())
    {
  integer i=1;
  DateTime val = DateTime.now();

  for (Account  acc : trigger.new) {
    Account_Status_Note__c asn = new Account_Status_Note__c ();
   
  
    if(acc.Misscall__c == true){
  
    asn.Account_Name__c = acc.id;
    asn.OwnerId = acc.OwnerId;
    asn.Status_Notes__c = 'Missed Call Email sent';
    asn.Follow_Up_Date__c = val + 1 ;
  
   
   
   
    insert asn;
   
   }
  }
  }
  }


Test Class

@isTest
private class UnitTestsMissCallStatusNote {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
       
      
       
        LIST<User> u4 = [select id from user where LastName = 'CRM Support Helpdesk'];  
        for(integer i = 0 ; i < u4.size(); i++){
       
        //create test account
        Account a = new Account();
        a.LastName = 'testabcd';
        a.PersonEmail='testyyy@test.com';
        a.Phone='85765';
        a.OwnerId = u4[i].id;
        a.Misscall__c = true;
        a.pb__Status__c = 'Unqualified';
        insert a;
        
       
       
      
        DateTime val = DateTime.now();
   
        Account_Status_Note__c asn = new Account_Status_Note__c ();
        asn.Account_Name__c = a.id;
        asn.OwnerId = a.OwnerId;
        asn.Status_Notes__c = 'Missed Call Email sent';
        asn.Follow_Up_Date__c = val + 1 ;
  
   
   
   
   
       insert asn;
   
      
       }
       
    }
}

Thanks a lot

Finney

Hi,

I have a trigger and I have also written a test class to test the trigger but only 20% of the trigger code is covered leaving 134 lines uncovered. My overall coverage is 60% and I'm trying to increase the coverage to 75%.

I am posting the trigger and the test class I've written. Can someone please help me.

trigger ShowingNotesAdded on pb__Showing__c (after insert, before update) {
    Account[] a = new Account[6];
    pb__InventoryItem__c[] i = new pb__InventoryItem__c[6];
    integer index = 0;
    integer c = 0;
    string response;
    Recordtype r;
    Date duedate;
    String[] toAddresses = new String[] {};
    for (pb__Showing__c s : trigger.new){
        //r = [select name from recordtype where sobjecttype = 'pb__Showing__c' and id = :s.RecordTypeId];
       
       
       if(trigger.IsInsert){
                  
            response = s.record_type_name__c;
            if (response.contains('Lettings')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Lettings Viewing'];
            }
            if (response.contains('Sales')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Sales Viewing'];
            }  
            if (response.contains('Lease')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Lease Viewing'];
            }  
         
            Event e = new Event();
            e.OwnerId = s.OwnerId;
            e.Subject = r.Name;
            e.RecordTypeId = r.Id;
            e.Description = 'Event created through Showing/Viewing';
            e.WhatId = s.Id;
            e.StartDateTime = s.start_time__c;
            e.EndDateTime = s.end_time__c;
            insert e;
      }
     
       
        if (trigger.IsUpdate){
            pb__Showing__c olds = Trigger.oldMap.get(s.ID);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           
            //create date from datetime
            duedate = Date.newInstance(s.Start_Time__c.year(),s.Start_Time__c.month(),s.Start_Time__c.day());
           
            if (s.pb__Inventory__c != null && s.Inventory_A_Notes__c != null && s.Send_Feedback_to_Vendor_A__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.pb__Inventory__c];
                a[index] = [select Id, Name, PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear ');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }    
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_A_Notes__c;
                t.WhatId = i[index].Id;
                t.ActivityDate = duedate;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
           if (s.Inventory_B__c != null && s.Inventory_B_Notes__c != null  && s.Send_Feedback_to_Vendor_B__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_B__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear ');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_B_Notes__c;
                t.ActivityDate = duedate;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_C__c != null && s.Inventory_C_Notes__c != olds.Inventory_C_Notes__c && s.Send_Feedback_to_Vendor_C__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_C__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
       
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.ActivityDate = duedate;
                t.Description = s.Inventory_C_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_D__c != null && s.Inventory_D_Notes__c != olds.Inventory_D_Notes__c && s.Send_Feedback_to_Vendor_D__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_D__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.ActivityDate = duedate;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_D_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_E__c != null && s.Inventory_E_Notes__c != olds.Inventory_E_Notes__c && s.Send_Feedback_to_Vendor_E__c != false){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_E__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
           
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
               Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.ActivityDate = duedate;
                t.Description = s.Inventory_E_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_F__c != null && s.Inventory_F_Notes__c != olds.Inventory_F_Notes__c && s.Send_Feedback_to_Vendor_F__c != false){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_F__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
           
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
              
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Lettings Viewing Feedback';
                t.Description = s.Inventory_F_Notes__c;
                t.ActivityDate = duedate;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
                insert t;
                index++;
            }
        }
    }
}
 

  • January 13, 2014
  • Like
  • 0

Hi,

 

I am getting an error when trying to save an event record due to a trigger I have which creates a SKEvent record when the Event record is created.

 

The error is

 

 Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateSKEVENT caused an unexpected exception, contact your administrator: CreateSKEVENT: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Event]: [Event]: Trigger.CreateSKEVENT: line 19, column 1

 

The code in red is the line of error.

 

Can anyone please help me. I am posting the code here.

 

Thanks

 

trigger CreateSKEVENT on Event (after insert) {
  integer i=1;
  for (Event  e : trigger.new) {
    S_K_Event__c ske = new S_K_Event__c();
    
   
   if(e.RecordTypeid == '012A0000000PYCa'){
    ske.Assigned_To__c = e.Ownerid;
    //ske.OwnerId = '005G00000024wtF';
    ske.Subject__c = e.Subject;
    ske.Start__c = e.StartDateTime;
    ske.Description__c = e.Description;
    ske.End__c = e.EndDateTime;
    ske.Related_To__c = e.Whatid;
    ske.RecordTypeId = '012G0000000jpYD';
    ske.Original_Event_Id__c = e.Id;
    
    
    insert ske;
    }
    
    S_K_Event__c ske1 = new S_K_Event__c();
    
   
   if(e.RecordTypeid == '012A0000000hRYf'|| e.RecordTypeid == '012A0000000PYCf'|| e.RecordTypeid == '012A0000000hRYk'){
    ske1.Assigned_To__c = e.Ownerid;
    //ske.OwnerId = '005G00000024wtF';
    ske1.Subject__c = e.Subject;
    ske1.Start__c = e.StartDateTime;
    ske1.Description__c = e.Description;
    ske1.End__c = e.EndDateTime;
    ske1.Related_To_Inventory__c = e.Whatid;
    ske1.RecordTypeId = '012G0000000jpY8';
    ske1.Original_Event_Id__c = e.Id;
    
    
    insert ske1;
    
    S_K_Event__c ske2 = new S_K_Event__c();
    
   
   if(e.RecordTypeid == '012A0000000S34u'){
    ske2.Assigned_To__c = e.Ownerid;
    //ske.OwnerId = '005G00000024wtF';
    ske2.Subject__c = e.Subject;
    ske2.Start__c = e.StartDateTime;
    ske2.Description__c = e.Description;
    ske2.End__c = e.EndDateTime;
    ske2.Related_To_Inventory__c = e.Whatid;
    ske2.RecordTypeId = '012G0000000jtbi';
    ske2.Original_Event_Id__c = e.Id;
    
    
    insert ske2;
     }
    }
   }
  }
  • December 11, 2013
  • Like
  • 0
Hi,
 
I am in need of a help regarding a coding error. Can you please help me.
 This is the error System.Exception: Too many SOQL queries: 101
 
 I have been struggling with this error for the past one month. I have tried everything
 
 
Please help me.
 
Thanks and Kind Regards
 
Finny B
  • December 03, 2013
  • Like
  • 0

Hi There,

 

I am getting an error when trying to save an Inventory record. I have a trigger on the Inventory Object which is causing the error.

 

Been strruggling with the trigger for days but couldn't find a solution.

 

I'm posting the trigger here

 

Please help me.

 

Thanks and Kind Regards

 

Finney

 

trigger CreateBankingExsLease on pb__InventoryItem__c(before update){
  List<pb__InventoryItem__c> invs = new List<pb__InventoryItem__c>();
  List<ID> invIds = New List<ID>();

  for( pb__InventoryItem__c inv: Trigger.new){
  invs.add(inv);
  invIds.add(inv.Id);
  pb__InventoryItem__c beforeUpdate = System.Trigger.oldMap.get(inv.Id);
     
  if (beforeUpdate.Property_Managed__c != inv.Property_Managed__c){ 
    
      
    }
  }

  List <pb__Agreement__c> Ag = [ SELECT Id, pb__InventoryId__c, pb__AgreementType__c, Stage__c  from
pb__Agreement__c where pb__InventoryId__c = :invIds and pb__AgreementType__c = 'Lease' and Stage__c = 'Transaction Closed and Commission Received'LIMIT 5];
 for(pb__Agreement__c agg : Ag)
    {
        for(pb__InventoryItem__c i: invs) 
  if(i.Property_Managed__c == true)
  Agg.Banking_Lease__c =  'Yes';
 
  update Ag;   
  
  }

  
}
  • November 28, 2013
  • Like
  • 0

Hi,

 

I have written a trigger on the agreement object to close the cases related to the agreement.

 

When I am doing any other update on the agreement, the trigger is throwing the error

 

Too many SOQL queries.

 

It used to work good until today. I don't know the reason for this error.

 

please find the trigger here

 

trigger CloseCase on pb__Agreement__c (before update) {
//List<ID> accIds = New List<ID>();
List<ID> agIds =New List<ID> ();
for(pb__Agreement__c ag:Trigger.new){
if(ag.pb__AgreementType__c == 'Sale' && ag.Stage__c == 'Transaction Closed'){
agIds.add(ag.Id);
}
}
List<Case> c = [ SELECT id,Agreement__c,Status, RecordTypeId from Case where Agreement__c = :agIds and RecordTypeId = '012A0000457547' LIMIT 2];
if(c.size() > 0){
Case cs = c[0];
c[0].Status = 'Closed';

}
update c;
}

 

 

Please help me.

 

Thanks and Kind Regards

 

Finney

  • November 07, 2013
  • Like
  • 0

Hi,

 

I am trying to write a class which generates a pdf as we all which sends an email alert to a lookup field on the object.

 

I am getting an error when clicking the button.

 

SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : u.Email: []

Error is in expression '{!XFDFInitKOA}' in component <apex:page> in page mergepdfkoa

 

 

An unexpected error has occurred. Your development organization has been notified.

 

 

Please find my code here

 

public with sharing class PDFMergerKOA {
public PDFMergerKOA() {
}

public PDFMergerKOA(ApexPages.StandardController controller) {
}

private String getXmlStringKOA(pb__InventoryItem__c c)
{
String sname = [Select pb__Value__c From pb__leanParameters__c Where Name = 'Server_Instance'].pb__Value__c;
date todayis = system.today();
datetime nowis = system.now();
String s = '<?xml version="1.0" encoding="UTF-8"?>' +
'<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">' +
'<f href="https://'+sname+'.salesforce.com/resource/1375791520000/Key_Out_Acknowledgement"/>' +
'<fields>' +
'<field name="Date"><value>' + todayis + '</value></field>' +
//'<field name="Owner"><value>' + c.Seller_Name__c + '</value></field>' +
'<field name="text2"><value>' + c.Name + '</value></field>' +
//'<field name="owner1"><value>' + c.Seller_Name__c + '</value></field>' +
//'<field name="Agents Name"><value>' + c.Sales_Consultant_Name__c + '</value></field>' +
//'<field name="Owner2"><value>' + c.Seller_Name__c + '</value></field>' +
'</fields><ids original="AD4D2075CAACA047844B948756BB055F" modified="C2F97965812CB048A1CD08602C94D0A6"/>' +
'</xfdf>';

return s;
}


public PageReference XFDFInitKOA()
{
list<pb__InventoryItem__c> c = [Select Name,OwnerId, Key_Out_Acknowledgement__c,Sales_Consultant__c,Sales_Consultant_Email__c, Seller_Name__c, Sales_Consultant_Name__c from pb__InventoryItem__c
WHERE id = :ApexPages.currentPage().getParameters().get('id')limit 1];

if(c.size()>0){
pb__InventoryItem__c nc = c[0];
/* User u = [SELECT id, Name FROM User
WHERE id = :c.Ownerid];*/
String xmlContent = getXmlStringKOA(nc);


Attachment attachment = new Attachment();
attachment.Body = Blob.valueOf(xmlContent);
attachment.Name = 'KOA_' + c[0].Name + '.XFDF';
attachment.ParentId = c[0].Id;

insert attachment;

/*Document d = new Document();
d.FolderId = '00lG0000001HE4S';
d.Body = Blob.valueOf(xmlContent);
d.Description = c[0].Name;
d.Name = 'KOA_' + c[0].Name+ '_' + System.now() + '.XFDF';
insert d;*/


{
User u = [SELECT id, Email, Name FROM User
WHERE id = :c[0].Sales_Consultant__c];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'u.Email'};
mail.setToAddresses(toAddresses);
mail.setSenderDisplayName('Testing');
mail.setSubject('Key Out Acknowledgement');
mail.setPlainTextBody('Please reassign the Qualified Lead: Lead Name as the owner has failed to take any action in the given 3 hours.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}



PageReference contactPage = new PageReference('/' + c[0].id);
contactPage.setRedirect(true);
return contactPage;
}
else{
PageReference contactPage = ApexPages.currentPage();
contactPage.setRedirect(true);
return contactPage;
}
}
}

 

Any help will be appreciated.

 

Thanks and Kind Regards

 

Finney

  • September 18, 2013
  • Like
  • 0

Hi There,

 

I am getting error when trying to deploy code from sandbox to production.

 

The code is working fine in sandbox and I am lost for thoughts on how to fix this.

 

I am posting the classes, the code that are causing the error and the error log.

 

Please help me.

 

trigger CloseCase on pb__Agreement__c (before update) {
//List<ID> accIds = New List<ID>();
List<ID> agIds =New List<ID> ();
for(pb__Agreement__c ag:Trigger.new){
if(ag.pb__AgreementType__c == 'Sale' && ag.Stage__c == 'Transaction Closed and Commission Received'){
agIds.add(ag.Id);
}
}
List<Case> c = [ SELECT id,Agreement__c,Status, RecordTypeId from Case where Agreement__c = :agIds and RecordTypeId = '012A0000000h1l4' LIMIT 2];
if(c.size() > 0){
Case cs = c[0];
c[0].Status = 'Closed';

}
update c;
}

 

  • April 22, 2013
  • Like
  • 0

Hi,

 

I am getting an error on a trigger .

 

I am posting the trigger here

 

Can someone help me please.

 

trigger rollupreferred3OpenAct on Account (before insert, before update) {
    
    if(trigger.isinsert) {
        for( Account ac:trigger.new)
            ac.Open_Actitvities_By_Referred_3__c = 0;
    }
    

else
    if(trigger.isupdate) { 
                 for( Account aci:trigger.new)
        
        for(Account ac : [select a.id, a.Referred_To_3__c, ( Select t.id from Tasks t where ( t.status != 'Completed' ) and ( t.ActivityDate >= Today ) 
        and ( t.OwnerId =: aci.Referred_To_3__c )) from Account a where a.id in :trigger.new])
           

     trigger.newmap.get(ac.id).Open_Actitvities_By_Referred_3__c = ac.Tasks.size();
   

     }
  }

  • March 26, 2013
  • Like
  • 0

Hi There,

 

I have 3 objects.

 

1) Inventory

2) Agreement

3) Banking

 

Inventory is a lookup field on Agreement.

 

Agreement is a lookup field on Banking.

 

We have 2 types of Agreements linked to the same Inventory record.

1) Lease

2) PM

 

The banking record is automatically created on the Lease agreement when the Lease Agreement Stage = Signed.

 

The PM Agreement doesn't have a banking record.

 

There is a field on the PM Agreement called as Management Fee.

 

I want to pull this Management Fee from the PM Agreement to the Banking Record linked to the Lease Agreement.

 

 

Can anyone please suggest a way to this.

 

Thanks

 

Finney

  • March 21, 2013
  • Like
  • 0

Hi,

 

I have written a trigger on the agreement object to create auto events when the record meets the given criteria.

 

I am getting the Null pointer error which is

 

CreateConditionReports: execution of AfterUpdate

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger:CreateConditionReports: line 14, Column 1

 

I am posting my trigger here. Please help.

 

trigger CreateConditionReports on pb__Agreement__c (afterupdate) {

  integer i=1;

 

for (pb__Agreement__c  ag : trigger.new) {

   

Event e = newEvent();

   

    datetime myDate = ag.X1st_Condition_Inspection__c;

   

if(ag.Stage__c == 'Agreement Signed and Passed to Conveyance'&& ag.Agreement_Signed__c == true){

    e.WhatId = ag.id;

    e.OwnerId ='005G00000024wtF';

    e.Subject ='Condition Report 1';

    e.RecordTypeId ='012G0000000jequ';

    e.Description ='Condition Report 1 Event created through Sale Agreement';

    e.StartDateTime = myDate;

    e.EndDateTime = myDate.addHours(2);

    e.Unit_Number__c = ag.Unit_Number__c;

    e.Unit_Type__c = ag.pb__UnitType__c;

    e.Unit_Bedrooms__c = ag.Unit_Bedrooms__c;

    e.Tenant_Name__c = ag.pb__PrimaryContactFullName__c;

    e.Lease_Expiration_Date__c = ag.pb__LeaseExpirationDate__c;*/

    e.Agreement_Name__c = ag.Name;

   

   

insert e;

    }

  

Event e1 = newEvent();

   

    datetime myDate1 = ag.X2nd_Condition_Inspection__c;

   

if(ag.Stage__c == 'Agreement Signed and Passed to Conveyance' && ag.Property_Tenanted__c == 'No'){

    e1.WhatId = ag.id;

    e1.OwnerId ='005G00000024wtF';

    e1.Subject ='Condition Report 2';

    e1.RecordTypeId ='012G0000000jeqz';

    e1.Description ='Condition Report 2 Event created through Sale Agreement';

    e1.StartDateTime = myDate1.addHours(6);

    e1.EndDateTime = myDate1.addHours(8);

    e1.Unit_Number__c = ag.Unit_Number__c;

    e1.Unit_Type__c = ag.pb__UnitType__c;

    e1.Unit_Bedrooms__c = ag.Unit_Bedrooms__c;

    e1.Tenant_Name__c = ag.pb__PrimaryContactFullName__c;

    e.Lease_Expiration_Date__c = ag.pb__LeaseExpirationDate__c;*/

    e1.Agreement_Name__c = ag.Name;

   

   

insert e1;

    }

 

   }

  }

 

Can someone please help me.

 

Finney

  • March 14, 2013
  • Like
  • 0

Hi

 

I have written a trigger on sandbox. But when I am writing a test class I am getting 0% coverage.

 

I am posting both my trigger and test class here.

 

Can someone please check and tell me where I have gone wrong?

 

trigger CreateNewShowing on pb__Showing__c (after update) {
  integer i=1;
  for (pb__Showing__c  sh : trigger.new) {
    pb__Showing__c s = new pb__Showing__c();
   
   datetime newDate = sh.Provisional_Date_A__c;
   if(sh.Status__c == 'Pending' && sh.Provisional_Date_A__c != Null){
    s.Account__c = sh.Account__c;
    s.pb__Inventory__c = sh.pb__Inventory__c;
    s.Start_Time__c = newDate ;
    s.End_Time__c = newDate.addHours(2);
    insert s;
    }
    pb__Showing__c s1 = new pb__Showing__c();
   
    datetime newDate1 = sh.Provisional_Date_B__c;
    if(sh.Status__c == 'Pending' && sh.Provisional_Date_B__c != Null){
    s1.Account__c = sh.Account__c;
    s1.pb__Inventory__c = sh.pb__Inventory__c;
    s1.Start_Time__c = newDate1 ;
    s1.End_Time__c = newDate1.addHours(2);
    insert s1;
    }
    pb__Showing__c s2 = new pb__Showing__c();
   
    datetime newDate2 = sh.Provisional_Date_C__c;
    if(sh.Status__c == 'Pending' && sh.Provisional_Date_C__c != Null){
    s2.Account__c = sh.Account__c;
    s2.pb__Inventory__c = sh.pb__Inventory__c;
    s2.Start_Time__c = newDate2 ;
    s2.End_Time__c = newDate2.addHours(2);
    insert s2;
    }
    pb__Showing__c s3 = new pb__Showing__c();
   
    datetime newDate3 = sh.Provisional_Date_D__c;
    if(sh.Status__c == 'Pending' && sh.Provisional_Date_D__c != Null){
    s3.Account__c = sh.Account__c;
    s3.pb__Inventory__c = sh.pb__Inventory__c;
    s3.Start_Time__c = newDate3 ;
    s3.End_Time__c = newDate3.addHours(2);
    insert s3;
    }
    pb__Showing__c s4 = new pb__Showing__c();
   
    datetime newDate4 = sh.Provisional_Date_E__c;
    if((sh.Status__c == 'Pending')&&(sh.Provisional_Date_E__c != Null)){
    s4.Account__c = sh.Account__c;
    s4.pb__Inventory__c = sh.pb__Inventory__c;
    s4.Start_Time__c = newDate4 ;
    s4.End_Time__c = newDate4.addHours(2);
    insert s4;
    }
    pb__Showing__c s5 = new pb__Showing__c();
   
    datetime newDate5 = sh.Provisional_Date_F__c;
    if(sh.Status__c == 'Pending' && sh.Provisional_Date_F__c != Null){
    s5.Account__c = sh.Account__c;
    s5.pb__Inventory__c = sh.pb__Inventory__c;
    s5.Start_Time__c = newDate5 ;
    s5.End_Time__c = newDate5.addHours(2);
    insert s5;
    }
   
   }
  }

 

 

Test Class

 

@isTest
private class UnitTestCreateNewShowing {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
     
      
     
     
        User u = [select id from user where LastName = 'Walsh'];
       
        //create test account
        Account a = new Account();
        a.LastName = 'testabcdef';
        a.PersonEmail='test@testsnk.com';
        a.Phone='987654';
        a.OwnerId = u.id;
        a.service_breach__c = false;
        a.pb__Status__c = 'Unqualified';
        insert a;
      
       pb__InventoryItem__c inv = new pb__InventoryItem__c();
        inv.name = 'abc123';
        inv.pb__IsForSale__c = true;
        inv.pb__PurchaseListPrice__c = 12313;
        inv.pb__IsAvailable__c = true;
        inv.Project__c = 'abcdd';
        inv.pb__ItemStatus__c = 'Available';
        inv.pb__IsBlocked__c = false;
        inv.SellerId__c = a.id;
        inv.Area__c = 'Marina';
        inv.Unit_No__c = '12test';
        inv.ItemStage__c = 'Available';
        insert inv;
      
      
       inv.OwnerId = u.id;
       update inv;

       //B
      
       pb__InventoryItem__c inv1 = new pb__InventoryItem__c();
        inv1.name = 'abc123';
        inv1.pb__IsForSale__c = true;
        inv1.pb__PurchaseListPrice__c = 12313;
        inv1.pb__IsAvailable__c = true;
        inv1.Project__c = 'abcdd';
        inv1.pb__ItemStatus__c = 'Available';
        inv1.pb__IsBlocked__c = false;
        inv1.SellerId__c = a.id;
        inv1.Area__c = 'Marina';
        inv1.Unit_No__c = '12test';
        inv1.ItemStage__c = 'Available';
        insert inv1;
      
      
       inv1.OwnerId = u.id;
       update inv1;
      
      
       pb__InventoryItem__c inv2 = new pb__InventoryItem__c();
        inv2.name = 'abc123';
        inv2.pb__IsForSale__c = true;
        inv2.pb__PurchaseListPrice__c = 12313;
        inv2.pb__IsAvailable__c = true;
        inv2.Project__c = 'abcdd';
        inv2.pb__ItemStatus__c = 'Available';
        inv2.pb__IsBlocked__c = false;
        inv2.SellerId__c = a.id;
        inv2.Area__c = 'Marina';
        inv2.Unit_No__c = '12test';
        inv2.ItemStage__c = 'Available';
        insert inv2;
      
      
       inv2.OwnerId = u.id;
       update inv2;
      
       Datetime todays= datetime.now();
      
         pb__Showing__c s = new pb__Showing__c();
         s.Start_Time__c=todays;
         s.End_Time__c=todays.addHours(2);
         s.Account__c=a.id;
         s.pb__Inventory__c=inv2.id;

         s.Provisional_Date_A__c = todays.addDays(2);
         s.Status__c = 'Pending';
         insert s;
      
      
      
   
    }
}

 

 

 

Kind Regards

 

Finney

  • February 14, 2013
  • Like
  • 0
The error is on line 40, column 1

I've marked the line BOLD.

Trigger SummingUpMonthlyValue On OTC_Contract_Product_Line_Items__c (After Insert, After Update, After Delete, After UnDelete){
    
    List<Id> accountManagerIds = New List<Id>();
    
    DateTime d = datetime.now();
    String monthName = d.format('MMMMM');
    System.debug('Current Month Name ****** ' + monthName);
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
         For(OTC_Contract_Product_Line_Items__c contr : Trigger.New){
             If(contr.Account_Manager__c != null){
                 accountManagerIds.add(contr.Account_Manager__c);
             }
         }   
    }
    
    If(Trigger.IsDelete){
        For(OTC_Contract_Product_Line_Items__c contr : Trigger.Old){
           If(contr.Account_Manager__c != null){
                 accountManagerIds.add(contr.Account_Manager__c);
             }
        }
    }
    
    Map<ID, Double > UserWithTotalInvoicevalue = New Map<ID, Double>();
    System.debug('-------------'+accountManagerIds);
    AggregateResult[] aggRes =  [Select Account_Manager__c,
                                        Sum(OTC_Unit_Price__c) sumac 
                                        FROM OTC_Contract_Product_Line_Items__c where Account_Manager__c = :accountManagerIds and OTC_Status__c = 'Active'
                                            Group by Account_Manager__c];//Invoice_Value_Current_Month__c
    System.debug('-------------------'+ aggRes);
    List<OTC_Contract_Product_Line_Items__c> cpliList = [Select Account_Manager__c,OTC_Unit_Price__c,OTC_Month__c,CreatedDate,OTC_Status__c,Month_Finance_Rev_Rec__c FROM OTC_Contract_Product_Line_Items__c where Account_Manager__c =:accountManagerIds and OTC_Status__c = 'Active'];
    Decimal monthlyAchieved = 0;
    Decimal DoubleUp = 0;
    Set<Id> idToSkip = new Set<Id>();
    Integer Month,Year;
    for(OTC_Contract_Product_Line_Items__c cpli: Trigger.New){
        Month = cpli.CreatedDate.month();
        Year = cpli.CreatedDate.Year();
        if( (cpli.Account_Manager__c != Trigger.oldMap.get(cpli.id).get('Account_Manager__c')) && (cpli.OTC_Status__c == 'Active') ){
            monthlyAchieved = monthlyAchieved + cpli.OTC_Unit_Price__c;
            idToSkip.add(cpli.id);
        }
    }
    for(OTC_Contract_Product_Line_Items__c cpli: cpliList){
        if(!idToSkip.contains(cpli.id)){
            if((cpli.CreatedDate.month() == Month) && (cpli.CreatedDate.year() == Year) && (cpli.OTC_Status__c == 'Active')  ){
                monthlyAchieved = monthlyAchieved + cpli.OTC_Unit_Price__c;
            }
        }
        if((cpli.OTC_Month__c.month() == Month-1) && (cpli.OTC_Status__c == 'Active') && (cpli.Month_Finance_Rev_Rec__c.month() == Month) ){
            DoubleUp = DoubleUp + cpli.OTC_Unit_Price__c;
        }
    }

    
    for(AggregateResult EveryAR : aggRes )
     {
         
         Id accountManagerId         = (Id)EveryAR.get('Account_Manager__c');
         Decimal TotalInvoiceValue   = (decimal)EveryAR.get('sumac');
         UserWithTotalInvoicevalue.put(accountManagerId ,TotalInvoiceValue);
     }    
     system.debug('-------'+ UserWithTotalInvoicevalue);
     List<Monthly_Target__c> targetFinalListToUpdate = New List<Monthly_Target__c>();
     
     For(Monthly_Target__c targ : [Select Id,No_of_Renewals__c, Portfolio_Total_Revenue__c, Active_Amount_Acheived__c, Monthly_Target_User__c, Start_Date__c
                                     FROM Monthly_Target__c WHERE Monthly_Target_User__c =: accountManagerIds LIMIT 1 ])
     {
         if( targ.Start_Date__c.month() == Month){
             targ.Portfolio_Total_Revenue__c = UserWithTotalInvoicevalue.get(targ.Monthly_Target_User__c);
             //targ.No_of_Renewals__c= UserWithTotalInvoicevalue.get(targ.Monthly_Target_User__c );
             targ.Active_Amount_Acheived__c = monthlyAchieved;
             targ.Double_Up_s_Current_Month__c = DoubleUp;
             targetFinalListToUpdate.add(targ);
         }
     }
     
     try{
         If(!targetFinalListToUpdate.IsEmpty()){
             update targetFinalListToUpdate;
         }
     }
     catch(Exception e){
         System.Debug('Thrown Exception for SummingUpInvoiceValue Trigger Is:: ' + e.getMessage());
     } 
     
    
}

Thanks in Advance.
Hi,

I have got a trigger that is as follows
  1. trigger UpdateTargets on Monthly_Target__c (before Insert,before update) {
  2. set<id> AMids=new set<id>();
  3. for(Monthly_Target__c tg:trigger.new)
  4. {
  5. AMids.add(tg.Monthly_Target_User__c);
  6. }
  7. Map<Id,decimal> AMTarget=new Map<Id,decimal>();
  8. aggregateResult[] aggRes=[Select Account_Manager__c,SUM(OTC_Unit_Price__c) sumac from OTC_Contract_Product_Line_Items__c where Account_Manager__c = : AMids AND OTC_Status__c= 'Active' Group by Account_Manager__c];
  9. for(aggregateResult ar:aggRes)
  10. {
  11. Id AM=(Id)ar.get('Account_Manager__c');
  12. double IV=(double)ar.get('sumac');
  13. AMTarget.put(AM,IV);
  14. }
  15. for(Monthly_Target__c tg:trigger.new)
  16. {
  17. tg.Portfolio_Total_Revenue__c=AMTarget.get(tg.Monthly_Target_User__c); 
  18. //tg.Active_Amount_Acheived__c=AMTarget.get(tg.Monthly_Target_User__c); 
  19. //tg.Portfolio_Total_Revenue__c=Integer.valueOf(ar.get('sumac');
  20. }
  21.  
  22. }


I have written a test class but the trigger is still showing 0% coverage.

I am unable to post the class here as it is too long.

Can anyone please help me with the test class?

Thanks
Hi,

I need help with pulling a field value on all contracts of a user to a custom Object.

The 2 objects here are
1) Contract - Standard object
2) Target - Custom Object.

Contract and Target object are not related to each other i.e. there is no lookup field for the Target object on the Contract Object.

There are 2 fields on the Contract object
a) Invoice Value - Currency
b) Account Manager - Lookup field to the user.

There are 2 fields on the Target object
a) Target Account Manager - Lookup field to the user.
b) Total Invoice Value - Should add up Invoice value of all Contracts under the Target Account Manager's name.

Any help would be greatly appreciated.

Thanks in advance.
I am getting an error on the following trigger.Will mark the error line in bold.
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) {

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    
   if((Trigger.isBefore && Trigger.isUpdate) || (Trigger.isBefore && Trigger.isUpdate) ){  
   
    for(Contract cont : Trigger.New){
        accountIds.add(cont.AccountId);
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
   
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_Emirates_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds LIMIT 1]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    if(contactIds.size() > 0) conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contact where Id = :contactIds]);
   
Hi , 

I am getting an error when trying to deploy a class to production.

The error is on line 10 of the trigger

Please find the trigger posted here.

This is the Trigger
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) {

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    for(Contract cont : Trigger.New){
        accountIds.add(cont.AccountId);
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_E_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_E_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    if(contactIds.size() > 0) conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_E_ID_Upload__c from Contact where Id = :contactIds]);
    
    for(Contract cont : Trigger.New){
        if(cont.Key_Contact__c != null && conMap.containsKey(cont.Key_Contact__c)){
            Contact con = conMap.get(cont.Key_Contact__c);
            cont.KeyContact_Email_id__c = con.Email;
            cont.KeyContact_MobileNumber__c = con.MobilePhone;
            cont.OTC_Key_Contact_Name__c = con.FirstName == null ? con.LastName : con.FirstName+' '+con.LastName;
            cont.KeyContact_Office__c = con.Phone;
            cont.E_ID_only_for_Jobs__c = con.OTC_E_ID_Upload__c;
            cont.OTC_Passport_Copy_Person_Signing_Cheque__c = con.Passport__c; 
        } else{
            if(accMap.get(cont.AccountId).IsPersonAccount == true){
                cont.KeyContact_Email_id__c = accMap.get(cont.AccountId).PersonEmail;
                cont.KeyContact_MobileNumber__c = accMap.get(cont.AccountId).PersonMobilePhone; 
                cont.OTC_Key_Contact_Name__c = accMap.get(cont.AccountId).Name;
                cont.KeyContact_Office__c = accMap.get(cont.AccountId).Phone;
                cont.OTC_Passport_Copy_Person_Signing_Cheque__c = accMap.get(cont.AccountId).Passport__pc;
                cont.E_ID_only_for_Jobs__c = accMap.get(cont.AccountId).OTC_E_ID_Upload__pc;
            }else if(accMap.get(cont.AccountId).Contacts.size()>0){
                cont.KeyContact_Email_id__c = accMap.get(cont.AccountId).Contacts[0].Email;
                cont.KeyContact_MobileNumber__c = accMap.get(cont.AccountId).Contacts[0].MobilePhone;
                cont.OTC_Key_Contact_Name__c = accMap.get(cont.AccountId).Contacts[0].FirstName == null ? accMap.get(cont.AccountId).Contacts[0].LastName : accMap.get(cont.AccountId).Contacts[0].FirstName+' '+accMap.get(cont.AccountId).Contacts[0].LastName;
                cont.KeyContact_Office__c = accMap.get(cont.AccountId).Contacts[0].Phone;
                cont.E_ID_only_for_Jobs__c = accMap.get(cont.AccountId).Contacts[0].OTC_E_ID_Upload__c;
                cont.OTC_Passport_Copy_Person_Signing_Cheque__c = accMap.get(cont.AccountId).Contacts[0].Passport__c;
            }
        }
    }

}
I have posted the class as a reply

Thanks
Hi,

I have the follwoing test class but its giving me an error when running a test.

Need your help on fixing it please

The error is 

Class.Test_SelectLineitemController.test_method_1: line 55, column 1


@istest
public class Test_SelectLineitemController {
    @testsetup static void setupData(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
        
        insert Test_cls_DCC_DFPDatafactory.getTestGoogleParametersList();
        
        Account acc = new account(name='testaccname');
        insert acc;
        List<Opportunity> lstopp = new List<Opportunity>();
        lstopp.add(Test_cls_DCC_DFPDatafactory.getTestOpportunity('Booking',100));
        lstopp.add(Test_cls_DCC_DFPDatafactory.getTestOpportunity('Proposal',30));
        lstopp[0].Is_Approved__c = true;
        lstopp[0].accountid = acc.id;
        insert lstopp;
        
         List<OpportunityLineItem> lstItems = new List<OpportunityLineItem>();
        lstItems.add(Test_cls_DCC_DFPDatafactory.getTestOpportunityLineItem(lstopp[0].id,'Test DFP Product',1));
        for(OpportunityLineItem Oli: lstItems){ //loop to the line items
        Oli.DFP_Id__c = string.valueof(system.now()).replaceAll('-', '').replaceAll(':', '').replaceAll(' ', '');
        Oli.DFP_External_Id__c = Oli.DFP_Id__c;
        Oli.Description = 'Test';
        Oli.Start_Date__c = System.Today();
        Oli.End_Date__c = System.Today() + 5;
        insert lstItems;
     }   
        insert Test_cls_DCC_DFPDatafactory.getTestDFPMapping();
        
    }
    
    
    static testMethod void test_method_1(){
        test.startTest();
        {
            SelectLineItemsController obj = null;
            PageReference pageRef = Page.SelectLineItems;
            Test.setCurrentPage(pageRef);
            obj = new SelectLineItemsController();
            pagereference cancel1 = obj.cancel();
            pagereference Sync_DFP1 = obj.Sync_DFP();
            Opportunity opp = [select id,name,(select id,name from opportunitylineitems limit 2) from opportunity where Is_Approved__c = true limit 1 ];
            ApexPages.currentPage().getparameters().put('id',opp.id);
            obj = new SelectLineItemsController();
            cancel1 = obj.cancel();
            
            Sync_DFP1 = obj.Sync_DFP();

            obj.lstwrapper[0].isselected = true;
            
            obj.lstwrapper[1].isselected = true;
            Sync_DFP1 = obj.Sync_DFP();
            
            obj.oppRecord.stagename='Proposal';
            obj.oppRecord.Trafficker_DFP_Id__c = '';
            obj.oppRecord.Targeting_Location__c = '';
            obj.oppRecord.Advertiser_DFP_Id__c = '';
            
            obj.oppRecord.opportunitylineitems[0].Description__c = '';
            obj.oppRecord.opportunitylineitems[0].Start_Date__c = null;
            obj.oppRecord.opportunitylineitems[0].End_Date__c = null;
            obj.oppRecord.opportunitylineitems[0].Product2.Height__c = '';
            obj.oppRecord.opportunitylineitems[0].Product2.Size__c = '';
            obj.oppRecord.opportunitylineitems[0].Description__c = 'Test';
            obj.oppRecord.opportunitylineitems[1].Start_Date__c = system.today().adddays(-2);
            obj.oppRecord.opportunitylineitems[1].End_Date__c = system.today().adddays(-3);
            Sync_DFP1 = obj.Sync_DFP();
            
        }
        test.stopTest();
    }
    
    static testMethod void test_method_2(){
         test.startTest();
        {
            string str = SelectLineItemsController.ValidateOpp(null);
        }
        test.stopTest();
    }
    
}
Dear All,

I have written a apex trigger to create a child object record when there is an update on the parent object.

The parent is account and child is account status note.

I am unable to cover the code on the trigger with the test class written.

I am posting both the trigger and class here. Please help me.

Trigger - 

trigger MissCallStatusNote on Account (after update) {
  if(recursivecheckBankingExsLease.runOnce())
    {
  integer i=1;
  DateTime val = DateTime.now();

  for (Account  acc : trigger.new) {
    Account_Status_Note__c asn = new Account_Status_Note__c ();
   
  
    if(acc.Misscall__c == true){
  
    asn.Account_Name__c = acc.id;
    asn.OwnerId = acc.OwnerId;
    asn.Status_Notes__c = 'Missed Call Email sent';
    asn.Follow_Up_Date__c = val + 1 ;
  
   
   
   
    insert asn;
   
   }
  }
  }
  }


Test Class

@isTest
private class UnitTestsMissCallStatusNote {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
       
      
       
        LIST<User> u4 = [select id from user where LastName = 'CRM Support Helpdesk'];  
        for(integer i = 0 ; i < u4.size(); i++){
       
        //create test account
        Account a = new Account();
        a.LastName = 'testabcd';
        a.PersonEmail='testyyy@test.com';
        a.Phone='85765';
        a.OwnerId = u4[i].id;
        a.Misscall__c = true;
        a.pb__Status__c = 'Unqualified';
        insert a;
        
       
       
      
        DateTime val = DateTime.now();
   
        Account_Status_Note__c asn = new Account_Status_Note__c ();
        asn.Account_Name__c = a.id;
        asn.OwnerId = a.OwnerId;
        asn.Status_Notes__c = 'Missed Call Email sent';
        asn.Follow_Up_Date__c = val + 1 ;
  
   
   
   
   
       insert asn;
   
      
       }
       
    }
}

Thanks a lot

Finney

Hi,

I have a trigger and I have also written a test class to test the trigger but only 20% of the trigger code is covered leaving 134 lines uncovered. My overall coverage is 60% and I'm trying to increase the coverage to 75%.

I am posting the trigger and the test class I've written. Can someone please help me.

trigger ShowingNotesAdded on pb__Showing__c (after insert, before update) {
    Account[] a = new Account[6];
    pb__InventoryItem__c[] i = new pb__InventoryItem__c[6];
    integer index = 0;
    integer c = 0;
    string response;
    Recordtype r;
    Date duedate;
    String[] toAddresses = new String[] {};
    for (pb__Showing__c s : trigger.new){
        //r = [select name from recordtype where sobjecttype = 'pb__Showing__c' and id = :s.RecordTypeId];
       
       
       if(trigger.IsInsert){
                  
            response = s.record_type_name__c;
            if (response.contains('Lettings')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Lettings Viewing'];
            }
            if (response.contains('Sales')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Sales Viewing'];
            }  
            if (response.contains('Lease')){
                r = [select id, Name from recordtype where sobjecttype = 'Event' and Name = 'Lease Viewing'];
            }  
         
            Event e = new Event();
            e.OwnerId = s.OwnerId;
            e.Subject = r.Name;
            e.RecordTypeId = r.Id;
            e.Description = 'Event created through Showing/Viewing';
            e.WhatId = s.Id;
            e.StartDateTime = s.start_time__c;
            e.EndDateTime = s.end_time__c;
            insert e;
      }
     
       
        if (trigger.IsUpdate){
            pb__Showing__c olds = Trigger.oldMap.get(s.ID);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           
            //create date from datetime
            duedate = Date.newInstance(s.Start_Time__c.year(),s.Start_Time__c.month(),s.Start_Time__c.day());
           
            if (s.pb__Inventory__c != null && s.Inventory_A_Notes__c != null && s.Send_Feedback_to_Vendor_A__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.pb__Inventory__c];
                a[index] = [select Id, Name, PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear ');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }    
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_A_Notes__c;
                t.WhatId = i[index].Id;
                t.ActivityDate = duedate;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
           if (s.Inventory_B__c != null && s.Inventory_B_Notes__c != null  && s.Send_Feedback_to_Vendor_B__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_B__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear ');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_B_Notes__c;
                t.ActivityDate = duedate;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_C__c != null && s.Inventory_C_Notes__c != olds.Inventory_C_Notes__c && s.Send_Feedback_to_Vendor_C__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_C__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
       
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.ActivityDate = duedate;
                t.Description = s.Inventory_C_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_D__c != null && s.Inventory_D_Notes__c != olds.Inventory_D_Notes__c && s.Send_Feedback_to_Vendor_D__c != false ){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_D__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
               
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.ActivityDate = duedate;
                t.Subject = 'Viewing Feedback';
                t.Description = s.Inventory_D_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_E__c != null && s.Inventory_E_Notes__c != olds.Inventory_E_Notes__c && s.Send_Feedback_to_Vendor_E__c != false){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_E__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
           
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
               Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Viewing Feedback';
                t.ActivityDate = duedate;
                t.Description = s.Inventory_E_Notes__c;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
   
                insert t;
                index++;
            }
           
            if (s.Inventory_F__c != null && s.Inventory_F_Notes__c != olds.Inventory_F_Notes__c && s.Send_Feedback_to_Vendor_F__c != false){
                toAddresses.clear();
                i[index] = [select id, Unit_No__c, AreaUAE__c, Project__c, sellerid__c from pb__InventoryItem__c where id =: s.Inventory_F__c];
                a[index] = [select Id, Name,PersonEmail from Account where Id =: i[index].SellerId__c];
           
                mail.setPlainTextBody('Dear');
                toAddresses.add(a[index].PersonEmail);
                mail.setToAddresses(toAddresses);                             
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Smith & Ken');                           
                mail.setSubject('Viewing Feedback');
               
                try{
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                catch(System.EmailException ex){
                    system.debug('============== email exception caught!!!=============');
                    response = ex.getMessage();
                }
              
                Task t = new Task();
                t.OwnerId = s.OwnerId;
                t.Subject = 'Lettings Viewing Feedback';
                t.Description = s.Inventory_F_Notes__c;
                t.ActivityDate = duedate;
                t.WhatId = i[index].Id;
                t.Status = 'Completed';
                insert t;
                index++;
            }
        }
    }
}
 

  • January 13, 2014
  • Like
  • 0
Hi,
 
I am in need of a help regarding a coding error. Can you please help me.
 This is the error System.Exception: Too many SOQL queries: 101
 
 I have been struggling with this error for the past one month. I have tried everything
 
 
Please help me.
 
Thanks and Kind Regards
 
Finny B
  • December 03, 2013
  • Like
  • 0

Hi There,

 

I am getting an error when trying to save an Inventory record. I have a trigger on the Inventory Object which is causing the error.

 

Been strruggling with the trigger for days but couldn't find a solution.

 

I'm posting the trigger here

 

Please help me.

 

Thanks and Kind Regards

 

Finney

 

trigger CreateBankingExsLease on pb__InventoryItem__c(before update){
  List<pb__InventoryItem__c> invs = new List<pb__InventoryItem__c>();
  List<ID> invIds = New List<ID>();

  for( pb__InventoryItem__c inv: Trigger.new){
  invs.add(inv);
  invIds.add(inv.Id);
  pb__InventoryItem__c beforeUpdate = System.Trigger.oldMap.get(inv.Id);
     
  if (beforeUpdate.Property_Managed__c != inv.Property_Managed__c){ 
    
      
    }
  }

  List <pb__Agreement__c> Ag = [ SELECT Id, pb__InventoryId__c, pb__AgreementType__c, Stage__c  from
pb__Agreement__c where pb__InventoryId__c = :invIds and pb__AgreementType__c = 'Lease' and Stage__c = 'Transaction Closed and Commission Received'LIMIT 5];
 for(pb__Agreement__c agg : Ag)
    {
        for(pb__InventoryItem__c i: invs) 
  if(i.Property_Managed__c == true)
  Agg.Banking_Lease__c =  'Yes';
 
  update Ag;   
  
  }

  
}
  • November 28, 2013
  • Like
  • 0

Hi,

 

I have written a trigger on the agreement object to close the cases related to the agreement.

 

When I am doing any other update on the agreement, the trigger is throwing the error

 

Too many SOQL queries.

 

It used to work good until today. I don't know the reason for this error.

 

please find the trigger here

 

trigger CloseCase on pb__Agreement__c (before update) {
//List<ID> accIds = New List<ID>();
List<ID> agIds =New List<ID> ();
for(pb__Agreement__c ag:Trigger.new){
if(ag.pb__AgreementType__c == 'Sale' && ag.Stage__c == 'Transaction Closed'){
agIds.add(ag.Id);
}
}
List<Case> c = [ SELECT id,Agreement__c,Status, RecordTypeId from Case where Agreement__c = :agIds and RecordTypeId = '012A0000457547' LIMIT 2];
if(c.size() > 0){
Case cs = c[0];
c[0].Status = 'Closed';

}
update c;
}

 

 

Please help me.

 

Thanks and Kind Regards

 

Finney

  • November 07, 2013
  • Like
  • 0

Hi,

 

I am trying to write a class which generates a pdf as we all which sends an email alert to a lookup field on the object.

 

I am getting an error when clicking the button.

 

SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : u.Email: []

Error is in expression '{!XFDFInitKOA}' in component <apex:page> in page mergepdfkoa

 

 

An unexpected error has occurred. Your development organization has been notified.

 

 

Please find my code here

 

public with sharing class PDFMergerKOA {
public PDFMergerKOA() {
}

public PDFMergerKOA(ApexPages.StandardController controller) {
}

private String getXmlStringKOA(pb__InventoryItem__c c)
{
String sname = [Select pb__Value__c From pb__leanParameters__c Where Name = 'Server_Instance'].pb__Value__c;
date todayis = system.today();
datetime nowis = system.now();
String s = '<?xml version="1.0" encoding="UTF-8"?>' +
'<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">' +
'<f href="https://'+sname+'.salesforce.com/resource/1375791520000/Key_Out_Acknowledgement"/>' +
'<fields>' +
'<field name="Date"><value>' + todayis + '</value></field>' +
//'<field name="Owner"><value>' + c.Seller_Name__c + '</value></field>' +
'<field name="text2"><value>' + c.Name + '</value></field>' +
//'<field name="owner1"><value>' + c.Seller_Name__c + '</value></field>' +
//'<field name="Agents Name"><value>' + c.Sales_Consultant_Name__c + '</value></field>' +
//'<field name="Owner2"><value>' + c.Seller_Name__c + '</value></field>' +
'</fields><ids original="AD4D2075CAACA047844B948756BB055F" modified="C2F97965812CB048A1CD08602C94D0A6"/>' +
'</xfdf>';

return s;
}


public PageReference XFDFInitKOA()
{
list<pb__InventoryItem__c> c = [Select Name,OwnerId, Key_Out_Acknowledgement__c,Sales_Consultant__c,Sales_Consultant_Email__c, Seller_Name__c, Sales_Consultant_Name__c from pb__InventoryItem__c
WHERE id = :ApexPages.currentPage().getParameters().get('id')limit 1];

if(c.size()>0){
pb__InventoryItem__c nc = c[0];
/* User u = [SELECT id, Name FROM User
WHERE id = :c.Ownerid];*/
String xmlContent = getXmlStringKOA(nc);


Attachment attachment = new Attachment();
attachment.Body = Blob.valueOf(xmlContent);
attachment.Name = 'KOA_' + c[0].Name + '.XFDF';
attachment.ParentId = c[0].Id;

insert attachment;

/*Document d = new Document();
d.FolderId = '00lG0000001HE4S';
d.Body = Blob.valueOf(xmlContent);
d.Description = c[0].Name;
d.Name = 'KOA_' + c[0].Name+ '_' + System.now() + '.XFDF';
insert d;*/


{
User u = [SELECT id, Email, Name FROM User
WHERE id = :c[0].Sales_Consultant__c];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'u.Email'};
mail.setToAddresses(toAddresses);
mail.setSenderDisplayName('Testing');
mail.setSubject('Key Out Acknowledgement');
mail.setPlainTextBody('Please reassign the Qualified Lead: Lead Name as the owner has failed to take any action in the given 3 hours.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}



PageReference contactPage = new PageReference('/' + c[0].id);
contactPage.setRedirect(true);
return contactPage;
}
else{
PageReference contactPage = ApexPages.currentPage();
contactPage.setRedirect(true);
return contactPage;
}
}
}

 

Any help will be appreciated.

 

Thanks and Kind Regards

 

Finney

  • September 18, 2013
  • Like
  • 0

Hi There,

 

I am getting error when trying to deploy code from sandbox to production.

 

The code is working fine in sandbox and I am lost for thoughts on how to fix this.

 

I am posting the classes, the code that are causing the error and the error log.

 

Please help me.

 

trigger CloseCase on pb__Agreement__c (before update) {
//List<ID> accIds = New List<ID>();
List<ID> agIds =New List<ID> ();
for(pb__Agreement__c ag:Trigger.new){
if(ag.pb__AgreementType__c == 'Sale' && ag.Stage__c == 'Transaction Closed and Commission Received'){
agIds.add(ag.Id);
}
}
List<Case> c = [ SELECT id,Agreement__c,Status, RecordTypeId from Case where Agreement__c = :agIds and RecordTypeId = '012A0000000h1l4' LIMIT 2];
if(c.size() > 0){
Case cs = c[0];
c[0].Status = 'Closed';

}
update c;
}

 

  • April 22, 2013
  • Like
  • 0

Hi,

 

I am getting an error on a trigger .

 

I am posting the trigger here

 

Can someone help me please.

 

trigger rollupreferred3OpenAct on Account (before insert, before update) {
    
    if(trigger.isinsert) {
        for( Account ac:trigger.new)
            ac.Open_Actitvities_By_Referred_3__c = 0;
    }
    

else
    if(trigger.isupdate) { 
                 for( Account aci:trigger.new)
        
        for(Account ac : [select a.id, a.Referred_To_3__c, ( Select t.id from Tasks t where ( t.status != 'Completed' ) and ( t.ActivityDate >= Today ) 
        and ( t.OwnerId =: aci.Referred_To_3__c )) from Account a where a.id in :trigger.new])
           

     trigger.newmap.get(ac.id).Open_Actitvities_By_Referred_3__c = ac.Tasks.size();
   

     }
  }

  • March 26, 2013
  • Like
  • 0

Hi,

 

I want to create a rollup field in Account Object with Opportunity Amount. Can any one help me on this, Actually i'm new in  trigger.