+ Start a Discussion
brozinickrbrozinickr 

Count Tasks Assigned to Certain Users in a Roll Up Summary Trigger

Hello,

 

I have a trigger that I have written that writes the Activity Count for an Account.  I have been now given the requirement that it should only count tasks for users that have the department of Account Management.  I'm not sure how to add this functionality to this trigger. I'm figuring that I am going to have get the set of user ids with a department like account management.  Then somehow map it to the task (task id as the key, user as the value?)  Then is it possible to map one map to another one?  so I could map accmap to task map?  Is there another easier way to do this?

 

 

trigger Activity_Count on Task (after insert, after update, after delete) 
{
    List<Id> taskIds = new List<Id>();
    List<Id> accIds = new List<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    List<Account> updateList = new List<Account>();  // edited
    String accPrefix = Account.sObjectType.getDescribe().getKeyPrefix();
    
    for (Task t : Trigger.isDelete ? Trigger.old : Trigger.new)
    {
        taskIds.add(t.Id);
        String str = t.whatId;
        if(str != null && str.startsWith(accPrefix))     // Task belongs to Account
          {
            accIds.add(t.whatId);
          }
    }
    
    if(accIds.size() > 0)
    {
        for(Account ac : [SELECT Id, Activity_Count__c FROM Account WHERE Id in :accIds])
        {
            accMap.put(ac.Id,ac);
        }

        for(AggregateResult ar : [SELECT Count(Id) c, WhatId w FROM Task WHERE whatId IN :accIds and Subject Like 'Call%' and CreatedDate = This_Month and IsBigDealRep__c = false GROUP BY WhatId])
        {
            Account acc = new Account();
            
            string str = string.valueOf(ar.get('w'));
            
            acc = accMap.get(str);   // Edited   //
            acc.Activity_Count__c = Integer.valueOf(ar.get('c'));   // Edited
            
            updateList.add(acc);
        }
    }
    
    if(updateList.size() > 0)
    {
        update updateList;
    
    }
}