LqMdTargetService.cs
37.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NCC.Common.Configuration;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Common.Helper;
using NCC.Common.Model.NPOI;
using NCC.DataEncryption;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqMdTarget;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.Extend.Interfaces.LqMdTarget;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend.LqMdTarget
{
/// <summary>
/// 门店目标服务
/// </summary>
[ApiDescriptionSettings(Tag = "绿纤门店目标服务", Name = "LqMdTarget", Order = 200)]
[Route("api/Extend/[controller]")]
public class LqMdTargetService : ILqMdTargetService, IDynamicApiController, ITransient
{
private const int InvalidStatus = (int)StatusEnum.无效;
private readonly ISqlSugarRepository<LqMdTargetEntity> _lqMdTargetRepository;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
private readonly IBusinessOperationLogService _businessOperationLogService;
/// <summary>
/// 初始化一个<see cref="LqMdTargetService"/>类型的新实例
/// </summary>
public LqMdTargetService(
ISqlSugarRepository<LqMdTargetEntity> lqMdTargetRepository,
IUserManager userManager,
IBusinessOperationLogService businessOperationLogService)
{
_lqMdTargetRepository = lqMdTargetRepository;
_db = _lqMdTargetRepository.Context;
_userManager = userManager;
_businessOperationLogService = businessOperationLogService;
}
#region 获取门店目标信息
/// <summary>
/// 获取门店目标信息
/// </summary>
/// <param name="id">主键ID</param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
var entity = await _db.Queryable<LqMdTargetEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var output = entity.Adapt<LqMdTargetInfoOutput>();
return output;
}
#endregion
#region 获取门店目标列表
/// <summary>
/// 获取门店目标列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] LqMdTargetListQueryInput input)
{
var sidx = input.sidx == null ? "id" : input.sidx;
var sort = string.IsNullOrEmpty(input.sort) ? "DESC" : input.sort;
var data = await BuildListOutputQuery(input)
.MergeTable()
.OrderBy($"{sidx} {sort}")
.ToPagedListAsync(input.currentPage, input.pageSize);
if (data.list != null)
{
var list = data.list.ToList();
await EnrichStoreDisplayAsync(list);
data.list = list;
}
return PageResult<LqMdTargetListOutput>.SqlSugarPageResult(data);
}
#endregion
#region 导出门店目标
/// <summary>
/// 导出门店目标设置
/// </summary>
/// <remarks>
/// 按与列表接口相同的筛选条件导出全部匹配数据(不分页)。
///
/// 示例请求:
/// GET /api/Extend/LqMdTarget/Actions/Export?month=202507&storeId=门店ID
///
/// 参数说明:
/// - storeId: 门店ID,可选
/// - month: 月份(YYYYMM),可选
/// - businessUnit: 归属事业部,可选
/// - techDepartment: 归属科技部,可选
/// - educationDepartment: 归属教育部,可选
/// - majorProjectDepartment: 归属大项目部,可选
/// </remarks>
/// <param name="input">查询参数(与列表接口一致)</param>
/// <returns>Excel 下载信息</returns>
/// <response code="200">导出成功</response>
[HttpGet("Actions/Export")]
public async Task<dynamic> Export([FromQuery] LqMdTargetListQueryInput input)
{
_ = await _userManager.GetUserInfo();
var sidx = input.sidx == null ? "id" : input.sidx;
var sort = string.IsNullOrEmpty(input.sort) ? "DESC" : input.sort;
var exportData = await BuildListOutputQuery(input)
.MergeTable()
.OrderBy($"{sidx} {sort}")
.ToListAsync();
await EnrichExportNamesAsync(exportData);
List<ParamsModel> paramList =
"[{\"value\":\"门店名称\",\"field\":\"storeName\"},{\"value\":\"月份\",\"field\":\"month\"},{\"value\":\"事业部\",\"field\":\"businessUnit\"},{\"value\":\"科技部\",\"field\":\"techDepartment\"},{\"value\":\"教育部\",\"field\":\"educationDepartment\"},{\"value\":\"大项目部\",\"field\":\"majorProjectDepartment\"},{\"value\":\"事业部目标\",\"field\":\"businessUnitTarget\"},{\"value\":\"科技部目标\",\"field\":\"techDepartmentTarget\"},{\"value\":\"教育部目标\",\"field\":\"educationDepartmentTarget\"},{\"value\":\"大项目部目标\",\"field\":\"majorProjectDepartmentTarget\"},{\"value\":\"门店目标\",\"field\":\"storeTarget\"},{\"value\":\"门店生命线\",\"field\":\"storeLifeline\"},{\"value\":\"门店耗卡目标\",\"field\":\"storeConsumeTarget\"},{\"value\":\"门店项目目标\",\"field\":\"storeProjectTarget\"},{\"value\":\"门店人员目标\",\"field\":\"storeHeadcountTarget\"},{\"value\":\"助理人员目标阶段1\",\"field\":\"assistantHeadcountTargetStage1\"},{\"value\":\"助理人员目标阶段2\",\"field\":\"assistantHeadcountTargetStage2\"}]".ToList<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "门店目标设置.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
foreach (var param in paramList)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = param.field, ExcelColumn = param.value });
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<LqMdTargetListOutput>.Export(exportData, excelconfig, addPath);
var summaryParts = new List<string>();
if (!string.IsNullOrEmpty(input.month))
summaryParts.Add($"月份={input.month}");
if (!string.IsNullOrEmpty(input.storeId))
{
var storeLabel = exportData.FirstOrDefault(x => x.storeId == input.storeId)?.storeName;
summaryParts.Add($"门店={storeLabel ?? input.storeId}");
}
var summary = summaryParts.Count > 0
? $"导出门店目标 {string.Join(",", summaryParts)},共 {exportData.Count} 条"
: $"导出门店目标,共 {exportData.Count} 条";
try
{
var detailJson = JsonConvert.SerializeObject(new
{
filters = new
{
storeId = input.storeId,
month = input.month,
businessUnit = input.businessUnit,
techDepartment = input.techDepartment,
educationDepartment = input.educationDepartment,
majorProjectDepartment = input.majorProjectDepartment
},
rowCount = exportData.Count,
fileName = excelconfig.FileName
});
await _businessOperationLogService.WriteAsync(
"门店目标",
"导出门店目标",
"lq_md_target",
null,
summary,
detailJson);
}
catch
{
// 写日志失败不影响导出结果
}
var fileName = _userManager.UserId + "|" + addPath + "|xls";
return new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
}
#endregion
#region 新建门店目标
/// <summary>
/// 新建门店目标
/// </summary>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] LqMdTargetCrInput input)
{
var userInfo = await _userManager.GetUserInfo();
// 验证门店ID和月份的唯一性
var exists = await _db.Queryable<LqMdTargetEntity>().Where(p => p.StoreId == input.storeId && p.Month == input.month).AnyAsync();
if (exists)
{
throw NCCException.Oh(ErrorCode.COM1000, "该门店在该月份已存在目标记录");
}
// 验证月份格式
if (input.month.Length != 6 || !Regex.IsMatch(input.month, @"^\d{6}$"))
{
throw NCCException.Oh(ErrorCode.COM1000, "月份格式必须为YYYYMM(如:202501)");
}
var entity = input.Adapt<LqMdTargetEntity>();
entity.Id = YitIdHelper.NextId().ToString();
await NormalizeOrganizeFieldsAsync(entity);
entity.CreateTime = DateTime.Now;
entity.CreateUser = userInfo.userId;
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0))
throw NCCException.Oh(ErrorCode.COM1000);
await TryWriteBusinessLogAsync(
"门店目标",
"新增门店目标",
"lq_md_target",
entity.Id,
$"新增门店目标:门店={input.storeId},月份={input.month}",
JsonConvert.SerializeObject(new { after = new { entity.Id, entity.StoreId, entity.Month } }));
}
#endregion
#region 根据门店批量创建数据
/// <summary>
/// 根据门店批量创建数据
/// 会删除设置月份的所有门店数据(谨用!!!)
/// </summary>
/// <param name="month">月份(YYYYMM格式)</param>
/// <returns></returns>
[HttpPost("BatchCreateByStores")]
public async Task<dynamic> BatchCreateByStores([FromQuery] string month)
{
var userInfo = await _userManager.GetUserInfo();
if (userInfo == null || string.IsNullOrEmpty(userInfo.userId))
{
throw NCCException.Oh("用户信息获取失败,请重新登录");
}
// 验证月份格式
if (string.IsNullOrEmpty(month) || month.Length != 6 || !Regex.IsMatch(month, @"^\d{6}$"))
{
throw NCCException.Oh("月份格式必须为YYYYMM(如:202501)");
}
//查询门店列表
var storeList = await _db.Queryable<LqMdxxEntity>().Select(p => p.Id).ToListAsync();
if (storeList == null || storeList.Count == 0)
{
return new { success = true, message = "没有有效的门店数据", createdCount = 0 };
}
// 删除设置月份的所有门店数据
await _db.Deleteable<LqMdTargetEntity>().Where(p => p.Month == month).ExecuteCommandAsync();
// 批量创建
var entities = new List<LqMdTargetEntity>();
foreach (var storeId in storeList)
{
if (string.IsNullOrEmpty(storeId))
continue;
entities.Add(new LqMdTargetEntity
{
Id = YitIdHelper.NextId().ToString(),
StoreId = storeId,
Month = month,
BusinessUnit = "",
TechDepartment = "",
EducationDepartment = "",
MajorProjectDepartment = "",
BusinessUnitTarget = 0,
TechDepartmentTarget = 0,
EducationDepartmentTarget = 0,
BusinessUnitGeneralManager = "",
BusinessUnitManager = "",
StoreTarget = 0,
StoreLifeline = 0,
StoreConsumeTarget = 0,
StoreProjectTarget = 0,
StoreHeadcountTarget = 0,
AssistantHeadcountTargetStage1 = 0,
AssistantHeadcountTargetStage2 = 0,
CreateTime = DateTime.Now,
CreateUser = userInfo.userId,
});
}
if (entities.Count == 0)
{
return new { success = true, message = "没有有效的门店数据可创建", createdCount = 0 };
}
var isOk = await _db.Insertable(entities).ExecuteCommandAsync();
if (!(isOk > 0))
throw NCCException.Oh(ErrorCode.COM1000, "批量创建失败");
await TryWriteBusinessLogAsync(
"门店目标",
"批量创建门店目标",
"lq_md_target",
null,
$"批量创建门店目标:月份={month},共 {isOk} 条",
JsonConvert.SerializeObject(new { month, createdCount = isOk }));
return new { success = true, message = $"成功创建{isOk}条记录", createdCount = isOk };
}
#endregion
#region 更新门店目标
/// <summary>
/// 更新门店目标
/// </summary>
/// <param name="id">主键ID</param>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] LqMdTargetUpInput input)
{
var userInfo = await _userManager.GetUserInfo();
// 验证记录是否存在
var entity = await _db.Queryable<LqMdTargetEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var beforeSnapshot = new { entity.StoreId, entity.Month, entity.StoreTarget, entity.StoreLifeline };
// 验证月份格式
if (input.month.Length != 6 || !Regex.IsMatch(input.month, @"^\d{6}$"))
{
throw NCCException.Oh("月份格式必须为YYYYMM(如:202501)");
}
// 如果门店ID或月份发生变化,需要验证唯一性
if (entity.StoreId != input.storeId || entity.Month != input.month)
{
var exists = await _db.Queryable<LqMdTargetEntity>().Where(p => p.StoreId == input.storeId && p.Month == input.month && p.Id != id).AnyAsync();
if (exists)
{
throw NCCException.Oh("该门店在该月份已存在目标记录");
}
}
var updateEntity = input.Adapt<LqMdTargetEntity>();
updateEntity.Id = id;
await NormalizeOrganizeFieldsAsync(updateEntity);
updateEntity.UpdateTime = DateTime.Now;
updateEntity.UpdateUser = userInfo.userId;
var isOk = await _db.Updateable(updateEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0))
throw NCCException.Oh(ErrorCode.COM1001);
await TryWriteBusinessLogAsync(
"门店目标",
"修改门店目标",
"lq_md_target",
id,
$"修改门店目标:门店={input.storeId},月份={input.month}",
JsonConvert.SerializeObject(new
{
before = beforeSnapshot,
after = new { input.storeId, input.month, input.storeTarget, input.storeLifeline }
}));
}
#endregion
#region 删除门店目标
/// <summary>
/// 删除门店目标
/// </summary>
/// <param name="id">主键ID</param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var entity = await _db.Queryable<LqMdTargetEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable<LqMdTargetEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0))
throw NCCException.Oh(ErrorCode.COM1002);
await TryWriteBusinessLogAsync(
"门店目标",
"删除门店目标",
"lq_md_target",
id,
$"删除门店目标:门店={entity.StoreId},月份={entity.Month}",
JsonConvert.SerializeObject(new { before = new { entity.Id, entity.StoreId, entity.Month } }));
}
#endregion
#region 同步上月数据
/// <summary>
/// 同步上月数据
/// </summary>
/// <param name="targetMonth">目标月份(YYYYMM格式),如果为空则同步到当前月份</param>
/// <returns></returns>
[HttpPost("SyncLastMonthData")]
public async Task<dynamic> SyncLastMonthData([FromQuery] string targetMonth = null)
{
var userInfo = await _userManager.GetUserInfo();
// 确定目标月份
string targetMonthStr;
if (string.IsNullOrEmpty(targetMonth))
{
// 如果未指定,使用当前月份
var now = DateTime.Now;
targetMonthStr = now.ToString("yyyyMM");
}
else
{
// 验证月份格式
if (targetMonth.Length != 6 || !Regex.IsMatch(targetMonth, @"^\d{6}$"))
{
throw NCCException.Oh(ErrorCode.COM1000, "月份格式必须为YYYYMM(如:202501)");
}
targetMonthStr = targetMonth;
}
// 计算上个月份
var targetDate = DateTime.ParseExact(targetMonthStr, "yyyyMM", null);
var lastMonthDate = targetDate.AddMonths(-1);
var lastMonthStr = lastMonthDate.ToString("yyyyMM");
// 查询上个月的所有门店目标数据
var lastMonthData = await _db.Queryable<LqMdTargetEntity>()
.Where(p => p.Month == lastMonthStr)
.ToListAsync();
if (lastMonthData == null || lastMonthData.Count == 0)
{
return new
{
success = true,
message = $"上个月({lastMonthStr})没有数据可同步",
syncedCount = 0,
skippedCount = 0
};
}
// 查询目标月份已存在的记录
var existingStoreIds = await _db.Queryable<LqMdTargetEntity>()
.Where(p => p.Month == targetMonthStr)
.Select(p => p.StoreId)
.ToListAsync();
// 过滤掉已存在的门店,只同步新门店
var newEntities = lastMonthData
.Where(p => !existingStoreIds.Contains(p.StoreId))
.Select(p => new LqMdTargetEntity
{
Id = YitIdHelper.NextId().ToString(),
StoreId = p.StoreId,
Month = targetMonthStr,
BusinessUnit = p.BusinessUnit,
TechDepartment = p.TechDepartment,
EducationDepartment = p.EducationDepartment,
MajorProjectDepartment = p.MajorProjectDepartment,
BusinessUnitTarget = p.BusinessUnitTarget,
TechDepartmentTarget = p.TechDepartmentTarget,
EducationDepartmentTarget = p.EducationDepartmentTarget,
BusinessUnitGeneralManager = p.BusinessUnitGeneralManager,
BusinessUnitManager = p.BusinessUnitManager,
StoreTarget = p.StoreTarget,
StoreLifeline = p.StoreLifeline,
StoreConsumeTarget = p.StoreConsumeTarget,
StoreProjectTarget = p.StoreProjectTarget,
StoreHeadcountTarget = p.StoreHeadcountTarget,
AssistantHeadcountTargetStage1 = p.AssistantHeadcountTargetStage1,
AssistantHeadcountTargetStage2 = p.AssistantHeadcountTargetStage2,
CreateTime = DateTime.Now,
CreateUser = userInfo.userId,
})
.ToList();
int syncedCount = 0;
int skippedCount = lastMonthData.Count - newEntities.Count;
if (newEntities.Count > 0)
{
var orgAliasMap = await BuildOrganizeAliasToIdMapAsync();
foreach (var entity in newEntities)
{
NormalizeOrganizeFields(entity, orgAliasMap);
}
syncedCount = await _db.Insertable(newEntities).ExecuteCommandAsync();
}
if (syncedCount > 0)
{
await TryWriteBusinessLogAsync(
"门店目标",
"同步上月门店目标",
"lq_md_target",
null,
$"同步上月门店目标:{lastMonthStr} → {targetMonthStr},共 {syncedCount} 条",
JsonConvert.SerializeObject(new { lastMonth = lastMonthStr, targetMonth = targetMonthStr, syncedCount, skippedCount }));
}
return new
{
success = true,
message = $"同步完成:成功同步{syncedCount}条记录,跳过{skippedCount}条已存在的记录",
syncedCount = syncedCount,
skippedCount = skippedCount,
lastMonth = lastMonthStr,
targetMonth = targetMonthStr
};
}
#endregion
#region 获取部门管理的门店列表
/// <summary>
/// 获取部门管理的门店列表
/// </summary>
/// <remarks>
/// 根据年月、组织类型、部门ID查询该部门在该月份管理的门店列表
///
/// 示例请求:
/// ```json
/// {
/// "month": "202511",
/// "organizationType": "事业部",
/// "departmentId": "部门ID"
/// }
/// ```
///
/// 参数说明:
/// - month: 年月,格式为YYYYMM(如:202511表示2025年11月)
/// - organizationType: 组织类型,可选值:事业部、科技部、教育部、大项目部
/// - departmentId: 部门ID
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>门店列表(包含门店ID和门店名称)</returns>
/// <response code="200">成功返回门店列表</response>
/// <response code="400">参数错误</response>
[HttpPost("GetManagedStores")]
public async Task<dynamic> GetManagedStores([FromBody] GetManagedStoresInput input)
{
try
{
// 验证参数
if (input == null)
{
throw NCCException.Oh("参数不能为空");
}
if (string.IsNullOrEmpty(input.Month))
{
throw NCCException.Oh("年月不能为空");
}
if (input.Month.Length != 6 || !Regex.IsMatch(input.Month, @"^\d{6}$"))
{
throw NCCException.Oh("年月格式必须为YYYYMM(如:202511)");
}
if (string.IsNullOrEmpty(input.OrganizationType))
{
throw NCCException.Oh("组织类型不能为空");
}
if (string.IsNullOrEmpty(input.DepartmentId))
{
throw NCCException.Oh("部门ID不能为空");
}
// 构建查询条件(使用多表关联方式)
var query = _db.Queryable<LqMdTargetEntity, LqMdxxEntity>(
(t, s) => t.StoreId == s.Id)
.Where((t, s) => t.Month == input.Month);
var orgAliasMap = await BuildOrganizeAliasToIdMapAsync();
var departmentId = ResolveOrganizeId(input.DepartmentId, orgAliasMap);
if (string.IsNullOrEmpty(departmentId))
{
throw NCCException.Oh("部门ID无效");
}
// 根据组织类型添加部门过滤条件(兼容历史名称脏数据)
switch (input.OrganizationType)
{
case "事业部":
query = query.Where((t, s) => t.BusinessUnit == departmentId || t.BusinessUnit == input.DepartmentId);
break;
case "科技部":
query = query.Where((t, s) => t.TechDepartment == departmentId || t.TechDepartment == input.DepartmentId);
break;
case "教育部":
query = query.Where((t, s) => t.EducationDepartment == departmentId || t.EducationDepartment == input.DepartmentId);
break;
case "大项目部":
query = query.Where((t, s) => t.MajorProjectDepartment == departmentId || t.MajorProjectDepartment == input.DepartmentId);
break;
default:
throw NCCException.Oh($"不支持的组织类型:{input.OrganizationType},支持的类型:事业部、科技部、教育部、大项目部");
}
// 关联门店表获取门店名称
var result = await query
.Select((t, s) => new ManagedStoreOutput
{
StoreId = t.StoreId,
StoreName = s.Dm ?? "未知门店"
})
.ToListAsync();
return result;
}
catch (Exception ex)
{
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 私有方法
/// <summary>
/// 构建与列表一致的筛选查询
/// </summary>
private ISugarQueryable<LqMdTargetEntity> BuildFilteredQuery(LqMdTargetListQueryInput input)
{
return _db.Queryable<LqMdTargetEntity>()
.WhereIF(!string.IsNullOrEmpty(input.storeId), p => p.StoreId.Contains(input.storeId))
.WhereIF(!string.IsNullOrEmpty(input.month), p => p.Month == input.month)
.WhereIF(!string.IsNullOrEmpty(input.businessUnit), p => p.BusinessUnit.Contains(input.businessUnit))
.WhereIF(!string.IsNullOrEmpty(input.techDepartment), p => p.TechDepartment.Contains(input.techDepartment))
.WhereIF(!string.IsNullOrEmpty(input.educationDepartment), p => p.EducationDepartment.Contains(input.educationDepartment))
.WhereIF(!string.IsNullOrEmpty(input.majorProjectDepartment), p => p.MajorProjectDepartment.Contains(input.majorProjectDepartment));
}
/// <summary>
/// 构建列表/导出共用的输出投影
/// </summary>
private ISugarQueryable<LqMdTargetListOutput> BuildListOutputQuery(LqMdTargetListQueryInput input)
{
return BuildFilteredQuery(input)
.Select(it => new LqMdTargetListOutput
{
id = it.Id,
storeId = it.StoreId,
month = it.Month,
businessUnit = it.BusinessUnit,
techDepartment = it.TechDepartment,
educationDepartment = it.EducationDepartment,
majorProjectDepartment = it.MajorProjectDepartment,
businessUnitTarget = it.BusinessUnitTarget,
techDepartmentTarget = it.TechDepartmentTarget,
educationDepartmentTarget = it.EducationDepartmentTarget,
majorProjectDepartmentTarget = it.MajorProjectDepartmentTarget,
businessUnitGeneralManager = it.BusinessUnitGeneralManager,
businessUnitManager = it.BusinessUnitManager,
storeTarget = it.StoreTarget,
storeLifeline = it.StoreLifeline,
storeConsumeTarget = it.StoreConsumeTarget,
storeProjectTarget = it.StoreProjectTarget,
storeHeadcountTarget = it.StoreHeadcountTarget,
assistantHeadcountTargetStage1 = it.AssistantHeadcountTargetStage1,
assistantHeadcountTargetStage2 = it.AssistantHeadcountTargetStage2,
createTime = it.CreateTime,
createUser = it.CreateUser,
updateTime = it.UpdateTime,
updateUser = it.UpdateUser,
});
}
/// <summary>
/// 列表展示:仅补门店名称,归属字段保持组织ID(避免编辑保存时把名称写回库)
/// </summary>
private async Task EnrichStoreDisplayAsync(List<LqMdTargetListOutput> rows)
{
if (rows == null || rows.Count == 0)
return;
var storeIds = rows
.Where(x => !string.IsNullOrEmpty(x.storeId))
.Select(x => x.storeId)
.Distinct()
.ToList();
if (storeIds.Count == 0)
return;
var storeDict = (await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm, x.Status })
.ToListAsync())
.ToDictionary(
x => x.Id,
x => new StoreDisplayInfo
{
Name = x.Dm ?? string.Empty,
Deleted = x.Status == InvalidStatus
});
foreach (var item in rows)
{
if (!string.IsNullOrEmpty(item.storeId) && storeDict.TryGetValue(item.storeId, out var storeInfo))
{
item.storeName = storeInfo.Name;
item.storeDeleted = storeInfo.Deleted;
}
}
}
/// <summary>
/// 解析门店与组织名称,供导出展示(含已软删门店)
/// </summary>
private async Task EnrichExportNamesAsync(List<LqMdTargetListOutput> exportData)
{
if (exportData == null || exportData.Count == 0)
return;
await EnrichStoreDisplayAsync(exportData);
var orgValues = exportData
.SelectMany(x => new[] { x.businessUnit, x.techDepartment, x.educationDepartment, x.majorProjectDepartment })
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
var orgDict = new Dictionary<string, string>();
var orgNameDict = new Dictionary<string, string>(StringComparer.Ordinal);
if (orgValues.Count > 0)
{
var orgs = await _db.Queryable<OrganizeEntity>()
.Where(x => (orgValues.Contains(x.Id) || orgValues.Contains(x.FullName))
&& x.DeleteMark == null
&& x.Category == "department")
.Select(x => new { x.Id, x.FullName })
.ToListAsync();
orgDict = orgs.ToDictionary(x => x.Id, x => x.FullName ?? string.Empty);
foreach (var org in orgs.Where(x => !string.IsNullOrEmpty(x.FullName)))
{
orgNameDict[org.FullName] = org.FullName;
}
}
foreach (var item in exportData)
{
item.businessUnit = ResolveOrganizeDisplayName(item.businessUnit, orgDict, orgNameDict);
item.techDepartment = ResolveOrganizeDisplayName(item.techDepartment, orgDict, orgNameDict);
item.educationDepartment = ResolveOrganizeDisplayName(item.educationDepartment, orgDict, orgNameDict);
item.majorProjectDepartment = ResolveOrganizeDisplayName(item.majorProjectDepartment, orgDict, orgNameDict);
}
}
/// <summary>
/// 保存前将归属字段统一归一化为 base_organize.F_Id
/// </summary>
private async Task NormalizeOrganizeFieldsAsync(LqMdTargetEntity entity)
{
if (entity == null)
return;
var orgAliasMap = await BuildOrganizeAliasToIdMapAsync();
NormalizeOrganizeFields(entity, orgAliasMap);
}
/// <summary>
/// 使用组织映射将归属字段归一化为组织ID
/// </summary>
private static void NormalizeOrganizeFields(LqMdTargetEntity entity, Dictionary<string, string> orgAliasMap)
{
if (entity == null)
return;
entity.BusinessUnit = ResolveOrganizeId(entity.BusinessUnit, orgAliasMap, "事业部");
entity.TechDepartment = ResolveOrganizeId(entity.TechDepartment, orgAliasMap, "科技部");
entity.EducationDepartment = ResolveOrganizeId(entity.EducationDepartment, orgAliasMap, "教育部");
entity.MajorProjectDepartment = ResolveOrganizeId(entity.MajorProjectDepartment, orgAliasMap, "大项目部");
}
/// <summary>
/// 构建组织别名(ID/名称)到组织ID的映射
/// </summary>
private async Task<Dictionary<string, string>> BuildOrganizeAliasToIdMapAsync()
{
var orgs = await _db.Queryable<OrganizeEntity>()
.Where(x => x.Category == "department" && x.DeleteMark == null)
.Select(x => new { x.Id, x.FullName })
.ToListAsync();
var map = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var org in orgs)
{
if (!string.IsNullOrEmpty(org.Id))
map[org.Id] = org.Id;
if (!string.IsNullOrEmpty(org.FullName) && !map.ContainsKey(org.FullName))
map[org.FullName] = org.Id;
}
return map;
}
/// <summary>
/// 组织归属值(ID 或名称)解析为标准组织ID;无法解析时抛出友好错误
/// </summary>
private static string ResolveOrganizeId(string rawValue, Dictionary<string, string> orgAliasMap, string fieldLabel = null)
{
if (string.IsNullOrWhiteSpace(rawValue))
return rawValue;
if (orgAliasMap != null && orgAliasMap.TryGetValue(rawValue, out var mappedId) && !string.IsNullOrEmpty(mappedId))
return mappedId;
if (Regex.IsMatch(rawValue, @"^\d{15,}$"))
return rawValue;
var label = string.IsNullOrEmpty(fieldLabel) ? "组织归属" : fieldLabel;
throw NCCException.Oh($"{label}「{rawValue}」无效,请重新选择部门");
}
/// <summary>
/// 门店展示信息(含软删标记)
/// </summary>
private sealed class StoreDisplayInfo
{
public string Name { get; set; }
public bool Deleted { get; set; }
}
/// <summary>
/// 组织ID解析为名称,解析不到则保留原值
/// </summary>
private static string ResolveOrganizeDisplayName(
string organizeValue,
Dictionary<string, string> orgIdDict,
Dictionary<string, string> orgNameDict)
{
if (string.IsNullOrEmpty(organizeValue))
return organizeValue;
if (orgIdDict.TryGetValue(organizeValue, out var name) && !string.IsNullOrEmpty(name))
return name;
if (orgNameDict.TryGetValue(organizeValue, out var existingName) && !string.IsNullOrEmpty(existingName))
return existingName;
return organizeValue;
}
private async Task TryWriteBusinessLogAsync(string moduleCode, string actionCode, string bizType, string bizId, string summary, string detailJson = null)
{
try
{
await _businessOperationLogService.WriteAsync(moduleCode, actionCode, bizType, bizId, summary, detailJson);
}
catch (Exception)
{
// 写日志失败不拖垮主业务
}
}
#endregion
}
}