Merge branch 'feat-tickets' into development

This commit is contained in:
2025-02-18 16:42:31 +08:00
44 changed files with 1051 additions and 317 deletions

View File

@@ -47,6 +47,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dlhis.Jip.Api", "Src\Dlhis.
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dlhis.Dh.Api", "Src\Dlhis.Dh.Api\Dlhis.Dh.Api.csproj", "{E673CA04-3567-4E03-9A86-994F50291ACC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dlhis.Constants", "Src\Dlhis.Constants\Dlhis.Constants.csproj", "{F98329D8-F8CA-4794-B1BF-8659112119F7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dlhis.Canteen.Api", "Src\Dlhis.Canteen.Api\Dlhis.Canteen.Api.csproj", "{7934BE46-9409-4D28-8B35-82A0F900DD01}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -117,6 +121,14 @@ Global
{E673CA04-3567-4E03-9A86-994F50291ACC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E673CA04-3567-4E03-9A86-994F50291ACC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E673CA04-3567-4E03-9A86-994F50291ACC}.Release|Any CPU.Build.0 = Release|Any CPU
{F98329D8-F8CA-4794-B1BF-8659112119F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F98329D8-F8CA-4794-B1BF-8659112119F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F98329D8-F8CA-4794-B1BF-8659112119F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F98329D8-F8CA-4794-B1BF-8659112119F7}.Release|Any CPU.Build.0 = Release|Any CPU
{7934BE46-9409-4D28-8B35-82A0F900DD01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7934BE46-9409-4D28-8B35-82A0F900DD01}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7934BE46-9409-4D28-8B35-82A0F900DD01}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7934BE46-9409-4D28-8B35-82A0F900DD01}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -134,6 +146,7 @@ Global
{A501D16E-638F-4156-989C-2BACCC2FAC2B} = {4EBCE46B-CE3A-4A47-9432-82A1854CA58A}
{841B7B43-5394-413F-9D68-A07EBDD6D4CD} = {4EBCE46B-CE3A-4A47-9432-82A1854CA58A}
{E673CA04-3567-4E03-9A86-994F50291ACC} = {4EBCE46B-CE3A-4A47-9432-82A1854CA58A}
{7934BE46-9409-4D28-8B35-82A0F900DD01} = {3D8A98C1-83C9-4375-AEAB-4F72AFAF365B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7439494A-E2FD-4FEA-8ABF-74AE57A4A5A0}

View File

@@ -53,6 +53,16 @@ public class DevicePermissionService : IDevicePermissionService
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.Code == request.UniqueValue).SingleAsync();
device.ThrowIfNull("设备不存在");
var deviceGroupCodes = await _dbContext.Queryable<DeviceGroupRelationshipEntity>().Where(x => x.DeviceCode == device.Code).Select(x => x.GroupCode).ToListAsync();
var existsTenantAssigned = await _dbContext.Queryable<DevicePermissionEntity>()
.Where(x => (x.UniqueType == DeviceAssignmentTypeEnumType.Device && x.UniqueValue == request.UniqueValue)
|| (x.UniqueType == DeviceAssignmentTypeEnumType.Group && deviceGroupCodes.Contains(x.UniqueValue)))
.Where(x => x.AssignType == AssignTypeEnumType.Tenant)
.AnyAsync();
existsTenantAssigned.ThrowIfTrue("当前设备或者所在分组已分配到厂区,无法操作");
//当前匹配的基地权限
var dps = await _dbContext.Queryable<DevicePermissionEntity>()
.Where(x => x.UniqueType == DeviceAssignmentTypeEnumType.Device)

View File

@@ -1,6 +1,7 @@
using Dlhis.Basic.Dishes.Request;
using Dlhis.Basic.Dishes.Response;
using Dlhis.Basic.Places.Services;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
@@ -45,7 +46,7 @@ public class DishesService : IDishesService
.ToPageListAsync(request);
}
public async Task SaveDishesAsync(DishesSaveRequest request)
{
if (!request.Id.HasValue)
@@ -68,7 +69,7 @@ public class DishesService : IDishesService
{
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 jinkoCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode) ?? string.Empty;
if (jinkoCode.IsPresent())
{
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == jinkoCode).FirstAsync();

View File

@@ -26,6 +26,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dlhis.Constants\Dlhis.Constants.csproj" />
<ProjectReference Include="..\Dlhis.Dh.Api\Dlhis.Dh.Api.csproj" />
<ProjectReference Include="..\Dlhis.Entity\Dlhis.Entity.csproj" />
<ProjectReference Include="..\Dlhis.InfoCheck.Api\Dlhis.InfoCheck.Api.csproj" />

View File

@@ -1,4 +1,5 @@
using System.Text;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
@@ -21,7 +22,7 @@ public class GainfoQrCodeService : IGainfoQrCodeService
public async Task<string> GetMyQrCodeAsync(bool isNeedRefresh = false)
{
var jinkoCode = _currentUser.GetUserClaim("jinko-code");
var jinkoCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
if (jinkoCode.IsEmpty())
{
return null;
@@ -63,11 +64,12 @@ public class GainfoQrCodeService : IGainfoQrCodeService
var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var qrCode = string.Concat("consumer", ":", code, ":");
return "01" + qrCode.ToArray().Select(x =>
return QrCodeConstants.User + qrCode.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];
return Convert.ToString(i);
}).Join(string.Empty) + ts;
}
}

View File

