feat 生日券功能,自动上传消费数据,提醒访客到期

This commit is contained in:
2025-12-09 11:35:05 +08:00
parent 323eb367d0
commit c1462a03dc
60 changed files with 1451 additions and 409 deletions

View File

@@ -0,0 +1,83 @@
using Dlhis.Canteen.Tickets.Request;
using Dlhis.Canteen.Voucher.Requests;
using Dlhis.Canteen.Voucher.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities.Voucher;
using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Tickets.Services.Implements;
public abstract class BaseVoucherService : IVoucherService
{
protected IDbContext DbContext { get; set; }
protected BaseVoucherService(IDbContext dbContext)
{
DbContext = dbContext;
}
public async Task<Pagination<VoucherPageResponse>> GetPageAsync(VoucherPageRequest request)
{
var pagination = await DbContext.Queryable<VoucherEntity>()
.LeftJoin<VoucherUserInfoEntity>((x, u) => x.No == u.VoucherNo)
.LeftJoin<GainfoEntity>((x, u, ga) => u.UserCode == ga.Code)
.Where(x => x.Type == request.Type)
.WhereIF(request.UserCode.IsPresent(), (x, u, ga) => u.UserCode == request.UserCode)
.WhereIF(request.SearchDateTimePeriod.HasValue(),
(x, u, ga) => x.CreateTime >= request.SearchDateTimePeriod.Start &&
x.CreateTime <= request.SearchDateTimePeriod.End)
.WhereIF(request.DepartmentNoFirst.IsPresent(),
(x, u, ga) => u.DepartmentNoFirst == request.DepartmentNoFirst)
.WhereIF(request.DepartmentNoSecond.IsPresent(),
(x, u, ga) => u.DepartmentNoSecond == request.DepartmentNoSecond)
.OrderByDescending(x => x.ClaimDateTime)
.Select((x, u, ga) => new VoucherPageResponse
{
Type = x.Type,
UserCode = u.UserCode,
UserName = ga.Name,
OriginalAmount = x.OriginalBalance,
Amount = x.Balance,
Remark = x.Remark,
Description = x.Description,
CostId = u.CostId,
DepartmentNo = u.DepartmentNo,
DepartmentNoFirst = u.DepartmentNoFirst,
DepartmentNoSecond = u.DepartmentNoSecond,
Werks = u.Werks,
Factory = u.Factory
})
.ToPageListAsync(request);
var searchNos = pagination.Data.SelectMany(x =>
{
return new List<string>
{
x.DepartmentNo,
x.DepartmentNoFirst,
x.DepartmentNoSecond
};
}).Distinct().ToList();
var departments = await DbContext.Queryable<DepartmentEntity>().Where(x => searchNos.Contains(x.No)).ToListAsync();
pagination.Data.ForEach(x =>
{
x.DepartmentName = departments.FirstOrDefault(d => d.No == x.DepartmentNo)?.Name;
x.DepartmentNameFirst = departments.FirstOrDefault(d => d.No == x.DepartmentNoFirst)?.Name;
x.DepartmentNameSecond = departments.FirstOrDefault(d => d.No == x.DepartmentNoSecond)?.Name;
});
return pagination;
}
public abstract Task CreateAsync(Dictionary<string, object> pairs);
public abstract Task<Pagination<VoucherBalancePageResponse>> GetVoucherBalancePageAsync(VoucherBalancePageRequest request);
}

View File

