feat 跳板机中间api

This commit is contained in:
2024-06-26 12:14:39 +08:00
parent 67fa5e5994
commit e71d714209
36 changed files with 1473 additions and 0 deletions

1
.gitignore vendored
View File

@@ -112,3 +112,4 @@ UpgradeLog*.XML
.idea
.vs
log
*.db

View File

@@ -0,0 +1,38 @@
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Dlhis.Middle.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Middle.Controllers;
/// <summary>
/// 订单
/// </summary>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
public OrdersController(IOrderService orderService)
{
_orderService = orderService;
}
/// <summary>
/// 消费
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Authorize(Policy = "consumer")]
[HttpPost]
[IgnoreTenant]
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{
return await _orderService.AddAsync(request);
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<None Remove="local.db" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dlhis.Entity\Dlhis.Entity.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="8.0.6" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlcipher" Version="2.1.8" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,24 @@
#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.
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.Middle/Dlhis.Middle.csproj", "Src/Dlhis.Middle/"]
COPY ["Src/Dlhis.Entity/Dlhis.Entity.csproj", "Src/Dlhis.Entity/"]
RUN dotnet restore "./Src/Dlhis.Middle/./Dlhis.Middle.csproj"
COPY . .
WORKDIR "/src/Src/Dlhis.Middle"
RUN dotnet build "./Dlhis.Middle.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Dlhis.Middle.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Dlhis.Middle.dll"]

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Canteen.Entities;
namespace Dlhis.Middle.Entities
{
public class LocalBalanceRecordEntity : BalanceRecordEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalBusinessPlaceEntity : BusinessPlaceEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalBusinessPlaceShiftRelationshipEntity : BusinessPlaceShiftRelationshipEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalBusinessShiftEntity : BusinessShiftEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities;
public class LocalBusinessShiftMealRelationshipEntity : BusinessShiftMealRelationshipEntity
{
public new int Id { get; set; }
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalCanteenSettingEntity : CanteenSettingEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalDepartmentEntity : DepartmentEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalDeviceEntity : DeviceEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Device.Entities;
namespace Dlhis.Middle.Entities
{
public class LocalDeviceRegistryEntity : DeviceRegistryEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalGainfoEntity : GainfoEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using Dlhis.Entity.Basic.Entity;
namespace Dlhis.Middle.Entities
{
public class LocalGainfoMealEntity : GainfoMealEntity
{
public new int Id { get; set; }
}
}

View File

@@ -0,0 +1,50 @@
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar;
using SqlSugar;
namespace Dlhis.Middle.Entities;
[SugarTable(TableName = "LocalOrders")]
public class LocalOrderEntity : SugarBaseEntity
{
public new int Id { get; set; }
/// <summary>
/// 是否离线数据
/// </summary>
public bool IsOffline { get; set; }
/// <summary>
/// 消费机器唯一信息
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 第三方订单号
/// </summary>
public string ThirdNo { get; set; }
/// <summary>
/// 档案号/QrCode/学工号
/// </summary>
public string UserUniqueNo { get; set; }
/// <summary>
/// 来源
/// </summary>
public BalanceRecordSourceEnumType Source { get; set; }
/// <summary>
/// 金额
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// 产生时间
/// </summary>
public DateTime CostDateTime { get; set; }
public bool IsSync { get; set; }
}

View File

@@ -0,0 +1,150 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Device.Entities;
using Dlhis.Middle.Entities;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Attributes;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Options;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Startup;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using SqlSugar;
namespace Dlhis.Middle.Packs;
public class SqlSugarPack : BaseAppPack
{
private const string _infoTemplate = "ExecuteCommand[{ms}] Timeout[{timeout}] \r\n {sql}";
public override void ConfigureServices(IServiceCollection services)
{
services.AddSqlSugar();
services.Replace(ServiceDescriptor.Scoped(typeof(ISqlSugarClient), sp =>
{
var options = sp.GetService<IOptions<SqlSugarOptions>>().Value;
var logger = sp.GetService<ILogger<SqlSugarClient>>();
var currentUser = sp.GetService<ICurrentUser>();
var sugarOptions = sp.GetService<ISqlSugarOptionsService>();
var configs = new List<ConnectionConfig>
{
new()
{
ConfigId = "db-main",
ConnectionString = options.DefaultConnectionString,
DbType = DbType.Sqlite,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
MoreSettings = new ConnMoreSettings
{
DisableNvarchar = true,
},
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (c, p) =>
{
if (!p.IsPrimarykey && c.PropertyType.IsGenericType && c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
|| (!p.IsPrimarykey && p.PropertyInfo.PropertyType == typeof(string)))
{
p.IsNullable = true;
}
}
}
}
};
ISqlSugarClient db = new SqlSugarClient(configs);
db.Ado.CommandTimeOut = options.Timeout;
db.Aop.OnLogExecuted = (sql, parameters) =>
{
var ms = db.Ado.SqlExecutionTime.Milliseconds;
//警告慢sql
if (ms >= options.SlowSqlTime * 1000)
logger.LogWarning(message: _infoTemplate, ms, options.Timeout, sql);
if (options.EnableSqlLog)
{
sql = UtilMethods.GetSqlString(DbType.MySql, sql, parameters);
logger.LogInformation(message: _infoTemplate, ms, options.Timeout, sql);
}
};
//软删除
db.QueryFilter.AddTableFilter<ISoftDeleted>(x => x.IsDeleted == false);
//增删改
db.Aop.DataExecuting = (oldValue, model) =>
{
if (sugarOptions.IgnoreTenant == false //启用租户
&& currentUser != null //用户信息存在
&& model.PropertyName == nameof(ITenantId.TenantId) //当前为租户字段
&& typeof(ITenantId).IsAssignableFrom(model.EntityValue.GetType())) //继承ITenantId
{
var tenant = currentUser.GetStringTenantId();
model.SetValue(tenant);
}
//处理人员和时间字段
switch (model.OperationType)
{
case DataFilterType.InsertByObject:
{
if (model.IsAnyAttribute<InsertDateTimeGenerationAttribute>())
{
model.SetValue(DateTime.Now);
}
if (currentUser != null && model.IsAnyAttribute<InsertUserGenerationAttribute>())
{
if ((int)model.EntityColumnInfo.PropertyInfo.GetValue(model.EntityValue) == 0)
{
model.SetValue(currentUser.GetStringSubjectId());
}
}
break;
}
case DataFilterType.UpdateByObject:
{
if (model.IsAnyAttribute<UpdateDateTimeGenerationAttribute>())
{
model.SetValue(DateTime.Now);
}
if (currentUser != null && model.IsAnyAttribute<UpdateUserGenerationAttribute>())
{
if ((int)model.EntityColumnInfo.PropertyInfo.GetValue(model.EntityValue) == 0)
{
model.SetValue(currentUser.GetStringSubjectId());
}
}
break;
}
}
};
return db;
}));
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
using var scope = app.ApplicationServices.CreateScope();
var db = scope.ServiceProvider.GetService<IDbContext>();
db.Client.DbMaintenance.CreateDatabase();
db.Client.CodeFirst.InitTables<LocalOrderEntity, LocalBalanceRecordEntity, LocalGainfoEntity, LocalGainfoMealEntity, LocalBusinessPlaceEntity>();
db.Client.CodeFirst.InitTables<LocalBusinessShiftEntity, LocalDeviceRegistryEntity, LocalDeviceEntity, LocalBusinessPlaceShiftRelationshipEntity, LocalBusinessShiftMealRelationshipEntity>();
db.Client.CodeFirst.InitTables<LocalCanteenSettingEntity, LocalDepartmentEntity>();
}
}

View File

@@ -0,0 +1,64 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Services;
using Dlhis.Middle.Services.Implements;
using Kurisu.AspNetCore.Startup;
using Microsoft.IdentityModel.Logging;
namespace Dlhis.Middle;
class Program
{
static void Main(string[] args)
{
KurisuHost.Run<Startup>(args);
}
}
public class Startup : DefaultStartup
{
public Startup(IConfiguration configuration) : base(configuration)
{
IdentityModelEventSource.ShowPII = true;
}
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
services.AddHttpClient("face").ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
return handler;
});
services.AddHostedService<HealthCheckBackgroundService>();
services.AddMemoryCache();
}
/// <inheritdoc />
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
base.Configure(app, env);
using var scope = app.ApplicationServices.CreateScope();
var factory = Configuration.GetSection("Factory").Value;
var ds = scope.ServiceProvider.GetService<IDataDownloadService>();
ds.TruncateAsync().Wait();
ds.DownloadAsync<LocalDepartmentEntity>(factory).Wait();
ds.DownloadAsync<LocalDeviceEntity>(factory).Wait();
ds.DownloadAsync<LocalDeviceRegistryEntity>(factory).Wait();
ds.DownloadAsync<LocalBusinessPlaceEntity>(factory).Wait();
ds.DownloadAsync<LocalBusinessShiftEntity>(factory).Wait();
ds.DownloadAsync<LocalBusinessPlaceShiftRelationshipEntity>(factory).Wait();
ds.DownloadAsync<LocalBusinessShiftMealRelationshipEntity>(factory).Wait();
ds.DownloadAsync<LocalGainfoEntity>(factory).Wait();
ds.DownloadAsync<LocalGainfoMealEntity>(factory).Wait();
}
}