@@ -2,6 +2,7 @@
using Dlhis.Basic.Device.Services;
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Response;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Device.Entities;
@@ -195,7 +196,7 @@ public class GainfoService : IGainfoService
public async Task<GainfoCurrentResponse> CurrentUserInfoAsync()
{
var code = _currentUser.GetUserClaim("jinko-code");
var code = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
if (code.IsEmpty())
{
_logger.LogWarning("工号为空尝试获取人员信息");

View File

@@ -1,3 +1,4 @@
using Dlhis.Constants;
using Dlhis.Entity.Sys.Entities;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
@@ -41,7 +42,7 @@ public class IdentityUserSyncService : IIdentityUserSyncService
var id = (int)await _identityDbContext.InsertReturnIdentityAsync(user);
user.Id = id;
await AddUserClaim(_identityDbContext, id, "jinko-code", userName);
await AddUserClaim(_identityDbContext, id, UserClaimConstants.JinkoCode, userName);
await AddUserClaim(_identityDbContext, id, "name", name);
}

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Kurisu.RemoteCall" Version="0.4.8" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,16 @@
using Kurisu.RemoteCall.Attributes;
namespace Dlhis.Canteen.Api;
[RequestResultHandler]
[EnableRemoteClient(Name = "canteen-service", BaseUrl = "${InternalRequest:CanteenRequestUrl}")]
public interface ITicketApi
{
/// <summary>
/// 创建券
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[Post("/api/tickets/{type}/create")]
Task CreateAsync(string type);
}

View File

@@ -22,6 +22,7 @@
<ItemGroup>
<ProjectReference Include="..\Dlhis.Basic.Api\Dlhis.Basic.Api.csproj" />
<ProjectReference Include="..\Dlhis.Constants\Dlhis.Constants.csproj" />
<ProjectReference Include="..\Dlhis.Entity\Dlhis.Entity.csproj" />
<ProjectReference Include="..\Dlhis.Sys.Api\Dlhis.Sys.Api.csproj" />
</ItemGroup>

View File

@@ -3,6 +3,7 @@ using Dlhis.Canteen.EMealVoucher.Request;
using Dlhis.Canteen.EMealVoucher.Response;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
@@ -65,7 +66,7 @@ public class EMealVoucherService : IEMealVoucherService
public async Task<Pagination<EMealVoucherMyPageResponse>> GetMyEMealVoucherPageAsync(EMealVoucherPageRequest request)
{
var code = _currentUser.GetUserClaim("jinko-code");
var code = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
return await _dbContext.Queryable<EMealVoucherEntity>()
.Where(x => x.Code == code)
@@ -126,7 +127,7 @@ public class EMealVoucherService : IEMealVoucherService
var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString().Reverse().Join(string.Empty);
var originData = string.Concat(eMealVoucher.No, ":", ts, ":", eMealVoucher.Code, ":", eMealVoucherDetail.IdNo);
var qrCode = "02" + originData.ToArray().Select(x =>
var qrCode = QrCodeConstants.EMealVoucher + originData.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];

View File

@@ -1,5 +1,6 @@
using Dlhis.Canteen.MealSupplementRecord.Request;
using Dlhis.Canteen.MealSupplementRecord.Response;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
@@ -93,7 +94,7 @@ public class MealSupplementRecordService : IMealSupplementRecordService
public async Task<MealSupplementRecordMyResponse> GetMyMealSupplementRecords(MealSupplementRecordMyRequest request)
{
var code = _currentUser.GetUserClaim("jinko-code") ?? string.Empty;
var code = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode) ?? string.Empty;
var data = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.CostDateTime >= request.SearchDateTimePeriod.Start && x.CostDateTime <= request.SearchDateTimePeriod.End)

View File

@@ -0,0 +1,31 @@
using Dlhis.Entity.Canteen.Enums;
namespace Dlhis.Canteen.Order.Dto;
public class OrderCheckResultDto
{
/// <summary>
/// 消费厂区
/// </summary>
public string Factory { get; set; }
/// <summary>
/// 消费日期
/// </summary>
public DateTime CostDate { get; set; }
/// <summary>
/// 消费餐次
/// </summary>
public ShiftEnumType ShiftType { get; set; }
/// <summary>
/// 消费营业点
/// </summary>
public Guid BusinessPlaceCode { get; set; }
/// <summary>
/// 消费餐别
/// </summary>
public Guid BusinessShiftCode { get; set; }
}

View File

@@ -1,16 +0,0 @@
using Dlhis.Entity.Canteen.Enums;
namespace Dlhis.Canteen.Order.Dto;
public class OrderPreCheckDto
{
public string Factory { get; set; }
public DateTime CostDate { get; set; }
public ShiftEnumType ShiftType { get; set; }
public Guid BusinessPlaceCode { get; set; }
public Guid BusinessShiftCode { get; set; }
}

View File

@@ -7,5 +7,5 @@ namespace Dlhis.Canteen.Order.Repository;
public interface IOrderRepository : IScopeDependency
{
Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo);
Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderCheckResultDto checkData, ConsumeRequest request, GainfoEntity gainfo);
}

View File

@@ -19,7 +19,7 @@ public class OrderRepository : IOrderRepository
}
/// <inheritdoc />
public async Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo)
public async Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderCheckResultDto checkData, ConsumeRequest request, GainfoEntity gainfo)
{
var order = new CanteenOrderEntity
{

View File

@@ -0,0 +1,110 @@
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
/// <summary>
/// 生日券消费处理
/// </summary>
[Service(nameof(BalanceRecordSourceEnumType.Birthday))]
public class BirthdayConsumeHandler : IConsumeHandler
{
private readonly IDbContext _dbContext;
private readonly IOrderCommonHandler _orderCommonHandler;
private readonly IOrderRepository _orderRepository;
public BirthdayConsumeHandler(IDbContext dbContext,
IOrderCommonHandler orderCommonHandler,
IOrderRepository orderRepository)
{
_dbContext = dbContext;
_orderCommonHandler = orderCommonHandler;
_orderRepository = orderRepository;
}
public async Task<DefaultApiResult<OrderResultResponse>> ConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
{
var msg = string.Empty;
var ticketNo = request.UserUniqueNo;
var exists = await _dbContext.Queryable<TicketEntity>()
.Where(x => x.Type == TicketEnumType.Birthday)
.Where(x => x.QrCode == ticketNo)
.AnyAsync();
exists.ThrowIfFalse("生日券无效");
try
{
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime!.Value);
var isSupermarket = await _dbContext.Queryable<BusinessPlaceEntity>()
.Where(x => x.Code == checkData.BusinessPlaceCode)
.Select(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
.SingleAsync();
isSupermarket.ThrowIfFalse("请在超市消费");
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request.Adapt<ConsumeRequest>(), gainfo);
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
{
await CommonHelper.RetryAsync(async () =>
{
var ticket = await _dbContext.Queryable<TicketEntity>()
.Where(x => x.Type == TicketEnumType.Birthday)
.Where(x => x.QrCode == ticketNo)
.SingleAsync();
//金额+-
ticket.Balance += order.Amount;
(ticket.Balance < 0).ThrowIfTrue("余额不足,无法消费");
await _dbContext.Updateable<TicketEntity>()
.SetColumns(x => x.Balance == ticket.Balance)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.QrCode == ticketNo && x.Version == ticket.Version) //必须与查询时的version一致
.ExecuteCommandThrowVersionAsync();
//写入记录
var balanceRecord = order.Adapt<BalanceRecordEntity>();
balanceRecord.Remark = $"{ticket.QrCode}(生日券消费)";
await _dbContext.InsertAsync(balanceRecord);
}, 5);
});
}
catch (Exception ex)
{
msg = ex.Message;
}
//获取餐券余额
var data = await _dbContext.Queryable<TicketEntity>()
.LeftJoin<GainfoEntity>((x, ga) => x.UserCode == ga.Code)
.Where(x => x.Type == TicketEnumType.Birthday && x.QrCode == ticketNo)
.Select((x, ga) => new OrderResultResponse
{
UserCode = x.UserCode,
UserName = ga.Name,
CurrentBalance = x.Balance
})
.SingleAsync();
return new DefaultApiResult<OrderResultResponse>
{
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
Data = data,
Msg = msg
};
}
}

