using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NCC.Code;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqEmployeeProfile;
using NCC.Extend.Entitys.Dto.LqEmployeeProfileSubmission;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_employee_profile;
using NCC.Extend.Helpers;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.Extend.Interfaces.UserProfileAudit;
using NCC.Extend.Interfaces.UserProfileVersion;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using NCC.System.Entitys.System;
using Newtonsoft.Json;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend
{
///
/// 员工档案扩展(与用户管理表单联动;主档仍在 BASE_USER)
///
[ApiDescriptionSettings(Tag = "员工档案", Name = "LqEmployeeProfile", Order = 210)]
[Route("api/Extend/LqEmployeeProfile")]
public class LqEmployeeProfileService : IDynamicApiController, ITransient
{
private const string BizLogModule = "员工档案";
private const string BizTypeProfile = "lq_employee_profile";
private readonly ISqlSugarClient _db;
private readonly IUserManager _userManager;
private readonly IBusinessOperationLogService _businessOperationLogService;
private readonly IUserProfileAuditAppender _userProfileAuditAppender;
private readonly IUserProfileVersionAppender _userProfileVersionAppender;
///
/// 初始化员工档案服务
///
public LqEmployeeProfileService(
ISqlSugarClient db,
IUserManager userManager,
IBusinessOperationLogService businessOperationLogService,
IUserProfileAuditAppender userProfileAuditAppender,
IUserProfileVersionAppender userProfileVersionAppender)
{
_db = db;
_userManager = userManager;
_businessOperationLogService = businessOperationLogService;
_userProfileAuditAppender = userProfileAuditAppender;
_userProfileVersionAppender = userProfileVersionAppender;
}
///
/// 按用户 ID 获取员工档案扩展详情(含年龄、司龄;银行卡脱敏)
///
///
/// 供用户管理表单加载档案扩展区;年龄优先按 BASE_USER 身份证号推算,司龄按 F_ENTRYDATE 推算。
///
/// 参数说明:
/// - userId: BASE_USER.F_Id
///
/// 用户 ID
/// 档案详情;无档案时仅返回 userId 与计算字段
/// 成功
/// userId 为空或用户不存在
/// 服务器错误
[HttpGet("GetByUserId")]
public async Task GetByUserIdAsync([FromQuery] string userId)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw NCCException.Oh("userId 不能为空");
}
var user = await _db.Queryable()
.Where(x => x.Id == userId && x.DeleteMark == null)
.FirstAsync();
if (user == null)
{
throw NCCException.Oh("用户不存在");
}
await EnsureAuthenticatedAsync();
var profile = await _db.Queryable()
.Where(x => x.UserId == userId)
.FirstAsync();
return await MapOutputAsync(profile, user);
}
///
/// 保存或更新员工档案扩展(管理后台)
///
///
/// 银行卡明文仅用于传输,落库为 AES 密文;空 bankCardNo 表示不修改已有卡号。
/// 若请求体为实质空白档案(关键扩展字段均未填写,枚举仅为 null/未选),则跳过校验与落库,直接返回当前档案或空结果,
/// 便于管理后台仅保存用户主档时不触发「现居住地址不能为空」等扩展档案必填校验。
///
/// 示例请求:
/// ```json
/// {
/// "userId": "1234567890",
/// "maritalStatus": 1,
/// "employeeType": 1,
/// "employeeStatus": 2,
/// "bankName": "中国银行",
/// "bankCardNo": "6222021234567890123"
/// }
/// ```
///
/// 保存参数
/// 保存后的档案详情
/// 保存成功
/// 参数校验失败
/// 服务器错误
[HttpPost("Save")]
public async Task SaveAsync([FromBody] LqEmployeeProfileSaveInput input)
{
if (input == null || string.IsNullOrWhiteSpace(input.userId))
{
throw NCCException.Oh("userId 不能为空");
}
var user = await _db.Queryable()
.Where(x => x.Id == input.userId && x.DeleteMark == null)
.FirstAsync();
if (user == null)
{
throw NCCException.Oh("用户不存在");
}
await EnsureCanEditUserAsync(user);
var existing = await _db.Queryable()
.Where(x => x.UserId == input.userId)
.FirstAsync();
if (IsSubstantiallyEmpty(input))
{
return MapOutput(existing, user);
}
ValidateSaveInput(input);
var autoRegularizationDate = EmployeeProfileSensitiveHelper.CalcRegularizationDate(
user.EntryDate, input.probationMonths);
if (autoRegularizationDate.HasValue)
{
input.regularizationDate = autoRegularizationDate;
}
if (!string.IsNullOrWhiteSpace(input.employeeNo))
{
var dup = await _db.Queryable()
.Where(x => x.EmployeeNo == input.employeeNo.Trim()
&& x.UserId != input.userId)
.AnyAsync();
if (dup)
{
throw NCCException.Oh("工号已被其他员工使用");
}
}
var operatorId = _userManager.UserId;
var operatorName = _userManager.RealName ?? _userManager.Account;
var now = DateTime.Now;
var beforeSnapshot = existing == null ? null : BuildProfileSnapshot(existing);
LqEmployeeProfileEntity entity;
if (existing == null)
{
entity = new LqEmployeeProfileEntity
{
Id = YitIdHelper.NextId().ToString(),
UserId = input.userId,
CreateTime = now,
CreateUser = operatorId
};
ApplyInput(entity, input, null);
entity.UpdateTime = now;
entity.UpdateUser = operatorId;
await _db.Insertable(entity).ExecuteCommandAsync();
}
else
{
entity = existing;
ApplyInput(entity, input, existing.BankCardCipher);
entity.UpdateTime = now;
entity.UpdateUser = operatorId;
await _db.Updateable(entity).ExecuteCommandAsync();
}
var afterSnapshot = BuildProfileSnapshot(entity);
var detailJson = JsonConvert.SerializeObject(new
{
before = beforeSnapshot,
after = afterSnapshot,
userId = input.userId
});
await _businessOperationLogService.WriteAsync(
BizLogModule,
existing == null ? "新增员工档案" : "修改员工档案",
BizTypeProfile,
entity.Id,
$"{(existing == null ? "新增" : "修改")}员工档案 userId={input.userId}",
detailJson);
return MapOutput(entity, user);
}
///
/// 员工自助查看个人公司档案
///
///
/// 供员工手机端查看本人档案;仅返回当前登录用户数据,不接受 userId 参数。
/// 同时返回系统开关 allowSelfEdit 及档案编辑所需下拉选项。
///
/// 参数说明:
/// - 无请求参数,从登录态读取当前用户 ID
///
/// 本人档案详情(含敏感字段明文及脱敏字段)
/// 成功返回本人档案
/// 未登录或用户不存在
/// 服务器错误
[HttpGet("GetMine")]
public async Task GetMineAsync()
{
var userId = _userManager.UserId;
if (string.IsNullOrWhiteSpace(userId))
{
throw NCCException.Oh("未登录或登录已失效");
}
var user = await _db.Queryable()
.Where(x => x.Id == userId && x.DeleteMark == null)
.FirstAsync();
if (user == null)
{
throw NCCException.Oh("用户不存在");
}
var profile = await _db.Queryable()
.Where(x => x.UserId == userId)
.FirstAsync();
var allowSelfEdit = await EmployeeProfileSelfEditConfigHelper.GetAllowSelfEditAsync(_db);
return await MapMineOutputAsync(profile, user, allowSelfEdit);
}
///
/// 员工自助保存个人公司档案
///
///
/// 仅当系统配置 employeeProfileSelfEditSwitch=1 时允许保存;关闭时直接拒绝。
/// 不可修改工号、员工类型/状态、试用期、转正日期、招聘类型等用工类 HR 字段。
/// 字段有填才校验,未填保留原值;银行卡号空表示不修改已有密文。
///
/// 示例请求:
/// ```json
/// {
/// "gender": 2,
/// "nation": "汉族",
/// "education": "本科",
/// "idCardNo": "510101199001011234",
/// "currentAddress": "四川省成都市武侯区XX路XX号",
/// "urgentContacts": "张三",
/// "urgentTelePhone": "13800138001",
/// "bankName": "中国银行",
/// "bankAccountName": "李四",
/// "bankCardNo": "6222021234567890123"
/// }
/// ```
///
/// 参数说明:
/// - gender: 性别(1=男,2=女;填写身份证号时以身份证解析为准)
/// - idCardNo: 身份证号明文(与 certificatesNumber 等价)
/// - bankCardNo: 银行卡明文,空则不修改已有卡号
///
/// 自助保存参数(不含 userId 及用工 HR 字段)
/// 保存后的本人档案
/// 保存成功
/// 开关关闭、参数校验失败或未登录
/// 服务器错误
[HttpPost("SaveMine")]
public async Task SaveMineAsync([FromBody] LqEmployeeProfileSelfSaveInput input)
{
if (!await EmployeeProfileSelfEditConfigHelper.GetAllowSelfEditAsync(_db))
{
throw NCCException.Oh("当前不允许员工自行修改个人档案");
}
var userId = _userManager.UserId;
if (string.IsNullOrWhiteSpace(userId))
{
throw NCCException.Oh("未登录或登录已失效");
}
if (input == null)
{
throw NCCException.Oh("参数不能为空");
}
var user = await _db.Queryable()
.Where(x => x.Id == userId && x.DeleteMark == null)
.FirstAsync();
if (user == null)
{
throw NCCException.Oh("用户不存在");
}
var existing = await _db.Queryable()
.Where(x => x.UserId == userId)
.FirstAsync();
ValidateSelfSaveInput(input, user, existing);
var beforeUser = UserProfileAuditAppenderService.CloneUser(user);
var beforeProfileSnapshot = existing == null ? null : BuildProfileSnapshot(existing);
var operatorId = userId;
var now = DateTime.Now;
ApplySelfSaveToUser(user, input);
user.LastModifyUserId = operatorId;
user.LastModifyTime = now;
await _db.Updateable(user).UpdateColumns(it => new
{
it.Gender,
it.Nation,
it.NativePlace,
it.Education,
it.CertificatesType,
it.CertificatesNumber,
it.CertificatesValidStart,
it.CertificatesValidEnd,
it.CertificatesValidLongTerm,
it.Birthday,
it.UrgentContacts,
it.UrgentTelePhone,
it.PostalAddress,
it.LastModifyUserId,
it.LastModifyTime
}).ExecuteCommandAsync();
LqEmployeeProfileEntity entity;
if (existing == null)
{
entity = new LqEmployeeProfileEntity
{
Id = YitIdHelper.NextId().ToString(),
UserId = userId,
CreateTime = now,
CreateUser = operatorId
};
ApplySelfInput(entity, input, null);
entity.UpdateTime = now;
entity.UpdateUser = operatorId;
await _db.Insertable(entity).ExecuteCommandAsync();
}
else
{
entity = existing;
ApplySelfInput(entity, input, existing.BankCardCipher);
entity.UpdateTime = now;
entity.UpdateUser = operatorId;
await _db.Updateable(entity).ExecuteCommandAsync();
}
var afterUser = UserProfileAuditAppenderService.CloneUser(
await _db.Queryable().Where(x => x.Id == userId).FirstAsync());
await _userProfileAuditAppender.AppendProfileDiffAsync(
beforeUser, afterUser, "SELF_EMPLOYEE_PROFILE_UPDATE", "APP");
await _userProfileVersionAppender.AfterUserProfilePersistedAsync(userId, "SELF_EMPLOYEE_PROFILE_UPDATE");
var afterProfileSnapshot = BuildProfileSnapshot(entity);
var detailJson = JsonConvert.SerializeObject(new
{
beforeUser = BuildSelfUserSnapshot(beforeUser),
afterUser = BuildSelfUserSnapshot(afterUser),
beforeProfile = beforeProfileSnapshot,
afterProfile = afterProfileSnapshot
});
await _businessOperationLogService.WriteAsync(
BizLogModule,
"员工自助修改档案",
BizTypeProfile,
entity.Id,
$"员工自助修改档案 userId={userId}",
detailJson);
return await MapMineOutputAsync(entity, afterUser, true);
}
private async Task EnsureCanEditUserAsync(UserEntity user)
{
var userInfo = await _userManager.GetUserInfo();
if (!userInfo.isAdministrator
&& !(userInfo.dataScope?.Any(x => x.organizeId == user.OrganizeId && x.Edit) ?? false))
{
throw NCCException.Oh(ErrorCode.D1013);
}
}
///
/// 员工信息 App 只读浏览:登录即可查看(敏感字段已脱敏)
///
private async Task EnsureAuthenticatedAsync()
{
_ = await _userManager.GetUserInfo();
}
///
/// 判定管理后台保存请求是否为实质空白档案(与前端空表单对齐:关键字段均未填,可空枚举未选择)。
/// 已有银行卡密文不在 input 中,不计为已填。
///
private static bool IsSubstantiallyEmpty(LqEmployeeProfileSaveInput input)
{
if (input == null)
{
return true;
}
if (!string.IsNullOrWhiteSpace(input.currentAddress)
|| !string.IsNullOrWhiteSpace(input.idCardAddress)
|| !string.IsNullOrWhiteSpace(input.idCardFrontUrl)
|| !string.IsNullOrWhiteSpace(input.idCardBackUrl)
|| !string.IsNullOrWhiteSpace(input.bankName)
|| !string.IsNullOrWhiteSpace(input.bankAccountName)
|| !string.IsNullOrWhiteSpace(input.bankCardNo))
{
return false;
}
if (!string.IsNullOrWhiteSpace(input.employeeNo)
|| !string.IsNullOrWhiteSpace(input.graduateSchool)
|| !string.IsNullOrWhiteSpace(input.major)
|| !string.IsNullOrWhiteSpace(input.previousCompany)
|| !string.IsNullOrWhiteSpace(input.previousPosition)
|| !string.IsNullOrWhiteSpace(input.emergencyContactRelation)
|| !string.IsNullOrWhiteSpace(input.emergencyContactAddress))
{
return false;
}
if (input.regularizationDate.HasValue
|| input.enrollmentDate.HasValue
|| input.graduationDate.HasValue
|| input.previousStartDate.HasValue
|| input.previousEndDate.HasValue)
{
return false;
}
if (input.maritalStatus.HasValue
|| input.politicalStatus.HasValue
|| input.householdType.HasValue
|| input.employeeType.HasValue
|| input.employeeStatus.HasValue
|| input.probationMonths.HasValue
|| input.recruitmentType.HasValue)
{
return false;
}
return true;
}
private static void ValidateSaveInput(LqEmployeeProfileSaveInput input)
{
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.maritalStatus))
{
throw NCCException.Oh("婚姻状况枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.politicalStatus))
{
throw NCCException.Oh("政治面貌枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.householdType))
{
throw NCCException.Oh("户口类型枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.employeeType))
{
throw NCCException.Oh("员工类型枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.employeeStatus))
{
throw NCCException.Oh("员工状态枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.probationMonths))
{
throw NCCException.Oh("试用期月数枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.recruitmentType))
{
throw NCCException.Oh("招聘类型枚举无效");
}
if (!string.IsNullOrWhiteSpace(input.idCardAddress)
&& !EmployeeProfileSensitiveHelper.IsValidFullAddress(input.idCardAddress))
{
throw NCCException.Oh("身份证地址须填写完整地址(含区/县/街道/门牌等详细信息)");
}
if (!string.IsNullOrWhiteSpace(input.idCardFrontUrl)
&& !EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardFrontUrl))
{
throw NCCException.Oh("身份证正面照片须为有效 URL");
}
if (!string.IsNullOrWhiteSpace(input.idCardBackUrl)
&& !EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardBackUrl))
{
throw NCCException.Oh("身份证反面照片须为有效 URL");
}
if (!string.IsNullOrWhiteSpace(input.bankCardNo)
&& !EmployeeProfileSensitiveHelper.IsValidBankCard(input.bankCardNo))
{
throw NCCException.Oh("银行卡号格式不正确");
}
if (input.enrollmentDate.HasValue && input.graduationDate.HasValue
&& input.graduationDate.Value.Date < input.enrollmentDate.Value.Date)
{
throw NCCException.Oh("毕业时间不能早于入学时间");
}
if (input.previousStartDate.HasValue && input.previousEndDate.HasValue
&& input.previousEndDate.Value.Date < input.previousStartDate.Value.Date)
{
throw NCCException.Oh("前公司结束时间不能早于开始时间");
}
}
private static void ApplyInput(LqEmployeeProfileEntity entity, LqEmployeeProfileSaveInput input, string existingBankCipher)
{
entity.MaritalStatus = input.maritalStatus;
entity.PoliticalStatus = input.politicalStatus;
entity.HouseholdType = input.householdType;
entity.CurrentAddress = input.currentAddress?.Trim();
entity.EmployeeNo = string.IsNullOrWhiteSpace(input.employeeNo) ? null : input.employeeNo.Trim();
entity.EmployeeType = input.employeeType;
entity.EmployeeStatus = input.employeeStatus;
entity.ProbationMonths = input.probationMonths;
entity.RegularizationDate = input.regularizationDate?.Date;
entity.RecruitmentType = input.recruitmentType;
entity.BankName = input.bankName?.Trim();
entity.BankAccountName = input.bankAccountName?.Trim();
entity.IdCardAddress = input.idCardAddress?.Trim();
entity.IdCardFrontUrl = input.idCardFrontUrl?.Trim();
entity.IdCardBackUrl = input.idCardBackUrl?.Trim();
if (!string.IsNullOrWhiteSpace(input.bankCardNo))
{
entity.BankCardCipher = EmployeeProfileSensitiveHelper.EncryptSensitive(
EmployeeProfileSensitiveHelper.NormalizeBankCard(input.bankCardNo));
}
else if (string.IsNullOrWhiteSpace(entity.BankCardCipher))
{
entity.BankCardCipher = existingBankCipher;
}
entity.GraduateSchool = input.graduateSchool?.Trim();
entity.EnrollmentDate = input.enrollmentDate?.Date;
entity.GraduationDate = input.graduationDate?.Date;
entity.Major = input.major?.Trim();
entity.PreviousCompany = input.previousCompany?.Trim();
entity.PreviousPosition = input.previousPosition?.Trim();
entity.PreviousStartDate = input.previousStartDate?.Date;
entity.PreviousEndDate = input.previousEndDate?.Date;
entity.EmergencyContactRelation = input.emergencyContactRelation?.Trim();
entity.EmergencyContactAddress = input.emergencyContactAddress?.Trim();
}
private static object BuildProfileSnapshot(LqEmployeeProfileEntity entity)
{
if (entity == null)
{
return null;
}
var bankPlain = EmployeeProfileSensitiveHelper.DecryptSensitive(entity.BankCardCipher);
return new
{
entity.Id,
entity.UserId,
entity.MaritalStatus,
entity.EmployeeNo,
entity.EmployeeType,
entity.EmployeeStatus,
entity.BankName,
entity.BankAccountName,
bankCardNoMasked = EmployeeProfileSensitiveHelper.MaskBankCard(bankPlain),
entity.IdCardAddress,
entity.GraduateSchool,
entity.Major
};
}
private static LqEmployeeProfileInfoOutput MapOutput(LqEmployeeProfileEntity profile, UserEntity user)
{
return MapOutputCore(profile, user);
}
private async Task MapOutputAsync(LqEmployeeProfileEntity profile, UserEntity user)
{
var output = MapOutputCore(profile, user);
output.idCardNo = user.CertificatesNumber;
output.idCardNoMasked = user.CertificatesNumber;
await EnrichUserDisplayFieldsAsync(output, user);
return output;
}
private static LqEmployeeProfileInfoOutput MapOutputCore(LqEmployeeProfileEntity profile, UserEntity user)
{
var bankPlain = profile == null
? null
: EmployeeProfileSensitiveHelper.DecryptSensitive(profile.BankCardCipher);
var output = new LqEmployeeProfileInfoOutput
{
id = profile?.Id,
userId = user.Id,
entryDate = user.EntryDate,
age = EmployeeProfileSensitiveHelper.CalcAgeFromIdCard(user.CertificatesNumber, user.Birthday),
tenureText = EmployeeProfileSensitiveHelper.CalcTenureText(user.EntryDate),
idCardNoMasked = EmployeeProfileSensitiveHelper.MaskIdCard(user.CertificatesNumber),
bankCardNoMasked = EmployeeProfileSensitiveHelper.MaskBankCard(bankPlain),
createTime = profile?.CreateTime,
updateTime = profile?.UpdateTime
};
if (profile == null)
{
return output;
}
output.maritalStatus = profile.MaritalStatus;
output.maritalStatusName = profile.MaritalStatus.HasValue
? EnumHelper.GetEnumDesc(profile.MaritalStatus.Value) : null;
output.politicalStatus = profile.PoliticalStatus;
output.politicalStatusName = profile.PoliticalStatus.HasValue
? EnumHelper.GetEnumDesc(profile.PoliticalStatus.Value) : null;
output.householdType = profile.HouseholdType;
output.householdTypeName = profile.HouseholdType.HasValue
? EnumHelper.GetEnumDesc(profile.HouseholdType.Value) : null;
output.currentAddress = profile.CurrentAddress;
output.employeeNo = profile.EmployeeNo;
output.employeeType = profile.EmployeeType;
output.employeeTypeName = profile.EmployeeType.HasValue
? EnumHelper.GetEnumDesc(profile.EmployeeType.Value) : null;
output.employeeStatus = profile.EmployeeStatus;
output.employeeStatusName = profile.EmployeeStatus.HasValue
? EnumHelper.GetEnumDesc(profile.EmployeeStatus.Value) : null;
output.probationMonths = profile.ProbationMonths;
output.regularizationDate = profile.RegularizationDate;
output.recruitmentType = profile.RecruitmentType;
output.recruitmentTypeName = profile.RecruitmentType.HasValue
? EnumHelper.GetEnumDesc(profile.RecruitmentType.Value) : null;
output.bankName = profile.BankName;
output.bankAccountName = profile.BankAccountName;
output.idCardAddress = profile.IdCardAddress;
output.idCardFrontUrl = profile.IdCardFrontUrl;
output.idCardBackUrl = profile.IdCardBackUrl;
output.graduateSchool = profile.GraduateSchool;
output.enrollmentDate = profile.EnrollmentDate;
output.graduationDate = profile.GraduationDate;
output.major = profile.Major;
output.previousCompany = profile.PreviousCompany;
output.previousPosition = profile.PreviousPosition;
output.previousStartDate = profile.PreviousStartDate;
output.previousEndDate = profile.PreviousEndDate;
output.emergencyContactRelation = profile.EmergencyContactRelation;
output.emergencyContactAddress = profile.EmergencyContactAddress;
return output;
}
private async Task EnrichUserDisplayFieldsAsync(LqEmployeeProfileInfoOutput output, UserEntity user)
{
if (output == null || user == null)
{
return;
}
var dictIds = new[] { user.Nation, user.Education }
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct()
.ToList();
var dictionaryNameDict = dictIds.Count == 0
? new Dictionary()
: (await _db.Queryable()
.Where(d => dictIds.Contains(d.Id))
.Select(d => new { d.Id, d.FullName })
.ToListAsync())
.GroupBy(x => x.Id)
.ToDictionary(g => g.Key, g => g.First().FullName ?? string.Empty);
output.nation = ResolveDictionaryDisplayName(user.Nation, dictionaryNameDict);
output.nativePlace = user.NativePlace;
output.education = ResolveDictionaryDisplayName(user.Education, dictionaryNameDict);
output.urgentContacts = user.UrgentContacts;
output.urgentTelePhone = user.UrgentTelePhone;
output.postalAddress = user.PostalAddress;
if (!string.IsNullOrWhiteSpace(user.ManagerId))
{
output.managerName = await _db.Queryable()
.Where(u => u.Id == user.ManagerId && u.DeleteMark == null)
.Select(u => u.RealName)
.FirstAsync();
}
}
private static string ResolveDictionaryDisplayName(string value, Dictionary dictionaryNameDict)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var key = value.Trim();
if (dictionaryNameDict.TryGetValue(key, out var name) && !string.IsNullOrWhiteSpace(name))
{
return name;
}
return key;
}
private async Task MapMineOutputAsync(
LqEmployeeProfileEntity profile,
UserEntity user,
bool allowSelfEdit)
{
var baseOutput = MapOutput(profile, user);
var bankPlain = profile == null
? null
: EmployeeProfileSensitiveHelper.DecryptSensitive(profile.BankCardCipher);
var idCardPlain = user.CertificatesNumber;
var organizeName = await ResolveOrganizeNameAsync(user.OrganizeId);
var positionName = await ResolvePositionNamesAsync(user.PositionId);
return new LqEmployeeProfileMineOutput
{
allowSelfEdit = allowSelfEdit,
realName = user.RealName,
account = user.Account,
organizeName = organizeName,
positionName = positionName,
entryDate = baseOutput.entryDate,
employeeNo = baseOutput.employeeNo,
employeeType = baseOutput.employeeType,
employeeTypeName = baseOutput.employeeTypeName,
employeeStatus = baseOutput.employeeStatus,
employeeStatusName = baseOutput.employeeStatusName,
probationMonths = baseOutput.probationMonths,
recruitmentType = baseOutput.recruitmentType,
recruitmentTypeName = baseOutput.recruitmentTypeName,
regularizationDate = baseOutput.regularizationDate,
tenureText = baseOutput.tenureText,
age = baseOutput.age,
gender = user.Gender,
nation = user.Nation,
nativePlace = user.NativePlace,
education = user.Education,
birthday = user.Birthday,
certificatesType = user.CertificatesType,
certificatesNumber = idCardPlain,
idCardNo = idCardPlain,
certificatesValidStart = user.CertificatesValidStart,
certificatesValidEnd = user.CertificatesValidEnd,
certificatesValidLongTerm = user.CertificatesValidLongTerm,
idCardNoMasked = baseOutput.idCardNoMasked,
telePhone = user.TelePhone,
mobilePhone = user.MobilePhone,
urgentContacts = user.UrgentContacts,
urgentTelePhone = user.UrgentTelePhone,
postalAddress = user.PostalAddress,
maritalStatus = baseOutput.maritalStatus,
maritalStatusName = baseOutput.maritalStatusName,
politicalStatus = baseOutput.politicalStatus,
politicalStatusName = baseOutput.politicalStatusName,
householdType = baseOutput.householdType,
householdTypeName = baseOutput.householdTypeName,
currentAddress = baseOutput.currentAddress,
idCardAddress = baseOutput.idCardAddress,
idCardFrontUrl = baseOutput.idCardFrontUrl,
idCardBackUrl = baseOutput.idCardBackUrl,
graduateSchool = baseOutput.graduateSchool,
enrollmentDate = baseOutput.enrollmentDate,
graduationDate = baseOutput.graduationDate,
major = baseOutput.major,
previousCompany = baseOutput.previousCompany,
previousPosition = baseOutput.previousPosition,
previousStartDate = baseOutput.previousStartDate,
previousEndDate = baseOutput.previousEndDate,
emergencyContactRelation = baseOutput.emergencyContactRelation,
emergencyContactAddress = baseOutput.emergencyContactAddress,
bankName = baseOutput.bankName,
bankAccountName = baseOutput.bankAccountName,
bankCardNo = bankPlain,
bankCardNoMasked = baseOutput.bankCardNoMasked,
educationOptions = EmployeeProfileSensitiveHelper.EducationLevels.ToList(),
maritalStatusOptions = BuildEnumOptions(),
politicalStatusOptions = BuildEnumOptions(),
householdTypeOptions = BuildEnumOptions()
};
}
private async Task ResolveOrganizeNameAsync(string organizeId)
{
if (string.IsNullOrWhiteSpace(organizeId))
{
return null;
}
return await _db.Queryable()
.Where(x => x.Id == organizeId && x.DeleteMark == null)
.Select(x => x.FullName)
.FirstAsync();
}
private async Task ResolvePositionNamesAsync(string positionId)
{
if (string.IsNullOrWhiteSpace(positionId))
{
return null;
}
var ids = positionId.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
if (ids.Count == 0)
{
return null;
}
var names = await _db.Queryable()
.Where(x => ids.Contains(x.Id) && x.DeleteMark == null)
.Select(x => x.FullName)
.ToListAsync();
return names.Count == 0 ? null : string.Join("、", names);
}
private static List BuildEnumOptions() where T : struct, Enum
{
return Enum.GetValues(typeof(T))
.Cast()
.Select(e => new EmployeeProfileEnumOption
{
value = Convert.ToInt32(e),
label = EnumHelper.GetEnumDesc(e)
})
.ToList();
}
private static void ValidateSelfSaveInput(
LqEmployeeProfileSelfSaveInput input,
UserEntity user,
LqEmployeeProfileEntity existing)
{
var idCardRaw = !string.IsNullOrWhiteSpace(input.idCardNo)
? input.idCardNo
: input.certificatesNumber;
var idCard = EmployeeProfileSensitiveHelper.NormalizeIdCard(idCardRaw);
if (!string.IsNullOrEmpty(idCard))
{
if (!idCard.IsIdentityCardId())
{
throw NCCException.Oh("身份证号不合法");
}
var idCardGender = EmployeeProfileSensitiveHelper.ParseGenderFromIdCard(idCard);
if (idCardGender.HasValue && input.gender.HasValue && idCardGender.Value != input.gender.Value)
{
throw NCCException.Oh("性别与身份证号不一致");
}
if (input.birthday.HasValue)
{
var idBirth = EmployeeProfileSensitiveHelper.ParseBirthdayFromIdCard(idCard);
if (idBirth.HasValue && idBirth.Value.Date != input.birthday.Value.Date)
{
throw NCCException.Oh("出生日期与身份证号不一致");
}
}
}
else if (input.gender.HasValue && input.gender.Value != 1 && input.gender.Value != 2)
{
throw NCCException.Oh("性别只能为男或女");
}
if (!string.IsNullOrWhiteSpace(input.education)
&& !EmployeeProfileSensitiveHelper.IsValidEducation(input.education))
{
throw NCCException.Oh("文化程度取值无效,请选择:博士、硕士、本科、大专、中专、技校、高中、初中、小学");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.maritalStatus))
{
throw NCCException.Oh("婚姻状况枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.politicalStatus))
{
throw NCCException.Oh("政治面貌枚举无效");
}
if (!EmployeeProfileSensitiveHelper.IsEnumDefined(input.householdType))
{
throw NCCException.Oh("户口类型枚举无效");
}
if (!string.IsNullOrWhiteSpace(input.urgentTelePhone))
{
if (!EmployeeProfileSensitiveHelper.IsValidMobile(input.urgentTelePhone))
{
throw NCCException.Oh("紧急联系人电话格式不正确");
}
if (EmployeeProfileSensitiveHelper.IsSamePhoneAfterNormalize(user.MobilePhone, input.urgentTelePhone))
{
throw NCCException.Oh("紧急联系人电话不能与员工手机号相同");
}
}
if (!string.IsNullOrWhiteSpace(input.idCardAddress)
&& !EmployeeProfileSensitiveHelper.IsValidFullAddress(input.idCardAddress))
{
throw NCCException.Oh("身份证地址须填写完整地址(含区/县/街道/门牌等详细信息)");
}
if (!string.IsNullOrWhiteSpace(input.idCardFrontUrl)
&& !EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardFrontUrl))
{
throw NCCException.Oh("身份证正面照片须为有效 URL");
}
if (!string.IsNullOrWhiteSpace(input.idCardBackUrl)
&& !EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardBackUrl))
{
throw NCCException.Oh("身份证反面照片须为有效 URL");
}
if (!string.IsNullOrWhiteSpace(input.bankCardNo)
&& !EmployeeProfileSensitiveHelper.IsValidBankCard(input.bankCardNo))
{
throw NCCException.Oh("银行卡号格式不正确");
}
var enrollmentDate = input.enrollmentDate ?? existing?.EnrollmentDate;
var graduationDate = input.graduationDate ?? existing?.GraduationDate;
if (enrollmentDate.HasValue && graduationDate.HasValue
&& graduationDate.Value.Date < enrollmentDate.Value.Date)
{
throw NCCException.Oh("毕业时间不能早于入学时间");
}
var previousStartDate = input.previousStartDate ?? existing?.PreviousStartDate;
var previousEndDate = input.previousEndDate ?? existing?.PreviousEndDate;
if (previousStartDate.HasValue && previousEndDate.HasValue
&& previousEndDate.Value.Date < previousStartDate.Value.Date)
{
throw NCCException.Oh("前公司结束时间不能早于开始时间");
}
if (input.certificatesValidLongTerm != 1
&& input.certificatesValidStart.HasValue && input.certificatesValidEnd.HasValue
&& input.certificatesValidEnd.Value.Date < input.certificatesValidStart.Value.Date)
{
throw NCCException.Oh("身份证有效期截止日期不能早于起始日期");
}
}
private static void ApplySelfSaveToUser(UserEntity user, LqEmployeeProfileSelfSaveInput input)
{
if (!string.IsNullOrWhiteSpace(input.nation))
{
user.Nation = input.nation.Trim();
}
if (!string.IsNullOrWhiteSpace(input.nativePlace))
{
user.NativePlace = input.nativePlace.Trim();
}
if (!string.IsNullOrWhiteSpace(input.education))
{
user.Education = input.education.Trim();
}
var idCardRaw = !string.IsNullOrWhiteSpace(input.idCardNo)
? input.idCardNo
: input.certificatesNumber;
var idCard = EmployeeProfileSensitiveHelper.NormalizeIdCard(idCardRaw);
if (!string.IsNullOrEmpty(idCard))
{
user.CertificatesNumber = idCard;
user.CertificatesType = EmployeeProfileSensitiveHelper.IdCardCertificateTypeId;
var idBirth = EmployeeProfileSensitiveHelper.ParseBirthdayFromIdCard(idCard);
if (idBirth.HasValue)
{
user.Birthday = idBirth;
}
var idGender = EmployeeProfileSensitiveHelper.ParseGenderFromIdCard(idCard);
if (idGender.HasValue)
{
user.Gender = idGender;
}
}
else
{
if (input.birthday.HasValue)
{
user.Birthday = input.birthday.Value.Date;
}
if (input.gender.HasValue)
{
user.Gender = input.gender;
}
if (!string.IsNullOrWhiteSpace(input.certificatesType))
{
user.CertificatesType = input.certificatesType.Trim();
}
}
if (!string.IsNullOrWhiteSpace(input.urgentContacts))
{
user.UrgentContacts = input.urgentContacts.Trim();
}
if (!string.IsNullOrWhiteSpace(input.urgentTelePhone))
{
user.UrgentTelePhone = EmployeeProfileSensitiveHelper.NormalizeMobile(input.urgentTelePhone);
}
if (!string.IsNullOrWhiteSpace(input.postalAddress))
{
user.PostalAddress = input.postalAddress.Trim();
}
else if (!string.IsNullOrWhiteSpace(input.currentAddress))
{
user.PostalAddress = input.currentAddress.Trim();
}
ApplyCertificatesValidity(user, input.certificatesValidStart, input.certificatesValidEnd, input.certificatesValidLongTerm);
}
private static void ApplyCertificatesValidity(
UserEntity user,
DateTime? start,
DateTime? end,
int? longTerm)
{
var isLongTerm = longTerm == 1;
user.CertificatesValidLongTerm = isLongTerm ? 1 : 0;
user.CertificatesValidStart = start.HasValue ? start.Value.Date : (DateTime?)null;
if (isLongTerm)
{
user.CertificatesValidEnd = null;
return;
}
user.CertificatesValidEnd = end.HasValue ? end.Value.Date : (DateTime?)null;
if (user.CertificatesValidStart.HasValue && user.CertificatesValidEnd.HasValue
&& user.CertificatesValidEnd.Value < user.CertificatesValidStart.Value)
{
throw NCCException.Oh("身份证有效期截止日期不能早于起始日期");
}
}
private static void ApplySelfInput(
LqEmployeeProfileEntity entity,
LqEmployeeProfileSelfSaveInput input,
string existingBankCipher)
{
if (input.maritalStatus.HasValue)
{
entity.MaritalStatus = input.maritalStatus;
}
if (input.politicalStatus.HasValue)
{
entity.PoliticalStatus = input.politicalStatus;
}
if (input.householdType.HasValue)
{
entity.HouseholdType = input.householdType;
}
if (!string.IsNullOrWhiteSpace(input.currentAddress))
{
entity.CurrentAddress = input.currentAddress.Trim();
}
if (!string.IsNullOrWhiteSpace(input.idCardAddress))
{
entity.IdCardAddress = input.idCardAddress.Trim();
}
if (!string.IsNullOrWhiteSpace(input.idCardFrontUrl))
{
entity.IdCardFrontUrl = input.idCardFrontUrl.Trim();
}
if (!string.IsNullOrWhiteSpace(input.idCardBackUrl))
{
entity.IdCardBackUrl = input.idCardBackUrl.Trim();
}
if (!string.IsNullOrWhiteSpace(input.bankName))
{
entity.BankName = input.bankName.Trim();
}
if (!string.IsNullOrWhiteSpace(input.bankAccountName))
{
entity.BankAccountName = input.bankAccountName.Trim();
}
if (!string.IsNullOrWhiteSpace(input.bankCardNo))
{
entity.BankCardCipher = EmployeeProfileSensitiveHelper.EncryptSensitive(
EmployeeProfileSensitiveHelper.NormalizeBankCard(input.bankCardNo));
}
else if (string.IsNullOrWhiteSpace(entity.BankCardCipher))
{
entity.BankCardCipher = existingBankCipher;
}
if (!string.IsNullOrWhiteSpace(input.graduateSchool))
{
entity.GraduateSchool = input.graduateSchool.Trim();
}
if (input.enrollmentDate.HasValue)
{
entity.EnrollmentDate = input.enrollmentDate.Value.Date;
}
if (input.graduationDate.HasValue)
{
entity.GraduationDate = input.graduationDate.Value.Date;
}
if (!string.IsNullOrWhiteSpace(input.major))
{
entity.Major = input.major.Trim();
}
if (!string.IsNullOrWhiteSpace(input.previousCompany))
{
entity.PreviousCompany = input.previousCompany.Trim();
}
if (!string.IsNullOrWhiteSpace(input.previousPosition))
{
entity.PreviousPosition = input.previousPosition.Trim();
}
if (input.previousStartDate.HasValue)
{
entity.PreviousStartDate = input.previousStartDate.Value.Date;
}
if (input.previousEndDate.HasValue)
{
entity.PreviousEndDate = input.previousEndDate.Value.Date;
}
if (!string.IsNullOrWhiteSpace(input.emergencyContactRelation))
{
entity.EmergencyContactRelation = input.emergencyContactRelation.Trim();
}
if (!string.IsNullOrWhiteSpace(input.emergencyContactAddress))
{
entity.EmergencyContactAddress = input.emergencyContactAddress.Trim();
}
}
private static object BuildSelfUserSnapshot(UserEntity user)
{
if (user == null)
{
return null;
}
return new
{
user.Id,
user.RealName,
user.Gender,
user.Nation,
user.NativePlace,
user.Education,
idCardNoMasked = EmployeeProfileSensitiveHelper.MaskIdCard(user.CertificatesNumber),
mobilePhoneMasked = EmployeeProfileSensitiveHelper.MaskPhone(user.MobilePhone),
user.UrgentContacts,
urgentTelePhoneMasked = EmployeeProfileSensitiveHelper.MaskPhone(user.UrgentTelePhone),
user.PostalAddress
};
}
}
}