Merge branch 'feat-wallet' into development

This commit is contained in:
2024-11-14 15:44:01 +08:00
84 changed files with 2096 additions and 1784 deletions

View File

@@ -1,16 +1,12 @@
using Dlhis.Canteen.Setting.Services;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
namespace Dlhis.Canteen.Order.Services;
public abstract class BaseOrderService
{
private readonly ICanteenSettingService _canteenSettingService;
private readonly IDbContext _dbContext;
private readonly ICurrentUser _currentUser;
private readonly ILogger _logger;
@@ -21,7 +17,6 @@ public abstract class BaseOrderService
ICurrentUser currentUser,
ILogger logger)
{
_canteenSettingService = canteenSettingService;
_dbContext = dbContext;
_currentUser = currentUser;
_logger = logger;
@@ -32,37 +27,4 @@ public abstract class BaseOrderService
protected IDbContext DbContext => _dbContext;
protected ICurrentUser CurrentUser => _currentUser;
/// <summary>
/// 获取参数配置
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="userNo"></param>
/// <param name="tenantId"></param>
/// <param name="item"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
protected async Task<T> GetSettingAsync<T>(string userNo, string tenantId, CanteenSettingItemEnumType item, T defaultValue = default)
{
_settings ??= await _canteenSettingService.GetUserSettingAsync(userNo, tenantId);
if (_settings.TryGetValue(item, out var v))
{
try
{
if (int.TryParse(v, out var n))
{
return n.Adapt<T>();
}
return v.Adapt<T>();
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
}

View File

@@ -14,7 +14,7 @@ public interface IBalanceService : IScopeDependency
Task<Pagination<BalanceRecordResponse>> GetUserBalanceGroupAsync(BalanceRecordUserGroupPageRequest request);
Task SupplementBalanceAsync(BalanceSupplementRequest request);
@@ -40,6 +40,4 @@ public interface IBalanceService : IScopeDependency
Task ManuallyImportBalanceAndReCalcAsync(List<BalanceManuallyImportRequest> requests);
Task ReCalcAsync(string userCode);
}

View File

@@ -1,19 +1,20 @@
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Canteen.Order.Services;
public interface IOrderService : IScopeDependency
{
Task<OrderResultResponseWithLogs> AddAsync(OrderAddRequest request);
Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request);
/// <summary>
/// 设备消费
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task<OrderResultResponseWithLogs> DeviceConsume(OrderAddRequest request);
Task<DefaultApiResult<OrderResultResponse>> DeviceConsume(OrderAddRequest request);
Task<Pagination<OrderAggregationResponse>> GetOrdersAggregationAsync(PageDto page);
}

View File

@@ -1,4 +1,5 @@
using Dlhis.Basic.Api;
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Setting.Services;
@@ -29,6 +30,7 @@ public class BalanceService : IBalanceService
private readonly ITenantApi _tenantApi;
private readonly ICanteenSettingService _canteenSettingService;
private readonly RedisCache _redisCache;
private readonly IBalanceRepository _balanceRepository;
private readonly IBusinessPlacePermissionsApi _businessPlacePermissionsApi;
public BalanceService(IDbContext dbContext,
@@ -36,6 +38,7 @@ public class BalanceService : IBalanceService
ITenantApi tenantApi,
ICanteenSettingService canteenSettingService,
RedisCache redisCache,
IBalanceRepository balanceRepository,
IBusinessPlacePermissionsApi businessPlacePermissionsApi)
{
_dbContext = dbContext;
@@ -43,6 +46,7 @@ public class BalanceService : IBalanceService
_tenantApi = tenantApi;
_canteenSettingService = canteenSettingService;
_redisCache = redisCache;
_balanceRepository = balanceRepository;
_businessPlacePermissionsApi = businessPlacePermissionsApi;
}
@@ -123,11 +127,7 @@ public class BalanceService : IBalanceService
balanceRecord.Remark = "退款";
await _dbContext.UpdateAsync(balanceRecord);
if (balanceRecord.Source is BalanceRecordSourceEnumType.Face or BalanceRecordSourceEnumType.QrCode)
{
await ReCalcAsync(balanceRecord.UserCode);
}
else if (balanceRecord.Source == BalanceRecordSourceEnumType.EMealVoucher)
if (balanceRecord.Source == BalanceRecordSourceEnumType.EMealVoucher)
{
var originData = balanceRecord.UserNo.Split(":");
var eNo = originData[0];
@@ -324,39 +324,29 @@ public class BalanceService : IBalanceService
await _dbContext.Client.Ado.RollbackTranAsync();
throw;
}
await CommonHelper.RetryAsync(async () =>
{
var gainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == balanceInfo.UserCode).SingleAsync();
var balance = gainfoMeal.Balance + Math.Abs(balanceInfo.Amount) + request.Amount;
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Balance == balance)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == balanceInfo.UserCode && x.Version == gainfoMeal.Version)
.ExecuteCommandThrowVersionAsync();
}, 10);
}
public async Task<BalanceRecordUserResultResponse> GetPageByUserAsync(BalanceRecordUserPageRequest request)
{
var jinkoCode = _currentUser.GetUserClaim("jinko-code") ?? string.Empty;
var userCode = _currentUser.GetUserClaim("jinko-code") ?? string.Empty;
var factory = await _dbContext.Queryable<WalletEntity>().Where(x => x.Code == request.WalletCode).Select(x => x.Factory).FirstAsync();
var factories = await _balanceRepository.GetWalletFactoriesAsync(factory);
var page = await _dbContext.Queryable<BalanceRecordEntity>()
.LeftJoin<GainfoEntity>((record, ga) => record.UserNo == ga.No)
.LeftJoin<DepartmentEntity>((record, ga, department) => ga.DepartmentNo == department.No)
.LeftJoin<BusinessPlaceEntity>((record, ga, department, bPlace) => record.BusinessPlaceCode == bPlace.Code)
.Where((record, ga) => record.UserCode == jinkoCode)
.Where(record => record.Type == BalanceRecordTypeEnumType.Out && (record.Status == BalanceRecordStatusEnumType.Valid || record.Status == BalanceRecordStatusEnumType.Obsolute))
.Where(record => record.Source != BalanceRecordSourceEnumType.EMealVoucher)
.Where((record, ga) => record.UserCode == userCode && factories.Contains(record.TenantId))
.Where(record => record.Status == BalanceRecordStatusEnumType.Valid || record.Status == BalanceRecordStatusEnumType.Obsolute)
.Where(record => record.Source != BalanceRecordSourceEnumType.EMealVoucher) //不展示电子餐券信息
.WhereIF(request.SearchDateTimePeriod.HasValue(), record => record.CostDate >= request.SearchDateTimePeriod.Start && record.CostDate <= request.SearchDateTimePeriod.End)
.WhereIF(request.ApplicationType.HasValue, record => record.ApplicationType == request.ApplicationType)
.OrderBy(record => record.CostDateTime)
.Select((record, ga, department, bPlace) => new BalanceRecordUserPageResponse
{
Id = record.Id,
CurrentAmount = SqlFunc.Abs(record.Amount),
CurrentAmount = record.Amount,
Source = record.Source,
Status = record.Status,
No = SqlFunc.IIF(record.Status == BalanceRecordStatusEnumType.Obsolute, "(已退)" + record.No, record.No),
@@ -372,11 +362,11 @@ public class BalanceService : IBalanceService
var monthEnd = monthStart.AddMonths(1).AddSeconds(-1);
var monthSum = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.CostDateTime >= monthStart && x.CostDateTime <= monthEnd)
.Where(x => x.Type == BalanceRecordTypeEnumType.Out && x.Status == BalanceRecordStatusEnumType.Valid)
.Where(x => x.UserCode == userCode && factories.Contains(x.TenantId))
.Where(x => x.CostDate >= monthStart && x.CostDate <= monthEnd)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher)
.Where(x => x.UserCode == jinkoCode)
.SumAsync(x => SqlFunc.Abs(x.Amount));
.SumAsync(x => x.Amount);
return new BalanceRecordUserResultResponse
{
@@ -544,82 +534,10 @@ public class BalanceService : IBalanceService
Werks = gainfo.Werks,
IsDeleted = false
});
await CommonHelper.RetryAsync(async () =>
{
var gainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == gainfo.Code).FirstAsync();
if (gainfoMeal == null)
{
gainfoMeal = new GainfoMealEntity
{
UserCode = gainfo.Code,
Balance = 0,
BalanceOfRecharge = 0,
BalanceOfSubsidies = 0,
Version = 0
};
await _dbContext.InsertAsync(gainfoMeal);
}
//重新核算
var balance = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == gainfo.Code)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.SumAsync(x => x.Amount);
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Balance == balance)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == gainfoMeal.UserCode && x.Version == gainfoMeal.Version)
.ExecuteCommandThrowVersionAsync();
}, 5);
}
}
public async Task ReCalcAsync(string userCode)
{
await CommonHelper.RetryAsync(async () =>
{
var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == userCode).SingleAsync()
?? await _dbContext.Queryable<GainfoLeaveEntity>().Where(x => x.Code == userCode).SingleAsync();
gainfo.ThrowIfNull("档案不存在");
var gainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == gainfo.Code).FirstAsync();
if (gainfoMeal == null)
{
gainfoMeal = new GainfoMealEntity
{
UserCode = gainfo.Code,
Balance = 0,
BalanceOfRecharge = 0,
BalanceOfSubsidies = 0,
Version = 0
};
await _dbContext.InsertAsync(gainfoMeal);
}
//重新核算
var balance = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == gainfo.Code)
.Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.SumAsync(x => x.Amount);
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Balance == balance)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == gainfoMeal.UserCode && x.Version == gainfoMeal.Version)
.ExecuteCommandThrowVersionAsync();
}, 5);
}
/// <summary>
/// 获取离线设备
/// </summary>