View File

@@ -0,0 +1,166 @@
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
/// <summary>
/// 电子餐券处理
/// </summary>
[Service(nameof(BalanceRecordSourceEnumType.EMealVoucher))]
public class EMealVoucherHandler : IConsumeHandler
{
private readonly IDbContext _dbContext;
private readonly IOrderRepository _orderRepository;
private readonly IOrderCommonHandler _orderCommonHandler;
public EMealVoucherHandler(IDbContext dbContext,
IOrderRepository orderRepository,
IOrderCommonHandler orderCommonHandler)
{
_dbContext = dbContext;
_orderRepository = orderRepository;
_orderCommonHandler = orderCommonHandler;
}
public async Task<DefaultApiResult<OrderResultResponse>> ConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
{
var msg = string.Empty;
var originData = await _dbContext.Queryable<EMealVoucherDetailQrCodeEntity>()
.Where(x => x.QrCode == request.UserUniqueNo)
.Select(x => x.OriginData)
.SingleAsync();
if (originData.IsEmpty())
{
msg = "无法识别";
return new DefaultApiResult<OrderResultResponse>
{
Code = ApiStateCode.Error,
Data = null,
Msg = msg
};
}
var originDataItems = originData.Split(":");
var no = originDataItems[0];
var idNo = originDataItems[3];
try
{
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, originData, no, idNo);
}
catch (Exception ex)
{
msg = ex.Message;
}
//获取餐券余额
var data = await _dbContext.Queryable<EMealVoucherEntity>()
.LeftJoin<EMealVoucherDetailEntity>((x, d) => x.No == d.No)
.Where((x, d) => x.No == no && d.IdNo == idNo)
.Select((x, d) => new OrderResultResponse
{
UserCode = d.IdNo,
UserName = d.Name,
CurrentBalance = d.Balance
})
.SingleAsync();
try
{
var v = data.UserCode ?? string.Empty;
var vc = v.ToCharArray().Reverse().ToList();
for (int i = 0; i < vc.Count; i++)
{
if (i + 1 > 4)
{
vc[i] = '*';
}
}
vc.Reverse();
data.UserCode = string.Join("", vc);
}
catch (Exception)
{
//ignore
}
return new DefaultApiResult<OrderResultResponse>
{
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
Data = data,
Msg = msg
};
}
/// <summary>
/// 电子餐券消费
/// </summary>
/// <param name="request"></param>
/// <param name="gainfo"></param>
/// <param name="originData"></param>
/// <param name="no"></param>
/// <param name="idNo"></param>
private async Task EMealVoucherConsumeAsync(ConsumeRequest request, GainfoEntity gainfo, string originData, string no, string idNo)
{
var now = DateTime.Now;
var current = await _dbContext.Queryable<EMealVoucherDetailEntity>()
.Where(x => x.No == no && x.IdNo == idNo)
.Select(x => new { x.Name, x.Start, x.End })
.SingleAsync();
(now >= current.Start && now <= current.End).ThrowIfFalse("餐券已过期");
var eMealVoucher = await _dbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
var isSupermarket = await _dbContext.Queryable<BusinessPlaceEntity>()
.Where(x => x.Code == checkData.BusinessPlaceCode)
.Select(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
.SingleAsync();
isSupermarket.ThrowIfTrue("禁止在超市消费");
eMealVoucher.Factories.Contains(checkData.Factory).ThrowIfFalse("禁止在当前厂区消费");
gainfo.No = originData;
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
{
await CommonHelper.RetryAsync(async () =>
{
var detail = await _dbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.No == no && x.IdNo == idNo).SingleAsync();
//金额+-
detail.Balance += order.Amount;
(detail.Balance < 0).ThrowIfTrue("余额不足,无法消费");
await _dbContext.Updateable<EMealVoucherDetailEntity>()
.SetColumns(x => x.Balance == detail.Balance)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.No == no && x.IdNo == idNo && x.Version == detail.Version) //必须与查询时的version一致
.ExecuteCommandThrowVersionAsync();
//写入记录
var balanceRecord = order.Adapt<BalanceRecordEntity>();
balanceRecord.Remark = $"({no})" + current.Name;
await _dbContext.InsertAsync(balanceRecord);
}, 5);
});
}
}

View File

