LqXmzlService.cs
44 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
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
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
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.LqXmzl;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys.lq_xmzl;
using NCC.Extend.Entitys.Dto.LqXmzl;
using NCC.Extend.Entitys.lq_kd_pxmx;
using NCC.Extend.Entitys.lq_xh_pxmx;
using NCC.Extend.Entitys.lq_hytk_mx;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_xh_hyhk;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_kd_deductinfo;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.Extend.Entitys.Enum;
namespace NCC.Extend.LqXmzl
{
/// <summary>
/// 项目资料服务
/// </summary>
[ApiDescriptionSettings(Tag = "绿纤品项资料服务", Name = "LqXmzl", Order = 200)]
[Route("api/Extend/[controller]")]
public class LqXmzlService : ILqXmzlService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository<LqXmzlEntity> _lqXmzlRepository;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
/// <summary>
/// 初始化一个<see cref="LqXmzlService"/>类型的新实例
/// </summary>
public LqXmzlService(ISqlSugarRepository<LqXmzlEntity> lqXmzlRepository, IUserManager userManager)
{
_lqXmzlRepository = lqXmzlRepository;
_db = _lqXmzlRepository.Context;
_userManager = userManager;
}
#region 获取品项资料
/// <summary>
/// 获取项目资料
/// </summary>
/// <param name="id">参数</param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
var entity = await _db.Queryable<LqXmzlEntity>().FirstAsync(p => p.Id == id);
var output = entity.Adapt<LqXmzlInfoOutput>();
return output;
}
#endregion
#region 获取品项资料列表
/// <summary>
/// 获取品项资料列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] LqXmzlListQueryInput input)
{
var sidx = input.sidx == null ? "id" : input.sidx;
var data = await _db.Queryable<LqXmzlEntity>()
.WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
.WhereIF(!string.IsNullOrEmpty(input.xmbh), p => p.Xmbh.Contains(input.xmbh))
.WhereIF(!string.IsNullOrEmpty(input.xmmc), p => p.Xmmc.Contains(input.xmmc))
.WhereIF(!string.IsNullOrEmpty(input.bzjg), p => p.Bzjg.Equals(input.bzjg))
.WhereIF(!string.IsNullOrEmpty(input.xmsc), p => p.Xmsc.Equals(input.xmsc))
.WhereIF(!string.IsNullOrEmpty(input.jcfwtc), p => p.Jcfwtc.Equals(input.jcfwtc))
.WhereIF(!string.IsNullOrEmpty(input.fl1), p => p.Fl1.Contains(input.fl1))
.WhereIF(!string.IsNullOrEmpty(input.fl2), p => p.Fl2.Contains(input.fl2))
.WhereIF(!string.IsNullOrEmpty(input.fl3), p => p.Fl3.Contains(input.fl3))
.WhereIF(!string.IsNullOrEmpty(input.fl4), p => p.Fl4.Contains(input.fl4))
.WhereIF(!string.IsNullOrEmpty(input.fl), p => p.Fl.Contains(input.fl))
.WhereIF(!string.IsNullOrEmpty(input.qt1), p => p.Qt1.Contains(input.qt1))
.WhereIF(!string.IsNullOrEmpty(input.qt2), p => p.Qt2.Contains(input.qt2))
.WhereIF(!string.IsNullOrEmpty(input.sgf), p => p.Sgf.Equals(input.sgf))
.WhereIF(!string.IsNullOrEmpty(input.beautyType), p => p.BeautyType.Contains(input.beautyType))
.WhereIF(input.isEffective != 0, p => p.IsEffective.Equals(input.isEffective))
.WhereIF(!string.IsNullOrEmpty(input.sourceType), p => p.SourceType.Contains(input.sourceType))
.Select(it => new LqXmzlListOutput
{
id = it.Id,
xmbh = it.Xmbh,
xmmc = it.Xmmc,
bzjg = it.Bzjg,
xmsc = it.Xmsc,
jcfwtc = it.Jcfwtc,
fl1 = it.Fl1,
fl2 = it.Fl2,
fl3 = it.Fl3,
fl4 = it.Fl4,
fl = it.Fl,
qt1 = it.Qt1,
qt2 = it.Qt2,
sgf = it.Sgf,
beautyType = it.BeautyType,
sourceType = it.SourceType,
isEffective = it.IsEffective,
medicalBeautyLaborCost = it.MedicalBeautyLaborCost,
techBeautyLaborCost = it.TechBeautyLaborCost,
lifeBeautyLaborCost = it.LifeBeautyLaborCost,
healthCoachLaborCost = it.HealthCoachLaborCost,
isAllowAccompanied = it.IsAllowAccompanied,
}).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<LqXmzlListOutput>.SqlSugarPageResult(data);
}
#endregion
#region 新建品项资料
/// <summary>
/// 新建品项资料
/// </summary>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] LqXmzlCrInput input)
{
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt<LqXmzlEntity>();
entity.Id = YitIdHelper.NextId().ToString();
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
#endregion
#region 获取品项资料无分页列表
/// <summary>
/// 获取品项资料无分页列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[NonAction]
public async Task<dynamic> GetNoPagingList([FromQuery] LqXmzlListQueryInput input)
{
var sidx = input.sidx == null ? "id" : input.sidx;
var data = await _db.Queryable<LqXmzlEntity>()
.WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
.WhereIF(!string.IsNullOrEmpty(input.xmbh), p => p.Xmbh.Contains(input.xmbh))
.WhereIF(!string.IsNullOrEmpty(input.xmmc), p => p.Xmmc.Contains(input.xmmc))
.WhereIF(!string.IsNullOrEmpty(input.bzjg), p => p.Bzjg.Equals(input.bzjg))
.WhereIF(!string.IsNullOrEmpty(input.xmsc), p => p.Xmsc.Equals(input.xmsc))
.WhereIF(!string.IsNullOrEmpty(input.jcfwtc), p => p.Jcfwtc.Equals(input.jcfwtc))
.WhereIF(!string.IsNullOrEmpty(input.fl1), p => p.Fl1.Contains(input.fl1))
.WhereIF(!string.IsNullOrEmpty(input.fl2), p => p.Fl2.Contains(input.fl2))
.WhereIF(!string.IsNullOrEmpty(input.fl3), p => p.Fl3.Contains(input.fl3))
.WhereIF(!string.IsNullOrEmpty(input.fl4), p => p.Fl4.Contains(input.fl4))
.WhereIF(!string.IsNullOrEmpty(input.fl), p => p.Fl.Contains(input.fl))
.WhereIF(!string.IsNullOrEmpty(input.qt1), p => p.Qt1.Contains(input.qt1))
.WhereIF(!string.IsNullOrEmpty(input.qt2), p => p.Qt2.Contains(input.qt2))
.WhereIF(!string.IsNullOrEmpty(input.sgf), p => p.Sgf.Equals(input.sgf))
.Select(it => new LqXmzlListOutput
{
id = it.Id,
xmbh = it.Xmbh,
xmmc = it.Xmmc,
bzjg = it.Bzjg,
xmsc = it.Xmsc,
jcfwtc = it.Jcfwtc,
fl1 = it.Fl1,
fl2 = it.Fl2,
fl3 = it.Fl3,
fl4 = it.Fl4,
fl = it.Fl,
qt1 = it.Qt1,
qt2 = it.Qt2,
sgf = it.Sgf,
}).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync();
return data;
}
#endregion
#region 导出品项资料
/// <summary>
/// 导出品项资料
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("Actions/Export")]
public async Task<dynamic> Export([FromQuery] LqXmzlListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = new List<LqXmzlListOutput>();
if (input.dataType == 0)
{
var data = Clay.Object(await this.GetList(input));
exportData = data.Solidify<PageResult<LqXmzlListOutput>>().list;
}
else
{
exportData = await this.GetNoPagingList(input);
}
List<ParamsModel> paramList = "[{\"value\":\"主键\",\"field\":\"id\"},{\"value\":\"项目编号\",\"field\":\"xmbh\"},{\"value\":\"项目名称\",\"field\":\"xmmc\"},{\"value\":\"标准价格\",\"field\":\"bzjg\"},{\"value\":\"时长(分)\",\"field\":\"xmsc\"},{\"value\":\"基础服务提成\",\"field\":\"jcfwtc\"},{\"value\":\"分类1汇总表\",\"field\":\"fl1\"},{\"value\":\"分类2汇总表\",\"field\":\"fl2\"},{\"value\":\"分类3工资用\",\"field\":\"fl3\"},{\"value\":\"分类4品项用\",\"field\":\"fl4\"},{\"value\":\"统计类别\",\"field\":\"tjlb\"},{\"value\":\"折扣类别\",\"field\":\"zklb\"},{\"value\":\"分类\",\"field\":\"fl\"},{\"value\":\"其它1\",\"field\":\"qt1\"},{\"value\":\"其它2\",\"field\":\"qt2\"},{\"value\":\"溯源金额\",\"field\":\"syje\"},{\"value\":\"Cell金额\",\"field\":\"cellje\"},{\"value\":\"手工费\",\"field\":\"sgf\"},]".ToList<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "项目资料.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
List<string> selectKeyList = input.selectKey.Split(',').ToList();
foreach (var item in selectKeyList)
{
var isExist = paramList.Find(p => p.field == item);
if (isExist != null)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
}
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<LqXmzlListOutput>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
#endregion
#region 批量删除品项资料
/// <summary>
/// 批量删除品项资料
/// </summary>
/// <param name="ids">主键数组</param>
/// <returns></returns>
[HttpPost("batchRemove")]
public async Task BatchRemove([FromBody] List<string> ids)
{
throw NCCException.Oh("不允许删除项目资料");
var entitys = await _db.Queryable<LqXmzlEntity>().In(it => it.Id, ids).ToListAsync();
if (entitys.Count > 0)
{
try
{
//开启事务
_db.BeginTran();
//批量删除项目资料
await _db.Deleteable<LqXmzlEntity>().In(d => d.Id, ids).ExecuteCommandAsync();
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw NCCException.Oh(ErrorCode.COM1002);
}
}
}
#endregion
#region 更新品项资料
/// <summary>
/// 更新品项资料
/// </summary>
/// <param name="id">主键</param>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] LqXmzlUpInput input)
{
var entity = input.Adapt<LqXmzlEntity>();
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
#endregion
#region 设置品项作废
/// <summary>
/// 设置品项作废
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
[HttpPut("SetInvalid/{id}")]
public async Task SetInvalid(string id)
{
var entity = await _db.Queryable<LqXmzlEntity>().FirstAsync(p => p.Id == id);
if (entity == null) throw NCCException.Oh("品项不存在");
entity.IsEffective = StatusEnum.无效.GetHashCode();
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
#endregion
#region 删除品项资料
/// <summary>
/// 删除品项资料
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task Delete(string id)
{
throw NCCException.Oh("不允许删除项目资料");
}
#endregion
#region 获取字段去重数据
/// <summary>
/// 获取指定字段的去重数据
/// </summary>
/// <param name="fieldName">字段名称,支持:fl1、fl2、fl3、fl4、fl、qt1、beautyType、sourceType</param>
/// <returns>去重后的字段数据</returns>
[HttpGet("GetDistinctFieldData")]
public async Task<dynamic> GetDistinctFieldData([FromQuery] string fieldName)
{
try
{
// 验证字段名称
var validFields = new[] { "fl1", "fl2", "fl3", "fl4", "fl", "qt1", "qt2", "beautyType", "sourceType" };
if (!validFields.Contains(fieldName))
{
throw NCCException.Oh($"无效的字段名称: {fieldName}。支持的字段: {string.Join(", ", validFields)}");
}
List<string> distinctValues = new List<string>();
switch (fieldName)
{
case "fl1":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Fl1))
.Select(p => p.Fl1)
.Distinct()
.ToListAsync();
break;
case "fl2":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Fl2))
.Select(p => p.Fl2)
.Distinct()
.ToListAsync();
break;
case "fl3":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Fl3))
.Select(p => p.Fl3)
.Distinct()
.ToListAsync();
break;
case "fl4":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Fl4))
.Select(p => p.Fl4)
.Distinct()
.ToListAsync();
break;
case "fl":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Fl))
.Select(p => p.Fl)
.Distinct()
.ToListAsync();
break;
case "qt1":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Qt1))
.Select(p => p.Qt1)
.Distinct()
.ToListAsync();
break;
case "qt2":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.Qt2))
.Select(p => p.Qt2)
.Distinct()
.ToListAsync();
break;
case "beautyType":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.BeautyType))
.Select(p => p.BeautyType)
.Distinct()
.ToListAsync();
break;
case "sourceType":
distinctValues = await _db.Queryable<LqXmzlEntity>()
.Where(p => !string.IsNullOrEmpty(p.SourceType))
.Select(p => p.SourceType)
.Distinct()
.ToListAsync();
break;
}
return new
{
fieldName = fieldName,
values = distinctValues.OrderBy(x => x).ToList()
};
}
catch (Exception ex)
{
throw NCCException.Oh($"获取字段去重数据失败:{ex.Message}");
}
}
#endregion
#region 品项维度统计
/// <summary>
/// 品项维度统计
/// </summary>
/// <remarks>
/// 按品项维度统计开卡、消耗、退卡、储扣等数据
/// 包括业绩、人数、占比、复购率、储扣次数及金额等指标
///
/// 示例请求:
/// ```json
/// {
/// "startTime": "2024-01-01",
/// "endTime": "2024-12-31",
/// "storeId": "store001",
/// "itemCategory": "科美",
/// "itemId": "item001"
/// }
/// ```
///
/// 参数说明:
/// - startTime: 开始时间(可选)
/// - endTime: 结束时间(可选)
/// - storeId: 门店ID(可选)
/// - category: 品项分类(可选,已废弃,建议使用itemCategory)
/// - itemCategory: 品项分类筛选(可选,支持:科美、医美、生美、产品等,对应lq_xmzl表的qt2字段)
/// - itemId: 品项ID(可选,单个品项统计)
///
/// 返回字段说明:
/// - ItemCategory: 品项分类(科美、医美、生美、产品等)
/// - DeductAmount: 储扣金额
/// - DeductCount: 储扣次数
/// </remarks>
/// <param name="input">统计输入参数</param>
/// <returns>品项维度统计数据</returns>
/// <response code="200">统计成功</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetItemStatistics")]
public async Task<dynamic> GetItemStatistics([FromBody] LqXmzlStatisticsInput input)
{
try
{
// 第一步:获取品项基础信息(优化:一次性查询,包含分类字段)
var itemsQuery = _db.Queryable<LqXmzlEntity>()
.Where(x => x.IsEffective == 1);
if (!string.IsNullOrEmpty(input.ItemId))
{
itemsQuery = itemsQuery.Where(x => x.Id == input.ItemId);
}
// 兼容旧的Category字段
if (!string.IsNullOrEmpty(input.Category))
{
itemsQuery = itemsQuery.Where(x => x.Fl1 == input.Category || x.Fl2 == input.Category || x.Fl == input.Category);
}
// 新增:按品项分类筛选(qt2字段:科美、医美、生美、产品等)
if (!string.IsNullOrEmpty(input.ItemCategory))
{
itemsQuery = itemsQuery.Where(x => x.Qt2 == input.ItemCategory);
}
var items = await itemsQuery.Select(x => new { x.Id, x.Xmmc, x.Xmbh, x.Qt2 }).ToListAsync();
if (!items.Any())
{
return new
{
success = true,
data = new List<LqXmzlStatisticsOutput>(),
message = "未找到符合条件的品项"
};
}
var itemIds = items.Select(x => x.Id).ToList();
// 创建品项信息字典,便于后续查找
var itemInfoDict = items.ToDictionary(x => x.Id, x => new { x.Xmmc, x.Xmbh, x.Qt2 });
// 第二步:开卡数据统计
var billingStats = await GetBillingStatistics(itemIds, input);
// 第三步:消耗数据统计
var consumeStats = await GetConsumeStatistics(itemIds, input);
// 第四步:退卡数据统计
var refundStats = await GetRefundStatistics(itemIds, input);
// 第五步:储扣数据统计(新增)
var deductStats = await GetDeductStatistics(itemIds, input);
// 第六步:计算总数据用于占比计算
var totalBillingAmount = billingStats.Sum(x => x.BillingAmount);
var totalConsumeAmount = consumeStats.Sum(x => x.ConsumeAmount);
var totalBuyers = billingStats.Sum(x => x.TotalBuyers);
// 第七步:合并数据并计算占比(优化:使用字典提升查找效率)
var billingDict = billingStats.ToDictionary(x => x.ItemId);
var consumeDict = consumeStats.ToDictionary(x => x.ItemId);
var refundDict = refundStats.ToDictionary(x => x.ItemId);
var deductDict = deductStats.ToDictionary(x => x.ItemId);
var result = new List<LqXmzlStatisticsOutput>();
foreach (var item in items)
{
billingDict.TryGetValue(item.Id, out var billingData);
consumeDict.TryGetValue(item.Id, out var consumeData);
refundDict.TryGetValue(item.Id, out var refundData);
deductDict.TryGetValue(item.Id, out var deductData);
var itemInfo = itemInfoDict[item.Id];
var output = new LqXmzlStatisticsOutput
{
ItemId = item.Id,
ItemName = itemInfo.Xmmc,
ItemNumber = itemInfo.Xmbh,
ItemCategory = itemInfo.Qt2 ?? "", // 显示品项分类
BillingAmount = billingData?.BillingAmount ?? 0,
BillingAmountRatio = totalBillingAmount > 0 ? (billingData?.BillingAmount ?? 0) / totalBillingAmount : 0,
TotalBuyers = billingData?.TotalBuyers ?? 0,
ItemRatio = totalBuyers > 0 ? (billingData?.TotalBuyers ?? 0) / (decimal)totalBuyers : 0,
RepeatBuyers = billingData?.RepeatBuyers ?? 0,
RepeatBuyRate = (billingData?.TotalBuyers ?? 0) > 0 ? (billingData?.RepeatBuyers ?? 0) / (decimal)(billingData?.TotalBuyers ?? 1) : 0,
ConsumeAmount = consumeData?.ConsumeAmount ?? 0,
ConsumeAmountRatio = totalConsumeAmount > 0 ? (consumeData?.ConsumeAmount ?? 0) / totalConsumeAmount : 0,
ConsumePurchaseCount = consumeData?.ConsumePurchaseCount ?? 0,
ConsumeGiftCount = consumeData?.ConsumeGiftCount ?? 0,
ConsumeExperienceCount = consumeData?.ConsumeExperienceCount ?? 0,
RefundAmount = refundData?.RefundAmount ?? 0,
RefundCount = refundData?.RefundCount ?? 0,
DeductAmount = deductData?.DeductAmount ?? 0, // 新增:储扣金额
DeductCount = deductData?.DeductCount ?? 0 // 新增:储扣次数
};
result.Add(output);
}
return new
{
success = true,
data = result,
message = "品项维度统计成功"
};
}
catch (Exception ex)
{
throw NCCException.Oh($"品项维度统计失败:{ex.Message}");
}
}
/// <summary>
/// 获取开卡统计数据
/// </summary>
private async Task<List<ItemStatisticsData>> GetBillingStatistics(List<string> itemIds, LqXmzlStatisticsInput input)
{
// 使用JOIN关联开单记录表,以便使用开单时间进行过滤
var query = _db.Queryable<LqKdPxmxEntity, LqKdKdjlbEntity>((px, kd) => new JoinQueryInfos(
JoinType.Inner, px.Glkdbh == kd.Id))
.Where((px, kd) => itemIds.Contains(px.Px) && px.IsEffective == 1 && kd.IsEffective == 1);
// 时间过滤(使用开单时间)
if (input.StartTime.HasValue)
{
query = query.Where((px, kd) => kd.Kdrq >= input.StartTime.Value);
}
if (input.EndTime.HasValue)
{
query = query.Where((px, kd) => kd.Kdrq <= input.EndTime.Value);
}
// 门店过滤
if (!string.IsNullOrEmpty(input.StoreId))
{
query = query.Where((px, kd) => kd.Djmd == input.StoreId);
}
var result = await query
.GroupBy((px, kd) => px.Px)
.Select((px, kd) => new ItemStatisticsData
{
ItemId = px.Px,
BillingAmount = SqlFunc.AggregateSum(px.Pxjg * px.ProjectNumber),
TotalBuyers = SqlFunc.AggregateCount(px.MemberId),
RepeatBuyers = 0 // 复购人数需要单独计算
})
.ToListAsync();
// 优化:批量计算复购人数,避免循环查询
if (result.Any())
{
var resultItemIds = result.Select(x => x.ItemId).ToList();
// 一次性查询所有品项的复购人数
var repeatBuyerQuery = _db.Queryable<LqKdPxmxEntity, LqKdKdjlbEntity>((px, kd) => new JoinQueryInfos(
JoinType.Inner, px.Glkdbh == kd.Id))
.Where((px, kd) => resultItemIds.Contains(px.Px) && px.IsEffective == 1 && kd.IsEffective == 1);
if (input.StartTime.HasValue)
{
repeatBuyerQuery = repeatBuyerQuery.Where((px, kd) => kd.Kdrq >= input.StartTime.Value);
}
if (input.EndTime.HasValue)
{
repeatBuyerQuery = repeatBuyerQuery.Where((px, kd) => kd.Kdrq <= input.EndTime.Value);
}
if (!string.IsNullOrEmpty(input.StoreId))
{
repeatBuyerQuery = repeatBuyerQuery.Where((px, kd) => kd.Djmd == input.StoreId);
}
// 按品项和会员分组,统计每个会员购买次数
var memberPurchaseStats = await repeatBuyerQuery
.GroupBy((px, kd) => new { px.Px, px.MemberId })
.Select((px, kd) => new { px.Px, px.MemberId, PurchaseCount = SqlFunc.AggregateCount(px.MemberId) })
.ToListAsync();
// 统计每个品项的复购人数(购买次数>1的会员数)
var repeatBuyerDict = memberPurchaseStats
.Where(x => x.PurchaseCount > 1)
.GroupBy(x => x.Px)
.ToDictionary(g => g.Key, g => g.Count());
// 填充复购人数
foreach (var item in result)
{
item.RepeatBuyers = repeatBuyerDict.ContainsKey(item.ItemId) ? repeatBuyerDict[item.ItemId] : 0;
}
}
return result;
}
/// <summary>
/// 获取消耗统计数据
/// </summary>
private async Task<List<ItemConsumeStatisticsData>> GetConsumeStatistics(List<string> itemIds, LqXmzlStatisticsInput input)
{
var query = _db.Queryable<LqXhPxmxEntity>()
.Where(x => itemIds.Contains(x.Px));
// 时间过滤
if (input.StartTime.HasValue)
{
query = query.Where(x => x.CreateTIme >= input.StartTime.Value);
}
if (input.EndTime.HasValue)
{
query = query.Where(x => x.CreateTIme <= input.EndTime.Value);
}
// 门店过滤(通过耗卡记录关联)
if (!string.IsNullOrEmpty(input.StoreId))
{
// 使用子查询过滤门店 - 在SQL层面过滤,避免别名问题
query = query.Where(x => SqlFunc.Subqueryable<LqXhHyhkEntity>()
.Where(xh => xh.Id == x.ConsumeInfoId && xh.Md == input.StoreId && xh.IsEffective == 1)
.Any());
}
var result = await query
.GroupBy(x => x.Px)
.Select(x => new ItemConsumeStatisticsData
{
ItemId = x.Px,
ConsumeAmount = SqlFunc.AggregateSum(x.Pxjg * x.ProjectNumber),
ConsumePurchaseCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.SourceType == "购买", x.ProjectNumber, 0)),
ConsumeGiftCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.SourceType == "赠送", x.ProjectNumber, 0)),
ConsumeExperienceCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.SourceType == "体验", x.ProjectNumber, 0))
})
.ToListAsync();
return result;
}
/// <summary>
/// 获取退卡统计数据
/// </summary>
private async Task<List<ItemRefundStatisticsData>> GetRefundStatistics(List<string> itemIds, LqXmzlStatisticsInput input)
{
var query = _db.Queryable<LqHytkMxEntity>()
.Where(x => itemIds.Contains(x.Px));
// 时间过滤
if (input.StartTime.HasValue)
{
query = query.Where(x => x.Tksj >= input.StartTime.Value);
}
if (input.EndTime.HasValue)
{
query = query.Where(x => x.Tksj <= input.EndTime.Value);
}
// 门店过滤(通过退卡记录关联)
if (!string.IsNullOrEmpty(input.StoreId))
{
// 使用子查询过滤门店 - 在SQL层面过滤,避免别名问题
query = query.Where(x => SqlFunc.Subqueryable<LqHytkHytkEntity>()
.Where(hytk => hytk.Id == x.RefundInfoId && hytk.Md == input.StoreId && hytk.IsEffective == 1)
.Any());
}
var result = await query
.GroupBy(x => x.Px)
.Select(x => new ItemRefundStatisticsData
{
ItemId = x.Px,
RefundAmount = SqlFunc.AggregateSum(x.Tkje ?? 0),
RefundCount = SqlFunc.AggregateCount(x.Id)
})
.ToListAsync();
return result;
}
/// <summary>
/// 获取储扣统计数据(新增)
/// </summary>
private async Task<List<ItemDeductStatisticsData>> GetDeductStatistics(List<string> itemIds, LqXmzlStatisticsInput input)
{
// 使用JOIN关联开单记录表,以便使用开单时间进行过滤
var query = _db.Queryable<LqKdDeductinfoEntity, LqKdKdjlbEntity>((deduct, kd) => new JoinQueryInfos(
JoinType.Inner, deduct.BillingId == kd.Id))
.Where((deduct, kd) => itemIds.Contains(deduct.ItemId) && deduct.IsEffective == 1 && kd.IsEffective == 1);
// 时间过滤(使用开单时间)
if (input.StartTime.HasValue)
{
query = query.Where((deduct, kd) => (deduct.BillingTime ?? kd.Kdrq) >= input.StartTime.Value);
}
if (input.EndTime.HasValue)
{
query = query.Where((deduct, kd) => (deduct.BillingTime ?? kd.Kdrq) <= input.EndTime.Value);
}
// 门店过滤
if (!string.IsNullOrEmpty(input.StoreId))
{
query = query.Where((deduct, kd) => kd.Djmd == input.StoreId);
}
var result = await query
.GroupBy((deduct, kd) => deduct.ItemId)
.Select((deduct, kd) => new ItemDeductStatisticsData
{
ItemId = deduct.ItemId,
DeductAmount = SqlFunc.AggregateSum(deduct.Amount ?? 0),
DeductCount = SqlFunc.AggregateCount(deduct.Id)
})
.ToListAsync();
return result;
}
#endregion
#region 获取品项门店统计
/// <summary>
/// 获取品项门店统计
/// </summary>
/// <remarks>
/// 根据品项ID、开始时间和结束时间,统计每个门店对于该品项的开单数、项目数、实付金额、退款金额
///
/// 示例请求:
/// ```json
/// {
/// "itemId": "17",
/// "startTime": "2025-11-01",
/// "endTime": "2025-11-30"
/// }
/// ```
///
/// 参数说明:
/// - itemId: 品项ID(必填)
/// - startTime: 开始时间(必填)
/// - endTime: 结束时间(必填)
///
/// 返回说明:
/// - StoreId: 门店ID
/// - StoreName: 门店名称
/// - BillingCount: 开单数(去重后的开单编号数量)
/// - ProjectCount: 项目数(项目次数总和,已废弃,使用TotalProjectCount代替)
/// - TotalProjectCount: 总项目数(项目次数总和)
/// - PurchaseProjectCount: 购买项目数(来源类型为"购买"的项目次数总和)
/// - ExperienceProjectCount: 体验项目数(来源类型为"体验"的项目次数总和)
/// - GiftProjectCount: 赠送项目数(来源类型为"赠送"的项目次数总和)
/// - ActualAmount: 实付金额(实付金额总和,使用开单记录的sfyj字段)
/// - RefundAmount: 退款金额(退款金额总和)
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>品项门店统计数据列表</returns>
/// <response code="200">成功返回品项门店统计数据列表</response>
/// <response code="400">参数无效</response>
/// <response code="500">服务器内部错误</response>
[HttpPost("get-item-store-statistics")]
public async Task<List<ItemStoreStatisticsOutput>> GetItemStoreStatistics(ItemStoreStatisticsInput input)
{
if (string.IsNullOrWhiteSpace(input.ItemId))
{
throw NCCException.Oh("品项ID不能为空");
}
// 查询开单统计数据(按门店分组)
// 修改:ActualAmount使用开单记录的实付金额(sfyj),而不是品项明细的实际价格
// 注意:需要先按开单去重,避免一个开单包含多个该品项时重复计算sfyj
// 新增:按来源类型(SourceType)拆分项目数统计
var billingSql = $@"
SELECT
store.F_Id as StoreId,
store.dm as StoreName,
COUNT(DISTINCT billing.F_Id) as BillingCount,
COALESCE(SUM(pxmx.F_ProjectNumber), 0) as TotalProjectCount,
COALESCE(SUM(CASE WHEN pxmx.F_SourceType = '购买' THEN pxmx.F_ProjectNumber ELSE 0 END), 0) as PurchaseProjectCount,
COALESCE(SUM(CASE WHEN pxmx.F_SourceType = '体验' THEN pxmx.F_ProjectNumber ELSE 0 END), 0) as ExperienceProjectCount,
COALESCE(SUM(CASE WHEN pxmx.F_SourceType = '赠送' THEN pxmx.F_ProjectNumber ELSE 0 END), 0) as GiftProjectCount
FROM lq_kd_pxmx pxmx
INNER JOIN lq_kd_kdjlb billing ON pxmx.glkdbh = billing.F_Id
INNER JOIN lq_mdxx store ON billing.djmd = store.F_Id
WHERE pxmx.px = '{input.ItemId}'
AND pxmx.F_IsEffective = 1
AND billing.F_IsEffective = 1
AND billing.kdrq >= '{input.StartTime:yyyy-MM-dd} 00:00:00'
AND billing.kdrq < '{input.EndTime.AddDays(1):yyyy-MM-dd} 00:00:00'
GROUP BY store.F_Id, store.dm";
// 查询实付金额(按门店分组,使用开单的sfyj字段,去重开单ID)
var actualAmountSql = $@"
SELECT
billing.djmd as StoreId,
COALESCE(SUM(billing.sfyj), 0) as ActualAmount
FROM (
SELECT DISTINCT billing2.F_Id, billing2.djmd, billing2.sfyj
FROM lq_kd_kdjlb billing2
INNER JOIN lq_kd_pxmx pxmx2 ON billing2.F_Id = pxmx2.glkdbh
WHERE pxmx2.px = '{input.ItemId}'
AND pxmx2.F_IsEffective = 1
AND billing2.F_IsEffective = 1
AND billing2.kdrq >= '{input.StartTime:yyyy-MM-dd} 00:00:00'
AND billing2.kdrq < '{input.EndTime.AddDays(1):yyyy-MM-dd} 00:00:00'
) billing
GROUP BY billing.djmd";
var actualAmountData = await _db.Ado.SqlQueryAsync<dynamic>(actualAmountSql);
// 创建实付金额字典
var actualAmountDict = actualAmountData
.Where(x => x.StoreId != null)
.ToDictionary(
x => x.StoreId.ToString(),
x => Convert.ToDecimal(x.ActualAmount ?? 0)
);
var billingData = await _db.Ado.SqlQueryAsync<dynamic>(billingSql);
// 查询退款统计数据(按门店分组)
var refundSql = $@"
SELECT
store.F_Id as StoreId,
store.dm as StoreName,
COALESCE(SUM(refund_mx.tkje), 0) as RefundAmount
FROM lq_hytk_mx refund_mx
INNER JOIN lq_hytk_hytk refund ON refund_mx.F_RefundInfoId = refund.F_Id
INNER JOIN lq_mdxx store ON refund.md = store.F_Id
WHERE refund_mx.px = '{input.ItemId}'
AND refund_mx.F_IsEffective = 1
AND refund.F_IsEffective = 1
AND refund.tksj >= '{input.StartTime:yyyy-MM-dd} 00:00:00'
AND refund.tksj < '{input.EndTime.AddDays(1):yyyy-MM-dd} 00:00:00'
GROUP BY store.F_Id, store.dm";
var refundData = await _db.Ado.SqlQueryAsync<dynamic>(refundSql);
// 合并数据
var resultDict = new Dictionary<string, ItemStoreStatisticsOutput>();
// 处理开单数据
foreach (var item in billingData ?? Enumerable.Empty<dynamic>())
{
var storeId = item.StoreId.ToString();
// 从实付金额字典中获取该门店的实付金额
var actualAmount = actualAmountDict.ContainsKey(storeId) ? actualAmountDict[storeId] : 0;
resultDict[storeId] = new ItemStoreStatisticsOutput
{
StoreId = storeId,
StoreName = item.StoreName.ToString(),
BillingCount = Convert.ToInt32(item.BillingCount),
ProjectCount = Convert.ToDecimal(item.TotalProjectCount ?? item.ProjectCount ?? 0), // 保持兼容性
TotalProjectCount = Convert.ToDecimal(item.TotalProjectCount ?? 0),
PurchaseProjectCount = Convert.ToDecimal(item.PurchaseProjectCount ?? 0),
ExperienceProjectCount = Convert.ToDecimal(item.ExperienceProjectCount ?? 0),
GiftProjectCount = Convert.ToDecimal(item.GiftProjectCount ?? 0),
ActualAmount = actualAmount, // 使用开单记录的实付金额(sfyj)
RefundAmount = 0
};
}
// 处理退款数据
foreach (var item in refundData ?? Enumerable.Empty<dynamic>())
{
var storeId = item.StoreId.ToString();
if (resultDict.ContainsKey(storeId))
{
resultDict[storeId].RefundAmount = Convert.ToDecimal(item.RefundAmount);
}
else
{
// 如果门店只有退款没有开单,也添加到结果中
resultDict[storeId] = new ItemStoreStatisticsOutput
{
StoreId = storeId,
StoreName = item.StoreName.ToString(),
BillingCount = 0,
ProjectCount = 0,
TotalProjectCount = 0,
PurchaseProjectCount = 0,
ExperienceProjectCount = 0,
GiftProjectCount = 0,
ActualAmount = 0,
RefundAmount = Convert.ToDecimal(item.RefundAmount)
};
}
}
// 按实付金额降序排列
return resultDict.Values.OrderByDescending(x => x.ActualAmount).ToList();
}
#endregion
}
/// <summary>
/// 品项统计数据(内部类)
/// </summary>
public class ItemStatisticsData
{
public string ItemId { get; set; }
public decimal BillingAmount { get; set; }
public int TotalBuyers { get; set; }
public int RepeatBuyers { get; set; }
}
/// <summary>
/// 品项消耗统计数据(内部类)
/// </summary>
public class ItemConsumeStatisticsData
{
public string ItemId { get; set; }
public decimal ConsumeAmount { get; set; }
public decimal ConsumePurchaseCount { get; set; }
public decimal ConsumeGiftCount { get; set; }
public decimal ConsumeExperienceCount { get; set; }
}
/// <summary>
/// 品项退卡统计数据(内部类)
/// </summary>
public class ItemRefundStatisticsData
{
public string ItemId { get; set; }
public decimal RefundAmount { get; set; }
public int RefundCount { get; set; }
}
/// <summary>
/// 品项储扣统计数据(内部类)
/// </summary>
public class ItemDeductStatisticsData
{
public string ItemId { get; set; }
public decimal DeductAmount { get; set; }
public int DeductCount { get; set; }
}
}