feat 优化消费过程
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
using Dlhis.Canteen.Order.Repository;
|
||||
using Dlhis.Canteen.Order.Request;
|
||||
using Dlhis.Canteen.Order.Response;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.UnifyResultAndValidation;
|
||||
using Kurisu.AspNetCore.Utils;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
using Mapster;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// 生日券消费处理
|
||||
/// </summary>
|
||||
[Service(nameof(BalanceRecordSourceEnumType.Birthday))]
|
||||
public class BirthdayConsumeHandler : IConsumeHandler
|
||||
{
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly IOrderCommonHandler _orderCommonHandler;
|
||||
private readonly IOrderRepository _orderRepository;
|
||||
|
||||
public BirthdayConsumeHandler(IDbContext dbContext,
|
||||
IOrderCommonHandler orderCommonHandler,
|
||||
IOrderRepository orderRepository)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_orderCommonHandler = orderCommonHandler;
|
||||
_orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
public async Task<DefaultApiResult<OrderResultResponse>> ConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
|
||||
{
|
||||
var msg = string.Empty;
|
||||
var ticketNo = request.UserUniqueNo;
|
||||
|
||||
var exists = await _dbContext.Queryable<TicketEntity>()
|
||||
.Where(x => x.Type == TicketEnumType.Birthday)
|
||||
.Where(x => x.QrCode == ticketNo)
|
||||
.AnyAsync();
|
||||
|
||||
exists.ThrowIfFalse("生日券无效");
|
||||
|
||||
try
|
||||
{
|
||||
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime!.Value);
|
||||
var isSupermarket = await _dbContext.Queryable<BusinessPlaceEntity>()
|
||||
.Where(x => x.Code == checkData.BusinessPlaceCode)
|
||||
.Select(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
|
||||
.SingleAsync();
|
||||
|
||||
isSupermarket.ThrowIfFalse("请在超市消费");
|
||||
|
||||
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request.Adapt<ConsumeRequest>(), gainfo);
|
||||
|
||||
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
|
||||
{
|
||||
await CommonHelper.RetryAsync(async () =>
|
||||
{
|
||||
var ticket = await _dbContext.Queryable<TicketEntity>()
|
||||
.Where(x => x.Type == TicketEnumType.Birthday)
|
||||
.Where(x => x.QrCode == ticketNo)
|
||||
.SingleAsync();
|
||||
|
||||
//金额+-
|
||||
ticket.Balance += order.Amount;
|
||||
(ticket.Balance < 0).ThrowIfTrue("余额不足,无法消费");
|
||||
|
||||
await _dbContext.Updateable<TicketEntity>()
|
||||
.SetColumns(x => x.Balance == ticket.Balance)
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.Where(x => x.QrCode == ticketNo && x.Version == ticket.Version) //必须与查询时的version一致
|
||||
.ExecuteCommandThrowVersionAsync();
|
||||
|
||||
//写入记录
|
||||
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
||||
balanceRecord.Remark = $"{ticket.QrCode}(生日券消费)";
|
||||
await _dbContext.InsertAsync(balanceRecord);
|
||||
}, 5);
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
msg = ex.Message;
|
||||
}
|
||||
|
||||
//获取餐券余额
|
||||
var data = await _dbContext.Queryable<TicketEntity>()
|
||||
.LeftJoin<GainfoEntity>((x, ga) => x.UserCode == ga.Code)
|
||||
.Where(x => x.Type == TicketEnumType.Birthday && x.QrCode == ticketNo)
|
||||
.Select((x, ga) => new OrderResultResponse
|
||||
{
|
||||
UserCode = x.UserCode,
|
||||
UserName = ga.Name,
|
||||
CurrentBalance = x.Balance
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
||||
Data = data,
|
||||
Msg = msg
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Dlhis.Canteen.Order.Repository;
|
||||
using Dlhis.Canteen.Order.Request;
|
||||
using Dlhis.Canteen.Order.Response;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.UnifyResultAndValidation;
|
||||
using Kurisu.AspNetCore.Utils;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
using Mapster;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// 电子餐券处理
|
||||
/// </summary>
|
||||
[Service(nameof(BalanceRecordSourceEnumType.EMealVoucher))]
|
||||
public class EMealVoucherHandler : IConsumeHandler
|
||||
{
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly IOrderRepository _orderRepository;
|
||||
private readonly IOrderCommonHandler _orderCommonHandler;
|
||||
|
||||
public EMealVoucherHandler(IDbContext dbContext,
|
||||
IOrderRepository orderRepository,
|
||||
IOrderCommonHandler orderCommonHandler)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_orderRepository = orderRepository;
|
||||
_orderCommonHandler = orderCommonHandler;
|
||||
}
|
||||
|
||||
public async Task<DefaultApiResult<OrderResultResponse>> ConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
|
||||
{
|
||||
var msg = string.Empty;
|
||||
var originData = await _dbContext.Queryable<EMealVoucherDetailQrCodeEntity>()
|
||||
.Where(x => x.QrCode == request.UserUniqueNo)
|
||||
.Select(x => x.OriginData)
|
||||
.SingleAsync();
|
||||
|
||||
if (originData.IsEmpty())
|
||||
{
|
||||
msg = "无法识别";
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
Code = ApiStateCode.Error,
|
||||
Data = null,
|
||||
Msg = msg
|
||||
};
|
||||
}
|
||||
|
||||
var originDataItems = originData.Split(":");
|
||||
var no = originDataItems[0];
|
||||
var idNo = originDataItems[3];
|
||||
|
||||
try
|
||||
{
|
||||
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, originData, no, idNo);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
msg = ex.Message;
|
||||
}
|
||||
|
||||
//获取餐券余额
|
||||
var data = await _dbContext.Queryable<EMealVoucherEntity>()
|
||||
.LeftJoin<EMealVoucherDetailEntity>((x, d) => x.No == d.No)
|
||||
.Where((x, d) => x.No == no && d.IdNo == idNo)
|
||||
.Select((x, d) => new OrderResultResponse
|
||||
{
|
||||
UserCode = d.IdNo,
|
||||
UserName = d.Name,
|
||||
CurrentBalance = d.Balance
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
try
|
||||
{
|
||||
var v = data.UserCode ?? string.Empty;
|
||||
var vc = v.ToCharArray().Reverse().ToList();
|
||||
|
||||
for (int i = 0; i < vc.Count; i++)
|
||||
{
|
||||
if (i + 1 > 4)
|
||||
{
|
||||
vc[i] = '*';
|
||||
}
|
||||
}
|
||||
|
||||
vc.Reverse();
|
||||
data.UserCode = string.Join("", vc);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//ignore
|
||||
}
|
||||
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
||||
Data = data,
|
||||
Msg = msg
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 电子餐券消费
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="gainfo"></param>
|
||||
/// <param name="originData"></param>
|
||||
/// <param name="no"></param>
|
||||
/// <param name="idNo"></param>
|
||||
private async Task EMealVoucherConsumeAsync(ConsumeRequest request, GainfoEntity gainfo, string originData, string no, string idNo)
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
|
||||
var current = await _dbContext.Queryable<EMealVoucherDetailEntity>()
|
||||
.Where(x => x.No == no && x.IdNo == idNo)
|
||||
.Select(x => new { x.Name, x.Start, x.End })
|
||||
.SingleAsync();
|
||||
|
||||
(now >= current.Start && now <= current.End).ThrowIfFalse("餐券已过期");
|
||||
|
||||
var eMealVoucher = await _dbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
|
||||
|
||||
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
||||
var isSupermarket = await _dbContext.Queryable<BusinessPlaceEntity>()
|
||||
.Where(x => x.Code == checkData.BusinessPlaceCode)
|
||||
.Select(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
|
||||
.SingleAsync();
|
||||
|
||||
isSupermarket.ThrowIfTrue("禁止在超市消费");
|
||||
|
||||
eMealVoucher.Factories.Contains(checkData.Factory).ThrowIfFalse("禁止在当前厂区消费");
|
||||
|
||||
gainfo.No = originData;
|
||||
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
|
||||
|
||||
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
|
||||
{
|
||||
await CommonHelper.RetryAsync(async () =>
|
||||
{
|
||||
var detail = await _dbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.No == no && x.IdNo == idNo).SingleAsync();
|
||||
//金额+-
|
||||
detail.Balance += order.Amount;
|
||||
(detail.Balance < 0).ThrowIfTrue("余额不足,无法消费");
|
||||
|
||||
await _dbContext.Updateable<EMealVoucherDetailEntity>()
|
||||
.SetColumns(x => x.Balance == detail.Balance)
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.Where(x => x.No == no && x.IdNo == idNo && x.Version == detail.Version) //必须与查询时的version一致
|
||||
.ExecuteCommandThrowVersionAsync();
|
||||
|
||||
//写入记录
|
||||
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
||||
balanceRecord.Remark = $"({no})" + current.Name;
|
||||
await _dbContext.InsertAsync(balanceRecord);
|
||||
}, 5);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using Dlhis.Canteen.Order.Dto;
|
||||
using Dlhis.Canteen.Setting.Services;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
using Dlhis.Entity.Device.Entities;
|
||||
using Dlhis.Entity.Device.Enums;
|
||||
using Kurisu.AspNetCore.CustomClass;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// 订单通用处理
|
||||
/// </summary>
|
||||
public class OrderCommonHandler : IOrderCommonHandler
|
||||
{
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly ICanteenSettingService _canteenSettingService;
|
||||
private readonly ILogger<OrderCommonHandler> _logger;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public OrderCommonHandler(IDbContext dbContext,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
ICanteenSettingService canteenSettingService,
|
||||
ILogger<OrderCommonHandler> logger)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_canteenSettingService = canteenSettingService;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置设备ip
|
||||
/// </summary>
|
||||
/// <param name="deviceNo"></param>
|
||||
public async Task SetDeviceIpInfoAsync(string deviceNo)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_httpContextAccessor.HttpContext!.Request.Headers.TryGetValue("X-Requested-DeviceIp", out var ip))
|
||||
{
|
||||
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceNo).SingleAsync();
|
||||
device.ConnectionInfo = new
|
||||
{
|
||||
ip = ip.ToString()
|
||||
}.ToJson();
|
||||
|
||||
await _dbContext.UpdateAsync(device);
|
||||
}
|
||||
|
||||
_logger.LogInformation("设备ip获取:{deviceNo} {ip}", deviceNo, ip);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//ignore
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 消费前预检
|
||||
/// </summary>
|
||||
/// <param name="deviceUniqueNo">设备号</param>
|
||||
/// <param name="costDateTime">消费时间</param>
|
||||
/// <returns></returns>
|
||||
public async Task<OrderCheckResultDto> PreCheckAsync(string deviceUniqueNo, DateTime costDateTime)
|
||||
{
|
||||
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).SingleAsync();
|
||||
device.ThrowIfNull("设备尚未登记");
|
||||
device.Enable.ThrowIfFalse("设备已被停用");
|
||||
(device.Type != DeviceTypeEnumType.Meal).ThrowIfTrue("设备类型有误");
|
||||
|
||||
var bindingInfo = await _dbContext.Queryable<DeviceRegistryEntity>()
|
||||
.LeftJoin<BusinessPlaceEntity>((x, b) => x.BusinessPlaceCode == b.Code)
|
||||
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, b, bs) => bs.PlaceCode == b.Code)
|
||||
.Where(x => x.DeviceUniqueNo == deviceUniqueNo && x.BusinessPlaceCode.HasValue)
|
||||
.Select((x, b, bs) => new
|
||||
{
|
||||
b.Code,
|
||||
bs.ShiftCode,
|
||||
Factory = x.TenantId
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
bindingInfo.ThrowIfNull("设备尚未登记营业点");
|
||||
|
||||
//获取当前消费餐次
|
||||
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>()
|
||||
.Where(x => x.ShiftCode == bindingInfo.ShiftCode)
|
||||
.Select(x => new { x.ShiftType, x.Start, x.End })
|
||||
.ToListAsync();
|
||||
shifts.ThrowIfEmpty("营业点餐次尚未设置");
|
||||
|
||||
var shift = shifts.FirstOrDefault(x => new TimePeriod
|
||||
{
|
||||
Start = x.Start,
|
||||
End = x.End
|
||||
}.IsPresent(costDateTime));
|
||||
shift.ThrowIfNull("非就餐时间");
|
||||
|
||||
var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, costDateTime);
|
||||
|
||||
return new OrderCheckResultDto
|
||||
{
|
||||
Factory = bindingInfo.Factory,
|
||||
CostDate = costDate,
|
||||
ShiftType = shift!.ShiftType,
|
||||
BusinessPlaceCode = bindingInfo.Code,
|
||||
BusinessShiftCode = bindingInfo.ShiftCode
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 消费更新处理
|
||||
/// </summary>
|
||||
/// <param name="orderId"></param>
|
||||
/// <param name="action"></param>
|
||||
public async Task TryConsumeAsync(long orderId, Func<Task> action)
|
||||
{
|
||||
try
|
||||
{
|
||||
await action();
|
||||
|
||||
await _dbContext.Updateable<CanteenOrderEntity>()
|
||||
.SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Success)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.Where(x => x.Id == orderId)
|
||||
.ExecuteCommandAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dbContext.Updateable<CanteenOrderEntity>()
|
||||
.SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Failure)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.SetColumns(x => x.Result == ex.Message)
|
||||
.Where(x => x.Id == orderId)
|
||||
.ExecuteCommandAsync();
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user