using System;
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.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqEmployeeProfile;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_employee_profile;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
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;
///
/// 初始化员工档案服务
///
public LqEmployeeProfileService(
ISqlSugarClient db,
IUserManager userManager,
IBusinessOperationLogService businessOperationLogService)
{
_db = db;
_userManager = userManager;
_businessOperationLogService = businessOperationLogService;
}
///
/// 按用户 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 EnsureCanEditUserAsync(user);
var profile = await _db.Queryable()
.Where(x => x.UserId == userId)
.FirstAsync();
return MapOutput(profile, user);
}
///
/// 保存或更新员工档案扩展(管理后台)
///
///
/// 银行卡明文仅用于传输,落库为 AES 密文;空 bankCardNo 表示不修改已有卡号。
///
/// 示例请求:
/// ```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();
ValidateSaveInput(input, existing?.BankCardCipher);
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);
}
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);
}
}
private static void ValidateSaveInput(LqEmployeeProfileSaveInput input, string existingBankCipher = null)
{
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.currentAddress))
{
throw NCCException.Oh("现居住地址不能为空");
}
if (!EmployeeProfileSensitiveHelper.IsValidFullAddress(input.idCardAddress))
{
throw NCCException.Oh("身份证地址不能为空,且须填写完整地址(含区/县/街道/门牌等详细信息)");
}
if (!EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardFrontUrl))
{
throw NCCException.Oh("身份证正面照片不能为空且须为有效 URL");
}
if (!EmployeeProfileSensitiveHelper.IsValidHttpUrl(input.idCardBackUrl))
{
throw NCCException.Oh("身份证反面照片不能为空且须为有效 URL");
}
if (string.IsNullOrWhiteSpace(input.bankName))
{
throw NCCException.Oh("开户行不能为空");
}
if (string.IsNullOrWhiteSpace(input.bankAccountName))
{
throw NCCException.Oh("开户实名不能为空");
}
var hasBankCard = !string.IsNullOrWhiteSpace(input.bankCardNo)
|| !string.IsNullOrWhiteSpace(existingBankCipher);
if (!hasBankCard)
{
throw NCCException.Oh("银行卡号不能为空");
}
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)
{
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;
}
}
}