LqMdTargetService.cs
15.4 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Filter;
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.LqMdTarget;
using NCC.FriendlyException;
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 readonly ISqlSugarRepository<LqMdTargetEntity> _lqMdTargetRepository;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
/// <summary>
/// 初始化一个<see cref="LqMdTargetService"/>类型的新实例
/// </summary>
public LqMdTargetService(ISqlSugarRepository<LqMdTargetEntity> lqMdTargetRepository, IUserManager userManager)
{
_lqMdTargetRepository = lqMdTargetRepository;
_db = _lqMdTargetRepository.Context;
_userManager = userManager;
}
#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 ? "F_Id" : input.sidx;
var data = await _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))
.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,
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,
})
.MergeTable()
.OrderBy(sidx + " " + input.sort)
.ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<LqMdTargetListOutput>.SqlSugarPageResult(data);
}
#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();
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);
}
#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 (string.IsNullOrEmpty(month) || month.Length != 6 || !Regex.IsMatch(month, @"^\d{6}$"))
{
throw NCCException.Oh(ErrorCode.COM1000, "月份格式必须为YYYYMM(如:202501)");
}
//查询门店列表
var storeList = await _db.Queryable<LqMdxxEntity>().Where(p => p.Status == StatusEnum.有效.GetHashCode()).Select(p => p.Id).ToListAsync();
// 删除设置月份的所有门店数据
await _db.Deleteable<LqMdTargetEntity>().Where(p => p.Month == month).ExecuteCommandAsync();
// 批量创建
var entities = storeList.Select(storeId => 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,
}).ToList();
var isOk = await _db.Insertable(entities).ExecuteCommandAsync();
if (!(isOk > 0))
throw NCCException.Oh(ErrorCode.COM1000);
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);
// 验证月份格式
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;
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);
}
#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);
}
#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)
{
syncedCount = await _db.Insertable(newEntities).ExecuteCommandAsync();
}
return new
{
success = true,
message = $"同步完成:成功同步{syncedCount}条记录,跳过{skippedCount}条已存在的记录",
syncedCount = syncedCount,
skippedCount = skippedCount,
lastMonth = lastMonthStr,
targetMonth = targetMonthStr
};
}
#endregion
}
}