View File

@@ -1,300 +1,302 @@
using Dlhis.Canteen.Dishes.Request;
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.Utils.Extensions;
using Kurisu.AspNetCore.Utils;
using Dlhis.Canteen.Setting.Services;
using Dlhis.Basic.Api;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using SqlSugar;
using Mapster;
namespace Dlhis.Canteen.Order.Services.Implements;
public class BookingOrderService : BaseOrderService, IBookingOrderService
{
private readonly IDishesMenuApi _dishesMenuApi;
private readonly IBusinessPlacePermissionsApi _businessPlacePermissionsApi;
public BookingOrderService(ICanteenSettingService canteenSettingService, IDbContext dbContext,
IDishesMenuApi dishesMenuApi,
IBusinessPlacePermissionsApi businessPlacePermissionsApi,
ICurrentUser currentUser, ILogger<BookingOrderService> logger)
: base(canteenSettingService, dbContext, currentUser, logger)
{
_dishesMenuApi = dishesMenuApi;
_businessPlacePermissionsApi = businessPlacePermissionsApi;
}
public async Task<BookingResponse> BookingAsync(BookingMealRequest request)
{
var gainfo = await CheckExistsMyBookingsAsync(request.BookingDate, request.ShiftType);
var businessPlace = await DbContext.Queryable<BusinessPlaceEntity>().Where(x => x.Code == request.BusinessPlaceCode).FirstAsync();
//预定时间
var now = DateTime.Now;
var bookingDeadline = await GetSettingAsync<TimeOnly?>(gainfo.No, businessPlace.TenantId, CanteenSettingItemEnumType.BookingDeadline) ?? new TimeOnly(20, 30, 00);
var dealLine = DateTime.Today.Add(bookingDeadline.ToTimeSpan());
(now >= dealLine).ThrowIfTrue("超出订餐时间");
//菜单存在
var menuDetailResult = await _dishesMenuApi.GetBookingDishesDetailAsync(request.BookingDate, request.BusinessPlaceCode, (int)request.ShiftType, request.DishesCode);
var menuDetail = menuDetailResult.Data;
menuDetail.ThrowIfNull("预定失败,菜品已经下架");
var order = new CanteenOrderEntity
{
RequestJson = request.ToJson(),
ThirdNo = string.Empty,
Type = BalanceRecordTypeEnumType.Out,
ApplicationType = CanteenApplicationTypeEnumType.Booking,
Name = gainfo.Name,
Source = request.Source,
UserNo = gainfo.No,
UserCode = gainfo.Code,
Amount = -Math.Abs(menuDetail.Price * request.Number),
BusinessPlaceCode = request.BusinessPlaceCode,
BusinessShiftCode = null,
ShiftType = request.ShiftType,
CostDate = now.Date,
CostId = gainfo.CostId,
DepartmentNo = gainfo.DepartmentNo,
DeviceUniqueNo = string.Empty,
DeliveryAddress = request.DeliveryAddress,
No = SnowFlakeHelper.Instance.NextId().ToString(),
IsOffline = false,
IsCostCrossTenant = await GetSettingAsync<bool>(gainfo.No, businessPlace.TenantId, CanteenSettingItemEnumType.AllowCrossTenant),
OriginTenantId = gainfo.Factory, //人员可能跨基地消费
Status = BalanceRecordStatusEnumType.Valid,
OrderStatus = CanteenOrderStatusEnumType.Success,
CostDateTime = now,
//标识当前消费的基地
TenantId = businessPlace.TenantId,
};
await DbContext.InsertAsync(order);
await CommonHelper.RetryAsync(async () =>
{
await _dishesMenuApi.GetBookingDishesDetailAsync(request.BookingDate, request.BusinessPlaceCode, (int)request.ShiftType, request.DishesCode);
menuDetail = menuDetailResult.Data;
menuDetail.ThrowIfNull("预定失败,菜品已经下架");
menuDetail.Number -= request.Number;
(menuDetail.Number < 0).ThrowIfTrue($"{menuDetail.DishesName}剩余数量不足");
//餐补
if (request.Source == BalanceRecordSourceEnumType.LocalTenantSubsidies)
{
var mealInfo = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).FirstAsync();
mealInfo.ThrowIfNull("余额不足,无法消费");
//金额+-
mealInfo.Balance += order.Amount;
(mealInfo.Balance < 0).ThrowIfTrue("余额不足,无法消费");
await DbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Balance == mealInfo.Balance)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == order.UserCode && x.Version == mealInfo.Version) //必须与查询时的version一致
.ExecuteCommandThrowVersionAsync();
}
await DbContext.Updateable<DishesMenuEntity>()
.SetColumns(x => x.Number == menuDetail.Number)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == now)
.Where(x => x.StartDate <= menuDetail.Date && menuDetail.Date <= x.EndDate
&& x.ShiftType == request.ShiftType
&& x.BusinessPlaceCode == request.BusinessPlaceCode
&& x.DishesCode == request.DishesCode
&& x.Version == menuDetail.Version
)
.ExecuteCommandThrowVersionAsync();
//写入记录
var balanceRecord = order.Adapt<BalanceRecordEntity>();
await DbContext.InsertAsync(balanceRecord);
await DbContext.InsertAsync(new CanteenOrderDetailEntity
{
OrderNo = order.No,
BookingDate = request.BookingDate,
DishesCode = request.DishesCode,
Price = menuDetail.Price,
Unit = request.Unit,
Number = request.Number,
TenantId = order.TenantId,
});
}, 10);
return new BookingResponse
{
No = order.No,
CreateTime = order.CreateTime,
Source = order.Source,
Amount = Math.Abs(order.Amount)
};
}
public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync(OrderBookingPageRequest request)
{
var myCodes = (await _businessPlacePermissionsApi.GetMyAsync()).Data.Select(x => (Guid?)x.Code).ToList();
var page = await DbContext.Queryable<CanteenOrderEntity>()
.LeftJoin<GainfoEntity>((x, ga) => x.UserNo == ga.No)
.LeftJoin<DepartmentEntity>((x, ga, dept) => dept.No == ga.DepartmentNo)
.Where(x => myCodes.Contains(x.BusinessPlaceCode))
.WhereIF(request.OrderStatus.HasValue, x => x.OrderStatus == request.OrderStatus)
.WhereIF(request.Source.HasValue, x => x.Source == request.Source)
.WhereIF(request.Search.IsPresent(), (x, ga) => x.UserCode == request.Search || ga.Name.Contains(request.Search))
.WhereIF(request.BookingPeriod?.Start.HasValue == true && request.BookingPeriod?.End.HasValue == true, x =>
SqlFunc.Subqueryable<CanteenOrderDetailEntity>()
.Where(p => p.OrderNo == x.No)
.Where(p => p.BookingDate >= request.BookingPeriod.Start)
.Where(p => p.BookingDate <= request.BookingPeriod.End)
.Any()
)
.WhereIF(request.ShiftType.HasValue, x => x.ShiftType == request.ShiftType)
.Select((x, ga, dept) => new OrderBookingResponse
{
No = x.No,
DeliveryAddress = x.DeliveryAddress,
Remark = x.Remark,
Amount = SqlFunc.Abs(x.Amount),
CreateTime = x.CreateTime,
ShiftType = x.ShiftType,
Status = x.OrderStatus,
UserCode = x.UserCode,
UserName = ga.Name,
Source = x.Source,
DepartmentName = dept.Name,
})
.ToPageListAsync(request);
var nos = page.Data.Select(x => x.No).ToList();
var details = await DbContext.Queryable<CanteenOrderDetailEntity>()
.LeftJoin<DishesEntity>((x, dishes) => x.DishesCode == dishes.CustomCode)
.Where(x => nos.Contains(x.OrderNo))
.Select((x, dishes) => new { x.OrderNo, x.BookingDate, x.Number, dishes.Name }).ToListAsync();
page.Data.ForEach(x =>
{
x.BookingDate = details.First(item => item.OrderNo == x.No).BookingDate;
x.TotalNumber = details.Where(item => item.OrderNo == x.No).Sum(item => item.Number);
x.DishesInfos = details.Where(item => item.OrderNo == x.No).Select(item => new
{
item.Name
})
.ToList();
});
return page;
}
public async Task UserCancelOrderAsync(OrderCancelRequest request)
{
var order = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.No == request.No).FirstAsync();
order.ThrowIfNull("订单不存在");
var bookingDeadline = await GetSettingAsync<TimeOnly?>(order.No, order.TenantId, CanteenSettingItemEnumType.BookingDeadline) ?? new TimeOnly(20, 30, 00);
var dealLine = DateTime.Today.Add(bookingDeadline.ToTimeSpan());
(DateTime.Now >= dealLine).ThrowIfTrue("不在订单取消允许范围内,不可操作");
await ManagerCancelOrderAsync(new OrderCancelRequest
{
No = request.No,
Reason = request.Reason,
});
}
public async Task ManagerCancelOrderAsync(OrderCancelRequest request)
{
var now = DateTime.Now;
var userId = CurrentUser.GetIntSubjectId();
var order = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.No == request.No).FirstAsync();
order.ThrowIfNull("订单不存在");
await DbContext.Updateable<CanteenOrderEntity>()
.SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Cancel)
.SetColumns(x => x.Remark == request.Reason)
.SetColumns(x => x.ModifiedTime == now)
.SetColumns(x => x.ModifiedBy == userId)
.Where(x => x.No == request.No)
.ExecuteCommandAsync();
await DbContext.Updateable<BalanceRecordEntity>()
.SetColumns(x => x.Status == BalanceRecordStatusEnumType.Obsolute)
.SetColumns(x => x.Remark == request.Reason)
.SetColumns(x => x.ModifiedTime == now)
.SetColumns(x => x.ModifiedBy == userId)
.Where(x => x.No == request.No)
.ExecuteCommandAsync();
if (order.Source == BalanceRecordSourceEnumType.LocalTenantSubsidies)
{
await CommonHelper.RetryAsync(async () =>
{
var mealInfo = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).FirstAsync();
var setBalance = mealInfo.Balance + Math.Abs(order.Amount);
await DbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Balance == setBalance)
.SetColumns(x => x.ModifiedTime == now)
.SetColumns(x => x.ModifiedBy == userId)
.Where(x => x.Id == mealInfo.Id && x.Version == mealInfo.Version)
.ExecuteCommandThrowVersionAsync();
}, 5);
}
}
/// <summary>
/// 检查我的订餐是否存在,存在抛出异常
/// </summary>
/// <param name="bookingDate"></param>
/// <param name="shiftType"></param>
/// <returns></returns>
private async Task<GainfoEntity> CheckExistsMyBookingsAsync(DateTime bookingDate, ShiftEnumType shiftType)
{
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 start = bookingDate.Date.AddDays(-1);
var end = start.AddDays(1).AddSeconds(-1);
var exists = await DbContext.Queryable<CanteenOrderEntity>()
.Where(x => x.ApplicationType == CanteenApplicationTypeEnumType.Booking)
.Where(x => x.OrderStatus == CanteenOrderStatusEnumType.Success)
.Where(x => x.ShiftType == shiftType)
.Where(x => x.UserNo == gainfo.No)
.Where(x => x.CreateTime >= start && x.CreateTime <= end)
.AnyAsync();
exists.ThrowIfTrue("不可重复订餐");
return gainfo;
}
}
// using Dlhis.Canteen.Dishes.Request;
// 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.Utils.Extensions;
// using Kurisu.AspNetCore.Utils;
// using Dlhis.Canteen.Setting.Services;
// using Dlhis.Basic.Api;
// using Kurisu.AspNetCore.Authentication.Abstractions;
// using Kurisu.AspNetCore.DataAccess.Dto;
// using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
// using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
// using SqlSugar;
// using Mapster;
//
// namespace Dlhis.Canteen.Order.Services.Implements;
//
// public class BookingOrderService : BaseOrderService, IBookingOrderService
// {
// private readonly ICanteenSettingService _canteenSettingService;
// private readonly IDishesMenuApi _dishesMenuApi;
// private readonly IBusinessPlacePermissionsApi _businessPlacePermissionsApi;
//
// public BookingOrderService(ICanteenSettingService canteenSettingService, IDbContext dbContext,
// IDishesMenuApi dishesMenuApi,
// IBusinessPlacePermissionsApi businessPlacePermissionsApi,
// ICurrentUser currentUser, ILogger<BookingOrderService> logger)
// : base(canteenSettingService, dbContext, currentUser, logger)
// {
// _canteenSettingService = canteenSettingService;
// _dishesMenuApi = dishesMenuApi;
// _businessPlacePermissionsApi = businessPlacePermissionsApi;
// }
//
// public async Task<BookingResponse> BookingAsync(BookingMealRequest request)
// {
// var gainfo = await CheckExistsMyBookingsAsync(request.BookingDate, request.ShiftType);
//
// var businessPlace = await DbContext.Queryable<BusinessPlaceEntity>().Where(x => x.Code == request.BusinessPlaceCode).FirstAsync();
//
// //预定时间
// var now = DateTime.Now;
//
// var bookingDeadline = await _canteenSettingService.GetSettingAsync(CanteenSettingItemEnumType.BookingDeadline, businessPlace.TenantId, gainfo.No, new TimeOnly(20, 30, 00));
// var dealLine = DateTime.Today.Add(bookingDeadline.ToTimeSpan());
// (now >= dealLine).ThrowIfTrue("超出订餐时间");
//
// //菜单存在
// var menuDetailResult = await _dishesMenuApi.GetBookingDishesDetailAsync(request.BookingDate, request.BusinessPlaceCode, (int)request.ShiftType, request.DishesCode);
// var menuDetail = menuDetailResult.Data;
// menuDetail.ThrowIfNull("预定失败,菜品已经下架");
//
// var order = new CanteenOrderEntity
// {
// RequestJson = request.ToJson(),
// ThirdNo = string.Empty,
// Type = BalanceRecordTypeEnumType.Out,
// ApplicationType = CanteenApplicationTypeEnumType.Booking,
// Name = gainfo.Name,
// Source = request.Source,
// UserNo = gainfo.No,
// UserCode = gainfo.Code,
// Amount = -Math.Abs(menuDetail.Price * request.Number),
// BusinessPlaceCode = request.BusinessPlaceCode,
// BusinessShiftCode = null,
// ShiftType = request.ShiftType,
// CostDate = now.Date,
// CostId = gainfo.CostId,
// DepartmentNo = gainfo.DepartmentNo,
// DeviceUniqueNo = string.Empty,
// DeliveryAddress = request.DeliveryAddress,
//
// No = SnowFlakeHelper.Instance.NextId().ToString(),
// IsOffline = false,
// IsCostCrossTenant = await _canteenSettingService.GetSettingAsync<bool>(CanteenSettingItemEnumType.AllowCrossTenant, businessPlace.TenantId, gainfo.No),
//
// OriginTenantId = gainfo.Factory, //人员可能跨基地消费
//
// Status = BalanceRecordStatusEnumType.Valid,
// OrderStatus = CanteenOrderStatusEnumType.Success,
//
// CostDateTime = now,
//
// //标识当前消费的基地
// TenantId = businessPlace.TenantId,
// };
//
// await DbContext.InsertAsync(order);
// await CommonHelper.RetryAsync(async () =>
// {
// await _dishesMenuApi.GetBookingDishesDetailAsync(request.BookingDate, request.BusinessPlaceCode, (int)request.ShiftType, request.DishesCode);
// menuDetail = menuDetailResult.Data;
// menuDetail.ThrowIfNull("预定失败,菜品已经下架");
// menuDetail.Number -= request.Number;
//
// (menuDetail.Number < 0).ThrowIfTrue($"{menuDetail.DishesName}剩余数量不足");
//
// //餐补
// if (request.Source == BalanceRecordSourceEnumType.LocalTenantSubsidies)
// {
// var mealInfo = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).FirstAsync();
// mealInfo.ThrowIfNull("余额不足,无法消费");
//
// //金额+-
// mealInfo.Balance += order.Amount;
// (mealInfo.Balance < 0).ThrowIfTrue("余额不足,无法消费");
//
// await DbContext.Updateable<GainfoMealEntity>()
// .SetColumns(x => x.Balance == mealInfo.Balance)
// .SetColumns(x => x.Version == x.Version + 1)
// .SetColumns(x => x.ModifiedTime == DateTime.Now)
// .Where(x => x.UserCode == order.UserCode && x.Version == mealInfo.Version) //必须与查询时的version一致
// .ExecuteCommandThrowVersionAsync();
// }
//
// await DbContext.Updateable<DishesMenuEntity>()
// .SetColumns(x => x.Number == menuDetail.Number)
// .SetColumns(x => x.Version == x.Version + 1)
// .SetColumns(x => x.ModifiedTime == now)
// .Where(x => x.StartDate <= menuDetail.Date && menuDetail.Date <= x.EndDate
// && x.ShiftType == request.ShiftType
// && x.BusinessPlaceCode == request.BusinessPlaceCode
// && x.DishesCode == request.DishesCode
// && x.Version == menuDetail.Version
// )
// .ExecuteCommandThrowVersionAsync();
//
// //写入记录
// var balanceRecord = order.Adapt<BalanceRecordEntity>();
// await DbContext.InsertAsync(balanceRecord);
//
// await DbContext.InsertAsync(new CanteenOrderDetailEntity
// {
// OrderNo = order.No,
// BookingDate = request.BookingDate,
// DishesCode = request.DishesCode,
// Price = menuDetail.Price,
// Unit = request.Unit,
// Number = request.Number,
// TenantId = order.TenantId,
// });
// }, 10);
//
//
// return new BookingResponse
// {
// No = order.No,
// CreateTime = order.CreateTime,
// Source = order.Source,
// Amount = Math.Abs(order.Amount)
// };
// }
//
//
// public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync(OrderBookingPageRequest request)
// {
// var myCodes = (await _businessPlacePermissionsApi.GetMyAsync()).Data.Select(x => (Guid?)x.Code).ToList();
//
// var page = await DbContext.Queryable<CanteenOrderEntity>()
// .LeftJoin<GainfoEntity>((x, ga) => x.UserNo == ga.No)
// .LeftJoin<DepartmentEntity>((x, ga, dept) => dept.No == ga.DepartmentNo)
// .Where(x => myCodes.Contains(x.BusinessPlaceCode))
// .WhereIF(request.OrderStatus.HasValue, x => x.OrderStatus == request.OrderStatus)
// .WhereIF(request.Source.HasValue, x => x.Source == request.Source)
// .WhereIF(request.Search.IsPresent(), (x, ga) => x.UserCode == request.Search || ga.Name.Contains(request.Search))
// .WhereIF(request.BookingPeriod?.Start.HasValue == true && request.BookingPeriod?.End.HasValue == true, x =>
// SqlFunc.Subqueryable<CanteenOrderDetailEntity>()
// .Where(p => p.OrderNo == x.No)
// .Where(p => p.BookingDate >= request.BookingPeriod.Start)
// .Where(p => p.BookingDate <= request.BookingPeriod.End)
// .Any()
// )
// .WhereIF(request.ShiftType.HasValue, x => x.ShiftType == request.ShiftType)
// .Select((x, ga, dept) => new OrderBookingResponse
// {
// No = x.No,
// DeliveryAddress = x.DeliveryAddress,
// Remark = x.Remark,
// Amount = SqlFunc.Abs(x.Amount),
// CreateTime = x.CreateTime,
// ShiftType = x.ShiftType,
// Status = x.OrderStatus,
// UserCode = x.UserCode,
// UserName = ga.Name,
// Source = x.Source,
// DepartmentName = dept.Name,
// })
// .ToPageListAsync(request);
//
// var nos = page.Data.Select(x => x.No).ToList();
// var details = await DbContext.Queryable<CanteenOrderDetailEntity>()
// .LeftJoin<DishesEntity>((x, dishes) => x.DishesCode == dishes.CustomCode)
// .Where(x => nos.Contains(x.OrderNo))
// .Select((x, dishes) => new { x.OrderNo, x.BookingDate, x.Number, dishes.Name }).ToListAsync();
//
// page.Data.ForEach(x =>
// {
// x.BookingDate = details.First(item => item.OrderNo == x.No).BookingDate;
// x.TotalNumber = details.Where(item => item.OrderNo == x.No).Sum(item => item.Number);
// x.DishesInfos = details.Where(item => item.OrderNo == x.No).Select(item => new
// {
// item.Name
// })
// .ToList();
// });
//
// return page;
// }
//
// public async Task UserCancelOrderAsync(OrderCancelRequest request)
// {
// var order = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.No == request.No).FirstAsync();
// order.ThrowIfNull("订单不存在");
//
// var bookingDeadline = await _canteenSettingService.GetSettingAsync(CanteenSettingItemEnumType.BookingDeadline, order.TenantId, order.No, new TimeOnly(20, 30, 00));
// var dealLine = DateTime.Today.Add(bookingDeadline.ToTimeSpan());
// (DateTime.Now >= dealLine).ThrowIfTrue("不在订单取消允许范围内,不可操作");
//
// await ManagerCancelOrderAsync(new OrderCancelRequest
// {
// No = request.No,
// Reason = request.Reason,
// });
// }
//
//
// public async Task ManagerCancelOrderAsync(OrderCancelRequest request)
// {
// var now = DateTime.Now;
// var userId = CurrentUser.GetIntSubjectId();
//
// var order = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.No == request.No).FirstAsync();
// order.ThrowIfNull("订单不存在");
//
// await DbContext.Updateable<CanteenOrderEntity>()
// .SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Cancel)
// .SetColumns(x => x.Remark == request.Reason)
// .SetColumns(x => x.ModifiedTime == now)
// .SetColumns(x => x.ModifiedBy == userId)
// .Where(x => x.No == request.No)
// .ExecuteCommandAsync();
//
// await DbContext.Updateable<BalanceRecordEntity>()
// .SetColumns(x => x.Status == BalanceRecordStatusEnumType.Obsolute)
// .SetColumns(x => x.Remark == request.Reason)
// .SetColumns(x => x.ModifiedTime == now)
// .SetColumns(x => x.ModifiedBy == userId)
// .Where(x => x.No == request.No)
// .ExecuteCommandAsync();
//
// if (order.Source == BalanceRecordSourceEnumType.LocalTenantSubsidies)
// {
// await CommonHelper.RetryAsync(async () =>
// {
// var mealInfo = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == order.UserCode).FirstAsync();
// var setBalance = mealInfo.Balance + Math.Abs(order.Amount);
// await DbContext.Updateable<GainfoMealEntity>()
// .SetColumns(x => x.Version == x.Version + 1)
// .SetColumns(x => x.Balance == setBalance)
// .SetColumns(x => x.ModifiedTime == now)
// .SetColumns(x => x.ModifiedBy == userId)
// .Where(x => x.Id == mealInfo.Id && x.Version == mealInfo.Version)
// .ExecuteCommandThrowVersionAsync();
// }, 5);
// }
// }
//
//
// /// <summary>
// /// 检查我的订餐是否存在,存在抛出异常
// /// </summary>
// /// <param name="bookingDate"></param>
// /// <param name="shiftType"></param>
// /// <returns></returns>
// private async Task<GainfoEntity> CheckExistsMyBookingsAsync(DateTime bookingDate, ShiftEnumType shiftType)
// {
// 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 start = bookingDate.Date.AddDays(-1);
// var end = start.AddDays(1).AddSeconds(-1);
//
// var exists = await DbContext.Queryable<CanteenOrderEntity>()
// .Where(x => x.ApplicationType == CanteenApplicationTypeEnumType.Booking)
// .Where(x => x.OrderStatus == CanteenOrderStatusEnumType.Success)
// .Where(x => x.ShiftType == shiftType)
// .Where(x => x.UserNo == gainfo.No)
// .Where(x => x.CreateTime >= start && x.CreateTime <= end)
// .AnyAsync();
//
// exists.ThrowIfTrue("不可重复订餐");
//
// return gainfo;
// }
// }

