feat(hub): 接入统一门户免登、人员目录同步与MCP密钥接口
- 新增 /sso/hub 免登落地页与 api/system/hub 接口封装,前端生成并登记 state 后用一次性票据换本地会话,清地址栏票据并限制站内相对跳转防开放重定向 - 新增 hub 人员目录同步页 views/system/hubSync,支持关键字/绑定状态/人工处理筛选,以及绑定、新建并绑定、解绑、忽略、恢复操作,均带 v-hasPermi 权限控制 - 新增 DSH 身份信封支撑类 DshEnvelopeClaim、DshEnvelopeException、DshEnvelopeUtils,用户身份只认信封解出的 subject,错误码供 hub 定位 - 新增 DshMcpKeyController、IDshMcpKeyService 与 DshMcpKeyServiceImpl 及 DshMcpKeyVo、DshMcpCredentialVo,提供 /dsh/mcp/keys 密钥签发与删除 - ShiroConfig 将 /dsh/mcp/keys 设为 anon 并给 McpBotAuthFilter 注入 HubProperties,支持门户凭据同路径鉴权与跨域白名单 - application.yml 新增 hub 配置块(总开关、登录分流、目录同步、H5 第二应用密钥、mcp 轮换旧钥与有效期),spring.profiles.active 切为 dev - application-prod.yml 更新管理端与 H5 生产密钥、补全 hub.mcp 段并将 auto-create-new 置为 false - ProjectOrderInfo 增加 finalApproveTime 字段,订单列表与详情页展示订单生效时间和最终生效时间 - 新增静态图片资源 static/img/pexels-kubiceknov-924824.jpgcp_1.0.0
parent
076fdfaffb
commit
7c27d2e404
|
|
@ -0,0 +1,106 @@
|
|||
import request from '@/utils/request'
|
||||
|
||||
// 统一登录状态:是否启用免登、hub 首页地址、退出是否回 hub
|
||||
export function getHubStatus() {
|
||||
return request({
|
||||
url: '/sso/hub/status',
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
// 登记本次跳转的 state(门户跳转本身不带 state,由前端生成后在此绑定会话)
|
||||
export function prepareHubState(state) {
|
||||
return request({
|
||||
url: '/sso/hub/state',
|
||||
method: 'post',
|
||||
data: { state }
|
||||
})
|
||||
}
|
||||
|
||||
// 用一次性票据换取本地会话
|
||||
export function verifyHubTicket(ticket, state) {
|
||||
return request({
|
||||
url: '/sso/hub/verify',
|
||||
method: 'post',
|
||||
headers: { isToken: false, repeatSubmit: false },
|
||||
data: { ticket, state }
|
||||
})
|
||||
}
|
||||
|
||||
// hub 人员目录列表:按关键字、绑定状态、人工处理状态过滤
|
||||
export function listHubUser(query) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/list',
|
||||
method: 'get',
|
||||
params: query
|
||||
})
|
||||
}
|
||||
|
||||
// 人工绑定:把 hub 人员绑定到指定本地账号
|
||||
export function bindHubUser(hubUserId, localUserId) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/bind',
|
||||
method: 'post',
|
||||
headers: { repeatSubmit: false },
|
||||
data: { hubUserId, localUserId }
|
||||
})
|
||||
}
|
||||
|
||||
// 新建并绑定:用 hub 人员信息创建本地账号并建立绑定(初始密码为系统默认密码)
|
||||
export function createBindHubUser(data) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/createBind',
|
||||
method: 'post',
|
||||
headers: { repeatSubmit: false },
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
// 解绑:本地账号回到本地密码登录
|
||||
export function unbindHubUser(localUserId) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/unbind',
|
||||
method: 'post',
|
||||
headers: { repeatSubmit: false },
|
||||
data: { localUserId }
|
||||
})
|
||||
}
|
||||
|
||||
// 忽略:目录里暂不处理的 hub 人员,备注可空
|
||||
export function ignoreHubUser(hubUserId, remark) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/ignore',
|
||||
method: 'post',
|
||||
headers: { repeatSubmit: false },
|
||||
data: { hubUserId, remark }
|
||||
})
|
||||
}
|
||||
|
||||
// 恢复:撤销忽略,重新交给同步任务自动处理
|
||||
export function restoreHubUser(hubUserId) {
|
||||
return request({
|
||||
url: '/system/hubSync/vue/restore',
|
||||
method: 'post',
|
||||
headers: { repeatSubmit: false },
|
||||
data: { hubUserId }
|
||||
})
|
||||
}
|
||||
|
||||
// 统一门户的口令要求:改密表单按它校验,不在前端写死长度与字符类别
|
||||
export function getHubPasswordPolicy() {
|
||||
return request({
|
||||
url: '/sso/hub/passwordPolicy',
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
// 已绑定统一门户的账号改密:后端调门户的服务端改密接口,前端不跳转门户
|
||||
// 未登录(登录页强制改密)需带 username + code;已登录(个人中心)由后端按会话认人
|
||||
export function changeHubPassword(data) {
|
||||
return request({
|
||||
url: '/sso/hub/password',
|
||||
method: 'post',
|
||||
headers: { isToken: false, repeatSubmit: false },
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
|
@ -15,6 +15,18 @@
|
|||
@select-partner="openSelectPartner"
|
||||
@select-related-order="openSelectRelatedOrder"
|
||||
/>
|
||||
<el-row>
|
||||
<el-col :span="8">
|
||||
<el-form-item label="订单生效时间" label-width="150px">
|
||||
<span>{{ parseTime(form.approveTime, '{y}-{m}-{d}') || '-' }}</span>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="8">
|
||||
<el-form-item label="订单最终生效时间" label-width="150px">
|
||||
<span>{{ parseTime(form.finalApproveTime, '{y}-{m}-{d}') || '-' }}</span>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="配置信息" name="config">
|
||||
|
|
|
|||
|
|
@ -122,6 +122,11 @@
|
|||
<span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="订单最终生效时间" align="center" prop="finalApproveTime" width="200">
|
||||
<template slot-scope="scope">
|
||||
<span>{{ parseTime(scope.row.finalApproveTime, '{y}-{m}-{d}') || '-' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
|
||||
<template slot-scope="scope">
|
||||
<div v-if="scope.row.showLog">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,144 @@
|
|||
<template>
|
||||
<div class="sso-hub-page">
|
||||
<div class="sso-hub-card">
|
||||
<template v-if="status === 'loading'">
|
||||
<i class="el-icon-loading sso-hub-icon" />
|
||||
<p class="sso-hub-text">正在通过统一门户登录…</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<i class="el-icon-warning-outline sso-hub-icon is-error" />
|
||||
<p class="sso-hub-text">{{ errorMessage }}</p>
|
||||
<div class="sso-hub-actions">
|
||||
<el-button v-if="hubHomeUrl" type="primary" size="small" @click="backToHub">返回统一门户</el-button>
|
||||
<el-button size="small" @click="goLocalLogin">使用账号密码登录</el-button>
|
||||
</div>
|
||||
<p class="sso-hub-tip">外部用户请使用账号密码登录;内部账号请从统一门户进入。</p>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { getHubStatus, prepareHubState, verifyHubTicket } from '@/api/system/hub'
|
||||
|
||||
const REDIRECT_WHITELIST_PREFIX = '/'
|
||||
|
||||
export default {
|
||||
name: 'SsoHub',
|
||||
data() {
|
||||
return {
|
||||
status: 'loading',
|
||||
errorMessage: '',
|
||||
hubHomeUrl: ''
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.handleLaunch()
|
||||
},
|
||||
methods: {
|
||||
async handleLaunch() {
|
||||
const query = this.$route.query || {}
|
||||
const ticket = query.ticket
|
||||
// 票据不进日志、不进埋点,这里只判断有无
|
||||
if (!ticket) {
|
||||
this.fail('缺少登录票据,请回到统一门户重新进入')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const statusRes = await getHubStatus()
|
||||
const hub = (statusRes && statusRes.data) || {}
|
||||
this.hubHomeUrl = hub.hubHomeUrl || ''
|
||||
if (!hub.loginEnabled) {
|
||||
this.fail('统一登录未启用,请使用账号密码登录')
|
||||
return
|
||||
}
|
||||
// 门户跳转不替下游生成 state,这里由本页面生成并绑定会话,验票时比对
|
||||
const state = this.buildState()
|
||||
await prepareHubState(state)
|
||||
await verifyHubTicket(ticket, state)
|
||||
// 换发本地会话成功:清掉地址栏票据,避免被历史与 Referer 带走
|
||||
this.cleanUrl()
|
||||
await this.$store.dispatch('GetInfo')
|
||||
const accessRoutes = await this.$store.dispatch('GenerateRoutes')
|
||||
this.$router.addRoutes(accessRoutes)
|
||||
this.$router.replace(this.safeRedirect(query.redirect))
|
||||
} catch (err) {
|
||||
this.cleanUrl()
|
||||
this.fail(typeof err === 'string' ? err : (err && err.message) || '统一门户登录失败,请重新进入')
|
||||
}
|
||||
},
|
||||
buildState() {
|
||||
const random = Math.random().toString(36).slice(2, 10)
|
||||
return `${Date.now().toString(36)}${random}`
|
||||
},
|
||||
// 只接受站内相对路径,且排除协议相对形式 //,防开放重定向
|
||||
safeRedirect(target) {
|
||||
if (!target || typeof target !== 'string') return '/index'
|
||||
if (!target.startsWith(REDIRECT_WHITELIST_PREFIX) || target.startsWith('//')) return '/index'
|
||||
return target
|
||||
},
|
||||
cleanUrl() {
|
||||
if (window.history && window.history.replaceState) {
|
||||
window.history.replaceState({}, document.title, window.location.pathname)
|
||||
}
|
||||
},
|
||||
fail(message) {
|
||||
this.status = 'error'
|
||||
this.errorMessage = message
|
||||
},
|
||||
backToHub() {
|
||||
window.location.href = this.hubHomeUrl
|
||||
},
|
||||
goLocalLogin() {
|
||||
this.$router.replace('/login')
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.sso-hub-page {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
|
||||
.sso-hub-card {
|
||||
width: 420px;
|
||||
padding: 40px 32px;
|
||||
text-align: center;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.sso-hub-icon {
|
||||
font-size: 40px;
|
||||
color: #409eff;
|
||||
|
||||
&.is-error {
|
||||
color: #e6a23c;
|
||||
}
|
||||
}
|
||||
|
||||
.sso-hub-text {
|
||||
margin: 16px 0 24px;
|
||||
font-size: 15px;
|
||||
color: #303133;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.sso-hub-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.sso-hub-tip {
|
||||
margin-top: 20px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,418 @@
|
|||
<template>
|
||||
<div class="app-container">
|
||||
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
|
||||
<el-form-item label="关键字" prop="keyword">
|
||||
<el-input
|
||||
v-model="queryParams.keyword"
|
||||
placeholder="门户账号 / 姓名 / 邮箱"
|
||||
clearable
|
||||
style="width: 220px"
|
||||
@keyup.enter.native="handleQuery"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="绑定状态" prop="boundState">
|
||||
<el-select v-model="queryParams.boundState" placeholder="全部" clearable style="width: 140px">
|
||||
<el-option v-for="item in boundStateOptions" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="人工处理" prop="reviewStatus">
|
||||
<el-select v-model="queryParams.reviewStatus" placeholder="全部" clearable style="width: 150px">
|
||||
<el-option v-for="item in reviewStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
|
||||
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-row :gutter="10" class="mb8">
|
||||
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
|
||||
</el-row>
|
||||
|
||||
<el-table v-loading="loading" :data="list">
|
||||
<el-table-column label="门户账号" align="center" prop="account" min-width="130" :show-overflow-tooltip="true" />
|
||||
<el-table-column label="姓名" align="center" prop="displayName" min-width="110" :show-overflow-tooltip="true" />
|
||||
<el-table-column label="邮箱" align="center" prop="email" min-width="170" :show-overflow-tooltip="true" />
|
||||
<el-table-column label="手机" align="center" prop="phone" width="120" />
|
||||
<el-table-column label="门户状态" align="center" prop="hubStatus" width="90">
|
||||
<template slot-scope="{ row }">
|
||||
<el-tag :type="hubStatusTagType(row.hubStatus)" size="mini">{{ hubStatusText(row.hubStatus) }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="在目录" align="center" prop="present" width="80">
|
||||
<template slot-scope="{ row }">
|
||||
<el-tag v-if="isPresent(row)" type="success" size="mini">是</el-tag>
|
||||
<el-tag v-else type="info" size="mini">已移除</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="绑定的本地账号" align="center" min-width="150" :show-overflow-tooltip="true">
|
||||
<template slot-scope="{ row }">
|
||||
<span v-if="row.boundLoginName">{{ row.boundLoginName }}({{ row.boundUserName }})</span>
|
||||
<span v-else class="text-muted">未绑定</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="人工处理" align="center" prop="reviewReason" width="170">
|
||||
<template slot-scope="{ row }">
|
||||
<el-tag v-if="String(row.reviewStatus) === '1'" type="warning" size="mini">{{ reviewReasonText(row.reviewReason) }}</el-tag>
|
||||
<el-tag v-else-if="String(row.reviewStatus) === '2'" type="info" size="mini">已忽略</el-tag>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近同步时间" align="center" prop="lastSyncTime" width="160">
|
||||
<template slot-scope="{ row }">
|
||||
<!-- 后端字段兼容:目录表用 lastSyncTime,旧字段 lastSeenTime 作为兜底 -->
|
||||
<span>{{ row.lastSyncTime || row.lastSeenTime || '-' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
|
||||
<template slot-scope="scope">
|
||||
<span v-if="canBind(scope.row)">
|
||||
<el-button
|
||||
size="mini"
|
||||
type="text"
|
||||
icon="el-icon-link"
|
||||
@click="handleBind(scope.row)"
|
||||
v-hasPermi="['system:hubSync:bind']"
|
||||
>绑定</el-button>
|
||||
<el-button
|
||||
size="mini"
|
||||
type="text"
|
||||
icon="el-icon-user"
|
||||
@click="handleCreateBind(scope.row)"
|
||||
v-hasPermi="['system:hubSync:create']"
|
||||
>新建并绑定</el-button>
|
||||
<el-button
|
||||
size="mini"
|
||||
type="text"
|
||||
icon="el-icon-close"
|
||||
@click="handleIgnore(scope.row)"
|
||||
v-hasPermi="['system:hubSync:ignore']"
|
||||
>忽略</el-button>
|
||||
</span>
|
||||
<el-button
|
||||
v-if="isBound(scope.row)"
|
||||
size="mini"
|
||||
type="text"
|
||||
icon="el-icon-circle-close"
|
||||
@click="handleUnbind(scope.row)"
|
||||
v-hasPermi="['system:hubSync:unbind']"
|
||||
>解绑</el-button>
|
||||
<el-button
|
||||
v-if="String(scope.row.reviewStatus) === '2'"
|
||||
size="mini"
|
||||
type="text"
|
||||
icon="el-icon-refresh-left"
|
||||
@click="handleRestore(scope.row)"
|
||||
v-hasPermi="['system:hubSync:ignore']"
|
||||
>恢复</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<pagination
|
||||
v-show="total > 0"
|
||||
:total="total"
|
||||
:page.sync="queryParams.pageNum"
|
||||
:limit.sync="queryParams.pageSize"
|
||||
@pagination="getList"
|
||||
/>
|
||||
|
||||
<!-- 绑定已有本地账号 -->
|
||||
<el-dialog title="绑定本地账号" :visible.sync="bindOpen" width="640px" append-to-body>
|
||||
<el-descriptions v-if="current" :column="2" border size="small" style="margin-bottom: 16px">
|
||||
<el-descriptions-item label="门户账号">{{ current.account }}</el-descriptions-item>
|
||||
<el-descriptions-item label="门户姓名">{{ current.displayName }}</el-descriptions-item>
|
||||
<el-descriptions-item label="门户邮箱">{{ current.email || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="门户手机号">{{ current.phone || '-' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-form size="small" :inline="true" @submit.native.prevent>
|
||||
<el-form-item label="登录账号">
|
||||
<el-input v-model="userQuery.loginName" placeholder="登录账号" clearable style="width: 160px" @keyup.enter.native="searchUsers" />
|
||||
</el-form-item>
|
||||
<el-form-item label="姓名">
|
||||
<el-input v-model="userQuery.userName" placeholder="姓名" clearable style="width: 140px" @keyup.enter.native="searchUsers" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="el-icon-search" @click="searchUsers">查询</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-table
|
||||
v-loading="userLoading"
|
||||
:data="userOptions"
|
||||
highlight-current-row
|
||||
max-height="260"
|
||||
@current-change="handleUserSelect"
|
||||
>
|
||||
<el-table-column width="46">
|
||||
<template slot-scope="{ row }">
|
||||
<el-radio v-model="selectedUserId" :label="row.userId"><span /></el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="登录账号" prop="loginName" min-width="130" />
|
||||
<el-table-column label="姓名" prop="userName" min-width="110" />
|
||||
<el-table-column label="部门" prop="dept.deptName" min-width="130" />
|
||||
<el-table-column label="已绑定门户ID" prop="hubUserId" width="120">
|
||||
<template slot-scope="{ row }">
|
||||
<el-tag v-if="row.hubUserId" type="warning" size="mini">{{ row.hubUserId }}</el-tag>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<pagination
|
||||
v-show="userTotal > 0"
|
||||
:total="userTotal"
|
||||
:page.sync="userQuery.pageNum"
|
||||
:limit.sync="userQuery.pageSize"
|
||||
@pagination="searchUsers"
|
||||
/>
|
||||
<div slot="footer" class="dialog-footer">
|
||||
<el-button type="primary" :disabled="!selectedUserId" @click="submitBind">确 定</el-button>
|
||||
<el-button @click="bindOpen = false">取 消</el-button>
|
||||
</div>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 用门户人员信息新建本地账号并绑定 -->
|
||||
<el-dialog title="新建并绑定" :visible.sync="createOpen" width="520px" append-to-body>
|
||||
<el-alert
|
||||
type="info"
|
||||
show-icon
|
||||
:closable="false"
|
||||
style="margin-bottom: 16px"
|
||||
title="初始密码为系统配置的默认密码,创建后可本地登录"
|
||||
/>
|
||||
<el-descriptions v-if="current" :column="1" border size="small" style="margin-bottom: 16px">
|
||||
<el-descriptions-item label="门户账号">{{ current.account }}</el-descriptions-item>
|
||||
<el-descriptions-item label="门户姓名">{{ current.displayName }}</el-descriptions-item>
|
||||
<el-descriptions-item label="门户邮箱">{{ current.email || '-' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-form ref="createForm" :model="createForm" :rules="createRules" label-width="90px" size="small">
|
||||
<el-form-item label="登录账号" prop="loginName">
|
||||
<el-input v-model="createForm.loginName" placeholder="请输入登录账号" maxlength="30" />
|
||||
</el-form-item>
|
||||
<el-form-item label="姓名" prop="userName">
|
||||
<el-input v-model="createForm.userName" placeholder="请输入姓名" maxlength="30" />
|
||||
</el-form-item>
|
||||
<el-form-item label="手机" prop="phonenumber">
|
||||
<el-input v-model="createForm.phonenumber" placeholder="选填" maxlength="11" />
|
||||
</el-form-item>
|
||||
<el-form-item label="邮箱" prop="email">
|
||||
<el-input v-model="createForm.email" placeholder="选填" maxlength="50" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div slot="footer" class="dialog-footer">
|
||||
<el-button type="primary" @click="submitCreateBind">确 定</el-button>
|
||||
<el-button @click="createOpen = false">取 消</el-button>
|
||||
</div>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
import { listHubUser, bindHubUser, createBindHubUser, unbindHubUser, ignoreHubUser, restoreHubUser } from '@/api/system/hub'
|
||||
import { listUser } from '@/api/system/user'
|
||||
|
||||
// 人工处理原因文案:未知值原样显示,避免后端新增原因时页面显示空白
|
||||
const REVIEW_REASON_TEXT = {
|
||||
DUPLICATE_NAME: '姓名重复无法自动绑定',
|
||||
NAME_EMPTY: '门户未提供姓名,无法自动匹配',
|
||||
CREATE_NO_LOGIN_NAME: '缺少可用登录名',
|
||||
LOGIN_NAME_TAKEN: '登录名已被占用',
|
||||
MANUAL_UNBOUND: '管理员已解绑',
|
||||
MANUAL_IGNORED: '管理员已忽略'
|
||||
}
|
||||
|
||||
export default {
|
||||
name: 'HubSync',
|
||||
data() {
|
||||
return {
|
||||
loading: false,
|
||||
showSearch: true,
|
||||
total: 0,
|
||||
list: [],
|
||||
queryParams: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
keyword: undefined,
|
||||
boundState: undefined,
|
||||
reviewStatus: undefined
|
||||
},
|
||||
// 枚举值少,直接写死,不再新增字典
|
||||
boundStateOptions: [
|
||||
{ label: '未绑定', value: '0' },
|
||||
{ label: '已绑定', value: '1' }
|
||||
],
|
||||
reviewStatusOptions: [
|
||||
{ label: '待人工确认', value: '1' },
|
||||
{ label: '已忽略', value: '2' }
|
||||
],
|
||||
// 当前操作的门户人员行
|
||||
current: null,
|
||||
bindOpen: false,
|
||||
userLoading: false,
|
||||
userOptions: [],
|
||||
userTotal: 0,
|
||||
userQuery: { loginName: '', userName: '', pageNum: 1, pageSize: 10 },
|
||||
selectedUserId: null,
|
||||
createOpen: false,
|
||||
createForm: { hubUserId: null, loginName: '', userName: '', phonenumber: '', email: '' },
|
||||
createRules: {
|
||||
loginName: [
|
||||
{ required: true, trigger: 'blur', message: '请输入登录账号' },
|
||||
{ max: 30, trigger: 'blur', message: '登录账号长度不能超过30个字符' }
|
||||
],
|
||||
userName: [
|
||||
{ required: true, trigger: 'blur', message: '请输入姓名' },
|
||||
{ max: 30, trigger: 'blur', message: '姓名长度不能超过30个字符' }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.getList()
|
||||
},
|
||||
methods: {
|
||||
getList() {
|
||||
this.loading = true
|
||||
listHubUser(this.queryParams).then(response => {
|
||||
this.list = response.rows || []
|
||||
this.total = response.total || 0
|
||||
this.loading = false
|
||||
}).catch(() => {
|
||||
this.loading = false
|
||||
})
|
||||
},
|
||||
handleQuery() {
|
||||
this.queryParams.pageNum = 1
|
||||
this.getList()
|
||||
},
|
||||
resetQuery() {
|
||||
this.queryParams = { pageNum: 1, pageSize: 10, keyword: undefined, boundState: undefined, reviewStatus: undefined }
|
||||
this.getList()
|
||||
},
|
||||
isPresent(row) {
|
||||
return String(row.present) === '1'
|
||||
},
|
||||
isBound(row) {
|
||||
return String(row.boundState) === '1' || !!row.boundUserId || !!row.boundLoginName
|
||||
},
|
||||
canBind(row) {
|
||||
return !this.isBound(row) && this.isPresent(row)
|
||||
},
|
||||
hubStatusText(status) {
|
||||
return { 0: '停用', 1: '启用', 2: '待审核', 3: '已驳回' }[status] || (status == null ? '-' : status)
|
||||
},
|
||||
hubStatusTagType(status) {
|
||||
return { 0: 'info', 1: 'success', 2: 'warning', 3: 'danger' }[status] || 'info'
|
||||
},
|
||||
reviewReasonText(reason) {
|
||||
return REVIEW_REASON_TEXT[reason] || reason || '待人工确认'
|
||||
},
|
||||
handleBind(row) {
|
||||
this.current = row
|
||||
this.selectedUserId = null
|
||||
this.userQuery.loginName = row.account || ''
|
||||
this.userQuery.userName = row.displayName || ''
|
||||
this.userQuery.pageNum = 1
|
||||
this.bindOpen = true
|
||||
this.searchUsers()
|
||||
},
|
||||
searchUsers() {
|
||||
this.userLoading = true
|
||||
// 走后端分页 + 模糊查询:全员灌入后本地账号可达数百人,前端过滤只会翻不到人
|
||||
listUser({
|
||||
pageNum: this.userQuery.pageNum,
|
||||
pageSize: this.userQuery.pageSize,
|
||||
loginName: this.userQuery.loginName || undefined,
|
||||
userName: this.userQuery.userName || undefined,
|
||||
status: '0'
|
||||
}).then(response => {
|
||||
this.userOptions = response.rows || []
|
||||
this.userTotal = response.total || 0
|
||||
this.userLoading = false
|
||||
}).catch(() => {
|
||||
this.userOptions = []
|
||||
this.userTotal = 0
|
||||
this.userLoading = false
|
||||
})
|
||||
},
|
||||
handleUserSelect(row) {
|
||||
if (row) {
|
||||
this.selectedUserId = row.userId
|
||||
}
|
||||
},
|
||||
submitBind() {
|
||||
if (!this.selectedUserId) {
|
||||
this.$modal.msgError('请选择要绑定的本地账号')
|
||||
return
|
||||
}
|
||||
bindHubUser(this.current.hubUserId, this.selectedUserId).then(() => {
|
||||
this.$modal.msgSuccess('绑定成功')
|
||||
this.bindOpen = false
|
||||
this.getList()
|
||||
})
|
||||
},
|
||||
handleCreateBind(row) {
|
||||
this.current = row
|
||||
this.createForm = {
|
||||
hubUserId: row.hubUserId,
|
||||
loginName: row.account || '',
|
||||
userName: row.displayName || '',
|
||||
phonenumber: row.phone || '',
|
||||
email: row.email || ''
|
||||
}
|
||||
this.createOpen = true
|
||||
this.$nextTick(() => {
|
||||
if (this.$refs.createForm) {
|
||||
this.$refs.createForm.clearValidate()
|
||||
}
|
||||
})
|
||||
},
|
||||
submitCreateBind() {
|
||||
this.$refs.createForm.validate(valid => {
|
||||
if (!valid) {
|
||||
return
|
||||
}
|
||||
createBindHubUser(this.createForm).then(() => {
|
||||
this.$modal.msgSuccess('创建并绑定成功')
|
||||
this.createOpen = false
|
||||
this.getList()
|
||||
})
|
||||
})
|
||||
},
|
||||
handleUnbind(row) {
|
||||
const name = row.boundLoginName || row.account
|
||||
this.$modal.confirm('解绑后 OMS 账号「' + name + '」回到本地密码登录,若本人没用过 OMS 密码请先在用户管理里重置密码,确定解绑?')
|
||||
.then(() => unbindHubUser(row.boundUserId))
|
||||
.then(() => {
|
||||
this.$modal.msgSuccess('已解绑')
|
||||
this.getList()
|
||||
})
|
||||
.catch(() => {})
|
||||
},
|
||||
handleIgnore(row) {
|
||||
this.$modal.prompt('请输入忽略原因(可留空)')
|
||||
.then(({ value }) => ignoreHubUser(row.hubUserId, value || ''))
|
||||
.then(() => {
|
||||
this.$modal.msgSuccess('已忽略')
|
||||
this.getList()
|
||||
})
|
||||
.catch(() => {})
|
||||
},
|
||||
handleRestore(row) {
|
||||
this.$modal.confirm('恢复后同步任务会重新尝试自动处理「' + (row.displayName || row.account) + '」,确定?')
|
||||
.then(() => restoreHubUser(row.hubUserId))
|
||||
.then(() => {
|
||||
this.$modal.msgSuccess('已恢复')
|
||||
this.getList()
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.text-muted {
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -83,7 +83,7 @@ hub:
|
|||
# 本系统在 hub 注册的应用编码;验票响应会回显该值用于防串号
|
||||
app-code: oms
|
||||
# 应用密钥明文,同时用于票据校验与目录导出。只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_INTEGRATION_KEY:820c8ed5c7b04b7778c84dadce03ce860451f1e0a27e01292c8a03e8941075f7}
|
||||
integration-key: ${HUB_INTEGRATION_KEY:7bda9d2b652f4497c19c8e5aa1bbc59f5c492ffe36b2a2d55d1e58916a0a8c39}
|
||||
connect-timeout-ms: 3000
|
||||
read-timeout-ms: 10000
|
||||
login:
|
||||
|
|
@ -108,7 +108,7 @@ hub:
|
|||
auto-bind-by-name: true
|
||||
# hub 侧新增的人(增量事件里出现、镜像中没有)是否自动建号并绑定。
|
||||
# 注意:全量同步不建号,首次全量匹配不上的人只留在镜像表,由管理员人工处理。
|
||||
auto-create-new: true
|
||||
auto-create-new: false
|
||||
# hub 停用是否同步停用本地账号(只停用,从不自动启用)
|
||||
disable-missing: true
|
||||
# 单批增量条数,hub 上限 500
|
||||
|
|
@ -123,4 +123,20 @@ hub:
|
|||
# H5 在 hub 注册的应用编码,用于校验验票回显防串号
|
||||
app-code: oms-wb
|
||||
# H5 的应用密钥明文,只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_H5_INTEGRATION_KEY:}
|
||||
integration-key: ${HUB_H5_INTEGRATION_KEY:6beae694fe7d8b3efbc6d8067bfa6a96cb694f3169a84510a4210711743afcab}
|
||||
# 统一 MCP 接入:方向与登录/同步相反,是 hub 拿着身份信封来调本系统。
|
||||
# MCP 服务地址沿用既有 /mcp(hub 按 home_url + /mcp 拼接),本节只管密钥接口与跨域。
|
||||
mcp:
|
||||
# 是否接受 hub 的密钥调用(POST/PUT/DELETE /dsh/mcp/keys)。关掉时接口整体回 503,
|
||||
# hub 提示「本系统尚未开启统一门户的 MCP 密钥接入」;/mcp 数据面不受本节影响。
|
||||
# 上线顺序:先执行 sql/20261203_sys_bot_credential_source.sql(补 source 列),
|
||||
# 再把本项置 true;顺序反了创建密钥会因缺列报 500。
|
||||
enabled: true
|
||||
# 轮换宽限期内保留的上一把应用密钥明文(hub 轮换后立刻用新摘要加密,本侧只有旧钥会
|
||||
# 表现为所有 hub 调用一律 401)。按 X-DSH-Auth-Kid 选钥,宽限期结束后置空即可。
|
||||
previous-integration-key: ${HUB_PREVIOUS_INTEGRATION_KEY:7bda9d2b652f4497c19c8e5aa1bbc59f5c492ffe36b2a2d55d1e58916a0a8c39}
|
||||
# 签发给门户用户的 MCP 密钥有效期天数,0 或负数表示不自动过期。
|
||||
expire-days: 365
|
||||
# MCP 数据面的跨域来源白名单(逗号分隔)。hub 不做反向代理,客户端浏览器从 hub 域名
|
||||
# 直连本系统 /mcp,不放行会表现为「MCP 连不上」。留空表示只允许同源。
|
||||
allowed-origins: 'https://hub.oa.unissense.tech'
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ spring:
|
|||
time-zone: GMT+8
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
profiles:
|
||||
active: prod
|
||||
active: dev
|
||||
# 文件上传
|
||||
servlet:
|
||||
multipart:
|
||||
|
|
@ -126,6 +126,76 @@ shiro:
|
|||
# 是否开启记住我
|
||||
enabled: true
|
||||
|
||||
# dsh-hub 统一登录与人员同步
|
||||
# enabled=false 时登录、同步、退出行为与接入 hub 之前完全一致(一键退回的逃生开关)
|
||||
hub:
|
||||
enabled: true
|
||||
# hub 站点基地址,生产必须 https,结尾不带 /
|
||||
base-url: 'http://localhost:5173'
|
||||
# base-url: 'https://hub.oa.unissense.tech'
|
||||
# 本系统在 hub 注册的应用编码;验票响应会回显该值用于防串号
|
||||
app-code: oms
|
||||
# 应用密钥明文,同时用于票据校验与目录导出。只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_INTEGRATION_KEY:d0e7ff831110c11dddcdd569028ad75bc577c8061485126900c3045c38a9bcd2}
|
||||
# integration-key: ${HUB_INTEGRATION_KEY:820c8ed5c7b04b7778c84dadce03ce860451f1e0a27e01292c8a03e8941075f7}
|
||||
connect-timeout-ms: 3000
|
||||
read-timeout-ms: 10000
|
||||
login:
|
||||
# 已绑定 hub 的内部账号提交本地 /login 时是否拒绝(外部用户不受影响)。
|
||||
# 关掉它等于允许内部人继续用本系统口令登录,统一登录形同虚设,只作应急手段。
|
||||
reject-bound-local-login: true
|
||||
# 是否允许在 OMS 登录页用统一门户账号密码直接登录。走的是 hub 的「口令代校验」
|
||||
# /api/v1/auth/password-verify(对接指南 2.8):不要门户图形验证码,人机校验仍由
|
||||
# 本系统那张验证码承担。前提是 hub 版本已含该接口,且该账号在 hub 侧已开通密码通道
|
||||
# (配 default_user_password 或让首次强制改密生效)。关掉后内部人只能从门户卡片免登进入。
|
||||
password-login-enabled: true
|
||||
# 统一门户不可达时是否允许绑定账号回退本系统口令。默认关:门户挂了内部人登不进来,
|
||||
# 需要应急时用 admin 改这里或直接把 hub.enabled 置 false。
|
||||
allow-local-fallback: false
|
||||
# 内部用户退出后是否跳转 hub 站点首页
|
||||
logout-redirect-hub: true
|
||||
directory:
|
||||
# 目录同步开关,与登录开关解耦,可先只镜像不接管登录做灰度
|
||||
enabled: true
|
||||
# 花名册条数,hub 取值 1-5000;返回被截断时会自动按上限重拉
|
||||
member-limit: 2000
|
||||
# 是否按「姓名唯一命中」自动绑定存量 OMS 账号。首次上线建议先置 false 跑一轮全量,
|
||||
# 在「hub人员目录」页核对结果后再打开;重名一律不自动绑,交人工。
|
||||
auto-bind-by-name: true
|
||||
# hub 侧新增的人(增量事件里出现、镜像中没有)是否自动建号并绑定。
|
||||
# 注意:全量同步不建号,首次全量匹配不上的人只留在镜像表,由管理员人工处理。
|
||||
auto-create-new: true
|
||||
# hub 停用是否同步停用本地账号(只停用,从不自动启用)
|
||||
disable-missing: true
|
||||
# 单批增量条数,hub 上限 500
|
||||
change-limit: 200
|
||||
# H5 审批系统在 hub 注册的第二个应用。
|
||||
# hub 的票据按应用隔离(验票会比对票据所属应用与调用方密钥),所以 H5 不能用上面那把
|
||||
# 管理端密钥验自己的票,必须在 hub 管理端单独注册一个应用并单独下发密钥。
|
||||
h5:
|
||||
# H5 免登开关(与 hub.enabled 是与关系)
|
||||
enabled: true
|
||||
# H5 在 hub 注册的应用编码,用于校验验票回显防串号
|
||||
app-code: oms-wb
|
||||
# H5 的应用密钥明文,只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_H5_INTEGRATION_KEY:87c8f848c0af6be5590636a6071b766e6ff4b455044b133fa61825b8271930d7}
|
||||
# 统一 MCP 接入:方向与上面的登录/同步相反,是 hub 拿着身份信封来调本系统。
|
||||
# MCP 服务地址沿用既有 /mcp(hub 按 home_url + /mcp 拼接),本节只负责密钥接口与跨域。
|
||||
mcp:
|
||||
# 是否接受 hub 的密钥调用(POST/DELETE /dsh/mcp/keys)。关掉时接口整体回 503,
|
||||
# hub 会提示「本系统尚未开启统一门户的 MCP 密钥接入」;/mcp 数据面不受本节影响。
|
||||
enabled: true
|
||||
# 轮换宽限期内保留的上一把应用密钥明文(hub 轮换后 hub 立刻用新摘要加密,本侧只有旧钥
|
||||
# 会表现为所有 hub 调用一律 401)。按 X-DSH-Auth-Kid 选钥,宽限期结束后置空即可。
|
||||
previous-integration-key: ${HUB_PREVIOUS_INTEGRATION_KEY:}
|
||||
# 签发给门户用户的 MCP 密钥有效期天数,0 或负数表示不自动过期。hub 只展示该时间,
|
||||
# 不会因过期自动调删除接口,这里作为本侧兜底。
|
||||
expire-days: 365
|
||||
# MCP 数据面的跨域来源白名单(逗号分隔)。hub 不做反向代理,客户端浏览器从 hub 域名
|
||||
# 直连本系统 /mcp,不放行会表现为「MCP 连不上」。留空表示只允许同源。
|
||||
# 例如:'https://hub.oa.unissense.tech'
|
||||
allowed-origins: ''
|
||||
|
||||
# 防止XSS攻击
|
||||
xss:
|
||||
# 过滤开关
|
||||
|
|
|
|||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
|
|
@ -0,0 +1,133 @@
|
|||
package com.ruoyi.common.utils.security;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* DSH-SA-v1 身份信封解密后的声明(dsh-hub 统一门户 → 业务系统的服务端到服务端调用)。
|
||||
*
|
||||
* <p>口径(对接文档 1.4):用户身份<b>只以密文传递</b>,业务系统解不出信封就没有身份可用,
|
||||
* 因此 {@link #sub} 是唯一可信的用户标识,任何明文 header 里出现的用户名都不参与判定。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public class DshEnvelopeClaim implements Serializable
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 签发方,固定 {@code dsh-hub} */
|
||||
private String issuer;
|
||||
|
||||
/** 目标应用编码,必须等于本系统在 hub 注册的 code */
|
||||
private String audience;
|
||||
|
||||
/** hub 登录账号,唯一可信的用户身份 */
|
||||
private String subject;
|
||||
|
||||
/** hub 用户ID(辅助字段,可能为空) */
|
||||
private Long userId;
|
||||
|
||||
/** 工号,hub 接入 HR 主数据后才会带,可能为空 */
|
||||
private String extId;
|
||||
|
||||
/** 本次动作,必须与被调接口约定的 action 一致 */
|
||||
private String action;
|
||||
|
||||
/** 签发时间(秒) */
|
||||
private Long issuedAt;
|
||||
|
||||
/** 过期时间(秒),有效期固定 60 秒 */
|
||||
private Long expiresAt;
|
||||
|
||||
/** 本次调用的唯一号,用于窗口内防重放 */
|
||||
private String jti;
|
||||
|
||||
public String getIssuer()
|
||||
{
|
||||
return issuer;
|
||||
}
|
||||
|
||||
public void setIssuer(String issuer)
|
||||
{
|
||||
this.issuer = issuer;
|
||||
}
|
||||
|
||||
public String getAudience()
|
||||
{
|
||||
return audience;
|
||||
}
|
||||
|
||||
public void setAudience(String audience)
|
||||
{
|
||||
this.audience = audience;
|
||||
}
|
||||
|
||||
public String getSubject()
|
||||
{
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject)
|
||||
{
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public Long getUserId()
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId)
|
||||
{
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getExtId()
|
||||
{
|
||||
return extId;
|
||||
}
|
||||
|
||||
public void setExtId(String extId)
|
||||
{
|
||||
this.extId = extId;
|
||||
}
|
||||
|
||||
public String getAction()
|
||||
{
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action)
|
||||
{
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public Long getIssuedAt()
|
||||
{
|
||||
return issuedAt;
|
||||
}
|
||||
|
||||
public void setIssuedAt(Long issuedAt)
|
||||
{
|
||||
this.issuedAt = issuedAt;
|
||||
}
|
||||
|
||||
public Long getExpiresAt()
|
||||
{
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(Long expiresAt)
|
||||
{
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public String getJti()
|
||||
{
|
||||
return jti;
|
||||
}
|
||||
|
||||
public void setJti(String jti)
|
||||
{
|
||||
this.jti = jti;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package com.ruoyi.common.utils.security;
|
||||
|
||||
/**
|
||||
* DSH-SA-v1 身份信封校验失败。
|
||||
*
|
||||
* <p>{@code message} 会被 dsh-hub <b>原样显示给最终用户</b>(对接文档 1.7),所以只写一句人能看懂的话,
|
||||
* 不带堆栈、不带异常类名;{@code error} 是给 hub 定位用的稳定错误码。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public class DshEnvelopeException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 信封解不开(密钥不对 / 结构不合法 / AAD 不匹配) */
|
||||
public static final String ERROR_INVALID_ENVELOPE = "invalid_envelope";
|
||||
|
||||
/** 信封已超过 60 秒有效期 */
|
||||
public static final String ERROR_TOKEN_EXPIRED = "token_expired";
|
||||
|
||||
/** 信封里的 action 与本接口约定的不一致 */
|
||||
public static final String ERROR_ACTION_MISMATCH = "action_mismatch";
|
||||
|
||||
/** 签发方不是 dsh-hub */
|
||||
public static final String ERROR_INVALID_ISSUER = "invalid_issuer";
|
||||
|
||||
/** 信封是发给别的应用的 */
|
||||
public static final String ERROR_INVALID_AUDIENCE = "invalid_audience";
|
||||
|
||||
private final int httpStatus;
|
||||
|
||||
private final String error;
|
||||
|
||||
public DshEnvelopeException(int httpStatus, String error, String message)
|
||||
{
|
||||
super(message);
|
||||
this.httpStatus = httpStatus;
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public int getHttpStatus()
|
||||
{
|
||||
return httpStatus;
|
||||
}
|
||||
|
||||
public String getError()
|
||||
{
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
package com.ruoyi.common.utils.security;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
|
||||
/**
|
||||
* DSH-SA-v1 服务间鉴权信封(dsh-hub → 业务系统)的解密与校验。
|
||||
*
|
||||
* <p>契约要点(对接文档第 1 章,逐项对应 {@link #open}):</p>
|
||||
* <ul>
|
||||
* <li>密钥 = 应用密钥明文的 SHA-256 <b>原始 32 字节</b>,不是十六进制文本;与 hub 侧
|
||||
* {@code secret_hash} 的字节值是同一个数,所以本系统不需要另配第二把凭据。</li>
|
||||
* <li>AAD = {@code appCode + "|" + action},少一个字符 GCM 校验就失败;这也是每张接口
|
||||
* 都必须显式声明自己 action 的原因。</li>
|
||||
* <li>GCM tag 附在密文尾部,用标准 AES-GCM 解密即可,<b>不要自己拆最后 16 字节</b>。</li>
|
||||
* <li>{@code base64url} 无填充,{@link Base64.getUrlDecoder()} 可直接接受。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>有效期固定 60 秒,时钟偏差容忍 10 秒且<b>只容忍一侧</b>:只判「已过期」,
|
||||
* 不判「签发时间在未来」——对方的钟不由我们控制,而过期是确定的事实。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public final class DshEnvelopeUtils
|
||||
{
|
||||
/** 信封头 */
|
||||
public static final String HEADER_ENVELOPE = "X-DSH-Auth";
|
||||
|
||||
/** 密钥选择头(轮换期内用哪把密钥) */
|
||||
public static final String HEADER_KID = "X-DSH-Auth-Kid";
|
||||
|
||||
/** 当前唯一版本号 */
|
||||
public static final String VERSION = "v1";
|
||||
|
||||
/** 固定签发方 */
|
||||
public static final String ISSUER = "dsh-hub";
|
||||
|
||||
/** 允许的时钟偏差(秒),与 hub 侧 mcpauth.ClockSkew 同口径 */
|
||||
private static final long CLOCK_SKEW_SECONDS = 10L;
|
||||
|
||||
/** nonce 长度(字节) */
|
||||
private static final int NONCE_BYTES = 12;
|
||||
|
||||
/** GCM tag 位数 */
|
||||
private static final int TAG_BITS = 128;
|
||||
|
||||
/** 密文上限,防止异常请求撑爆内存 */
|
||||
private static final int MAX_CIPHERTEXT_BYTES = 1 << 20;
|
||||
|
||||
/** kid 长度(摘要十六进制的前 8 个字符) */
|
||||
private static final int KID_LENGTH = 8;
|
||||
|
||||
private DshEnvelopeUtils()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* 由应用密钥明文派生 AES-256 密钥(SHA-256 摘要的原始 32 字节)。
|
||||
*
|
||||
* @param secret 密钥明文
|
||||
* @return 32 字节密钥
|
||||
*/
|
||||
public static byte[] deriveKey(String secret)
|
||||
{
|
||||
return sha256(secret);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算密钥的 {@code kid}:摘要十六进制文本的前 8 位(小写),hub 按同一规则下发。
|
||||
*
|
||||
* @param secret 密钥明文
|
||||
* @return 8 位 kid
|
||||
*/
|
||||
public static String keyId(String secret)
|
||||
{
|
||||
return toHex(sha256(secret)).substring(0, KID_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解开一个信封并完成对接文档 1.5 要求的全部校验。
|
||||
*
|
||||
* @param envelopeHeader {@code X-DSH-Auth} 头的值
|
||||
* @param secret 用来解密的应用密钥明文(调用方按 kid 选好)
|
||||
* @param appCode 本系统在 hub 注册的应用编码,同时用于 AAD 与 {@code aud} 比对
|
||||
* @param expectedAction 本接口约定的动作,同时用于 AAD 与 {@code action} 比对
|
||||
* @return 校验通过的声明,永不为 null
|
||||
* @throws DshEnvelopeException 校验不通过,携带 hub 需要的 HTTP 状态与错误码
|
||||
*/
|
||||
public static DshEnvelopeClaim open(String envelopeHeader, String secret, String appCode, String expectedAction)
|
||||
{
|
||||
if (StringUtils.isBlank(envelopeHeader))
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"统一门户的调用缺少身份信封");
|
||||
}
|
||||
if (StringUtils.isBlank(secret) || StringUtils.isBlank(appCode))
|
||||
{
|
||||
// 本系统没配好,不该让人看到「密钥无效」这种误导 hub 提示的措辞
|
||||
throw new DshEnvelopeException(503, "config_missing",
|
||||
"本系统尚未配置统一门户的对接密钥,请联系管理员");
|
||||
}
|
||||
String[] parts = envelopeHeader.trim().split("\\.");
|
||||
if (parts.length != 3 || !VERSION.equals(parts[0]))
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"统一门户的身份信封格式无法识别");
|
||||
}
|
||||
byte[] nonce;
|
||||
byte[] ciphertext;
|
||||
try
|
||||
{
|
||||
nonce = Base64.getUrlDecoder().decode(parts[1]);
|
||||
ciphertext = Base64.getUrlDecoder().decode(parts[2]);
|
||||
}
|
||||
catch (IllegalArgumentException ex)
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"统一门户的身份信封无法解析");
|
||||
}
|
||||
if (nonce.length != NONCE_BYTES || ciphertext.length == 0
|
||||
|| ciphertext.length > MAX_CIPHERTEXT_BYTES)
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"统一门户的身份信封内容不合法");
|
||||
}
|
||||
|
||||
byte[] aad = (appCode.trim() + "|" + expectedAction).getBytes(StandardCharsets.UTF_8);
|
||||
JSONObject payload;
|
||||
try
|
||||
{
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(deriveKey(secret), "AES"),
|
||||
new GCMParameterSpec(TAG_BITS, nonce));
|
||||
cipher.updateAAD(aad);
|
||||
byte[] plaintext = cipher.doFinal(ciphertext);
|
||||
payload = JSON.parseObject(new String(plaintext, StandardCharsets.UTF_8));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 解密失败绝大多数是本侧密钥没跟着轮换(对接文档 1.6),日志留证据,提示留人话
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"本系统无法解开统一门户的身份信封,通常是应用密钥已轮换而两边未同步");
|
||||
}
|
||||
if (payload == null)
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"统一门户的身份信封内容为空");
|
||||
}
|
||||
return toClaim(payload, appCode.trim(), expectedAction);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验声明字段并转成对象(对接文档 1.5 的第 2~6 步)。
|
||||
*/
|
||||
private static DshEnvelopeClaim toClaim(JSONObject payload, String appCode, String expectedAction)
|
||||
{
|
||||
DshEnvelopeClaim claim = new DshEnvelopeClaim();
|
||||
claim.setIssuer(payload.getString("iss"));
|
||||
claim.setAudience(payload.getString("aud"));
|
||||
claim.setSubject(payload.getString("sub"));
|
||||
claim.setUserId(payload.getLong("uid"));
|
||||
claim.setExtId(payload.getString("ext_id"));
|
||||
claim.setAction(payload.getString("action"));
|
||||
claim.setIssuedAt(payload.getLong("iat"));
|
||||
claim.setExpiresAt(payload.getLong("exp"));
|
||||
claim.setJti(payload.getString("jti"));
|
||||
|
||||
if (!ISSUER.equals(claim.getIssuer()))
|
||||
{
|
||||
throw new DshEnvelopeException(403, DshEnvelopeException.ERROR_INVALID_ISSUER,
|
||||
"身份信封的签发方不是统一门户");
|
||||
}
|
||||
if (!appCode.equals(StringUtils.trimToEmpty(claim.getAudience())))
|
||||
{
|
||||
throw new DshEnvelopeException(403, DshEnvelopeException.ERROR_INVALID_AUDIENCE,
|
||||
"身份信封不是发给本系统的");
|
||||
}
|
||||
if (StringUtils.isBlank(claim.getSubject()))
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"身份信封缺少用户身份");
|
||||
}
|
||||
if (claim.getExpiresAt() == null || claim.getExpiresAt() <= 0L)
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_INVALID_ENVELOPE,
|
||||
"身份信封缺少有效期");
|
||||
}
|
||||
long nowSeconds = System.currentTimeMillis() / 1000L;
|
||||
if (nowSeconds > claim.getExpiresAt() + CLOCK_SKEW_SECONDS)
|
||||
{
|
||||
throw new DshEnvelopeException(401, DshEnvelopeException.ERROR_TOKEN_EXPIRED,
|
||||
"统一门户的身份信封已过期,请重试");
|
||||
}
|
||||
if (!expectedAction.equals(claim.getAction()))
|
||||
{
|
||||
throw new DshEnvelopeException(403, DshEnvelopeException.ERROR_ACTION_MISMATCH,
|
||||
"身份信封的动作与本接口不一致");
|
||||
}
|
||||
return claim;
|
||||
}
|
||||
|
||||
private static byte[] sha256(String value)
|
||||
{
|
||||
try
|
||||
{
|
||||
return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
catch (NoSuchAlgorithmException ex)
|
||||
{
|
||||
throw new IllegalStateException("当前 JDK 不支持 SHA-256", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes)
|
||||
{
|
||||
StringBuilder builder = new StringBuilder(bytes.length * 2);
|
||||
for (byte item : bytes)
|
||||
{
|
||||
String hex = Integer.toHexString(item & 0xFF);
|
||||
if (hex.length() == 1)
|
||||
{
|
||||
builder.append('0');
|
||||
}
|
||||
builder.append(hex);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,7 @@ import com.ruoyi.framework.shiro.web.filter.LogoutFilter;
|
|||
import com.ruoyi.framework.shiro.web.filter.captcha.CaptchaValidateFilter;
|
||||
import com.ruoyi.framework.shiro.web.filter.kickout.KickoutSessionFilter;
|
||||
import com.ruoyi.framework.shiro.web.filter.mcp.McpBotAuthFilter;
|
||||
import com.ruoyi.framework.hub.HubProperties;
|
||||
import com.ruoyi.framework.shiro.web.filter.online.OnlineSessionFilter;
|
||||
import com.ruoyi.framework.shiro.web.filter.sync.SyncOnlineSessionFilter;
|
||||
import com.ruoyi.framework.shiro.web.filter.user.CustomUserFilter;
|
||||
|
|
@ -303,6 +304,14 @@ public class ShiroConfig
|
|||
// 退出 logout地址,shiro去清除session
|
||||
filterChainDefinitionMap.put("/mcp", "mcpBot");
|
||||
filterChainDefinitionMap.put("/mcp/**", "mcpBot");
|
||||
/*
|
||||
* 统一门户(dsh-hub)调用的 MCP 密钥接口:调用方是 hub 服务端,没有本系统会话,
|
||||
* 身份由 X-DSH-Auth 信封自带(AES-256-GCM,见 DshEnvelopeUtils),因此这里放行会话认证,
|
||||
* 由控制器自行判定信封。必须 anon 而不是 user:被网关/过滤器 302 到登录页时 hub 会按
|
||||
* 「3xx 视为失败」处理,表现为密钥创建莫名失败。
|
||||
*/
|
||||
filterChainDefinitionMap.put("/dsh/mcp/keys", "anon");
|
||||
filterChainDefinitionMap.put("/dsh/mcp/keys/**", "anon");
|
||||
filterChainDefinitionMap.put("/logout", "logout");
|
||||
// 不需要拦截的访问
|
||||
filterChainDefinitionMap.put("/login/resetPwd", "anon");
|
||||
|
|
@ -427,6 +436,8 @@ public class ShiroConfig
|
|||
filter.setSecurityManager(securityManager);
|
||||
filter.setRealmName(userRealm.getName());
|
||||
filter.setBotCredentialService(SpringUtils.getBean(ISysBotCredentialService.class));
|
||||
// 统一门户签发的 MCP 凭据走同一认证路径(头名与本系统原生一致),跨域白名单由 hub.mcp 配置
|
||||
filter.setHubProperties(SpringUtils.getBean(HubProperties.class));
|
||||
return filter;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ public class HubProperties
|
|||
|
||||
private H5 h5 = new H5();
|
||||
|
||||
private Mcp mcp = new Mcp();
|
||||
|
||||
public static class Login
|
||||
{
|
||||
/**
|
||||
|
|
@ -289,6 +291,92 @@ public class HubProperties
|
|||
this.h5 = h5;
|
||||
}
|
||||
|
||||
public Mcp getMcp()
|
||||
{
|
||||
return mcp;
|
||||
}
|
||||
|
||||
public void setMcp(Mcp mcp)
|
||||
{
|
||||
this.mcp = mcp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一 MCP 接入(hub 主动调用本系统,与登录/目录同步的方向相反)。
|
||||
*
|
||||
* <p>契约来自 dsh-hub《统一 MCP 与算力平台对接》第 1、2、3 章:hub 用「应用密钥摘要的原始
|
||||
* 字节」作 AES-256-GCM 密钥,把用户身份封进信封调用本系统的密钥接口;密钥主数据留在本系统,
|
||||
* hub 只保存返回结果并渲染进客户端配置。</p>
|
||||
*
|
||||
* <p>MCP 数据面路径沿用既有 {@code /mcp},本类不再配置;密钥接口路径固定
|
||||
* {@code /dsh/mcp/keys}(hub 侧可按应用覆盖,两边不一致时 hub 会收到 404)。</p>
|
||||
*/
|
||||
public static class Mcp
|
||||
{
|
||||
/** 是否接受 hub 的 MCP 密钥调用,默认关闭,配置就绪后再打开 */
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* 轮换宽限期内保留的上一把应用密钥明文。
|
||||
*
|
||||
* <p>管理员在 hub 上轮换密钥后,hub 立刻用新摘要加密(kid 也跟着变),本侧若只有旧密钥,
|
||||
* 表现是<b>所有 hub 调用一律 401</b>(对接文档 1.6)。因此允许同时配置新旧两把,
|
||||
* 按 {@code X-DSH-Auth-Kid} 选钥。宽限期结束后把本项置空即可,不需要额外的到期时间配置。</p>
|
||||
*/
|
||||
private String previousIntegrationKey = "";
|
||||
|
||||
/** 密钥有效期天数,>0 时写入 expire_time;hub 不会因过期自动回收,仅作本侧兜底 */
|
||||
private int expireDays = 365;
|
||||
|
||||
/**
|
||||
* MCP 数据面允许的跨域来源(逗号分隔,客户端浏览器直连本系统 {@code /mcp})。
|
||||
*
|
||||
* <p>hub 不做反向代理,客户端从 hub 域名发请求,因此需要显式放行;
|
||||
* 留空表示不下发 CORS 头,等同于「只有同源客户端能用」。</p>
|
||||
*/
|
||||
private String allowedOrigins = "";
|
||||
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled)
|
||||
{
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getPreviousIntegrationKey()
|
||||
{
|
||||
return previousIntegrationKey;
|
||||
}
|
||||
|
||||
public void setPreviousIntegrationKey(String previousIntegrationKey)
|
||||
{
|
||||
this.previousIntegrationKey = previousIntegrationKey;
|
||||
}
|
||||
|
||||
public int getExpireDays()
|
||||
{
|
||||
return expireDays;
|
||||
}
|
||||
|
||||
public void setExpireDays(int expireDays)
|
||||
{
|
||||
this.expireDays = expireDays;
|
||||
}
|
||||
|
||||
public String getAllowedOrigins()
|
||||
{
|
||||
return allowedOrigins;
|
||||
}
|
||||
|
||||
public void setAllowedOrigins(String allowedOrigins)
|
||||
{
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* H5 审批系统在 hub 注册的第二个应用。
|
||||
*
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import com.ruoyi.common.core.domain.entity.SysUser;
|
|||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.IpUtils;
|
||||
import com.ruoyi.common.utils.McpErrorUtils;
|
||||
import com.ruoyi.framework.hub.HubProperties;
|
||||
import com.ruoyi.system.service.ISysBotCredentialService;
|
||||
import org.apache.shiro.mgt.SecurityManager;
|
||||
import org.apache.shiro.subject.SimplePrincipalCollection;
|
||||
|
|
@ -13,34 +14,68 @@ import org.apache.shiro.util.ThreadContext;
|
|||
import org.apache.shiro.web.filter.AccessControlFilter;
|
||||
import org.apache.shiro.web.subject.WebSubject;
|
||||
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* {@code /mcp} 的机器人凭据准入(JSON-RPC 数据面)。
|
||||
*
|
||||
* <p>统一门户(dsh-hub)按 MCP 契约签发的凭据与本系统个人中心自己生成的凭据是同一形态
|
||||
* ({@code X-Bot-Id} = bot_id、{@code X-Bot-Secret} = secret,2026-12-03 起这是契约的默认头名,
|
||||
* 与本系统原生头名重合),凭据主数据都在 {@code sys_bot_credential},因此 hub 签发的 key 与
|
||||
* 本系统自建的 key 拥有完全相同的工具权限(绑定用户的角色权限),客户端配置不需要改名。</p>
|
||||
*
|
||||
* <p>两个头都不带时沿用既有行为直接放行(交给后续 Shiro 链),保证接入门户前后的调用方式并存。</p>
|
||||
*/
|
||||
public class McpBotAuthFilter extends AccessControlFilter {
|
||||
private static final String HEADER_BOT_ID = "X-Bot-Id";
|
||||
private static final String HEADER_BOT_SECRET = "X-Bot-Secret";
|
||||
|
||||
/**
|
||||
* 旧契约的默认凭据头名(dsh-hub 2026-12-03 之前),hub 按「创建时的头名」保存已签发的凭据,
|
||||
* 因此这里继续接受一次,免得改动前已建好的 key 当场 401。新签发的凭据一律用上面的新名。
|
||||
*/
|
||||
private static final String HEADER_MCP_KEY = "X-MCP-Key";
|
||||
private static final String HEADER_MCP_SECRET = "X-MCP-Secret";
|
||||
|
||||
private static final String ATTR_ERROR_MESSAGE = "mcpBotErrorMessage";
|
||||
|
||||
/** 已就地应答的跨域预检标记,置位后 onAccessDenied 不再写 401 体 */
|
||||
private static final String ATTR_PREFLIGHT_HANDLED = "mcpCorsPreflightHandled";
|
||||
|
||||
private ISysBotCredentialService botCredentialService;
|
||||
private SecurityManager securityManager;
|
||||
private String realmName;
|
||||
private HubProperties hubProperties;
|
||||
|
||||
@Override
|
||||
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
String botId = httpRequest.getHeader(HEADER_BOT_ID);
|
||||
String botSecret = httpRequest.getHeader(HEADER_BOT_SECRET);
|
||||
if (writeCorsHeaders(httpRequest, (HttpServletResponse) response)
|
||||
&& "OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
|
||||
// 命中跨域白名单的预检:不带凭据,就地以 204 结束,不进入认证。
|
||||
// 未命中白名单时保持原样交给 Spring MVC 处理,接入门户前后的 OPTIONS 行为不变。
|
||||
request.setAttribute(ATTR_PREFLIGHT_HANDLED, Boolean.TRUE);
|
||||
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NO_CONTENT);
|
||||
return false;
|
||||
}
|
||||
|
||||
String botId = firstNonBlank(httpRequest.getHeader(HEADER_BOT_ID), httpRequest.getHeader(HEADER_MCP_KEY));
|
||||
String botSecret = firstNonBlank(httpRequest.getHeader(HEADER_BOT_SECRET),
|
||||
httpRequest.getHeader(HEADER_MCP_SECRET));
|
||||
|
||||
if (isBlank(botId) && isBlank(botSecret)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isBlank(botId) || isBlank(botSecret)) {
|
||||
request.setAttribute(ATTR_ERROR_MESSAGE, "Both X-Bot-Id and X-Bot-Secret are required");
|
||||
request.setAttribute(ATTR_ERROR_MESSAGE, "MCP 调用缺少凭据,需要同时提供 X-Bot-Id 与 X-Bot-Secret");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -63,6 +98,10 @@ public class McpBotAuthFilter extends AccessControlFilter {
|
|||
@Override
|
||||
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
if (Boolean.TRUE.equals(request.getAttribute(ATTR_PREFLIGHT_HANDLED))) {
|
||||
// 预检已在 isAccessAllowed 里应答完(204 + CORS 头),不要再写错误体
|
||||
return false;
|
||||
}
|
||||
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
httpResponse.setContentType("application/json");
|
||||
httpResponse.setCharacterEncoding("UTF-8");
|
||||
|
|
@ -91,6 +130,52 @@ public class McpBotAuthFilter extends AccessControlFilter {
|
|||
this.realmName = realmName;
|
||||
}
|
||||
|
||||
public void setHubProperties(HubProperties hubProperties) {
|
||||
this.hubProperties = hubProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP 客户端由浏览器直连本系统(hub 不做反向代理,对接文档 2.4),跨域来源需要显式放开。
|
||||
*
|
||||
* <p>来源白名单为空时不下发任何 CORS 头,行为与接入门户前一致;不使用 {@code *},
|
||||
* 因为 SSE 长连接带凭据时浏览器不接受通配来源。</p>
|
||||
*
|
||||
* @return 是否已按白名单放行该 Origin(只有放行才需要替它应答预检)
|
||||
*/
|
||||
private boolean writeCorsHeaders(HttpServletRequest request, HttpServletResponse response) {
|
||||
if (hubProperties == null || hubProperties.getMcp() == null) {
|
||||
return false;
|
||||
}
|
||||
String configured = hubProperties.getMcp().getAllowedOrigins();
|
||||
if (configured == null || configured.trim().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<String> origins = Arrays.asList(configured.split(","));
|
||||
String origin = request.getHeader("Origin");
|
||||
if (isBlank(origin)) {
|
||||
return false;
|
||||
}
|
||||
for (String candidate : origins) {
|
||||
if (origin.trim().equals(candidate.trim())) {
|
||||
response.setHeader("Access-Control-Allow-Origin", origin.trim());
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setHeader("Access-Control-Allow-Headers",
|
||||
"Content-Type, Accept, Last-Event-ID, " + HEADER_BOT_ID + ", " + HEADER_BOT_SECRET + ", "
|
||||
+ HEADER_MCP_KEY + ", " + HEADER_MCP_SECRET);
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
response.setHeader("Access-Control-Max-Age", "600");
|
||||
response.setHeader("Vary", "Origin");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
response.setHeader("Vary", "Origin");
|
||||
return false;
|
||||
}
|
||||
|
||||
private String firstNonBlank(String first, String second) {
|
||||
return isBlank(first) ? second : first;
|
||||
}
|
||||
|
||||
private boolean isBlank(String value) {
|
||||
return value == null || value.trim().isEmpty();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -272,7 +272,15 @@ public class ProjectOrderInfo extends BaseEntity {
|
|||
private String deliveryStatus;
|
||||
private String signStatus;
|
||||
private String outerStatus;
|
||||
/**
|
||||
* 订单生效时间:第一次公司领导审批通过的时间,之后再次审批通过不再覆盖
|
||||
*/
|
||||
private Date approveTime;
|
||||
/**
|
||||
* 订单最终生效时间:每次公司领导审批通过都写当次时间;撤单(含撤单审批通过、直接撤单)后置空。
|
||||
* 未撤单时与 approveTime 一致。
|
||||
*/
|
||||
private Date finalApproveTime;
|
||||
private Date approveTimeStart;
|
||||
private Date approveTimeEnd;
|
||||
private BigDecimal discountFold;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,224 @@
|
|||
package com.ruoyi.sip.hub.controller;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.ruoyi.common.annotation.Anonymous;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.common.utils.security.DshEnvelopeClaim;
|
||||
import com.ruoyi.common.utils.security.DshEnvelopeException;
|
||||
import com.ruoyi.common.utils.security.DshEnvelopeUtils;
|
||||
import com.ruoyi.framework.hub.HubProperties;
|
||||
import com.ruoyi.sip.hub.service.IDshMcpKeyService;
|
||||
|
||||
/**
|
||||
* 统一 MCP 密钥接口(dsh-hub 主动调用,对接文档第 3 章)。
|
||||
*
|
||||
* <p>与登录/目录同步的方向相反:这里是 hub 拿着身份信封来找本系统要钥匙,密钥主数据留在
|
||||
* {@code sys_bot_credential},hub 只保存返回结果并渲染进客户端配置。</p>
|
||||
*
|
||||
* <p>三条必须遵守的硬约定:</p>
|
||||
* <ol>
|
||||
* <li><b>成功一律 200</b>。hub 只认 200,{@code 201}/{@code 204}/{@code 3xx} 都算失败,
|
||||
* 因此这里不用 REST 惯例,也不允许被网关重定向去登录页(故全部 {@code @Anonymous})。</li>
|
||||
* <li><b>身份只认信封</b>。请求体不含用户信息,用户由 {@code X-DSH-Auth} 解密后的 {@code sub} 决定。</li>
|
||||
* <li><b>失败返回人话</b>。{@code message} 会被 hub 原样显示给用户,不贴堆栈与异常类名。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>路径固定为 hub 的统一默认 {@code /dsh/mcp/keys};MCP 数据面本身仍是原有的 {@code /mcp},
|
||||
* 路径不变,hub 侧按默认规则拼 {@code home_url + /mcp} 即可,两侧都不需要「后缀例外」。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/dsh/mcp/keys")
|
||||
public class DshMcpKeyController
|
||||
{
|
||||
private static final Logger log = LoggerFactory.getLogger(DshMcpKeyController.class);
|
||||
|
||||
@Autowired
|
||||
private IDshMcpKeyService keyService;
|
||||
|
||||
@Autowired
|
||||
private HubProperties properties;
|
||||
|
||||
/** 创建密钥({@code action=mcp.key.create}),成功 200 + key_id + credentials */
|
||||
@Anonymous
|
||||
@PostMapping
|
||||
public ResponseEntity<Object> create(HttpServletRequest request)
|
||||
{
|
||||
if (!isEnabled())
|
||||
{
|
||||
return disabled();
|
||||
}
|
||||
try
|
||||
{
|
||||
DshEnvelopeClaim claim = openEnvelope(request, IDshMcpKeyService.ACTION_CREATE);
|
||||
return ResponseEntity.ok((Object) keyService.createKey(claim));
|
||||
}
|
||||
catch (DshEnvelopeException e)
|
||||
{
|
||||
return envelopeFailure("创建", request, e);
|
||||
}
|
||||
catch (ServiceException e)
|
||||
{
|
||||
return failure(400, "key_rejected", e.getMessage());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return unexpected("创建", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 轮换密钥({@code action=mcp.key.update});hub 一期不调用,实现先行留出契约 */
|
||||
@Anonymous
|
||||
@PutMapping("/{keyId}")
|
||||
public ResponseEntity<Object> update(@PathVariable("keyId") String keyId, HttpServletRequest request)
|
||||
{
|
||||
if (!isEnabled())
|
||||
{
|
||||
return disabled();
|
||||
}
|
||||
try
|
||||
{
|
||||
DshEnvelopeClaim claim = openEnvelope(request, IDshMcpKeyService.ACTION_UPDATE);
|
||||
return ResponseEntity.ok((Object) keyService.updateKey(claim, keyId));
|
||||
}
|
||||
catch (DshEnvelopeException e)
|
||||
{
|
||||
return envelopeFailure("轮换", request, e);
|
||||
}
|
||||
catch (ServiceException e)
|
||||
{
|
||||
return failure(400, "key_rejected", e.getMessage());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return unexpected("轮换", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 撤销密钥({@code action=mcp.key.delete});幂等,不存在也回 200 */
|
||||
@Anonymous
|
||||
@DeleteMapping("/{keyId}")
|
||||
public ResponseEntity<Object> delete(@PathVariable("keyId") String keyId, HttpServletRequest request)
|
||||
{
|
||||
if (!isEnabled())
|
||||
{
|
||||
return disabled();
|
||||
}
|
||||
try
|
||||
{
|
||||
DshEnvelopeClaim claim = openEnvelope(request, IDshMcpKeyService.ACTION_DELETE);
|
||||
keyService.deleteKey(claim, keyId);
|
||||
// hub 不读删除的响应体,但要的是 200 而不是 204
|
||||
return ResponseEntity.ok((Object) new LinkedHashMap<String, Object>());
|
||||
}
|
||||
catch (DshEnvelopeException e)
|
||||
{
|
||||
return envelopeFailure("撤销", request, e);
|
||||
}
|
||||
catch (ServiceException e)
|
||||
{
|
||||
return failure(400, "key_rejected", e.getMessage());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return unexpected("撤销", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解开身份信封。按 {@code X-DSH-Auth-Kid} 在当前密钥与轮换保留密钥之间选钥(对接文档 1.6)。
|
||||
*
|
||||
* <p>不实现选钥的后果很好认:管理员在 hub 上点「轮换密钥」,本侧所有 MCP 密钥操作立刻全 401。</p>
|
||||
*/
|
||||
private DshEnvelopeClaim openEnvelope(HttpServletRequest request, String action)
|
||||
{
|
||||
String envelope = request.getHeader(DshEnvelopeUtils.HEADER_ENVELOPE);
|
||||
String kid = StringUtils.trimToEmpty(request.getHeader(DshEnvelopeUtils.HEADER_KID));
|
||||
String appCode = properties.getAppCode();
|
||||
String current = properties.getIntegrationKey();
|
||||
String previous = properties.getMcp() == null ? null : properties.getMcp().getPreviousIntegrationKey();
|
||||
|
||||
if (StringUtils.isNotBlank(previous) && StringUtils.isNotBlank(kid)
|
||||
&& !kid.equalsIgnoreCase(DshEnvelopeUtils.keyId(current))
|
||||
&& kid.equalsIgnoreCase(DshEnvelopeUtils.keyId(previous)))
|
||||
{
|
||||
return DshEnvelopeUtils.open(envelope, previous, appCode, action);
|
||||
}
|
||||
try
|
||||
{
|
||||
return DshEnvelopeUtils.open(envelope, current, appCode, action);
|
||||
}
|
||||
catch (DshEnvelopeException e)
|
||||
{
|
||||
// kid 缺失或与两把密钥都不匹配时仍给旧钥一次机会:hub 的 kid 取的是摘要前 8 位,
|
||||
// 与本侧算不一致(例如密钥串两端多空格)不该让人直接不可用,真正的判据是 GCM 校验。
|
||||
if (DshEnvelopeException.ERROR_INVALID_ENVELOPE.equals(e.getError()) && StringUtils.isNotBlank(previous))
|
||||
{
|
||||
return DshEnvelopeUtils.open(envelope, previous, appCode, action);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 开关未开时明确拒绝(404 会被 hub 归为「无法连接/异常」,503 更能说明是本侧未启用) */
|
||||
private boolean isEnabled()
|
||||
{
|
||||
HubProperties.Mcp mcp = properties.getMcp();
|
||||
return mcp != null && mcp.isEnabled() && StringUtils.isNotBlank(properties.getIntegrationKey());
|
||||
}
|
||||
|
||||
private ResponseEntity<Object> disabled()
|
||||
{
|
||||
return failure(503, "mcp_disabled", "本系统尚未开启统一门户的 MCP 密钥接入");
|
||||
}
|
||||
|
||||
private ResponseEntity<Object> envelopeFailure(String action, HttpServletRequest request,
|
||||
DshEnvelopeException e)
|
||||
{
|
||||
log.warn("统一门户{}MCP 密钥的身份信封校验失败, status={}, error={}, kid={}", action, e.getHttpStatus(),
|
||||
e.getError(), request.getHeader(DshEnvelopeUtils.HEADER_KID));
|
||||
return failure(e.getHttpStatus(), e.getError(), e.getMessage());
|
||||
}
|
||||
|
||||
/** 失败响应形状(对接文档 1.7):{@code {"error":...,"message":...}},message 原样显示给用户 */
|
||||
private ResponseEntity<Object> failure(int status, String error, String message)
|
||||
{
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("error", error);
|
||||
body.put("message", StringUtils.isBlank(message) ? "统一门户调用本系统失败,请稍后重试" : message);
|
||||
return ResponseEntity.status(status).body((Object) body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未预期异常必须转成 5xx,不能让 {@code GlobalExceptionHandler} 接手。
|
||||
*
|
||||
* <p>它对
|
||||
* 所有异常回 {@code AjaxResult},HTTP 状态是 <b>200</b>(业务码 500 在响应体里)。
|
||||
* 对本契约这是最坏的失败面:hub 只认状态码,创建会因解析不出 {@code key_id} 报错,
|
||||
* 而撤销会被当成成功——密钥其实还在生效,却没人知道。典型触发点是
|
||||
* {@code sql/20261203_sys_bot_credential_source.sql} 没执行(缺 source 列)。
|
||||
*/
|
||||
private ResponseEntity<Object> unexpected(String action, Exception e)
|
||||
{
|
||||
log.error("统一门户{}MCP 密钥发生未预期异常", action, e);
|
||||
return failure(500, "internal_error",
|
||||
"本系统" + action + "MCP 密钥时发生异常,请联系管理员检查数据库变更脚本是否已执行");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package com.ruoyi.sip.hub.service;
|
||||
|
||||
import com.ruoyi.common.utils.security.DshEnvelopeClaim;
|
||||
import com.ruoyi.sip.hub.vo.DshMcpKeyVo;
|
||||
|
||||
/**
|
||||
* 统一 MCP 密钥契约(dsh-hub 主动调用本系统)。
|
||||
*
|
||||
* <p>职责边界(对接文档第 3 章):密钥的<b>主数据在本系统</b>——hub 不签发、不校验、也不知道
|
||||
* key 被谁用了,它只按契约调用、保存返回结果、渲染进客户端配置。因此本服务是这把钥匙的
|
||||
* 唯一权威源,与个人中心自己生成的 bot 凭据同表同源。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public interface IDshMcpKeyService
|
||||
{
|
||||
/** 创建动作(AAD 与 {@code action} 都用它,对接文档 1.3、3.1) */
|
||||
String ACTION_CREATE = "mcp.key.create";
|
||||
|
||||
/** 更新/轮换动作,hub 一期不调用,实现先行留出契约 */
|
||||
String ACTION_UPDATE = "mcp.key.update";
|
||||
|
||||
/** 删除/撤销动作 */
|
||||
String ACTION_DELETE = "mcp.key.delete";
|
||||
|
||||
/**
|
||||
* 为信封里的用户创建一把 MCP 密钥。
|
||||
*
|
||||
* @param claim 已通过校验的身份信封声明,只认 {@code sub}
|
||||
* @return 契约响应({@code key_id} + 两个凭据 + 可选过期时间)
|
||||
*/
|
||||
DshMcpKeyVo createKey(DshEnvelopeClaim claim);
|
||||
|
||||
/**
|
||||
* 轮换(一期 hub 不调用):为同一个用户重新签发一把,语义等同创建新密钥。
|
||||
*
|
||||
* @param claim 身份信封声明
|
||||
* @param keyId 路径里的密钥标识,与本系统不一致时直接拒绝
|
||||
* @return 契约响应
|
||||
*/
|
||||
DshMcpKeyVo updateKey(DshEnvelopeClaim claim, String keyId);
|
||||
|
||||
/**
|
||||
* 撤销一把密钥,必须幂等:不存在或已撤销同样按成功返回(对接文档 3.3)。
|
||||
*
|
||||
* @param claim 身份信封声明
|
||||
* @param keyId 路径里的密钥标识
|
||||
*/
|
||||
void deleteKey(DshEnvelopeClaim claim, String keyId);
|
||||
}
|
||||
|
|
@ -0,0 +1,247 @@
|
|||
package com.ruoyi.sip.hub.service.impl;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.ruoyi.common.constant.UserConstants;
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.common.utils.security.DshEnvelopeClaim;
|
||||
import com.ruoyi.framework.hub.HubProperties;
|
||||
import com.ruoyi.sip.hub.domain.SysHubUser;
|
||||
import com.ruoyi.sip.hub.mapper.SysHubUserMapper;
|
||||
import com.ruoyi.sip.hub.service.IDshMcpKeyService;
|
||||
import com.ruoyi.sip.hub.vo.DshMcpCredentialVo;
|
||||
import com.ruoyi.sip.hub.vo.DshMcpKeyVo;
|
||||
import com.ruoyi.system.domain.SysBotCredential;
|
||||
import com.ruoyi.system.mapper.SysUserMapper;
|
||||
import com.ruoyi.system.service.ISysBotCredentialService;
|
||||
|
||||
/**
|
||||
* 统一 MCP 密钥契约实现。
|
||||
*
|
||||
* <p>认人只有一条路:信封里的 {@code sub}(hub 登录账号)与 {@code uid}(hub 用户ID),
|
||||
* 最终落到 {@code sys_user.hub_user_id} 这一处绑定关系(ADR-0015)。hub 的密钥接口
|
||||
* 不走 Shiro 会话,所以这里必须自己完成「门户账号 → 本地账号」的换算,且<b>绝不接受</b>
|
||||
* 明文 header 提供的身份。</p>
|
||||
*
|
||||
* <p>签发的凭据与个人中心自己生成的 bot 凭据同表同算法,因此 hub 的 key 一拿到就能直接
|
||||
* 调 {@code /mcp},工具权限等于该绑定用户的角色权限,不需要第二套授权模型。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
@Service
|
||||
public class DshMcpKeyServiceImpl implements IDshMcpKeyService
|
||||
{
|
||||
private static final Logger log = LoggerFactory.getLogger(DshMcpKeyServiceImpl.class);
|
||||
|
||||
/**
|
||||
* 契约默认凭据头名(对接文档 2.3,2026-12-03 起就是 {@code X-Bot-Id} / {@code X-Bot-Secret}),
|
||||
* 与本系统原生头名同名,因此门户签发的钥匙和个人中心自己生成的钥匙连请求头都不用换。
|
||||
*
|
||||
* <p>仍然显式返回而不是留空让 hub 回填:hub 只把「没带 header 名」的凭据按<b>它当前配置的</b>
|
||||
* 默认名回填,一旦 hub 管理员改了统一头名,客户端就会带着本系统不认识的头来连。</p>
|
||||
*/
|
||||
private static final String HEADER_BOT_ID = "X-Bot-Id";
|
||||
|
||||
private static final String HEADER_BOT_SECRET = "X-Bot-Secret";
|
||||
|
||||
/** hub 侧展示用的过期时间格式:ISO8601 UTC,例如 2027-12-02T00:00:00Z */
|
||||
private static final DateTimeFormatter ISO_UTC = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.of("UTC"));
|
||||
|
||||
@Autowired
|
||||
private ISysBotCredentialService botCredentialService;
|
||||
|
||||
@Autowired
|
||||
private SysUserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
private SysHubUserMapper hubUserMapper;
|
||||
|
||||
@Autowired
|
||||
private HubProperties properties;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public DshMcpKeyVo createKey(DshEnvelopeClaim claim)
|
||||
{
|
||||
SysUser user = requireBoundUser(claim);
|
||||
Map<String, Object> issued = botCredentialService.createHubCredential(user, resolveExpireTime(),
|
||||
claim.getSubject());
|
||||
|
||||
DshMcpKeyVo vo = new DshMcpKeyVo();
|
||||
vo.setKeyId(String.valueOf(issued.get("botId")));
|
||||
vo.setCredentials(Arrays.asList(
|
||||
new DshMcpCredentialVo(HEADER_BOT_ID, vo.getKeyId()),
|
||||
new DshMcpCredentialVo(HEADER_BOT_SECRET, String.valueOf(issued.get("botSecret")))));
|
||||
vo.setExpiresAt(formatUtc((Date) issued.get("expireTime")));
|
||||
log.info("统一门户为 hub 用户 {} 创建 MCP 密钥, keyId={}, localUserId={}", claim.getSubject(), vo.getKeyId(),
|
||||
user.getUserId());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public DshMcpKeyVo updateKey(DshEnvelopeClaim claim, String keyId)
|
||||
{
|
||||
// 一期 hub 没有「轮换」动作,这里按「先撤销旧的、再发新的」实现,
|
||||
// 语义与用户撤销后重新创建一致,hub 之后接上无需本侧改动。
|
||||
requireExistingHubKey(keyId);
|
||||
deleteKey(claim, keyId);
|
||||
return createKey(claim);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteKey(DshEnvelopeClaim claim, String keyId)
|
||||
{
|
||||
SysBotCredential credential = botCredentialService.selectByBotId(keyId);
|
||||
if (credential == null)
|
||||
{
|
||||
// 幂等(对接文档 3.3):hub 的删除走异步重试队列,「已经没了」必须算成功,
|
||||
// 否则队列会永远重试不完。
|
||||
log.info("统一门户撤销的 MCP 密钥不存在,按幂等成功处理, keyId={}, subject={}", keyId, claim.getSubject());
|
||||
return;
|
||||
}
|
||||
if (!SysBotCredential.SOURCE_HUB.equals(credential.getSource()))
|
||||
{
|
||||
// 个人中心自己生成的钥匙不归 hub 回收;回 4xx 让运维看得见,而不是静默删掉别人的钥匙
|
||||
throw new ServiceException("该密钥不是统一门户签发的,请在 OMS 个人中心管理");
|
||||
}
|
||||
if (!isOwnershipConsistent(credential, claim))
|
||||
{
|
||||
log.warn("统一门户撤销的 MCP 密钥归属与信封用户不一致, keyId={}, keyUserId={}, subject={}", keyId,
|
||||
credential.getUserId(), claim.getSubject());
|
||||
}
|
||||
botCredentialService.revokeHubCredentialByBotId(keyId, claim.getSubject());
|
||||
log.info("统一门户已撤销 MCP 密钥, keyId={}, subject={}", keyId, claim.getSubject());
|
||||
}
|
||||
|
||||
/**
|
||||
* 只允许吊销本系统签发的 hub 密钥,其它情况一律拒绝,避免误删本地凭据。
|
||||
*/
|
||||
private SysBotCredential requireExistingHubKey(String keyId)
|
||||
{
|
||||
SysBotCredential credential = botCredentialService.selectByBotId(keyId);
|
||||
if (credential == null || !SysBotCredential.SOURCE_HUB.equals(credential.getSource()))
|
||||
{
|
||||
throw new ServiceException("要轮换的密钥不存在或不是统一门户签发的");
|
||||
}
|
||||
return credential;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把信封身份换成本地账号。
|
||||
*
|
||||
* <p>先按 {@code uid} 直查绑定(最可靠,绑定关系就是它),查不到再按 {@code sub} 走目录镜像
|
||||
* 反查,兼容 hub 未带 uid 或镜像与绑定尚未跑齐的情况。<b>两条路都不通就拒绝</b>:
|
||||
* 宁可让人去绑定,也不能把一把能查订单数据的钥匙发给不认识的人。</p>
|
||||
*/
|
||||
private SysUser requireBoundUser(DshEnvelopeClaim claim)
|
||||
{
|
||||
if (claim.getUserId() != null)
|
||||
{
|
||||
SysUser byHubId = userMapper.selectUserByHubUserId(claim.getUserId());
|
||||
if (byHubId != null)
|
||||
{
|
||||
return requireUsableUser(byHubId, claim);
|
||||
}
|
||||
}
|
||||
SysUser byAccount = findUserByHubAccount(claim.getSubject());
|
||||
if (byAccount != null)
|
||||
{
|
||||
return requireUsableUser(byAccount, claim);
|
||||
}
|
||||
throw new ServiceException("统一门户账号尚未绑定 OMS 账号,请联系管理员在「hub人员目录」完成绑定后重试");
|
||||
}
|
||||
|
||||
/**
|
||||
* 按门户账号反查绑定的本地账号;镜像不唯一命中或本人被标记忽略时都不认。
|
||||
*/
|
||||
private SysUser findUserByHubAccount(String account)
|
||||
{
|
||||
if (StringUtils.isBlank(account))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
List<SysHubUser> hits = hubUserMapper.selectHubUserByAccount(account.trim());
|
||||
if (hits.size() != 1)
|
||||
{
|
||||
if (hits.size() > 1)
|
||||
{
|
||||
log.warn("门户账号 {} 在镜像表命中 {} 行,无法唯一认人", account, hits.size());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
SysHubUser mirror = hits.get(0);
|
||||
if (SysHubUser.REVIEW_IGNORED.equals(mirror.getReviewStatus()))
|
||||
{
|
||||
log.info("门户账号 {} 已被管理员忽略,不发放 MCP 密钥", account);
|
||||
return null;
|
||||
}
|
||||
if (mirror.getBoundUserId() == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return userMapper.selectUserById(mirror.getBoundUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用/删除的账号不发放密钥:hub 的停用回收是异步的,这里再兜一层,
|
||||
* 免得回收还没跑到人已经拿到了新钥匙。
|
||||
*/
|
||||
private SysUser requireUsableUser(SysUser user, DshEnvelopeClaim claim)
|
||||
{
|
||||
if (!UserConstants.NORMAL.equals(user.getStatus()) || !"0".equals(user.getDelFlag()))
|
||||
{
|
||||
throw new ServiceException("该门户账号绑定的 OMS 账号已停用,请联系管理员");
|
||||
}
|
||||
log.debug("统一门户身份已认定, subject={}, uid={}, localUserId={}", claim.getSubject(), claim.getUserId(),
|
||||
user.getUserId());
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 密钥归属是否与信封一致(只用于留痕,不据此拒绝):hub 的删除按 key_id 定位,
|
||||
* 人在 hub 侧被改绑过本地账号时归属会自然错位,此时以 key_id 为准继续回收。
|
||||
*/
|
||||
private boolean isOwnershipConsistent(SysBotCredential credential, DshEnvelopeClaim claim)
|
||||
{
|
||||
if (claim.getUserId() == null || credential.getUserId() == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
SysUser bound = userMapper.selectUserById(credential.getUserId());
|
||||
return bound != null && claim.getUserId().equals(bound.getHubUserId());
|
||||
}
|
||||
|
||||
/** 按配置算过期时间;配置成 0 或负数表示不自动过期 */
|
||||
private Date resolveExpireTime()
|
||||
{
|
||||
int days = properties.getMcp() == null ? 0 : properties.getMcp().getExpireDays();
|
||||
if (days <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.add(Calendar.DAY_OF_MONTH, days);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
private String formatUtc(Date date)
|
||||
{
|
||||
return date == null ? null : ISO_UTC.format(date.toInstant());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package com.ruoyi.sip.hub.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* hub MCP 密钥契约里的一条凭据(对接文档 3.2 的 {@code credentials[]})。
|
||||
*
|
||||
* <p>{@code header} 决定客户端连接 MCP 地址时带头的名字;显式写出而不是留空让 hub
|
||||
* 按默认名回填,是为了让「本系统实际校验哪两个头」在契约里自证,不依赖 hub 的配置。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
@Data
|
||||
public class DshMcpCredentialVo
|
||||
{
|
||||
/** 凭据名,本系统固定用 {@code X-Bot-Id} / {@code X-Bot-Secret}(与本系统原生头名一致) */
|
||||
private String header;
|
||||
|
||||
/** 凭据明文,hub 保存后渲染进客户端配置 */
|
||||
private String value;
|
||||
|
||||
public DshMcpCredentialVo()
|
||||
{
|
||||
}
|
||||
|
||||
public DshMcpCredentialVo(String header, String value)
|
||||
{
|
||||
this.header = header;
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package com.ruoyi.sip.hub.vo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* hub MCP 密钥接口的成功响应(对接文档 3.2)。
|
||||
*
|
||||
* <p>字段名即契约,hub 不做名字映射,因此下划线写法用 {@link JsonProperty} 显式固定;
|
||||
* hub 只把 HTTP 200 当成功,状态码由控制器决定。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
@Data
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class DshMcpKeyVo
|
||||
{
|
||||
/**
|
||||
* 密钥在本系统的稳定标识,hub 用它定位并拼进 URL 路径。
|
||||
*
|
||||
* <p>hub 强制 {@code ^[A-Za-z0-9_\-\.]{1,64}$},本系统的 bot_id 天然是 {@code 前缀_32位十六进制},
|
||||
* 不含斜杠与中文,直接复用可保证「hub 手里的 key_id」与「本系统的凭据」一一对应。</p>
|
||||
*/
|
||||
@JsonProperty("key_id")
|
||||
private String keyId;
|
||||
|
||||
/** 客户端连接 MCP 地址时要带的凭据 */
|
||||
private List<DshMcpCredentialVo> credentials;
|
||||
|
||||
/** 过期时间(ISO8601 UTC),hub 只做展示,不会因过期自动回收 */
|
||||
@JsonProperty("expires_at")
|
||||
private String expiresAt;
|
||||
}
|
||||
|
|
@ -6,13 +6,15 @@ import org.springframework.stereotype.Component;
|
|||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* MCP 层限流:同一机器人(同 X-Bot-Id,无凭证时按匿名/绑定用户)每 {@value #WINDOW_MS} 毫秒最多 {@value #LIMIT} 次调用。
|
||||
* MCP 层限流:同一机器人(同 X-Bot-Id,旧契约凭据为 X-MCP-Key;无凭证时按匿名/绑定用户)
|
||||
* 每 {@value #WINDOW_MS} 毫秒最多 {@value #LIMIT} 次调用。
|
||||
*
|
||||
* <p>实现为进程内滑动窗口(项目未引入 Redis,故不落地"状态存 Redis"的原始设计),
|
||||
* 目的是防止 Agent 循环翻页 / 并发调用打满 Druid 连接池(maxActive=20)。
|
||||
|
|
@ -22,6 +24,10 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
public class McpRateLimiter {
|
||||
|
||||
private static final String HEADER_BOT_ID = "X-Bot-Id";
|
||||
|
||||
/** 旧统一 MCP 契约的密钥头名(dsh-hub 2026-12-03 之前的默认名,与 McpBotAuthFilter 对齐) */
|
||||
private static final String HEADER_MCP_KEY = "X-MCP-Key";
|
||||
|
||||
/** 窗口内允许的最大调用次数 */
|
||||
private static final int LIMIT = 60;
|
||||
/** 滑动窗口长度(毫秒) */
|
||||
|
|
@ -74,11 +80,11 @@ public class McpRateLimiter {
|
|||
}
|
||||
|
||||
/**
|
||||
* 限流身份:优先机器人凭证标识(与 McpBotAuthFilter 的 X-Bot-Id 对齐),
|
||||
* 限流身份:优先机器人凭证标识(与 McpBotAuthFilter 一致,X-Bot-Id 优先,兼容旧契约 X-MCP-Key),
|
||||
* 无凭证时退回绑定的 Shiro 用户,再退回匿名。
|
||||
*/
|
||||
private String resolveKey() {
|
||||
String botId = currentBotId();
|
||||
String botId = currentCredentialId();
|
||||
if (botId != null) {
|
||||
return "bot:" + botId;
|
||||
}
|
||||
|
|
@ -92,15 +98,21 @@ public class McpRateLimiter {
|
|||
return "anonymous";
|
||||
}
|
||||
|
||||
private String currentBotId() {
|
||||
private String currentCredentialId() {
|
||||
try {
|
||||
ServletRequestAttributes attributes =
|
||||
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return null;
|
||||
}
|
||||
String botId = attributes.getRequest().getHeader(HEADER_BOT_ID);
|
||||
return botId == null || botId.trim().isEmpty() ? null : botId.trim();
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
for (String header : new String[] { HEADER_BOT_ID, HEADER_MCP_KEY }) {
|
||||
String value = request.getHeader(header);
|
||||
if (value != null && !value.trim().isEmpty()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,229 @@
|
|||
package com.ruoyi.sip.llm.tools;
|
||||
|
||||
import com.ruoyi.sip.llm.tools.support.AbstractMcpQueryToolProvider;
|
||||
import com.ruoyi.sip.llm.tools.support.McpAuth;
|
||||
import com.ruoyi.sip.llm.tools.support.McpCursor;
|
||||
import com.ruoyi.sip.llm.tools.support.McpFormat;
|
||||
import com.ruoyi.sip.llm.tools.support.McpPages;
|
||||
import com.ruoyi.sip.llm.tools.support.McpParams;
|
||||
import com.ruoyi.sip.llm.tools.support.McpTimeRange;
|
||||
import com.ruoyi.sip.mapper.ProjectOrderInfoLogMapper;
|
||||
import com.ruoyi.sip.vo.ProjectOrderInfoLogVo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* MCP 工具 project_order_info_log(订单审批历史快照查询,<b>只读</b>,游标分页)。
|
||||
*
|
||||
* <p><b>数据是什么</b>:{@code project_order_info_log} 是订单的<b>整行历史快照</b>,不是 JSON、不是 diff。
|
||||
* 写入方只有两处:①「公司领导审批通过」{@code ProjectOrderInfoServiceImpl#handleCompanyLeaderApproval}
|
||||
* 调 {@code ProjectOrderInfoMapper#bakData};②「撤单审批通过」{@code ExecutionTrackServiceImpl}
|
||||
* 在撤单状态落库后补一次 {@code bakData}。因此同一个 order_code 每审批通过一次留一条、每撤单通过一次留一条,
|
||||
* 按时间倒序就是「这个单的审批历史版本线」。表无 {@code del_flag},快照不可变更。</p>
|
||||
*
|
||||
* <p><b>为什么直连 Mapper、不经 Service</b>:该表全仓库只有写路径、没有任何读路径,也没有对应 Service 层;
|
||||
* 本工具只做只读查询,不引入业务写操作,故直接复用为本次查询新建的
|
||||
* {@link ProjectOrderInfoLogMapper}(仅 SELECT),不为空壳强造 Service 层。</p>
|
||||
*
|
||||
* <p><b>性能约束</b>:该表原本除自增主键 {@code bak_id} 外零索引,所以 {@code order_code} 为<b>强制</b>入参,
|
||||
* 与 {@code sql/20261203_order_final_approve_time.sql} 新增的 {@code idx_order_code_create_time(order_code, create_time)}
|
||||
* 配套:等值命中 {@code order_code} 后按索引反向扫描即可满足 {@code order by create_time desc, bak_id desc},
|
||||
* 单订单快照通常个位数条,不触达 MCP 查询超时上限。索引未建前该查询是全表扫描,属已知风险。</p>
|
||||
*
|
||||
* <p><b>鉴权</b>:入口 {@code McpController} 无 {@code @RequiresPermissions},先由
|
||||
* {@code McpBotAuthFilter} 用机器人凭证绑定 SysUser,再由本工具显式
|
||||
* {@link McpAuth#requireAnyPermission} 校验 {@code project:order:list} / {@code project:order:approve}
|
||||
* (与订单页面接口一致),权限不足抛 AUTH_ERROR 而不是返回空列表。</p>
|
||||
*
|
||||
* <p><b>不新增 HTTP 业务接口</b>:只挂 MCP 工具,不改 Controller。</p>
|
||||
*
|
||||
* @author ai-context
|
||||
* @date 2026-12-03
|
||||
*/
|
||||
@Component
|
||||
public class ProjectOrderInfoLogToolProvider extends AbstractMcpQueryToolProvider {
|
||||
|
||||
/** 排序表达式,与 Mapper XML 的 order by 保持一致 */
|
||||
private static final String SORT_BY = "create_time desc, bak_id desc";
|
||||
|
||||
@Autowired
|
||||
private ProjectOrderInfoLogMapper projectOrderInfoLogMapper;
|
||||
|
||||
@Override
|
||||
protected String getToolName() {
|
||||
return "project_order_info_log";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getToolDescription() {
|
||||
return "订单审批历史快照查询(只读,按订单号查询)。project_order_info_log 是订单审批通过时的整行历史快照:"
|
||||
+ "每次公司领导审批通过和撤单审批通过各留一条快照,同一 order_code 按时间倒序即该订单的审批版本线,"
|
||||
+ "可回答“这单上次审批通过时金额/状态是多少”“撤单前的快照长什么样”。"
|
||||
+ "必须传 order_code(合同编号,等值匹配);可选 create_time_start/create_time_end 按快照时间区间收窄。"
|
||||
+ "注意:快照列为审批当时 project_order_info 的原样副本,create_time/update_time 不是快照落库时间;"
|
||||
+ "为保护隐私不返回电话/邮箱/收货地址类字段。"
|
||||
+ "分页查询工具:若返回 page_info.has_more 为 true,必须携带 page_info.next_cursor 继续调用直到 "
|
||||
+ "has_more 为 false,否则数据不完整。";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, Object> buildInputSchema() {
|
||||
Map<String, Object> properties = new LinkedHashMap<>();
|
||||
properties.put("order_code", stringProperty("合同编号(必填,等值匹配,自动 trim;该表无索引时按此列走 "
|
||||
+ "idx_order_code_create_time 索引,缺失会退化为全表扫描,故强制要求)"));
|
||||
properties.put("create_time_start", stringProperty("快照时间区间开始(可选),格式 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss,左闭"));
|
||||
properties.put("create_time_end", stringProperty("快照时间区间结束(可选),格式 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss,右开;"
|
||||
+ "只写到天时按“含当天”处理"));
|
||||
withPagingProperties(properties, McpPages.MAX_LIST_PAGE_SIZE, McpPages.DEFAULT_PAGE_SIZE);
|
||||
return objectSchema(properties, "order_code");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object handle(Map<String, Object> params) {
|
||||
String orderCode = McpParams.requireStr(params, "order_code");
|
||||
// 权限来源见类注释(订单列表 / 审批入口接口权限,任意一个满足即放行;不足直接 AUTH_ERROR)
|
||||
McpAuth.requireAnyPermission("project:order:list", "project:order:approve");
|
||||
|
||||
// 默认不设时间窗:order_code 等值已足够收敛,区间仅作可选收窄(跨度不限制)
|
||||
McpTimeRange range = McpParams.timeRange(params, "create_time", 0, 0);
|
||||
int pageSize = McpPages.pageSize(params, McpPages.DEFAULT_PAGE_SIZE, McpPages.MAX_LIST_PAGE_SIZE);
|
||||
|
||||
String filterHash = McpParams.filterHash(getToolName(), orderCode, McpParams.describe(range));
|
||||
McpCursor cursor = McpPages.cursor(params, getToolName(), filterHash, McpPages.DEFAULT_LIST_MAX_PAGES);
|
||||
int pageNo = cursor == null ? 1 : cursor.getP();
|
||||
int offset = (pageNo - 1) * pageSize;
|
||||
|
||||
Map<String, Object> q = new HashMap<>();
|
||||
q.put("orderCode", orderCode);
|
||||
q.put("startTime", range.getStart());
|
||||
q.put("endTime", range.getEnd());
|
||||
q.put("limit", pageSize + 1);
|
||||
q.put("offset", offset);
|
||||
|
||||
List<ProjectOrderInfoLogVo> rows = projectOrderInfoLogMapper.listOrderLogPage(q);
|
||||
boolean hasMore = McpPages.hasMore(rows, pageSize);
|
||||
List<ProjectOrderInfoLogVo> page = McpPages.trim(rows, pageSize);
|
||||
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
List<String> lastSortKeys = null;
|
||||
for (ProjectOrderInfoLogVo row : page) {
|
||||
items.add(toItem(row));
|
||||
}
|
||||
if (!page.isEmpty()) {
|
||||
ProjectOrderInfoLogVo last = page.get(page.size() - 1);
|
||||
lastSortKeys = keysOf(McpFormat.dateTime(last.getCreateTime()), last.getBakId());
|
||||
}
|
||||
|
||||
q.remove("limit");
|
||||
q.remove("offset");
|
||||
long total = projectOrderInfoLogMapper.countOrderLogPage(q);
|
||||
|
||||
Map<String, Object> pageInfo = McpPages.pageInfo(items.size(), pageSize, hasMore,
|
||||
hasMore ? McpCursor.encode(getToolName(), filterHash, pageNo + 1, lastSortKeys) : null,
|
||||
SORT_BY, pageNo, total, false, false);
|
||||
|
||||
Map<String, Object> query = new LinkedHashMap<>();
|
||||
query.put("order_code", orderCode);
|
||||
query.put("time_field", "create_time");
|
||||
query.put("time_range", McpParams.describe(range));
|
||||
query.put("page_size", pageSize);
|
||||
query.put("page_no", pageNo);
|
||||
|
||||
return response(buildMetadata(orderCode), query, listData(items, pageInfo, total));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 行映射
|
||||
|
||||
/**
|
||||
* VO -> 出参:显式列字段(不做全字段透传),日期统一格式化,编码类字段统一 trim。
|
||||
*/
|
||||
private Map<String, Object> toItem(ProjectOrderInfoLogVo row) {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("bakId", row.getBakId());
|
||||
item.put("id", row.getId());
|
||||
item.put("projectId", row.getProjectId());
|
||||
item.put("orderCode", McpFormat.trim(row.getOrderCode()));
|
||||
item.put("versionCode", McpFormat.trim(row.getVersionCode()));
|
||||
item.put("province", row.getProvince());
|
||||
item.put("city", row.getCity());
|
||||
item.put("orderType", row.getOrderType());
|
||||
item.put("orderStatus", row.getOrderStatus());
|
||||
item.put("rebackApproveStatus", row.getRebackApproveStatus());
|
||||
item.put("deliveryStatus", row.getDeliveryStatus());
|
||||
item.put("signStatus", row.getSignStatus());
|
||||
item.put("outerStatus", row.getOuterStatus());
|
||||
item.put("processType", row.getProcessType());
|
||||
item.put("processTemplate", row.getProcessTemplate());
|
||||
item.put("orderChannel", row.getOrderChannel());
|
||||
item.put("companyDelivery", row.getCompanyDelivery());
|
||||
item.put("currencyType", row.getCurrencyType());
|
||||
item.put("shipmentAmount", McpFormat.decimal(row.getShipmentAmount()));
|
||||
item.put("actualPurchaseAmount", McpFormat.decimal(row.getActualPurchaseAmount()));
|
||||
item.put("discountFold", McpFormat.decimal(row.getDiscountFold()));
|
||||
item.put("approveTime", McpFormat.dateTime(row.getApproveTime()));
|
||||
item.put("finalApproveTime", McpFormat.dateTime(row.getFinalApproveTime()));
|
||||
item.put("orderEndTime", McpFormat.dateTime(row.getOrderEndTime()));
|
||||
item.put("deliveryTime", McpFormat.dateTime(row.getDeliveryTime()));
|
||||
item.put("duty", row.getDuty());
|
||||
item.put("dutyPhone", row.getDutyPhone());
|
||||
item.put("businessPerson", row.getBusinessPerson());
|
||||
item.put("notifier", row.getNotifier());
|
||||
item.put("notifierPhone", row.getNotifierPhone());
|
||||
item.put("partnerUserName", row.getPartnerUserName());
|
||||
item.put("partnerCode", McpFormat.trim(row.getPartnerCode()));
|
||||
item.put("supplier", row.getSupplier());
|
||||
item.put("remark", row.getRemark());
|
||||
item.put("operationVersion", row.getOperationVersion());
|
||||
item.put("createBy", row.getCreateBy());
|
||||
item.put("createTime", McpFormat.dateTime(row.getCreateTime()));
|
||||
item.put("updateBy", row.getUpdateBy());
|
||||
item.put("updateTime", McpFormat.dateTime(row.getUpdateTime()));
|
||||
return item;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 元数据
|
||||
|
||||
private Map<String, Object> buildMetadata(String orderCode) {
|
||||
Map<String, Object> metadata = metadata("订单审批历史快照(project_order_info_log)只读查询,按合同编号 "
|
||||
+ orderCode + " 的整行快照列表,排序 " + SORT_BY + "。");
|
||||
metadata.put("snapshot_semantics", mapData(
|
||||
"写入时机", "公司领导审批通过(ProjectOrderInfoServiceImpl#handleCompanyLeaderApproval)与撤单审批通过"
|
||||
+ "(ExecutionTrackServiceImpl 撤单完成后补快照)各调用一次 bakData",
|
||||
"快照内容", "project_order_info 的整行 INSERT ... SELECT 副本(非 JSON、非 diff、不含产品行明细)",
|
||||
"时间口径", "create_time / update_time 是快照原样复制的订单时间,不是快照落库时间;"
|
||||
+ "排序用 create_time,同秒多条用 bak_id 兜底",
|
||||
"不可变更", "快照表无 del_flag,写入后不更新,可用于对比“当时是什么状态”"));
|
||||
metadata.put("permission_source", "VueProjectOrderInfoController#list、#listApprove、#listApproveLog 与 "
|
||||
+ "ProjectOrderInfoController#list:project:order:list / project:order:approve(Logical.OR,已抄取);"
|
||||
+ "本表无独立 Controller,取订单列表页面权限组合。McpController 无 @RequiresPermissions,"
|
||||
+ "身份由 McpBotAuthFilter 按机器人凭证绑定 SysUser,权限在本工具内显式校验");
|
||||
metadata.put("pii_trimmed_fields", keysOf(
|
||||
"business_phone", "partner_phone", "business_email", "notifier_email",
|
||||
"partner_email", "duty_email", "notifier_address"));
|
||||
metadata.put("enum_fields", mapData(
|
||||
"orderStatus", "ProjectOrderInfo.OrderStatus:0 待提交 / 1 待审核 / 2 审批完成 / 3 已驳回(只回显编码)",
|
||||
"rebackApproveStatus", "com.ruoyi.common.enums.ApproveStatusEnum:1 待审核 / 2 审批完成(撤单通过)/ "
|
||||
+ "3 已驳回;null 表示无撤单流程或补列前的历史快照",
|
||||
"deliveryStatus", "ProjectOrderInfo.DeliveryStatusEnum:0 未发货 / 1 部分发货 / 2 全部发货",
|
||||
"signStatus", "ProjectOrderInfo.SignStatusEnum:0 未签收 / 1 已签收",
|
||||
"outerStatus", "ProjectOrderInfo.OuterStatusEnum:0 未出库 / 1 部分出库 / 2 全部出库 / 3 已退回",
|
||||
"processType", "ProjectOrderInfo.ProcessTypeEnum:0 电子订单 / 1 纸质合同",
|
||||
"processTemplate", "ProjectOrderInfo.ProcessTemplateEnum:0 直签合同 / 1 总代合同 / 2 定制开发",
|
||||
"orderChannel", "ProjectOrderInfo.OrderChannelEnum:1 总代 / 2 直签",
|
||||
"orderType", "ProjectOrderInfo.OrderTypeEnum:1 正常订单 / 2 仅维保"));
|
||||
metadata.put("index_dependency", mapData(
|
||||
"必需索引", "idx_order_code_create_time(order_code, create_time),见 sql/20261203_order_final_approve_time.sql",
|
||||
"使用方式", "order_code 等值命中索引前缀,create_time 有序可满足倒序排序,limit+1 探测下一页",
|
||||
"缺失后果", "无索引时该表按 order_code 过滤是全表扫描,慢查询会被 MCP 查询超时中止"));
|
||||
metadata.put("notes", "只读工具,无写操作;单次调用最多返回 page_size 条,翻页上限 "
|
||||
+ McpPages.DEFAULT_LIST_MAX_PAGES + " 页;时间区间为左闭右开下推(create_time >= start and create_time < end),"
|
||||
+ "不使用 date_format;编码类入参与出参统一 trim。");
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import cn.hutool.core.collection.CollUtil;
|
|||
import cn.hutool.core.date.DateUtil;
|
||||
import com.ruoyi.common.utils.DateUtils;
|
||||
import com.ruoyi.common.utils.DictUtils;
|
||||
import com.ruoyi.common.enums.ApproveStatusEnum;
|
||||
import com.ruoyi.sip.domain.InventoryInfo;
|
||||
import com.ruoyi.sip.domain.InventoryOuter;
|
||||
import com.ruoyi.sip.domain.OmsInventoryInner;
|
||||
|
|
@ -42,6 +43,8 @@ public class ProjectOrderInfoToolProvider extends AbstractMcpToolProvider {
|
|||
private static final String INDUSTRY_TYPE_YYS_DICT_TYPE = "bg_yys";
|
||||
private static final String PROJECT_STAGE_DICT_TYPE = "project_stage";
|
||||
private static final String NOT_DELIVERED_TEXT = "未配货完成";
|
||||
/** 撤单审批通过后订单的展示状态,非 order_status 字典项 */
|
||||
private static final String ORDER_RECALLED_LABEL = "已撤单";
|
||||
private static final Set<String> SERVICE_MERGE_SOFTWARE_CODES = initCodeSet("0504A14F", "0504A1JX");
|
||||
private static final Set<String> SERVICE_MERGE_SERVICE_CODES = initCodeSet("0202A1NU", "0202A1NS", "0202A1NT");
|
||||
|
||||
|
|
@ -174,12 +177,13 @@ public class ProjectOrderInfoToolProvider extends AbstractMcpToolProvider {
|
|||
item.put("projectStage", getProjectStage(projectInfo));
|
||||
item.put("orderDate", formatDate(orderInfo.getEstimatedOrderTime()));
|
||||
item.put("orderEffectiveDate", formatDate(orderInfo.getApproveTime()));
|
||||
item.put("orderFinalEffectiveDate", formatDate(orderInfo.getFinalApproveTime()));
|
||||
item.put("requiredDeliveryDate", formatDate(orderInfo.getDeliveryTime()));
|
||||
item.put("contractCode", orderInfo.getOrderCode());
|
||||
item.put("projectName", orderInfo.getProjectName());
|
||||
item.put("h3cSales", projectInfo == null ? "" : projectInfo.getH3cPerson());
|
||||
item.put("agentName", orderInfo.getAgentName());
|
||||
item.put("orderStatus", DictUtils.getDictLabel("order_status", orderInfo.getOrderStatus()));
|
||||
item.put("orderStatus", resolveOrderStatus(orderInfo));
|
||||
item.put("orderStockingStatus", resolveOrderStockingStatus(orderInfo));
|
||||
item.put("outerStatus", resolveOuterStatus(orderInfo));
|
||||
item.put("signStatus", resolveSignStatus(orderInfo));
|
||||
|
|
@ -200,7 +204,9 @@ public class ProjectOrderInfoToolProvider extends AbstractMcpToolProvider {
|
|||
item.put("partnerContactName", orderInfo.getPartnerUserName());
|
||||
item.put("partnerContactPhone", orderInfo.getPartnerPhone());
|
||||
item.put("executionDeadline", formatDate(orderInfo.getOrderEndTime()));
|
||||
item.put("archiveTime", formatDateTime(orderInfo.getApproveTime()));
|
||||
// 归档时间取最近一次审批通过时间:approve_time 已收敛为第一次生效时间,撤单后 final_approve_time 为空则回退
|
||||
item.put("archiveTime", formatDateTime(orderInfo.getFinalApproveTime() != null
|
||||
? orderInfo.getFinalApproveTime() : orderInfo.getApproveTime()));
|
||||
|
||||
ProductGroupSummary softwareSummary = appendProductFields(item, "software", softwareList,
|
||||
orderShipmentMap, Collections.emptyMap(), true, orderInfo.getOrderCode());
|
||||
|
|
@ -807,6 +813,26 @@ public class ProjectOrderInfoToolProvider extends AbstractMcpToolProvider {
|
|||
return orderInfo.getOrderStockingStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单状态展示口径:审批完成的订单若撤单审批已通过,展示「已撤单」,与前端列表
|
||||
* (views/project/order/index.vue 的 orderStatus === '2' && rebackApproveStatus === '2')保持一致。
|
||||
* 「已撤单」不是 order_status 字典项,撤单审批通过只写 reback_approve_status,不改 order_status。
|
||||
*/
|
||||
private String resolveOrderStatus(ProjectOrderInfo orderInfo) {
|
||||
if (orderInfo == null) {
|
||||
return "";
|
||||
}
|
||||
if (ProjectOrderInfo.OrderStatus.APPROVE_COMPLETE.getCode().equals(orderInfo.getOrderStatus())
|
||||
&& ApproveStatusEnum.APPROVE_COMPLETE.getCode().equals(orderInfo.getRebackApproveStatus())) {
|
||||
return ORDER_RECALLED_LABEL;
|
||||
}
|
||||
if (isBlank(orderInfo.getOrderStatus())) {
|
||||
return "";
|
||||
}
|
||||
String label = DictUtils.getDictLabel("order_status", orderInfo.getOrderStatus());
|
||||
return isBlank(label) ? orderInfo.getOrderStatus() : label;
|
||||
}
|
||||
|
||||
private String resolveOuterStatus(ProjectOrderInfo orderInfo) {
|
||||
if (orderInfo == null || isBlank(orderInfo.getOuterStatus())) {
|
||||
return "";
|
||||
|
|
|
|||
|
|
@ -0,0 +1,42 @@
|
|||
package com.ruoyi.sip.mapper;
|
||||
|
||||
import com.ruoyi.sip.vo.ProjectOrderInfoLogVo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单审批历史快照({@code project_order_info_log})只读 Mapper。
|
||||
*
|
||||
* <p><b>为什么直连 Mapper、不经 Service 层</b>:该表是「公司领导审批通过」时由
|
||||
* {@code ProjectOrderInfoMapper#bakData}({@code INSERT ... SELECT} 整行快照)写入的历史备份表,
|
||||
* 全仓库<b>只有写路径、没有任何读路径,也没有对应的 Service</b>。本次只为 MCP 工具开放只读查询,
|
||||
* 不新增业务写操作,因此无需 Service 层,直接由本 Mapper 提供 SELECT,避免为空壳强造一层抽象。</p>
|
||||
*
|
||||
* <p>查询约束(与 {@code sql/20261203_order_final_approve_time.sql} 的索引配套):
|
||||
* {@code order_code} 是<b>强制</b>等值条件,排序为 {@code create_time desc, bak_id desc},
|
||||
* 走 {@code idx_order_code_create_time(order_code, create_time)};不使用 PageHelper,
|
||||
* 分页由调用方(MCP 游标分页)以 {@code limit}/{@code offset} 传入。</p>
|
||||
*
|
||||
* @author ai-context
|
||||
* @date 2026-12-03
|
||||
*/
|
||||
public interface ProjectOrderInfoLogMapper {
|
||||
|
||||
/**
|
||||
* 按合同编号(必填)+ 可选快照时间区间查询审批历史快照列表。
|
||||
*
|
||||
* @param params orderCode(必填,等值)、startTime/endTime(可选,左闭右开,作用列由 XML 决定)、
|
||||
* limit(调用方传 pageSize+1 以探测下一页)、offset
|
||||
* @return 快照列表,按 create_time desc, bak_id desc 排序
|
||||
*/
|
||||
List<ProjectOrderInfoLogVo> listOrderLogPage(Map<String, Object> params);
|
||||
|
||||
/**
|
||||
* 统计命中条数(与 {@link #listOrderLogPage} 同一套过滤条件,忽略分页)。
|
||||
*
|
||||
* @param params orderCode(必填)、startTime/endTime(可选)
|
||||
* @return 命中条数
|
||||
*/
|
||||
long countOrderLogPage(Map<String, Object> params);
|
||||
}
|
||||
|
|
@ -73,6 +73,14 @@ public interface ProjectOrderInfoMapper
|
|||
*/
|
||||
public int clearRebackApproveStatus(Long id);
|
||||
|
||||
/**
|
||||
* 清空订单最终生效时间(撤单时使用:直接撤单与撤单审批通过)
|
||||
*
|
||||
* @param id 订单管理主键
|
||||
* @return 结果
|
||||
*/
|
||||
public int clearFinalApproveTime(Long id);
|
||||
|
||||
/**
|
||||
* 清空订单的关联项目(仅维保订单改回正常订单时使用)
|
||||
*
|
||||
|
|
|
|||
|
|
@ -317,6 +317,9 @@ public class ExecutionTrackServiceImpl implements IExecutionTrackService, TodoCo
|
|||
updateOrder.setUpdateTime(new Date());
|
||||
updateOrder.setId(id);
|
||||
projectOrderInfoMapper.updateProjectOrderInfo(updateOrder);
|
||||
// 撤单后清空订单最终生效时间(直接撤单与撤单审批通过都会经过此处):
|
||||
// 动态update不会写入null,需用专用语句显式置空;approve_time 保留首次审批时间不变
|
||||
projectOrderInfoMapper.clearFinalApproveTime(id);
|
||||
//订单撤回记录
|
||||
ProjectOrderInfoRecall projectOrderInfoRecall = new ProjectOrderInfoRecall();
|
||||
projectOrderInfoRecall.setOrderCode(projectOrderInfo.getOrderCode());
|
||||
|
|
@ -511,6 +514,12 @@ public class ExecutionTrackServiceImpl implements IExecutionTrackService, TodoCo
|
|||
projectOrderInfoMapper.updateProjectOrderInfo(updateOrder);
|
||||
// 撤单审批通过不重置订单审批状态(orderStatus),保持原状态
|
||||
recall(orderId, updateBy, false);
|
||||
// 撤单状态全部落库后补一次快照:让 project_order_info_log 记录撤单后的订单状态
|
||||
// (reback_approve_status=2、final_approve_time 已置空),与审批通过时的快照不重复
|
||||
ProjectOrderInfo recalledOrder = projectOrderInfoMapper.selectProjectOrderInfoById(orderId);
|
||||
if (recalledOrder != null) {
|
||||
projectOrderInfoMapper.bakData(recalledOrder);
|
||||
}
|
||||
// 退单审批整体完成后回调CRM:商机阶段回退为S4并清空签约信息
|
||||
notifyCrmOrderReturn(orderId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1594,11 +1594,12 @@ public class InventoryDeliveryServiceImpl implements IInventoryDeliveryService,
|
|||
}
|
||||
|
||||
/**
|
||||
* 同一SN+产品编码的续算排序:审批时间(为空回退创建时间)升序,完全相同按订单id升序
|
||||
* 同一SN+产品编码的续算排序:最终生效时间优先(为空依次回退审批时间、创建时间)升序,完全相同按订单id升序
|
||||
*/
|
||||
private Comparator<DeliveryInfoVo> maintenanceSnComparator() {
|
||||
Comparator<Date> dateComparator = Comparator.nullsLast(Comparator.naturalOrder());
|
||||
return Comparator.comparing((DeliveryInfoVo vo) -> vo.getApproveTime() != null ? vo.getApproveTime() : vo.getCreateTime(), dateComparator)
|
||||
return Comparator.comparing((DeliveryInfoVo vo) -> vo.getFinalApproveTime() != null ? vo.getFinalApproveTime()
|
||||
: (vo.getApproveTime() != null ? vo.getApproveTime() : vo.getCreateTime()), dateComparator)
|
||||
.thenComparing(DeliveryInfoVo::getOrderId, Comparator.nullsLast(Comparator.naturalOrder()));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -460,6 +460,10 @@ public class ProjectOrderInfoServiceImpl implements IProjectOrderInfoService, To
|
|||
}
|
||||
//不更新订单编号
|
||||
projectOrderInfo.setOrderCode(null);
|
||||
// 生效时间由审批流维护:编辑表单会回填详情里的历史值,这里统一不回写,
|
||||
// 否则撤单置空的 final_approve_time 会被旧值覆盖
|
||||
projectOrderInfo.setApproveTime(null);
|
||||
projectOrderInfo.setFinalApproveTime(null);
|
||||
projectOrderInfo.setUpdateBy(ShiroUtils.getUserId().toString());
|
||||
projectOrderInfo.setUpdateTime(DateUtils.getNowDate());
|
||||
saveProductInfo(projectOrderInfo, projectOrderInfo.getProjectId());
|
||||
|
|
@ -736,6 +740,7 @@ public class ProjectOrderInfoServiceImpl implements IProjectOrderInfoService, To
|
|||
"projectStage",
|
||||
"orderDate",
|
||||
"orderEffectiveDate",
|
||||
"orderFinalEffectiveDate",
|
||||
"requiredDeliveryDate",
|
||||
"contractCode",
|
||||
"projectName",
|
||||
|
|
@ -864,6 +869,8 @@ public class ProjectOrderInfoServiceImpl implements IProjectOrderInfoService, To
|
|||
return "下单时间";
|
||||
case "orderEffectiveDate":
|
||||
return "订单生效时间";
|
||||
case "orderFinalEffectiveDate":
|
||||
return "订单最终生效时间";
|
||||
case "requiredDeliveryDate":
|
||||
return "要求到货时间";
|
||||
case "contractCode":
|
||||
|
|
@ -1828,7 +1835,13 @@ public class ProjectOrderInfoServiceImpl implements IProjectOrderInfoService, To
|
|||
|
||||
ProjectOrderInfo projectOrderInfo = new ProjectOrderInfo();
|
||||
projectOrderInfo.setOrderStatus(ProjectOrderInfo.OrderStatus.APPROVE_COMPLETE.getCode());
|
||||
projectOrderInfo.setApproveTime(DateUtils.getNowDate());
|
||||
// 订单生效时间只记录第一次审批通过时间:以数据库当前值为准(编辑页会回填旧值,不能信任传入对象),
|
||||
// 库中已有值时保持不更新
|
||||
if (dbProjectOrderInfo.getApproveTime() == null) {
|
||||
projectOrderInfo.setApproveTime(DateUtils.getNowDate());
|
||||
}
|
||||
// 订单最终生效时间:每次公司领导审批通过都写当次时间,撤单时置空
|
||||
projectOrderInfo.setFinalApproveTime(DateUtils.getNowDate());
|
||||
|
||||
// 修改执行单时间 只有直签且有现金折扣的时间才是配置时间 否则默认30天
|
||||
int addHour = ProjectOrderInfo.ProcessTemplateEnum.DIRECT_SIGNING.getCode().equals(dbProjectOrderInfo.getProcessTemplate())
|
||||
|
|
@ -2519,7 +2532,9 @@ public class ProjectOrderInfoServiceImpl implements IProjectOrderInfoService, To
|
|||
row.add(formatAmount(hardPrice));
|
||||
|
||||
row.add(formatAmount(mainPrice));
|
||||
row.add(DateUtil.format(info.getApproveTime(), "yyyy-MM-dd HH:mm:ss"));
|
||||
// 归档时间取最近一次审批通过时间;approve_time 已收敛为第一次生效时间,撤单后为空则回退
|
||||
row.add(DateUtil.format(info.getFinalApproveTime() != null
|
||||
? info.getFinalApproveTime() : info.getApproveTime(), "yyyy-MM-dd HH:mm:ss"));
|
||||
row.add(DateUtil.format(info.getOrderEndTime(), "yyyy-MM-dd"));
|
||||
row.add(info.getAgentName());
|
||||
row.add(info.getDutyName());
|
||||
|
|
|
|||
|
|
@ -43,6 +43,11 @@ public class DeliveryInfoVo {
|
|||
*/
|
||||
@JsonIgnore
|
||||
private Date approveTime;
|
||||
/**
|
||||
* 订单最终生效时间:仅维保续算时用于订单排序,撤单后为空则回退 approveTime / createTime
|
||||
*/
|
||||
@JsonIgnore
|
||||
private Date finalApproveTime;
|
||||
/**
|
||||
* 订单创建时间
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,229 @@
|
|||
package com.ruoyi.sip.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 订单审批历史快照({@code project_order_info_log})只读查询出参。
|
||||
*
|
||||
* <p>该表是「公司领导审批通过」时对 {@code project_order_info} 做的整行快照
|
||||
* (写入见 {@code ProjectOrderInfoMapper.xml} 的 {@code bakData},{@code INSERT ... SELECT} 43 列,
|
||||
* 不是 JSON、不是 diff),除自增主键 {@code bak_id} 外原表无索引、无 {@code del_flag},
|
||||
* 属只写不读的历史表,因此本 VO 仅用于 MCP 只读查询,不参与任何业务写路径。</p>
|
||||
*
|
||||
* <p><b>字段裁剪(PII)</b>:为避免把客户/联系人隐私一次性吐给外部 Agent,以下列<b>不返回</b>,
|
||||
* SQL 也不 select:{@code business_phone}、{@code partner_phone}(联系人电话)、
|
||||
* {@code business_email}、{@code notifier_email}、{@code partner_email}、{@code duty_email}(各角色邮箱)、
|
||||
* {@code notifier_address}(收货地址,含门牌与收件人信息)。
|
||||
* 保留 {@code duty_phone}(责任人电话属内部责任人联系方式,审批链路排障必需)与
|
||||
* {@code notifierPhone}(收货通知人电话,配货/物流跟单必需);
|
||||
* 人名类({@code businessPerson}/{@code notifier}/{@code duty}/{@code partnerUserName})保留,
|
||||
* 便于回答「当时是谁负责」。</p>
|
||||
*
|
||||
* <p>金额字段按规范统一用 {@link BigDecimal},不用 {@code double};
|
||||
* 日期字段保留 {@link Date} 原值,由工具层格式化为 {@code yyyy-MM-dd HH:mm:ss} 后输出。</p>
|
||||
*
|
||||
* @author ai-context
|
||||
* @date 2026-12-03
|
||||
*/
|
||||
@Data
|
||||
public class ProjectOrderInfoLogVo {
|
||||
|
||||
/**
|
||||
* 快照自增主键(bak_id),同订单多条快照的唯一区分键,也是分页排序的次级键
|
||||
*/
|
||||
private Long bakId;
|
||||
|
||||
/**
|
||||
* 快照来源:project_order_info.id(订单主键,非快照主键)
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 快照来源:项目主键
|
||||
*/
|
||||
private Long projectId;
|
||||
|
||||
/**
|
||||
* 省
|
||||
*/
|
||||
private String province;
|
||||
|
||||
/**
|
||||
* 市
|
||||
*/
|
||||
private String city;
|
||||
|
||||
/**
|
||||
* 进货商商务接口人姓名(邮箱/电话已按 PII 裁剪)
|
||||
*/
|
||||
private String businessPerson;
|
||||
|
||||
/**
|
||||
* 版本号
|
||||
*/
|
||||
private String versionCode;
|
||||
|
||||
/**
|
||||
* 合同编号(本工具的强制过滤条件)
|
||||
*/
|
||||
private String orderCode;
|
||||
|
||||
/**
|
||||
* 币种(列名为 currencyType,非下划线风格)
|
||||
*/
|
||||
private String currencyType;
|
||||
|
||||
/**
|
||||
* 出货金额
|
||||
*/
|
||||
private BigDecimal shipmentAmount;
|
||||
|
||||
/**
|
||||
* 实际进货金额
|
||||
*/
|
||||
private BigDecimal actualPurchaseAmount;
|
||||
|
||||
/**
|
||||
* 执行单有效截止时间
|
||||
*/
|
||||
private Date orderEndTime;
|
||||
|
||||
/**
|
||||
* 要求到货时间
|
||||
*/
|
||||
private Date deliveryTime;
|
||||
|
||||
/**
|
||||
* 公司直发
|
||||
*/
|
||||
private String companyDelivery;
|
||||
|
||||
/**
|
||||
* 收货通知人姓名(邮箱与收货地址已按 PII 裁剪)
|
||||
*/
|
||||
private String notifier;
|
||||
|
||||
/**
|
||||
* 收货通知人电话(邮箱与收货地址已按 PII 裁剪)
|
||||
*/
|
||||
private String notifierPhone;
|
||||
|
||||
/**
|
||||
* 责任人
|
||||
*/
|
||||
private String duty;
|
||||
|
||||
/**
|
||||
* 责任人电话(邮箱已按 PII 裁剪)
|
||||
*/
|
||||
private String dutyPhone;
|
||||
|
||||
/**
|
||||
* 下单通路编码(字典见 ProjectOrderInfo.OrderChannelEnum:2 直签 / 1 总代)
|
||||
*/
|
||||
private String orderChannel;
|
||||
|
||||
/**
|
||||
* 进货商联系人姓名(电话、邮箱已按 PII 裁剪)
|
||||
*/
|
||||
private String partnerUserName;
|
||||
|
||||
/**
|
||||
* 进货商编码
|
||||
*/
|
||||
private String partnerCode;
|
||||
|
||||
/**
|
||||
* 供货商
|
||||
*/
|
||||
private String supplier;
|
||||
|
||||
/**
|
||||
* 其它特别说明
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 发货状态编码(快照时刻的值,字典见 ProjectOrderInfo.DeliveryStatusEnum)
|
||||
*/
|
||||
private String deliveryStatus;
|
||||
|
||||
/**
|
||||
* 签收状态编码(快照时刻的值,字典见 ProjectOrderInfo.SignStatusEnum)
|
||||
*/
|
||||
private String signStatus;
|
||||
|
||||
/**
|
||||
* 出库状态编码(快照时刻的值,字典见 ProjectOrderInfo.OuterStatusEnum)
|
||||
*/
|
||||
private String outerStatus;
|
||||
|
||||
/**
|
||||
* 审批通过时间
|
||||
*/
|
||||
private Date approveTime;
|
||||
|
||||
/**
|
||||
* 订单最终生效时间(撤单后置空;历史快照在补列前为 null)
|
||||
*/
|
||||
private Date finalApproveTime;
|
||||
|
||||
/**
|
||||
* 订单状态编码(字典见 ProjectOrderInfo.OrderStatus:0 待提交 1 待审核 2 审批完成 3 已驳回)
|
||||
*/
|
||||
private String orderStatus;
|
||||
|
||||
/**
|
||||
* 撤单审批状态编码(字典见 com.ruoyi.common.enums.ApproveStatusEnum:1 待审核 2 审批完成 3 已驳回;
|
||||
* 历史快照在补列前为 null)
|
||||
*/
|
||||
private String rebackApproveStatus;
|
||||
|
||||
/**
|
||||
* 订单创建人(快照原样复制,非快照写入人)
|
||||
*/
|
||||
private String createBy;
|
||||
|
||||
/**
|
||||
* 订单创建时间(快照原样复制,不是快照落库时间)
|
||||
*/
|
||||
private Date createTime;
|
||||
|
||||
/**
|
||||
* 订单更新人(快照原样复制)
|
||||
*/
|
||||
private String updateBy;
|
||||
|
||||
/**
|
||||
* 订单更新时间:快照落库前最后一次更新,可用它近似判断快照先后
|
||||
*/
|
||||
private Date updateTime;
|
||||
|
||||
/**
|
||||
* 订单处理方式编码(0 电子订单 / 1 纸质合同)
|
||||
*/
|
||||
private String processType;
|
||||
|
||||
/**
|
||||
* 合同模板编码(0 直签 / 1 总代 / 2 定制开发)
|
||||
*/
|
||||
private String processTemplate;
|
||||
|
||||
/**
|
||||
* 订单类型编码(1 正常订单 / 2 仅维保)
|
||||
*/
|
||||
private String orderType;
|
||||
|
||||
/**
|
||||
* 折上折
|
||||
*/
|
||||
private BigDecimal discountFold;
|
||||
|
||||
/**
|
||||
* 操作版本
|
||||
*/
|
||||
private Integer operationVersion;
|
||||
}
|
||||
|
|
@ -94,6 +94,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
t5.id as order_id,
|
||||
t5.approve_time,
|
||||
t5.create_time,
|
||||
t5.final_approve_time,
|
||||
d.product_sn as 'serialNumber' ,
|
||||
t3.product_code,
|
||||
t4.description as 'productDescription',
|
||||
|
|
@ -116,6 +117,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
t5.id as order_id,
|
||||
t5.approve_time,
|
||||
t5.create_time,
|
||||
t5.final_approve_time,
|
||||
t2.product_sn as 'serialNumber' ,
|
||||
t2.product_code,
|
||||
t4.description as 'productDescription',
|
||||
|
|
@ -154,7 +156,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
and sn.serialNumber = #{serialNumber}
|
||||
</when>
|
||||
</choose>
|
||||
order by sn.serialNumber, ifnull(sn.approve_time, sn.create_time), sn.order_id
|
||||
order by sn.serialNumber, ifnull(ifnull(sn.final_approve_time, sn.approve_time), sn.create_time), sn.order_id
|
||||
</select>
|
||||
|
||||
|
||||
|
|
@ -479,4 +481,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
</where>
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
</mapper>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,127 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<!--
|
||||
订单审批历史快照 project_order_info_log:只读查询(MCP 工具 project_order_info_log 专用)。
|
||||
该表由 ProjectOrderInfoMapper.xml 的 bakData(INSERT ... SELECT 整行快照)在
|
||||
「公司领导审批通过」与「撤单审批通过」时写入,全仓库无读路径、无 del_flag。
|
||||
SQL 约定:显式列名(禁 select *);order_code 强制等值条件;时间区间左闭右开;
|
||||
order by create_time desc, bak_id desc 走 idx_order_code_create_time(order_code, create_time);
|
||||
不使用 PageHelper,分页由 MCP 游标层以 limit/offset 传入。
|
||||
PII 列(business_phone / partner_phone / business_email / notifier_email / partner_email /
|
||||
duty_email / notifier_address)不 select,裁剪原因见 ProjectOrderInfoLogVo 类注释。
|
||||
-->
|
||||
<mapper namespace="com.ruoyi.sip.mapper.ProjectOrderInfoLogMapper">
|
||||
|
||||
<resultMap type="com.ruoyi.sip.vo.ProjectOrderInfoLogVo" id="ProjectOrderInfoLogResult">
|
||||
<result property="bakId" column="bak_id" />
|
||||
<result property="id" column="id" />
|
||||
<result property="projectId" column="project_id" />
|
||||
<result property="province" column="province" />
|
||||
<result property="city" column="city" />
|
||||
<result property="businessPerson" column="business_person" />
|
||||
<result property="versionCode" column="version_code" />
|
||||
<result property="orderCode" column="order_code" />
|
||||
<result property="currencyType" column="currencyType" />
|
||||
<result property="shipmentAmount" column="shipment_amount" />
|
||||
<result property="actualPurchaseAmount" column="actual_purchase_amount" />
|
||||
<result property="orderEndTime" column="order_end_time" />
|
||||
<result property="deliveryTime" column="delivery_time" />
|
||||
<result property="companyDelivery" column="company_delivery" />
|
||||
<result property="notifier" column="notifier" />
|
||||
<result property="notifierPhone" column="notifier_phone" />
|
||||
<result property="duty" column="duty" />
|
||||
<result property="dutyPhone" column="duty_phone" />
|
||||
<result property="orderChannel" column="order_channel" />
|
||||
<result property="partnerUserName" column="partner_user_name" />
|
||||
<result property="partnerCode" column="partner_code" />
|
||||
<result property="supplier" column="supplier" />
|
||||
<result property="remark" column="remark" />
|
||||
<result property="deliveryStatus" column="delivery_status" />
|
||||
<result property="signStatus" column="sign_status" />
|
||||
<result property="outerStatus" column="outer_status" />
|
||||
<result property="approveTime" column="approve_time" />
|
||||
<result property="finalApproveTime" column="final_approve_time" />
|
||||
<result property="orderStatus" column="order_status" />
|
||||
<result property="rebackApproveStatus" column="reback_approve_status" />
|
||||
<result property="createBy" column="create_by" />
|
||||
<result property="createTime" column="create_time" />
|
||||
<result property="updateBy" column="update_by" />
|
||||
<result property="updateTime" column="update_time" />
|
||||
<result property="processType" column="process_type" />
|
||||
<result property="processTemplate" column="process_template" />
|
||||
<result property="orderType" column="order_type" />
|
||||
<result property="discountFold" column="discount_fold" />
|
||||
<result property="operationVersion" column="operation_version" />
|
||||
</resultMap>
|
||||
|
||||
<!-- 显式列名:与 bakData 实写列一致,另含后补的 reback_approve_status、final_approve_time -->
|
||||
<sql id="selectProjectOrderInfoLogVo">
|
||||
select t1.bak_id,
|
||||
t1.id,
|
||||
t1.project_id,
|
||||
t1.province,
|
||||
t1.city,
|
||||
t1.business_person,
|
||||
t1.version_code,
|
||||
t1.order_code,
|
||||
t1.currencyType,
|
||||
t1.shipment_amount,
|
||||
t1.actual_purchase_amount,
|
||||
t1.order_end_time,
|
||||
t1.delivery_time,
|
||||
t1.company_delivery,
|
||||
t1.notifier,
|
||||
t1.notifier_phone,
|
||||
t1.duty,
|
||||
t1.duty_phone,
|
||||
t1.order_channel,
|
||||
t1.partner_user_name,
|
||||
t1.partner_code,
|
||||
t1.supplier,
|
||||
t1.remark,
|
||||
t1.delivery_status,
|
||||
t1.sign_status,
|
||||
t1.outer_status,
|
||||
t1.approve_time,
|
||||
t1.final_approve_time,
|
||||
t1.order_status,
|
||||
t1.reback_approve_status,
|
||||
t1.create_by,
|
||||
t1.create_time,
|
||||
t1.update_by,
|
||||
t1.update_time,
|
||||
t1.process_type,
|
||||
t1.process_template,
|
||||
t1.order_type,
|
||||
t1.discount_fold,
|
||||
t1.operation_version
|
||||
from project_order_info_log t1
|
||||
</sql>
|
||||
|
||||
<!-- order_code 为强制条件(Java 层已校验非空),时间区间左闭右开 -->
|
||||
<sql id="orderLogPageFilter">
|
||||
and t1.order_code = #{orderCode}
|
||||
<if test="startTime != null">and t1.create_time >= #{startTime}</if>
|
||||
<if test="endTime != null">and t1.create_time < #{endTime}</if>
|
||||
</sql>
|
||||
|
||||
<select id="listOrderLogPage" parameterType="java.util.Map" resultMap="ProjectOrderInfoLogResult">
|
||||
<include refid="selectProjectOrderInfoLogVo"/>
|
||||
<where>
|
||||
<include refid="orderLogPageFilter"/>
|
||||
</where>
|
||||
order by t1.create_time desc, t1.bak_id desc
|
||||
limit #{limit} offset #{offset}
|
||||
</select>
|
||||
|
||||
<select id="countOrderLogPage" parameterType="java.util.Map" resultType="long">
|
||||
select count(1)
|
||||
from project_order_info_log t1
|
||||
<where>
|
||||
<include refid="orderLogPageFilter"/>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
|
@ -50,6 +50,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<result property="operationVersion" column="operation_version" />
|
||||
<result property="orderStockingStatus" column="order_stocking_status" />
|
||||
<result property="rebackApproveStatus" column="reback_approve_status" />
|
||||
<result property="finalApproveTime" column="final_approve_time" />
|
||||
<result property="relatedOrderId" column="related_order_id" />
|
||||
<result property="relatedOrderCode" column="related_order_code" />
|
||||
<result property="relatedProjectName" column="related_project_name" />
|
||||
|
|
@ -60,7 +61,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
shipment_amount, actual_purchase_amount, order_end_time, delivery_time, company_delivery, notifier,finance_status,
|
||||
notifier_email, notifier_phone, duty, duty_email, duty_phone, order_channel, partner_code, supplier,notifier_address,
|
||||
remark, order_status, create_by, create_time, update_by, update_time,version_code,process_type,process_template,discount_fold,order_stocking_status,
|
||||
delivery_status,sign_status,outer_status,approve_time,payment_method,payment_ratio,payment_description,order_type,operation_version,reback_approve_status,related_order_id
|
||||
delivery_status,sign_status,outer_status,approve_time,final_approve_time,payment_method,payment_ratio,payment_description,order_type,operation_version,reback_approve_status,related_order_id
|
||||
|
||||
from project_order_info t1
|
||||
</sql>
|
||||
|
|
@ -70,7 +71,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
t1.notifier_email, t1.notifier_phone, t1.duty, t1.duty_email, t1.duty_phone, t1.order_channel, t1.partner_code, t1.supplier,
|
||||
t1.remark, t1.order_status, t1.create_by, t1.create_time, t1.update_by, t1.update_time,t1.partner_user_name,t1.partner_email
|
||||
,t1.partner_phone,t1.version_code,t1.process_type,t1.process_template,t1.discount_fold,t1.notifier_address,t1.finance_status,
|
||||
t1.delivery_status,t1.sign_status,t1.outer_status,t1.approve_time,t1.payment_method,t1.payment_ratio,t1.payment_description,t1.operation_version,t1.order_stocking_status,t1.reback_approve_status,t1.related_order_id
|
||||
t1.delivery_status,t1.sign_status,t1.outer_status,t1.approve_time,t1.final_approve_time,t1.payment_method,t1.payment_ratio,t1.payment_description,t1.operation_version,t1.order_stocking_status,t1.reback_approve_status,t1.related_order_id
|
||||
,t2.project_code,t2.project_name,t2.project_desc,t2.software_info,t2.hardware_info,t2.terminal_peripheral,t2.server_configuration
|
||||
,t2.management_version,t2.desktop_vm_os_version,t2.vm_spec_quantity,t2.key_problem,t2.joint_trial_result
|
||||
,t2.province,t2.customer_name,t2.customer_code,t2.industry_type,t2.bg_property,t2.agent_code,t2.estimated_order_time
|
||||
|
|
@ -102,7 +103,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<if test="projectName != null and projectName != ''">
|
||||
and t2.project_name like concat('%',#{projectName},'%')
|
||||
</if>
|
||||
order by ifnull(t1.approve_time, t1.create_time) desc, t1.id desc
|
||||
order by ifnull(t1.final_approve_time, ifnull(t1.approve_time, t1.create_time)) desc, t1.id desc
|
||||
</select>
|
||||
|
||||
<select id="selectProjectOrderInfoList" parameterType="ProjectOrderInfo" resultMap="ProjectOrderInfoResult">
|
||||
|
|
@ -446,7 +447,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
t1.notifier_email, t1.notifier_phone, t1.duty, t1.duty_email, t1.duty_phone, t1.order_channel, t1.partner_code, t1.supplier,
|
||||
t1.remark, t1.order_status, t1.create_by, t1.create_time, t1.update_by, t1.update_time,t1.partner_user_name,t1.partner_email
|
||||
,t1.partner_phone,t1.version_code,t1.process_type,t1.process_template,t1.discount_fold,t1.notifier_address,t1.finance_status,
|
||||
t1.delivery_status,t1.sign_status,t1.outer_status,t1.approve_time,t1.payment_method,t1.payment_ratio,t1.payment_description,t1.operation_version,t1.order_stocking_status
|
||||
t1.delivery_status,t1.sign_status,t1.outer_status,t1.approve_time,t1.final_approve_time,t1.payment_method,t1.payment_ratio,t1.payment_description,t1.operation_version,t1.order_stocking_status
|
||||
,t2.project_code,t2.project_name,t2.province,t2.customer_name,t2.customer_code,t2.industry_type,t2.bg_property,t2.agent_code,t2.estimated_order_time
|
||||
,t2.customer_phone,t2.customer_user_name,t2.agent_code,t2.customer_code,t2.partner_name project_partner_name
|
||||
,t3.partner_name,t3.level,t3.system_user_id,t3.address partner_address
|
||||
|
|
@ -762,7 +763,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
process_template,
|
||||
order_type,
|
||||
discount_fold,
|
||||
operation_version)
|
||||
operation_version,
|
||||
reback_approve_status,
|
||||
final_approve_time)
|
||||
select id,
|
||||
project_id,
|
||||
province,
|
||||
|
|
@ -805,7 +808,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
process_template,
|
||||
order_type,
|
||||
discount_fold,
|
||||
operation_version
|
||||
operation_version,
|
||||
reback_approve_status,
|
||||
final_approve_time
|
||||
from project_order_info
|
||||
where order_code = #{orderCode}
|
||||
</insert>
|
||||
|
|
@ -855,6 +860,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<if test="updateBy != null">update_by = #{updateBy},</if>
|
||||
<if test="updateTime != null">update_time = #{updateTime},</if>
|
||||
<if test="approveTime != null">approve_time = #{approveTime},</if>
|
||||
<if test="finalApproveTime != null">final_approve_time = #{finalApproveTime},</if>
|
||||
<if test="paymentMethod != null and paymentMethod != ''">payment_method = #{paymentMethod},</if>
|
||||
<if test="paymentRatio != null">payment_ratio = #{paymentRatio},</if>
|
||||
<if test="paymentDescription != null and paymentDescription != ''">payment_description = #{paymentDescription},</if>
|
||||
|
|
@ -870,6 +876,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
set reback_approve_status = null
|
||||
where id = #{id}
|
||||
</update>
|
||||
<!-- 撤单后清空订单最终生效时间:动态update不会写入null,需显式清空 -->
|
||||
<update id="clearFinalApproveTime" parameterType="Long">
|
||||
update project_order_info
|
||||
set final_approve_time = null
|
||||
where id = #{id}
|
||||
</update>
|
||||
<!-- 订单类型由仅维保改回正常时清空关联项目:动态update不会写入null,需显式清空 -->
|
||||
<update id="clearRelatedOrderId" parameterType="Long">
|
||||
update project_order_info
|
||||
|
|
@ -886,6 +898,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<if test="businessEmail != null">business_email = #{businessEmail},</if>
|
||||
<if test="businessPhone != null">business_phone = #{businessPhone},</if>
|
||||
<if test="approveTime != null">approve_time = #{approveTime},</if>
|
||||
<if test="finalApproveTime != null">final_approve_time = #{finalApproveTime},</if>
|
||||
<if test="paymentMethod != null and paymentMethod != ''">payment_method = #{paymentMethod},</if>
|
||||
<if test="paymentRatio != null">payment_ratio = #{paymentRatio},</if>
|
||||
<if test="paymentDescription != null and paymentDescription != ''">payment_description = #{paymentDescription},</if>
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ router:
|
|||
project_list: [项目, 立项, 项目进度, POC, 试点, 会审, 报价, 报价单, 项目清单, 把握度, 合同明细]
|
||||
cross_domain_aggregate: [交叉分析, 透视, 组合分析, 客户产品, 按客户按产品, 按代表处, 多维, 销售额, 销量, 营业额, 交叉表, 多维统计]
|
||||
approval_list: [待办, 已办, 审批, 审批意见, 驳回, 待我审批, 审批到哪了]
|
||||
project_order_info_log: [订单审批历史, 审批快照, 历史快照, 历史版本, 订单历史, 撤单前状态, 生效时间历史]
|
||||
|
||||
# 同义词:口语 -> 工具(可带 #entity 作为参数建议),权重 2.5
|
||||
synonyms:
|
||||
|
|
@ -138,3 +139,9 @@ router:
|
|||
订单: [project_order_info]
|
||||
合同: [project_order_info]
|
||||
合同编号: [project_order_info]
|
||||
# ===== 订单审批历史快照 =====
|
||||
审批历史: [project_order_info_log]
|
||||
审批快照: [project_order_info_log]
|
||||
历史快照: [project_order_info_log]
|
||||
历史版本: [project_order_info_log]
|
||||
订单历史: [project_order_info_log]
|
||||
|
|
|
|||
|
|
@ -9,6 +9,12 @@ import java.util.Date;
|
|||
public class SysBotCredential extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 来源:本系统个人中心手工生成 */
|
||||
public static final String SOURCE_LOCAL = "local";
|
||||
|
||||
/** 来源:统一门户(dsh-hub)按契约签发 */
|
||||
public static final String SOURCE_HUB = "hub";
|
||||
|
||||
private Long id;
|
||||
private String botId;
|
||||
private String secretHash;
|
||||
|
|
@ -19,4 +25,13 @@ public class SysBotCredential extends BaseEntity {
|
|||
private Date lastAccessTime;
|
||||
private String lastAccessIp;
|
||||
private String remark;
|
||||
|
||||
/** 凭据来源(local 本系统生成 / hub 统一门户签发),决定谁能吊销它 */
|
||||
private String source;
|
||||
|
||||
/** 是否由统一门户签发 */
|
||||
public boolean isHubSource()
|
||||
{
|
||||
return SOURCE_HUB.equals(source);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
package com.ruoyi.system.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import com.ruoyi.system.domain.SysBotCredential;
|
||||
|
||||
public interface SysBotCredentialMapper {
|
||||
|
|
@ -12,4 +14,15 @@ public interface SysBotCredentialMapper {
|
|||
int updateSysBotCredential(SysBotCredential credential);
|
||||
|
||||
int updateLastAccessInfo(SysBotCredential credential);
|
||||
|
||||
/**
|
||||
* 吊销一把统一门户签发的密钥。
|
||||
*
|
||||
* <p>只影响 {@code source='hub'} 且仍可用的行:个人中心自己生成的钥匙不归 hub 回收。</p>
|
||||
*
|
||||
* @param botId 密钥标识
|
||||
* @param updateBy 操作人
|
||||
* @return 影响行数
|
||||
*/
|
||||
int revokeHubCredential(@Param("botId") String botId, @Param("updateBy") String updateBy);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.ruoyi.system.service;
|
|||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.system.domain.SysBotCredential;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
public interface ISysBotCredentialService {
|
||||
|
|
@ -11,4 +12,37 @@ public interface ISysBotCredentialService {
|
|||
SysBotCredential selectByUserId(Long userId);
|
||||
|
||||
Map<String, Object> generateCredentialForUser(SysUser user);
|
||||
|
||||
/**
|
||||
* 按密钥标识取凭据(含已吊销的行,供调用方区分「不存在」与「已撤销」)。
|
||||
*
|
||||
* @param botId 密钥标识,对 hub 而言就是它保存的 {@code key_id}
|
||||
* @return 凭据,不存在时 null
|
||||
*/
|
||||
SysBotCredential selectByBotId(String botId);
|
||||
|
||||
/**
|
||||
* 为统一门户(dsh-hub)创建一把 MCP 密钥,复用与本地生成完全相同的凭据形态。
|
||||
*
|
||||
* <p>与 {@link #generateCredentialForUser(SysUser)} 的区别只有一个:本方法<b>总是新建</b>一行,
|
||||
* 不覆盖该用户已有的凭据。hub 侧每人每应用默认只有一把,但它的幂等判定在 hub 自己库里,
|
||||
* 覆盖式写入会让用户早先手工生成的凭据凭空失效。</p>
|
||||
*
|
||||
* @param user 绑定到的本地用户
|
||||
* @param expireTime 过期时间,可为空(空表示不自动过期)
|
||||
* @param createBy 创建人(hub 侧账号,便于审计)
|
||||
* @return {@code botId}(= hub 的 key_id)、{@code botSecret}(明文,只在此刻可得)、{@code expireTime}
|
||||
*/
|
||||
Map<String, Object> createHubCredential(SysUser user, Date expireTime, String createBy);
|
||||
|
||||
/**
|
||||
* 按密钥标识吊销统一门户签发的 MCP 密钥(只动 {@code source='hub'} 的行)。
|
||||
*
|
||||
* <p>不物理删除:业务归属、审计与「这把钥匙曾是谁的」都还要查得到。</p>
|
||||
*
|
||||
* @param botId 密钥标识
|
||||
* @param operName 操作人
|
||||
* @return 影响行数,0 表示这把钥匙不是 hub 签发的或本就不存在
|
||||
*/
|
||||
int revokeHubCredentialByBotId(String botId, String operName);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,6 +102,8 @@ public class SysBotCredentialServiceImpl implements ISysBotCredentialService {
|
|||
credential.setUserId(user.getUserId());
|
||||
credential.setStatus(UserConstants.NORMAL);
|
||||
credential.setRemark("MCP bot credential");
|
||||
// 本地生成的钥匙一律标 local:hub 的删除接口只回收 hub 签发的行,不能把用户自己建的钥匙带走
|
||||
credential.setSource(SysBotCredential.SOURCE_LOCAL);
|
||||
credential.setUpdateBy(user.getLoginName());
|
||||
|
||||
if (existing == null) {
|
||||
|
|
@ -119,6 +121,69 @@ public class SysBotCredentialServiceImpl implements ISysBotCredentialService {
|
|||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SysBotCredential selectByBotId(String botId)
|
||||
{
|
||||
if (StringUtils.isEmpty(botId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return botCredentialMapper.selectByBotId(botId.trim());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> createHubCredential(SysUser user, Date expireTime, String createBy)
|
||||
{
|
||||
if (user == null || user.getUserId() == null)
|
||||
{
|
||||
throw new ServiceException("Current user not found");
|
||||
}
|
||||
if (!UserConstants.NORMAL.equals(user.getStatus()) || !"0".equals(user.getDelFlag()))
|
||||
{
|
||||
throw new ServiceException("Bound user is disabled or deleted");
|
||||
}
|
||||
|
||||
// 前缀带 hub_ 是 hub 侧的建议(无此前缀它只记日志不拒绝),带上 userId 方便运维从钥匙反查到人
|
||||
String botId = McpBotCredentialUtils.generateBotId("hub_" + user.getUserId());
|
||||
String botSecret = McpBotCredentialUtils.generateSecret();
|
||||
String salt = McpBotCredentialUtils.generateSalt();
|
||||
|
||||
SysBotCredential credential = new SysBotCredential();
|
||||
credential.setBotId(botId);
|
||||
credential.setSecretHash(McpBotCredentialUtils.hashSecret(botId, botSecret, salt));
|
||||
credential.setSecretSalt(salt);
|
||||
credential.setUserId(user.getUserId());
|
||||
credential.setStatus(UserConstants.NORMAL);
|
||||
credential.setExpireTime(expireTime);
|
||||
credential.setSource(SysBotCredential.SOURCE_HUB);
|
||||
credential.setRemark("MCP key issued by dsh-hub");
|
||||
credential.setCreateBy(StringUtils.isEmpty(createBy) ? "dsh-hub" : createBy);
|
||||
credential.setUpdateBy(credential.getCreateBy());
|
||||
botCredentialMapper.insertSysBotCredential(credential);
|
||||
|
||||
// 明文只在这一次返回给 hub(hub 保存后渲染进客户端配置),库里只留 hash + salt
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("botId", botId);
|
||||
result.put("botSecret", botSecret);
|
||||
result.put("expireTime", expireTime);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int revokeHubCredentialByBotId(String botId, String operName)
|
||||
{
|
||||
if (StringUtils.isEmpty(botId))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return botCredentialMapper.revokeHubCredential(botId.trim(), safeOperName(operName));
|
||||
}
|
||||
|
||||
private String safeOperName(String operName)
|
||||
{
|
||||
return StringUtils.isEmpty(operName) ? "dsh-hub" : operName;
|
||||
}
|
||||
|
||||
private void enrichRolePermissions(SysUser user) {
|
||||
List<SysRole> roles = user.getRoles();
|
||||
if (roles == null || roles.isEmpty()) {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<result property="lastAccessTime" column="last_access_time"/>
|
||||
<result property="lastAccessIp" column="last_access_ip"/>
|
||||
<result property="remark" column="remark"/>
|
||||
<result property="source" column="source"/>
|
||||
<result property="createBy" column="create_by"/>
|
||||
<result property="createTime" column="create_time"/>
|
||||
<result property="updateBy" column="update_by"/>
|
||||
|
|
@ -32,6 +33,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
last_access_time,
|
||||
last_access_ip,
|
||||
remark,
|
||||
source,
|
||||
create_by,
|
||||
create_time,
|
||||
update_by,
|
||||
|
|
@ -41,6 +43,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
limit 1
|
||||
</select>
|
||||
|
||||
<!-- 个人中心只看自己生成的那把:统一门户签发的钥匙归 hub 管理(用户在门户个人中心创建/撤销),
|
||||
若把它混进来,用户在个人中心点「生成」会复用 hub 那行的 bot_id 并换掉 secret,
|
||||
结果是 hub 里保存的 secret 当场失效、MCP 立刻连不上。 -->
|
||||
<select id="selectByUserId" parameterType="Long" resultMap="SysBotCredentialResult">
|
||||
select id,
|
||||
bot_id,
|
||||
|
|
@ -52,12 +57,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
last_access_time,
|
||||
last_access_ip,
|
||||
remark,
|
||||
source,
|
||||
create_by,
|
||||
create_time,
|
||||
update_by,
|
||||
update_time
|
||||
from sys_bot_credential
|
||||
where user_id = #{userId}
|
||||
and ifnull(source, 'local') = 'local'
|
||||
order by id desc
|
||||
limit 1
|
||||
</select>
|
||||
|
|
@ -73,6 +80,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
last_access_time,
|
||||
last_access_ip,
|
||||
remark,
|
||||
source,
|
||||
create_by,
|
||||
create_time,
|
||||
update_by,
|
||||
|
|
@ -87,6 +95,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
#{lastAccessTime},
|
||||
#{lastAccessIp},
|
||||
#{remark},
|
||||
#{source},
|
||||
#{createBy},
|
||||
sysdate(),
|
||||
#{updateBy},
|
||||
|
|
@ -103,6 +112,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
status = #{status},
|
||||
expire_time = #{expireTime},
|
||||
remark = #{remark},
|
||||
source = #{source},
|
||||
update_by = #{updateBy},
|
||||
update_time = sysdate()
|
||||
where id = #{id}
|
||||
|
|
@ -115,4 +125,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
update_time = sysdate()
|
||||
where id = #{id}
|
||||
</update>
|
||||
|
||||
<!-- 只吊销 hub 签发的行:个人中心自己生成的钥匙不归 hub 管,不能因为门户侧的一次删除
|
||||
就把用户手工建的凭据干掉。status='1' 与本模块既有口径一致(0 正常,非 0 即不可用)。 -->
|
||||
<update id="revokeHubCredential">
|
||||
update sys_bot_credential
|
||||
set status = '1',
|
||||
update_by = #{updateBy},
|
||||
update_time = sysdate()
|
||||
where source = 'hub'
|
||||
and status = '0'
|
||||
and bot_id = #{botId}
|
||||
</update>
|
||||
</mapper>
|
||||
|
|
|
|||
Loading…
Reference in New Issue