LqEmployeeProfileService.cs 15.7 KB
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
{
    /// <summary>
    /// 员工档案扩展(与用户管理表单联动;主档仍在 BASE_USER)
    /// </summary>
    [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;

        /// <summary>
        /// 初始化员工档案服务
        /// </summary>
        public LqEmployeeProfileService(
            ISqlSugarClient db,
            IUserManager userManager,
            IBusinessOperationLogService businessOperationLogService)
        {
            _db = db;
            _userManager = userManager;
            _businessOperationLogService = businessOperationLogService;
        }

        /// <summary>
        /// 按用户 ID 获取员工档案扩展详情(含年龄、司龄;银行卡脱敏)
        /// </summary>
        /// <remarks>
        /// 供用户管理表单加载档案扩展区;年龄优先按 BASE_USER 身份证号推算,司龄按 F_ENTRYDATE 推算。
        ///
        /// 参数说明:
        /// - userId: BASE_USER.F_Id
        /// </remarks>
        /// <param name="userId">用户 ID</param>
        /// <returns>档案详情;无档案时仅返回 userId 与计算字段</returns>
        /// <response code="200">成功</response>
        /// <response code="400">userId 为空或用户不存在</response>
        /// <response code="500">服务器错误</response>
        [HttpGet("GetByUserId")]
        public async Task<LqEmployeeProfileInfoOutput> GetByUserIdAsync([FromQuery] string userId)
        {
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw NCCException.Oh("userId 不能为空");
            }

            var user = await _db.Queryable<UserEntity>()
                .Where(x => x.Id == userId && x.DeleteMark == null)
                .FirstAsync();
            if (user == null)
            {
                throw NCCException.Oh("用户不存在");
            }
            await EnsureCanEditUserAsync(user);

            var profile = await _db.Queryable<LqEmployeeProfileEntity>()
                .Where(x => x.UserId == userId)
                .FirstAsync();

            return MapOutput(profile, user);
        }

        /// <summary>
        /// 保存或更新员工档案扩展(管理后台)
        /// </summary>
        /// <remarks>
        /// 银行卡明文仅用于传输,落库为 AES 密文;空 bankCardNo 表示不修改已有卡号。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "userId": "1234567890",
        ///   "maritalStatus": 1,
        ///   "employeeType": 1,
        ///   "employeeStatus": 2,
        ///   "bankName": "中国银行",
        ///   "bankCardNo": "6222021234567890123"
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">保存参数</param>
        /// <returns>保存后的档案详情</returns>
        /// <response code="200">保存成功</response>
        /// <response code="400">参数校验失败</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("Save")]
        public async Task<LqEmployeeProfileInfoOutput> SaveAsync([FromBody] LqEmployeeProfileSaveInput input)
        {
            if (input == null || string.IsNullOrWhiteSpace(input.userId))
            {
                throw NCCException.Oh("userId 不能为空");
            }

            ValidateSaveInput(input);

            var user = await _db.Queryable<UserEntity>()
                .Where(x => x.Id == input.userId && x.DeleteMark == null)
                .FirstAsync();
            if (user == null)
            {
                throw NCCException.Oh("用户不存在");
            }
            await EnsureCanEditUserAsync(user);

            var existing = await _db.Queryable<LqEmployeeProfileEntity>()
                .Where(x => x.UserId == input.userId)
                .FirstAsync();

            if (!string.IsNullOrWhiteSpace(input.employeeNo))
            {
                var dup = await _db.Queryable<LqEmployeeProfileEntity>()
                    .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)
        {
            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeMaritalStatusEnum>(input.maritalStatus))
            {
                throw NCCException.Oh("婚姻状况枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeePoliticalStatusEnum>(input.politicalStatus))
            {
                throw NCCException.Oh("政治面貌枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeHouseholdTypeEnum>(input.householdType))
            {
                throw NCCException.Oh("户口类型枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeTypeEnum>(input.employeeType))
            {
                throw NCCException.Oh("员工类型枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeProfileStatusEnum>(input.employeeStatus))
            {
                throw NCCException.Oh("员工状态枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeProbationMonthsEnum>(input.probationMonths))
            {
                throw NCCException.Oh("试用期月数枚举无效");
            }

            if (!EmployeeProfileSensitiveHelper.IsEnumDefined<EmployeeRecruitmentTypeEnum>(input.recruitmentType))
            {
                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();
            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,
                bankCardNoMasked = EmployeeProfileSensitiveHelper.MaskBankCard(bankPlain),
                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<EmployeeMaritalStatusEnum>(profile.MaritalStatus.Value) : null;
            output.politicalStatus = profile.PoliticalStatus;
            output.politicalStatusName = profile.PoliticalStatus.HasValue
                ? EnumHelper.GetEnumDesc<EmployeePoliticalStatusEnum>(profile.PoliticalStatus.Value) : null;
            output.householdType = profile.HouseholdType;
            output.householdTypeName = profile.HouseholdType.HasValue
                ? EnumHelper.GetEnumDesc<EmployeeHouseholdTypeEnum>(profile.HouseholdType.Value) : null;
            output.currentAddress = profile.CurrentAddress;
            output.employeeNo = profile.EmployeeNo;
            output.employeeType = profile.EmployeeType;
            output.employeeTypeName = profile.EmployeeType.HasValue
                ? EnumHelper.GetEnumDesc<EmployeeTypeEnum>(profile.EmployeeType.Value) : null;
            output.employeeStatus = profile.EmployeeStatus;
            output.employeeStatusName = profile.EmployeeStatus.HasValue
                ? EnumHelper.GetEnumDesc<EmployeeProfileStatusEnum>(profile.EmployeeStatus.Value) : null;
            output.probationMonths = profile.ProbationMonths;
            output.regularizationDate = profile.RegularizationDate;
            output.recruitmentType = profile.RecruitmentType;
            output.recruitmentTypeName = profile.RecruitmentType.HasValue
                ? EnumHelper.GetEnumDesc<EmployeeRecruitmentTypeEnum>(profile.RecruitmentType.Value) : null;
            output.bankName = profile.BankName;
            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;
        }
    }
}