add 消费处理完成
This commit is contained in:
@@ -39,7 +39,9 @@ public class SysDataService : ISysDataService
|
||||
case "GainfoMeal":
|
||||
{
|
||||
var codes = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Factory == factory).Select(x => x.Code).ToListAsync();
|
||||
return await _dbContext.Queryable<GainfoMealEntity>().Where(x => codes.Contains(x.UserCode)).Select(x => (object)x).ToListAsync();
|
||||
return null;
|
||||
//todo 余额
|
||||
///return await _dbContext.Queryable<GainfoMealEntity>().Where(x => codes.Contains(x.UserCode)).Select(x => (object)x).ToListAsync();
|
||||
}
|
||||
default:
|
||||
return await _dbContext.Client.SqlQueryable<object>(sql).ToListAsync();
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using Dlhis.Basic.Organization.Response;
|
||||
using Dlhis.Basic.Organization.Services;
|
||||
using Kurisu.AspNetCore.DataAccess.Dto;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -33,15 +32,4 @@ public class GainfoMealController : ControllerBase
|
||||
{
|
||||
return await _mealUserService.GetPageAsync(request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 迁移
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
[Transactional]
|
||||
[HttpPost("migration")]
|
||||
public async Task MigrationAsync(GainfoBalanceMigrationRequest request)
|
||||
{
|
||||
await _mealUserService.MigrationAsync(request);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace Dlhis.Basic.Organization.Response;
|
||||
|
||||
public class GainfoCurrentMealInfoResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 余额
|
||||
/// </summary>
|
||||
public decimal Balance { get; set; }
|
||||
}
|
||||
@@ -62,9 +62,4 @@ public class GainfoCurrentResponse
|
||||
/// 卡类型名称
|
||||
/// </summary>
|
||||
public string CardTypeName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 就餐信息
|
||||
/// </summary>
|
||||
public GainfoCurrentMealInfoResponse MealInfo { get; set; }
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public class GainfoMealResponse
|
||||
/// <summary>
|
||||
/// 餐补总额
|
||||
/// </summary>
|
||||
public decimal? MealSupplementAmount { get; set; }
|
||||
public decimal MealSupplementAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 档案状态
|
||||
|
||||
@@ -7,6 +7,4 @@ namespace Dlhis.Basic.Organization.Services;
|
||||
public interface IGainfoMealService : IScopeDependency
|
||||
{
|
||||
Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request);
|
||||
|
||||
Task MigrationAsync(GainfoBalanceMigrationRequest request);
|
||||
}
|
||||
@@ -9,7 +9,6 @@ using Kurisu.AspNetCore.CustomClass;
|
||||
using Kurisu.AspNetCore.DataAccess.Dto;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.Utils;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
using SqlSugar;
|
||||
|
||||
@@ -28,138 +27,47 @@ public class GainfoMealService : IGainfoMealService
|
||||
|
||||
public async Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request)
|
||||
{
|
||||
var tenantId = _currentUser.GetStringTenantId();
|
||||
var factory = _currentUser.GetStringTenantId();
|
||||
var factories = await GetWalletFactoriesAsync(_currentUser.GetStringTenantId());
|
||||
|
||||
var page = await _dbContext.Queryable<GainfoMealEntity>()
|
||||
.LeftJoin<GainfoEntity>((meal, gainfo) => meal.UserCode == gainfo.Code)
|
||||
.LeftJoin<GainfoLeaveEntity>((meal, gainfo, gainfoLeave) => meal.UserCode == gainfoLeave.Code)
|
||||
.LeftJoin<DepartmentEntity>((meal, gainfo, gainfoLeave, dept1) => dept1.No == gainfo.DepartmentNo)
|
||||
.LeftJoin<DepartmentEntity>((meal, gainfo, gainfoLeave, dept1, dept2) => dept2.No == gainfoLeave.DepartmentNo)
|
||||
.WhereIF(request.Search.IsPresent(), (meal, gainfo, gainfoLeave, dept1, dept2) => meal.UserCode == request.Search
|
||||
|| gainfo.Name == request.Search
|
||||
|| gainfoLeave.Name == request.Search)
|
||||
.Where((meal, gainfo, gainfoLeave) => gainfo.Factory == tenantId || gainfoLeave.Factory == tenantId)
|
||||
.WhereIF(request.IsLeave, (meal, gainfo, gainfoLeave) => SqlFunc.Subqueryable<GainfoLeaveEntity>().Where(x => x.Code == meal.UserCode).Any())
|
||||
.WhereIF(request.IsLeave && request.SearchDateTimePeriod.HasValue(), (meal, gainfo, gainfoLeave) => gainfoLeave.ResignationDate >= request.SearchDateTimePeriod.Start && gainfoLeave.ResignationDate <= request.SearchDateTimePeriod.End)
|
||||
.Select((meal, gainfo, gainfoLeave, dept1, dept2) => new GainfoMealResponse
|
||||
return await _dbContext.Queryable<GainfoEntity>().AS(request.IsLeave ? "GainfoLeave" : "Gainfo")
|
||||
.LeftJoin<DepartmentEntity>((x, dept) => dept.No == x.DepartmentNo)
|
||||
.WhereIF(request.Search.IsPresent(), x => x.Code == request.Search || x.Name == request.Search)
|
||||
.Where(x => x.Factory == factory)
|
||||
.WhereIF(request.IsLeave && request.SearchDateTimePeriod.HasValue(), x => x.ResignationDate >= request.SearchDateTimePeriod.Start &&
|
||||
x.ResignationDate <= request.SearchDateTimePeriod.End)
|
||||
.Select((x, dept) => new GainfoMealResponse
|
||||
{
|
||||
Balance = meal.Balance,
|
||||
UserCode = meal.UserCode,
|
||||
UserName = SqlFunc.IsNull(gainfo.Name, gainfoLeave.Name),
|
||||
UserNo = SqlFunc.IsNull(gainfo.No, gainfoLeave.No),
|
||||
DepartmentName = SqlFunc.IsNull(dept1.Name, dept2.Name),
|
||||
Status = SqlFunc.IsNullOrEmpty(gainfo.No) ? GainfoStatusEnumType.Leave : GainfoStatusEnumType.Working
|
||||
UserCode = x.Code,
|
||||
UserName = x.Name,
|
||||
UserNo = x.No,
|
||||
DepartmentName = dept.Name,
|
||||
Status = request.IsLeave
|
||||
? GainfoStatusEnumType.Leave
|
||||
: GainfoStatusEnumType.Working,
|
||||
MealSupplementAmount = SqlFunc.Subqueryable<MealSupplementRecordEntity>()
|
||||
.Where(p => p.Code == x.Code)
|
||||
.Where(p => factories.Contains(p.Factory))
|
||||
.WhereIF(request.SearchDateTimePeriod.HasValue(), p => p.Date >= request.SearchDateTimePeriod.Start && p.Date <= request.SearchDateTimePeriod.End)
|
||||
.Sum(p => p.Amount),
|
||||
Balance = SqlFunc.Subqueryable<BalanceRecordEntity>()
|
||||
.Where(p => factories.Contains(p.TenantId))
|
||||
.Where(p => p.UserCode == x.Code && p.Status == BalanceRecordStatusEnumType.Valid && p.IsDeleted == false)
|
||||
.Where(p => p.Source != BalanceRecordSourceEnumType.EMealVoucher)
|
||||
.Sum(p => p.Amount)
|
||||
})
|
||||
.ToPageListAsync(request);
|
||||
|
||||
var userCodes = page.Data.Select(x => x.UserCode).ToList();
|
||||
var summary = await _dbContext.Queryable<MealSupplementRecordEntity>()
|
||||
.Where(x => userCodes.Contains(x.Code))
|
||||
.WhereIF(request.SearchDateTimePeriod.HasValue(), x => x.Date >= request.SearchDateTimePeriod.Start && x.Date <= request.SearchDateTimePeriod.End)
|
||||
.GroupBy(x => x.Code)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Code,
|
||||
Amount = SqlFunc.AggregateSum(x.Amount)
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
page.Data.ForEach(x => { x.MealSupplementAmount = summary.FirstOrDefault(item => item.Code == x.UserCode)?.Amount ?? 0; });
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
public async Task MigrationAsync(GainfoBalanceMigrationRequest request)
|
||||
|
||||
//***********************************************************************************************************************************************************************
|
||||
|
||||
|
||||
public async Task<List<string>> GetWalletFactoriesAsync(string factory)
|
||||
{
|
||||
//只能针对离职人员
|
||||
var gainfoLeave = await _dbContext.Queryable<GainfoLeaveEntity>().Where(x => x.Code == request.BeforeCode).SingleAsync();
|
||||
gainfoLeave.ThrowIfNull("需要对已离职人员迁移");
|
||||
var wallets = await _dbContext.Queryable<WalletEntity>().ToListAsync();
|
||||
var code = wallets.First(x => x.Factory == factory).Code;
|
||||
|
||||
var beforeBalance = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.BeforeCode).Select(x => x.Balance).SingleAsync();
|
||||
(beforeBalance <= 0).ThrowIfTrue("不可操作,余额不足");
|
||||
|
||||
var now = DateTime.Now;
|
||||
|
||||
await _dbContext.InsertAsync(new BalanceRecordEntity
|
||||
{
|
||||
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
||||
UserNo = gainfoLeave.No,
|
||||
Name = gainfoLeave.Name,
|
||||
UserCode = gainfoLeave.Code,
|
||||
DepartmentNo = gainfoLeave.DepartmentNo,
|
||||
Source = BalanceRecordSourceEnumType.BalanceMigration,
|
||||
Type = BalanceRecordTypeEnumType.In,
|
||||
Amount = -Math.Abs(beforeBalance),
|
||||
BusinessPlaceCode = null,
|
||||
BusinessShiftCode = null,
|
||||
ShiftType = null,
|
||||
CostDate = now.Date,
|
||||
DeviceUniqueNo = null,
|
||||
IP = null,
|
||||
CostId = gainfoLeave.CostId,
|
||||
OriginTenantId = gainfoLeave.Factory,
|
||||
IsCostCrossTenant = false,
|
||||
Status = BalanceRecordStatusEnumType.Valid,
|
||||
CostDateTime = DateTime.Now,
|
||||
Remark = $"{gainfoLeave.Code}:余额转出",
|
||||
ApplicationType = CanteenApplicationTypeEnumType.BalanceMigration,
|
||||
TenantId = gainfoLeave.Factory,
|
||||
Werks = gainfoLeave.Werks,
|
||||
IsDeleted = false,
|
||||
});
|
||||
|
||||
var beforeBalanceAmount = await _dbContext.Queryable<BalanceRecordEntity>()
|
||||
.Where(x => x.UserCode == gainfoLeave.Code)
|
||||
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
|
||||
.SumAsync(x => x.Amount);
|
||||
|
||||
await _dbContext.Updateable<GainfoMealEntity>()
|
||||
.SetColumns(x => x.Balance == beforeBalanceAmount)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.Where(x => x.UserCode == request.BeforeCode) //不需要判断version
|
||||
.ExecuteCommandAsync();
|
||||
|
||||
//转移到现有人员
|
||||
var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == request.NowCode).SingleAsync();
|
||||
gainfo.ThrowIfNull("目标人员不存在");
|
||||
|
||||
await _dbContext.InsertAsync(new BalanceRecordEntity
|
||||
{
|
||||
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
||||
UserNo = gainfo.No,
|
||||
Name = gainfo.Name,
|
||||
UserCode = gainfo.Code,
|
||||
DepartmentNo = gainfo.DepartmentNo,
|
||||
Source = BalanceRecordSourceEnumType.BalanceMigration,
|
||||
Type = BalanceRecordTypeEnumType.In,
|
||||
Amount = beforeBalance,
|
||||
BusinessPlaceCode = null,
|
||||
BusinessShiftCode = null,
|
||||
ShiftType = null,
|
||||
CostDate = now.Date,
|
||||
DeviceUniqueNo = null,
|
||||
IP = null,
|
||||
CostId = gainfo.CostId,
|
||||
OriginTenantId = gainfo.Factory,
|
||||
IsCostCrossTenant = false,
|
||||
Status = BalanceRecordStatusEnumType.Valid,
|
||||
CostDateTime = DateTime.Now,
|
||||
Remark = $"{gainfoLeave.Code}:余额转入",
|
||||
ApplicationType = CanteenApplicationTypeEnumType.MealSupplement,
|
||||
TenantId = gainfo.Factory,
|
||||
Werks = gainfo.Werks,
|
||||
IsDeleted = false,
|
||||
});
|
||||
|
||||
var nowGainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.NowCode).SingleAsync();
|
||||
var nowBalance = nowGainfoMeal.Balance + beforeBalance;
|
||||
|
||||
await _dbContext.Updateable<GainfoMealEntity>()
|
||||
.SetColumns(x => x.Balance == nowBalance)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.Where(x => x.UserCode == request.NowCode && x.Version == nowGainfoMeal.Version)
|
||||
.ExecuteCommandThrowVersionAsync("转入失败");
|
||||
return wallets.Where(x => x.Code == code).Select(x => x.Factory).ToList();
|
||||
}
|
||||
}
|
||||
@@ -197,10 +197,9 @@ public class GainfoService : IGainfoService
|
||||
|
||||
var info = await _gainfoStore.Queryable(GainfoStatusEnumType.Working)
|
||||
.LeftJoin<DepartmentEntity>((ga, department) => ga.DepartmentNo == department.No)
|
||||
.LeftJoin<GainfoMealEntity>((ga, department, mealUser) => ga.Code == mealUser.UserCode)
|
||||
.LeftJoin<BasicTypeEntity>((ga, department, mealUser, type) => type.Code == ga.CardType.ToString() && type.Type == "timeperiod")
|
||||
.LeftJoin<BasicTypeEntity>((ga, department, type) => type.Code == ga.CardType.ToString() && type.Type == "timeperiod")
|
||||
.Where((ga, department) => ga.Id == gainfo.Id)
|
||||
.Select((ga, department, mealUser, type) => new GainfoCurrentResponse
|
||||
.Select((ga, department, type) => new GainfoCurrentResponse
|
||||
{
|
||||
UserNo = ga.No,
|
||||
Birthday = ga.Birthday,
|
||||
@@ -210,10 +209,6 @@ public class GainfoService : IGainfoService
|
||||
UserCode = ga.Code,
|
||||
UserName = ga.Name,
|
||||
Factory = ga.Factory,
|
||||
MealInfo = new GainfoCurrentMealInfoResponse
|
||||
{
|
||||
Balance = mealUser.Balance
|
||||
},
|
||||
CardType = ga.CardType,
|
||||
CardTypeName = type.Display
|
||||
}).SingleAsync();
|
||||
|
||||
@@ -187,37 +187,6 @@ public class MealSupplementRecordService : IMealSupplementRecordService
|
||||
DepartmentNo = gainfo.DepartmentNo,
|
||||
DeviceUniqueNo = null
|
||||
});
|
||||
|
||||
await CommonHelper.RetryAsync(async () =>
|
||||
{
|
||||
var mealUser = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.Code).FirstAsync();
|
||||
if (mealUser == null)
|
||||
{
|
||||
mealUser = new GainfoMealEntity
|
||||
{
|
||||
UserCode = gainfo.Code,
|
||||
Balance = 0,
|
||||
BalanceOfRecharge = 0,
|
||||
BalanceOfSubsidies = 0,
|
||||
Version = 0
|
||||
};
|
||||
|
||||
await _dbContext.InsertAsync(mealUser);
|
||||
}
|
||||
|
||||
//重新核算
|
||||
var balance = await _dbContext.Queryable<BalanceRecordEntity>()
|
||||
.Where(x => x.UserCode == request.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 == mealUser.UserCode && x.Version == mealUser.Version)
|
||||
.ExecuteCommandThrowVersionAsync();
|
||||
}, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,36 +167,4 @@ public class BalancesController : ControllerBase
|
||||
{
|
||||
await _balanceService.ManuallyImportBalanceAndReCalcAsync(requests);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 重算
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
[Authorize(Roles = "admin")]
|
||||
[HttpPost("recalc")]
|
||||
[IgnoreTenant]
|
||||
[Transactional(IsolationLevel.ReadCommitted)]
|
||||
public async Task ReCalcAsync(BalanceReCalcRequest request)
|
||||
{
|
||||
await _balanceService.ReCalcAsync(request.UserCode);
|
||||
}
|
||||
|
||||
[HttpPost("recalc1")]
|
||||
[Transactional(IsolationLevel.ReadCommitted)]
|
||||
[IgnoreTenant]
|
||||
public async Task ReC5()
|
||||
{
|
||||
var sp = App.GetServiceProvider();
|
||||
var db = sp.GetService<IDbContext>();
|
||||
var middleService = sp.GetService<IMiddleService>();
|
||||
var others = await db.Queryable<BalanceRecordEntity>().AS("LocalBalanceRecordEntity")
|
||||
.Where(x => SqlFunc.Subqueryable<BalanceRecordEntity>().Where(p => p.No == x.No).NotAny())
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var item in others)
|
||||
{
|
||||
await middleService.MiddleUploadAsync(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,12 +19,10 @@ namespace Dlhis.Canteen.Order.Controllers;
|
||||
public class OrdersController : ControllerBase
|
||||
{
|
||||
private readonly IOrderService _orderService;
|
||||
private readonly IBookingOrderService _bookingOrderService;
|
||||
|
||||
public OrdersController(IOrderService orderService, IBookingOrderService bookingOrderService)
|
||||
public OrdersController(IOrderService orderService)
|
||||
{
|
||||
_orderService = orderService;
|
||||
_bookingOrderService = bookingOrderService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,56 +64,56 @@ public class OrdersController : ControllerBase
|
||||
return await _orderService.GetOrdersAggregationAsync(page);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取消订单
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut("user-cancel")]
|
||||
[Transactional]
|
||||
[IgnoreTenant]
|
||||
public async Task CancelOrderAsync(OrderCancelRequest request)
|
||||
{
|
||||
await _bookingOrderService.UserCancelOrderAsync(request);
|
||||
}
|
||||
// /// <summary>
|
||||
// /// 取消订单
|
||||
// /// </summary>
|
||||
// /// <param name="request"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpPut("user-cancel")]
|
||||
// [Transactional]
|
||||
// [IgnoreTenant]
|
||||
// public async Task CancelOrderAsync(OrderCancelRequest request)
|
||||
// {
|
||||
// await _bookingOrderService.UserCancelOrderAsync(request);
|
||||
// }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 取消订单
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut("manager-cancel")]
|
||||
[Transactional]
|
||||
[IgnoreTenant]
|
||||
public async Task ManagerCancelOrderAsync(OrderCancelRequest request)
|
||||
{
|
||||
await _bookingOrderService.ManagerCancelOrderAsync(request);
|
||||
}
|
||||
|
||||
//************************************************************** 订餐功能 **********************************************************************************
|
||||
|
||||
/// <summary>
|
||||
/// 取消订单
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("booking")]
|
||||
[Transactional]
|
||||
[IgnoreTenant]
|
||||
public async Task<BookingResponse> Booking(BookingMealRequest request)
|
||||
{
|
||||
return await _bookingOrderService.BookingAsync(request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 订单分页
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("booking/page")]
|
||||
public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync([FromQuery] OrderBookingPageRequest request)
|
||||
{
|
||||
return await _bookingOrderService.GetBookingPageAsync(request);
|
||||
}
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 取消订单
|
||||
// /// </summary>
|
||||
// /// <param name="request"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpPut("manager-cancel")]
|
||||
// [Transactional]
|
||||
// [IgnoreTenant]
|
||||
// public async Task ManagerCancelOrderAsync(OrderCancelRequest request)
|
||||
// {
|
||||
// await _bookingOrderService.ManagerCancelOrderAsync(request);
|
||||
// }
|
||||
//
|
||||
// //************************************************************** 订餐功能 **********************************************************************************
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 取消订单
|
||||
// /// </summary>
|
||||
// /// <param name="request"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpPost("booking")]
|
||||
// [Transactional]
|
||||
// [IgnoreTenant]
|
||||
// public async Task<BookingResponse> Booking(BookingMealRequest request)
|
||||
// {
|
||||
// return await _bookingOrderService.BookingAsync(request);
|
||||
// }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 订单分页
|
||||
// /// </summary>
|
||||
// /// <param name="request"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpGet("booking/page")]
|
||||
// public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync([FromQuery] OrderBookingPageRequest request)
|
||||
// {
|
||||
// return await _bookingOrderService.GetBookingPageAsync(request);
|
||||
// }
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Dto
|
||||
namespace Dlhis.Canteen.Order.Dto;
|
||||
|
||||
public class OrderPreCheckDto
|
||||
{
|
||||
public class OrderPreCheckDto
|
||||
{
|
||||
public DateTime CostDate { get; set; }
|
||||
public BusinessShiftMealRelationshipEntity Shift { get; set; }
|
||||
public string Factory { get; set; }
|
||||
|
||||
public string BusinessPlaceTenantId { get; set; }
|
||||
public DateTime CostDate { get; set; }
|
||||
|
||||
public Guid BusinessPlaceCode { get; set; }
|
||||
public ShiftEnumType ShiftType { get; set; }
|
||||
|
||||
public Guid BusinessShiftCode { get; set; }
|
||||
}
|
||||
public Guid BusinessPlaceCode { get; set; }
|
||||
|
||||
public Guid BusinessShiftCode { get; set; }
|
||||
}
|
||||
40
Src/Dlhis.Canteen/Order/Repository/IBalanceRepository.cs
Normal file
40
Src/Dlhis.Canteen/Order/Repository/IBalanceRepository.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Repository;
|
||||
|
||||
public interface IBalanceRepository : IScopeDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取余额
|
||||
/// </summary>
|
||||
/// <param name="userCode"></param>
|
||||
/// <param name="factory"></param>
|
||||
/// <returns></returns>
|
||||
Task<decimal> GetBalanceAsync(string userCode, string factory);
|
||||
|
||||
/// <summary>
|
||||
/// 获取消费明细
|
||||
/// </summary>
|
||||
/// <param name="userCode"></param>
|
||||
/// <param name="factory"></param>
|
||||
/// <param name="startTime"></param>
|
||||
/// <param name="endTime"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<BalanceRecordEntity>> GetBalanceRecordsAsync(string userCode, string factory, DateTime startTime, DateTime endTime);
|
||||
|
||||
/// <summary>
|
||||
/// 获取钱包厂区
|
||||
/// </summary>
|
||||
/// <param name="factory"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<string>> GetWalletFactoriesAsync(string factory);
|
||||
|
||||
/// <summary>
|
||||
/// 检测余额是否足够
|
||||
/// </summary>
|
||||
/// <param name="userCode"></param>
|
||||
/// <param name="factory"></param>
|
||||
/// <param name="cost"></param>
|
||||
/// <returns></returns>
|
||||
Task CheckConsumableAsync(string userCode, string factory, decimal cost);
|
||||
}
|
||||
11
Src/Dlhis.Canteen/Order/Repository/IOrderRepository.cs
Normal file
11
Src/Dlhis.Canteen/Order/Repository/IOrderRepository.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using Dlhis.Canteen.Order.Dto;
|
||||
using Dlhis.Canteen.Order.Request;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Repository;
|
||||
|
||||
public interface IOrderRepository : IScopeDependency
|
||||
{
|
||||
Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Repository.Implements;
|
||||
|
||||
public class BalanceRepository : IBalanceRepository
|
||||
{
|
||||
private readonly IDbContext _dbContext;
|
||||
|
||||
public BalanceRepository(IDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
public async Task<decimal> GetBalanceAsync(string userCode, string factory)
|
||||
{
|
||||
var factories = await GetWalletFactoriesAsync(factory);
|
||||
|
||||
return await _dbContext.Queryable<BalanceRecordEntity>()
|
||||
.Where(x => x.UserCode == userCode && x.Status == BalanceRecordStatusEnumType.Valid)
|
||||
.Where(x => factories.Contains(x.TenantId))
|
||||
.Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher)
|
||||
.SumAsync(x => x.Amount);
|
||||
}
|
||||
|
||||
|
||||
public async Task<List<BalanceRecordEntity>> GetBalanceRecordsAsync(string userCode, string factory, DateTime startTime, DateTime endTime)
|
||||
{
|
||||
var factories = await GetWalletFactoriesAsync(factory);
|
||||
|
||||
return await _dbContext.Queryable<BalanceRecordEntity>()
|
||||
.Where(x => x.UserCode == userCode)
|
||||
.Where(x => factories.Contains(x.TenantId))
|
||||
.Where(x => x.Type == BalanceRecordTypeEnumType.Out)
|
||||
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
|
||||
.Where(x => x.CostDateTime >= startTime && x.CostDateTime <= endTime)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<List<string>> GetWalletFactoriesAsync(string factory)
|
||||
{
|
||||
var wallets = await _dbContext.Queryable<WalletEntity>().ToListAsync();
|
||||
var code = wallets.First(x => x.Factory == factory).Code;
|
||||
|
||||
return wallets.Where(x => x.Code == code).Select(x => x.Factory).ToList();
|
||||
}
|
||||
|
||||
|
||||
public async Task CheckConsumableAsync(string userCode, string factory, decimal cost)
|
||||
{
|
||||
var balance = await GetBalanceAsync(userCode, factory);
|
||||
var isEnough = balance - Math.Abs(cost) >= 0;
|
||||
isEnough.ThrowIfFalse($"钱包余额不足({balance}元)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Dlhis.Canteen.Order.Dto;
|
||||
using Dlhis.Canteen.Order.Request;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
using Dlhis.Entity.Canteen.Enums;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
|
||||
using Kurisu.AspNetCore.Utils;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Repository.Implements;
|
||||
|
||||
public class OrderRepository : IOrderRepository
|
||||
{
|
||||
private readonly IDbContext _dbContext;
|
||||
|
||||
public OrderRepository(IDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo)
|
||||
{
|
||||
var order = new CanteenOrderEntity
|
||||
{
|
||||
RequestJson = request.ToJson(),
|
||||
IsOffline = request.IsOffline,
|
||||
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
||||
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.ShiftType,
|
||||
CostDate = checkData.CostDate,
|
||||
CostDateTime = request.CostDateTime,
|
||||
CostId = gainfo.CostId,
|
||||
DepartmentNo = gainfo.DepartmentNo,
|
||||
DeviceUniqueNo = request.DeviceUniqueNo,
|
||||
|
||||
Remark = null,
|
||||
DeliveryAddress = null,
|
||||
Result = null,
|
||||
IP = null,
|
||||
|
||||
IsCostCrossTenant = gainfo.Factory != checkData.Factory,
|
||||
|
||||
Werks = gainfo.Werks,
|
||||
OriginTenantId = gainfo.Factory,
|
||||
//标识当前消费的基地
|
||||
TenantId = checkData.Factory,
|
||||
|
||||
Status = BalanceRecordStatusEnumType.Valid,
|
||||
OrderStatus = CanteenOrderStatusEnumType.Wait,
|
||||
|
||||
IsDeleted = false,
|
||||
};
|
||||
|
||||
var orderId = await _dbContext.InsertReturnIdentityAsync(order);
|
||||
order.Id = orderId;
|
||||
return order;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -122,11 +122,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];
|
||||
@@ -323,19 +319,6 @@ 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)
|
||||
@@ -542,82 +525,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>
|
||||
|
||||
@@ -1,302 +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 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;
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
// }
|
||||
// }
|
||||
@@ -25,21 +25,19 @@ public class MiddleService : IMiddleService
|
||||
if (!await _dbContext.Queryable<BalanceRecordEntity>().AnyAsync(x => x.No == entity.No))
|
||||
{
|
||||
await _dbContext.InsertAsync(entity);
|
||||
await _balanceService.ReCalcAsync(entity.UserCode);
|
||||
}
|
||||
|
||||
//获取人员余额
|
||||
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 = x.Balance todo 余额
|
||||
})
|
||||
.SingleAsync();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Dlhis.Canteen.Order.Dto;
|
||||
using Dlhis.Canteen.Order.Repository;
|
||||
using Dlhis.Canteen.Setting.Services;
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Dlhis.Entity.Canteen.Entities;
|
||||
@@ -11,6 +12,7 @@ using SqlSugar;
|
||||
using Dlhis.Canteen.Order.Response;
|
||||
using Dlhis.Canteen.Order.Request;
|
||||
using Dlhis.Entity.Device;
|
||||
using Dlhis.Entity.Device.Enums;
|
||||
using Kurisu.AspNetCore.Authentication.Abstractions;
|
||||
using Kurisu.AspNetCore.CustomClass;
|
||||
using Kurisu.AspNetCore.DataAccess.Dto;
|
||||
@@ -20,23 +22,34 @@ using Kurisu.AspNetCore.UnifyResultAndValidation;
|
||||
|
||||
namespace Dlhis.Canteen.Order.Services.Implements;
|
||||
|
||||
public class OrderService : BaseOrderService, IOrderService
|
||||
public class OrderService : IOrderService
|
||||
{
|
||||
private readonly ICanteenSettingService _canteenSettingService;
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly ICurrentUser _currentUser;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IBalanceRepository _balanceRepository;
|
||||
private readonly IOrderRepository _orderRepository;
|
||||
private readonly RedisCache _redisCache;
|
||||
private readonly ILogger<OrderService> _logger;
|
||||
|
||||
public OrderService(ICanteenSettingService canteenSettingService,
|
||||
IDbContext dbContext,
|
||||
ICurrentUser currentUser,
|
||||
IServiceProvider serviceProvider,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IBalanceRepository balanceRepository,
|
||||
IOrderRepository orderRepository,
|
||||
RedisCache redisCache,
|
||||
ILogger<OrderService> logger)
|
||||
: base(canteenSettingService, dbContext, currentUser, logger)
|
||||
{
|
||||
_canteenSettingService = canteenSettingService;
|
||||
_serviceProvider = serviceProvider;
|
||||
_dbContext = dbContext;
|
||||
_currentUser = currentUser;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_balanceRepository = balanceRepository;
|
||||
_orderRepository = orderRepository;
|
||||
_redisCache = redisCache;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -56,28 +69,12 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
/// <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 SetDeviceIpInfoAsync(request.DeviceUniqueNo);
|
||||
|
||||
await DbContext.UpdateAsync(device);
|
||||
}
|
||||
|
||||
Logger.LogInformation("设备IP获取:{deviceNo} {ip}", request.DeviceUniqueNo, ip);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//ignore
|
||||
}
|
||||
await using var handler = await _redisCache.LockAsync($"consume:device:{request.UserUniqueNo}");
|
||||
handler.Acquired.ThrowIfFalse("请勿频繁消费");
|
||||
|
||||
var gainfo = await GetUserAsync(request);
|
||||
|
||||
return new OrderResultResponseWithLogs
|
||||
{
|
||||
Response = await ToDoAsync(request, gainfo)
|
||||
@@ -87,15 +84,15 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
|
||||
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;
|
||||
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();
|
||||
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == jinkoCode).FirstAsync();
|
||||
}
|
||||
|
||||
var pageResult = await DbContext.Queryable<CanteenOrderEntity>().Where(x => x.UserNo == gainfo.No)
|
||||
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)
|
||||
@@ -110,7 +107,7 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
.ToPageListAsync(page);
|
||||
|
||||
var nos = pageResult.Data.Select(x => x.No).ToList();
|
||||
var dtos = await DbContext.Queryable<CanteenOrderDetailEntity>()
|
||||
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
|
||||
@@ -152,10 +149,10 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
else if (request.UserUniqueNo.StartsWith("02"))
|
||||
{
|
||||
request.Source = BalanceRecordSourceEnumType.EMealVoucher;
|
||||
var eMealVoucherQrCode = await DbContext.Queryable<EMealVoucherDetailQrCodeEntity>().Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
|
||||
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();
|
||||
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == code).SingleAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -165,7 +162,7 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
else
|
||||
{
|
||||
//根据档案号
|
||||
gainfo = await DbContext.Queryable<GainfoEntity>()
|
||||
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)
|
||||
@@ -181,7 +178,7 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
else
|
||||
{
|
||||
//兼容hpt尚未删除人员后产生的消费数据
|
||||
gainfo ??= await DbContext.Queryable<GainfoEntity>().AS("GainfoLeave")
|
||||
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)
|
||||
@@ -192,33 +189,6 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取成本日期
|
||||
/// </summary>
|
||||
/// <param name="shift"></param>
|
||||
/// <param name="costDateTime"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<DateTime> GetCostDateAsync(BusinessShiftMealRelationshipEntity shift, DateTime costDateTime)
|
||||
{
|
||||
var switchTime = await _canteenSettingService.GetSettingAsync<TimeOnly?>(CanteenSettingItemEnumType.BusinessSwitchTime, shift.TenantId, string.Empty);
|
||||
|
||||
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>
|
||||
@@ -231,15 +201,10 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
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 todayAllBalanceRecords = await _balanceRepository.GetBalanceRecordsAsync(order.UserCode, order.TenantId, beginOfDay, endOfDay);
|
||||
|
||||
//超市营业点
|
||||
var supermarketCodes = await DbContext.Queryable<BusinessPlaceEntity>()
|
||||
var supermarketCodes = await _dbContext.Queryable<BusinessPlaceEntity>()
|
||||
.Where(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
|
||||
.Select(x => x.Code)
|
||||
.ToListAsync();
|
||||
@@ -286,40 +251,6 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <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>
|
||||
@@ -327,36 +258,35 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
/// <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
|
||||
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
|
||||
{
|
||||
x.Code,
|
||||
sr.ShiftCode,
|
||||
x.TenantId
|
||||
b.Code, bs.ShiftCode, Factory = x.TenantId
|
||||
})
|
||||
.FirstAsync();
|
||||
.SingleAsync();
|
||||
|
||||
|
||||
//获取当前消费餐次
|
||||
var shifts = await DbContext.Queryable<BusinessShiftMealRelationshipEntity>().Where(x => x.ShiftCode == businessPlaceInfo.ShiftCode).ToListAsync();
|
||||
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>()
|
||||
.Where(x => x.ShiftCode == bindingInfo.ShiftCode).ToListAsync();
|
||||
|
||||
var shift = shifts.FirstOrDefault(x => new TimePeriod()
|
||||
var shift = shifts.FirstOrDefault(x => new TimePeriod
|
||||
{
|
||||
Start = x.Start,
|
||||
End = x.End
|
||||
}.IsPresent(request.CostDateTime));
|
||||
|
||||
var costDate = await GetCostDateAsync(shift, 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,
|
||||
@@ -364,7 +294,7 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
UserNo = gainfo.No,
|
||||
UserCode = gainfo.Code,
|
||||
Amount = request.Amount,
|
||||
BusinessPlaceCode = businessPlaceInfo?.Code,
|
||||
BusinessPlaceCode = bindingInfo.Code,
|
||||
BusinessShiftCode = shift?.ShiftCode,
|
||||
ShiftType = shift?.ShiftType,
|
||||
CostDate = costDate.Date,
|
||||
@@ -372,9 +302,7 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
DepartmentNo = gainfo.DepartmentNo,
|
||||
DeviceUniqueNo = request.DeviceUniqueNo,
|
||||
|
||||
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
||||
IsOffline = request.IsOffline,
|
||||
IsCostCrossTenant = businessPlaceInfo!.TenantId != gainfo.Factory,
|
||||
IsCostCrossTenant = bindingInfo.Factory != gainfo.Factory,
|
||||
|
||||
OriginTenantId = gainfo.Factory,
|
||||
Werks = gainfo.Werks,
|
||||
@@ -386,48 +314,12 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
CostDateTime = request.CostDateTime,
|
||||
|
||||
//标识当前消费的基地
|
||||
TenantId = businessPlaceInfo!.TenantId,
|
||||
TenantId = bindingInfo.Factory,
|
||||
};
|
||||
|
||||
|
||||
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);
|
||||
await _dbContext.InsertReturnIdentityAsync(order);
|
||||
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
||||
await _dbContext.InsertAsync(balanceRecord);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -439,79 +331,83 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
private async Task ConsumeAsync(ConsumeRequest request, GainfoEntity gainfo)
|
||||
{
|
||||
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
||||
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
|
||||
|
||||
//(request.Source == BalanceRecordSourceEnumType.QrCode && checkData.BusinessPlaceTenantId != gainfo.Factory).ThrowIfTrue("禁止跨厂区消费");
|
||||
|
||||
var order = new CanteenOrderEntity
|
||||
if (request.Image.IsPresent())
|
||||
{
|
||||
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,
|
||||
await _dbContext.InsertAsync(new ImageRecordEntity
|
||||
{
|
||||
No = order.No,
|
||||
TableName = "B",
|
||||
Image = request.Image
|
||||
});
|
||||
}
|
||||
|
||||
No = SnowFlakeHelper.Instance.NextId().ToString(),
|
||||
IsOffline = request.IsOffline,
|
||||
IsCostCrossTenant = gainfo.Factory != checkData.BusinessPlaceTenantId,
|
||||
await TryConsumeAsync(order.Id, async () =>
|
||||
{
|
||||
//校验
|
||||
await Verify(order);
|
||||
|
||||
OriginTenantId = gainfo.Factory,
|
||||
Werks = gainfo.Werks,
|
||||
Status = BalanceRecordStatusEnumType.Valid,
|
||||
await _balanceRepository.CheckConsumableAsync(order.UserCode, order.TenantId, order.Amount);
|
||||
|
||||
OrderStatus = CanteenOrderStatusEnumType.Wait,
|
||||
//写入记录
|
||||
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
||||
await _dbContext.InsertAsync(balanceRecord);
|
||||
});
|
||||
}
|
||||
|
||||
CostDateTime = request.CostDateTime,
|
||||
private async Task<DefaultApiResult<OrderResultResponse>> EMealVoucherConsumeAsync(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();
|
||||
|
||||
//标识当前消费的基地
|
||||
TenantId = checkData.BusinessPlaceTenantId
|
||||
};
|
||||
if (originData.IsEmpty())
|
||||
{
|
||||
msg = "无法识别";
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
Code = ApiStateCode.Error,
|
||||
Data = null,
|
||||
Msg = msg
|
||||
};
|
||||
}
|
||||
|
||||
var orderId = await DbContext.InsertReturnIdentityAsync(order);
|
||||
var originDataItems = originData.Split(":");
|
||||
var no = originDataItems[0];
|
||||
var idNo = originDataItems[3];
|
||||
|
||||
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();
|
||||
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, originData, no, idNo);
|
||||
}
|
||||
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;
|
||||
msg = ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
//获取餐券余额
|
||||
var data = await _dbContext.Queryable<EMealVoucherEntity>()
|
||||
.LeftJoin<EMealVoucherDetailEntity>((x, d) => x.No == d.No)
|
||||
.LeftJoin<GainfoEntity>((x, d, u) => u.IdNo == d.IdNo)
|
||||
.Where((x, d) => x.No == no && d.IdNo == idNo)
|
||||
.Select((x, d, u) => new OrderResultResponse
|
||||
{
|
||||
UserCode = u.Code,
|
||||
UserName = u.Name,
|
||||
CurrentBalance = d.Balance
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
||||
Data = data,
|
||||
Msg = msg
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分支处理在线/离线消费
|
||||
@@ -524,26 +420,35 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
var message = string.Empty;
|
||||
|
||||
if (request.Source == BalanceRecordSourceEnumType.EMealVoucher)
|
||||
return await EMealVoucherConsumeAsync(request, gainfo);
|
||||
|
||||
if (request.IsOffline)
|
||||
{
|
||||
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 idNo = originData[3];
|
||||
|
||||
try
|
||||
{
|
||||
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, eMealVoucherQrCode.OriginData, no, idNo);
|
||||
if (request.ThirdNo.IsPresent() && await ToCheckAbleOfflineConsumeAsync(request.ThirdNo))
|
||||
{
|
||||
await using var handler = await _redisCache.LockAsync($"consume:device-offline:{request.ThirdNo}");
|
||||
if (handler.Acquired)
|
||||
{
|
||||
await HandleOfflineAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await HandleOfflineAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
await ConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -590,92 +495,33 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
Msg = message
|
||||
};
|
||||
}
|
||||
else
|
||||
|
||||
var currentFactory = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == request.DeviceUniqueNo).Select(x => x.TenantId).SingleAsync();
|
||||
var balance = await _balanceRepository.GetBalanceAsync(gainfo.Code, currentFactory);
|
||||
|
||||
//获取人员余额
|
||||
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
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
return new DefaultApiResult<OrderResultResponse>
|
||||
{
|
||||
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;
|
||||
}
|
||||
Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
|
||||
Data = data,
|
||||
Msg = message
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 根据二维码获取消费用户
|
||||
/// </summary>
|
||||
@@ -683,74 +529,57 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
/// <returns></returns>
|
||||
private async Task<GainfoEntity> GetUserByQrCodeAsync(string qrCode)
|
||||
{
|
||||
var gainfoQrCode = await DbContext.Queryable<GainfoQrCodeEntity>().Where(x => x.QrCode == qrCode).SingleAsync();
|
||||
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();
|
||||
return await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == gainfoQrCode.UserCode).SingleAsync();
|
||||
}
|
||||
|
||||
/// <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).SingleAsync();
|
||||
(now >= current.Start && now <= current.End).ThrowIfFalse("餐券已过期");
|
||||
var nowDate = DateTime.Now.Date;
|
||||
|
||||
var eMealVoucher = await DbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
|
||||
var current = await _dbContext.Queryable<EMealVoucherDetailEntity>()
|
||||
.Where(x => x.No == no && x.IdNo == idNo)
|
||||
.Select(x => new { x.Start, x.End })
|
||||
.SingleAsync();
|
||||
|
||||
(nowDate >= current.Start && nowDate <= current.End).ThrowIfFalse("餐券已过期");
|
||||
|
||||
|
||||
var eMealVoucher = await _dbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
|
||||
|
||||
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
|
||||
var isSupermarket = await DbContext.Queryable<BusinessPlaceEntity>().Where(x => x.Code == checkData.BusinessPlaceCode)
|
||||
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.BusinessPlaceTenantId).ThrowIfFalse("禁止在当前厂区消费");
|
||||
eMealVoucher.Factories.Contains(checkData.Factory).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,
|
||||
gainfo.No = originData;
|
||||
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
|
||||
|
||||
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 TryConsumeAsync(order.Id, async () =>
|
||||
{
|
||||
await CommonHelper.RetryAsync(async () =>
|
||||
{
|
||||
var detail = await DbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.No == no && x.IdNo == idNo).SingleAsync();
|
||||
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>()
|
||||
await _dbContext.Updateable<EMealVoucherDetailEntity>()
|
||||
.SetColumns(x => x.Balance == detail.Balance)
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
@@ -759,26 +588,9 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
|
||||
//写入记录
|
||||
var balanceRecord = order.Adapt<BalanceRecordEntity>();
|
||||
await DbContext.InsertAsync(balanceRecord);
|
||||
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>
|
||||
@@ -789,28 +601,28 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
/// <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();
|
||||
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).SingleAsync();
|
||||
device.ThrowIfNull("设备尚未登记");
|
||||
device.Enable.ThrowIfFalse("设备已被停用");
|
||||
(device.Type != DeviceTypeEnumType.Meal).ThrowIfTrue("设备类型有误");
|
||||
|
||||
var businessPlaceInfo = await DbContext.Queryable<BusinessPlaceEntity>()
|
||||
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, sr) => x.Code == sr.PlaceCode)
|
||||
.Where(x => x.Code == registry.BusinessPlaceCode)
|
||||
.Select((x, sr) => new
|
||||
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
|
||||
{
|
||||
x.Code,
|
||||
sr.ShiftCode,
|
||||
x.TenantId
|
||||
b.Code, bs.ShiftCode, Factory = x.TenantId
|
||||
})
|
||||
.SingleAsync();
|
||||
|
||||
businessPlaceInfo.ThrowIfNull("设备尚未登记营业点");
|
||||
bindingInfo.ThrowIfNull("设备尚未登记营业点");
|
||||
|
||||
//获取当前消费餐次
|
||||
var shifts = await DbContext.Queryable<BusinessShiftMealRelationshipEntity>().Where(x => x.ShiftCode == businessPlaceInfo.ShiftCode).ToListAsync();
|
||||
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
|
||||
@@ -818,17 +630,88 @@ public class OrderService : BaseOrderService, IOrderService
|
||||
Start = x.Start,
|
||||
End = x.End
|
||||
}.IsPresent(costDateTime));
|
||||
shift.ThrowIfNull("非就餐时间,无法消费");
|
||||
shift.ThrowIfNull("非就餐时间");
|
||||
|
||||
var costDate = await GetCostDateAsync(shift, costDateTime);
|
||||
var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, costDateTime);
|
||||
|
||||
return new OrderPreCheckDto
|
||||
{
|
||||
Factory = bindingInfo.Factory,
|
||||
CostDate = costDate,
|
||||
Shift = shift,
|
||||
BusinessPlaceTenantId = businessPlaceInfo.TenantId,
|
||||
BusinessPlaceCode = businessPlaceInfo.Code,
|
||||
BusinessShiftCode = businessPlaceInfo.ShiftCode
|
||||
ShiftType = shift!.ShiftType,
|
||||
BusinessPlaceCode = bindingInfo.Code,
|
||||
BusinessShiftCode = bindingInfo.ShiftCode
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置设备ip
|
||||
/// </summary>
|
||||
/// <param name="deviceNo"></param>
|
||||
private 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>
|
||||
/// 检查是否能够进行离线消费,处理hpt重复提交
|
||||
/// </summary>
|
||||
/// <param name="thirdNo"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<bool> ToCheckAbleOfflineConsumeAsync(string thirdNo)
|
||||
{
|
||||
var order = await _dbContext.Queryable<CanteenOrderEntity>()
|
||||
.Where(x => x.ThirdNo == thirdNo)
|
||||
.OrderBy(x => x.CreateTime, OrderByType.Desc)
|
||||
.SingleAsync();
|
||||
|
||||
if (order == null)
|
||||
return true;
|
||||
|
||||
//存在在线order数据,但是状态未成功
|
||||
return !order.IsOffline && order.OrderStatus != CanteenOrderStatusEnumType.Success;
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,4 +45,6 @@ public interface ICanteenSettingService : IScopeDependency
|
||||
|
||||
|
||||
Task<T> GetSettingAsync<T>(CanteenSettingItemEnumType item, string factory, string userNo , T defaultValue = default);
|
||||
|
||||
Task<DateTime> GetCostDateAsync(string factory, DateTime costDateTime);
|
||||
}
|
||||
@@ -139,6 +139,24 @@ public class CanteenSettingService : ICanteenSettingService
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DateTime> GetCostDateAsync(string factory, DateTime costDateTime)
|
||||
{
|
||||
var switchTime = await GetSettingAsync<TimeOnly?>(CanteenSettingItemEnumType.BusinessSwitchTime, factory, string.Empty);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
//*********************************************** help methods ***************************************************//
|
||||
|
||||
private async Task CheckDuplicateSettingAsync(CanteenSettingSaveRequest request)
|
||||
|
||||
@@ -10,37 +10,37 @@ namespace Dlhis.Entity.Basic.Entity;
|
||||
public class BusinessShiftMealRelationshipEntity : SugarBaseEntity, ITenantId
|
||||
{
|
||||
/// <summary>
|
||||
/// 餐别Code
|
||||
/// 餐别Code
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "餐别Code", UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })]
|
||||
public Guid ShiftCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 餐别手工号
|
||||
/// 餐别手工号
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "餐别编码")]
|
||||
public string ShiftCustomCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 餐次
|
||||
/// 餐次
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "餐次", ColumnDataType = "varchar(50)", SqlParameterDbType = typeof(EnumToStringConvert), UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })]
|
||||
public ShiftEnumType ShiftType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 经营开始时间
|
||||
/// 经营开始时间
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "经营开始时间")]
|
||||
public TimeOnly Start { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 经营结束时间
|
||||
/// 经营结束时间
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "经营结束时间")]
|
||||
public TimeOnly End { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 序号
|
||||
/// 序号
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "序号")]
|
||||
public int Sequence { get; set; }
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
using Kurisu.AspNetCore.DataAccess.Entity;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Dlhis.Entity.Basic.Entity
|
||||
{
|
||||
/// <summary>
|
||||
/// 就餐人员
|
||||
/// </summary>
|
||||
[SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")]
|
||||
public class GainfoMealEntity : SugarBaseEntity, IVersion
|
||||
{
|
||||
/// <summary>
|
||||
/// 工号
|
||||
/// </summary>
|
||||
[SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })]
|
||||
public string UserCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额")]
|
||||
public decimal Balance { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额(充值)
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额(充值)")]
|
||||
public decimal BalanceOfRecharge { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额(餐补)
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额(餐补)")]
|
||||
public decimal BalanceOfSubsidies { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "版本号")]
|
||||
public int Version { get; set; }
|
||||
}
|
||||
}
|
||||
// using Kurisu.AspNetCore.DataAccess.Entity;
|
||||
// using Kurisu.AspNetCore.DataAccess.SqlSugar;
|
||||
// using SqlSugar;
|
||||
//
|
||||
// namespace Dlhis.Entity.Basic.Entity
|
||||
// {
|
||||
// /// <summary>
|
||||
// /// 就餐人员
|
||||
// /// </summary>
|
||||
// [SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")]
|
||||
// public class GainfoMealEntity : SugarBaseEntity, IVersion
|
||||
// {
|
||||
// /// <summary>
|
||||
// /// 工号
|
||||
// /// </summary>
|
||||
// [SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })]
|
||||
// public string UserCode { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 余额
|
||||
// /// </summary>
|
||||
// [SugarColumn(ColumnDescription = "余额")]
|
||||
// public decimal Balance { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 余额(充值)
|
||||
// /// </summary>
|
||||
// [SugarColumn(ColumnDescription = "余额(充值)")]
|
||||
// public decimal BalanceOfRecharge { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 余额(餐补)
|
||||
// /// </summary>
|
||||
// [SugarColumn(ColumnDescription = "余额(餐补)")]
|
||||
// public decimal BalanceOfSubsidies { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 版本号
|
||||
// /// </summary>
|
||||
// [SugarColumn(ColumnDescription = "版本号")]
|
||||
// public int Version { get; set; }
|
||||
// }
|
||||
// }
|
||||
29
Src/Dlhis.Entity/Canteen/Entities/WalletEntity.cs
Normal file
29
Src/Dlhis.Entity/Canteen/Entities/WalletEntity.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Dlhis.Entity.Canteen.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 钱包
|
||||
/// </summary>
|
||||
[SugarTable(TableName = "Wallets", TableDescription = "钱包")]
|
||||
public class WalletEntity : SugarBaseEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// 钱包编码
|
||||
/// </summary>
|
||||
[SugarColumn(IsNullable = false)]
|
||||
public string Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 钱包名称
|
||||
/// </summary>
|
||||
[SugarColumn(IsNullable = false)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 厂区
|
||||
/// </summary>
|
||||
[SugarColumn(IsNullable = false, UniqueGroupNameList = new[] { "idx_wallets_facotry" })]
|
||||
public string Factory { get; set; }
|
||||
}
|
||||
@@ -8,6 +8,9 @@ namespace Dlhis.Entity.Canteen.Enums;
|
||||
[Description("餐饮应用类型")]
|
||||
public enum CanteenApplicationTypeEnumType
|
||||
{
|
||||
/// <summary>
|
||||
/// 设备消费
|
||||
/// </summary>
|
||||
[Description("设备消费")]
|
||||
Device = 100,
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using Dlhis.Entity.Basic.Entity;
|
||||
using Kurisu.AspNetCore.DataAccess.Entity;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Dlhis.Middle.Entities
|
||||
{
|
||||
@@ -6,4 +9,42 @@ namespace Dlhis.Middle.Entities
|
||||
{
|
||||
public new int Id { get; set; }
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 就餐人员
|
||||
/// </summary>
|
||||
[SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")]
|
||||
public class GainfoMealEntity : SugarBaseEntity, IVersion
|
||||
{
|
||||
/// <summary>
|
||||
/// 工号
|
||||
/// </summary>
|
||||
[SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })]
|
||||
public string UserCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额")]
|
||||
public decimal Balance { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额(充值)
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额(充值)")]
|
||||
public decimal BalanceOfRecharge { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 余额(餐补)
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "余额(餐补)")]
|
||||
public decimal BalanceOfSubsidies { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "版本号")]
|
||||
public int Version { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using Dlhis.ScheduledTask.Common.Response;
|
||||
|
||||
namespace Dlhis.ScheduledTask.Common.Services;
|
||||
|
||||
public interface IJinkoJIPService : ISingletonDependency
|
||||
public interface IJinkoJipService : ISingletonDependency
|
||||
{
|
||||
Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests);
|
||||
|
||||
|
||||
36
Src/Dlhis.ScheduledTask/Common/Services/IJinkoJipService.cs
Normal file
36
Src/Dlhis.ScheduledTask/Common/Services/IJinkoJipService.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using Dlhis.ScheduledTask.Common.Request;
|
||||
using Dlhis.ScheduledTask.Common.Response;
|
||||
|
||||
namespace Dlhis.ScheduledTask.Common.Services;
|
||||
|
||||
public interface IJinkoJipService : ISingletonDependency
|
||||
{
|
||||
Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests);
|
||||
|
||||
Task<string> SyncMealSupplementRecordsAsync(List<SyncMealSupplementRecordRequest> requests);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取出差信息
|
||||
/// </summary>
|
||||
/// <param name="begin"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="fatory"></param>
|
||||
/// <returns></returns>
|
||||
Task<SapBusinessTripInfoResponse> GetTravelInfosByFactoryAsync(DateTime begin, DateTime end, string fatory);
|
||||
|
||||
/// <summary>
|
||||
/// 获取出差信息
|
||||
/// </summary>
|
||||
/// <param name="begin"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="userCode"></param>
|
||||
/// <returns></returns>
|
||||
Task<SapBusinessTripInfoResponse> GetTravelInfosByUserCodeAsync(DateTime begin, DateTime end, string userCode);
|
||||
|
||||
|
||||
Task<SapFaceSyncResponse> SyncFaceToSapAsync(string userCode, string base64);
|
||||
|
||||
|
||||
string IssueToken();
|
||||
}
|
||||
@@ -12,9 +12,9 @@ public class HangfireService : IHangfireService
|
||||
{
|
||||
private readonly RedisCache _redisCache;
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly IJinkoJIPService _jinkoJipService;
|
||||
private readonly IJinkoJipService _jinkoJipService;
|
||||
|
||||
public HangfireService(RedisCache redisCache, IDbContext dbContext, IJinkoJIPService jinkoJipService)
|
||||
public HangfireService(RedisCache redisCache, IDbContext dbContext, IJinkoJipService jinkoJipService)
|
||||
{
|
||||
_redisCache = redisCache;
|
||||
_dbContext = dbContext;
|
||||
|
||||
@@ -10,13 +10,13 @@ using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Dlhis.ScheduledTask.Common.Services.Implements;
|
||||
|
||||
public class JinkoJIPService : IJinkoJIPService
|
||||
public class JinkoJipService : IJinkoJipService
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<JinkoJIPService> _logger;
|
||||
private readonly ILogger<JinkoJipService> _logger;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public JinkoJIPService(IHttpClientFactory httpClientFactory, ILogger<JinkoJIPService> logger, IConfiguration configuration)
|
||||
public JinkoJipService(IHttpClientFactory httpClientFactory, ILogger<JinkoJipService> logger, IConfiguration configuration)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_logger = logger;
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Dlhis.ScheduledTask.Common.Request;
|
||||
using Dlhis.ScheduledTask.Common.Response;
|
||||
using Kurisu.AspNetCore.Utils.Extensions;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Dlhis.ScheduledTask.Common.Services.Implements;
|
||||
|
||||
public class JinkoJipService : IJinkoJipService
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<JinkoJipService> _logger;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public JinkoJipService(IHttpClientFactory httpClientFactory, ILogger<JinkoJipService> logger, IConfiguration configuration)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_logger = logger;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
private HttpClient GetHttpClient()
|
||||
{
|
||||
var httpClient = _httpClientFactory.CreateClient();
|
||||
httpClient.BaseAddress = new Uri(_configuration.GetSection("JinkoOptions:Jip:BaseUrl").Value);
|
||||
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", IssueToken());
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public async Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests)
|
||||
{
|
||||
var requestUrl = "/JIP/HCM/HCM_SWIPE_DATA_SAVE";
|
||||
|
||||
var body = new
|
||||
{
|
||||
T_DATA = requests,
|
||||
};
|
||||
|
||||
var json = body.ToJson();
|
||||
|
||||
//_logger.LogInformation("上传考勤记录请求:{json}", json);
|
||||
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
var response = await GetHttpClient().PostAsync(requestUrl, content);
|
||||
var responseJson = await response.Content.ReadAsStringAsync();
|
||||
|
||||
_logger.LogInformation("上传考勤记录响应:{json}", responseJson);
|
||||
|
||||
try
|
||||
{
|
||||
return responseJson.ToObject<UploadAttendanceResponse>();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return new UploadAttendanceResponse
|
||||
{
|
||||
OLX = "99",
|
||||
OMS = "接口响应数据异常,无法反序列化"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<string> SyncMealSupplementRecordsAsync(List<SyncMealSupplementRecordRequest> requests)
|
||||
{
|
||||
var requestUrl = "/JIP/DHR/DHR_DL_CALLBACK";
|
||||
|
||||
var json = requests.ToJson(Kurisu.AspNetCore.Utils.Extensions.JsonExtensions.DefaultSetting);
|
||||
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
var response = await GetHttpClient().PostAsync(requestUrl, content);
|
||||
var responseJson = await response.Content.ReadAsStringAsync();
|
||||
|
||||
_logger.LogInformation("餐补状态同步响应:{json}", responseJson);
|
||||
|
||||
var jobj = JObject.Parse(responseJson);
|
||||
if (jobj.TryGetValue("exp", out var exp))
|
||||
{
|
||||
true.ThrowIfTrue(exp.Value<string>());
|
||||
}
|
||||
|
||||
if (jobj.TryGetValue("message", out var message) && !jobj.ContainsKey("code"))
|
||||
{
|
||||
true.ThrowIfTrue(message.Value<string>());
|
||||
}
|
||||
|
||||
(jobj.GetValue("code").Value<int>() != 200).ThrowIfTrue(jobj.GetValue("message").Value<string>());
|
||||
|
||||
return responseJson;
|
||||
}
|
||||
|
||||
|
||||
public async Task<SapBusinessTripInfoResponse> GetTravelInfosByFactoryAsync(DateTime begin, DateTime end, string factory)
|
||||
{
|
||||
const string apiUrl = "/JIP/HCM/HCM_TRAVELINFO";
|
||||
|
||||
var beginDay = begin.ToString("yyyyMMdd");
|
||||
var endDay = end.ToString("yyyyMMdd");
|
||||
|
||||
var obj = new
|
||||
{
|
||||
I_PAGE = 1,
|
||||
I_LINE = 500,
|
||||
IV_BEGDA = beginDay,
|
||||
IV_ENDDA = endDay,
|
||||
IT_CCMDD = new List<object>
|
||||
{
|
||||
new
|
||||
{
|
||||
IV_CCMDD = factory
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var body = obj.ToJson();
|
||||
|
||||
var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||||
var response = await GetHttpClient().PostAsync(apiUrl, content);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var jsonResponse = await response.Content.ReadAsStringAsync();
|
||||
return jsonResponse.ToObject<SapBusinessTripInfoResponse>();
|
||||
}
|
||||
|
||||
public async Task<SapBusinessTripInfoResponse> GetTravelInfosByUserCodeAsync(DateTime begin, DateTime end, string userCode)
|
||||
{
|
||||
const string apiUrl = "/JIP/HCM/HCM_TRAVELINFO";
|
||||
|
||||
var beginDay = begin.ToString("yyyyMMdd");
|
||||
var endDay = end.ToString("yyyyMMdd");
|
||||
|
||||
//IV_GONGH IV_ORGID
|
||||
//IT_2002GH
|
||||
var obj = new
|
||||
{
|
||||
IV_BEGDA = beginDay,
|
||||
IV_ENDDA = endDay,
|
||||
IT_2002GH = new List<object>
|
||||
{
|
||||
new
|
||||
{
|
||||
IV_GONGH = userCode
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var body = obj.ToJson();
|
||||
|
||||
var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||||
var response = await GetHttpClient().PostAsync(apiUrl, content);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var jsonResponse = await response.Content.ReadAsStringAsync();
|
||||
return jsonResponse.ToObject<SapBusinessTripInfoResponse>();
|
||||
}
|
||||
|
||||
public async Task<SapFaceSyncResponse> SyncFaceToSapAsync(string userCode, string base64)
|
||||
{
|
||||
const string apiUrl = "/JIP/HCM/HCM_I_PHOTO";
|
||||
var obj = new
|
||||
{
|
||||
I_WORKCODE = userCode,
|
||||
I_PHOTO_STR = base64
|
||||
};
|
||||
|
||||
var body = obj.ToJson();
|
||||
|
||||
var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||||
var response = await GetHttpClient().PostAsync(apiUrl, content);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var jsonResponse = await response.Content.ReadAsStringAsync();
|
||||
return jsonResponse.ToObject<SapFaceSyncResponse>();
|
||||
}
|
||||
|
||||
|
||||
public string IssueToken()
|
||||
{
|
||||
var jwtKey = _configuration.GetSection("JinkoOptions:Jip:Key").Value;
|
||||
var jwtSecret = _configuration.GetSection("JinkoOptions:Jip:Secret").Value;
|
||||
const int min = 5;
|
||||
|
||||
var now = DateTime.Now.AddMinutes(-min);
|
||||
var expires = DateTime.Now.AddMinutes(min);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(now).ToUnixTimeSeconds()}"),
|
||||
new(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(expires).ToUnixTimeSeconds()}"),
|
||||
new(JwtRegisteredClaimNames.Iss, jwtKey),
|
||||
};
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret));
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
Issuer = jwtKey,
|
||||
IssuedAt = now,
|
||||
NotBefore = now,
|
||||
Expires = expires,
|
||||
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
|
||||
};
|
||||
|
||||
var jwtHandler = new JwtSecurityTokenHandler();
|
||||
var securityToken = jwtHandler.CreateToken(descriptor);
|
||||
return jwtHandler.WriteToken(securityToken);
|
||||
}
|
||||
}
|
||||
@@ -15,12 +15,12 @@ namespace Dlhis.ScheduledTask.Common.Services.Implements;
|
||||
|
||||
public class SapBusinessTripService : ISapBusinessTripService
|
||||
{
|
||||
private readonly IJinkoJIPService _jinkoJipService;
|
||||
private readonly IJinkoJipService _jinkoJipService;
|
||||
private readonly IDbContext _dbContext;
|
||||
private readonly IDevicePermissionApi _devicePermissionApi;
|
||||
private readonly ILogger<SapBusinessTripService> _logger;
|
||||
|
||||
public SapBusinessTripService(IJinkoJIPService jinkoJipService, IDbContext dbContext, IDevicePermissionApi devicePermissionApi, ILogger<SapBusinessTripService> logger)
|
||||
public SapBusinessTripService(IJinkoJipService jinkoJipService, IDbContext dbContext, IDevicePermissionApi devicePermissionApi, ILogger<SapBusinessTripService> logger)
|
||||
{
|
||||
_jinkoJipService = jinkoJipService;
|
||||
_dbContext = dbContext;
|
||||
|
||||
@@ -6,8 +6,6 @@ using Dlhis.ScheduledTask.Attributes;
|
||||
using Dlhis.ScheduledTask.Common.Request;
|
||||
using Dlhis.ScheduledTask.Common.Services;
|
||||
using Hangfire;
|
||||
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
|
||||
using Kurisu.AspNetCore.Utils;
|
||||
|
||||
namespace Dlhis.ScheduledTask.Jobs;
|
||||
|
||||
@@ -17,10 +15,10 @@ namespace Dlhis.ScheduledTask.Jobs;
|
||||
[RecurringJob(nameof(MealSupplementHandlerJob), "0 0/30 * * * ?", Name = "餐补核算")]
|
||||
public class MealSupplementHandlerJob : BaseJob
|
||||
{
|
||||
private readonly IJinkoJIPService _jinkoJIPService;
|
||||
private readonly IJinkoJipService _jinkoJIPService;
|
||||
|
||||
public MealSupplementHandlerJob(IServiceProvider serviceProvider,
|
||||
IJinkoJIPService jinkoJIPService) : base(serviceProvider)
|
||||
IJinkoJipService jinkoJIPService) : base(serviceProvider)
|
||||
{
|
||||
_jinkoJIPService = jinkoJIPService;
|
||||
}
|
||||
@@ -85,23 +83,6 @@ public class MealSupplementHandlerJob : BaseJob
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//创建余额数据
|
||||
var mealUser = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == gainfo.Code).SingleAsync();
|
||||
if (mealUser == null)
|
||||
{
|
||||
mealUser = new GainfoMealEntity
|
||||
{
|
||||
Balance = 0,
|
||||
BalanceOfRecharge = 0,
|
||||
BalanceOfSubsidies = 0,
|
||||
UserCode = gainfo.Code,
|
||||
Version = 0,
|
||||
};
|
||||
|
||||
await DbContext.InsertAsync(mealUser);
|
||||
}
|
||||
|
||||
await SetMealSupplementAsync(gainfo, item);
|
||||
}
|
||||
}
|
||||
@@ -111,19 +92,6 @@ public class MealSupplementHandlerJob : BaseJob
|
||||
await DbContext.Client.Ado.BeginTranAsync();
|
||||
try
|
||||
{
|
||||
await CommonHelper.RetryAsync(async () =>
|
||||
{
|
||||
var mealUser = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == mealSupplement.Code).FirstAsync();
|
||||
var b = mealUser.Balance += mealSupplement.Amount;
|
||||
|
||||
await DbContext.Updateable<GainfoMealEntity>()
|
||||
.SetColumns(x => x.Version == x.Version + 1)
|
||||
.SetColumns(x => x.Balance == b)
|
||||
.SetColumns(x => x.ModifiedTime == DateTime.Now)
|
||||
.Where(x => x.UserCode == mealUser.UserCode && x.Version == mealUser.Version)
|
||||
.ExecuteCommandThrowVersionAsync();
|
||||
}, 5);
|
||||
|
||||
await DbContext.InsertAsync(new BalanceRecordEntity
|
||||
{
|
||||
Amount = mealSupplement.Amount,
|
||||
|
||||
@@ -7,10 +7,10 @@ namespace Dlhis.ScheduledTask.Jobs;
|
||||
[RecurringJob(nameof(SyncFaceJob), "0 0/15 * * * ?", Name = "face数据同步sap")]
|
||||
public class SyncFaceJob : BaseJob
|
||||
{
|
||||
private readonly IJinkoJIPService _jinkoJipService;
|
||||
private readonly IJinkoJipService _jinkoJipService;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SyncFaceJob(IServiceProvider serviceProvider, IJinkoJIPService jinkoJipService) : base(serviceProvider)
|
||||
public SyncFaceJob(IServiceProvider serviceProvider, IJinkoJipService jinkoJipService) : base(serviceProvider)
|
||||
{
|
||||
_jinkoJipService = jinkoJipService;
|
||||
}
|
||||
|
||||
@@ -14,9 +14,9 @@ namespace Dlhis.ScheduledTask.Jobs;
|
||||
[RecurringJob(nameof(SyncOriginCardInfoJob), "0 0/1 * * * ?", Name = "上传考勤记录")]
|
||||
public class SyncOriginCardInfoJob : BaseJob
|
||||
{
|
||||
private readonly IJinkoJIPService _jinkoJIPService;
|
||||
private readonly IJinkoJipService _jinkoJIPService;
|
||||
|
||||
public SyncOriginCardInfoJob(IJinkoJIPService jinkoJIPService, IServiceProvider serviceProvider) : base(serviceProvider)
|
||||
public SyncOriginCardInfoJob(IJinkoJipService jinkoJIPService, IServiceProvider serviceProvider) : base(serviceProvider)
|
||||
{
|
||||
_jinkoJIPService = jinkoJIPService;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,6 @@ public class Startup : DefaultStartup
|
||||
{
|
||||
base.Configure(app, env);
|
||||
|
||||
var token = app.ApplicationServices.GetService<IJinkoJIPService>().IssueToken();
|
||||
var token = app.ApplicationServices.GetService<IJinkoJipService>().IssueToken();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user