@@ -0,0 +1,144 @@
using Dlhis.Canteen.Order.Dto;
using Dlhis.Canteen.Setting.Services;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Order.Services.ConsumeHandlers;
/// <summary>
/// 订单通用处理
/// </summary>
public class OrderCommonHandler : IOrderCommonHandler
{
private readonly IDbContext _dbContext;
private readonly ICanteenSettingService _canteenSettingService;
private readonly ILogger<OrderCommonHandler> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
public OrderCommonHandler(IDbContext dbContext,
IHttpContextAccessor httpContextAccessor,
ICanteenSettingService canteenSettingService,
ILogger<OrderCommonHandler> logger)
{
_dbContext = dbContext;
_canteenSettingService = canteenSettingService;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
}
/// <summary>
/// 设置设备ip
/// </summary>
/// <param name="deviceNo"></param>
public async Task SetDeviceIpInfoAsync(string deviceNo)
{
try
{
if (_httpContextAccessor.HttpContext!.Request.Headers.TryGetValue("X-Requested-DeviceIp", out var ip))
{
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceNo).SingleAsync();
device.ConnectionInfo = new
{
ip = ip.ToString()
}.ToJson();
await _dbContext.UpdateAsync(device);
}
_logger.LogInformation("设备ip获取:{deviceNo} {ip}", deviceNo, ip);
}
catch (Exception)
{
//ignore
}
}
/// <summary>
/// 消费前预检
/// </summary>
/// <param name="deviceUniqueNo">设备号</param>
/// <param name="costDateTime">消费时间</param>
/// <returns></returns>
public async Task<OrderCheckResultDto> PreCheckAsync(string deviceUniqueNo, DateTime costDateTime)
{
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).SingleAsync();
device.ThrowIfNull("设备尚未登记");
device.Enable.ThrowIfFalse("设备已被停用");
(device.Type != DeviceTypeEnumType.Meal).ThrowIfTrue("设备类型有误");
var bindingInfo = await _dbContext.Queryable<DeviceRegistryEntity>()
.LeftJoin<BusinessPlaceEntity>((x, b) => x.BusinessPlaceCode == b.Code)
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, b, bs) => bs.PlaceCode == b.Code)
.Where(x => x.DeviceUniqueNo == deviceUniqueNo && x.BusinessPlaceCode.HasValue)
.Select((x, b, bs) => new
{
b.Code,
bs.ShiftCode,
Factory = x.TenantId
})
.SingleAsync();
bindingInfo.ThrowIfNull("设备尚未登记营业点");
//获取当前消费餐次
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>()
.Where(x => x.ShiftCode == bindingInfo.ShiftCode)
.Select(x => new { x.ShiftType, x.Start, x.End })
.ToListAsync();
shifts.ThrowIfEmpty("营业点餐次尚未设置");
var shift = shifts.FirstOrDefault(x => new TimePeriod
{
Start = x.Start,
End = x.End
}.IsPresent(costDateTime));
shift.ThrowIfNull("非就餐时间");
var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, costDateTime);
return new OrderCheckResultDto
{
Factory = bindingInfo.Factory,
CostDate = costDate,
ShiftType = shift!.ShiftType,
BusinessPlaceCode = bindingInfo.Code,
BusinessShiftCode = bindingInfo.ShiftCode
};
}
/// <summary>
/// 消费更新处理
/// </summary>
/// <param name="orderId"></param>
/// <param name="action"></param>
public async Task TryConsumeAsync(long orderId, Func<Task> action)
{
try
{
await action();
await _dbContext.Updateable<CanteenOrderEntity>()
.SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Success)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.Id == orderId)
.ExecuteCommandAsync();
}
catch (Exception ex)
{
await _dbContext.Updateable<CanteenOrderEntity>()
.SetColumns(x => x.OrderStatus == CanteenOrderStatusEnumType.Failure)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.SetColumns(x => x.Result == ex.Message)
.Where(x => x.Id == orderId)
.ExecuteCommandAsync();
throw;
}
}
}

View File

@@ -0,0 +1,20 @@
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Entity.Basic.Entity;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Canteen.Order.Services;
/// <summary>
/// 消费处理器
/// </summary>
public interface IConsumeHandler : IScopeDependency
{
/// <summary>
/// 消费
/// </summary>
/// <param name="request"></param>
/// <param name="gainfo"></param>
/// <returns></returns>
Task<DefaultApiResult<OrderResultResponse>> ConsumeAsync(OrderAddRequest request, GainfoEntity gainfo);
}

View File

@@ -0,0 +1,29 @@
using Dlhis.Canteen.Order.Dto;
namespace Dlhis.Canteen.Order.Services;
public interface IOrderCommonHandler : IScopeDependency
{
/// <summary>
/// 消费更新处理
/// </summary>
/// <param name="orderId"></param>
/// <param name="action"></param>
/// <returns></returns>
Task TryConsumeAsync(long orderId, Func<Task> action);
/// <summary>
/// 设置设备ip
/// </summary>
/// <param name="deviceNo"></param>
/// <returns></returns>
Task SetDeviceIpInfoAsync(string deviceNo);
/// <summary>
/// 消费前预检
/// </summary>
/// <param name="deviceUniqueNo">设备号</param>
/// <param name="costDateTime">消费时间</param>
/// <returns></returns>
Task<OrderCheckResultDto> PreCheckAsync(string deviceUniqueNo, DateTime costDateTime);
}

View File

@@ -3,6 +3,7 @@ using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Setting.Services;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
@@ -332,7 +333,7 @@ public class BalanceService : IBalanceService
public async Task<BalanceRecordUserResultResponse> GetPageByUserAsync(BalanceRecordUserPageRequest request)
{
var userCode = _currentUser.GetUserClaim("jinko-code") ?? string.Empty;
var userCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode) ?? string.Empty;
var factory = await _dbContext.Queryable<WalletEntity>().Where(x => x.Code == request.WalletCode).Select(x => x.Factory).FirstAsync();
var factories = await _balanceRepository.GetWalletFactoriesAsync(factory);

View File

