4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
1
2
|
using System.Globalization;
using System.Text.Json;
|
3b307558
李曜臣
统计接口实现
|
3
4
|
using FoodLabeling.Application.Contracts.Dtos.Dashboard;
using FoodLabeling.Application.Contracts.IServices;
|
49755ef0
李曜臣
6-12代码优化
|
5
|
using FoodLabeling.Application.Helpers;
|
3b307558
李曜臣
统计接口实现
|
6
7
|
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
|
4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
8
|
using SqlSugar;
|
3b307558
李曜臣
统计接口实现
|
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
|
using Volo.Abp.Application.Services;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Application.Services;
/// <summary>
/// Dashboard 统计服务(美国版)
/// </summary>
public class DashboardAppService : ApplicationService, IDashboardAppService
{
private readonly ISqlSugarDbContext _dbContext;
private readonly ISqlSugarRepository<LocationAggregateRoot, Guid> _locationRepository;
private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
public DashboardAppService(
ISqlSugarDbContext dbContext,
ISqlSugarRepository<LocationAggregateRoot, Guid> locationRepository,
ISqlSugarRepository<UserAggregateRoot, Guid> userRepository)
{
_dbContext = dbContext;
_locationRepository = locationRepository;
_userRepository = userRepository;
}
/// <inheritdoc />
public async Task<DashboardOverviewOutputDto> GetOverviewAsync()
{
var now = DateTime.Now;
var todayStart = now.Date;
var tomorrowStart = todayStart.AddDays(1);
var yesterdayStart = todayStart.AddDays(-1);
var weekStart = todayStart.AddDays(-6);
var prevWeekStart = todayStart.AddDays(-13);
|
49755ef0
李曜臣
6-12代码优化
|
44
45
46
47
48
49
50
|
var db = _dbContext.SqlSugarClient;
var scopeLocationIds = await DashboardScopeHelper.ResolveDashboardLocationIdsAsync(CurrentUser, _dbContext);
var platformAdminUserIds = await DashboardScopeHelper.GetPlatformAdminUserIdStringsAsync(db);
var printTodayQuery = DashboardScopeHelper.ApplyPrintTaskLocationScope(
db.Queryable<FlLabelPrintTaskDbEntity>(), scopeLocationIds);
var printedToday = await printTodayQuery
|
3b307558
李曜臣
统计接口实现
|
51
52
|
.CountAsync(x => x.CreationTime >= todayStart && x.CreationTime < tomorrowStart);
|
49755ef0
李曜臣
6-12代码优化
|
53
54
|
var printedYesterday = await DashboardScopeHelper.ApplyPrintTaskLocationScope(
db.Queryable<FlLabelPrintTaskDbEntity>(), scopeLocationIds)
|
3b307558
李曜臣
统计接口实现
|
55
56
57
58
59
60
61
|
.CountAsync(x => x.CreationTime >= yesterdayStart && x.CreationTime < todayStart);
var activeTemplates = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.CountAsync(x => !x.IsDeleted && x.State);
var activeTemplatesPrevWeek = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.CountAsync(x => !x.IsDeleted && x.State && x.CreationTime < weekStart);
|
49755ef0
李曜臣
6-12代码优化
|
62
63
64
65
|
var activeUsers = await DashboardScopeHelper.CountScopedTeamMembersAsync(
db, scopeLocationIds, platformAdminUserIds, activeOnly: true, createdBefore: null);
var activeUsersPrevWeek = await DashboardScopeHelper.CountScopedTeamMembersAsync(
db, scopeLocationIds, platformAdminUserIds, activeOnly: true, createdBefore: weekStart);
|
3b307558
李曜臣
统计接口实现
|
66
|
|
49755ef0
李曜臣
6-12代码优化
|
67
68
69
|
var locations = await DashboardScopeHelper.CountScopedLocationsAsync(db, scopeLocationIds, null);
var locationsPrevWeek = await DashboardScopeHelper.CountScopedLocationsAsync(
db, scopeLocationIds, weekStart);
|
3b307558
李曜臣
统计接口实现
|
70
|
|
49755ef0
李曜臣
6-12代码优化
|
71
72
73
74
|
var people = await DashboardScopeHelper.CountScopedTeamMembersAsync(
db, scopeLocationIds, platformAdminUserIds, activeOnly: false, createdBefore: null);
var peoplePrevWeek = await DashboardScopeHelper.CountScopedTeamMembersAsync(
db, scopeLocationIds, platformAdminUserIds, activeOnly: false, createdBefore: weekStart);
|
3b307558
李曜臣
统计接口实现
|
75
|
|
49755ef0
李曜臣
6-12代码优化
|
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
var productQuery = db.Queryable<FlProductDbEntity>().Where(x => !x.IsDeleted);
if (scopeLocationIds is not null)
{
if (scopeLocationIds.Count == 0)
{
productQuery = productQuery.Where(_ => false);
}
else
{
productQuery = productQuery.Where(p =>
SqlFunc.Subqueryable<FlLocationProductDbEntity>()
.Where(lp => lp.ProductId == p.Id && scopeLocationIds.Contains(lp.LocationId))
.Any());
}
}
var products = await productQuery.CountAsync();
|
3b307558
李曜臣
统计接口实现
|
93
94
95
|
// fl_product 当前实体未映射 CreationTime,无法按时间切分对比,先回退为同口径总量对比
var productsPrevWeek = products;
|
49755ef0
李曜臣
6-12代码优化
|
96
97
98
|
var weeklyPrintQuery = DashboardScopeHelper.ApplyPrintTaskLocationScope(
db.Queryable<FlLabelPrintTaskDbEntity>(), scopeLocationIds);
var weeklyPrintRaw = await weeklyPrintQuery
|
3b307558
李曜臣
统计接口实现
|
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
.Where(x => x.CreationTime >= weekStart && x.CreationTime < tomorrowStart)
.Select(x => x.CreationTime)
.ToListAsync();
var weeklyDict = weeklyPrintRaw
.GroupBy(x => x.Date)
.ToDictionary(g => g.Key, g => g.Count());
var weeklyTrend = Enumerable.Range(0, 7)
.Select(i =>
{
var d = weekStart.AddDays(i).Date;
return new DashboardDailyTrendPointDto
{
Date = d.ToString("yyyy-MM-dd"),
Value = weeklyDict.TryGetValue(d, out var v) ? v : 0
};
})
.ToList();
var categories = await _dbContext.SqlSugarClient.Queryable<FlLabelCategoryDbEntity>()
.Where(x => !x.IsDeleted && x.State)
.ToListAsync();
var labelCategoryIds = categories.Select(x => x.Id).ToList();
var labelRows = labelCategoryIds.Count == 0
? new List<string?>()
: await _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
.Where(x => !x.IsDeleted && x.LabelCategoryId != null && labelCategoryIds.Contains(x.LabelCategoryId))
.Select(x => x.LabelCategoryId)
.ToListAsync();
var labelCountByCategory = labelRows
.Where(x => !string.IsNullOrWhiteSpace(x))
.GroupBy(x => x!)
.ToDictionary(g => g.Key, g => g.Count());
var categoryDistributionTotal = labelCountByCategory.Values.Sum();
var categoryDistribution = categories
.Select(c =>
{
var count = labelCountByCategory.TryGetValue(c.Id, out var v) ? v : 0;
var ratio = categoryDistributionTotal == 0
? 0m
: Math.Round(count * 100m / categoryDistributionTotal, 2);
return new DashboardCategoryDistributionDto
{
CategoryId = c.Id,
CategoryName = c.CategoryName,
Count = count,
Ratio = ratio
};
})
.Where(x => x.Count > 0)
.OrderByDescending(x => x.Count)
.ThenBy(x => x.CategoryName)
.ToList();
|
4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
157
|
const int recentLabelsTake = 10;
|
49755ef0
李曜臣
6-12代码优化
|
158
159
160
|
var recentBaseQuery = DashboardScopeHelper.ApplyPrintTaskLocationScope(
db.Queryable<FlLabelPrintTaskDbEntity>(), scopeLocationIds);
var recentRaw = await recentBaseQuery
|
4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
|
.LeftJoin<FlLabelDbEntity>((t, l) => t.LabelId == l.Id)
.LeftJoin<FlProductDbEntity>((t, l, p) => t.ProductId == p.Id)
.LeftJoin<FlLabelTemplateDbEntity>((t, l, p, tpl) => t.TemplateId == tpl.Id)
.OrderBy((t, l, p, tpl) => SqlFunc.IsNull(t.PrintedAt, t.CreationTime), OrderByType.Desc)
.Take(recentLabelsTake)
.Select((t, l, p, tpl) => new
{
t.Id,
LabelCode = l.LabelCode,
LabelName = l.LabelName,
ProductName = p.ProductName,
tpl.Width,
tpl.Height,
tpl.Unit,
t.PrintInputJson,
PrintedAt = SqlFunc.IsNull(t.PrintedAt, t.CreationTime),
t.CreatedBy
})
.ToListAsync();
var recentUserIds = recentRaw
.Select(x => x.CreatedBy)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x!.Trim())
.Distinct()
.Select(x => Guid.TryParse(x, out var g) ? g : (Guid?)null)
.Where(x => x.HasValue)
.Select(x => x!.Value)
.ToList();
var recentUserMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (recentUserIds.Count > 0)
{
var users = await _userRepository._DbQueryable
.Where(u => !u.IsDeleted && recentUserIds.Contains(u.Id))
.Select(u => new { u.Id, u.Name, u.UserName })
.ToListAsync();
foreach (var u in users)
{
var display = !string.IsNullOrWhiteSpace(u.Name) ? u.Name.Trim() : u.UserName.Trim();
recentUserMap[u.Id.ToString()] = string.IsNullOrWhiteSpace(display) ? "无" : display;
}
}
var recentLabels = recentRaw.Select(x =>
{
var displayName = !string.IsNullOrWhiteSpace(x.ProductName)
? x.ProductName.Trim()
: (string.IsNullOrWhiteSpace(x.LabelName) ? "无" : x.LabelName.Trim());
var printedAt = x.PrintedAt ?? DateTime.MinValue;
var status = ResolveRecentLabelStatus(x.PrintInputJson);
return new DashboardRecentLabelItemDto
{
TaskId = x.Id,
LabelCode = string.IsNullOrWhiteSpace(x.LabelCode) ? "无" : x.LabelCode.Trim(),
DisplayName = displayName,
PrintedByUserId = x.CreatedBy?.Trim(),
PrintedByName = ResolveRecentUserName(recentUserMap, x.CreatedBy),
PrintedAt = printedAt,
Status = status,
LabelTypeBadge = FormatTemplateBadge(x.Width, x.Height, x.Unit)
};
}).ToList();
|
3b307558
李曜臣
统计接口实现
|
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
var labelsPrintedTodayCard = BuildMetricCard("labelsPrintedToday", "Labels Printed Today", printedToday, printedYesterday);
var activeTemplatesCard = BuildMetricCard("activeTemplates", "Active Templates", activeTemplates, activeTemplatesPrevWeek);
var activeUsersCard = BuildMetricCard("activeUsers", "Active Users", activeUsers, activeUsersPrevWeek);
var locationsCard = BuildMetricCard("locations", "Locations", locations, locationsPrevWeek);
var peopleCard = BuildMetricCard("people", "People", people, peoplePrevWeek);
var productsCard = BuildMetricCard("products", "Products", products, productsPrevWeek);
var output = new DashboardOverviewOutputDto
{
LabelsPrintedToday = labelsPrintedTodayCard,
ActiveTemplates = activeTemplatesCard,
ActiveUsers = activeUsersCard,
Locations = locationsCard,
People = peopleCard,
Products = productsCard,
MetricCards = new List<DashboardMetricCardDto>
{
labelsPrintedTodayCard,
activeTemplatesCard,
activeUsersCard,
locationsCard,
peopleCard,
productsCard
},
WeeklyPrintVolume = weeklyTrend,
CategoryDistribution = categoryDistribution,
CategoryDistributionTotal = categoryDistributionTotal,
ByCategory = categoryDistribution,
ByCategoryTotal = categoryDistributionTotal,
|
4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
254
|
RecentLabels = recentLabels,
|
3b307558
李曜臣
统计接口实现
|
255
256
257
258
259
260
|
GeneratedAt = now
};
return output;
}
|
4d328ec2
李曜臣
平台端报表reports,仪表盘D...
|
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
|
private static string ResolveRecentUserName(Dictionary<string, string> map, string? createdBy)
{
if (string.IsNullOrWhiteSpace(createdBy))
{
return "无";
}
return map.TryGetValue(createdBy.Trim(), out var n) ? n : "无";
}
/// <summary>
/// 依据 PrintInputJson 中的保质期字段与「当前日期」比较得到 active/expired。
/// </summary>
private static string ResolveRecentLabelStatus(string? printInputJson)
{
if (!TryParseExpiryDate(printInputJson, out var expiryDate))
{
return "active";
}
var today = DateTime.Now.Date;
return expiryDate.Date < today ? "expired" : "active";
}
private static bool TryParseExpiryDate(string? printInputJson, out DateTime expiryDate)
{
expiryDate = default;
if (string.IsNullOrWhiteSpace(printInputJson))
{
return false;
}
try
{
using var doc = JsonDocument.Parse(printInputJson);
if (doc.RootElement.ValueKind != JsonValueKind.Object)
{
return false;
}
foreach (var prop in doc.RootElement.EnumerateObject())
{
var key = prop.Name.Trim();
if (!key.Equals("expiryDate", StringComparison.OrdinalIgnoreCase) &&
!key.Equals("expiry", StringComparison.OrdinalIgnoreCase) &&
!key.Equals("expirationDate", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var v = prop.Value;
if (v.ValueKind == JsonValueKind.String)
{
var s = v.GetString();
if (!string.IsNullOrWhiteSpace(s) &&
DateTime.TryParse(s, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal | DateTimeStyles.AllowWhiteSpaces, out var dt))
{
expiryDate = dt;
return true;
}
}
else if (v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var unix))
{
expiryDate = DateTimeOffset.FromUnixTimeSeconds(unix).LocalDateTime;
return true;
}
}
}
catch
{
return false;
}
return false;
}
private static string FormatTemplateBadge(decimal w, decimal h, string? unit)
{
var u = (unit ?? "inch").Trim().ToLowerInvariant();
var ws = w.ToString(CultureInfo.InvariantCulture);
var hs = h.ToString(CultureInfo.InvariantCulture);
return u is "inch" or "in"
? $"{ws}\"x{hs}\""
: $"{ws}x{hs}{u}";
}
|
3b307558
李曜臣
统计接口实现
|
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
private static DashboardMetricCardDto BuildMetricCard(string key, string title, int value, int previousValue)
{
var changeValue = value - previousValue;
var changeRate = previousValue <= 0
? (value > 0 ? 100m : 0m)
: Math.Round(changeValue * 100m / previousValue, 2);
return new DashboardMetricCardDto
{
Key = key,
Title = title,
Value = value,
PreviousValue = previousValue,
ChangeValue = changeValue,
ChangeRate = changeRate
};
}
}
|