-
Notifications
You must be signed in to change notification settings - Fork 22
/
BestSellingProductsReport.cs
86 lines (76 loc) · 3.26 KB
/
BestSellingProductsReport.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using Nwazet.Commerce.Models;
using Nwazet.Commerce.Models.Reporting;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
using Orchard.Core.Title.Models;
using Orchard.Localization;
namespace Nwazet.Commerce.Reports {
public class BestSellingProductsReport : ICommerceReport {
private readonly IContentManager _contentManager;
public BestSellingProductsReport(IContentManager contentManager) {
_contentManager = contentManager;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public string Name {
get { return T("Best Sellers").Text; }
}
public string Description {
get { return T("Best selling products as a percentage of the total number of products sold.").Text; }
}
public string DescriptionColumnHeader {
get { return T("Product").Text; }
}
public string ValueColumnHeader {
get { return T("Percentage of total number of products sold").Text; }
}
public string ValueFormat {
get { return "p"; }
}
public ChartType ChartType {
get { return ChartType.Doughnut; }
}
public ReportData GetData(DateTime startDate, DateTime endDate, TimePeriod granularity) {
var orders = _contentManager
.Query<CommonPart, CommonPartRecord>("Order")
.Where(r =>
r.CreatedUtc >= startDate.ToUniversalTime()
&& r.CreatedUtc <= endDate.ToUniversalTime())
.Join<OrderPartRecord>()
.Where(order => order.Status != OrderPart.Cancelled)
.List()
.ToList();
var totalQuantities = new Dictionary<int, int>();
foreach (var order in orders) {
var checkoutItems = order.As<OrderPart>().Items;
foreach (var checkoutItem in checkoutItems) {
var productId = checkoutItem.ProductId;
if (totalQuantities.ContainsKey(productId)) {
totalQuantities[productId] += checkoutItem.Quantity;
}
else {
totalQuantities.Add(productId, checkoutItem.Quantity);
}
}
}
var totalProductsSold = totalQuantities.Values.Sum();
var products = _contentManager.GetMany<TitlePart>(
totalQuantities.Keys,
VersionOptions.Published,
QueryHints.Empty)
.ToDictionary(title => title.Id, title => title.Title);
return new ReportData {
DataPoints = totalQuantities
.Select(q => new ReportDataPoint {
Description = products.ContainsKey(q.Key) ? products[q.Key] : q.Key.ToString(),
Value = q.Value,
ValueString = T("{0:p} ({1})", (double) q.Value/totalProductsSold, q.Value).Text
})
.OrderByDescending(q => q.Value)
};
}
}
}