View File

@@ -0,0 +1,37 @@
{
"profiles": {
"Dlhis.Middle": {
"commandName": "Project",
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5027"
},
"IIS Express": {
"commandName": "IISExpress",
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast",
"environmentVariables": {
"ASPNETCORE_URLS": "http://+:80"
},
"publishAllPorts": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:1982",
"sslPort": 0
}
}
}

View File

@@ -0,0 +1,44 @@
using Dlhis.Entity.Canteen.Enums;
namespace Dlhis.Middle.Request;
public class ConsumeRequest
{
/// <summary>
/// 是否离线数据
/// </summary>
public bool IsOffline { get; set; }
/// <summary>
/// 消费机器唯一信息
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 第三方订单号
/// </summary>
public string ThirdNo { get; set; }
/// <summary>
/// 档案号/QrCode/学工号
/// </summary>
public string UserUniqueNo { get; set; }
/// <summary>
/// 来源
/// </summary>
public BalanceRecordSourceEnumType Source { get; set; }
/// <summary>
/// 金额
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// 产生时间
/// </summary>
public DateTime CostDateTime { get; set; }
public string Image { get; set; }
}

View File

@@ -0,0 +1,63 @@
using System.ComponentModel.DataAnnotations;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Middle.Request;
public class OrderAddRequest : IValidatableObject
{
/// <summary>
/// 是否离线数据
/// </summary>
public bool IsOffline { get; set; } = false;
/// <summary>
/// 消费机器唯一信息
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 第三方订单号
/// </summary>
public string ThirdNo { get; set; }
/// <summary>
/// 档案号/QrCode/学工号
/// </summary>
[Required(ErrorMessage = "人员档案号/QrCode/学工号/userId 不能为空")]
public string UserUniqueNo { get; set; }
/// <summary>
/// 来源
/// </summary>
[EnumDataType(typeof(BalanceRecordSourceEnumType))]
public BalanceRecordSourceEnumType Source { get; set; }
/// <summary>
/// 金额
/// </summary>
[Range(0.01, double.MaxValue)]
public decimal Amount { get; set; }
/// <summary>
/// 产生时间
/// </summary>
public DateTime? CostDateTime { get; set; }
public string Image { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//处理金额
Amount = -Math.Abs(Amount);
CostDateTime ??= DateTime.Now;
if (DeviceUniqueNo.IsEmpty())
{
yield return new ValidationResult("设备号不能为空", new[] { nameof(DeviceUniqueNo) });
}
}
}

