function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Olavo ZapataOlavo Zapata 

Apex Events Select is not showing all records

Hello guys,

I'm facing a pretty weird problem in the Apex behavior that needs to bring me users with events occupying their calendar.

Contextualizing:
We have a code that distributes the qualified opportunities for the sales rep (SREPs) from an event which the schedule was defined by the client.
The Code searches for the time which the client chose for who SREPs are available to call him.

Since we could not find "available" in the calendar, we searched through all the "Open" Events at that time and then took out the sales rep who were busy.

Resulting in the list of sellers without event.

The problem:
The result of the described operation sometimes brings me sreps who are busy at the moment, which causes discomfort to the customer.

We try to debug in different ways to understand why this happens, but when we run the same query anywhere else shows the busy srep, but in the APEX execution shows as a free srep to call.

We have also created an "Apex Debug log" object where it logs code execution steps for us to know how it was at the time of the opportunity distribution and we can't explain why it happens.
Can it be by routing being in short time slots and the apex using some cash?

Has anyone seen anything like this and could it help?

The code is extensive, but the event call is as follows:
public Map<Id,Event> hasActivityforUser(List<Id> userids,Datetime starttime, Datetime endtime){

		Map<Id,Event> calendar = new Map<Id,Event>();

		List<Event> events =[
						SELECT
							ID,
							WhoId,
							OwnerId
						FROM
							Event
						WHERE
							(OwnerId IN :userids
						AND
							((StartDateTime <=:starttime
						AND
							EndDateTime	>=:starttime)	
						OR
							(StartDateTime <=:endtime
						AND
							EndDateTime	>=:endtime))
						AND 
							status__c = 'Aberta')
		];
		for (Event ev : events) {
		   calendar.put(ev.OwnerId,ev);
		}
		
		return calendar;
	}
Map<Id,Event> calendar =  EventDAO.getInstance().hasActivityforUser(ids,evt.StartDateTime,evt.EndDateTime);

        for(Id id : ids){
            if(calendar.isEmpty() || !calendar.containsKey(id)){
               evt.OwnerId = id;
               return;
            }
        }

Advice for this situation will be great help as well.
Thanks,
Best Answer chosen by Olavo Zapata
Olavo ZapataOlavo Zapata
We found the solution by ourself.

The change needs to be done on the class definition.
Before:
public with sharing class EventDAO
After we change to "without sharing"
With this, the SELECT of Event run as an Admin and not as an SalesRep. That doesn't have access to all events.