+ Start a Discussion
Shailesh DeshpandeShailesh Deshpande 

Issue with trigger on Event object.

Hi,

 

1. I am having a trigger on Event object. The trigger is written in such a way that there can be no two Events or Meetings for the same user at same time. This works fine when we deal with normal events however when we try to create a recurring event, I get an error saying "Changes made to the series will affect all occurrences on or after mm/dd/yyyy."

 

Does any body know what can be the issue behind this?

 

Due to above error I have temporarily disabled Recurring Tasks and Events in my org.

 

2. Also I am trying to write the test coverage for this, the logic for avoiding duplicate events gets covered properly. jowever, I am unable to cover the code which was written to avoid duplicate Meetings. I am distinguishing between Events and Meetings by the "GroupEventType" field on the event object.

 

Please let me know if there is a way by which i can cover that code.

 

Thanks,

Shailesh. P. Deshpande

prady-cmprady-cm

Post in some code, so that we can see what the issue is.

Its very difficult to help without code specially in test classes

SRKSRK

I am still looking into u r issue

but  what i fell is that as u r creating Recurring Tasks and Events & all the Recurring Tasks and Events are created in a flow & all are inderdepandent so if one event or task have error it effect all other

also just deactive u r trigger & on the Recurring Tasks and Events & then test it is working fine

 

 

 

