Merge branch 'feat-wallet' into development

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

View File

@@ -3,7 +3,7 @@
public class BusinessPlaceShiftTinyResponse public class BusinessPlaceShiftTinyResponse
{ {
/// <summary> /// <summary>
/// 无用字段,暂时不删除 //todo /// 无用字段,暂时不删除
/// </summary> /// </summary>
public string CustomCode { get; set; } public string CustomCode { get; set; }

View File

@@ -0,0 +1,29 @@
using Dlhis.Basic.Common.SysData.Request;
using Dlhis.Basic.Common.SysData.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Basic.Common.SysData.Controller;
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class MiddlesController : ControllerBase
{
private readonly IHealthCheckService _healthCheckService;
public MiddlesController(IHealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
}
/// <summary>
/// 健康检查
/// </summary>
/// <param name="request"></param>
[HttpPost("healthz")]
public async Task CheckAsync(MiddleHealthCheckRequest request)
{
await _healthCheckService.CheckAsync(request.Factories);
}
}

View File

@@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;
namespace Dlhis.Basic.Common.SysData.Request;
public class HealthCheckRequest
{
[MinLength(1)]
public List<string> Factories { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Basic.Common.SysData.Request;
public class MiddleHealthCheckRequest
{
public List<string> Factories { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Basic.Common.SysData.Services;
public interface IHealthCheckService : IScopeDependency
{
Task CheckAsync(List<string> factories);
}

View File

@@ -0,0 +1,10 @@
namespace Dlhis.Basic.Common.SysData.Services.Implements;
public class HealthCheckService : IHealthCheckService
{
public async Task CheckAsync(List<string> factories)
{
//todo 状态显示
await Task.CompletedTask;
}
}

View File

@@ -1,5 +1,7 @@
using System.Reflection; using System.Reflection;
using Dlhis.Entity.Basic.Entity; using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore; using Kurisu.AspNetCore;
using Kurisu.AspNetCore.DataAccess.Entity; using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
@@ -22,27 +24,53 @@ public class SysDataService : ISysDataService
var type = App.ActiveTypes var type = App.ActiveTypes
.Where(x => x.IsDefined(typeof(SugarTable), false)) .Where(x => x.IsDefined(typeof(SugarTable), false))
.Where(x => !x.IsDefined(typeof(SkipScanAttribute), false)) .Where(x => !x.IsDefined(typeof(SkipScanAttribute), false))
.First(x => x.GetCustomAttribute<SugarTable>()!.TableName == tableName); .FirstOrDefault(x => x.GetCustomAttribute<SugarTable>()!.TableName == tableName);
var table = type.GetCustomAttribute<SugarTable>()!.TableName; var table = type?.GetCustomAttribute<SugarTable>()!.TableName;
var sql = $"select * from {table}"; var sql = $"select * from {table}";
if (type.IsAssignableTo(typeof(ITenantId)))
if (type == null)
{ {
sql += $" where tenantId = '{factory}'"; table = tableName;
}
else
{
if (type.IsAssignableTo(typeof(ITenantId)))
{
sql += $" where tenantId = '{factory}'";
}
} }
switch (tableName) switch (table)
{ {
case "Gainfo": case "Gainfo":
//sql = $"select * from Gainfo where factory = '{factory}'";
return await _dbContext.Queryable<GainfoEntity>().Where(x => x.Factory == factory).Select(x => (object)x).ToListAsync(); return await _dbContext.Queryable<GainfoEntity>().Where(x => x.Factory == factory).Select(x => (object)x).ToListAsync();
case "GainfoMeal": case "GainfoMeal":
{ {
var codes = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Factory == factory).Select(x => x.Code).ToListAsync(); var r = await _dbContext.Queryable<GainfoEntity>()
return await _dbContext.Queryable<GainfoMealEntity>().Where(x => codes.Contains(x.UserCode)).Select(x => (object)x).ToListAsync(); .Where(x => x.Factory == factory)
.GroupBy(x => x.Code)
.Select(x => new
{
UserCode = x.Code,
Balance = SqlFunc.Subqueryable<BalanceRecordEntity>().Where(p => p.UserCode == x.Code)
.Where(p => p.Source != BalanceRecordSourceEnumType.EMealVoucher && p.Status == BalanceRecordStatusEnumType.Valid && p.IsDeleted == false)
.Sum(p => p.Amount)
})
.ToListAsync();
return r.Select(x => (object)x).ToList();
} }
default: default:
return await _dbContext.Client.SqlQueryable<object>(sql).ToListAsync(); return await _dbContext.Client.SqlQueryable<object>(sql).ToListAsync();
} }
} }
public async Task<List<string>> GetWalletFactoriesAsync(string factory)
{
var wallets = await _dbContext.Queryable<WalletEntity>().ToListAsync();
var code = wallets.First(x => x.Factory == factory).Code;
return wallets.Where(x => x.Code == code).Select(x => x.Factory).ToList();
}
} }

View File

@@ -2,7 +2,6 @@
using Dlhis.Basic.Organization.Response; using Dlhis.Basic.Organization.Response;
using Dlhis.Basic.Organization.Services; using Dlhis.Basic.Organization.Services;
using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -33,15 +32,4 @@ public class GainfoMealController : ControllerBase
{ {
return await _mealUserService.GetPageAsync(request); return await _mealUserService.GetPageAsync(request);
} }
/// <summary>
/// 迁移
/// </summary>
/// <param name="request"></param>
[Transactional]
[HttpPost("migration")]
public async Task MigrationAsync(GainfoBalanceMigrationRequest request)
{
await _mealUserService.MigrationAsync(request);
}
} }

View File

@@ -1,9 +0,0 @@
namespace Dlhis.Basic.Organization.Response;
public class GainfoCurrentMealInfoResponse
{
/// <summary>
/// 余额
/// </summary>
public decimal Balance { get; set; }
}

View File

@@ -49,10 +49,15 @@ public class GainfoCurrentResponse
public DateTime Birthday { get; set; } public DateTime Birthday { get; set; }
/// <summary> /// <summary>
/// 厂区 /// 厂区编码
/// </summary> /// </summary>
public string Factory { get; set; } public string Factory { get; set; }
/// <summary>
/// 厂区名称
/// </summary>
public string FactoryName { get; set; }
/// <summary> /// <summary>
/// 卡类型 /// 卡类型
/// </summary> /// </summary>
@@ -62,9 +67,4 @@ public class GainfoCurrentResponse
/// 卡类型名称 /// 卡类型名称
/// </summary> /// </summary>
public string CardTypeName { get; set; } public string CardTypeName { get; set; }
/// <summary>
/// 就餐信息
/// </summary>
public GainfoCurrentMealInfoResponse MealInfo { get; set; }
} }

View File

@@ -1,5 +1,6 @@
using Dlhis.Entity.Basic.Enums; using Dlhis.Entity.Basic.Enums;
using Kurisu.AspNetCore.Utils.Extensions; using Kurisu.AspNetCore.Utils.Extensions;
using Newtonsoft.Json;
namespace Dlhis.Basic.Organization.Response; namespace Dlhis.Basic.Organization.Response;
@@ -20,7 +21,10 @@ public class GainfoMealResponse
/// <summary> /// <summary>
/// 余额 /// 余额
/// </summary> /// </summary>
public decimal Balance { get; set; } public string Balance => CurrentBalance.ToString("F2");
[JsonIgnore]
public decimal CurrentBalance { get; set; }
// /// <summary> // /// <summary>
// /// 余额(充值) // /// 余额(充值)
@@ -41,7 +45,9 @@ public class GainfoMealResponse
/// <summary> /// <summary>
/// 餐补总额 /// 餐补总额
/// </summary> /// </summary>
public decimal? MealSupplementAmount { get; set; } public string MealSupplementAmount => CurrentMealSupplementAmount.ToString("F2");
public decimal CurrentMealSupplementAmount { get; set; }
/// <summary> /// <summary>
/// 档案状态 /// 档案状态

View File

@@ -7,6 +7,4 @@ namespace Dlhis.Basic.Organization.Services;
public interface IGainfoMealService : IScopeDependency public interface IGainfoMealService : IScopeDependency
{ {
Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request); Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request);
Task MigrationAsync(GainfoBalanceMigrationRequest request);
} }

View File

