Blame view

netcore/src/Modularity/Extend/NCC.Extend/LqEducationDepartmentDashboardFeaturedDataService.cs 55 KB
e1dcb3a0   “wangming”   1
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
87
88
89
90
91
92
93
94
95
96
97
98
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
157
158
159
160
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
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
254
255
256
257
258
259
260
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using Newtonsoft.Json;
  using NCC.Common.Core.Manager;
  using NCC.Common.Extension;
  using NCC.Common.Filter;
  using NCC.Common.Helper;
  using NCC.Common.Model.NPOI;
  using NCC.DataEncryption;
  using NCC.Extend.Entitys.Dto.LqEducationDepartmentDashboard;
  using NCC.Extend.Entitys.Enum;
  using NCC.Extend.Entitys.lq_education_dashboard_featured_item;
  using NCC.Extend.Entitys.lq_khxx;
  using NCC.Extend.Entitys.lq_md_major_project_teacher_assignment;
  using NCC.Extend.Entitys.lq_mdxx;
  using NCC.Extend.Entitys.lq_xh_feedback;
  using NCC.Extend.Entitys.lq_xh_hyhk;
  using NCC.Extend.Entitys.lq_xmzl;
  using NCC.FriendlyException;
  using NCC.System.Entitys.Permission;
  using SqlSugar;
  using Yitter.IdGenerator;
  
  namespace NCC.Extend
  {
      /// <summary>
      /// 教育部经营看板重点品项、客户与服务日志功能
      /// </summary>
      public partial class LqEducationDepartmentDashboardService
      {
          private const string FeaturedItemBizType = "lq_education_dashboard_featured_item";
  
          #region 重点品项配置
  
          /// <summary>
          /// 分页查询教育部经营看板重点品项配置
          /// </summary>
          /// <remarks>
          /// 查询重点品项配置及原始生美品项信息。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "currentPage": 1,
          ///   "pageSize": 20,
          ///   "keyword": "生命",
          ///   "enabled": 1
          /// }
          /// ```
          ///
          /// 参数说明:
          /// - keyword: 按原始品项名称、编号或显示名模糊搜索
          /// - enabled: 0禁用,1启用
          /// </remarks>
          /// <param name="input">分页查询条件</param>
          /// <returns>重点品项配置分页列表</returns>
          /// <response code="200">成功返回配置列表</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetFeaturedItemConfigList")]
          public async Task<dynamic> GetFeaturedItemConfigList(
              [FromBody] EducationDashboardFeaturedItemListInput input)
          {
              input ??= new EducationDashboardFeaturedItemListInput();
              var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
  
              var page = await _db.Queryable<LqEducationDashboardFeaturedItemEntity, LqXmzlEntity>(
                      (config, item) => config.ItemId == item.Id)
                  .WhereIF(input.Enabled.HasValue, (config, item) => config.Enabled == input.Enabled.Value)
                  .WhereIF(keyword != null, (config, item) =>
                      config.DisplayName.Contains(keyword) ||
                      item.Xmmc.Contains(keyword) ||
                      item.Xmbh.Contains(keyword))
                  .OrderBy((config, item) => config.Sort)
                  .OrderBy((config, item) => config.CreateTime, OrderByType.Desc)
                  .Select((config, item) => new EducationDashboardFeaturedItemListOutput
                  {
                      Id = config.Id,
                      ItemId = config.ItemId,
                      ItemCode = item.Xmbh,
                      OriginalItemName = item.Xmmc,
                      ItemCategory = item.Qt2,
                      DisplayName = config.DisplayName,
                      Sort = config.Sort,
                      Enabled = config.Enabled,
                      CreateTime = config.CreateTime,
                      UpdateTime = config.UpdateTime
                  })
                  .ToPagedListAsync(input.currentPage, input.pageSize);
  
              return PageResult<EducationDashboardFeaturedItemListOutput>.SqlSugarPageResult(page);
          }
  
          /// <summary>
          /// 搜索可配置的生美品项
          /// </summary>
          /// <remarks>
          /// 仅搜索有效且 lq_xmzl.qt2=生美 的原始品项,可排除已配置品项。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "currentPage": 1,
          ///   "pageSize": 20,
          ///   "keyword": "生命",
          ///   "excludeConfigured": true
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">品项搜索条件</param>
          /// <returns>生美品项分页列表</returns>
          /// <response code="200">成功返回品项列表</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("SearchLifeBeautyItems")]
          public async Task<dynamic> SearchLifeBeautyItems(
              [FromBody] EducationDashboardLifeBeautyItemSearchInput input)
          {
              input ??= new EducationDashboardLifeBeautyItemSearchInput();
              var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
              var configuredItemIds = await _db.Queryable<LqEducationDashboardFeaturedItemEntity>()
                  .Select(x => x.ItemId)
                  .ToListAsync();
  
              var page = await _db.Queryable<LqXmzlEntity>()
                  .Where(x => x.IsEffective == 1 && x.Qt2 == LifeBeautyCategory)
                  .WhereIF(input.ExcludeConfigured && configuredItemIds.Any(),
                      x => !configuredItemIds.Contains(x.Id))
                  .WhereIF(keyword != null, x => x.Xmmc.Contains(keyword) || x.Xmbh.Contains(keyword))
                  .OrderBy(x => x.Xmmc)
                  .Select(x => new EducationDashboardLifeBeautyItemOptionOutput
                  {
                      ItemId = x.Id,
                      ItemCode = x.Xmbh,
                      ItemName = x.Xmmc,
                      ItemCategory = x.Qt2,
                      Configured = configuredItemIds.Contains(x.Id)
                  })
                  .ToPagedListAsync(input.currentPage, input.pageSize);
  
              return PageResult<EducationDashboardLifeBeautyItemOptionOutput>.SqlSugarPageResult(page);
          }
  
          /// <summary>
          /// 保存教育部经营看板重点品项配置
          /// </summary>
          /// <remarks>
          /// ID 为空时新增,否则编辑;同一原始品项只能配置一次。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "id": "",
          ///   "itemId": "品项ID",
          ///   "displayName": "生命之波",
          ///   "sort": 10,
          ///   "enabled": 1
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">保存参数</param>
          /// <returns>配置ID</returns>
          /// <response code="200">保存成功</response>
          /// <response code="400">参数或唯一性校验失败</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("SaveFeaturedItemConfig")]
          public async Task<dynamic> SaveFeaturedItemConfig(
              [FromBody] EducationDashboardFeaturedItemSaveInput input)
          {
              ValidateFeaturedItemSaveInput(input);
              var item = await GetLifeBeautyItemAsync(input.ItemId);
              var duplicate = await _db.Queryable<LqEducationDashboardFeaturedItemEntity>()
                  .Where(x => x.ItemId == input.ItemId)
                  .WhereIF(!string.IsNullOrWhiteSpace(input.Id), x => x.Id != input.Id)
                  .AnyAsync();
              if (duplicate) throw NCCException.Oh("该生美品项已配置,请勿重复添加");
  
              if (string.IsNullOrWhiteSpace(input.Id))
              {
                  var entity = new LqEducationDashboardFeaturedItemEntity
                  {
                      Id = YitIdHelper.NextId().ToString(),
                      ItemId = input.ItemId.Trim(),
                      DisplayName = input.DisplayName.Trim(),
                      Sort = input.Sort,
                      Enabled = input.Enabled,
                      CreateUserId = _userManager.UserId,
                      CreateTime = DateTime.Now
                  };
                  await _db.Insertable(entity).ExecuteCommandAsync();
                  await WriteConfigLogAsync("新增重点品项", entity.Id, null, entity,
                      $"新增重点品项配置:{entity.DisplayName}({item.Xmmc})");
                  return new { id = entity.Id };
              }
  
              var existing = await _db.Queryable<LqEducationDashboardFeaturedItemEntity>()
                  .Where(x => x.Id == input.Id)
                  .FirstAsync();
              if (existing == null) throw NCCException.Oh("重点品项配置不存在");
              var before = SnapshotFeaturedItem(existing);
  
              existing.ItemId = input.ItemId.Trim();
              existing.DisplayName = input.DisplayName.Trim();
              existing.Sort = input.Sort;
              existing.Enabled = input.Enabled;
              existing.UpdateUserId = _userManager.UserId;
              existing.UpdateTime = DateTime.Now;
              await _db.Updateable(existing).ExecuteCommandAsync();
              await WriteConfigLogAsync("修改重点品项", existing.Id, before, existing,
                  $"修改重点品项配置:{existing.DisplayName}({item.Xmmc})");
              return new { id = existing.Id };
          }
  
          /// <summary>
          /// 删除教育部经营看板重点品项配置
          /// </summary>
          /// <remarks>
          /// 物理删除指定配置,不影响原始品项资料。
          ///
          /// 示例请求:`DELETE /api/Extend/LqEducationDepartmentDashboard/DeleteFeaturedItemConfig/{id}`
          /// </remarks>
          /// <param name="id">配置ID</param>
          /// <returns>删除结果</returns>
          /// <response code="200">删除成功</response>
          /// <response code="400">配置不存在</response>
          /// <response code="500">服务器错误</response>
          [HttpDelete("DeleteFeaturedItemConfig/{id}")]
          public async Task DeleteFeaturedItemConfig([FromRoute] string id)
          {
              if (string.IsNullOrWhiteSpace(id)) throw NCCException.Oh("配置ID不能为空");
              var entity = await _db.Queryable<LqEducationDashboardFeaturedItemEntity>()
                  .Where(x => x.Id == id)
                  .FirstAsync();
              if (entity == null) throw NCCException.Oh("重点品项配置不存在");
  
              await _db.Deleteable<LqEducationDashboardFeaturedItemEntity>()
                  .Where(x => x.Id == id)
                  .ExecuteCommandAsync();
              await WriteConfigLogAsync("删除重点品项", entity.Id, entity, null,
                  $"删除重点品项配置:{entity.DisplayName}");
          }
  
          /// <summary>
          /// 变更教育部经营看板重点品项启用状态
          /// </summary>
          /// <remarks>
          /// 启用或禁用指定重点品项。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "id": "配置ID",
          ///   "enabled": 1
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">状态变更参数</param>
          /// <returns>状态变更结果</returns>
          /// <response code="200">状态变更成功</response>
          /// <response code="400">参数错误或配置不存在</response>
          /// <response code="500">服务器错误</response>
          [HttpPut("ChangeFeaturedItemStatus")]
          public async Task ChangeFeaturedItemStatus(
              [FromBody] EducationDashboardFeaturedItemStatusInput input)
          {
              if (input == null || string.IsNullOrWhiteSpace(input.Id))
                  throw NCCException.Oh("配置ID不能为空");
              if (!Enum.IsDefined(typeof(EducationDashboardFeaturedItemStatus), input.Enabled))
                  throw NCCException.Oh("启用状态无效");
  
              var entity = await _db.Queryable<LqEducationDashboardFeaturedItemEntity>()
                  .Where(x => x.Id == input.Id)
                  .FirstAsync();
              if (entity == null) throw NCCException.Oh("重点品项配置不存在");
              var before = SnapshotFeaturedItem(entity);
  
              entity.Enabled = input.Enabled;
              entity.UpdateUserId = _userManager.UserId;
              entity.UpdateTime = DateTime.Now;
              await _db.Updateable(entity)
                  .UpdateColumns(x => new { x.Enabled, x.UpdateUserId, x.UpdateTime })
                  .ExecuteCommandAsync();
  
              var action = input.Enabled == EducationDashboardFeaturedItemStatus.Enabled
                  ? "启用重点品项"
                  : "禁用重点品项";
              await WriteConfigLogAsync(action, entity.Id, before, entity,
                  $"{action}:{entity.DisplayName}");
          }
  
          private static void ValidateFeaturedItemSaveInput(EducationDashboardFeaturedItemSaveInput input)
          {
              if (input == null) throw NCCException.Oh("请求参数不能为空");
              if (string.IsNullOrWhiteSpace(input.ItemId)) throw NCCException.Oh("品项ID不能为空");
              if (string.IsNullOrWhiteSpace(input.DisplayName)) throw NCCException.Oh("显示名不能为空");
              if (input.DisplayName.Trim().Length > 200) throw NCCException.Oh("显示名不能超过200个字符");
              if (input.Sort < 0) throw NCCException.Oh("排序号不能小于0");
              if (!Enum.IsDefined(typeof(EducationDashboardFeaturedItemStatus), input.Enabled))
                  throw NCCException.Oh("启用状态无效");
          }
  
          private async Task<LqXmzlEntity> GetLifeBeautyItemAsync(string itemId)
          {
              var item = await _db.Queryable<LqXmzlEntity>()
                  .Where(x => x.Id == itemId && x.IsEffective == 1 && x.Qt2 == LifeBeautyCategory)
                  .FirstAsync();
              if (item == null) throw NCCException.Oh("所选品项不存在、已失效或不属于生美");
              return item;
          }
  
          private static object SnapshotFeaturedItem(LqEducationDashboardFeaturedItemEntity entity)
          {
              if (entity == null) return null;
              return new
              {
                  entity.Id,
                  entity.ItemId,
                  entity.DisplayName,
                  entity.Sort,
                  entity.Enabled,
                  entity.CreateUserId,
                  entity.CreateTime,
                  entity.UpdateUserId,
                  entity.UpdateTime
              };
          }
  
          private async Task WriteConfigLogAsync(
              string actionCode,
              string bizId,
              object before,
              object after,
              string summary)
          {
              await _businessOperationLogService.WriteAsync(
                  BizLogModule,
                  actionCode,
                  FeaturedItemBizType,
                  bizId,
                  summary,
                  JsonConvert.SerializeObject(new { before, after }));
          }
  
          #endregion
  
          #region 重点品项与客户统计
  
          /// <summary>
          /// 获取教育部经营看板重点品项统计
          /// </summary>
          /// <remarks>
          /// 按已启用配置汇总开单金额、耗卡金额、主单次数及环比同比,不硬编码品项。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604"
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">公共看板筛选条件</param>
          /// <returns>重点品项统计</returns>
          /// <response code="200">成功返回统计结果</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetFeaturedItemStatistics")]
          public async Task<EducationDepartmentFeaturedItemStatisticsOutput> GetFeaturedItemStatistics(
              [FromBody] EducationDepartmentDashboardStatisticsInput input)
          {
              ValidateStatisticsInput(input);
              var configs = await LoadEnabledFeaturedItemsAsync();
              if (!configs.Any()) return new EducationDepartmentFeaturedItemStatisticsOutput();
  
7fc03b57   “wangming”   1
379
380
381
              MonthlySnapshot current;
              MonthlySnapshot previous;
              MonthlySnapshot lastYear;
e1dcb3a0   “wangming”   1
382
  
7fc03b57   “wangming”   1
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
              if (input.StartDate.HasValue && input.EndDate.HasValue)
              {
                  var range = NormalizeDateRange(input);
                  var currentStores = await GetStoreIdsForDateRangeAsync(
                      input.EducationDepartmentId, input.StoreIds, range.StatisticsMonths);
                  var currentTarget = await GetTargetByStoreForDateRangeAsync(currentStores, range.StatisticsMonths);
                  current = await BuildRangeSnapshotAsync(
                      currentStores, range.StartInclusive, range.EndInclusive, currentTarget);
  
                  var dayCount = (range.EndInclusive.Date - range.StartInclusive.Date).Days + 1;
                  var prevEndDate = range.StartInclusive.Date.AddDays(-1);
                  var prevStartDate = prevEndDate.AddDays(-(dayCount - 1));
                  var prevRange = NormalizeDateRange(prevStartDate, prevEndDate);
                  var prevStores = await GetStoreIdsForDateRangeAsync(
                      input.EducationDepartmentId, input.StoreIds, prevRange.StatisticsMonths);
                  var prevTarget = await GetTargetByStoreForDateRangeAsync(prevStores, prevRange.StatisticsMonths);
                  previous = await BuildRangeSnapshotAsync(
                      prevStores, prevRange.StartInclusive, prevRange.EndInclusive, prevTarget);
  
                  var lastYearStart = range.StartInclusive.AddYears(-1);
                  var lastYearEndDate = range.EndInclusive.Date.AddYears(-1);
                  var lastYearRange = NormalizeDateRange(lastYearStart, lastYearEndDate);
                  var lastYearStores = await GetStoreIdsForDateRangeAsync(
                      input.EducationDepartmentId, input.StoreIds, lastYearRange.StatisticsMonths);
                  var lastYearTarget = await GetTargetByStoreForDateRangeAsync(lastYearStores, lastYearRange.StatisticsMonths);
                  lastYear = await BuildRangeSnapshotAsync(
                      lastYearStores, lastYearRange.StartInclusive, lastYearRange.EndInclusive, lastYearTarget);
              }
              else
              {
                  var currentMonth = DateTime.ParseExact(input.StatisticsMonth, "yyyyMM", null);
                  var lastMonth = currentMonth.AddMonths(-1).ToString("yyyyMM");
                  var lastYearMonth = currentMonth.AddYears(-1).ToString("yyyyMM");
e1dcb3a0   “wangming”   1
416
  
7fc03b57   “wangming”   1
417
418
419
420
421
422
423
424
                  var currentStores = await GetStoreIdsAsync(input.EducationDepartmentId, input.StoreIds, input.StatisticsMonth);
                  var lastMonthStores = await GetStoreIdsForMonthAsync(input.EducationDepartmentId, input.StoreIds, lastMonth);
                  var lastYearStores = await GetStoreIdsForMonthAsync(input.EducationDepartmentId, input.StoreIds, lastYearMonth);
  
                  current = await BuildMonthlySnapshotAsync(currentStores, input.StatisticsMonth);
                  previous = await BuildMonthlySnapshotAsync(lastMonthStores, lastMonth);
                  lastYear = await BuildMonthlySnapshotAsync(lastYearStores, lastYearMonth);
              }
e1dcb3a0   “wangming”   1
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
  
              var result = new EducationDepartmentFeaturedItemStatisticsOutput();
              foreach (var config in configs)
              {
                  var currentBilling = current.SourceData.BillingRows.Where(x => x.ItemId == config.ItemId).ToList();
                  var currentConsume = current.SourceData.ConsumeRows.Where(x => x.ItemId == config.ItemId).ToList();
                  var previousBilling = previous.SourceData.BillingRows.Where(x => x.ItemId == config.ItemId).ToList();
                  var previousConsume = previous.SourceData.ConsumeRows.Where(x => x.ItemId == config.ItemId).ToList();
                  var lastYearBilling = lastYear.SourceData.BillingRows.Where(x => x.ItemId == config.ItemId).ToList();
                  var lastYearConsume = lastYear.SourceData.ConsumeRows.Where(x => x.ItemId == config.ItemId).ToList();
  
                  var billingAmount = currentBilling.Sum(x => x.Amount);
                  var consumeAmount = currentConsume.Sum(x => x.Amount);
                  var previousBillingAmount = previousBilling.Sum(x => x.Amount);
                  var previousConsumeAmount = previousConsume.Sum(x => x.Amount);
                  var lastYearBillingAmount = lastYearBilling.Sum(x => x.Amount);
                  var lastYearConsumeAmount = lastYearConsume.Sum(x => x.Amount);
  
                  result.Items.Add(new EducationDepartmentFeaturedItemStatisticsItem
                  {
                      ConfigId = config.Id,
                      ItemId = config.ItemId,
                      OriginalItemName = config.OriginalItemName,
                      ItemCategory = config.ItemCategory,
                      DisplayName = config.DisplayName,
                      Sort = config.Sort,
                      BillingAmount = billingAmount,
                      BillingCount = currentBilling.Select(x => x.BillId).Distinct().Count(),
                      ConsumeAmount = consumeAmount,
                      ConsumeCount = currentConsume.Select(x => x.ConsumeId).Distinct().Count(),
                      BillingMonthOverMonthRate = CalculateGrowthRate(billingAmount, previousBillingAmount),
                      BillingYearOverYearRate = CalculateGrowthRate(billingAmount, lastYearBillingAmount),
                      ConsumeMonthOverMonthRate = CalculateGrowthRate(consumeAmount, previousConsumeAmount),
                      ConsumeYearOverYearRate = CalculateGrowthRate(consumeAmount, lastYearConsumeAmount)
                  });
              }
  
              return result;
          }
  
          /// <summary>
          /// 获取教育部经营看板客户消费频次
          /// </summary>
          /// <remarks>
          /// 按生美品项统计耗卡客户数、耗卡主单次数和人均频次;配置显示名仅作为附加展示名。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604"
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">公共看板筛选条件</param>
          /// <returns>客户频次统计</returns>
          /// <response code="200">成功返回统计结果</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetCustomerFrequencyStatistics")]
          public async Task<EducationDepartmentCustomerFrequencyStatisticsOutput> GetCustomerFrequencyStatistics(
              [FromBody] EducationDepartmentDashboardStatisticsInput input)
          {
7fc03b57   “wangming”   1
488
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(input);
e1dcb3a0   “wangming”   1
489
490
              if (!storeIds.Any()) return new EducationDepartmentCustomerFrequencyStatisticsOutput();
  
7fc03b57   “wangming”   1
491
492
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
e1dcb3a0   “wangming”   1
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
              var configMap = (await LoadEnabledFeaturedItemsAsync())
                  .ToDictionary(x => x.ItemId, x => x.DisplayName);
  
              var items = snapshot.SourceData.ConsumeRows
                  .GroupBy(x => new { x.ItemId, x.ItemName, x.ItemCategory })
                  .Select(g =>
                  {
                      var customerCount = g.Select(x => x.MemberId)
                          .Where(x => !string.IsNullOrWhiteSpace(x))
                          .Distinct()
                          .Count();
                      var consumeCount = g.Select(x => x.ConsumeId).Distinct().Count();
                      return new EducationDepartmentCustomerFrequencyItem
                      {
                          ItemId = g.Key.ItemId,
                          OriginalItemName = g.Key.ItemName,
                          ItemCategory = g.Key.ItemCategory,
                          DisplayName = configMap.TryGetValue(g.Key.ItemId, out var displayName)
                              ? displayName
                              : string.Empty,
                          CustomerCount = customerCount,
                          TotalConsumeCount = consumeCount,
                          AverageFrequency = customerCount > 0
                              ? decimal.Round((decimal)consumeCount / customerCount, 2)
                              : 0m
                      };
                  })
                  .OrderByDescending(x => x.TotalConsumeCount)
                  .ToList();
  
              return new EducationDepartmentCustomerFrequencyStatisticsOutput { Items = items };
          }
  
          /// <summary>
          /// 获取教育部经营看板客户维度汇总
          /// </summary>
          /// <remarks>
          /// 返回教育部会员、新增会员、生美开单会员、生美耗卡会员和去重开单主单数。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604"
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">公共看板筛选条件</param>
          /// <returns>客户维度汇总</returns>
          /// <response code="200">成功返回汇总</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetCustomerDimensionStatistics")]
          public async Task<EducationDepartmentCustomerDimensionStatisticsOutput> GetCustomerDimensionStatistics(
              [FromBody] EducationDepartmentDashboardStatisticsInput input)
          {
7fc03b57   “wangming”   1
549
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(input);
e1dcb3a0   “wangming”   1
550
551
              if (!storeIds.Any()) return new EducationDepartmentCustomerDimensionStatisticsOutput();
  
7fc03b57   “wangming”   1
552
553
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
e1dcb3a0   “wangming”   1
554
              var (memberCount, newMemberCount) =
7fc03b57   “wangming”   1
555
                  await QueryEducationMemberStatsAsync(storeIds, range.StartInclusive, range.EndInclusive);
e1dcb3a0   “wangming”   1
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
  
              return new EducationDepartmentCustomerDimensionStatisticsOutput
              {
                  EducationMemberCount = memberCount,
                  NewEducationMemberCount = newMemberCount,
                  BillingMemberCount = snapshot.Metrics.BillingMemberCount,
                  ConsumeMemberCount = snapshot.Metrics.ConsumeMemberCount,
                  BillingCount = snapshot.Metrics.BillingCount
              };
          }
  
          /// <summary>
          /// 分页查询教育部经营看板客户明细
          /// </summary>
          /// <remarks>
          /// 查询教育部会员及当月发生生美开单/耗卡/退卡的客户,返回统一业务口径的客户明细。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604",
          ///   "currentPage": 1,
          ///   "pageSize": 20,
          ///   "memberName": "张"
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">分页筛选条件</param>
          /// <returns>客户明细分页列表</returns>
          /// <response code="200">成功返回客户明细</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetCustomerDetailList")]
          public async Task<dynamic> GetCustomerDetailList(
              [FromBody] EducationDepartmentCustomerDetailListInput input)
          {
              var (list, total) = await QueryCustomerDetailListAsync(input, true);
              return PageResult<EducationDepartmentCustomerDetailListOutput>.SqlSugarPageResult(
                  new SqlSugarPagedList<EducationDepartmentCustomerDetailListOutput>
                  {
                      list = list,
                      pagination = new PagedModel
                      {
                          PageIndex = NormalizePageIndex(input.currentPage),
                          PageSize = NormalizePageSize(input.pageSize),
                          Total = total
                      }
                  });
          }
  
          #endregion
  
          #region 服务日志
  
          /// <summary>
          /// 获取教育部经营看板服务日志统计
          /// </summary>
          /// <remarks>
          /// 仅统计 lq_xh_feedback,并通过 F_ConsumeId 关联有效生美耗卡记录和门店。
          /// 教育老师仅统计本人创建且属于本人当月负责门店的日志。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604"
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">公共看板筛选条件</param>
          /// <returns>日志数、覆盖率和前后照片完整率</returns>
          /// <response code="200">成功返回统计结果</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetServiceLogStatistics")]
          public async Task<EducationDepartmentServiceLogStatisticsOutput> GetServiceLogStatistics(
              [FromBody] EducationDepartmentDashboardStatisticsInput input)
          {
7fc03b57   “wangming”   1
635
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(input);
e1dcb3a0   “wangming”   1
636
637
              if (!storeIds.Any()) return new EducationDepartmentServiceLogStatisticsOutput();
  
7fc03b57   “wangming”   1
638
639
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
e1dcb3a0   “wangming”   1
640
641
642
643
644
645
646
              var consumeIds = snapshot.SourceData.ConsumeRows
                  .Select(x => x.ConsumeId)
                  .Where(x => !string.IsNullOrWhiteSpace(x))
                  .Distinct()
                  .ToList();
              if (!consumeIds.Any()) return new EducationDepartmentServiceLogStatisticsOutput();
  
7fc03b57   “wangming”   1
647
              var isEducationTeacher = await IsEducationTeacherInMonthsAsync(range.StatisticsMonths);
e1dcb3a0   “wangming”   1
648
649
              var logs = await _db.Queryable<LqXhFeedbackEntity>()
                  .Where(x => consumeIds.Contains(x.ConsumeId))
7fc03b57   “wangming”   1
650
                  .Where(x => x.CreateTime >= range.StartInclusive && x.CreateTime <= range.EndInclusive)
e1dcb3a0   “wangming”   1
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
                  .WhereIF(isEducationTeacher, x => x.CreateUser == _userManager.UserId)
                  .Select(x => new ServiceLogStatisticRow
                  {
                      ConsumeId = x.ConsumeId,
                      BeforeImage = x.BeforeImage,
                      AfterImage = x.AfterImage
                  })
                  .ToListAsync();
  
              var coveredConsumeCount = logs.Select(x => x.ConsumeId).Distinct().Count();
              var completePhotoCount = logs.Count(x =>
                  !string.IsNullOrWhiteSpace(x.BeforeImage) &&
                  !string.IsNullOrWhiteSpace(x.AfterImage));
  
              return new EducationDepartmentServiceLogStatisticsOutput
              {
                  ServiceLogCount = logs.Count,
                  LifeBeautyConsumeCount = consumeIds.Count,
                  CoveredConsumeCount = coveredConsumeCount,
                  CoverageRate = consumeIds.Count > 0
                      ? decimal.Round((decimal)coveredConsumeCount / consumeIds.Count * 100m, 2)
                      : 0m,
                  CompletePhotoLogCount = completePhotoCount,
                  CompletePhotoRate = logs.Count > 0
                      ? decimal.Round((decimal)completePhotoCount / logs.Count * 100m, 2)
                      : 0m
              };
          }
  
          /// <summary>
          /// 分页查询教育部经营看板服务日志
          /// </summary>
          /// <remarks>
          /// 仅查询关联有效生美耗卡记录的 lq_xh_feedback。
          /// 教育老师仅可查看本人创建且属于本人负责门店的日志。
          ///
          /// 示例请求:
          /// ```json
          /// {
          ///   "educationDepartmentId": "734725416912160005",
          ///   "statisticsMonth": "202604",
          ///   "currentPage": 1,
          ///   "pageSize": 20,
          ///   "hasCompletePhotos": true
          /// }
          /// ```
          /// </remarks>
          /// <param name="input">分页筛选条件</param>
          /// <returns>服务日志分页列表</returns>
          /// <response code="200">成功返回日志明细</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("GetServiceLogList")]
          public async Task<dynamic> GetServiceLogList(
              [FromBody] EducationDepartmentServiceLogListInput input)
          {
              var (list, total) = await QueryServiceLogListAsync(input, true);
              return PageResult<EducationDepartmentServiceLogListOutput>.SqlSugarPageResult(
                  new SqlSugarPagedList<EducationDepartmentServiceLogListOutput>
                  {
                      list = list,
                      pagination = new PagedModel
                      {
                          PageIndex = NormalizePageIndex(input.currentPage),
                          PageSize = NormalizePageSize(input.pageSize),
                          Total = total
                      }
                  });
          }
  
          #endregion
  
          #region 新增导出
  
          /// <summary>
          /// 导出教育部经营看板门店明细
          /// </summary>
          /// <remarks>
          /// 导出条件与 GetStoreDetailList 完全一致,成功后写中文业务操作日志。
          /// </remarks>
          /// <param name="input">门店明细筛选条件</param>
          /// <returns>Excel 下载信息</returns>
          /// <response code="200">成功返回下载链接</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("ExportStoreDetailList")]
          public async Task<dynamic> ExportStoreDetailList(
              [FromBody] EducationDepartmentDashboardStoreDetailListInput input)
          {
              var list = await QueryStoreDetailDataAsync(input);
              return await ExportFeaturedDataAsync(
                  list,
                  "导出门店明细",
                  "lq_md_target",
                  input,
                  "[{\"value\":\"门店编码\",\"field\":\"storeCode\"},{\"value\":\"门店名称\",\"field\":\"storeName\"}," +
                  "{\"value\":\"开单金额\",\"field\":\"billingAmount\"},{\"value\":\"退卡金额\",\"field\":\"refundAmount\"}," +
                  "{\"value\":\"净业绩\",\"field\":\"netPerformance\"},{\"value\":\"储扣金额\",\"field\":\"deductAmount\"}," +
                  "{\"value\":\"耗卡金额\",\"field\":\"consumeAmount\"},{\"value\":\"目标业绩\",\"field\":\"targetPerformance\"}," +
                  "{\"value\":\"完成率\",\"field\":\"completionRate\"},{\"value\":\"开单次数\",\"field\":\"billingCount\"}," +
                  "{\"value\":\"耗卡次数\",\"field\":\"consumeCount\"},{\"value\":\"退卡次数\",\"field\":\"refundCount\"}," +
                  "{\"value\":\"耗卡人头\",\"field\":\"consumeMemberCount\"},{\"value\":\"项目数\",\"field\":\"projectCount\"}]");
          }
  
          /// <summary>
          /// 导出教育部经营看板客户明细
          /// </summary>
          /// <remarks>
          /// 导出条件与 GetCustomerDetailList 完全一致,成功后写中文业务操作日志。
          /// </remarks>
          /// <param name="input">客户明细筛选条件</param>
          /// <returns>Excel 下载信息</returns>
          /// <response code="200">成功返回下载链接</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("ExportCustomerDetailList")]
          public async Task<dynamic> ExportCustomerDetailList(
              [FromBody] EducationDepartmentCustomerDetailListInput input)
          {
              var (list, _) = await QueryCustomerDetailListAsync(input, false);
              return await ExportFeaturedDataAsync(
                  list,
                  "导出客户明细",
                  "lq_khxx",
                  input,
                  "[{\"value\":\"会员姓名\",\"field\":\"memberName\"},{\"value\":\"手机号\",\"field\":\"mobile\"}," +
                  "{\"value\":\"门店\",\"field\":\"storeName\"},{\"value\":\"是否教育部会员\",\"field\":\"isEducationMember\"}," +
                  "{\"value\":\"成为教育部会员时间\",\"field\":\"educationMemberTime\"},{\"value\":\"开单次数\",\"field\":\"billingCount\"}," +
                  "{\"value\":\"开单金额\",\"field\":\"billingAmount\"},{\"value\":\"耗卡次数\",\"field\":\"consumeCount\"}," +
                  "{\"value\":\"耗卡金额\",\"field\":\"consumeAmount\"},{\"value\":\"退卡次数\",\"field\":\"refundCount\"}," +
                  "{\"value\":\"退卡金额\",\"field\":\"refundAmount\"},{\"value\":\"最近耗卡日\",\"field\":\"lastConsumeDate\"}]");
          }
  
          /// <summary>
          /// 导出教育部经营看板服务日志
          /// </summary>
          /// <remarks>
          /// 导出条件与 GetServiceLogList 完全一致,并沿用教育老师本人/负责门店权限。
          /// </remarks>
          /// <param name="input">服务日志筛选条件</param>
          /// <returns>Excel 下载信息</returns>
          /// <response code="200">成功返回下载链接</response>
          /// <response code="400">参数错误</response>
          /// <response code="500">服务器错误</response>
          [HttpPost("ExportServiceLogList")]
          public async Task<dynamic> ExportServiceLogList(
              [FromBody] EducationDepartmentServiceLogListInput input)
          {
              var (list, _) = await QueryServiceLogListAsync(input, false);
              return await ExportFeaturedDataAsync(
                  list,
                  "导出服务日志",
                  "lq_xh_feedback",
                  input,
                  "[{\"value\":\"门店\",\"field\":\"storeName\"},{\"value\":\"会员\",\"field\":\"memberName\"}," +
                  "{\"value\":\"老师\",\"field\":\"createUserName\"},{\"value\":\"备注\",\"field\":\"remark\"}," +
                  "{\"value\":\"前照片\",\"field\":\"beforeImage\"},{\"value\":\"后照片\",\"field\":\"afterImage\"}," +
                  "{\"value\":\"照片完整\",\"field\":\"hasCompletePhotos\"},{\"value\":\"创建时间\",\"field\":\"createTime\"}]");
          }
  
          #endregion
  
          #region 私有查询
  
          private async Task<List<FeaturedItemConfigRow>> LoadEnabledFeaturedItemsAsync()
          {
              return await _db.Queryable<LqEducationDashboardFeaturedItemEntity, LqXmzlEntity>(
                      (config, item) => config.ItemId == item.Id)
                  .Where((config, item) =>
                      config.Enabled == EducationDashboardFeaturedItemStatus.Enabled &&
                      item.IsEffective == 1 &&
                      item.Qt2 == LifeBeautyCategory)
                  .OrderBy((config, item) => config.Sort)
                  .Select((config, item) => new FeaturedItemConfigRow
                  {
                      Id = config.Id,
                      ItemId = config.ItemId,
                      OriginalItemName = item.Xmmc,
                      ItemCategory = item.Qt2,
                      DisplayName = config.DisplayName,
                      Sort = config.Sort
                  })
                  .ToListAsync();
          }
  
          private async Task<bool> IsCurrentEducationTeacherAsync(string statisticsMonth)
          {
              var year = statisticsMonth.Substring(0, 4);
              var month = statisticsMonth.Substring(4, 2);
              return await _db.Queryable<LqMdMajorProjectTeacherAssignmentEntity>()
                  .Where(x => x.Year == year &&
                              x.Month == month &&
                              x.EducationTeacherId == _userManager.UserId)
                  .AnyAsync();
          }
  
          private async Task<(List<EducationDepartmentCustomerDetailListOutput> list, int total)>
              QueryCustomerDetailListAsync(EducationDepartmentCustomerDetailListInput input, bool paged)
          {
              if (input == null) throw NCCException.Oh("请求参数不能为空");
7fc03b57   “wangming”   1
851
852
              var statisticsInput = ToStatisticsInput(input);
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(statisticsInput);
e1dcb3a0   “wangming”   1
853
854
              if (!storeIds.Any()) return (new List<EducationDepartmentCustomerDetailListOutput>(), 0);
  
7fc03b57   “wangming”   1
855
856
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
e1dcb3a0   “wangming”   1
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
              var activityMemberIds = snapshot.SourceData.BillingRows.Select(x => x.MemberId)
                  .Concat(snapshot.SourceData.ConsumeRows.Select(x => x.MemberId))
                  .Concat(snapshot.SourceData.RefundRows.Select(x => x.MemberId))
                  .Where(x => !string.IsNullOrWhiteSpace(x))
                  .Distinct()
                  .ToList();
  
              var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
              var query = _db.Queryable<LqKhxxEntity, LqMdxxEntity>(
                      (member, store) => new JoinQueryInfos(JoinType.Left, member.Gsmd == store.Id))
                  .Where((member, store) =>
                      storeIds.Contains(member.Gsmd) &&
                      (member.IsEducationMember == 1 || activityMemberIds.Contains(member.Id)))
                  .WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (member, store) => member.Gsmd == input.StoreId)
                  .WhereIF(!string.IsNullOrWhiteSpace(input.MemberName), (member, store) =>
                      member.Khmc.Contains(input.MemberName))
                  .WhereIF(!string.IsNullOrWhiteSpace(input.Mobile), (member, store) =>
                      member.Sjh.Contains(input.Mobile))
                  .WhereIF(input.IsEducationMember.HasValue, (member, store) =>
                      member.IsEducationMember == input.IsEducationMember.Value)
                  .WhereIF(keyword != null, (member, store) =>
                      member.Khmc.Contains(keyword) ||
                      member.Sjh.Contains(keyword) ||
                      store.Dm.Contains(keyword))
                  .OrderBy((member, store) => member.EducationMemberTime, OrderByType.Desc)
                  .Select((member, store) => new EducationDepartmentCustomerDetailListOutput
                  {
                      MemberId = member.Id,
                      MemberName = member.Khmc,
                      Mobile = member.Sjh,
                      StoreId = member.Gsmd,
                      StoreName = store.Dm,
                      IsEducationMember = member.IsEducationMember,
                      EducationMemberTime = member.EducationMemberTime
                  });
  
              List<EducationDepartmentCustomerDetailListOutput> members;
              int total;
              if (paged)
              {
                  var page = await query.ToPagedListAsync(
                      NormalizePageIndex(input.currentPage),
                      NormalizePageSize(input.pageSize));
                  members = page.list.ToList();
                  total = page.pagination.Total;
              }
              else
              {
                  members = await query.ToListAsync();
                  total = members.Count;
              }
  
              foreach (var member in members)
              {
                  var billing = snapshot.SourceData.BillingRows.Where(x => x.MemberId == member.MemberId).ToList();
                  var consume = snapshot.SourceData.ConsumeRows.Where(x => x.MemberId == member.MemberId).ToList();
                  var refund = snapshot.SourceData.RefundRows.Where(x => x.MemberId == member.MemberId).ToList();
                  member.BillingCount = billing.Select(x => x.BillId).Distinct().Count();
                  member.BillingAmount = billing.Sum(x => x.Amount);
                  member.ConsumeCount = consume.Select(x => x.ConsumeId).Distinct().Count();
                  member.ConsumeAmount = consume.Sum(x => x.Amount);
                  member.RefundCount = refund.Select(x => x.RefundId).Distinct().Count();
                  member.RefundAmount = refund.Sum(x => x.Amount);
                  member.LastConsumeDate = consume.Any()
                      ? consume.Max(x => x.ConsumeDate)
                      : null;
              }
  
              return (members, total);
          }
  
          private async Task<(List<EducationDepartmentServiceLogListOutput> list, int total)>
              QueryServiceLogListAsync(EducationDepartmentServiceLogListInput input, bool paged)
          {
              if (input == null) throw NCCException.Oh("请求参数不能为空");
7fc03b57   “wangming”   1
932
933
              var statisticsInput = ToStatisticsInput(input);
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(statisticsInput);
e1dcb3a0   “wangming”   1
934
935
              if (!storeIds.Any()) return (new List<EducationDepartmentServiceLogListOutput>(), 0);
  
7fc03b57   “wangming”   1
936
937
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
e1dcb3a0   “wangming”   1
938
939
940
941
942
943
              var consumeIds = snapshot.SourceData.ConsumeRows.Select(x => x.ConsumeId)
                  .Where(x => !string.IsNullOrWhiteSpace(x))
                  .Distinct()
                  .ToList();
              if (!consumeIds.Any()) return (new List<EducationDepartmentServiceLogListOutput>(), 0);
  
7fc03b57   “wangming”   1
944
              var isEducationTeacher = await IsEducationTeacherInMonthsAsync(range.StatisticsMonths);
e1dcb3a0   “wangming”   1
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
              var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
  
              var query = _db.Queryable<
                      LqXhFeedbackEntity,
                      LqXhHyhkEntity,
                      LqKhxxEntity,
                      LqMdxxEntity,
                      UserEntity>((log, consume, member, store, user) => new JoinQueryInfos(
                      JoinType.Inner, log.ConsumeId == consume.Id,
                      JoinType.Left, log.MemberId == member.Id,
                      JoinType.Left, consume.Md == store.Id,
                      JoinType.Left, log.CreateUser == user.Id))
                  .Where((log, consume, member, store, user) =>
                      consumeIds.Contains(log.ConsumeId) &&
                      storeIds.Contains(consume.Md) &&
7fc03b57   “wangming”   1
960
961
                      log.CreateTime >= range.StartInclusive &&
                      log.CreateTime <= range.EndInclusive)
e1dcb3a0   “wangming”   1
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
                  .WhereIF(isEducationTeacher, (log, consume, member, store, user) =>
                      log.CreateUser == _userManager.UserId)
                  .WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (log, consume, member, store, user) =>
                      consume.Md == input.StoreId)
                  .WhereIF(!string.IsNullOrWhiteSpace(input.MemberName), (log, consume, member, store, user) =>
                      member.Khmc.Contains(input.MemberName))
                  .WhereIF(!string.IsNullOrWhiteSpace(input.CreateUserName), (log, consume, member, store, user) =>
                      user.RealName.Contains(input.CreateUserName))
                  .WhereIF(input.HasCompletePhotos == true, (log, consume, member, store, user) =>
                      log.BeforeImage != null && log.BeforeImage != "" &&
                      log.AfterImage != null && log.AfterImage != "")
                  .WhereIF(input.HasCompletePhotos == false, (log, consume, member, store, user) =>
                      log.BeforeImage == null || log.BeforeImage == "" ||
                      log.AfterImage == null || log.AfterImage == "")
                  .WhereIF(keyword != null, (log, consume, member, store, user) =>
                      member.Khmc.Contains(keyword) ||
                      store.Dm.Contains(keyword) ||
                      user.RealName.Contains(keyword) ||
                      log.Remark.Contains(keyword))
                  .OrderBy((log, consume, member, store, user) => log.CreateTime, OrderByType.Desc)
                  .Select((log, consume, member, store, user) => new EducationDepartmentServiceLogListOutput
                  {
                      ServiceLogId = log.Id,
                      ConsumeId = log.ConsumeId,
                      StoreId = consume.Md,
                      StoreName = store.Dm,
                      MemberId = log.MemberId,
                      MemberName = member.Khmc,
                      CreateUserId = log.CreateUser,
                      CreateUserName = user.RealName,
                      Remark = log.Remark,
                      BeforeImage = log.BeforeImage,
                      AfterImage = log.AfterImage,
                      HasCompletePhotos =
                          log.BeforeImage != null && log.BeforeImage != "" &&
                          log.AfterImage != null && log.AfterImage != "",
                      CreateTime = log.CreateTime
                  });
  
              if (paged)
              {
                  var page = await query.ToPagedListAsync(
                      NormalizePageIndex(input.currentPage),
                      NormalizePageSize(input.pageSize));
                  return (page.list.ToList(), page.pagination.Total);
              }
  
              var list = await query.ToListAsync();
              return (list, list.Count);
          }
  
          private async Task<List<EducationDepartmentDashboardStoreDetailListOutput>>
              QueryStoreDetailDataAsync(EducationDepartmentDashboardStoreDetailListInput input)
          {
              if (input == null) throw NCCException.Oh("请求参数不能为空");
7fc03b57   “wangming”   1
1017
1018
              var statisticsInput = ToStatisticsInput(input);
              var (storeIds, range, targetByStore) = await ResolveRangeAsync(statisticsInput);
e1dcb3a0   “wangming”   1
1019
1020
              if (!storeIds.Any()) return new List<EducationDepartmentDashboardStoreDetailListOutput>();
  
7fc03b57   “wangming”   1
1021
1022
1023
              var snapshot = await BuildRangeSnapshotAsync(
                  storeIds, range.StartInclusive, range.EndInclusive, targetByStore);
              var deductByStore = await LoadDeductByStoreAsync(storeIds, range.StartInclusive, range.EndInclusive);
e1dcb3a0   “wangming”   1
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
              var storeQuery = _db.Queryable<LqMdxxEntity>()
                  .Where(x => storeIds.Contains(x.Id))
                  .WhereIF(!string.IsNullOrWhiteSpace(input.StoreName), x => x.Dm.Contains(input.StoreName))
                  .WhereIF(!string.IsNullOrWhiteSpace(input.keyword),
                      x => x.Dm.Contains(input.keyword) || x.Mdbm.Contains(input.keyword));
              var stores = await storeQuery.Select(x => new { x.Id, x.Dm, x.Mdbm }).ToListAsync();
  
              return stores.Select(store =>
              {
                  var metrics = BuildMetrics(
                      snapshot.SourceData.BillingRows.Where(x => x.StoreId == store.Id),
                      snapshot.SourceData.ConsumeRows.Where(x => x.StoreId == store.Id),
                      snapshot.SourceData.RefundRows.Where(x => x.StoreId == store.Id),
                      targetByStore.TryGetValue(store.Id, out var target) ? target : 0m,
                      deductByStore.TryGetValue(store.Id, out var deduct) ? deduct : 0m);
                  return new EducationDepartmentDashboardStoreDetailListOutput
                  {
                      StoreId = store.Id,
                      StoreCode = store.Mdbm ?? string.Empty,
                      StoreName = store.Dm ?? string.Empty,
                      BillingAmount = metrics.BillingAmount,
                      RefundAmount = metrics.RefundAmount,
                      NetPerformance = metrics.NetPerformance,
                      DeductAmount = metrics.DeductAmount,
                      ConsumeAmount = metrics.ConsumeAmount,
                      TargetPerformance = metrics.TargetPerformance,
                      CompletionRate = metrics.CompletionRate,
                      BillingCount = metrics.BillingCount,
                      ConsumeCount = metrics.ConsumeCount,
                      RefundCount = metrics.RefundCount,
                      ConsumeMemberCount = metrics.ConsumeMemberCount,
                      ProjectCount = metrics.ProjectCount
                  };
              }).OrderByDescending(x => x.NetPerformance).ToList();
          }
  
          private async Task<dynamic> ExportFeaturedDataAsync<T>(
              List<T> exportData,
              string actionCode,
              string bizType,
              object filters,
              string columnsJson)
          {
              if (exportData == null || !exportData.Any())
                  return new { name = string.Empty, url = string.Empty, message = "没有找到符合条件的数据" };
  
              var columns = columnsJson.ToList<ParamsModel>();
              var excelConfig = new ExcelConfig
              {
                  FileName = actionCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls",
                  HeadFont = "微软雅黑",
                  HeadPoint = 10,
                  IsAllSizeColumn = true,
                  ColumnModel = columns.Select(x => new ExcelColumnModel
                  {
                      Column = x.field,
                      ExcelColumn = x.value
                  }).ToList()
              };
  
              var exportFilesPath = Path.Combine(ResolveProjectRoot(), "ExportFiles");
              if (!Directory.Exists(exportFilesPath)) Directory.CreateDirectory(exportFilesPath);
              var addPath = Path.Combine(exportFilesPath, excelConfig.FileName);
              ExcelExportHelper<T>.Export(exportData, excelConfig, addPath);
              var encryptedFileName = _userManager.UserId + "|" + addPath + "|xls";
  
              await _businessOperationLogService.WriteAsync(
                  BizLogModule,
                  actionCode,
                  bizType,
                  null,
                  $"{actionCode},共 {exportData.Count} 条",
                  JsonConvert.SerializeObject(new
                  {
                      filters,
                      rowCount = exportData.Count,
                      fileName = excelConfig.FileName
                  }));
  
              return new
              {
                  name = excelConfig.FileName,
                  url = "/api/File/Download?encryption=" +
                        DESCEncryption.Encrypt(encryptedFileName, "NCC")
              };
          }
  
          private static EducationDepartmentDashboardStatisticsInput ToStatisticsInput(
              EducationDepartmentCustomerDetailListInput input)
          {
              return new EducationDepartmentDashboardStatisticsInput
              {
                  EducationDepartmentId = input.EducationDepartmentId,
                  StoreIds = input.StoreIds,
7fc03b57   “wangming”   1
1118
1119
1120
                  StatisticsMonth = input.StatisticsMonth,
                  StartDate = input.StartDate,
                  EndDate = input.EndDate
e1dcb3a0   “wangming”   1
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
              };
          }
  
          private static EducationDepartmentDashboardStatisticsInput ToStatisticsInput(
              EducationDepartmentServiceLogListInput input)
          {
              return new EducationDepartmentDashboardStatisticsInput
              {
                  EducationDepartmentId = input.EducationDepartmentId,
                  StoreIds = input.StoreIds,
7fc03b57   “wangming”   1
1131
1132
1133
                  StatisticsMonth = input.StatisticsMonth,
                  StartDate = input.StartDate,
                  EndDate = input.EndDate
e1dcb3a0   “wangming”   1
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
              };
          }
  
          private static decimal CalculateGrowthRate(decimal current, decimal compare)
          {
              return compare == 0m ? 0m : decimal.Round((current - compare) / compare * 100m, 2);
          }
  
          private static int NormalizePageIndex(int value) => value > 0 ? value : 1;
  
          private static int NormalizePageSize(int value) => value > 0 ? value : 20;
  
          private class FeaturedItemConfigRow
          {
              public string Id { get; set; }
              public string ItemId { get; set; }
              public string OriginalItemName { get; set; }
              public string ItemCategory { get; set; }
              public string DisplayName { get; set; }
              public int Sort { get; set; }
          }
  
          private class ServiceLogStatisticRow
          {
              public string ConsumeId { get; set; }
              public string BeforeImage { get; set; }
              public string AfterImage { get; set; }
          }
  
          #endregion
      }
  }