@@ -1,19 +1,14 @@
using Dlhis.Basic.Api;
using Dlhis.Canteen.Order.Dto;
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Setting.Services;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Dlhis.Entity.Device.Entities;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
using SqlSugar;
using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Order.Request;
using Dlhis.Entity.Device;
using Dlhis.Entity.Device.Enums;
using Dlhis.Entity.Device.Entities;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.Cache;
using Kurisu.AspNetCore.CustomClass;
@@ -21,6 +16,10 @@ using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
using SqlSugar;
namespace Dlhis.Canteen.Order.Services.Implements;
@@ -29,31 +28,34 @@ public class OrderService : IOrderService
private readonly ICanteenSettingService _canteenSettingService;
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 IGainfoPermissionApi _gainfoPermissionApi;
private readonly IOrderCommonHandler _orderCommonHandler;
private readonly INamedResolver _namedResolver;
private readonly ILogger<OrderService> _logger;
public OrderService(ICanteenSettingService canteenSettingService,
IDbContext dbContext,
ICurrentUser currentUser,
IHttpContextAccessor httpContextAccessor,
IBalanceRepository balanceRepository,
IOrderRepository orderRepository,
RedisCache redisCache,
IGainfoPermissionApi gainfoPermissionApi,
IOrderCommonHandler orderCommonHandler,
INamedResolver namedResolver,
ILogger<OrderService> logger)
{
_canteenSettingService = canteenSettingService;
_dbContext = dbContext;
_currentUser = currentUser;
_httpContextAccessor = httpContextAccessor;
_balanceRepository = balanceRepository;
_orderRepository = orderRepository;
_redisCache = redisCache;
_gainfoPermissionApi = gainfoPermissionApi;
_orderCommonHandler = orderCommonHandler;
_namedResolver = namedResolver;
_logger = logger;
}
@@ -74,7 +76,7 @@ public class OrderService : IOrderService
/// <returns></returns>
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{
await SetDeviceIpInfoAsync(request.DeviceUniqueNo);
await _orderCommonHandler.SetDeviceIpInfoAsync(request.DeviceUniqueNo);
await using var handler = await _redisCache.LockAsync($"consume:device:{request.UserUniqueNo}");
handler.Acquired.ThrowIfFalse("请勿频繁消费");
@@ -88,7 +90,7 @@ public class OrderService : IOrderService
{
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 jinkoCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode) ?? string.Empty;
if (jinkoCode.IsPresent())
{
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == jinkoCode).SingleAsync();
@@ -151,33 +153,47 @@ public class OrderService : IOrderService
var s = long.TryParse(request.UserUniqueNo, out var userId);
GainfoEntity gainfo;
//条码消费
if (request.Source == BalanceRecordSourceEnumType.QrCode)
{
if (request.UserUniqueNo.StartsWith("01"))
var flag = request.UserUniqueNo.Substring(0, 2);
switch (flag)
{
gainfo = await GetUserByQrCodeAsync(request.UserUniqueNo);
await CheckPermissionAsync(gainfo.Code, request.DeviceUniqueNo);
}
else if (request.UserUniqueNo.StartsWith("02"))
{
request.Source = BalanceRecordSourceEnumType.EMealVoucher;
var eMealVoucherQrCode = await _dbContext.Queryable<EMealVoucherDetailQrCodeEntity>().Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
eMealVoucherQrCode.ThrowIfNull("无法识别");
var code = eMealVoucherQrCode.OriginData.Split(':')[2];
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == code).SingleAsync();
}
else
{
throw new UserFriendlyException($"无法识别{request.UserUniqueNo}");
case QrCodeConstants.User:
{
gainfo = await GetUserByQrCodeAsync(request.UserUniqueNo);
await CheckPermissionAsync(gainfo.Code, request.DeviceUniqueNo);
}
break;
case QrCodeConstants.EMealVoucher:
{
request.Source = BalanceRecordSourceEnumType.EMealVoucher;
var eMealVoucherQrCode = await _dbContext.Queryable<EMealVoucherDetailQrCodeEntity>().Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
eMealVoucherQrCode.ThrowIfNull("无法识别");
var code = eMealVoucherQrCode.OriginData.Split(':')[2];
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == code).SingleAsync();
}
break;
case QrCodeConstants.Birthday:
{
request.Source = BalanceRecordSourceEnumType.Birthday;
var ticket = await _dbContext.Queryable<TicketEntity>().Where(x => x.Type == TicketEnumType.Birthday).Where(x => x.QrCode == request.UserUniqueNo).SingleAsync();
ticket.ThrowIfNull("无法识别");
gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == ticket.UserCode).SingleAsync();
}
break;
default: throw new UserFriendlyException($"无法识别{request.UserUniqueNo}");
}
}
else
{
//根据档案号
//区分userId和code: 工号纯数字避免跟userId相同导致查询到的消费人错误
gainfo = await _dbContext.Queryable<GainfoEntity>()
.WhereIF(request.Source == BalanceRecordSourceEnumType.Card, x => x.CardNo == request.UserUniqueNo)
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && !request.IsUserId, x => x.Code == request.UserUniqueNo)
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && request.IsUserId && s, x => x.Id == userId)
.WhereIF(request.Source == BalanceRecordSourceEnumType.Card, x => x.CardNo == request.UserUniqueNo) //卡号
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && !request.IsUserId, x => x.Code == request.UserUniqueNo) //工号
.WhereIF(request.Source != BalanceRecordSourceEnumType.Card && request.IsUserId && s, x => x.Id == userId) //user id
.SingleAsync();
}
@@ -223,7 +239,7 @@ public class OrderService : IOrderService
//一天消费金额
var dayCostMax = await _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.DayCostMax, order.TenantId, order.UserNo);
if (dayCostMax != default)
if (dayCostMax != 0)
{
//消费记录一定会有营业点代码!.Value是安全用法
var cost = todayAllBalanceRecords
@@ -235,7 +251,7 @@ public class OrderService : IOrderService
//一次消费金额
var onceCostMax = await _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.OnceCostMax, order.TenantId, order.UserNo);
if (onceCostMax != default)
if (onceCostMax != 0)
{
(Math.Abs(order.Amount) > onceCostMax).ThrowIfTrue($"单次消费金额不能超出{onceCostMax}元");
}
@@ -244,7 +260,7 @@ public class OrderService : IOrderService
if (order.BusinessPlaceCode.HasValue && supermarketCodes.Contains(order.BusinessPlaceCode.Value))
{
var dayMarketCostMax = await _canteenSettingService.GetSettingAsync<decimal>(CanteenSettingItemEnumType.DayMarketCostMax, order.TenantId, order.UserNo);
if (dayMarketCostMax != default)
if (dayMarketCostMax != 0)
{
var cost = todayAllBalanceRecords.Where(x => x.BusinessPlaceCode.HasValue)
.Where(x => supermarketCodes.Contains(x.BusinessPlaceCode.Value))
@@ -276,7 +292,9 @@ public class OrderService : IOrderService
.Where(x => x.DeviceUniqueNo == request.DeviceUniqueNo && x.BusinessPlaceCode.HasValue)
.Select((x, b, bs) => new
{
b.Code, bs.ShiftCode, Factory = x.TenantId
b.Code,
bs.ShiftCode,
Factory = x.TenantId
})
.SingleAsync();
@@ -345,7 +363,7 @@ public class OrderService : IOrderService
/// <returns></returns>
private async Task ConsumeAsync(ConsumeRequest request, GainfoEntity gainfo)
{
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
var checkData = await _orderCommonHandler.PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
if (request.Image.IsPresent())
@@ -358,7 +376,7 @@ public class OrderService : IOrderService
});
}
await TryConsumeAsync(order.Id, async () =>
await _orderCommonHandler.TryConsumeAsync(order.Id, async () =>
{
//校验
await Verify(order);
@@ -371,78 +389,11 @@ public class OrderService : IOrderService
});
}
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();
if (originData.IsEmpty())
{
msg = "无法识别";
return new DefaultApiResult<OrderResultResponse>
{
Code = ApiStateCode.Error,
Data = null,
Msg = msg
};
}
var originDataItems = originData.Split(":");
var no = originDataItems[0];
var idNo = originDataItems[3];
try
{
await EMealVoucherConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo, originData, no, idNo);
}
catch (Exception ex)
{
msg = ex.Message;
}
//获取餐券余额
var data = await _dbContext.Queryable<EMealVoucherEntity>()
.LeftJoin<EMealVoucherDetailEntity>((x, d) => x.No == d.No)
.Where((x, d) => x.No == no && d.IdNo == idNo)
.Select((x, d) => new OrderResultResponse
{
UserCode = d.IdNo,
UserName = d.Name,
CurrentBalance = d.Balance
})
.SingleAsync();
try
{
var v = data.UserCode ?? string.Empty;
var vc = v.ToCharArray().Reverse().ToList();
for (int i = 0; i < vc.Count; i++)
{
if (i + 1 > 4)
{
vc[i] = '*';
}
}
vc.Reverse();
data.UserCode = string.Join("", vc);
}
catch (Exception)
{
//ignore
}
return new DefaultApiResult<OrderResultResponse>
{
Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
Data = data,
Msg = msg
};
}
// private async Task<DefaultApiResult<OrderResultResponse>> BirthdayConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
// {
//
// }
private async Task OfflineConsumeAsync(OrderAddRequest request, GainfoEntity gainfo)
@@ -481,8 +432,9 @@ public class OrderService : IOrderService
{
var message = string.Empty;
if (request.Source == BalanceRecordSourceEnumType.EMealVoucher)
return await EMealVoucherConsumeAsync(request, gainfo);
var otherTypes = new[] { BalanceRecordSourceEnumType.EMealVoucher, BalanceRecordSourceEnumType.Birthday };
if (otherTypes.Contains(request.Source))
return await _namedResolver.GetService<IConsumeHandler>(request.Source.ToString()).ConsumeAsync(request, gainfo);
if (request.IsOffline)
await OfflineConsumeAsync(request, gainfo);
@@ -538,142 +490,6 @@ public class OrderService : IOrderService
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)
.Select(x => new { x.Name, x.Start, x.End })
.SingleAsync();
(now >= current.Start && now <= current.End).ThrowIfFalse("餐券已过期");
var eMealVoucher = await _dbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == no).SingleAsync();
var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime);
var isSupermarket = await _dbContext.Queryable<BusinessPlaceEntity>().Where(x => x.Code == checkData.BusinessPlaceCode)
.Select(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
.SingleAsync();
isSupermarket.ThrowIfTrue("禁止在超市消费");
eMealVoucher.Factories.Contains(checkData.Factory).ThrowIfFalse("禁止在当前厂区消费");
gainfo.No = originData;
var order = await _orderRepository.CreateDeviceConsumeOrderAsync(checkData, request, gainfo);
await TryConsumeAsync(order.Id, async () =>
{
await CommonHelper.RetryAsync(async () =>
{
var detail = await _dbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.No == no && x.IdNo == idNo).SingleAsync();
//金额+-
detail.Balance += order.Amount;
(detail.Balance < 0).ThrowIfTrue("余额不足,无法消费");
await _dbContext.Updateable<EMealVoucherDetailEntity>()
.SetColumns(x => x.Balance == detail.Balance)
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.No == no && x.IdNo == idNo && x.Version == detail.Version) //必须与查询时的version一致
.ExecuteCommandThrowVersionAsync();
//写入记录
var balanceRecord = order.Adapt<BalanceRecordEntity>();
balanceRecord.Remark = $"({no})" + current.Name;
await _dbContext.InsertAsync(balanceRecord);
}, 5);
});
}
/// <summary>
/// 消费前预检
/// </summary>
/// <param name="deviceUniqueNo"></param>
/// <param name="costDateTime"></param>
/// <returns></returns>
private async Task<OrderPreCheckDto> PreCheckAsync(string deviceUniqueNo, DateTime costDateTime)
{
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == deviceUniqueNo).SingleAsync();
device.ThrowIfNull("设备尚未登记");
device.Enable.ThrowIfFalse("设备已被停用");
(device.Type != DeviceTypeEnumType.Meal).ThrowIfTrue("设备类型有误");
var bindingInfo = await _dbContext.Queryable<DeviceRegistryEntity>()
.LeftJoin<BusinessPlaceEntity>((x, b) => x.BusinessPlaceCode == b.Code)
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, b, bs) => bs.PlaceCode == b.Code)
.Where(x => x.DeviceUniqueNo == deviceUniqueNo && x.BusinessPlaceCode.HasValue)
.Select((x, b, bs) => new
{
b.Code, bs.ShiftCode, Factory = x.TenantId
})
.SingleAsync();
bindingInfo.ThrowIfNull("设备尚未登记营业点");
//获取当前消费餐次
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>()
.Where(x => x.ShiftCode == bindingInfo.ShiftCode)
.Select(x => new { x.ShiftType, x.Start, x.End })
.ToListAsync();
shifts.ThrowIfEmpty("营业点餐次尚未设置");
var shift = shifts.FirstOrDefault(x => new TimePeriod
{
Start = x.Start,
End = x.End
}.IsPresent(costDateTime));
shift.ThrowIfNull("非就餐时间");
var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, costDateTime);
return new OrderPreCheckDto
{
Factory = bindingInfo.Factory,
CostDate = costDate,
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>
@@ -689,34 +505,9 @@ public class OrderService : IOrderService
if (orders.IsEmpty())
return true;
var order = orders.FirstOrDefault();
var order = orders.FirstOrDefault()!;
//存在在线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;
}
}
}