@@ -9,7 +9,6 @@ using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions; using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions; using Kurisu.AspNetCore.Utils.Extensions;
using SqlSugar; using SqlSugar;
@@ -28,138 +27,47 @@ public class GainfoMealService : IGainfoMealService
public async Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request) public async Task<Pagination<GainfoMealResponse>> GetPageAsync(GainfoMealPageRequest request)
{ {
var tenantId = _currentUser.GetStringTenantId(); var factory = _currentUser.GetStringTenantId();
var factories = await GetWalletFactoriesAsync(factory);
var page = await _dbContext.Queryable<GainfoMealEntity>() return await _dbContext.Queryable<GainfoEntity>().AS(request.IsLeave ? "GainfoLeave" : "Gainfo")
.LeftJoin<GainfoEntity>((meal, gainfo) => meal.UserCode == gainfo.Code) .LeftJoin<DepartmentEntity>((x, dept) => dept.No == x.DepartmentNo)
.LeftJoin<GainfoLeaveEntity>((meal, gainfo, gainfoLeave) => meal.UserCode == gainfoLeave.Code) .WhereIF(request.Search.IsPresent(), x => x.Code == request.Search || x.Name == request.Search)
.LeftJoin<DepartmentEntity>((meal, gainfo, gainfoLeave, dept1) => dept1.No == gainfo.DepartmentNo) .Where(x => SqlFunc.Subqueryable<BalanceRecordEntity>().Where(p => p.UserCode == x.Code && factories.Contains(p.TenantId)).Any())
.LeftJoin<DepartmentEntity>((meal, gainfo, gainfoLeave, dept1, dept2) => dept2.No == gainfoLeave.DepartmentNo) .WhereIF(request.IsLeave && request.SearchDateTimePeriod.HasValue(), x => x.ResignationDate >= request.SearchDateTimePeriod.Start &&
.WhereIF(request.Search.IsPresent(), (meal, gainfo, gainfoLeave, dept1, dept2) => meal.UserCode == request.Search x.ResignationDate <= request.SearchDateTimePeriod.End)
|| gainfo.Name == request.Search .Select((x, dept) => new GainfoMealResponse
|| gainfoLeave.Name == request.Search)
.Where((meal, gainfo, gainfoLeave) => gainfo.Factory == tenantId || gainfoLeave.Factory == tenantId)
.WhereIF(request.IsLeave, (meal, gainfo, gainfoLeave) => SqlFunc.Subqueryable<GainfoLeaveEntity>().Where(x => x.Code == meal.UserCode).Any())
.WhereIF(request.IsLeave && request.SearchDateTimePeriod.HasValue(), (meal, gainfo, gainfoLeave) => gainfoLeave.ResignationDate >= request.SearchDateTimePeriod.Start && gainfoLeave.ResignationDate <= request.SearchDateTimePeriod.End)
.Select((meal, gainfo, gainfoLeave, dept1, dept2) => new GainfoMealResponse
{ {
Balance = meal.Balance, UserCode = x.Code,
UserCode = meal.UserCode, UserName = x.Name,
UserName = SqlFunc.IsNull(gainfo.Name, gainfoLeave.Name), UserNo = x.No,
UserNo = SqlFunc.IsNull(gainfo.No, gainfoLeave.No), DepartmentName = dept.Name,
DepartmentName = SqlFunc.IsNull(dept1.Name, dept2.Name), Status = request.IsLeave
Status = SqlFunc.IsNullOrEmpty(gainfo.No) ? GainfoStatusEnumType.Leave : GainfoStatusEnumType.Working ? GainfoStatusEnumType.Leave
: GainfoStatusEnumType.Working,
CurrentMealSupplementAmount = SqlFunc.Subqueryable<MealSupplementRecordEntity>()
.Where(p => p.Code == x.Code)
.Where(p => factories.Contains(p.Factory))
.WhereIF(request.SearchDateTimePeriod.HasValue(), p => p.Date >= request.SearchDateTimePeriod.Start && p.Date <= request.SearchDateTimePeriod.End)
.Sum(p => p.Amount),
CurrentBalance = SqlFunc.Subqueryable<BalanceRecordEntity>()
.Where(p => factories.Contains(p.TenantId))
.Where(p => p.UserCode == x.Code && p.Status == BalanceRecordStatusEnumType.Valid && p.IsDeleted == false)
.Where(p => p.Source != BalanceRecordSourceEnumType.EMealVoucher)
.Sum(p => p.Amount)
}) })
.ToPageListAsync(request); .ToPageListAsync(request);
var userCodes = page.Data.Select(x => x.UserCode).ToList();
var summary = await _dbContext.Queryable<MealSupplementRecordEntity>()
.Where(x => userCodes.Contains(x.Code))
.WhereIF(request.SearchDateTimePeriod.HasValue(), x => x.Date >= request.SearchDateTimePeriod.Start && x.Date <= request.SearchDateTimePeriod.End)
.GroupBy(x => x.Code)
.Select(x => new
{
x.Code,
Amount = SqlFunc.AggregateSum(x.Amount)
})
.ToListAsync();
page.Data.ForEach(x => { x.MealSupplementAmount = summary.FirstOrDefault(item => item.Code == x.UserCode)?.Amount ?? 0; });
return page;
} }
public async Task MigrationAsync(GainfoBalanceMigrationRequest request)
//***********************************************************************************************************************************************************************
public async Task<List<string>> GetWalletFactoriesAsync(string factory)
{ {
//只能针对离职人员 var wallets = await _dbContext.Queryable<WalletEntity>().ToListAsync();
var gainfoLeave = await _dbContext.Queryable<GainfoLeaveEntity>().Where(x => x.Code == request.BeforeCode).SingleAsync(); var code = wallets.First(x => x.Factory == factory).Code;
gainfoLeave.ThrowIfNull("需要对已离职人员迁移");
var beforeBalance = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.BeforeCode).Select(x => x.Balance).SingleAsync(); return wallets.Where(x => x.Code == code).Select(x => x.Factory).ToList();
(beforeBalance <= 0).ThrowIfTrue("不可操作,余额不足");
var now = DateTime.Now;
await _dbContext.InsertAsync(new BalanceRecordEntity
{
No = SnowFlakeHelper.Instance.NextId().ToString(),
UserNo = gainfoLeave.No,
Name = gainfoLeave.Name,
UserCode = gainfoLeave.Code,
DepartmentNo = gainfoLeave.DepartmentNo,
Source = BalanceRecordSourceEnumType.BalanceMigration,
Type = BalanceRecordTypeEnumType.In,
Amount = -Math.Abs(beforeBalance),
BusinessPlaceCode = null,
BusinessShiftCode = null,
ShiftType = null,
CostDate = now.Date,
DeviceUniqueNo = null,
IP = null,
CostId = gainfoLeave.CostId,
OriginTenantId = gainfoLeave.Factory,
IsCostCrossTenant = false,
Status = BalanceRecordStatusEnumType.Valid,
CostDateTime = DateTime.Now,
Remark = $"{gainfoLeave.Code}:余额转出",
ApplicationType = CanteenApplicationTypeEnumType.BalanceMigration,
TenantId = gainfoLeave.Factory,
Werks = gainfoLeave.Werks,
IsDeleted = false,
});
var beforeBalanceAmount = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == gainfoLeave.Code)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.SumAsync(x => x.Amount);
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Balance == beforeBalanceAmount)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.SetColumns(x => x.Version == x.Version + 1)
.Where(x => x.UserCode == request.BeforeCode) //不需要判断version
.ExecuteCommandAsync();
//转移到现有人员
var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == request.NowCode).SingleAsync();
gainfo.ThrowIfNull("目标人员不存在");
await _dbContext.InsertAsync(new BalanceRecordEntity
{
No = SnowFlakeHelper.Instance.NextId().ToString(),
UserNo = gainfo.No,
Name = gainfo.Name,
UserCode = gainfo.Code,
DepartmentNo = gainfo.DepartmentNo,
Source = BalanceRecordSourceEnumType.BalanceMigration,
Type = BalanceRecordTypeEnumType.In,
Amount = beforeBalance,
BusinessPlaceCode = null,
BusinessShiftCode = null,
ShiftType = null,
CostDate = now.Date,
DeviceUniqueNo = null,
IP = null,
CostId = gainfo.CostId,
OriginTenantId = gainfo.Factory,
IsCostCrossTenant = false,
Status = BalanceRecordStatusEnumType.Valid,
CostDateTime = DateTime.Now,
Remark = $"{gainfoLeave.Code}:余额转入",
ApplicationType = CanteenApplicationTypeEnumType.MealSupplement,
TenantId = gainfo.Factory,
Werks = gainfo.Werks,
IsDeleted = false,
});
var nowGainfoMeal = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.NowCode).SingleAsync();
var nowBalance = nowGainfoMeal.Balance + beforeBalance;
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Balance == nowBalance)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.SetColumns(x => x.Version == x.Version + 1)
.Where(x => x.UserCode == request.NowCode && x.Version == nowGainfoMeal.Version)
.ExecuteCommandThrowVersionAsync("转入失败");
} }
} }

View File

@@ -197,10 +197,9 @@ public class GainfoService : IGainfoService
var info = await _gainfoStore.Queryable(GainfoStatusEnumType.Working) var info = await _gainfoStore.Queryable(GainfoStatusEnumType.Working)
.LeftJoin<DepartmentEntity>((ga, department) => ga.DepartmentNo == department.No) .LeftJoin<DepartmentEntity>((ga, department) => ga.DepartmentNo == department.No)
.LeftJoin<GainfoMealEntity>((ga, department, mealUser) => ga.Code == mealUser.UserCode) .LeftJoin<BasicTypeEntity>((ga, department, type) => type.Code == ga.CardType.ToString() && type.Type == "timeperiod")
.LeftJoin<BasicTypeEntity>((ga, department, mealUser, type) => type.Code == ga.CardType.ToString() && type.Type == "timeperiod")
.Where((ga, department) => ga.Id == gainfo.Id) .Where((ga, department) => ga.Id == gainfo.Id)
.Select((ga, department, mealUser, type) => new GainfoCurrentResponse .Select((ga, department, type) => new GainfoCurrentResponse
{ {
UserNo = ga.No, UserNo = ga.No,
Birthday = ga.Birthday, Birthday = ga.Birthday,
@@ -210,10 +209,6 @@ public class GainfoService : IGainfoService
UserCode = ga.Code, UserCode = ga.Code,
UserName = ga.Name, UserName = ga.Name,
Factory = ga.Factory, Factory = ga.Factory,
MealInfo = new GainfoCurrentMealInfoResponse
{
Balance = mealUser.Balance
},
CardType = ga.CardType, CardType = ga.CardType,
CardTypeName = type.Display CardTypeName = type.Display
}).SingleAsync(); }).SingleAsync();
@@ -225,7 +220,7 @@ public class GainfoService : IGainfoService
var tenantResult = await _tenantApi.GetTenantByCodeAsync(info.Factory); var tenantResult = await _tenantApi.GetTenantByCodeAsync(info.Factory);
if (tenantResult is { Data: not null }) if (tenantResult is { Data: not null })
{ {
info.Factory = tenantResult.Data.Name; info.FactoryName = tenantResult.Data.Name;
} }
} }
catch (Exception) catch (Exception)

View File

@@ -187,37 +187,6 @@ public class MealSupplementRecordService : IMealSupplementRecordService
DepartmentNo = gainfo.DepartmentNo, DepartmentNo = gainfo.DepartmentNo,
DeviceUniqueNo = null DeviceUniqueNo = null
}); });
await CommonHelper.RetryAsync(async () =>
{
var mealUser = await _dbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == request.Code).FirstAsync();
if (mealUser == null)
{
mealUser = new GainfoMealEntity
{
UserCode = gainfo.Code,
Balance = 0,
BalanceOfRecharge = 0,
BalanceOfSubsidies = 0,
Version = 0
};
await _dbContext.InsertAsync(mealUser);
}
//重新核算
var balance = await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == request.Code)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.SumAsync(x => x.Amount);
await _dbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Balance == balance)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == mealUser.UserCode && x.Version == mealUser.Version)
.ExecuteCommandThrowVersionAsync();
}, 5);
} }
} }
} }

View File

@@ -1,16 +1,11 @@
using System.ComponentModel.DataAnnotations; using System.Data;
using System.Data;
using Dlhis.Canteen.Order.Request; using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response; using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Order.Services; using Dlhis.Canteen.Order.Services;
using Dlhis.Entity.Canteen.Entities;
using Kurisu.AspNetCore;
using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop; using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SqlSugar;
namespace Dlhis.Canteen.Order.Controllers; namespace Dlhis.Canteen.Order.Controllers;
@@ -167,36 +162,4 @@ public class BalancesController : ControllerBase
{ {
await _balanceService.ManuallyImportBalanceAndReCalcAsync(requests); await _balanceService.ManuallyImportBalanceAndReCalcAsync(requests);
} }
/// <summary>
/// 重算
/// </summary>
/// <param name="request"></param>
[Authorize(Roles = "admin")]
[HttpPost("recalc")]
[IgnoreTenant]
[Transactional(IsolationLevel.ReadCommitted)]
public async Task ReCalcAsync(BalanceReCalcRequest request)
{
await _balanceService.ReCalcAsync(request.UserCode);
}
[HttpPost("recalc1")]
[Transactional(IsolationLevel.ReadCommitted)]
[IgnoreTenant]
public async Task ReC5()
{
var sp = App.GetServiceProvider();
var db = sp.GetService<IDbContext>();
var middleService = sp.GetService<IMiddleService>();
var others = await db.Queryable<BalanceRecordEntity>().AS("LocalBalanceRecordEntity")
.Where(x => SqlFunc.Subqueryable<BalanceRecordEntity>().Where(p => p.No == x.No).NotAny())
.ToListAsync();
foreach (var item in others)
{
await middleService.MiddleUploadAsync(item);
}
}
} }

View File

