diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 7bf0acf..3299136 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -360,12 +360,13 @@ module.exports = { avatar: { type: 'string', description: '该账号在此主体下的头像 URL' }, role: { type: 'string', description: '角色标识,如 admin' }, role_id: { type: 'integer', description: '角色组ID(roles.id),为空表示未分配' }, + email: { type: 'string', description: '账号邮箱(选填):仅临时账号(邮箱为空)可补填,已绑定邮箱请员工在个人设置中修改' }, company_ids: { type: 'array', itemType: 'integer', description: '所属公司(下属公司)ID列表;非所有者至少一家' }, is_default: { type: 'integer', description: '是否默认主体:1是 0否,默认0' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, }, invitePrincipalUserRequest: { - email: { type: 'string', required: true, description: '被邀请人邮箱,全局唯一,创建后作为登录账号' }, + email: { type: 'string', description: '被邀请人邮箱(选填):填了则全局唯一并作为登录账号;留空则创建临时账号(自动生成账号名、邮箱留空,后续可微信扫码绑定或补填邮箱)' }, name: { type: 'string', required: true, description: '该员工在此主体下的名称(推送单据操作人取此值)' }, avatar: { type: 'string', description: '该员工在此主体下的头像 URL(选填)' }, principal_id: { type: 'integer', required: true, description: '目标主体ID,需当前账号已绑定该主体' }, @@ -375,11 +376,12 @@ module.exports = { invitePrincipalUserData: { user_id: { type: 'integer', description: '新建/复用的用户ID' }, relation_id: { type: 'integer', description: '主体用户关联记录ID' }, - email: { type: 'string', description: '邮箱(即登录账号)' }, - username: { type: 'string', description: '登录账号(此处为邮箱)' }, + email: { type: 'string', description: '邮箱(即登录账号);临时账号为空' }, + username: { type: 'string', description: '登录账号(填邮箱时为邮箱,临时账号为自动生成的账号名)' }, nickname: { type: 'string', description: '用户名称' }, password: { type: 'string', description: '随机生成的初始密码(仅新建账号时返回一次);复用已有账号时为 null' }, reused: { type: 'boolean', description: '是否复用已有账号(邮箱已注册,沿用原密码登录)' }, + temporary: { type: 'boolean', description: '是否为临时账号(未填邮箱,账号名自动生成,后续扫码绑定微信或补填邮箱)' }, }, invitePrincipalUserResponse: { code: { type: 'integer', description: '业务状态码,0 成功' }, diff --git a/backend/app/controller/principalUser.js b/backend/app/controller/principalUser.js index 864a33c..0aeb080 100644 --- a/backend/app/controller/principalUser.js +++ b/backend/app/controller/principalUser.js @@ -364,8 +364,9 @@ class PrincipalUserController extends Controller { /** * @summary 邀请开通主体账号 - * @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)、主体ID、角色组与所属公司, - * 绑定到该主体;邮箱未注册时自动创建新用户(随机初始密码),已注册时复用现有账号并沿用原密码; + * @description 传入用户名称(写入主体账号关联表 principal_users.name)、主体ID、角色组与所属公司,绑定到该主体; + * 邮箱选填:填了邮箱且已注册时复用现有账号并沿用原密码;未注册时创建新用户(随机初始密码); + * 不填邮箱时创建「临时账号」(自动生成登录账号、邮箱留空),后续可用微信扫码绑定或自行补填邮箱; * 角色组必选,除所有者外必须至少关联一家公司(所在公司权限的账号只能关联自己所属的公司); * 新建账号时返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不能在同一主体重复添加 * @router post /api/principal-users/invite @@ -385,7 +386,9 @@ class PrincipalUserController extends Controller { company_ids: bodyCompanyIds, } = ctx.request.body; - if (!email || !EMAIL_REGEX.test(email)) { + // 邮箱选填:留空表示先建临时账号(自动生成账号名,后续微信扫码绑定或补填邮箱) + const emailInput = String(email == null ? '' : email).trim(); + if (emailInput && !EMAIL_REGEX.test(emailInput)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; @@ -410,7 +413,7 @@ class PrincipalUserController extends Controller { } // 邮箱已注册时复用现有账号:只要该账号尚未属于当前主体,就直接新增主体关联(沿用原密码登录) - const existUser = await ctx.model.User.findOne({ where: { email } }); + const existUser = emailInput ? await ctx.model.User.findOne({ where: { email: emailInput } }) : null; let existingUser = null; if (existUser) { const bound = await ctx.model.PrincipalUser.findOne({ @@ -510,12 +513,15 @@ class PrincipalUserController extends Controller { const password = this.generateRandomPassword(12); const salt = generateSalt(); const hashed = hashPassword(password, salt); + // 未填邮箱 → 临时账号:自动生成登录账号名,邮箱留空(后续扫码绑定微信或自行补填邮箱) + const username = emailInput || await this.nextTempUsername(); const transaction = await ctx.model.transaction(); try { const user = await ctx.model.User.create({ - username: email, - email, + username, + email: emailInput || null, + nickname: String(name).trim(), salt, password: hashed, status: 1, @@ -553,10 +559,12 @@ class PrincipalUserController extends Controller { data: { user_id: user.id, relation_id: relation.id, - email: user.email, + email: user.email || '', username: user.username, nickname: relation.name, password, + // 临时账号:邮箱为空,可用微信扫码绑定(已有微信账号时直接绑定到该账号) + temporary: !user.email, }, }; } catch (err) { @@ -566,6 +574,24 @@ class PrincipalUserController extends Controller { } } + /** + * 生成临时账号的登录名(未填邮箱时使用):tmp_ + 8 位随机字符,保证全局唯一 + * @return {Promise} 未被占用的登录名 + */ + async nextTempUsername() { + const { ctx } = this; + const chars = 'abcdefghijkmnopqrstuvwxyz23456789'; + for (let i = 0; i < 10; i++) { + const bytes = crypto.randomBytes(8); + let name = 'tmp_'; + for (let j = 0; j < 8; j++) name += chars[bytes[j] % chars.length]; + const exist = await ctx.model.User.findOne({ where: { username: name }, attributes: [ 'id' ] }); + if (!exist) return name; + } + // 极端情况下兜底:带时间戳,仍保证唯一性检查 + return `tmp_${Date.now().toString(36)}`; + } + /** * 生成随机密码:12 位,含大小写字母与数字(去除易混淆字符 0/O/1/l/I) * @param {Number} len 长度,默认 12 @@ -621,6 +647,37 @@ class PrincipalUserController extends Controller { if (body[key] !== undefined) patch[key] = body[key]; } + // 邮箱维护:临时账号(邮箱为空)可由管理员补填;已绑定邮箱的账号需员工在「个人设置」自行修改 + let emailPatch = null; + if (body.email !== undefined) { + const email = String(body.email == null ? '' : body.email).trim(); + const account = await ctx.model.User.findByPk(relation.user_id, { attributes: [ 'id', 'email' ] }); + if (!account) { + ctx.status = 404; + ctx.body = { code: 404, message: '员工账号不存在' }; + return; + } + if (email) { + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '邮箱格式不正确' }; + return; + } + if (account.email && String(account.email) !== email) { + ctx.status = 400; + ctx.body = { code: 400, message: '该账号已绑定邮箱,如需修改请让员工在「个人设置」中维护' }; + return; + } + const exist = await ctx.model.User.findOne({ where: { email }, attributes: [ 'id' ] }); + if (exist && Number(exist.id) !== Number(relation.user_id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱已被其他账号使用' }; + return; + } + if (!account.email) emailPatch = email; + } + } + // 所在公司权限:角色组与所属公司均不可修改(防止自我/他人提权、跨公司调配) if (!scope.access.isGroup) { if (patch.role !== undefined || body.role_id !== undefined) { @@ -699,12 +756,16 @@ class PrincipalUserController extends Controller { } await relation.update(patch); + if (emailPatch) { + await ctx.model.User.update({ email: emailPatch }, { where: { id: relation.user_id } }); + await ctx.service.cache.invalidateUser(relation.user_id); + } if (companyIds) await this.syncCompanies(relation, companyIds); await ctx.service.cache.invalidateUserPrincipals(relation.user_id); ctx.body = { code: 0, message: 'success', - data: { id: relation.id, name: relation.name, avatar: relation.avatar }, + data: { id: relation.id, name: relation.name, avatar: relation.avatar, email: emailPatch || undefined }, }; } diff --git a/backend/app/controller/wechatAuth.js b/backend/app/controller/wechatAuth.js index c7c70a7..fb18b6e 100644 --- a/backend/app/controller/wechatAuth.js +++ b/backend/app/controller/wechatAuth.js @@ -264,6 +264,10 @@ class WechatAuthController extends Controller { /** * 处理绑定通知:写入 user_wechat_binds(同一账号重新绑定则覆盖,同一微信只能绑一个账号) + * + * 员工档案发起的绑定(state 带 principal_user_id)额外处理「微信已有账号」的情况: + * - 该微信已绑定账号 A 且 A 不是该员工当前账号 → 把员工切换到 A(同一主体下已存在则提示冲突) + * - 该微信未绑定任何账号 → 直接绑定到员工当前账号(临时账号即在此完成「账号 + 绑定」) * @param {Egg.Application} app egg application * @param {Object} body 通知报文 * @param {Object} record 扫码会话内容 @@ -273,6 +277,7 @@ class WechatAuthController extends Controller { async handleBindNotify(app, body, record, state) { const { ctx } = this; const userId = Number(record.user_id); + const relationId = Number(record.principal_user_id) || 0; const openid = String(body.openid || ''); if (!userId || !openid) { @@ -289,6 +294,21 @@ class WechatAuthController extends Controller { const occupied = await ctx.model.UserWechatBind.findOne({ where: { openid } }); if (occupied && Number(occupied.user_id) !== userId) { + // 员工档案绑定:该微信已有账号 → 把员工关联到已有账号,而不是报冲突 + if (relationId) { + const switched = await this.switchEmployeeAccount(relationId, Number(occupied.user_id)); + if (switched.ok) { + await writeResult(app, bindKey(state), { + status: 'success', + message: switched.same ? '绑定成功' : '该微信已有账号,已绑定到该账号', + }); + ctx.body = { code: 0, message: 'success' }; + return; + } + await writeResult(app, bindKey(state), { status: 'conflict', message: switched.message }); + this.fail(new WechatGatewayError(switched.message, 409)); + return; + } await writeResult(app, bindKey(state), { status: 'conflict', message: '该微信已绑定其他系统账号,请先在对应账号解绑' }); this.fail(new WechatGatewayError('该微信已绑定其他系统账号', 409)); return; @@ -322,6 +342,56 @@ class WechatAuthController extends Controller { ctx.body = { code: 0, message: 'success' }; } + /** + * 把员工的系统账号切换为「微信已绑定的账号」 + * + * 用于员工档案绑定微信时,扫码的微信此前已绑定过系统账号 A:把员工关联到 A, + * 原临时账号(邮箱为空且不再有任何主体关联)置为禁用,避免遗留可登录的孤儿账号。 + * @param {Number} relationId 员工(主体账号关联)ID + * @param {Number} newUserId 微信已绑定的账号ID + * @return {Promise<{ok: Boolean, same?: Boolean, message?: String}>} 切换结果 + */ + async switchEmployeeAccount(relationId, newUserId) { + const { ctx } = this; + const relation = await ctx.model.PrincipalUser.findByPk(relationId); + if (!relation) return { ok: false, message: '员工不存在或已被移除' }; + + const oldUserId = Number(relation.user_id); + if (oldUserId === Number(newUserId)) return { ok: true, same: true }; + + const target = await ctx.model.User.findByPk(newUserId); + if (!target || Number(target.status) !== 1) { + return { ok: false, message: '该微信绑定的账号不存在或已禁用,请联系管理员' }; + } + + const dup = await ctx.model.PrincipalUser.findOne({ + where: { principal_id: relation.principal_id, user_id: Number(newUserId) }, + attributes: [ 'id' ], + }); + if (dup) return { ok: false, message: '该微信对应的账号已在当前主体中,无需重复绑定' }; + + const transaction = await ctx.model.transaction(); + try { + await relation.update({ user_id: Number(newUserId) }, { transaction }); + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + ctx.logger.warn(`[wechat] 员工 ${relationId} 切换账号失败:${err.message}`); + return { ok: false, message: '切换账号失败,请稍后重试' }; + } + + // 原账号是临时账号(无邮箱)且已无任何主体关联 → 禁用,避免遗留可登录的孤儿账号 + const oldUser = await ctx.model.User.findByPk(oldUserId); + if (oldUser && !oldUser.email) { + const linked = await ctx.model.PrincipalUser.count({ where: { user_id: oldUserId } }); + if (!linked) await oldUser.update({ status: 0 }); + } + await ctx.service.cache.invalidateUserPrincipals(oldUserId); + await ctx.service.cache.invalidateUserPrincipals(Number(newUserId)); + ctx.logger.info(`[wechat] 员工 ${relationId} 已切换到微信账号 ${newUserId}(原账号 ${oldUserId})`); + return { ok: true }; + } + /** * 处理登录通知:按 openid 找到绑定账号,把可签发的用户写入 Redis 供前端轮询取走 * @param {Egg.Application} app egg application diff --git a/frontend/src/api/principalUser.ts b/frontend/src/api/principalUser.ts index 2b29819..ff8f78b 100644 --- a/frontend/src/api/principalUser.ts +++ b/frontend/src/api/principalUser.ts @@ -42,13 +42,17 @@ export interface PrincipalUserItem { export interface InviteResult { user_id: number relation_id: number + /** 邮箱(临时账号为空字符串) */ email: string + /** 登录账号(填邮箱时为邮箱,临时账号为自动生成的账号名) */ username: string nickname: string /** 初始密码(仅新建账号返回一次;复用已有账号为 null) */ password: string | null /** 是否复用已有账号(邮箱已注册,沿用原密码登录) */ reused?: boolean + /** 是否临时账号(未填邮箱,后续扫码绑定微信或补填邮箱) */ + temporary?: boolean } /** 当前主体下的用户关联列表(principal_id 由请求拦截器自动注入) */ @@ -59,9 +63,9 @@ export function getPrincipalUsers(params?: object) { ) } -/** 新增员工:创建用户(随机初始密码)并绑定到当前主体,角色组与所属公司必填 */ +/** 新增员工:创建用户(随机初始密码)并绑定到当前主体,角色组与所属公司必填;邮箱选填(留空创建临时账号) */ export function invitePrincipalUser(data: { - email: string + email?: string name: string avatar?: string | null role_id: number @@ -70,7 +74,7 @@ export function invitePrincipalUser(data: { return post('/principal-users/invite', data) } -/** 更新关联(名称 / 头像 / 角色组 / 所属公司 / 状态) */ +/** 更新关联(名称 / 头像 / 角色组 / 所属公司 / 状态 / 邮箱) */ export function updatePrincipalUser( id: number, data: { @@ -78,6 +82,7 @@ export function updatePrincipalUser( avatar?: string | null role?: string role_id?: number | null + email?: string company_ids?: number[] status?: number }, diff --git a/frontend/src/views/PrincipalUser/Index.vue b/frontend/src/views/PrincipalUser/Index.vue index 9e4d601..95015a5 100644 --- a/frontend/src/views/PrincipalUser/Index.vue +++ b/frontend/src/views/PrincipalUser/Index.vue @@ -134,7 +134,7 @@ const inviteAvatarList = computed({ }) const inviteRules: FormRules = { email: [ - { required: true, message: '请输入邮箱', trigger: 'blur' }, + // 邮箱选填:不填时创建「临时账号」,后续可微信扫码绑定或自行补填邮箱 { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }, ], name: [{ required: true, message: '请输入名称', trigger: 'blur' }], @@ -143,7 +143,12 @@ const inviteRules: FormRules = { } /** 新增成功后返回的账号信息(初始密码仅返回一次) */ -const inviteResult = ref<{ username: string; password: string; reused: boolean } | null>(null) +const inviteResult = ref<{ + username: string + password: string + reused: boolean + temporary: boolean +} | null>(null) const inviteResultVisible = ref(false) /** 复制文本:优先 Clipboard API,非安全上下文回退到 execCommand */ @@ -201,6 +206,8 @@ async function submitInvite() { // 复用已有账号时不返回密码(沿用原密码登录),只提示已关联 if (res.reused) { ElMessage.success('该邮箱已有账号,已关联到当前主体(沿用原密码登录)') + } else if (!inviteForm.email.trim()) { + ElMessage.success('员工创建成功(临时账号,建议扫码绑定微信或补填邮箱)') } else { ElMessage.success('员工创建成功') } @@ -209,6 +216,7 @@ async function submitInvite() { username: res.username, password: res.password || '', reused: !!res.reused, + temporary: !!res.temporary, } inviteResultVisible.value = true await fetchList() @@ -227,11 +235,14 @@ const editFormRef = ref() const editId = ref(null) const editForm = reactive({ name: '', + email: '', avatar: null as string | null, role_id: '' as string | number, company_ids: [] as number[], status: 1, }) +/** 邮箱已绑定时只读(修改走员工的个人设置) */ +const editEmailLocked = ref(false) const editAvatarList = computed({ get: () => (editForm.avatar ? [ editForm.avatar ] : []), set: (value: string[]) => { editForm.avatar = value[0] || null }, @@ -240,6 +251,7 @@ const editAvatarList = computed({ const editIsOwner = ref(false) const editRules: FormRules = { name: [{ required: true, message: '请输入名称', trigger: 'blur' }], + email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }], role_id: [{ required: true, message: '请选择角色组', trigger: 'change' }], company_ids: [ { @@ -257,6 +269,8 @@ function openEdit(row: PrincipalUserItem) { editId.value = row.id editIsOwner.value = row.role === 'owner' editForm.name = row.name || row.user?.nickname || row.user?.username || '' + editForm.email = row.user?.email || '' + editEmailLocked.value = Boolean(row.user?.email) editForm.avatar = row.avatar || null editForm.role_id = row.role_id ?? '' editForm.company_ids = (row.companies || []).map(item => Number(item.subsidiary_id)) @@ -276,6 +290,10 @@ async function submitEdit() { avatar: editForm.avatar, status: editForm.status, } + // 临时账号补填邮箱(已绑定邮箱时输入框只读,不提交) + if (!editEmailLocked.value && editForm.email.trim()) { + payload.email = editForm.email.trim() + } if (!isCompanyScope.value) { payload.role_id = Number(editForm.role_id) payload.company_ids = editForm.company_ids @@ -462,7 +480,12 @@ onUnmounted(stopWechatPolling) - + + + @@ -539,7 +562,10 @@ onUnmounted(stopWechatPolling) - + +
+ 填邮箱后作为登录账号;留空则生成临时账号(邮箱可后续补填,也可直接用微信扫码绑定) +
@@ -575,6 +601,16 @@ onUnmounted(stopWechatPolling) + + +
+ {{ editEmailLocked ? '邮箱已绑定,如需修改请让员工在「个人设置」中维护' : '临时账号可在此补填邮箱,补填后即可用邮箱登录' }} +
+
@@ -624,6 +660,13 @@ onUnmounted(stopWechatPolling) title="该邮箱已注册过账号,已直接关联到当前主体;登录密码沿用原账号密码,如需重置请在登录页使用「忘记密码」" style="margin-bottom: 16px" /> +