@@ -0,0 +1,254 @@
using System.Collections.Generic;
using System.Text;
using Dlhis.Basic.Api;
using Dlhis.Canteen.Tickets.Services;
using Dlhis.Canteen.Tickets.Services.Implements;
using Dlhis.Canteen.Voucher.Requests;
using Dlhis.Canteen.Voucher.Response;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Entities.Voucher;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.Entity;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using SqlSugar;
namespace Dlhis.Canteen.Voucher.Services.Implements;
[Service("BirthdayVoucherService")]
public class BirthdayVoucherService : BaseVoucherService, IVoucherService
{
private readonly IFactorySettingApi _factorySettingApi;
/// <inheritdoc />
public BirthdayVoucherService(IDbContext dbContext, IFactorySettingApi factorySettingApi) : base(dbContext)
{
_factorySettingApi = factorySettingApi;
}
/// <inheritdoc />
public override async Task CreateAsync(Dictionary<string, object> pairs)
{
var p = GetDateRange(pairs);
var remark = pairs != null && pairs.TryGetValue("remark", out var r) ? r?.ToString() : string.Empty;
var userCodes = pairs != null && pairs.TryGetValue("userCodes", out var c) ? c as List<string> : new List<string>();
//忽略tenant操作
await DbContext.IgnoreAsync<ITenantId>(async () =>
{
var gainfos = await GetGainfosAsync(userCodes, p.begin, p.end);
var departmentNos = gainfos.Select(g => g.DepartmentNo).Distinct().ToList();
var departmentInfos = await DbContext.Queryable<DepartmentEntity>()
.Where(x => departmentNos.Contains(x.No))
.ToListAsync();
foreach (var gainfo in gainfos.Where(x => x.Birthday.HasValue))
{
await DbContext.Client.Ado.BeginTranAsync();
try
{
var years = GetBirthdayYears(gainfo.Birthday.Value, p.begin, p.end);
foreach (var year in years)
{
await GenerateVoucherAsync(gainfo, departmentInfos, year, remark);
}
await DbContext.Client.Ado.CommitTranAsync();
}
catch (Exception)
{
await DbContext.Client.Ado.RollbackTranAsync();
}
}
});
}
private async Task GenerateVoucherAsync(GainfoEntity gainfo, List<DepartmentEntity> departments, int year, string remark)
{
//生日券金额固定100元
const decimal amount = 100;
var dayStr = year + "-" + gainfo.Birthday.Value.ToString("MM-dd");
//由数据类型+工号+生日组成唯一标识
var no = GenerateUniqueCode(VoucherEnumType.Birthday.ToString() + gainfo.Code + dayStr);
if (!await DbContext.Queryable<VoucherEntity>()
.Where(x => x.No == no)
.Where(x => x.Type == VoucherEnumType.Birthday)
.AnyAsync())
{
await DbContext.InsertAsync(new VoucherEntity
{
No = no,
Type = VoucherEnumType.Birthday,
ClaimDateTime = new DateTime(year, gainfo.Birthday.Value.Month, gainfo.Birthday.Value.Day),
OriginalBalance = amount,
Balance = amount,
Description = dayStr + "生日券",
Remark = remark,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
Version = 0
});
var department = departments.FirstOrDefault(x => x.No == gainfo.DepartmentNo);
await DbContext.InsertAsync(new VoucherUserInfoEntity
{
VoucherNo = no,
UserCode = gainfo.Code,
CostId = gainfo.CostId,
Werks = gainfo.Werks,
Factory = gainfo.Factory,
DepartmentNo = gainfo.DepartmentNo,
DepartmentNoFirst = department?.DepartmentNoFirst,
DepartmentNoSecond = department?.DepartmentNoSecond,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now
});
}
}
private (DateTime begin, DateTime end) GetDateRange(Dictionary<string, object> pairs)
{
var begin = DateTime.Today;
var end = begin;
if (pairs != null)
{
if (pairs.TryGetValue("begin", out var b))
{
if (b is DateTime bb)
{
begin = bb;
}
}
if (pairs.TryGetValue("end", out var e))
{
if (e is DateTime ee)
{
end = ee;
}
}
}
return (begin, end);
}
private async Task<List<GainfoEntity>> GetGainfosAsync(List<string> userCodes, DateTime begin, DateTime end)
{
var factries = await _factorySettingApi.GetEnableBirthdayVoucherFactoriesAsync();
var isToday = begin.Date == end.Date;
var beginMonth = begin.Month;
var endMonth = end.Month;
var overYear = endMonth < beginMonth;
//var limit = end.Date.AddHours(9);//9点入职
return await DbContext.Queryable<GainfoEntity>()
.WhereIF(userCodes.IsPresent(), x => userCodes.Contains(x.Code))
.Where(x => x.Type == GainfoUserTypeEnumType.Normal || x.Type == GainfoUserTypeEnumType.SecurityWhite)
.Where(x => x.Birthday.HasValue && !string.IsNullOrEmpty(x.CostId))
.WhereIF(isToday, x => SqlFunc.DateValue(x.Birthday.Value, DateType.Month) == begin.Month && SqlFunc.DateValue(x.Birthday.Value, DateType.Day) == begin.Day)
.WhereIF(!isToday && !overYear, x => SqlFunc.DateValue(x.Birthday.Value, DateType.Month) >= beginMonth && SqlFunc.DateValue(x.Birthday.Value, DateType.Month) <= endMonth)
.WhereIF(!isToday && overYear, x => SqlFunc.DateValue(x.Birthday.Value, DateType.Month) >= beginMonth || SqlFunc.DateValue(x.Birthday.Value, DateType.Month) <= endMonth)
.Where(x => factries.Contains(x.Factory))
.ToListAsync();
}
private static string GenerateUniqueCode(string data)
{
return QrCodeConstants.Birthday + data.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];
return Convert.ToString(i);
}).Join(string.Empty);
}
/// <summary>
/// 计算给定生日在区间 [begin, end] 内出现的所有年份(可能为0、1或多个)。
/// - 对于每个候选年份构造安全的日期(处理 2/29 在非闰年的情况,退到当年最大天数)。
/// - 若区间内找不到匹配年份,则返回包含 begin.Year 的单元素列表作为兜底行为,保持向后兼容。
/// </summary>
private static List<int> GetBirthdayYears(DateTime birthday, DateTime begin, DateTime end)
{
var years = new List<int>();
// 扩展范围到 begin.Year-1 .. end.Year+1 以覆盖跨年边界的极端情况
var startYear = begin.Year - 1;
var endYear = end.Year + 1;
for (var y = startYear; y <= endYear; y++)
{
var candidate = SafeDate(y, birthday);
if (candidate >= begin && candidate <= end)
{
years.Add(candidate.Year);
}
}
// 去重并排序
years = years.Distinct().OrderBy(x => x).ToList();
return years;
static DateTime SafeDate(int year, DateTime bday)
{
var day = Math.Min(bday.Day, DateTime.DaysInMonth(year, bday.Month));
return new DateTime(year, bday.Month, day);
}
}
public override async Task<Pagination<VoucherBalancePageResponse>> GetVoucherBalancePageAsync(VoucherBalancePageRequest request)
{
return await DbContext.Queryable<BalanceRecordEntity>()
.LeftJoin<BusinessPlaceEntity>((x, bPlace) => x.BusinessPlaceCode == bPlace.Code)
.LeftJoin<DepartmentEntity>((x, bPlace, department) => x.DepartmentNo == department.No)
.Where(x => x.UserCode == request.UserCode)
.WhereIF(request.SearchDateTimePeriod.HasValue(), x => x.CostDate >= request.SearchDateTimePeriod.Start && x.CostDate <= request.SearchDateTimePeriod.End) //成本日期
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid && x.Type == BalanceRecordTypeEnumType.Out) //有效,消费数据
.Where(x => x.Source == BalanceRecordSourceEnumType.Birthday)
.Select((x, bPlace, department) => new VoucherBalancePageResponse
{
No = x.No,
UserNo = x.UserNo,
Name = x.Name,
UserCode = x.UserCode,
DepartmentNo = x.DepartmentNo,
DepartmentName = department.Name,
CostDate = x.CostDate,
Remark = x.Remark,
Source = x.Source,
Type = x.Type,
Amount = SqlFunc.Abs(x.Amount),
BusinessPlaceName = bPlace.Name,
ShiftType = x.ShiftType,
DeviceInfo = x.DeviceUniqueNo,
CostId = x.CostId,
OriginTenantId = x.OriginTenantId,
Status = x.Status,
CostDateTime = x.CostDateTime,
Factory = x.TenantId,
Werks = x.Werks
})
.ToPageListAsync(request);
}
}