View File

@@ -1,5 +1,6 @@
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Setting.Response;
using Dlhis.Constants;
using Dlhis.Entity.Canteen.Entities;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
@@ -37,7 +38,7 @@ public class WalletService : IWalletService
/// <inheritdoc />
public async Task<decimal> GetBalanceAsync(string walletCode)
{
var userCode = _currentUser.GetUserClaim("jinko-code");
var userCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
if (!await _dbContext.Queryable<UserBalanceEntity>().Where(x => x.UserCode == userCode).AnyAsync())
{

View File

@@ -0,0 +1,50 @@
using Dlhis.Canteen.Tickets.Request;
using Dlhis.Canteen.Tickets.Response;
using Dlhis.Canteen.Tickets.Services;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Canteen.Tickets.Controllers;
/// <summary>
/// 券
/// </summary>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class TicketsController : ControllerBase
{
private readonly INamedResolver _namedResolver;
public TicketsController(INamedResolver namedResolver)
{
_namedResolver = namedResolver;
}
/// <summary>
/// 获取分页数据(按券类型)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("page")]
public async Task<Pagination<TicketPageResponse>> GetPageAsync(TicketPageRequest request)
{
return await _namedResolver.GetService<ITicketService>(request.Type.ToString()).GetPageAsync(request);
}
/// <summary>
/// 创建券
/// </summary>
/// <param name="type">券类型,需要后端支持</param>
[AllowAnonymous]
[HttpPost("{type:required}/create")]
public async Task CreateAsync(string type)
{
var srv = _namedResolver.GetService<ITicketService>(type);
srv.ThrowIfNull("不支持的券类型");
await srv.CreateAsync();
}
}

View File

@@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.Dto;
namespace Dlhis.Canteen.Tickets.Request;
public class TicketPageRequest : PageDto
{
/// <summary>
/// 类型
/// </summary>
[EnumDataType(typeof(TicketEnumType))]
public TicketEnumType Type { get; set; }
/// <summary>
/// 工号
/// </summary>
public string UserCode { get; set; }
}

View File

@@ -0,0 +1,41 @@
using Dlhis.Entity.Canteen.Enums;
namespace Dlhis.Canteen.Tickets.Response;
public class TicketPageResponse
{
/// <summary>
/// 券类型
/// </summary>
public TicketEnumType Type { get; set; }
/// <summary>
/// 工号
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 初始余额
/// </summary>
public decimal OriginalAmount { get; set; }
/// <summary>
/// 当前余额
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// 消费码
/// </summary>
public string QrCode { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Canteen.Tickets.Services;
public interface IBirthdayTicketService : ITicketService
{
}

View File

@@ -0,0 +1,24 @@
using Dlhis.Canteen.Tickets.Request;
using Dlhis.Canteen.Tickets.Response;
using Kurisu.AspNetCore.DataAccess.Dto;
namespace Dlhis.Canteen.Tickets.Services;
/// <summary>
/// 券
/// </summary>
public interface ITicketService : IScopeDependency
{
/// <summary>
/// 分页数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task<Pagination<TicketPageResponse>> GetPageAsync(TicketPageRequest request);
/// <summary>
/// 创建
/// </summary>
/// <returns></returns>
Task CreateAsync();
}

View File

@@ -0,0 +1,65 @@
using System.Text;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using SqlSugar;
namespace Dlhis.Canteen.Tickets.Services.Implements;
[Service(nameof(TicketEnumType.Birthday))]
public class BirthdayTicketService : BaseTicketService, IBirthdayTicketService
{
/// <inheritdoc />
public BirthdayTicketService(IDbContext dbContext) : base(dbContext)
{
}
/// <inheritdoc />
public override async Task CreateAsync()
{
await DbContext.IgnoreAsync<ITenantId>(async () =>
{
var today = DateTime.Today;
var userCodes = await DbContext.Queryable<GainfoEntity>()
.Where(x => SqlFunc.DateIsSame(SqlFunc.ToDate(x.Birthday), today, DateType.Day))
.Select(x => new { x.Code, x.Factory })
.ToListAsync();
const decimal amount = 30;
var todayStr = today.ToString("yyyy-MM-dd");
foreach (var item in userCodes)
{
var qrCode = GetQrCode(item.Code + todayStr);
if (!await DbContext.Queryable<TicketEntity>().Where(x => x.Type == TicketEnumType.Birthday && x.UserCode == item.Code && x.QrCode == qrCode).AnyAsync())
{
await DbContext.InsertAsync(new TicketEntity
{
Type = TicketEnumType.Birthday,
UserCode = item.Code,
OriginalBalance = amount,
Balance = amount,
QrCode = qrCode,
Remark = todayStr + "生日券",
TenantId = item.Factory
});
}
}
});
}
private static string GetQrCode(string data)
{
var qrCode = QrCodeConstants.Birthday + data.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];
return Convert.ToString(i);
}).Join(string.Empty);
return qrCode;
}
}

View File

@@ -0,0 +1,32 @@
using Dlhis.Canteen.Tickets.Request;
using Dlhis.Canteen.Tickets.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Tickets.Services.Implements;
public abstract class BaseTicketService : ITicketService
{
protected IDbContext DbContext { get; set; }
protected BaseTicketService(IDbContext dbContext)
{
DbContext = dbContext;
}
public async Task<Pagination<TicketPageResponse>> GetPageAsync(TicketPageRequest request)
{
return await DbContext.Queryable<TicketEntity>()
.LeftJoin<GainfoEntity>((x, ga) => x.UserCode == ga.Code)
.Where(x => x.Type == request.Type)
.WhereIF(request.UserCode.IsPresent(), x => x.UserCode == request.UserCode)
.Select((x, ga) => new TicketPageResponse { UserName = ga.Name }, true)
.ToPageListAsync(request);
}
public abstract Task CreateAsync();
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,19 @@
namespace Dlhis.Constants;
public class QrCodeConstants
{
/// <summary>
/// 个人码
/// </summary>
public const string User = "01";
/// <summary>
/// 电子餐券
/// </summary>
public const string EMealVoucher = "02";
/// <summary>
/// 生日券
/// </summary>
public const string Birthday = "03";
}

View File

@@ -0,0 +1,6 @@
// namespace Dlhis.Constants;
//
// public class TickConstants
// {
// public const string { get; set; }
// }

View File

@@ -0,0 +1,9 @@
namespace Dlhis.Constants;
public class UserClaimConstants
{
/// <summary>
/// 晶科工号
/// </summary>
public const string JinkoCode = "jinko-code";
}

View File

@@ -0,0 +1,55 @@
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar;
using SqlSugar;
using SqlSugar.DbConvert;
namespace Dlhis.Entity.Canteen.Entities;
/// <summary>
/// 券
/// </summary>
[SugarTable("Tickets", TableDescription = "券")]
public class TicketEntity : SugarBaseEntity, ITenantId, IVersion
{
/// <summary>
/// 类型
/// </summary>
[SugarColumn(IsNullable = false, ColumnDataType = "varchar(50)", ColumnDescription = "券类型", SqlParameterDbType = typeof(EnumToStringConvert))]
public TicketEnumType Type { get; set; }
/// <summary>
/// 工号
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "工号")]
public string UserCode { get; set; }
/// <summary>
/// 初始余额
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "初始余额")]
public decimal OriginalBalance { get; set; }
/// <summary>
/// 当前余额
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "当前余额")]
public decimal Balance { get; set; }
/// <summary>
/// 消费码
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "消费码")]
public string QrCode { get; set; }
/// <summary>
/// 备注
/// </summary>
[SugarColumn(IsNullable = true, ColumnDescription = "备注")]
public string Remark { get; set; }
public string TenantId { get; set; }
/// <inheritdoc />
public int Version { get; set; }
}

