LqEmployeeProfileService.cs 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
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 不能为空");
            }

            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();

            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<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, string existingBankCipher = null)
        {
            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.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<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.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;
        }
    }
}