LqLaundryFlowService.cs
39.3 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
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
851
852
853
854
855
856
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
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": "备注",
/// "sendTime": "2025-01-15T10:30:00" // 可选,如果不传则使用当前时间
/// }
/// ```
///
/// 参数说明:
/// - storeId: 门店ID(必填)
/// - productType: 产品类型(必填)
/// - laundrySupplierId: 清洗商ID(必填)
/// - quantity: 送出数量(必填)
/// - remark: 备注(可选)
/// - sendTime: 送出时间(可选,如果不传则使用当前时间)
/// </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 = input.Quantity * supplier.LaundryPrice, // 送出时总费用为数量 * 单价
Remark = input.Remark,
IsEffective = StatusEnum.有效.GetHashCode(),
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now,
SendTime = input.SendTime ?? 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条损坏",
/// "returnTime": "2025-01-20T14:30:00" // 可选,如果不传则使用当前时间
/// }
/// ```
///
/// 参数说明:
/// - batchNumber: 批次号(必填)
/// - laundrySupplierId: 清洗商ID(必填)
/// - quantity: 送回数量(必填)
/// - remark: 备注(可选)
/// - returnTime: 送回时间(可选,如果不传则使用当前时间)
/// </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,
ReturnTime = input.ReturnTime ?? 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>
/// 修改清洗流水记录的数量、送出时间、送回时间和备注
///
/// 示例请求:
/// ```json
/// {
/// "id": "记录ID",
/// "quantity": 95,
/// "sendTime": "2025-11-01 10:00:00",
/// "returnTime": "2025-11-05 15:00:00",
/// "remark": "修改备注"
/// }
/// ```
///
/// 参数说明:
/// - id: 记录ID(必填)
/// - quantity: 数量(可选,修改时需重新计算总费用)
/// - sendTime: 送出时间(可选,仅流水类型为0时有效)
/// - returnTime: 送回时间(可选,仅流水类型为1时有效)
/// - remark: 备注(可选)
/// </remarks>
/// <param name="input">修改输入</param>
/// <returns>修改结果</returns>
/// <response code="200">修改成功</response>
/// <response code="400">记录不存在或参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("Update")]
public async Task<dynamic> UpdateAsync([FromBody] LqLaundryFlowUpdateInput input)
{
try
{
// 查询记录是否存在
var entity = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.Id == input.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (entity == null)
{
throw NCCException.Oh("记录不存在或已失效");
}
// 更新数量(如果提供)
if (input.Quantity.HasValue)
{
entity.Quantity = input.Quantity.Value;
// 重新计算总费用
entity.TotalPrice = entity.Quantity * entity.LaundryPrice;
}
// 更新送出时间(仅流水类型为0时有效)
if (input.SendTime.HasValue)
{
if (entity.FlowType != 0)
{
throw NCCException.Oh("只有送出记录才能修改送出时间");
}
entity.SendTime = input.SendTime.Value;
}
// 更新送回时间(仅流水类型为1时有效)
if (input.ReturnTime.HasValue)
{
if (entity.FlowType != 1)
{
throw NCCException.Oh("只有送回记录才能修改送回时间");
}
entity.ReturnTime = input.ReturnTime.Value;
}
// 更新备注(如果提供)
if (input.Remark != null)
{
entity.Remark = input.Remark;
}
// 执行更新
var isOk = await _db.Updateable(entity)
.UpdateColumns(it => new
{
it.Quantity,
it.TotalPrice,
it.SendTime,
it.ReturnTime,
it.Remark
})
.ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
return new { message = "修改成功", totalPrice = entity.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 query = _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)
// 清洗商ID筛选:优先使用多选列表,如果为空则使用单选
.WhereIF(input.LaundrySupplierIds != null && input.LaundrySupplierIds.Any(), (flow, store, supplier) => input.LaundrySupplierIds.Contains(flow.LaundrySupplierId))
.WhereIF((input.LaundrySupplierIds == null || !input.LaundrySupplierIds.Any()) && !string.IsNullOrWhiteSpace(input.LaundrySupplierId), (flow, store, supplier) => flow.LaundrySupplierId == input.LaundrySupplierId)
// 创建时间过滤:优先使用SendTime,如果为空则使用CreateTime(与工资计算逻辑保持一致)
.WhereIF(input.StartTime.HasValue, (flow, store, supplier) => (flow.SendTime ?? flow.CreateTime) >= input.StartTime.Value)
.WhereIF(input.EndTime.HasValue, (flow, store, supplier) => (flow.SendTime ?? flow.CreateTime) <= input.EndTime.Value)
// 送出时间过滤
.WhereIF(input.SendStartTime.HasValue, (flow, store, supplier) => flow.SendTime.HasValue && flow.SendTime.Value >= input.SendStartTime.Value)
.WhereIF(input.SendEndTime.HasValue, (flow, store, supplier) => flow.SendTime.HasValue && flow.SendTime.Value <= input.SendEndTime.Value)
// 送回时间过滤
.WhereIF(input.ReturnStartTime.HasValue, (flow, store, supplier) => flow.ReturnTime.HasValue && flow.ReturnTime.Value >= input.ReturnStartTime.Value)
.WhereIF(input.ReturnEndTime.HasValue, (flow, store, supplier) => flow.ReturnTime.HasValue && flow.ReturnTime.Value <= input.ReturnEndTime.Value)
.WhereIF(input.IsEffective.HasValue, (flow, store, supplier) => flow.IsEffective == input.IsEffective.Value);
var data = await query
.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,
sendTime = flow.SendTime,
returnTime = flow.ReturnTime
})
.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,
sendTime = flow.SendTime,
returnTime = flow.ReturnTime
})
.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.SendTime
})
.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.ReturnTime,
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
#region 作废送洗记录
/// <summary>
/// 作废送洗记录
/// </summary>
/// <remarks>
/// 作废送洗记录(将F_IsEffective设置为0),同时可以修改备注说明作废原因
///
/// **重要说明**:
/// - 作废后的记录不会参与费用计算、成本计算、工资计算、股份计算等相关计算
/// - 所有计算逻辑都使用了F_IsEffective=1的条件,因此作废是安全的
/// - 作废后的记录仍保留在数据库中,可以通过列表查询查看,但不会参与统计
///
/// 示例请求:
/// ```json
/// {
/// "id": "记录ID",
/// "remark": "作废原因说明"
/// }
/// ```
///
/// 参数说明:
/// - id: 记录ID(必填)
/// - remark: 备注(可选,用于说明作废原因)
/// </remarks>
/// <param name="input">作废输入</param>
/// <returns>作废结果</returns>
/// <response code="200">作废成功</response>
/// <response code="400">记录不存在或已作废</response>
/// <response code="500">服务器错误</response>
[HttpPost("Cancel")]
public async Task<dynamic> CancelAsync([FromBody] LqLaundryFlowCancelInput input)
{
try
{
if (input == null || string.IsNullOrWhiteSpace(input.Id))
{
throw NCCException.Oh("记录ID不能为空");
}
// 查询记录是否存在
var entity = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.Id == input.Id)
.FirstAsync();
if (entity == null)
{
throw NCCException.Oh("送洗记录不存在");
}
// 检查是否已经作废
if (entity.IsEffective == StatusEnum.无效.GetHashCode())
{
throw NCCException.Oh("该记录已经作废");
}
// 如果该记录是送出记录(F_FlowType = 0),需要检查是否有对应的送回记录
if (entity.FlowType == 0)
{
var returnRecord = await _db.Queryable<LqLaundryFlowEntity>()
.Where(x => x.BatchNumber == entity.BatchNumber
&& x.FlowType == 1
&& x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (returnRecord != null)
{
throw NCCException.Oh("该送出记录已有对应的送回记录,不能单独作废送出记录。如需作废,请先作废对应的送回记录");
}
}
// 作废记录:将F_IsEffective设置为0
entity.IsEffective = StatusEnum.无效.GetHashCode();
// 更新备注(如果提供了备注)
if (!string.IsNullOrWhiteSpace(input.Remark))
{
// 如果原备注不为空,追加新备注;否则直接设置
if (!string.IsNullOrWhiteSpace(entity.Remark))
{
entity.Remark = $"{entity.Remark}\n[作废]{input.Remark}";
}
else
{
entity.Remark = $"[作废]{input.Remark}";
}
}
else if (string.IsNullOrWhiteSpace(entity.Remark))
{
// 如果没有提供备注且原备注为空,则添加默认作废标记
entity.Remark = "[作废]";
}
else
{
// 如果没有提供备注但原备注不为空,则添加默认作废标记
entity.Remark = $"{entity.Remark}\n[作废]";
}
// 执行更新
var isOk = await _db.Updateable(entity)
.UpdateColumns(it => new
{
it.IsEffective,
it.Remark
})
.ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
return new { message = "作废成功", id = entity.Id, remark = entity.Remark };
}
catch (Exception ex)
{
_logger.LogError(ex, "作废送洗记录失败");
throw NCCException.Oh($"作废失败:{ex.Message}");
}
}
#endregion
}
}