LqSalaryService.cs
33.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
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NCC.Common.Enum;
using NCC.Common.Filter;
using NCC.Common.Helper;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqSalary;
using Yitter.IdGenerator;
using NCC.Extend.Entitys.lq_attendance_summary;
using NCC.Extend.Entitys.lq_jinsanjiao_user;
using NCC.Extend.Entitys.lq_kd_jksyj;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_person_times_record;
using NCC.Extend.Entitys.lq_salary_statistics;
using NCC.Extend.Entitys.lq_xh_jksyj;
using NCC.Extend.Entitys.lq_ycsd_jsj;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_md_xdbhsj;
using NCC.Extend.Entitys.lq_salary_extra_calculation;
using NCC.System.Entitys.Permission;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NCC.Extend
{
/// <summary>
/// 薪酬服务
/// </summary>
[ApiDescriptionSettings(Tag = "薪酬服务", Name = "LqSalary", Order = 300)]
[Route("api/Extend/[controller]")]
public class LqSalaryService : IDynamicApiController, ITransient
{
private readonly ISqlSugarClient _db;
/// <summary>
/// 初始化一个<see cref="LqSalaryService"/>类型的新实例
/// </summary>
public LqSalaryService(ISqlSugarClient db)
{
_db = db;
}
/// <summary>
/// 获取健康师工资列表
/// </summary>
/// <param name="input">查询参数</param>
/// <returns>健康师工资分页列表</returns>
[HttpGet("health-coach")]
public async Task<PageResult<HealthCoachSalaryOutput>> GetHealthCoachSalaryList([FromQuery] HealthCoachSalaryInput input)
{
var monthStr = $"{input.Year}{input.Month:D2}";
// 1. 检查当月是否已生成工资数据
var exists = await _db.Queryable<LqSalaryStatisticsEntity>()
.AnyAsync(x => x.StatisticsMonth == monthStr);
// 2. 如果没有数据,则进行计算
if (!exists)
{
await CalculateHealthCoachSalary(input.Year, input.Month);
}
// 3. 查询数据
var query = _db.Queryable<LqSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr);
if (!string.IsNullOrEmpty(input.StoreId))
{
query = query.Where(x => x.StoreId == input.StoreId);
}
if (!string.IsNullOrEmpty(input.Keyword))
{
query = query.Where(x => x.EmployeeName.Contains(input.Keyword) || x.EmployeeId.Contains(input.Keyword));
}
var list = await query.Select(x => new HealthCoachSalaryOutput
{
Id = x.Id,
StoreName = x.StoreName,
EmployeeName = x.EmployeeName,
Position = x.Position,
GoldTriangleTeam = x.GoldTriangleTeam,
TotalPerformance = x.TotalPerformance,
BasePerformance = x.BasePerformance,
CooperationPerformance = x.CooperationPerformance,
RewardPerformance = x.RewardPerformance,
Consumption = x.Consumption,
ProjectCount = x.ProjectCount,
CustomerCount = x.CustomerCount,
WorkingDays = x.WorkingDays,
HealthCoachBaseSalary = x.HealthCoachBaseSalary,
TotalCommission = x.TotalCommission,
HandworkFee = x.HandworkFee,
TotalSubsidy = x.TotalSubsidy,
TotalDeduction = x.TotalDeduction,
ActualSalary = x.ActualSalary,
IsLocked = x.IsLocked,
UpdateTime = x.UpdateTime,
IsNewStore = x.IsNewStore,
NewStoreProtectionStage = x.NewStoreProtectionStage,
StoreType = x.StoreType,
StoreCategory = x.StoreCategory,
ActualBasePerformance = x.ActualBasePerformance,
ActualCooperationPerformance = x.ActualCooperationPerformance,
NewCustomerCommission = x.NewCustomerPerformanceCommission,
UpgradeCommission = x.UpgradePerformanceCommission
})
.ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<HealthCoachSalaryOutput>.SqlSugarPageResult(list);
}
/// <summary>
/// 计算健康师工资
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns></returns>
[HttpPost("calculate/health-coach")]
public async Task CalculateHealthCoachSalary(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 业绩数据 (lq_kd_jksyj)
var performanceList = await _db.Queryable<LqKdJksyjEntity>()
.Where(x => x.Yjsj >= startDate && x.Yjsj <= endDate.AddDays(1) && x.IsEffective == 1)
.ToListAsync();
// 1.1.1 获取关联的开单记录(用于获取 sfskdd)
var billingIds = performanceList.Select(x => x.Glkdbh).Distinct().ToList();
var billingDict = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => billingIds.Contains(x.Id) && x.Id != null)
.ToDictionaryAsync(x => x.Id, x => x.Sfskdd);
// 1.1.2 组合数据
var performanceData = performanceList.Select(p => new
{
Jks = p.Jkszh, // 使用 Jkszh (账号/ID) 而不是 Jks (姓名)
p.Jksxm,
p.StoreId,
p.Jksyj,
p.ItemCategory,
p.PerformanceType, // 新增业绩类型字段
Sfskdd = billingDict.ContainsKey(p.Glkdbh) ? billingDict[p.Glkdbh] : null
}).ToList();
// 1.2 消耗数据 (lq_xh_jksyj)
var consumptionList = await _db.Queryable<LqXhJksyjEntity>()
.Where(x => x.Yjsj >= startDate && x.Yjsj <= endDate.AddDays(1) && x.IsEffective == 1)
.ToListAsync();
// 1.3 考勤数据 (lq_attendance_summary)
var attendanceList = await _db.Queryable<LqAttendanceSummaryEntity>()
.Where(x => x.Year == year && x.Month == month && x.IsEffective == 1)
.ToListAsync();
// 1.4 战队成员及顾问信息 (lq_jinsanjiao_user + lq_ycsd_jsj)
var teamUserList = await _db.Queryable<LqJinsanjiaoUserEntity>()
.Where(x => x.Month == monthStr && x.DeleteMark == 0)
.ToListAsync();
// 1.4.1 获取战队信息
var teamIds = teamUserList.Select(x => x.JsjId).Distinct().ToList();
var teamList = await _db.Queryable<LqYcsdJsjEntity>()
.Where(x => teamIds.Contains(x.Id))
.ToListAsync();
var teamDict = teamList.Where(x => !string.IsNullOrEmpty(x.Id)).ToDictionary(x => x.Id, x => x.Jsj);
// 1.4.2 组合数据
var teamMembers = teamUserList.Select(user => new
{
user.UserId,
user.IsLeader,
TeamId = user.JsjId,
TeamName = teamDict.ContainsKey(user.JsjId) ? teamDict[user.JsjId] : (string)null
}).ToList();
// 1.5 到店人头 (lq_person_times_record)
// 统计每个健康师的去重会员数
var headcountList = await _db.Queryable<LqPersonTimesRecordEntity>()
.Where(x => x.WorkMonth == monthStr && x.IsEffective == 1)
.GroupBy(x => x.PersonId)
.Select(x => new { PersonId = x.PersonId, Count = SqlFunc.AggregateDistinctCount(x.MemberId) })
.ToListAsync();
// 1.6 门店生命线 (lq_md_target)
var storeTargets = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.Month == monthStr)
.ToListAsync();
// 1.6.1 门店总业绩计算 (开单实付 - 退款金额)
// 开单实付
var storeBillingList = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Kdrq >= startDate && x.Kdrq <= endDate.AddDays(1) && x.IsEffective == 1)
.Select(x => new { x.Djmd, x.Sfyj })
.ToListAsync();
var storeBillingDict = storeBillingList
.Where(x => !string.IsNullOrEmpty(x.Djmd))
.GroupBy(x => x.Djmd)
.ToDictionary(g => g.Key, g => g.Sum(x => x.Sfyj));
// 退款金额
var storeRefundList = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Tksj >= startDate && x.Tksj <= endDate.AddDays(1) && x.IsEffective == 1)
.Select(x => new { x.Mdbh, x.Tkje })
.ToListAsync();
var storeRefundDict = storeRefundList
.Where(x => !string.IsNullOrEmpty(x.Mdbh))
.GroupBy(x => x.Mdbh)
.ToDictionary(g => g.Key, g => g.Sum(x => x.Tkje ?? 0));
// 1.7 门店信息 (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.7.1 门店新店保护信息 (lq_md_xdbhsj)
var newStoreProtectionList = await _db.Queryable<LqMdXdbhsjEntity>()
.Where(x => x.Sfqy == 1)
.ToListAsync();
// 构造新店保护查找字典: StoreId -> List<ProtectionInfo>
// 因为一个门店可能有多个阶段配置,虽然通常是一个时间段,但为了严谨取符合当前月份的配置
// 逻辑: 统计月份 (startDate ~ endDate) 是否在 bhkssj ~ bhjssj 范围内
// 只要统计月份与保护期有交集,就算保护期。或者严格一点,统计月份的第一天在保护期内。
// 这里取: 统计月份的第一天 (startDate) 在保护期内
var newStoreProtectionDict = newStoreProtectionList
.Where(x => x.Bhkssj <= startDate && x.Bhjssj >= startDate)
.GroupBy(x => x.Mdid)
.ToDictionary(g => g.Key, g => g.First()); // 取第一个匹配的配置
// 1.8 健康师工资额外计算数据 (lq_salary_extra_calculation)
var extraCalculationList = await _db.Queryable<LqSalaryExtraCalculationEntity>()
.Where(x => x.Year == year && x.Month == month)
.ToListAsync();
var extraCalculationDict = extraCalculationList
.Where(x => !string.IsNullOrEmpty(x.EmployeeId))
.ToDictionary(x => x.EmployeeId, x => x);
// 2. 聚合每个健康师的数据对象
var employeeStats = new Dictionary<string, LqSalaryStatisticsEntity>();
// 获取所有涉及的健康师ID
var allEmployeeIds = performanceData.Select(x => x.Jks)
.Union(consumptionList.Select(x => x.Jks))
.Union(attendanceList.Select(x => x.UserId))
.Union(teamMembers.Select(x => x.UserId))
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
// 1.8 批量获取员工信息 (BASE_USER + BASE_POSITION)
// 使用 allEmployeeIds 作为驱动,查询 BASE_USER
var userList = await _db.Queryable<UserEntity>()
.Where(x => allEmployeeIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName, x.PositionId, x.Mdid })
.ToListAsync();
var userDict = userList.ToDictionary(x => x.Id, x => x);
var positionIds = userList.Select(x => x.PositionId).Distinct().ToList();
var positionList = await _db.Queryable<PositionEntity>().Where(x => positionIds.Contains(x.Id)).ToListAsync();
var positionLookup = positionList.Where(x => !string.IsNullOrEmpty(x.Id)).ToDictionary(x => x.Id, x => x.FullName);
foreach (var empId in allEmployeeIds)
{
var salary = new LqSalaryStatisticsEntity
{
Id = YitIdHelper.NextId().ToString(),
EmployeeId = empId,
StatisticsMonth = monthStr,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now,
IsLocked = 0
};
// 填充基础信息 (优先从 BASE_USER 获取)
string userMdid = null;
if (userDict.ContainsKey(empId))
{
var user = userDict[empId];
salary.EmployeeName = user.RealName;
userMdid = user.Mdid;
// 岗位
if (user.PositionId != null && positionLookup.ContainsKey(user.PositionId))
{
salary.Position = positionLookup[user.PositionId];
}
}
// 如果 BASE_USER 没名字,尝试从业务表获取
if (string.IsNullOrEmpty(salary.EmployeeName))
{
var perfRecord = performanceData.FirstOrDefault(x => x.Jks == empId);
var consRecord = consumptionList.FirstOrDefault(x => x.Jks == empId);
if (perfRecord != null) salary.EmployeeName = perfRecord.Jksxm;
else if (consRecord != null) salary.EmployeeName = consRecord.Jksxm;
}
// 填充门店ID (从业务数据获取,因为 User 表的 OrganizeId 未必是门店)
var perfStore = performanceData.FirstOrDefault(x => x.Jks == empId && !string.IsNullOrEmpty(x.StoreId));
var consStore = consumptionList.FirstOrDefault(x => x.Jks == empId && !string.IsNullOrEmpty(x.StoreId));
if (perfStore != null) salary.StoreId = perfStore.StoreId;
else if (consStore != null) salary.StoreId = consStore.StoreId;
// 如果业务数据没门店,尝试使用 User.Mdid
if (string.IsNullOrEmpty(salary.StoreId) && !string.IsNullOrEmpty(userMdid))
{
if (storeDict.ContainsKey(userMdid))
{
salary.StoreId = userMdid;
}
}
// 填充门店名称及分类信息
if (!string.IsNullOrEmpty(salary.StoreId) && storeDict.ContainsKey(salary.StoreId))
{
var store = storeDict[salary.StoreId];
salary.StoreName = store.Dm;
salary.StoreType = store.StoreType;
salary.StoreCategory = store.StoreCategory;
}
// 填充新店保护信息
if (!string.IsNullOrEmpty(salary.StoreId) && newStoreProtectionDict.ContainsKey(salary.StoreId))
{
var protection = newStoreProtectionDict[salary.StoreId];
salary.IsNewStore = "是";
salary.NewStoreProtectionStage = protection.Stage;
}
else
{
salary.IsNewStore = "否";
salary.NewStoreProtectionStage = 0;
}
// 2.1 计算个人业绩
var myPerf = performanceData.Where(x => x.Jks == empId).ToList();
salary.BasePerformance = myPerf.Where(x => (x.PerformanceType ?? "").Trim() == "基础业绩").Sum(x => decimal.Parse(x.Jksyj ?? "0"));
salary.CooperationPerformance = myPerf.Where(x => (x.PerformanceType ?? "").Trim() == "合作业绩").Sum(x => decimal.Parse(x.Jksyj ?? "0"));
salary.TotalPerformance = myPerf.Sum(x => decimal.Parse(x.Jksyj ?? "0"));
// 新客与升单业绩
salary.NewCustomerPerformance = myPerf.Where(x => x.Sfskdd == "是").Sum(x => decimal.Parse(x.Jksyj ?? "0"));
salary.UpgradePerformance = myPerf.Where(x => x.Sfskdd == "否").Sum(x => decimal.Parse(x.Jksyj ?? "0"));
// 2.1.1 填充额外计算数据
if (extraCalculationDict.ContainsKey(empId))
{
var extraData = extraCalculationDict[empId];
salary.BaseRewardPerformance = extraData.BaseRewardPerformance;
salary.CooperationRewardPerformance = extraData.CooperationRewardPerformance;
salary.OtherPerformanceAdd = extraData.OtherPerformanceAdd;
salary.OtherPerformanceSubtract = extraData.OtherPerformanceSubtract;
salary.UpgradeCustomerCount = extraData.UpgradeCustomerCount;
salary.NewCustomerConversionRate = extraData.NewCustomerConversionRate;
}
// 2.1.2 计算实际基础业绩和实际合作业绩
// 定义新店相关变量,供后续多处使用
bool isNewStore = salary.IsNewStore == "是";
int newStoreStage = salary.NewStoreProtectionStage;
// 实际基础业绩 = 基础业绩 - 基础奖励业绩 + 其他业绩加 - 其他业绩减
decimal actualBasePerformance = salary.BasePerformance
- salary.BaseRewardPerformance
+ salary.OtherPerformanceAdd
- salary.OtherPerformanceSubtract;
// 新店额外调整:根据阶段扣除新客业绩或升单业绩
if (isNewStore)
{
if (newStoreStage == 1)
{
// 第一阶段:扣除新客业绩
actualBasePerformance -= salary.NewCustomerPerformance;
}
else if (newStoreStage == 2)
{
// 第二阶段:扣除升单业绩
actualBasePerformance -= salary.UpgradePerformance;
}
}
salary.ActualBasePerformance = actualBasePerformance;
// 实际合作业绩 = 合作业绩 - 合作奖励业绩
salary.ActualCooperationPerformance = salary.CooperationPerformance - salary.CooperationRewardPerformance;
// 2.2 计算消耗和项目数
var myCons = consumptionList.Where(x => x.Jks == empId).ToList();
salary.Consumption = myCons.Sum(x => x.Jksyj ?? 0);
salary.ProjectCount = myCons.Sum(x => x.KdpxNumber ?? 0);
salary.HandworkFee = myCons.Sum(x => x.LaborCost ?? 0); // 使用 F_LaborCost
// 2.3 考勤数据
var myAtt = attendanceList.FirstOrDefault(x => x.UserId == empId);
salary.WorkingDays = myAtt?.WorkDays ?? 0;
salary.LeaveDays = myAtt?.LeaveDays ?? 0;
// 2.4 到店人头
var myHeadcount = headcountList.FirstOrDefault(x => x.PersonId == empId);
salary.CustomerCount = myHeadcount?.Count ?? 0;
// 2.5 战队信息 (初始)
var myTeam = teamMembers.FirstOrDefault(x => x.UserId == empId);
// 初始判断岗位:如果是战队队长(IsLeader=1)则是顾问,否则是健康师
// 注意:这里先根据战队设置判断,后续考勤不足21天会降级
if (myTeam != null && myTeam.IsLeader == 1)
{
salary.Position = "顾问";
}
else if (string.IsNullOrEmpty(salary.Position)) // 如果BASE_USER没岗位,且不是队长,默认为健康师
{
salary.Position = "健康师";
}
if (myTeam != null)
{
salary.GoldTriangleId = myTeam.TeamId;
salary.GoldTriangleTeam = myTeam.TeamName ?? "个人";
}
else
{
salary.GoldTriangleTeam = "个人";
}
// 2.6 门店总业绩
if (!string.IsNullOrEmpty(salary.StoreId))
{
decimal billing = storeBillingDict.ContainsKey(salary.StoreId) ? storeBillingDict[salary.StoreId] : 0;
decimal refund = storeRefundDict.ContainsKey(salary.StoreId) ? storeRefundDict[salary.StoreId] : 0;
salary.StoreTotalPerformance = billing - refund;
}
employeeStats[empId] = salary;
}
// 3. 处理战队逻辑 (考勤规则)
// 规则:若出勤天数 < 21天,则该健康师不计入战队,按单人计算。
// 按战队分组
var teamGroups = employeeStats.Values
.Where(x => !string.IsNullOrEmpty(x.GoldTriangleId))
.GroupBy(x => x.GoldTriangleId)
.ToList();
foreach (var group in teamGroups)
{
var validMembers = new List<LqSalaryStatisticsEntity>();
var invalidMembers = new List<LqSalaryStatisticsEntity>();
foreach (var member in group)
{
if (member.WorkingDays >= 21)
{
validMembers.Add(member);
}
else
{
invalidMembers.Add(member);
}
}
// 对于无效成员,移除战队标识,视为单人,并重置岗位为健康师
foreach (var member in invalidMembers)
{
member.GoldTriangleId = null;
member.GoldTriangleTeam = "个人";
member.Position = "健康师"; // 降级为健康师
}
// 计算有效战队的总业绩
var teamTotalPerformance = validMembers.Sum(x => x.TotalPerformance);
// 更新有效成员的战队业绩
foreach (var member in validMembers)
{
member.TeamPerformance = teamTotalPerformance;
}
}
// 4. 计算薪资 (底薪 & 提成)
foreach (var salary in employeeStats.Values)
{
// 定义新店相关变量,供底薪和提成计算使用
bool isNewStore = salary.IsNewStore == "是";
int newStoreStage = salary.NewStoreProtectionStage;
// 4.1 底薪计算
salary.HealthCoachBaseSalary = CalculateBaseSalary(salary.Consumption, salary.ProjectCount, isNewStore);
// 4.2 提成计算
// 单人业绩 <= 6000 无提成
if (salary.TotalPerformance <= 6000)
{
salary.TotalCommission = 0;
salary.BasePerformanceCommission = 0;
salary.CooperationPerformanceCommission = 0;
salary.ConsultantCommission = 0;
}
else
{
// 确定提成点
decimal commissionPoint = 0;
if (!string.IsNullOrEmpty(salary.GoldTriangleId))
{
// 是战队成员
// 获取战队人数 (注意:这里应该是有效战队人数)
var teamMemberCount = employeeStats.Values.Count(x => x.GoldTriangleId == salary.GoldTriangleId);
// 注意:提成点按原始基础业绩计算,不是实际基础业绩
commissionPoint = GetTeamCommissionPoint(teamMemberCount, salary.TeamPerformance);
}
else
{
// 单人 (或被剔除出战队)
// 注意:提成点按原始总业绩计算
commissionPoint = GetTeamCommissionPoint(1, salary.TotalPerformance);
}
salary.CommissionPoint = commissionPoint;
// 计算基础/合作提成(使用实际业绩)
salary.BasePerformanceCommission = salary.ActualBasePerformance * 0.95m * commissionPoint;
salary.CooperationPerformanceCommission = salary.ActualCooperationPerformance * 0.95m * 0.65m * commissionPoint;
// 计算新客转化率提成和升单人头提成(根据新店阶段)
// isNewStore 和 newStoreStage 已在上面定义
if (isNewStore)
{
if (newStoreStage == 1)
{
// 第一阶段:计算新客转化率提成
salary.NewCustomerPerformanceCommission = CalculateNewCustomerConversionCommission(
salary.NewCustomerPerformance,
salary.NewCustomerConversionRate);
}
else if (newStoreStage == 2)
{
// 第二阶段:计算升单人头提成
salary.UpgradePerformanceCommission = CalculateUpgradeCustomerCommission(
salary.UpgradePerformance,
salary.UpgradeCustomerCount);
}
// 第三阶段:不计算新客/升单提成
}
// 计算顾问提成
// 检查是否是顾问
// 注意:这里需要重新判断是否是顾问,因为可能被降级了
if (salary.Position == "顾问" && !string.IsNullOrEmpty(salary.GoldTriangleId))
{
salary.ConsultantCommission = CalculateConsultantCommission(
salary.TeamPerformance,
employeeStats.Values.Where(x => x.GoldTriangleId == salary.GoldTriangleId).ToList(),
isNewStore);
}
salary.TotalCommission = salary.BasePerformanceCommission
+ salary.CooperationPerformanceCommission
+ salary.ConsultantCommission
+ salary.NewCustomerPerformanceCommission
+ salary.UpgradePerformanceCommission;
}
// 计算占比
if (salary.TeamPerformance > 0)
{
salary.Percentage = salary.TotalPerformance / salary.TeamPerformance;
}
else if (salary.TotalPerformance > 0 && string.IsNullOrEmpty(salary.GoldTriangleId))
{
salary.Percentage = 1; // 单人占比100%
}
// 4.3 最终工资
salary.ActualSalary = salary.HealthCoachBaseSalary + salary.TotalCommission + salary.HandworkFee + salary.TotalSubsidy - salary.TotalDeduction;
}
// 5. 保存数据
if (employeeStats.Any())
{
// 先删除当月旧数据 (防止重复)
await _db.Deleteable<LqSalaryStatisticsEntity>().Where(x => x.StatisticsMonth == monthStr).ExecuteCommandAsync();
await _db.Insertable(employeeStats.Values.ToList()).ExecuteCommandAsync();
}
}
/// <summary>
/// 计算底薪
/// </summary>
private decimal CalculateBaseSalary(decimal consumption, decimal projectCount, bool isNewStore)
{
// 0星:<1w 或 <96个 -> 1800
// 1星:>=1w 且 >=96个 -> 2000
// 2星:>=2w 且 >=126个 -> 2200
// 3星:>=4w 且 >=156个 -> 2400
// 特殊规则:若消耗或项目数中仅一项未达标(0星),底薪按1星(2000元)计算
// 新店规则:新店底薪最低为1星(2000元),不满足1星按1星算
int starCons = 0;
if (consumption >= 40000) starCons = 3;
else if (consumption >= 20000) starCons = 2;
else if (consumption >= 10000) starCons = 1;
int starProj = 0;
if (projectCount >= 156) starProj = 3;
else if (projectCount >= 126) starProj = 2;
else if (projectCount >= 96) starProj = 1;
int finalStar = Math.Min(starCons, starProj);
// 特殊规则处理: 仅一项未达标(0星) -> 1星
if (finalStar == 0 && (starCons > 0 || starProj > 0))
{
finalStar = 1;
}
decimal baseSalary = finalStar switch
{
3 => 2400,
2 => 2200,
1 => 2000,
_ => 1800
};
// 新店保底1星(2000元)
if (isNewStore && baseSalary < 2000)
{
baseSalary = 2000;
}
return baseSalary;
}
/// <summary>
/// 获取战队提成点
/// </summary>
private decimal GetTeamCommissionPoint(int memberCount, decimal teamPerformance)
{
if (memberCount >= 3)
{
if (teamPerformance >= 150000) return 0.07m;
if (teamPerformance >= 120000) return 0.06m;
if (teamPerformance >= 90000) return 0.05m;
if (teamPerformance >= 60000) return 0.04m;
if (teamPerformance >= 30000) return 0.03m;
}
else if (memberCount == 2)
{
if (teamPerformance >= 80000) return 0.06m;
if (teamPerformance >= 60000) return 0.05m;
if (teamPerformance >= 40000) return 0.04m;
if (teamPerformance >= 20000) return 0.03m;
}
else // 1人
{
if (teamPerformance >= 60000) return 0.06m;
if (teamPerformance >= 40000) return 0.05m;
if (teamPerformance >= 20000) return 0.04m;
if (teamPerformance >= 10000) return 0.03m;
}
return 0;
}
/// <summary>
/// 计算顾问提成
/// </summary>
private decimal CalculateConsultantCommission(decimal teamPerformance, List<LqSalaryStatisticsEntity> teamMembers, bool isNewStore)
{
// 顾问提成规则:
// 高级顾问:战队总业绩 ≥ 6万元 且 组员业绩达到40%以上 且 消耗达到6万元 → 团队总业绩0.8%
// 普通顾问:战队总业绩 ≥ 4万元 且 组员业绩达到30%以上 且 消耗达到4万元 → 团队总业绩0.3%
// 注意:
// 1. "组员业绩"指除顾问外的其他成员业绩总和
// 2. 只统计有效战队成员(考勤≥21天,未被剔除的成员)
// 3. "达到X%以上"指:组员业绩总和 ≥ 团队总业绩 × X%
// 4. 新店顾问不考核消耗
var teamConsumption = teamMembers.Sum(x => x.Consumption);
// 计算组员(非顾问)业绩总和
// teamMembers 已经是过滤后的有效成员列表(GoldTriangleId 相同且未被剔除)
var memberPerformance = teamMembers.Where(x => x.Position != "顾问").Sum(x => x.TotalPerformance);
// 高级顾问:业绩≥6万 且 组员业绩≥40% 且 (新店 或 消耗≥6万)
if (teamPerformance >= 60000 && memberPerformance >= teamPerformance * 0.4m)
{
if (isNewStore || teamConsumption >= 60000)
{
return teamPerformance * 0.008m;
}
}
// 普通顾问:业绩≥4万 且 组员业绩≥30% 且 (新店 或 消耗≥4万)
if (teamPerformance >= 40000 && memberPerformance >= teamPerformance * 0.3m)
{
if (isNewStore || teamConsumption >= 40000)
{
return teamPerformance * 0.003m;
}
}
return 0;
}
/// <summary>
/// 计算新客转化率提成
/// </summary>
private decimal CalculateNewCustomerConversionCommission(decimal newCustomerPerformance, decimal conversionRate)
{
decimal commissionRate = 0;
if (conversionRate >= 0.5m) commissionRate = 0.20m;
else if (conversionRate >= 0.45m) commissionRate = 0.15m;
else if (conversionRate >= 0.35m) commissionRate = 0.10m;
else if (conversionRate >= 0) commissionRate = 0.06m;
return newCustomerPerformance * commissionRate;
}
/// <summary>
/// 计算升单人头提成
/// </summary>
private decimal CalculateUpgradeCustomerCommission(decimal upgradePerformance, decimal upgradeCustomerCount)
{
decimal commissionRate = 0;
if (upgradeCustomerCount >= 10) commissionRate = 0.20m;
else if (upgradeCustomerCount >= 4) commissionRate = 0.10m;
// 0-4个: 0%
return upgradePerformance * commissionRate;
}
}
}