+ Start a Discussion
StaciStaci 

trigger to count licenses

I have existing code, which doesn't work completely.  I have a custom object called Licenses__c.  I have a trigger that is supposed to update the licenses used and licenses available for a certain group when a new user is created, or an existing user is updated.  I have added new license groups and it doesn't seem to like to update those.  It will update the existing groups just fine.  Not sure why.  I inherited this code, so please let me know if you have questions
 
trigger updateLicense on User (Before Insert, After Insert, Before Update, After Update) 
{
    User cfU = trigger.new[0];
    IF (cfU.UserType != 'CsnOnly')       
    {
    Integer lGroups = [SELECT count() FROM License__c];
            
        ID gID = License__c.SObjectType.getDescribe().getRecordTypeInfosByName().get('License Group').getRecordTypeId();
                
        IF (Trigger.isBefore)
        {
            ID orgId = UserInfo.getOrganizationId();
            IF ((orgId != Label.PROD_ORG_ID) && (lGroups == 0))
                LicenseUser.createLicenseGroups();    
            IF ((Test.isRunningTest()) && (lGroups == 0))
                TestLicenseUser.createTestGroups();

            MAP<String,ID> nuMap = new MAP<String,ID>();
            MAP<ID,Decimal> usedMap = new MAP<ID,Decimal>();
            MAP<ID,Decimal> ownedMap = new MAP<ID,Decimal>(); 
            List<String> inActiveUser = new List<String>();

            for (License__c l : [SELECT ID,Owner_Group_Name__c, Licenses_Used__c, Licenses_Owned__c from License__c where RecordTypeId = :gID]) 
            {
               nuMap.put(l.Owner_Group_Name__c,l.ID);   
               usedMap.put(l.ID,l.Licenses_Used__c);
               ownedMap.put(l.ID,l.Licenses_Owned__c);
            }
            
            system.debug('nuMap------------'+nuMap);
            integer uCount = 0;
            for(User u: Trigger.New)
            {                                
                ID ownerId = nuMap.get(u.SF_License_Owner_Type__c);
                system.debug('ownerId------------'+ownerId);
                system.debug('usedMap------------'+usedMap);
                Decimal usedCnt = usedMap.get(ownerId);
                
                system.debug('usedCnt------------'+usedCnt);
                          
                IF (u.SF_License_Owner_Type__c == null)
                    u.SF_License_Owner_Type__c.addError('The SF License Owner/Type field must be populated.');
            
                IF (u.UserType == 'CsnOnly')
                {
                    uCount++;
                    continue;
                }            

                Boolean noLicense = (usedCnt >= ownedMap.get(ownerId)),
                        deActivate = false,
                        updActive = false,
                        updOwner = false;
                        
                IF (Trigger.isInsert)
                { 
                    IF (noLicense) {deActivate = true;}
                }
            
                IF (Trigger.isUpdate)
                {
                    updActive = (u.IsActive != trigger.old[uCount].IsActive);
                    updOwner = (u.SF_License_Owner_Type__c != trigger.old[uCount].SF_License_Owner_Type__c);
                
                    IF (updActive)        //IF isActive flag changed on user record
                    {
                        IF (u.isActive)    //IF user was activated
                        {
                            IF (noLicense) {deActivate = true;}        //IF no license(s) then de-activate user
                        }
                        ELSE {deActivate = true;}        //User de-activated, flag to update license counts
                    }
                
                    IF (updOwner)        //IF SF_License_Owner_Type__c changed
                    {
                        IF ((u.SF_License_Owner_Type__c != null) && (u.isActive))        //IF License Owner populated and user is active
                        {
                            IF (noLicense) {deActivate = true;}        //IF no license(s) then de-activate user
                        }
                    }
                }
            
                IF (deActivate)
                {                               
                    IF ((!Trigger.isInsert) && (trigger.old[uCount].SF_License_Owner_Type__c != null))    //IF de-activating a user while
                    {                                                                             //License Owner populated or changed
                        ID ownerId2 = nuMap.get(trigger.old[uCount].SF_License_Owner_Type__c);                  
                        Decimal usedCnt2 = usedMap.get(ownerId2);

                        usedMap.remove(ownerId2);
                        usedCnt2--;        //decrement license used count by 1
                        usedMap.put(ownerId2,usedCnt2);  
                    }
                        
                    IF (u.isActive)        //De-Activating user
                    {
                        Trigger.New[uCount].isActive = FALSE;
                        inActiveUser.add(u.firstname + ' ' + u.lastname + ' using License from Group: ' + u.SF_License_Owner_Type__c);                  
                    }
                }
                ELSE        //Activating user
                {
                    system.debug('usedMap before remove------------'+usedMap);
                    usedMap.remove(ownerId);
                    system.debug('usedMap after remove------------'+usedMap);
                    system.debug('usedCnt-----------'+usedCnt);
                    usedCnt++;        //increment license used count by 1
                    usedMap.put(ownerId,usedCnt);            
                }        
                uCount++; 
          
                IF (InActiveUser.size() > 0)        //Notify the user triggering invocation via chatter and email    
                {                                   //that user(s) was/were de-activated due to insufficient licenses
                    Messaging.reserveSingleEmailCapacity(2);  
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                    User u2=[Select email from User where id=:UserInfo.getUserId()];
                    List<String> UserEmail = new List<String>();
                    UserEmail.add(u2.email);
            
                    mail.setToAddresses(UserEmail);
                    mail.setSenderDisplayName('Salesforce Support');
                    mail.setSubject('IMPORTANT: Insufficient Licenses available to Activate users!');

                    String body = 'The following users were de-activated due to insufficient licenses being available: \n';
                    for(Integer i = 0; i < InActiveUser.size(); i++)
                    {
                        body = body + InActiveUser.get(i) + '\n';
                    }
                
                    mail.setPlainTextBody(body);
            
                    postChatterFeedToUser.postToUser(UserInfo.getUserId(),body);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });        
                }
            }
        }

        IF (Trigger.isAfter)
        {        
            List<ID> delUsers = new List<ID>();
            MAP<ID,String> addUsers = new MAP<ID,String>();

            integer userCount = 0;        
            for(User u2 : Trigger.New) 
            {                       
                IF (u2.UserType == 'CsnOnly')
                {
                    userCount++;
                    continue;
                }

                Boolean updActive = false,
                        updOwner = false,
                        isAdd = false,
                        isDel = false;            
                         
                IF (Trigger.isInsert)
                {
                    IF(u2.IsActive) {isAdd = true;}          //IF user is being activated, add to License table      
                }
            
                IF (Trigger.isUpdate)
                {
                    updActive = (u2.IsActive != trigger.old[userCount].IsActive);
                    updOwner = (u2.SF_License_Owner_Type__c != trigger.old[userCount].SF_License_Owner_Type__c);
                
                    IF (updActive)        //IF isActive flag changed on user record
                    {
                        IF (u2.isActive) {isAdd = true;}        //IF user is being activated, add to License table
                        ELSE{isDel = true;}                     //ELSE delete it from License table
                    }
                
                    IF ((updOwner) && (u2.isActive))        //IF updating License Owner on active user
                    {
                        isDel = true;        //Delete from previous group (SF_License_Owner_Type__c before) on License table if needed
                    
                        IF (u2.SF_License_Owner_Type__c != null)
                        {
                            isAdd = true;        //Add to the current group (SF_License_Owner_Type__c after) on License
                        }
                    }
                }
            
                IF (isAdd)
                {
                    addUsers.put(u2.ID,u2.SF_License_Owner_Type__c);        //Add user to license addition list
                }
        
                IF (isDel)
                {
                    IF (trigger.old[userCount].SF_License_Owner_Type__c != null)        //Only delete if prior value existed
                    {
                        delUsers.add(trigger.old[userCount].Id);        //Add user to license removal list
                    }
                }
                                           
                UserCount++;
            }  
    
            IF (delUsers.size() > 0)
            {
                LicenseUser.delLicenseUser(delUsers);        
            }
    
            IF (addUsers.size() > 0)
            {
                LicenseUser.addLicenseUser(addUsers);
            }
        }
    }    
}

 
Abhilash Mishra 13Abhilash Mishra 13
Hi,
Not able to understand what you are trying to do at Line 62. and after that.
updActive = (u.IsActive != trigger.old[uCount].IsActive);
How these two users will be related as value of  uCount is totally depends on userType= 'csnOnly'
so it might to change to any number depending upo UserType. its like comparing two random users.

-Abhilash