admin/src/Oms.Application/Shared/OmsSessionHelper.cs
2026-06-25 19:10:44 +08:00

106 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Fake.Application;
using Fake.Users;
using Oms.Domain.CustomersAggregate.Entities;
using Oms.Domain.CustomersAggregate.Repositories;
namespace Oms.Application.Shared;
/// <summary>
/// 从 JWT Claims 解析当前会话类型(管理员 / 客户)。
/// </summary>
public static class OmsSessionHelper
{
public const string LoginTypeClaim = "loginType";
private const string CustomerLoginType = "1";
public static bool IsCustomerLogin(ICurrentUser currentUser) =>
string.Equals(
currentUser.FindClaimOrNull(LoginTypeClaim)?.Value,
CustomerLoginType,
StringComparison.Ordinal);
/// <summary>
/// 客户登录时返回 mapId(对应 t_customer.UserId / 订单 CreateUserId);管理员返回 null。
/// </summary>
public static int? TryGetCustomerMapId(ICurrentUser currentUser)
{
if (!IsCustomerLogin(currentUser))
{
return null;
}
var userId = currentUser.GetId<int>();
return userId > 0 ? userId : null;
}
/// <summary>
/// 客户登录时返回 mapId(对应订单 CreateUserId);管理员返回 null(不过滤)。
/// </summary>
public static int? TryGetCustomerCreateUserId(ICurrentUser currentUser) =>
TryGetCustomerMapId(currentUser);
/// <summary>
/// 解析当前会话对应的 t_customer 记录(客户按 UserId=mapId;管理员可按 CustomerId 代提交)。
/// </summary>
public static async Task<Customer> ResolveSessionCustomerAsync(
ICustomerRepository customerRepository,
ICurrentUser currentUser,
int? requestedCustomerId = null)
{
var mapId = TryGetCustomerMapId(currentUser);
if (mapId.HasValue)
{
var sessionCustomer = await customerRepository.FirstOrDefaultAsync(x => x.UserId == mapId.Value);
if (sessionCustomer == null)
{
throw new BusinessException("未找到客户信息");
}
if (requestedCustomerId is > 0 && requestedCustomerId.Value != sessionCustomer.Id)
{
throw new BusinessException("无权为该客户提交充值");
}
return sessionCustomer;
}
var customerId = requestedCustomerId ?? currentUser.GetId<int>();
if (customerId <= 0)
{
throw new BusinessException("客户ID不能为空");
}
var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId);
if (customer == null)
{
throw new BusinessException("客户不存在");
}
return customer;
}
/// <summary>
/// 客户登录时强制返回 t_customer.Id;管理员返回入参 customerId。
/// </summary>
public static async Task<int?> ResolveListCustomerIdAsync(
ICustomerRepository customerRepository,
ICurrentUser currentUser,
int? requestedCustomerId)
{
var mapId = TryGetCustomerMapId(currentUser);
if (!mapId.HasValue)
{
return requestedCustomerId;
}
var customer = await customerRepository.FirstOrDefaultAsync(x => x.UserId == mapId.Value);
if (customer == null)
{
throw new BusinessException("未找到客户信息");
}
return customer.Id;
}
}