@@ -1,5 +1,4 @@
using Dlhis.Canteen.Dishes.Request; using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response; using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Order.Services; using Dlhis.Canteen.Order.Services;
using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.DataAccess.Dto;
@@ -19,12 +18,10 @@ namespace Dlhis.Canteen.Order.Controllers;
public class OrdersController : ControllerBase public class OrdersController : ControllerBase
{ {
private readonly IOrderService _orderService; private readonly IOrderService _orderService;
private readonly IBookingOrderService _bookingOrderService;
public OrdersController(IOrderService orderService, IBookingOrderService bookingOrderService) public OrdersController(IOrderService orderService)
{ {
_orderService = orderService; _orderService = orderService;
_bookingOrderService = bookingOrderService;
} }
/// <summary> /// <summary>
@@ -37,8 +34,7 @@ public class OrdersController : ControllerBase
[IgnoreTenant] [IgnoreTenant]
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request) public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{ {
var result = await _orderService.AddAsync(request); return await _orderService.AddAsync(request);
return result.Response;
} }
/// <summary> /// <summary>
@@ -51,8 +47,7 @@ public class OrdersController : ControllerBase
[IgnoreTenant] [IgnoreTenant]
public async Task<DefaultApiResult<OrderResultResponse>> DeviceConsume(OrderAddRequest request) public async Task<DefaultApiResult<OrderResultResponse>> DeviceConsume(OrderAddRequest request)
{ {
var result = await _orderService.AddAsync(request); return await _orderService.AddAsync(request);
return result.Response;
} }
/// <summary> /// <summary>
@@ -66,56 +61,56 @@ public class OrdersController : ControllerBase
return await _orderService.GetOrdersAggregationAsync(page); return await _orderService.GetOrdersAggregationAsync(page);
} }
/// <summary> // /// <summary>
/// 取消订单 // /// 取消订单
/// </summary> // /// </summary>
/// <param name="request"></param> // /// <param name="request"></param>
/// <returns></returns> // /// <returns></returns>
[HttpPut("user-cancel")] // [HttpPut("user-cancel")]
[Transactional] // [Transactional]
[IgnoreTenant] // [IgnoreTenant]
public async Task CancelOrderAsync(OrderCancelRequest request) // public async Task CancelOrderAsync(OrderCancelRequest request)
{ // {
await _bookingOrderService.UserCancelOrderAsync(request); // await _bookingOrderService.UserCancelOrderAsync(request);
} // }
//
/// <summary> // /// <summary>
/// 取消订单 // /// 取消订单
/// </summary> // /// </summary>
/// <param name="request"></param> // /// <param name="request"></param>
/// <returns></returns> // /// <returns></returns>
[HttpPut("manager-cancel")] // [HttpPut("manager-cancel")]
[Transactional] // [Transactional]
[IgnoreTenant] // [IgnoreTenant]
public async Task ManagerCancelOrderAsync(OrderCancelRequest request) // public async Task ManagerCancelOrderAsync(OrderCancelRequest request)
{ // {
await _bookingOrderService.ManagerCancelOrderAsync(request); // await _bookingOrderService.ManagerCancelOrderAsync(request);
} // }
//
//************************************************************** 订餐功能 ********************************************************************************** // //************************************************************** 订餐功能 **********************************************************************************
//
/// <summary> // /// <summary>
/// 取消订单 // /// 取消订单
/// </summary> // /// </summary>
/// <param name="request"></param> // /// <param name="request"></param>
/// <returns></returns> // /// <returns></returns>
[HttpPost("booking")] // [HttpPost("booking")]
[Transactional] // [Transactional]
[IgnoreTenant] // [IgnoreTenant]
public async Task<BookingResponse> Booking(BookingMealRequest request) // public async Task<BookingResponse> Booking(BookingMealRequest request)
{ // {
return await _bookingOrderService.BookingAsync(request); // return await _bookingOrderService.BookingAsync(request);
} // }
//
/// <summary> // /// <summary>
/// 订单分页 // /// 订单分页
/// </summary> // /// </summary>
/// <param name="request"></param> // /// <param name="request"></param>
/// <returns></returns> // /// <returns></returns>
[HttpGet("booking/page")] // [HttpGet("booking/page")]
public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync([FromQuery] OrderBookingPageRequest request) // public async Task<Pagination<OrderBookingResponse>> GetBookingPageAsync([FromQuery] OrderBookingPageRequest request)
{ // {
return await _bookingOrderService.GetBookingPageAsync(request); // return await _bookingOrderService.GetBookingPageAsync(request);
} // }
} }

View File

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

View File

@@ -0,0 +1,40 @@
using Dlhis.Entity.Canteen.Entities;
namespace Dlhis.Canteen.Order.Repository;
public interface IBalanceRepository : IScopeDependency
{
/// <summary>
/// 获取余额
/// </summary>
/// <param name="userCode"></param>
/// <param name="factory"></param>
/// <returns></returns>
Task<decimal> GetBalanceAsync(string userCode, string factory);
/// <summary>
/// 获取消费明细
/// </summary>
/// <param name="userCode"></param>
/// <param name="factory"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
Task<List<BalanceRecordEntity>> GetBalanceRecordsAsync(string userCode, string factory, DateTime startTime, DateTime endTime);
/// <summary>
/// 获取钱包厂区
/// </summary>
/// <param name="factory"></param>
/// <returns></returns>
Task<List<string>> GetWalletFactoriesAsync(string factory);
/// <summary>
/// 检测余额是否足够
/// </summary>
/// <param name="userCode"></param>
/// <param name="factory"></param>
/// <param name="cost"></param>
/// <returns></returns>
Task CheckConsumableAsync(string userCode, string factory, decimal cost);
}

View File

@@ -0,0 +1,11 @@
using Dlhis.Canteen.Order.Dto;
using Dlhis.Canteen.Order.Request;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
namespace Dlhis.Canteen.Order.Repository;
public interface IOrderRepository : IScopeDependency
{
Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo);
}

View File

@@ -0,0 +1,60 @@
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Order.Repository.Implements;
public class BalanceRepository : IBalanceRepository
{
private readonly IDbContext _dbContext;
public BalanceRepository(IDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<decimal> GetBalanceAsync(string userCode, string factory)
{
var queryable = _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == userCode && x.Status == BalanceRecordStatusEnumType.Valid)
.Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher);
if (!factory.IsPresent())
{
return await queryable.SumAsync(x => x.Amount);
}
var factories = await GetWalletFactoriesAsync(factory);
return await queryable.Where(x => factories.Contains(x.TenantId)).SumAsync(x => x.Amount);
}
public async Task<List<BalanceRecordEntity>> GetBalanceRecordsAsync(string userCode, string factory, DateTime startTime, DateTime endTime)
{
var factories = await GetWalletFactoriesAsync(factory);
return await _dbContext.Queryable<BalanceRecordEntity>()
.Where(x => x.UserCode == userCode)
.Where(x => factories.Contains(x.TenantId))
.Where(x => x.Type == BalanceRecordTypeEnumType.Out)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid)
.Where(x => x.CostDateTime >= startTime && x.CostDateTime <= endTime)
.ToListAsync();
}
public async Task<List<string>> GetWalletFactoriesAsync(string factory)
{
var wallets = await _dbContext.Queryable<WalletEntity>().ToListAsync();
var code = wallets.First(x => x.Factory == factory).Code;
return wallets.Where(x => x.Code == code).Select(x => x.Factory).ToList();
}
public async Task CheckConsumableAsync(string userCode, string factory, decimal cost)
{
var balance = await GetBalanceAsync(userCode, factory);
var isEnough = balance - Math.Abs(cost) >= 0;
isEnough.ThrowIfFalse($"钱包余额不足({balance}元)");
}
}

View File

@@ -0,0 +1,68 @@
using Dlhis.Canteen.Order.Dto;
using Dlhis.Canteen.Order.Request;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Order.Repository.Implements;
public class OrderRepository : IOrderRepository
{
private readonly IDbContext _dbContext;
public OrderRepository(IDbContext dbContext)
{
_dbContext = dbContext;
}
/// <inheritdoc />
public async Task<CanteenOrderEntity> CreateDeviceConsumeOrderAsync(OrderPreCheckDto checkData, ConsumeRequest request, GainfoEntity gainfo)
{
var order = new CanteenOrderEntity
{
RequestJson = request.ToJson(),
IsOffline = request.IsOffline,
No = SnowFlakeHelper.Instance.NextId().ToString(),
ThirdNo = request.ThirdNo,
Type = BalanceRecordTypeEnumType.Out,
ApplicationType = CanteenApplicationTypeEnumType.Device,
Name = gainfo.Name,
Source = request.Source,
UserNo = gainfo.No,
UserCode = gainfo.Code,
Amount = request.Amount,
BusinessPlaceCode = checkData.BusinessPlaceCode,
BusinessShiftCode = checkData.BusinessShiftCode,
ShiftType = checkData.ShiftType,
CostDate = checkData.CostDate,
CostDateTime = request.CostDateTime,
CostId = gainfo.CostId,
DepartmentNo = gainfo.DepartmentNo,
DeviceUniqueNo = request.DeviceUniqueNo,
Remark = null,
DeliveryAddress = null,
Result = null,
IP = null,
IsCostCrossTenant = gainfo.Factory != checkData.Factory,
Werks = gainfo.Werks,
OriginTenantId = gainfo.Factory,
//标识当前消费的基地
TenantId = checkData.Factory,
Status = BalanceRecordStatusEnumType.Valid,
OrderStatus = CanteenOrderStatusEnumType.Wait,
IsDeleted = false,
};
var orderId = await _dbContext.InsertReturnIdentityAsync(order);
order.Id = orderId;
return order;
}
}

View File

@@ -17,6 +17,11 @@ public class BalanceRecordUserPageRequest : PageDto, IValidatableObject
/// </summary> /// </summary>
public DateTimePeriod SearchDateTimePeriod { get; set; } public DateTimePeriod SearchDateTimePeriod { get; set; }
/// <summary>
/// 钱包code
/// </summary>
[Required(ErrorMessage = "请选择钱包")]
public string WalletCode { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{ {
@@ -27,4 +32,4 @@ public class BalanceRecordUserPageRequest : PageDto, IValidatableObject
yield break; yield break;
} }
} }

View File

@@ -32,4 +32,13 @@ public class OrderResultResponse
/// 余额 /// 余额
/// </summary> /// </summary>
public string Balance => CurrentBalance.ToString("f2"); public string Balance => CurrentBalance.ToString("f2");
}
[JsonIgnore]
public decimal CurrentTotalBalance { get; set; }
/// <summary>
/// 总余额
/// </summary>
public string TotalBalance => CurrentTotalBalance.ToString("f2");
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
using System.ComponentModel.DataAnnotations;
using Dlhis.Canteen.Setting.Response;
using Dlhis.Canteen.Setting.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Canteen.Setting.Controllers;
/// <summary>
/// 钱包
/// </summary>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class WalletsController : ControllerBase
{
private readonly IWalletService _walletService;
public WalletsController(IWalletService walletService)
{
_walletService = walletService;
}
/// <summary>
/// 钱包列表
/// </summary>
/// <returns></returns>
[HttpGet("list")]
public async Task<List<WalletResponse>> GetListAsync()
{
return await _walletService.GetListAsync();
}
/// <summary>
/// 余额
/// </summary>
/// <param name="walletCode">钱包code</param>
/// <returns></returns>
[HttpGet("balance")]
[IgnoreTenant]
public async Task<decimal> GetBalanceAsync([Required] string walletCode)
{
return await _walletService.GetBalanceAsync(walletCode);
}
}

View File

@@ -0,0 +1,19 @@
namespace Dlhis.Canteen.Setting.Response;
public class WalletResponse
{
/// <summary>
/// 钱包编码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 钱包名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 厂区
/// </summary>
public List<string> Factories { get; set; }
}

View File

@@ -7,10 +7,25 @@ namespace Dlhis.Canteen.Setting.Services;
public interface ICanteenSettingService : IScopeDependency public interface ICanteenSettingService : IScopeDependency
{ {
/// <summary>
/// 获取配置分页数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task<Pagination<CanteenSettingResponse>> GetPageAsync(CanteenSettingPageRequest request); Task<Pagination<CanteenSettingResponse>> GetPageAsync(CanteenSettingPageRequest request);
/// <summary>
/// 保存配置
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task SaveSettingAsync(CanteenSettingSaveRequest request); Task SaveSettingAsync(CanteenSettingSaveRequest request);
/// <summary>
/// 设置配置启用开关
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task SetEnableAsync(CanteenSettingSetEnableRequest request); Task SetEnableAsync(CanteenSettingSetEnableRequest request);
/// <summary> /// <summary>
@@ -21,7 +36,21 @@ public interface ICanteenSettingService : IScopeDependency
/// <returns></returns> /// <returns></returns>
Task<Dictionary<CanteenSettingItemEnumType, string>> GetUserSettingAsync(string userNo, string tenantId); Task<Dictionary<CanteenSettingItemEnumType, string>> GetUserSettingAsync(string userNo, string tenantId);
/// <summary>
/// 获取营业点切换时间
/// </summary>
/// <param name="tenantId"></param>
/// <returns></returns>
Task<TimeOnly?> GetBusinessSwitchTimeAsync(string tenantId); Task<TimeOnly?> GetBusinessSwitchTimeAsync(string tenantId);
}
Task<T> GetSettingAsync<T>(CanteenSettingItemEnumType item, string factory, string userNo, T defaultValue = default);
/// <summary>
/// 获取消费日期
/// </summary>
/// <param name="factory"></param>
/// <param name="costDateTime"></param>
/// <returns></returns>
Task<DateTime> GetCostDateAsync(string factory, DateTime costDateTime);
}

View File

@@ -0,0 +1,10 @@
using Dlhis.Canteen.Setting.Response;
namespace Dlhis.Canteen.Setting.Services;
public interface IWalletService : IScopeDependency
{
Task<List<WalletResponse>> GetListAsync();
Task<decimal> GetBalanceAsync(string walletCode);
}

