Skip to main content
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Source Link

Utitlising Matt'sMatt's excellent answer here is something I've come up with.

Utitlising Matt's excellent answer here is something I've come up with.

Utitlising Matt's excellent answer here is something I've come up with.

Source Link
dreza
  • 6.4k
  • 2
  • 29
  • 42

I can't shake this feeling that you could use grouping to get the same result of totaling up the sales of the month hence effectively doing all of the hard work in SQL and limiting the amount of queries required.

Utitlising Matt's excellent answer here is something I've come up with.

public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)
{    
    // utitilising the method suggested by Mats Mug below
    var team = GetTeamGoalAndUsers(teamId); 
    var dailySales = GetTeamDailySalesTotal(team.Users);
 
    return dailySales.Select(p => new DailyTeamGoal
     {
        Date = p.Key,
        TeamGogal = team.Goal,
        DailyTotal = p.Value
     });
}
 
private static Dictionary<int, int> GetTeamDailySalesTotal(IEnumerable<ProPit_User> teamMembers)
{
    // Date ranges
    DateTime now = DateTime.Now;
    DateTime dtStartDate = new DateTime(now.Year,now.Month,1);
    int numberOfDaysInMonth = dtStartDate.DaysInMonth();
    DateTime dtEndDate = new DateTime(now.Year,now.Month,numberOfDaysInMonth);  

    // ensure every day has at least an entry for it even if there are 0 sales on that day
    var sales = InitialiseSalesPerMonth(numberOfDaysInMonth);
    
    // Get the total sum of the daily sales for each rep
    var dailySalesTotal = (from o in orders
      where o.DateCompleted >= dtStartDate
      && o.DateCompleted <= dtEndDate
      && (o.Status == 1 || o.Status == 2)
      && o.Kiosk != 0
      && teamMemberIds.Any(m =>m == o.SalesRepID)
      group o by o.DateCompleted.Day into s
      select new {
            Day = s.Key,
            OrderTotal = s.Sum(p => p.OrderTotal)
      }).ToList();
        
    dailySalesTotal.Foreach(p => sales[p.Day] = p.OrderTotal);      
    
    return sales;
}
 
 private Dictionary<int, int> InitialiseSalesPerMonth(int numberOfDays)
 {
    var sales = new Dictionary<int, int>();
    
    for(int i = 1; i <= numberOfDays; i++)
    {
        sales.Add(i, 0);
    }
    
    return sales;
 }