using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NCC; using NCC.Code; using NCC.Common.Const; using NCC.Common.Core.Manager; using NCC.Common.Enum; using NCC.Common.Filter; using NCC.Common.Util; using NCC.Common.Extension; using NCC.DataEncryption; using NCC.Dependency; using NCC.DynamicApiController; using NCC.Extend.Entitys.Dto.LqEmployeeProfileSubmission; using NCC.Extend.Entitys.Enum; using NCC.Extend.Entitys.lq_employee_profile; using NCC.Extend.Entitys.lq_employee_profile_submission; using NCC.Extend.Entitys.lq_mdxx; using NCC.Extend.Interfaces.BusinessOperationLog; using NCC.Extend.Interfaces.EmployeeStore; using NCC.Extend.Interfaces.UserProfileAudit; using NCC.Extend.Interfaces.UserProfileVersion; using NCC.FriendlyException; using NCC.System.Entitys.Permission; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SqlSugar; using Yitter.IdGenerator; namespace NCC.Extend { /// /// 员工档案扫码入职匿名提交与人事审核 /// [ApiDescriptionSettings(Tag = "员工档案-扫码入职", Name = "LqEmployeeProfileSubmission", Order = 211)] [Route("api/Extend/LqEmployeeProfileSubmission")] public class LqEmployeeProfileSubmissionService : IDynamicApiController, ITransient { private const string BizLogModule = "员工档案"; private const string BizTypeSubmission = "lq_employee_profile_submission"; private const string AuditSource = "EMPLOYEE_PROFILE_SUBMISSION"; private readonly ISqlSugarClient _db; private readonly IUserManager _userManager; private readonly IBusinessOperationLogService _businessOperationLogService; private readonly IUserProfileAuditAppender _userProfileAuditAppender; private readonly IUserProfileVersionAppender _userProfileVersionAppender; private readonly IEmployeeStoreAssignmentHook _employeeStoreAssignmentHook; /// /// 初始化扫码入职提交服务 /// public LqEmployeeProfileSubmissionService( ISqlSugarClient db, IUserManager userManager, IBusinessOperationLogService businessOperationLogService, IUserProfileAuditAppender userProfileAuditAppender, IUserProfileVersionAppender userProfileVersionAppender, IEmployeeStoreAssignmentHook employeeStoreAssignmentHook) { _db = db; _userManager = userManager; _businessOperationLogService = businessOperationLogService; _userProfileAuditAppender = userProfileAuditAppender; _userProfileVersionAppender = userProfileVersionAppender; _employeeStoreAssignmentHook = employeeStoreAssignmentHook; } #region 公开接口 /// /// 获取扫码入职公开表单配置 /// /// /// 匿名页面初始化时调用,返回表单枚举、必填项,以及当前有效的组织和门店下拉项。 /// 组织和门店仅返回ID与名称,不包含主管、电话、地址等内部或敏感字段。 /// /// 示例请求: /// ```json /// {} /// ``` /// /// 参数说明: /// - 无请求参数 /// /// 不含敏感信息的公开表单配置 /// 成功返回公开表单配置 /// 服务器查询配置失败 [AllowAnonymous] [HttpGet("GetPublicConfig")] public async Task GetPublicConfigAsync() { var organizeOptions = await _db.Queryable() .Where(x => x.DeleteMark == null && x.EnabledMark == 1) .OrderBy(x => x.SortCode) .OrderBy(x => x.FullName) .Select(x => new EmployeeProfilePublicOption { id = x.Id, name = x.FullName }) .ToListAsync(); var storeOptions = await _db.Queryable() .Where(x => x.Zxzt == "开店") .Where(x => x.Status == null || x.Status != -1) .OrderBy(x => x.Dm) .Select(x => new EmployeeProfilePublicOption { id = x.Id, name = x.Dm }) .ToListAsync(); return new LqEmployeeProfileSubmissionPublicConfigOutput { certificatesTypeName = "身份证", requiredFields = EmployeeProfileSensitiveHelper.PublicRequiredFields.ToList(), educationOptions = EmployeeProfileSensitiveHelper.EducationLevels.ToList(), maritalStatusOptions = BuildEnumOptions(), politicalStatusOptions = BuildEnumOptions(), householdTypeOptions = BuildEnumOptions(), employeeTypeOptions = BuildEnumOptions(), employeeStatusOptions = BuildEnumOptions(), probationMonthsOptions = BuildEnumOptions(), recruitmentTypeOptions = BuildEnumOptions(), organizeOptions = organizeOptions, storeOptions = storeOptions, submitHint = "提交后进入待审核,组织、岗位等信息由人事审核时填写;审核通过后才会创建/更新员工账号,请勿重复提交。" }; } /// /// 校验扫码入职表单(不落库) /// /// /// 匿名提交前调用,校验字段格式、枚举值,并确认组织和可选门店仍处于有效状态。 /// /// 示例请求: /// ```json /// { /// "realName": "张三", /// "organizeId": "组织ID", /// "mdid": "门店ID" /// } /// ``` /// /// 参数说明: /// - input: 扫码入职公开填报数据 /// /// 表单数据 /// 校验结果 /// 校验通过 /// 校验失败 /// 服务器错误 [AllowAnonymous] [HttpPost("ValidateSubmit")] public async Task ValidateSubmitAsync([FromBody] LqEmployeeProfileSubmissionCrInput input) { await ValidateSubmissionInputAsync(input, false); return new { valid = true, message = "校验通过" }; } /// /// 匿名提交扫码入职申请 /// /// /// 校验公开填报数据及组织、门店有效性后创建待审核申请,不会直接创建或更新员工账号。 /// /// 示例请求: /// ```json /// { /// "realName": "张三", /// "organizeId": "组织ID", /// "mdid": "门店ID" /// } /// ``` /// /// 参数说明: /// - input: 扫码入职公开填报数据 /// /// 表单数据 /// 申请编号 /// 提交成功 /// 校验失败或重复提交 /// 服务器错误 [AllowAnonymous] [HttpPost("Submit")] public async Task SubmitAsync([FromBody] LqEmployeeProfileSubmissionCrInput input) { await ValidateSubmissionInputAsync(input, true); var idCard = EmployeeProfileSensitiveHelper.NormalizeIdCard(input.idCardNo); var idCardHash = EmployeeProfileSensitiveHelper.ComputeIdCardHash(idCard); var mobile = EmployeeProfileSensitiveHelper.NormalizeMobile(input.mobilePhone); var (submitIp, userAgent) = EmployeeProfileSensitiveHelper.ResolveSubmitClient(); await EnsureNotDuplicateSubmitAsync(idCardHash, submitIp); var now = DateTime.Now; var entity = MapSubmissionEntity(input, idCard, idCardHash, mobile, submitIp, userAgent, now); entity.Id = YitIdHelper.NextId().ToString(); entity.SubmissionNo = EmployeeProfileSensitiveHelper.GenerateSubmissionNo(); entity.Status = (int)EmployeeProfileSubmissionStatusEnum.待审核; entity.SubmitSource = (int)EmployeeProfileSubmissionSourceEnum.扫码填报; entity.SubmitTime = now; entity.CreateTime = now; entity.UpdateTime = now; entity.FormSnapshotJson = BuildSanitizedSnapshotJson(input, idCard, idCardHash); var ok = await _db.Insertable(entity).ExecuteCommandAsync(); if (ok <= 0) { throw NCCException.Oh("提交失败,请稍后重试"); } return new LqEmployeeProfileSubmissionSubmitOutput { submissionNo = entity.SubmissionNo, message = "提交成功,请等待人事审核" }; } #endregion #region 人事端 /// /// 分页查询扫码入职申请 /// /// 查询条件 /// 分页列表 /// 成功 /// 服务器错误 [HttpGet("GetList")] public async Task GetListAsync([FromQuery] LqEmployeeProfileSubmissionListQueryInput input) { input ??= new LqEmployeeProfileSubmissionListQueryInput(); var kw = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim(); var endExclusive = input.submitTimeEnd?.Date.AddDays(1); var userInfo = await _userManager.GetUserInfo(); var allowedOrganizeIds = userInfo.isAdministrator ? new List() : (userInfo.dataScope ?? new List()) .Where(x => x.Edit) .Select(x => x.organizeId) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct() .ToList(); var data = await _db.Queryable() .WhereIF(!userInfo.isAdministrator, x => string.IsNullOrEmpty(x.OrganizeId) || allowedOrganizeIds.Contains(x.OrganizeId)) .WhereIF(input.status.HasValue, x => x.Status == input.status.Value) .WhereIF(input.submitTimeStart.HasValue, x => x.SubmitTime >= input.submitTimeStart.Value) .WhereIF(endExclusive.HasValue, x => x.SubmitTime < endExclusive.Value) .WhereIF(kw != null, x => x.RealName.Contains(kw) || x.MobilePhone.Contains(kw) || x.SubmissionNo.Contains(kw)) .OrderBy(x => x.SubmitTime, OrderByType.Desc) .Select(x => new LqEmployeeProfileSubmissionListOutput { id = x.Id, submissionNo = x.SubmissionNo, status = x.Status, realName = x.RealName, mobilePhoneMasked = x.MobilePhone, idCardNoMasked = x.IdCardCipher, entryDate = x.EntryDate, employeeNo = x.EmployeeNo, submitSource = x.SubmitSource, submitTime = x.SubmitTime, reviewUserName = x.ReviewUserName, reviewTime = x.ReviewTime, linkedUserId = x.LinkedUserId }) .ToPagedListAsync(input.currentPage, input.pageSize); foreach (var row in data.list) { row.statusName = EnumHelper.GetEnumDesc(row.status); row.submitSourceName = EnumHelper.GetEnumDesc(row.submitSource); row.mobilePhoneMasked = EmployeeProfileSensitiveHelper.MaskPhone(row.mobilePhoneMasked); var idPlain = EmployeeProfileSensitiveHelper.DecryptSensitive(row.idCardNoMasked); row.idCardNoMasked = EmployeeProfileSensitiveHelper.MaskIdCard(idPlain); } return PageResult.SqlSugarPageResult(data); } /// /// 获取扫码入职申请详情(敏感字段默认脱敏) /// /// /// 人事审核弹窗传 revealSensitive=true 返回手机号/身份证完整明文(需组织权限); /// showTail4=true 时仅展示后 4 位;二者都不传则常规脱敏。 /// /// 申请 ID /// 是否展示后 4 位(审核比对) /// 是否返回手机号/身份证完整明文(人事审核) /// 详情 /// 成功 /// 记录不存在 /// 服务器错误 [HttpGet("GetInfo")] public async Task GetInfoAsync( [FromQuery] string id, [FromQuery] bool showTail4 = false, [FromQuery] bool revealSensitive = false) { var entity = await GetSubmissionOrThrowAsync(id); await EnsureCanEditOrganizeAsync(entity.OrganizeId); return MapInfoOutput(entity, showTail4, revealSensitive); } /// /// 审核通过(事务+幂等;可关联已有用户或创建新用户) /// /// 审核参数 /// 关联用户 ID /// 审核成功 /// 状态或参数错误 /// 服务器错误 [HttpPost("Approve")] public async Task ApproveAsync([FromBody] LqEmployeeProfileSubmissionApproveInput input) { if (input == null || string.IsNullOrWhiteSpace(input.id)) { throw NCCException.Oh("id 不能为空"); } var submission = await GetSubmissionOrThrowAsync(input.id); var reviewer = await EnsureCanEditOrganizeAsync(submission.OrganizeId); if (submission.Status == (int)EmployeeProfileSubmissionStatusEnum.已通过 && !string.IsNullOrWhiteSpace(submission.LinkedUserId)) { return new { linkedUserId = submission.LinkedUserId, message = "该申请已通过,无需重复操作", idempotent = true }; } if (submission.Status != (int)EmployeeProfileSubmissionStatusEnum.待审核) { throw NCCException.Oh("仅待审核申请可通过"); } if (input.linkExistingUser) { if (string.IsNullOrWhiteSpace(input.linkedUserId)) { throw NCCException.Oh("关联已有用户时 linkedUserId 不能为空"); } } await ApplyApproveHrFieldsAsync(submission, input); reviewer = await EnsureCanEditOrganizeAsync(submission.OrganizeId); var idCardPlain = EmployeeProfileSensitiveHelper.DecryptSensitive(submission.IdCardCipher); if (string.IsNullOrWhiteSpace(idCardPlain)) { throw NCCException.Oh("申请身份证密文无效,无法审核"); } if (!input.linkExistingUser && !reviewer.isAdministrator && !(reviewer.dataScope?.Any(x => x.organizeId == submission.OrganizeId && x.Add) ?? false)) { throw NCCException.Oh(ErrorCode.D1013); } var reviewerId = reviewer.userId; var reviewerName = reviewer.userName; var now = DateTime.Now; string linkedUserId; UserEntity beforeUser = null; UserEntity afterUser; try { _db.Ado.BeginTran(); if (input.linkExistingUser) { var loadedUser = await _db.Queryable() .Where(x => x.Id == input.linkedUserId && x.DeleteMark == null) .FirstAsync(); if (loadedUser == null) { throw NCCException.Oh("关联用户不存在"); } if (!reviewer.isAdministrator && !(reviewer.dataScope?.Any(x => x.organizeId == loadedUser.OrganizeId && x.Edit) ?? false)) { throw NCCException.Oh(ErrorCode.D1013); } beforeUser = UserProfileAuditAppenderService.CloneUser(loadedUser); afterUser = UserProfileAuditAppenderService.CloneUser(loadedUser); ApplySubmissionToUser(afterUser, submission, idCardPlain, keepAccount: true); await _db.Updateable(afterUser).ExecuteCommandAsync(); linkedUserId = afterUser.Id; } else { var candidate = await FindCandidateUserAsync(submission, idCardPlain); if (candidate != null) { throw NCCException.Oh($"检测到已有账号({candidate.Account}),请勾选关联已有用户并指定 linkedUserId={candidate.Id}"); } afterUser = BuildNewUserFromSubmission(submission, idCardPlain); afterUser.Id = YitIdHelper.NextId().ToString(); afterUser.CreatorTime = now; afterUser.CreatorUserId = reviewerId; await _db.Insertable(afterUser).ExecuteCommandAsync(); linkedUserId = afterUser.Id; beforeUser = null; } await UpsertProfileFromSubmissionAsync(submission, linkedUserId, reviewerId, reviewerName, now); submission.Status = (int)EmployeeProfileSubmissionStatusEnum.已通过; submission.LinkedUserId = linkedUserId; submission.ReviewUserId = reviewerId; submission.ReviewUserName = reviewerName; submission.ReviewTime = now; submission.UpdateTime = now; await _db.Updateable(submission).ExecuteCommandAsync(); await _userProfileAuditAppender.AppendProfileDiffAsync( beforeUser, afterUser, "USER_ONBOARD_APPROVE", AuditSource, submission.Id, input.remark); await _userProfileVersionAppender.AfterUserProfilePersistedAsync(linkedUserId, AuditSource); if (!string.IsNullOrWhiteSpace(afterUser.Mdid)) { var oldMdid = beforeUser?.Mdid; await _employeeStoreAssignmentHook.OnMdidChangedAsync( linkedUserId, oldMdid, afterUser.Mdid.Trim(), reviewerId, reviewerName); } _db.Ado.CommitTran(); } catch (Exception) { _db.Ado.RollbackTran(); throw; } var detailJson = JsonConvert.SerializeObject(new { submissionId = submission.Id, submissionNo = submission.SubmissionNo, linkedUserId, linkExistingUser = input.linkExistingUser, remark = input.remark }); await _businessOperationLogService.WriteAsync( BizLogModule, "审核通过扫码入职", BizTypeSubmission, submission.Id, $"审核通过扫码入职申请 {submission.SubmissionNo},关联用户 {linkedUserId}", detailJson); return new { linkedUserId, message = "审核通过", idempotent = false }; } /// /// 驳回扫码入职申请 /// /// 驳回参数 /// 操作结果 /// 驳回成功 /// 状态或参数错误 /// 服务器错误 [HttpPost("Reject")] public async Task RejectAsync([FromBody] LqEmployeeProfileSubmissionRejectInput input) { if (input == null || string.IsNullOrWhiteSpace(input.id)) { throw NCCException.Oh("id 不能为空"); } if (string.IsNullOrWhiteSpace(input.rejectReason)) { throw NCCException.Oh("驳回原因不能为空"); } var submission = await GetSubmissionOrThrowAsync(input.id); await EnsureCanEditOrganizeAsync(submission.OrganizeId); if (submission.Status == (int)EmployeeProfileSubmissionStatusEnum.已驳回) { return new { message = "该申请已驳回", idempotent = true }; } if (submission.Status != (int)EmployeeProfileSubmissionStatusEnum.待审核) { throw NCCException.Oh("仅待审核申请可驳回"); } var before = new { submission.Status, submission.RejectReason }; var now = DateTime.Now; submission.Status = (int)EmployeeProfileSubmissionStatusEnum.已驳回; submission.RejectReason = input.rejectReason.Trim(); submission.ReviewUserId = _userManager.UserId; submission.ReviewUserName = _userManager.RealName ?? _userManager.Account; submission.ReviewTime = now; submission.UpdateTime = now; await _db.Updateable(submission).ExecuteCommandAsync(); await _businessOperationLogService.WriteAsync( BizLogModule, "驳回扫码入职", BizTypeSubmission, submission.Id, $"驳回扫码入职申请 {submission.SubmissionNo},原因:{submission.RejectReason}", JsonConvert.SerializeObject(new { before, after = new { submission.Status, submission.RejectReason } })); return new { message = "已驳回", idempotent = false }; } /// /// 作废扫码入职申请 /// /// 作废参数 /// 操作结果 /// 作废成功 /// 状态错误 /// 服务器错误 [HttpPost("Void")] public async Task VoidAsync([FromBody] LqEmployeeProfileSubmissionVoidInput input) { if (input == null || string.IsNullOrWhiteSpace(input.id)) { throw NCCException.Oh("id 不能为空"); } var submission = await GetSubmissionOrThrowAsync(input.id); await EnsureCanEditOrganizeAsync(submission.OrganizeId); if (submission.Status == (int)EmployeeProfileSubmissionStatusEnum.已作废) { return new { message = "该申请已作废", idempotent = true }; } if (submission.Status == (int)EmployeeProfileSubmissionStatusEnum.已通过) { throw NCCException.Oh("已通过的申请不可作废,请走用户管理处理"); } var beforeStatus = submission.Status; var now = DateTime.Now; submission.Status = (int)EmployeeProfileSubmissionStatusEnum.已作废; submission.VoidUserId = _userManager.UserId; submission.VoidTime = now; submission.UpdateTime = now; await _db.Updateable(submission).ExecuteCommandAsync(); await _businessOperationLogService.WriteAsync( BizLogModule, "作废扫码入职", BizTypeSubmission, submission.Id, $"作废扫码入职申请 {submission.SubmissionNo}" + (string.IsNullOrWhiteSpace(input.reason) ? "" : $",原因:{input.reason}"), JsonConvert.SerializeObject(new { before = new { status = beforeStatus }, after = new { status = submission.Status }, reason = input.reason })); return new { message = "已作废", idempotent = false }; } #endregion #region 私有方法 private async Task GetSubmissionOrThrowAsync(string id) { if (string.IsNullOrWhiteSpace(id)) { throw NCCException.Oh("id 不能为空"); } var entity = await _db.Queryable() .Where(x => x.Id == id) .FirstAsync(); if (entity == null) { throw NCCException.Oh("申请记录不存在"); } return entity; } 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 async Task ValidateSubmissionInputAsync( LqEmployeeProfileSubmissionCrInput input, bool checkDuplicatePending) { if (input == null) { throw NCCException.Oh("参数不能为空"); } if (string.IsNullOrWhiteSpace(input.realName)) { throw NCCException.Oh("姓名不能为空"); } if (!EmployeeProfileSensitiveHelper.IsValidMobile(input.mobilePhone)) { throw NCCException.Oh("手机号格式不正确"); } if (!input.gender.HasValue || (input.gender.Value != 1 && input.gender.Value != 2)) { throw NCCException.Oh("性别只能为男或女"); } var idCard = EmployeeProfileSensitiveHelper.NormalizeIdCard(input.idCardNo); if (string.IsNullOrEmpty(idCard) || !idCard.IsIdentityCardId()) { throw NCCException.Oh("身份证号不合法"); } var idCardGender = EmployeeProfileSensitiveHelper.ParseGenderFromIdCard(idCard); if (idCardGender.HasValue && idCardGender.Value != input.gender.Value) { throw NCCException.Oh("性别与身份证号不一致"); } if (!string.IsNullOrWhiteSpace(input.organizeId)) { input.organizeId = input.organizeId.Trim(); var organizeExists = await _db.Queryable() .AnyAsync(x => x.Id == input.organizeId && x.DeleteMark == null && x.EnabledMark == 1); if (!organizeExists) { throw NCCException.Oh("所选组织不存在或已停用"); } } if (!string.IsNullOrWhiteSpace(input.mdid)) { input.mdid = input.mdid.Trim(); var storeExists = await _db.Queryable() .AnyAsync(x => x.Id == input.mdid && x.Zxzt == "开店" && (x.Status == null || x.Status != -1)); if (!storeExists) { throw NCCException.Oh("所选门店不存在或已停用"); } } if (string.IsNullOrWhiteSpace(input.urgentContacts)) { throw NCCException.Oh("紧急联系人不能为空"); } if (!EmployeeProfileSensitiveHelper.IsValidMobile(input.urgentTelePhone)) { throw NCCException.Oh("紧急联系人电话格式不正确"); } if (EmployeeProfileSensitiveHelper.IsSamePhoneAfterNormalize(input.mobilePhone, input.urgentTelePhone)) { throw NCCException.Oh("紧急联系人电话不能与员工手机号相同"); } if (!EmployeeProfileSensitiveHelper.IsValidEducation(input.education)) { 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.bankCardNo)) { throw NCCException.Oh("银行卡号不能为空"); } if (string.IsNullOrWhiteSpace(input.bankAccountName)) { 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 (!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.bankCardNo) && !EmployeeProfileSensitiveHelper.IsValidBankCard(input.bankCardNo)) { throw NCCException.Oh("银行卡号格式不正确"); } var autoRegularizationDate = EmployeeProfileSensitiveHelper.CalcRegularizationDate( input.entryDate, input.probationMonths); if (autoRegularizationDate.HasValue) { input.regularizationDate = autoRegularizationDate; } if (input.birthday.HasValue) { var idBirth = EmployeeProfileSensitiveHelper.ParseBirthdayFromIdCard(idCard); if (idBirth.HasValue && idBirth.Value.Date != input.birthday.Value.Date) { 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("前公司结束时间不能早于开始时间"); } if (input.regularizationDate.HasValue && input.entryDate.HasValue && input.regularizationDate.Value.Date < input.entryDate.Value.Date) { throw NCCException.Oh("转正日期不能早于入职日期"); } if (checkDuplicatePending) { return; } } private async Task EnsureNotDuplicateSubmitAsync(string idCardHash, string submitIp) { var pending = await _db.Queryable() .Where(x => x.IdCardHash == idCardHash && x.Status == (int)EmployeeProfileSubmissionStatusEnum.待审核) .AnyAsync(); if (pending) { throw NCCException.Oh("该身份证已有待审核申请,请勿重复提交"); } var windowStart = DateTime.Now.AddMinutes(-EmployeeProfileSensitiveHelper.DuplicateSubmitWindowMinutes); var recentSameId = await _db.Queryable() .Where(x => x.IdCardHash == idCardHash && x.SubmitTime >= windowStart) .AnyAsync(); if (recentSameId) { throw NCCException.Oh("提交过于频繁,请稍后再试"); } if (!string.IsNullOrWhiteSpace(submitIp)) { var ipWindow = DateTime.Now.AddMinutes(-EmployeeProfileSensitiveHelper.SameIpSubmitWindowMinutes); var recentIp = await _db.Queryable() .Where(x => x.SubmitIp == submitIp && x.IdCardHash == idCardHash && x.SubmitTime >= ipWindow) .AnyAsync(); if (recentIp) { throw NCCException.Oh("同一网络下提交过于频繁,请稍后再试"); } } } private static LqEmployeeProfileSubmissionEntity MapSubmissionEntity( LqEmployeeProfileSubmissionCrInput input, string idCard, string idCardHash, string mobile, string submitIp, string userAgent, DateTime now) { return new LqEmployeeProfileSubmissionEntity { RealName = input.realName?.Trim(), MobilePhone = mobile, Gender = input.gender, Birthday = input.birthday?.Date ?? EmployeeProfileSensitiveHelper.ParseBirthdayFromIdCard(idCard), Nation = input.nation?.Trim(), NativePlace = input.nativePlace?.Trim(), IdCardCipher = EmployeeProfileSensitiveHelper.EncryptSensitive(idCard), IdCardHash = idCardHash, Education = input.education?.Trim(), EntryDate = input.entryDate?.Date, OrganizeId = input.organizeId?.Trim(), Mdid = input.mdid?.Trim(), Zw = input.zw?.Trim(), Gwfl = input.gwfl?.Trim(), Gw = input.gw?.Trim(), TelePhone = input.telePhone?.Trim(), Landline = input.landline?.Trim(), UrgentContacts = input.urgentContacts?.Trim(), UrgentTelePhone = EmployeeProfileSensitiveHelper.NormalizeMobile(input.urgentTelePhone), PostalAddress = input.postalAddress?.Trim(), MaritalStatus = input.maritalStatus, PoliticalStatus = input.politicalStatus, HouseholdType = input.householdType, CurrentAddress = input.currentAddress?.Trim(), EmployeeNo = string.IsNullOrWhiteSpace(input.employeeNo) ? null : input.employeeNo.Trim(), EmployeeType = input.employeeType, EmployeeStatus = input.employeeStatus, ProbationMonths = input.probationMonths, RegularizationDate = EmployeeProfileSensitiveHelper.CalcRegularizationDate(input.entryDate, input.probationMonths) ?? input.regularizationDate?.Date, RecruitmentType = input.recruitmentType, BankName = input.bankName?.Trim(), BankCardCipher = string.IsNullOrWhiteSpace(input.bankCardNo) ? null : EmployeeProfileSensitiveHelper.EncryptSensitive( EmployeeProfileSensitiveHelper.NormalizeBankCard(input.bankCardNo)), BankAccountName = input.bankAccountName?.Trim(), IdCardAddress = input.idCardAddress?.Trim(), IdCardFrontUrl = input.idCardFrontUrl?.Trim(), IdCardBackUrl = input.idCardBackUrl?.Trim(), GraduateSchool = input.graduateSchool?.Trim(), EnrollmentDate = input.enrollmentDate?.Date, GraduationDate = input.graduationDate?.Date, Major = input.major?.Trim(), PreviousCompany = input.previousCompany?.Trim(), PreviousPosition = input.previousPosition?.Trim(), PreviousStartDate = input.previousStartDate?.Date, PreviousEndDate = input.previousEndDate?.Date, EmergencyContactRelation = input.emergencyContactRelation?.Trim(), EmergencyContactAddress = input.emergencyContactAddress?.Trim(), SubmitIp = submitIp, UserAgent = userAgent }; } private static string BuildSanitizedSnapshotJson( LqEmployeeProfileSubmissionCrInput input, string idCard, string idCardHash) { var snapshot = JObject.FromObject(input); snapshot[nameof(input.idCardNo)] = EmployeeProfileSensitiveHelper.MaskIdCard(idCard); snapshot[nameof(input.bankCardNo)] = string.IsNullOrWhiteSpace(input.bankCardNo) ? null : EmployeeProfileSensitiveHelper.MaskBankCard( EmployeeProfileSensitiveHelper.NormalizeBankCard(input.bankCardNo)); snapshot["idCardHash"] = idCardHash; return snapshot.ToString(Formatting.None); } private static LqEmployeeProfileSubmissionInfoOutput MapInfoOutput( LqEmployeeProfileSubmissionEntity entity, bool showTail4, bool revealSensitive = false) { var idPlain = EmployeeProfileSensitiveHelper.DecryptSensitive(entity.IdCardCipher); var bankPlain = EmployeeProfileSensitiveHelper.DecryptSensitive(entity.BankCardCipher); string MaskSensitive(string plain, Func defaultMask, bool allowReveal) { if (string.IsNullOrWhiteSpace(plain)) { return "无"; } // 人事审核:手机号/身份证返回完整明文 if (allowReveal && revealSensitive) { return plain.Trim(); } return showTail4 ? EmployeeProfileSensitiveHelper.MaskTail4(plain) : defaultMask(plain); } return new LqEmployeeProfileSubmissionInfoOutput { id = entity.Id, submissionNo = entity.SubmissionNo, status = entity.Status, statusName = EnumHelper.GetEnumDesc(entity.Status), rejectReason = entity.RejectReason, linkedUserId = entity.LinkedUserId, reviewUserName = entity.ReviewUserName, reviewTime = entity.ReviewTime, submitSource = entity.SubmitSource, submitSourceName = EnumHelper.GetEnumDesc(entity.SubmitSource), submitIp = entity.SubmitIp, submitTime = entity.SubmitTime, realName = entity.RealName, mobilePhoneMasked = MaskSensitive(entity.MobilePhone, EmployeeProfileSensitiveHelper.MaskPhone, allowReveal: true), gender = entity.Gender, birthday = entity.Birthday, nation = entity.Nation, nativePlace = entity.NativePlace, idCardNoMasked = MaskSensitive(idPlain, EmployeeProfileSensitiveHelper.MaskIdCard, allowReveal: true), education = entity.Education, entryDate = entity.EntryDate, organizeId = entity.OrganizeId, mdid = entity.Mdid, zw = entity.Zw, gwfl = entity.Gwfl, gw = entity.Gw, telePhone = entity.TelePhone, landline = entity.Landline, urgentContacts = entity.UrgentContacts, urgentTelePhone = entity.UrgentTelePhone, postalAddress = entity.PostalAddress, maritalStatus = entity.MaritalStatus, politicalStatus = entity.PoliticalStatus, householdType = entity.HouseholdType, currentAddress = entity.CurrentAddress, employeeNo = entity.EmployeeNo, employeeType = entity.EmployeeType, employeeStatus = entity.EmployeeStatus, probationMonths = entity.ProbationMonths, regularizationDate = entity.RegularizationDate, recruitmentType = entity.RecruitmentType, bankName = entity.BankName, bankCardNoMasked = MaskSensitive(bankPlain, EmployeeProfileSensitiveHelper.MaskBankCard, allowReveal: false), bankAccountName = entity.BankAccountName, idCardAddress = entity.IdCardAddress, idCardFrontUrl = entity.IdCardFrontUrl, idCardBackUrl = entity.IdCardBackUrl, graduateSchool = entity.GraduateSchool, enrollmentDate = entity.EnrollmentDate, graduationDate = entity.GraduationDate, major = entity.Major, previousCompany = entity.PreviousCompany, previousPosition = entity.PreviousPosition, previousStartDate = entity.PreviousStartDate, previousEndDate = entity.PreviousEndDate, emergencyContactRelation = entity.EmergencyContactRelation, emergencyContactAddress = entity.EmergencyContactAddress }; } private async Task FindCandidateUserAsync(LqEmployeeProfileSubmissionEntity submission, string idCardPlain) { var byCert = await _db.Queryable() .Where(x => x.DeleteMark == null && x.CertificatesNumber == idCardPlain) .FirstAsync(); if (byCert != null) { return byCert; } var byMobile = await _db.Queryable() .Where(x => x.DeleteMark == null && x.MobilePhone == submission.MobilePhone) .FirstAsync(); if (byMobile != null) { return byMobile; } var byAccount = await _db.Queryable() .Where(x => x.DeleteMark == null && x.Account == submission.MobilePhone) .FirstAsync(); if (byAccount != null) { return byAccount; } return null; } private async Task EnsureCanEditOrganizeAsync( string organizeId) { var userInfo = await _userManager.GetUserInfo(); if (userInfo.isAdministrator) { return userInfo; } if (string.IsNullOrWhiteSpace(organizeId)) { if (userInfo.dataScope?.Any(x => x.Edit) ?? false) { return userInfo; } throw NCCException.Oh(ErrorCode.D1013); } if (!(userInfo.dataScope?.Any(x => x.organizeId == organizeId && x.Edit) ?? false)) { throw NCCException.Oh(ErrorCode.D1013); } return userInfo; } private async Task ApplyApproveHrFieldsAsync( LqEmployeeProfileSubmissionEntity submission, LqEmployeeProfileSubmissionApproveInput input) { if (input.entryDate.HasValue) { submission.EntryDate = input.entryDate.Value.Date; } if (!string.IsNullOrWhiteSpace(input.organizeId)) { submission.OrganizeId = input.organizeId.Trim(); } if (input.mdid != null) { submission.Mdid = string.IsNullOrWhiteSpace(input.mdid) ? null : input.mdid.Trim(); } if (input.zw != null) { submission.Zw = string.IsNullOrWhiteSpace(input.zw) ? null : input.zw.Trim(); } if (input.gwfl != null) { submission.Gwfl = string.IsNullOrWhiteSpace(input.gwfl) ? null : input.gwfl.Trim(); } if (input.gw != null) { submission.Gw = string.IsNullOrWhiteSpace(input.gw) ? null : input.gw.Trim(); } if (input.employeeNo != null) { submission.EmployeeNo = string.IsNullOrWhiteSpace(input.employeeNo) ? null : input.employeeNo.Trim(); } if (input.employeeType.HasValue) { submission.EmployeeType = input.employeeType; } if (input.employeeStatus.HasValue) { submission.EmployeeStatus = input.employeeStatus; } if (input.probationMonths.HasValue) { submission.ProbationMonths = input.probationMonths; } if (input.regularizationDate.HasValue) { submission.RegularizationDate = input.regularizationDate.Value.Date; } var autoRegularizationDate = EmployeeProfileSensitiveHelper.CalcRegularizationDate( submission.EntryDate, submission.ProbationMonths); if (autoRegularizationDate.HasValue) { submission.RegularizationDate = autoRegularizationDate; } if (input.recruitmentType.HasValue) { submission.RecruitmentType = input.recruitmentType; } if (!submission.EntryDate.HasValue) { throw NCCException.Oh("审核通过前必须填写入职日期"); } if (string.IsNullOrWhiteSpace(submission.OrganizeId)) { throw NCCException.Oh("审核通过前必须选择组织"); } var organizeExists = await _db.Queryable() .AnyAsync(x => x.Id == submission.OrganizeId && x.DeleteMark == null && x.EnabledMark == 1); if (!organizeExists) { throw NCCException.Oh("所选组织不存在或已停用"); } if (!string.IsNullOrWhiteSpace(submission.Mdid)) { var storeExists = await _db.Queryable() .AnyAsync(x => x.Id == submission.Mdid && x.Zxzt == "开店" && (x.Status == null || x.Status != -1)); if (!storeExists) { throw NCCException.Oh("所选门店不存在或已停用"); } } if (!EmployeeProfileSensitiveHelper.IsEnumDefined(submission.EmployeeType)) { throw NCCException.Oh("员工类型枚举无效"); } if (!EmployeeProfileSensitiveHelper.IsEnumDefined(submission.EmployeeStatus)) { throw NCCException.Oh("员工状态枚举无效"); } if (!EmployeeProfileSensitiveHelper.IsEnumDefined(submission.ProbationMonths)) { throw NCCException.Oh("试用期月数枚举无效"); } if (!EmployeeProfileSensitiveHelper.IsEnumDefined(submission.RecruitmentType)) { throw NCCException.Oh("招聘类型枚举无效"); } ValidateSubmissionProfileFields(submission); if (submission.RegularizationDate.HasValue && submission.RegularizationDate.Value.Date < submission.EntryDate.Value.Date) { throw NCCException.Oh("转正日期不能早于入职日期"); } } private static void ValidateSubmissionProfileFields(LqEmployeeProfileSubmissionEntity submission) { if (!EmployeeProfileSensitiveHelper.IsValidEducation(submission.Education)) { throw NCCException.Oh("文化程度取值无效,请选择:博士、硕士、本科、大专、中专、技校、高中、初中、小学"); } if (string.IsNullOrWhiteSpace(submission.CurrentAddress)) { throw NCCException.Oh("现居住地址不能为空"); } if (!EmployeeProfileSensitiveHelper.IsValidFullAddress(submission.IdCardAddress)) { throw NCCException.Oh("身份证地址不能为空,且须填写完整地址(含区/县/街道/门牌等详细信息)"); } if (!EmployeeProfileSensitiveHelper.IsValidHttpUrl(submission.IdCardFrontUrl)) { throw NCCException.Oh("身份证正面照片不能为空且须为有效 URL"); } if (!EmployeeProfileSensitiveHelper.IsValidHttpUrl(submission.IdCardBackUrl)) { throw NCCException.Oh("身份证反面照片不能为空且须为有效 URL"); } if (string.IsNullOrWhiteSpace(submission.BankName)) { throw NCCException.Oh("开户行不能为空"); } if (string.IsNullOrWhiteSpace(submission.BankCardCipher)) { throw NCCException.Oh("银行卡号不能为空"); } if (string.IsNullOrWhiteSpace(submission.BankAccountName)) { throw NCCException.Oh("开户实名不能为空"); } if (EmployeeProfileSensitiveHelper.IsSamePhoneAfterNormalize( submission.MobilePhone, submission.UrgentTelePhone)) { throw NCCException.Oh("紧急联系人电话不能与员工手机号相同"); } } private static UserEntity BuildNewUserFromSubmission(LqEmployeeProfileSubmissionEntity submission, string idCardPlain) { var mobile = submission.MobilePhone; var entity = new UserEntity { Account = mobile, RealName = submission.RealName, NickName = submission.RealName, Gender = submission.Gender, Birthday = submission.Birthday, MobilePhone = mobile, TelePhone = submission.TelePhone, Landline = submission.Landline, Nation = submission.Nation, NativePlace = submission.NativePlace, CertificatesType = EmployeeProfileSensitiveHelper.IdCardCertificateTypeId, CertificatesNumber = idCardPlain, Education = submission.Education, EntryDate = submission.EntryDate, OrganizeId = submission.OrganizeId, Mdid = submission.Mdid, Zw = submission.Zw, Gwfl = submission.Gwfl, Gw = submission.Gw, UrgentContacts = submission.UrgentContacts, UrgentTelePhone = submission.UrgentTelePhone, PostalAddress = submission.PostalAddress, IsOnJob = 1, LeaveDate = null, EnabledMark = 1, IsAdministrator = 0, HeadIcon = "001.png", QuickQuery = PinyinUtil.PinyinString(submission.RealName), Secretkey = Guid.NewGuid().ToString(), ExtensionLong = 1024L * 1024 * 1024 }; entity.Password = MD5Encryption.Encrypt( MD5Encryption.Encrypt(CommonConst.DEFAULT_PASSWORD) + entity.Secretkey); return entity; } private static void ApplySubmissionToUser( UserEntity user, LqEmployeeProfileSubmissionEntity submission, string idCardPlain, bool keepAccount) { if (!keepAccount) { user.Account = submission.MobilePhone; } user.RealName = submission.RealName; user.NickName = submission.RealName; user.Gender = submission.Gender; user.Birthday = submission.Birthday; user.MobilePhone = submission.MobilePhone; user.TelePhone = submission.TelePhone; user.Landline = submission.Landline; user.Nation = submission.Nation; user.NativePlace = submission.NativePlace; user.CertificatesType = EmployeeProfileSensitiveHelper.IdCardCertificateTypeId; user.CertificatesNumber = idCardPlain; user.Education = submission.Education; user.EntryDate = submission.EntryDate; user.OrganizeId = submission.OrganizeId; user.Mdid = submission.Mdid; user.Zw = submission.Zw; user.Gwfl = submission.Gwfl; user.Gw = submission.Gw; user.UrgentContacts = submission.UrgentContacts; user.UrgentTelePhone = submission.UrgentTelePhone; user.PostalAddress = submission.PostalAddress; user.IsOnJob = 1; user.LeaveDate = null; user.LastModifyTime = DateTime.Now; user.QuickQuery = PinyinUtil.PinyinString(submission.RealName); } private async Task UpsertProfileFromSubmissionAsync( LqEmployeeProfileSubmissionEntity submission, string userId, string reviewerId, string reviewerName, DateTime now) { if (!string.IsNullOrWhiteSpace(submission.EmployeeNo)) { var dup = await _db.Queryable() .Where(x => x.EmployeeNo == submission.EmployeeNo && x.UserId != userId) .AnyAsync(); if (dup) { throw NCCException.Oh("工号已被其他员工使用"); } } var existing = await _db.Queryable() .Where(x => x.UserId == userId) .FirstAsync(); if (existing == null) { var profile = new LqEmployeeProfileEntity { Id = YitIdHelper.NextId().ToString(), UserId = userId, MaritalStatus = submission.MaritalStatus, PoliticalStatus = submission.PoliticalStatus, HouseholdType = submission.HouseholdType, CurrentAddress = submission.CurrentAddress, EmployeeNo = submission.EmployeeNo, EmployeeType = submission.EmployeeType, EmployeeStatus = submission.EmployeeStatus, ProbationMonths = submission.ProbationMonths, RegularizationDate = submission.RegularizationDate, RecruitmentType = submission.RecruitmentType, BankName = submission.BankName, BankCardCipher = submission.BankCardCipher, BankAccountName = submission.BankAccountName, IdCardAddress = submission.IdCardAddress, IdCardFrontUrl = submission.IdCardFrontUrl, IdCardBackUrl = submission.IdCardBackUrl, GraduateSchool = submission.GraduateSchool, EnrollmentDate = submission.EnrollmentDate, GraduationDate = submission.GraduationDate, Major = submission.Major, PreviousCompany = submission.PreviousCompany, PreviousPosition = submission.PreviousPosition, PreviousStartDate = submission.PreviousStartDate, PreviousEndDate = submission.PreviousEndDate, EmergencyContactRelation = submission.EmergencyContactRelation, EmergencyContactAddress = submission.EmergencyContactAddress, CreateTime = now, CreateUser = reviewerId, UpdateTime = now, UpdateUser = reviewerId, LastReviewUserId = reviewerId, LastReviewUserName = reviewerName, LastReviewTime = now }; await _db.Insertable(profile).ExecuteCommandAsync(); } else { existing.MaritalStatus = submission.MaritalStatus; existing.PoliticalStatus = submission.PoliticalStatus; existing.HouseholdType = submission.HouseholdType; existing.CurrentAddress = submission.CurrentAddress; existing.EmployeeNo = submission.EmployeeNo; existing.EmployeeType = submission.EmployeeType; existing.EmployeeStatus = submission.EmployeeStatus; existing.ProbationMonths = submission.ProbationMonths; existing.RegularizationDate = submission.RegularizationDate; existing.RecruitmentType = submission.RecruitmentType; existing.BankName = submission.BankName; if (!string.IsNullOrWhiteSpace(submission.BankCardCipher)) { existing.BankCardCipher = submission.BankCardCipher; } existing.BankAccountName = submission.BankAccountName; existing.IdCardAddress = submission.IdCardAddress; existing.IdCardFrontUrl = submission.IdCardFrontUrl; existing.IdCardBackUrl = submission.IdCardBackUrl; existing.GraduateSchool = submission.GraduateSchool; existing.EnrollmentDate = submission.EnrollmentDate; existing.GraduationDate = submission.GraduationDate; existing.Major = submission.Major; existing.PreviousCompany = submission.PreviousCompany; existing.PreviousPosition = submission.PreviousPosition; existing.PreviousStartDate = submission.PreviousStartDate; existing.PreviousEndDate = submission.PreviousEndDate; existing.EmergencyContactRelation = submission.EmergencyContactRelation; existing.EmergencyContactAddress = submission.EmergencyContactAddress; existing.UpdateTime = now; existing.UpdateUser = reviewerId; existing.LastReviewUserId = reviewerId; existing.LastReviewUserName = reviewerName; existing.LastReviewTime = now; await _db.Updateable(existing).ExecuteCommandAsync(); } } #endregion } }