Is a User logged in

Platform Change : As of v29.0 you can now query the AuthSession object . According to the session timeout documentation, the last LastModifiedDate on the AuthSession gets updated when there is activity by the user in the last half of his or her the session.

An approach making use of the above : If you are prepared to reduce the session timeout to 15 minutes (the minimum value permitted) , you can arrive at a fairly viable solution that's accurate to within at least 15 minutes or even better if the last activity by a user was within 7.5 minutes of their respective session expiring.

Again its worth repeating the advice in earlier answers - no approach will be 100% accurate

Heres an experiment I performed at 15:15 which appears to validate the salesforce documentation links above - I initiated a standard UI session and a workbench session straight after.

Under workbench I ran the following query

[ 
  SELECT   LastModifiedDate,LoginType,NumSecondsValid,SessionType,UsersId
  FROM AuthSession 
  WHERE SessionType = 'UI'
        AND LoginType = 'Application'
]

at 15:20 the query returned

AuthSession:{ ... LastModifiedDate=2014-01-26 15:15:12, ...}

At 15:23

  • I navigated to a detail view of an Account
  • I then ran the same query under workbench which returned

AuthSession:{... LastModifiedDate=2014-01-26 15:22:16, ...}

Summary

The basic approach for the "approximate reps logged in table" is therefore as follows:

  • Set the session timeout to the minimum available ( 15 minutes ).

  • Create a SOQL query over the AuthSession object
    filtering on SessionType = 'UI' AND LoginType = 'Application' returning userIds

  • Although Salesforce appears to eliminate expired session records, consider dropping any records WHERE System.Now() > authSession.LastModifiedDate.AddSeconds(authSession.NumSecondsValid)

  • Finally filter this list of UserIds to only those Ids representing Reps


The bottom line is that you can't do this in a reliable way using Apex - we've had a few tries at it. The best we've been able to come up with is a sidebar component that updates a custom field on the user or a related custom object whenever it is rendered. However, given the web nature of the Salesforce UI, you only know what the user is doing when they choose to interact with a page, so if they close the browser immediately after opening that page you have no way of knowing it.

You could use the mechanism I've outlined above to figure out reps who were recently seen on the system, then assign them the lead, but add some time based workflow that takes action if the lead doesn't get updated inside a period of time - kind of like case escalation. It will still be rather hit and miss though.