View File

@@ -114,6 +114,49 @@ public class CanteenSettingService : ICanteenSettingService
} }
} }
/// <inheritdoc />
public async Task<T> GetSettingAsync<T>(CanteenSettingItemEnumType item, string factory, string userNo, T defaultValue = default)
{
var settings = await GetUserSettingAsync(userNo, factory);
if (settings.TryGetValue(item, out var v))
{
try
{
if (int.TryParse(v, out var n))
{
return n.Adapt<T>();
}
return v.Adapt<T>();
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
/// <inheritdoc />
public async Task<DateTime> GetCostDateAsync(string factory, DateTime costDateTime)
{
var switchTime = await GetSettingAsync<TimeOnly?>(CanteenSettingItemEnumType.BusinessSwitchTime, factory, string.Empty);
var costDate = costDateTime.Date;
if (!switchTime.HasValue) return costDate;
var beginOfDay = costDateTime.Date;
var setTime = beginOfDay.Add(switchTime.Value.ToTimeSpan());
if (costDateTime < setTime)
costDate = costDateTime.Date.AddDays(-1);
return costDate;
}
//*********************************************** help methods ***************************************************// //*********************************************** help methods ***************************************************//
private async Task CheckDuplicateSettingAsync(CanteenSettingSaveRequest request) private async Task CheckDuplicateSettingAsync(CanteenSettingSaveRequest request)

View File

@@ -0,0 +1,45 @@
using Dlhis.Canteen.Order.Repository;
using Dlhis.Canteen.Setting.Response;
using Dlhis.Entity.Canteen.Entities;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using SqlSugar;
namespace Dlhis.Canteen.Setting.Services.Implements;
public class WalletService : IWalletService
{
private readonly IDbContext _dbContext;
private readonly ICurrentUser _currentUser;
private readonly IBalanceRepository _balanceRepository;
public WalletService(IDbContext dbContext, ICurrentUser currentUser, IBalanceRepository balanceRepository)
{
_dbContext = dbContext;
_currentUser = currentUser;
_balanceRepository = balanceRepository;
}
/// <inheritdoc />
public async Task<List<WalletResponse>> GetListAsync()
{
return await _dbContext.Queryable<WalletEntity>()
.GroupBy(x => new { x.Code, x.Name })
.Select(x => new WalletResponse
{
Code = x.Code,
Name = x.Name + "钱包",
Factories = SqlFunc.Subqueryable<WalletEntity>().Where(p => p.Code == x.Code).ToList(p => p.Factory)
})
.ToListAsync();
}
/// <inheritdoc />
public async Task<decimal> GetBalanceAsync(string walletCode)
{
var userCode = _currentUser.GetUserClaim("jinko-code");
var factory = await _dbContext.Queryable<WalletEntity>().Where(x => x.Code == walletCode).Select(x => x.Factory).FirstAsync();
return await _balanceRepository.GetBalanceAsync(userCode, factory);
}
}

View File

@@ -10,37 +10,37 @@ namespace Dlhis.Entity.Basic.Entity;
public class BusinessShiftMealRelationshipEntity : SugarBaseEntity, ITenantId public class BusinessShiftMealRelationshipEntity : SugarBaseEntity, ITenantId
{ {
/// <summary> /// <summary>
/// 餐别Code /// 餐别Code
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "餐别Code", UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })] [SugarColumn(ColumnDescription = "餐别Code", UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })]
public Guid ShiftCode { get; set; } public Guid ShiftCode { get; set; }
/// <summary> /// <summary>
/// 餐别手工号 /// 餐别手工号
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "餐别编码")] [SugarColumn(ColumnDescription = "餐别编码")]
public string ShiftCustomCode { get; set; } public string ShiftCustomCode { get; set; }
/// <summary> /// <summary>
/// 餐次 /// 餐次
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "餐次", ColumnDataType = "varchar(50)", SqlParameterDbType = typeof(EnumToStringConvert), UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })] [SugarColumn(ColumnDescription = "餐次", ColumnDataType = "varchar(50)", SqlParameterDbType = typeof(EnumToStringConvert), UniqueGroupNameList = new[] { "idx_CanteenBusinessShiftRelationship_shiftcode_shifttype" })]
public ShiftEnumType ShiftType { get; set; } public ShiftEnumType ShiftType { get; set; }
/// <summary> /// <summary>
/// 经营开始时间 /// 经营开始时间
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "经营开始时间")] [SugarColumn(ColumnDescription = "经营开始时间")]
public TimeOnly Start { get; set; } public TimeOnly Start { get; set; }
/// <summary> /// <summary>
/// 经营结束时间 /// 经营结束时间
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "经营结束时间")] [SugarColumn(ColumnDescription = "经营结束时间")]
public TimeOnly End { get; set; } public TimeOnly End { get; set; }
/// <summary> /// <summary>
/// 序号 /// 序号
/// </summary> /// </summary>
[SugarColumn(ColumnDescription = "序号")] [SugarColumn(ColumnDescription = "序号")]
public int Sequence { get; set; } public int Sequence { get; set; }

View File

@@ -1,43 +1,43 @@
using Kurisu.AspNetCore.DataAccess.Entity; // using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar; // using Kurisu.AspNetCore.DataAccess.SqlSugar;
using SqlSugar; // using SqlSugar;
//
namespace Dlhis.Entity.Basic.Entity // namespace Dlhis.Entity.Basic.Entity
{ // {
/// <summary> // /// <summary>
/// 就餐人员 // /// 就餐人员
/// </summary> // /// </summary>
[SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")] // [SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")]
public class GainfoMealEntity : SugarBaseEntity, IVersion // public class GainfoMealEntity : SugarBaseEntity, IVersion
{ // {
/// <summary> // /// <summary>
/// 工号 // /// 工号
/// </summary> // /// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })] // [SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })]
public string UserCode { get; set; } // public string UserCode { get; set; }
//
/// <summary> // /// <summary>
/// 余额 // /// 余额
/// </summary> // /// </summary>
[SugarColumn(ColumnDescription = "余额")] // [SugarColumn(ColumnDescription = "余额")]
public decimal Balance { get; set; } // public decimal Balance { get; set; }
//
/// <summary> // /// <summary>
/// 余额(充值) // /// 余额(充值)
/// </summary> // /// </summary>
[SugarColumn(ColumnDescription = "余额(充值)")] // [SugarColumn(ColumnDescription = "余额(充值)")]
public decimal BalanceOfRecharge { get; set; } // public decimal BalanceOfRecharge { get; set; }
//
/// <summary> // /// <summary>
/// 余额(餐补) // /// 余额(餐补)
/// </summary> // /// </summary>
[SugarColumn(ColumnDescription = "余额(餐补)")] // [SugarColumn(ColumnDescription = "余额(餐补)")]
public decimal BalanceOfSubsidies { get; set; } // public decimal BalanceOfSubsidies { get; set; }
//
/// <summary> // /// <summary>
/// 版本号 // /// 版本号
/// </summary> // /// </summary>
[SugarColumn(ColumnDescription = "版本号")] // [SugarColumn(ColumnDescription = "版本号")]
public int Version { get; set; } // public int Version { get; set; }
} // }
} // }

View File

@@ -0,0 +1,29 @@
using Kurisu.AspNetCore.DataAccess.SqlSugar;
using SqlSugar;
namespace Dlhis.Entity.Canteen.Entities;
/// <summary>
/// 钱包
/// </summary>
[SugarTable(TableName = "Wallets", TableDescription = "钱包")]
public class WalletEntity : SugarBaseEntity
{
/// <summary>
/// 钱包编码
/// </summary>
[SugarColumn(IsNullable = false)]
public string Code { get; set; }
/// <summary>
/// 钱包名称
/// </summary>
[SugarColumn(IsNullable = false)]
public string Name { get; set; }
/// <summary>
/// 厂区
/// </summary>
[SugarColumn(IsNullable = false, UniqueGroupNameList = new[] { "idx_wallets_factry" })]
public string Factory { get; set; }
}

View File

@@ -8,6 +8,9 @@ namespace Dlhis.Entity.Canteen.Enums;
[Description("餐饮应用类型")] [Description("餐饮应用类型")]
public enum CanteenApplicationTypeEnumType public enum CanteenApplicationTypeEnumType
{ {
/// <summary>
/// 设备消费
/// </summary>
[Description("设备消费")] [Description("设备消费")]
Device = 100, Device = 100,

View File

@@ -1,37 +0,0 @@
using System.Text;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.RemoteCall.Abstractions;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
namespace Dlhis.Middle.Api
{
public class FaceBearerTokenHandler : IAuthTokenHandler
{
/// <inheritdoc />
public string GetToken(IServiceProvider serviceProvider)
{
var cache = serviceProvider.GetService<IMemoryCache>();
if (cache.TryGetValue("token", out string token)) return "Bearer " + token;
var httpClient = serviceProvider.GetService<IHttpClientFactory>().CreateClient("face");
var hostName = serviceProvider.GetService<IConfiguration>().GetSection("HostName").Value;
var tokenResponse = httpClient.PostAsync($"https://{hostName}/api/user/oauth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new
{
ClientId = "e509c2aaa98e300c",
ClientSecret = "6184d8979fc48105"
}), Encoding.UTF8, "application/json")).GetAwaiter().GetResult();
var tokenJson = tokenResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var tokenInfo = JsonConvert.DeserializeObject<DefaultApiResult<TokenResponse>>(tokenJson);
token = tokenInfo.Data.AccessToken;
cache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires));
return token;
}
}
}

View File

@@ -0,0 +1,23 @@
using Kurisu.RemoteCall.Abstractions;
namespace Dlhis.Middle.Apis.Handlers;
public class ClientHandler : IHttpRemoteCallPolicyHandler
{
/// <inheritdoc />
public IHttpClientBuilder ConfigureHttpClient(IHttpClientBuilder builder)
{
builder.ConfigureHttpClient(client => { client.Timeout = TimeSpan.FromSeconds(10); }).ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
return handler;
});
return builder;
}
}

View File

@@ -0,0 +1,14 @@
using Dlhis.Middle.Services;
using Kurisu.RemoteCall.Abstractions;
namespace Dlhis.Middle.Apis.Handlers;
public class FaceBearerTokenHandler : IAsyncAuthTokenHandler
{
/// <inheritdoc />
public async Task<string> GetTokenAsync(IServiceProvider serviceProvider)
{
var tokenService = serviceProvider.GetService<ITokenService>();
return await tokenService.AuthAsync();
}
}

View File

@@ -1,11 +1,13 @@
using Dlhis.Middle.Apis.Handlers;
using Dlhis.Middle.Request; using Dlhis.Middle.Request;
using Dlhis.Middle.Response; using Dlhis.Middle.Response;
using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.RemoteCall.Attributes; using Kurisu.RemoteCall.Attributes;
namespace Dlhis.Middle.Api; namespace Dlhis.Middle.Apis;
[EnableRemoteClient(Name = "face-service", BaseUrl = "${Authority}")] [RequestLog]
[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))]
public interface IAssignmentDeviceTaskApi public interface IAssignmentDeviceTaskApi
{ {
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Auth(TokenHandler = typeof(FaceBearerTokenHandler))]

View File

@@ -1,26 +1,29 @@
using Dlhis.Middle.Apis.Handlers;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Request; using Dlhis.Middle.Request;
using Dlhis.Middle.Response; using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.RemoteCall.Attributes; using Kurisu.RemoteCall.Attributes;
namespace Dlhis.Middle.Api; namespace Dlhis.Middle.Apis;
[EnableRemoteClient(Name = "face-service", BaseUrl = "${Authority}")] [RequestLog]
[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))]
public interface ICanteenApi public interface ICanteenApi
{ {
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Post("/api/canteen/orders")] [Post("/api/canteen/orders")]
Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request); Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request);
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Post("/api/canteen/middle/upload")]
Task<DefaultApiResult<OrderResultResponse>> UploadAsync(LocalBalanceRecordEntity entity);
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Post("/api/canteen/balances/device/page")] [Post("/api/canteen/balances/device/page")]
Task<DefaultApiResult<Pagination<BalanceRecordDeviceResponse>>> GetPageByDeviceUniqueNoAsync(BalanceRecordPageByDeviceUniqueNoRequest request); Task<DefaultApiResult<Pagination<BalanceRecordDeviceResponse>>> GetPageByDeviceUniqueNoAsync(BalanceRecordPageByDeviceUniqueNoRequest request);
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Post("/api/canteen/balances/refund")] [Post("/api/canteen/balances/refund")]
Task<DefaultApiResult<OrderResultResponse>> RefundAsync(BalanceRecordRefundRequest request); Task<DefaultApiResult<OrderResultResponse>> RefundAsync(BalanceRecordRefundRequest request);