View File

@@ -37,6 +37,14 @@ public enum BalanceRecordSourceEnumType
/// </summary>
[Description("电子餐券")]
EMealVoucher,
/// <summary>
/// 生日券
/// </summary>
[Description("生日券")]
Birthday,
//*********************************************************************************************************
/// <summary>
@@ -70,7 +78,7 @@ public enum BalanceRecordSourceEnumType
/// </summary>
[Description("其他基地餐补")]
OtherTenantSubsidies,
/// <summary>
/// 余额写入
/// </summary>

View File

@@ -0,0 +1,16 @@
using System.ComponentModel;
namespace Dlhis.Entity.Canteen.Enums;
/// <summary>
/// 券类型
/// </summary>
[Description("券类型")]
public enum TicketEnumType
{
/// <summary>
/// 生日券
/// </summary>
[Description("生日券")]
Birthday = 1
}

View File

@@ -1,4 +1,5 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
@@ -95,7 +96,7 @@ public class DeviceUploadLogService : IDeviceUploadLogService
public async Task<List<DeviceUploadLogResponse>> GetMyRecordsAsync(DeviceUploadLogMyRecordRequest request)
{
var jinkoCode = _currentUser.GetUserClaim("jinko-code") ?? string.Empty;
var jinkoCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode) ?? string.Empty;
return await _dbContext.Queryable<DeviceUploadLogEntity>()
.LeftJoin<DeviceEntity>((log, d) => log.DeviceUniqueNo == d.UniqueNo)

