LqLaundryFlowService.cs
28.2 KB
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
379
380
381
382
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
416
417
418
419
420
421
422
423
424
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
488
489
490
491
492
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
549
550
551
552
553
554
555
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqLaundryFlow;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_laundry_flow;
using NCC.Extend.Entitys.lq_laundry_supplier;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Interfaces.LqLaundryFlow;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend
{
/// <summary>
/// 清洗流水服务
/// </summary>
[ApiDescriptionSettings(Tag = "绿纤清洗流水管理", Name = "LqLaundryFlow", Order = 200)]
[Route("api/Extend/LqLaundryFlow")]
public class LqLaundryFlowService : IDynamicApiController, ITransient, ILqLaundryFlowService
{
private readonly IUserManager _userManager;
private readonly ILogger<LqLaundryFlowService> _logger;
private readonly ISqlSugarClient _db;
/// <summary>
/// 构造函数
/// </summary>
public LqLaundryFlowService(IUserManager userManager, ILogger<LqLaundryFlowService> logger, ISqlSugarClient db)
{
_userManager = userManager;
_logger = logger;
_db = db;
}
#region 创建送出记录
/// <summary>
/// 创建送出记录
/// </summary>
/// <remarks>
/// 门店选择清洗商和产品,填写送出数量,创建送出记录
///
/// 示例请求:
/// ```json
/// {
/// "storeId": "门店ID",
/// "productType": "毛巾",
/// "laundrySupplierId": "清洗商ID",
/// "quantity": 100,
/// "remark": "备注"
/// }
/// ```
/// </remarks>
/// <param name="input">送出输入</param>
/// <returns>创建结果(包含批次号)</returns>
/// <response code="200">创建成功</response>
/// <response code="400">参数错误或清洗商不存在</response>
/// <response code="500">服务器错误</response>
[HttpPost("Send")]
public async Task<dynamic> SendAsync([FromBody] LqLaundryFlowSendInput input)
{
try
{
// 验证门店是否存在
var store = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Id == input.StoreId)
.FirstAsync();
if (store == null)
{
throw NCCException.Oh("门店不存在");
}
// 验证清洗商是否存在
var supplier = await _db.Queryable<LqLaundrySupplierEntity>()
.Where(x => x.Id == input.LaundrySupplierId && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (supplier == null)
{
throw NCCException.Oh("清洗商不存在或已失效");
}
// 验证产品类型是否匹配
if (supplier.ProductType != input.ProductType)
{
throw NCCException.Oh($"清洗商【{supplier.SupplierName}】不支持清洗产品类型【{input.ProductType}】");
}
// 生成批次号(使用ID)
var batchId = YitIdHelper.NextId().ToString();
// 创建送出记录
var entity = new LqLaundryFlowEntity
{
Id = batchId,
FlowType = 0, // 送出
BatchNumber = batchId, // 批次号等于ID
StoreId = input.StoreId,
ProductType = input.ProductType,
LaundrySupplierId = input.LaundrySupplierId,
Quantity = input.Quantity,
LaundryPrice = supplier.LaundryPrice, // 记录历史价格
TotalPrice = 0, // 送出时总费用为0
Remark = input.Remark,
IsEffective = StatusEnum.有效.GetHashCode(),
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now
};
var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
return new { batchNumber = batchId, message = "送出记录创建成功" };
}
catch (Exception ex)
{
_logger.LogError(ex, "创建送出记录失败");
throw NCCException.Oh($"创建失败:{ex.Message}");
}
}
#endregion
#region 创建送回记录
/// <summary>
/// 创建送回记录
/// </summary>
/// <remarks>
/// 清洗完毕后,填写送回清洗商、送回数量,创建送回记录
///
/// 示例请求:
/// ```json
/// {
/// "batchNumber": "批次号(对应的送出记录的ID)",
/// "laundrySupplierId": "清洗商ID",
/// "quantity": 95,
/// "remark": "5条损坏"
/// }
/// ```
/// </remarks>
/// <param name="input">送回输入</param>
/// <returns>创建结果</returns>
/// <response code="200">创建成功</response>
/// <response code="400">批次号不存在或参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("Return")]
public async Task<dynamic> ReturnAsync([FromBody] LqLaundryFlowReturnInput input)
{
try
{
// 验证对应的送出记录是否存在
var sendRecord = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.BatchNumber == input.BatchNumber && x.FlowType == 0 && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (sendRecord == null)
{
throw NCCException.Oh("对应的送出记录不存在或已失效");
}
// 检查是否已经存在送回记录
var existingReturn = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.BatchNumber == input.BatchNumber && x.FlowType == 1 && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (existingReturn != null)
{
throw NCCException.Oh("该批次已存在送回记录");
}
// 验证清洗商是否存在
var supplier = await _db.Queryable<LqLaundrySupplierEntity>()
.Where(x => x.Id == input.LaundrySupplierId && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (supplier == null)
{
throw NCCException.Oh("清洗商不存在或已失效");
}
// 验证产品类型是否匹配
if (supplier.ProductType != sendRecord.ProductType)
{
throw NCCException.Oh($"清洗商【{supplier.SupplierName}】不支持清洗产品类型【{sendRecord.ProductType}】");
}
// 计算总费用(送回数量 × 清洗单价)
var totalPrice = input.Quantity * supplier.LaundryPrice;
// 创建送回记录
var entity = new LqLaundryFlowEntity
{
Id = YitIdHelper.NextId().ToString(),
FlowType = 1, // 送回
BatchNumber = input.BatchNumber, // 使用送出记录的批次号
StoreId = sendRecord.StoreId,
ProductType = sendRecord.ProductType,
LaundrySupplierId = input.LaundrySupplierId,
Quantity = input.Quantity,
LaundryPrice = supplier.LaundryPrice, // 记录历史价格(可能已变化)
TotalPrice = totalPrice,
Remark = input.Remark,
IsEffective = StatusEnum.有效.GetHashCode(),
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now
};
var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
return new { message = "送回记录创建成功", totalPrice = totalPrice };
}
catch (Exception ex)
{
_logger.LogError(ex, "创建送回记录失败");
throw NCCException.Oh($"创建失败:{ex.Message}");
}
}
#endregion
#region 获取清洗流水列表
/// <summary>
/// 获取清洗流水列表
/// </summary>
/// <remarks>
/// 分页查询清洗流水列表,支持按流水类型、批次号、门店、产品类型、清洗商、时间范围筛选
/// </remarks>
/// <param name="input">查询输入</param>
/// <returns>清洗流水列表</returns>
/// <response code="200">查询成功</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetList")]
public async Task<dynamic> GetListAsync([FromQuery] LqLaundryFlowListQueryInput input)
{
try
{
var sidx = string.IsNullOrEmpty(input.sidx) ? "createTime" : input.sidx;
var sort = string.IsNullOrEmpty(input.sort) ? "desc" : input.sort;
var data = await _db.Queryable<LqLaundryFlowEntity, LqMdxxEntity, LqLaundrySupplierEntity>(
(flow, store, supplier) => flow.StoreId == store.Id && flow.LaundrySupplierId == supplier.Id)
.WhereIF(input.FlowType.HasValue, (flow, store, supplier) => flow.FlowType == input.FlowType.Value)
.WhereIF(!string.IsNullOrWhiteSpace(input.BatchNumber), (flow, store, supplier) => flow.BatchNumber == input.BatchNumber)
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (flow, store, supplier) => flow.StoreId == input.StoreId)
.WhereIF(!string.IsNullOrWhiteSpace(input.ProductType), (flow, store, supplier) => flow.ProductType == input.ProductType)
.WhereIF(!string.IsNullOrWhiteSpace(input.LaundrySupplierId), (flow, store, supplier) => flow.LaundrySupplierId == input.LaundrySupplierId)
.WhereIF(input.StartTime.HasValue, (flow, store, supplier) => flow.CreateTime >= input.StartTime.Value)
.WhereIF(input.EndTime.HasValue, (flow, store, supplier) => flow.CreateTime <= input.EndTime.Value)
.WhereIF(input.IsEffective.HasValue, (flow, store, supplier) => flow.IsEffective == input.IsEffective.Value)
.Select((flow, store, supplier) => new LqLaundryFlowListOutput
{
id = flow.Id,
flowType = flow.FlowType,
flowTypeName = flow.FlowType == 0 ? "送出" : "送回",
batchNumber = flow.BatchNumber,
storeId = flow.StoreId,
storeName = store.Dm ?? "",
productType = flow.ProductType,
laundrySupplierId = flow.LaundrySupplierId,
laundrySupplierName = supplier.SupplierName ?? "",
quantity = flow.Quantity,
laundryPrice = flow.LaundryPrice,
totalPrice = flow.TotalPrice,
remark = flow.Remark,
isEffective = flow.IsEffective,
createUser = flow.CreateUser,
createUserName = "",
createTime = flow.CreateTime
})
.MergeTable()
.OrderBy(sidx + " " + sort)
.ToPagedListAsync(input.currentPage, input.pageSize);
// 补充用户名称信息
var userIds = data.list.Select(x => x.createUser)
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
if (userIds.Any())
{
var userList = await _db.Queryable<UserEntity>()
.Where(x => userIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = userList.ToDictionary(k => k.Id, v => v.RealName);
foreach (var item in data.list)
{
item.createUserName = userDict.ContainsKey(item.createUser) ? userDict[item.createUser] : "";
}
}
return PageResult<LqLaundryFlowListOutput>.SqlSugarPageResult(data);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取清洗流水列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 获取清洗流水详情
/// <summary>
/// 获取清洗流水详情
/// </summary>
/// <remarks>
/// 根据ID获取清洗流水的详细信息
/// </remarks>
/// <param name="id">流水ID</param>
/// <returns>流水详情</returns>
/// <response code="200">查询成功</response>
/// <response code="400">记录不存在</response>
/// <response code="500">服务器错误</response>
[HttpGet("{id}")]
public async Task<LqLaundryFlowInfoOutput> GetInfoAsync(string id)
{
try
{
var entity = await _db.Queryable<LqLaundryFlowEntity, LqMdxxEntity, LqLaundrySupplierEntity>(
(flow, store, supplier) => flow.StoreId == store.Id && flow.LaundrySupplierId == supplier.Id)
.Where((flow, store, supplier) => flow.Id == id)
.Select((flow, store, supplier) => new LqLaundryFlowInfoOutput
{
id = flow.Id,
flowType = flow.FlowType,
flowTypeName = flow.FlowType == 0 ? "送出" : "送回",
batchNumber = flow.BatchNumber,
storeId = flow.StoreId,
storeName = store.Dm ?? "",
productType = flow.ProductType,
laundrySupplierId = flow.LaundrySupplierId,
laundrySupplierName = supplier.SupplierName ?? "",
quantity = flow.Quantity,
laundryPrice = flow.LaundryPrice,
totalPrice = flow.TotalPrice,
remark = flow.Remark,
isEffective = flow.IsEffective,
createUser = flow.CreateUser,
createUserName = "",
createTime = flow.CreateTime
})
.FirstAsync();
if (entity == null)
{
throw NCCException.Oh("流水记录不存在");
}
// 补充用户名称
if (!string.IsNullOrEmpty(entity.createUser))
{
var createUser = await _db.Queryable<UserEntity>()
.Where(x => x.Id == entity.createUser)
.Select(x => x.RealName)
.FirstAsync();
entity.createUserName = createUser ?? "";
}
return entity;
}
catch (Exception ex)
{
_logger.LogError(ex, "获取清洗流水详情失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 查询差异记录
/// <summary>
/// 查询差异记录(送出数量 > 送回数量)
/// </summary>
/// <remarks>
/// 查询所有送出数量大于送回数量的记录,用于追踪差异来源
/// </remarks>
/// <param name="input">查询输入(支持分页)</param>
/// <returns>差异记录列表</returns>
/// <response code="200">查询成功</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetDifferenceList")]
public async Task<dynamic> GetDifferenceListAsync([FromBody] LqLaundryFlowListQueryInput input)
{
try
{
// 查询所有送出记录
var sendRecords = await _db.Queryable<LqLaundryFlowEntity, LqMdxxEntity>(
(flow, store) => flow.StoreId == store.Id)
.Where((flow, store) => flow.FlowType == 0 && flow.IsEffective == StatusEnum.有效.GetHashCode())
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (flow, store) => flow.StoreId == input.StoreId)
.WhereIF(!string.IsNullOrWhiteSpace(input.ProductType), (flow, store) => flow.ProductType == input.ProductType)
.WhereIF(input.StartTime.HasValue, (flow, store) => flow.CreateTime >= input.StartTime.Value)
.WhereIF(input.EndTime.HasValue, (flow, store) => flow.CreateTime <= input.EndTime.Value)
.Select((flow, store) => new
{
flow.BatchNumber,
flow.StoreId,
StoreName = store.Dm ?? "",
flow.ProductType,
SendQuantity = flow.Quantity,
SendTime = flow.CreateTime
})
.ToListAsync();
if (!sendRecords.Any())
{
return new
{
list = new List<LqLaundryFlowDifferenceOutput>(),
pagination = new
{
page = input.currentPage,
pageSize = input.pageSize,
total = 0
}
};
}
// 查询所有送回记录
var returnRecords = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.FlowType == 1 && x.IsEffective == StatusEnum.有效.GetHashCode())
.Select(x => new
{
x.BatchNumber,
ReturnQuantity = x.Quantity,
ReturnTime = x.CreateTime,
x.Remark
})
.ToListAsync();
var returnDict = returnRecords
.GroupBy(x => x.BatchNumber)
.ToDictionary(g => g.Key, g => g.First());
// 计算差异
var differenceList = sendRecords
.Select(send => new LqLaundryFlowDifferenceOutput
{
batchNumber = send.BatchNumber,
storeId = send.StoreId,
storeName = send.StoreName,
productType = send.ProductType,
sendQuantity = send.SendQuantity,
returnQuantity = returnDict.ContainsKey(send.BatchNumber) ? returnDict[send.BatchNumber].ReturnQuantity : 0,
differenceQuantity = send.SendQuantity - (returnDict.ContainsKey(send.BatchNumber) ? returnDict[send.BatchNumber].ReturnQuantity : 0),
differenceRemark = returnDict.ContainsKey(send.BatchNumber) ? returnDict[send.BatchNumber].Remark : "",
sendTime = send.SendTime,
returnTime = returnDict.ContainsKey(send.BatchNumber) ? returnDict[send.BatchNumber].ReturnTime : (DateTime?)null
})
.Where(x => x.differenceQuantity > 0)
.ToList();
// 手动分页
var totalCount = differenceList.Count;
var pagedList = differenceList
.Skip((input.currentPage - 1) * input.pageSize)
.Take(input.pageSize)
.ToList();
return new
{
list = pagedList,
pagination = new
{
page = input.currentPage,
pageSize = input.pageSize,
total = totalCount
}
};
}
catch (Exception ex)
{
_logger.LogError(ex, "查询差异记录失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 门店每月清洗费用统计
/// <summary>
/// 门店每月清洗费用统计
/// </summary>
/// <remarks>
/// 统计每个门店每月的清洗费用(只统计送回记录)
///
/// 示例请求:
/// ```json
/// {
/// "startMonth": "202411",
/// "endMonth": "202412",
/// "storeId": "门店ID(可选)"
/// }
/// ```
/// </remarks>
/// <param name="input">统计输入</param>
/// <returns>统计结果</returns>
/// <response code="200">统计成功</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetStoreMonthlyStatistics")]
public async Task<List<LqLaundryStatisticsOutput>> GetStoreMonthlyStatisticsAsync([FromBody] LaundryStatisticsInput input)
{
try
{
// 构建月份过滤条件
var startDate = (DateTime?)null;
var endDate = (DateTime?)null;
if (!string.IsNullOrWhiteSpace(input.StartMonth) && input.StartMonth.Length == 6)
{
var year = int.Parse(input.StartMonth.Substring(0, 4));
var month = int.Parse(input.StartMonth.Substring(4, 2));
startDate = new DateTime(year, month, 1);
}
if (!string.IsNullOrWhiteSpace(input.EndMonth) && input.EndMonth.Length == 6)
{
var year = int.Parse(input.EndMonth.Substring(0, 4));
var month = int.Parse(input.EndMonth.Substring(4, 2));
endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
}
var query = _db.Queryable<LqLaundryFlowEntity, LqMdxxEntity>(
(flow, store) => flow.StoreId == store.Id)
.Where((flow, store) => flow.FlowType == 1 && flow.IsEffective == StatusEnum.有效.GetHashCode())
.WhereIF(startDate.HasValue, (flow, store) => flow.CreateTime >= startDate.Value)
.WhereIF(endDate.HasValue, (flow, store) => flow.CreateTime <= endDate.Value)
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (flow, store) => flow.StoreId == input.StoreId);
var allRecords = await query
.Select((flow, store) => new
{
flow.StoreId,
StoreName = store.Dm ?? "",
flow.CreateTime,
flow.TotalPrice,
flow.Id
})
.ToListAsync();
// 在内存中分组统计
var result = allRecords
.GroupBy(x => new { x.StoreId, x.StoreName, Month = x.CreateTime.ToString("yyyyMM") })
.Select(g => new LqLaundryStatisticsOutput
{
storeId = g.Key.StoreId,
storeName = g.Key.StoreName,
statisticsMonth = g.Key.Month,
totalPrice = g.Sum(x => x.TotalPrice),
count = g.Count()
})
.OrderBy(x => x.storeId)
.ThenBy(x => x.statisticsMonth)
.ToList();
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "门店每月清洗费用统计失败");
throw NCCException.Oh($"统计失败:{ex.Message}");
}
}
#endregion
#region 产品每月清洗费用统计
/// <summary>
/// 产品每月清洗费用统计
/// </summary>
/// <remarks>
/// 统计每个产品每月的清洗费用(只统计送回记录)
///
/// 示例请求:
/// ```json
/// {
/// "startMonth": "202411",
/// "endMonth": "202412",
/// "productType": "毛巾(可选)"
/// }
/// ```
/// </remarks>
/// <param name="input">统计输入</param>
/// <returns>统计结果</returns>
/// <response code="200">统计成功</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetProductMonthlyStatistics")]
public async Task<List<LqLaundryStatisticsOutput>> GetProductMonthlyStatisticsAsync([FromBody] LaundryStatisticsInput input)
{
try
{
// 构建月份过滤条件
var startDate = (DateTime?)null;
var endDate = (DateTime?)null;
if (!string.IsNullOrWhiteSpace(input.StartMonth) && input.StartMonth.Length == 6)
{
var year = int.Parse(input.StartMonth.Substring(0, 4));
var month = int.Parse(input.StartMonth.Substring(4, 2));
startDate = new DateTime(year, month, 1);
}
if (!string.IsNullOrWhiteSpace(input.EndMonth) && input.EndMonth.Length == 6)
{
var year = int.Parse(input.EndMonth.Substring(0, 4));
var month = int.Parse(input.EndMonth.Substring(4, 2));
endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
}
var query = _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.FlowType == 1 && x.IsEffective == StatusEnum.有效.GetHashCode())
.WhereIF(startDate.HasValue, x => x.CreateTime >= startDate.Value)
.WhereIF(endDate.HasValue, x => x.CreateTime <= endDate.Value)
.WhereIF(!string.IsNullOrWhiteSpace(input.ProductType), x => x.ProductType == input.ProductType);
var allRecords = await query
.Select(x => new
{
x.ProductType,
x.CreateTime,
x.TotalPrice,
x.Id
})
.ToListAsync();
// 在内存中分组统计
var result = allRecords
.GroupBy(x => new { x.ProductType, Month = x.CreateTime.ToString("yyyyMM") })
.Select(g => new LqLaundryStatisticsOutput
{
productType = g.Key.ProductType,
statisticsMonth = g.Key.Month,
totalPrice = g.Sum(x => x.TotalPrice),
count = g.Count()
})
.OrderBy(x => x.productType)
.ThenBy(x => x.statisticsMonth)
.ToList();
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "产品每月清洗费用统计失败");
throw NCCException.Oh($"统计失败:{ex.Message}");
}
}
#endregion
}
}