View File

@@ -0,0 +1,186 @@
using System.Text;
using Dlhis.Canteen.Order.Request;
using Dlhis.Canteen.Order.Response;
using Dlhis.Canteen.Voucher.Requests;
using Dlhis.Canteen.Voucher.Response;
using Dlhis.Constants;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Canteen.Entities;
using Dlhis.Entity.Canteen.Entities.EMealVoucher;
using Dlhis.Entity.Canteen.Enums;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Extensions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using SqlSugar;
namespace Dlhis.Canteen.Voucher.Services.Implements;
public class EMealVoucherService : IEMealVoucherService
{
private readonly IDbContext _dbContext;
private readonly ICurrentUser _currentUser;
public EMealVoucherService(IDbContext dbContext, ICurrentUser currentUser)
{
_dbContext = dbContext;
_currentUser = currentUser;
}
/// <inheritdoc />
public async Task<Pagination<EMealVoucherPageResponse>> GetPageAsync(EMealVoucherPageRequest request)
{
return await _dbContext.Queryable<EMealVoucherEntity>()
.WhereIF(request.Search.IsPresent(), x => x.No == request.Search ||
x.Code == request.Search ||
x.Title.Contains(request.Search))
.WhereIF(request.SearchDateTimePeriod.HasValue(), x => x.Date >= request.SearchDateTimePeriod.Start && x.Date <= request.SearchDateTimePeriod.End)
.OrderBy(x => x.Date, OrderByType.Desc)
.Select(x => new EMealVoucherPageResponse
{
No = x.No,
Title = x.Title,
Code = x.Code,
Phone = x.Phone,
CurrentFactories = x.Factories.ToString(),
Date = x.Date,
CostId = x.CostId,
Source = x.Source,
Reason = x.Reason,
CurrentShifts = x.Shifts.ToString(),
Details = SqlFunc.Subqueryable<EMealVoucherDetailEntity>().Where(p => p.No == x.No).ToList(p => new EMealVoucherDetailResponse
{
Id = p.Id,
Name = p.Name,
Phone = p.Phone,
Start = p.Start,
End = p.End,
Balance = p.Balance,
OriginBalance = p.OriginBalance,
})
})
.ToPageListAsync(request);
}
public async Task<Pagination<EMealVoucherMyPageResponse>> GetMyEMealVoucherPageAsync(EMealVoucherPageRequest request)
{
var code = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
return await _dbContext.Queryable<EMealVoucherEntity>()
.Where(x => x.Code == code)
.OrderBy(x => x.Id, OrderByType.Desc)
.Select<EMealVoucherMyPageResponse>()
.ToPageListAsync(request);
}
public async Task<List<EMealVoucherDetailResponse>> GetDetailsByNoAsync(string no)
{
return await _dbContext.Queryable<EMealVoucherDetailEntity>()
.Where(x => x.No == no)
.Select<EMealVoucherDetailResponse>()
.ToListAsync();
}
public async Task<string> GetQrCodeSignatureAsync(long detailId)
{
return await GenerateSignatureAsync(detailId, false);
}
public async Task RefreshSignatureAsync(long detailId)
{
await GenerateSignatureAsync(detailId, true);
}
private async Task<string> GenerateSignatureAsync(long detailId, bool isRefresh)
{
var eMealVoucherDetail = await _dbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.Id == detailId).SingleAsync();
eMealVoucherDetail.ThrowIfNull("数据不存在");
if (eMealVoucherDetail.Signature.IsPresent())
{
if (isRefresh)
{
await _dbContext.Deleteable<EMealVoucherDetailQrCodeEntity>().Where(x => x.Signature == eMealVoucherDetail.Signature).ExecuteCommandAsync();
}
else
{
return eMealVoucherDetail.Signature;
}
}
eMealVoucherDetail.Signature = Guid.NewGuid().ToString().Replace("-", "") + DateTimeOffset.Now.ToUnixTimeMilliseconds();
await _dbContext.UpdateAsync(eMealVoucherDetail);
return eMealVoucherDetail.Signature;
}
/// <inheritdoc />
public async Task<string> GetQrCodeAsync(string signature)
{
var eMealVoucherDetail = await _dbContext.Queryable<EMealVoucherDetailEntity>().Where(x => x.Signature == signature).SingleAsync();
eMealVoucherDetail.ThrowIfNull("无效地址");
var eMealVoucher = await _dbContext.Queryable<EMealVoucherEntity>().Where(x => x.No == eMealVoucherDetail.No).SingleAsync();
var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString().Reverse().Join(string.Empty);
var originData = string.Concat(eMealVoucher.No, ":", ts, ":", eMealVoucher.Code, ":", eMealVoucherDetail.IdNo);
var qrCode = QrCodeConstants.EMealVoucher + originData.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];
return Convert.ToString(i);
}).Join(string.Empty);
await _dbContext.InsertAsync(new EMealVoucherDetailQrCodeEntity
{
Signature = signature,
OriginData = originData,
QrCode = qrCode
});
return qrCode;
}
/// <inheritdoc />
public async Task<Pagination<BalanceRecordEMealVoucherResponse>> GetEMealVoucherPageAsync(BalanceRecordEMealVoucherPageRequest request)
{
var tenantId = _currentUser.GetStringTenantId();
return await _dbContext.Queryable<BalanceRecordEntity>()
.LeftJoin<BusinessPlaceEntity>((x, bPlace) => x.BusinessPlaceCode == bPlace.Code)
.LeftJoin<DepartmentEntity>((x, bPlace, department) => x.DepartmentNo == department.No)
.Where(x => x.Status == BalanceRecordStatusEnumType.Valid && x.Type == BalanceRecordTypeEnumType.Out) //有效,消费数据
.WhereIF(request.SearchDateTimePeriod.HasValue(), x => x.CostDate >= request.SearchDateTimePeriod.Start && x.CostDate <= request.SearchDateTimePeriod.End) //成本日期
.Where(x => x.Source == BalanceRecordSourceEnumType.EMealVoucher)
.Where(x => SqlFunc.Subqueryable<EMealVoucherEntity>().Where(p => p.Factory == tenantId).Where(p => p.Code == x.UserCode).Any() || x.TenantId == tenantId)
.Select((x, bPlace, department) => new BalanceRecordEMealVoucherResponse
{
No = x.No,
UserNo = x.UserNo,
Name = x.Name,
UserCode = x.UserCode,
DepartmentNo = x.DepartmentNo,
DepartmentName = department.Name,
CostDate = x.CostDate,
Remark = x.Remark,
Source = x.Source,
Type = x.Type,
Amount = SqlFunc.Abs(x.Amount),
BusinessPlaceName = bPlace.Name,
ShiftType = x.ShiftType,
DeviceInfo = x.DeviceUniqueNo,
CostId = x.CostId,
OriginTenantId = x.OriginTenantId,
Status = x.Status,
CostDateTime = x.CostDateTime,
Factory = x.TenantId,
Werks = x.Werks
})
.ToPageListAsync(request);
}
}