View File

@@ -20,10 +20,13 @@
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.7" />
<PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.9.3" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dlhis.Basic.Api\Dlhis.Basic.Api.csproj" />
<ProjectReference Include="..\Dlhis.Canteen.Api\Dlhis.Canteen.Api.csproj" />
<ProjectReference Include="..\Dlhis.Constants\Dlhis.Constants.csproj" />
<ProjectReference Include="..\Dlhis.Entity\Dlhis.Entity.csproj" />
<ProjectReference Include="..\Dlhis.Jip.Api\Dlhis.Jip.Api.csproj" />
<ProjectReference Include="..\Dlhis.Sys.Api\Dlhis.Sys.Api.csproj" />

View File

@@ -1,25 +1,34 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
# 请参阅 https://aka.ms/customizecontainer 以了解如何自定义调试容器,以及 Visual Studio 如何使用此 Dockerfile 生成映像以更快地进行调试。
# 此阶段用于在快速模式(默认为调试配置)下从 VS 运行时
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
# 此阶段用于生成服务项目
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["Src/Dlhis.ScheduledTask/Dlhis.ScheduledTask.csproj", "Src/Dlhis.ScheduledTask/"]
COPY ["Src/Dlhis.Basic.Api/Dlhis.Basic.Api.csproj", "Src/Dlhis.Basic.Api/"]
COPY ["Src/Dlhis.Canteen.Api/Dlhis.Canteen.Api.csproj", "Src/Dlhis.Canteen.Api/"]
COPY ["Src/Dlhis.Constants/Dlhis.Constants.csproj", "Src/Dlhis.Constants/"]
COPY ["Src/Dlhis.Entity/Dlhis.Entity.csproj", "Src/Dlhis.Entity/"]
COPY ["Src/Dlhis.DataPermission.Model/Dlhis.DataPermission.Model.csproj", "Src/Dlhis.DataPermission.Model/"]
COPY ["Src/Dlhis.Jip.Api/Dlhis.Jip.Api.csproj", "Src/Dlhis.Jip.Api/"]
COPY ["Src/Dlhis.Sys.Api/Dlhis.Sys.Api.csproj", "Src/Dlhis.Sys.Api/"]
RUN dotnet restore "./Src/Dlhis.ScheduledTask/./Dlhis.ScheduledTask.csproj"
RUN dotnet restore "./Src/Dlhis.ScheduledTask/Dlhis.ScheduledTask.csproj"
COPY . .
WORKDIR "/src/Src/Dlhis.ScheduledTask"
RUN dotnet build "./Dlhis.ScheduledTask.csproj" -c $BUILD_CONFIGURATION -o /app/build
# 此阶段用于发布要复制到最终阶段的服务项目
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Dlhis.ScheduledTask.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# 此阶段在生产中使用,或在常规模式下从 VS 运行时使用(在不使用调试配置时为默认值)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .

View File

@@ -0,0 +1,22 @@
using Dlhis.Canteen.Api;
using Dlhis.Entity.Canteen.Enums;
using Dlhis.ScheduledTask.Attributes;
namespace Dlhis.ScheduledTask.Jobs;
/// <summary>
///
/// </summary>
[RecurringJob(nameof(CreateBirthdayTicketJob), "0 0 1 * * ?", Name = "生日券发放")]
public class CreateBirthdayTicketJob : BaseJob
{
public CreateBirthdayTicketJob(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <inheritdoc />
protected override async Task RunAsync(IServiceProvider serviceProvider)
{
await serviceProvider.GetService<ITicketApi>().CreateAsync(TicketEnumType.Birthday.ToString());
}
}

View File

@@ -7,7 +7,8 @@
},
"InternalRequest": {
"SysRequestUrl": "http://localhost:5003",
"BasicRequestUrl": "http://localhost:5002"
"BasicRequestUrl": "http://localhost:5002",
"CanteenRequestUrl": "http://localhost:5008"
},
"FaceUrlOptions": {
"Url": "http://192.168.199.115:5002/api/gainfos/face?token=",
@@ -36,18 +37,18 @@
"ClientSecret": "123456"
}
},
// "JinkoOptions": {
// "Jip": {
// "BaseUrl": "http://172.16.202.34:8000",
// "Key": "FACE-7409WIBX",
// "Secret": "be0a4b88-cd80-4509-b9b9-865205d0d3d8"
// }
// },
// "JinkoOptions": {
// "Jip": {
// "BaseUrl": "http://172.16.202.34:8000",
// "Key": "FACE-7409WIBX",
// "Secret": "be0a4b88-cd80-4509-b9b9-865205d0d3d8"
// }
// },
"JinkoOptions": {
"Jip": {
"BaseUrl": "http://jip.jinkosolar.com",
"Key": "FACE-CUOJG9N7",
"Secret": "130c2f2d-03a0-4720-8e25-538ffac7a7cb"
}
},
}
}

View File

@@ -7,7 +7,8 @@
},
"InternalRequest": {
"SysRequestUrl": "http://sys",
"BasicRequestUrl": "http://basic"
"BasicRequestUrl": "http://basic",
"CanteenRequestUrl": "http://canteen"
},
"DataProtectionOptions": {
"Enable": true,