809 lines
31 KiB
C#
809 lines
31 KiB
C#
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 Kurisu.AspNetCore.Utils;
|
|
using Kurisu.AspNetCore.Utils.Extensions;
|
|
using Mapster;
|
|
using SqlSugar;
|
|
using Dlhis.Canteen.Order.Response;
|
|
using Dlhis.Canteen.Order.Request;
|
|
using Dlhis.Entity.Device;
|
|
using Kurisu.AspNetCore.Authentication.Abstractions;
|
|
using Kurisu.AspNetCore.CustomClass;
|
|
using Kurisu.AspNetCore.DataAccess.Dto;
|
|
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
|
|
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
|
using Kurisu.AspNetCore.UnifyResultAndValidation;
|
|
|
|
namespace Dlhis.Canteen.Order.Services.Implements;
|
|
|
|
public class OrderService : BaseOrderService, IOrderService
|
|
{
|
|
private readonly IServiceProvider _serviceProvider;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public OrderService(ICanteenSettingService canteenSettingService,
|
|
IDbContext dbContext,
|
|
ICurrentUser currentUser,
|
|
IServiceProvider serviceProvider,
|
|
IHttpContextAccessor httpContextAccessor,
|
|
ILogger<OrderService> logger)
|
|
: base(canteenSettingService, dbContext, currentUser, logger)
|
|
{
|
|
_serviceProvider = serviceProvider;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设备消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <returns></returns>
|
|
public async Task<OrderResultResponseWithLogs> DeviceConsume(OrderAddRequest request)
|
|
{
|
|
return await AddAsync(request);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设备消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <returns></returns>
|
|
public async Task<OrderResultResponseWithLogs> AddAsync(OrderAddRequest request)
|
|
{
|
|
try
|
|
{
|
|
if (_httpContextAccessor.HttpContext!.Request.Headers.TryGetValue("X-Requested-DeviceIp", out var ip))
|
|
{
|
|
var device = await DbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == request.DeviceUniqueNo).SingleAsync();
|
|
device.ConnectionInfo = new
|
|
{
|
|
ip = ip.ToString()
|
|
}.ToJson();
|
|
|
|
await DbContext.UpdateAsync(device);
|
|
}
|
|
|
|
Logger.LogInformation("设备IP获取:{deviceNo} {ip}", request.DeviceUniqueNo, ip);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
//ignore
|
|
}
|
|
|
|
var gainfo = await GetUserAsync(request);
|
|
|
|
return new OrderResultResponseWithLogs
|
|
{
|
|
Response = await ToDoAsync(request, gainfo)
|
|
};
|
|
}
|
|
|
|
|
|
public async Task<Pagination<OrderAggregationResponse>> GetOrdersAggregationAsync(PageDto page)
|
|
{
|
|
var subjectId = CurrentUser.GetIntSubjectId();
|
|
var gainfo = await DbContext.Queryable<GainfoEntity>().Where(x => x.IdentityUserId == subjectId).FirstAsync();
|
|
var jinkoCode = CurrentUser.GetUserClaim("jinko-code") ?? string.Empty;
|
|
if (jinkoCode.IsPresent())
|
|
{
|
|
gainfo = await DbContext.Queryable<GainfoEntity>().Where(x => x.Code == jinkoCode).FirstAsync();
|
|
}
|
|
|
|
var pageResult = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.UserNo == gainfo.No)
|
|
.LeftJoin<BusinessPlaceEntity>((x, bPlace) => x.BusinessPlaceCode == bPlace.Code)
|
|
.Where(x => x.ApplicationType == CanteenApplicationTypeEnumType.Booking)
|
|
.OrderBy(x => x.CreateTime, OrderByType.Desc)
|
|
.Select((x, bPlace) => new OrderAggregationResponse
|
|
{
|
|
No = x.No,
|
|
BusinessPlaceName = bPlace.Name,
|
|
CreateTime = x.CreateTime,
|
|
Remark = x.Remark,
|
|
OrderStatus = x.OrderStatus,
|
|
})
|
|
.ToPageListAsync(page);
|
|
|
|
var nos = pageResult.Data.Select(x => x.No).ToList();
|
|
var dtos = await DbContext.Queryable<CanteenOrderDetailEntity>()
|
|
.LeftJoin<DishesEntity>((x, d) => x.DishesCode == d.CustomCode)
|
|
.Where(x => nos.Contains(x.OrderNo))
|
|
.Select((x, d) => new DishesDto
|
|
{
|
|
No = x.OrderNo,
|
|
DishesCode = x.DishesCode,
|
|
Name = d.Name,
|
|
ImageUrl = d.ImageUrl,
|
|
Number = x.Number,
|
|
Price = x.Price,
|
|
})
|
|
.ToListAsync();
|
|
|
|
|
|
pageResult.Data.ForEach(item => { item.Dishes = dtos.Where(x => x.No == item.No).ToList(); });
|
|
|
|
return pageResult;
|
|
}
|
|
|
|
//******************************************************* help methods ************************************************************/
|
|
|
|
/// <summary>
|
|
/// 获取当前消费人员
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <returns></returns>
|
|
private async Task<GainfoEntity> GetUserAsync(OrderAddRequest request)
|
|
{
|
|
//尝试匹配userId
|
|
var s = long.TryParse(request.UserUniqueNo, out var userId);
|
|
GainfoEntity gainfo;
|
|
|
|
if (request.Source == BalanceRecordSourceEnumType.QrCode)
|
|
{
|
|
if (request.UserUniqueNo.StartsWith("01"))
|
|
{
|
|
gainfo = await GetUserByQrCodeAsync(request.UserUniqueNo);
|
|
}
|
|
else if (request.UserUniqueNo.StartsWith("02"))
|
|
{
|
|
request.Source = BalanceRecordSourceEnumType.EMealVoucher;
|
|
var eMealVoucherQrCode = await DbContext.Queryable<EMealVoucherDetailQrCodeEntity>().Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
|
|
eMealVoucherQrCode.ThrowIfNull("无法识别");
|
|
var code = eMealVoucherQrCode.OriginData.Split(':')[2];
|
|
gainfo = await DbContext.Queryable<GainfoEntity>().Where(x => x.Code == code).SingleAsync();
|
|
}
|
|
else
|
|
{
|
|
throw new UserFriendlyException($"无法识别{request.UserUniqueNo}");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
//根据档案号
|
|
gainfo = await DbContext.Queryable<GainfoEntity>()
|
|
.WhereIF(request.Source == BalanceRecordSourceEnumType.Card, x => x.CardNo == request.UserUniqueNo)
|
|
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && !request.IsUserId, x => x.Code == request.UserUniqueNo)
|
|
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && request.IsUserId && s, x => x.Id == userId)
|
|
.SingleAsync();
|
|
}
|
|
|
|
|
|
//在线
|
|
if (!request.IsOffline)
|
|
{
|
|
gainfo.ThrowIfNull("无法识别");
|
|
}
|
|
else
|
|
{
|
|
//兼容hpt尚未删除人员后产生的消费数据
|
|
gainfo ??= await DbContext.Queryable<GainfoEntity>().AS("GainfoLeave")
|
|
.WhereIF(request.Source == BalanceRecordSourceEnumType.Card, x => x.CardNo == request.UserUniqueNo)
|
|
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && !request.IsUserId, x => x.Code == request.UserUniqueNo)
|
|
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && request.IsUserId && s, x => x.IdentityUserId == userId)
|
|
.FirstAsync();
|
|
}
|
|
|
|
return gainfo;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 获取成本日期
|
|
/// </summary>
|
|
/// <param name="shift"></param>
|
|
/// <param name="costDateTime"></param>
|
|
/// <returns></returns>
|
|
private async Task<DateTime> GetCostDateAsync(BusinessShiftMealRelationshipEntity shift, DateTime costDateTime)
|
|
{
|
|
var switchTime = await GetSettingAsync<TimeOnly?>(string.Empty, shift.TenantId, CanteenSettingItemEnumType.BusinessSwitchTime);
|
|
|
|
var costDate = costDateTime.Date;
|
|
|
|
if (!switchTime.HasValue)
|
|
{
|
|
return costDate;
|
|
}
|
|
|
|
var beginOfDay = costDateTime.Date;
|
|
|
|
var setTime = beginOfDay.Add(switchTime.Value.ToTimeSpan());
|
|
if (costDateTime < setTime)
|
|
costDate = costDateTime.Date.AddDays(-1);
|
|
|
|
return costDate;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 验证参数
|
|
/// </summary>
|
|
/// <param name="order"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="UserFriendlyException"></exception>
|
|
private async Task Verify(CanteenOrderEntity order)
|
|
{
|
|
var beginOfDay = DateTime.Today;
|
|
var endOfDay = beginOfDay.AddDays(1).AddSeconds(-1);
|
|
|
|
//今天所有消费记录
|
|
var todayAllBalanceRecords = await DbContext.Queryable<BalanceRecordEntity>()
|
|
.Where(x => x.UserNo == order.UserNo)
|
|
.Where(x => x.Type == BalanceRecordTypeEnumType.Out)
|
|
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
|
|
.Where(x => x.CreateTime >= beginOfDay && x.CreateTime <= endOfDay)
|
|
.ToListAsync();
|
|
|
|
//超市营业点
|
|
var supermarketCodes = await DbContext.Queryable<BusinessPlaceEntity>()
|
|
.Where(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
|
|
.Select(x => x.Code)
|
|
.ToListAsync();
|
|
|
|
//一天消费金额
|
|
var dayCostMax = await GetSettingAsync<decimal>(order.UserNo, order.TenantId, CanteenSettingItemEnumType.DayCostMax);
|
|
if (dayCostMax != default)
|
|
{
|
|
//消费记录一定会有营业点代码!.Value是安全用法
|
|
var cost = todayAllBalanceRecords
|
|
.Where(x => !supermarketCodes.Contains(x.BusinessPlaceCode!.Value)) //filter supermarket
|
|
.Sum(x => Math.Abs(x.Amount));
|
|
|
|
(cost + Math.Abs(order.Amount) > dayCostMax).ThrowIfTrue($"超出当天消费限制{dayCostMax}元,无法消费");
|
|
}
|
|
|
|
//一次消费金额
|
|
var onceCostMax = await GetSettingAsync<decimal>(order.UserNo, order.TenantId, CanteenSettingItemEnumType.OnceCostMax);
|
|
if (onceCostMax != default)
|
|
{
|
|
(Math.Abs(order.Amount) > onceCostMax).ThrowIfTrue($"单次消费金额不能超出{onceCostMax}元");
|
|
}
|
|
|
|
//超市消费限额
|
|
if (order.BusinessPlaceCode.HasValue && supermarketCodes.Contains(order.BusinessPlaceCode.Value))
|
|
{
|
|
var dayMarketCostMax = await GetSettingAsync<decimal>(order.UserNo, order.TenantId, CanteenSettingItemEnumType.DayMarketCostMax);
|
|
if (dayMarketCostMax != default)
|
|
{
|
|
var cost = todayAllBalanceRecords.Where(x => x.BusinessPlaceCode.HasValue)
|
|
.Where(x => supermarketCodes.Contains(x.BusinessPlaceCode.Value))
|
|
.Sum(x => Math.Abs(x.Amount));
|
|
|
|
(cost + Math.Abs(order.Amount) > dayMarketCostMax).ThrowIfTrue($"超出当天超市消费限制{dayMarketCostMax},无法消费");
|
|
}
|
|
}
|
|
|
|
//重复餐次消费
|
|
var allowRepeatInOneShift = await GetSettingAsync(order.UserNo, order.TenantId, CanteenSettingItemEnumType.AllowRepeatInOneShift, true);
|
|
if (!allowRepeatInOneShift)
|
|
{
|
|
var costCount = todayAllBalanceRecords.Count(x => x.ShiftType == order.ShiftType);
|
|
(costCount > 1).ThrowIfTrue($"{order.ShiftType?.GetDescription()}不允许多次消费");
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 生成充值记录
|
|
/// </summary>
|
|
/// <param name="orderId"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="UserFriendlyException"></exception>
|
|
/// <exception cref="VersionExceptions"></exception>
|
|
private async Task GenerateConsumeRecordAsync(long orderId)
|
|
{
|
|
var order = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.Id == orderId).SingleAsync();
|
|
//校验
|
|
await Verify(order);
|
|
|
|
await CommonHelper.RetryAsync(async () =>
|
|
{
|
|
var gainfoMeal = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).SingleAsync();
|
|
//金额+-
|
|
gainfoMeal.Balance += order.Amount;
|
|
(gainfoMeal.Balance < 0).ThrowIfTrue("余额不足,无法消费");
|
|
|
|
await DbContext.Updateable<GainfoMealEntity>()
|
|
.SetColumns(x => x.Balance == gainfoMeal.Balance)
|
|
.SetColumns(x => x.Version == x.Version + 1)
|
|
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
|
.Where(x => x.UserCode == order.UserCode && x.Version == gainfoMeal.Version) //必须与查询时的version一致
|
|
.ExecuteCommandThrowVersionAsync();
|
|
|
|
//写入记录
|
|
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
|
await DbContext.InsertAsync(balanceRecord);
|
|
}, 5);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 离线消费处理
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="gainfo"></param>
|
|
private async Task HandleOfflineAsync(ConsumeRequest request, GainfoEntity gainfo)
|
|
{
|
|
var registry = await DbContext.Queryable<DeviceRegistryEntity>()
|
|
.Where(x => x.DeviceUniqueNo == request.DeviceUniqueNo)
|
|
.FirstAsync();
|
|
|
|
var businessPlaceInfo = await DbContext.Queryable<BusinessPlaceEntity>()
|
|
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, sr) => x.Code == sr.PlaceCode)
|
|
.Where(x => x.Code == registry.BusinessPlaceCode)
|
|
.Select((x, sr) => new
|
|
{
|
|
x.Code,
|
|
sr.ShiftCode,
|
|
x.TenantId
|
|
})
|
|
.FirstAsync();
|
|
|
|
//获取当前消费餐次
|
|
var shifts = await DbContext.Queryable<BusinessShiftMealRelationshipEntity>().Where(x => x.ShiftCode == businessPlaceInfo.ShiftCode).ToListAsync();
|
|
|
|
var shift = shifts.FirstOrDefault(x => new TimePeriod()
|
|
{
|
|
Start = x.Start,
|
|
End = x.End
|
|
}.IsPresent(request.CostDateTime));
|
|
|
|
var costDate = await GetCostDateAsync(shift, request.CostDateTime);
|
|
|
|
var order = new CanteenOrderEntity
|
|
{
|
|
RequestJson = request.ToJson(),
|
|
ThirdNo = request.ThirdNo,
|
|
Type = BalanceRecordTypeEnumType.Out,
|
|
ApplicationType = CanteenApplicationTypeEnumType.Device,
|
|
Name = gainfo.Name,
|
|
Source = request.Source,
|
|
UserNo = gainfo.No,
|
|
UserCode = gainfo.Code,
|
|
Amount = request.Amount,
|
|
BusinessPlaceCode = businessPlaceInfo?.Code,
|
|
BusinessShiftCode = shift?.ShiftCode,
|
|
ShiftType = shift?.ShiftType,
|
|
CostDate = costDate.Date,
|
|
CostId = gainfo.CostId,
|
|
DepartmentNo = gainfo.DepartmentNo,
|
|
DeviceUniqueNo = request.DeviceUniqueNo,
|
|
|
|
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
|
IsOffline = request.IsOffline,
|
|
IsCostCrossTenant = businessPlaceInfo!.TenantId != gainfo.Factory,
|
|
|
|
OriginTenantId = gainfo.Factory,
|
|
Werks = gainfo.Werks,
|
|
|
|
Status = BalanceRecordStatusEnumType.Valid,
|
|
|
|
OrderStatus = CanteenOrderStatusEnumType.Success,
|
|
|
|
CostDateTime = request.CostDateTime,
|
|
|
|
//标识当前消费的基地
|
|
TenantId = businessPlaceInfo!.TenantId,
|
|
};
|
|
|
|
|
|
await DbContext.InsertReturnIdentityAsync(order);
|
|
|
|
await CommonHelper.RetryAsync(async () =>
|
|
{
|
|
var redisCache = _serviceProvider.GetService<RedisCache>();
|
|
await using var handler = await redisCache.LockAsync($"gainfo:meal:{order.UserNo}", retryInterval: TimeSpan.FromSeconds(1));
|
|
if (handler.Acquired)
|
|
{
|
|
var gainfoMeal = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).FirstAsync();
|
|
if (gainfoMeal == null)
|
|
{
|
|
gainfoMeal = new GainfoMealEntity
|
|
{
|
|
Balance = 0,
|
|
BalanceOfRecharge = 0,
|
|
BalanceOfSubsidies = 0,
|
|
Version = 0,
|
|
UserCode = order.UserCode,
|
|
};
|
|
|
|
await DbContext.InsertAsync(gainfoMeal);
|
|
}
|
|
|
|
//金额+-
|
|
gainfoMeal.Balance += order.Amount;
|
|
|
|
await DbContext.Updateable<GainfoMealEntity>()
|
|
.SetColumns(x => x.Balance == gainfoMeal.Balance)
|
|
.SetColumns(x => x.Version == x.Version + 1)
|
|
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
|
.Where(x => x.UserCode == order.UserCode && x.Version == gainfoMeal.Version) //必须与查询时的version一致
|
|
.ExecuteCommandThrowVersionAsync();
|
|
|
|
//写入记录
|
|
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
|
await DbContext.InsertAsync(balanceRecord);
|
|
}
|
|
}, 5);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="gainfo"></param>
|
|
/// <returns></returns>
|
|
private async Task ConsumeAsync(ConsumeRequest request, GainfoEntity gainfo)
|
|
{
|
|
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
|
|
|
//(request.Source == BalanceRecordSourceEnumType.QrCode && checkData.BusinessPlaceTenantId != gainfo.Factory).ThrowIfTrue("禁止跨厂区消费");
|
|
|
|
var order = new CanteenOrderEntity
|
|
{
|
|
RequestJson = request.ToJson(),
|
|
ThirdNo = request.ThirdNo,
|
|
Type = BalanceRecordTypeEnumType.Out,
|
|
ApplicationType = CanteenApplicationTypeEnumType.Device,
|
|
Name = gainfo.Name,
|
|
Source = request.Source,
|
|
UserNo = gainfo.No,
|
|
UserCode = gainfo.Code,
|
|
Amount = request.Amount,
|
|
BusinessPlaceCode = checkData.BusinessPlaceCode,
|
|
BusinessShiftCode = checkData.BusinessShiftCode,
|
|
ShiftType = checkData.Shift.ShiftType,
|
|
CostDate = checkData.CostDate,
|
|
CostId = gainfo.CostId,
|
|
DepartmentNo = gainfo.DepartmentNo,
|
|
DeviceUniqueNo = request.DeviceUniqueNo,
|
|
|
|
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
|
IsOffline = request.IsOffline,
|
|
IsCostCrossTenant = gainfo.Factory != checkData.BusinessPlaceTenantId,
|
|
|
|
OriginTenantId = gainfo.Factory,
|
|
Werks = gainfo.Werks,
|
|
Status = BalanceRecordStatusEnumType.Valid,
|
|
|
|
OrderStatus = CanteenOrderStatusEnumType.Wait,
|
|
|
|
CostDateTime = request.CostDateTime,
|
|
|
|
//标识当前消费的基地
|
|
TenantId = checkData.BusinessPlaceTenantId
|
|
};
|
|
|
|
var orderId = await DbContext.InsertReturnIdentityAsync(order);
|
|
|
|
try
|
|
{
|
|
await GenerateConsumeRecordAsync(orderId);
|
|
|
|
if (request.Image.IsPresent())
|
|
{
|
|
await DbContext.InsertAsync(new ImageRecordEntity
|
|
{
|
|
No = order.No,
|
|
TableName = "B",
|
|
Image = request.Image
|
|
});
|
|
}
|
|
|
|
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.Result == ex.Message)
|
|
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
|
.Where(x => x.Id == orderId)
|
|
.ExecuteCommandAsync();
|
|
|
|
throw;
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 分支处理在线/离线消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="gainfo"></param>
|
|
/// <returns></returns>
|
|
private async Task<DefaultApiResult<OrderResultResponse>> ToDoAsync(OrderAddRequest request, GainfoEntity gainfo)
|
|
{
|
|
var message = string.Empty;
|
|
|
|
if (request.Source == BalanceRecordSourceEnumType.EMealVoucher)
|
|
{
|
|
var eMealVoucherQrCode = await DbContext.Queryable<EMealVoucherDetailQrCodeEntity>().Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
|
|
if (eMealVoucherQrCode == null)
|
|
{
|
|
message = "无法识别";
|
|
return new DefaultApiResult<OrderResultResponse>
|
|
{
|
|
Code = ApiStateCode.Error,
|
|
Data = null,
|
|
Msg = message
|
|
};
|
|
}
|
|
|
|
var originData = eMealVoucherQrCode.OriginData.Split(':');
|
|
|
|
var no = originData[0];
|
|
var ts = originData[1];
|
|
var idNo = originData[3];
|
|
|
|
try
|
|
{
|
|
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, eMealVoucherQrCode.OriginData, no, ts, idNo);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
message = ex.Message;
|
|
}
|
|
|
|
//获取餐券余额
|
|
var data = await DbContext.Queryable<EMealVoucherEntity>()
|
|
.LeftJoin<EMealVoucherDetailEntity>((x, d) => x.No == d.No)
|
|
.Where((x, d) => d.IdNo == idNo)
|
|
.Select((x, d) => new OrderResultResponse
|
|
{
|
|
CurrentBalance = d.Balance
|
|
})
|
|
.SingleAsync();
|
|
|
|
return new DefaultApiResult<OrderResultResponse>
|
|
{
|
|
Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
|
Data = data,
|
|
Msg = message
|
|
};
|
|
}
|
|
else
|
|
{
|
|
if (request.IsOffline)
|
|
{
|
|
if (request.ThirdNo.IsPresent())
|
|
{
|
|
var redisCache = _serviceProvider.GetService<RedisCache>();
|
|
|
|
await using var handler = await redisCache.LockAsync($"consume:device:{request.ThirdNo}");
|
|
if (handler.Acquired && await ToCheckAbleOfflineConsumeAsync(request.ThirdNo))
|
|
{
|
|
try
|
|
{
|
|
await HandleOfflineAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
await HandleOfflineAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
(await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == gainfo.Code).AnyAsync()).ThrowIfFalse("就餐余额不足");
|
|
await ConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
message = ex.Message;
|
|
}
|
|
}
|
|
|
|
//获取人员余额
|
|
var data = await DbContext.Queryable<GainfoMealEntity>()
|
|
.LeftJoin<GainfoEntity>((x, ga) => x.UserCode == ga.Code)
|
|
.LeftJoin<DepartmentEntity>((x, ga, department) => ga.DepartmentNo == department.No)
|
|
.Where(x => x.UserCode == gainfo.Code)
|
|
.Select((x, ga, department) => new OrderResultResponse
|
|
{
|
|
UserCode = ga.Code,
|
|
UserName = ga.Name,
|
|
DepartmentNo = ga.DepartmentNo,
|
|
DepartmentName = department.Name,
|
|
CurrentBalance = x.Balance
|
|
})
|
|
.SingleAsync();
|
|
|
|
return new DefaultApiResult<OrderResultResponse>
|
|
{
|
|
Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
|
Data = data,
|
|
Msg = message
|
|
};
|
|
}
|
|
|
|
async Task<bool> ToCheckAbleOfflineConsumeAsync(string thirdNo)
|
|
{
|
|
var order = await DbContext.Queryable<CanteenOrderEntity>()
|
|
.Where(x => x.ThirdNo == thirdNo)
|
|
.OrderBy(x => x.CreateTime, OrderByType.Desc)
|
|
.FirstAsync();
|
|
|
|
if (order == null)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
//存在在线order数据,但是状态未成功
|
|
return !order.IsOffline && order.OrderStatus != CanteenOrderStatusEnumType.Success;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据二维码获取消费用户
|
|
/// </summary>
|
|
/// <param name="qrCode"></param>
|
|
/// <returns></returns>
|
|
private async Task<GainfoEntity> GetUserByQrCodeAsync(string qrCode)
|
|
{
|
|
var gainfoQrCode = await DbContext.Queryable<GainfoQrCodeEntity>().Where(x => x.QrCode == qrCode).SingleAsync();
|
|
gainfoQrCode.ThrowIfNull("消费码已过期");
|
|
(gainfoQrCode.ModifiedTime.AddMinutes(60) < DateTime.Now).ThrowIfTrue("消费码已过期");
|
|
|
|
return await DbContext.Queryable<GainfoEntity>().Where(x => x.Code == gainfoQrCode.UserCode).SingleAsync();
|
|
}
|
|
|
|
private async Task EMealVoucherConsumeAsync(ConsumeRequest request, GainfoEntity gainfo, string originData, string no, string ts, string idNo)
|
|
{
|
|
var nowDate = DateTime.Now.Date;
|
|
var current = await DbContext.Queryable<EMealVoucherDetailEntity>()
|
|
.Where(x => x.No == no && x.IdNo == idNo).SingleAsync();
|
|
(nowDate >= current.Start && nowDate <= current.End).ThrowIfFalse("餐券已过期");
|
|
|
|
var time = DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(ts.Reverse().Join(string.Empty))).ToLocalTime().DateTime;
|
|
(time.AddMinutes(60) >= DateTime.Now).ThrowIfFalse("餐券二维码已过期");
|
|
|
|
var eMealVoucher = await DbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
|
|
|
|
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
|
eMealVoucher.Factories.Contains(checkData.BusinessPlaceTenantId).ThrowIfFalse("禁止在当前厂区消费");
|
|
|
|
var order = new CanteenOrderEntity
|
|
{
|
|
RequestJson = request.ToJson(),
|
|
ThirdNo = request.ThirdNo,
|
|
Type = BalanceRecordTypeEnumType.Out,
|
|
ApplicationType = CanteenApplicationTypeEnumType.Device,
|
|
Name = gainfo.Name,
|
|
Source = request.Source,
|
|
UserNo = originData, //记录为当前消费券
|
|
UserCode = gainfo.Code,
|
|
Amount = request.Amount,
|
|
BusinessPlaceCode = checkData.BusinessPlaceCode,
|
|
BusinessShiftCode = checkData.BusinessShiftCode,
|
|
ShiftType = checkData.Shift.ShiftType,
|
|
CostDate = checkData.CostDate,
|
|
CostId = gainfo.CostId,
|
|
DepartmentNo = gainfo.DepartmentNo,
|
|
DeviceUniqueNo = request.DeviceUniqueNo,
|
|
|
|
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
|
IsOffline = false,
|
|
IsCostCrossTenant = gainfo.Factory != checkData.BusinessPlaceTenantId,
|
|
|
|
OriginTenantId = gainfo.Factory,
|
|
Werks = gainfo.Werks,
|
|
Status = BalanceRecordStatusEnumType.Valid,
|
|
OrderStatus = CanteenOrderStatusEnumType.Wait,
|
|
CostDateTime = request.CostDateTime,
|
|
//标识当前消费的基地
|
|
TenantId = checkData.BusinessPlaceTenantId,
|
|
};
|
|
|
|
var orderId = await DbContext.InsertReturnIdentityAsync(order);
|
|
|
|
try
|
|
{
|
|
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>();
|
|
await DbContext.InsertAsync(balanceRecord);
|
|
}, 5);
|
|
|
|
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.Result == ex.Message)
|
|
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
|
.Where(x => x.Id == orderId)
|
|
.ExecuteCommandAsync();
|
|
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 消费前预检
|
|
/// </summary>
|
|
/// <param name="deviceUniqueNo"></param>
|
|
/// <param name="costDateTime"></param>
|
|
/// <returns></returns>
|
|
private async Task<OrderPreCheckDto> PreCheckAsync(string deviceUniqueNo, DateTime costDateTime)
|
|
{
|
|
var registry = await DbContext.Queryable<DeviceRegistryEntity>().Where(x => x.DeviceUniqueNo == deviceUniqueNo).SingleAsync();
|
|
registry.ThrowIfNull("设备尚未登记");
|
|
|
|
var device = await DbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).SingleAsync();
|
|
device.ThrowIfNull("设备尚未登记");
|
|
device.Enable.ThrowIfFalse("设备已被停用");
|
|
|
|
var businessPlaceInfo = await DbContext.Queryable<BusinessPlaceEntity>()
|
|
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, sr) => x.Code == sr.PlaceCode)
|
|
.Where(x => x.Code == registry.BusinessPlaceCode)
|
|
.Select((x, sr) => new
|
|
{
|
|
x.Code,
|
|
sr.ShiftCode,
|
|
x.TenantId
|
|
})
|
|
.SingleAsync();
|
|
|
|
businessPlaceInfo.ThrowIfNull("设备尚未登记营业点");
|
|
|
|
//获取当前消费餐次
|
|
var shifts = await DbContext.Queryable<BusinessShiftMealRelationshipEntity>().Where(x => x.ShiftCode == businessPlaceInfo.ShiftCode).ToListAsync();
|
|
shifts.ThrowIfEmpty("营业点餐次尚未设置");
|
|
|
|
var shift = shifts.FirstOrDefault(x => new TimePeriod
|
|
{
|
|
Start = x.Start,
|
|
End = x.End
|
|
}.IsPresent(costDateTime));
|
|
shift.ThrowIfNull("非就餐时间,无法消费");
|
|
|
|
var costDate = await GetCostDateAsync(shift, costDateTime);
|
|
|
|
return new OrderPreCheckDto
|
|
{
|
|
CostDate = costDate,
|
|
Shift = shift,
|
|
BusinessPlaceTenantId = businessPlaceInfo.TenantId,
|
|
BusinessPlaceCode = businessPlaceInfo.Code,
|
|
BusinessShiftCode = businessPlaceInfo.ShiftCode
|
|
};
|
|
}
|
|
} |