View File

@@ -0,0 +1,75 @@

using System.Text;
using Dlhis.Constants;
using Dlhis.Entity.Canteen.Entities.Voucher;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Canteen.Voucher.Services.Implements;
public class VoucherQrCodeService : IVoucherQrCodeService
{
private readonly IDbContext _dbContext;
private readonly ICurrentUser _currentUser;
public VoucherQrCodeService(IDbContext dbContext, ICurrentUser currentUser)
{
_dbContext = dbContext;
_currentUser = currentUser;
}
public async Task<string> GetQrCodeAsync(string voucherNo, bool isNeedRefresh = false)
{
var userCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode);
if (!await _dbContext.Queryable<VoucherUserInfoEntity>().Where(x => x.VoucherNo == voucherNo && x.UserCode == userCode).AnyAsync())
{
true.ThrowIfTrue("非法的消费券");
}
var qrcodeInfo = await _dbContext.Queryable<VoucherQrCodeEntity>().SingleAsync(x => x.VoucherNo == voucherNo);
if (qrcodeInfo == null)
{
qrcodeInfo = new VoucherQrCodeEntity
{
VoucherNo = voucherNo,
QrCode = GenerateQrCode(voucherNo)
};
await _dbContext.InsertAsync(qrcodeInfo);
return qrcodeInfo.QrCode;
}
var now = DateTime.Now;
if (qrcodeInfo.ModifiedTime.AddMinutes(1) >= now && !isNeedRefresh)
{
return qrcodeInfo.QrCode;
}
qrcodeInfo.QrCode = GenerateQrCode(voucherNo);
await _dbContext.UpdateAsync(qrcodeInfo);
return qrcodeInfo.QrCode;
}
/// <summary>
/// qrCode生成
/// </summary>
/// <param name="voucherNo"></param>
/// <returns></returns>
private static string GenerateQrCode(string voucherNo)
{
var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds();
return QrCodeConstants.Birthday + voucherNo.ToArray().Select(x =>
{
var b = Encoding.ASCII.GetBytes(x.ToString());
int i = b[0];
return Convert.ToString(i);
}).Join(string.Empty) + ts;
}
}