diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 57995f5..7bf0acf 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -337,7 +337,12 @@ module.exports = { company_ids: { type: 'array', itemType: 'integer', description: '所属公司(下属公司)ID列表' }, companies: { type: 'array', itemType: 'principalUserCompanyItem', description: '所属公司明细' }, is_default: { type: 'integer', description: '是否默认主体:1是 0否' }, - status: { type: 'integer', description: '状态:1启用 0禁用' }, + status: { type: 'integer', description: '状态:1启用 0禁用(禁用后该账号登录不再展示此主体)' }, + wechat_bound: { type: 'boolean', description: '是否已绑定微信' }, + wechat_openid: { type: 'string', description: '已绑定微信的脱敏 openid' }, + wechat_bind_scene: { type: 'string', description: '微信绑定来源:bind 主动绑定 / login 扫码登录自动绑定' }, + wechat_bound_at: { type: 'string', description: '微信绑定时间' }, + wechat_last_login_at: { type: 'string', description: '最近一次微信登录时间' }, created_at: { type: 'string', description: '创建时间' }, updated_at: { type: 'string', description: '更新时间' }, }, diff --git a/backend/app/controller/principalUser.js b/backend/app/controller/principalUser.js index 67fc03e..864a33c 100644 --- a/backend/app/controller/principalUser.js +++ b/backend/app/controller/principalUser.js @@ -4,6 +4,18 @@ const { Controller } = require('egg'); const crypto = require('crypto'); const { generateSalt, hashPassword } = require('../lib/password'); const { parsePagination, buildPageResult } = require('../lib/pagination'); +const { + SCENE_BIND, + bindKey, + clearState, + createTempCode, + maskOpenid, + newState, + readState, + saveState, + takeResult, + WechatGatewayError, +} = require('../lib/wechatGateway'); /** * @controller PrincipalUserController 主体用户关联管理 @@ -82,9 +94,173 @@ class PrincipalUserController extends Controller { return plain; }); + await this.attachWechatBind(list); + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } + /** + * 给员工列表补上微信绑定信息(是否绑定 / 脱敏 openid / 绑定时间) + * + * 微信绑定按系统账号(users.id)建立,而员工是「主体 + 账号」的关联, + * 因此这里按 user_id 批量查一次 user_wechat_binds 再回填,避免 N+1。 + * @param {Array} list 员工列表(会被就地补充字段) + * @return {Promise} 无返回值 + */ + async attachWechatBind(list) { + const { ctx } = this; + const items = Array.isArray(list) ? list : []; + if (!items.length) return; + const userIds = [ ...new Set(items.map(item => Number(item.user_id)).filter(id => id > 0)) ]; + if (!userIds.length) return; + const rows = await ctx.model.UserWechatBind.findAll({ + where: { user_id: { [ctx.app.Sequelize.Op.in]: userIds } }, + attributes: [ 'user_id', 'openid', 'bind_scene', 'created_at', 'last_login_at' ], + raw: true, + }); + const byUser = new Map(rows.map(row => [ Number(row.user_id), row ])); + for (const item of items) { + const bind = byUser.get(Number(item.user_id)); + item.wechat_bound = Boolean(bind); + item.wechat_openid = bind ? maskOpenid(bind.openid) : ''; + item.wechat_bind_scene = bind ? bind.bind_scene : ''; + item.wechat_bound_at = bind ? bind.created_at : null; + item.wechat_last_login_at = bind ? bind.last_login_at : null; + } + } + + /** + * 取员工记录并校验当前账号能否管理(用于微信绑定类操作) + * @param {number|string} id 员工(主体账号关联)主键ID + * @return {Promise<{ok: boolean, relation?: Object, message?: string, status?: number}>} 校验结果 + */ + async loadManageableRelation(id) { + const { ctx } = this; + const relation = await ctx.model.PrincipalUser.findByPk(id); + if (!relation) return { ok: false, status: 404, message: '员工不存在' }; + if (relation.role === 'owner') { + return { ok: false, status: 400, message: '系统管理员(默认创建者)不可操作微信绑定' }; + } + const scope = await this.assertManageTarget(relation); + if (!scope.ok) return { ok: false, status: 403, message: scope.message }; + return { ok: true, relation }; + } + + /** + * @summary 拉取员工的微信绑定二维码 + * @description 为指定员工申请一次性扫码会话(scene=bind,绑定目标为该员工的系统账号); + * 员工用微信扫码确认后,其账号即与本系统账号建立绑定,可用于微信扫码登录 + * @router post /api/principal-users/{id}/wechat/bind-code + * @apikey + * @request path integer *id 员工(主体账号关联)主键ID + * @response 200 wechatQrcodeResponse success + */ + async wechatBindCode() { + const { ctx, app } = this; + const target = await this.loadManageableRelation(ctx.params.id); + if (!target.ok) { + ctx.status = target.status; + ctx.body = { code: target.status, message: target.message }; + return; + } + + const state = newState(); + try { + // 绑定目标是员工账号(不是当前操作人),并记录操作人用于轮询校验 + await saveState(app, state, { + scene: SCENE_BIND, + user_id: Number(target.relation.user_id), + operator_id: Number(ctx.userId), + principal_user_id: Number(target.relation.id), + }); + const data = await createTempCode(app, { scene: SCENE_BIND, state }); + const { stateTtl } = app.config.wechatGateway; + ctx.body = { + code: 0, + message: 'success', + data: { + scene: SCENE_BIND, + state, + temp_code: data.tempCode, + page_url: data.pageUrl, + expires_in: Number(data.expiresIn) || stateTtl, + }, + }; + } catch (err) { + const status = err instanceof WechatGatewayError ? err.status : 502; + ctx.status = status; + ctx.body = { code: status, message: err.message }; + } + } + + /** + * @summary 轮询员工微信绑定结果 + * @description pending 待扫码确认;success 绑定成功;conflict 该微信已绑定其他账号;failed 账号不存在或已禁用 + * @router get /api/principal-users/{id}/wechat/bind-status + * @apikey + * @request path integer *id 员工(主体账号关联)主键ID + * @request query string state 扫码会话标识 + * @response 200 wechatBindStatusResponse success + */ + async wechatBindStatus() { + const { ctx, app } = this; + const target = await this.loadManageableRelation(ctx.params.id); + if (!target.ok) { + ctx.status = target.status; + ctx.body = { code: target.status, message: target.message }; + return; + } + + const state = String(ctx.query.state || ''); + const record = await readState(app, state); + if ( + !record + || record.scene !== SCENE_BIND + || Number(record.operator_id) !== Number(ctx.userId) + || Number(record.principal_user_id) !== Number(target.relation.id) + ) { + ctx.status = 400; + ctx.body = { code: 400, message: '二维码已失效,请刷新后重试' }; + return; + } + + const result = await takeResult(app, bindKey(state)); + if (!result) { + ctx.body = { code: 0, message: 'success', data: { status: 'pending' } }; + return; + } + await clearState(app, state); + ctx.body = { code: 0, message: 'success', data: { status: result.status, message: result.message || '' } }; + } + + /** + * @summary 解绑员工的微信 + * @description 删除该员工系统账号的微信绑定;解绑后该员工不能再使用微信扫码登录 + * @router delete /api/principal-users/{id}/wechat/bind + * @apikey + * @request path integer *id 员工(主体账号关联)主键ID + * @response 200 baseResponse success + */ + async wechatUnbind() { + const { ctx } = this; + const target = await this.loadManageableRelation(ctx.params.id); + if (!target.ok) { + ctx.status = target.status; + ctx.body = { code: target.status, message: target.message }; + return; + } + + const count = await ctx.model.UserWechatBind.destroy({ + where: { user_id: Number(target.relation.user_id) }, + }); + if (!count) { + ctx.status = 404; + ctx.body = { code: 404, message: '该员工尚未绑定微信' }; + return; + } + ctx.body = { code: 0, message: 'success', data: { unbound: true } }; + } + /** * @summary 关联详情 * @description 按主键查询关联记录,并带出用户与主体信息 diff --git a/backend/app/controller/warehouseApi.js b/backend/app/controller/warehouseApi.js index 88cac23..879f8af 100644 --- a/backend/app/controller/warehouseApi.js +++ b/backend/app/controller/warehouseApi.js @@ -87,7 +87,8 @@ class WarehouseApiController extends Controller { /** * @summary 新增仓库接口配置 - * @description warehouse_id 与 name 必填;仓库必须属于当前主体;接口类型由服务端固定为类奇门JSON接口(qimen); + * @description warehouse_id 与 name 必填;仓库必须属于当前主体;每个仓库只能存在一个接口配置; + * 接口类型由服务端固定为类奇门JSON接口(qimen); * 配置项值不在此接口维护,请使用 PUT /api/warehouse-apis/{id}/fields * @router post /api/warehouse-apis * @apikey @@ -111,6 +112,17 @@ class WarehouseApiController extends Controller { return; } + // 每个仓库只能存在一个接口配置:仓库与外部 WMS 是一对一关系,多份配置无法确定用哪一份 + const exist = await ctx.model.WarehouseApi.findOne({ + where: { principal_id: principalId, warehouse_id: Number(warehouseId) }, + attributes: [ 'id', 'name' ], + }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: `该仓库已存在接口配置(${exist.name}),每个仓库只能配置一个接口` }; + return; + } + // 接口类型仅支持类奇门JSON接口,忽略入参由服务端固定写入;extra 由字段值接口维护 const payload = { ...ctx.request.body, principal_id: principalId, type: API_TYPE_QIMEN }; delete payload.extra; diff --git a/backend/app/router.js b/backend/app/router.js index 1cd0657..916c4bf 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -58,6 +58,10 @@ module.exports = app => { // select 需在 resources 之前注册,避免被 /:id 误匹配 router.get('/api/principal-subsidiaries/select', jwtAuth, principalCheck(), controller.principalSubsidiary.select); router.resources('principalSubsidiaries', '/api/principal-subsidiaries', jwtAuth, principalCheck({ model: 'PrincipalSubsidiary' }), controller.principalSubsidiary); + // 员工微信绑定:拉取绑定码 / 轮询结果 / 解绑,需在 resources 之前注册,避免被 /:id 误匹配 + router.post('/api/principal-users/:id/wechat/bind-code', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.wechatBindCode); + router.get('/api/principal-users/:id/wechat/bind-status', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.wechatBindStatus); + router.delete('/api/principal-users/:id/wechat/bind', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.wechatUnbind); // 主体用户关联:需校验主体绑定关系 router.resources('principalUsers', '/api/principal-users', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser); // 权限管理:权限表(按菜单分类,每个菜单含集团全部/所在公司两种权限) diff --git a/backend/app/service/access.js b/backend/app/service/access.js index bfb45f4..3413627 100644 --- a/backend/app/service/access.js +++ b/backend/app/service/access.js @@ -33,9 +33,11 @@ class AccessService extends Service { const relation = await this.ctx.model.PrincipalUser.findOne({ where: { user_id: userId, principal_id: Number(principalId) }, - attributes: [ 'id', 'role', 'role_id' ], + attributes: [ 'id', 'role', 'role_id', 'status' ], }); if (!relation) return empty; + // 员工在该主体下被停用:视为没有任何权限(兜底,正常应被主体绑定校验拦住) + if (Number(relation.status) !== 1) return empty; const companyRows = await this.ctx.model.PrincipalUserCompany.findAll({ where: { principal_user_id: relation.id }, diff --git a/backend/app/service/cache.js b/backend/app/service/cache.js index 7a9d6bc..8025e0a 100644 --- a/backend/app/service/cache.js +++ b/backend/app/service/cache.js @@ -132,13 +132,14 @@ class CacheService extends Service { /** * 用户已绑定的主体ID列表(用于多租户数据隔离) + * 只返回启用状态(principal_users.status=1)的关联:员工被停用后不再拥有该主体的任何权限 * @param {Number} userId 用户ID * @return {Promise>} 主体ID数组 */ async getUserPrincipalIds(userId) { return await this.remember(KEYS.userPrincipals(userId), this.ttls.principal, async () => { const rows = await this.ctx.model.PrincipalUser.findAll({ - where: { user_id: userId }, + where: { user_id: userId, status: 1 }, attributes: [ 'principal_id' ], }); return rows.map(row => Number(row.principal_id)); @@ -147,13 +148,14 @@ class CacheService extends Service { /** * 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识) + * 只返回启用状态的关联:员工在某个主体下被停用后,登录后不再展示该主体 * @param {Number} userId 用户ID * @return {Promise>} 主体选项列表 */ async getUserPrincipalOptions(userId) { return await this.remember(KEYS.principalOptions(userId), this.ttls.principalOptions, async () => { const relations = await this.ctx.model.PrincipalUser.findAll({ - where: { user_id: userId }, + where: { user_id: userId, status: 1 }, attributes: [ 'id', 'principal_id', 'role', 'is_default', 'status' ], order: [[ 'is_default', 'DESC' ], [ 'id', 'ASC' ]], }); diff --git a/backend/app/utils/exportDefs.js b/backend/app/utils/exportDefs.js index 33d8342..905aafc 100644 --- a/backend/app/utils/exportDefs.js +++ b/backend/app/utils/exportDefs.js @@ -548,6 +548,12 @@ const PRINCIPAL_USER_COLUMNS = [ expr: "(SELECT GROUP_CONCAT(s.name SEPARATOR '、') FROM principal_user_companies puc JOIN principal_subsidiaries s ON s.id = puc.subsidiary_id WHERE puc.principal_user_id = t.id)", }, { key: 'is_default', header: '默认主体', format: yesNo }, + { + key: 'wechat_bound', + header: '微信绑定', + expr: 'IF(EXISTS(SELECT 1 FROM user_wechat_binds w WHERE w.user_id = t.user_id), 1, 0)', + format: yesNo, + }, { key: 'status', header: '状态', format: labels(ENABLE_MAP) }, { key: 'created_at', header: '创建时间' }, ]; diff --git a/backend/database/migrations/20261105093000-add-unique-warehouse-to-warehouse-apis.js b/backend/database/migrations/20261105093000-add-unique-warehouse-to-warehouse-apis.js new file mode 100644 index 0000000..ae51d93 --- /dev/null +++ b/backend/database/migrations/20261105093000-add-unique-warehouse-to-warehouse-apis.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 仓库接口配置与仓库之间改为「一对一」 + * + * 业务上每个仓库只能对接一个外部 WMS 接口,存在多份配置时无法确定用哪一份推送/回调, + * 因此这里先清理历史重复数据(同一仓库保留最新一条),再加唯一索引兜底并发创建。 + */ +module.exports = { + async up(queryInterface) { + const [ duplicates ] = await queryInterface.sequelize.query(` + SELECT warehouse_id, COUNT(*) AS total, MAX(id) AS keep_id + FROM warehouse_apis + GROUP BY warehouse_id + HAVING COUNT(*) > 1 + `); + + for (const row of duplicates) { + await queryInterface.sequelize.query( + 'DELETE FROM warehouse_apis WHERE warehouse_id = ? AND id <> ?', + { replacements: [ row.warehouse_id, row.keep_id ] } + ); + } + + await queryInterface.addIndex('warehouse_apis', [ 'warehouse_id' ], { + name: 'uk_warehouse_apis_warehouse', + unique: true, + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('warehouse_apis', 'uk_warehouse_apis_warehouse'); + }, +}; diff --git a/frontend/src/api/principalUser.ts b/frontend/src/api/principalUser.ts index 36eead0..2b29819 100644 --- a/frontend/src/api/principalUser.ts +++ b/frontend/src/api/principalUser.ts @@ -1,4 +1,5 @@ import { get, post, put, del } from '@/utils/request' +import type { WechatQrcode, WechatBindStatus } from '@/api/wechat' export interface PrincipalUserItem { id: number @@ -19,6 +20,16 @@ export interface PrincipalUserItem { companies?: { id: number; subsidiary_id: number; name: string }[] is_default: number status: number + /** 是否已绑定微信 */ + wechat_bound?: boolean + /** 已绑定微信的脱敏 openid */ + wechat_openid?: string + /** 微信绑定来源:bind 主动绑定 / login 扫码登录自动绑定 */ + wechat_bind_scene?: string + /** 微信绑定时间 */ + wechat_bound_at?: string | null + /** 最近一次微信登录时间 */ + wechat_last_login_at?: string | null created_at?: string user?: { id: number @@ -78,3 +89,18 @@ export function updatePrincipalUser( export function deletePrincipalUser(id: number) { return del<{ id: number }>(`/principal-users/${id}`) } + +/** 拉取指定员工的微信绑定二维码(扫码后绑定该员工的系统账号) */ +export function createEmployeeWechatBindCode(id: number) { + return post(`/principal-users/${id}/wechat/bind-code`) +} + +/** 轮询指定员工的微信绑定结果(结果一次性,取到即失效) */ +export function getEmployeeWechatBindStatus(id: number, state: string) { + return get(`/principal-users/${id}/wechat/bind-status`, { state }) +} + +/** 解绑指定员工的微信 */ +export function unbindEmployeeWechat(id: number) { + return del<{ unbound: boolean }>(`/principal-users/${id}/wechat/bind`) +} diff --git a/frontend/src/views/ExternalApi/Index.vue b/frontend/src/views/ExternalApi/Index.vue index 0fe4c00..be7d520 100644 --- a/frontend/src/views/ExternalApi/Index.vue +++ b/frontend/src/views/ExternalApi/Index.vue @@ -1068,11 +1068,25 @@ onMounted(async () => {
- + 新增配置
+
@@ -1596,6 +1610,9 @@ onMounted(async () => { margin-bottom: 8px; min-height: 32px; } +.config-once-tip { + margin-bottom: 8px; +} .items-toolbar .el-button { height: 28px; padding: 0 12px; diff --git a/frontend/src/views/PrincipalUser/Index.vue b/frontend/src/views/PrincipalUser/Index.vue index 69cb3e0..9e4d601 100644 --- a/frontend/src/views/PrincipalUser/Index.vue +++ b/frontend/src/views/PrincipalUser/Index.vue @@ -1,17 +1,23 @@ + + + +
+

+ 绑定对象:{{ wechatTarget ? userLabel(wechatTarget) : '-' }} +

+
+ +
+ + {{ wechatHint || '正在准备二维码…' }} +
+
+

请该员工使用微信扫码,并在手机上确认绑定

+

绑定成功后窗口会自动关闭

+ + 刷新二维码 + +
+
@@ -573,4 +736,55 @@ onMounted(async () => { color: var(--el-text-color-secondary); line-height: 1.6; } +/* 微信列:绑定状态 + 详情 */ +.wechat-cell { + display: flex; + align-items: center; + gap: 6px; +} +.wechat-link-text { + font-size: 12px; + color: var(--el-text-color-secondary); + cursor: default; + text-decoration: underline dotted; +} +.wechat-dialog { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; +} +.wechat-target { + margin: 0; + font-weight: 600; +} +.wechat-qr { + width: 196px; + height: 196px; + display: flex; + align-items: center; + justify-content: center; +} +.wechat-qr-empty { + width: 180px; + height: 180px; + display: flex; + align-items: center; + justify-content: center; + border: 1px dashed var(--el-border-color); + border-radius: 8px; + color: var(--el-text-color-secondary); + font-size: 13px; + text-align: center; + padding: 8px; +} +.wechat-hint { + margin: 0; + font-size: 13px; + color: var(--el-text-color-regular); +} +.wechat-sub { + color: var(--el-text-color-secondary); + font-size: 12px; +}