69 lines
1.9 KiB
C#
69 lines
1.9 KiB
C#
using Fake.Rbac.Infrastructure;
|
||
using Fake.EntityFrameworkCore;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Oms.Domain.CustomersAggregate.Entities;
|
||
|
||
namespace Oms.Application.Shared;
|
||
|
||
/// <summary>
|
||
/// 顾问邀请绑定:注册时把所属顾问(CustomerService)写成员工登录账号。
|
||
/// </summary>
|
||
public static class StaffAdvisorBinder
|
||
{
|
||
/// <summary>
|
||
/// 仅在 CustomerService 为空时绑定;advisorCode 为员工 Account(来自 ?advisor=)。
|
||
/// 无效账号静默跳过,不阻断注册。
|
||
/// </summary>
|
||
public static async Task BindAdvisorOnCreateAsync(
|
||
Customer entity,
|
||
string? advisorCode,
|
||
FakeRbacDbContext rbacDbContext,
|
||
CancellationToken cancellationToken = default)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(entity.CustomerService))
|
||
{
|
||
return;
|
||
}
|
||
|
||
var key = advisorCode?.Trim();
|
||
if (string.IsNullOrWhiteSpace(key))
|
||
{
|
||
return;
|
||
}
|
||
|
||
var account = await ResolveStaffAccountAsync(rbacDbContext, key, cancellationToken);
|
||
if (string.IsNullOrWhiteSpace(account))
|
||
{
|
||
return;
|
||
}
|
||
|
||
entity.CustomerService = account;
|
||
}
|
||
|
||
private static async Task<string?> ResolveStaffAccountAsync(
|
||
FakeRbacDbContext rbacDbContext,
|
||
string key,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var sql = $@"
|
||
SELECT u.`Account` AS `Account`
|
||
FROM `{FakeTables.User}` u
|
||
WHERE u.`IsDeleted` = 0
|
||
AND u.`Account` = {{0}}
|
||
ORDER BY u.`CreateTime` ASC
|
||
LIMIT 1
|
||
";
|
||
|
||
var row = await rbacDbContext.Database
|
||
.SqlQueryRaw<AccountRow>(sql, key)
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
|
||
return string.IsNullOrWhiteSpace(row?.Account) ? null : row.Account.Trim();
|
||
}
|
||
|
||
private sealed class AccountRow
|
||
{
|
||
public string? Account { get; set; }
|
||
}
|
||
}
|