You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

122 lines
3.3 KiB

using Easy.DDD.Domain.Entities;
using Identity.Api.Clean.Shared.Consts;
using System.Collections.ObjectModel;
namespace Identity.Api.Clean.Domain.Entites;
public class OrganizationUnit : AggregateRoot<Guid>
{
public virtual Guid? TenantId { get; protected set; }
/// <summary>
/// 父 <see cref="OrganizationUnit"/> Id.
/// Null,如果此 OU 是根。
/// </summary>
public virtual Guid? ParentId { get; internal set; }
/// <summary>
/// 此组织单位的层次代码。
/// 示例:“00001.00042.00005”。
/// 这是组织单位的唯一代码。
/// 如果OU层次结构改变,它是可变的。
/// </summary>
public virtual string Code { get; internal set; }
/// <summary>
/// 此组织单位的显示名称。
/// </summary>
public virtual string DisplayName { get; set; }
/// <summary>
/// 此 OU 的角色。
/// </summary>
public virtual ICollection<OrganizationUnitRole> Roles { get; protected set; }
/// <summary>
/// Initializes a new instance of the <see cref="OrganizationUnit"/> class.
/// </summary>
public OrganizationUnit()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrganizationUnit"/> class.
/// </summary>
/// <param name="id">id</param>
/// <param name="displayName">显示名称.</param>
/// <param name="parentId">如果 OU 是根,则为父 ID 或 null.</param>
/// <param name="tenantId">主机的租户 ID 或 null.</param>
public OrganizationUnit(Guid id, string displayName, Guid? parentId = null, Guid? tenantId = null)
: base(id)
{
TenantId = tenantId;
DisplayName = displayName;
ParentId = parentId;
Roles = new Collection<OrganizationUnitRole>();
}
public static string CreateCode(params int[] numbers)
{
if (numbers == null)
{
return null;
}
return string.Join(".", numbers.Select(number => number.ToString(new string('0', OrganizationUnitConsts.CodeUnitLength))));
}
public static string AppendCode(string parentCode, string childCode)
{
if (string.IsNullOrEmpty(parentCode))
{
return childCode;
}
return parentCode + "." + childCode;
}
public static string CalculateNextCode(string code)
{
var parentCode = GetParentCode(code);
var lastUnitCode = GetLastUnitCode(code);
return AppendCode(parentCode, CreateCode(Convert.ToInt32(lastUnitCode) + 1));
static string GetLastUnitCode(string code)
{
var splittedCode = code.Split('.');
return splittedCode[^1];
}
static string GetParentCode(string code)
{
var splittedCode = code.Split('.');
if (splittedCode.Length == 1)
{
return null;
}
return string.Join(".", splittedCode.Take(splittedCode.Length - 1));
}
}
public virtual void AddRole(Guid roleId)
{
if (!Roles.Any(r => r.RoleId == roleId))
{
Roles.Add(new OrganizationUnitRole(roleId, Id, TenantId));
}
}
public virtual void RemoveRole(Guid roleId)
{
var item = Roles.FirstOrDefault(r => r.RoleId == roleId);
if (item != null)
Roles.Remove(item);
}
}