View File

@@ -0,0 +1,44 @@
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Middle.Response;
public class CanteenSettingResponse
{
public long Id { get; set; }
public CanteenSettingUnqiueEnumType UniqueType { get; set; }
public string UniqueTypeDesc => UniqueType.GetDescription();
/// <summary>
/// 唯一值
/// </summary>
public string UniqueValue { get; set; }
/// <summary>
/// 唯一值说明
/// </summary>
public string UniqueValueDesc { get; set; }
/// <summary>
/// 分类
/// </summary>
public string Catalog { get; set; }
/// <summary>
/// 参数
/// </summary>
public CanteenSettingItemEnumType Item { get; set; }
public string ItemDesc => Item.GetDescription();
/// <summary>
/// 值
/// </summary>
public string Value { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool Enable { get; set; }
}

View File

@@ -0,0 +1,35 @@
using Newtonsoft.Json;
namespace Dlhis.Middle.Response;
public class OrderResultResponse
{
/// <summary>
/// 用户工号
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 部门号
/// </summary>
public string DepartmentNo { get; set; }
/// <summary>
/// 部门名称
/// </summary>
public string DepartmentName { get; set; }
[JsonIgnore]
public decimal CurrentBalance { get; set; }
/// <summary>
/// 余额
/// </summary>
public string Balance => CurrentBalance.ToString("f2");
}

View File

@@ -0,0 +1,22 @@
using Newtonsoft.Json;
namespace Dlhis.Middle.Response;
public class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
/// <summary>
///
/// </summary>
[JsonProperty("scope")]
public string Scope { get; set; }
[JsonProperty("expires_in")]
public int Expires { get; set; }
}

