Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
3.0 kB
5
Indexable
Never
@isTest
public class Helper_classetest {
	@isTest
    public static void testami(){
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
         User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.comm');
        Profile p1 = [SELECT Id FROM Profile WHERE Name='Standard User'];
         User u1 = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.commm');

       System.runAs(u) {
        list<account> lista = new list<account>();
        for (integer i = 0; i<16; i++){
            account a = new account(name='nome' + i, ownerid = u.id);
            lista.add(a);
            }
            insert lista;
    	}
        
        System.runAs(u1) {
        	account a = new account(name='nome', ownerid = u1.id);
            insert a;
        	}
        
        list<account> listainput = new list<account>();
        for (integer i = 0; i<16; i++){
            account a = new account(name='nome' + i, ownerid = u.id);
            listainput.add(a);
        }
        
        test.startTest();
        Helper.CheckRecord(listainput);
        test.stopTest();
        
        list<AggregateResult> appoggio = [select ownerid, count(id) numrecord from account group by ownerid];
        System.debug(appoggio);
      
    	}
    }







public class Helper {
    public static void CheckRecord(list<account> accs) {
        Integer cnt = 0;
        Integer sizeaccount = accs.size();
        ID IdProp = accs.get(0).ownerid;
        list<AggregateResult> appoggio = [select ownerid, count(id) numrecord from account where ownerid =: IdProp group by ownerid];
        Integer numAccount = (Integer) appoggio.get(0).get('numrecord');
        if (numAccount + sizeaccount > 20) {
            cnt = (sizeaccount + numAccount) - 20;
            if (cnt > 0) {
                list<account> avanzi = new list<account>();
                for (integer i=cnt; i>0; i--) {
                	avanzi.add(accs.get(i));
                }
                list<AggregateResult> app2 = [select ownerid, count(id) from account group by ownerid having count(id) > 0 order by count(id) ASC LIMIT 1];
                ID NuovoProp = (ID) app2.get(0).get('ownerid');
                for (account acc:avanzi) {
                    if (IdProp == Nuovoprop) acc.addError('Non ci sono altri record di altri account');
                    else acc.ownerid = nuovoProp;
            	}
            }
        }  
    }
}