0

I have written the trigger for user creation to check whether UserType is Standarad one is not.Trigger is on before insert and before update.So how can I get the usertype of the user on before insert.

Trigger

trigger triggerUser on User (before insert, before update, after insert) {

     //validating user with Transcation logic Ends
   // if (!Test.isRunningTest()){
         List<IGT_Licence_Allocation_Transaction__c> ListTransaction = new List<IGT_Licence_Allocation_Transaction__c>();
         Map<String, IGT_Licence_Allocation_Transaction__c> TransactionMap = new Map<String, IGT_Licence_Allocation_Transaction__c>(); 
         set<string> names = new set<string>();
         set<string> emails = new set<string>();
         set<string> userNames = new set<string>();
         set<Id> roleIds = new set<Id>();
         set<Id> profileIds = new set<Id>();

         for(User u : trigger.new){
             if(u.FirstName != null){
                names.add(u.FirstName.trim()+' '+u.LastName.trim()); 
             }
             else
                 names.add(u.LastName.trim());

            // names.add(u.FirstName.trim()+' '+u.LastName.trim());
             emails.add(u.Email);
             userNames.add(u.UserName);
             roleIds.add(u.UserRoleId);
             profileIds.add(u.ProfileId);

         }          

        Map<Id,Profile> profileMap = new Map<Id,Profile>([select id,name,UserLicense.Name from profile where id in :profileIds]);                   
        Map<Id,UserRole> roleMap = new Map<Id,UserRole>([select id,Name from UserRole where id in :roleIds]);


        for(IGT_Licence_Allocation_Transaction__c objTransaction : [Select id,User_Full_Name__c,Username__c,Email__c,Related_User__c,From_Department__c,From_Cost_Center__c,
                                                                    Role__c,Profile__c,User_License__c,Alias__c,name from IGT_Licence_Allocation_Transaction__c  
                                                                    where RecordType.DeveloperName='Create_User' AND Status__c  = 'Approved' 
                                                                    and User_Full_Name__c in :names and Email__c in :emails and Username__c in :userNames])


            TransactionMap.put(objTransaction.User_Full_Name__c.trim() +'_'+objTransaction.Email__c+'_'+objTransaction.Username__c, objTransaction);

        if((Trigger.isBefore && Trigger.isInsert)  && (Trigger.isInsert || Trigger.isUpdate)){

            for(User u : trigger.new){  
            system.debug('UserType----->'+u.UserType);
             if(u.UserType == 'Standard'){//user type 
             system.debug('In IF-------------->');
              string userName =' '; 
               if(u.FirstName != null){
                   userName = u.FirstName.trim()+' '+u.LastName.trim()+'_'+u.Email+'_'+u.UserName;
               }else{
                   userName = u.LastName.trim()+'_'+u.Email+'_'+u.UserName;
               }
               System.debug('userName detail ---->'+userName);
               //Integer.valueOf(userName+'>>'+TransactionMap.keySet());

                if(TransactionMap.containsKey(userName)){
                    System.debug('Map Contains Record ---->');
                    IGT_Licence_Allocation_Transaction__c objTrans = TransactionMap.get(userName);

                    if(objTrans.Related_User__c!= null){
                      if(!Test.isRunningTest())  u.addError('This user has already been provisioned');                       
                    } 
                    else{      

                        if(objTrans.User_License__c!=profileMap.get(u.ProfileId).UserLicense.Name){                            
                          if(!Test.isRunningTest())   u.addError('There is no approved License Allocation Transaction for this License Type');                                
                        }                           
                        else{
                            Boolean isValidRoleOrProfile=true;
                            UserRole objRole = roleMap.get(u.UserRoleId);
                            if(objRole!=null){
                                if(objTrans.Role__c!=null && roleMap.get(u.UserRoleId).Name!=objTrans.Role__c){                     
                                    isValidRoleOrProfile = false;
                                }
                            }else{
                                isValidRoleOrProfile = false;
                            }
                            if(objTrans.Profile__c!=null && profileMap.get(u.ProfileId).Name!=objTrans.Profile__c){                     
                                isValidRoleOrProfile = false;
                            }
                            if(isValidRoleOrProfile){
                                u.IGT_Department__c =objTrans.From_Department__c;
                                u.IGT_Cost_Center__c = objTrans.From_Cost_Center__c;
                                u.User_Creation_Transaction__c=objTrans.name;
                            }
                            else
                               if(!Test.isRunningTest()) u.addError('There is no approved License Allocation Transaction for selected Role or Profile');                                                     
                        }
                    }

                }else
                  if(!Test.isRunningTest())  u.addError('There is no approved License Allocation Transaction to create this user.');
             }
         }
   }    

       if (Trigger.isBefore) {

            for(User u : trigger.new){
                // sandbox email addresses cause an issue, so don't copy them
                if (u.Username != null && u.Username.endsWith('@igt.com')) {
                    u.Email_ID__c = u.Username;
                }

                if (Trigger.isInsert) {
                    u.DigestFrequency = 'D';                    
                }
            } 

            if(Trigger.isUpdate){
                set<id> userIdset = new set<id>();

                for(user u:trigger.new){
                    if(trigger.oldMap.get(u.id).isactive && !u.isactive){
                        userIdset.add(u.id);                           
                    }
                }

                set<Id> approvedUserIds = new Set<Id>();

                //list<IGT_Licence_Allocation_Transaction__c> listTransaction = new list<IGT_Licence_Allocation_Transaction__c>([select id,Related_User__c FROM IGT_Licence_Allocation_Transaction__c WHERE Status__c='Approved' and Related_User__c in :userIdset and recordtype.DeveloperName='Deactivate_User']);
                for(IGT_Licence_Allocation_Transaction__c objTrans : [select id,Related_User__c FROM IGT_Licence_Allocation_Transaction__c WHERE Status__c='Approved' and Related_User__c in :userIdset and recordtype.DeveloperName='Deactivate_User']){
                    approvedUserIds.add(objTrans.Related_User__c);
                }

                for(User ObjUser : trigger.New){

                    Boolean isUserDeactivated = trigger.oldMap.get(ObjUser.id).isactive && !ObjUser.isactive;
                    if(isUserDeactivated && !approvedUserIds.contains(ObjUser.Id)){
                       if(!Test.isRunningTest()) ObjUser.addError('There is no approved License Allocation Transaction for selected User');
                    }
                }                   

            }

        }

Test class

@isTest
private  class TriggerTest {

    @isTest
    public static void testUserTrigger() 
    {

        User u = new User();
        u = [Select Id, Email_Id__c, Username, City from User WHERE IsActive = true limit 1];
        System.debug('User Details Before Update---> '+u);
        System.runAs(u){
            u.City = 'Sao Paulo';
            try{
                update(u);
            }
            catch(DmlException de){
            }

        }
        u = [Select Id,Name, Email, Email_Id__c, Username, City from User WHERE IsActive = true limit 1];  
        System.debug('User Details After Update---> '+u);
        //system.assertEquals(u.Email, U.Email_Id__c); // doesn't work in sandbox

       RecordType ObjRecordType = [Select Name, Id From RecordType where sObjectType='IGT_Licence_Allocation_Transaction__c' AND DeveloperName = 'Create_User'];

        IGT_Department__c ObjDepartment = new IGT_Department__c();
        ObjDepartment.Name = 'Test Department';
        ObjDepartment.CurrencyIsoCode = 'EUR';
        insert ObjDepartment;

        IGT_Licence_Allocation_Type__c ObjAllocation = new IGT_Licence_Allocation_Type__c();
        ObjAllocation.name = 'Test Allocation';
        ObjAllocation.Department__c = ObjDepartment.id;
        ObjAllocation.Licence_Type__c = 'Salesforce Platform';
        ObjAllocation.Allocated__c = 5;
        insert ObjAllocation;

        IGT_Cost_Center__c ObjCostCenter = new IGT_Cost_Center__c();
        ObjCostCenter.Name = 'Test Cost Center';
        ObjCostCenter.CurrencyIsoCode = 'USD';
        ObjCostCenter.Department__c = ObjDepartment.id;
        insert ObjCostCenter;

        IGT_User_Licence_Type__c objUserLicence = new IGT_User_Licence_Type__c();
        objUserLicence.Department__c = ObjDepartment.Id;
        objUserLicence.Cost_Center__c = ObjCostCenter.Id;
        objUserLicence.Related_User__c = UserInfo.getUserId();
        objUserLicence.Licence__c = 'Salesforce Platform';
        objUserLicence.Licence_Type__c = UserInfo.getUserId()+'-'+'Salesforce Platform';
        insert objUserLicence;  
        User objUserOne = [SELECT Id, Username, FirstName, LastName, Email FROM User WHERE Id =: UserInfo.getUserId()];

        //IGT_TestDataUtility_LicenseAlloc objUtil = new IGT_TestDataUtility_LicenseAlloc(); 
        //IGT_Licence_Allocation_Transaction__c ObjTransaction = objUtil.crtIGT_LAT_CreateUser('[email protected]', 'Create_User', UserInfo.getUserId());
        IGT_Licence_Allocation_Transaction__c objLAT = new IGT_Licence_Allocation_Transaction__c();
        objLAT.From_Department__c = ObjDepartment.Id;
        objLAT.From_Cost_Center__c = ObjCostCenter.Id;
        objLAT.User_License__c = 'Salesforce Platform';
         //objLAT.Other_Licence_Types__c = 'Conga';
        objLAT.RecordTypeId = ObjRecordType.Id;
        objLAT.Status__c  = 'Approved';
         objLAT.User_First_name__c = objUserOne.FirstName;
         objLAT.User_Last_name__c = objUserOne.LastName;
         objLAT.Username__c = objUserOne.Username;
         objLAT.Email__c = '[email protected]';
         objLAT.Employee_Number__c = 'E001';
         objLAT.Email__c = objUserOne.Email;
         //objLAT.Profile__c = 'Standard User';
         //objLAT.Role__c = 'Accounting';
         //objLAT.Locale__c = 'en_US';
        // objLAT.Time_Zone__c = 'America/Los_Angeles';
        objLAT.Like_User__c = UserInfo.getUserId();
        insert objLAT;

        User Objuser = new User();
         Profile objProfile = [select id from profile where Name='Standard Platform User']; 
         UserRole objR = [select id, name from UserRole where name='Accounting'];        
         Objuser.FirstName = 'ABD';
         Objuser.LastName = 'XY-Z';
         Objuser.Email = '[email protected]';
         Objuser.Username = '[email protected]';
         Objuser.CompanyName = 'TEST';
         Objuser.Title = 'title';
         Objuser.Alias = 'AXYZ';
         Objuser.UserRoleId = objR.Id;
         objUser.ProfileId = objProfile.Id;
         Objuser.TimeZoneSidKey = 'America/Los_Angeles';
         Objuser.EmailEncodingKey = 'UTF-8';
         Objuser.LanguageLocaleKey = 'en_US';                  
         Objuser.LocaleSidKey = 'en_US';


         system.runAs(new User(Id = UserInfo.getUserId())){          
            //insert Objuser;
            objUserOne = [SELECT Id FROM User WHERE Id =: UserInfo.getUserId()];
            try{
                update objUserOne;
            }catch(DMLException e){
                String message = e.getMessage();
                System.assert(message.contains('There is no approved License Allocation Transaction to create this user.'), 'message=' + message);                
            }
         }
    }

    @isTest
    public static void testUserTriggerOne() 
    {

        User u = new User();
        u = [Select Id, Email_Id__c, Username, City from User WHERE IsActive = true limit 1];
        System.debug('User Details Before Update---> '+u);
        System.runAs(u){
            u.City = 'Sao Paulo';
            try{
                update(u);
            }
            catch(DmlException de){
            }

        }
        u = [Select Id,Name, Email, Email_Id__c, Username, City from User WHERE IsActive = true limit 1];  
        System.debug('User Details After Update---> '+u);
        //system.assertEquals(u.Email, U.Email_Id__c); // doesn't work in sandbox

       RecordType ObjRecordType = [Select Name, Id From RecordType where sObjectType='IGT_Licence_Allocation_Transaction__c' AND DeveloperName = 'Create_User'];

        IGT_Department__c ObjDepartment = new IGT_Department__c();
        ObjDepartment.Name = 'Test Department';
        ObjDepartment.CurrencyIsoCode = 'EUR';
        insert ObjDepartment;

        IGT_Licence_Allocation_Type__c ObjAllocation = new IGT_Licence_Allocation_Type__c();
        ObjAllocation.name = 'Test Allocation';
        ObjAllocation.Department__c = ObjDepartment.id;
        ObjAllocation.Licence_Type__c = 'Salesforce';
        ObjAllocation.Allocated__c = 5;
        insert ObjAllocation;

        IGT_Cost_Center__c ObjCostCenter = new IGT_Cost_Center__c();
        ObjCostCenter.Name = 'Test Cost Center';
        ObjCostCenter.CurrencyIsoCode = 'USD';
        ObjCostCenter.Department__c = ObjDepartment.id;
        insert ObjCostCenter;

        IGT_User_Licence_Type__c objUserLicence = new IGT_User_Licence_Type__c();
        objUserLicence.Department__c = ObjDepartment.Id;
        objUserLicence.Cost_Center__c = ObjCostCenter.Id;
        objUserLicence.Related_User__c = UserInfo.getUserId();
        objUserLicence.Licence__c = 'Salesforce Platform';
        objUserLicence.Licence_Type__c = UserInfo.getUserId()+'-'+'Salesforce';
        insert objUserLicence;  
        User objUserOne = [SELECT Id, Username, FirstName, LastName, Email FROM User WHERE Id =: UserInfo.getUserId()];

        //IGT_TestDataUtility_LicenseAlloc objUtil = new IGT_TestDataUtility_LicenseAlloc(); 
        //IGT_Licence_Allocation_Transaction__c ObjTransaction = objUtil.crtIGT_LAT_CreateUser('[email protected]', 'Create_User', UserInfo.getUserId());
        IGT_Licence_Allocation_Transaction__c objLAT = new IGT_Licence_Allocation_Transaction__c();
        objLAT.From_Department__c = ObjDepartment.Id;
        objLAT.From_Cost_Center__c = ObjCostCenter.Id;
        objLAT.User_License__c = 'Salesforce';
         //objLAT.Other_Licence_Types__c = 'Conga';
        objLAT.RecordTypeId = ObjRecordType.Id;
        objLAT.Status__c  = 'Approved';
         objLAT.User_First_name__c = objUserOne.FirstName;
         objLAT.User_Last_name__c = objUserOne.LastName;
         objLAT.Username__c = objUserOne.Username;
         objLAT.Email__c = '[email protected]';
         objLAT.Employee_Number__c = 'E001';
         objLAT.Email__c = objUserOne.Email;
         //objLAT.Profile__c = 'Standard User';
         //objLAT.Role__c = 'Accounting';
         //objLAT.Locale__c = 'en_US';
        // objLAT.Time_Zone__c = 'America/Los_Angeles';
        objLAT.Like_User__c = UserInfo.getUserId();
        objLAT.Related_User__c = UserInfo.getUserId();
        insert objLAT;

        User Objuser = new User();
         Profile objProfile = [select id from profile where Name='Standard Platform User']; 
         UserRole objR = [select id, name from UserRole where name='Accounting'];        
         Objuser.FirstName = 'ABD';
         Objuser.LastName = 'XY-Z';
         Objuser.Email = '[email protected]';
         Objuser.Username = '[email protected]';
         Objuser.CompanyName = 'TEST';
         Objuser.Title = 'title';
         Objuser.Alias = 'AXYZ';
         Objuser.UserRoleId = objR.Id;
         objUser.ProfileId = objProfile.Id;
         Objuser.TimeZoneSidKey = 'America/Los_Angeles';
         Objuser.EmailEncodingKey = 'UTF-8';
         Objuser.LanguageLocaleKey = 'en_US';                  
         Objuser.LocaleSidKey = 'en_US';


         system.runAs(new User(Id = UserInfo.getUserId())){          
            //insert Objuser;
            objUserOne = [SELECT Id FROM User WHERE Id =: UserInfo.getUserId()];
            try{
                update objUserOne;
            }catch(DMLException e){
                String message = e.getMessage();
                System.assert(message.contains('There is no approved License Allocation Transaction to create this user.'), 'message=' + message);                
            }
         }
    }    

    @isTest
    public static void testUserMethod(){
        User u = new User();
        u = [Select Id,Name, Email, Email_Id__c, Username, City from User WHERE IsActive = true limit 1];  
        System.debug('User Details After Update---> '+u);
        //system.assertEquals(u.Email, U.Email_Id__c); // doesn't work in sandbox

       RecordType ObjRecordType = [Select Name, Id From RecordType where sObjectType='IGT_Licence_Allocation_Transaction__c' AND DeveloperName = 'Create_User'];

        IGT_Department__c ObjDepartment = new IGT_Department__c();
        ObjDepartment.Name = 'Test Department';
        ObjDepartment.CurrencyIsoCode = 'EUR';
        insert ObjDepartment;

        IGT_Licence_Allocation_Type__c ObjAllocation = new IGT_Licence_Allocation_Type__c();
        ObjAllocation.name = 'Test Allocation';
        ObjAllocation.Department__c = ObjDepartment.id;
        ObjAllocation.Licence_Type__c = 'Salesforce Platform';
        ObjAllocation.Allocated__c = 5;
        insert ObjAllocation;

        IGT_Cost_Center__c ObjCostCenter = new IGT_Cost_Center__c();
        ObjCostCenter.Name = 'Test Cost Center';
        ObjCostCenter.CurrencyIsoCode = 'USD';
        ObjCostCenter.Department__c = ObjDepartment.id;
        insert ObjCostCenter;

        IGT_Licence_Allocation_Transaction__c ObjTransaction = new IGT_Licence_Allocation_Transaction__c();
        ObjTransaction.User_First_Name__c = 'ABD';
        objTransaction.Related_User__c = u.id;
        ObjTransaction.User_Last_Name__c = 'XYZ';
        ObjTransaction.Email__c = '[email protected]';
        ObjTransaction.Username__c = '[email protected]';
        ObjTransaction.From_Department__c = ObjDepartment.id;
        ObjTransaction.From_Cost_Center__c = ObjCostCenter.id;
        objTransaction.Profile__c='Standard User';
        objTransaction.Role__c = 'Accounting';
        objTransaction.Alias__c= 'AXYZ';
        ObjTransaction.User_License__c = 'Salesforce Platform';
        ObjTransaction.Nickname__c = 'testnick';
        ObjTransaction.RecordTypeId = ObjRecordType.id;
        ObjTransaction.Status__c = 'Approved';
        ObjTransaction.Locale__c = 'en_US';
        ObjTransaction.Time_Zone__c = 'America/Los_Angeles';
        insert ObjTransaction;


        User Objuser = new User();
         Profile objProfile = [select id from profile where Name='Standard Platform User']; 
         //UserRole objR = null;        
         Objuser.FirstName = 'ABD';
         Objuser.LastName = 'XY-Z';
         Objuser.Email = '[email protected]';
         Objuser.Username = '[email protected]';
         Objuser.CompanyName = 'TEST';
         Objuser.Title = 'title';
         Objuser.Alias = 'AXYZ';
        // Objuser.UserRoleId = objR.Id;
         objUser.ProfileId = objProfile.Id;
         Objuser.TimeZoneSidKey = 'America/Los_Angeles';
         Objuser.EmailEncodingKey = 'UTF-8';
         Objuser.LanguageLocaleKey = 'en_US';                  
         Objuser.LocaleSidKey = 'en_US';       
         Objuser.isActive = true;
         //insert Objuser;

         system.runAs(new User(Id = UserInfo.getUserId())){

             insert Objuser;
             System.debug('Objuser ->'+Objuser);             
               Objuser = [select UserType From User where id =:Objuser.id];
             // System.assertEquals('There is no approved License Allocation Transaction to create this user.',result.getErrors()[0].getMessage());

              //System.assertEquals('This user has already been provisioned',result.getErrors()[0].getMessage());

        }
    }

    @isTest
    public static void testOppProductIsDailyTrigger() 
    {
        Account acct = new Account(
            Name = 'TestAccount'
        );
        insert acct;

        Product2 pIsDaily = new Product2(
            CanUseQuantitySchedule = true,
            CanUseRevenueSchedule = true,
            IsActive = true,
            IsDaily__c = true,
            Name = 'TestProduct1',
            NumberOfQuantityInstallments = 12,
            NumberOfRevenueInstallments = 12,
            QuantityInstallmentPeriod = 'Monthly',
            QuantityScheduleType = 'Repeat'
        );

        insert pIsDaily;

        Product2 pNotDaily = new Product2(
            CanUseQuantitySchedule = true,
            CanUseRevenueSchedule = true,
            IsActive = true,
            IsDaily__c = false,
            Name = 'TestProduct1',
            NumberOfQuantityInstallments = 12,
            NumberOfRevenueInstallments = 12,
            QuantityInstallmentPeriod = 'Monthly',
            QuantityScheduleType = 'Repeat'
        );

        insert pNotDaily;

        Pricebook2 pb2 = [SELECT Id FROM Pricebook2 WHERE IsStandard = true LIMIT 1];

        PricebookEntry pbe1 = new PricebookEntry(
            IsActive = true,
            UnitPrice = 10.00, 
            Pricebook2Id = pb2.Id,
            Product2Id = pIsDaily.Id
        );
        insert pbe1;


        PricebookEntry pbe2 = new PricebookEntry(
            IsActive = true,
            UnitPrice = 10.00, 
            Pricebook2Id = pb2.Id,
            Product2Id = pNotDaily.Id
        );
        insert pbe2;



        String stageName = [SELECT MasterLabel FROM OpportunityStage WHERE IsClosed = false AND IsWon = false AND IsActive = true LIMIT 1].MasterLabel;

        Opportunity opp1 = new Opportunity(
            Name = 'TestOpp',
            StageName = stageName,
            CloseDate = Date.today()
        );
        insert opp1;

        OpportunityLineItem lineItem1 = new OpportunityLineItem(
            OpportunityId = opp1.Id,
            UnitPrice = 10.00,
            Quantity = -4,
            PricebookEntryId = pbe1.Id      
        );

        Opportunity opp2 = new Opportunity(
            Name = 'TestOpp',
            StageName = stageName,
            CloseDate = Date.today(),
            RecordTypeId = [SELECT Id FROM RecordType where SObjectType = 'Opportunity' LIMIT 1].Id
        );
        insert opp2;

        OpportunityLineItem lineItem2 = new OpportunityLineItem(
            OpportunityId = opp2.Id,
            UnitPrice = 10.00,
            Quantity = 3,
            PricebookEntryId = pbe1.Id      
        );


        insert new List<OpportunityLineItem> {lineItem1, lineItem2};


        OpportunityLineItem afterInsert = [SELECT Id, UnitPrice FROM OpportunityLineItem WHERE Id = :lineItem1.Id LIMIT 1];
        System.debug('UNIT PRICE = ' + afterInsert.UnitPrice);
        //System.assert(afterInsert.UnitPrice == 300.00);

        afterInsert = [SELECT Id, UnitPrice FROM OpportunityLineItem WHERE Id = :lineItem2.Id LIMIT 1];
        //System.assert(afterInsert.UnitPrice == 10.00);
    }
}
2
  • FYI, there's no point in using TRIM on fields loaded from the database, as they will never have leading or trailing spaces.
    – sfdcfox
    Commented Feb 4, 2017 at 8:09
  • okay i will remove that Commented Feb 4, 2017 at 8:28

1 Answer 1

0

This is answering the "how can I get the usertype of the user on before insert" part.

The UserType entry in this User documentation includes this:

The category of user license. Each UserType is associated with one or more UserLicense records. Each UserLicense is associated with one or more profiles.

I presume the field is populated as part of the User insert (or update) based on the Profile that is chosen.

So if you absolutely need to do something in before insert, you may be able to query the Profile and UserLicense objects to obtain the information. But the first thing I would try is to restructure the trigger to do the work in the after insert where the User.UserType could be queried to get its value.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .