LqMallAppointmentService.cs
21.9 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.ClayObject;
using NCC.Common.Configuration;
using NCC.Common.Const;
using NCC.Common.Core.Manager;
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.Mall;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_mall_appointment;
using NCC.Extend.Entitys.lq_mall_member;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.FriendlyException;
using NCC.JsonSerialization;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend
{
/// <summary>
/// 会员商城-预约意向(会员提交到店预约意向,门店/后台查看后电话确认;不关联现有预约业务)
/// </summary>
[ApiDescriptionSettings(Tag = "会员商城-预约", Name = "LqMallAppointment", Order = 304)]
[Route("api/Extend/LqMallAppointment")]
public class LqMallAppointmentService : IDynamicApiController, ITransient
{
private readonly IUserManager _userManager;
private readonly ILogger<LqMallAppointmentService> _logger;
private readonly ISqlSugarClient _db;
private readonly IBusinessOperationLogService _log;
/// <summary>
/// 构造函数
/// </summary>
public LqMallAppointmentService(
IUserManager userManager,
ILogger<LqMallAppointmentService> logger,
ISqlSugarClient db,
IBusinessOperationLogService log)
{
_userManager = userManager;
_logger = logger;
_db = db;
_log = log;
}
#region C 端(会员小程序)
/// <summary>
/// 创建预约意向
/// </summary>
/// <param name="input">预约输入</param>
/// <returns>预约 Id 与单号</returns>
[HttpPost("CreateAppointment")]
public async Task<dynamic> CreateAppointmentAsync([FromBody] MallAppointmentCreateInput input)
{
var memberId = GetCurrentMemberId();
if (input == null) throw NCCException.Oh("参数不能为空");
if (string.IsNullOrWhiteSpace(input.StoreId)) throw NCCException.Oh("请选择预约门店");
if (input.AppointDate == null) throw NCCException.Oh("请选择期望到店日期");
if (string.IsNullOrWhiteSpace(input.TimeSlot)) throw NCCException.Oh("请选择期望到店时段");
var member = await _db.Queryable<LqMallMemberEntity>()
.Where(x => x.Id == memberId && x.DeleteMark == null).FirstAsync();
if (member == null) throw NCCException.Oh("会员不存在");
var store = await _db.Queryable<LqMdxxEntity>().Where(x => x.Id == input.StoreId).FirstAsync();
if (store == null) throw NCCException.Oh("预约门店不存在");
var phone = string.IsNullOrWhiteSpace(input.ContactPhone) ? member.Phone : input.ContactPhone.Trim();
if (string.IsNullOrWhiteSpace(phone)) throw NCCException.Oh("请填写联系手机号");
var entity = new LqMallAppointmentEntity
{
Id = YitIdHelper.NextId().ToString(),
AppointmentNo = GenerateAppointmentNo(),
MemberId = member.Id,
MemberName = member.NickName,
MemberPhone = phone,
StoreId = store.Id,
StoreName = store.Dm,
AppointDate = input.AppointDate.Value.Date,
TimeSlot = input.TimeSlot.Trim(),
ProjectDesc = input.ProjectDesc,
Remark = input.Remark,
Status = (int)MallAppointmentStatusEnum.待确认,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now
};
var ok = await _db.Insertable(entity).ExecuteCommandAsync();
if (ok <= 0) throw NCCException.Oh("预约提交失败,请重试");
return new { id = entity.Id, appointmentNo = entity.AppointmentNo };
}
/// <summary>
/// 我的预约列表(分页,可按状态过滤)
/// </summary>
/// <param name="input">查询条件</param>
/// <returns>预约分页列表</returns>
[HttpGet("GetMyAppointments")]
public async Task<dynamic> GetMyAppointmentsAsync([FromQuery] MallMyAppointmentQueryInput input)
{
var memberId = GetCurrentMemberId();
var data = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.MemberId == memberId && x.DeleteMark == null)
.WhereIF(input.Status.HasValue, x => x.Status == input.Status.Value)
.OrderBy(x => x.CreateTime, OrderByType.Desc)
.Select(x => new MallAppointmentListOutput
{
id = x.Id,
appointmentNo = x.AppointmentNo,
memberId = x.MemberId,
memberName = x.MemberName,
memberPhone = x.MemberPhone,
storeId = x.StoreId,
storeName = x.StoreName,
appointDate = x.AppointDate,
timeSlot = x.TimeSlot,
projectDesc = x.ProjectDesc,
remark = x.Remark,
status = x.Status,
confirmUserName = x.ConfirmUserName,
confirmTime = x.ConfirmTime,
confirmRemark = x.ConfirmRemark,
cancelReason = x.CancelReason,
createTime = x.CreateTime
})
.ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<MallAppointmentListOutput>.SqlSugarPageResult(data);
}
/// <summary>
/// 我的预约详情
/// </summary>
/// <param name="id">预约 Id</param>
/// <returns>预约详情</returns>
[HttpGet("GetAppointmentDetail")]
public async Task<dynamic> GetAppointmentDetailAsync([FromQuery] string id)
{
var memberId = GetCurrentMemberId();
if (string.IsNullOrWhiteSpace(id)) throw NCCException.Oh("预约 Id 不能为空");
var entity = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.Id == id && x.MemberId == memberId && x.DeleteMark == null).FirstAsync();
if (entity == null) throw NCCException.Oh("预约不存在");
return MapDetail(entity);
}
/// <summary>
/// 取消预约(仅待确认可取消)
/// </summary>
/// <param name="id">预约 Id</param>
[HttpPut("CancelAppointment/{id}")]
public async Task CancelAppointmentAsync([FromRoute] string id)
{
var memberId = GetCurrentMemberId();
var entity = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.Id == id && x.MemberId == memberId && x.DeleteMark == null).FirstAsync();
if (entity == null) throw NCCException.Oh("预约不存在");
if (entity.Status != (int)MallAppointmentStatusEnum.待确认)
throw NCCException.Oh("仅待确认的预约可取消");
entity.Status = (int)MallAppointmentStatusEnum.已取消;
entity.CancelReason = "会员取消";
entity.UpdateTime = DateTime.Now;
await _db.Updateable(entity)
.UpdateColumns(x => new { x.Status, x.CancelReason, x.UpdateTime })
.ExecuteCommandAsync();
}
#endregion
#region 管理端
/// <summary>
/// 管理端预约列表(分页,多条件筛选,全门店)
/// </summary>
/// <param name="input">查询条件</param>
/// <returns>预约分页列表</returns>
[HttpGet("GetAdminList")]
public async Task<dynamic> GetAdminListAsync([FromQuery] MallAppointmentAdminQueryInput input)
{
var data = await BuildAdminQuery(input).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<MallAppointmentListOutput>.SqlSugarPageResult(data);
}
/// <summary>
/// 管理端预约详情
/// </summary>
/// <param name="id">预约 Id</param>
/// <returns>预约详情</returns>
[HttpGet("GetAdminDetail")]
public async Task<dynamic> GetAdminDetailAsync([FromQuery] string id)
{
if (string.IsNullOrWhiteSpace(id)) throw NCCException.Oh("预约 Id 不能为空");
var entity = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.Id == id && x.DeleteMark == null).FirstAsync();
if (entity == null) throw NCCException.Oh("预约不存在");
return MapDetail(entity);
}
/// <summary>
/// 确认预约(待确认→已确认,记录确认人与沟通结果;管理端与门店端共用)
/// </summary>
/// <param name="input">确认输入(门店端需传 StoreId 做归属校验)</param>
/// <returns>确认结果</returns>
[HttpPut("Confirm")]
public async Task<dynamic> ConfirmAsync([FromBody] MallAppointmentConfirmInput input)
{
if (input == null || string.IsNullOrWhiteSpace(input.Id))
throw NCCException.Oh("预约 Id 不能为空");
var entity = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.Id == input.Id && x.DeleteMark == null).FirstAsync();
if (entity == null) throw NCCException.Oh("预约不存在");
if (!string.IsNullOrWhiteSpace(input.StoreId) && entity.StoreId != input.StoreId)
throw NCCException.Oh("该预约不属于当前门店");
if (entity.Status == (int)MallAppointmentStatusEnum.已取消)
throw NCCException.Oh("预约已取消,无法确认");
if (entity.Status == (int)MallAppointmentStatusEnum.已确认)
throw NCCException.Oh("预约已确认,请勿重复操作");
var operatorId = _userManager.UserId;
var operatorName = "";
if (!string.IsNullOrWhiteSpace(operatorId))
{
operatorName = await _db.Queryable<UserEntity>()
.Where(x => x.Id == operatorId).Select(x => x.RealName).FirstAsync();
}
entity.Status = (int)MallAppointmentStatusEnum.已确认;
entity.ConfirmUser = operatorId;
entity.ConfirmUserName = operatorName;
entity.ConfirmTime = DateTime.Now;
entity.ConfirmRemark = input.ConfirmRemark;
entity.UpdateTime = DateTime.Now;
await _db.Updateable(entity)
.UpdateColumns(x => new { x.Status, x.ConfirmUser, x.ConfirmUserName, x.ConfirmTime, x.ConfirmRemark, x.UpdateTime })
.ExecuteCommandAsync();
await _log.WriteAsync("会员商城", "确认预约", "mall_appointment", entity.Id,
$"确认会员预约:{entity.MemberName}({entity.MemberPhone}){entity.AppointmentNo}");
return new { success = true, id = entity.Id };
}
/// <summary>
/// 管理端取消预约(待确认/已确认均可取消,记录原因)
/// </summary>
/// <param name="input">确认输入(复用,读取 Id / ConfirmRemark 作为取消原因)</param>
[HttpPut("AdminCancel")]
public async Task AdminCancelAsync([FromBody] MallAppointmentConfirmInput input)
{
if (input == null || string.IsNullOrWhiteSpace(input.Id))
throw NCCException.Oh("预约 Id 不能为空");
var entity = await _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.Id == input.Id && x.DeleteMark == null).FirstAsync();
if (entity == null) throw NCCException.Oh("预约不存在");
if (!string.IsNullOrWhiteSpace(input.StoreId) && entity.StoreId != input.StoreId)
throw NCCException.Oh("该预约不属于当前门店");
if (entity.Status == (int)MallAppointmentStatusEnum.已取消)
throw NCCException.Oh("预约已取消");
entity.Status = (int)MallAppointmentStatusEnum.已取消;
entity.CancelReason = string.IsNullOrWhiteSpace(input.ConfirmRemark) ? "门店取消" : input.ConfirmRemark.Trim();
entity.UpdateTime = DateTime.Now;
await _db.Updateable(entity)
.UpdateColumns(x => new { x.Status, x.CancelReason, x.UpdateTime })
.ExecuteCommandAsync();
await _log.WriteAsync("会员商城", "取消预约", "mall_appointment", entity.Id,
$"取消会员预约:{entity.MemberName}({entity.MemberPhone}){entity.AppointmentNo}");
}
/// <summary>
/// 导出线上预约(固定列,忽略 selectKey)
/// </summary>
/// <remarks>
/// GET /api/Extend/LqMallAppointment/Actions/Export?dataType=1
/// dataType:0 当前页,1 全部;筛选条件与 GetAdminList 一致。
/// </remarks>
/// <param name="input">管理端查询参数</param>
/// <returns>Excel 下载信息(name、url)</returns>
[HttpGet("Actions/Export")]
public async Task<dynamic> ExportAsync([FromQuery] MallAppointmentAdminQueryInput input)
{
input ??= new MallAppointmentAdminQueryInput();
var list = new List<MallAppointmentListOutput>();
if (input.dataType == 0)
{
var data = Clay.Object(await GetAdminListAsync(input));
list = data.Solidify<PageResult<MallAppointmentListOutput>>().list;
}
else
{
list = await BuildAdminQuery(input).ToListAsync();
}
var exportData = list.Select(x => new MallAppointmentExportOutput
{
appointmentNo = x.appointmentNo,
memberName = x.memberName,
memberPhone = x.memberPhone,
storeName = x.storeName,
appointDisplay = FormatAppointDisplay(x.appointDate, x.timeSlot),
projectDesc = x.projectDesc,
statusText = ResolveMallAppointmentStatusText(x.status),
createTime = x.createTime
}).ToList();
List<ParamsModel> paramList =
"[{\"value\":\"预约单号\",\"field\":\"appointmentNo\"},{\"value\":\"会员名称\",\"field\":\"memberName\"},{\"value\":\"手机号\",\"field\":\"memberPhone\"},{\"value\":\"门店名称\",\"field\":\"storeName\"},{\"value\":\"期望到店\",\"field\":\"appointDisplay\"},{\"value\":\"需求\",\"field\":\"projectDesc\"},{\"value\":\"状态\",\"field\":\"statusText\"},{\"value\":\"提交时间\",\"field\":\"createTime\"}]"
.ToList<ParamsModel>();
var excelconfig = new ExcelConfig
{
FileName = "线上预约.xls",
HeadFont = "微软雅黑",
HeadPoint = 10,
IsAllSizeColumn = true,
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<MallAppointmentExportOutput>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
await TryWriteBizLogAsync(
"导出线上预约",
"mall_appointment",
null,
$"导出线上预约,共 {exportData.Count} 条",
new
{
filters = new { input.StoreId, input.Status, input.Keyword, input.StartDate, input.EndDate, input.dataType },
rowCount = exportData.Count,
fileName = excelconfig.FileName
}.Serialize());
return new { name = excelconfig.FileName, url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC") };
}
#endregion
#region 门店端
/// <summary>
/// 门店端预约列表(仅本门店,分页,可按状态过滤)
/// </summary>
/// <param name="input">查询条件(StoreId 必填)</param>
/// <returns>预约分页列表</returns>
[HttpGet("GetStoreList")]
public async Task<dynamic> GetStoreListAsync([FromQuery] MallAppointmentAdminQueryInput input)
{
if (input == null || string.IsNullOrWhiteSpace(input.StoreId))
throw NCCException.Oh("门店 Id 不能为空");
var data = await BuildAdminQuery(input).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<MallAppointmentListOutput>.SqlSugarPageResult(data);
}
#endregion
#region 私有方法
/// <summary>
/// 构建管理端/门店端通用查询
/// </summary>
private ISugarQueryable<MallAppointmentListOutput> BuildAdminQuery(MallAppointmentAdminQueryInput input)
{
return _db.Queryable<LqMallAppointmentEntity>()
.Where(x => x.DeleteMark == null)
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), x => x.StoreId == input.StoreId)
.WhereIF(input.Status.HasValue, x => x.Status == input.Status.Value)
.WhereIF(!string.IsNullOrWhiteSpace(input.Keyword),
x => x.MemberName.Contains(input.Keyword) || x.MemberPhone.Contains(input.Keyword))
.WhereIF(input.StartDate.HasValue, x => x.AppointDate >= input.StartDate.Value.Date)
.WhereIF(input.EndDate.HasValue, x => x.AppointDate <= input.EndDate.Value.Date)
.OrderBy(x => x.CreateTime, OrderByType.Desc)
.Select(x => new MallAppointmentListOutput
{
id = x.Id,
appointmentNo = x.AppointmentNo,
memberId = x.MemberId,
memberName = x.MemberName,
memberPhone = x.MemberPhone,
storeId = x.StoreId,
storeName = x.StoreName,
appointDate = x.AppointDate,
timeSlot = x.TimeSlot,
projectDesc = x.ProjectDesc,
remark = x.Remark,
status = x.Status,
confirmUserName = x.ConfirmUserName,
confirmTime = x.ConfirmTime,
confirmRemark = x.ConfirmRemark,
cancelReason = x.CancelReason,
createTime = x.CreateTime
});
}
private static object MapDetail(LqMallAppointmentEntity x)
{
return new
{
id = x.Id,
appointmentNo = x.AppointmentNo,
memberId = x.MemberId,
memberName = x.MemberName,
memberPhone = x.MemberPhone,
storeId = x.StoreId,
storeName = x.StoreName,
appointDate = x.AppointDate,
timeSlot = x.TimeSlot,
projectDesc = x.ProjectDesc,
remark = x.Remark,
status = x.Status,
confirmUser = x.ConfirmUser,
confirmUserName = x.ConfirmUserName,
confirmTime = x.ConfirmTime,
confirmRemark = x.ConfirmRemark,
cancelReason = x.CancelReason,
createTime = x.CreateTime,
updateTime = x.UpdateTime
};
}
/// <summary>
/// 生成预约单号(Y + 时间戳 + 随机)
/// </summary>
private static string GenerateAppointmentNo()
{
var rnd = new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999);
return "Y" + DateTime.Now.ToString("yyyyMMddHHmmss") + rnd;
}
/// <summary>
/// 获取当前登录会员 Id
/// </summary>
private string GetCurrentMemberId()
{
var memberId = App.User?.FindFirstValue(ClaimConst.CLAINM_USERID);
if (string.IsNullOrWhiteSpace(memberId)) throw NCCException.Oh("未登录");
return memberId;
}
private static string FormatAppointDisplay(DateTime? appointDate, string timeSlot)
{
var datePart = appointDate?.ToString("yyyy-MM-dd") ?? string.Empty;
var slotPart = (timeSlot ?? string.Empty).Trim();
if (string.IsNullOrEmpty(datePart))
return slotPart;
if (string.IsNullOrEmpty(slotPart))
return datePart;
return $"{datePart} {slotPart}";
}
private static string ResolveMallAppointmentStatusText(int status)
{
if (global::System.Enum.IsDefined(typeof(MallAppointmentStatusEnum), status))
return ((MallAppointmentStatusEnum)status).GetDescription();
return status.ToString();
}
private async Task TryWriteBizLogAsync(
string actionCode,
string bizType,
string bizId,
string summary,
string detailJson)
{
try
{
await _log.WriteAsync("线上预约", actionCode, bizType, bizId, summary, detailJson);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "写入线上预约业务操作日志失败 action={Action}", actionCode);
}
}
#endregion
}
}