View File

@@ -1,3 +1,4 @@
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
@@ -8,12 +9,12 @@ namespace Dlhis.Canteen.Order.Services.Implements;
public class MiddleService : IMiddleService
{
private readonly IDbContext _dbContext;
private readonly IBalanceService _balanceService;
private readonly IBalanceRepository _balanceRepository;
public MiddleService(IDbContext dbContext, IBalanceService balanceService)
public MiddleService(IDbContext dbContext, IBalanceRepository balanceRepository)
{
_dbContext = dbContext;
_balanceService = balanceService;
_balanceRepository = balanceRepository;
}
/// <inheritdoc />
@@ -25,21 +26,21 @@ public class MiddleService : IMiddleService
if (!await _dbContext.Queryable<BalanceRecordEntity>().AnyAsync(x => x.No == entity.No))
{
await _dbContext.InsertAsync(entity);
await _balanceService.ReCalcAsync(entity.UserCode);
}
var balance = await _balanceRepository.GetBalanceAsync(entity.UserCode, string.Empty);
//获取人员余额
return 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 == entity.UserCode)
.Select((x, ga, department) => new OrderResultResponse
return await _dbContext.Queryable<GainfoEntity>()
.LeftJoin<DepartmentEntity>((x, department) => x.DepartmentNo == department.No)
.Where(x => x.Code == entity.UserCode)
.Select((x, department) => new OrderResultResponse
{
UserCode = ga.Code,
UserName = ga.Name,
DepartmentNo = ga.DepartmentNo,
UserCode = x.Code,
UserName = x.Name,
DepartmentNo = x.DepartmentNo,
DepartmentName = department.Name,
CurrentBalance = x.Balance
CurrentBalance = balance
})
.SingleAsync();
}

File diff suppressed because it is too large Load Diff