View File

@@ -0,0 +1,18 @@
using Dlhis.Entity.Canteen.Enums;
namespace Dlhis.Middle.Services;
public interface ICanteenSettingService : IScopeDependency
{
/// <summary>
/// 获取人员的就餐配置信息
/// </summary>
/// <param name="userNo">就餐人员档案号</param>
/// <param name="tenantId"></param>
/// <returns></returns>
Task<Dictionary<CanteenSettingItemEnumType, string>> GetUserSettingAsync(string userNo, string tenantId);
Task<TimeOnly?> GetBusinessSwitchTimeAsync(string tenantId);
}

View File

@@ -0,0 +1,8 @@
namespace Dlhis.Middle.Services;
public interface IDataDownloadService : IScopeDependency
{
Task DownloadAsync<T>(string factory) where T : class, new();
Task TruncateAsync();
}

View File

@@ -0,0 +1,8 @@
namespace Dlhis.Middle.Services;
public interface IHealthCheckService : ISingletonDependency
{
bool GetIsOffline();
Task DoHealthCheckAsync();
}

View File

@@ -0,0 +1,10 @@
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Middle.Services;
public interface IOrderService : IScopeDependency
{
Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request);
}

View File

@@ -0,0 +1,12 @@
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Middle.Services;
public interface IRemoteOrderService : IScopeDependency
{
Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request);
Task<bool> AbleRemoteCallAsync();
}

View File

@@ -0,0 +1,104 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Mapster;
namespace Dlhis.Middle.Services.Implements;
/// <summary>
/// 餐饮配置
/// </summary>
public class CanteenSettingService : ICanteenSettingService
{
private readonly IDbContext _context;
public CanteenSettingService(IDbContext context)
{
_context = context;
}
public async Task<Dictionary<CanteenSettingItemEnumType, string>> GetUserSettingAsync(string userNo, string tenantId)
{
var settings = await _context.Queryable<CanteenSettingEntity>()
.Where(x => x.Enable)
.Where(x => x.TenantId == tenantId)
.Where(x => x.UniqueType == CanteenSettingUnqiueEnumType.Person && x.UniqueValue == userNo || x.UniqueType == CanteenSettingUnqiueEnumType.Tenant)
.ToListAsync();
//从基地 -> 个人,确保下面循环做到覆盖,并且以个人配置为主
settings = settings.OrderBy(x => x.UniqueType).ToList();
var result = new Dictionary<CanteenSettingItemEnumType, string>();
settings.ForEach(x => { result[x.Item] = x.Value; });
return result;
}
public async Task<TimeOnly?> GetBusinessSwitchTimeAsync(string tenantId)
{
var setting = await _context.Queryable<CanteenSettingEntity>()
.Where(x => x.Enable)
.Where(x => x.TenantId == tenantId)
.Where(x => x.Item == CanteenSettingItemEnumType.BusinessSwitchTime)
.FirstAsync();
try
{
return TimeOnly.Parse(setting.Value);
}
catch (Exception)
{
return null;
}
}
//*********************************************** help methods ***************************************************//
/// <summary>
/// 检验参数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="type"></param>
/// <returns></returns>
private static bool IsValidFormat<T>(string value, CanteenSettingItemEnumType? type = null)
{
try
{
//判断0/1
if (type == CanteenSettingItemEnumType.AllowSendAtMeal ||
type == CanteenSettingItemEnumType.AllowRepeatInOneShift ||
type == CanteenSettingItemEnumType.AllowNoBalance ||
type == CanteenSettingItemEnumType.AllowCrossTenant)
{
var intvaule = int.Parse(value);
if (intvaule == 0 || intvaule == 1)
{
return true;
}
else
{
return false;
}
}
if (type == CanteenSettingItemEnumType.BusinessSwitchTime)
{
var timeOnly = value.Adapt<TimeOnly>();
return timeOnly.Minute == 0 && timeOnly.Second == 0;
}
//mapster
value.Adapt<T>();
}
catch (Exception)
{
return false;
}
return true;
}
}

View File