View File

@@ -0,0 +1,22 @@
using Dlhis.Middle.Apis.Handlers;
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.RemoteCall.Attributes;
namespace Dlhis.Middle.Apis;
[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))]
public interface ICommonApi
{
[Post("/api/user/oauth2/clientgrant")]
public Task<DefaultApiResult<TokenResponse>> AuthAsync(object request);
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Post("/api/common/middles/healthz")]
public Task<DefaultApiResult> CheckHealthAsync(HealthCheckRequest request);
[Auth(TokenHandler = typeof(FaceBearerTokenHandler))]
[Get("/api/common/SysData/download")]
public Task<DefaultApiResult<List<T>>> DownloadAsync<T>(string factory, string tableName);
}

View File

@@ -0,0 +1,131 @@
using Dlhis.Middle.Apis;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Middle.BackgroundServices;
public class BalanceRecordUploadBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<BalanceRecordUploadBackgroundService> _logger;
private readonly IWebHostEnvironment _environment;
private readonly ISettingService _settingService;
private readonly ICanteenApi _canteenApi;
private readonly IHealthCheckService _healthCheckService;
public BalanceRecordUploadBackgroundService(IServiceProvider serviceProvider,
ILogger<BalanceRecordUploadBackgroundService> logger,
IWebHostEnvironment environment,
ISettingService settingService,
ICanteenApi canteenApi,
IHealthCheckService healthCheckService)
{
_serviceProvider = serviceProvider;
_logger = logger;
_environment = environment;
_settingService = settingService;
_canteenApi = canteenApi;
_healthCheckService = healthCheckService;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested && _environment.IsProduction())
{
if (!_healthCheckService.GetIsOffline())
{
var now = DateTime.Now;
using var scope = _serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetService<IDbContext>();
var ds = scope.ServiceProvider.GetService<IDataDownloadService>();
var factories = _settingService.GetFactories();
foreach (var factory in factories)
{
try
{
var balanceRecords = await db.Queryable<LocalBalanceRecordEntity>().Where(x => x.TenantId == factory).Where(x => !x.IsSync).ToListAsync(stoppingToken);
if (balanceRecords.Any())
{
_logger.LogInformation("上传离线订单");
foreach (var balanceRecord in balanceRecords)
{
//事务
await db.Client.Ado.BeginTranAsync();
try
{
var r = await _canteenApi.UploadAsync(balanceRecord);
if (r.Code != ApiStateCode.Success)
{
throw new Exception(r.Msg);
}
var d = r.Data;
//更新本地余额表
await db.Updateable<LocalGainfoMealEntity>()
.SetColumns(x => x.Balance == d.Balance)
.Where(x => x.UserCode == d.UserCode)
.ExecuteCommandAsync(stoppingToken);
//eg:一定要在此处更新为已同步
balanceRecord.IsSync = true;
await db.UpdateAsync(balanceRecord);
await db.Client.Ado.CommitTranAsync();
}
catch (Exception e)
{
_logger.LogError(e, "{factory}上传离线消费失败:{message}", factory, e.Message);
await db.Client.Ado.RollbackTranAsync();
}
}
balanceRecords = await db.Queryable<LocalBalanceRecordEntity>().Where(x => x.TenantId == factory).Where(x => !x.IsSync).ToListAsync(stoppingToken);
if (!balanceRecords.Any())
{
_logger.LogInformation("上传离线订单完成");
}
}
}
catch (Exception e)
{
_logger.LogError(e, "{factory}同步离线数据失败:{message}", factory, e.Message);
}
}
try
{
if (now is { Hour: 4, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(factories);
}
else if (now is { Hour: 15, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(factories);
}
else if (now is { Hour: 20, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(factories);
}
}
catch (Exception e)
{
_logger.LogError(e, "定时同步离线数据失败");
}
}
await Task.Delay(60 * 1000, stoppingToken);
}
}
}

View File

@@ -0,0 +1,35 @@
using Dlhis.Middle.Services;
namespace Dlhis.Middle.BackgroundServices;
public class HealthCheckBackgroundService : BackgroundService
{
private readonly IHealthCheckService _healthCheckService;
private readonly IServiceProvider _serviceProvider;
private bool _init;
public HealthCheckBackgroundService(IHealthCheckService healthCheckService, IServiceProvider serviceProvider)
{
_healthCheckService = healthCheckService;
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (await _healthCheckService.DoHealthCheckAsync())
{
if (!_init)
{
using var scope = _serviceProvider.CreateScope();
var factories = scope.ServiceProvider.GetService<ISettingService>().GetFactories();
var ds = scope.ServiceProvider.GetService<IDataDownloadService>();
await ds.InitAsync(factories);
}
}
_init = true;
}
}
}

View File

@@ -1,5 +1,5 @@
using Dlhis.Entity.Device.Enums; using Dlhis.Entity.Device.Enums;
using Dlhis.Middle.Api; using Dlhis.Middle.Apis;
using Dlhis.Middle.Request; using Dlhis.Middle.Request;
using Dlhis.Middle.Response; using Dlhis.Middle.Response;
using Dlhis.Middle.Services; using Dlhis.Middle.Services;

View File

@@ -1,4 +1,4 @@
using Dlhis.Middle.Api; using Dlhis.Middle.Apis;
using Dlhis.Middle.Request; using Dlhis.Middle.Request;
using Dlhis.Middle.Response; using Dlhis.Middle.Response;
using Dlhis.Middle.Services; using Dlhis.Middle.Services;

View File

@@ -1,4 +1,5 @@
using Dlhis.Middle.Filters; using Dlhis.Middle.Filters;
using Dlhis.Middle.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -12,14 +13,13 @@ namespace Dlhis.Middle.Controllers;
public class GainfosController : ControllerBase public class GainfosController : ControllerBase
{ {
private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration; private readonly ISettingService _settingService;
private readonly ILogger<GainfosController> _logger;
public GainfosController(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<GainfosController> logger) public GainfosController(IHttpClientFactory httpClientFactory,
ISettingService settingService)
{ {
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
_configuration = configuration; _settingService = settingService;
_logger = logger;
} }
/// <summary> /// <summary>
@@ -32,14 +32,11 @@ public class GainfosController : ControllerBase
[HttpGet("face")] [HttpGet("face")]
public async Task<IActionResult> GetFaceAsync(string token) public async Task<IActionResult> GetFaceAsync(string token)
{ {
var hostName = _configuration.GetSection("HostName").Value; var httpClient = _httpClientFactory.CreateClient();
var httpClient = _httpClientFactory.CreateClient("face");
_logger.LogInformation("token:{token}", token);
try try
{ {
var faceBytes = await httpClient.GetByteArrayAsync($"https://{hostName}/api/basic/gainfos/face?token={token}"); var faceBytes = await httpClient.GetByteArrayAsync($"{_settingService.GetBaseUrl()}/api/basic/gainfos/face?token={token}");
if (faceBytes.Length == 0) if (faceBytes.Length == 0)
{ {

View File

@@ -1,4 +1,5 @@
using System.Text; using System.Text;
using Dlhis.Middle.Apis;
using Dlhis.Middle.Request; using Dlhis.Middle.Request;
using Dlhis.Middle.Services; using Dlhis.Middle.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -13,23 +14,20 @@ namespace Dlhis.Middle.Controllers;
[ApiController] [ApiController]
public class OAuth2Controller : ControllerBase public class OAuth2Controller : ControllerBase
{ {
private readonly IHttpClientFactory _httpClientFactory; private readonly ICommonApi _commonApi;
private readonly IConfiguration _configuration;
private readonly IHealthCheckService _healthCheckService; private readonly IHealthCheckService _healthCheckService;
public OAuth2Controller(IHttpClientFactory httpClientFactory, IConfiguration configuration, IHealthCheckService healthCheckService) public OAuth2Controller(
ICommonApi commonApi,
IHealthCheckService healthCheckService)
{ {
_httpClientFactory = httpClientFactory; _commonApi = commonApi;
_configuration = configuration;
_healthCheckService = healthCheckService; _healthCheckService = healthCheckService;
} }
[HttpPost("clientgrant")] [HttpPost("clientgrant")]
public async Task<object> ClientGrant(ClientGrantRequest request) public async Task<object> ClientGrant(ClientGrantRequest request)
{ {
var authority = _configuration.GetSection("Authority").Value;
var httpClient = _httpClientFactory.CreateClient("face");
if (_healthCheckService.GetIsOffline()) if (_healthCheckService.GetIsOffline())
{ {
return new return new
@@ -41,9 +39,12 @@ public class OAuth2Controller : ControllerBase
}; };
} }
var content = new StringContent($"grant_type=client_credentials&client_id={request.ClientId}&client_secret={request.ClientSecret}&scope={request.Scope}", Encoding.UTF8, "application/x-www-form-urlencoded"); var r = await _commonApi.AuthAsync(new
var response = await httpClient.PostAsync($"{authority}/oauth2/connect/token", content); {
var result = await response.Content.ReadAsStringAsync(); request.ClientId,
return JObject.Parse(result); request.ClientSecret
});
return r.Data;
} }
} }

View File

@@ -17,10 +17,23 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Kurisu.RemoteCall" Version="0.4.2" /> <PackageReference Include="Kurisu.RemoteCall" Version="0.4.4" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="8.0.6" /> <PackageReference Include="Microsoft.Data.Sqlite.Core" Version="8.0.6" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlcipher" Version="2.1.8" /> <PackageReference Include="SQLitePCLRaw.bundle_e_sqlcipher" Version="2.1.8" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.Development.json">
<DependentUpon>appsettings.json</DependentUpon>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Remove="Api\FaceBearerTokenHandler.cs" />
<Compile Remove="Api\IAssignmentDeviceTaskApi.cs" />
<Compile Remove="Services\Implements\BalanceRecordCheckBackgroundService.cs" />
<Compile Remove="Services\Implements\HealthCheckBackgroundService.cs" />
</ItemGroup>
</Project> </Project>

View File

@@ -1,4 +1,6 @@
using Dlhis.Entity.Basic.Entity; using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar;
using SqlSugar;
namespace Dlhis.Middle.Entities namespace Dlhis.Middle.Entities
{ {
@@ -6,4 +8,30 @@ namespace Dlhis.Middle.Entities
{ {
public new int Id { get; set; } public new int Id { get; set; }
} }
/// <summary>
/// 就餐人员
/// </summary>
[SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")]
public class GainfoMealEntity : SugarBaseEntity, IVersion
{
/// <summary>
/// 工号
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "工号", UniqueGroupNameList = new[] { "idx_CanteenUser_UserCode" })]
public string UserCode { get; set; }
/// <summary>
/// 余额
/// </summary>
[SugarColumn(ColumnDescription = "余额")]
public decimal Balance { get; set; }
/// <summary>
/// 版本号
/// </summary>
[SugarColumn(ColumnDescription = "版本号")]
public int Version { get; set; }
}
} }

View File

@@ -1,7 +1,4 @@
using Dlhis.Entity.Basic.Entity; using Dlhis.Middle.Entities;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Device.Entities;
using Dlhis.Middle.Entities;
using Kurisu.AspNetCore.Authentication.Abstractions; using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.Entity; using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Attributes; using Kurisu.AspNetCore.DataAccess.SqlSugar.Attributes;
@@ -141,7 +138,7 @@ public class SqlSugarPack : BaseAppPack
{ {
using var scope = app.ApplicationServices.CreateScope(); using var scope = app.ApplicationServices.CreateScope();
var db = scope.ServiceProvider.GetService<IDbContext>(); var db = scope.ServiceProvider.GetService<IDbContext>();
db.Client.DbMaintenance.CreateDatabase(); db.Client.DbMaintenance.CreateDatabase();
db.Client.CodeFirst.InitTables<LocalBalanceRecordEntity, LocalGainfoEntity, LocalGainfoMealEntity, LocalBusinessPlaceEntity>(); db.Client.CodeFirst.InitTables<LocalBalanceRecordEntity, LocalGainfoEntity, LocalGainfoMealEntity, LocalBusinessPlaceEntity>();
db.Client.CodeFirst.InitTables<LocalBusinessShiftEntity, LocalDeviceRegistryEntity, LocalDeviceEntity, LocalBusinessPlaceShiftRelationshipEntity, LocalBusinessShiftMealRelationshipEntity>(); db.Client.CodeFirst.InitTables<LocalBusinessShiftEntity, LocalDeviceRegistryEntity, LocalDeviceEntity, LocalBusinessPlaceShiftRelationshipEntity, LocalBusinessShiftMealRelationshipEntity>();

View File

@@ -1,5 +1,4 @@
using Dlhis.Middle.Services; using Dlhis.Middle.BackgroundServices;
using Dlhis.Middle.Services.Implements;
using Kurisu.AspNetCore; using Kurisu.AspNetCore;
using Kurisu.AspNetCore.Startup; using Kurisu.AspNetCore.Startup;
using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Logging;
@@ -24,35 +23,11 @@ public class Startup : DefaultStartup
public override void ConfigureServices(IServiceCollection services) public override void ConfigureServices(IServiceCollection services)
{ {
base.ConfigureServices(services); base.ConfigureServices(services);
services.AddHostedService<BalanceRecordUploadBackgroundService>();
services.AddHostedService<HealthCheckBackgroundService>();
services.AddRemoteCall(App.ActiveTypes); services.AddRemoteCall(App.ActiveTypes);
services.AddHttpClient("face", client => { client.Timeout = TimeSpan.FromSeconds(30); }).ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
return handler;
});
services.AddHostedService<BalanceRecordCheckBackgroundService>();
services.AddHostedService<HealthCheckBackgroundService>();
services.AddMemoryCache(); services.AddMemoryCache();
} }
/// <inheritdoc />
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
base.Configure(app, env);
if (Configuration.GetSection("Download").Value == "1")
{
using var scope = app.ApplicationServices.CreateScope();
var factory = Configuration.GetSection("Factory").Value;
var ds = scope.ServiceProvider.GetService<IDataDownloadService>();
ds.InitAsync(factory).Wait();
}
}
} }

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Middle.Request;
public class HealthCheckRequest
{
public List<string> Factories { get; set; }
}

View File

@@ -28,4 +28,7 @@ public class OrderResultResponse
/// 余额 /// 余额
/// </summary> /// </summary>
public decimal Balance { get; set; } public decimal Balance { get; set; }
public decimal TotalBalance { get; set; }
} }

