LqBusinessUnitManagerSalaryService.cs
29.8 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
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.LqBusinessUnitManagerSalary;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_attendance_summary;
using NCC.Extend.Entitys.lq_cooperation_cost;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_laundry_flow;
using NCC.Extend.Entitys.lq_md_general_manager_lifeline;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_business_unit_manager_salary_statistics;
using NCC.Extend.Entitys.lq_store_expense;
using NCC.System.Entitys.Permission;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
namespace NCC.Extend
{
/// <summary>
/// 事业部总经理/经理薪酬服务
/// </summary>
[ApiDescriptionSettings(Tag = "事业部总经理/经理薪酬服务", Name = "LqBusinessUnitManagerSalary", Order = 304)]
[Route("api/Extend/[controller]")]
public class LqBusinessUnitManagerSalaryService : IDynamicApiController, ITransient
{
private readonly ISqlSugarClient _db;
/// <summary>
/// 初始化一个<see cref="LqBusinessUnitManagerSalaryService"/>类型的新实例
/// </summary>
public LqBusinessUnitManagerSalaryService(ISqlSugarClient db)
{
_db = db;
}
/// <summary>
/// 获取事业部总经理/经理工资列表
/// </summary>
/// <param name="input">查询参数</param>
/// <returns>事业部总经理/经理工资分页列表</returns>
[HttpGet("business-unit-manager")]
public async Task<dynamic> GetBusinessUnitManagerSalaryList([FromQuery] BusinessUnitManagerSalaryInput input)
{
var monthStr = $"{input.Year}{input.Month:D2}";
// 1. 检查当月是否已生成工资数据
var exists = await _db.Queryable<LqBusinessUnitManagerSalaryStatisticsEntity>()
.AnyAsync(x => x.StatisticsMonth == monthStr);
// 2. 如果没有数据,则进行计算
if (!exists)
{
await CalculateBusinessUnitManagerSalary(input.Year, input.Month);
}
// 3. 查询数据
var query = _db.Queryable<LqBusinessUnitManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr);
if (input.ManagerType.HasValue)
{
query = query.Where(x => x.ManagerType == input.ManagerType.Value);
}
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 BusinessUnitManagerSalaryOutput
{
Id = x.Id,
StatisticsMonth = x.StatisticsMonth,
Position = x.Position,
EmployeeName = x.EmployeeName,
EmployeeId = x.EmployeeId,
EmployeeAccount = x.EmployeeAccount,
ManagerType = x.ManagerType,
IsTerminated = x.IsTerminated,
StorePerformanceDetail = x.StorePerformanceDetail,
SalesPerformance = x.SalesPerformance,
ProductMaterial = x.ProductMaterial,
CooperationCost = x.CooperationCost,
StoreExpense = x.StoreExpense,
LaundryCost = x.LaundryCost,
GrossProfit = x.GrossProfit,
BaseSalary = x.BaseSalary,
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<BusinessUnitManagerSalaryOutput>.SqlSugarPageResult(list);
}
/// <summary>
/// 计算事业部总经理/经理工资
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns></returns>
[HttpPost("calculate/business-unit-manager")]
public async Task CalculateBusinessUnitManagerSalary(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_md_general_manager_lifeline表)
var lifelineList = await _db.Queryable<LqMdGeneralManagerLifelineEntity>()
.Where(x => x.Month == monthStr)
.ToListAsync();
if (!lifelineList.Any())
{
// 如果没有归属信息,直接返回
return;
}
// 1.2 获取所有不重复的总经理/经理ID(确保所有总经理/经理都被计算)
var allManagerIds = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId))
.Select(x => x.GeneralManagerId)
.Distinct()
.ToList();
// 1.3 按总经理/经理ID分组,获取每个总经理/经理管理的门店
var managerStoreDict = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId) && !string.IsNullOrEmpty(x.StoreId))
.GroupBy(x => x.GeneralManagerId)
.ToDictionary(g => g.Key, g => g.Select(x => x.StoreId).Distinct().ToList());
// 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.5 门店生命线信息 (lq_md_target)
var targetList = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.Month == monthStr)
.ToListAsync();
var storeLifelineDict = targetList
.Where(x => !string.IsNullOrEmpty(x.StoreId))
.ToDictionary(x => x.StoreId, x => x.StoreLifeline);
// 1.6 门店销售业绩计算 (开单实付 - 退卡金额)
// 开单实付(从lq_kd_kdjlb表统计sfyj字段)
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));
// 退卡金额(从lq_hytk_hytk表统计,使用F_ActualRefundAmount,如果没有则使用tkje)
var storeRefundList = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Tksj >= startDate && x.Tksj <= endDate.AddDays(1) && x.IsEffective == 1)
.Select(x => new { x.Md, x.ActualRefundAmount, x.Tkje })
.ToListAsync();
var storeRefundDict = storeRefundList
.Where(x => !string.IsNullOrEmpty(x.Md))
.GroupBy(x => x.Md)
.ToDictionary(g => g.Key, g => g.Sum(x => x.ActualRefundAmount ?? x.Tkje ?? 0));
// 1.7 产品物料统计(仓库领用金额,注意11月特殊规则)
var queryMonth = monthStr;
if (month == 11)
{
// 11月工资算10月数据
queryMonth = $"{year}10";
}
var productMaterialSql = $@"
SELECT
F_StoreId as StoreId,
COALESCE(SUM(F_TotalAmount), 0) as MaterialAmount
FROM lq_inventory_usage
WHERE F_IsEffective = 1
AND DATE_FORMAT(F_UsageTime, '%Y%m') = @queryMonth
GROUP BY F_StoreId";
var productMaterialData = await _db.Ado.SqlQueryAsync<dynamic>(productMaterialSql, new { queryMonth });
var productMaterialDict = productMaterialData
.Where(x => x.StoreId != null)
.ToDictionary(x => x.StoreId.ToString(), x => Convert.ToDecimal(x.MaterialAmount ?? 0));
// 1.8 合作项目成本统计
// Month字段格式为"11"(月份数字),不是"202511"(YYYYMM格式)
var cooperationCostMonth = $"{month:D2}"; // 格式化为"11"
var cooperationCostList = await _db.Queryable<LqCooperationCostEntity>()
.Where(x => x.Year == year && x.Month == cooperationCostMonth && x.IsEffective == StatusEnum.有效.GetHashCode())
.Select(x => new { x.StoreId, x.TotalAmount })
.ToListAsync();
var cooperationCostDict = cooperationCostList
.Where(x => !string.IsNullOrEmpty(x.StoreId))
.GroupBy(x => x.StoreId)
.ToDictionary(g => g.Key, g => g.Sum(x => x.TotalAmount));
// 1.9 店内支出统计
var storeExpenseSql = $@"
SELECT
F_StoreId as StoreId,
COALESCE(SUM(F_Amount), 0) as ExpenseAmount
FROM lq_store_expense
WHERE F_IsEffective = 1
AND DATE_FORMAT(F_ExpenseDate, '%Y%m') = @monthStr
GROUP BY F_StoreId";
var storeExpenseData = await _db.Ado.SqlQueryAsync<dynamic>(storeExpenseSql, new { monthStr });
var storeExpenseDict = storeExpenseData
.Where(x => x.StoreId != null)
.ToDictionary(x => x.StoreId.ToString(), x => Convert.ToDecimal(x.ExpenseAmount ?? 0));
// 1.10 洗毛巾费用统计(只统计送出的记录,F_FlowType = 0)
// 优先使用送出时间(F_SendTime),如果为空则使用创建时间(F_CreateTime)
var laundryCostSql = $@"
SELECT
F_StoreId as StoreId,
COALESCE(SUM(F_TotalPrice), 0) as LaundryAmount
FROM lq_laundry_flow
WHERE F_IsEffective = 1
AND F_FlowType = 0
AND DATE_FORMAT(COALESCE(F_SendTime, F_CreateTime), '%Y%m') = @monthStr
GROUP BY F_StoreId";
var laundryCostData = await _db.Ado.SqlQueryAsync<dynamic>(laundryCostSql, new { monthStr });
var laundryCostDict = laundryCostData
.Where(x => x.StoreId != null)
.ToDictionary(x => x.StoreId.ToString(), x => Convert.ToDecimal(x.LaundryAmount ?? 0));
// 1.11 考勤数据 (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.12 获取员工信息 (BASE_USER)
var userList = await _db.Queryable<UserEntity>()
.Where(x => allManagerIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName, x.Account, x.IsOnJob })
.ToListAsync();
var userDict = userList.ToDictionary(x => x.Id, x => x);
// 2. 按总经理/经理聚合数据
var managerStats = new Dictionary<string, LqBusinessUnitManagerSalaryStatisticsEntity>();
foreach (var managerId in allManagerIds)
{
if (string.IsNullOrEmpty(managerId))
{
continue;
}
// 获取该总经理/经理的信息
var managerLifeline = lifelineList.FirstOrDefault(x => x.GeneralManagerId == managerId);
if (managerLifeline == null)
{
continue;
}
// 2.1 创建工资统计对象
var salary = new LqBusinessUnitManagerSalaryStatisticsEntity
{
Id = YitIdHelper.NextId().ToString(),
StatisticsMonth = monthStr,
EmployeeId = managerId,
ManagerType = managerLifeline.ManagerType,
Position = managerLifeline.ManagerType == 1 ? "总经理" : "经理",
IsTerminated = 0,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now,
IsLocked = 0
};
// 2.2 填充员工信息
if (userDict.ContainsKey(managerId))
{
var user = userDict[managerId];
salary.EmployeeName = user.RealName ?? "";
salary.EmployeeAccount = user.Account ?? "";
salary.IsTerminated = user.IsOnJob == 0 ? 1 : 0;
}
// 2.3 考勤数据
var attendance = attendanceDict.ContainsKey(managerId) ? attendanceDict[managerId] : null;
salary.WorkingDays = attendance?.WorkDays ?? 0;
salary.LeaveDays = attendance?.LeaveDays ?? 0;
// 2.4 计算底薪(固定4000元)
salary.BaseSalary = 4000m;
// 2.5 遍历该总经理/经理管理的每个门店,计算提成
var storePerformanceDetails = new List<StorePerformanceDetail>();
decimal totalCommission = 0m;
decimal totalSalesPerformance = 0m;
decimal totalProductMaterial = 0m;
decimal totalCooperationCost = 0m;
decimal totalStoreExpense = 0m;
decimal totalLaundryCost = 0m;
decimal totalGrossProfit = 0m;
// 获取该总经理/经理管理的门店列表(如果没有管理的门店,则为空列表)
var managedStores = managerStoreDict.ContainsKey(managerId) ? managerStoreDict[managerId] : new List<string>();
foreach (var storeId in managedStores)
{
if (string.IsNullOrEmpty(storeId))
{
continue;
}
// 获取该门店的提成阶梯设置
var storeLifelineSetting = lifelineList.FirstOrDefault(x => x.StoreId == storeId && x.GeneralManagerId == managerId);
if (storeLifelineSetting == null)
{
continue;
}
// 获取门店信息
var storeName = storeDict.ContainsKey(storeId) ? storeDict[storeId].Dm ?? "" : "";
// 获取门店生命线(仅用于记录)
var storeLifeline = storeLifelineDict.ContainsKey(storeId) ? storeLifelineDict[storeId] : 0;
// 计算销售业绩(开单业绩-退款业绩)
var billing = storeBillingDict.ContainsKey(storeId) ? storeBillingDict[storeId] : 0;
var refund = storeRefundDict.ContainsKey(storeId) ? storeRefundDict[storeId] : 0;
var salesPerformance = billing - refund;
// 统计各项成本
var productMaterial = productMaterialDict.ContainsKey(storeId) ? productMaterialDict[storeId] : 0;
var cooperationCost = cooperationCostDict.ContainsKey(storeId) ? cooperationCostDict[storeId] : 0;
var storeExpense = storeExpenseDict.ContainsKey(storeId) ? storeExpenseDict[storeId] : 0;
var laundryCost = laundryCostDict.ContainsKey(storeId) ? laundryCostDict[storeId] : 0;
// 计算毛利
// 毛利 = 销售业绩 - 产品物料 - 合作项目成本 - 店内支出 - 洗毛巾
var grossProfit = salesPerformance - productMaterial - cooperationCost - storeExpense - laundryCost;
// 累加各项数据
totalSalesPerformance += salesPerformance;
totalProductMaterial += productMaterial;
totalCooperationCost += cooperationCost;
totalStoreExpense += storeExpense;
totalLaundryCost += laundryCost;
totalGrossProfit += grossProfit;
// 计算提成(必须满足提成阶梯1才能有提成资格,使用毛利计算)
var commissionResult = CalculateStoreCommission(grossProfit, storeLifelineSetting);
var commissionAmount = commissionResult.Amount;
var calculationDetail = commissionResult.Detail;
totalCommission += commissionAmount;
// 添加到门店业绩明细
storePerformanceDetails.Add(new StorePerformanceDetail
{
StoreId = storeId,
StoreName = storeName,
StoreLifeline = storeLifeline,
BillingPerformance = billing,
RefundPerformance = refund,
SalesPerformance = salesPerformance,
ProductMaterial = productMaterial,
CooperationCost = cooperationCost,
StoreExpense = storeExpense,
LaundryCost = laundryCost,
GrossProfit = grossProfit,
StorePerformance = grossProfit, // 用于提成计算的业绩是毛利
ReachedLifeline1 = grossProfit >= storeLifelineSetting.Lifeline1, // 是否达到提成阶梯1
Lifeline1 = storeLifelineSetting.Lifeline1,
CommissionRate1 = storeLifelineSetting.CommissionRate1,
Lifeline2 = storeLifelineSetting.Lifeline2,
CommissionRate2 = storeLifelineSetting.CommissionRate2,
Lifeline3 = storeLifelineSetting.Lifeline3,
CommissionRate3 = storeLifelineSetting.CommissionRate3,
CommissionAmount = commissionAmount,
CalculationDetail = calculationDetail
});
}
// 2.6 保存门店业绩明细(JSON格式)
salary.StorePerformanceDetail = storePerformanceDetails.ToJson();
// 2.7 保存毛利相关数据
salary.SalesPerformance = totalSalesPerformance;
salary.ProductMaterial = totalProductMaterial;
salary.CooperationCost = totalCooperationCost;
salary.StoreExpense = totalStoreExpense;
salary.LaundryCost = totalLaundryCost;
salary.GrossProfit = totalGrossProfit;
// 2.8 提成合计
salary.TotalCommission = totalCommission;
// 2.9 计算应发工资
salary.CalculatedGrossSalary = salary.BaseSalary + salary.TotalCommission;
salary.FinalGrossSalary = salary.CalculatedGrossSalary;
// 2.9 初始化其他字段(默认值为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())
{
// 先删除当月旧数据 (防止重复)
await _db.Deleteable<LqBusinessUnitManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == monthStr)
.ExecuteCommandAsync();
await _db.Insertable(managerStats.Values.ToList()).ExecuteCommandAsync();
}
}
/// <summary>
/// 计算门店提成(分段累进式)
/// </summary>
/// <param name="grossProfit">门店毛利</param>
/// <param name="lifelineSetting">提成阶梯设置</param>
/// <returns>提成金额和计算说明</returns>
/// <remarks>
/// 提成规则(分段累进式):
/// 1. 前提条件:必须满足提成阶梯1才能有提成资格
/// 2. 提成基数:使用毛利计算,而不是开单业绩
/// 3. 分段累进式计算:不同区间按不同比例分别计算后累加
/// - 毛利 < 提成阶梯1:无提成
/// - 提成阶梯1 ≤ 毛利 < 提成阶梯2:提成阶梯1 × 提成比例1 + (毛利 - 提成阶梯1) × 提成比例2
/// - 提成阶梯2 ≤ 毛利 < 提成阶梯3:提成阶梯1 × 提成比例1 + (提成阶梯2 - 提成阶梯1) × 提成比例2 + (毛利 - 提成阶梯2) × 提成比例3
/// - 毛利 ≥ 提成阶梯3:提成阶梯1 × 提成比例1 + (提成阶梯2 - 提成阶梯1) × 提成比例2 + (提成阶梯3 - 提成阶梯2) × 提成比例3 + (毛利 - 提成阶梯3) × 提成比例3
///
/// 示例:毛利 = 100,000元,提成阶梯1 = 150,000元,提成比例1 = 1%
/// 计算:100,000 < 150,000,未达到提成阶梯1,提成 = 0元
/// </remarks>
private (decimal Amount, string Detail) CalculateStoreCommission(decimal grossProfit, LqMdGeneralManagerLifelineEntity lifelineSetting)
{
// 验证提成阶梯1和提成比例1必须设置
if (lifelineSetting.Lifeline1 <= 0 || lifelineSetting.CommissionRate1 <= 0)
{
return (0m, "提成阶梯1或提成比例1未设置,无法计算提成");
}
// 必须满足提成阶梯1才能有提成资格
if (grossProfit < lifelineSetting.Lifeline1)
{
return (0m, $"毛利{grossProfit:N2}元,< 提成阶梯1({lifelineSetting.Lifeline1:N2}元),未达到提成资格,提成 = 0元");
}
decimal commissionAmount = 0m;
string detail = "";
var lifeline1 = lifelineSetting.Lifeline1;
var rate1 = lifelineSetting.CommissionRate1;
var lifeline2 = lifelineSetting.Lifeline2 ?? 0;
var rate2 = lifelineSetting.CommissionRate2 ?? 0;
var lifeline3 = lifelineSetting.Lifeline3 ?? 0;
var rate3 = lifelineSetting.CommissionRate3 ?? 0;
// 分段累进式计算(已通过提成阶梯1检查)
if (lifeline2 > 0 && grossProfit < lifeline2)
{
// 提成阶梯1 ≤ 毛利 < 提成阶梯2:分段累进计算
var part1 = lifeline1 * (rate1 / 100m);
var part2 = (grossProfit - lifeline1) * (rate2 / 100m);
commissionAmount = part1 + part2;
detail = $"毛利{grossProfit:N2}元,≥ 提成阶梯1({lifeline1:N2}元) 且 < 提成阶梯2({lifeline2:N2}元),提成 = {lifeline1:N2} × {rate1}% + ({grossProfit:N2} - {lifeline1:N2}) × {rate2}% = {part1:N2} + {part2:N2} = {commissionAmount:N2}元";
}
else if (lifeline3 > 0 && grossProfit < lifeline3)
{
// 提成阶梯2 ≤ 毛利 < 提成阶梯3:分段累进计算
var part1 = lifeline1 * (rate1 / 100m);
var part2 = (lifeline2 - lifeline1) * (rate2 / 100m);
var part3 = (grossProfit - lifeline2) * (rate3 / 100m);
commissionAmount = part1 + part2 + part3;
detail = $"毛利{grossProfit:N2}元,≥ 提成阶梯2({lifeline2:N2}元) 且 < 提成阶梯3({lifeline3:N2}元),提成 = {lifeline1:N2} × {rate1}% + ({lifeline2:N2} - {lifeline1:N2}) × {rate2}% + ({grossProfit:N2} - {lifeline2:N2}) × {rate3}% = {part1:N2} + {part2:N2} + {part3:N2} = {commissionAmount:N2}元";
}
else if (lifeline3 > 0)
{
// 毛利 ≥ 提成阶梯3:分段累进计算
var part1 = lifeline1 * (rate1 / 100m);
var part2 = (lifeline2 - lifeline1) * (rate2 / 100m);
var part3 = (lifeline3 - lifeline2) * (rate3 / 100m);
var part4 = (grossProfit - lifeline3) * (rate3 / 100m);
commissionAmount = part1 + part2 + part3 + part4;
detail = $"毛利{grossProfit:N2}元,≥ 提成阶梯3({lifeline3:N2}元),提成 = {lifeline1:N2} × {rate1}% + ({lifeline2:N2} - {lifeline1:N2}) × {rate2}% + ({lifeline3:N2} - {lifeline2:N2}) × {rate3}% + ({grossProfit:N2} - {lifeline3:N2}) × {rate3}% = {part1:N2} + {part2:N2} + {part3:N2} + {part4:N2} = {commissionAmount:N2}元";
}
else if (lifeline2 > 0)
{
// 提成阶梯3未设置,毛利 ≥ 提成阶梯2:分段累进计算
var part1 = lifeline1 * (rate1 / 100m);
var part2 = (grossProfit - lifeline1) * (rate2 / 100m);
commissionAmount = part1 + part2;
detail = $"毛利{grossProfit:N2}元,≥ 提成阶梯2({lifeline2:N2}元),提成阶梯3未设置,提成 = {lifeline1:N2} × {rate1}% + ({grossProfit:N2} - {lifeline1:N2}) × {rate2}% = {part1:N2} + {part2:N2} = {commissionAmount:N2}元";
}
else
{
// 只有提成阶梯1,毛利 ≥ 提成阶梯1:分段累进计算(提成阶梯1部分 × 提成比例1 + 超出部分 × 提成比例1)
var part1 = lifeline1 * (rate1 / 100m);
var part2 = (grossProfit - lifeline1) * (rate1 / 100m);
commissionAmount = part1 + part2;
detail = $"毛利{grossProfit:N2}元,≥ 提成阶梯1({lifeline1:N2}元),提成阶梯2未设置,提成 = {lifeline1:N2} × {rate1}% + ({grossProfit:N2} - {lifeline1:N2}) × {rate1}% = {part1:N2} + {part2:N2} = {commissionAmount:N2}元";
}
return (commissionAmount, detail);
}
/// <summary>
/// 门店业绩明细(用于JSON序列化)
/// </summary>
private class StorePerformanceDetail
{
public string StoreId { get; set; }
public string StoreName { get; set; }
public decimal StoreLifeline { get; set; }
public decimal BillingPerformance { get; set; }
public decimal RefundPerformance { get; set; }
public decimal SalesPerformance { get; set; }
public decimal ProductMaterial { get; set; }
public decimal CooperationCost { get; set; }
public decimal StoreExpense { get; set; }
public decimal LaundryCost { get; set; }
public decimal GrossProfit { get; set; }
public decimal StorePerformance { get; set; } // 用于提成计算的业绩(等于毛利)
public bool ReachedLifeline1 { get; set; } // 是否达到提成阶梯1
public decimal Lifeline1 { get; set; }
public decimal CommissionRate1 { get; set; }
public decimal? Lifeline2 { get; set; }
public decimal? CommissionRate2 { get; set; }
public decimal? Lifeline3 { get; set; }
public decimal? CommissionRate3 { get; set; }
public decimal CommissionAmount { get; set; }
public string CalculationDetail { get; set; }
}
}
}