@@ -0,0 +1,85 @@
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using SqlSugar;
namespace Dlhis.Middle.Services.Implements;
public class DataDownloadService : IDataDownloadService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IDbContext _dbContext;
private readonly string _hostName;
public DataDownloadService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IConfiguration configuration, IDbContext dbContext)
{
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_dbContext = dbContext;
_hostName = configuration.GetSection("HostName").Value;
}
public async Task DownloadAsync<T>(string factory) where T : class, new()
{
var token = await AuthAsync();
var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var requestUrl = QueryHelpers.AddQueryString($"https://{_hostName}/api/common/SysData/download", new Dictionary<string, string>
{
["factory"] = factory,
["tableName"] = typeof(T).GetCustomAttribute<SugarTable>()!.TableName
});
var response = await httpClient.GetStringAsync(requestUrl);
var pack = response.ToObject<DefaultApiResult<List<T>>>();
await _dbContext.InsertAsync(pack.Data);
}
/// <inheritdoc />
public async Task TruncateAsync()
{
await _dbContext.Client.Deleteable<LocalDepartmentEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalDeviceEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalDeviceRegistryEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalBusinessPlaceEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalBusinessShiftEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalBusinessPlaceShiftRelationshipEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalBusinessShiftMealRelationshipEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalGainfoEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalGainfoMealEntity>().ExecuteCommandAsync();
}
private async Task<string> AuthAsync()
{
var httpClient = _httpClientFactory.CreateClient("face");
if (_memoryCache.TryGetValue("token", out string token)) return token;
var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new
{
ClientId = "e509c2aaa98e300c",
ClientSecret = "6184d8979fc48105"
}), Encoding.UTF8, "application/json"));
var tokenJson = await tokenResponse.Content.ReadAsStringAsync();
var tokenInfo = JsonConvert.DeserializeObject<DefaultApiResult<TokenResponse>>(tokenJson);
token = tokenInfo.Data.AccessToken;
_memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires));
return token;
}
}

View File

@@ -0,0 +1,19 @@
namespace Dlhis.Middle.Services.Implements;
public class HealthCheckBackgroundService : BackgroundService
{
private readonly IHealthCheckService _healthCheckService;
public HealthCheckBackgroundService(IHealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await _healthCheckService.DoHealthCheckAsync();
}
}
}

View File

@@ -0,0 +1,65 @@
using System.Net.Sockets;
namespace Dlhis.Middle.Services.Implements;
public class HealthCheckService : IHealthCheckService
{
private bool _isOffline = true;
private readonly string _hostName;
private readonly ILogger<HealthCheckService> _logger;
private int _successRetry;
private int _retry;
public HealthCheckService(ILogger<HealthCheckService> logger, IConfiguration configuration)
{
_logger = logger;
_hostName = configuration.GetSection("HostName").Value;
}
public bool GetIsOffline()
{
return _isOffline;
}
public async Task DoHealthCheckAsync()
{
var tcpClient = new TcpClient();
try
{
_logger.LogInformation("tcp connecting {host} {port}", _hostName, 443);
await tcpClient.ConnectAsync(_hostName, 443);
_retry++;
_logger.LogInformation("retry {retry}", _retry);
if (tcpClient.Connected)
{
_successRetry++;
_logger.LogInformation("success connected {count}", _successRetry);
if (_successRetry == 4)
{
_isOffline = false;
_successRetry = 0;
_retry = 0;
_logger.LogInformation("current is {status}", "healthy");
}
else
{
_logger.LogInformation("wait next check in {waitTime}", _successRetry * 1000);
await Task.Delay(_successRetry * 1000);
}
}
else
{
_successRetry = 0;
_isOffline = true;
_logger.LogInformation("current is {status}", "unavailable");
await Task.Delay(2000);
}
}
catch (Exception ex)
{
_logger.LogError("fail cause :{reason}", ex.Message);
_isOffline = true;
await Task.Delay(5000);
}
}
}

View File

