49 lines
1.6 KiB
Plaintext
49 lines
1.6 KiB
Plaintext
trigger ActiveUserCountTrigger on User (after insert, after update) {
|
|
|
|
Boolean needsRecount = false;
|
|
|
|
// Collect all ProfileIds to check their license type
|
|
Set<Id> profileIds = new Set<Id>();
|
|
for (User u : Trigger.new) {
|
|
profileIds.add(u.ProfileId);
|
|
}
|
|
if (Trigger.isUpdate) {
|
|
for (User u : Trigger.oldMap.values()) {
|
|
profileIds.add(u.ProfileId);
|
|
}
|
|
}
|
|
|
|
// Query which profiles have a Salesforce license
|
|
Set<Id> sfLicenseProfileIds = new Set<Id>();
|
|
for (Profile p : [SELECT Id FROM Profile WHERE UserLicense.Name = 'Salesforce' AND Id IN :profileIds]) {
|
|
sfLicenseProfileIds.add(p.Id);
|
|
}
|
|
|
|
if (Trigger.isInsert) {
|
|
for (User u : Trigger.new) {
|
|
if (u.IsActive && sfLicenseProfileIds.contains(u.ProfileId)) {
|
|
needsRecount = true;
|
|
break;
|
|
}
|
|
}
|
|
} else if (Trigger.isUpdate) {
|
|
for (User u : Trigger.new) {
|
|
User oldUser = Trigger.oldMap.get(u.Id);
|
|
Boolean isSfLicenseNow = sfLicenseProfileIds.contains(u.ProfileId);
|
|
Boolean wasSfLicenseBefore = sfLicenseProfileIds.contains(oldUser.ProfileId);
|
|
|
|
if (u.IsActive != oldUser.IsActive && (isSfLicenseNow || wasSfLicenseBefore)) {
|
|
needsRecount = true;
|
|
break;
|
|
}
|
|
if (u.ProfileId != oldUser.ProfileId && u.IsActive && (isSfLicenseNow || wasSfLicenseBefore)) {
|
|
needsRecount = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (needsRecount) {
|
|
ActiveUserCountHandler.handleActiveUserCount();
|
|
}
|
|
} |