Shailesh DeshpandeShailesh Deshpande
trigger trgUnplannedTriggerCreation on Event (before insert, before update, after insert, after update) {

    try{
    if(!clsUtility.FieldVisitLoaderRecursiveBlock){
        //Initialisations
  
        Set<Id> setEventIds = new Set<Id>();
        Set<Id> setOwnerIds = new Set<Id>();
        
        Map<Id,String> mapofAccountRecordTypes = new Map<Id,String>();
        Map<Id,String> maplistofAccountAndSalesOfficeCode = new Map<Id,String>();
        Map<String, List<DateTime>> mapEventStartDate = new Map<String, List<DateTime>>(); // Key = Owner, Value= List of Datetime. will hold the start datetimes for normal events
        Map<String, List<DateTime>> mapEventEndDate = new Map<String, List<DateTime>>(); //  Key = Owner, Value= List of Datetime. will hold the end datetimes for normal events
		Map<String, List<DateTime>> mapGroupEventStartDate = new Map<String, List<DateTime>>(); // Key = Owner, Value= List of Datetime. will hold the start datetimes for Meetings
        Map<String, List<DateTime>> mapGroupEventEndDate = new Map<String, List<DateTime>>(); //  Key = Owner, Value= List of Datetime. will hold the End datetimes for Meetins       
        
		List<Event> listOfEvents = new List<Event>();
        List<Id> listOfAccounts = new List<Id>();
		List<DateTime> lstEventDates = new List<DateTime>();  // will hold all the dates Start Dates as well as End dates in a sorted order
		List<DateTime> lstEventDates2 = new List<DateTime>(); // will hold the start datetimes
		List<DateTime> lstEventDates3 = new List<DateTime>(); // will hold the End datetimes
        
        Date dtToday = Date.today();
        
        //getting the Account Id
        for(Event objEvent : Trigger.new)
        {
            if(objEvent.WhatId != NULL && !objEvent.IsRecurrence)
            {
                if(String.valueOf(objEvent.WhatId).startsWith('001'))
                {   
                    listOfAccounts.add(objEvent.WhatId);
                }
            }
            if(objEvent.StartDateTime != null && objEvent.EndDateTime != null)
            {
        		lstEventDates.add(objEvent.StartDateTime);
        		lstEventDates.add(objEvent.EndDateTime);
        		setOwnerIds.add(objEvent.OwnerId);
        		setEventIds.add(objEvent.Id);
            }
            system.debug('========lstDate=========='+lstEventDates);
            //elsel
                //objEvent.addError('Add Account Lookup');
        }
		
		        
        if(!lstEventDates.isEmpty())
        {
        	// get all the events that exist in the system within the given date - time range for a particular user
        	lstEventDates.sort();
	        for(Event objEvent : [SELECT Id, OwnerId, StartDateTime, EndDateTime, Group_Event_Type__c 
	        					  FROM   Event
	        					  WHERE  ((StartDateTime >=: lstEventDates[0] AND StartDateTime <=: lstEventDates[1])
	        					  		  OR
	        					  		 (EndDateTime >=: lstEventDates[0] AND EndDateTime <=: lstEventDates[1])
	        					  		  OR
	        					  		 (StartDateTime <=: lstEventDates[0] AND EndDateTime >=: lstEventDates[1]))
	        					  		 AND
	        					  		 OwnerId in: setOwnerIds
	        					  		 AND
	        					  		 Id not in: setEventIds      					  		 
	        					  ])
	        {
	        	
	        	if(objEvent.Group_Event_Type__c == '2')
	        	{
		        	if(!mapGroupEventStartDate.containsKey(objEvent.OwnerId))
	        		{
	        			mapGroupEventStartDate.put(objEvent.OwnerId, new List<Datetime>());
	        			mapGroupEventEndDate.put(objEvent.OwnerId, new List<Datetime>());
	        			
	        			mapGroupEventStartDate.get(objEvent.OwnerId).add(objEvent.StartDateTime); // populate the map with start date time for the Meeting.
	        			mapGroupEventEndDate.get(objEvent.OwnerId).add(objEvent.EndDateTime); // populate the map with end date time for the Meeting.
	        		}
	        		else
	        		{
	        			mapGroupEventStartDate.get(objEvent.OwnerId).add(objEvent.StartDateTime);
	        			mapGroupEventEndDate.get(objEvent.OwnerId).add(objEvent.EndDateTime);
	        		}
	        	}
	        	else
	        	{
	        		if(!mapEventStartDate.containsKey(objEvent.OwnerId))
	        		{
	        			mapEventStartDate.put(objEvent.OwnerId, new List<Datetime>());
	        			mapEventEndDate.put(objEvent.OwnerId, new List<Datetime>());
	        			
	        			mapEventStartDate.get(objEvent.OwnerId).add(objEvent.StartDateTime); // populate the map with start date time for the Meeting.
	        			mapEventEndDate.get(objEvent.OwnerId).add(objEvent.EndDateTime); // populate the map with end date time for the Meeting.
	        		}
	        		else
	        		{
	        			mapEventStartDate.get(objEvent.OwnerId).add(objEvent.StartDateTime);
	        			mapEventEndDate.get(objEvent.OwnerId).add(objEvent.EndDateTime);
	        		}
	        	}
	 
	        	//lstEventDates2.add(objEvent.StartDateTime);
	        	//lstEventDates3.add(objEvent.EndDateTime);
	        }
	        setEventIds = new Set<Id>();
        }	        					  
        
        //Querying for Account
        for(Account objAccount : [SELECT Id, Name, RecordTypeId,Sales_Office_Code__c,
                                   Sales_Office_Description__c,SAP_Code__c
                                FROM Account
                                WHERE SAP_Code__c!= NULL AND 
                                      Id in:listOfAccounts
                            ])
        {
            maplistofAccountAndSalesOfficeCode.put(objAccount.id,objAccount.Sales_Office_Code__c + ' - ' + objAccount.Sales_Office_Description__c);
        }
     
        // checking for error conditions
        for(Event objTypeEvent : Trigger.new)
        {
        	// enter this block only if it is a normal event and not a meeting
            if(Trigger.isBefore && !(Trigger.IsUpdate && !Trigger.IsInsert && Trigger.oldMap.get(objTypeEvent.Id).GroupEventType == '2' && objTypeEvent.GroupEventType == '1'))
            {
            	system.debug('In main block'+mapEventStartDate+'============'+mapEventEndDate);
                if((dtToday.month() > objTypeEvent.StartDateTime.month() && dttoday.year() == objTypeEvent.StartDateTime.year())
                || (dtToday.month() < objTypeEvent.StartDateTime.month() && dttoday.year() > objTypeEvent.StartDateTime.year()))
                {
                    if(dtToday.day() > 5)
                        objTypeEvent.addError('You cannot create an unplanned call as the visit date upload for the month is completed');
                }       
                if((objTypeEvent.StartDateTime > System.now()) && (objTypeEvent.Topics_Discussed__c != NULL || objTypeEvent.Next_Action__c != NULL || objTypeEvent.Summary__c != NULL))
                {
                    objTypeEvent.addError('Enter comments for future call in description field. Field Visit Details section can be updated only on or after activity date.');
                }
                 
                // Adding the logic to make all unplanned future calls as planned
                if(objTypeEvent.StartDateTime > System.today()+1)
                {
                    objTypeEvent.IsPlanned__c = true;
                }
                
                system.debug('=====SFDC ===='+objTypeEvent.GroupEventType);
                //Adding logic to update visit update date and sales office code
                
                objTypeEvent.VisitUpdateDate__c = Date.newInstance(Integer.valueOf(objTypeEvent.StartDateTime.year()),Integer.valueOf(objTypeEvent.StartDateTime.month())+1,5);
                objTypeEvent.Sales_Office_Code__c = maplistofAccountAndSalesOfficeCode.get(objTypeEvent.WhatId);
                objTypeEvent.Uniqueness__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.StartDateTime + ' - ' + objTypeEvent.GroupEventType;
                objTypeEvent.End_Time_Uniquess__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.EndDateTime + ' - ' + objTypeEvent.GroupEventType;
                objTypeEvent.Group_Event_Type__c = objTypeEvent.GroupEventType;
                
                if(mapEventStartDate.containsKey(objTypeEvent.OwnerId))
            	{
            		lstEventDates2 = mapEventStartDate.get(objTypeEvent.OwnerId);
            		lstEventDates3 = mapEventEndDate.get(objTypeEvent.OwnerId);
	            	for(Integer i=0; i < lstEventDates2.size(); i++)
		        	{
		        		// if start date and end date are same
		        		if(objTypeEvent.StartDateTime == lstEventDates2[i] && objTypeEvent.EndDateTime == lstEventDates3[i])
		        		{
		        			objTypeEvent.addError('An Event/Meeting is already scheduled for this date range.');						
		        			//Trigger.new[0].addError('An event is already scheduled for this date range.');
		        		}
		        		
		        		// if start date and end date lie between any of the events start date or end date for the same user, do not allow the user to create the event 
		        		if(!((objTypeEvent.StartDateTime < lstEventDates2[i] && objTypeEvent.EndDateTime <= lstEventDates2[i]) || (objTypeEvent.StartDateTime >= lstEventDates3[i] && objTypeEvent.EndDateTime > lstEventDates3[i])))
		        		{
		        			objTypeEvent.addError('An Event/Meeting is already scheduled for this date range.');
		        		}	
		        	}
            	}
                
                if(Trigger.isUpdate && objTypeEvent.IsPlanned__c)
                {
                    if((objTypeEvent.StartDateTime.date() != Trigger.oldMap.get(objTypeEvent.Id).StartDateTime.date() || (objTypeEvent.EndDateTime.date() != Trigger.oldMap.get(objTypeEvent.Id).EndDateTime.date())))
                    {
                        if(objTypeEvent.Reasons_for_Deviation__c == NULL)
                        {
                            objTypeEvent.addError('Enter Reasons for deviating this call');
                        }
                        else{
                            objTypeEvent.Uniqueness__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.StartDateTime + ' - ' + objTypeEvent.GroupEventType + ' - ' + objTypeEvent.Reasons_for_Deviation__c;
                            objTypeEvent.End_Time_Uniquess__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.EndDateTime  + ' - ' + objTypeEvent.GroupEventType + ' - ' + objTypeEvent.Reasons_for_Deviation__c;
                            objTypeEvent.Subject = 'DEVIATED : ' + objTypeEvent.Subject ;
                        }
                    }
                }
            }
            else if(Trigger.isAfter && !Trigger.isInsert && Trigger.isUpdate && Trigger.oldMap.get(objTypeEvent.Id).GroupEventType == '2' && objTypeEvent.GroupEventType == '1') // if the event is of type "Meeting"
            {
            	system.debug('===== In Else == ');
            	setEventIds.add(objTypeEvent.Id);
            }
        
        }
        
        // if the event is of type "Meeting"
        if(Trigger.isAfter)
        {
	        for (Event objTypeEvent : [Select Uniqueness__c, End_Time_Uniquess__c, OwnerId, StartDateTime, EndDateTime, Reasons_for_Deviation__c from Event where Id in : setEventIds])
	        {
        		if(mapGroupEventStartDate.containsKey(objTypeEvent.OwnerId))
            	{
            		system.debug('=====in if after event=====');
            		system.debug('In main block'+mapGroupEventStartDate+'============'+mapEventEndDate);
            		lstEventDates2 = mapGroupEventStartDate.get(objTypeEvent.OwnerId);
            		lstEventDates3 = mapGroupEventEndDate.get(objTypeEvent.OwnerId);
            		system.debug('=========lstEventDates2======'+lstEventDates2 + '=======lstEventDates3======' + lstEventDates3);
	            	
	            	for(Integer i=0; i < lstEventDates2.size(); i++)
		        	{
		        		system.debug('=========dates======'+objTypeEvent.StartDateTime + '=============' + objTypeEvent.EndDateTime);
		        		system.debug('=========='+(objTypeEvent.StartDateTime == lstEventDates2[i] && objTypeEvent.EndDateTime == lstEventDates3[i]));
		        		
		        		// if start date and end date are same
		        		if(objTypeEvent.StartDateTime == lstEventDates2[i] && objTypeEvent.EndDateTime == lstEventDates3[i])
		        		{
		        			throw new RealTimeTxnException('An Event/Meeting is already scheduled for this date range.');						
		        			//Trigger.new[0].addError('An event is already scheduled for this date range.');
		        		}
		        		
		        		// if start date and end date lie between any of the events start date or end date for the same user, do not allow the user to create the event
		        		if(!((objTypeEvent.StartDateTime < lstEventDates2[i] && objTypeEvent.EndDateTime <= lstEventDates2[i]) || (objTypeEvent.StartDateTime >= lstEventDates3[i] && objTypeEvent.EndDateTime > lstEventDates3[i])))
		        		{
		        			throw new RealTimeTxnException('An Event/Meeting is already scheduled for this date range.');
		        			//Trigger.new[0].addError('An event is already scheduled for this date range.');
		        		}	
		        	}
            	}
            	objTypeEvent.Group_Event_Type__c = Trigger.oldMap.get(objTypeEvent.Id).GroupEventType;
	        	objTypeEvent.Uniqueness__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.StartDateTime + ' - ' + Trigger.oldMap.get(objTypeEvent.Id).GroupEventType;
	            objTypeEvent.End_Time_Uniquess__c = objTypeEvent.OwnerId + ' - ' + objTypeEvent.EndDateTime  + ' - ' + Trigger.oldMap.get(objTypeEvent.Id).GroupEventType;
	            listOfEvents.add(objTypeEvent);
	        }
	        
	        if(listOfEvents.size() > 0) 
	        {
	        	clsUtility.FieldVisitLoaderRecursiveBlock = true;
        		update listOfEvents;
	        }
        }
       // clsUtility.FieldVisitLoaderRecursiveBlock = true;
    }
	}
    catch(Exception ex)
    {
    	Trigger.new[0].addError(ex.getMessage());
    }
 }