@@ -0,0 +1,320 @@
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 Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Dlhis.Middle.Response;
using Dlhis.Middle.Request;
namespace Dlhis.Middle.Services.Implements;
public class OrderService : IOrderService
{
private readonly ICanteenSettingService _canteenSettingService;
private readonly IRemoteOrderService _remoteOrderService;
private readonly string _factory;
private readonly IDbContext _dbContext;
private Dictionary<CanteenSettingItemEnumType, string> _settings;
public OrderService(ICanteenSettingService canteenSettingService,
IRemoteOrderService remoteOrderService,
IConfiguration configuration,
IDbContext dbContext)
{
_canteenSettingService = canteenSettingService;
_remoteOrderService = remoteOrderService;
_factory = configuration.GetSection("Factory").Value;
_dbContext = dbContext;
}
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{
if (await _remoteOrderService.AbleRemoteCallAsync())
{
return await _remoteOrderService.AddAsync(request);
}
//尝试匹配userId
_ = long.TryParse(request.UserUniqueNo, out var userId);
//根据档案号
var gainfo = await _dbContext.Queryable<GainfoEntity>()
.Where(x => x.Code == request.UserUniqueNo || x.Id == userId || x.CardNo == request.UserUniqueNo)
.FirstAsync();
var message = string.Empty;
gainfo.ThrowIfNull("无消费权限");
try
{
(await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserNo == gainfo.No).AnyAsync())
.ThrowIfFalse("余额不足,无法消费");
await ConsumeAsync(request.Adapt<ConsumeRequest>(), gainfo);
}
catch (Exception ex)
{
message = ex.Message;
}
//获取人员余额
var data = await _dbContext.Queryable<GainfoEntity>()
.LeftJoin<DepartmentEntity>((ga, department) => ga.DepartmentNo == department.No)
.LeftJoin<GainfoMealEntity>((ga, department, mealUser) => ga.No == mealUser.UserNo)
.Where(ga => ga.Id == gainfo.Id)
.Select((ga, department, mealUser) => new OrderResultResponse
{
UserCode = ga.Code,
UserName = ga.Name,
DepartmentNo = ga.DepartmentNo,
DepartmentName = department.Name,
CurrentBalance = mealUser.Balance
})
.SingleAsync();
return new DefaultApiResult<OrderResultResponse>
{
Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success,
Data = data,
Msg = message,
};
}
/// <summary>
/// 消费
/// </summary>
/// <param name="request"></param>
/// <param name="gainfo"></param>
/// <returns></returns>
private async Task ConsumeAsync(ConsumeRequest request, GainfoEntity gainfo)
{
var registry = await _dbContext.Queryable<DeviceRegistryEntity>().Where(x => x.DeviceUniqueNo == request.DeviceUniqueNo).SingleAsync();
registry.ThrowIfNull("设备尚未登记");
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == request.DeviceUniqueNo).SingleAsync();
device.ThrowIfNull("设备尚未登记");
device.Enable.ThrowIfFalse("设备已被停用");
var businessPlaceInfo = await _dbContext.Queryable<BusinessPlaceEntity>()
.LeftJoin<BusinessPlaceShiftRelationshipEntity>((x, sr) => x.Code == sr.PlaceCode)
.Where(x => x.Code == registry.BusinessPlaceCode)
.Select((x, sr) => new
{
x.Code,
sr.ShiftCode,
x.TenantId
})
.FirstAsync();
businessPlaceInfo.ThrowIfNull("设备尚未登记营业点");
//获取当前消费餐次
var shifts = await _dbContext.Queryable<BusinessShiftMealRelationshipEntity>().Where(x => x.ShiftCode == businessPlaceInfo.ShiftCode).ToListAsync();
shifts.ThrowIfEmpty("营业点餐次尚未设置");
var shift = shifts.FirstOrDefault(x => new TimePeriod
{
Start = x.Start,
End = x.End
}.IsPresent1(request.CostDateTime));
shift.ThrowIfNull("非就餐时间,无法消费");
var costDate = await GetCostDateAsync(shift, request.CostDateTime);
var balanceRecord = new BalanceRecordEntity
{
// RequestJson = request.ToJson(),
// ThirdNo = request.ThirdNo,
Type = BalanceRecordTypeEnumType.Out,
ApplicationType = CanteenApplicationTypeEnumType.Device,
Name = gainfo.Name,
Source = request.Source,
UserNo = gainfo.No,
UserCode = gainfo.Code,
Amount = request.Amount,
BusinessPlaceCode = businessPlaceInfo?.Code,
BusinessShiftCode = shift?.ShiftCode,
ShiftType = shift?.ShiftType,
CostDate = costDate.Date,
CostId = gainfo.CostId,
DepartmentNo = gainfo.DepartmentNo,
DeviceUniqueNo = request.DeviceUniqueNo,
No = _factory + "-" + SnowFlakeHelper.Instance.NextId(),
SubsidiesFromMonth = request.CostDateTime.ToString("yyyyMM"),
// IsOffline = request.IsOffline,
IsCostCrossTenant = await GetSettingAsync<bool>(businessPlaceInfo!.TenantId, CanteenSettingItemEnumType.AllowCrossTenant),
OriginTenantId = gainfo.Factory,
Werks = gainfo.Werks,
//餐别异常处理
Status = shift == null
? BalanceRecordStatusEnumType.Doubtful
: BalanceRecordStatusEnumType.Valid,
//OrderStatus = CanteenOrderStatusEnumType.Wait,
CostDateTime = request.CostDateTime,
//标识当前消费的基地
TenantId = businessPlaceInfo.TenantId,
};
//校验
await Verify(balanceRecord);
var allowNoBalance = await GetSettingAsync<bool>(balanceRecord.TenantId, CanteenSettingItemEnumType.AllowNoBalance);
await CommonHelper.RetryAsync(async () =>
{
if (!allowNoBalance)
{
var gainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserNo == balanceRecord.UserNo).SingleAsync();
//金额+-
gainfoMeal.Balance += balanceRecord.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.UserNo == balanceRecord.UserNo && x.Version == gainfoMeal.Version) //必须与查询时的version一致
.ExecuteCommandThrowVersionAsync();
}
await _dbContext.InsertAsync(balanceRecord);
}, 5);
}
//******************************************************* help methods ************************************************************/
/// <summary>
/// 获取成本日期
/// </summary>
/// <param name="shift"></param>
/// <param name="costDateTime"></param>
/// <returns></returns>
private async Task<DateTime> GetCostDateAsync(BusinessShiftMealRelationshipEntity shift, DateTime costDateTime)
{
var switchTime = await GetSettingAsync<TimeOnly?>(shift.TenantId, CanteenSettingItemEnumType.BusinessSwitchTime);
var costDate = costDateTime.Date;
if (switchTime.HasValue)
{
var beginOfDay = costDateTime.Date;
var setTime = beginOfDay.Add(switchTime.Value.ToTimeSpan());
if (costDateTime < setTime)
costDate = costDateTime.Date.AddDays(-1);
}
return costDate;
}
/// <summary>
/// 验证参数
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
private async Task Verify(BalanceRecordEntity order)
{
var beginOfDay = DateTime.Today;
var endOfDay = beginOfDay.AddDays(1).AddSeconds(-1);
//今天所有消费记录
var todayAllBalanceRecords = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserNo == order.UserNo)
.Where(x => x.Type == BalanceRecordTypeEnumType.Out)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.Where(x => x.CreateTime >= beginOfDay && x.CreateTime <= endOfDay)
.ToListAsync();
//超市营业点
var supermarketCodes = await _dbContext.Queryable<BusinessPlaceEntity>()
.Where(x => x.Catalog == CanteenBusinessPlaceCatalogEnumType.Supermarket)
.Select(x => x.Code)
.ToListAsync();
//一天消费金额
var dayCostMax = await GetSettingAsync<decimal>(order.TenantId, CanteenSettingItemEnumType.DayCostMax);
if (dayCostMax != default)
{
//must has business place code, use .Value is safe
var cost = todayAllBalanceRecords
.Where(x => !supermarketCodes.Contains(x.BusinessPlaceCode.Value)) //filter supermarket
.Sum(x => Math.Abs(x.Amount));
(cost + Math.Abs(order.Amount) > dayCostMax).ThrowIfTrue($"超出当天消费限制{dayCostMax}元,无法消费");
}
//一次消费金额
var onceCostMax = await GetSettingAsync<decimal>(order.TenantId, CanteenSettingItemEnumType.OnceCostMax);
if (onceCostMax != default)
{
(Math.Abs(order.Amount) > onceCostMax).ThrowIfTrue($"单次消费金额不能超出{onceCostMax}元");
}
//超时消费限额
var dayMarketCostMax = await GetSettingAsync<decimal>(order.TenantId, CanteenSettingItemEnumType.DayMarketCostMax);
if (dayMarketCostMax != default)
{
//current businessplace is supermarket
if (order.BusinessPlaceCode.HasValue && supermarketCodes.Contains(order.BusinessPlaceCode.Value))
{
var cost = todayAllBalanceRecords.Where(x => x.BusinessPlaceCode.HasValue)
.Where(x => supermarketCodes.Contains(x.BusinessPlaceCode.Value))
.Sum(x => Math.Abs(x.Amount));
(cost + Math.Abs(order.Amount) > dayMarketCostMax).ThrowIfTrue($"超出当天超市消费限制{dayMarketCostMax},无法消费");
}
}
//重复餐次消费
var allowRepeatInOneShift = await GetSettingAsync(order.TenantId, CanteenSettingItemEnumType.AllowRepeatInOneShift, true);
if (!allowRepeatInOneShift)
{
var costCount = todayAllBalanceRecords.Count(x => x.ShiftType == order.ShiftType);
(costCount > 1).ThrowIfTrue($"{order?.ShiftType?.GetDescription()}不允许多次消费");
}
}
/// <summary>
/// 获取参数配置
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tenantId"></param>
/// <param name="item"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
private async Task<T> GetSettingAsync<T>(string tenantId, CanteenSettingItemEnumType item, T defaultValue = default)
{
_settings ??= await _canteenSettingService.GetUserSettingAsync(string.Empty, tenantId);
if (_settings.TryGetValue(item, out var v))
{
try
{
return int.TryParse(v, out var n) ? n.Adapt<T>() : v.Adapt<T>();
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
}

View File

@@ -0,0 +1,87 @@
using System.Net.Http.Headers;
using System.Text;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
namespace Dlhis.Middle.Services.Implements;
public class RemoteOrderService : IRemoteOrderService
{
private readonly string _hostName;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IHealthCheckService _healthCheckService;
private readonly IDbContext _dbContext;
public RemoteOrderService(IHttpClientFactory httpClientFactory,
IMemoryCache memoryCache,
IConfiguration configuration,
IHealthCheckService healthCheckService,
IDbContext dbContext)
{
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_hostName = configuration.GetSection("hostName").Value;
_healthCheckService = healthCheckService;
_dbContext = dbContext;
}
/// <inheritdoc />
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{
var token = await AuthAsync();
var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync($"https://{_hostName}/api/Canteen/Orders/device", content);
var responseJson = await response.Content.ReadAsStringAsync();
return responseJson.ToObject<DefaultApiResult<OrderResultResponse>>();
}
/// <inheritdoc />
public async Task<bool> AbleRemoteCallAsync()
{
if (await _dbContext.Queryable<LocalOrderEntity>().AnyAsync(x => !x.IsSync))
{
return false;
}
return !_healthCheckService.GetIsOffline();
}
private async Task<string> AuthAsync()
{
var httpClient = _httpClientFactory.CreateClient("face");
if (_memoryCache.TryGetValue("token", out string token)) return token;
var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new
{
ClientId = "e569c2aaa98e300c",
ClientSecret = "6184d8979fc48105"
}), Encoding.UTF8, "application/json"));
var tokenJson = await tokenResponse.Content.ReadAsStringAsync();
var tokenInfo = JsonConvert.DeserializeObject<DefaultApiResult<TokenResponse>>(tokenJson);
token = tokenInfo.Data.AccessToken;
_memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires));
return token;
}
}