View File

@@ -2,9 +2,7 @@ namespace Dlhis.Middle.Services;
public interface IDataDownloadService : IScopeDependency public interface IDataDownloadService : IScopeDependency
{ {
Task InitAsync(string factory); Task InitAsync(string[] factories);
Task DownloadAsync<T>(string factory) where T : class, new(); Task DownloadAsync<T>(string factory) where T : class, new();
Task TruncateAsync();
} }

View File

@@ -4,5 +4,5 @@ public interface IHealthCheckService : ISingletonDependency
{ {
bool GetIsOffline(); bool GetIsOffline();
Task DoHealthCheckAsync(); Task<bool> DoHealthCheckAsync();
} }

View File

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

View File

@@ -0,0 +1,8 @@
namespace Dlhis.Middle.Services;
public interface ISettingService : ISingletonDependency
{
string[] GetFactories();
string GetBaseUrl();
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Middle.Services;
public interface ITokenService : ISingletonDependency
{
Task<string> AuthAsync();
}

View File

@@ -1,169 +0,0 @@
using System.Net.Http.Headers;
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.Extensions.Caching.Memory;
using Newtonsoft.Json;
namespace Dlhis.Middle.Services.Implements;
public class BalanceRecordCheckBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<BalanceRecordCheckBackgroundService> _logger;
private readonly IMemoryCache _memoryCache;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IHealthCheckService _healthCheckService;
private readonly string _factory;
private readonly string _hostName;
public BalanceRecordCheckBackgroundService(IServiceProvider serviceProvider,
ILogger<BalanceRecordCheckBackgroundService> logger,
IMemoryCache memoryCache,
IHttpClientFactory httpClientFactory,
IHealthCheckService healthCheckService,
IConfiguration configuration)
{
_serviceProvider = serviceProvider;
_logger = logger;
_memoryCache = memoryCache;
_httpClientFactory = httpClientFactory;
_healthCheckService = healthCheckService;
_factory = configuration.GetSection("Factory").Value;
_hostName = configuration.GetSection("HostName").Value;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (!_healthCheckService.GetIsOffline())
{
var now = DateTime.Now;
using var scope = _serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetService<IDbContext>();
var ds = scope.ServiceProvider.GetService<IDataDownloadService>();
foreach (var factory in _factory.Split(','))
{
try
{
var balanceRecords = await db.Queryable<LocalBalanceRecordEntity>().Where(x => x.TenantId == factory).Where(x => !x.IsSync).ToListAsync(stoppingToken);
if (balanceRecords.Any())
{
_logger.LogInformation("上传离线订单");
foreach (var balanceRecord in balanceRecords)
{
//事务
await db.Client.Ado.BeginTranAsync();
try
{
var r = await UploadAsync(balanceRecord);
if (r.Code != ApiStateCode.Success)
{
throw new Exception(r.Msg);
}
var d = r.Data;
//更新本地余额表
await db.Updateable<LocalGainfoMealEntity>()
.SetColumns(x => x.Balance == d.Balance)
.Where(x => x.UserCode == d.UserCode)
.ExecuteCommandAsync(stoppingToken);
//eg:一定要在此处更新为已同步
balanceRecord.IsSync = true;
await db.UpdateAsync(balanceRecord);
await db.Client.Ado.CommitTranAsync();
}
catch (Exception e)
{
_logger.LogError(e, "{factory}上传离线消费失败:{message}", factory, e.Message);
await db.Client.Ado.RollbackTranAsync();
}
}
balanceRecords = await db.Queryable<LocalBalanceRecordEntity>().Where(x => x.TenantId == factory).Where(x => !x.IsSync).ToListAsync(stoppingToken);
if (!balanceRecords.Any())
{
_logger.LogInformation("上传离线订单完成");
}
}
}
catch (Exception e)
{
_logger.LogError(e, "{factory}同步离线数据失败:{message}", factory, e.Message);
}
}
if (now is { Hour: 4, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(_factory);
}
else if (now is { Hour: 15, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(_factory);
}
else if (now is { Hour: 20, Minute: 1 }
&& !_healthCheckService.GetIsOffline()
&& !await db.Queryable<LocalBalanceRecordEntity>().Where(x => !x.IsSync).AnyAsync())
{
await ds.InitAsync(_factory);
}
}
await Task.Delay(60 * 1000, stoppingToken);
}
}
public async Task<DefaultApiResult<OrderResultResponse>> UploadAsync(LocalBalanceRecordEntity entity)
{
var token = await AuthAsync();
var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var url = $"https://{_hostName}/api/canteen/middle/upload";
var json = entity.ToJson();
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
var responseJson = await response.Content.ReadAsStringAsync();
return responseJson.ToObject<DefaultApiResult<OrderResultResponse>>();
}
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

@@ -1,43 +1,32 @@
using System.Net.Http.Headers;
using System.Reflection; using System.Reflection;
using System.Text; using Dlhis.Middle.Apis;
using Dlhis.Middle.Entities; using Dlhis.Middle.Entities;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; 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; using SqlSugar;
namespace Dlhis.Middle.Services.Implements; namespace Dlhis.Middle.Services.Implements;
public class DataDownloadService : IDataDownloadService public class DataDownloadService : IDataDownloadService
{ {
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IDbContext _dbContext; private readonly IDbContext _dbContext;
private readonly ICommonApi _commonApi;
private readonly ILogger<DataDownloadService> _logger; private readonly ILogger<DataDownloadService> _logger;
private readonly string _hostName;
public DataDownloadService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IConfiguration configuration, IDbContext dbContext, ILogger<DataDownloadService> logger) public DataDownloadService(
IDbContext dbContext,
ICommonApi commonApi,
ILogger<DataDownloadService> logger)
{ {
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_dbContext = dbContext; _dbContext = dbContext;
_commonApi = commonApi;
_logger = logger; _logger = logger;
_hostName = configuration.GetSection("HostName").Value;
} }
public async Task InitAsync(string factory) public async Task InitAsync(string[] factories)
{ {
//需要上传完记录才可下载
if (await _dbContext.Queryable<LocalBalanceRecordEntity>().Where(x => x.IsSync == false).AnyAsync()) if (await _dbContext.Queryable<LocalBalanceRecordEntity>().Where(x => x.IsSync == false).AnyAsync())
{
return; return;
}
var factories = factory.Split(',');
await _dbContext.Client.Ado.BeginTranAsync(); await _dbContext.Client.Ado.BeginTranAsync();
try try
@@ -84,9 +73,10 @@ public class DataDownloadService : IDataDownloadService
_logger.LogInformation("档案{count}", await _dbContext.Queryable<LocalGainfoEntity>().CountAsync()); _logger.LogInformation("档案{count}", await _dbContext.Queryable<LocalGainfoEntity>().CountAsync());
_logger.LogInformation("余额{count}", await _dbContext.Queryable<LocalGainfoMealEntity>().CountAsync()); _logger.LogInformation("余额{count}", await _dbContext.Queryable<LocalGainfoMealEntity>().CountAsync());
_logger.LogInformation("下载完成"); _logger.LogInformation("下载完成");
await _dbContext.Client.Ado.CommitTranAsync(); await _dbContext.Client.Ado.CommitTranAsync();
} }
catch (Exception e) catch (Exception)
{ {
await _dbContext.Client.Ado.RollbackTranAsync(); await _dbContext.Client.Ado.RollbackTranAsync();
throw; throw;
@@ -95,27 +85,11 @@ public class DataDownloadService : IDataDownloadService
public async Task DownloadAsync<T>(string factory) where T : class, new() public async Task DownloadAsync<T>(string factory) where T : class, new()
{ {
var token = await AuthAsync(); var pack = await _commonApi.DownloadAsync<T>(factory, typeof(T).GetCustomAttribute<SugarTable>()!.TableName);
var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var url = $"https://{_hostName}/api/common/SysData/download";
var requestUrl = QueryHelpers.AddQueryString(url, 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); await _dbContext.InsertAsync(pack.Data);
} }
/// <inheritdoc /> private async Task TruncateAsync()
public async Task TruncateAsync()
{ {
await _dbContext.Client.Deleteable<LocalDepartmentEntity>().ExecuteCommandAsync(); await _dbContext.Client.Deleteable<LocalDepartmentEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalDeviceEntity>().ExecuteCommandAsync(); await _dbContext.Client.Deleteable<LocalDeviceEntity>().ExecuteCommandAsync();
@@ -128,26 +102,4 @@ public class DataDownloadService : IDataDownloadService
await _dbContext.Client.Deleteable<LocalGainfoEntity>().ExecuteCommandAsync(); await _dbContext.Client.Deleteable<LocalGainfoEntity>().ExecuteCommandAsync();
await _dbContext.Client.Deleteable<LocalGainfoMealEntity>().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

@@ -1,19 +0,0 @@
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

@@ -1,19 +1,26 @@
using System.Net.Sockets; using Dlhis.Middle.Apis;
using Dlhis.Middle.Request;
using Kurisu.AspNetCore.UnifyResultAndValidation;
namespace Dlhis.Middle.Services.Implements; namespace Dlhis.Middle.Services.Implements;
public class HealthCheckService : IHealthCheckService public class HealthCheckService : IHealthCheckService
{ {
private bool _isOffline; private bool _isOffline;
private readonly string _hostName;
private readonly ILogger<HealthCheckService> _logger; private readonly ILogger<HealthCheckService> _logger;
private int _successRetry; private readonly ISettingService _settingService;
private int _retry; private readonly ICommonApi _healthCheckApi;
private int _attempted;
public HealthCheckService(ILogger<HealthCheckService> logger, IConfiguration configuration) private bool _isBegin;
public HealthCheckService(ILogger<HealthCheckService> logger,
ISettingService settingService,
ICommonApi healthCheckApi)
{ {
_logger = logger; _logger = logger;
_hostName = configuration.GetSection("HostName").Value; _settingService = settingService;
_healthCheckApi = healthCheckApi;
} }
public bool GetIsOffline() public bool GetIsOffline()
@@ -21,46 +28,49 @@ public class HealthCheckService : IHealthCheckService
return _isOffline; return _isOffline;
} }
public async Task DoHealthCheckAsync() public async Task<bool> DoHealthCheckAsync()
{ {
var cancellationTokenSource = new CancellationTokenSource(5000);
var tcpClient = new TcpClient();
try try
{ {
_logger.LogDebug("tcp connecting {host} {port}", _hostName, 443); var factories = _settingService.GetFactories();
await tcpClient.ConnectAsync(_hostName, 443, cancellationTokenSource.Token);
_retry++; var response = await _healthCheckApi.CheckHealthAsync(new HealthCheckRequest { Factories = factories.ToList() });
_logger.LogDebug("retry {retry}", _retry); if (response.Code == ApiStateCode.Success)
if (tcpClient.Connected)
{ {
_successRetry++; _attempted++;
_logger.LogDebug("success connected {count}", _successRetry); if (_attempted == 5)
if (_successRetry == 4)
{ {
_isOffline = false; _isOffline = false;
_successRetry = 0; _attempted = 0;
_retry = 0;
_logger.LogInformation("current is {status}", "healthy");
} }
else
if (!_isBegin)
{ {
_logger.LogDebug("wait next check in {waitTime}", _successRetry * 1000); _isOffline = false;
await Task.Delay(_successRetry * 1000, cancellationTokenSource.Token); _isBegin = true;
}
await Task.Delay(_attempted * 1000);
if (_isOffline == false)
{
_logger.LogInformation("Health");
return true;
} }
} }
else else
{ {
_successRetry = 0;
_isOffline = true; _isOffline = true;
_logger.LogDebug("current is {status}", "unavailable"); _logger.LogInformation("Error {message}", response.Msg);
await Task.Delay(500);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("fail cause :{reason}", ex.Message); _logger.LogError("Failed cause :{reason}", ex.Message);
_isOffline = true; _isOffline = true;
await Task.Delay(5000);
} }
return false;
} }
} }

View File

@@ -1,5 +1,6 @@
using System.Diagnostics; using System.Diagnostics;
using Dlhis.Entity.Canteen.Enums; using Dlhis.Entity.Canteen.Enums;
using Dlhis.Middle.Apis;
using Dlhis.Middle.Entities; using Dlhis.Middle.Entities;
using Kurisu.AspNetCore.Utils; using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions; using Kurisu.AspNetCore.Utils.Extensions;
@@ -17,6 +18,7 @@ public class OrderService : IOrderService
{ {
private readonly ICanteenSettingService _canteenSettingService; private readonly ICanteenSettingService _canteenSettingService;
private readonly IRemoteOrderService _remoteOrderService; private readonly IRemoteOrderService _remoteOrderService;
private readonly ICanteenApi _canteenApi;
private readonly ILogger<OrderService> _logger; private readonly ILogger<OrderService> _logger;
private readonly string _factory; private readonly string _factory;
private readonly IDbContext _dbContext; private readonly IDbContext _dbContext;
@@ -24,14 +26,16 @@ public class OrderService : IOrderService
public OrderService(ICanteenSettingService canteenSettingService, public OrderService(ICanteenSettingService canteenSettingService,
IRemoteOrderService remoteOrderService, IRemoteOrderService remoteOrderService,
IConfiguration configuration, ISettingService settingService,
ICanteenApi canteenApi,
ILogger<OrderService> logger, ILogger<OrderService> logger,
IDbContext dbContext) IDbContext dbContext)
{ {
_canteenSettingService = canteenSettingService; _canteenSettingService = canteenSettingService;
_remoteOrderService = remoteOrderService; _remoteOrderService = remoteOrderService;
_canteenApi = canteenApi;
_logger = logger; _logger = logger;
_factory = configuration.GetSection("Factory").Value; _factory = settingService.GetFactories().Join(",");
_dbContext = dbContext; _dbContext = dbContext;
} }
@@ -43,12 +47,12 @@ public class OrderService : IOrderService
{ {
if (await _remoteOrderService.AbleRemoteCallAsync()) if (await _remoteOrderService.AbleRemoteCallAsync())
{ {
var remoteResult = await _remoteOrderService.AddAsync(request); var remoteResult = await _canteenApi.AddAsync(request);
if (remoteResult.Code == ApiStateCode.Success) if (remoteResult.Code == ApiStateCode.Success)
{ {
var d = remoteResult.Data; var d = remoteResult.Data;
await _dbContext.Updateable<LocalGainfoMealEntity>() await _dbContext.Updateable<LocalGainfoMealEntity>()
.SetColumns(x => x.Balance == d.Balance) .SetColumns(x => x.Balance == d.TotalBalance)
.Where(x => x.UserCode == d.UserCode) .Where(x => x.UserCode == d.UserCode)
.ExecuteCommandAsync(); .ExecuteCommandAsync();
} }

View File

@@ -1,54 +1,37 @@
using System.Net.Http.Headers;
using System.Text;
using Dlhis.Middle.Entities; using Dlhis.Middle.Entities;
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; 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; namespace Dlhis.Middle.Services.Implements;
public class RemoteOrderService : IRemoteOrderService public class RemoteOrderService : IRemoteOrderService
{ {
private readonly string _hostName;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IHealthCheckService _healthCheckService; private readonly IHealthCheckService _healthCheckService;
private readonly IDbContext _dbContext; private readonly IDbContext _dbContext;
public RemoteOrderService(IHttpClientFactory httpClientFactory, public RemoteOrderService(
IMemoryCache memoryCache,
IConfiguration configuration,
IHealthCheckService healthCheckService, IHealthCheckService healthCheckService,
IDbContext dbContext) IDbContext dbContext)
{ {
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_hostName = configuration.GetSection("hostName").Value;
_healthCheckService = healthCheckService; _healthCheckService = healthCheckService;
_dbContext = dbContext; _dbContext = dbContext;
} }
/// <inheritdoc /> ///// <inheritdoc />
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request) // public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{ // {
var token = await AuthAsync(); // var token = await _tokenService.AuthAsync();
//
var httpClient = _httpClientFactory.CreateClient("face"); // var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//
var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json"); // var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json");
//
var response = await httpClient.PostAsync($"https://{_hostName}/api/canteen/orders", content); // var response = await httpClient.PostAsync($"{_settingService.GetBaseUrl()}/api/canteen/orders", content);
//
var responseJson = await response.Content.ReadAsStringAsync(); // var responseJson = await response.Content.ReadAsStringAsync();
return responseJson.ToObject<DefaultApiResult<OrderResultResponse>>(); // return responseJson.ToObject<DefaultApiResult<OrderResultResponse>>();
} // }
/// <inheritdoc /> /// <inheritdoc />
public async Task<bool> AbleRemoteCallAsync() public async Task<bool> AbleRemoteCallAsync()
@@ -60,28 +43,4 @@ public class RemoteOrderService : IRemoteOrderService
return !_healthCheckService.GetIsOffline(); 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 = "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,23 @@
namespace Dlhis.Middle.Services.Implements;
public class SettingService : ISettingService
{
private readonly IConfiguration _configuration;
public SettingService(IConfiguration configuration)
{
_configuration = configuration;
}
/// <inheritdoc />
public string[] GetFactories()
{
return _configuration.GetSection("Factory").Value.Split(",");
}
/// <inheritdoc />
public string GetBaseUrl()
{
return _configuration.GetSection("BaseUrl").Value;
}
}

View File

@@ -0,0 +1,43 @@
using Dlhis.Middle.Apis;
using Microsoft.Extensions.Caching.Memory;
namespace Dlhis.Middle.Services.Implements;
public class TokenService : ITokenService
{
private readonly IMemoryCache _memoryCache;
private readonly ICommonApi _commonApi;
public TokenService(IMemoryCache memoryCache, ICommonApi commonApi)
{
_memoryCache = memoryCache;
_commonApi = commonApi;
}
/// <inheritdoc />
public async Task<string> AuthAsync()
{
var exists = _memoryCache.TryGetValue("token", out string token);
try
{
if (!exists)
{
var tokenInfo = await _commonApi.AuthAsync(new
{
ClientId = "e509c2aaa98e300c",
ClientSecret = "6184d8979fc48105"
});
token = tokenInfo.Data.AccessToken;
_memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires));
}
}
finally
{
token = "Bearer " + token;
}
return token;
}
}

View File

@@ -5,8 +5,7 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"Authority": "https://face.jinkosolar.com", "BaseUrl": "https://yikatong.isawesome.cn",
"Factory": "1201", "Factory": "1234",
"HostName": "face.jinkosolar.com", "InternalIP":""
"Download":1
} }

View File

@@ -12,9 +12,6 @@
"SlowSqlTime": 1, "SlowSqlTime": 1,
"EnableSqlLog": false "EnableSqlLog": false
}, },
"Authority": "https://face.jinkosolar.com",
"Factory": "",
"HostName": "face.jinkosolar.com",
"AllowedHosts": "*", "AllowedHosts": "*",
"SwaggerOptions": { "SwaggerOptions": {
"Enable": true, "Enable": true,

View File

@@ -3,7 +3,7 @@ using Dlhis.ScheduledTask.Common.Response;
namespace Dlhis.ScheduledTask.Common.Services; namespace Dlhis.ScheduledTask.Common.Services;
public interface IJinkoJIPService : ISingletonDependency public interface IJinkoJipService : ISingletonDependency
{ {
Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests); Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests);

View File

@@ -0,0 +1,36 @@
using Dlhis.ScheduledTask.Common.Request;
using Dlhis.ScheduledTask.Common.Response;
namespace Dlhis.ScheduledTask.Common.Services;
public interface IJinkoJipService : ISingletonDependency
{
Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests);
Task<string> SyncMealSupplementRecordsAsync(List<SyncMealSupplementRecordRequest> requests);
/// <summary>
/// 获取出差信息
/// </summary>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="fatory"></param>
/// <returns></returns>
Task<SapBusinessTripInfoResponse> GetTravelInfosByFactoryAsync(DateTime begin, DateTime end, string fatory);
/// <summary>
/// 获取出差信息
/// </summary>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="userCode"></param>
/// <returns></returns>
Task<SapBusinessTripInfoResponse> GetTravelInfosByUserCodeAsync(DateTime begin, DateTime end, string userCode);
Task<SapFaceSyncResponse> SyncFaceToSapAsync(string userCode, string base64);
string IssueToken();
}

View File

@@ -12,9 +12,9 @@ public class HangfireService : IHangfireService
{ {
private readonly RedisCache _redisCache; private readonly RedisCache _redisCache;
private readonly IDbContext _dbContext; private readonly IDbContext _dbContext;
private readonly IJinkoJIPService _jinkoJipService; private readonly IJinkoJipService _jinkoJipService;
public HangfireService(RedisCache redisCache, IDbContext dbContext, IJinkoJIPService jinkoJipService) public HangfireService(RedisCache redisCache, IDbContext dbContext, IJinkoJipService jinkoJipService)
{ {
_redisCache = redisCache; _redisCache = redisCache;
_dbContext = dbContext; _dbContext = dbContext;

View File

@@ -10,13 +10,13 @@ using Newtonsoft.Json.Linq;
namespace Dlhis.ScheduledTask.Common.Services.Implements; namespace Dlhis.ScheduledTask.Common.Services.Implements;
public class JinkoJIPService : IJinkoJIPService public class JinkoJipService : IJinkoJipService
{ {
private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<JinkoJIPService> _logger; private readonly ILogger<JinkoJipService> _logger;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
public JinkoJIPService(IHttpClientFactory httpClientFactory, ILogger<JinkoJIPService> logger, IConfiguration configuration) public JinkoJipService(IHttpClientFactory httpClientFactory, ILogger<JinkoJipService> logger, IConfiguration configuration)
{ {
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
_logger = logger; _logger = logger;

View File

@@ -0,0 +1,213 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Dlhis.ScheduledTask.Common.Request;
using Dlhis.ScheduledTask.Common.Response;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
namespace Dlhis.ScheduledTask.Common.Services.Implements;
public class JinkoJipService : IJinkoJipService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<JinkoJipService> _logger;
private readonly IConfiguration _configuration;
public JinkoJipService(IHttpClientFactory httpClientFactory, ILogger<JinkoJipService> logger, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configuration = configuration;
}
private HttpClient GetHttpClient()
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_configuration.GetSection("JinkoOptions:Jip:BaseUrl").Value);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", IssueToken());
return httpClient;
}
public async Task<UploadAttendanceResponse> UploadAttendancesAsync(List<UploadAttendanceRequest> requests)
{
var requestUrl = "/JIP/HCM/HCM_SWIPE_DATA_SAVE";
var body = new
{
T_DATA = requests,
};
var json = body.ToJson();
//_logger.LogInformation("上传考勤记录请求:{json}", json);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await GetHttpClient().PostAsync(requestUrl, content);
var responseJson = await response.Content.ReadAsStringAsync();
_logger.LogInformation("上传考勤记录响应:{json}", responseJson);
try
{
return responseJson.ToObject<UploadAttendanceResponse>();
}
catch (Exception)
{
return new UploadAttendanceResponse
{
OLX = "99",
OMS = "接口响应数据异常,无法反序列化"
};
}
}
public async Task<string> SyncMealSupplementRecordsAsync(List<SyncMealSupplementRecordRequest> requests)
{
var requestUrl = "/JIP/DHR/DHR_DL_CALLBACK";
var json = requests.ToJson(Kurisu.AspNetCore.Utils.Extensions.JsonExtensions.DefaultSetting);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await GetHttpClient().PostAsync(requestUrl, content);
var responseJson = await response.Content.ReadAsStringAsync();
_logger.LogInformation("餐补状态同步响应:{json}", responseJson);
var jobj = JObject.Parse(responseJson);
if (jobj.TryGetValue("exp", out var exp))
{
true.ThrowIfTrue(exp.Value<string>());
}
if (jobj.TryGetValue("message", out var message) && !jobj.ContainsKey("code"))
{
true.ThrowIfTrue(message.Value<string>());
}
(jobj.GetValue("code").Value<int>() != 200).ThrowIfTrue(jobj.GetValue("message").Value<string>());
return responseJson;
}
public async Task<SapBusinessTripInfoResponse> GetTravelInfosByFactoryAsync(DateTime begin, DateTime end, string factory)
{
const string apiUrl = "/JIP/HCM/HCM_TRAVELINFO";
var beginDay = begin.ToString("yyyyMMdd");
var endDay = end.ToString("yyyyMMdd");
var obj = new
{
I_PAGE = 1,
I_LINE = 500,
IV_BEGDA = beginDay,
IV_ENDDA = endDay,
IT_CCMDD = new List<object>
{
new
{
IV_CCMDD = factory
}
}
};
var body = obj.ToJson();
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await GetHttpClient().PostAsync(apiUrl, content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<SapBusinessTripInfoResponse>();
}
public async Task<SapBusinessTripInfoResponse> GetTravelInfosByUserCodeAsync(DateTime begin, DateTime end, string userCode)
{
const string apiUrl = "/JIP/HCM/HCM_TRAVELINFO";
var beginDay = begin.ToString("yyyyMMdd");
var endDay = end.ToString("yyyyMMdd");
//IV_GONGH IV_ORGID
//IT_2002GH
var obj = new
{
IV_BEGDA = beginDay,
IV_ENDDA = endDay,
IT_2002GH = new List<object>
{
new
{
IV_GONGH = userCode
}
}
};
var body = obj.ToJson();
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await GetHttpClient().PostAsync(apiUrl, content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<SapBusinessTripInfoResponse>();
}
public async Task<SapFaceSyncResponse> SyncFaceToSapAsync(string userCode, string base64)
{
const string apiUrl = "/JIP/HCM/HCM_I_PHOTO";
var obj = new
{
I_WORKCODE = userCode,
I_PHOTO_STR = base64
};
var body = obj.ToJson();
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await GetHttpClient().PostAsync(apiUrl, content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<SapFaceSyncResponse>();
}
public string IssueToken()
{
var jwtKey = _configuration.GetSection("JinkoOptions:Jip:Key").Value;
var jwtSecret = _configuration.GetSection("JinkoOptions:Jip:Secret").Value;
const int min = 5;
var now = DateTime.Now.AddMinutes(-min);
var expires = DateTime.Now.AddMinutes(min);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(now).ToUnixTimeSeconds()}"),
new(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(expires).ToUnixTimeSeconds()}"),
new(JwtRegisteredClaimNames.Iss, jwtKey),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret));
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Issuer = jwtKey,
IssuedAt = now,
NotBefore = now,
Expires = expires,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
};
var jwtHandler = new JwtSecurityTokenHandler();
var securityToken = jwtHandler.CreateToken(descriptor);
return jwtHandler.WriteToken(securityToken);
}
}

View File

@@ -15,12 +15,12 @@ namespace Dlhis.ScheduledTask.Common.Services.Implements;
public class SapBusinessTripService : ISapBusinessTripService public class SapBusinessTripService : ISapBusinessTripService
{ {
private readonly IJinkoJIPService _jinkoJipService; private readonly IJinkoJipService _jinkoJipService;
private readonly IDbContext _dbContext; private readonly IDbContext _dbContext;
private readonly IDevicePermissionApi _devicePermissionApi; private readonly IDevicePermissionApi _devicePermissionApi;
private readonly ILogger<SapBusinessTripService> _logger; private readonly ILogger<SapBusinessTripService> _logger;
public SapBusinessTripService(IJinkoJIPService jinkoJipService, IDbContext dbContext, IDevicePermissionApi devicePermissionApi, ILogger<SapBusinessTripService> logger) public SapBusinessTripService(IJinkoJipService jinkoJipService, IDbContext dbContext, IDevicePermissionApi devicePermissionApi, ILogger<SapBusinessTripService> logger)
{ {
_jinkoJipService = jinkoJipService; _jinkoJipService = jinkoJipService;
_dbContext = dbContext; _dbContext = dbContext;

View File

@@ -6,8 +6,6 @@ using Dlhis.ScheduledTask.Attributes;
using Dlhis.ScheduledTask.Common.Request; using Dlhis.ScheduledTask.Common.Request;
using Dlhis.ScheduledTask.Common.Services; using Dlhis.ScheduledTask.Common.Services;
using Hangfire; using Hangfire;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.Utils;
namespace Dlhis.ScheduledTask.Jobs; namespace Dlhis.ScheduledTask.Jobs;
@@ -17,10 +15,10 @@ namespace Dlhis.ScheduledTask.Jobs;
[RecurringJob(nameof(MealSupplementHandlerJob), "0 0/30 * * * ?", Name = "餐补核算")] [RecurringJob(nameof(MealSupplementHandlerJob), "0 0/30 * * * ?", Name = "餐补核算")]
public class MealSupplementHandlerJob : BaseJob public class MealSupplementHandlerJob : BaseJob
{ {
private readonly IJinkoJIPService _jinkoJIPService; private readonly IJinkoJipService _jinkoJIPService;
public MealSupplementHandlerJob(IServiceProvider serviceProvider, public MealSupplementHandlerJob(IServiceProvider serviceProvider,
IJinkoJIPService jinkoJIPService) : base(serviceProvider) IJinkoJipService jinkoJIPService) : base(serviceProvider)
{ {
_jinkoJIPService = jinkoJIPService; _jinkoJIPService = jinkoJIPService;
} }
@@ -85,23 +83,6 @@ public class MealSupplementHandlerJob : BaseJob
} }
} }
//创建余额数据
var mealUser = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == gainfo.Code).SingleAsync();
if (mealUser == null)
{
mealUser = new GainfoMealEntity
{
Balance = 0,
BalanceOfRecharge = 0,
BalanceOfSubsidies = 0,
UserCode = gainfo.Code,
Version = 0,
};
await DbContext.InsertAsync(mealUser);
}
await SetMealSupplementAsync(gainfo, item); await SetMealSupplementAsync(gainfo, item);
} }
} }
@@ -111,19 +92,6 @@ public class MealSupplementHandlerJob : BaseJob
await DbContext.Client.Ado.BeginTranAsync(); await DbContext.Client.Ado.BeginTranAsync();
try try
{ {
await CommonHelper.RetryAsync(async () =>
{
var mealUser = await DbContext.Queryable<GainfoMealEntity>().Where(x => x.UserCode == mealSupplement.Code).FirstAsync();
var b = mealUser.Balance += mealSupplement.Amount;
await DbContext.Updateable<GainfoMealEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Balance == b)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(x => x.UserCode == mealUser.UserCode && x.Version == mealUser.Version)
.ExecuteCommandThrowVersionAsync();
}, 5);
await DbContext.InsertAsync(new BalanceRecordEntity await DbContext.InsertAsync(new BalanceRecordEntity
{ {
Amount = mealSupplement.Amount, Amount = mealSupplement.Amount,

View File

@@ -7,10 +7,10 @@ namespace Dlhis.ScheduledTask.Jobs;
[RecurringJob(nameof(SyncFaceJob), "0 0/15 * * * ?", Name = "face数据同步sap")] [RecurringJob(nameof(SyncFaceJob), "0 0/15 * * * ?", Name = "face数据同步sap")]
public class SyncFaceJob : BaseJob public class SyncFaceJob : BaseJob
{ {
private readonly IJinkoJIPService _jinkoJipService; private readonly IJinkoJipService _jinkoJipService;
/// <inheritdoc /> /// <inheritdoc />
public SyncFaceJob(IServiceProvider serviceProvider, IJinkoJIPService jinkoJipService) : base(serviceProvider) public SyncFaceJob(IServiceProvider serviceProvider, IJinkoJipService jinkoJipService) : base(serviceProvider)
{ {
_jinkoJipService = jinkoJipService; _jinkoJipService = jinkoJipService;
} }

View File

@@ -14,9 +14,9 @@ namespace Dlhis.ScheduledTask.Jobs;
[RecurringJob(nameof(SyncOriginCardInfoJob), "0 0/1 * * * ?", Name = "上传考勤记录")] [RecurringJob(nameof(SyncOriginCardInfoJob), "0 0/1 * * * ?", Name = "上传考勤记录")]
public class SyncOriginCardInfoJob : BaseJob public class SyncOriginCardInfoJob : BaseJob
{ {
private readonly IJinkoJIPService _jinkoJIPService; private readonly IJinkoJipService _jinkoJIPService;
public SyncOriginCardInfoJob(IJinkoJIPService jinkoJIPService, IServiceProvider serviceProvider) : base(serviceProvider) public SyncOriginCardInfoJob(IJinkoJipService jinkoJIPService, IServiceProvider serviceProvider) : base(serviceProvider)
{ {
_jinkoJIPService = jinkoJIPService; _jinkoJIPService = jinkoJIPService;
} }

View File

@@ -26,6 +26,6 @@ public class Startup : DefaultStartup
{ {
base.Configure(app, env); base.Configure(app, env);
var token = app.ApplicationServices.GetService<IJinkoJIPService>().IssueToken(); var token = app.ApplicationServices.GetService<IJinkoJipService>().IssueToken();
} }
} }