There is a scenario in which we have a territory object and against each territory, we have one to many sales rep. So there is a child object named SalesRep_To_Terr__c. This child object contains an effective date field and isActive flag. For any territory, there might be more than 1 active record in this object but I was needed to get the latest among all the active record. Latest means which has the most recent effective date. So to get that latest effective date first I maintained a Map contains the Sales Rep Id as key and list of SalesRep_To_Terr__c.
Initially, I have maintained a set of all territory
map<String , list<SalesRep_to_Terr__c>> MapUserSRT = new map<String , list<SalesRep_to_Terr__c>>();
Set<Id> sTerr = new Set<Id>(); // contains all the Territory
List<datetime> LstDT ;
datetime maxTDate ;
for(SalesRep_to_Terr__c terr : [select Effective_Date__c,Sales_Representative__c ,Active__c from SalesRep_to_Terr__c where Effective_Date__c != null and Territory__c IN: sTerr and active__c= true order by Effective_Date__c LIMIT 1])
{
if(MapUserSRT.containsKey(terr.Sales_Representative__c))
{
list<SalesRep_to_Terr__c> lstDWP = MapUserSRT.get(terr.Sales_Representative__c);
lstDWP.add(terr);
MapUserSRT.put(terr.Sales_Representative__c, lstDWP);
}
else
{
MapUserSRT.put(terr.Sales_Representative__c, new List<SalesRep_to_Terr__c> { terr });
}
}
|
Now the sole of this topic to get the latest among each territory is given below
for(String UserRec : MapUserSRT.keyset())
{
LstDT = new List<datetime>();
for(SalesRep_to_Terr__c Terr : MapUserSRT.get(UserRec))
{
LstDT.add(Terr.Effective_Date__c);
}
LstDT.sort();
maxTDate = LstDT.get(LstDT.size()-1);
for(SalesRep_to_Terr__c Terr : MapUserSRT.get(UserRec))
{
if(Terr.Effective_Date__c == maxTDate)
{
if(Terr.Active__c)
{
MapUserLTerritory.put(Terr.Territory__c,UserRec);
break;
}
}
}
}
|
The yellow part above actually describes to first fill the list of datetime for each user and then sort it. The default sort function sort the list to Ascending order means the recent date would be at the end of the list on the last index. MaxTDate variable holds the recent date. Then against each Sales rep Territory record check the date and Active flag. Lastly maintained a Map contains the Territory as Key and Sales rep as the value