View File

@@ -0,0 +1,42 @@
using Kurisu.AspNetCore.CustomClass;
namespace Dlhis.Middle;
/// <summary>
/// 临时的扩展类 todo: 嵌入框架
/// </summary>
public static class TimePeriodExtensions
{
public static bool IsPresent1(this TimePeriod period, DateTime dateTime)
{
DateTime start;
DateTime end;
if (period.IsCrossDay())
{
//period = [22:00:00,03:00:00]
var currentStart = dateTime.Date.Add(period.Start.Value.ToTimeSpan());
var endOfDay = dateTime.Date.AddDays(1).AddSeconds(-1);
//assume is left range . then currentStart is 2024-04-16 22:00:00 and endOfDay is 2024-04-16 23:59:59
if (dateTime >= currentStart && dateTime <= endOfDay)
{
start = currentStart; //2024-04-16 22:00:00
end = dateTime.Date.AddDays(1).Add(period.End.Value.ToTimeSpan());//2024-04-17 03:00:00
}
else
{
start = dateTime.Date.AddDays(-1).Add(period.Start.Value.ToTimeSpan());
end = dateTime.Date.Add(period.End.Value.ToTimeSpan());
}
}
else
{
start = dateTime.Date.Add(period.Start.Value.ToTimeSpan());
end = dateTime.Date.Add(period.End.Value.ToTimeSpan());
}
return dateTime >= start && dateTime <= end;
}
}