LqTechGeneralManagerSalaryService.cs
50.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
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Filter;
using NCC.Common.Helper;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqSalary;
using NCC.Extend.Entitys.Dto.LqTechGeneralManagerSalary;
using NCC.Extend.Entitys.lq_attendance_summary;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_hytk_jksyj;
using NCC.Extend.Entitys.lq_hytk_mx;
using NCC.Extend.Entitys.lq_kd_jksyj;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_kd_pxmx;
using NCC.Extend.Entitys.lq_md_general_manager_lifeline;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_tech_general_manager_salary_statistics;
using NCC.Extend.Entitys.lq_xmzl;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
namespace NCC.Extend
{
/// <summary>
/// 科技部总经理薪酬服务
/// </summary>
[ApiDescriptionSettings(Tag = "科技部总经理薪酬服务", Name = "LqTechGeneralManagerSalary", Order = 305)]
[Route("api/Extend/[controller]")]
public class LqTechGeneralManagerSalaryService : IDynamicApiController, ITransient
{
private readonly ISqlSugarClient _db;
private readonly ILogger<LqTechGeneralManagerSalaryService> _logger;
/// <summary>
/// 初始化一个<see cref="LqTechGeneralManagerSalaryService"/>类型的新实例
/// </summary>
public LqTechGeneralManagerSalaryService(ISqlSugarClient db, ILogger<LqTechGeneralManagerSalaryService> logger)
{
_db = db;
_logger = logger;
}
/// <summary>
/// 获取科技部总经理工资列表
/// </summary>
/// <param name="input">查询参数</param>
/// <returns>科技部总经理工资分页列表</returns>
[HttpGet("tech-general-manager")]
public async Task<dynamic> GetTechGeneralManagerSalaryList([FromQuery] TechGeneralManagerSalaryInput input)
{
var monthStr = $"{input.Year}{input.Month:D2}";
// 查询数据
var query = _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr);
if (!string.IsNullOrEmpty(input.Position))
{
query = query.Where(x => x.Position == input.Position);
}
if (!string.IsNullOrEmpty(input.Keyword))
{
query = query.Where(x => x.EmployeeName.Contains(input.Keyword) || x.EmployeeAccount.Contains(input.Keyword));
}
var list = await query.Select(x => new TechGeneralManagerSalaryOutput
{
Id = x.Id,
StatisticsMonth = x.StatisticsMonth,
Position = x.Position,
EmployeeName = x.EmployeeName,
EmployeeId = x.EmployeeId,
EmployeeAccount = x.EmployeeAccount,
IsTerminated = x.IsTerminated,
StoreDetail = x.StoreDetail,
TraceabilityAmount = x.TraceabilityAmount,
CellAmount = x.CellAmount,
BaseSalary = x.BaseSalary,
TraceabilityCommissionRate = x.TraceabilityCommissionRate,
TraceabilityCommissionAmount = x.TraceabilityCommissionAmount,
CellCommissionRate = x.CellCommissionRate,
CellCommissionAmount = x.CellCommissionAmount,
TotalCommission = x.TotalCommission,
WorkingDays = x.WorkingDays,
LeaveDays = x.LeaveDays,
CalculatedGrossSalary = x.CalculatedGrossSalary,
FinalGrossSalary = x.FinalGrossSalary,
MonthlyTrainingSubsidy = x.MonthlyTrainingSubsidy,
MonthlyTransportSubsidy = x.MonthlyTransportSubsidy,
LastMonthTrainingSubsidy = x.LastMonthTrainingSubsidy,
LastMonthTransportSubsidy = x.LastMonthTransportSubsidy,
TotalSubsidy = x.TotalSubsidy,
MissingCard = x.MissingCard,
LateArrival = x.LateArrival,
LeaveDeduction = x.LeaveDeduction,
SocialInsuranceDeduction = x.SocialInsuranceDeduction,
RewardDeduction = x.RewardDeduction,
AccommodationDeduction = x.AccommodationDeduction,
StudyPeriodDeduction = x.StudyPeriodDeduction,
WorkClothesDeduction = x.WorkClothesDeduction,
TotalDeduction = x.TotalDeduction,
Bonus = x.Bonus,
ReturnPhoneDeposit = x.ReturnPhoneDeposit,
ReturnAccommodationDeposit = x.ReturnAccommodationDeposit,
ActualSalary = x.ActualSalary,
MonthlyPaymentStatus = x.MonthlyPaymentStatus,
PaidAmount = x.PaidAmount,
PendingAmount = x.PendingAmount,
LastMonthSupplement = x.LastMonthSupplement,
MonthlyTotalPayment = x.MonthlyTotalPayment,
IsLocked = x.IsLocked,
UpdateTime = x.UpdateTime
})
.ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<TechGeneralManagerSalaryOutput>.SqlSugarPageResult(list);
}
/// <summary>
/// 通过月份和员工ID查询工资
/// </summary>
[HttpGet("query-by-employee")]
public async Task<TechGeneralManagerSalaryOutput> GetSalaryByEmployee([FromQuery] SalaryQueryByEmployeeInput input)
{
if (input.Year <= 0 || input.Month <= 0 || input.Month > 12)
throw NCCException.Oh("年份和月份参数不正确");
if (string.IsNullOrWhiteSpace(input.EmployeeId))
throw NCCException.Oh("员工ID不能为空");
var monthStr = $"{input.Year}{input.Month:D2}";
var salary = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr && x.EmployeeId == input.EmployeeId)
.Select(x => new TechGeneralManagerSalaryOutput
{
Id = x.Id,
StatisticsMonth = x.StatisticsMonth,
Position = x.Position,
EmployeeName = x.EmployeeName,
EmployeeId = x.EmployeeId,
EmployeeAccount = x.EmployeeAccount,
IsTerminated = x.IsTerminated,
StoreDetail = x.StoreDetail,
TraceabilityAmount = x.TraceabilityAmount,
CellAmount = x.CellAmount,
BaseSalary = x.BaseSalary,
TraceabilityCommissionRate = x.TraceabilityCommissionRate,
TraceabilityCommissionAmount = x.TraceabilityCommissionAmount,
CellCommissionRate = x.CellCommissionRate,
CellCommissionAmount = x.CellCommissionAmount,
TotalCommission = x.TotalCommission,
WorkingDays = x.WorkingDays,
LeaveDays = x.LeaveDays,
CalculatedGrossSalary = x.CalculatedGrossSalary,
FinalGrossSalary = x.FinalGrossSalary,
MonthlyTrainingSubsidy = x.MonthlyTrainingSubsidy,
MonthlyTransportSubsidy = x.MonthlyTransportSubsidy,
LastMonthTrainingSubsidy = x.LastMonthTrainingSubsidy,
LastMonthTransportSubsidy = x.LastMonthTransportSubsidy,
TotalSubsidy = x.TotalSubsidy,
MissingCard = x.MissingCard,
LateArrival = x.LateArrival,
LeaveDeduction = x.LeaveDeduction,
SocialInsuranceDeduction = x.SocialInsuranceDeduction,
RewardDeduction = x.RewardDeduction,
AccommodationDeduction = x.AccommodationDeduction,
StudyPeriodDeduction = x.StudyPeriodDeduction,
WorkClothesDeduction = x.WorkClothesDeduction,
TotalDeduction = x.TotalDeduction,
Bonus = x.Bonus,
ReturnPhoneDeposit = x.ReturnPhoneDeposit,
ReturnAccommodationDeposit = x.ReturnAccommodationDeposit,
ActualSalary = x.ActualSalary,
MonthlyPaymentStatus = x.MonthlyPaymentStatus,
PaidAmount = x.PaidAmount,
PendingAmount = x.PendingAmount,
LastMonthSupplement = x.LastMonthSupplement,
MonthlyTotalPayment = x.MonthlyTotalPayment,
IsLocked = x.IsLocked,
UpdateTime = x.UpdateTime
})
.FirstAsync();
if (salary == null)
throw NCCException.Oh($"未找到员工{input.EmployeeId}在{input.Year}年{input.Month}月的工资记录");
return salary;
}
/// <summary>
/// 计算科技部总经理工资
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns></returns>
[HttpPost("calculate/tech-general-manager")]
public async Task CalculateTechGeneralManagerSalary(int year, int month)
{
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var monthStr = $"{year}{month:D2}";
// 1. 获取基础数据
// 1.1 先从BASE_ORGANIZE表查找组织名称包含"科技一部"或"科技二部"的组织
var techOrganizeList = await _db.Queryable<OrganizeEntity>()
.Where(x => x.FullName != null && (x.FullName.Contains("科技一部") || x.FullName.Contains("科技二部"))
&& x.DeleteMark == null && x.EnabledMark == 1)
.Select(x => new { x.Id, x.FullName })
.ToListAsync();
if (!techOrganizeList.Any())
{
// 如果没有找到科技部组织,直接返回
return;
}
var techOrganizeIds = techOrganizeList.Select(x => x.Id).ToList();
var techOrganizeDict = techOrganizeList.ToDictionary(x => x.Id, x => x.FullName);
// 1.2 从BASE_USER表查询岗位为"总经理"且组织ID在科技一部或科技二部的员工
var techGeneralManagerUserList = await _db.Queryable<UserEntity>()
.Where(x => x.Gw == "总经理"
&& techOrganizeIds.Contains(x.OrganizeId)
&& x.DeleteMark == null && x.EnabledMark == 1)
.Select(x => new { x.Id, x.RealName, x.Account, x.Gw, x.OrganizeId, x.IsOnJob })
.ToListAsync();
if (!techGeneralManagerUserList.Any())
{
// 如果没有科技部总经理员工,直接返回
return;
}
if (!techGeneralManagerUserList.Any())
{
// 如果没有科技部总经理员工,直接返回
return;
}
// 1.3 获取科技部总经理归属信息(从lq_md_general_manager_lifeline表)
// 通过门店的科技部组织ID(kjb字段)找到科技一部或科技二部管理的门店
// 然后在lifeline表中找到这些门店的记录,这些记录对应的总经理就是科技部总经理
var lifelineList = await _db.Queryable<LqMdGeneralManagerLifelineEntity, LqMdxxEntity>(
(lifeline, store) => lifeline.StoreId == store.Id)
.Where((lifeline, store) =>
lifeline.Month == monthStr
&& techOrganizeIds.Contains(store.Kjb))
.Select((lifeline, store) => lifeline)
.ToListAsync();
// 1.4 获取科技一部和科技二部管理的门店(通过门店的kjb字段)
var techManagedStoreIds = await _db.Queryable<LqMdxxEntity>()
.Where(x => techOrganizeIds.Contains(x.Kjb))
.Select(x => x.Id)
.ToListAsync();
// 1.5 按科技部总经理ID分组,获取每个科技部总经理管理的门店
// 科技部总经理管理的门店 = 科技一部/科技二部管理的所有门店(通过门店的kjb字段确定)
var managerStoreDict = new Dictionary<string, List<string>>();
foreach (var managerUser in techGeneralManagerUserList)
{
var managerId = managerUser.Id;
var managerOrganizeId = managerUser.OrganizeId;
// 如果该总经理属于科技一部,则管理所有科技一部的门店
// 如果该总经理属于科技二部,则管理所有科技二部的门店
var managedStores = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Kjb == managerOrganizeId)
.Select(x => x.Id)
.ToListAsync();
managerStoreDict[managerId] = managedStores;
}
// 1.4 门店信息 (lq_mdxx)
var storeList = await _db.Queryable<LqMdxxEntity>().ToListAsync();
var storeDict = storeList.Where(x => !string.IsNullOrEmpty(x.Id)).ToDictionary(x => x.Id, x => x);
// 1.6 考勤数据 (lq_attendance_summary)
var attendanceList = await _db.Queryable<LqAttendanceSummaryEntity>()
.Where(x => x.Year == year && x.Month == month && x.IsEffective == 1)
.ToListAsync();
var attendanceDict = attendanceList.ToDictionary(x => x.UserId, x => x);
// 1.7 获取所有管理的门店ID列表(用于后续查询,如果没有管理的门店,则为空列表)
var allManagedStoreIds = managerStoreDict.Values.SelectMany(x => x).Distinct().ToList();
// 1.8 按科技部总经理和门店分组统计(用于生成门店明细JSON和汇总数据)
var storeDetailDict = new Dictionary<string, Dictionary<string, StoreDetailItem>>();
// 按门店统计溯源和Cell金额(如果有管理的门店)
if (allManagedStoreIds.Any())
{
foreach (var storeId in allManagedStoreIds)
{
// 该门店的开单溯源金额(从健康师业绩表统计)
var storeTraceabilityBillingList = await _db.Queryable<LqKdJksyjEntity>()
.Where(x => x.IsEffective == 1
&& x.StoreId == storeId
&& (x.BeautyType == "溯源系统" || x.BeautyType == "溯源")
&& x.Yjsj >= startDate && x.Yjsj <= endDate.AddDays(1))
.Select(x => x.Jksyj)
.ToListAsync();
var storeTraceabilityBilling = storeTraceabilityBillingList
.Where(x => !string.IsNullOrEmpty(x))
.Sum(x => decimal.TryParse(x, out var val) ? val : 0m);
// 该门店的退卡溯源金额(从退卡健康师业绩表统计)
var storeTraceabilityRefund = await _db.Queryable<LqHytkJksyjEntity>()
.Where(x => x.IsEffective == 1
&& x.StoreId == storeId
&& (x.BeautyType == "溯源系统" || x.BeautyType == "溯源")
&& x.Tksj >= startDate && x.Tksj <= endDate.AddDays(1))
.SumAsync(x => (decimal?)x.Jksyj) ?? 0m;
// 该门店的开单Cell金额(从健康师业绩表统计)
var storeCellBillingList = await _db.Queryable<LqKdJksyjEntity>()
.Where(x => x.IsEffective == 1
&& x.StoreId == storeId
&& (x.BeautyType == "cell" || x.BeautyType == "Cell")
&& x.Yjsj >= startDate && x.Yjsj <= endDate.AddDays(1))
.Select(x => x.Jksyj)
.ToListAsync();
var storeCellBilling = storeCellBillingList
.Where(x => !string.IsNullOrEmpty(x))
.Sum(x => decimal.TryParse(x, out var val) ? val : 0m);
// 该门店的退卡Cell金额(从退卡健康师业绩表统计)
var storeCellRefund = await _db.Queryable<LqHytkJksyjEntity>()
.Where(x => x.IsEffective == 1
&& x.StoreId == storeId
&& (x.BeautyType == "cell" || x.BeautyType == "Cell")
&& x.Tksj >= startDate && x.Tksj <= endDate.AddDays(1))
.SumAsync(x => (decimal?)x.Jksyj) ?? 0m;
// 获取该门店属于哪些科技部总经理
// 通过门店的kjb字段确定:如果门店的kjb等于科技一部的组织ID,则该门店属于科技一部总经理
var store = storeDict.ContainsKey(storeId) ? storeDict[storeId] : null;
var managersOfStore = new List<string>();
if (store != null && !string.IsNullOrEmpty(store.Kjb))
{
// 找到组织ID等于门店kjb的科技部总经理
var managers = techGeneralManagerUserList
.Where(x => x.OrganizeId == store.Kjb)
.Select(x => x.Id)
.ToList();
managersOfStore.AddRange(managers);
}
foreach (var managerId in managersOfStore)
{
if (!storeDetailDict.ContainsKey(managerId))
{
storeDetailDict[managerId] = new Dictionary<string, StoreDetailItem>();
}
var storeName = storeDict.ContainsKey(storeId) ? storeDict[storeId].Dm ?? "" : "";
storeDetailDict[managerId][storeId] = new StoreDetailItem
{
StoreId = storeId,
StoreName = storeName,
TraceabilityBillingAmount = storeTraceabilityBilling,
TraceabilityRefundAmount = storeTraceabilityRefund,
TraceabilityAmount = storeTraceabilityBilling - storeTraceabilityRefund,
CellBillingAmount = storeCellBilling,
CellRefundAmount = storeCellRefund,
CellAmount = storeCellBilling - storeCellRefund
};
}
}
}
// 2. 按科技部总经理聚合数据
var managerStats = new Dictionary<string, LqTechGeneralManagerSalaryStatisticsEntity>();
foreach (var managerUser in techGeneralManagerUserList)
{
var managerId = managerUser.Id;
// 获取该科技部总经理管理的门店列表
var managedStores = managerStoreDict.ContainsKey(managerId) ? managerStoreDict[managerId] : new List<string>();
// 2.1 创建工资统计对象
// 岗位使用组织名称(科技一部/科技二部)
var position = techOrganizeDict.ContainsKey(managerUser.OrganizeId)
? techOrganizeDict[managerUser.OrganizeId]
: "";
var salary = new LqTechGeneralManagerSalaryStatisticsEntity
{
Id = YitIdHelper.NextId().ToString(),
StatisticsMonth = monthStr,
EmployeeId = managerId,
Position = position,
EmployeeName = managerUser.RealName ?? "",
EmployeeAccount = managerUser.Account ?? "",
IsTerminated = managerUser.IsOnJob == 0 ? 1 : 0,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now,
IsLocked = 0
};
// 2.2 考勤数据
var attendance = attendanceDict.ContainsKey(managerId) ? attendanceDict[managerId] : null;
salary.WorkingDays = attendance?.WorkDays ?? 0;
salary.LeaveDays = attendance?.LeaveDays ?? 0;
// 2.3 计算底薪(固定4000元)
salary.BaseSalary = 4000m;
// 2.4 统计该科技部总经理管理的所有门店的溯源金额和Cell金额总和
decimal totalTraceabilityAmount = 0m;
decimal totalCellAmount = 0m;
var storeDetails = new List<StoreDetailItem>();
if (managedStores.Any() && storeDetailDict.ContainsKey(managerId))
{
foreach (var storeId in managedStores)
{
if (storeDetailDict[managerId].ContainsKey(storeId))
{
var storeDetail = storeDetailDict[managerId][storeId];
totalTraceabilityAmount += storeDetail.TraceabilityAmount;
totalCellAmount += storeDetail.CellAmount;
storeDetails.Add(storeDetail);
}
}
}
salary.TraceabilityAmount = totalTraceabilityAmount;
salary.CellAmount = totalCellAmount;
// 2.5 保存门店明细(JSON格式)
salary.StoreDetail = JsonConvert.SerializeObject(storeDetails);
// 2.6 计算溯源金额提成(分段累进)
var traceabilityCommission = CalculateTraceabilityCommission(totalTraceabilityAmount);
salary.TraceabilityCommissionAmount = traceabilityCommission.Amount;
salary.TraceabilityCommissionRate = traceabilityCommission.Rate;
// 2.7 计算Cell金额提成(分段累进)
var cellCommission = CalculateCellCommission(totalCellAmount);
salary.CellCommissionAmount = cellCommission.Amount;
salary.CellCommissionRate = cellCommission.Rate;
// 2.8 提成合计
salary.TotalCommission = salary.TraceabilityCommissionAmount + salary.CellCommissionAmount;
// 2.9 计算应发工资
salary.CalculatedGrossSalary = salary.BaseSalary + salary.TotalCommission;
salary.FinalGrossSalary = salary.CalculatedGrossSalary;
// 2.10 初始化其他字段(默认值为0)
salary.MonthlyTrainingSubsidy = 0;
salary.MonthlyTransportSubsidy = 0;
salary.LastMonthTrainingSubsidy = 0;
salary.LastMonthTransportSubsidy = 0;
salary.TotalSubsidy = 0;
salary.MissingCard = 0;
salary.LateArrival = 0;
salary.LeaveDeduction = 0;
salary.SocialInsuranceDeduction = 0;
salary.RewardDeduction = 0;
salary.AccommodationDeduction = 0;
salary.StudyPeriodDeduction = 0;
salary.WorkClothesDeduction = 0;
salary.TotalDeduction = 0;
salary.Bonus = 0;
salary.ReturnPhoneDeposit = 0;
salary.ReturnAccommodationDeposit = 0;
salary.ActualSalary = salary.FinalGrossSalary - salary.TotalDeduction + salary.TotalSubsidy + salary.Bonus;
salary.MonthlyPaymentStatus = "未发放";
salary.PaidAmount = 0;
salary.PendingAmount = salary.ActualSalary;
salary.LastMonthSupplement = 0;
salary.MonthlyTotalPayment = 0;
managerStats[managerId] = salary;
}
// 3. 保存数据
if (managerStats.Any())
{
var existingRecords = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr).ToListAsync();
var existingDict = existingRecords.Where(x => !string.IsNullOrEmpty(x.EmployeeId))
.GroupBy(x => x.EmployeeId).ToDictionary(g => g.Key, g => g.First());
var recordsToInsert = new List<LqTechGeneralManagerSalaryStatisticsEntity>();
var recordsToUpdate = new List<LqTechGeneralManagerSalaryStatisticsEntity>();
var skippedCount = 0;
foreach (var salary in managerStats.Values)
{
if (existingDict.ContainsKey(salary.EmployeeId))
{
var existing = existingDict[salary.EmployeeId];
if (existing.IsLocked == 1 || existing.EmployeeConfirmStatus == 1) { skippedCount++; continue; }
salary.Id = existing.Id;
salary.EmployeeConfirmStatus = existing.EmployeeConfirmStatus;
salary.EmployeeConfirmTime = existing.EmployeeConfirmTime;
salary.EmployeeConfirmRemark = existing.EmployeeConfirmRemark;
salary.IsLocked = existing.IsLocked;
salary.CreateTime = existing.CreateTime;
salary.CreateUser = existing.CreateUser;
recordsToUpdate.Add(salary);
}
else
{
salary.Id = YitIdHelper.NextId().ToString();
salary.EmployeeConfirmStatus = 0;
salary.IsLocked = 0;
salary.CreateTime = DateTime.Now;
salary.CreateUser = "";
recordsToInsert.Add(salary);
}
}
if (recordsToInsert.Any()) await _db.Insertable(recordsToInsert).ExecuteCommandAsync();
if (recordsToUpdate.Any()) await _db.Updateable(recordsToUpdate).ExecuteCommandAsync();
if (skippedCount > 0) _logger.LogWarning($"计算工资时跳过了 {skippedCount} 条已锁定或已确认的记录(月份:{monthStr})");
}
}
/// <summary>
/// 计算溯源金额提成(分段累进)
/// </summary>
/// <param name="traceabilityAmount">溯源金额</param>
/// <returns>提成金额和平均比例</returns>
private (decimal Amount, decimal? Rate) CalculateTraceabilityCommission(decimal traceabilityAmount)
{
if (traceabilityAmount <= 0)
{
return (0m, null);
}
decimal commissionAmount = 0m;
decimal? averageRate = null;
if (traceabilityAmount < 200000m)
{
// < 200,000元:1%
commissionAmount = traceabilityAmount * 0.01m;
averageRate = 1.00m;
}
else if (traceabilityAmount < 300000m)
{
// 200,000-300,000元:1.5%
commissionAmount = 200000m * 0.01m + (traceabilityAmount - 200000m) * 0.015m;
averageRate = (commissionAmount / traceabilityAmount) * 100m;
}
else if (traceabilityAmount < 500000m)
{
// 300,000-500,000元:2%
commissionAmount = 200000m * 0.01m + 100000m * 0.015m + (traceabilityAmount - 300000m) * 0.02m;
averageRate = (commissionAmount / traceabilityAmount) * 100m;
}
else
{
// ≥ 500,000元:2.5%
commissionAmount = 200000m * 0.01m + 100000m * 0.015m + 200000m * 0.02m + (traceabilityAmount - 500000m) * 0.025m;
averageRate = (commissionAmount / traceabilityAmount) * 100m;
}
return (commissionAmount, averageRate);
}
/// <summary>
/// 计算Cell金额提成(分段累进)
/// </summary>
/// <param name="cellAmount">Cell金额</param>
/// <returns>提成金额和平均比例</returns>
private (decimal Amount, decimal? Rate) CalculateCellCommission(decimal cellAmount)
{
if (cellAmount <= 0)
{
return (0m, null);
}
if (cellAmount < 50000m)
{
// < 50,000元:无提成
return (0m, null);
}
decimal commissionAmount = 0m;
decimal? averageRate = null;
if (cellAmount < 400000m)
{
// 50,000-400,000元:1%
commissionAmount = (cellAmount - 50000m) * 0.01m;
averageRate = (commissionAmount / cellAmount) * 100m;
}
else
{
// ≥ 400,000元:1.5%
commissionAmount = 350000m * 0.01m + (cellAmount - 400000m) * 0.015m;
averageRate = (commissionAmount / cellAmount) * 100m;
}
return (commissionAmount, averageRate);
}
/// <summary>
/// 门店明细项(用于JSON序列化)
/// </summary>
private class StoreDetailItem
{
public string StoreId { get; set; }
public string StoreName { get; set; }
public decimal TraceabilityBillingAmount { get; set; }
public decimal TraceabilityRefundAmount { get; set; }
public decimal TraceabilityAmount { get; set; }
public decimal CellBillingAmount { get; set; }
public decimal CellRefundAmount { get; set; }
public decimal CellAmount { get; set; }
}
#region 员工工资确认
/// <summary>
/// 员工确认工资条
/// </summary>
/// <remarks>
/// 员工确认自己的工资条,确认后工资数据不可再修改
///
/// 示例请求:
/// <code>
/// {
/// "id": "工资记录ID",
/// "employeeId": "员工ID",
/// "remark": "确认备注(可选)"
/// }
/// </code>
///
/// 参数说明:
/// - id: 工资记录ID(必填)
/// - employeeId: 员工ID(必填)
/// - remark: 确认备注(可选)
///
/// 注意事项:
/// - 只能确认自己的工资条
/// - 只能确认已锁定的工资条(IsLocked = 1)
/// - 已确认的工资条不能重复确认
/// </remarks>
/// <param name="input">确认参数</param>
/// <returns>操作结果</returns>
/// <response code="200">确认成功</response>
/// <response code="400">参数错误或记录不存在</response>
[HttpPost("confirm")]
public async Task<string> ConfirmSalary([FromBody] SalaryConfirmInput input)
{
try
{
if (string.IsNullOrWhiteSpace(input.Id) || string.IsNullOrWhiteSpace(input.EmployeeId))
throw NCCException.Oh("工资记录ID和员工ID不能为空");
var salary = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(s => s.Id == input.Id && s.EmployeeId == input.EmployeeId).FirstAsync();
if (salary == null) throw NCCException.Oh("工资记录不存在或不属于该员工");
if (salary.EmployeeConfirmStatus == 1) throw NCCException.Oh("该工资条已确认,不能重复确认");
if (salary.IsLocked != 1) throw NCCException.Oh("该工资条尚未锁定,请等待管理员锁定后再确认");
salary.EmployeeConfirmStatus = 1;
salary.EmployeeConfirmTime = DateTime.Now;
salary.EmployeeConfirmRemark = input.Remark;
salary.UpdateTime = DateTime.Now;
await _db.Updateable(salary).ExecuteCommandAsync();
return "确认成功";
}
catch (Exception ex)
{
throw NCCException.Oh($"确认工资条失败: {ex.Message}");
}
}
#endregion
#region 工资锁定/解锁
/// <summary>
/// 批量锁定/解锁工资条
/// </summary>
[HttpPost("lock")]
public async Task<string> LockSalary([FromBody] SalaryLockInput input)
{
try
{
if (input == null || input.Ids == null || !input.Ids.Any())
throw NCCException.Oh("工资记录ID列表不能为空");
var salaries = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(s => input.Ids.Contains(s.Id))
.ToListAsync();
if (!salaries.Any())
throw NCCException.Oh("未找到指定的工资记录");
var lockedCount = 0;
var unlockedCount = 0;
var skippedCount = 0;
foreach (var salary in salaries)
{
if (salary.EmployeeConfirmStatus == 1 && !input.IsLocked)
{
skippedCount++;
continue;
}
salary.IsLocked = input.IsLocked ? 1 : 0;
salary.UpdateTime = DateTime.Now;
if (input.IsLocked) lockedCount++; else unlockedCount++;
}
await _db.Updateable(salaries).ExecuteCommandAsync();
var action = input.IsLocked ? "锁定" : "解锁";
var count = input.IsLocked ? lockedCount : unlockedCount;
var message = $"{action}成功:{count}条";
if (skippedCount > 0)
message += $",跳过{skippedCount}条(已确认的记录不能解锁)";
return message;
}
catch (Exception ex)
{
throw NCCException.Oh($"锁定/解锁工资条失败: {ex.Message}");
}
}
/// <summary>
/// 批量锁定当月所有工资
/// </summary>
/// <param name="input">批量锁定输入参数</param>
/// <returns>锁定结果</returns>
[HttpPost("lock-by-month")]
public async Task<dynamic> LockSalaryByMonth([FromBody] SalaryLockByMonthInput input)
{
try
{
if (input == null)
throw NCCException.Oh("参数不能为空");
if (input.Year <= 0 || input.Month <= 0 || input.Month > 12)
throw NCCException.Oh("年份和月份参数不正确");
var monthStr = $"{input.Year}{input.Month:D2}";
var salaries = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(s => s.StatisticsMonth == monthStr)
.ToListAsync();
if (!salaries.Any())
throw NCCException.Oh($"未找到{input.Year}年{input.Month}月的工资记录");
var lockedCount = 0;
var unlockedCount = 0;
var skippedCount = 0;
var alreadyLockedCount = 0;
foreach (var salary in salaries)
{
if (salary.EmployeeConfirmStatus == 1 && !input.IsLocked)
{
skippedCount++;
continue;
}
if (salary.IsLocked == 1 && input.IsLocked)
{
alreadyLockedCount++;
continue;
}
if (salary.IsLocked == 0 && !input.IsLocked)
{
alreadyLockedCount++;
continue;
}
salary.IsLocked = input.IsLocked ? 1 : 0;
salary.UpdateTime = DateTime.Now;
if (input.IsLocked)
lockedCount++;
else
unlockedCount++;
}
if (lockedCount > 0 || unlockedCount > 0)
{
var salariesToUpdate = salaries.Where(s =>
(input.IsLocked && s.IsLocked == 0) ||
(!input.IsLocked && s.IsLocked == 1 && s.EmployeeConfirmStatus != 1)
).ToList();
if (salariesToUpdate.Any())
{
await _db.Updateable(salariesToUpdate)
.UpdateColumns(s => new { s.IsLocked, s.UpdateTime })
.ExecuteCommandAsync();
}
}
var action = input.IsLocked ? "锁定" : "解锁";
var count = input.IsLocked ? lockedCount : unlockedCount;
var message = $"{action}成功:{count}条";
if (alreadyLockedCount > 0)
message += $",跳过{alreadyLockedCount}条(已是{action}状态)";
if (skippedCount > 0)
message += $",跳过{skippedCount}条(已确认的记录不能解锁)";
return new
{
success = true,
message = message,
total = salaries.Count,
locked = lockedCount,
unlocked = unlockedCount,
skipped = skippedCount,
alreadyLocked = alreadyLockedCount
};
}
catch (Exception ex)
{
_logger.LogError(ex, "批量锁定当月工资失败");
var action = input?.IsLocked == true ? "锁定" : "解锁";
throw NCCException.Oh($"批量{action}当月工资失败: {ex.Message}");
}
}
#endregion
#region 导入工资
/// <summary>
/// 从Excel导入科技部总经理工资数据
/// </summary>
/// <param name="file">Excel文件</param>
/// <returns>导入结果</returns>
[HttpPost("import")]
public async Task<dynamic> ImportSalaryFromExcel(IFormFile file)
{
try
{
if (file == null || file.Length == 0)
throw NCCException.Oh("请选择要上传的Excel文件");
var allowedExtensions = new[] { ".xlsx", ".xls" };
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowedExtensions.Contains(fileExtension))
throw NCCException.Oh("只支持.xlsx和.xls格式的Excel文件");
var recordsToInsert = new List<LqTechGeneralManagerSalaryStatisticsEntity>();
var recordsToUpdate = new List<LqTechGeneralManagerSalaryStatisticsEntity>();
var errorMessages = new List<string>();
var successCount = 0;
var failCount = 0;
var skippedCount = 0;
var tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
try
{
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var dataTable = ExcelImportHelper.ToDataTable(tempFilePath, 0, 0);
if (dataTable.Rows.Count == 0)
throw NCCException.Oh("Excel文件中没有数据行");
Func<string, decimal> ParseDecimal = (str) =>
{
if (string.IsNullOrWhiteSpace(str)) return 0;
var cleaned = str.Trim().Replace(",", "").Replace(",", "").Replace("¥", "").Replace("$", "").Replace("元", "").Replace("%", "").Replace(" ", "");
return decimal.TryParse(cleaned, out decimal result) ? result : 0;
};
Func<string, int> ParseInt = (str) =>
{
if (string.IsNullOrWhiteSpace(str)) return 0;
var cleaned = str.Trim().Replace(",", "").Replace(",", "").Replace(" ", "");
return int.TryParse(cleaned, out int result) ? result : 0;
};
for (int i = 1; i < dataTable.Rows.Count; i++)
{
try
{
var row = dataTable.Rows[i];
Func<int, string> GetColumnValue = (colIndex) => colIndex < row.ItemArray.Length && row[colIndex] != null ? row[colIndex].ToString().Trim() : "";
var firstColumnValue = GetColumnValue(0);
bool isOldFormat = !string.IsNullOrWhiteSpace(firstColumnValue) && (firstColumnValue == "员工姓名" || (!long.TryParse(firstColumnValue, out _) && firstColumnValue.Length > 20));
int employeeNameIndex = isOldFormat ? 0 : 1;
int offset = isOldFormat ? 0 : 1;
var id = isOldFormat ? "" : GetColumnValue(0);
var employeeName = GetColumnValue(employeeNameIndex);
if (string.IsNullOrWhiteSpace(id) && string.IsNullOrWhiteSpace(employeeName))
continue;
if (string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(employeeName))
{
var matchedRecord = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(x => x.EmployeeName == employeeName)
.OrderBy(x => x.CreateTime, OrderByType.Desc)
.FirstAsync();
if (matchedRecord != null) id = matchedRecord.Id;
}
if (string.IsNullOrWhiteSpace(employeeName))
{
errorMessages.Add($"第{i + 1}行:员工姓名不能为空");
failCount++;
continue;
}
LqTechGeneralManagerSalaryStatisticsEntity existing = null;
if (!string.IsNullOrWhiteSpace(id))
{
existing = await _db.Queryable<LqTechGeneralManagerSalaryStatisticsEntity>()
.Where(x => x.Id == id).FirstAsync();
if (existing != null && (existing.IsLocked == 1 || existing.EmployeeConfirmStatus == 1))
{
skippedCount++;
failCount++;
continue;
}
}
var entity = existing ?? new LqTechGeneralManagerSalaryStatisticsEntity
{
Id = string.IsNullOrWhiteSpace(id) ? YitIdHelper.NextId().ToString() : id,
EmployeeConfirmStatus = 0,
IsLocked = 0,
CreateTime = DateTime.Now,
CreateUser = ""
};
// Excel字段映射(科技部总经理工资41列:员工姓名,员工账号,核算岗位,统计月份,是否离职,溯源金额,Cell金额,底薪,溯源金额提成比例,溯源金额提成金额,Cell金额提成比例,Cell金额提成金额,提成合计...)
entity.EmployeeName = employeeName;
entity.EmployeeAccount = GetColumnValue(1 + offset);
entity.Position = GetColumnValue(2 + offset);
entity.StatisticsMonth = GetColumnValue(3 + offset);
entity.IsTerminated = GetColumnValue(4 + offset) == "离职" || GetColumnValue(4 + offset) == "1" ? 1 : 0;
entity.TraceabilityAmount = ParseDecimal(GetColumnValue(5 + offset));
entity.CellAmount = ParseDecimal(GetColumnValue(6 + offset));
entity.BaseSalary = ParseDecimal(GetColumnValue(7 + offset));
entity.TraceabilityCommissionRate = ParseDecimal(GetColumnValue(8 + offset));
entity.TraceabilityCommissionAmount = ParseDecimal(GetColumnValue(9 + offset));
entity.CellCommissionRate = ParseDecimal(GetColumnValue(10 + offset));
entity.CellCommissionAmount = ParseDecimal(GetColumnValue(11 + offset));
entity.TotalCommission = ParseDecimal(GetColumnValue(12 + offset));
entity.WorkingDays = ParseDecimal(GetColumnValue(13 + offset));
entity.LeaveDays = ParseDecimal(GetColumnValue(14 + offset));
entity.CalculatedGrossSalary = ParseDecimal(GetColumnValue(15 + offset));
entity.FinalGrossSalary = ParseDecimal(GetColumnValue(16 + offset));
entity.MonthlyTrainingSubsidy = ParseDecimal(GetColumnValue(17 + offset));
entity.MonthlyTransportSubsidy = ParseDecimal(GetColumnValue(18 + offset));
entity.LastMonthTrainingSubsidy = ParseDecimal(GetColumnValue(19 + offset));
entity.LastMonthTransportSubsidy = ParseDecimal(GetColumnValue(20 + offset));
entity.TotalSubsidy = ParseDecimal(GetColumnValue(21 + offset));
entity.MissingCard = ParseDecimal(GetColumnValue(22 + offset));
entity.LateArrival = ParseDecimal(GetColumnValue(23 + offset));
entity.LeaveDeduction = ParseDecimal(GetColumnValue(24 + offset));
entity.SocialInsuranceDeduction = ParseDecimal(GetColumnValue(25 + offset));
entity.RewardDeduction = ParseDecimal(GetColumnValue(26 + offset));
entity.AccommodationDeduction = ParseDecimal(GetColumnValue(27 + offset));
entity.StudyPeriodDeduction = ParseDecimal(GetColumnValue(28 + offset));
entity.WorkClothesDeduction = ParseDecimal(GetColumnValue(29 + offset));
entity.TotalDeduction = ParseDecimal(GetColumnValue(30 + offset));
entity.Bonus = ParseDecimal(GetColumnValue(31 + offset));
entity.ReturnPhoneDeposit = ParseDecimal(GetColumnValue(32 + offset));
entity.ReturnAccommodationDeposit = ParseDecimal(GetColumnValue(33 + offset));
entity.LastMonthSupplement = ParseDecimal(GetColumnValue(34 + offset));
entity.ActualSalary = ParseDecimal(GetColumnValue(35 + offset));
entity.MonthlyPaymentStatus = GetColumnValue(36 + offset);
entity.PaidAmount = ParseDecimal(GetColumnValue(37 + offset));
entity.PendingAmount = ParseDecimal(GetColumnValue(38 + offset));
entity.MonthlyTotalPayment = ParseDecimal(GetColumnValue(39 + offset));
var isLockedStr = GetColumnValue(40 + offset);
entity.IsLocked = isLockedStr == "已锁定" || isLockedStr == "1" || isLockedStr == "锁定" ? 1 : 0;
if (existing != null)
{
entity.EmployeeId = existing.EmployeeId;
entity.StoreDetail = existing.StoreDetail;
}
else
{
if (!string.IsNullOrWhiteSpace(employeeName))
{
var user = await _db.Queryable<UserEntity>()
.Where(u => u.RealName == employeeName).FirstAsync();
if (user != null) entity.EmployeeId = user.Id;
}
}
entity.UpdateTime = DateTime.Now;
if (existing != null) recordsToUpdate.Add(entity);
else recordsToInsert.Add(entity);
successCount++;
}
catch (Exception ex)
{
errorMessages.Add($"第{i + 1}行数据处理失败: {ex.Message}");
failCount++;
}
}
}
finally
{
if (File.Exists(tempFilePath)) File.Delete(tempFilePath);
}
if (recordsToInsert.Any()) await _db.Insertable(recordsToInsert).ExecuteCommandAsync();
if (recordsToUpdate.Any()) await _db.Updateable(recordsToUpdate).ExecuteCommandAsync();
return new
{
success = true,
message = $"导入完成:成功 {successCount} 条,失败 {failCount} 条,跳过 {skippedCount} 条(已锁定或已确认)",
successCount,
failCount,
skippedCount,
errors = errorMessages
};
}
catch (Exception ex)
{
throw NCCException.Oh($"导入科技部总经理工资数据失败: {ex.Message}");
}
}
#endregion
}
}