511 lines
20 KiB
C#
511 lines
20 KiB
C#
using Dlhis.Basic.Api;
|
|
using Dlhis.Canteen.Order.Repository;
|
|
using Dlhis.Canteen.Order.Request;
|
|
using Dlhis.Canteen.Order.Response;
|
|
using Dlhis.Canteen.Setting.Services;
|
|
using Dlhis.Constants;
|
|
using Dlhis.Entity.Basic.Entity;
|
|
using Dlhis.Entity.Canteen.Entities;
|
|
using Dlhis.Entity.Canteen.Enums;
|
|
using Dlhis.Entity.Device;
|
|
using Dlhis.Entity.Device.Entities;
|
|
using Kurisu.AspNetCore.Authentication.Abstractions;
|
|
using Kurisu.AspNetCore.Cache;
|
|
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;
|
|
using Kurisu.AspNetCore.Utils;
|
|
using Kurisu.AspNetCore.Utils.Extensions;
|
|
using Mapster;
|
|
using SqlSugar;
|
|
|
|
namespace Dlhis.Canteen.Order.Services.Implements;
|
|
|
|
public class OrderService : IOrderService
|
|
{
|
|
private readonly ICanteenSettingService _canteenSettingService;
|
|
private readonly IDbContext _dbContext;
|
|
private readonly ICurrentUser _currentUser;
|
|
private readonly IBalanceRepository _balanceRepository;
|
|
private readonly IOrderRepository _orderRepository;
|
|
private readonly RedisCache _redisCache;
|
|
private readonly IGainfoPermissionApi _gainfoPermissionApi;
|
|
private readonly IOrderCommonHandler _orderCommonHandler;
|
|
private readonly INamedResolver _namedResolver;
|
|
private readonly ILogger<OrderService> _logger;
|
|
|
|
public OrderService(ICanteenSettingService canteenSettingService,
|
|
IDbContext dbContext,
|
|
ICurrentUser currentUser,
|
|
IBalanceRepository balanceRepository,
|
|
IOrderRepository orderRepository,
|
|
RedisCache redisCache,
|
|
IGainfoPermissionApi gainfoPermissionApi,
|
|
IOrderCommonHandler orderCommonHandler,
|
|
INamedResolver namedResolver,
|
|
ILogger<OrderService> logger)
|
|
{
|
|
_canteenSettingService = canteenSettingService;
|
|
_dbContext = dbContext;
|
|
_currentUser = currentUser;
|
|
_balanceRepository = balanceRepository;
|
|
_orderRepository = orderRepository;
|
|
_redisCache = redisCache;
|
|
_gainfoPermissionApi = gainfoPermissionApi;
|
|
_orderCommonHandler = orderCommonHandler;
|
|
_namedResolver = namedResolver;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设备消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <returns></returns>
|
|
public async Task<DefaultApiResult<OrderResultResponse>> DeviceConsume(OrderAddRequest request)
|
|
{
|
|
return await AddAsync(request);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设备消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <returns></returns>
|
|
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
|
|
{
|
|
await _orderCommonHandler.SetDeviceIpInfoAsync(request.DeviceUniqueNo);
|
|
|
|
await using var handler = await _redisCache.LockAsync($"consume:device:{request.UserUniqueNo}");
|
|
handler.Acquired.ThrowIfFalse("请勿频繁消费");
|
|
|
|
var gainfo = await GetUserAsync(request);
|
|
return 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(UserClaimConstants.JinkoCode) ?? string.Empty;
|
|
if (jinkoCode.IsPresent())
|
|
{
|
|
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == jinkoCode).SingleAsync();
|
|
}
|
|
|
|
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 ************************************************************/
|
|
|
|
private async Task CheckPermissionAsync(string userCode, string deviceUniqueNo)
|
|
{
|
|
var data = await _gainfoPermissionApi.GetPermissionsDeviceCodesAsync(userCode);
|
|
|
|
var code = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).Select(x => x.Code).SingleAsync();
|
|
data.Contains(code).ThrowIfFalse("无权消费");
|
|
}
|
|
|
|
|
|
/// <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)
|
|
{
|
|
var flag = request.UserUniqueNo.Substring(0, 2);
|
|
switch (flag)
|
|
{
|
|
case QrCodeConstants.User:
|
|
{
|
|
gainfo = await GetUserByQrCodeAsync(request.UserUniqueNo);
|
|
await CheckPermissionAsync(gainfo.Code, request.DeviceUniqueNo);
|
|
}
|
|
break;
|
|
case QrCodeConstants.EMealVoucher:
|
|
{
|
|
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();
|
|
}
|
|
break;
|
|
case QrCodeConstants.Birthday:
|
|
{
|
|
request.Source = BalanceRecordSourceEnumType.Birthday;
|
|
var ticket = await _dbContext.Queryable<TicketEntity>().Where(x => x.Type == TicketEnumType.Birthday).Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
|
|
ticket.ThrowIfNull("无法识别");
|
|
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == ticket.UserCode).SingleAsync();
|
|
}
|
|
break;
|
|
|
|
default: throw new UserFriendlyException($"无法识别{request.UserUniqueNo}");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
//根据档案号
|
|
//区分userId和code: 工号纯数字避免跟userId相同导致查询到的消费人错误
|
|
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) //user id
|
|
.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="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 _balanceRepository.GetBalanceRecordsAsync(order.UserCode, order.TenantId, beginOfDay, endOfDay);
|
|
|
|
//超市营业点
|
|
var supermarketCodes = await _dbContext.Queryable<BusinessPlaceEntity>()
|
|
.Where(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
|
|
.Select(x => x.Code)
|
|
.ToListAsync();
|
|
|
|
//一天消费金额
|
|
var dayCostMax = await _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.DayCostMax, order.TenantId, order.UserNo);
|
|
if (dayCostMax != 0)
|
|
{
|
|
//消费记录一定会有营业点代码!.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 _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.OnceCostMax, order.TenantId, order.UserNo);
|
|
if (onceCostMax != 0)
|
|
{
|
|
(Math.Abs(order.Amount) > onceCostMax).ThrowIfTrue($"单次消费金额不能超出{onceCostMax}元");
|
|
}
|
|
|
|
//超市消费限额
|
|
if (order.BusinessPlaceCode.HasValue && supermarketCodes.Contains(order.BusinessPlaceCode.Value))
|
|
{
|
|
var dayMarketCostMax = await _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.DayMarketCostMax, order.TenantId, order.UserNo);
|
|
if (dayMarketCostMax != 0)
|
|
{
|
|
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 _canteenSettingService.GetSettingAsync(CanteenSettingItemEnumType.AllowRepeatInOneShift, order.TenantId, order.UserNo, true);
|
|
if (!allowRepeatInOneShift)
|
|
{
|
|
var costCount = todayAllBalanceRecords.Count(x => x.ShiftType == order.ShiftType);
|
|
(costCount > 1).ThrowIfTrue($"{order.ShiftType?.GetDescription()}不允许多次消费");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 离线消费处理
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="gainfo"></param>
|
|
private async Task OfflineHandleAsync(ConsumeRequest request, GainfoEntity gainfo)
|
|
{
|
|
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 == request.DeviceUniqueNo && x.BusinessPlaceCode.HasValue)
|
|
.Select((x, b, bs) => new
|
|
{
|
|
b.Code, bs.ShiftCode, Factory = b.TenantId
|
|
})
|
|
.SingleAsync();
|
|
|
|
|
|
//获取当前消费餐次
|
|
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>()
|
|
.Where(x => x.ShiftCode == bindingInfo.ShiftCode).ToListAsync();
|
|
|
|
var shift = shifts.FirstOrDefault(x =>
|
|
new TimePeriod
|
|
{
|
|
Start = x.Start,
|
|
End = x.End
|
|
}.IsPresent(request.CostDateTime)
|
|
);
|
|
|
|
var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, request.CostDateTime);
|
|
|
|
var order = new CanteenOrderEntity
|
|
{
|
|
RequestJson = request.ToJson(),
|
|
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
|
ThirdNo = request.ThirdNo,
|
|
IsOffline = request.IsOffline,
|
|
Type = BalanceRecordTypeEnumType.Out,
|
|
ApplicationType = CanteenApplicationTypeEnumType.Device,
|
|
Name = gainfo.Name,
|
|
Source = request.Source,
|
|
UserNo = gainfo.No,
|
|
UserCode = gainfo.Code,
|
|
Amount = request.Amount,
|
|
BusinessPlaceCode = bindingInfo.Code,
|
|
BusinessShiftCode = shift?.ShiftCode,
|
|
ShiftType = shift?.ShiftType,
|
|
CostDate = costDate.Date,
|
|
CostId = gainfo.CostId,
|
|
DepartmentNo = gainfo.DepartmentNo,
|
|
DeviceUniqueNo = request.DeviceUniqueNo,
|
|
|
|
IsCostCrossTenant = bindingInfo.Factory != gainfo.Factory,
|
|
|
|
OriginTenantId = gainfo.Factory,
|
|
Werks = gainfo.Werks,
|
|
|
|
Status = BalanceRecordStatusEnumType.Valid,
|
|
|
|
OrderStatus = CanteenOrderStatusEnumType.Success,
|
|
|
|
CostDateTime = request.CostDateTime,
|
|
|
|
//标识当前消费的基地
|
|
TenantId = bindingInfo.Factory,
|
|
};
|
|
|
|
await _dbContext.InsertAsync(order);
|
|
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
|
await _dbContext.InsertAsync(balanceRecord);
|
|
await _balanceRepository.CalculateBalanceAsync(balanceRecord.UserCode);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 消费
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="gainfo"></param>
|
|
/// <returns></returns>
|
|
private async Task ConsumeAsync(ConsumeRequest request, GainfoEntity gainfo)
|
|
{
|
|
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
|
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
|
|
|
|
if (request.Image.IsPresent())
|
|
{
|
|
await _dbContext.InsertAsync(new ImageRecordEntity
|
|
{
|
|
No = order.No,
|
|
TableName = "B",
|
|
Image = request.Image
|
|
});
|
|
}
|
|
|
|
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
|
|
{
|
|
//校验
|
|
await Verify(order);
|
|
|
|
await _balanceRepository.ConsumeBalanceAsync(order.UserCode, order.Amount);
|
|
|
|
//写入记录
|
|
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
|
await _dbContext.InsertAsync(balanceRecord);
|
|
});
|
|
}
|
|
|
|
|
|
// private async Task<DefaultApiResult<OrderResultResponse>> BirthdayConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
|
|
// {
|
|
//
|
|
// }
|
|
|
|
|
|
private async Task OfflineConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
|
|
{
|
|
try
|
|
{
|
|
if (request.ThirdNo.IsPresent())
|
|
{
|
|
await using var handler = await _redisCache.LockAsync($"consume:device-offline:{request.ThirdNo}");
|
|
if (handler.Acquired)
|
|
{
|
|
if (await ToCheckAbleOfflineConsumeAsync(request.ThirdNo))
|
|
{
|
|
await OfflineHandleAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
await OfflineHandleAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message);
|
|
}
|
|
}
|
|
|
|
/// <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;
|
|
|
|
var otherTypes = new[] { BalanceRecordSourceEnumType.EMealVoucher, BalanceRecordSourceEnumType.Birthday };
|
|
if (otherTypes.Contains(request.Source))
|
|
return await _namedResolver.GetService<IConsumeHandler>(request.Source.ToString()).ConsumeAsync(request, gainfo);
|
|
|
|
if (request.IsOffline)
|
|
await OfflineConsumeAsync(request, gainfo);
|
|
else
|
|
{
|
|
try
|
|
{
|
|
await ConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
message = ex.Message;
|
|
}
|
|
}
|
|
|
|
var balance = await _balanceRepository.GetBalanceAsync(gainfo.Code);
|
|
|
|
var data = await _dbContext.Queryable<GainfoEntity>()
|
|
.LeftJoin<DepartmentEntity>((x, department) => x.DepartmentNo == department.No)
|
|
.Where(x => x.Code == gainfo.Code)
|
|
.Select((x, department) => new OrderResultResponse
|
|
{
|
|
UserCode = x.Code,
|
|
UserName = x.Name,
|
|
DepartmentNo = x.DepartmentNo,
|
|
DepartmentName = department.Name,
|
|
|
|
CurrentBalance = balance,
|
|
CurrentTotalBalance = balance
|
|
})
|
|
.SingleAsync();
|
|
|
|
return new DefaultApiResult<OrderResultResponse>
|
|
{
|
|
Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
|
Data = data,
|
|
Msg = message
|
|
};
|
|
}
|
|
|
|
|
|
/// <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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检查是否能够进行离线消费,处理hpt重复提交
|
|
/// </summary>
|
|
/// <param name="thirdNo"></param>
|
|
/// <returns></returns>
|
|
private async Task<bool> ToCheckAbleOfflineConsumeAsync(string thirdNo)
|
|
{
|
|
var orders = await _dbContext.Queryable<CanteenOrderEntity>()
|
|
.Where(x => x.ThirdNo == thirdNo)
|
|
.OrderBy(x => x.CreateTime, OrderByType.Desc)
|
|
.ToListAsync();
|
|
|
|
if (orders.IsEmpty())
|
|
return true;
|
|
|
|
var order = orders.FirstOrDefault()!;
|
|
|
|
//存在在线order数据,但是状态未成功
|
|
return !order.IsOffline && order.OrderStatus != CanteenOrderStatusEnumType.Success;
|
|
}
|
|
} |