ow
This commit is contained in:
1 parent
9b01c4a57a
commit
6417562c4f
37 files changed
+2767
-202
No files matched your search
@@ -1698,6 +1698,10 @@ namespace CloudBuilder.Master.Service
|
||||
entity.OwerId = service.UserId;
|
||||
entity.IsLinkIndc = YesNoPolicy.NO;
|
||||
|
||||
// 网盘额度闸门:按当前用户类型限额,已用(KB)+本次(KB) 超限直接拒。
|
||||
// 放任何 InsertNow 之前,抛异常时主表/上传表/目录关系均未落库,DB 保持一致(仅物理文件可能成为孤儿,属上传前置阶段)。
|
||||
EnsureQuotaAllowed(dmsFile.FileSize);
|
||||
|
||||
repository.InsertNow(entity);
|
||||
|
||||
IRepository<DmsFileUploadEntity> repositoryUpload = repository.GetRepository<IRepository<DmsFileUploadEntity>>();
|
||||
@@ -1715,6 +1719,86 @@ namespace CloudBuilder.Master.Service
|
||||
return entity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当前登录用户的网盘用量汇总:类型/头像取自 security_user,已用取自 dms_file_usage_view(ower_id=本人 且非目录),
|
||||
/// 额度按 user_type 从 appsettings:NetDiskQuota 解析。供 dashboard 两张卡片一次拉取。
|
||||
/// </summary>
|
||||
[PermissionOperate(name: MasterPermissionPolicy.DmsFile, operate: Operate.Find)]
|
||||
public StorageUsageData GetMyStorageUsage()
|
||||
{
|
||||
IRepository<SecurityUserEntity> repositoryUser = repository.GetRepository<IRepository<SecurityUserEntity>>();
|
||||
SecurityUserEntity user = repositoryUser.DetachedEntities.Where(x => x.UserName == service.UserId).FirstOrDefault();
|
||||
string userType = user?.UserType;
|
||||
if (string.IsNullOrWhiteSpace(userType)) userType = SecurityUserTypePolicy.UNAUTHENTICATED_USERS;
|
||||
|
||||
long usedKB = GetUsedKB(service.UserId);
|
||||
long quotaKB = ServiceSettingsPolicy.GetNetDiskQuotaKB(service, userType);
|
||||
int percent = quotaKB > 0 ? (int)(usedKB * 100 / quotaKB) : 0;
|
||||
|
||||
return new StorageUsageData
|
||||
{
|
||||
UserType = userType,
|
||||
AvatarUrl = FileTypePolicy.PackAvatarUrl(service, UploadFolderPolicy.USER_AVATAR, user?.UserIconImgPath) ?? "",
|
||||
UsedKB = usedKB,
|
||||
QuotaKB = quotaKB,
|
||||
Percent = percent
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传并保存当前登录用户头像:复用与成员头像同一套 PackUploadFile 落盘(目录名统一走 UploadFolderPolicy.USER_AVATAR),
|
||||
/// 末片物理名回写 security_user.user_icon_img_path(与 family_person.avatar_filename 同口径存物理名),返回可访问 URL。
|
||||
/// </summary>
|
||||
[PermissionOperate(name: MasterPermissionPolicy.DmsFile, operate: Operate.Insert)]
|
||||
[UnitOfWork]
|
||||
public string UploadUserAvatar()
|
||||
{
|
||||
var files = httpContextAccessor.HttpContext.Request.Form.Files;
|
||||
if (files == null || files.Count == 0) return "";
|
||||
|
||||
IFormFile file = files[0];
|
||||
if (file == null || file.Length <= 0) return "";
|
||||
|
||||
// 落盘:单片三段式名(uni-时间戳-1-1.ext)会在 PackUploadFile 内合并到备份目录
|
||||
PackUploadFile(file, UploadFolderPolicy.USER_AVATAR);
|
||||
|
||||
string filename = file.FileName;
|
||||
|
||||
IRepository<SecurityUserEntity> repositoryUser = repository.GetRepository<IRepository<SecurityUserEntity>>();
|
||||
SecurityUserEntity user = repositoryUser.DetachedEntities.Where(x => x.UserName == service.UserId).FirstOrDefault();
|
||||
if (user != null)
|
||||
{
|
||||
user.UserIconImgPath = filename;
|
||||
repositoryUser.UpdateNow(user);
|
||||
}
|
||||
|
||||
return FileTypePolicy.PackAvatarUrl(service, UploadFolderPolicy.USER_AVATAR, filename) ?? "";
|
||||
}
|
||||
|
||||
/// <summary>查本人已用容量(KB)。按 dms_file_usage_view 视图实体标准 LINQ 链路取数,
|
||||
/// 无行(从未上传)记 0;ower_id 源自 JWT 登录态非外部入参。</summary>
|
||||
private long GetUsedKB(string owerId)
|
||||
{
|
||||
IRepository<DmsFileUsageViewEntity> repositoryView = repository.GetRepository<IRepository<DmsFileUsageViewEntity>>();
|
||||
return repositoryView.DetachedEntities.Where(x => x.OwerId == owerId).Select(x => x.UsedKb).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>上传额度校验:额度未配(≤0)视为不限;已用+本次超额度则抛业务异常拒上传。</summary>
|
||||
private void EnsureQuotaAllowed(int incomingKB)
|
||||
{
|
||||
IRepository<SecurityUserEntity> repositoryUser = repository.GetRepository<IRepository<SecurityUserEntity>>();
|
||||
string userType = repositoryUser.DetachedEntities.Where(x => x.UserName == service.UserId).FirstOrDefault()?.UserType;
|
||||
long quotaKB = ServiceSettingsPolicy.GetNetDiskQuotaKB(service, userType);
|
||||
if (quotaKB <= 0) return;
|
||||
long usedKB = GetUsedKB(service.UserId);
|
||||
if (usedKB + incomingKB > quotaKB)
|
||||
{
|
||||
long limitGB = quotaKB / (1024 * 1024);
|
||||
long usedGB = usedKB / (1024 * 1024);
|
||||
throw new ValidatedException($"网盘容量不足(上限约 {limitGB} GB,已用约 {usedGB} GB),请清理或升级会员后再上传。");
|
||||
}
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.DmsFile, operate: Operate.Find)]
|
||||
public dynamic DownloadFile(long fileId)
|
||||
{
|
||||
|
||||
@@ -18,9 +18,6 @@ namespace CloudBuilder.Master.Service
|
||||
{
|
||||
public class FamilyPersonService : IFamilyPersonService
|
||||
{
|
||||
/// <summary>头像上传目录,与前端 FileUpload 的 file-path 保持一致</summary>
|
||||
private const string AVATAR_FOLDER_NAME = "FamilyPersonAvatar";
|
||||
|
||||
private readonly IApplicationService service;
|
||||
|
||||
private IRepository<FamilyPersonEntity> repository;
|
||||
@@ -51,7 +48,7 @@ namespace CloudBuilder.Master.Service
|
||||
|
||||
data.FamilyPerson.IsCanAmend = new FamilyTreePermissionHelper(service).HasPermission(data.FamilyPerson.TreeId, data.FamilyPerson.PersonId);
|
||||
|
||||
data.FamilyPerson.AvatarUrl = FileTypePolicy.PackAvatarUrl(service, AVATAR_FOLDER_NAME, data.FamilyPerson.AvatarFilename);
|
||||
data.FamilyPerson.AvatarUrl = FileTypePolicy.PackAvatarUrl(service, UploadFolderPolicy.FAMILY_PERSON_AVATAR, data.FamilyPerson.AvatarFilename);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -16,13 +16,12 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
namespace CloudBuilder.Master.Service
|
||||
{
|
||||
public class FamilyTreeService : IFamilyTreeService
|
||||
{
|
||||
/// <summary>头像上传目录,与前端 FileUpload 的 file-path 保持一致</summary>
|
||||
private const string AVATAR_FOLDER_NAME = "FamilyPersonAvatar";
|
||||
|
||||
private readonly IApplicationService service;
|
||||
|
||||
private IRepository<FamilyTreeEntity> repository;
|
||||
@@ -36,7 +35,7 @@ namespace CloudBuilder.Master.Service
|
||||
private void FillAvatarUrl(FamilyPersonDisplayData person)
|
||||
{
|
||||
if (person == null) return;
|
||||
person.AvatarUrl = FileTypePolicy.PackAvatarUrl(service, AVATAR_FOLDER_NAME, person.AvatarFilename);
|
||||
person.AvatarUrl = FileTypePolicy.PackAvatarUrl(service, UploadFolderPolicy.FAMILY_PERSON_AVATAR, person.AvatarFilename);
|
||||
}
|
||||
|
||||
/// <summary>批量填充头像访问地址</summary>
|
||||
@@ -151,17 +150,30 @@ namespace CloudBuilder.Master.Service
|
||||
{
|
||||
currentPerson = d.AncestorPersonId;
|
||||
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == currentPerson).FirstOrDefault()!);
|
||||
FamilyPersonEntity ancestor0 = repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == currentPerson).FirstOrDefault();
|
||||
// 始祖行缺失是数据破损,给可读的业务错误而不是 NullReference 服务异常
|
||||
if (ancestor0 == null) throw new ValidatedException("该族谱未设置始祖或始祖档案已丢失.");
|
||||
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(ancestor0);
|
||||
|
||||
data.FamilyTree.AncestorPersonGenealogyName = data.CurrentPerson.FamilyPerson.GenealogyName;
|
||||
}
|
||||
else
|
||||
{
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == d.AncestorPersonId).FirstOrDefault()!);
|
||||
FamilyPersonEntity ancestor = repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == d.AncestorPersonId).FirstOrDefault();
|
||||
if (ancestor != null)
|
||||
{
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(ancestor);
|
||||
|
||||
data.FamilyTree.AncestorPersonGenealogyName = data.CurrentPerson.FamilyPerson.GenealogyName;
|
||||
data.FamilyTree.AncestorPersonGenealogyName = data.CurrentPerson.FamilyPerson.GenealogyName;
|
||||
}
|
||||
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == personId).FirstOrDefault()!);
|
||||
// 旧 personId 失效(如整谱替换/备份还原后全员重编号)回落始祖,不再抛「Source entity is null」服务异常
|
||||
FamilyPersonEntity current = repositoryFamilyPerson.DetachedEntities.Where(x => x.PersonId == personId).FirstOrDefault() ?? ancestor;
|
||||
if (current == null) throw new ValidatedException("该族谱中没有可用的族员.");
|
||||
currentPerson = current.PersonId;
|
||||
|
||||
data.CurrentPerson.FamilyPerson = new FamilyPersonDisplayData(current);
|
||||
}
|
||||
|
||||
FillAvatarUrl(data.CurrentPerson.FamilyPerson);
|
||||
@@ -362,6 +374,78 @@ namespace CloudBuilder.Master.Service
|
||||
repositoryPermission.InsertNow(fresh);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 小系替换后的权限行迁移(用户拍板:按新旧编号关联保留绑定权限):
|
||||
/// 被删后代/入配配偶若能经 idMap(文件旧号→重编新号)关联上则换绑到新号(同谱 round-trip 场景);
|
||||
/// 关联不上(跨谱嫁接/文件已删掉的人)的悬挂行顺手删除。
|
||||
/// 管理员行(ManagerIndc=YES)与 PersonId 空行(申请/未绑)一律不动;返回 moved/dropped 统计进审计。
|
||||
/// </summary>
|
||||
private string MigrateSubTreePermissions(string treeId, HashSet<string> deletedIds, Dictionary<string, string> idMap)
|
||||
{
|
||||
IRepository<FamilyTreePermissionEntity> repositoryPermission = repository.GetRepository<IRepository<FamilyTreePermissionEntity>>();
|
||||
FamilyTreePermissionEntity[] rows = repositoryPermission.DetachedEntities.Where(x => x.TreeId == treeId).ToArray();
|
||||
int moved = 0;
|
||||
int dropped = 0;
|
||||
foreach (FamilyTreePermissionEntity row in rows)
|
||||
{
|
||||
if (row.ManagerIndc == YesNoPolicy.YES || string.IsNullOrEmpty(row.PersonId) || !deletedIds.Contains(row.PersonId)) continue;
|
||||
string newId = idMap.ContainsKey(row.PersonId) ? idMap[row.PersonId] : null;
|
||||
// 新号已被同名其它行占用(理论上不会)则只删旧行,防复合主键冲突
|
||||
if (newId != null && rows.Any(x => x.PersonId == newId && x.UserName == row.UserName)) newId = null;
|
||||
if (newId == null)
|
||||
{
|
||||
repositoryPermission.DeleteNow(row);
|
||||
dropped++;
|
||||
continue;
|
||||
}
|
||||
RebindFamilyTreePermission(row, newId);
|
||||
moved++;
|
||||
}
|
||||
return $"moved={moved};dropped={dropped}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跨谱整谱替换后的权限行清理:全员重编号后本谱引用已删旧号的成员权限行必然悬挂(垃圾行),顺手删除;
|
||||
/// 管理员行(ManagerIndc=YES,建谱时 PersonId 指向始祖,IsManager 判定不看 PersonId)与 PersonId 空行保留。
|
||||
/// 同谱替换编号不变权限行天然无损,不需要走这里。返回删除条数进审计。
|
||||
/// </summary>
|
||||
private int CleanDanglingPermissions(string treeId, HashSet<string> aliveIds)
|
||||
{
|
||||
IRepository<FamilyTreePermissionEntity> repositoryPermission = repository.GetRepository<IRepository<FamilyTreePermissionEntity>>();
|
||||
List<string> alive = aliveIds.ToList();
|
||||
FamilyTreePermissionEntity[] dangling = repositoryPermission.DetachedEntities
|
||||
.Where(x => x.TreeId == treeId && x.ManagerIndc != YesNoPolicy.YES && x.PersonId != "" && !alive.Contains(x.PersonId)).ToArray();
|
||||
if (dangling.Length > 0) repositoryPermission.DeleteNow(dangling);
|
||||
return dangling.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 备份还原的权限回放(绝对闭环):把本谱权限行整体替换为备份快照,PersonId 经 idMap 重映射
|
||||
/// (还原恒同谱→编号不变→权限行原样落回);管理员行随快照一并恢复,还原人自身也在快照内故不会自锁。
|
||||
/// 仅备份(含权限快照)触发;.fm 导入无权限快照不会走到这里。返回恢复条数进审计。
|
||||
/// </summary>
|
||||
private int RestorePermissions(string treeId, FamilyTreePermissionEntity[] snapshot, Dictionary<string, string> idMap)
|
||||
{
|
||||
IRepository<FamilyTreePermissionEntity> repositoryPermission = repository.GetRepository<IRepository<FamilyTreePermissionEntity>>();
|
||||
FamilyTreePermissionEntity[] current = repositoryPermission.DetachedEntities.Where(x => x.TreeId == treeId).ToArray();
|
||||
if (current.Length > 0) repositoryPermission.DeleteNow(current);
|
||||
int restored = 0;
|
||||
foreach (FamilyTreePermissionEntity row in snapshot)
|
||||
{
|
||||
FamilyTreePermissionEntity fresh = new FamilyTreePermissionEntity
|
||||
{
|
||||
TreeId = treeId,
|
||||
UserName = row.UserName,
|
||||
PersonId = string.IsNullOrEmpty(row.PersonId) || !idMap.ContainsKey(row.PersonId) ? row.PersonId : idMap[row.PersonId],
|
||||
ManagerIndc = row.ManagerIndc,
|
||||
ValidIndc = row.ValidIndc,
|
||||
};
|
||||
repositoryPermission.InsertNow(fresh);
|
||||
restored++;
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户中文姓名(security_user.user_local_name);登录账号只是标识,不参与同名比较
|
||||
/// </summary>
|
||||
@@ -718,5 +802,599 @@ namespace CloudBuilder.Master.Service
|
||||
Delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
//=================== 族谱全系/小系 .fm 导入导出(D1-D8 决策) ===================
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public string GetExchangeFactor()
|
||||
{
|
||||
// D2:前端用「用户密码⊕系统因子」PBKDF2 派生 AES 密钥,因子由后端下发,不进前端包体
|
||||
return FamilyTreeExchangePolicy.EXCHANGE_FACTOR;
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public FamilyTreeExchangeData ExportFamilyTree(string treeId, string scope, string anchorPersonId)
|
||||
{
|
||||
FamilyTreeEntity tree = repository.DetachedEntities.Where(x => x.TreeId == treeId).FirstOrDefault();
|
||||
if (tree == null) throw new ValidatedException("族谱不存在.");
|
||||
|
||||
bool isSub = scope == FamilyTreeExchangeScope.SUB;
|
||||
FamilyTreePermissionHelper helper = new FamilyTreePermissionHelper(service);
|
||||
bool isManager = helper.IsManager(treeId);
|
||||
// D8 闸门:全系导出仅管理员;小系导出管理员任意锚点、成员仅限自己可编辑家支的锚点
|
||||
if (!isManager)
|
||||
{
|
||||
if (!helper.IsMember(treeId)) throw new ValidatedException("您没有导出权限.");
|
||||
if (!isSub) throw new ValidatedException("全系导出需要族谱管理员权限.");
|
||||
if (!helper.GetAmendablePersonIds(treeId).Contains(anchorPersonId)) throw new ValidatedException("只能导出以自己为锚点的家支.");
|
||||
}
|
||||
|
||||
IRepository<FamilyPersonEntity> repositoryPerson = repository.GetRepository<IRepository<FamilyPersonEntity>>();
|
||||
IRepository<FamilyTreeSpouseMapEntity> repositorySpouse = repository.GetRepository<IRepository<FamilyTreeSpouseMapEntity>>();
|
||||
IRepository<FamilyTreeChildrenMapEntity> repositoryChild = repository.GetRepository<IRepository<FamilyTreeChildrenMapEntity>>();
|
||||
|
||||
FamilyTreeSpouseMapEntity[] spouseMaps = repositorySpouse.DetachedEntities.Where(x => x.TreeId == treeId).OrderBy(x => x.Orderby).ToArray();
|
||||
FamilyTreeChildrenMapEntity[] childrenMaps = repositoryChild.DetachedEntities.Where(x => x.TreeId == treeId).OrderBy(x => x.Orderby).ToArray();
|
||||
FamilyPersonEntity[] persons = repositoryPerson.DetachedEntities.Where(x => x.TreeId == treeId).ToArray();
|
||||
|
||||
if (isSub)
|
||||
{
|
||||
// 小系子集口径 = 权限 helper 同源家支展开(后代闭包 + 配偶 + 上溯两代及其配偶):
|
||||
// 管理员拿传入锚点展开;成员闸门已验过锚点,直接用自己可编集合
|
||||
List<string> ids;
|
||||
if (isManager)
|
||||
{
|
||||
ids = new List<string>();
|
||||
helper.PackPersonIdByChildrenMaps(childrenMaps, spouseMaps, anchorPersonId, ids);
|
||||
}
|
||||
else
|
||||
{
|
||||
ids = helper.GetAmendablePersonIds(treeId);
|
||||
}
|
||||
persons = persons.Where(x => ids.Contains(x.PersonId)).ToArray();
|
||||
spouseMaps = spouseMaps.Where(x => ids.Contains(x.PersonId) && ids.Contains(x.SpouseId)).ToArray();
|
||||
childrenMaps = childrenMaps.Where(x => ids.Contains(x.PersonId) && ids.Contains(x.ChildrenId)).ToArray();
|
||||
}
|
||||
|
||||
string exportFileName = FamilyTreeExchangePolicy.BuildFileName(isSub ? FamilyTreeExchangeScope.SUB : FamilyTreeExchangeScope.ALL, treeId, anchorPersonId);
|
||||
WriteExchangeLog("OUT", treeId, isSub ? FamilyTreeExchangeScope.SUB : FamilyTreeExchangeScope.ALL, anchorPersonId, exportFileName, persons.Length, "OK", "");
|
||||
|
||||
return new FamilyTreeExchangeData
|
||||
{
|
||||
Scope = isSub ? FamilyTreeExchangeScope.SUB : FamilyTreeExchangeScope.ALL,
|
||||
FamilyTree = tree,
|
||||
Persons = persons,
|
||||
SpouseMaps = spouseMaps,
|
||||
ChildrenMaps = childrenMaps,
|
||||
// 二期:小系文件把锚点写进 payload,导入侧据此验明同一人(一期只体在文件名里,旧文件读进来为空串)
|
||||
AnchorPersonId = isSub ? anchorPersonId : "",
|
||||
ExportedBy = service.UserId,
|
||||
ExportedAt = DateTime.Now,
|
||||
};
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public string SaveExchangeFile(string fileName, string contentBase64)
|
||||
{
|
||||
if (!FamilyTreeExchangePolicy.IsValidFileName(fileName)) throw new ValidatedException("文件名不合法(须为 A谱号_时间.fm 或 P谱号-人名号_时间.fm).");
|
||||
FamilyTreePermissionHelper helper = new FamilyTreePermissionHelper(service);
|
||||
// 管理员也有生效权限行,IsMember 一并覆盖
|
||||
if (!helper.IsMember(FamilyTreeExchangePolicy.ParseFileName(fileName).Item1)) throw new ValidatedException("您不是该族谱成员.");
|
||||
|
||||
byte[] bytes;
|
||||
try { bytes = Convert.FromBase64String(contentBase64 ?? ""); }
|
||||
catch { throw new ValidatedException("文件内容不是合法的 base64."); }
|
||||
if (bytes.Length == 0 || bytes.Length > 50 * 1024 * 1024) throw new ValidatedException("文件大小异常(限 1B~50MB).");
|
||||
|
||||
string dir = FamilyTreeExchangePolicy.GetExchangeDirectory(service);
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllBytes(Path.Combine(dir, fileName), bytes);
|
||||
return fileName;
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public FamilyTreeExchangeFileInfo[] ListExchangeFiles(string treeId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(treeId)) throw new ValidatedException("请先选择族谱.");
|
||||
if (!new FamilyTreePermissionHelper(service).IsMember(treeId)) throw new ValidatedException("您不是该族谱成员.");
|
||||
|
||||
string dir = FamilyTreeExchangePolicy.GetExchangeDirectory(service);
|
||||
if (!Directory.Exists(dir)) return [];
|
||||
|
||||
List<FamilyTreeExchangeFileInfo> files = new List<FamilyTreeExchangeFileInfo>();
|
||||
foreach (string path in Directory.GetFiles(dir, "*" + FamilyTreeExchangePolicy.FILE_EXTENSION))
|
||||
{
|
||||
string name = Path.GetFileName(path);
|
||||
var parsed = FamilyTreeExchangePolicy.ParseFileName(name);
|
||||
// 只列本谱的文件(非法文件名一律跳过)
|
||||
if (parsed == null || parsed.Item1 != treeId) continue;
|
||||
FileInfo info = new FileInfo(path);
|
||||
files.Add(new FamilyTreeExchangeFileInfo
|
||||
{
|
||||
FileName = name,
|
||||
Size = info.Length,
|
||||
LastModified = info.LastWriteTime,
|
||||
Scope = parsed.Item3,
|
||||
TreeId = parsed.Item1,
|
||||
AnchorPersonId = parsed.Item2,
|
||||
});
|
||||
}
|
||||
// 导入以最新为准:时间降序,前端取第一条即可
|
||||
return files.OrderByDescending(x => x.LastModified).ToArray();
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public string ReadExchangeFile(string fileName)
|
||||
{
|
||||
if (!FamilyTreeExchangePolicy.IsValidFileName(fileName)) throw new ValidatedException("文件名不合法.");
|
||||
if (!new FamilyTreePermissionHelper(service).IsMember(FamilyTreeExchangePolicy.ParseFileName(fileName).Item1)) throw new ValidatedException("您不是该族谱成员.");
|
||||
|
||||
string path = Path.Combine(FamilyTreeExchangePolicy.GetExchangeDirectory(service), fileName);
|
||||
if (!File.Exists(path)) throw new ValidatedException("文件不存在或已被清理.");
|
||||
return Convert.ToBase64String(File.ReadAllBytes(path));
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Update)]
|
||||
[UnitOfWork]
|
||||
public int ImportFamilyTree(string targetTreeId, FamilyTreeExchangeData data)
|
||||
{
|
||||
FamilyTreeEntity target = repository.DetachedEntities.Where(x => x.TreeId == targetTreeId).FirstOrDefault();
|
||||
if (target == null) throw new ValidatedException("目标族谱不存在.");
|
||||
// D4:整谱替换是谱级破坏性操作,仅目标谱管理员;失败由 ValidatedException 抛回,事务整体回滚
|
||||
if (!new FamilyTreePermissionHelper(service).IsManager(targetTreeId)) throw new ValidatedException("只有族谱管理员可以整谱替换导入.");
|
||||
if (data == null || data.Persons == null || data.Persons.Length == 0) throw new ValidatedException("导入数据为空.");
|
||||
// 一期只开放全系文件替换;小系 merge 未开(P 文件导进谱会把别人家支的人叠进来,关系锚点不明)
|
||||
if (data.Scope != FamilyTreeExchangeScope.ALL) throw new ValidatedException("目前仅支持全系(ALL)文件导入,小系合并暂未开放.");
|
||||
// D3:允许跨谱导入(payload 自带谱信息,主键以目标谱为准),无谱信息的是非法包
|
||||
if (data.FamilyTree == null) throw new ValidatedException("导入数据缺少谱信息.");
|
||||
return ReplaceTreeCore(target, data, "IN");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 替换前整谱 JSON 备份(回滚点):明文存交换目录 Backup 子目录,文件名进审计 message;
|
||||
/// ListExchangeFiles 只看 *.fm,备份不会被列成可导入文件。
|
||||
/// </summary>
|
||||
private string BackupTree(FamilyTreeEntity target, FamilyPersonEntity[] oldPersons, FamilyTreeSpouseMapEntity[] oldSpouses, FamilyTreeChildrenMapEntity[] oldChildren)
|
||||
{
|
||||
string backupName = FamilyTreeExchangePolicy.BuildBackupFileName(target.TreeId);
|
||||
string backupDir = FamilyTreeExchangePolicy.GetBackupDirectory(service);
|
||||
Directory.CreateDirectory(backupDir);
|
||||
// 权限行一并入快照(还原时随谱回滚,绝对闭环);整份密文落盘(含账号名隐私)
|
||||
IRepository<FamilyTreePermissionEntity> repositoryPermission = repository.GetRepository<IRepository<FamilyTreePermissionEntity>>();
|
||||
FamilyTreePermissionEntity[] perms = repositoryPermission.DetachedEntities.Where(x => x.TreeId == target.TreeId).ToArray();
|
||||
string plainJson = System.Text.Json.JsonSerializer.Serialize(new FamilyTreeExchangeData
|
||||
{
|
||||
Scope = FamilyTreeExchangeScope.ALL,
|
||||
FamilyTree = target,
|
||||
Persons = oldPersons,
|
||||
SpouseMaps = oldSpouses,
|
||||
ChildrenMaps = oldChildren,
|
||||
Permissions = perms,
|
||||
ExportedBy = service.UserId,
|
||||
});
|
||||
File.WriteAllText(Path.Combine(backupDir, backupName), FamilyTreeExchangePolicy.EncryptBackup(plainJson));
|
||||
return backupName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 整谱替换本体(ImportFamilyTree 与 RestoreBackup 共用,调用方已开事务):
|
||||
/// 先备份现谱→关系先行、人后删→插入→关系双端 remap→谱信息行更新→审计。
|
||||
/// 同谱(文件谱号==目标谱,备份还原/服务器文件导入恒同谱):编号与绑定原样保留,库与文件 100% 一致,权限行不悬挂;
|
||||
/// 跨谱嫁接:全员重编号+清绑定(防主键冲突与绑定劫持)。入库前先过完整性闸,坏文件直接拒绝。
|
||||
/// 审计动码区分来源:IN=外部文件导入 / RESTORE=备份回滚回放。
|
||||
/// </summary>
|
||||
private int ReplaceTreeCore(FamilyTreeEntity target, FamilyTreeExchangeData data, string action)
|
||||
{
|
||||
string targetTreeId = target.TreeId;
|
||||
// 同谱判定:文件谱号与目标谱一致(还原走 R6 闸恒同谱;跨谱全系只能来自本地上传)
|
||||
bool sameTree = string.Equals(data.FamilyTree?.TreeId ?? "", targetTreeId, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 0) 完整性闸:整谱数据必须内部闭合(人员编号非空不重复、关系行两端都在文件内),
|
||||
// 否则拒绝——宁可不导也不允许静默丢行,保证落库与文件 100% 相同
|
||||
HashSet<string> fileIdSet = new HashSet<string>();
|
||||
foreach (FamilyPersonEntity p in data.Persons)
|
||||
if (string.IsNullOrEmpty(p.PersonId) || !fileIdSet.Add(p.PersonId))
|
||||
throw new ValidatedException("导入/还原失败:文件内人员编号为空或重复,数据不完整.");
|
||||
foreach (FamilyTreeSpouseMapEntity m in data.SpouseMaps ?? [])
|
||||
if (!fileIdSet.Contains(m.PersonId) || !fileIdSet.Contains(m.SpouseId))
|
||||
throw new ValidatedException("导入/还原失败:配偶关系引用了文件外的人员,数据不完整.");
|
||||
foreach (FamilyTreeChildrenMapEntity m in data.ChildrenMaps ?? [])
|
||||
if (!fileIdSet.Contains(m.PersonId) || !fileIdSet.Contains(m.ChildrenId))
|
||||
throw new ValidatedException("导入/还原失败:父子关系引用了文件外的人员,数据不完整.");
|
||||
|
||||
IRepository<FamilyPersonEntity> repositoryPerson = repository.GetRepository<IRepository<FamilyPersonEntity>>();
|
||||
IRepository<FamilyTreeSpouseMapEntity> repositorySpouse = repository.GetRepository<IRepository<FamilyTreeSpouseMapEntity>>();
|
||||
IRepository<FamilyTreeChildrenMapEntity> repositoryChild = repository.GetRepository<IRepository<FamilyTreeChildrenMapEntity>>();
|
||||
|
||||
// 1) 替换前自动备份(回滚点)
|
||||
FamilyPersonEntity[] oldPersons = repositoryPerson.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
FamilyTreeSpouseMapEntity[] oldSpouses = repositorySpouse.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
FamilyTreeChildrenMapEntity[] oldChildren = repositoryChild.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
string backupName = BackupTree(target, oldPersons, oldSpouses, oldChildren);
|
||||
|
||||
// 2) 清空当前谱:关系先行、人后删(事务内任一环节失败全部回滚,备份文件已落盘不受影响)
|
||||
if (oldSpouses.Length > 0) repositorySpouse.DeleteNow(oldSpouses);
|
||||
if (oldChildren.Length > 0) repositoryChild.DeleteNow(oldChildren);
|
||||
foreach (FamilyPersonEntity old in oldPersons) repositoryPerson.DeleteNow(old);
|
||||
|
||||
// 同谱回放需保留文件里的 Created 印章,而框架 SaveChanges 会对 Added 强制盖 CreatedBy/CreatedDatetime,
|
||||
// 故插入段临时关闭审计印章(仿 LocaleService 先例;跨谱不开——照旧由框架盖当次操作人/时间);
|
||||
// 下方手工赋值不受影响(Updated* 均为代码显式设置),末尾 finally 复位防残留
|
||||
MasterDbContext dbCtx = repository.GetDbContext() as MasterDbContext;
|
||||
Dictionary<string, string> idMap = new Dictionary<string, string>();
|
||||
try
|
||||
{
|
||||
if (sameTree && dbCtx != null) dbCtx.SkipAudit = true;
|
||||
|
||||
// 3) 编号策略:同谱保留原编号与绑定(权限行/锚点继续有效,数据 100% 回放);
|
||||
// 跨谱一律走号段生成器重发 PersonId + 清绑定(防冲突防劫持,进谱后重走审批绑定)
|
||||
ISecurityGeneratorNumberService generator = service.ServiceProvider.GetService<ISecurityGeneratorNumberService>()!;
|
||||
DateTime now = DateTime.Now;
|
||||
foreach (FamilyPersonEntity p in data.Persons)
|
||||
{
|
||||
idMap[p.PersonId] = sameTree ? p.PersonId : generator.GetNo(MasterPrefixPolicy.FAMILY_PERSON, MasterPrefixPolicy.FAMILY_PERSON_PERSON_ID, MasterPrefixPolicy.FAMILY_PERSON_PREFIX, YesNoPolicy.NO, MasterPrefixPolicy.FAMILY_PERSON_FORMAT);
|
||||
}
|
||||
foreach (FamilyPersonEntity p in data.Persons)
|
||||
{
|
||||
FamilyPersonEntity fresh = p.Clone();
|
||||
fresh.PersonId = idMap[p.PersonId];
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.FatherId = string.IsNullOrEmpty(p.FatherId) ? null : (idMap.ContainsKey(p.FatherId) ? idMap[p.FatherId] : null);
|
||||
fresh.BindUserId = sameTree ? p.BindUserId : null;
|
||||
fresh.IsBindUser = sameTree ? p.IsBindUser : null;
|
||||
if (sameTree)
|
||||
{
|
||||
fresh.CreatedBy = p.CreatedBy;
|
||||
fresh.CreatedDatetime = p.CreatedDatetime;
|
||||
}
|
||||
else
|
||||
{
|
||||
fresh.CreatedBy = service.UserId;
|
||||
fresh.CreatedDatetime = now;
|
||||
}
|
||||
fresh.UpdatedBy = service.UserId;
|
||||
fresh.UpdatedDatetime = now;
|
||||
repositoryPerson.InsertNow(fresh);
|
||||
}
|
||||
|
||||
// 4) 关系行双端 remap(完整性闸已保证两端都在文件内,此处必全量命中);
|
||||
// 同谱时 Created 印章随 Clone 原样回放,Updated 补当次操作痕迹;跨谱由框架盖当次
|
||||
foreach (FamilyTreeSpouseMapEntity m in data.SpouseMaps ?? [])
|
||||
{
|
||||
if (!idMap.ContainsKey(m.PersonId) || !idMap.ContainsKey(m.SpouseId)) continue;
|
||||
FamilyTreeSpouseMapEntity fresh = m.Clone();
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.PersonId = idMap[m.PersonId];
|
||||
fresh.SpouseId = idMap[m.SpouseId];
|
||||
if (sameTree)
|
||||
{
|
||||
fresh.UpdatedBy = service.UserId;
|
||||
fresh.UpdatedDatetime = now;
|
||||
}
|
||||
repositorySpouse.InsertNow(fresh);
|
||||
}
|
||||
foreach (FamilyTreeChildrenMapEntity m in data.ChildrenMaps ?? [])
|
||||
{
|
||||
if (!idMap.ContainsKey(m.PersonId) || !idMap.ContainsKey(m.ChildrenId)) continue;
|
||||
FamilyTreeChildrenMapEntity fresh = m.Clone();
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.PersonId = idMap[m.PersonId];
|
||||
fresh.ChildrenId = idMap[m.ChildrenId];
|
||||
if (sameTree)
|
||||
{
|
||||
fresh.UpdatedBy = service.UserId;
|
||||
fresh.UpdatedDatetime = now;
|
||||
}
|
||||
repositoryChild.InsertNow(fresh);
|
||||
}
|
||||
|
||||
// 5) 谱信息字段以数据为准(主键 TreeId 保持目标谱;始祖指向重编后的始祖)
|
||||
target.TreeName = data.FamilyTree.TreeName;
|
||||
target.Brief = data.FamilyTree.Brief;
|
||||
target.TreeCoverFilename = data.FamilyTree.TreeCoverFilename;
|
||||
target.PublicIndc = data.FamilyTree.PublicIndc;
|
||||
target.AncestorPersonId = idMap.ContainsKey(data.FamilyTree.AncestorPersonId ?? "") ? idMap[data.FamilyTree.AncestorPersonId] : target.AncestorPersonId;
|
||||
target.UpdatedBy = service.UserId;
|
||||
target.UpdatedDatetime = now;
|
||||
repository.UpdateNow(target);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (dbCtx != null) dbCtx.SkipAudit = false;
|
||||
}
|
||||
|
||||
// 权限闭环:备份还原(含权限快照)→ 权限整体回放到备份时刻;跨谱 .fm 导入(无快照)→ 清悬挂行;同谱 .fm 导入→不碰
|
||||
string permStat;
|
||||
if (data.Permissions != null && data.Permissions.Length > 0)
|
||||
permStat = $"; permRestored={RestorePermissions(targetTreeId, data.Permissions, idMap)}";
|
||||
else if (!sameTree)
|
||||
permStat = $"; permDropped={CleanDanglingPermissions(targetTreeId, new HashSet<string>(idMap.Values))}";
|
||||
else
|
||||
permStat = "";
|
||||
|
||||
// 6) 审计(事务回滚则审计同滚——失败场景弹错给用户,不留半截日志)
|
||||
WriteExchangeLog(action, targetTreeId, FamilyTreeExchangeScope.ALL, "", backupName, idMap.Count, "OK", $"backup={backupName}; sameTree={(sameTree ? 1 : 0)}{permStat}");
|
||||
return idMap.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 支系闭包:锚点以下后代 + 后代的配偶(迭代到不动点,防回头婚配漏拉);锚点本人不进集合。
|
||||
/// 目标侧算删除集、文件侧算插入集共用此口径,保证删/插范围对称。
|
||||
/// </summary>
|
||||
static HashSet<string> BranchClosure(string anchorId, FamilyTreeChildrenMapEntity[] childrenMaps, FamilyTreeSpouseMapEntity[] spouseMaps)
|
||||
{
|
||||
HashSet<string> set = new HashSet<string>();
|
||||
bool changed = true;
|
||||
while (changed)
|
||||
{
|
||||
changed = false;
|
||||
foreach (FamilyTreeChildrenMapEntity m in childrenMaps ?? [])
|
||||
{
|
||||
if ((m.PersonId == anchorId || set.Contains(m.PersonId)) && m.ChildrenId != anchorId && set.Add(m.ChildrenId)) changed = true;
|
||||
}
|
||||
foreach (FamilyTreeSpouseMapEntity m in spouseMaps ?? [])
|
||||
{
|
||||
if (set.Contains(m.PersonId) && m.SpouseId != anchorId && set.Add(m.SpouseId)) changed = true;
|
||||
if (set.Contains(m.SpouseId) && m.PersonId != anchorId && set.Add(m.PersonId)) changed = true;
|
||||
}
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Update)]
|
||||
[UnitOfWork]
|
||||
public int ImportSubTree(string targetTreeId, string anchorPersonId, FamilyTreeExchangeData data)
|
||||
{
|
||||
FamilyTreeEntity target = repository.DetachedEntities.Where(x => x.TreeId == targetTreeId).FirstOrDefault();
|
||||
if (target == null) throw new ValidatedException("目标族谱不存在.");
|
||||
if (data == null || data.Persons == null || data.Persons.Length == 0) throw new ValidatedException("导入数据为空.");
|
||||
if (data.Scope != FamilyTreeExchangeScope.SUB) throw new ValidatedException("支系导入仅收小系(SUB)文件,全系请走整谱替换.");
|
||||
if (string.IsNullOrEmpty(data.AnchorPersonId)) throw new ValidatedException("导入文件未标记小系锚点(旧版导出文件),请重新导出.");
|
||||
if (string.IsNullOrEmpty(anchorPersonId)) throw new ValidatedException("请先选择要替换的族内锚点族人.");
|
||||
|
||||
FamilyTreePermissionHelper helper = new FamilyTreePermissionHelper(service);
|
||||
// P6 权限闸:管理员任意锚点;成员仅限自己可编家支的锚点(与小系导出同一把闸)
|
||||
if (!helper.IsManager(targetTreeId))
|
||||
{
|
||||
if (!helper.IsMember(targetTreeId)) throw new ValidatedException("您没有导入权限.");
|
||||
if (!helper.GetAmendablePersonIds(targetTreeId).Contains(anchorPersonId)) throw new ValidatedException("只能替换自己家支的锚点.");
|
||||
}
|
||||
|
||||
IRepository<FamilyPersonEntity> repositoryPerson = repository.GetRepository<IRepository<FamilyPersonEntity>>();
|
||||
IRepository<FamilyTreeSpouseMapEntity> repositorySpouse = repository.GetRepository<IRepository<FamilyTreeSpouseMapEntity>>();
|
||||
IRepository<FamilyTreeChildrenMapEntity> repositoryChild = repository.GetRepository<IRepository<FamilyTreeChildrenMapEntity>>();
|
||||
|
||||
FamilyPersonEntity targetAnchor = repositoryPerson.DetachedEntities.Where(x => x.TreeId == targetTreeId && x.PersonId == anchorPersonId).FirstOrDefault();
|
||||
if (targetAnchor == null) throw new ValidatedException("锚点族人不存在.");
|
||||
// P2/P3 同一人验证:文件锚点与所选族人 姓+谱名 全量一致才同意,否则拒绝
|
||||
FamilyPersonEntity fileAnchor = data.Persons.FirstOrDefault(x => x.PersonId == data.AnchorPersonId);
|
||||
if (fileAnchor == null) throw new ValidatedException("文件里找不到锚点人.");
|
||||
string Trim(string s) => (s ?? "").Trim();
|
||||
if (Trim(fileAnchor.Surname) != Trim(targetAnchor.Surname) || Trim(fileAnchor.GenealogyName) != Trim(targetAnchor.GenealogyName))
|
||||
throw new ValidatedException("文件锚点与所选族人不是同一人(姓/谱名不符),已拒绝导入.");
|
||||
|
||||
FamilyPersonEntity[] oldPersons = repositoryPerson.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
FamilyTreeSpouseMapEntity[] oldSpouses = repositorySpouse.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
FamilyTreeChildrenMapEntity[] oldChildren = repositoryChild.DetachedEntities.Where(x => x.TreeId == targetTreeId).ToArray();
|
||||
|
||||
// 1) 替换前整谱 JSON 备份(P7,回滚点,同整谱替换口径)
|
||||
string backupName = BackupTree(target, oldPersons, oldSpouses, oldChildren);
|
||||
|
||||
// 1.5) 方案 C:锚点本人也纳入替换——资料整体覆盖为文件锚点(备份已先行,可回滚);
|
||||
// PersonId/TreeId/FatherId/绑定字段/建档信息保留目标侧,防锚点脱谱、防绑定被文件旧值劫持
|
||||
DateTime now = DateTime.Now;
|
||||
FamilyPersonEntity mergedAnchor = targetAnchor.Clone();
|
||||
mergedAnchor.CopyFrom(fileAnchor);
|
||||
mergedAnchor.PersonId = targetAnchor.PersonId;
|
||||
mergedAnchor.TreeId = targetTreeId;
|
||||
mergedAnchor.FatherId = targetAnchor.FatherId;
|
||||
mergedAnchor.BindUserId = targetAnchor.BindUserId;
|
||||
mergedAnchor.IsBindUser = targetAnchor.IsBindUser;
|
||||
mergedAnchor.CreatedBy = targetAnchor.CreatedBy;
|
||||
mergedAnchor.CreatedDatetime = targetAnchor.CreatedDatetime;
|
||||
mergedAnchor.UpdatedBy = service.UserId;
|
||||
mergedAnchor.UpdatedDatetime = now;
|
||||
repositoryPerson.UpdateNow(mergedAnchor);
|
||||
|
||||
// 2) 删除集:目标锚点以下后代闭包 + 锚点配偶(方案 C 扩展:锚点整家替换;锚点本人已在 1.5 步覆盖)
|
||||
// 配偶仅「纯入配」(无其它婚配/血缘关系、无账号绑定、非始祖)才随删重插;否则只断与锚点的关系行、人行保留防悬挂
|
||||
HashSet<string> delSet = BranchClosure(anchorPersonId, oldChildren, oldSpouses);
|
||||
HashSet<string> delSpousePersons = new HashSet<string>();
|
||||
foreach (string sid in oldSpouses.Where(x => x.PersonId == anchorPersonId || x.SpouseId == anchorPersonId)
|
||||
.Select(x => x.PersonId == anchorPersonId ? x.SpouseId : x.PersonId).Distinct())
|
||||
{
|
||||
if (sid == anchorPersonId || sid == target.AncestorPersonId || delSet.Contains(sid)) continue;
|
||||
FamilyPersonEntity sp = oldPersons.FirstOrDefault(x => x.PersonId == sid);
|
||||
if (sp == null) continue;
|
||||
bool pure = string.IsNullOrEmpty(sp.BindUserId)
|
||||
&& !oldSpouses.Any(x => (x.PersonId == sid || x.SpouseId == sid) && x.PersonId != anchorPersonId && x.SpouseId != anchorPersonId)
|
||||
&& !oldChildren.Any(x => x.PersonId == sid || x.ChildrenId == sid);
|
||||
if (pure) delSpousePersons.Add(sid);
|
||||
}
|
||||
FamilyTreeSpouseMapEntity[] delSpouses = oldSpouses.Where(x => delSet.Contains(x.PersonId) || delSet.Contains(x.SpouseId) || x.PersonId == anchorPersonId || x.SpouseId == anchorPersonId).ToArray();
|
||||
FamilyTreeChildrenMapEntity[] delChildren = oldChildren.Where(x => delSet.Contains(x.ChildrenId)).ToArray();
|
||||
FamilyPersonEntity[] delPersons = oldPersons.Where(x => delSet.Contains(x.PersonId) || delSpousePersons.Contains(x.PersonId)).ToArray();
|
||||
if (delSpouses.Length > 0) repositorySpouse.DeleteNow(delSpouses);
|
||||
if (delChildren.Length > 0) repositoryChild.DeleteNow(delChildren);
|
||||
foreach (FamilyPersonEntity old in delPersons) repositoryPerson.DeleteNow(old);
|
||||
|
||||
// 3) 插入集:文件侧同口径闭包(上溯段落不插,P4)+ 文件锚点的配偶(方案 C 扩展,与目标侧删除对称);文件锚点映射到保留的目标锚点,其余重编号
|
||||
HashSet<string> insSet = BranchClosure(data.AnchorPersonId, data.ChildrenMaps, data.SpouseMaps);
|
||||
foreach (string fsid in (data.SpouseMaps ?? []).Where(x => x.PersonId == data.AnchorPersonId || x.SpouseId == data.AnchorPersonId)
|
||||
.Select(x => x.PersonId == data.AnchorPersonId ? x.SpouseId : x.PersonId).Distinct())
|
||||
{
|
||||
if (fsid != data.AnchorPersonId && !insSet.Contains(fsid) && data.Persons.Any(p => p.PersonId == fsid)) insSet.Add(fsid);
|
||||
}
|
||||
ISecurityGeneratorNumberService generator = service.ServiceProvider.GetService<ISecurityGeneratorNumberService>()!;
|
||||
Dictionary<string, string> idMap = new Dictionary<string, string> { [data.AnchorPersonId] = anchorPersonId };
|
||||
foreach (FamilyPersonEntity p in data.Persons)
|
||||
{
|
||||
if (!insSet.Contains(p.PersonId) || idMap.ContainsKey(p.PersonId)) continue;
|
||||
idMap[p.PersonId] = generator.GetNo(MasterPrefixPolicy.FAMILY_PERSON, MasterPrefixPolicy.FAMILY_PERSON_PERSON_ID, MasterPrefixPolicy.FAMILY_PERSON_PREFIX, YesNoPolicy.NO, MasterPrefixPolicy.FAMILY_PERSON_FORMAT);
|
||||
}
|
||||
foreach (FamilyPersonEntity p in data.Persons)
|
||||
{
|
||||
if (!insSet.Contains(p.PersonId)) continue; // 锚点以外的文件人(上溯段)一律不插
|
||||
FamilyPersonEntity fresh = p.Clone();
|
||||
fresh.PersonId = idMap[p.PersonId];
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.FatherId = string.IsNullOrEmpty(p.FatherId) ? null : (idMap.ContainsKey(p.FatherId) ? idMap[p.FatherId] : null);
|
||||
fresh.BindUserId = null;
|
||||
fresh.IsBindUser = null;
|
||||
fresh.CreatedBy = service.UserId;
|
||||
fresh.CreatedDatetime = now;
|
||||
fresh.UpdatedBy = service.UserId;
|
||||
fresh.UpdatedDatetime = now;
|
||||
repositoryPerson.InsertNow(fresh);
|
||||
}
|
||||
|
||||
// 4) 关系行双端 remap(文件锚点端直接对接保留的目标锚点);引用集合外人的行丢弃防悬挂
|
||||
foreach (FamilyTreeSpouseMapEntity m in data.SpouseMaps ?? [])
|
||||
{
|
||||
if (!idMap.ContainsKey(m.PersonId) || !idMap.ContainsKey(m.SpouseId)) continue;
|
||||
if (m.PersonId == data.AnchorPersonId && m.SpouseId == data.AnchorPersonId) continue;
|
||||
FamilyTreeSpouseMapEntity fresh = m.Clone();
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.PersonId = idMap[m.PersonId];
|
||||
fresh.SpouseId = idMap[m.SpouseId];
|
||||
repositorySpouse.InsertNow(fresh);
|
||||
}
|
||||
foreach (FamilyTreeChildrenMapEntity m in data.ChildrenMaps ?? [])
|
||||
{
|
||||
if (!idMap.ContainsKey(m.PersonId) || !idMap.ContainsKey(m.ChildrenId)) continue;
|
||||
FamilyTreeChildrenMapEntity fresh = m.Clone();
|
||||
fresh.TreeId = targetTreeId;
|
||||
fresh.PersonId = idMap[m.PersonId];
|
||||
fresh.ChildrenId = idMap[m.ChildrenId];
|
||||
repositoryChild.InsertNow(fresh);
|
||||
}
|
||||
|
||||
// 4.5) 权限行迁移(用户拍板:按新旧编号关联保留绑定权限):被删后代/入配配偶的绑定成员随人换绑到新号,
|
||||
// 关联不上的悬挂行删除;锚点行(id 未变)与枝外/管理员行不动
|
||||
string permStat = MigrateSubTreePermissions(targetTreeId, new HashSet<string>(delPersons.Select(x => x.PersonId)), idMap);
|
||||
|
||||
// 5) 审计 MERGE(P7 独立动作码,统计口径与整谱替换的 IN 分开):Message 记合并报告;人数含锚点本人(方案 C 同步覆盖)
|
||||
WriteExchangeLog("MERGE", targetTreeId, FamilyTreeExchangeScope.SUB, anchorPersonId, backupName, insSet.Count + 1, "OK", $"backup={backupName}; deleted={delPersons.Length}; inserted={insSet.Count}; anchor=1; anchorSpouse={delSpousePersons.Count}; perm {permStat}");
|
||||
return insSet.Count + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 备份列表(R1 收紧:备份是谁的操作谁的回滚——成员只见自己创建的,管理员不限):
|
||||
/// 只列本谱 BK 文件,R5 保留窗口(一年)内,按备份时刻降序;时刻以文件名为准,归属看 JSON 里的 ExportedBy。
|
||||
/// </summary>
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Find)]
|
||||
public FamilyTreeExchangeFileInfo[] ListBackups(string treeId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(treeId)) throw new ValidatedException("请先选择族谱.");
|
||||
FamilyTreePermissionHelper helper = new FamilyTreePermissionHelper(service);
|
||||
if (!helper.IsMember(treeId)) throw new ValidatedException("您不是该族谱成员.");
|
||||
bool isManager = helper.IsManager(treeId);
|
||||
|
||||
string dir = FamilyTreeExchangePolicy.GetBackupDirectory(service);
|
||||
if (!Directory.Exists(dir)) return [];
|
||||
|
||||
List<FamilyTreeExchangeFileInfo> files = new List<FamilyTreeExchangeFileInfo>();
|
||||
DateTime earliest = DateTime.Now.AddYears(-FamilyTreeExchangePolicy.BACKUP_KEEP_YEARS);
|
||||
foreach (string path in Directory.GetFiles(dir, $"BK{treeId}_*.json"))
|
||||
{
|
||||
string name = Path.GetFileName(path);
|
||||
var parsed = FamilyTreeExchangePolicy.ParseBackupFileName(name);
|
||||
// 谱号不符(大小写变体防御)、时刻超出保留窗口、文件名解析失败的一律不列
|
||||
if (parsed == null || parsed.Item1 != treeId || parsed.Item2 < earliest) continue;
|
||||
// 非管理员只列自己创建的备份(读 JSON 取 ExportedBy,大小写不敏感;解析不出归属的旧文件对成员隐藏、管理员可见)
|
||||
if (!isManager && ReadBackupOwner(path) != service.UserId) continue;
|
||||
files.Add(new FamilyTreeExchangeFileInfo
|
||||
{
|
||||
FileName = name,
|
||||
Size = new FileInfo(path).Length,
|
||||
LastModified = parsed.Item2,
|
||||
Scope = "BK",
|
||||
TreeId = treeId,
|
||||
AnchorPersonId = "",
|
||||
});
|
||||
}
|
||||
return files.OrderByDescending(x => x.LastModified).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>从备份 JSON 轻量提取创建人(ExportedBy);密文先解密再读,读不到/损坏返 null</summary>
|
||||
private static string ReadBackupOwner(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using System.Text.Json.JsonDocument doc = System.Text.Json.JsonDocument.Parse(FamilyTreeExchangePolicy.DecryptBackup(File.ReadAllText(path)));
|
||||
foreach (System.Text.Json.JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (string.Equals(p.Name, "ExportedBy", StringComparison.OrdinalIgnoreCase)) return p.Value.GetString();
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 备份还原(R2:导小系/导全系出事,用替换前自动备份整谱回放退回):
|
||||
/// R1 成员也可还原;R3 还原前先把现谱再备份一份(还原错了还能退回去);
|
||||
/// R6 文件名严格 BK 格式且谱号必须等于目标谱(防路径穿越与跨谱灌数据)。
|
||||
/// 还原走整谱替换本体:全员重编号、绑定清除,与整谱导入同副作用。
|
||||
/// </summary>
|
||||
[PermissionOperate(name: MasterPermissionPolicy.FamilyTree, operate: Operate.Update)]
|
||||
[UnitOfWork]
|
||||
public int RestoreBackup(string targetTreeId, string backupFileName)
|
||||
{
|
||||
FamilyTreeEntity target = repository.DetachedEntities.Where(x => x.TreeId == targetTreeId).FirstOrDefault();
|
||||
if (target == null) throw new ValidatedException("目标族谱不存在.");
|
||||
if (!new FamilyTreePermissionHelper(service).IsMember(targetTreeId)) throw new ValidatedException("您没有还原权限.");
|
||||
|
||||
// R6:格式闸(含目录成分拒绝)+ 归属闸(只能还原本谱的备份)+ R5 保留窗口闸
|
||||
var parsed = FamilyTreeExchangePolicy.ParseBackupFileName(backupFileName ?? "");
|
||||
if (parsed == null) throw new ValidatedException("备份文件名不合法.");
|
||||
if (parsed.Item1 != targetTreeId) throw new ValidatedException("备份文件不属于本族谱,不能跨谱还原.");
|
||||
if (parsed.Item2 < DateTime.Now.AddYears(-FamilyTreeExchangePolicy.BACKUP_KEEP_YEARS)) throw new ValidatedException("备份已超出保留窗口(一年),不允许还原.");
|
||||
|
||||
string path = Path.Combine(FamilyTreeExchangePolicy.GetBackupDirectory(service), backupFileName);
|
||||
if (!File.Exists(path)) throw new ValidatedException("备份文件不存在或已被清理.");
|
||||
FamilyTreeExchangeData data;
|
||||
try
|
||||
{
|
||||
// 备份密文先解密(旧明文备份无 ENC: 前缀直接透传);直读需大小写不敏感,实体属性对不上时会静默空值,故下面验内容完整性
|
||||
data = System.Text.Json.JsonSerializer.Deserialize<FamilyTreeExchangeData>(FamilyTreeExchangePolicy.DecryptBackup(File.ReadAllText(path)),
|
||||
new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new ValidatedException($"备份文件已损坏,无法解析: {ex.Message}");
|
||||
}
|
||||
if (data == null || data.Persons == null || data.Persons.Length == 0 || data.FamilyTree == null)
|
||||
throw new ValidatedException("备份内容不完整,禁止还原.");
|
||||
// R1 收紧:成员只能还原自己创建的备份(防绕过列表直调接口);管理员不限
|
||||
if (!new FamilyTreePermissionHelper(service).IsManager(targetTreeId) && data.ExportedBy != service.UserId)
|
||||
throw new ValidatedException("该备份由其他用户创建,成员只能还原自己的备份.");
|
||||
|
||||
return ReplaceTreeCore(target, data, "RESTORE");
|
||||
}
|
||||
|
||||
/// <summary>D7 审计:写 family_tree_file_log;失败不阻断主流程(日志丢了可以补,导不出去的体验才是大事)</summary>
|
||||
private void WriteExchangeLog(string action, string treeId, string scope, string anchorPersonId, string fileName, int personCount, string result, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
IRepository<FamilyTreeFileLogEntity> repositoryLog = repository.GetRepository<IRepository<FamilyTreeFileLogEntity>>();
|
||||
DateTime now = DateTime.Now;
|
||||
repositoryLog.InsertNow(new FamilyTreeFileLogEntity
|
||||
{
|
||||
CreatedDatetime = now,
|
||||
CreatedBy = service.UserId,
|
||||
UpdatedDatetime = now,
|
||||
UpdatedBy = service.UserId,
|
||||
TreeId = treeId,
|
||||
Action = action,
|
||||
Scope = scope,
|
||||
AnchorPersonId = string.IsNullOrEmpty(anchorPersonId) ? null : anchorPersonId,
|
||||
FileName = fileName,
|
||||
PersonCount = personCount,
|
||||
Result = result,
|
||||
Message = message,
|
||||
});
|
||||
}
|
||||
catch (Exception ex) { Console.WriteLine($"[FamilyTreeExchange] 审计写入失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
using CloudBuilder.Core.DatabaseAccessor.Entity;
|
||||
using CloudBuilder.Master.Data;
|
||||
using CloudBuilder.Security.Policy;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace CloudBuilder.Master.Service.FamilyTreeUtility
|
||||
{
|
||||
/// <summary>
|
||||
/// 族谱全系/小系 .fm 交换文件的规则:目录、文件名、系统因子。
|
||||
/// 不新增配置节——目录与身份证/头像上传同根(FileServiceSettings:UploadFileDirectory),固定挂在 FamilyTree 子目录下
|
||||
/// </summary>
|
||||
public static class FamilyTreeExchangePolicy
|
||||
{
|
||||
/// <summary>交换目录名(身份证用 FamilyPersonAvatar/IdCard,这里同款机制)</summary>
|
||||
public const string EXCHANGE_FOLDER_NAME = "FamilyTree";
|
||||
|
||||
public const string FILE_EXTENSION = ".fm";
|
||||
|
||||
/// <summary>D2 系统因子:前端 PBKDF2(用户密码⊕因子) 派生 AES 密钥,防「只漏密码」离线破解</summary>
|
||||
public const string EXCHANGE_FACTOR = "YouJiaLa.FamilyTree.Exchange.v1";
|
||||
|
||||
// D1 文件名:全系 A{treeId}_{ts}.fm;小系 P{treeId}-{personId}_{ts}.fm(ts=yyyyMMddHHmmss)
|
||||
private static readonly Regex ALL_FILE = new Regex(@"^AT\w+_\d{14}\.fm$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
private static readonly Regex SUB_FILE = new Regex(@"^PT\w+-P\w+_\d{14}\.fm$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
// R6 备份文件名:BK{treeId}_{ts}.json(替换前自动落盘的整谱回滚点,存 Backup 子目录,不进交换文件白名单)
|
||||
private static readonly Regex BACKUP_FILE = new Regex(@"^BKT\w+_\d{14}\.json$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>备份目录名(挂在交换目录下)</summary>
|
||||
public const string BACKUP_FOLDER_NAME = "Backup";
|
||||
|
||||
/// <summary>R5 备份保留窗口:列表与还原都只认一年内</summary>
|
||||
public static readonly int BACKUP_KEEP_YEARS = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 备份密文魔数前缀:备份含成员权限行(账号名等隐私),统一用服务端 AES 密钥加密落盘;
|
||||
/// 前缀区分新老格式(无此前缀视为旧明文库,向后兼容),不新增配置节(复用 EncryptHelper 内置密钥)
|
||||
/// </summary>
|
||||
public const string BACKUP_ENCRYPT_PREFIX = "ENC:";
|
||||
|
||||
/// <summary>备份明文 JSON → 密文文本(写盘前调用)</summary>
|
||||
public static string EncryptBackup(string plainJson)
|
||||
{
|
||||
return BACKUP_ENCRYPT_PREFIX + EncryptHelper.AesEncrypt(plainJson);
|
||||
}
|
||||
|
||||
/// <summary>备份文件文本 → 明文 JSON(带 ENC: 前缀解密;旧明文备份直接透传)</summary>
|
||||
public static string DecryptBackup(string fileContent)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileContent)) return fileContent;
|
||||
return fileContent.StartsWith(BACKUP_ENCRYPT_PREFIX)
|
||||
? EncryptHelper.AesDecrpt(fileContent.Substring(BACKUP_ENCRYPT_PREFIX.Length))
|
||||
: fileContent;
|
||||
}
|
||||
|
||||
public static string GetExchangeDirectory(IApplicationService service)
|
||||
{
|
||||
return Path.Combine(ServiceSettingsPolicy.GetUploadFileDirectory(service), EXCHANGE_FOLDER_NAME);
|
||||
}
|
||||
|
||||
/// <summary>生成 D1 规范文件名</summary>
|
||||
public static string BuildFileName(string scope, string treeId, string anchorPersonId)
|
||||
{
|
||||
string ts = DateTime.Now.ToString("yyyyMMddHHmmss");
|
||||
return scope == FamilyTreeExchangeScope.SUB
|
||||
? $"P{treeId}-{anchorPersonId}_{ts}{FILE_EXTENSION}"
|
||||
: $"A{treeId}_{ts}{FILE_EXTENSION}";
|
||||
}
|
||||
|
||||
/// <summary>校验文件名:只准 D1 两种格式,且拒绝任何目录成分(防 ../ 路径穿越)</summary>
|
||||
public static bool IsValidFileName(string fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName)) return false;
|
||||
if (fileName != Path.GetFileName(fileName)) return false;
|
||||
return ALL_FILE.IsMatch(fileName) || SUB_FILE.IsMatch(fileName);
|
||||
}
|
||||
|
||||
/// <summary>从合法文件名反解析 (treeId, anchorPersonId, scope);非法返回 null</summary>
|
||||
public static Tuple<string, string, string> ParseFileName(string fileName)
|
||||
{
|
||||
if (!IsValidFileName(fileName)) return null;
|
||||
// 去掉前缀字母与时间戳,取中间的 id 段
|
||||
string body = fileName.Substring(1, fileName.Length - 1 - FILE_EXTENSION.Length).Split('_')[0];
|
||||
if (fileName[0].ToString().Equals("A", StringComparison.OrdinalIgnoreCase))
|
||||
return Tuple.Create(body, "", FamilyTreeExchangeScope.ALL);
|
||||
string[] parts = body.Split('-');
|
||||
return Tuple.Create(parts[0], parts[1], FamilyTreeExchangeScope.SUB);
|
||||
}
|
||||
|
||||
public static string GetBackupDirectory(IApplicationService service)
|
||||
{
|
||||
return Path.Combine(GetExchangeDirectory(service), BACKUP_FOLDER_NAME);
|
||||
}
|
||||
|
||||
/// <summary>生成备份文件名(谱号+秒级时间戳,同谱同秒重名由覆盖兼容:秒内连点两次导入的极小概率场景)</summary>
|
||||
public static string BuildBackupFileName(string treeId)
|
||||
{
|
||||
return $"BK{treeId}_{DateTime.Now:yyyyMMddHHmmss}.json";
|
||||
}
|
||||
|
||||
/// <summary>校验备份文件名:只准 BK 格式,拒绝任何目录成分(还原入口防路径穿越/拿 *.fm 灌数据)</summary>
|
||||
public static bool IsValidBackupFileName(string fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName)) return false;
|
||||
if (fileName != Path.GetFileName(fileName)) return false;
|
||||
return BACKUP_FILE.IsMatch(fileName);
|
||||
}
|
||||
|
||||
/// <summary>从合法备份文件名反解析 (treeId, 备份时刻);非法返回 null。时刻以文件名为准(不依赖文件系统时间戳)</summary>
|
||||
public static Tuple<string, DateTime> ParseBackupFileName(string fileName)
|
||||
{
|
||||
if (!IsValidBackupFileName(fileName)) return null;
|
||||
string body = fileName.Substring(2, fileName.Length - 2 - ".json".Length);
|
||||
string[] parts = body.Split('_');
|
||||
if (!DateTime.TryParseExact(parts[1], "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime ts))
|
||||
return null;
|
||||
return Tuple.Create(parts[0], ts);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user