Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21275ef770 | ||
|
|
d3735e3afa | ||
|
|
4248e9574e | ||
|
|
6c2601950b | ||
|
|
1be0d98ebd | ||
|
|
5e484d0e74 | ||
|
|
3caf5f8816 | ||
|
|
861c78efb5 | ||
|
|
6187ec69df | ||
|
|
2d60f7899f | ||
|
|
f76bda1efa | ||
|
|
4edb7619bc | ||
|
|
dfb74f3386 | ||
|
|
9fc3385d6c | ||
|
|
c1c75edc55 | ||
|
|
47cccc9ca5 | ||
|
|
5c97c57c76 | ||
|
|
ca0db57f24 | ||
|
|
8335ef780c | ||
|
|
1ad9793ea2 | ||
|
|
45e84722e1 | ||
|
|
f4e00b4d95 | ||
|
|
e740cbf403 | ||
|
|
44f75acebe | ||
|
|
0a100548a9 | ||
|
|
c0298c27a5 | ||
|
|
1fc34f1bcd | ||
|
|
2c325136ab |
@@ -0,0 +1,37 @@
|
||||
# CODEOWNERS — 善缘丹阳公益婚恋平台 审查角色分配(草案)
|
||||
#
|
||||
# 作用:开 PR 时 GitHub 自动向对应路径的 owner 请求审查;配合分支保护与
|
||||
# docs/governance/CODE_REVIEW_STANDARDS.md 的 T0/T1/T2 分级与双审规则使用。
|
||||
# 语法:https://docs.github.com/en/repositories/managing-your-repositories-settings-and-features/customizing-your-repository/about-code-owners
|
||||
#
|
||||
# 当前为一人团队,默认全部归技术负责人 @g1307092382。
|
||||
# 待扩员时,把各端拆给对应熟悉者即可;T2 高危改动按审查标准须 2 人复核(其中 1 人为该端 owner)。
|
||||
# 说明:CODEOWNERS 只负责「请求谁审」,不强制「必须不同人」;双审由审查流程纪律保证。
|
||||
# 排序:子路径必须放在父路径之后(GitHub 取最后一个匹配的规则)。
|
||||
|
||||
# —— 默认兜底 ——
|
||||
* @g1307092382
|
||||
|
||||
# —— 后端(Spring Boot / Java)——
|
||||
/backend/ @g1307092382
|
||||
|
||||
# 数据库迁移(Flyway):schema 变更属 T2,须重点复核(放在 /backend/ 之后)
|
||||
/backend/src/main/resources/db/migration/ @g1307092382
|
||||
|
||||
# —— 微信小程序(原生 WXML/WXSS/TS)——
|
||||
/miniapp/ @g1307092382
|
||||
|
||||
# —— 管理端(Vue3 / TS / pnpm)——
|
||||
/admin-web/ @g1307092382
|
||||
|
||||
# —— 测试与契约守卫(跨端契约,需熟悉各端)——
|
||||
/tests/ @g1307092382
|
||||
/ui-tests/ @g1307092382
|
||||
/scripts/run-ui-contracts.mjs @g1307092382
|
||||
|
||||
# —— 基础设施 / 部署(Compose / 镜像 / 密钥)——
|
||||
/infrastructure/ @g1307092382
|
||||
|
||||
# —— 治理与审查机制文档(变更须经技术负责人确认)——
|
||||
/docs/governance/ @g1307092382
|
||||
/.github/ @g1307092382
|
||||
@@ -0,0 +1,69 @@
|
||||
<!--
|
||||
提 PR 前请先读 docs/governance/CODE_REVIEW_STANDARDS.md。
|
||||
本模板是合并准入的硬性门槛:逐项打勾 = 已实际验证(不是"应该没问题")。
|
||||
证据优先:描述里的"✅已完成"不是证据,请贴命令+输出/代码 diff/实测结论。
|
||||
-->
|
||||
|
||||
## 变更摘要
|
||||
<!-- 改了什么、为什么、影响面 -->
|
||||
|
||||
## 风险分级(见审查标准 §2)
|
||||
- [ ] T0 琐碎(纯文案/文档/格式化/资源重命名)
|
||||
- [ ] T1 常规(单端功能/Bug/UI/单 API)
|
||||
- [ ] T2 高危(鉴权/支付/隐私/跨端契约/DB schema/并发幂等/已知阻塞项)— 需 2 人复核
|
||||
|
||||
## 验证方式(必填,证据优先)
|
||||
<!-- 贴实际跑过的命令与关键输出;不要只写"已自测通过" -->
|
||||
- 本地测试/契约守卫命令与结果:
|
||||
- 运行时实测(如涉及渲染/接口,贴 mock/路由/关键响应):
|
||||
- 负向注入(新增或修改测试时必填:故意改坏后测试是否转红):
|
||||
|
||||
## 技术栈审查清单(按本 PR 涉及项打勾)
|
||||
### 后端 Java / Spring Boot
|
||||
- [ ] 业务拒绝用 `BusinessException`+`ApiResponseCode`(HTTP 400≤code<500),无裸 `RuntimeException`
|
||||
- [ ] 测试对业务拒绝断言 `400 ≤ status < 500`(非仅 `!= 200`)
|
||||
- [ ] 核心不变量(INV-014/015、Required/Mutual/Block 等)未被绕过
|
||||
- [ ] 主键/唯一键/CHECK 约束与 Java 枚举一致,无静默 no-op 写
|
||||
- [ ] 无新增死表/死配置(`system_configs`/`match_rule_configs` 类)
|
||||
|
||||
### 小程序 miniapp
|
||||
- [ ] `app.json`/`pages.json` 路径与磁盘文件一致、无前导 `/`
|
||||
- [ ] `ignoreDevUnusedFiles`/`ignoreUploadUnusedFiles` = false(资源不被吞)
|
||||
- [ ] 跨端字段名与后端规范名一致(tsc 不保护 JS 层字段名)
|
||||
- [ ] WXSS 无通配符/属性选择器/嵌套注释;`<image>` 显式高度
|
||||
- [ ] 胶囊安全区让出 `--nav-right`
|
||||
|
||||
### 管理端 admin-web
|
||||
- [ ] 渲染相关状态走 `ref`/`reactive`,已补渲染态实测
|
||||
- [ ] 颜色/字号收敛到 `src/theme/` token,EP 主色阶补全 `-light-N`/`-dark-2`/`-rgb`
|
||||
- [ ] 表单校验类型安全、出错保留输入
|
||||
- [ ] 触摸目标 ≥44px,尊重 `prefers-reduced-motion`
|
||||
|
||||
### 数据库迁移 SQL
|
||||
- [ ] `V<序号>__<描述>.sql` 命名,版本连续唯一
|
||||
- [ ] 向后兼容,NOT NULL 新列有默认值/迁移
|
||||
- [ ] CHECK 约束与枚举一致,破坏性变更有回滚方案
|
||||
|
||||
### 测试 / 契约守卫
|
||||
- [ ] 无空壳 `skip`/`pass` 测试
|
||||
- [ ] 已做负向注入证明判别力
|
||||
- [ ] `scripts/run-ui-contracts.mjs` 的 `MIN_GUARDS`(当前 23) 同步(增删守卫必改)
|
||||
|
||||
### 脚本 / 基础设施
|
||||
- [ ] 脚本真实依赖已在 CI 对应 job 安装(非仅本地能跑)
|
||||
- [ ] 密钥仅运行期、不落盘;本地栈固定 `-p danyang`
|
||||
|
||||
## 判据纪律自查(见审查标准 §5,对应改动必查)
|
||||
- [ ] 非空数据验证(无空数据假绿,如推荐/列表返回空也能过)
|
||||
- [ ] 无直连绕过(关键路径至少一个经 HTTP 层断言)
|
||||
- [ ] 约束相关改动在带约束环境验证(无测试库缺约束假绿)
|
||||
- [ ] 小程序改动不走 `Mini Program Compile Check` 的"仅 tsc"假绿,已真编译/查资源
|
||||
- [ ] 合并后回读 `git rev-parse HEAD` + 轮询 CI 确认本次 head 真 success
|
||||
|
||||
## 已知阻塞 / 决策关联
|
||||
- [ ] 本 PR 是否触碰上线阻塞项(微信真实登录 / 照片直传落库)?若是:✅本次解决 / ⚠️未解决已登记 known-risks
|
||||
- [ ] 是否与 `decision-register` 的 LOCKED 决策冲突?若是:已回决策层确认(附结论)
|
||||
- [ ] 是否产生新债务?若是:已登记 `known-risks.md`(编号 KR-xx)
|
||||
|
||||
## 关联
|
||||
<!-- 关联 Issue / 决策 / 风险编号 -->
|
||||
@@ -25,6 +25,13 @@ jobs:
|
||||
working-directory: backend
|
||||
run: mvn verify -B
|
||||
|
||||
# 后端契约门禁(与 scripts/run-ui-contracts.mjs 同级):
|
||||
# 固化关键后端回归/契约测试(含 v1.1.0 修复的 3 个回归测试 + JwtAuthFilter Cookie 兜底
|
||||
# + 核心不变量),先校验这些测试源文件存在性下限(防改名/删除后门禁假绿),
|
||||
# 再用 `mvn test -Dtest=<列表>` 真跑。复用本 job 已编译产物与依赖缓存,开销极小。
|
||||
- name: 后端契约门禁(curated + 下限校验)
|
||||
run: node scripts/run-backend-contracts.mjs
|
||||
|
||||
- name: Upload Test Results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <https://unlicense.org/>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "danyang-match-admin",
|
||||
"version": "1.0.0-rc.2",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
# 后者生成 Vue 版本桥接),允许它们执行。
|
||||
packages:
|
||||
- '.'
|
||||
allowBuilds:
|
||||
esbuild: set this to true or false
|
||||
vue-demi: set this to true or false
|
||||
onlyBuiltDependencies:
|
||||
- esbuild
|
||||
- vue-demi
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import router from '@/router'
|
||||
import { getAccessToken, setAccessToken, clearAccessToken } from '@/utils/token'
|
||||
|
||||
const client = axios.create({
|
||||
baseURL: '/api/v1',
|
||||
timeout: 10000,
|
||||
})
|
||||
|
||||
// 防止 401 时并发触发多次刷新
|
||||
let refreshing = false
|
||||
|
||||
client.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
@@ -17,11 +21,45 @@ client.interceptors.request.use((config) => {
|
||||
|
||||
client.interceptors.response.use(
|
||||
(res) => res.data,
|
||||
(err) => {
|
||||
if (err.response?.status === 401) {
|
||||
localStorage.removeItem('accessToken')
|
||||
router.push('/login')
|
||||
async (err) => {
|
||||
const status = err.response?.status
|
||||
const original = err.config
|
||||
const isAuthEndpoint = !!original?.url?.includes('/auth/operator/')
|
||||
|
||||
// access token 过期:尝试用 HttpOnly refresh Cookie 静默刷新一次后重试原请求
|
||||
// __retried 防止刷新后重试仍 401 时再次触发刷新,形成循环
|
||||
if (status === 401 && !refreshing && !isAuthEndpoint && !(original as any)?.__retried) {
|
||||
refreshing = true
|
||||
try {
|
||||
const resp: any = await client.post('/auth/operator/refresh', {})
|
||||
if (resp?.success) {
|
||||
const newToken = resp.data.accessToken
|
||||
setAccessToken(newToken)
|
||||
refreshing = false
|
||||
;(original as any).__retried = true
|
||||
const headers = (original.headers || {}) as Record<string, string>
|
||||
headers.Authorization = `Bearer ${newToken}`
|
||||
original.headers = headers as any
|
||||
return client(original)
|
||||
}
|
||||
} catch {
|
||||
// 刷新失败:清除并跳登录
|
||||
} finally {
|
||||
refreshing = false
|
||||
}
|
||||
clearAccessToken()
|
||||
ElMessage.error('登录已过期,请重新登录')
|
||||
router.push('/login')
|
||||
return Promise.reject(err)
|
||||
}
|
||||
|
||||
// 刷新/登录等鉴权端点自身 401:交由调用方处理文案,不全局弹窗跳转
|
||||
if (status === 401) {
|
||||
if (!isAuthEndpoint) {
|
||||
clearAccessToken()
|
||||
ElMessage.error('登录已过期,请重新登录')
|
||||
router.push('/login')
|
||||
}
|
||||
} else if (err.response?.data?.message) {
|
||||
ElMessage.error(err.response.data.message)
|
||||
} else {
|
||||
|
||||
@@ -174,8 +174,8 @@ const navigation: NavigationItem[] = [
|
||||
{ label: '用户管理', path: '/users', permissions: ['user.view'], icon: User },
|
||||
{ label: '资料审核', path: '/review', permissions: ['review.view'], icon: DocumentChecked },
|
||||
{ label: '匹配管理', path: '/activities/interests', permissions: ['activity.review_registration'], icon: StarFilled },
|
||||
{ label: '公益红娘', path: '/referral', permissions: ['referral.manage'], icon: Connection },
|
||||
{ label: '红娘服务', path: '/matchmaker', permissions: ['matchmaker.service.view'], icon: Connection },
|
||||
{ label: '公益红娘', path: '/referral', permissions: ['matchmaker.service'], icon: Connection },
|
||||
{ label: '红娘服务', path: '/matchmaker', permissions: ['matchmaker.view'], icon: Connection },
|
||||
{ label: '公益咨询', path: '/counseling', permissions: ['counseling.service.view'], icon: ChatDotRound },
|
||||
{ label: '活动管理', path: '/activities', permissions: ['activity.view'], icon: Calendar },
|
||||
{ label: '活动签到', path: '/activities/checkin', permissions: ['activity.checkin'], icon: Calendar },
|
||||
@@ -217,7 +217,7 @@ const currentRoleName = computed(() => {
|
||||
if (perms.includes('counseling.service.view')) return '公益咨询人员'
|
||||
if (perms.includes('service_appointment.view')) return '服务站运营人员'
|
||||
if (perms.includes('review.view')) return '资料审核人员'
|
||||
if (perms.includes('matchmaker.service.view')) return '公益红娘'
|
||||
if (perms.includes('matchmaker.view')) return '公益红娘'
|
||||
return '运营人员'
|
||||
})
|
||||
const visibleNavigation = computed(() => navigation.filter((item) => item.permissions.every(hasPerm)))
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
/**
|
||||
* U32 活动签到工作台(Phase 15)
|
||||
*
|
||||
@@ -111,7 +112,7 @@ const TYPE_TEXT: Record<string, string> = {
|
||||
}
|
||||
const typeText = (t: string) => TYPE_TEXT[t] || t || '未分类'
|
||||
|
||||
const authHeader = () => ({ Authorization: `Bearer ${localStorage.getItem('accessToken') || ''}` })
|
||||
const authHeader = () => ({ Authorization: `Bearer ${getAccessToken() || ''}` })
|
||||
|
||||
const formatTime = (v: any) => {
|
||||
if (!v) return '-'
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get } from '@/api/client'
|
||||
|
||||
@@ -55,7 +56,7 @@ const mutualList = ref<any[]>([])
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/activities/operator/activity-interest-summary', {}, { Authorization: `Bearer ${token}` })
|
||||
const rows = res.data || []
|
||||
tableData.value = searchActivityId.value
|
||||
@@ -72,7 +73,7 @@ async function viewMutuals(activityId: string) {
|
||||
drawerVisible.value = true
|
||||
currentActivity.value = tableData.value.find(row => row.activityId === activityId)
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const mutualRes: any = await get(`/activities/operator/${activityId}/mutuals`, {}, { Authorization: `Bearer ${token}` })
|
||||
mutualList.value = mutualRes.data || []
|
||||
} catch (e) {
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
/**
|
||||
* 活动管理(V1.1 Phase 14)
|
||||
*
|
||||
@@ -259,7 +260,7 @@ function emptyForm() {
|
||||
}
|
||||
|
||||
function authHeader() {
|
||||
return { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
|
||||
return { Authorization: `Bearer ${getAccessToken()}` }
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
|
||||
@@ -213,6 +213,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { get } from '@/api/client'
|
||||
import { token } from '@/theme/tokens'
|
||||
@@ -302,7 +303,7 @@ async function loadFunnel() {
|
||||
try {
|
||||
// 注意:这里曾是 `const token = ...`,与顶部从 @/theme/tokens 导入的**颜色助手**
|
||||
// `token` 同名(函数内遮蔽)。现已改名 authToken,避免后续在函数内误用颜色助手。
|
||||
const authToken = localStorage.getItem('accessToken')
|
||||
const authToken = getAccessToken()
|
||||
if (dateRange.value[0] && dateRange.value[1]) {
|
||||
const [userRes, matchRes, safetyRes, v11Res]: any[] = await Promise.all([
|
||||
get('/operator/analytics/user-funnel', {
|
||||
@@ -328,7 +329,7 @@ async function loadFunnel() {
|
||||
|
||||
async function loadDailySummary() {
|
||||
try {
|
||||
const authToken = localStorage.getItem('accessToken')
|
||||
const authToken = getAccessToken()
|
||||
const res: any = await get('/operator/analytics/daily-summary', { days: 30 }, { Authorization: `Bearer ${authToken}` })
|
||||
dailySummary.value = res.data || []
|
||||
} catch (e) { console.error(e) }
|
||||
|
||||
@@ -84,6 +84,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get, post } from '@/api/client'
|
||||
import { token as tokenColor } from '@/theme/tokens'
|
||||
@@ -109,7 +110,7 @@ const STATUS_MAP: Record<string, { text: string; type: string }> = {
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/appeals/pending', {}, { Authorization: `Bearer ${token}` })
|
||||
tableData.value = res.data || []
|
||||
loadStats()
|
||||
@@ -119,7 +120,7 @@ async function loadData() {
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/appeals/stats', {}, { Authorization: `Bearer ${token}` })
|
||||
const data = res.data || {}
|
||||
stats.value = [
|
||||
@@ -138,7 +139,7 @@ async function openDetail(id: string) {
|
||||
decision.value = 'approve'
|
||||
decisionNote.value = ''
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get(`/operator/appeals/${id}`, {}, { Authorization: `Bearer ${token}` })
|
||||
detail.value = res.data
|
||||
} catch (e) { console.error(e) }
|
||||
@@ -148,7 +149,7 @@ async function handleProcess() {
|
||||
if (!decision.value) return
|
||||
processing.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
await post(`/operator/appeals/${currentId.value}/process`,
|
||||
{ decision: decision.value, decisionNote: decisionNote.value },
|
||||
{ Authorization: `Bearer ${token}` })
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get } from '@/api/client'
|
||||
|
||||
@@ -70,7 +71,7 @@ const ACTION_TEXT: Record<string, string> = {
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/audit/logs', {
|
||||
resourceType: resourceFilter.value || undefined,
|
||||
page: page.value,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
<el-card>
|
||||
<template #header><div class="card-header"><span>公益红娘管理</span></div></template>
|
||||
<el-tabs v-model="activeTab">
|
||||
<el-tab-pane label="服务请求队列" name="services">
|
||||
<!-- ZC-MM-002:服务请求队列仅分配权持有者可见(matchmaker.assign 或 matchmaker.team.assign) -->
|
||||
<el-tab-pane v-if="canAssign" label="服务请求队列" name="services">
|
||||
<el-table :data="services" stripe v-loading="loading">
|
||||
<el-table-column prop="userId" label="用户ID" width="120" />
|
||||
<el-table-column prop="serviceType" label="服务类型" width="160">
|
||||
@@ -19,7 +20,7 @@
|
||||
<el-table-column label="操作" width="200">
|
||||
<template #default="{ row }">
|
||||
<el-button v-if="row.status==='submitted'" size="small" type="primary" @click="openAssign(row)">分配</el-button>
|
||||
<el-button v-if="row.status==='assigned' || row.status==='processing'" size="small" @click="openRecommendation(row)">创建推荐</el-button>
|
||||
<el-button v-if="row.status==='assigned' || row.status==='in_service'" size="small" @click="openRecommendation(row)">创建推荐</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@@ -38,16 +39,77 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
|
||||
<!-- ZC-MM-002 新增:服务对象分配(本人名下生效中的分配 + 转分配/撤销/结束) -->
|
||||
<el-tab-pane label="服务对象分配" name="assignments">
|
||||
<el-table :data="assignments" stripe v-loading="assignmentsLoading">
|
||||
<el-table-column prop="userId" label="用户ID" width="120" />
|
||||
<el-table-column prop="assignmentScope" label="范围" width="90">
|
||||
<template #default="{ row }">{{ assignmentScopeLabel(row.assignmentScope) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assignmentReason" label="分配理由" show-overflow-tooltip />
|
||||
<el-table-column prop="status" label="状态" width="90">
|
||||
<template #default="{ row }"><el-tag :type="assignmentStatusTag(row.status)">{{ assignmentStatusLabel(row.status) }}</el-tag></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assignedAt" label="分配时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.assignedAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="expiresAt" label="有效期至" width="170">
|
||||
<template #default="{ row }">{{ row.expiresAt ? formatDateTime(row.expiresAt) : '长期' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="220">
|
||||
<template #default="{ row }">
|
||||
<el-button size="small" type="primary" @click="openTransfer(row)">转分配</el-button>
|
||||
<el-button size="small" @click="openTerminate(row, 'revoke')">撤销</el-button>
|
||||
<el-button size="small" @click="openTerminate(row, 'end')">结束</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
<!-- ZC-MM-003 / B1 立项:受控联系授权(审批岗队列 + 本人授权/撤销) -->
|
||||
<el-tab-pane label="联系授权审批" name="contactAuths">
|
||||
<el-table :data="contactAuths" stripe v-loading="contactAuthsLoading">
|
||||
<el-table-column prop="operatorId" label="红娘ID" width="120" />
|
||||
<el-table-column prop="userId" label="用户ID" width="120" />
|
||||
<el-table-column prop="channel" label="渠道" width="110">
|
||||
<template #default="{ row }">{{ contactChannelLabel(row.channel) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="purpose" label="授权目的" show-overflow-tooltip />
|
||||
<el-table-column prop="status" label="状态" width="110">
|
||||
<template #default="{ row }"><el-tag :type="contactStatusTag(row.status)">{{ contactStatusLabel(row.status) }}</el-tag></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createdAt" label="申请时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="expiresAt" label="窗口/有效期至" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.expiresAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="220">
|
||||
<template #default="{ row }">
|
||||
<template v-if="row.status === 'pending_approval' && canApprove">
|
||||
<el-button size="small" type="primary" @click="doContactApprove(row)">批准</el-button>
|
||||
<el-button size="small" type="danger" @click="doContactReject(row)">拒绝</el-button>
|
||||
</template>
|
||||
<el-button v-if="['active','pending_approval','pending_consent'].includes(row.status)"
|
||||
size="small" @click="doContactRevoke(row)">撤销</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-card>
|
||||
|
||||
<!-- 分配弹窗 -->
|
||||
<el-dialog v-model="assignDialogVisible" title="分配红娘服务" width="400px">
|
||||
<el-form label-width="80px">
|
||||
<el-form-item label="红娘"><el-select v-model="assignForm.operatorId" placeholder="选择红娘">
|
||||
<el-option label="王红娘" value="operator_wang" />
|
||||
<el-option label="陈红娘" value="operator_chen" />
|
||||
</el-select></el-form-item>
|
||||
<!-- 分配弹窗(ZC-MM-002:去硬编码红娘名单,改为加载可分配红娘接口;理由必填) -->
|
||||
<el-dialog v-model="assignDialogVisible" title="分配红娘服务" width="440px">
|
||||
<el-form label-width="90px">
|
||||
<el-form-item label="红娘">
|
||||
<el-select v-model="assignForm.matchmakerOperatorId" placeholder="选择红娘" style="width: 100%">
|
||||
<el-option v-for="op in assignableMatchmakers" :key="op.id" :label="op.name" :value="op.id" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="分配理由" required>
|
||||
<el-input v-model="assignForm.reason" type="textarea" :rows="2" placeholder="说明分配依据(必填)" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="assignDialogVisible=false">取消</el-button>
|
||||
@@ -55,6 +117,37 @@
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 转分配弹窗(ZC-MM-002:服务对象分配) -->
|
||||
<el-dialog v-model="transferDialogVisible" title="转分配服务对象" width="440px">
|
||||
<el-form label-width="90px">
|
||||
<el-form-item label="新红娘">
|
||||
<el-select v-model="transferForm.newMatchmakerOperatorId" placeholder="选择接手红娘" style="width: 100%">
|
||||
<el-option v-for="op in assignableMatchmakers" :key="op.id" :label="op.name" :value="op.id" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="转分配理由" required>
|
||||
<el-input v-model="transferForm.reason" type="textarea" :rows="2" placeholder="说明转分配依据(必填)" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="transferDialogVisible=false">取消</el-button>
|
||||
<el-button type="primary" @click="doTransfer">确认转分配</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 撤销/结束弹窗(ZC-MM-002:服务对象分配) -->
|
||||
<el-dialog v-model="terminateDialogVisible" :title="terminateAction==='revoke' ? '撤销服务对象分配' : '结束服务对象分配'" width="440px">
|
||||
<el-form label-width="90px">
|
||||
<el-form-item :label="terminateAction==='revoke' ? '撤销理由' : '结束理由'" required>
|
||||
<el-input v-model="terminateForm.reason" type="textarea" :rows="2" placeholder="说明理由(必填)" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="terminateDialogVisible=false">取消</el-button>
|
||||
<el-button type="danger" @click="doTerminate">确认</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 创建推荐弹窗 -->
|
||||
<el-dialog v-model="recDialogVisible" title="创建红娘推荐" width="480px">
|
||||
<el-form label-width="100px">
|
||||
@@ -71,18 +164,35 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { get, post } from '@/api/client'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const activeTab = ref('services')
|
||||
const authStore = useAuthStore()
|
||||
// ZC-MM-002:分配权 = matchmaker.assign(平台授权)或 matchmaker.team.assign(红娘组长)
|
||||
const canAssign = computed(() => {
|
||||
const perms: string[] = authStore.permissions || []
|
||||
return perms.includes('matchmaker.assign') || perms.includes('matchmaker.team.assign')
|
||||
})
|
||||
|
||||
const activeTab = ref(canAssign.value ? 'services' : 'assignments')
|
||||
const loading = ref(false)
|
||||
const services = ref<any[]>([])
|
||||
const recommendations = ref<any[]>([])
|
||||
const assignments = ref<any[]>([])
|
||||
const assignmentsLoading = ref(false)
|
||||
const assignableMatchmakers = ref<any[]>([])
|
||||
const assignDialogVisible = ref(false)
|
||||
const recDialogVisible = ref(false)
|
||||
const transferDialogVisible = ref(false)
|
||||
const terminateDialogVisible = ref(false)
|
||||
const currentServiceId = ref('')
|
||||
const assignForm = ref({ operatorId: '' })
|
||||
const currentUserId = ref('')
|
||||
const currentAssignmentId = ref('')
|
||||
const terminateAction = ref<'revoke' | 'end'>('revoke')
|
||||
const assignForm = ref({ matchmakerOperatorId: '', reason: '' })
|
||||
const transferForm = ref({ newMatchmakerOperatorId: '', reason: '' })
|
||||
const terminateForm = ref({ reason: '' })
|
||||
const recForm = ref({ userId: '', targetUserId: '', reason: '' })
|
||||
|
||||
const SERVICE_TYPE_LABEL: Record<string, string> = {
|
||||
@@ -90,10 +200,12 @@ const SERVICE_TYPE_LABEL: Record<string, string> = {
|
||||
referral_activity: '转介活动', referral_station: '转介服务站'
|
||||
}
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
submitted: '待分配', assigned: '已分配', processing: '处理中', completed: '已完成', cancelled: '已取消'
|
||||
submitted: '待分配', assigned: '已分配', in_service: '服务中', waiting_user: '等待用户',
|
||||
processing: '处理中', completed: '已完成', cancelled: '已取消'
|
||||
}
|
||||
const STATUS_TAG: Record<string, string> = {
|
||||
submitted: 'warning', assigned: 'primary', processing: '', completed: 'success', cancelled: 'danger'
|
||||
submitted: 'warning', assigned: 'primary', in_service: 'primary', waiting_user: 'warning',
|
||||
processing: '', completed: 'success', cancelled: 'danger'
|
||||
}
|
||||
const REC_STATUS_LABEL: Record<string, string> = {
|
||||
pending_view: '待用户查看', viewed: '已查看', liked: '已喜欢',
|
||||
@@ -103,18 +215,79 @@ const REC_STATUS_TAG: Record<string, string> = {
|
||||
pending_view: 'warning', viewed: 'info', liked: 'primary',
|
||||
passed: 'info', confirmed_mutual: 'success', rejected: 'danger', expired: 'info'
|
||||
}
|
||||
const ASSIGNMENT_STATUS_LABEL: Record<string, string> = {
|
||||
active: '生效中', ended: '已结束', revoked: '已撤销', transferred: '已转分配', expired: '已过期'
|
||||
}
|
||||
const ASSIGNMENT_STATUS_TAG: Record<string, string> = {
|
||||
active: 'success', ended: 'info', revoked: 'danger', transferred: 'info', expired: 'info'
|
||||
}
|
||||
|
||||
// ===== ZC-MM-003 / B1:受控联系授权(枚举码不上屏,中文映射) =====
|
||||
const CONTACT_CHANNEL_LABEL: Record<string, string> = {
|
||||
phone: '电话联系', offline_meeting: '线下见面', full_contact: '完整联系方式'
|
||||
}
|
||||
const CONTACT_STATUS_LABEL: Record<string, string> = {
|
||||
pending_approval: '待审批', pending_consent: '待用户确认', active: '生效中',
|
||||
rejected: '已拒绝', expired: '已过期', revoked: '已撤销'
|
||||
}
|
||||
const CONTACT_STATUS_TAG: Record<string, string> = {
|
||||
pending_approval: 'warning', pending_consent: 'warning', active: 'success',
|
||||
rejected: 'danger', expired: 'info', revoked: 'info'
|
||||
}
|
||||
|
||||
function serviceTypeLabel(t: string) { return SERVICE_TYPE_LABEL[t] || t }
|
||||
function statusLabel(s: string) { return STATUS_LABEL[s] || s }
|
||||
function statusTag(s: string) { return STATUS_TAG[s] || 'info' }
|
||||
function recStatusLabel(s: string) { return REC_STATUS_LABEL[s] || s }
|
||||
function recStatusTag(s: string) { return REC_STATUS_TAG[s] || 'info' }
|
||||
function assignmentStatusLabel(s: string) { return ASSIGNMENT_STATUS_LABEL[s] || s }
|
||||
function assignmentStatusTag(s: string) { return ASSIGNMENT_STATUS_TAG[s] || 'info' }
|
||||
function assignmentScopeLabel(s: string) { return s === 'primary' ? '主责' : '协同' }
|
||||
function formatDateTime(d: string) { return d ? new Date(d).toLocaleString('zh-CN') : '-' }
|
||||
function contactChannelLabel(s: string) { return CONTACT_CHANNEL_LABEL[s] || s }
|
||||
function contactStatusLabel(s: string) { return CONTACT_STATUS_LABEL[s] || s }
|
||||
function contactStatusTag(s: string) { return CONTACT_STATUS_TAG[s] || 'info' }
|
||||
|
||||
// ===== ZC-MM-003 / B1:受控联系授权 =====
|
||||
// 审批岗客户端可见性提示(真实判定在 Service 层动态执行:principal 权限 ∈ approver-authorities 配置)
|
||||
const canApprove = computed(() => {
|
||||
const perms: string[] = authStore.permissions || []
|
||||
return perms.includes('matchmaker.assign') || perms.includes('matchmaker.team.assign')
|
||||
})
|
||||
const contactAuths = ref<any[]>([])
|
||||
const contactAuthsLoading = ref(false)
|
||||
|
||||
async function loadContactAuths() {
|
||||
contactAuthsLoading.value = true
|
||||
try { const res: any = await get('/operator/matchmaker/contact-authorizations/my'); contactAuths.value = res?.data?.list || [] } finally { contactAuthsLoading.value = false }
|
||||
}
|
||||
async function doContactApprove(row: any) {
|
||||
try {
|
||||
await post(`/operator/matchmaker/contact-authorizations/${row.id}/approve`, {})
|
||||
ElMessage.success('已批准,等待用户单独确认'); loadContactAuths()
|
||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||
}
|
||||
async function doContactReject(row: any) {
|
||||
try {
|
||||
await post(`/operator/matchmaker/contact-authorizations/${row.id}/reject`, {})
|
||||
ElMessage.success('已拒绝'); loadContactAuths()
|
||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||
}
|
||||
async function doContactRevoke(row: any) {
|
||||
try {
|
||||
const { value } = await ElMessageBox.prompt('撤销理由(必填)', '撤销联系授权', {
|
||||
confirmButtonText: '确认撤销', cancelButtonText: '取消',
|
||||
inputValidator: (v: string) => (v && v.trim() ? true : '撤销理由必填'),
|
||||
})
|
||||
await post(`/operator/matchmaker/contact-authorizations/${row.id}/revoke`, { reason: value.trim() })
|
||||
ElMessage.success('已撤销'); loadContactAuths()
|
||||
} catch { /* 用户取消 */ }
|
||||
}
|
||||
|
||||
async function loadServices() {
|
||||
loading.value = true
|
||||
// Phase 13 契约修复:原 `/matchmaker/services/operator/queue` 后端不存在(404)。
|
||||
// 后端实际为 GET /operator/matchmaker/pending(待分配队列)。
|
||||
// 后端实际为 GET /operator/matchmaker/pending(待分配队列,ZC-MM-002 后仅分配权持有者可调)。
|
||||
try { const res: any = await get('/operator/matchmaker/pending'); services.value = res?.data || [] } finally { loading.value = false }
|
||||
}
|
||||
async function loadRecommendations() {
|
||||
@@ -123,19 +296,81 @@ async function loadRecommendations() {
|
||||
// 后端新增 GET /operator/matchmaker/recommendations(限本人名下服务的推荐)。
|
||||
try { const res: any = await get('/operator/matchmaker/recommendations'); recommendations.value = res?.data || [] } finally { loading.value = false }
|
||||
}
|
||||
async function loadAssignments() {
|
||||
assignmentsLoading.value = true
|
||||
// ZC-MM-002:本人名下生效中的服务对象分配
|
||||
try { const res: any = await get('/operator/matchmaker/assignments/my'); assignments.value = res?.data || [] } finally { assignmentsLoading.value = false }
|
||||
}
|
||||
async function loadAssignableMatchmakers() {
|
||||
// ZC-MM-002:去硬编码红娘名单,改为后端可分配红娘接口(组长按组织过滤、平台授权人员全部)
|
||||
try { const res: any = await get('/operator/matchmaker/assignments/assignable-matchmakers'); assignableMatchmakers.value = res?.data || [] } catch { assignableMatchmakers.value = [] }
|
||||
}
|
||||
async function refresh() {
|
||||
if (activeTab.value === 'services') await loadServices(); else await loadRecommendations()
|
||||
if (activeTab.value === 'services') await loadServices()
|
||||
else if (activeTab.value === 'assignments') await loadAssignments()
|
||||
else if (activeTab.value === 'contactAuths') await loadContactAuths()
|
||||
else await loadRecommendations()
|
||||
}
|
||||
|
||||
async function openAssign(row: any) { currentServiceId.value = row.id; assignForm.value.operatorId = ''; assignDialogVisible.value = true }
|
||||
async function openAssign(row: any) {
|
||||
// /pending 返回字段为 serviceId(Phase 13 契约),兜底 row.id
|
||||
currentServiceId.value = row.serviceId || row.id
|
||||
currentUserId.value = row.userId
|
||||
assignForm.value = { matchmakerOperatorId: '', reason: '' }
|
||||
await loadAssignableMatchmakers()
|
||||
assignDialogVisible.value = true
|
||||
}
|
||||
async function doAssign() {
|
||||
// Phase 13 契约修复:原 PUT /matchmaker/services/{id}/assign → 后端为 POST /operator/matchmaker/services/{id}/assign
|
||||
if (!assignForm.value.matchmakerOperatorId) { ElMessage.warning('请选择红娘'); return }
|
||||
if (!assignForm.value.reason || !assignForm.value.reason.trim()) { ElMessage.warning('分配理由必填'); return }
|
||||
// ZC-MM-002:分配走统一分配接口(创建 assignment + 服务单联动置 assigned,同事务)
|
||||
try {
|
||||
await post(`/operator/matchmaker/services/${currentServiceId.value}/assign`, { operatorId: assignForm.value.operatorId })
|
||||
await post('/operator/matchmaker/assignments', {
|
||||
userId: currentUserId.value,
|
||||
matchmakerOperatorId: assignForm.value.matchmakerOperatorId,
|
||||
serviceId: currentServiceId.value,
|
||||
reason: assignForm.value.reason.trim()
|
||||
})
|
||||
ElMessage.success('分配成功'); assignDialogVisible.value = false; loadServices()
|
||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||
}
|
||||
|
||||
async function openTransfer(row: any) {
|
||||
currentAssignmentId.value = row.id
|
||||
transferForm.value = { newMatchmakerOperatorId: '', reason: '' }
|
||||
await loadAssignableMatchmakers()
|
||||
transferDialogVisible.value = true
|
||||
}
|
||||
async function doTransfer() {
|
||||
if (!transferForm.value.newMatchmakerOperatorId) { ElMessage.warning('请选择接手红娘'); return }
|
||||
if (!transferForm.value.reason || !transferForm.value.reason.trim()) { ElMessage.warning('转分配理由必填'); return }
|
||||
try {
|
||||
await post(`/operator/matchmaker/assignments/${currentAssignmentId.value}/transfer`, {
|
||||
newMatchmakerOperatorId: transferForm.value.newMatchmakerOperatorId,
|
||||
reason: transferForm.value.reason.trim()
|
||||
})
|
||||
ElMessage.success('转分配成功'); transferDialogVisible.value = false; loadAssignments()
|
||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||
}
|
||||
|
||||
function openTerminate(row: any, action: 'revoke' | 'end') {
|
||||
currentAssignmentId.value = row.id
|
||||
terminateAction.value = action
|
||||
terminateForm.value = { reason: '' }
|
||||
terminateDialogVisible.value = true
|
||||
}
|
||||
async function doTerminate() {
|
||||
if (!terminateForm.value.reason || !terminateForm.value.reason.trim()) {
|
||||
ElMessage.warning(terminateAction.value === 'revoke' ? '撤销理由必填' : '结束理由必填'); return
|
||||
}
|
||||
try {
|
||||
await post(`/operator/matchmaker/assignments/${currentAssignmentId.value}/${terminateAction.value}`, {
|
||||
reason: terminateForm.value.reason.trim()
|
||||
})
|
||||
ElMessage.success('操作成功'); terminateDialogVisible.value = false; loadAssignments()
|
||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||
}
|
||||
|
||||
function openRecommendation(row: any) {
|
||||
currentServiceId.value = row.id
|
||||
recForm.value = { userId: row.userId, targetUserId: '', reason: '' }
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get, post, put } from '@/api/client'
|
||||
|
||||
@@ -79,7 +80,7 @@ const orgMap = ref<Record<string, string>>({})
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/operators', { page: page.value, pageSize: pageSize.value }, { Authorization: `Bearer ${token}` })
|
||||
tableData.value = res.data?.list || []
|
||||
total.value = res.data?.total || 0
|
||||
@@ -89,7 +90,7 @@ async function loadData() {
|
||||
|
||||
async function loadOrgs() {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/operators/organizations', {}, { Authorization: `Bearer ${token}` })
|
||||
orgList.value = res.data || []
|
||||
orgList.value.forEach(o => { orgMap.value[o.id] = o.name })
|
||||
@@ -105,7 +106,7 @@ async function save() {
|
||||
if (!form.value.username || !form.value.password) return
|
||||
saving.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
await post('/operator/operators', form.value, { Authorization: `Bearer ${token}` })
|
||||
formVisible.value = false
|
||||
loadData()
|
||||
@@ -115,7 +116,7 @@ async function save() {
|
||||
|
||||
async function toggleStatus(row: any) {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const action = row.status === 'normal' ? 'disable' : 'enable'
|
||||
await put(`/operator/operators/${row.id}/${action}`, {}, { Authorization: `Bearer ${token}` })
|
||||
loadData()
|
||||
@@ -126,7 +127,7 @@ async function resetPwd(id: string) {
|
||||
const pwd = prompt('请输入新密码(至少8位)')
|
||||
if (!pwd || pwd.length < 8) return
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
await put(`/operator/operators/${id}/reset-password`, { newPassword: pwd }, { Authorization: `Bearer ${token}` })
|
||||
} catch (e) { console.error(e) }
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get, post, put } from '@/api/client'
|
||||
|
||||
@@ -78,7 +79,7 @@ const ORG_TYPE_TEXT: Record<string, string> = {
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/organizations', {}, { Authorization: `Bearer ${token}` })
|
||||
tableData.value = res.data || []
|
||||
} catch (e) { console.error(e) }
|
||||
@@ -101,7 +102,7 @@ async function save() {
|
||||
if (!form.value.name) return
|
||||
saving.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
if (editId.value) {
|
||||
await put(`/operator/organizations/${editId.value}`, form.value, {
|
||||
Authorization: `Bearer ${token}`
|
||||
@@ -119,7 +120,7 @@ async function save() {
|
||||
|
||||
async function toggleStatus(row: any) {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const action = row.status === 'normal' ? 'disable' : 'enable'
|
||||
await put(`/operator/organizations/${row.id}/${action}`, {}, {
|
||||
Authorization: `Bearer ${token}`
|
||||
|
||||
@@ -98,6 +98,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getAccessToken } from '@/utils/token'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { get, post } from '@/api/client'
|
||||
import { token as tokenColor } from '@/theme/tokens'
|
||||
@@ -124,7 +125,7 @@ const STATUS_MAP: Record<string, { text: string; type: string }> = {
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get(`/operator/risk/reports/${statusFilter.value}`, {}, { Authorization: `Bearer ${token}` })
|
||||
tableData.value = res.data || []
|
||||
loadStats()
|
||||
@@ -134,7 +135,7 @@ async function loadData() {
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get('/operator/risk/reports/stats', {}, { Authorization: `Bearer ${token}` })
|
||||
const data = res.data || {}
|
||||
stats.value = [
|
||||
@@ -152,7 +153,7 @@ async function openDetail(reportId: string) {
|
||||
processResult.value = 'no_action'
|
||||
processNote.value = ''
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
const res: any = await get(`/operator/risk/reports/${reportId}`, {}, { Authorization: `Bearer ${token}` })
|
||||
detail.value = res.data
|
||||
} catch (e) { console.error(e) }
|
||||
@@ -162,7 +163,7 @@ async function handleProcess() {
|
||||
if (!processResult.value) return
|
||||
processing.value = true
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const token = getAccessToken()
|
||||
await post(`/operator/risk/reports/${currentReportId.value}/process`,
|
||||
{ processResult: processResult.value, processNote: processNote.value },
|
||||
{ Authorization: `Bearer ${token}` })
|
||||
|
||||
@@ -37,8 +37,8 @@ const routes: RouteRecordRaw[] = [
|
||||
{ path: 'service-appointment', name: 'ServiceAppointment', component: () => import('@/modules/service-appointment/ServiceAppointmentView.vue'), meta: { title: '服务预约', permissions: ['service_appointment.view'] } },
|
||||
{ path: 'service-program', name: 'ServiceProgram', component: () => import('@/modules/service-program/ServiceProgramView.vue'), meta: { title: '专项服务项目', permissions: ['service_program.manage'] } },
|
||||
{ path: 'counseling', name: 'Counseling', component: () => import('@/modules/counseling/CounselingView.vue'), meta: { title: '婚恋咨询', permissions: ['counseling.service.view'] } },
|
||||
{ path: 'referral', name: 'ReferralManagement', component: () => import('@/modules/referral/ReferralManagementView.vue'), meta: { title: '转介管理', permissions: ['referral.manage'] } },
|
||||
{ path: 'matchmaker', name: 'MatchmakerManagement', component: () => import('@/modules/matchmaker/MatchmakerManagementView.vue'), meta: { title: '红娘管理', permissions: ['matchmaker.service.view'] } },
|
||||
{ path: 'referral', name: 'ReferralManagement', component: () => import('@/modules/referral/ReferralManagementView.vue'), meta: { title: '转介管理', permissions: ['matchmaker.service'] } },
|
||||
{ path: 'matchmaker', name: 'MatchmakerManagement', component: () => import('@/modules/matchmaker/MatchmakerManagementView.vue'), meta: { title: '红娘管理', permissions: ['matchmaker.view'] } },
|
||||
|
||||
],
|
||||
},
|
||||
@@ -48,10 +48,13 @@ const routes: RouteRecordRaw[] = [
|
||||
// 否则部署在 /admin/ 子路径下时,刷新或直达 /admin/xxx 会因路由匹配基准不符而白屏。
|
||||
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes })
|
||||
|
||||
router.beforeEach((to) => {
|
||||
router.beforeEach(async (to) => {
|
||||
const authStore = useAuthStore()
|
||||
const requiredPerms = (to.meta.permissions as string[]) || []
|
||||
|
||||
// 0. 页面刷新后内存态清空,先凭 HttpOnly refresh Cookie 静默恢复会话(无则跳登录)
|
||||
await authStore.initializeSession()
|
||||
|
||||
// 1. 登录检查
|
||||
if (to.path !== '/login' && !authStore.isLoggedIn) {
|
||||
return { path: '/login', query: { redirect: to.fullPath } }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { post } from '@/api/client'
|
||||
import { setAccessToken, clearAccessToken } from '@/utils/token'
|
||||
|
||||
interface OperatorInfo {
|
||||
operatorId: string
|
||||
@@ -12,9 +13,9 @@ interface OperatorInfo {
|
||||
|
||||
const previewRolePermissions: Record<string, string[]> = {
|
||||
reviewer: ['review.view', 'user.view'],
|
||||
counselor: ['counseling.service.view', 'referral.manage'],
|
||||
counselor: ['counseling.service.view', 'matchmaker.service'],
|
||||
station: ['service_location.view', 'service_appointment.view'],
|
||||
operator: ['review.view', 'user.view', 'organization.manage', 'permission.manage', 'activity.review_registration', 'risk.report.view', 'risk.report.process', 'analytics.view', 'banner.view', 'content.view', 'service_location.view', 'service_appointment.view', 'service_program.manage', 'counseling.service.view', 'referral.manage'],
|
||||
operator: ['review.view', 'user.view', 'organization.manage', 'permission.manage', 'activity.review_registration', 'risk.report.view', 'risk.report.process', 'analytics.view', 'banner.view', 'content.view', 'service_location.view', 'service_appointment.view', 'service_program.manage', 'counseling.service.view', 'matchmaker.view', 'matchmaker.service'],
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
@@ -23,38 +24,70 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
const previewOperator: OperatorInfo | null = previewRolePermissions[previewRole]
|
||||
? { operatorId: 'ui-preview', name: '界面验收员', username: 'preview', permissions: previewRolePermissions[previewRole], organizationId: null }
|
||||
: null
|
||||
const token = ref<string>(previewOperator ? 'ui-preview-only' : (localStorage.getItem('accessToken') || ''))
|
||||
const operator = ref<OperatorInfo | null>(
|
||||
previewOperator || JSON.parse(localStorage.getItem('operator') || 'null')
|
||||
)
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
const token = ref<string>(previewOperator ? 'ui-preview-only' : '')
|
||||
const operator = ref<OperatorInfo | null>(previewOperator)
|
||||
let sessionInitialized = false
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value && !!operator.value)
|
||||
const permissions = computed(() => operator.value?.permissions || [])
|
||||
// ZC-MM-002:最小只读 helper —— 组件按权限码做 UI 显隐(与后端 @PreAuthorize 同码)
|
||||
const hasPermission = (code: string) => permissions.value.includes(code)
|
||||
|
||||
function applyAuthData(data: any) {
|
||||
token.value = data.accessToken || ''
|
||||
operator.value = {
|
||||
operatorId: data.operatorId,
|
||||
name: data.name,
|
||||
username: data.username,
|
||||
permissions: data.permissions || [],
|
||||
organizationId: data.organizationId ?? null,
|
||||
}
|
||||
// 同步内存态令牌(供 axios 拦截器注入 Authorization 头;生产同源场景 Cookie 也会自动携带)
|
||||
setAccessToken(token.value)
|
||||
}
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
const res: any = await post('/auth/operator/login', { username, password })
|
||||
if (res.success) {
|
||||
token.value = res.data.accessToken
|
||||
operator.value = {
|
||||
operatorId: res.data.operatorId,
|
||||
name: res.data.name,
|
||||
username: res.data.username,
|
||||
permissions: res.data.permissions || [],
|
||||
organizationId: res.data.organizationId ?? null,
|
||||
}
|
||||
localStorage.setItem('accessToken', res.data.accessToken)
|
||||
localStorage.setItem('operator', JSON.stringify(operator.value))
|
||||
applyAuthData(res.data)
|
||||
return res.data
|
||||
}
|
||||
throw new Error(res.message || '登录失败')
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = ''
|
||||
operator.value = null
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('operator')
|
||||
/**
|
||||
* 静默恢复会话:页面刷新后内存态清空,凭 HttpOnly refresh Cookie(dy_op_rt)刷新令牌,
|
||||
* 无需用户重新登录。refresh token 不落地、不可被 JS 读取,抗 XSS。
|
||||
* 开发跨端口代理下 Cookie 不共享,刷新将失败并回落到登录页(符合预期)。
|
||||
*/
|
||||
async function initializeSession(): Promise<boolean> {
|
||||
if (sessionInitialized) return isLoggedIn.value
|
||||
sessionInitialized = true
|
||||
if (token.value) return true
|
||||
try {
|
||||
const res: any = await post('/auth/operator/refresh', {})
|
||||
if (res.success) {
|
||||
applyAuthData(res.data)
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
// 未登录或 refresh 失效,交由路由守卫跳转登录页
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return { token, operator, isLoggedIn, permissions, login, logout }
|
||||
function logout() {
|
||||
// 尽力通知后端注销并清除 Cookie(best-effort)
|
||||
try {
|
||||
post('/auth/operator/logout', {}).catch(() => {})
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
token.value = ''
|
||||
operator.value = null
|
||||
clearAccessToken()
|
||||
}
|
||||
|
||||
return { token, operator, isLoggedIn, permissions, hasPermission, login, logout, initializeSession }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// 内存态访问令牌。
|
||||
//
|
||||
// 不再落地 localStorage:XSS 无法读取/外泄令牌,也无法改写伪造权限。
|
||||
// 生产环境由 HttpOnly Cookie(dy_op_at)抗 XSS 承载令牌;开发跨端口代理场景由本内存态经
|
||||
// Authorization 头承载。两者并存,互不冲突。
|
||||
|
||||
let currentToken = ''
|
||||
|
||||
export function getAccessToken(): string {
|
||||
return currentToken
|
||||
}
|
||||
|
||||
export function setAccessToken(token: string): void {
|
||||
currentToken = token || ''
|
||||
}
|
||||
|
||||
export function clearAccessToken(): void {
|
||||
currentToken = ''
|
||||
}
|
||||
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 467 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 295 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 187 KiB |
@@ -13,9 +13,9 @@
|
||||
|
||||
<groupId>com.danyang.match</groupId>
|
||||
<artifactId>danyang-match-platform</artifactId>
|
||||
<version>1.0.0-RC.1</version>
|
||||
<version>1.2.0</version>
|
||||
<name>Danyang Match Platform</name>
|
||||
<description>丹阳公益婚恋服务平台 V1.0 - Backend</description>
|
||||
<description>丹阳公益婚恋服务平台 V1.1 - Backend</description>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
|
||||
@@ -9,7 +9,7 @@ import com.danyang.match.platform.activity.entity.ActivityInterest;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.danyang.match.platform.shared.idempotency.Idempotent;
|
||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
||||
import com.danyang.match.platform.relationship.service.RelationshipService;
|
||||
import com.danyang.match.platform.activity_mutual.service.ActivityMutualConsentService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -30,7 +30,8 @@ import java.util.Map;
|
||||
public class ActivityInterestController {
|
||||
|
||||
private final ActivityInterestService interestService;
|
||||
private final RelationshipService relationshipService;
|
||||
/** 二阶段同意(INV-014/015):`interests/confirm` 与 `/mutual/*` 共用同一实现,避免越权旁路。 */
|
||||
private final ActivityMutualConsentService consentService;
|
||||
private final ActivityMapper activityMapper;
|
||||
|
||||
@GetMapping("/operator/activity-interest-summary")
|
||||
@@ -105,7 +106,12 @@ public class ActivityInterestController {
|
||||
/**
|
||||
* 确认开启线上沟通(V1.1 Phase 08)
|
||||
* POST /api/v1/activities/{id}/interests/confirm
|
||||
* 双方确认后创建 Match Episode,不自动创建 Conversation
|
||||
*
|
||||
* <p><b>2026-09-23 UAT 走查修复(INV-014/015)</b>:此前本端点仅校验「双向互选」便直调
|
||||
* {@code RelationshipService.confirmActivityInterest} —— 那是「建 Match」的底层原语
|
||||
* (不做任何同意校验),于是**单方调用即可建 Match/会话**,绕过「双方各自显式确认」
|
||||
* 的二阶段同意。现改为与 {@code /activities/{id}/mutual/*} 走**同一条**二阶段链路:
|
||||
* 本端点只登记「我方确认」,只有双方都 accepted 时才建 Match/会话。
|
||||
*/
|
||||
@Idempotent
|
||||
@PostMapping("/{id}/interests/confirm")
|
||||
@@ -120,13 +126,16 @@ public class ActivityInterestController {
|
||||
com.danyang.match.platform.shared.enums.ApiResponseCode.BAD_REQUEST,
|
||||
"partnerId不能为空");
|
||||
}
|
||||
// 验证互选状态
|
||||
// 验证互选状态(保留原前置条件:无双向互选不进入确认环节)
|
||||
if (!interestService.hasMutualInterest(userId, partnerId, id)) {
|
||||
return ApiResponse.error(
|
||||
com.danyang.match.platform.shared.enums.ApiResponseCode.CONFLICT,
|
||||
"您与该用户未形成活动双向互选");
|
||||
}
|
||||
return ApiResponse.ok(relationshipService.confirmActivityInterest(userId, partnerId));
|
||||
// 二阶段同意:先幂等确保同意记录存在,再仅提交「我方确认」。
|
||||
// 单方调用不再可能创建 Match(INV-014/015)。
|
||||
consentService.createMutualConsent(id, userId, partnerId);
|
||||
return ApiResponse.ok(consentService.confirmConnection(userId, id, partnerId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -26,6 +26,7 @@ import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
/**
|
||||
* 活动互选服务
|
||||
@@ -69,7 +70,7 @@ public class ActivityInterestService {
|
||||
|
||||
// 2. 验证用户已报名且通过审核
|
||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||
.orElseThrow(() -> new RuntimeException("您未报名该活动"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.FORBIDDEN, "您未报名该活动"));
|
||||
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名未通过审核,无法提交反馈");
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -407,7 +408,7 @@ public class ActivityService {
|
||||
@Transactional
|
||||
public ActivityRegistration cancelRegistration(String userId, String activityId) {
|
||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||
.orElseThrow(() -> new RuntimeException("没有找到报名记录"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到报名记录"));
|
||||
if (!Constants.REGISTRATION_STATUS_PENDING.equals(registration.getStatus()) &&
|
||||
!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不能取消");
|
||||
|
||||
@@ -29,6 +29,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.ServerErrorException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
/**
|
||||
* 签到服务
|
||||
@@ -64,7 +65,7 @@ public class CheckinService {
|
||||
*/
|
||||
public Map<String, Object> generateCheckinToken(String userId, String activityId) {
|
||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||
.orElseThrow(() -> new RuntimeException("您没有报名该活动"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.FORBIDDEN, "您没有报名该活动"));
|
||||
|
||||
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名尚未审核通过,无法签到");
|
||||
|
||||
@@ -16,6 +16,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -67,7 +69,7 @@ public class ActivityMutualConsentService {
|
||||
@Transactional
|
||||
public Map<String, Object> confirmConnection(String userId, String activityId, String partnerId) {
|
||||
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
||||
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到该活动的互选记录"));
|
||||
|
||||
// 原子确认本方(Phase 16 核心):仅当本方 pending、未过期、未软删时写入 accepted,
|
||||
// 并借助 both_confirmed_at 从 NULL→非NULL 的原子 UPDATE 实现 exactly-once。
|
||||
@@ -76,7 +78,7 @@ public class ActivityMutualConsentService {
|
||||
|
||||
// 回读权威状态(可能受并发另一方提交影响)
|
||||
consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
||||
.orElseThrow(() -> new RuntimeException("互选记录已不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "互选记录已不存在"));
|
||||
|
||||
boolean aAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserAStatus());
|
||||
boolean bAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus());
|
||||
@@ -120,7 +122,7 @@ public class ActivityMutualConsentService {
|
||||
|
||||
public Map<String, Object> declineConnection(String userId, String activityId, String partnerId) {
|
||||
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
||||
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到该活动的互选记录"));
|
||||
if (userId.equals(consent.getUserAId())) {
|
||||
consent.setUserAStatus(Constants.MUTUAL_CONSENT_STATUS_DECLINED);
|
||||
} else {
|
||||
|
||||
@@ -19,4 +19,15 @@ public class AuditLog extends BaseEntity {
|
||||
private String afterData;
|
||||
private String ip;
|
||||
private String userAgent;
|
||||
|
||||
// ==================== ZC-MM-006 / T01 扩展审计字段(V055,全可空) ====================
|
||||
|
||||
/** 业务目的码,规范:matchmaker.service.assign/recommend/followup/complete/view。 */
|
||||
private String purposeCode;
|
||||
/** 关联的 matchmaker_assignments.id(非分配场景为 null)。 */
|
||||
private String serviceAssignmentId;
|
||||
/** 落库时操作者权限快照(permissions 逗号拼接,截断 128)。 */
|
||||
private String actorRoleSnapshot;
|
||||
/** 请求追踪 ID(RequestIdFilter 写入 MDC 的 requestId)。 */
|
||||
private String requestTraceId;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,11 @@ public class AuditLogService {
|
||||
m.put("ip", log.getIp());
|
||||
m.put("userAgent", log.getUserAgent());
|
||||
m.put("createdAt", log.getCreatedAt());
|
||||
// ZC-MM-006 / T01:扩展审计字段输出(可空键,存量行输出 null,读取兼容)
|
||||
m.put("purposeCode", log.getPurposeCode());
|
||||
m.put("serviceAssignmentId", log.getServiceAssignmentId());
|
||||
m.put("actorRoleSnapshot", log.getActorRoleSnapshot());
|
||||
m.put("requestTraceId", log.getRequestTraceId());
|
||||
return m;
|
||||
}).collect(java.util.stream.Collectors.toList());
|
||||
|
||||
@@ -73,11 +78,23 @@ public class AuditLogService {
|
||||
*/
|
||||
@Transactional
|
||||
public void recordSensitiveAccess(String operatorId, String resourceType, String resourceId) {
|
||||
recordSensitiveAccess(operatorId, resourceType, resourceId, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZC-MM-006 / T01 扩展版敏感访问记录:附加目的码与关联分配 ID。
|
||||
* 旧 3 参签名委托本方法(purposeCode/serviceAssignmentId 为 null),存量调用兼容。
|
||||
*/
|
||||
@Transactional
|
||||
public void recordSensitiveAccess(String operatorId, String resourceType, String resourceId,
|
||||
String purposeCode, String serviceAssignmentId) {
|
||||
AuditLog auditLog = new AuditLog();
|
||||
auditLog.setOperatorId(operatorId);
|
||||
auditLog.setAction("SENSITIVE_ACCESS");
|
||||
auditLog.setResourceType(resourceType);
|
||||
auditLog.setResourceId(resourceId);
|
||||
auditLog.setPurposeCode(purposeCode);
|
||||
auditLog.setServiceAssignmentId(serviceAssignmentId);
|
||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs) {
|
||||
HttpServletRequest req = attrs.getRequest();
|
||||
auditLog.setIp(req.getRemoteAddr());
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
package com.danyang.match.platform.auth.controller;
|
||||
|
||||
import com.danyang.match.platform.auth.cookie.OperatorCookieWriter;
|
||||
import com.danyang.match.platform.auth.service.OperatorAuthService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -17,14 +23,80 @@ import java.util.Map;
|
||||
public class OperatorAuthController {
|
||||
|
||||
private final OperatorAuthService operatorAuthService;
|
||||
private final OperatorCookieWriter cookieWriter;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<Map<String, Object>> login(@RequestBody Map<String, String> body) {
|
||||
public ApiResponse<Map<String, Object>> login(@RequestBody Map<String, String> body,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
String username = body.get("username");
|
||||
String password = body.get("password");
|
||||
if (username == null || username.isBlank() || password == null || password.isBlank()) {
|
||||
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, "用户名和密码不能为空");
|
||||
}
|
||||
return ApiResponse.ok(operatorAuthService.login(username, password));
|
||||
Map<String, Object> result = operatorAuthService.login(username, password);
|
||||
// 同时下发 HttpOnly + SameSite=Lax Cookie(access / refresh),抗 XSS 读取令牌。
|
||||
// Cookie max-age 由 OperatorCookieWriter 按 JWT 有效期计算,控制器不引用 JWT 工具
|
||||
// (控制器禁止解析/引用 JWT 工具,见 PrincipalInjectionContractTest 契约)。
|
||||
cookieWriter.writeLoginCookies(response,
|
||||
(String) result.get("accessToken"), (String) result.get("refreshToken"));
|
||||
return ApiResponse.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新 Operator Token。
|
||||
*
|
||||
* <p>refresh token 优先取请求体(兼容旧前端/跨端口开发代理),缺省时回退到 HttpOnly Cookie
|
||||
* {@code dy_op_rt}(生产同源场景,前端不持有 refresh token,抗 XSS)。
|
||||
* 响应同时下发新的 access / refresh Cookie,实现刷新即轮换。
|
||||
*/
|
||||
@PostMapping("/refresh")
|
||||
public ApiResponse<Map<String, Object>> refresh(@RequestBody(required = false) Map<String, String> body,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
String refreshToken = (body != null) ? body.get("refreshToken") : null;
|
||||
if (refreshToken == null || refreshToken.isBlank()) {
|
||||
refreshToken = readCookie(request, OperatorCookieWriter.REFRESH_COOKIE);
|
||||
}
|
||||
if (refreshToken == null || refreshToken.isBlank()) {
|
||||
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, "缺少 Refresh Token");
|
||||
}
|
||||
String operatorId = (body != null) ? body.get("operatorId") : null;
|
||||
Map<String, Object> result = operatorAuthService.refreshToken(operatorId, refreshToken);
|
||||
cookieWriter.writeLoginCookies(response,
|
||||
(String) result.get("accessToken"), (String) result.get("refreshToken"));
|
||||
return ApiResponse.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登出:后端将当前 access token 加入黑名单并清除 HttpOnly Cookie。
|
||||
* operatorId 取自 SecurityContext 中的 OperatorPrincipal(由 JwtAuthFilter 写入),
|
||||
* 不再由控制器自行解析 JWT;token 取自 Authorization 头,缺省时回退到 access Cookie,
|
||||
* 仅用于黑名单登记。
|
||||
*/
|
||||
@PostMapping("/logout")
|
||||
public ApiResponse<Void> logout(HttpServletRequest request, HttpServletResponse response,
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
String token = readBearer(request);
|
||||
if (token != null && principal != null) {
|
||||
operatorAuthService.logout(principal.id(), token);
|
||||
}
|
||||
cookieWriter.clearCookies(response);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
private String readCookie(HttpServletRequest request, String name) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) return null;
|
||||
for (Cookie c : cookies) {
|
||||
if (name.equals(c.getName())) return c.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String readBearer(HttpServletRequest request) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
return header.substring(7);
|
||||
}
|
||||
return readCookie(request, OperatorCookieWriter.ACCESS_COOKIE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.danyang.match.platform.auth.cookie;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 管理端鉴权 Cookie 写入工具。
|
||||
*
|
||||
* <p>登录 / 刷新成功时下发 HttpOnly + SameSite=Lax 的 access / refresh Cookie;登出时清除。
|
||||
* Cookie 为 HttpOnly,JS 无法读取,从根本上消除 XSS 读取令牌并外泄的风险(此前令牌存于
|
||||
* 前端 localStorage,XSS 可读写并伪造权限)。
|
||||
*
|
||||
* <p>{@code Secure} 标志由 {@code app.auth-cookie-secure} 控制:生产(https)为 true;
|
||||
* dev / docker(http)为 false,否则浏览器拒绝写入。
|
||||
*
|
||||
* <p>路径固定为 {@code /api/v1}(即后端 servlet context-path),确保只随同源 API 请求携带。
|
||||
*/
|
||||
@Component
|
||||
public class OperatorCookieWriter {
|
||||
|
||||
public static final String ACCESS_COOKIE = "dy_op_at";
|
||||
public static final String REFRESH_COOKIE = "dy_op_rt";
|
||||
|
||||
@Value("${app.auth-cookie-secure:true}")
|
||||
private boolean secure;
|
||||
|
||||
// Cookie 生命周期与 JWT 自身有效期对齐(access 2h / refresh 14d),由配置驱动、不写死。
|
||||
// 由本组件持有而非控制器持有:控制器不得直接引用 JwtTokenService
|
||||
// (PrincipalInjectionContractTest 契约禁止控制器解析/引用 JWT 工具)。
|
||||
@Value("${jwt.access-token-expiration-ms:7200000}")
|
||||
private long accessExpirationMs;
|
||||
|
||||
@Value("${jwt.refresh-token-expiration-ms:1209600000}")
|
||||
private long refreshExpirationMs;
|
||||
|
||||
/** 登录/刷新下发 Cookie,max-age 自动取 JWT 有效期(秒)。 */
|
||||
public void writeLoginCookies(HttpServletResponse response, String accessToken, String refreshToken) {
|
||||
writeLoginCookies(response, accessToken, refreshToken, accessExpirationMs / 1000, refreshExpirationMs / 1000);
|
||||
}
|
||||
|
||||
public void writeLoginCookies(HttpServletResponse response, String accessToken, String refreshToken,
|
||||
long accessMaxAgeSec, long refreshMaxAgeSec) {
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, build(ACCESS_COOKIE, accessToken, accessMaxAgeSec).toString());
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, build(REFRESH_COOKIE, refreshToken, refreshMaxAgeSec).toString());
|
||||
}
|
||||
|
||||
public void clearCookies(HttpServletResponse response) {
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, build(ACCESS_COOKIE, "", 0).toString());
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, build(REFRESH_COOKIE, "", 0).toString());
|
||||
}
|
||||
|
||||
private ResponseCookie build(String name, String value, long maxAgeSec) {
|
||||
return ResponseCookie.from(name, value)
|
||||
.httpOnly(true)
|
||||
.secure(secure)
|
||||
.sameSite("Lax")
|
||||
.path("/api/v1")
|
||||
.maxAge(maxAgeSec)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,15 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Mock 微信登录 Provider(开发/测试环境使用)
|
||||
* Mock 微信登录 Provider(开发/测试环境使用)。
|
||||
*
|
||||
* <p>属性已从 {@code verification.provider} 解耦为独立的 {@code wechat.login.provider},
|
||||
* 避免与实名核验 Provider 共用一把开关导致生产误启 Mock。
|
||||
* 保留 {@code matchIfMissing = true}:未显式配置时本地/测试默认走 Mock;
|
||||
* 生产必须在 {@code application-production.yml} 显式置 {@code wechat.login.provider=real}。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "verification.provider", havingValue = "mock", matchIfMissing = true)
|
||||
@ConditionalOnProperty(name = "wechat.login.provider", havingValue = "mock", matchIfMissing = true)
|
||||
public class MockWechatLoginProvider implements WechatLoginProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MockWechatLoginProvider.class);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.danyang.match.platform.auth.provider;
|
||||
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 真实微信登录 Provider(生产环境使用)。
|
||||
*
|
||||
* <p>通过 {@code code2session} 用登录临时凭证 {@code code} 换取 {@code openid / session_key / unionid}。
|
||||
* 由配置 {@code wechat.login.provider=real} 激活;未显式配置时默认是 Mock(见 {@link MockWechatLoginProvider}),
|
||||
* 因此生产环境必须在 {@code application-production.yml} 里显式置 {@code real},否则启动即应失败(而非悄悄走 Mock)。
|
||||
*
|
||||
* <p>安全要点:
|
||||
* <ul>
|
||||
* <li>{@code appId / appSecret} 必须来自环境变量({@code WECHAT_APP_ID / WECHAT_APP_SECRET}),不得硬编码;
|
||||
* 缺失即 fail-fast,避免用占位值放行任意 code。</li>
|
||||
* <li>code 必须进 URL 前编码;响应必须校验 {@code errcode},微信对非法/过期 code 会返回 errcode 而非抛网络异常。</li>
|
||||
* <li>绝不把 appSecret / session_key 回传给前端。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "wechat.login.provider", havingValue = "real")
|
||||
public class RealWechatLoginProvider implements WechatLoginProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RealWechatLoginProvider.class);
|
||||
private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
|
||||
|
||||
@Value("${wechat.app-id:}")
|
||||
private String appId;
|
||||
|
||||
@Value("${wechat.app-secret:}")
|
||||
private String appSecret;
|
||||
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Map<String, String> getCodeSession(String code) {
|
||||
if (appId == null || appId.isBlank() || appSecret == null || appSecret.isBlank()) {
|
||||
// 配置缺失 = 生产未就绪,fail-fast 而非放行任意 code
|
||||
throw new BusinessException(ApiResponseCode.SERVER_ERROR, "微信登录未配置 appId/appSecret");
|
||||
}
|
||||
if (code == null || code.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "微信登录失败:缺少 code");
|
||||
}
|
||||
|
||||
String url = CODE2SESSION_URL
|
||||
+ "?appid=" + appId
|
||||
+ "&secret=" + appSecret
|
||||
+ "&js_code=" + URLEncoder.encode(code, StandardCharsets.UTF_8)
|
||||
+ "&grant_type=authorization_code";
|
||||
|
||||
try {
|
||||
String resp = restTemplate.getForObject(url, String.class);
|
||||
JsonNode node = objectMapper.readTree(resp);
|
||||
if (node.has("errcode") && node.get("errcode").asInt(0) != 0) {
|
||||
log.warn("[Wechat] code2session 失败: errcode={}, errmsg={}",
|
||||
node.get("errcode").asText(), node.has("errmsg") ? node.get("errmsg").asText() : "");
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "微信登录失败,请重试");
|
||||
}
|
||||
String openid = node.has("openid") ? node.get("openid").asText() : null;
|
||||
if (openid == null || openid.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "微信登录失败:无法获取 openid");
|
||||
}
|
||||
String sessionKey = node.has("session_key") ? node.get("session_key").asText() : null;
|
||||
String unionid = node.has("unionid") ? node.get("unionid").asText() : null;
|
||||
|
||||
// 用 HashMap(允许 unionid 为 null),不要 Map.of(禁止 null 值)
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("openid", openid);
|
||||
result.put("unionid", unionid);
|
||||
result.put("session_key", sessionKey);
|
||||
result.put("appid", appId);
|
||||
return result;
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("[Wechat] code2session 调用异常", e);
|
||||
throw new BusinessException(ApiResponseCode.SERVER_ERROR, "微信登录服务异常");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMock() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -90,7 +91,9 @@ public class AuthService {
|
||||
|
||||
// 将 refreshToken 存入 Redis(用于撤销)
|
||||
String refreshTokenKey = "auth:refresh_token:" + user.getId();
|
||||
redisTemplate.opsForValue().set(refreshTokenKey, refreshToken, Duration.ofMillis(jwtTokenService.getExpirationMs() * 2));
|
||||
// 刷新令牌 Redis 登记的 TTL 必须与 refresh JWT 自身有效期一致(getRefreshExpirationMs,
|
||||
// 默认 14 天),否则 4h 后记录消失、刷新即失效,用户被迫频繁重新登录。
|
||||
redisTemplate.opsForValue().set(refreshTokenKey, refreshToken, Duration.ofMillis(jwtTokenService.getRefreshExpirationMs()));
|
||||
|
||||
// 记录审计日志
|
||||
saveAuditLog(user.getId(), null, "LOGIN", "user", user.getId(), null, null);
|
||||
@@ -111,7 +114,7 @@ public class AuthService {
|
||||
public void bindPhone(String userId, String phoneCode) {
|
||||
// TODO: Phase 03 对接真实短信验证码
|
||||
User user = userMapper.findById(userId)
|
||||
.orElseThrow(() -> new RuntimeException("用户不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "用户不存在"));
|
||||
|
||||
// 检查手机号是否已被其他用户占用
|
||||
userMapper.findByPhone(phoneCode).ifPresent(existing -> {
|
||||
@@ -172,9 +175,9 @@ public class AuthService {
|
||||
String newAccessToken = jwtTokenService.generateAccessToken(userId, null);
|
||||
String newRefreshToken = jwtTokenService.generateRefreshToken(userId);
|
||||
|
||||
// 更新 Redis
|
||||
// 更新 Redis:TTL 与 refresh JWT 一致(getRefreshExpirationMs),避免刷新记录先于令牌过期。
|
||||
redisTemplate.opsForValue().set("auth:refresh_token:" + userId, newRefreshToken,
|
||||
Duration.ofMillis(jwtTokenService.getExpirationMs() * 2));
|
||||
Duration.ofMillis(jwtTokenService.getRefreshExpirationMs()));
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("accessToken", newAccessToken);
|
||||
@@ -200,7 +203,7 @@ public class AuthService {
|
||||
*/
|
||||
public Map<String, Object> getMeStatus(String userId) {
|
||||
User user = userMapper.findById(userId)
|
||||
.orElseThrow(() -> new RuntimeException("用户不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "用户不存在"));
|
||||
|
||||
Map<String, Object> status = new HashMap<>();
|
||||
status.put("userId", user.getId());
|
||||
|
||||
@@ -25,6 +25,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -100,6 +101,9 @@ public class OperatorAuthService {
|
||||
.toList();
|
||||
|
||||
// 签发 Token
|
||||
// ZC-MM-006 / T02 声明:claims 中的 permissions 仅为登录时刻的展示快照(只写不读),
|
||||
// **不是授权事实源** —— 服务端每请求实时查库(JwtAuthFilter → PermissionMapper),
|
||||
// 权限回收/角色调整/账号禁用即时生效,无需等待 token 过期或撤销名单。
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("operatorId", operator.getId());
|
||||
claims.put("organizationId", operator.getOrganizationId());
|
||||
@@ -144,7 +148,7 @@ public class OperatorAuthService {
|
||||
*/
|
||||
public Map<String, Object> getMe(String operatorId) {
|
||||
Operator operator = operatorMapper.findById(operatorId)
|
||||
.orElseThrow(() -> new RuntimeException("Operator 不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "Operator 不存在"));
|
||||
|
||||
List<Permission> permissions = permissionMapper.findPermissionsByOperatorId(operatorId);
|
||||
List<String> permissionCodes = permissions.stream()
|
||||
@@ -176,6 +180,11 @@ public class OperatorAuthService {
|
||||
throw new UnauthorizedException("Refresh Token 无效");
|
||||
}
|
||||
|
||||
// 前端未传 operatorId 时,由 refresh token 自证身份(Cookie 场景下前端不持有 token)
|
||||
if (operatorId == null || operatorId.isBlank()) {
|
||||
operatorId = jwtTokenService.getUserIdFromRefreshToken(refreshToken);
|
||||
}
|
||||
|
||||
String storedToken = redisTemplate.opsForValue().get("auth:operator_refresh:" + operatorId);
|
||||
if (storedToken == null || !storedToken.equals(refreshToken)) {
|
||||
throw new UnauthorizedException("Refresh Token 无效");
|
||||
@@ -193,6 +202,12 @@ public class OperatorAuthService {
|
||||
result.put("accessToken", accessToken);
|
||||
result.put("refreshToken", newRefreshToken);
|
||||
result.put("expiresIn", jwtTokenService.getExpirationMs() / 1000);
|
||||
// 同步 operator 概要:前端凭 HttpOnly refresh cookie 静默刷新后,可直接恢复菜单态,无需重新登录
|
||||
result.put("operatorId", operatorInfo.get("operatorId"));
|
||||
result.put("name", operatorInfo.get("name"));
|
||||
result.put("username", operatorInfo.get("username"));
|
||||
result.put("organizationId", operatorInfo.get("organizationId"));
|
||||
result.put("permissions", operatorInfo.get("permissions"));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -215,9 +215,21 @@ public class JwtTokenService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Token 过期时间
|
||||
* 获取 Access Token 过期时间(毫秒)
|
||||
*/
|
||||
public long getExpirationMs() {
|
||||
return accessExpirationMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Refresh Token 过期时间(毫秒)。
|
||||
*
|
||||
* <p>刷新令牌 Redis 登记的 TTL 必须使用本值,而不是 {@link #getExpirationMs()}
|
||||
* (access 过期,默认 2h)。此前 AuthService 用 {@code getExpirationMs() * 2}
|
||||
* 把 Redis 记录设成 4h,而 refresh JWT 自身有效期是 {@code refreshExpirationMs}
|
||||
* (默认 14 天)—— 4h 后 Redis 记录消失,刷新即抛未授权,用户被迫每 4h 重新登录。
|
||||
*/
|
||||
public long getRefreshExpirationMs() {
|
||||
return refreshExpirationMs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.danyang.match.platform.contactauth.controller;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.service.ContactAuthorizationService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 受控联系授权控制器(C 端用户,ZC-MM-003 / B1 立项)。
|
||||
*
|
||||
* <p>端点(基路径 {@code /api/v1/contact-authorizations},USER 角色兜底):
|
||||
* <ul>
|
||||
* <li>GET {@code /my} —— 我的授权列表 + 待同意队列;</li>
|
||||
* <li>POST {@code /{id}/consent} —— 用户<b>单独明示同意</b>(独立端点,
|
||||
* 非任何其他操作的捆绑步骤、无预勾选/预同意参数);</li>
|
||||
* <li>POST {@code /{id}/decline} —— 用户拒绝。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>归属校验(userId.equals)在 Service 层 {@code requireOwnedAuthorization} 承担;
|
||||
* 不碰 SecurityConfig(路径落入 {@code /** → hasRole("USER")} 兜底规则)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/contact-authorizations")
|
||||
@RequiredArgsConstructor
|
||||
public class ContactAuthorizationUserController {
|
||||
|
||||
private final ContactAuthorizationService contactAuthorizationService;
|
||||
|
||||
/** 我的授权列表 + 待同意队列。 */
|
||||
@GetMapping("/my")
|
||||
public ApiResponse<Map<String, Object>> my(@AuthenticationPrincipal UserPrincipal principal) {
|
||||
if (principal == null) return ApiResponse.unauthorized();
|
||||
return ApiResponse.ok(contactAuthorizationService.myAuthorizationsForUser(principal.id()));
|
||||
}
|
||||
|
||||
/** 单独明示同意(独立端点,无预同意参数)。 */
|
||||
@PostMapping("/{id}/consent")
|
||||
public ApiResponse<Object> consent(@PathVariable String id,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
if (principal == null) return ApiResponse.unauthorized();
|
||||
return ApiResponse.ok(contactAuthorizationService.consent(id, principal.id()));
|
||||
}
|
||||
|
||||
/** 拒绝授权请求。 */
|
||||
@PostMapping("/{id}/decline")
|
||||
public ApiResponse<Object> decline(@PathVariable String id,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
if (principal == null) return ApiResponse.unauthorized();
|
||||
return ApiResponse.ok(contactAuthorizationService.decline(id, principal.id()));
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ public class MatchEligibilityService {
|
||||
private final UserMapper userMapper;
|
||||
private final UserProfileMapper userProfileMapper;
|
||||
private final LocalEligibilityMapper localEligibilityMapper;
|
||||
/** 评分与双向 Required 的唯一事实源(2026-09-23 去桩:原候选池/评分/Required 均为 TODO 空实现)。 */
|
||||
private final MatchScoringService matchScoringService;
|
||||
|
||||
/**
|
||||
* 获取每日推荐列表
|
||||
@@ -103,14 +105,17 @@ public class MatchEligibilityService {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 双向 Required 检查
|
||||
// 2. 双向 Required 检查(唯一事实源 MatchScoringService;INV-001 Required 不可自动放宽)
|
||||
UserPreference targetPref = preferenceMapper.findByUserId(targetUserId).orElse(null);
|
||||
if (targetPref == null) {
|
||||
return null; // 目标用户未设置择偶条件,无法双向验证
|
||||
}
|
||||
|
||||
// A → B Required 检查
|
||||
if (!checkBidirectionalRequired(myPref, targetPref)) {
|
||||
UserProfile myProfile = userProfileMapper.findByUserId(userId).orElse(null);
|
||||
UserProfile targetProfile = userProfileMapper.findByUserId(targetUserId).orElse(null);
|
||||
if (myProfile == null || targetProfile == null) {
|
||||
return null; // 资料缺失则无法核验 Required,不假定满足
|
||||
}
|
||||
if (!matchScoringService.bidirectionalRequiredSatisfied(myPref, myProfile, targetPref, targetProfile)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -175,36 +180,18 @@ public class MatchEligibilityService {
|
||||
return "verified".equals(el.getVerificationStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* 双向 Required 检查
|
||||
* Required 是 Hard Constraint,不可自动放宽
|
||||
*/
|
||||
private boolean checkBidirectionalRequired(UserPreference myPref, UserPreference targetPref) {
|
||||
// 需要通过外部传入的 UserProfile 检查,本方法只比较 Preference
|
||||
// 完整检查在 getDailyRecommendations 的循环中调用 evaluateCandidate
|
||||
// 此处仅返回 true(实际过滤由 evaluateCandidate 的 isBasicEligible 和 Profile 数据完成)
|
||||
return true;
|
||||
}
|
||||
// checkBidirectionalRequired 已于 2026-09-23 收敛进 MatchScoringService.bidirectionalRequiredSatisfied
|
||||
// (原实现恒 return true,等于 Required 不生效——已删除,避免「声明做校验实际不校验」的 landmine)。
|
||||
|
||||
/**
|
||||
* 方向性评分(A对B的适配度)
|
||||
* 基于 Preferred 维度计算 0-100 分
|
||||
*/
|
||||
private double directionalScore(String fromUserId, String toUserId, UserPreference pref) {
|
||||
double score = 0;
|
||||
double totalWeight = pref.getAgeWeight() + pref.getRegionWeight() +
|
||||
pref.getMaritalWeight() + pref.getChildrenWeight() +
|
||||
pref.getEducationWeight() + pref.getHeightWeight() +
|
||||
pref.getMarriagePlanWeight() + pref.getSettlementWeight() +
|
||||
pref.getLifestyleWeight() + pref.getInterestWeight();
|
||||
|
||||
// TODO: 实现各维度评分逻辑
|
||||
// 年龄匹配:在范围内得满分,超出范围按比例扣分
|
||||
// 地区匹配:同地区得满分,不同地区按比例扣分
|
||||
// ...
|
||||
|
||||
if (totalWeight == 0.0) return 50.0; // 无权重配置时给默认分
|
||||
return (int)(Math.round(score / totalWeight * 100));
|
||||
// 委托唯一事实源;此前 score 恒 0(TODO 未实现)→ 任何候选都被阈值过滤。
|
||||
return userProfileMapper.findByUserId(toUserId)
|
||||
.map(p -> matchScoringService.scoreDirectionally(pref, p))
|
||||
.orElse(0.0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,20 +199,21 @@ public class MatchEligibilityService {
|
||||
*/
|
||||
private List<String> generateReasons(String userId, String targetUserId,
|
||||
UserPreference myPref, UserPreference targetPref) {
|
||||
List<String> reasons = new ArrayList<>();
|
||||
// TODO: 根据实际资料生成真实推荐理由
|
||||
reasons.add("年龄符合双方择偶要求");
|
||||
reasons.add("都长期生活在丹阳");
|
||||
reasons.add("婚姻计划接近");
|
||||
return reasons;
|
||||
// 委托唯一事实源,按实际达成维度生成(此前为无条件套话)。
|
||||
return userProfileMapper.findByUserId(targetUserId)
|
||||
.map(p -> matchScoringService.reasons(myPref, p))
|
||||
.orElseGet(ArrayList::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已Pass的用户ID集合(冷却期内)
|
||||
*/
|
||||
private Set<String> getPassedUserIds(String userId, Instant since) {
|
||||
// TODO: 查询 user_relations 表中 passed 关系的 target_user_id
|
||||
return Collections.emptySet();
|
||||
// 此前恒返回空集(TODO)→ Pass 冷却期失效;改为读取推荐记录中的 passed 行为。
|
||||
return recommendationRecordMapper.findRecentByUserId(userId, since).stream()
|
||||
.filter(r -> "passed".equals(r.getAction()))
|
||||
.map(RecommendationRecord::getTargetUserId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,14 +228,28 @@ public class MatchEligibilityService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建候选池(简化版)
|
||||
* TODO: Phase 06 后续接入数据库查询可用用户
|
||||
* 构建候选池:查库取「性别相反 + 审核通过 + 未软删」的用户,再排除自己/已 Pass 冷却期/今日已推荐。
|
||||
* (2026-09-23:替换原 `return List.of()` 空实现。)
|
||||
*/
|
||||
private List<String> buildCandidatePool(String userId, UserPreference myPref,
|
||||
Set<String> excludedIds, Set<String> alreadyRecommended) {
|
||||
// TODO: 从数据库查询符合条件的用户
|
||||
// 当前返回空列表,等待后续阶段完善
|
||||
return List.of();
|
||||
// 此前 return List.of()(TODO 未实现)→ 此路径必然无候选。
|
||||
// 基础过滤:性别相反 + 审核通过 + 未软删;其余条件在 evaluateCandidate 逐条判定。
|
||||
UserProfile me = userProfileMapper.findByUserId(userId).orElse(null);
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserProfile> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.isNotNull(UserProfile::getGender)
|
||||
.eq(UserProfile::getProfileStatus, Constants.PROFILE_STATUS_APPROVED)
|
||||
.isNull(UserProfile::getDeletedAt);
|
||||
if (me != null && me.getGender() != null && !me.getGender().isBlank()) {
|
||||
wrapper.ne(UserProfile::getGender, me.getGender());
|
||||
}
|
||||
return userProfileMapper.selectList(wrapper).stream()
|
||||
.map(UserProfile::getUserId)
|
||||
.filter(id -> !id.equals(userId))
|
||||
.filter(id -> !excludedIds.contains(id))
|
||||
.filter(id -> !alreadyRecommended.contains(id))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private RecommendationCandidateDTO toDTO(String userId, double score, List<String> reasons) {
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package com.danyang.match.platform.match.service;
|
||||
|
||||
import com.danyang.match.platform.profile.entity.UserPreference;
|
||||
import com.danyang.match.platform.profile.entity.UserProfile;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 匹配评分 —— **全仓唯一事实源**。
|
||||
*
|
||||
* <p>背景:`RecommendationEngineService.calculateScore` 与
|
||||
* `MatchEligibilityService.directionalScore` 曾各自是**桩**(前者 `return 50.0`、
|
||||
* 后者 `score` 恒 0),而阈值 `match.default-score-threshold` 默认 60 →
|
||||
* `mutualScore < 60` 恒成立 → **推荐列表恒为空**(2026-09-23 UAT 走查实测确认)。
|
||||
* 且两处评分逻辑重复,是典型的「双实现漂移」隐患。
|
||||
*
|
||||
* <p>本类把「择偶条件 × 候选人资料」的方向性评分收敛到一处,供两条推荐路径共用。
|
||||
*
|
||||
* <p><b>规则(不新造常量)</b>:直接使用 {@link UserPreference} 上<b>已存在</b>的
|
||||
* 十个维度权重;只为「用户实际设置了的条件」计分(未设置 = 不构成约束,不计入分母)。
|
||||
* 某维度上候选人缺少可用于判定的资料时,该维度计 0 分(「无法核验即不假定满足」,
|
||||
* 与 Required「不可自动放宽」一致)。若用户未设置任何条件,视为无约束 → 返回 100。
|
||||
*
|
||||
* <p>返回值域 0–100;调用方按 `match.default-score-threshold`(技术默认 60,OQ-MATCH-001)过滤。
|
||||
*/
|
||||
@Service
|
||||
public class MatchScoringService {
|
||||
|
||||
/** 学历高低序列,取索引差做比较(与 chk_profile_edu 顺序一致)。 */
|
||||
private static final List<String> EDUCATION_ORDER = List.of(
|
||||
"primary", "junior_high", "senior_high", "vocational", "college", "bachelor", "master", "doctor");
|
||||
|
||||
/**
|
||||
* 方向性评分:seeker 的择偶条件对 candidate 资料的适配度(0–100)。
|
||||
*
|
||||
* @param pref seeker 的择偶条件(可为 null → 无约束)
|
||||
* @param candidate 候选人资料
|
||||
*/
|
||||
public double scoreDirectionally(UserPreference pref, UserProfile candidate) {
|
||||
if (candidate == null) return 0;
|
||||
if (pref == null) return 100;
|
||||
|
||||
double acc = 0; // 加权得分
|
||||
double denom = 0; // 已设置条件的权重合计
|
||||
|
||||
// —— 年龄 ——(设置了 min/maxAge 才构成约束)
|
||||
if (pref.getMinAge() != null && pref.getMaxAge() != null) {
|
||||
double w = w(pref.getAgeWeight());
|
||||
denom += w;
|
||||
acc += w * rangeRatio(age(candidate.getBirthDate()), pref.getMinAge(), pref.getMaxAge());
|
||||
}
|
||||
// —— 身高 ——
|
||||
if (pref.getMinHeightCm() != null && pref.getMaxHeightCm() != null) {
|
||||
double w = w(pref.getHeightWeight());
|
||||
denom += w;
|
||||
Integer h = candidate.getHeightCm();
|
||||
acc += w * (h == null ? 0 : rangeRatio(h, pref.getMinHeightCm(), pref.getMaxHeightCm()));
|
||||
}
|
||||
// —— 地区(regionScope 为地区码数组)——
|
||||
if (hasJsonArray(pref.getRegionScope())) {
|
||||
double w = w(pref.getRegionWeight());
|
||||
denom += w;
|
||||
acc += w * (inJsonArray(pref.getRegionScope(), candidate.getRegionCode()) ? 1 : 0);
|
||||
}
|
||||
// —— 婚姻状况(maritalStatuses 数组)——
|
||||
if (hasJsonArray(pref.getMaritalStatuses())) {
|
||||
double w = w(pref.getMaritalWeight());
|
||||
denom += w;
|
||||
acc += w * (inJsonArray(pref.getMaritalStatuses(), candidate.getMaritalStatus()) ? 1 : 0);
|
||||
}
|
||||
// —— 子女(childrenAcceptance:any/accept/reject,兼容中文)——
|
||||
if (notBlank(pref.getChildrenAcceptance())) {
|
||||
double w = w(pref.getChildrenWeight());
|
||||
denom += w;
|
||||
acc += w * (childrenAcceptable(pref.getChildrenAcceptance(), candidate.getChildrenStatus()) ? 1 : 0);
|
||||
}
|
||||
// —— 学历(minEducationCode 为下限)——
|
||||
if (notBlank(pref.getMinEducationCode())) {
|
||||
double w = w(pref.getEducationWeight());
|
||||
denom += w;
|
||||
acc += w * (educationAtLeast(candidate.getEducationCode(), pref.getMinEducationCode()) ? 1 : 0);
|
||||
}
|
||||
// —— 婚恋规划(marriagePlanPreference 与 candidate.marriagePlan 一致)——
|
||||
if (notBlank(pref.getMarriagePlanPreference())) {
|
||||
double w = w(pref.getMarriagePlanWeight());
|
||||
denom += w;
|
||||
acc += w * (sameValue(pref.getMarriagePlanPreference(), candidate.getMarriagePlan()) ? 1 : 0);
|
||||
}
|
||||
// —— 定居意愿(settlementPreference 对照 candidate 长期/未来丹阳意向)——
|
||||
if (notBlank(pref.getSettlementPreference())) {
|
||||
double w = w(pref.getSettlementWeight());
|
||||
denom += w;
|
||||
boolean ok = sameValue(pref.getSettlementPreference(), candidate.getLongTermDanyang())
|
||||
|| sameValue(pref.getSettlementPreference(), candidate.getFutureDanyang());
|
||||
acc += w * (ok ? 1 : 0);
|
||||
}
|
||||
// —— 生活方式(吸烟 / 饮酒,取已设置者的均值)——
|
||||
double lifeW = w(pref.getLifestyleWeight());
|
||||
int lifeDims = 0;
|
||||
double lifeHit = 0;
|
||||
if (notBlank(pref.getSmokingPreference())) {
|
||||
lifeDims++;
|
||||
if (sameValue(pref.getSmokingPreference(), candidate.getSmokingStatus())) lifeHit++;
|
||||
}
|
||||
if (notBlank(pref.getDrinkingPreference())) {
|
||||
lifeDims++;
|
||||
if (sameValue(pref.getDrinkingPreference(), candidate.getDrinkingStatus())) lifeHit++;
|
||||
}
|
||||
if (lifeDims > 0) {
|
||||
denom += lifeW;
|
||||
acc += lifeW * (lifeHit / lifeDims);
|
||||
}
|
||||
// interestWeight:当前无对应择偶条件字段,不参与计分(保留权重以备扩展)。
|
||||
|
||||
if (denom == 0) return 100; // 用户未设置任何条件 → 无约束
|
||||
return clamp(acc / denom * 100.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成中文推荐理由(基于**实际达成**的维度,不再是无条件套话)。
|
||||
* 未达成任何具体维度时回退为「资料符合基本要求」。
|
||||
*/
|
||||
public List<String> reasons(UserPreference pref, UserProfile candidate) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (pref == null || candidate == null) return out;
|
||||
if (pref.getMinAge() != null && pref.getMaxAge() != null
|
||||
&& rangeRatio(age(candidate.getBirthDate()), pref.getMinAge(), pref.getMaxAge()) > 0) {
|
||||
out.add("年龄在您的要求范围内");
|
||||
}
|
||||
if (hasJsonArray(pref.getRegionScope()) && inJsonArray(pref.getRegionScope(), candidate.getRegionCode())) {
|
||||
out.add("同在您期望的地区");
|
||||
}
|
||||
if (hasJsonArray(pref.getMaritalStatuses())
|
||||
&& inJsonArray(pref.getMaritalStatuses(), candidate.getMaritalStatus())) {
|
||||
out.add("婚姻状况符合您的期望");
|
||||
}
|
||||
if (notBlank(pref.getMinEducationCode())
|
||||
&& educationAtLeast(candidate.getEducationCode(), pref.getMinEducationCode())) {
|
||||
out.add("学历符合您的要求");
|
||||
}
|
||||
if (notBlank(pref.getAgePriority()) && "required".equals(pref.getAgePriority())) {
|
||||
out.add("年龄为您设定的必要条件");
|
||||
}
|
||||
if (out.isEmpty()) out.add("资料符合基本要求");
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 双向 Required 硬约束校验(INV-001「Required 不可自动放宽」)——唯一事实源。
|
||||
*
|
||||
* <p>任一方把某维度设为 `required`,则对方该维度<b>必须</b>落在要求内,否则整条候选被否。
|
||||
* 覆盖年龄 / 身高 / 地区 / 婚姻状况四类(当前产品定义的 Required 维度)。
|
||||
*
|
||||
* @return true 表示双向 Required 全部满足
|
||||
*/
|
||||
public boolean bidirectionalRequiredSatisfied(UserPreference myPref, UserProfile myProfile,
|
||||
UserPreference targetPref, UserProfile targetProfile) {
|
||||
if (myPref == null || myProfile == null || targetPref == null || targetProfile == null) return false;
|
||||
|
||||
// 年龄
|
||||
if (isRequired(myPref.getAgePriority()) && myPref.getMinAge() != null && myPref.getMaxAge() != null) {
|
||||
Integer candAge = age(targetProfile.getBirthDate());
|
||||
if (candAge == null || candAge < myPref.getMinAge() || candAge > myPref.getMaxAge()) return false;
|
||||
}
|
||||
if (isRequired(targetPref.getAgePriority()) && targetPref.getMinAge() != null && targetPref.getMaxAge() != null) {
|
||||
Integer myAge = age(myProfile.getBirthDate());
|
||||
if (myAge == null || myAge < targetPref.getMinAge() || myAge > targetPref.getMaxAge()) return false;
|
||||
}
|
||||
// 身高
|
||||
if (isRequired(myPref.getHeightPriority()) && myPref.getMinHeightCm() != null && myPref.getMaxHeightCm() != null) {
|
||||
Integer h = targetProfile.getHeightCm();
|
||||
if (h == null || h < myPref.getMinHeightCm() || h > myPref.getMaxHeightCm()) return false;
|
||||
}
|
||||
if (isRequired(targetPref.getHeightPriority()) && targetPref.getMinHeightCm() != null && targetPref.getMaxHeightCm() != null) {
|
||||
Integer h = myProfile.getHeightCm();
|
||||
if (h == null || h < targetPref.getMinHeightCm() || h > targetPref.getMaxHeightCm()) return false;
|
||||
}
|
||||
// 地区(Required 用 isJsonArray:空数组=自相矛盾的硬约束 → 拒绝;不可放宽为「无约束」)
|
||||
if (isRequired(myPref.getRegionPriority()) && isJsonArray(myPref.getRegionScope())
|
||||
&& !inJsonArray(myPref.getRegionScope(), targetProfile.getRegionCode())) return false;
|
||||
if (isRequired(targetPref.getRegionPriority()) && isJsonArray(targetPref.getRegionScope())
|
||||
&& !inJsonArray(targetPref.getRegionScope(), myProfile.getRegionCode())) return false;
|
||||
// 婚姻状况
|
||||
if (isRequired(myPref.getMaritalPriority()) && isJsonArray(myPref.getMaritalStatuses())
|
||||
&& !inJsonArray(myPref.getMaritalStatuses(), targetProfile.getMaritalStatus())) return false;
|
||||
if (isRequired(targetPref.getMaritalPriority()) && isJsonArray(targetPref.getMaritalStatuses())
|
||||
&& !inJsonArray(targetPref.getMaritalStatuses(), myProfile.getMaritalStatus())) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isRequired(String priority) { return "required".equals(priority); }
|
||||
|
||||
// ==================== 私有工具 ====================
|
||||
|
||||
private static double w(Double v) { return v == null ? 0 : Math.max(0, v); }
|
||||
|
||||
private static boolean notBlank(String s) { return s != null && !s.isBlank(); }
|
||||
|
||||
private static Integer age(LocalDate birthDate) {
|
||||
if (birthDate == null) return null;
|
||||
return Period.between(birthDate, LocalDate.now()).getYears();
|
||||
}
|
||||
|
||||
/** 在 [min,max] 内 → 1;否则按越界距离线性衰减(跨度越大衰减越慢),最低 0。 */
|
||||
private static double rangeRatio(Integer value, int min, int max) {
|
||||
if (value == null) return 0;
|
||||
if (min > max) { int t = min; min = max; max = t; }
|
||||
if (value >= min && value <= max) return 1.0;
|
||||
int span = Math.max(1, max - min);
|
||||
int distance = value < min ? (min - value) : (value - max);
|
||||
return Math.max(0.0, 1.0 - (double) distance / span);
|
||||
}
|
||||
|
||||
/** 评分用:仅当数组**非空**才算「用户表达了该条件」。空数组 = 未设置,不计入分母。 */
|
||||
private static boolean hasJsonArray(JsonNode node) {
|
||||
return node != null && node.isArray() && node.size() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Required 校验用:只要节点是数组即「用户声明了该硬约束」。
|
||||
* 空数组是自相矛盾的声明(要求必填却无任何可接受值)→ 交由调用方判为不满足,
|
||||
* 与「Required 不可自动放宽」(INV-001)一致;不可退化成「无约束」。
|
||||
*/
|
||||
private static boolean isJsonArray(JsonNode node) {
|
||||
return node != null && node.isArray();
|
||||
}
|
||||
|
||||
private static boolean inJsonArray(JsonNode node, String value) {
|
||||
if (node == null || !node.isArray() || value == null) return false;
|
||||
for (int i = 0; i < node.size(); i++) {
|
||||
if (value.equals(node.get(i).asText())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 子女接受度:any/不限 → 恒满足;accept/可接受 → 有孩与否皆可;reject/不接受 → 仅无孩。 */
|
||||
private static boolean childrenAcceptable(String acceptance, String childrenStatus) {
|
||||
String a = acceptance == null ? "" : acceptance.trim();
|
||||
boolean candidateHasChildren = "yes".equals(childrenStatus) || "has".equals(childrenStatus)
|
||||
|| "有".equals(childrenStatus);
|
||||
return switch (a) {
|
||||
case "any", "不限" -> true;
|
||||
case "accept", "可接受" -> true; // 接受带孩(且同样接受无孩)
|
||||
case "reject", "不接受" -> !candidateHasChildren;
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean educationAtLeast(String candidateCode, String minCode) {
|
||||
int ci = EDUCATION_ORDER.indexOf(candidateCode);
|
||||
int mi = EDUCATION_ORDER.indexOf(minCode);
|
||||
if (mi < 0) return true; // 下限码不在白名单 → 不做约束
|
||||
if (ci < 0) return false; // 候选人学历缺失/未知 → 无法核验,不假定满足
|
||||
return ci >= mi;
|
||||
}
|
||||
|
||||
/** 宽松相等:去空白、忽略大小写;两边都非空才比较。 */
|
||||
private static boolean sameValue(String a, String b) {
|
||||
if (!notBlank(a) || !notBlank(b)) return false;
|
||||
return a.trim().equalsIgnoreCase(b.trim());
|
||||
}
|
||||
|
||||
private static double clamp(double v) {
|
||||
if (v < 0) return 0;
|
||||
if (v > 100) return 100;
|
||||
return v;
|
||||
}
|
||||
|
||||
/** 便于单测/文档:常量键说明。 */
|
||||
public static Map<String, String> weightKeys() {
|
||||
return Map.of(
|
||||
"age", "ageWeight", "region", "regionWeight", "marital", "maritalWeight",
|
||||
"children", "childrenWeight", "education", "educationWeight", "height", "heightWeight",
|
||||
"marriagePlan", "marriagePlanWeight", "lifestyle", "lifestyleWeight",
|
||||
"settlement", "settlementWeight", "interest", "interestWeight");
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -55,6 +54,8 @@ public class RecommendationEngineService {
|
||||
private final UserMapper userMapper;
|
||||
private final UserPrivacySettingsMapper privacySettingsMapper;
|
||||
private final LocalEligibilityMapper localEligibilityMapper;
|
||||
/** 评分唯一事实源(2026-09-23:替换原 `return 50.0` 桩,修复「推荐恒空」)。 */
|
||||
private final MatchScoringService matchScoringService;
|
||||
|
||||
/**
|
||||
* 获取每日推荐列表
|
||||
@@ -241,86 +242,16 @@ public class RecommendationEngineService {
|
||||
return userProfileMapper.findByUserId(userId).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 双向 Required 硬约束校验(INV-001「Required 不可自动放宽」)——委托
|
||||
* {@link MatchScoringService#bidirectionalRequiredSatisfied} 唯一事实源。
|
||||
*
|
||||
* <p>此前本方法自带一份等价实现,与事实源构成「双实现漂移」隐患;2026-09-23 收敛为单点。
|
||||
* 参数对映:本方法的 {@code candidate} 即事实源签名中的 {@code targetProfile}。
|
||||
*/
|
||||
boolean checkBidirectionalRequired(UserPreference myPref, UserProfile candidate,
|
||||
UserPreference targetPref, UserProfile myProfile) {
|
||||
if (myPref == null || candidate == null || targetPref == null || myProfile == null) return false;
|
||||
// 1. 年龄 Required 检查
|
||||
if ("required".equals(myPref.getAgePriority()) && myPref.getMinAge() != null && myPref.getMaxAge() != null) {
|
||||
int candidateAge = calculateAge(candidate.getBirthDate());
|
||||
if (candidateAge < myPref.getMinAge() || candidateAge > myPref.getMaxAge()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if ("required".equals(targetPref.getAgePriority()) && targetPref.getMinAge() != null && targetPref.getMaxAge() != null) {
|
||||
int myAge = calculateAge(myProfile.getBirthDate());
|
||||
if (myAge < targetPref.getMinAge() || myAge > targetPref.getMaxAge()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 身高 Required 检查
|
||||
if ("required".equals(myPref.getHeightPriority())
|
||||
&& myPref.getMinHeightCm() != null && myPref.getMaxHeightCm() != null) {
|
||||
if (candidate.getHeightCm() == null
|
||||
|| candidate.getHeightCm() < myPref.getMinHeightCm()
|
||||
|| candidate.getHeightCm() > myPref.getMaxHeightCm()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if ("required".equals(targetPref.getHeightPriority())
|
||||
&& targetPref.getMinHeightCm() != null && targetPref.getMaxHeightCm() != null) {
|
||||
if (myProfile.getHeightCm() == null
|
||||
|| myProfile.getHeightCm() < targetPref.getMinHeightCm()
|
||||
|| myProfile.getHeightCm() > targetPref.getMaxHeightCm()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 地区 Required 检查
|
||||
if ("required".equals(myPref.getRegionPriority()) && myPref.getRegionScope() != null && myPref.getRegionScope().isArray()) {
|
||||
boolean inScope = false;
|
||||
for (int i = 0; i < myPref.getRegionScope().size(); i++) {
|
||||
if (myPref.getRegionScope().get(i).asText().equals(candidate.getRegionCode())) {
|
||||
inScope = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!inScope) return false;
|
||||
}
|
||||
if ("required".equals(targetPref.getRegionPriority()) && targetPref.getRegionScope() != null && targetPref.getRegionScope().isArray()) {
|
||||
boolean inScope = false;
|
||||
for (int i = 0; i < targetPref.getRegionScope().size(); i++) {
|
||||
if (targetPref.getRegionScope().get(i).asText().equals(myProfile.getRegionCode())) {
|
||||
inScope = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!inScope) return false;
|
||||
}
|
||||
|
||||
// 4. 婚姻状况 Required 检查
|
||||
if ("required".equals(myPref.getMaritalPriority()) && myPref.getMaritalStatuses() != null && myPref.getMaritalStatuses().isArray()) {
|
||||
boolean accepted = false;
|
||||
for (int i = 0; i < myPref.getMaritalStatuses().size(); i++) {
|
||||
if (myPref.getMaritalStatuses().get(i).asText().equals(candidate.getMaritalStatus())) {
|
||||
accepted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!accepted) return false;
|
||||
}
|
||||
if ("required".equals(targetPref.getMaritalPriority()) && targetPref.getMaritalStatuses() != null && targetPref.getMaritalStatuses().isArray()) {
|
||||
boolean accepted = false;
|
||||
for (int i = 0; i < targetPref.getMaritalStatuses().size(); i++) {
|
||||
if (targetPref.getMaritalStatuses().get(i).asText().equals(myProfile.getMaritalStatus())) {
|
||||
accepted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!accepted) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return matchScoringService.bidirectionalRequiredSatisfied(myPref, myProfile, targetPref, candidate);
|
||||
}
|
||||
|
||||
private boolean isParticipantEligible(String userId) {
|
||||
@@ -341,23 +272,19 @@ public class RecommendationEngineService {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方向性评分:委托 {@link MatchScoringService}(唯一事实源)。
|
||||
*
|
||||
* <p>此前为桩 `return 50.0`,而阈值默认 60 → `mutualScore < 60` 恒成立,
|
||||
* 导致 `GET /recommendations` **恒返回空数组**(2026-09-23 UAT 走查实测)。
|
||||
*/
|
||||
private double calculateScore(String fromUserId, UserProfile target, UserPreference pref) {
|
||||
// TODO: Phase 07 后续完善评分逻辑
|
||||
return 50.0; // V1 简化:默认中间分
|
||||
return matchScoringService.scoreDirectionally(pref, target);
|
||||
}
|
||||
|
||||
private List<String> generateReasons(String userId, UserProfile candidate,
|
||||
UserPreference myPref, UserPreference targetPref) {
|
||||
List<String> reasons = new ArrayList<>();
|
||||
// TODO: 基于真实资料生成推荐理由
|
||||
reasons.add("年龄符合双方择偶要求");
|
||||
reasons.add("都希望长期在丹阳生活");
|
||||
return reasons;
|
||||
}
|
||||
|
||||
private int calculateAge(LocalDate birthDate) {
|
||||
if (birthDate == null) return 0;
|
||||
return Period.between(birthDate, LocalDate.now()).getYears();
|
||||
return matchScoringService.reasons(myPref, candidate);
|
||||
}
|
||||
|
||||
private Set<String> getPassedUserIds(String userId, Instant since) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.danyang.match.platform.matchmaker.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 受控联系授权配置(ZC-MM-003 / B1 立项,对照 {@code ProfileProperties} 范式)。
|
||||
*
|
||||
* <p><b>配置化纪律</b>(AGENTS.md #12:未确认数量参数不得硬编码):
|
||||
* 五个 canonical key 统一在此管理,禁止散落在 Controller/Service/前端各自写死;
|
||||
* 治理登记见 T06 config-register(OQ-MATCHMAKER-003)。
|
||||
*
|
||||
* <p><b>fail-safe 语义</b>:{@code enabled} 的 Java 字段缺省为 <b>false</b> ——
|
||||
* 若配置键完全缺失(如新环境漏配),机制整体关闭(fail-safe 关闭优于意外开放)。
|
||||
* 生产 {@code application.yml} 显式声明 {@code matchmaker.contact.enabled: true};
|
||||
* "默认开启" 指的是配置注册表中的生效默认值,而非代码缺省。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "matchmaker.contact")
|
||||
public class ContactAuthorizationConfig {
|
||||
|
||||
/**
|
||||
* 机制总开关。
|
||||
* Java 缺省 false(fail-safe:配置缺失 → 机制关闭);生产 yml 显式置 true。
|
||||
* disclose(H4 唯一披露出口)前强校验,关闭时任何披露请求 404 化拒绝。
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* 审批岗权限码(逗号分隔,任一命中即可审批)。
|
||||
* 默认 "matchmaker.team.assign,matchmaker.assign"(组长组织内审批 / 平台授权岗位全量审批)。
|
||||
* 审批权限在 Service 层动态判定(principal 权限 ∈ 本集合),不用 @PreAuthorize 静态注解 ——
|
||||
* 审批岗名单可经 yml 调整而无需改代码。
|
||||
*/
|
||||
private String approverAuthorities = "matchmaker.team.assign,matchmaker.assign";
|
||||
|
||||
/**
|
||||
* 用户同意窗口(小时):pending_consent 超窗未同意 → 惰性 expired。
|
||||
* 默认 72h(治理登记 OQ-MATCHMAKER-003 技术默认,待产品确认)。
|
||||
*/
|
||||
private int consentDeadlineHours = 72;
|
||||
|
||||
/**
|
||||
* 授权默认有效期(天):用户 consent 起算,expires_at = consent + N 天。
|
||||
* 默认 7 天;到期由双态惰性收敛置 expired。
|
||||
*/
|
||||
private int defaultValidityDays = 7;
|
||||
|
||||
/**
|
||||
* 授权审计数据保留期(天):受控联系相关审计/敏感访问记录的保留下限口径。
|
||||
* 默认 365 天;当前以 /my 响应元数据形式下发(retentionDays 字段)供前端展示,
|
||||
* 治理登记 T06 open-questions 同步说明。
|
||||
*/
|
||||
private int retentionDays = 365;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.danyang.match.platform.matchmaker.controller;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.service.MatchmakerAssignmentService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 服务对象分配接口(运营端,ZC-MM-002 / A1)。
|
||||
*
|
||||
* <p>权限模型(D2):
|
||||
* <ul>
|
||||
* <li>写操作(创建/转分配/撤销/结束/可分配列表):
|
||||
* {@code matchmaker.assign}(平台授权人员,不限组织)
|
||||
* 或 {@code matchmaker.team.assign}(红娘组长,同组织范围);</li>
|
||||
* <li>读自己名下分配(/my):{@code matchmaker.service}(普通红娘即可)。</li>
|
||||
* </ul>
|
||||
* operatorId 一律取当前认证主体(principal),不信任请求参数。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/operator/matchmaker/assignments")
|
||||
@RequiredArgsConstructor
|
||||
public class MatchmakerAssignmentController {
|
||||
|
||||
private final MatchmakerAssignmentService assignmentService;
|
||||
|
||||
/**
|
||||
* 创建分配。
|
||||
* Body: userId / matchmakerOperatorId / serviceId? / reason(必填)/ expiresAt?(ISO-8601)
|
||||
*/
|
||||
@PostMapping
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<?> create(@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@RequestBody Map<String, String> body) {
|
||||
MatchmakerAssignment created = assignmentService.create(
|
||||
principal.id(),
|
||||
principal.hasPermission("matchmaker.assign"),
|
||||
body.get("userId"),
|
||||
body.get("matchmakerOperatorId"),
|
||||
body.getOrDefault("serviceId", null),
|
||||
body.get("reason"),
|
||||
parseInstant(body.get("expiresAt")));
|
||||
return ApiResponse.ok(assignmentView(created));
|
||||
}
|
||||
|
||||
/** 转分配:旧记录置 transferred,同事务新建 active。reason 必填。 */
|
||||
@PostMapping("/{id}/transfer")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<?> transfer(@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id,
|
||||
@RequestBody Map<String, String> body) {
|
||||
MatchmakerAssignment created = assignmentService.transfer(
|
||||
id,
|
||||
principal.id(),
|
||||
principal.hasPermission("matchmaker.assign"),
|
||||
body.get("newMatchmakerOperatorId"),
|
||||
body.get("reason"));
|
||||
return ApiResponse.ok(assignmentView(created));
|
||||
}
|
||||
|
||||
/** 撤销分配。reason 必填。 */
|
||||
@PostMapping("/{id}/revoke")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<?> revoke(@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(assignmentView(assignmentService.revoke(
|
||||
id, principal.id(), principal.hasPermission("matchmaker.assign"),
|
||||
body.get("reason"))));
|
||||
}
|
||||
|
||||
/** 结束分配。reason 必填。 */
|
||||
@PostMapping("/{id}/end")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<?> end(@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(assignmentView(assignmentService.end(
|
||||
id, principal.id(), principal.hasPermission("matchmaker.assign"),
|
||||
body.get("reason"))));
|
||||
}
|
||||
|
||||
/** 我名下生效中的服务对象分配(普通红娘工作台)。 */
|
||||
@GetMapping("/my")
|
||||
@PreAuthorize("hasAuthority('matchmaker.service')")
|
||||
public ApiResponse<List<Map<String, Object>>> my(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
List<Map<String, Object>> list = assignmentService.listMy(principal.id()).stream()
|
||||
.map(this::assignmentView)
|
||||
.toList();
|
||||
return ApiResponse.ok(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可分配红娘列表(创建/转分配弹窗数据源)。
|
||||
* 返回 id/name/organizationId,不含联系方式(字段级隐私,ZC-MM-005 范围)。
|
||||
*/
|
||||
@GetMapping("/assignable-matchmakers")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<List<Map<String, Object>>> assignable(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
return ApiResponse.ok(assignmentService.listAssignableMatchmakers(
|
||||
principal.id(), principal.hasPermission("matchmaker.assign")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 组长团队统计(ZC-MM-005 / E4 新增)。仅 matchmaker.team.assign 持有者可调;
|
||||
* 以组长本人 organization_id 为边界(NULL 组长统计平台直属)。
|
||||
* 返回纯脱敏计数:activeAssignmentCount / perMatchmakerCounts / activeMatchmakerCount,
|
||||
* 不含任何用户身份或联系方式。
|
||||
*/
|
||||
@GetMapping("/team/statistics")
|
||||
@PreAuthorize("hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<Map<String, Object>> teamStatistics(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
return ApiResponse.ok(assignmentService.teamStatistics(principal.id()));
|
||||
}
|
||||
|
||||
private Instant parseInstant(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(raw);
|
||||
}
|
||||
|
||||
private Map<String, Object> assignmentView(MatchmakerAssignment a) {
|
||||
return Map.ofEntries(
|
||||
Map.entry("id", a.getId()),
|
||||
Map.entry("userId", a.getUserId()),
|
||||
Map.entry("matchmakerOperatorId", a.getMatchmakerOperatorId()),
|
||||
Map.entry("serviceId", a.getServiceId() == null ? "" : a.getServiceId()),
|
||||
Map.entry("assignmentScope", a.getAssignmentScope()),
|
||||
Map.entry("status", a.getStatus()),
|
||||
Map.entry("assignmentReason", a.getAssignmentReason()),
|
||||
Map.entry("assignedAt", a.getAssignedAt() == null ? "" : a.getAssignedAt().toString()),
|
||||
Map.entry("expiresAt", a.getExpiresAt() == null ? "" : a.getExpiresAt().toString()),
|
||||
Map.entry("endedAt", a.getEndedAt() == null ? "" : a.getEndedAt().toString()),
|
||||
Map.entry("endReason", a.getEndReason() == null ? "" : a.getEndReason())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.danyang.match.platform.matchmaker.controller;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||
import com.danyang.match.platform.matchmaker.service.ContactAuthorizationService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 受控联系授权控制器(运营端,ZC-MM-003 / B1 立项)。
|
||||
*
|
||||
* <p>端点(基路径 {@code /api/v1/operator/matchmaker/contact-authorizations}):
|
||||
* <ul>
|
||||
* <li>POST {@code ""} —— 红娘发起授权申请(matchmaker.service,purpose 必填);</li>
|
||||
* <li>POST {@code /{id}/approve} / {@code /{id}/reject} —— 审批岗批准/拒绝
|
||||
* (审批岗权限码在 Service 层动态判定 ∈ approver-authorities,组长另有组织范围校验);</li>
|
||||
* <li>GET {@code /my} —— 红娘本人授权列表;</li>
|
||||
* <li>POST {@code /{id}/revoke} —— 申请人或审批人撤销(reason 必填);</li>
|
||||
* <li>GET {@code /disclose} —— H4 唯一披露出口(userId/purpose 必填,
|
||||
* 每次落 SensitiveAccessLog;phone 不落任何应用日志)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>类级 {@code matchmaker.view} 覆盖列表/详情读;写动作方法级收敛;
|
||||
* 审批岗动态权限与 G4 404 化拒绝、approve 403 边界均由
|
||||
* {@code ContactAuthorizationService} 承担(T06 open-questions OQ-MATCHMAKER-009)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/operator/matchmaker/contact-authorizations")
|
||||
@PreAuthorize("hasAuthority('matchmaker.view')")
|
||||
@RequiredArgsConstructor
|
||||
public class MatchmakerContactAuthorizationController {
|
||||
|
||||
private final ContactAuthorizationService contactAuthorizationService;
|
||||
|
||||
/** 红娘发起授权申请(须持分配;purpose 必填)。 */
|
||||
@PostMapping
|
||||
@PreAuthorize("hasAuthority('matchmaker.service')")
|
||||
public ApiResponse<MatchmakerContactAuthorization> request(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(contactAuthorizationService.request(
|
||||
principal.id(),
|
||||
body.get("userId"),
|
||||
body.get("channel"),
|
||||
body.get("purpose")));
|
||||
}
|
||||
|
||||
/** 审批岗批准(权限动态判定 + 组长组织范围校验)。 */
|
||||
@PostMapping("/{id}/approve")
|
||||
public ApiResponse<MatchmakerContactAuthorization> approve(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
return ApiResponse.ok(contactAuthorizationService.approve(
|
||||
id, principal.id(), principal.permissions()));
|
||||
}
|
||||
|
||||
/** 审批岗拒绝。 */
|
||||
@PostMapping("/{id}/reject")
|
||||
public ApiResponse<MatchmakerContactAuthorization> reject(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
return ApiResponse.ok(contactAuthorizationService.reject(
|
||||
id, principal.id(), principal.permissions()));
|
||||
}
|
||||
|
||||
/** 红娘本人授权列表(含保留期元数据)。 */
|
||||
@GetMapping("/my")
|
||||
public ApiResponse<Map<String, Object>> my(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
return ApiResponse.ok(contactAuthorizationService.myAuthorizations(principal.id()));
|
||||
}
|
||||
|
||||
/** 申请人或审批人撤销(reason 必填)。 */
|
||||
@PostMapping("/{id}/revoke")
|
||||
public ApiResponse<MatchmakerContactAuthorization> revoke(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(contactAuthorizationService.revoke(
|
||||
id, principal.id(), body.get("reason")));
|
||||
}
|
||||
|
||||
/** H4 唯一披露出口:userId/purpose 必填,channel 缺省 phone。 */
|
||||
@GetMapping("/disclose")
|
||||
public ApiResponse<Map<String, Object>> disclose(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@RequestParam String userId,
|
||||
@RequestParam String purpose,
|
||||
@RequestParam(required = false) String channel) {
|
||||
return ApiResponse.ok(contactAuthorizationService.disclose(
|
||||
principal.id(), userId, channel, purpose));
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 红娘服务端点
|
||||
* 红娘服务端点(用户端)
|
||||
*
|
||||
* 用户端:
|
||||
* POST /api/v1/matchmaker/services — 提交红娘服务请求
|
||||
@@ -26,10 +26,15 @@ import java.util.Map;
|
||||
* POST /api/v1/matchmaker/recommendations/{id}/accept — 用户主动接受(Like target)
|
||||
* POST /api/v1/matchmaker/recommendations/{id}/pass
|
||||
*
|
||||
* 操作人端(Matchmaker/Operator role):
|
||||
* PUT /api/v1/matchmaker/services/{id}/assign
|
||||
* POST /api/v1/matchmaker/services/{id}/recommendation — 为用户推荐对象
|
||||
* POST /api/v1/matchmaker/services/{id}/referral — 为用户转介服务
|
||||
* 操作人端(Matchmaker/Operator)在 {@link MatchmakerOperatorController},基路径为
|
||||
* <b>{@code /api/v1/operator/matchmaker}</b>(如 {@code POST /services/{id}/assign}、
|
||||
* {@code POST /services/{id}/recommend}、{@code POST /services/{id}/followup}、
|
||||
* {@code POST /services/{id}/complete})。
|
||||
*
|
||||
* <p><b>2026-09-23 修正</b>:本注释此前把上述 operator 端点写成
|
||||
* {@code /matchmaker/services/{id}/assign|recommendation|referral},但本类从未注册过这些路由
|
||||
* ({@code /referral} 亦不复存在,转介能力由独立控制器提供)——文档与实现不符会误导调用方。
|
||||
* 路由已由 {@code MatchmakerRouteContractTest} 之类的机械守卫锁定,此处只如实描述。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/matchmaker")
|
||||
|
||||
@@ -13,6 +13,11 @@ import java.util.Map;
|
||||
|
||||
/**
|
||||
* 红娘工作台控制器(Operator调用)
|
||||
*
|
||||
* <p>ZC-MM-002(A1)状态机变更:原 {@code POST /services/{id}/claim}(红娘接单)端点已删除。
|
||||
* 服务对象归属统一由 matchmaker_assignments 建模(D3 决策:不保留组长认领),
|
||||
* 分配入口收敛为 {@code MatchmakerAssignmentController}(POST /operator/matchmaker/assignments),
|
||||
* 服务单状态由分配动作同事务联动(submitted → assigned)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/operator/matchmaker")
|
||||
@@ -29,42 +34,57 @@ public class MatchmakerOperatorController {
|
||||
return ApiResponse.ok(matchmakerServiceService.getDashboard(operatorId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 待分配队列。ZC-MM-002(D4):方法级权限收敛 —— 仅分配权持有者
|
||||
* (matchmaker.assign 平台授权 / matchmaker.team.assign 组长)可看全局待分配队列,
|
||||
* 普通红娘(仅 matchmaker.view/service)403。
|
||||
*
|
||||
* <p>组长视角说明(ZC-MM-005 / E4,治理登记 007):matchmaker_services 表无组织归属字段
|
||||
* (organization_id 恒 null 的已知限制),因此待分配队列无法按组长组织过滤,
|
||||
* 权衡后对分配权持有者全局可读 —— 待分配服务单尚无负责人,队列不含敏感分配关系。
|
||||
* 组织归属字段的补齐登记至 ZC-MM-007。
|
||||
*/
|
||||
@GetMapping("/pending")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||
public ApiResponse<List<Map<String, Object>>> getPending(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
return ApiResponse.ok(matchmakerServiceService.getPendingServices());
|
||||
}
|
||||
|
||||
/**
|
||||
* 分配服务给红娘(兼容入口)。ZC-MM-002(D4):
|
||||
* 同事务联动「创建 matchmaker_assignments 分配 + 服务单置 assigned」。
|
||||
*/
|
||||
@PostMapping("/services/{id}/assign")
|
||||
@PreAuthorize("hasAuthority('matchmaker.assign')")
|
||||
public ApiResponse<?> assignService(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id,
|
||||
@RequestBody Map<String, String> body) {
|
||||
String operatorId = principal.id();
|
||||
String assignOperatorId = body.get("operatorId");
|
||||
return ApiResponse.ok(matchmakerServiceService.assignService(id, assignOperatorId, null));
|
||||
String assignerOperatorId = principal.id();
|
||||
String targetOperatorId = body.get("operatorId");
|
||||
String reason = body.getOrDefault("reason", "红娘服务单分配");
|
||||
return ApiResponse.ok(matchmakerServiceService.assignService(
|
||||
id, assignerOperatorId, targetOperatorId, reason));
|
||||
}
|
||||
|
||||
@PostMapping("/services/{id}/claim")
|
||||
@PreAuthorize("hasAuthority('matchmaker.service')")
|
||||
public ApiResponse<?> claimService(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
String operatorId = principal.id();
|
||||
return ApiResponse.ok(matchmakerServiceService.claimService(operatorId, id));
|
||||
}
|
||||
|
||||
@GetMapping("/my-services")
|
||||
public ApiResponse<?> getMyServices(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||
String operatorId = principal.id();
|
||||
return ApiResponse.ok(matchmakerServiceService.getMyServices(operatorId));
|
||||
}
|
||||
// GET /my-services 已删除(ZC-MM-005 / E4 死端点清理):
|
||||
// 原实现把 operatorId 误当 user_id 传给 getMyServices(按 C 端 user_id 查询,恒空),
|
||||
// 且 admin-web / miniapp 零调用。运营端"我的服务对象"替代路径:
|
||||
// GET /operator/matchmaker/assignments/my(ZC-MM-002 A1 新增)。
|
||||
// getMyServices 服务方法保留,供 C 端 GET /matchmaker/services 使用。
|
||||
|
||||
/**
|
||||
* Phase 13:红娘名下服务的全部推荐列表(运营端工作台用)。
|
||||
* 红娘名下服务的全部推荐列表(运营端工作台用)。
|
||||
* 补此前 admin-web 调用 `/matchmaker/recommendations/operator` 404 的契约缺口。
|
||||
*
|
||||
* <p>口径核查(ZC-MM-005 收口 / P1-1):范围事实源是 {@code matchmaker_assignments}
|
||||
* 中本人<b>生效中的分配</b>(active 且未过有效期)→ 该分配对象(user)名下
|
||||
* 服务单上的推荐,经 matchmaker_services 桥接;既不按
|
||||
* matchmaker_services.assigned_operator_id 残留列过滤,也<b>不</b>按
|
||||
* recommendation.operator_id 过滤(推荐条目只含 targetUserId/reason/status
|
||||
* 摘要,不涉及服务对象字段级隐私)。分配 revoke/end 后不再可见
|
||||
* (DEC-002 规则7:撤销即失权)。
|
||||
*/
|
||||
@GetMapping("/recommendations")
|
||||
public ApiResponse<List<Map<String, Object>>> getRecommendations(
|
||||
@@ -72,16 +92,19 @@ public class MatchmakerOperatorController {
|
||||
return ApiResponse.ok(matchmakerServiceService.getRecommendationsByOperator(principal.id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务详情(ZC-MM-005 / E2 防探测 404)。
|
||||
*
|
||||
* <p>语义变更:非持有人与查无 serviceId 抛出完全相同的
|
||||
* BusinessException(NOT_FOUND, "服务不存在") —— 响应体逐字段一致
|
||||
* (success=false / code=NOT_FOUND / message=服务不存在),无法区分"无权"与"不存在"。
|
||||
* 此前 002 的 viewerIsOwner 双态(持有人完整 / 非负责人脱敏)已删除。
|
||||
*/
|
||||
@GetMapping("/services/{id}")
|
||||
public ApiResponse<Map<String, Object>> getServiceDetail(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
// Phase 13 D4:传入调用者身份,Service 层按归属决定返回完整/脱敏详情
|
||||
Map<String, Object> detail = matchmakerServiceService.getServiceDetail(id, principal.id());
|
||||
if (detail == null) {
|
||||
return ApiResponse.error(com.danyang.match.platform.shared.enums.ApiResponseCode.NOT_FOUND);
|
||||
}
|
||||
return ApiResponse.ok(detail);
|
||||
return ApiResponse.ok(matchmakerServiceService.getServiceDetail(id, principal.id()));
|
||||
}
|
||||
|
||||
@PostMapping("/services/{id}/recommend")
|
||||
@@ -114,7 +137,8 @@ public class MatchmakerOperatorController {
|
||||
public ApiResponse<?> completeService(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
return ApiResponse.ok(matchmakerServiceService.completeService(id));
|
||||
// ZC-MM-002(D4):归属判定切换到 ServiceAssignmentPolicy(服务层完成)
|
||||
return ApiResponse.ok(matchmakerServiceService.completeService(id, principal.id()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.danyang.match.platform.matchmaker.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.danyang.match.platform.shared.base.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* 服务对象分配(ZC-MM-002 / A1)
|
||||
* 对应 DB: matchmaker_assignments(V053)
|
||||
*
|
||||
* <p>建模说明:
|
||||
* <ul>
|
||||
* <li>{@code matchmakerOperatorId}:持有该用户服务对象的红娘(operators 主体,
|
||||
* 沿用 matchmaker_services.assigned_operator_id 惯例)。</li>
|
||||
* <li>{@code assignedBy}:做出本次分配的操作者(组长 / 平台授权人员)。</li>
|
||||
* <li>状态机(D5):active → transferred / revoked / ended;
|
||||
* expires_at 届满由 {@code ServiceAssignmentPolicy} 惰性置 expired(无定时任务);
|
||||
* 终态一律拒绝再转换。</li>
|
||||
* <li>scope:primary(主责,同用户仅一条生效中,DB 部分唯一索引兜底)/
|
||||
* collaborating(协同)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("matchmaker_assignments")
|
||||
public class MatchmakerAssignment extends BaseEntity {
|
||||
|
||||
/** 被服务用户 */
|
||||
private String userId;
|
||||
|
||||
/** 持有服务对象的红娘(operators.id) */
|
||||
private String matchmakerOperatorId;
|
||||
|
||||
/** 关联的服务单(可空:允许脱离服务单的用户级分配) */
|
||||
private String serviceId;
|
||||
|
||||
/** 做出本次分配的操作者(operators.id) */
|
||||
private String assignedBy;
|
||||
|
||||
/** 分配范围:primary / collaborating(与 V053 chk_mm_assignment_scope 白名单一致) */
|
||||
private String assignmentScope;
|
||||
|
||||
/** 分配理由(必填) */
|
||||
private String assignmentReason;
|
||||
|
||||
/** 状态:active/ended/revoked/transferred/expired(与 V053 chk_mm_assignment_status 白名单一致) */
|
||||
private String status;
|
||||
|
||||
private Instant assignedAt;
|
||||
|
||||
/** 有效期届满时间;null 表示长期有效 */
|
||||
private Instant expiresAt;
|
||||
|
||||
/** 终态时间(ended/revoked/transferred/expired 时落库) */
|
||||
private Instant endedAt;
|
||||
|
||||
/** 终态理由(revoked/ended 必填;transferred 记录转分配理由;expired 为固定文案) */
|
||||
private String endReason;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.danyang.match.platform.matchmaker.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.danyang.match.platform.shared.base.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* 受控联系授权(ZC-MM-003 / B1 例外通道,架构师设计 H4)。
|
||||
*
|
||||
* <p>状态机(六态):pending_approval → pending_consent → active / rejected;
|
||||
* pending_consent / active 双态惰性收敛为 expired(有效期或同意窗口届满);
|
||||
* active → revoked(申请人或审批人撤销)。V056 建表。
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("matchmaker_contact_authorizations")
|
||||
public class MatchmakerContactAuthorization extends BaseEntity {
|
||||
|
||||
/** 发起申请的红娘 operator id */
|
||||
private String operatorId;
|
||||
/** 被联系用户 id */
|
||||
private String userId;
|
||||
/** 联系渠道:phone / offline_meeting / full_contact */
|
||||
private String channel;
|
||||
/** 授权目的(必填,用户同意页明示) */
|
||||
private String purpose;
|
||||
/** 状态:pending_approval / pending_consent / active / rejected / expired / revoked */
|
||||
private String status;
|
||||
/** 审批岗 operator id */
|
||||
private String approvedBy;
|
||||
private Instant approvedAt;
|
||||
/** 用户单独同意时间(独立端点,无预同意参数) */
|
||||
private Instant userConsentedAt;
|
||||
/** 生效截止:pending 期为同意窗口上界,consent 后重算为 consent + validity days */
|
||||
private Instant expiresAt;
|
||||
private Instant revokedAt;
|
||||
private String revokedBy;
|
||||
private String revokeReason;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.danyang.match.platform.matchmaker.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 服务对象分配 Mapper(ZC-MM-002 / A1)
|
||||
*
|
||||
* <p>「生效中」的统一口径:status = 'active' 且(expires_at IS NULL OR expires_at > NOW())。
|
||||
* 惰性过期由 {@link #expireOverdue} 负责(读前触发,无定时任务),
|
||||
* 这里的 expires 条件是双保险:即使惰性过期尚未执行,已届满的行也不会被当作生效中。
|
||||
*/
|
||||
@Mapper
|
||||
public interface MatchmakerAssignmentMapper extends BaseMapper<MatchmakerAssignment> {
|
||||
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE id = #{id} AND deleted_at IS NULL LIMIT 1")
|
||||
Optional<MatchmakerAssignment> findById(@Param("id") String id);
|
||||
|
||||
/** 某红娘名下全部生效中的分配(GET /my、GET /assignable 的工作台口径) */
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE matchmaker_operator_id = #{operatorId} " +
|
||||
"AND status = 'active' AND (expires_at IS NULL OR expires_at > NOW()) " +
|
||||
"AND deleted_at IS NULL ORDER BY assigned_at DESC")
|
||||
List<MatchmakerAssignment> findActiveByOperator(@Param("operatorId") String operatorId);
|
||||
|
||||
/** 某红娘对某用户是否持有生效中的分配(数据范围判定核心查询) */
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE matchmaker_operator_id = #{operatorId} " +
|
||||
"AND user_id = #{userId} AND status = 'active' " +
|
||||
"AND (expires_at IS NULL OR expires_at > NOW()) " +
|
||||
"AND deleted_at IS NULL ORDER BY assigned_at DESC LIMIT 1")
|
||||
Optional<MatchmakerAssignment> findActiveByOperatorAndUser(@Param("operatorId") String operatorId,
|
||||
@Param("userId") String userId);
|
||||
|
||||
/** 某用户当前生效中的主责分配(创建/转分配前的唯一性预检) */
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE user_id = #{userId} " +
|
||||
"AND status = 'active' AND assignment_scope = 'primary' " +
|
||||
"AND (expires_at IS NULL OR expires_at > NOW()) " +
|
||||
"AND deleted_at IS NULL LIMIT 1")
|
||||
Optional<MatchmakerAssignment> findActivePrimaryByUser(@Param("userId") String userId);
|
||||
|
||||
/** 某服务单上生效中的分配(服务单维度的归属判定) */
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE service_id = #{serviceId} " +
|
||||
"AND status = 'active' AND (expires_at IS NULL OR expires_at > NOW()) " +
|
||||
"AND deleted_at IS NULL ORDER BY assigned_at DESC LIMIT 1")
|
||||
Optional<MatchmakerAssignment> findActiveByService(@Param("serviceId") String serviceId);
|
||||
|
||||
/** 某服务单的全部分配历史(追溯用) */
|
||||
@Select("SELECT * FROM matchmaker_assignments WHERE service_id = #{serviceId} " +
|
||||
"AND deleted_at IS NULL ORDER BY assigned_at DESC")
|
||||
List<MatchmakerAssignment> findByService(@Param("serviceId") String serviceId);
|
||||
|
||||
/**
|
||||
* 惰性过期:把 expires_at 已届满的 active 行置为 expired 并落库。
|
||||
* 由 {@code ServiceAssignmentPolicy} 在读取路径前触发,无定时任务。
|
||||
*
|
||||
* @return 本次被置为 expired 的行数
|
||||
*/
|
||||
@Update("UPDATE matchmaker_assignments SET status = 'expired', " +
|
||||
"ended_at = NOW(), end_reason = '有效期届满自动失效', updated_at = NOW() " +
|
||||
"WHERE status = 'active' AND expires_at IS NOT NULL AND expires_at < NOW() " +
|
||||
"AND deleted_at IS NULL")
|
||||
int expireOverdue();
|
||||
|
||||
// ==================== ZC-MM-005 / E4:组长团队统计(纯脱敏计数) ====================
|
||||
// 组织边界:organization_id IS NOT DISTINCT FROM #{organizationId} ——
|
||||
// NULL=NULL 平台直属规则在 SQL 层等价复用(有组织组长统计本组织;NULL 组长统计平台直属)。
|
||||
|
||||
/** 某组织范围内生效中的分配总数 */
|
||||
@Select("SELECT COUNT(*) FROM matchmaker_assignments ma " +
|
||||
"JOIN operators o ON o.id = ma.matchmaker_operator_id " +
|
||||
"WHERE ma.status = 'active' AND (ma.expires_at IS NULL OR ma.expires_at > NOW()) " +
|
||||
"AND ma.deleted_at IS NULL AND o.deleted_at IS NULL " +
|
||||
"AND o.organization_id IS NOT DISTINCT FROM #{organizationId}")
|
||||
long countActiveByOrganization(@Param("organizationId") String organizationId);
|
||||
|
||||
/** 某组织范围内各红娘的生效分配数(operatorId/name/activeCount;别名加引号保持驼峰键名) */
|
||||
@Select("SELECT o.id AS \"operatorId\", o.name AS \"operatorName\", COUNT(*) AS \"activeCount\" " +
|
||||
"FROM matchmaker_assignments ma " +
|
||||
"JOIN operators o ON o.id = ma.matchmaker_operator_id " +
|
||||
"WHERE ma.status = 'active' AND (ma.expires_at IS NULL OR ma.expires_at > NOW()) " +
|
||||
"AND ma.deleted_at IS NULL AND o.deleted_at IS NULL " +
|
||||
"AND o.organization_id IS NOT DISTINCT FROM #{organizationId} " +
|
||||
"GROUP BY o.id, o.name ORDER BY \"activeCount\" DESC")
|
||||
List<Map<String, Object>> countActiveGroupByOperator(@Param("organizationId") String organizationId);
|
||||
|
||||
/** 某组织范围内持有生效分配的红娘数(去重) */
|
||||
@Select("SELECT COUNT(DISTINCT ma.matchmaker_operator_id) FROM matchmaker_assignments ma " +
|
||||
"JOIN operators o ON o.id = ma.matchmaker_operator_id " +
|
||||
"WHERE ma.status = 'active' AND (ma.expires_at IS NULL OR ma.expires_at > NOW()) " +
|
||||
"AND ma.deleted_at IS NULL AND o.deleted_at IS NULL " +
|
||||
"AND o.organization_id IS NOT DISTINCT FROM #{organizationId}")
|
||||
long countActiveOperators(@Param("organizationId") String organizationId);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.danyang.match.platform.matchmaker.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 受控联系授权 Mapper(ZC-MM-003 / B1 立项)。
|
||||
*
|
||||
* <p>双态惰性收敛(对照 005 expireOverdue 范式,读前触发、无定时任务):
|
||||
* ① active 且 expires_at 届满 → expired(授权有效期到);
|
||||
* ② pending_consent 且同意窗口(expires_at 在 request/approve 期承载窗口上界)届满 → expired。
|
||||
*/
|
||||
@Mapper
|
||||
public interface MatchmakerContactAuthorizationMapper extends BaseMapper<MatchmakerContactAuthorization> {
|
||||
|
||||
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE id = #{id} AND deleted_at IS NULL LIMIT 1")
|
||||
Optional<MatchmakerContactAuthorization> findById(@Param("id") String id);
|
||||
|
||||
/** 某红娘的全部授权记录(工作台列表,倒序) */
|
||||
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE operator_id = #{operatorId} " +
|
||||
"AND deleted_at IS NULL ORDER BY created_at DESC")
|
||||
List<MatchmakerContactAuthorization> findByOperator(@Param("operatorId") String operatorId);
|
||||
|
||||
/** 用户待同意队列(pending_consent,C 端同意页数据源) */
|
||||
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE user_id = #{userId} " +
|
||||
"AND status = 'pending_consent' AND expires_at > NOW() AND deleted_at IS NULL " +
|
||||
"ORDER BY created_at DESC")
|
||||
List<MatchmakerContactAuthorization> findPendingConsentByUser(@Param("userId") String userId);
|
||||
|
||||
/** 某红娘对某用户某渠道当前生效中的授权 */
|
||||
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE operator_id = #{operatorId} " +
|
||||
"AND user_id = #{userId} AND channel = #{channel} AND status = 'active' " +
|
||||
"AND expires_at > NOW() AND deleted_at IS NULL LIMIT 1")
|
||||
Optional<MatchmakerContactAuthorization> findActiveByOperatorUserChannel(@Param("operatorId") String operatorId,
|
||||
@Param("userId") String userId,
|
||||
@Param("channel") String channel);
|
||||
|
||||
/** 某用户的全部授权记录(C 端我的授权列表) */
|
||||
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE user_id = #{userId} " +
|
||||
"AND deleted_at IS NULL ORDER BY created_at DESC")
|
||||
List<MatchmakerContactAuthorization> findByUser(@Param("userId") String userId);
|
||||
|
||||
/**
|
||||
* 双态惰性收敛:
|
||||
* ① active 过期 → expired;
|
||||
* ② pending_consent 超同意窗口 → expired(expires_at 即窗口上界)。
|
||||
*
|
||||
* @return 本次被收敛的行数
|
||||
*/
|
||||
@Update("UPDATE matchmaker_contact_authorizations SET status = 'expired', updated_at = NOW() " +
|
||||
"WHERE status IN ('active', 'pending_consent') AND expires_at < NOW() AND deleted_at IS NULL")
|
||||
int expireOverdue();
|
||||
}
|
||||
@@ -30,13 +30,19 @@ public interface MatchmakerRecommendationMapper extends BaseMapper<MatchmakerRec
|
||||
int markViewed(@Param("id") String id);
|
||||
|
||||
/**
|
||||
* Phase 13:某红娘名下服务的全部推荐(运营端列表用)。
|
||||
* 通过 service_id 关联 matchmaker_services.assigned_operator_id 限定为本人名下,
|
||||
* 避免运营端越权看到他人推荐。
|
||||
* 某红娘推荐列表(运营端工作台用)。
|
||||
*
|
||||
* <p>ZC-MM-005 收口(P1-1):范围事实源由 matchmaker_services.assigned_operator_id
|
||||
* 残留列切换为 matchmaker_assignments 生效中分配(active 且未过有效期)。
|
||||
* 语义 = 「本人当前有效分配对象(user)名下服务单上的推荐」—— 分配 revoke/end 后
|
||||
* 残留列不再构成可见凭据(DEC-002 规则7:撤销即失权)。
|
||||
*/
|
||||
@Select("SELECT r.* FROM matchmaker_recommendations r " +
|
||||
"JOIN matchmaker_services s ON s.id = r.service_id " +
|
||||
"WHERE s.assigned_operator_id = #{operatorId} AND s.deleted_at IS NULL " +
|
||||
"JOIN matchmaker_services s ON s.id = r.service_id AND s.deleted_at IS NULL " +
|
||||
"JOIN matchmaker_assignments a ON a.user_id = s.user_id " +
|
||||
"AND a.matchmaker_operator_id = #{operatorId} " +
|
||||
"AND a.status = 'active' AND (a.expires_at IS NULL OR a.expires_at > NOW()) " +
|
||||
"AND a.deleted_at IS NULL " +
|
||||
"ORDER BY r.created_at DESC")
|
||||
List<MatchmakerRecommendation> findByOperatorId(@Param("operatorId") String operatorId);
|
||||
}
|
||||
|
||||
@@ -26,35 +26,51 @@ public interface MatchmakerServiceMapper extends BaseMapper<MatchmakerServiceRec
|
||||
@Select("SELECT COUNT(*) FROM matchmaker_services WHERE status = 'submitted' AND deleted_at IS NULL")
|
||||
long countSubmitted();
|
||||
|
||||
/** 某红娘进行中的服务数(工作台统计) */
|
||||
@Select("SELECT COUNT(*) FROM matchmaker_services WHERE assigned_operator_id = #{operatorId} " +
|
||||
"AND status = 'processing' AND deleted_at IS NULL")
|
||||
/**
|
||||
* 某红娘进行中的服务数(工作台统计)。
|
||||
* ZC-MM-005 收口(P1-2):范围事实源由 assigned_operator_id 残留列切换为
|
||||
* matchmaker_assignments 生效中分配(active 且未过有效期)——「本人名下进行中」
|
||||
* = 本人 active 分配关联 user 的服务单中 status='in_service'。
|
||||
* 分配 end/revoke 后,该用户的服务单不再计入本人(DEC-002 规则7:服务结束失去访问权)。
|
||||
* 状态口径沿用 ZC-MM-002(D4)修正:'in_service'('processing' 不在 V009 白名单)。
|
||||
*/
|
||||
@Select("SELECT COUNT(DISTINCT s.id) FROM matchmaker_services s " +
|
||||
"JOIN matchmaker_assignments a ON a.user_id = s.user_id " +
|
||||
"AND a.matchmaker_operator_id = #{operatorId} " +
|
||||
"AND a.status = 'active' AND (a.expires_at IS NULL OR a.expires_at > NOW()) " +
|
||||
"AND a.deleted_at IS NULL " +
|
||||
"WHERE s.status = 'in_service' AND s.deleted_at IS NULL")
|
||||
long countInProgressByOperator(@Param("operatorId") String operatorId);
|
||||
|
||||
/** 某红娘今天名下新流转的服务数(工作台「今日」本人口径,ZC-MM-005 收口 / P1-2:按生效分配 join) */
|
||||
@Select("SELECT COUNT(DISTINCT s.id) FROM matchmaker_services s " +
|
||||
"JOIN matchmaker_assignments a ON a.user_id = s.user_id " +
|
||||
"AND a.matchmaker_operator_id = #{operatorId} " +
|
||||
"AND a.status = 'active' AND (a.expires_at IS NULL OR a.expires_at > NOW()) " +
|
||||
"AND a.deleted_at IS NULL " +
|
||||
"WHERE CAST(s.assigned_at AS DATE) = CURRENT_DATE AND s.deleted_at IS NULL")
|
||||
long countTodayByOperator(@Param("operatorId") String operatorId);
|
||||
|
||||
/**
|
||||
* 某红娘名下已完成的服务数(工作台「已完成」本人口径,ZC-MM-005 收口 / P1-2)。
|
||||
* 口径说明(与 E1「服务结束失去访问权」一致):按当前生效分配统计 ——
|
||||
* 分配 end/revoke 后,该用户的历史 completed 服务单<b>不再计入</b>本人完成数;
|
||||
* 仅当分配仍生效时,其名下 completed 单才计入。
|
||||
*/
|
||||
@Select("SELECT COUNT(DISTINCT s.id) FROM matchmaker_services s " +
|
||||
"JOIN matchmaker_assignments a ON a.user_id = s.user_id " +
|
||||
"AND a.matchmaker_operator_id = #{operatorId} " +
|
||||
"AND a.status = 'active' AND (a.expires_at IS NULL OR a.expires_at > NOW()) " +
|
||||
"AND a.deleted_at IS NULL " +
|
||||
"WHERE s.status = 'completed' AND s.deleted_at IS NULL")
|
||||
long countCompletedByOperator(@Param("operatorId") String operatorId);
|
||||
|
||||
@Select("SELECT * FROM matchmaker_services WHERE user_id = #{userId} ORDER BY created_at DESC LIMIT #{limit}")
|
||||
List<MatchmakerServiceRecord> findByUser(@Param("userId") String userId, @Param("limit") int limit);
|
||||
|
||||
/** 某红娘名下全部服务(含历史)—— 红娘工作台 */
|
||||
@Select("SELECT * FROM matchmaker_services WHERE assigned_operator_id = #{operatorId} " +
|
||||
"AND deleted_at IS NULL ORDER BY created_at DESC")
|
||||
List<MatchmakerServiceRecord> findByOperatorId(@Param("operatorId") String operatorId);
|
||||
|
||||
@Select("SELECT * FROM matchmaker_services WHERE assigned_operator_id = #{operatorId} AND status IN ('submitted','assigned','processing') ORDER BY created_at DESC")
|
||||
List<MatchmakerServiceRecord> findAssignedTo(@Param("operatorId") String operatorId);
|
||||
|
||||
/**
|
||||
* Phase 13:查该红娘名下、且服务对象为该用户的进行中服务(转介授权校验用)。
|
||||
* 转介必须挂在真实存在的服务关系上,否则等于任意红娘可代任意用户操作。
|
||||
*/
|
||||
@Select("SELECT * FROM matchmaker_services WHERE assigned_operator_id = #{operatorId} " +
|
||||
"AND user_id = #{userId} AND status IN ('assigned','in_service','waiting_user','submitted') " +
|
||||
"AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1")
|
||||
Optional<MatchmakerServiceRecord> findActiveByOperatorAndUser(@Param("operatorId") String operatorId,
|
||||
@Param("userId") String userId);
|
||||
|
||||
/**
|
||||
* 注销前检查(P16 收尾 2e):该用户仍处于非终态的红娘服务数。
|
||||
* 状态口径与 {@link #findActiveByOperatorAndUser} 一致(submitted/assigned/in_service/waiting_user)。
|
||||
* 状态口径(submitted/assigned/in_service/waiting_user)。
|
||||
* ⚠️ 勿用 {@code Constants.MATCHMAKER_STATUS_PENDING} / {@code IN_PROGRESS} ——
|
||||
* 这两个常量不在生产 chk_matchmaker_status 白名单(V009),该表永不出现这两个值。
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.danyang.match.platform.matchmaker.service;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerContactAuthorizationMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 受控联系授权判定器(ZC-MM-003 / B1 立项,架构师设计 G4)。
|
||||
*
|
||||
* <p>红娘对某用户某渠道能否披露联系方式,唯一事实源是
|
||||
* {@code matchmaker_contact_authorizations} 中「生效中的授权」
|
||||
* (status=active 且未过期,读前双态惰性收敛)。
|
||||
*
|
||||
* <p>判定无效时走 {@link DataScopeGuard#denyAsNotFound}:先落 DATA_SCOPE_DENIED 审计,
|
||||
* 再抛 404「服务不存在」(G4 防探测范式,与分配判定器同款)。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ContactAuthorizationPolicy {
|
||||
|
||||
private final MatchmakerContactAuthorizationMapper authorizationMapper;
|
||||
private final DataScopeGuard dataScopeGuard;
|
||||
|
||||
/**
|
||||
* 断言生效中的授权;无效时先审计后 404。
|
||||
*
|
||||
* @return 生效中的授权记录(永不返回 null)
|
||||
*/
|
||||
public MatchmakerContactAuthorization assertContactAllowed(String operatorId, String userId,
|
||||
String channel, String purpose) {
|
||||
Optional<MatchmakerContactAuthorization> found = canContact(operatorId, userId, channel);
|
||||
if (found.isPresent()) {
|
||||
return found.get();
|
||||
}
|
||||
dataScopeGuard.denyAsNotFound(operatorId, "matchmaker_contact_authorization", userId,
|
||||
"服务不存在", null, null);
|
||||
return null; // denyAsNotFound 必然抛出,此行不可达
|
||||
}
|
||||
|
||||
/**
|
||||
* 徽标查询(不审计):双态惰性收敛后查生效授权。
|
||||
* 供 UI「可联系」徽标等高频读场景,避免每徽标一次拒绝审计。
|
||||
*/
|
||||
public Optional<MatchmakerContactAuthorization> canContact(String operatorId, String userId,
|
||||
String channel) {
|
||||
authorizationMapper.expireOverdue();
|
||||
return authorizationMapper.findActiveByOperatorUserChannel(operatorId, userId,
|
||||
channel == null ? Constants.CONTACT_CHANNEL_PHONE : channel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package com.danyang.match.platform.matchmaker.service;
|
||||
|
||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||
import com.danyang.match.platform.audit.entity.SensitiveAccessLog;
|
||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||
import com.danyang.match.platform.audit.mapper.SensitiveAccessLogMapper;
|
||||
import com.danyang.match.platform.matchmaker.config.ContactAuthorizationConfig;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerContactAuthorizationMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
||||
import com.danyang.match.platform.user.entity.User;
|
||||
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 受控联系授权服务(ZC-MM-003 / B1 立项,架构师设计 H4)。
|
||||
*
|
||||
* <p>六操作状态机(全矩阵):
|
||||
* <pre>
|
||||
* request : 红娘(须持分配)→ pending_approval,审计含 service_assignment_id
|
||||
* approve : 审批岗(权限码动态判定 ∈ approver-authorities + 组长组织范围)
|
||||
* pending_approval → pending_consent;违规 403(无资源枚举面维持 403)
|
||||
* reject : 审批岗拒绝 pending_approval → rejected
|
||||
* consent : C 端用户本人(归属校验,独立端点、无预同意参数)
|
||||
* pending_consent → active(expires_at = consent + default-validity-days)
|
||||
* decline : C 端用户本人 pending_consent → rejected
|
||||
* revoke : 申请人或审批人,reason 必填 → revoked
|
||||
* disclose : H4 唯一披露出口 —— enabled(fail-safe) → 持分配 → 生效授权;
|
||||
* 返回 {phone, disclosedAt, authorizationId};每次落 SensitiveAccessLog;
|
||||
* phone 不落任何应用日志
|
||||
* </pre>
|
||||
*
|
||||
* <p>拒绝口径(G4 防探测):disclose 及授权有效性判定一律 404 化 deny
|
||||
* (先 DATA_SCOPE_DENIED 审计再 404「服务不存在」);approve/管理类违规维持 403。
|
||||
* 状态机非法转换一律 CONFLICT。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ContactAuthorizationService {
|
||||
|
||||
private static final String RESOURCE_TYPE = "matchmaker_contact_authorization";
|
||||
/** 披露敏感访问的数据类型(SensitiveAccessLog.data_type) */
|
||||
public static final String SENSITIVE_DATA_TYPE_PHONE_DISCLOSURE = "user_phone_disclosure";
|
||||
|
||||
private final MatchmakerContactAuthorizationMapper authorizationMapper;
|
||||
private final ServiceAssignmentPolicy serviceAssignmentPolicy;
|
||||
private final MatchmakerAssignmentService matchmakerAssignmentService;
|
||||
private final ContactAuthorizationPolicy contactAuthorizationPolicy;
|
||||
private final ContactAuthorizationConfig config;
|
||||
private final DataScopeGuard dataScopeGuard;
|
||||
private final AuditLogMapper auditLogMapper;
|
||||
private final SensitiveAccessLogMapper sensitiveAccessLogMapper;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
// ==================== ① request:红娘发起申请 ====================
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization request(String operatorId, String userId,
|
||||
String channel, String purpose) {
|
||||
if (purpose == null || purpose.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "授权目的必填");
|
||||
}
|
||||
requireValidChannel(channel);
|
||||
|
||||
// 未持分配申请 → 403 + DATA_SCOPE_DENIED 审计(申请凭据是分配而非授权本身)
|
||||
MatchmakerAssignment assignment = serviceAssignmentPolicy.assertActiveAssignment(
|
||||
operatorId, userId, RESOURCE_TYPE);
|
||||
|
||||
// 同 (operator,user,channel) 已有生效授权或待处理申请 → CONFLICT(防重复申请洪泛)
|
||||
if (authorizationMapper.findActiveByOperatorUserChannel(operatorId, userId, channel).isPresent()) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "该渠道已存在生效中的授权");
|
||||
}
|
||||
boolean hasPending = authorizationMapper.findByOperator(operatorId).stream()
|
||||
.anyMatch(a -> a.getUserId().equals(userId) && a.getChannel().equals(channel)
|
||||
&& (Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL.equals(a.getStatus())
|
||||
|| Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT.equals(a.getStatus())));
|
||||
if (hasPending) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "该渠道已存在待处理的授权申请");
|
||||
}
|
||||
|
||||
MatchmakerContactAuthorization auth = new MatchmakerContactAuthorization();
|
||||
auth.setOperatorId(operatorId);
|
||||
auth.setUserId(userId);
|
||||
auth.setChannel(channel);
|
||||
auth.setPurpose(purpose.trim());
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL);
|
||||
// pending 期 expires_at 承载同意窗口上界(consent 后重算为有效期)
|
||||
auth.setExpiresAt(Instant.now().plusSeconds(config.getConsentDeadlineHours() * 3600L));
|
||||
authorizationMapper.insert(auth);
|
||||
|
||||
log.info("受控联系授权申请: authId={}, operatorId={}, userId={}, channel={}",
|
||||
auth.getId(), operatorId, userId, channel);
|
||||
saveAudit(operatorId, Constants.CONTACT_AUDIT_ACTION_REQUEST, auth.getId(),
|
||||
assignment != null ? assignment.getId() : null,
|
||||
"matchmaker.contact.request", "channel=" + channel + ";purpose=" + auth.getPurpose());
|
||||
return auth;
|
||||
}
|
||||
|
||||
// ==================== ② approve / ③ reject:审批岗 ====================
|
||||
|
||||
/** 审批岗权限码动态判定(principal 权限 ∈ approver-authorities 配置,非 @PreAuthorize 静态)。 */
|
||||
private void assertApproverAuthority(String approverOperatorId, String authId,
|
||||
Set<String> principalPermissions) {
|
||||
Set<String> approverAuthorities = Arrays.stream(config.getApproverAuthorities().split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toSet());
|
||||
boolean authorized = principalPermissions != null
|
||||
&& principalPermissions.stream().anyMatch(approverAuthorities::contains);
|
||||
if (!authorized) {
|
||||
// 非审批岗 → 403(approve 无资源枚举面,维持 403;边界登记 T06 OQ-MATCHMAKER-009)
|
||||
dataScopeGuard.deny(approverOperatorId, RESOURCE_TYPE, authId,
|
||||
"非审批岗,禁止审批受控联系授权");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization approve(String authId, String approverOperatorId,
|
||||
Set<String> principalPermissions) {
|
||||
assertApproverAuthority(approverOperatorId, authId, principalPermissions);
|
||||
MatchmakerContactAuthorization auth = requireAuthorization(authId);
|
||||
if (!Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL.equals(auth.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"当前状态(" + auth.getStatus() + ")不允许审批");
|
||||
}
|
||||
// 组长组织范围校验(002 assertAssignScope 复用):matchmaker.assign 持有者不限组织
|
||||
boolean hasGlobalAssign = principalPermissions != null
|
||||
&& principalPermissions.contains("matchmaker.assign");
|
||||
matchmakerAssignmentService.assertTeamScope(approverOperatorId, hasGlobalAssign,
|
||||
auth.getOperatorId(), authId);
|
||||
|
||||
auth.setApprovedBy(approverOperatorId);
|
||||
auth.setApprovedAt(Instant.now());
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT);
|
||||
// 刷新同意窗口上界(给用户完整窗口)
|
||||
auth.setExpiresAt(Instant.now().plusSeconds(config.getConsentDeadlineHours() * 3600L));
|
||||
authorizationMapper.updateById(auth);
|
||||
|
||||
log.info("受控联系授权审批通过: authId={}, approver={}", authId, approverOperatorId);
|
||||
saveAudit(approverOperatorId, Constants.CONTACT_AUDIT_ACTION_APPROVE, authId,
|
||||
activeAssignmentIdOf(auth), "matchmaker.contact.approve",
|
||||
"result=approved;channel=" + auth.getChannel());
|
||||
return auth;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization reject(String authId, String approverOperatorId,
|
||||
Set<String> principalPermissions) {
|
||||
assertApproverAuthority(approverOperatorId, authId, principalPermissions);
|
||||
MatchmakerContactAuthorization auth = requireAuthorization(authId);
|
||||
if (!Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL.equals(auth.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"当前状态(" + auth.getStatus() + ")不允许拒绝");
|
||||
}
|
||||
boolean hasGlobalAssign = principalPermissions != null
|
||||
&& principalPermissions.contains("matchmaker.assign");
|
||||
matchmakerAssignmentService.assertTeamScope(approverOperatorId, hasGlobalAssign,
|
||||
auth.getOperatorId(), authId);
|
||||
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_REJECTED);
|
||||
authorizationMapper.updateById(auth);
|
||||
|
||||
log.info("受控联系授权审批拒绝: authId={}, approver={}", authId, approverOperatorId);
|
||||
saveAudit(approverOperatorId, Constants.CONTACT_AUDIT_ACTION_APPROVE, authId,
|
||||
activeAssignmentIdOf(auth), "matchmaker.contact.approve",
|
||||
"result=rejected;channel=" + auth.getChannel());
|
||||
return auth;
|
||||
}
|
||||
|
||||
// ==================== ④ consent / ⑤ decline:C 端用户本人 ====================
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization consent(String authId, String userId) {
|
||||
MatchmakerContactAuthorization auth = requireOwnedAuthorization(authId, userId);
|
||||
if (!Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT.equals(auth.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"当前状态(" + auth.getStatus() + ")不允许同意");
|
||||
}
|
||||
auth.setUserConsentedAt(Instant.now());
|
||||
auth.setExpiresAt(Instant.now().plusSeconds(config.getDefaultValidityDays() * 86400L));
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_ACTIVE);
|
||||
authorizationMapper.updateById(auth);
|
||||
|
||||
log.info("受控联系授权用户同意: authId={}, userId={}", authId, userId);
|
||||
saveAudit(userId, Constants.CONTACT_AUDIT_ACTION_CONSENT, authId,
|
||||
activeAssignmentIdOf(auth), "matchmaker.contact.consent",
|
||||
"channel=" + auth.getChannel());
|
||||
return auth;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization decline(String authId, String userId) {
|
||||
MatchmakerContactAuthorization auth = requireOwnedAuthorization(authId, userId);
|
||||
if (!Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT.equals(auth.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"当前状态(" + auth.getStatus() + ")不允许拒绝");
|
||||
}
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_REJECTED);
|
||||
authorizationMapper.updateById(auth);
|
||||
|
||||
log.info("受控联系授权用户拒绝: authId={}, userId={}", authId, userId);
|
||||
saveAudit(userId, Constants.CONTACT_AUDIT_ACTION_DECLINE, authId,
|
||||
activeAssignmentIdOf(auth), "matchmaker.contact.decline",
|
||||
"channel=" + auth.getChannel());
|
||||
return auth;
|
||||
}
|
||||
|
||||
// ==================== ⑥ revoke:申请人或审批人 ====================
|
||||
|
||||
@Transactional
|
||||
public MatchmakerContactAuthorization revoke(String authId, String operatorId, String reason) {
|
||||
if (reason == null || reason.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "撤销理由必填");
|
||||
}
|
||||
MatchmakerContactAuthorization auth = requireAuthorization(authId);
|
||||
boolean isApplicant = operatorId.equals(auth.getOperatorId());
|
||||
boolean isApprover = operatorId.equals(auth.getApprovedBy());
|
||||
if (!isApplicant && !isApprover) {
|
||||
dataScopeGuard.deny(operatorId, RESOURCE_TYPE, authId,
|
||||
"仅申请人或审批人可撤销授权");
|
||||
}
|
||||
if (!Constants.CONTACT_AUTH_STATUS_ACTIVE.equals(auth.getStatus())
|
||||
&& !Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL.equals(auth.getStatus())
|
||||
&& !Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT.equals(auth.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"当前状态(" + auth.getStatus() + ")不允许撤销");
|
||||
}
|
||||
auth.setStatus(Constants.CONTACT_AUTH_STATUS_REVOKED);
|
||||
auth.setRevokedAt(Instant.now());
|
||||
auth.setRevokedBy(operatorId);
|
||||
auth.setRevokeReason(reason.trim());
|
||||
authorizationMapper.updateById(auth);
|
||||
|
||||
log.info("受控联系授权撤销: authId={}, by={}", authId, operatorId);
|
||||
saveAudit(operatorId, Constants.CONTACT_AUDIT_ACTION_REVOKE, authId,
|
||||
activeAssignmentIdOf(auth), "matchmaker.contact.revoke",
|
||||
"reason=" + auth.getRevokeReason());
|
||||
return auth;
|
||||
}
|
||||
|
||||
// ==================== ⑦ disclose:H4 唯一披露出口 ====================
|
||||
|
||||
/**
|
||||
* 披露用户电话(H4 唯一出口)。
|
||||
* 链路:enabled fail-safe → 持分配(404 化)→ 生效授权(404 化)→ 返回三键;
|
||||
* 每次落 SensitiveAccessLog(user_phone_disclosure);<b>phone 不落任何应用日志</b>。
|
||||
*/
|
||||
@Transactional
|
||||
public Map<String, Object> disclose(String operatorId, String userId, String channel,
|
||||
String purpose) {
|
||||
// fail-safe:机制关闭(配置缺失/显式关闭)→ 404 化拒绝
|
||||
if (!config.isEnabled()) {
|
||||
dataScopeGuard.denyAsNotFound(operatorId, RESOURCE_TYPE, userId,
|
||||
"服务不存在", null, null);
|
||||
}
|
||||
if (purpose == null || purpose.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "披露目的必填");
|
||||
}
|
||||
// 持分配校验(404 化,G4)
|
||||
MatchmakerAssignment assignment = serviceAssignmentPolicy.assertActiveAssignmentOrNotFound(
|
||||
operatorId, userId, RESOURCE_TYPE, userId);
|
||||
// 生效授权校验(404 化;未同意/已拒绝/已过期/已撤销全部落同一响应)
|
||||
MatchmakerContactAuthorization auth = contactAuthorizationPolicy.assertContactAllowed(
|
||||
operatorId, userId, channel, purpose);
|
||||
|
||||
User user = userMapper.selectById(userId);
|
||||
String phone = user != null ? user.getPhone() : null;
|
||||
|
||||
SensitiveAccessLog accessLog = new SensitiveAccessLog();
|
||||
accessLog.setOperatorId(operatorId);
|
||||
accessLog.setUserId(userId);
|
||||
accessLog.setDataType(SENSITIVE_DATA_TYPE_PHONE_DISCLOSURE);
|
||||
accessLog.setReason(purpose.trim());
|
||||
accessLog.setAccessTarget(auth.getId());
|
||||
accessLog.setAccessResult(Constants.SENSITIVE_ACCESS_RESULT_SUCCESS);
|
||||
sensitiveAccessLogMapper.insert(accessLog);
|
||||
|
||||
// 审计不含 phone(afterData 只记 channel;log.info 不打 phone)
|
||||
log.info("受控联系披露: authId={}, operatorId={}, userId={}, channel={}",
|
||||
auth.getId(), operatorId, userId, auth.getChannel());
|
||||
saveAudit(operatorId, Constants.CONTACT_AUDIT_ACTION_DISCLOSE, auth.getId(),
|
||||
assignment != null ? assignment.getId() : null,
|
||||
"matchmaker.contact.disclose", "channel=" + auth.getChannel());
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("phone", phone);
|
||||
result.put("disclosedAt", Instant.now());
|
||||
result.put("authorizationId", auth.getId());
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== 查询 ====================
|
||||
|
||||
/** 红娘工作台:本人全部授权(含保留期元数据 retentionDays)。 */
|
||||
public Map<String, Object> myAuthorizations(String operatorId) {
|
||||
List<Map<String, Object>> items = authorizationMapper.findByOperator(operatorId).stream()
|
||||
.map(this::toView).collect(Collectors.toList());
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("list", items);
|
||||
result.put("retentionDays", config.getRetentionDays());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** C 端:我的授权列表 + 待同意队列。 */
|
||||
public Map<String, Object> myAuthorizationsForUser(String userId) {
|
||||
List<Map<String, Object>> items = authorizationMapper.findByUser(userId).stream()
|
||||
.map(this::toView).collect(Collectors.toList());
|
||||
List<Map<String, Object>> pendingConsent = authorizationMapper
|
||||
.findPendingConsentByUser(userId).stream()
|
||||
.map(this::toView).collect(Collectors.toList());
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("list", items);
|
||||
result.put("pendingConsent", pendingConsent);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 视图投影:不含任何联系方式字段(授权表本身无 phone 列)。 */
|
||||
private Map<String, Object> toView(MatchmakerContactAuthorization auth) {
|
||||
Map<String, Object> item = new HashMap<>();
|
||||
item.put("id", auth.getId());
|
||||
item.put("operatorId", auth.getOperatorId());
|
||||
item.put("userId", auth.getUserId());
|
||||
item.put("channel", auth.getChannel());
|
||||
item.put("purpose", auth.getPurpose());
|
||||
item.put("status", auth.getStatus());
|
||||
item.put("createdAt", auth.getCreatedAt());
|
||||
item.put("approvedAt", auth.getApprovedAt());
|
||||
item.put("userConsentedAt", auth.getUserConsentedAt());
|
||||
item.put("expiresAt", auth.getExpiresAt());
|
||||
item.put("revokeReason", auth.getRevokeReason());
|
||||
return item;
|
||||
}
|
||||
|
||||
// ==================== 内部实现 ====================
|
||||
|
||||
private void requireValidChannel(String channel) {
|
||||
boolean valid = Constants.CONTACT_CHANNEL_PHONE.equals(channel)
|
||||
|| Constants.CONTACT_CHANNEL_OFFLINE_MEETING.equals(channel)
|
||||
|| Constants.CONTACT_CHANNEL_FULL_CONTACT.equals(channel);
|
||||
if (!valid) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "不支持的授权渠道: " + channel);
|
||||
}
|
||||
}
|
||||
|
||||
private MatchmakerContactAuthorization requireAuthorization(String authId) {
|
||||
return authorizationMapper.findById(authId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "授权记录不存在"));
|
||||
}
|
||||
|
||||
/** C 端归属校验:仅授权记录的本人用户可 consent/decline,违规 403。 */
|
||||
private MatchmakerContactAuthorization requireOwnedAuthorization(String authId, String userId) {
|
||||
MatchmakerContactAuthorization auth = requireAuthorization(authId);
|
||||
if (!auth.getUserId().equals(userId)) {
|
||||
dataScopeGuard.deny(userId, RESOURCE_TYPE, authId, "仅本人可处理该授权请求");
|
||||
}
|
||||
return auth;
|
||||
}
|
||||
|
||||
/** 审计用 service_assignment_id:当前 (红娘,用户) 生效中的分配 id,无则 null。 */
|
||||
private String activeAssignmentIdOf(MatchmakerContactAuthorization auth) {
|
||||
Optional<MatchmakerAssignment> assignment =
|
||||
serviceAssignmentPolicy.findActiveAssignment(auth.getOperatorId(), auth.getUserId());
|
||||
return assignment.map(MatchmakerAssignment::getId).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 审计写入:purpose_code(matchmaker.contact.*)+ service_assignment_id +
|
||||
* request_trace_id(MDC requestId)。afterData 一律不含 phone。
|
||||
*/
|
||||
private void saveAudit(String operatorId, String action, String authId,
|
||||
String serviceAssignmentId, String purposeCode, String afterData) {
|
||||
AuditLog auditLog = new AuditLog();
|
||||
auditLog.setOperatorId(operatorId);
|
||||
auditLog.setAction(action);
|
||||
auditLog.setResourceType(RESOURCE_TYPE);
|
||||
auditLog.setResourceId(authId);
|
||||
auditLog.setAfterData(afterData);
|
||||
auditLog.setPurposeCode(purposeCode);
|
||||
auditLog.setServiceAssignmentId(serviceAssignmentId);
|
||||
auditLog.setRequestTraceId(MDC.get("requestId"));
|
||||
auditLogMapper.insert(auditLog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
package com.danyang.match.platform.matchmaker.service;
|
||||
|
||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerAssignmentMapper;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||
import com.danyang.match.platform.permission.entity.Operator;
|
||||
import com.danyang.match.platform.permission.mapper.OperatorMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 服务对象分配服务(ZC-MM-002 / A1,架构师设计 D5)。
|
||||
*
|
||||
* <p>状态机矩阵(status ∈ active/ended/revoked/transferred/expired):
|
||||
* <pre>
|
||||
* active → transferred(transfer:旧记录置 transferred + end_reason,同事务新建 active)
|
||||
* active → revoked (撤销,end_reason 必填)
|
||||
* active → ended (结束,end_reason 必填)
|
||||
* 终态(ended/revoked/transferred/expired)一律拒绝再转换 → CONFLICT
|
||||
* </pre>
|
||||
*
|
||||
* <p>权限模型(D2):
|
||||
* <ul>
|
||||
* <li>{@code matchmaker.assign}:平台授权人员,不限组织;</li>
|
||||
* <li>{@code matchmaker.team.assign}:红娘组长,团队边界 = 同 organization_id。</li>
|
||||
* </ul>
|
||||
* 组织边界规则(技术默认,治理登记后续补充):
|
||||
* <b>NULL=NULL 视为平台直属</b> —— 平台直属组长只能分配平台直属红娘;
|
||||
* 有组织组长不能分配 org=NULL 红娘;org=NULL 普通红娘只能由 matchmaker.assign 持有者分配。
|
||||
* 范围违规统一走 {@link DataScopeGuard#deny}(自动落 DATA_SCOPE_DENIED 审计,403)。
|
||||
*
|
||||
* <p>唯一性:同 user_id + primary scope 同时最多一条 active(DB 部分唯一索引兜底),
|
||||
* 业务层预检 + 捕获 DuplicateKeyException 双保险,均映射 CONFLICT。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MatchmakerAssignmentService {
|
||||
|
||||
private static final String RESOURCE_TYPE = "matchmaker_assignment";
|
||||
|
||||
private final MatchmakerAssignmentMapper assignmentMapper;
|
||||
private final MatchmakerServiceMapper serviceMapper;
|
||||
private final OperatorMapper operatorMapper;
|
||||
private final DataScopeGuard dataScopeGuard;
|
||||
private final AuditLogMapper auditLogMapper;
|
||||
/** 读路径复用判定器(含惰性过期);Policy 不反向依赖本 Service,无环。 */
|
||||
private final ServiceAssignmentPolicy serviceAssignmentPolicy;
|
||||
|
||||
/**
|
||||
* 创建分配(primary)。含可选服务单联动:serviceId 非空时同事务把服务单置为 assigned。
|
||||
*
|
||||
* @param assignerOperatorId 当前操作者(分配人)
|
||||
* @param hasGlobalAssign 操作者是否持有 matchmaker.assign(true=不限组织)
|
||||
* @param userId 被服务用户
|
||||
* @param matchmakerOperatorId 目标红娘
|
||||
* @param serviceId 关联服务单(可空)
|
||||
* @param reason 分配理由(必填)
|
||||
* @param expiresAt 有效期(可空=长期)
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerAssignment create(String assignerOperatorId, boolean hasGlobalAssign,
|
||||
String userId, String matchmakerOperatorId,
|
||||
String serviceId, String reason, Instant expiresAt) {
|
||||
requireReason(reason, "分配理由必填");
|
||||
|
||||
Operator target = requireActiveOperator(matchmakerOperatorId, "目标红娘不存在");
|
||||
// create/assign 类无资源寻址端点维持 403(ZC-MM-006 / T04 口径)
|
||||
assertAssignScope(assignerOperatorId, hasGlobalAssign, matchmakerOperatorId,
|
||||
"组长只能分配同组织的红娘(NULL=NULL 平台直属)", matchmakerOperatorId, false);
|
||||
|
||||
assignmentMapper.findActivePrimaryByUser(userId).ifPresent(existing -> {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"该用户已存在生效中的主责分配,请先转分配或撤销");
|
||||
});
|
||||
|
||||
if (serviceId != null && !serviceId.isBlank()) {
|
||||
linkServiceRow(serviceId, matchmakerOperatorId);
|
||||
}
|
||||
|
||||
MatchmakerAssignment assignment = new MatchmakerAssignment();
|
||||
assignment.setUserId(userId);
|
||||
assignment.setMatchmakerOperatorId(matchmakerOperatorId);
|
||||
assignment.setServiceId(serviceId);
|
||||
assignment.setAssignedBy(assignerOperatorId);
|
||||
assignment.setAssignmentScope(Constants.ASSIGNMENT_SCOPE_PRIMARY);
|
||||
assignment.setAssignmentReason(reason);
|
||||
assignment.setStatus(Constants.ASSIGNMENT_STATUS_ACTIVE);
|
||||
assignment.setAssignedAt(Instant.now());
|
||||
assignment.setExpiresAt(expiresAt);
|
||||
try {
|
||||
assignmentMapper.insert(assignment);
|
||||
} catch (DuplicateKeyException e) {
|
||||
// 并发竞态兜底:uq_mm_assignment_active_primary 部分唯一索引拒绝第二条 active+primary
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"该用户已存在生效中的主责分配(并发创建被唯一索引拒绝)");
|
||||
}
|
||||
|
||||
log.info("服务对象分配创建: assignmentId={}, userId={}, matchmakerOperatorId={}, by={}",
|
||||
assignment.getId(), userId, matchmakerOperatorId, assignerOperatorId);
|
||||
saveAudit(assignerOperatorId, Constants.AUDIT_ACTION_ASSIGNMENT_CREATE, assignment.getId(),
|
||||
auditSummary(matchmakerOperatorId, assignment.getAssignmentScope(), reason));
|
||||
return assignment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转分配(active → transferred + 同事务新建 active)。
|
||||
* 旧记录置 transferred + end_reason,新记录 assigned_by = 当前操作者。
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerAssignment transfer(String assignmentId, String assignerOperatorId,
|
||||
boolean hasGlobalAssign, String newMatchmakerOperatorId,
|
||||
String reason) {
|
||||
requireReason(reason, "转分配理由必填");
|
||||
|
||||
MatchmakerAssignment old = requireAssignment(assignmentId);
|
||||
assertActiveForTransition(old, "转分配");
|
||||
|
||||
// 防御纵深(QA P2-1):不仅新目标红娘要在操作者范围内,
|
||||
// 被转记录的**原持有人**也必须在范围内(与 terminate 路径同口径;
|
||||
// 否则 org=X 组长可把 org=Y 红娘持有的分配"顺手"转走)。
|
||||
// ZC-MM-006 / T04:transfer 为资源寻址写端点,范围违规 404 化(防探测)。
|
||||
assertAssignScope(assignerOperatorId, hasGlobalAssign, old.getMatchmakerOperatorId(),
|
||||
"组长只能处置同组织红娘持有的分配(NULL=NULL 平台直属)", assignmentId, true);
|
||||
|
||||
requireActiveOperator(newMatchmakerOperatorId, "目标红娘不存在");
|
||||
assertAssignScope(assignerOperatorId, hasGlobalAssign, newMatchmakerOperatorId,
|
||||
"组长只能转分配给同组织的红娘(NULL=NULL 平台直属)", assignmentId, true);
|
||||
|
||||
// 1) 旧记录置 transferred
|
||||
old.setStatus(Constants.ASSIGNMENT_STATUS_TRANSFERRED);
|
||||
old.setEndReason(reason);
|
||||
old.setEndedAt(Instant.now());
|
||||
assignmentMapper.updateById(old);
|
||||
|
||||
// 2) 同事务新建 active 分配
|
||||
MatchmakerAssignment created = new MatchmakerAssignment();
|
||||
created.setUserId(old.getUserId());
|
||||
created.setMatchmakerOperatorId(newMatchmakerOperatorId);
|
||||
created.setServiceId(old.getServiceId());
|
||||
created.setAssignedBy(assignerOperatorId);
|
||||
created.setAssignmentScope(old.getAssignmentScope());
|
||||
created.setAssignmentReason(reason);
|
||||
created.setStatus(Constants.ASSIGNMENT_STATUS_ACTIVE);
|
||||
created.setAssignedAt(Instant.now());
|
||||
created.setExpiresAt(old.getExpiresAt());
|
||||
try {
|
||||
assignmentMapper.insert(created);
|
||||
} catch (DuplicateKeyException e) {
|
||||
// 事务内旧记录已非 active,正常不应触发;仍兜底映射 CONFLICT(整个事务回滚)
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"该用户已存在生效中的主责分配(并发转分配被唯一索引拒绝)");
|
||||
}
|
||||
|
||||
log.info("服务对象转分配: oldId={}, newId={}, fromUser={}, toOperator={}, by={}",
|
||||
old.getId(), created.getId(), old.getUserId(), newMatchmakerOperatorId, assignerOperatorId);
|
||||
saveAudit(assignerOperatorId, Constants.AUDIT_ACTION_ASSIGNMENT_TRANSFER, assignmentId,
|
||||
auditSummary(newMatchmakerOperatorId, created.getAssignmentScope(), reason));
|
||||
return created;
|
||||
}
|
||||
|
||||
/** 撤销分配(active → revoked,end_reason 必填)。 */
|
||||
@Transactional
|
||||
public MatchmakerAssignment revoke(String assignmentId, String operatorId,
|
||||
boolean hasGlobalAssign, String reason) {
|
||||
return terminate(assignmentId, operatorId, hasGlobalAssign, reason,
|
||||
Constants.ASSIGNMENT_STATUS_REVOKED, Constants.AUDIT_ACTION_ASSIGNMENT_REVOKE, "撤销");
|
||||
}
|
||||
|
||||
/** 结束分配(active → ended,end_reason 必填)。 */
|
||||
@Transactional
|
||||
public MatchmakerAssignment end(String assignmentId, String operatorId,
|
||||
boolean hasGlobalAssign, String reason) {
|
||||
return terminate(assignmentId, operatorId, hasGlobalAssign, reason,
|
||||
Constants.ASSIGNMENT_STATUS_ENDED, Constants.AUDIT_ACTION_ASSIGNMENT_END, "结束");
|
||||
}
|
||||
|
||||
/** 我(当前红娘)名下生效中的服务对象分配。读前惰性过期。 */
|
||||
public List<MatchmakerAssignment> listMy(String operatorId) {
|
||||
return serviceAssignmentPolicy.findActiveByOperator(operatorId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可分配红娘列表(创建分配弹窗数据源)。
|
||||
* operators.status='active';组长按组织过滤、平台授权人员(matchmaker.assign)返回全部。
|
||||
* 返回 id/name/organizationId,<b>不含联系方式</b>(字段级隐私,ZC-MM-005 范围)。
|
||||
*/
|
||||
public List<Map<String, Object>> listAssignableMatchmakers(String assignerOperatorId,
|
||||
boolean hasGlobalAssign) {
|
||||
String assignerOrg = null;
|
||||
if (!hasGlobalAssign) {
|
||||
Operator assigner = operatorMapper.findById(assignerOperatorId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "操作者不存在"));
|
||||
assignerOrg = assigner.getOrganizationId();
|
||||
}
|
||||
String orgFilter = assignerOrg;
|
||||
return operatorMapper.selectList(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Operator>()
|
||||
.eq(Operator::getStatus, "active")
|
||||
.isNull(Operator::getDeletedAt))
|
||||
.stream()
|
||||
.filter(op -> hasGlobalAssign || Objects.equals(orgFilter, op.getOrganizationId()))
|
||||
.map(op -> {
|
||||
Map<String, Object> item = new HashMap<>();
|
||||
item.put("id", op.getId());
|
||||
item.put("name", op.getName());
|
||||
item.put("organizationId", op.getOrganizationId());
|
||||
return item;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 组长团队统计(ZC-MM-005 / E4 新增):以组长本人 organization_id 为边界
|
||||
* (NULL 组长统计平台直属,SQL 侧 IS NOT DISTINCT FROM 复用 NULL=NULL 规则)。
|
||||
* 返回纯脱敏计数,不含任何用户身份或联系方式:
|
||||
* <ul>
|
||||
* <li>activeAssignmentCount —— 组织内生效中的分配总数;</li>
|
||||
* <li>perMatchmakerCounts —— 各红娘的生效分配数(operatorId/name/activeCount);</li>
|
||||
* <li>activeMatchmakerCount —— 持有生效分配的红娘数(去重)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>字段脱敏决策(P2-4,对照《决策》§5.2 字段分类 + 功能权限矩阵)</b>:
|
||||
* perMatchmakerCounts 中的 <b>operatorName(红娘姓名)保留、不做脱敏</b>。依据:
|
||||
* <ol>
|
||||
* <li>红娘姓名属于「本人/团队范围内的工作人员标识」,<b>不是用户 PII</b>
|
||||
* (§5.2 隐私清单的禁放字段是 phone/wechat/idNumber 等用户敏感数据);</li>
|
||||
* <li>组长统计本团队工作量属其管理职责(DEC-MATCHMAKER-002 红娘组长:
|
||||
* 团队内进度与工作量管理),「查看脱敏服务统计:组长=团队范围」是既有授权口径;</li>
|
||||
* <li>组长已可经 GET /assignable-matchmakers 拿到同批红娘姓名 —— 此字段
|
||||
* 非新增泄露面,管理范围 ≠ 用户敏感数据。</li>
|
||||
* </ol>
|
||||
* 决策依据同时登记于 docs/governance/open-questions.md(OQ-MATCHMAKER-002),
|
||||
* 避免后人误判"统计含姓名=越权"。
|
||||
*/
|
||||
public Map<String, Object> teamStatistics(String leaderOperatorId) {
|
||||
Operator leader = operatorMapper.findById(leaderOperatorId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "操作者不存在"));
|
||||
String orgId = leader.getOrganizationId();
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("organizationId", orgId);
|
||||
result.put("activeAssignmentCount", assignmentMapper.countActiveByOrganization(orgId));
|
||||
result.put("perMatchmakerCounts", assignmentMapper.countActiveGroupByOperator(orgId));
|
||||
result.put("activeMatchmakerCount", assignmentMapper.countActiveOperators(orgId));
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== 内部实现 ====================
|
||||
|
||||
/** revoke / end 共用的终态迁移(仅允许 active → 终态)。 */
|
||||
private MatchmakerAssignment terminate(String assignmentId, String operatorId,
|
||||
boolean hasGlobalAssign, String reason,
|
||||
String targetStatus, String auditAction,
|
||||
String actionLabel) {
|
||||
requireReason(reason, actionLabel + "理由必填");
|
||||
|
||||
MatchmakerAssignment assignment = requireAssignment(assignmentId);
|
||||
assertActiveForTransition(assignment, actionLabel);
|
||||
|
||||
// 范围校验:操作者必须有权处置该红娘的分配(assign 不限组织 / team.assign 同组织)
|
||||
// ZC-MM-006 / T04:revoke/end 为资源寻址写端点,范围违规 404 化(防探测)
|
||||
assertAssignScope(operatorId, hasGlobalAssign, assignment.getMatchmakerOperatorId(),
|
||||
"组长只能处置同组织红娘的分配(NULL=NULL 平台直属)", assignmentId, true);
|
||||
|
||||
assignment.setStatus(targetStatus);
|
||||
assignment.setEndReason(reason);
|
||||
assignment.setEndedAt(Instant.now());
|
||||
assignmentMapper.updateById(assignment);
|
||||
|
||||
log.info("服务对象分配{}: assignmentId={}, operatorId={}, by={}",
|
||||
actionLabel, assignmentId, assignment.getMatchmakerOperatorId(), operatorId);
|
||||
saveAudit(operatorId, auditAction, assignmentId,
|
||||
auditSummary(assignment.getMatchmakerOperatorId(), assignment.getAssignmentScope(), reason));
|
||||
return assignment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 受控联系审批的组织范围校验(ZC-MM-003 / B1 立项)。
|
||||
* {@link #assertAssignScope} 的公开入口:审批岗(team.assign 组长)只能审批
|
||||
* 同组织红娘的授权申请(NULL=NULL 平台直属);matchmaker.assign 持有者不限组织。
|
||||
* 违规走 DataScopeGuard.deny(403,approve 无资源枚举面维持 403)。
|
||||
*
|
||||
* @param approverOperatorId 审批人
|
||||
* @param hasGlobalAssign 审批人是否持有 matchmaker.assign(true=不限组织)
|
||||
* @param targetOperatorId 被审批授权的红娘
|
||||
* @param auditResourceId 审计 resourceId(授权记录 id)
|
||||
*/
|
||||
public void assertTeamScope(String approverOperatorId, boolean hasGlobalAssign,
|
||||
String targetOperatorId, String auditResourceId) {
|
||||
assertAssignScope(approverOperatorId, hasGlobalAssign, targetOperatorId,
|
||||
"组长只能审批同组织红娘的授权申请(NULL=NULL 平台直属)", auditResourceId, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组织范围判定(D2):hasGlobalAssign(matchmaker.assign)不限组织;
|
||||
* team.assign 时校验操作者与目标红娘 organization_id 一致。
|
||||
* <b>NULL=NULL 视为平台直属</b>:平台直属组长只能分配平台直属红娘;
|
||||
* 有组织组长不能分配 org=NULL 红娘。违规统一先落 DATA_SCOPE_DENIED 审计。
|
||||
*
|
||||
* <p>拒绝口径(ZC-MM-006 / T04):
|
||||
* <ul>
|
||||
* <li>{@code notFoundOnDeny=false}(create/assign 类,无资源寻址)→ 403 AccessDeniedException;</li>
|
||||
* <li>{@code notFoundOnDeny=true}(transfer/revoke/end,资源寻址写端点)→ 404 化
|
||||
* {@link DataScopeGuard#denyAsNotFound}(响应与"资源不存在"逐字段一致,防探测)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
private void assertAssignScope(String assignerOperatorId, boolean hasGlobalAssign,
|
||||
String targetOperatorId, String denyMessage,
|
||||
String auditResourceId, boolean notFoundOnDeny) {
|
||||
if (hasGlobalAssign) {
|
||||
return; // 平台授权人员(matchmaker.assign),不限组织
|
||||
}
|
||||
Operator assigner = operatorMapper.findById(assignerOperatorId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "操作者不存在"));
|
||||
Operator target = operatorMapper.findById(targetOperatorId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "目标红娘不存在"));
|
||||
// Objects.equals 的 NULL=NULL → true 语义即「平台直属对平台直属」规则
|
||||
if (Objects.equals(assigner.getOrganizationId(), target.getOrganizationId())) {
|
||||
return;
|
||||
}
|
||||
if (notFoundOnDeny) {
|
||||
dataScopeGuard.denyAsNotFound(assignerOperatorId, RESOURCE_TYPE, auditResourceId,
|
||||
"服务不存在", null, null);
|
||||
} else {
|
||||
dataScopeGuard.deny(assignerOperatorId, RESOURCE_TYPE, auditResourceId, denyMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/** 服务单联动(同事务):仅 submitted 状态允许关联分配并置为 assigned。 */
|
||||
private void linkServiceRow(String serviceId, String matchmakerOperatorId) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) {
|
||||
throw new BusinessException(ApiResponseCode.NOT_FOUND, "关联服务单不存在");
|
||||
}
|
||||
if (!Constants.MATCHMAKER_STATUS_SUBMITTED.equals(service.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "服务单当前状态不允许关联分配");
|
||||
}
|
||||
service.setAssignedOperatorId(matchmakerOperatorId);
|
||||
service.setStatus(Constants.MATCHMAKER_STATUS_ASSIGNED);
|
||||
service.setAssignedAt(Instant.now());
|
||||
serviceMapper.updateById(service);
|
||||
}
|
||||
|
||||
private MatchmakerAssignment requireAssignment(String assignmentId) {
|
||||
return assignmentMapper.findById(assignmentId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "分配记录不存在"));
|
||||
}
|
||||
|
||||
private Operator requireActiveOperator(String operatorId, String notFoundMessage) {
|
||||
Operator operator = operatorMapper.findById(operatorId)
|
||||
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, notFoundMessage));
|
||||
if (!"active".equals(operator.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "目标红娘账号非 active 状态");
|
||||
}
|
||||
return operator;
|
||||
}
|
||||
|
||||
/** 终态一律拒绝再转换(D5 状态机矩阵)。 */
|
||||
private void assertActiveForTransition(MatchmakerAssignment assignment, String actionLabel) {
|
||||
if (!Constants.ASSIGNMENT_STATUS_ACTIVE.equals(assignment.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT,
|
||||
"分配已处于终态(" + assignment.getStatus() + "),不允许" + actionLabel);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireReason(String reason, String message) {
|
||||
if (reason == null || reason.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** afterData 摘要:只记 operatorId/scope/reason(D5 审计口径,不落敏感数据)。 */
|
||||
private String auditSummary(String matchmakerOperatorId, String scope, String reason) {
|
||||
String summary = "matchmakerOperatorId=" + matchmakerOperatorId
|
||||
+ ";scope=" + scope
|
||||
+ ";reason=" + (reason == null ? "" : reason);
|
||||
return summary.length() > 500 ? summary.substring(0, 500) : summary;
|
||||
}
|
||||
|
||||
private void saveAudit(String operatorId, String action, String resourceId, String afterData) {
|
||||
AuditLog auditLog = new AuditLog();
|
||||
auditLog.setOperatorId(operatorId);
|
||||
auditLog.setAction(action);
|
||||
auditLog.setResourceType(RESOURCE_TYPE);
|
||||
auditLog.setResourceId(resourceId);
|
||||
auditLog.setAfterData(afterData);
|
||||
auditLogMapper.insert(auditLog);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.danyang.match.platform.matchmaker.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||
import com.danyang.match.platform.audit.entity.SensitiveAccessLog;
|
||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||
import com.danyang.match.platform.audit.mapper.SensitiveAccessLogMapper;
|
||||
import com.danyang.match.platform.matchmaker.dto.MatchmakerRecommendationDTO;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerFollowup;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerRecommendation;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
||||
@@ -11,7 +13,9 @@ import com.danyang.match.platform.matchmaker.mapper.MatchmakerFollowupMapper;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerRecommendationMapper;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||
import com.danyang.match.platform.notification.service.NotificationService;
|
||||
import com.danyang.match.platform.profile.entity.UserPrivacySettings;
|
||||
import com.danyang.match.platform.profile.entity.UserProfile;
|
||||
import com.danyang.match.platform.profile.mapper.UserPrivacySettingsMapper;
|
||||
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -27,6 +31,31 @@ import java.util.stream.Collectors;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
|
||||
/**
|
||||
* 红娘服务服务层。
|
||||
*
|
||||
* <p>ZC-MM-002(A1)变更说明:
|
||||
* <ul>
|
||||
* <li>claimService(红娘接单)已删除(D3:不保留组长认领),服务对象归属统一由
|
||||
* matchmaker_assignments 建模;</li>
|
||||
* <li>写接口(recommend/followup/complete)归属判定切换到
|
||||
* {@link ServiceAssignmentPolicy}(D4),拒绝统一走 DataScopeGuard(审计 + 403);
|
||||
* 存量兼容:assignment 表上线前的服务单仍按 assigned_operator_id 判定(005 阶段收敛);</li>
|
||||
* <li>assignService 同事务联动「创建分配 + 服务单置 assigned」。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>ZC-MM-005(E1 双轨切纯判定器)变更说明:
|
||||
* <ul>
|
||||
* <li><b>删除 assigned_operator_id 回退分支</b>:002 的 "assignment 优先 +
|
||||
* assigned_operator_id 回退" 有真漏洞 —— 分配 revoke/end 后服务单残留
|
||||
* assigned_operator_id,回退分支会放行已失去访问权的红娘(违反 DEC-002 规则7)。
|
||||
* V053 已回填全部存量进行中服务单,数据一致性已建立;终态服务单不回填是有意设计
|
||||
* (服务结束即失去访问权)。{@link ServiceAssignmentPolicy} 成为唯一事实源;</li>
|
||||
* <li>读详情(getServiceDetail)改用 E2 防探测 404:非持有人响应与"不存在"逐字段一致,
|
||||
* 删除 viewerIsOwner 双态与"非负责人脱敏详情"整段;</li>
|
||||
* <li>行为变化:红娘读自己历史 completed 服务单详情将 404(符合 DEC-002 决策)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MatchmakerServiceService {
|
||||
@@ -37,8 +66,12 @@ public class MatchmakerServiceService {
|
||||
private final MatchmakerRecommendationMapper recommendationMapper;
|
||||
private final MatchmakerFollowupMapper followupMapper;
|
||||
private final UserProfileMapper userProfileMapper;
|
||||
private final UserPrivacySettingsMapper userPrivacySettingsMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final AuditLogMapper auditLogMapper;
|
||||
private final SensitiveAccessLogMapper sensitiveAccessLogMapper;
|
||||
private final ServiceAssignmentPolicy serviceAssignmentPolicy;
|
||||
private final MatchmakerAssignmentService matchmakerAssignmentService;
|
||||
|
||||
/**
|
||||
* 用户申请红娘服务
|
||||
@@ -82,43 +115,46 @@ public class MatchmakerServiceService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 分配服务给红娘
|
||||
* 分配服务给红娘(ZC-MM-002 / D4 联动版)。
|
||||
*
|
||||
* <p>同事务完成:① 创建 matchmaker_assignments 主责分配(含组织范围校验、
|
||||
* 唯一性约束、CREATE 审计,由 {@link MatchmakerAssignmentService#create} 承担);
|
||||
* ② 服务单 submitted → assigned、写回 assigned_operator_id。
|
||||
* 任何一步失败整体回滚。
|
||||
*
|
||||
* @param serviceId 服务单 ID
|
||||
* @param assignerOperatorId 当前操作者(分配人,principal)
|
||||
* @param targetOperatorId 目标红娘
|
||||
* @param reason 分配理由(默认文案由 Controller 传入)
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerServiceRecord assignService(String serviceId, String operatorId, String organizationId) {
|
||||
public MatchmakerServiceRecord assignService(String serviceId, String assignerOperatorId,
|
||||
String targetOperatorId, String reason) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
if (!Constants.MATCHMAKER_STATUS_SUBMITTED.equals(service.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不允许分配");
|
||||
}
|
||||
|
||||
service.setAssignedOperatorId(operatorId);
|
||||
service.setOrganizationId(organizationId);
|
||||
service.setStatus(Constants.MATCHMAKER_STATUS_ASSIGNED);
|
||||
service.setAssignedAt(Instant.now());
|
||||
serviceMapper.updateById(service);
|
||||
|
||||
log.info("分配红娘服务: serviceId={}, operatorId={}", serviceId, operatorId);
|
||||
saveAuditLog(operatorId, "MATCHMAKER_ASSIGN", "matchmaker_service", serviceId, null, null);
|
||||
return service;
|
||||
}
|
||||
|
||||
/**
|
||||
* 红娘接单
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerServiceRecord claimService(String operatorId, String serviceId) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
if (!Constants.MATCHMAKER_STATUS_ASSIGNED.equals(service.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不允许接单");
|
||||
if (targetOperatorId == null || targetOperatorId.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "目标红娘必填");
|
||||
}
|
||||
|
||||
service.setStatus(Constants.MATCHMAKER_STATUS_IN_SERVICE);
|
||||
serviceMapper.updateById(service);
|
||||
// ① 创建分配(matchmaker.assign 入口为平台授权,hasGlobalAssign=true)
|
||||
MatchmakerAssignment createdAssignment = matchmakerAssignmentService.create(assignerOperatorId, true,
|
||||
service.getUserId(), targetOperatorId, serviceId, reason, null);
|
||||
|
||||
log.info("红娘接单: operatorId={}, serviceId={}", operatorId, serviceId);
|
||||
return service;
|
||||
// ② 服务单联动(create 内已对 submitted 服务单置 assigned;此处再校验一次确保联动生效)
|
||||
MatchmakerServiceRecord after = serviceMapper.selectById(serviceId);
|
||||
if (!Constants.MATCHMAKER_STATUS_ASSIGNED.equals(after.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "服务单分配联动失败");
|
||||
}
|
||||
|
||||
log.info("分配红娘服务: serviceId={}, targetOperatorId={}, by={}",
|
||||
serviceId, targetOperatorId, assignerOperatorId);
|
||||
// ZC-MM-006 / T01:审计补 purpose_code + service_assignment_id
|
||||
saveAuditLog(assignerOperatorId, "MATCHMAKER_ASSIGN", "matchmaker_service", serviceId, null, null,
|
||||
"matchmaker.service.assign", createdAssignment.getId());
|
||||
return after;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,10 +168,10 @@ public class MatchmakerServiceService {
|
||||
/**
|
||||
* 红娘推荐候选人给用户
|
||||
*
|
||||
* Phase 13 复验修复(D3):补 assigned_operator 归属校验。
|
||||
* 此前只校验 service 存在,任何持 matchmaker.service 权限的 operator
|
||||
* 都能对**任意** serviceId 创建推荐(越权)。与
|
||||
* MatchmakerService.createRecommendation:118-121 的校验保持同一口径。
|
||||
* Phase 13 复验修复(D3):补归属校验。
|
||||
* ZC-MM-002(D4):归属判定切换到 {@link ServiceAssignmentPolicy}(matchmaker_assignments
|
||||
* 是服务对象归属的唯一事实源,无任何 assigned_operator_id 回退);拒绝统一走
|
||||
* DataScopeGuard(DATA_SCOPE_DENIED 审计 + 403),不再抛裸 IllegalStateException。
|
||||
*
|
||||
* AGENTS.md #5:红娘只创建 pending_view 推荐记录,不替用户 Like。
|
||||
*/
|
||||
@@ -145,10 +181,8 @@ public class MatchmakerServiceService {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
|
||||
// Phase 13 D3:归属校验 —— 只有该服务的负责人才能推荐
|
||||
if (!operatorId.equals(service.getAssignedOperatorId())) {
|
||||
throw new IllegalStateException("您不是此服务的负责人");
|
||||
}
|
||||
// D4:归属校验 —— 只有该服务对象的负责人(分配持有人)才能推荐
|
||||
MatchmakerAssignment assignment = assertServiceAccess(operatorId, service);
|
||||
// 不能推荐给自己(服务申请人)
|
||||
if (service.getUserId() != null && service.getUserId().equals(targetUserId)) {
|
||||
throw new IllegalArgumentException("不能推荐用户给自己");
|
||||
@@ -171,7 +205,9 @@ public class MatchmakerServiceService {
|
||||
"matchmaker_recommendation", rec.getId().toString());
|
||||
|
||||
log.info("红娘推荐: serviceId={}, operatorId={}, targetUserId={}", serviceId, operatorId, targetUserId);
|
||||
saveAuditLog(operatorId, "MATCHMAKER_RECOMMEND", "matchmaker_service", serviceId, null, null);
|
||||
// ZC-MM-006 / T01:审计补 purpose_code + service_assignment_id
|
||||
saveAuditLog(operatorId, "MATCHMAKER_RECOMMEND", "matchmaker_service", serviceId, null, null,
|
||||
"matchmaker.service.recommend", assignment != null ? assignment.getId() : null);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("recommendationId", rec.getId());
|
||||
@@ -182,11 +218,18 @@ public class MatchmakerServiceService {
|
||||
|
||||
/**
|
||||
* 红娘添加跟进记录
|
||||
*
|
||||
* ZC-MM-002(D4):补归属校验(此前无任何校验,任何持 matchmaker.service 权限的
|
||||
* operator 可对任意 serviceId 写跟进 → 越权写)。判定口径同 recommendPartner。
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerFollowup addFollowup(String serviceId, String operatorId,
|
||||
String followupType, String content,
|
||||
String nextFollowupAt) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
MatchmakerAssignment followupAssignment = assertServiceAccess(operatorId, service);
|
||||
|
||||
MatchmakerFollowup followup = new MatchmakerFollowup();
|
||||
followup.setServiceId(serviceId);
|
||||
followup.setOperatorId(operatorId);
|
||||
@@ -198,17 +241,23 @@ public class MatchmakerServiceService {
|
||||
followupMapper.insert(followup);
|
||||
|
||||
log.info("红娘跟进: serviceId={}, operatorId={}, type={}", serviceId, operatorId, followupType);
|
||||
saveAuditLog(operatorId, "MATCHMAKER_FOLLOWUP", "matchmaker_service", serviceId, null, null);
|
||||
// ZC-MM-006 / T01:审计补 purpose_code + service_assignment_id
|
||||
saveAuditLog(operatorId, "MATCHMAKER_FOLLOWUP", "matchmaker_service", serviceId, null, null,
|
||||
"matchmaker.service.followup", followupAssignment != null ? followupAssignment.getId() : null);
|
||||
return followup;
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成服务
|
||||
*
|
||||
* ZC-MM-002(D4):补归属校验(判定口径同 recommendPartner);
|
||||
* operatorId 由 Controller 传入 principal,不信任请求参数。
|
||||
*/
|
||||
@Transactional
|
||||
public MatchmakerServiceRecord completeService(String serviceId) {
|
||||
public MatchmakerServiceRecord completeService(String serviceId, String operatorId) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
MatchmakerAssignment completeAssignment = assertServiceAccess(operatorId, service);
|
||||
if (!Constants.MATCHMAKER_STATUS_IN_SERVICE.equals(service.getStatus()) &&
|
||||
!Constants.MATCHMAKER_STATUS_WAITING_USER.equals(service.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不能完成");
|
||||
@@ -219,7 +268,9 @@ public class MatchmakerServiceService {
|
||||
serviceMapper.updateById(service);
|
||||
|
||||
log.info("红娘服务完成: serviceId={}", serviceId);
|
||||
saveAuditLog(null, "MATCHMAKER_COMPLETE", "matchmaker_service", serviceId, null, null);
|
||||
// ZC-MM-006 / T01:审计补 purpose_code + service_assignment_id
|
||||
saveAuditLog(null, "MATCHMAKER_COMPLETE", "matchmaker_service", serviceId, null, null,
|
||||
"matchmaker.service.complete", completeAssignment != null ? completeAssignment.getId() : null);
|
||||
return service;
|
||||
}
|
||||
|
||||
@@ -257,6 +308,24 @@ public class MatchmakerServiceService {
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取红娘工作台数据。
|
||||
*
|
||||
* ZC-MM-002(D4):today / completed 改为本人口径(该红娘名下的服务),
|
||||
* pendingCount 保留全局口径(待分配队列是分配权持有者的全局视图);
|
||||
* inProgress 统计的状态口径由错误的 'processing' 修正为 'in_service'
|
||||
* ('processing' 不在 V009 chk_matchmaker_status 白名单,恒为 0)。
|
||||
*
|
||||
* <p>ZC-MM-005 收口(P1-2):inProgress / today / completed 三项计数统一切换为
|
||||
* <b>matchmaker_assignments 生效中分配</b>口径(SQL 侧 join assignments,见
|
||||
* MatchmakerServiceMapper 计数查询)。口径说明:
|
||||
* <ul>
|
||||
* <li>三项均只统计「本人当前生效分配对象名下」的服务单;</li>
|
||||
* <li>分配 end / revoke 后(含他人接手后原红娘),该用户的服务单
|
||||
* <b>不再计入</b>原红娘的 dashboard 计数(DEC-002 规则7:服务结束失去访问权);</li>
|
||||
* <li>completed 计数同理:历史 completed 单仅在分配仍生效时计入本人。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public Map<String, Object> getDashboard(String operatorId) {
|
||||
long pendingCount = serviceMapper.countSubmitted();
|
||||
long inProgressCount = serviceMapper.countInProgressByOperator(operatorId);
|
||||
@@ -264,57 +333,69 @@ public class MatchmakerServiceService {
|
||||
Map<String, Object> dashboard = new HashMap<>();
|
||||
dashboard.put("pendingCount", pendingCount);
|
||||
dashboard.put("inProgressCount", inProgressCount);
|
||||
long todayCount = serviceMapper.selectCount(
|
||||
new LambdaQueryWrapper<MatchmakerServiceRecord>()
|
||||
.eq(MatchmakerServiceRecord::getStatus, "submitted"));
|
||||
// 本人口径:今天新流转到该红娘名下(按 assigned_at)的服务数
|
||||
long todayCount = serviceMapper.countTodayByOperator(operatorId);
|
||||
dashboard.put("todayCount", todayCount);
|
||||
long completedCount = serviceMapper.selectCount(
|
||||
new LambdaQueryWrapper<MatchmakerServiceRecord>()
|
||||
.eq(MatchmakerServiceRecord::getStatus, "completed"));
|
||||
// 本人口径:该红娘名下已完成的服务数
|
||||
long completedCount = serviceMapper.countCompletedByOperator(operatorId);
|
||||
dashboard.put("completedCount", completedCount);
|
||||
return dashboard;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取我的服务列表(红娘工作台)
|
||||
*/
|
||||
public List<MatchmakerServiceRecord> getOperatorServices(String operatorId) {
|
||||
return serviceMapper.findByOperatorId(operatorId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务详情
|
||||
* 获取服务详情(ZC-MM-005 / E1+E2 重构)。
|
||||
*
|
||||
* Phase 13 复验修复(D4):改为按调用者授权范围返回。
|
||||
* 此前无任何归属校验,任何持 matchmaker.view 的 operator 都能读取
|
||||
* **任意** serviceId 的详情,其中包含该用户的完整资料
|
||||
* (displayName/gender/age/regionName/education/occupation/maritalStatus)→ 越权读。
|
||||
* <p>此前(002 双轨)语义:负责人 → 完整详情;其他 operator → 脱敏详情(含 viewerIsOwner
|
||||
* 双态)。该设计有两个问题:① assigned_operator_id 回退分支在分配 revoke/end 后仍放行
|
||||
* (服务单残留该列);② 脱敏详情响应可被用于按 serviceId 枚举探测资源存在性。
|
||||
*
|
||||
* 现语义:
|
||||
* - 服务负责人(assigned_operator_id)→ 返回完整详情(含 userProfile + followups)
|
||||
* - 其他 operator(如仅需了解队列的中台人员)→ 返回脱敏详情
|
||||
* (不含 userProfile;followups 正文也不返回,仅给条数)
|
||||
* <p>现语义(判定器唯一事实源,无回退):
|
||||
* <ul>
|
||||
* <li>查无此 serviceId → 抛 BusinessException(NOT_FOUND, "服务不存在");</li>
|
||||
* <li>非持有人(无生效中的分配)→ {@link ServiceAssignmentPolicy}
|
||||
* #assertActiveAssignmentOrNotFound:先落 DATA_SCOPE_DENIED 审计,
|
||||
* 再抛与"查无"完全相同的 NOT_FOUND 异常 —— 两种失败响应逐字段一致,防探测;</li>
|
||||
* <li>持有人 → 完整详情(申请人 userId / 诉求描述 / 白名单 userProfile / 跟进正文 /
|
||||
* 推荐列表),不再有 viewerIsOwner 双态字段。</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param serviceId 服务 ID
|
||||
* <p>行为变化:红娘读自己历史 completed 服务单详情将 404(分配已终态,符合 DEC-002)。
|
||||
*
|
||||
* @param serviceId 服务 ID
|
||||
* @param requesterId 调用者 operator ID
|
||||
*/
|
||||
public Map<String, Object> getServiceDetail(String serviceId, String requesterId) {
|
||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||
if (service == null) return null;
|
||||
if (service == null) {
|
||||
// 与"非持有人"路径抛出完全相同的异常 → 响应体逐字段一致(防探测,E2)
|
||||
throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
}
|
||||
|
||||
boolean isOwner = requesterId != null && requesterId.equals(service.getAssignedOperatorId());
|
||||
// E1:判定器唯一事实源;E2:非持有人防探测 404(先审计后 NOT_FOUND)
|
||||
serviceAssignmentPolicy.assertActiveAssignmentOrNotFound(
|
||||
requesterId, service.getUserId(), "matchmaker_service", serviceId);
|
||||
|
||||
// ZC-MM-006 / T03:持有人读取服务对象详情 = 敏感数据访问,必须落 sensitive_access_logs
|
||||
// (AGENTS.md #8:查看动作本身必须可溯源)。拒绝路径走判定器的 DATA_SCOPE_DENIED 审计,
|
||||
// 双记录互斥 —— 非持有人不会走到本行(不重复写 SensitiveAccessLog)。
|
||||
SensitiveAccessLog accessLog = new SensitiveAccessLog();
|
||||
accessLog.setOperatorId(requesterId);
|
||||
accessLog.setUserId(service.getUserId());
|
||||
accessLog.setDataType(Constants.SENSITIVE_DATA_TYPE_MATCHMAKER_SERVICE_DETAIL);
|
||||
accessLog.setReason(Constants.SENSITIVE_ACCESS_REASON_MATCHMAKER_DETAIL);
|
||||
accessLog.setAccessTarget(serviceId);
|
||||
accessLog.setAccessResult(Constants.SENSITIVE_ACCESS_RESULT_SUCCESS);
|
||||
sensitiveAccessLogMapper.insert(accessLog);
|
||||
|
||||
Map<String, Object> detail = new HashMap<>();
|
||||
detail.put("serviceId", service.getId());
|
||||
detail.put("serviceType", service.getServiceType());
|
||||
detail.put("status", service.getStatus());
|
||||
detail.put("assignedOperatorId", service.getAssignedOperatorId());
|
||||
detail.put("createdAt", service.getCreatedAt());
|
||||
detail.put("assignedAt", service.getAssignedAt());
|
||||
detail.put("completedAt", service.getCompletedAt());
|
||||
detail.put("viewerIsOwner", isOwner);
|
||||
|
||||
// 加载推荐列表(推荐是服务进展的必要摘要,两者都可见)
|
||||
// 推荐列表(服务进展摘要)
|
||||
List<MatchmakerRecommendation> recs = recommendationMapper.findByService(serviceId);
|
||||
detail.put("recommendations", recs.stream().map(r -> {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
@@ -326,35 +407,78 @@ public class MatchmakerServiceService {
|
||||
return map;
|
||||
}).collect(Collectors.toList()));
|
||||
|
||||
if (isOwner) {
|
||||
// 仅服务负责人可见:申请人 userId / 诉求描述 / 用户资料 / 跟进正文
|
||||
detail.put("userId", service.getUserId());
|
||||
detail.put("description", service.getDescription());
|
||||
userProfileMapper.findByUserId(service.getUserId()).ifPresent(profile -> {
|
||||
Map<String, Object> userProfile = new HashMap<>();
|
||||
userProfile.put("displayName", profile.getDisplayName());
|
||||
userProfile.put("gender", profile.getGender());
|
||||
userProfile.put("age", calculateAge(profile.getBirthDate()));
|
||||
userProfile.put("regionName", profile.getRegionName());
|
||||
userProfile.put("educationCode", profile.getEducationCode());
|
||||
userProfile.put("occupationCode", profile.getOccupationCode());
|
||||
userProfile.put("maritalStatus", profile.getMaritalStatus());
|
||||
detail.put("userProfile", userProfile);
|
||||
});
|
||||
detail.put("followups", followupMapper.findByServiceId(serviceId));
|
||||
} else {
|
||||
// 非负责人:只给跟进条数作为进度摘要,不返回正文
|
||||
detail.put("followupCount", followupMapper.findByServiceId(serviceId).size());
|
||||
}
|
||||
// 仅持有人可见:申请人 userId / 诉求描述 / 白名单用户资料 / 跟进正文
|
||||
detail.put("userId", service.getUserId());
|
||||
detail.put("description", service.getDescription());
|
||||
UserPrivacySettings privacy = userPrivacySettingsMapper.findByUserId(service.getUserId())
|
||||
.orElse(null);
|
||||
userProfileMapper.findByUserId(service.getUserId()).ifPresent(profile ->
|
||||
detail.put("userProfile", assembleMatchmakerUserProfile(profile, privacy)));
|
||||
detail.put("followups", followupMapper.findByServiceId(serviceId));
|
||||
|
||||
return detail;
|
||||
}
|
||||
|
||||
/**
|
||||
* 红娘侧用户资料装配(ZC-MM-005 / E3 字段白名单显式化)。
|
||||
*
|
||||
* <p>逐字段对照《安全、隐私、合规与风控体系设计》§5.2 字段级隐私清单:
|
||||
* <ul>
|
||||
* <li>displayName —— 基础展示字段,允许</li>
|
||||
* <li>gender —— 基础展示字段,允许</li>
|
||||
* <li>age —— 由 birthDate 计算的派生值(<b>不输出原始 birthDate</b>)</li>
|
||||
* <li>regionName —— 地区展示名(非精确坐标),允许</li>
|
||||
* <li>educationCode —— 枚举码,允许</li>
|
||||
* <li>occupationCode —— 枚举码,<b>受隐私开关 showOccupation 控制</b>:
|
||||
* 用户明确关闭(false)时不输出;隐私记录缺失或开关未设置(null)按缺省放行</li>
|
||||
* <li>maritalStatus —— 枚举码,允许</li>
|
||||
* </ul>
|
||||
* §5.2 禁放字段(phone/mobile/wechat/idNumber/birthDate/address/id_card 等)
|
||||
* 一律不进入装配;守卫见 MatchmakerFieldPrivacyGuardTest(源码级白名单扫描)。
|
||||
*
|
||||
* @param profile 用户资料(可空字段自然输出 null,由前端按缺失处理)
|
||||
* @param privacy 用户隐私设置;null 表示用户未设置过(缺省=全放行)
|
||||
*/
|
||||
private Map<String, Object> assembleMatchmakerUserProfile(UserProfile profile,
|
||||
UserPrivacySettings privacy) {
|
||||
// 缺省=全放行:仅在用户显式关闭(showOccupation == false)时隐藏职业
|
||||
boolean showOccupation = privacy == null || !Boolean.FALSE.equals(privacy.getShowOccupation());
|
||||
Map<String, Object> userProfile = new HashMap<>();
|
||||
userProfile.put("displayName", profile.getDisplayName());
|
||||
userProfile.put("gender", profile.getGender());
|
||||
// 派生年龄:不输出原始 birthDate(§5.2 禁放)
|
||||
userProfile.put("age", calculateAge(profile.getBirthDate()));
|
||||
userProfile.put("regionName", profile.getRegionName());
|
||||
userProfile.put("educationCode", profile.getEducationCode());
|
||||
if (showOccupation) {
|
||||
userProfile.put("occupationCode", profile.getOccupationCode());
|
||||
}
|
||||
userProfile.put("maritalStatus", profile.getMaritalStatus());
|
||||
return userProfile;
|
||||
}
|
||||
|
||||
private int calculateAge(java.time.LocalDate birthDate) {
|
||||
if (birthDate == null) return 0;
|
||||
return java.time.Period.between(birthDate, java.time.LocalDate.now()).getYears();
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务归属校验(ZC-MM-005 / E1 纯判定器版;ZC-MM-006 / T04 写接口 404 化)。
|
||||
*
|
||||
* <p><b>无任何回退</b>:matchmaker_assignments 是服务对象归属的唯一事实源。
|
||||
* 002 的 assigned_operator_id 回退分支已删除 —— 分配 revoke/end 后服务单残留的
|
||||
* assigned_operator_id 不再构成访问凭据(DEC-002 规则7:撤销即失权)。
|
||||
* 写接口(recommend/followup/complete,资源寻址端点)口径:判定无效 →
|
||||
* {@link ServiceAssignmentPolicy#assertActiveAssignmentOrNotFound}:
|
||||
* 先落 DATA_SCOPE_DENIED 审计,再抛 404「服务不存在」—— 与读详情口径逐字段一致,防探测。
|
||||
*
|
||||
* @return 生效中的分配记录(供审计写入 service_assignment_id;deny 必然抛出,不会返回 null)
|
||||
*/
|
||||
private MatchmakerAssignment assertServiceAccess(String operatorId, MatchmakerServiceRecord service) {
|
||||
return serviceAssignmentPolicy.assertActiveAssignmentOrNotFound(operatorId, service.getUserId(),
|
||||
"matchmaker_service", service.getId());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取红娘为该用户推荐的人员列表
|
||||
@@ -394,11 +518,25 @@ public class MatchmakerServiceService {
|
||||
|
||||
private void saveAuditLog(String operatorId, String action, String resourceType,
|
||||
String resourceId, String beforeData, String afterData) {
|
||||
// ZC-MM-006 / T01 兼容性:缺省调用(不带 purposeCode/assignmentId)仍可写(负向用例覆盖)
|
||||
saveAuditLog(operatorId, action, resourceType, resourceId, beforeData, afterData, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZC-MM-006 / T01 扩展版审计写入:附加 purpose_code 与 service_assignment_id。
|
||||
*/
|
||||
private void saveAuditLog(String operatorId, String action, String resourceType,
|
||||
String resourceId, String beforeData, String afterData,
|
||||
String purposeCode, String serviceAssignmentId) {
|
||||
AuditLog auditLog = new AuditLog();
|
||||
auditLog.setOperatorId(operatorId);
|
||||
auditLog.setAction(action);
|
||||
auditLog.setResourceType(resourceType);
|
||||
auditLog.setResourceId(resourceId);
|
||||
auditLog.setBeforeData(beforeData);
|
||||
auditLog.setAfterData(afterData);
|
||||
auditLog.setPurposeCode(purposeCode);
|
||||
auditLog.setServiceAssignmentId(serviceAssignmentId);
|
||||
auditLogMapper.insert(auditLog);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.danyang.match.platform.matchmaker.service;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerAssignmentMapper;
|
||||
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 服务对象分配判定器(ZC-MM-002 / A1,架构师设计 D6;ZC-MM-005 / E1-E2 增强)。
|
||||
*
|
||||
* <p>红娘对某个用户能否读/写,唯一事实源是 matchmaker_assignments 里
|
||||
* 「生效中的分配」(active 且未过有效期)。所有读路径前先 {@link #expireOverdue}
|
||||
* 惰性过期(无定时任务,D5 决策),保证过期分配立即失效。
|
||||
*
|
||||
* <p>判定无效时的两种处置:
|
||||
* <ul>
|
||||
* <li>{@link #assertActiveAssignment}:写接口口径 —— 落 DATA_SCOPE_DENIED 审计 +
|
||||
* 抛 AccessDeniedException(403);</li>
|
||||
* <li>{@link #assertActiveAssignmentOrNotFound}(ZC-MM-005 / E2):读详情口径 ——
|
||||
* 先落 DATA_SCOPE_DENIED 审计(语义上仍是 403 越权),再抛
|
||||
* BusinessException(NOT_FOUND)(响应 404,与"资源不存在"逐字段一致),
|
||||
* 防止枚举 serviceId 探测资源存在性。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ServiceAssignmentPolicy {
|
||||
|
||||
private final MatchmakerAssignmentMapper assignmentMapper;
|
||||
private final DataScopeGuard dataScopeGuard;
|
||||
|
||||
/**
|
||||
* 惰性过期:把 expires_at 已届满的 active 分配置为 expired 并落库。
|
||||
* 读路径入口统一调用;无定时任务(D5 决策)。
|
||||
*/
|
||||
public int expireOverdue() {
|
||||
return assignmentMapper.expireOverdue();
|
||||
}
|
||||
|
||||
/** 查询某红娘对某用户的生效中分配;不存在返回 empty。 */
|
||||
public Optional<MatchmakerAssignment> findActiveAssignment(String operatorId, String userId) {
|
||||
expireOverdue();
|
||||
return assignmentMapper.findActiveByOperatorAndUser(operatorId, userId);
|
||||
}
|
||||
|
||||
/** 某红娘当前是否可访问某用户(存在生效中的分配)。 */
|
||||
public boolean canAccessUser(String operatorId, String userId) {
|
||||
return findActiveAssignment(operatorId, userId).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* 断言某红娘对某用户持有生效中的分配;无效时:
|
||||
* 落 DATA_SCOPE_DENIED 审计 + 抛 AccessDeniedException(403)。
|
||||
*
|
||||
* @param resourceType 审计 resourceType(如 matchmaker_service / matchmaker_user)
|
||||
* @return 生效中的分配记录(永不返回 null)
|
||||
*/
|
||||
public MatchmakerAssignment assertActiveAssignment(String operatorId, String userId,
|
||||
String resourceType) {
|
||||
Optional<MatchmakerAssignment> found = findActiveAssignment(operatorId, userId);
|
||||
if (found.isPresent()) {
|
||||
return found.get();
|
||||
}
|
||||
dataScopeGuard.deny(operatorId, resourceType, userId,
|
||||
"未持有该服务对象的分配关系,禁止访问");
|
||||
return null; // deny 必然抛出,此行不可达
|
||||
}
|
||||
|
||||
/**
|
||||
* 读详情口径的断言(ZC-MM-005 / E2 防探测 404)。
|
||||
*
|
||||
* <p>无效时先写 DATA_SCOPE_DENIED 审计(字段口径与 {@link DataScopeGuard#deny} 对齐,
|
||||
* 语义上这是一次越权尝试),再抛 {@code BusinessException(NOT_FOUND, "服务不存在")}。
|
||||
* 全局异常处理器将其映射为 404 响应体 {@code {success:false, code:NOT_FOUND,
|
||||
* message:"服务不存在"}} —— 与查询一个真正不存在的 serviceId 的响应逐字段一致,
|
||||
* 调用方无法区分"无权"与"不存在",杜绝按 serviceId 枚举探测。
|
||||
*
|
||||
* <p>适用面(ZC-MM-006 / T04 扩展):读详情 + <b>带资源寻址的写端点</b>
|
||||
* (recommend / followup / complete / 转介)范围校验失败统一 404 化(防探测);
|
||||
* create / assign 类无资源寻址端点维持 {@link #assertActiveAssignment} 的 403 口径。
|
||||
*
|
||||
* @param resourceType 审计 resourceType(如 matchmaker_service)
|
||||
* @param resourceId 审计 resourceId(被探测的 serviceId)
|
||||
* @return 生效中的分配记录(永不返回 null)
|
||||
*/
|
||||
public MatchmakerAssignment assertActiveAssignmentOrNotFound(String operatorId, String userId,
|
||||
String resourceType,
|
||||
String resourceId) {
|
||||
Optional<MatchmakerAssignment> found = findActiveAssignment(operatorId, userId);
|
||||
if (found.isPresent()) {
|
||||
return found.get();
|
||||
}
|
||||
// ZC-MM-006 / T04:防探测 404 化 deny —— 审计与 404 抛出统一收敛到
|
||||
// {@link DataScopeGuard#denyAsNotFound}(审计含权限快照 + 请求追踪 ID)。
|
||||
// 该方法同时服务读详情与(本阶段起)写接口范围校验,拒绝口径全程一致。
|
||||
dataScopeGuard.denyAsNotFound(operatorId, resourceType, resourceId, "服务不存在", null, null);
|
||||
return null; // denyAsNotFound 必然抛出,此行不可达
|
||||
}
|
||||
|
||||
/** 某红娘名下全部生效中的分配(GET /my 口径),读前惰性过期。 */
|
||||
public List<MatchmakerAssignment> findActiveByOperator(String operatorId) {
|
||||
expireOverdue();
|
||||
return assignmentMapper.findActiveByOperator(operatorId);
|
||||
}
|
||||
}
|
||||
@@ -232,6 +232,25 @@ public class MeController {
|
||||
return ApiResponse.ok(photoService.getUploadToken(principal.id(), photoType));
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认直传照片落库(REST §29 补)。
|
||||
* 客户端先 {@code POST /me/photos/upload-token} 拿预签名 URL 直传对象存储,
|
||||
* 上传成功后再调本端点把 fileKey 落成 user_photos 记录;否则照片不展示、签名访问也过不了归属校验。
|
||||
* POST /api/v1/me/photos/confirm
|
||||
*/
|
||||
@PostMapping("/photos/confirm")
|
||||
public ApiResponse<Map<String, Object>> confirmPhoto(
|
||||
@AuthenticationPrincipal UserPrincipal principal,
|
||||
@RequestBody Map<String, String> body) {
|
||||
String fileKey = body.get("fileKey");
|
||||
String photoType = body.getOrDefault("photoType", "lifestyle");
|
||||
UserPhoto photo = photoService.confirmDirectUpload(principal.id(), fileKey, photoType);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("photoId", photo.getId());
|
||||
result.put("photoType", photo.getPhotoType());
|
||||
return ApiResponse.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除本人照片(REST §32)。
|
||||
* DELETE /api/v1/me/photos/{photoId}
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
/**
|
||||
* Operator 管理服务
|
||||
@@ -85,7 +86,7 @@ public class OperatorService {
|
||||
@Transactional
|
||||
public void disableOperator(String operatorId) {
|
||||
Operator operator = operatorMapper.findById(operatorId)
|
||||
.orElseThrow(() -> new RuntimeException("Operator 不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "Operator 不存在"));
|
||||
|
||||
operator.setStatus(Constants.ACCOUNT_STATUS_SUSPENDED);
|
||||
operator.setUpdatedAt(Instant.now());
|
||||
@@ -101,7 +102,7 @@ public class OperatorService {
|
||||
@Transactional
|
||||
public void enableOperator(String operatorId) {
|
||||
Operator operator = operatorMapper.findById(operatorId)
|
||||
.orElseThrow(() -> new RuntimeException("Operator 不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "Operator 不存在"));
|
||||
|
||||
operator.setStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||
operator.setUpdatedAt(Instant.now());
|
||||
|
||||
@@ -187,6 +187,33 @@ public class PhotoService {
|
||||
return photo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认直传照片落库(客户端直传对象存储成功后调用)。
|
||||
*
|
||||
* <p>直传路径({@code /me/photos/upload-token} 签发预签名 PUT URL)对象先进入私有桶,
|
||||
* 但此前没有任何端点把 {@code fileKey} 写成 {@code user_photos} 记录,导致「传了白传」:
|
||||
* 列表不展示、签名访问的归属校验也过不了。本方法补齐落库,并设两道护栏:
|
||||
* <ol>
|
||||
* <li>归属校验:{@code fileKey} 必须以 {@code photos/{userId}/} 开头(由本用户直传凭证生成),
|
||||
* 禁止客户端传入任意 fileKey 把别人的对象据为己有或写入非法 key;</li>
|
||||
* <li>存在性校验:对象必须已存在于私有桶(客户端确实完成了 PUT),否则拒绝落库,
|
||||
* 避免只拿了凭证却没上传成功就生成孤儿记录。</li>
|
||||
* </ol>
|
||||
*/
|
||||
@Transactional
|
||||
public UserPhoto confirmDirectUpload(String userId, String fileKey, String photoType) {
|
||||
if (fileKey == null || !fileKey.startsWith("photos/" + userId + "/")) {
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "非法的文件标识");
|
||||
}
|
||||
if (!amazonS3.doesObjectExist(privateBucket, fileKey)) {
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "文件尚未上传完成");
|
||||
}
|
||||
// countActiveProfilePhotos 返回 long,落库排序用 int(与 savePhoto 形参一致);
|
||||
// 照片数量不会触及 int 上界,此处安全窄化。
|
||||
int sortOrder = (int) (photoMapper.countActiveProfilePhotos(userId) + 1);
|
||||
return savePhoto(userId, fileKey, photoType, sortOrder);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理后端直传:接收文件 → 上传到 MinIO → 保存记录
|
||||
*/
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.danyang.match.platform.profile.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.danyang.match.platform.profile.entity.UserPreference;
|
||||
import com.danyang.match.platform.profile.mapper.UserPreferenceMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -25,37 +27,55 @@ public class UserPreferenceService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存择偶条件
|
||||
* 保存择偶条件(无则插入、有则更新)。
|
||||
*
|
||||
* <p>2026-09-23 UAT 走查修复:此前无论记录是否存在都调 {@code insert()},
|
||||
* 再次保存即触发主键冲突(实测 {@code PUT /me/preferences} → 409
|
||||
* {@code duplicate key value violates unique constraint "user_preferences_pkey"})。
|
||||
*
|
||||
* <p><b>为何不用 {@code updateById}</b>:{@code UserPreference} 继承 {@code BaseEntity},
|
||||
* 其 {@code @TableId} 为 {@code id},而库中真正的主键是 {@code user_id}
|
||||
* ({@code id} 是 V037 后补的可空列 + 唯一索引,V037 之后新插入的行 {@code id} 为 NULL)。
|
||||
* 用 {@code updateById} 会退化成 {@code WHERE id IS NULL} 静默不更新,
|
||||
* 因此按 {@code user_id} 定位。
|
||||
*/
|
||||
@Transactional
|
||||
public UserPreference savePreference(String userId, Map<String, Object> data) {
|
||||
UserPreference pref = userPreferenceMapper.findByUserId(userId)
|
||||
.orElseGet(() -> {
|
||||
UserPreference p = new UserPreference();
|
||||
p.setUserId(userId);
|
||||
return p;
|
||||
});
|
||||
UserPreference pref = userPreferenceMapper.findByUserId(userId).orElse(null);
|
||||
boolean exists = pref != null;
|
||||
if (!exists) {
|
||||
pref = new UserPreference();
|
||||
pref.setUserId(userId);
|
||||
}
|
||||
|
||||
if (data.containsKey("minAge")) pref.setMinAge((Integer) data.get("minAge"));
|
||||
if (data.containsKey("maxAge")) pref.setMaxAge((Integer) data.get("maxAge"));
|
||||
if (data.containsKey("agePriority")) pref.setAgePriority((String) data.get("agePriority"));
|
||||
if (data.containsKey("minHeightCm")) pref.setMinHeightCm((Integer) data.get("minHeightCm"));
|
||||
if (data.containsKey("maxHeightCm")) pref.setMaxHeightCm((Integer) data.get("maxHeightCm"));
|
||||
if (data.containsKey("heightPriority")) pref.setHeightPriority((String) data.get("heightPriority"));
|
||||
if (data.containsKey("regionScope")) pref.setRegionScope(toJsonNode(data.get("regionScope")));
|
||||
if (data.containsKey("regionPriority")) pref.setRegionPriority((String) data.get("regionPriority"));
|
||||
if (data.containsKey("maritalStatuses")) pref.setMaritalStatuses(toJsonNode(data.get("maritalStatuses")));
|
||||
if (data.containsKey("maritalPriority")) pref.setMaritalPriority((String) data.get("maritalPriority"));
|
||||
if (data.containsKey("minEducationCode")) pref.setMinEducationCode((String) data.get("minEducationCode"));
|
||||
if (data.containsKey("educationPriority")) pref.setEducationPriority((String) data.get("educationPriority"));
|
||||
if (data.containsKey("childrenAcceptance")) pref.setChildrenAcceptance((String) data.get("childrenAcceptance"));
|
||||
if (data.containsKey("childrenPriority")) pref.setChildrenPriority((String) data.get("childrenPriority"));
|
||||
if (data.containsKey("smokingPreference")) pref.setSmokingPreference((String) data.get("smokingPreference"));
|
||||
if (data.containsKey("drinkingPreference")) pref.setDrinkingPreference((String) data.get("drinkingPreference"));
|
||||
if (data.containsKey("settlementPreference")) pref.setSettlementPreference((String) data.get("settlementPreference"));
|
||||
if (data.containsKey("marriagePlanPreference")) pref.setMarriagePlanPreference((String) data.get("marriagePlanPreference"));
|
||||
if (data != null) {
|
||||
if (data.containsKey("minAge")) pref.setMinAge((Integer) data.get("minAge"));
|
||||
if (data.containsKey("maxAge")) pref.setMaxAge((Integer) data.get("maxAge"));
|
||||
if (data.containsKey("agePriority")) pref.setAgePriority((String) data.get("agePriority"));
|
||||
if (data.containsKey("minHeightCm")) pref.setMinHeightCm((Integer) data.get("minHeightCm"));
|
||||
if (data.containsKey("maxHeightCm")) pref.setMaxHeightCm((Integer) data.get("maxHeightCm"));
|
||||
if (data.containsKey("heightPriority")) pref.setHeightPriority((String) data.get("heightPriority"));
|
||||
if (data.containsKey("regionScope")) pref.setRegionScope(toJsonNode(data.get("regionScope")));
|
||||
if (data.containsKey("regionPriority")) pref.setRegionPriority((String) data.get("regionPriority"));
|
||||
if (data.containsKey("maritalStatuses")) pref.setMaritalStatuses(toJsonNode(data.get("maritalStatuses")));
|
||||
if (data.containsKey("maritalPriority")) pref.setMaritalPriority((String) data.get("maritalPriority"));
|
||||
if (data.containsKey("minEducationCode")) pref.setMinEducationCode((String) data.get("minEducationCode"));
|
||||
if (data.containsKey("educationPriority")) pref.setEducationPriority((String) data.get("educationPriority"));
|
||||
if (data.containsKey("childrenAcceptance")) pref.setChildrenAcceptance((String) data.get("childrenAcceptance"));
|
||||
if (data.containsKey("childrenPriority")) pref.setChildrenPriority((String) data.get("childrenPriority"));
|
||||
if (data.containsKey("smokingPreference")) pref.setSmokingPreference((String) data.get("smokingPreference"));
|
||||
if (data.containsKey("drinkingPreference")) pref.setDrinkingPreference((String) data.get("drinkingPreference"));
|
||||
if (data.containsKey("settlementPreference")) pref.setSettlementPreference((String) data.get("settlementPreference"));
|
||||
if (data.containsKey("marriagePlanPreference")) pref.setMarriagePlanPreference((String) data.get("marriagePlanPreference"));
|
||||
}
|
||||
|
||||
userPreferenceMapper.insert(pref);;
|
||||
if (exists) {
|
||||
pref.setUpdatedAt(Instant.now());
|
||||
userPreferenceMapper.update(pref,
|
||||
new LambdaUpdateWrapper<UserPreference>().eq(UserPreference::getUserId, userId));
|
||||
} else {
|
||||
userPreferenceMapper.insert(pref);
|
||||
}
|
||||
return pref;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@ import com.danyang.match.platform.profile.mapper.UserPrivacySettingsMapper;
|
||||
import com.danyang.match.platform.match.mapper.UserRelationMapper;
|
||||
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
import com.danyang.match.platform.verification.entity.UserIdentity;
|
||||
import com.danyang.match.platform.verification.mapper.UserIdentityMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -27,6 +31,7 @@ public class UserProfileService {
|
||||
private final UserPreferenceMapper userPreferenceMapper;
|
||||
private final UserPrivacySettingsMapper privacySettingsMapper;
|
||||
private final UserRelationMapper relationMapper;
|
||||
private final UserIdentityMapper userIdentityMapper;
|
||||
|
||||
/**
|
||||
* 获取自己完整资料(含隐私设置)
|
||||
@@ -60,8 +65,13 @@ public class UserProfileService {
|
||||
prefMap.put("maxHeightCm", pref.getMaxHeightCm());
|
||||
prefMap.put("heightPriority", pref.getHeightPriority());
|
||||
prefMap.put("regionScope", pref.getRegionScope());
|
||||
prefMap.put("regionPriority", pref.getRegionPriority());
|
||||
prefMap.put("maritalStatuses", pref.getMaritalStatuses());
|
||||
prefMap.put("maritalPriority", pref.getMaritalPriority());
|
||||
prefMap.put("minEducationCode", pref.getMinEducationCode());
|
||||
prefMap.put("educationPriority", pref.getEducationPriority());
|
||||
prefMap.put("childrenAcceptance", pref.getChildrenAcceptance());
|
||||
prefMap.put("childrenPriority", pref.getChildrenPriority());
|
||||
prefMap.put("smokingPreference", pref.getSmokingPreference());
|
||||
prefMap.put("drinkingPreference", pref.getDrinkingPreference());
|
||||
prefMap.put("settlementPreference", pref.getSettlementPreference());
|
||||
@@ -84,56 +94,185 @@ public class UserProfileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新基础资料
|
||||
* 更新基础资料(资料完善流程分节写)。
|
||||
*
|
||||
* <p>2026-09-23 UAT 走查修复:此前无论记录是否存在都调 {@code insert()},
|
||||
* 已有资料再次保存 → 主键冲突 → 500。改为「无则 insert / 有则 updateById」。
|
||||
* 另补 {@code gender}/{@code birth_date} 的 NOT NULL 兜底(见 {@link #ensureIdentityFields})。
|
||||
*/
|
||||
@Transactional
|
||||
public UserProfile updateBasicProfile(String userId, Map<String, Object> fields) {
|
||||
UserProfile profile = userProfileMapper.findByUserId(userId)
|
||||
.orElseGet(() -> {
|
||||
UserProfile p = new UserProfile();
|
||||
p.setUserId(userId);
|
||||
p.setProfileStatus(Constants.PROFILE_STATUS_IN_PROGRESS);
|
||||
return p;
|
||||
});
|
||||
|
||||
if (fields.containsKey("displayName")) profile.setDisplayName((String) fields.get("displayName"));
|
||||
if (fields.containsKey("heightCm")) profile.setHeightCm((Integer) fields.get("heightCm"));
|
||||
if (fields.containsKey("regionCode")) profile.setRegionCode((String) fields.get("regionCode"));
|
||||
if (fields.containsKey("regionName")) profile.setRegionName((String) fields.get("regionName"));
|
||||
if (fields.containsKey("maritalStatus")) profile.setMaritalStatus((String) fields.get("maritalStatus"));
|
||||
if (fields.containsKey("childrenStatus")) profile.setChildrenStatus((String) fields.get("childrenStatus"));
|
||||
if (fields.containsKey("educationCode")) profile.setEducationCode((String) fields.get("educationCode"));
|
||||
if (fields.containsKey("occupationCode")) profile.setOccupationCode((String) fields.get("occupationCode"));
|
||||
if (fields.containsKey("workRegionCode")) profile.setWorkRegionCode((String) fields.get("workRegionCode"));
|
||||
UserProfile profile = userProfileMapper.findByUserId(userId).orElse(null);
|
||||
boolean exists = profile != null;
|
||||
if (!exists) {
|
||||
profile = new UserProfile();
|
||||
profile.setUserId(userId);
|
||||
profile.setProfileStatus(Constants.PROFILE_STATUS_IN_PROGRESS);
|
||||
}
|
||||
|
||||
applyProfileFields(profile, fields);
|
||||
ensureIdentityFields(profile);
|
||||
profile.setProfileCompletion(calculateCompletion(profile));
|
||||
userProfileMapper.insert(profile);
|
||||
persistProfile(profile, exists);
|
||||
|
||||
return profile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新个人资料
|
||||
* 更新个人资料(资料完善向导的最终提交,置为 completed)。
|
||||
*
|
||||
* <p>2026-09-23 UAT 走查修复:同 {@link #updateBasicProfile},消除「二次保存必崩」。
|
||||
*/
|
||||
@Transactional
|
||||
public void updateProfile(String userId, Map<String, Object> fields) {
|
||||
UserProfile profile = userProfileMapper.findByUserId(userId).orElse(new UserProfile());
|
||||
profile.setUserId(userId);
|
||||
|
||||
// 基础字段映射
|
||||
if (fields.containsKey("displayName")) profile.setDisplayName((String) fields.get("displayName"));
|
||||
if (fields.containsKey("heightCm")) profile.setHeightCm((Integer) fields.get("heightCm"));
|
||||
if (fields.containsKey("regionCode")) profile.setRegionCode((String) fields.get("regionCode"));
|
||||
if (fields.containsKey("regionName")) profile.setRegionName((String) fields.get("regionName"));
|
||||
if (fields.containsKey("maritalStatus")) profile.setMaritalStatus((String) fields.get("maritalStatus"));
|
||||
if (fields.containsKey("childrenStatus")) profile.setChildrenStatus((String) fields.get("childrenStatus"));
|
||||
if (fields.containsKey("educationCode")) profile.setEducationCode((String) fields.get("educationCode"));
|
||||
if (fields.containsKey("occupationCode")) profile.setOccupationCode((String) fields.get("occupationCode"));
|
||||
if (fields.containsKey("workRegionCode")) profile.setWorkRegionCode((String) fields.get("workRegionCode"));
|
||||
UserProfile profile = userProfileMapper.findByUserId(userId).orElse(null);
|
||||
boolean exists = profile != null;
|
||||
if (!exists) {
|
||||
profile = new UserProfile();
|
||||
profile.setUserId(userId);
|
||||
}
|
||||
|
||||
applyProfileFields(profile, fields);
|
||||
ensureIdentityFields(profile);
|
||||
profile.setProfileCompletion(calculateCompletion(profile));
|
||||
profile.setProfileStatus(Constants.PROFILE_STATUS_COMPLETED);
|
||||
userProfileMapper.insert(profile);
|
||||
persistProfile(profile, exists);
|
||||
}
|
||||
|
||||
/**
|
||||
* 落库:无则插入、有则按主键 user_id 更新。
|
||||
*
|
||||
* <p>{@code UserProfile} 的 {@code @TableId = userId},与库主键 {@code user_profiles.user_id}
|
||||
* 一致,故 {@code updateById} 安全(对比 {@code UserPreference} 实体 id 与库主键不一致的情形)。
|
||||
*/
|
||||
private void persistProfile(UserProfile profile, boolean exists) {
|
||||
if (exists) {
|
||||
userProfileMapper.updateById(profile);
|
||||
} else {
|
||||
userProfileMapper.insert(profile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把请求字段映射到资料实体。
|
||||
*
|
||||
* <p>同时接受「规范字段名」与小程序的既有字段名,二者等价:
|
||||
* <ul>
|
||||
* <li>{@code childrenStatus}(none/yes)↔ {@code hasChildren}(布尔)</li>
|
||||
* <li>{@code occupationCode} ↔ {@code occupationCategory}</li>
|
||||
* <li>{@code workRegionCode} ↔ {@code workRegion}</li>
|
||||
* </ul>
|
||||
* 这使「REST 规范 / 管理端」与「小程序完善资料向导」共用同一写接口,
|
||||
* 避免因命名不一致导致字段被静默丢弃(UAT 走查发现向导的子女/职业/工作地三项
|
||||
* 此前根本写不进库)。
|
||||
*/
|
||||
private void applyProfileFields(UserProfile profile, Map<String, Object> fields) {
|
||||
if (fields == null) return;
|
||||
if (fields.containsKey("displayName")) profile.setDisplayName(asString(fields.get("displayName")));
|
||||
if (fields.containsKey("gender")) profile.setGender(asString(fields.get("gender")));
|
||||
if (fields.containsKey("birthDate")) profile.setBirthDate(asDate(fields.get("birthDate")));
|
||||
if (fields.containsKey("heightCm")) profile.setHeightCm(asInteger(fields.get("heightCm")));
|
||||
if (fields.containsKey("regionCode")) profile.setRegionCode(asString(fields.get("regionCode")));
|
||||
if (fields.containsKey("regionName")) profile.setRegionName(asString(fields.get("regionName")));
|
||||
if (fields.containsKey("maritalStatus")) profile.setMaritalStatus(asString(fields.get("maritalStatus")));
|
||||
|
||||
// 子女:规范名 childrenStatus(none/yes)优先,兼容向导的 hasChildren(布尔)
|
||||
if (fields.containsKey("childrenStatus")) {
|
||||
profile.setChildrenStatus(asString(fields.get("childrenStatus")));
|
||||
} else if (fields.containsKey("hasChildren")) {
|
||||
Boolean has = asBoolean(fields.get("hasChildren"));
|
||||
if (has != null) profile.setChildrenStatus(has ? "yes" : "none");
|
||||
}
|
||||
|
||||
if (fields.containsKey("educationCode")) profile.setEducationCode(asString(fields.get("educationCode")));
|
||||
|
||||
// 职业:规范名 occupationCode 优先,兼容向导的 occupationCategory
|
||||
if (fields.containsKey("occupationCode")) {
|
||||
profile.setOccupationCode(asString(fields.get("occupationCode")));
|
||||
} else if (fields.containsKey("occupationCategory")) {
|
||||
profile.setOccupationCode(asString(fields.get("occupationCategory")));
|
||||
}
|
||||
|
||||
// 工作地:规范名 workRegionCode 优先,兼容向导的 workRegion
|
||||
if (fields.containsKey("workRegionCode")) {
|
||||
profile.setWorkRegionCode(asString(fields.get("workRegionCode")));
|
||||
} else if (fields.containsKey("workRegion")) {
|
||||
profile.setWorkRegionCode(asString(fields.get("workRegion")));
|
||||
}
|
||||
|
||||
if (fields.containsKey("smokingStatus")) profile.setSmokingStatus(asString(fields.get("smokingStatus")));
|
||||
if (fields.containsKey("drinkingStatus")) profile.setDrinkingStatus(asString(fields.get("drinkingStatus")));
|
||||
if (fields.containsKey("longTermDanyang")) profile.setLongTermDanyang(asString(fields.get("longTermDanyang")));
|
||||
if (fields.containsKey("futureDanyang")) profile.setFutureDanyang(asString(fields.get("futureDanyang")));
|
||||
if (fields.containsKey("relationshipGoal")) profile.setRelationshipGoal(asString(fields.get("relationshipGoal")));
|
||||
if (fields.containsKey("marriagePlan")) profile.setMarriagePlan(asString(fields.get("marriagePlan")));
|
||||
if (fields.containsKey("selfIntro")) profile.setSelfIntro(asString(fields.get("selfIntro")));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code user_profiles.gender} 与 {@code birth_date} 在库中为 NOT NULL,而资料完善向导
|
||||
* 不采集这两项(性别是「已认证」的只读信息)——权威来源是实名认证
|
||||
* ({@code user_identities}),产品流程亦为「先实名、后完善资料」。
|
||||
*
|
||||
* <p>因此:请求未提供时从已通过实名认证的记录补齐;仍缺失则给出明确的
|
||||
* 4xx 业务拒绝(而非让数据库抛 NOT NULL 约束错渲染成 500)。
|
||||
*/
|
||||
private void ensureIdentityFields(UserProfile profile) {
|
||||
boolean needGender = profile.getGender() == null || profile.getGender().isBlank();
|
||||
boolean needBirth = profile.getBirthDate() == null;
|
||||
if (!needGender && !needBirth) return;
|
||||
|
||||
UserIdentity identity = userIdentityMapper.findByUserId(profile.getUserId()).orElse(null);
|
||||
if (identity != null && Constants.VERIFICATION_STATUS_VERIFIED.equals(identity.getVerificationStatus())) {
|
||||
if (needGender && identity.getGender() != null && !identity.getGender().isBlank()) {
|
||||
profile.setGender(identity.getGender());
|
||||
needGender = false;
|
||||
}
|
||||
if (needBirth && identity.getBirthDate() != null) {
|
||||
profile.setBirthDate(identity.getBirthDate());
|
||||
needBirth = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (needGender || needBirth) {
|
||||
throw new GlobalExceptionHandler.BusinessException(ApiResponseCode.BAD_REQUEST,
|
||||
"请先完成实名认证后再完善资料");
|
||||
}
|
||||
}
|
||||
|
||||
private static String asString(Object v) {
|
||||
return v == null ? null : String.valueOf(v);
|
||||
}
|
||||
|
||||
private static Integer asInteger(Object v) {
|
||||
if (v == null) return null;
|
||||
if (v instanceof Number n) return n.intValue();
|
||||
try {
|
||||
return Integer.valueOf(String.valueOf(v).trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean asBoolean(Object v) {
|
||||
if (v == null) return null;
|
||||
if (v instanceof Boolean b) return b;
|
||||
String s = String.valueOf(v).trim();
|
||||
if ("true".equalsIgnoreCase(s) || "yes".equalsIgnoreCase(s) || "has".equalsIgnoreCase(s)) return true;
|
||||
if ("false".equalsIgnoreCase(s) || "no".equalsIgnoreCase(s) || "none".equalsIgnoreCase(s)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static LocalDate asDate(Object v) {
|
||||
if (v == null) return null;
|
||||
if (v instanceof LocalDate d) return d;
|
||||
String s = String.valueOf(v).trim();
|
||||
if (s.isEmpty()) return null;
|
||||
try {
|
||||
return LocalDate.parse(s);
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ReferralService {
|
||||
private final ActivityRegistrationMapper activityRegistrationMapper;
|
||||
private final OperatorMapper operatorMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper matchmakerServiceMapper;
|
||||
private final com.danyang.match.platform.matchmaker.service.ServiceAssignmentPolicy serviceAssignmentPolicy;
|
||||
|
||||
/**
|
||||
* Phase 13 复验修复(D5):转介必须挂在「该红娘名下、服务对象为该用户」的真实服务关系上。
|
||||
@@ -39,16 +39,24 @@ public class ReferralService {
|
||||
* 任何持 matchmaker.service 权限的 operator 可把**任意用户**转介到任意活动/服务站,
|
||||
* 并顺带为该用户创建一条 activity_registration / service_appointment(越权代操作)。
|
||||
*
|
||||
* 修复后:先断言存在进行中的 matchmaker_service(assigned_operator_id=红娘, user_id=目标用户),
|
||||
* 否则拒绝。这样工作人员只能在真实的红娘服务关系内转介。
|
||||
* 修复后:先断言存在生效中的分配关系,否则拒绝。这样工作人员只能在真实的红娘服务关系内转介。
|
||||
*
|
||||
* <p>ZC-MM-005 收口(P1-3):授权事实源切换为
|
||||
* {@link com.danyang.match.platform.matchmaker.service.ServiceAssignmentPolicy}
|
||||
* 判定器 —— 与写接口 recommend / followup 同口径(matchmaker_assignments 生效中分配)。
|
||||
* 分配 revoke / end 后残留列不再构成转介凭据(DEC-002 规则7:撤销即失权)。
|
||||
*
|
||||
* <p>ZC-MM-006 / T04(写接口 404 统一·防探测):转介为资源寻址写端点,拒绝路径
|
||||
* 404 化 {@code denyAsNotFound}(先 DATA_SCOPE_DENIED 审计,再抛 404「服务不存在」,
|
||||
* 与读详情口径逐字段一致);并消灭裸 IllegalArgumentException ——
|
||||
* 缺失目标用户也统一映射为同一 404 响应,不泄露"目标是否存在"的任何信号。
|
||||
*/
|
||||
private void assertMatchmakerServesUser(String matchmakerId, String userId) {
|
||||
if (userId == null || userId.isBlank()) {
|
||||
throw new IllegalArgumentException("缺少转介目标用户");
|
||||
throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||
}
|
||||
matchmakerServiceMapper.findActiveByOperatorAndUser(matchmakerId, userId)
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"您不是该用户的服务负责人,无法发起转介"));
|
||||
serviceAssignmentPolicy.assertActiveAssignmentOrNotFound(matchmakerId, userId,
|
||||
"matchmaker_referral", userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
||||
@@ -26,6 +26,7 @@ import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
/**
|
||||
* 关系服务
|
||||
@@ -104,7 +105,7 @@ public class RelationshipService {
|
||||
@Transactional
|
||||
public void cancelLike(String userId, String targetUserId) {
|
||||
UserRelation relation = relationMapper.findByRelation(userId, targetUserId, Constants.RELATION_TYPE_LIKED)
|
||||
.orElseThrow(() -> new RuntimeException("没有找到喜欢关系"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到喜欢关系"));
|
||||
|
||||
relationMapper.deleteById(relation.getId());
|
||||
log.info("取消喜欢: userId={}, targetUserId={}", userId, targetUserId);
|
||||
@@ -184,7 +185,7 @@ public class RelationshipService {
|
||||
@Transactional
|
||||
public void unblock(String userId, String targetUserId) {
|
||||
UserRelation relation = relationMapper.findByRelation(userId, targetUserId, Constants.RELATION_TYPE_BLOCKED)
|
||||
.orElseThrow(() -> new RuntimeException("没有拉黑过该用户"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有拉黑过该用户"));
|
||||
|
||||
relationMapper.deleteById(relation.getId());
|
||||
log.info("解除拉黑: userId={}, targetUserId={}", userId, targetUserId);
|
||||
@@ -323,7 +324,7 @@ public class RelationshipService {
|
||||
@Transactional
|
||||
public void unmatch(String userId, String targetUserId) {
|
||||
Match match = matchMapper.findActiveMatch(userId, targetUserId)
|
||||
.orElseThrow(() -> new RuntimeException("没有找到有效的匹配关系"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到有效的匹配关系"));
|
||||
|
||||
match.setStatus(Constants.MATCH_STATUS_UNMATCHED);
|
||||
match.setUnmatchedAt(Instant.now());
|
||||
|
||||
@@ -95,9 +95,9 @@ public class ReviewController {
|
||||
public ApiResponse<ReviewResultDTO> approve(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String taskId,
|
||||
@RequestBody Map<String, String> body) {
|
||||
@RequestBody Map<String, Object> body) {
|
||||
String operatorId = principal.id();
|
||||
String comment = body.getOrDefault("comment", "");
|
||||
String comment = (String) body.getOrDefault("comment", "");
|
||||
return ApiResponse.ok(reviewService.approve(taskId, operatorId, comment));
|
||||
}
|
||||
|
||||
@@ -140,8 +140,8 @@ public class ReviewController {
|
||||
public ApiResponse<ReviewResultDTO> needEvidence(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String taskId,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(reviewService.needEvidence(taskId, principal.id(), body.get("comment")));
|
||||
@RequestBody Map<String, Object> body) {
|
||||
return ApiResponse.ok(reviewService.needEvidence(taskId, principal.id(), (String) body.get("comment")));
|
||||
}
|
||||
|
||||
@PostMapping("/{taskId}/approve-local-eligibility")
|
||||
@@ -149,8 +149,8 @@ public class ReviewController {
|
||||
public ApiResponse<ReviewResultDTO> approveLocalEligibility(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String taskId,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(reviewService.approveLocalEligibility(taskId, principal.id(), body.get("comment")));
|
||||
@RequestBody Map<String, Object> body) {
|
||||
return ApiResponse.ok(reviewService.approveLocalEligibility(taskId, principal.id(), (String) body.get("comment")));
|
||||
}
|
||||
|
||||
@PostMapping("/{taskId}/reject-local-eligibility")
|
||||
@@ -158,8 +158,8 @@ public class ReviewController {
|
||||
public ApiResponse<ReviewResultDTO> rejectLocalEligibility(
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String taskId,
|
||||
@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(reviewService.rejectLocalEligibility(taskId, principal.id(), body.get("comment")));
|
||||
@RequestBody Map<String, Object> body) {
|
||||
return ApiResponse.ok(reviewService.rejectLocalEligibility(taskId, principal.id(), (String) body.get("comment")));
|
||||
}
|
||||
|
||||
@PostMapping("/{taskId}/evidences/{evidenceId}/access")
|
||||
@@ -168,9 +168,9 @@ public class ReviewController {
|
||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||
@PathVariable String taskId,
|
||||
@PathVariable String evidenceId,
|
||||
@RequestBody Map<String, String> body) {
|
||||
@RequestBody Map<String, Object> body) {
|
||||
return ApiResponse.ok(reviewService.accessLocalEligibilityEvidence(
|
||||
taskId, evidenceId, principal.id(), body.get("purpose")));
|
||||
taskId, evidenceId, principal.id(), (String) body.get("purpose")));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,6 +32,7 @@ import java.time.Instant;
|
||||
import java.util.*;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -280,7 +281,7 @@ public class ReviewService {
|
||||
public ReviewTask resubmit(String userId) {
|
||||
// 找到最新的需修改任务
|
||||
ReviewTask latestTask = reviewTaskMapper.findLatestByUserId(userId)
|
||||
.orElseThrow(() -> new RuntimeException("未找到可重新提交的审核任务"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "未找到可重新提交的审核任务"));
|
||||
|
||||
if (!Constants.REVIEW_STATUS_NEED_EDIT.equals(latestTask.getStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不允许重新提交");
|
||||
|
||||
@@ -330,9 +330,68 @@ public final class Constants {
|
||||
public static final String RECOMMENDATION_SOURCE_MATCHMAKER = "matchmaker";
|
||||
public static final String PROFILE_STATUS_PENDING_REVIEW = "pending_review";
|
||||
|
||||
// ========== 服务对象分配(ZC-MM-002 / A1,与 V053 数据库 CHECK 白名单一致)==========
|
||||
// 状态机:active → transferred / revoked / ended;expires_at 届满由判定器惰性置 expired。
|
||||
// 终态(ended/revoked/transferred/expired)一律拒绝再转换。
|
||||
public static final String ASSIGNMENT_STATUS_ACTIVE = "active";
|
||||
public static final String ASSIGNMENT_STATUS_ENDED = "ended";
|
||||
public static final String ASSIGNMENT_STATUS_REVOKED = "revoked";
|
||||
public static final String ASSIGNMENT_STATUS_TRANSFERRED = "transferred";
|
||||
public static final String ASSIGNMENT_STATUS_EXPIRED = "expired";
|
||||
|
||||
// 分配范围:primary(主责,同用户仅一条生效中)/ collaborating(协同)
|
||||
public static final String ASSIGNMENT_SCOPE_PRIMARY = "primary";
|
||||
public static final String ASSIGNMENT_SCOPE_COLLABORATING = "collaborating";
|
||||
|
||||
// 服务对象分配审计 action(resourceType = matchmaker_assignment)
|
||||
public static final String AUDIT_ACTION_ASSIGNMENT_CREATE = "MATCHMAKER_ASSIGNMENT_CREATE";
|
||||
public static final String AUDIT_ACTION_ASSIGNMENT_TRANSFER = "MATCHMAKER_ASSIGNMENT_TRANSFER";
|
||||
public static final String AUDIT_ACTION_ASSIGNMENT_REVOKE = "MATCHMAKER_ASSIGNMENT_REVOKE";
|
||||
public static final String AUDIT_ACTION_ASSIGNMENT_END = "MATCHMAKER_ASSIGNMENT_END";
|
||||
|
||||
// ========== V1.1 本地资格审核 ==========
|
||||
/** 本地资格审核任务类型 */
|
||||
public static final String REVIEW_TYPE_LOCAL_ELIGIBILITY = "local_eligibility";
|
||||
/** 本地资格佐证数据类型(用于敏感访问审计) */
|
||||
public static final String SENSITIVE_DATA_TYPE_LOCAL_EVIDENCE = "local_eligibility_evidence";
|
||||
|
||||
// ========== ZC-MM-006 / T03 红娘域敏感访问审计 ==========
|
||||
/** 红娘工作台服务对象详情数据类型(用于敏感访问审计) */
|
||||
public static final String SENSITIVE_DATA_TYPE_MATCHMAKER_SERVICE_DETAIL = "matchmaker_service_detail";
|
||||
/** 敏感访问成功结果(与 SensitiveAccessLog.accessResult 白名单 success/denied/failed 对齐) */
|
||||
public static final String SENSITIVE_ACCESS_RESULT_SUCCESS = "success";
|
||||
/** 红娘查看服务对象详情的访问理由文案 */
|
||||
public static final String SENSITIVE_ACCESS_REASON_MATCHMAKER_DETAIL = "matchmaker 工作台查看服务对象详情";
|
||||
|
||||
// ========== ZC-MM-003 / B1 立项:受控联系授权(V056) ==========
|
||||
/** 授权状态:待审批 */
|
||||
public static final String CONTACT_AUTH_STATUS_PENDING_APPROVAL = "pending_approval";
|
||||
/** 授权状态:待用户同意 */
|
||||
public static final String CONTACT_AUTH_STATUS_PENDING_CONSENT = "pending_consent";
|
||||
/** 授权状态:生效中 */
|
||||
public static final String CONTACT_AUTH_STATUS_ACTIVE = "active";
|
||||
/** 授权状态:用户已拒绝 */
|
||||
public static final String CONTACT_AUTH_STATUS_REJECTED = "rejected";
|
||||
/** 授权状态:已过期(有效期/同意窗口届满,双态惰性收敛) */
|
||||
public static final String CONTACT_AUTH_STATUS_EXPIRED = "expired";
|
||||
/** 授权状态:已撤销 */
|
||||
public static final String CONTACT_AUTH_STATUS_REVOKED = "revoked";
|
||||
/** 渠道:电话联系 */
|
||||
public static final String CONTACT_CHANNEL_PHONE = "phone";
|
||||
/** 渠道:线下见面 */
|
||||
public static final String CONTACT_CHANNEL_OFFLINE_MEETING = "offline_meeting";
|
||||
/** 渠道:完整联系方式 */
|
||||
public static final String CONTACT_CHANNEL_FULL_CONTACT = "full_contact";
|
||||
/** 审计动作:红娘发起授权申请 */
|
||||
public static final String CONTACT_AUDIT_ACTION_REQUEST = "MATCHMAKER_CONTACT_REQUEST";
|
||||
/** 审计动作:审批岗批准/拒绝申请 */
|
||||
public static final String CONTACT_AUDIT_ACTION_APPROVE = "MATCHMAKER_CONTACT_APPROVE";
|
||||
/** 审计动作:用户单独同意 */
|
||||
public static final String CONTACT_AUDIT_ACTION_CONSENT = "MATCHMAKER_CONTACT_CONSENT";
|
||||
/** 审计动作:用户拒绝 */
|
||||
public static final String CONTACT_AUDIT_ACTION_DECLINE = "MATCHMAKER_CONTACT_DECLINE";
|
||||
/** 审计动作:披露联系方式(H4 唯一披露出口) */
|
||||
public static final String CONTACT_AUDIT_ACTION_DISCLOSE = "MATCHMAKER_CONTACT_DISCLOSE";
|
||||
/** 审计动作:撤销授权 */
|
||||
public static final String CONTACT_AUDIT_ACTION_REVOKE = "MATCHMAKER_CONTACT_REVOKE";
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
package com.danyang.match.platform.shared.filter;
|
||||
|
||||
import com.danyang.match.platform.auth.token.JwtTokenService;
|
||||
import com.danyang.match.platform.permission.mapper.OperatorMapper;
|
||||
import com.danyang.match.platform.permission.service.PermissionService;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import com.danyang.match.platform.shared.security.principal.PlatformPrincipal;
|
||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -33,6 +35,7 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtTokenService jwtTokenService;
|
||||
private final PermissionService permissionService;
|
||||
private final OperatorMapper operatorMapper;
|
||||
|
||||
private static final List<String> PERMITTED_PATHS = List.of(
|
||||
"/api/v1/auth/**",
|
||||
@@ -58,12 +61,26 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||
String token = null;
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
token = authHeader.substring(7);
|
||||
} else {
|
||||
// 浏览器同源请求:管理端登录后由 HttpOnly Cookie(dy_op_at)携带 access token。
|
||||
// 作为 Authorization 头的兜底(抗 XSS 读取;小程序/用户端仍走 Authorization 头,不受影响)。
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies != null) {
|
||||
for (Cookie c : cookies) {
|
||||
if ("dy_op_at".equals(c.getName())) {
|
||||
token = c.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (token == null) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String token = authHeader.substring(7);
|
||||
if (!jwtTokenService.validateToken(token)) {
|
||||
sendUnauthorized(response);
|
||||
return;
|
||||
@@ -72,6 +89,20 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
String subject = jwtTokenService.getUserIdFromToken(token);
|
||||
String tokenType = jwtTokenService.parseToken(token).get("type", String.class);
|
||||
boolean operatorToken = "operator_access".equals(tokenType);
|
||||
if (operatorToken) {
|
||||
// ZC-MM-006 / T02(JWT 权限回收·实时查库路线,不建撤销名单):
|
||||
// 运营 token 每请求实时查 operators.status —— 账号不存在(含软删除)或非 active
|
||||
// 一律 401、不建 principal,已签发 token 立即失效;零缓存。
|
||||
// 注意:此处只接受 "active";"normal" 是用户账号状态(ACCOUNT_STATUS_NORMAL),
|
||||
// 运营账号禁用/待激活均不得通过过滤器。
|
||||
var operator = operatorMapper.findById(subject);
|
||||
if (operator.isEmpty() || !"active".equals(operator.get().getStatus())) {
|
||||
sendUnauthorized(response);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// ZC-MM-006 / T02:权限实时查库(PermissionMapper join role_permissions/operator_roles),
|
||||
// 每请求生效;token claims 中的 permissions 仅作展示快照(只写不读),不是授权事实源。
|
||||
List<String> permissions = operatorToken
|
||||
? permissionService.getPermissions(subject)
|
||||
: List.of();
|
||||
|
||||
@@ -35,6 +35,9 @@ public class AuthorizationAuditListener {
|
||||
audit.setAction("AUTHORIZATION_DENIED");
|
||||
audit.setResourceType("authorization");
|
||||
audit.setResourceId(limit(String.valueOf(event.getObject()), 128));
|
||||
// ZC-MM-006 / T01:权限快照(permissions 逗号拼接,截断 128)+ 请求追踪 ID
|
||||
audit.setActorRoleSnapshot(limit(String.join(",", principal.permissions()), 128));
|
||||
audit.setRequestTraceId(org.slf4j.MDC.get("requestId"));
|
||||
audit.setCreatedAt(Instant.now());
|
||||
|
||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
|
||||
|
||||
@@ -2,13 +2,18 @@ package com.danyang.match.platform.shared.security;
|
||||
|
||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
/** Denies out-of-scope operator access and records the attempt before returning 403. */
|
||||
@Slf4j
|
||||
@@ -19,12 +24,28 @@ public class DataScopeGuard {
|
||||
private final AuditLogMapper auditLogMapper;
|
||||
|
||||
public void deny(String operatorId, String resourceType, String resourceId, String message) {
|
||||
// ZC-MM-006 / T01 兼容性:缺省调用(不带 purposeCode/assignmentId)仍可写
|
||||
deny(operatorId, resourceType, resourceId, message, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZC-MM-006 / T01 扩展版拒绝审计:附加业务目的码与关联分配 ID。
|
||||
*
|
||||
* @param purposeCode 业务目的码(如 matchmaker.service.view),可空
|
||||
* @param serviceAssignmentId 关联的 matchmaker_assignments.id(拒绝路径通常无生效分配 → null)
|
||||
*/
|
||||
public void deny(String operatorId, String resourceType, String resourceId, String message,
|
||||
String purposeCode, String serviceAssignmentId) {
|
||||
AuditLog audit = new AuditLog();
|
||||
audit.setId(UUID.randomUUID().toString());
|
||||
audit.setOperatorId(operatorId);
|
||||
audit.setAction("DATA_SCOPE_DENIED");
|
||||
audit.setResourceType(resourceType);
|
||||
audit.setResourceId(resourceId);
|
||||
audit.setPurposeCode(purposeCode);
|
||||
audit.setServiceAssignmentId(serviceAssignmentId);
|
||||
audit.setActorRoleSnapshot(currentActorRoleSnapshot());
|
||||
audit.setRequestTraceId(MDC.get("requestId"));
|
||||
audit.setCreatedAt(Instant.now());
|
||||
try {
|
||||
auditLogMapper.insert(audit);
|
||||
@@ -34,4 +55,57 @@ public class DataScopeGuard {
|
||||
}
|
||||
throw new AccessDeniedException(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZC-MM-006 / T04(写接口 404 统一·防探测):范围校验失败的写端点 ——
|
||||
* 先落与 {@link #deny} 完全相同的 DATA_SCOPE_DENIED 审计(语义上仍是 403 越权),
|
||||
* 再抛 {@code BusinessException(NOT_FOUND, "服务不存在")}:响应与"资源不存在"逐字段一致,
|
||||
* 调用方无法区分"无权"与"不存在",杜绝按资源 ID 枚举探测写端点。
|
||||
*
|
||||
* <p>适用面:带资源寻址的写端点(transfer/revoke/end/recommend/followup/complete/转介);
|
||||
* create/assign 类无资源寻址端点维持 {@link #deny} 的 403 口径。
|
||||
*
|
||||
* @param message 404 响应 message(统一 "服务不存在",与读详情口径一致)
|
||||
*/
|
||||
public void denyAsNotFound(String operatorId, String resourceType, String resourceId, String message,
|
||||
String purposeCode, String serviceAssignmentId) {
|
||||
AuditLog audit = new AuditLog();
|
||||
audit.setId(UUID.randomUUID().toString());
|
||||
audit.setOperatorId(operatorId);
|
||||
audit.setAction("DATA_SCOPE_DENIED");
|
||||
audit.setResourceType(resourceType);
|
||||
audit.setResourceId(resourceId);
|
||||
audit.setPurposeCode(purposeCode);
|
||||
audit.setServiceAssignmentId(serviceAssignmentId);
|
||||
audit.setActorRoleSnapshot(currentActorRoleSnapshot());
|
||||
audit.setRequestTraceId(MDC.get("requestId"));
|
||||
audit.setCreatedAt(Instant.now());
|
||||
try {
|
||||
auditLogMapper.insert(audit);
|
||||
} catch (RuntimeException exception) {
|
||||
log.error("写入数据范围拒绝审计失败: operatorId={}, resourceType={}, resourceId={}",
|
||||
operatorId, resourceType, resourceId, exception);
|
||||
}
|
||||
throw new BusinessException(ApiResponseCode.NOT_FOUND, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前操作者权限快照(与 {@link AuthorizationAuditListener} 同口径):
|
||||
* OperatorPrincipal.permissions() 逗号拼接,截断 128。
|
||||
*/
|
||||
private String currentActorRoleSnapshot() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal()
|
||||
instanceof com.danyang.match.platform.shared.security.principal.OperatorPrincipal principal) {
|
||||
return limit(String.join(",", principal.permissions()), 128);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String limit(String value, int maxLength) {
|
||||
if (value == null || value.length() <= maxLength) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,15 @@ import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Mock 实名认证 Provider
|
||||
* 开发/测试环境使用,生产环境替换为正式 Provider
|
||||
* 开发/测试环境使用,生产环境替换为正式 Provider。
|
||||
*
|
||||
* <p>属性已从 {@code verification.provider} 解耦为独立的 {@code identity.verification.provider},
|
||||
* 由 {@link RealIdentityVerificationProvider} 承接 {@code real} 取值;本类保留
|
||||
* {@code matchIfMissing = true},未显式配置时本地默认仍是 Mock。生产必须在
|
||||
* {@code application-production.yml} 显式置 {@code identity.verification.provider=real}。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "verification.provider", havingValue = "mock", matchIfMissing = true)
|
||||
@ConditionalOnProperty(name = "identity.verification.provider", havingValue = "mock", matchIfMissing = true)
|
||||
public class MockIdentityVerificationProvider implements IdentityVerificationProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MockIdentityVerificationProvider.class);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package com.danyang.match.platform.verification.provider;
|
||||
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 真实实名认证 Provider(生产环境使用)。
|
||||
*
|
||||
* <p>由配置 {@code identity.verification.provider=real} 激活;未显式配置时默认是 Mock
|
||||
* (见 {@link MockIdentityVerificationProvider}),因此生产环境必须在
|
||||
* {@code application-production.yml} 里显式置 {@code real},否则启动即应失败(而非悄悄走 Mock)。
|
||||
*
|
||||
* <p>核验策略(fail-closed,绝不静默放行):
|
||||
* <ul>
|
||||
* <li>本地强校验:身份证号 GB 11643-1999 校验位(mod 11-2)。校验位不符直接判定未通过,
|
||||
* 在发起任何外部调用前拦截明显伪造的证件号。</li>
|
||||
* <li>第三方核验:必须配置 {@code identity.verification.real.api-url} 与
|
||||
* {@code identity.verification.real.api-key}(环境变量 {@code VERIFICATION_API_URL} /
|
||||
* {@code VERIFICATION_API_KEY})。未配置即 fail-fast —— 真实核验无法凭空完成,
|
||||
* 绝不能回退成「放行」。</li>
|
||||
* <li>任何无法判定为明确的「核验通过」的响应,一律按「未通过」处理(fail-closed)。</li>
|
||||
* <li>绝不把身份证号原文作为日志明文输出;仅记录脱敏值。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>对接说明:第三方请求/响应契约需在接入具体厂商(如公安实名、运营商三要素)时最终确认。
|
||||
* 当前实现以「明确的 success/match/verified/passed 布尔为 true」判定通过,其余一律视为未通过。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "identity.verification.provider", havingValue = "real")
|
||||
public class RealIdentityVerificationProvider implements IdentityVerificationProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RealIdentityVerificationProvider.class);
|
||||
|
||||
/** 身份证号校验位权重(GB 11643-1999,前 17 位) */
|
||||
private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
|
||||
/** 校验位映射:索引 = 加权和 mod 11;'X' 表示余数 2 */
|
||||
private static final String CHECK_CODES = "10X98765432";
|
||||
|
||||
@Value("${identity.verification.real.api-url:}")
|
||||
private String apiUrl;
|
||||
|
||||
@Value("${identity.verification.real.api-key:}")
|
||||
private String apiKey;
|
||||
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Map<String, Object> verify(String realName, String idNumber) {
|
||||
if (apiUrl == null || apiUrl.isBlank() || apiKey == null || apiKey.isBlank()) {
|
||||
// 配置缺失 = 生产未就绪,fail-fast 而非放行任意证件
|
||||
throw new BusinessException(ApiResponseCode.SERVER_ERROR, "实名核验未配置第三方核验服务");
|
||||
}
|
||||
if (realName == null || realName.isBlank()) {
|
||||
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "实名认证失败:缺少姓名");
|
||||
}
|
||||
|
||||
// 1. 本地校验位强校验:伪造证件号在外部调用前即拒绝
|
||||
if (!isValidChecksum(idNumber)) {
|
||||
log.warn("[Identity] 身份证校验位不合法: idNumber={}", maskIdNumber(idNumber));
|
||||
return buildResult(false, idNumber, realName, null, null, UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
LocalDate birthDate = parseBirthDateFromIdNumber(idNumber);
|
||||
String gender = parseGenderFromIdNumber(idNumber);
|
||||
|
||||
// 2. 第三方核验(fail-closed)
|
||||
boolean matched = callThirdParty(realName, idNumber);
|
||||
return buildResult(matched, idNumber, realName, birthDate.toString(), gender, UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用第三方实名核验。仅当响应中明确出现「通过」语义的布尔字段为 true 时才返回 true;
|
||||
* 其余(缺字段、字段为 false、解析失败、网络异常)一律返回 false(fail-closed)。
|
||||
*/
|
||||
private boolean callThirdParty(String realName, String idNumber) {
|
||||
try {
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("realName", realName);
|
||||
body.put("idNumber", idNumber);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("Authorization", "Bearer " + apiKey);
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
|
||||
ResponseEntity<String> resp = restTemplate.postForEntity(apiUrl, entity, String.class);
|
||||
if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
|
||||
log.warn("[Identity] 第三方核验返回非成功状态: status={}", resp.getStatusCode());
|
||||
return false;
|
||||
}
|
||||
JsonNode node = objectMapper.readTree(resp.getBody());
|
||||
return isExplicitlyVerified(node);
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("[Identity] 第三方核验调用异常", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅在响应中明确的「通过」布尔字段为 true 时判定通过。 */
|
||||
private boolean isExplicitlyVerified(JsonNode node) {
|
||||
for (String field : new String[]{"success", "match", "verified", "passed", "isValid"}) {
|
||||
JsonNode v = node.get(field);
|
||||
if (v != null && v.isBoolean() && v.asBoolean()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// 兼容 { "code": 0, "message": "ok" } 形态
|
||||
JsonNode code = node.get("code");
|
||||
if (code != null && code.isNumber() && code.asInt() == 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildResult(boolean verified, String idNumber, String realName,
|
||||
String birthDate, String gender, String requestId) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("verified", verified);
|
||||
result.put("realName", realName);
|
||||
result.put("idNumberHash", idNumber);
|
||||
result.put("birthDate", birthDate);
|
||||
result.put("gender", gender);
|
||||
result.put("requestId", requestId);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMock() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** GB 11643-1999 校验位(mod 11-2)。 */
|
||||
private boolean isValidChecksum(String idNumber) {
|
||||
if (idNumber == null || idNumber.length() != 18) {
|
||||
return false;
|
||||
}
|
||||
if (!idNumber.substring(0, 17).matches("\\d{17}")) {
|
||||
return false;
|
||||
}
|
||||
char last = idNumber.charAt(17);
|
||||
if (!(Character.isDigit(last) || last == 'X' || last == 'x')) {
|
||||
return false;
|
||||
}
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 17; i++) {
|
||||
sum += (idNumber.charAt(i) - '0') * WEIGHTS[i];
|
||||
}
|
||||
char expected = CHECK_CODES.charAt(sum % 11);
|
||||
return Character.toUpperCase(last) == expected;
|
||||
}
|
||||
|
||||
private LocalDate parseBirthDateFromIdNumber(String idNumber) {
|
||||
try {
|
||||
int year = Integer.parseInt(idNumber.substring(6, 10));
|
||||
int month = Integer.parseInt(idNumber.substring(10, 12));
|
||||
int day = Integer.parseInt(idNumber.substring(12, 14));
|
||||
return LocalDate.of(year, month, day);
|
||||
} catch (Exception e) {
|
||||
return LocalDate.now().minusYears(25);
|
||||
}
|
||||
}
|
||||
|
||||
private String parseGenderFromIdNumber(String idNumber) {
|
||||
int genderDigit = Integer.parseInt(idNumber.substring(16, 17));
|
||||
return (genderDigit % 2 == 1) ? "male" : "female";
|
||||
}
|
||||
|
||||
private String maskIdNumber(String idNumber) {
|
||||
if (idNumber == null || idNumber.length() < 10) return "****";
|
||||
return idNumber.substring(0, 6) + "**********" + idNumber.substring(idNumber.length() - 4);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import java.util.Map;
|
||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||
import com.danyang.match.platform.shared.exception.ServerErrorException;
|
||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -136,7 +137,7 @@ public class IdentityVerificationService {
|
||||
*/
|
||||
public Map<String, Object> getIdentityStatus(String userId) {
|
||||
User user = userMapper.findById(userId)
|
||||
.orElseThrow(() -> new RuntimeException("用户不存在"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "用户不存在"));
|
||||
|
||||
return userIdentityMapper.findByUserId(userId)
|
||||
.map(identity -> {
|
||||
@@ -212,7 +213,7 @@ public class IdentityVerificationService {
|
||||
@Transactional
|
||||
public void cancelIdentity(String userId) {
|
||||
UserIdentity identity = userIdentityMapper.findByUserId(userId)
|
||||
.orElseThrow(() -> new RuntimeException("未找到实名认证记录"));
|
||||
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "未找到实名认证记录"));
|
||||
|
||||
if (Constants.VERIFICATION_STATUS_VERIFIED.equals(identity.getVerificationStatus())) {
|
||||
throw new BusinessException(ApiResponseCode.OPERATION_NOT_ALLOWED, "已认证的实名记录不能撤销");
|
||||
|
||||
@@ -38,10 +38,17 @@ object-storage:
|
||||
region: us-east-1
|
||||
signature-version: s3v4
|
||||
|
||||
verification:
|
||||
provider: ${VERIFICATION_PROVIDER:mock}
|
||||
api-url: ${VERIFICATION_API_URL:}
|
||||
api-key: ${VERIFICATION_API_KEY:}
|
||||
# 实名核验:docker 本地/CI 默认走 Mock(VERIFICATION_PROVIDER=real 时启用真实实现,需同时配置 api-url/api-key)
|
||||
identity:
|
||||
verification:
|
||||
provider: ${VERIFICATION_PROVIDER:mock}
|
||||
real:
|
||||
api-url: ${VERIFICATION_API_URL:}
|
||||
api-key: ${VERIFICATION_API_KEY:}
|
||||
|
||||
# 管理端鉴权 Cookie:docker 内部为 http,关闭 Secure 标志
|
||||
app:
|
||||
auth-cookie-secure: false
|
||||
|
||||
match:
|
||||
rule-version: 1
|
||||
|
||||
@@ -14,3 +14,27 @@ spring:
|
||||
user:
|
||||
name: disabled
|
||||
password: ${SPRING_SECURITY_FALLBACK_PASSWORD}
|
||||
|
||||
# 微信登录:生产必须显式启用真实实现(wechat.login.provider=real)。
|
||||
# 未配置时本地默认走 Mock;生产若漏配此行,RealWechatLoginProvider 不会激活、
|
||||
# MockWechatLoginProvider 又因 havingValue=mock 不匹配 → 无 WechatLoginProvider Bean,启动即失败(fail-fast,不悄悄放行任意 code)。
|
||||
wechat:
|
||||
login:
|
||||
provider: real
|
||||
app-id: ${WECHAT_APP_ID}
|
||||
app-secret: ${WECHAT_APP_SECRET}
|
||||
|
||||
# 实名核验:生产必须显式启用真实实现(identity.verification.provider=real)。
|
||||
# 未配置时本地默认走 Mock;生产若漏配此行,RealIdentityVerificationProvider 不会激活、
|
||||
# MockIdentityVerificationProvider 又因 havingValue=mock 不匹配 → 无 IdentityVerificationProvider Bean,启动即失败(fail-fast,不悄悄放行任意证件)。
|
||||
# 真实核验还需配置第三方核验服务地址与密钥(缺失则核验请求 fail-fast)。
|
||||
identity:
|
||||
verification:
|
||||
provider: real
|
||||
real:
|
||||
api-url: ${VERIFICATION_API_URL:}
|
||||
api-key: ${VERIFICATION_API_KEY:}
|
||||
|
||||
# 管理端鉴权 Cookie:生产走 https,开启 Secure 标志(HttpOnly + SameSite=Lax 始终生效)
|
||||
app:
|
||||
auth-cookie-secure: true
|
||||
|
||||
@@ -92,3 +92,13 @@ spring.security:
|
||||
rate-limit:
|
||||
max-requests-per-window: 20
|
||||
window-seconds: 60
|
||||
|
||||
# 受控联系授权(ZC-MM-003 / B1 立项,canonical key 见 ContactAuthorizationConfig;治理登记 T06 config-register)
|
||||
# 注意:代码缺省 enabled=false(fail-safe),生产显式开启;新环境漏配时机制整体关闭而非意外开放。
|
||||
matchmaker:
|
||||
contact:
|
||||
enabled: true
|
||||
approver-authorities: matchmaker.team.assign,matchmaker.assign
|
||||
consent-deadline-hours: 72
|
||||
default-validity-days: 7
|
||||
retention-days: 365
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
-- ============================================================
|
||||
-- V052: 补齐 matchmaker(公益红娘)角色权限
|
||||
--
|
||||
-- 发现方式:2026-10-09 搭建本地演示栈、创建红娘运营账号 wanghongniang 并授予
|
||||
-- matchmaker 角色后发现,该角色在 role_permissions 中零条授权。
|
||||
-- 用该账号登录后台,点「红娘服务」菜单加载 GET /operator/matchmaker/dashboard
|
||||
-- 直接 403;同时前端菜单权限码(referral.manage / matchmaker.service.view)与后端
|
||||
-- 真实 authority 码(matchmaker.service / matchmaker.view)不匹配,导致这两个菜单
|
||||
-- 对所有角色(含 super_admin)被 visibleNavigation 过滤隐藏。
|
||||
--
|
||||
-- 根因:与 V043/V044 同族 —— 角色定义了、权限定义了,两者之间从未连上。
|
||||
-- V015 只把全部权限授予 super_admin;matchmaker 等运营角色从未被授予任何权限。
|
||||
--
|
||||
-- 授权范围(最小权限原则,与后端 @PreAuthorize 严格对应):
|
||||
-- * matchmaker.view —— 查看红娘服务(GET /operator/matchmaker/*)
|
||||
-- * matchmaker.service —— 认领/推荐/跟进/完成红娘服务 + 转介管理(referral 控制器)
|
||||
-- * matchmaker.assign —— 分配红娘服务
|
||||
-- 后端 MatchmakerOperatorController / ReferralController 的 @PreAuthorize 仅要求这三条,
|
||||
-- 故仅授予这三条,不扩权。
|
||||
--
|
||||
-- 幂等:ON CONFLICT (role_id, permission_id) DO NOTHING。
|
||||
-- ============================================================
|
||||
|
||||
INSERT INTO role_permissions (role_id, permission_id)
|
||||
SELECT '00000000-0000-0000-0000-000000000005', id
|
||||
FROM permissions
|
||||
WHERE code IN ('matchmaker.view', 'matchmaker.service', 'matchmaker.assign')
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,79 @@
|
||||
-- ============================================================
|
||||
-- V053: 服务对象分配表(ZC-MM-002 / A1 服务对象分配建模)
|
||||
--
|
||||
-- 建模决策(架构师设计 D1/D5):
|
||||
-- * 决策文档 5.1 的 matchmaker_user_id 对应 operators 主体,
|
||||
-- 定名 matchmaker_operator_id(沿用 matchmaker_services.assigned_operator_id 惯例)。
|
||||
-- * status 状态机:active → transferred / revoked / ended;
|
||||
-- expires_at < now 的 active 行由 ServiceAssignmentPolicy 惰性置 expired(无定时任务);
|
||||
-- 终态(transferred/revoked/ended/expired)一律不允许再次转换。
|
||||
-- * assignment_scope:primary(主责)/ collaborating(协同)。
|
||||
-- * 同一用户同时最多一条 active + primary 分配 → 部分唯一索引兜底
|
||||
-- (业务层 SELECT-then-INSERT 有竞态,只有 DB 唯一索引能兜住)。
|
||||
--
|
||||
-- 存量回填说明:
|
||||
-- matchmaker_services.assigned_operator_id IS NOT NULL 且服务仍处于非终态
|
||||
-- (assigned / in_service / waiting_user,与 V009 chk_matchmaker_status 白名单一致)的行,
|
||||
-- 回填为 active + primary 分配。assigned_by 无历史记录可考,取技术回填值
|
||||
-- = assigned_operator_id(仅表示"分配关系成立",不代表当年实际操作者)。
|
||||
-- 幂等:NOT EXISTS 防重复回填(按 service_id 关联)。
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS matchmaker_assignments (
|
||||
id UUID PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
matchmaker_operator_id UUID NOT NULL REFERENCES operators(id),
|
||||
service_id UUID REFERENCES matchmaker_services(id),
|
||||
assigned_by UUID NOT NULL REFERENCES operators(id),
|
||||
assignment_scope VARCHAR(32) NOT NULL DEFAULT 'primary',
|
||||
assignment_reason VARCHAR(500) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||
assigned_at TIMESTAMPTZ,
|
||||
expires_at TIMESTAMPTZ,
|
||||
ended_at TIMESTAMPTZ,
|
||||
end_reason VARCHAR(500),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
ALTER TABLE matchmaker_assignments ADD CONSTRAINT chk_mm_assignment_status CHECK (status IN (
|
||||
'active', 'ended', 'revoked', 'transferred', 'expired'
|
||||
));
|
||||
ALTER TABLE matchmaker_assignments ADD CONSTRAINT chk_mm_assignment_scope CHECK (assignment_scope IN (
|
||||
'primary', 'collaborating'
|
||||
));
|
||||
|
||||
-- 部分唯一索引:同一用户最多一条「生效中的主责分配」。
|
||||
-- 终态行(ended/revoked/transferred/expired)不占位,允许历史多条。
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_mm_assignment_active_primary
|
||||
ON matchmaker_assignments(user_id)
|
||||
WHERE status = 'active' AND assignment_scope = 'primary';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mm_assignment_operator ON matchmaker_assignments(matchmaker_operator_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_mm_assignment_user ON matchmaker_assignments(user_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_mm_assignment_service ON matchmaker_assignments(service_id);
|
||||
|
||||
-- 存量回填(幂等)
|
||||
INSERT INTO matchmaker_assignments (
|
||||
id, user_id, matchmaker_operator_id, service_id, assigned_by,
|
||||
assignment_scope, assignment_reason, status, assigned_at, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
gen_random_uuid(),
|
||||
ms.user_id,
|
||||
ms.assigned_operator_id,
|
||||
ms.id,
|
||||
ms.assigned_operator_id, -- assigned_by 为技术回填值:历史分配操作者未记录
|
||||
'primary',
|
||||
'V053 存量回填:原始分配人未记录',
|
||||
'active',
|
||||
COALESCE(ms.assigned_at, NOW()),
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM matchmaker_services ms
|
||||
WHERE ms.assigned_operator_id IS NOT NULL
|
||||
AND ms.status IN ('assigned', 'in_service', 'waiting_user')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM matchmaker_assignments ma WHERE ma.service_id = ms.id
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
-- ============================================================
|
||||
-- V054: 新增红娘组长角色与团队分配权限(ZC-MM-002 / A1,架构师设计 D2)
|
||||
--
|
||||
-- 角色权限边界:
|
||||
-- * matchmaker_leader(014)授 view(020) + service(022) + team.assign(023),
|
||||
-- **不给** matchmaker.assign(021) —— 组长只能在同组织范围内分配;
|
||||
-- 组织边界判定:组长团队边界 = 同 organization_id,NULL=NULL 视为平台直属
|
||||
-- (平台直属组长只能分配平台直属红娘;有组织组长不能分配 org=NULL 红娘;
|
||||
-- org=NULL 普通红娘只能由 matchmaker.assign 持有者分配 —— 该技术默认
|
||||
-- 写在 ServiceAssignmentPolicy / MatchmakerAssignmentService 代码注释,
|
||||
-- 治理登记后续补充)。
|
||||
-- * 普通红娘(005)权限现状不变(view/service),由 V052 授予。
|
||||
--
|
||||
-- 幂等:全部 ON CONFLICT DO NOTHING(对照 V052 风格)。
|
||||
-- ============================================================
|
||||
|
||||
INSERT INTO roles (id, code, name, description, system_role) VALUES (
|
||||
'00000000-0000-0000-0000-000000000014',
|
||||
'matchmaker_leader',
|
||||
'红娘组长',
|
||||
'公益红娘团队组长,可在同组织范围内分配/转分配服务对象',
|
||||
TRUE
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO permissions (id, code, name, module, description) VALUES (
|
||||
'10000000-0000-0000-0000-000000000023',
|
||||
'matchmaker.team.assign',
|
||||
'红娘团队分配',
|
||||
'matchmaker',
|
||||
'在组长同组织范围内分配/转分配/撤销/结束服务对象分配'
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 红娘组长:view + service + team.assign(不含 matchmaker.assign)
|
||||
INSERT INTO role_permissions (role_id, permission_id)
|
||||
SELECT '00000000-0000-0000-0000-000000000014', id
|
||||
FROM permissions
|
||||
WHERE code IN ('matchmaker.view', 'matchmaker.service', 'matchmaker.team.assign')
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- ============================================================
|
||||
-- V055: audit_logs 扩展红娘域审计字段(ZC-MM-006 / T01)
|
||||
--
|
||||
-- 新增 4 列(全部可空、存量不回填、语句幂等):
|
||||
-- purpose_code 业务目的码,规范:matchmaker.service.assign/recommend/followup/complete/view
|
||||
-- service_assignment_id 关联的 matchmaker_assignments.id(可空:非分配场景为 NULL)
|
||||
-- actor_role_snapshot 审计落库时操作者的权限快照(OperatorPrincipal.permissions() 逗号拼接,截断 128)
|
||||
-- request_trace_id 请求追踪 ID(RequestIdFilter 写入 MDC 的 requestId,16 位)
|
||||
--
|
||||
-- 兼容性:全部可空 → 缺省调用(不传新字段)仍可正常写入,存量行为不变。
|
||||
-- 幂等:H2/PostgreSQL 均无 ADD COLUMN IF NOT EXISTS 统一保障时,
|
||||
-- 用 information_schema 判空后执行(对照 V034/V035 风格)。
|
||||
-- ============================================================
|
||||
|
||||
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS purpose_code VARCHAR(64);
|
||||
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS service_assignment_id UUID;
|
||||
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS actor_role_snapshot VARCHAR(128);
|
||||
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS request_trace_id VARCHAR(64);
|
||||
@@ -0,0 +1,50 @@
|
||||
-- ============================================================
|
||||
-- V056: 受控联系授权表 matchmaker_contact_authorizations
|
||||
-- (ZC-MM-003 / B1 例外通道立项,架构师设计 H4/G4)
|
||||
--
|
||||
-- 语义:红娘对分配对象发起联系方式/线下见面授权申请,经审批岗批准、
|
||||
-- 用户单独明示同意(独立端点,无预同意参数)后方可生效;
|
||||
-- 唯一披露出口为 ContactAuthorizationService.disclose(每次落敏感访问审计)。
|
||||
--
|
||||
-- 状态机(六态):
|
||||
-- pending_approval → pending_consent(审批岗批准)
|
||||
-- pending_consent → active(用户单独同意)/ rejected(用户拒绝)
|
||||
-- active / pending_consent → expired(双态惰性收敛:有效期/同意窗口届满)
|
||||
-- active → revoked(申请人或审批人撤销)
|
||||
--
|
||||
-- 幂等:CREATE TABLE / INDEX 全部 IF NOT EXISTS,可重放。
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS matchmaker_contact_authorizations (
|
||||
id UUID PRIMARY KEY,
|
||||
operator_id UUID NOT NULL REFERENCES operators(id),
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
channel VARCHAR(32) NOT NULL,
|
||||
purpose VARCHAR(200) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending_approval',
|
||||
approved_by UUID,
|
||||
approved_at TIMESTAMPTZ,
|
||||
user_consented_at TIMESTAMPTZ,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
revoked_by UUID,
|
||||
revoke_reason VARCHAR(500),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT chk_contact_auth_channel CHECK (channel IN ('phone', 'offline_meeting', 'full_contact')),
|
||||
CONSTRAINT chk_contact_auth_status CHECK (status IN (
|
||||
'pending_approval', 'pending_consent', 'active', 'rejected', 'expired', 'revoked'
|
||||
))
|
||||
);
|
||||
|
||||
-- 同一 (红娘, 用户, 渠道) 同时最多一条 active(防重复生效授权)
|
||||
-- H2 测试库以生成列 + 唯一索引等价实现(见 schema-h2.sql 注释)。
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_mm_contact_auth_active
|
||||
ON matchmaker_contact_authorizations(operator_id, user_id, channel)
|
||||
WHERE status = 'active';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_contact_auth_operator_status
|
||||
ON matchmaker_contact_authorizations(operator_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_contact_auth_user_status
|
||||
ON matchmaker_contact_authorizations(user_id, status);
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.danyang.match.platform.activity.controller;
|
||||
|
||||
import com.danyang.match.platform.activity.mapper.ActivityMapper;
|
||||
import com.danyang.match.platform.activity.service.ActivityInterestService;
|
||||
import com.danyang.match.platform.activity_mutual.service.ActivityMutualConsentService;
|
||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* 活动互选确认的**行为型**回归守卫(INV-014 / INV-015)。
|
||||
*
|
||||
* <p><b>存在意义</b>:UAT 走查(2026-09-23)发现遗留端点
|
||||
* {@code POST /activities/{id}/interests/confirm} 仅校验「双向互选」就直调
|
||||
* {@code RelationshipService.confirmActivityInterest} —— 后者是**不做任何同意校验**的
|
||||
* 「建 Match」底层原语(见其实现:查无 active Match 即 createMatch)——
|
||||
* 于是**单方调用即可创建 Match 并开启会话**,绕过「双方各自显式确认」的二阶段同意。
|
||||
*
|
||||
* <p>修复后本端点与 {@code /activities/{id}/mutual/*} 共用
|
||||
* {@link ActivityMutualConsentService}:本端点只登记「我方确认」,
|
||||
* 只有双方都 accepted 才建 Match。本测试把这一接线钉死 ——
|
||||
* 若有人把直连 {@code confirmActivityInterest} 的捷径改回来,这里会红。
|
||||
*/
|
||||
class ActivityInterestConfirmConsentBehaviorTest {
|
||||
|
||||
private ActivityInterestService interestService;
|
||||
private ActivityMutualConsentService consentService;
|
||||
private ActivityInterestController controller;
|
||||
|
||||
private static final String ACTIVITY = "act-1";
|
||||
private static final String ME = "u-a";
|
||||
private static final String PARTNER = "u-b";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
interestService = mock(ActivityInterestService.class);
|
||||
consentService = mock(ActivityMutualConsentService.class);
|
||||
controller = new ActivityInterestController(interestService, consentService, mock(ActivityMapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("INV-014/015:单方调用 confirm 只登记『我方确认』,不得直接建 Match")
|
||||
void legacyConfirmOnlyRecordsMyOwnConsent() {
|
||||
when(interestService.hasMutualInterest(ME, PARTNER, ACTIVITY)).thenReturn(true);
|
||||
// 二阶段同意服务回「对方尚未确认」→ 不得建 Match
|
||||
when(consentService.confirmConnection(ME, ACTIVITY, PARTNER))
|
||||
.thenReturn(Map.of("myStatus", "accepted", "partnerStatus", "pending",
|
||||
"bothConfirmed", false, "matchCreated", false));
|
||||
|
||||
ApiResponse<Map<String, Object>> resp =
|
||||
controller.confirmInterest(new UserPrincipal(ME), ACTIVITY, Map.of("partnerId", PARTNER));
|
||||
|
||||
assertTrue(resp.isSuccess(), "调用本身应成功(我方确认已登记)");
|
||||
assertEquals(Boolean.FALSE, resp.getData().get("matchCreated"),
|
||||
"对方未确认时不得创建 Match —— 单方不可开启沟通");
|
||||
assertEquals(Boolean.FALSE, resp.getData().get("bothConfirmed"));
|
||||
// 关键接线:必经二阶段同意服务(幂等建档 + 提交我方确认)
|
||||
verify(consentService).createMutualConsent(ACTIVITY, ME, PARTNER);
|
||||
verify(consentService).confirmConnection(ME, ACTIVITY, PARTNER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("判别力:无双向互选时直接拒绝,且完全不触碰同意服务")
|
||||
void noMutualInterestIsRejectedWithoutTouchingConsent() {
|
||||
when(interestService.hasMutualInterest(ME, PARTNER, ACTIVITY)).thenReturn(false);
|
||||
|
||||
ApiResponse<Map<String, Object>> resp =
|
||||
controller.confirmInterest(new UserPrincipal(ME), ACTIVITY, Map.of("partnerId", PARTNER));
|
||||
|
||||
assertFalse(resp.isSuccess(), "无双向互选不得进入确认环节");
|
||||
verifyNoInteractions(consentService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("partnerId 为空 → 400 语义拒绝,且不触碰同意服务")
|
||||
void blankPartnerIdIsRejected() {
|
||||
ApiResponse<Map<String, Object>> resp =
|
||||
controller.confirmInterest(new UserPrincipal(ME), ACTIVITY, Map.of("partnerId", " "));
|
||||
|
||||
assertFalse(resp.isSuccess());
|
||||
verifyNoInteractions(consentService);
|
||||
verify(interestService, never()).hasMutualInterest(anyString(), anyString(), anyString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.danyang.match.platform.auth.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.danyang.match.platform.auth.provider.WechatLoginProvider;
|
||||
import com.danyang.match.platform.auth.token.JwtTokenService;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.user.entity.User;
|
||||
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* 回归守卫:刷新 Token 在 Redis 中登记的 TTL 必须与 refresh JWT 自身有效期一致
|
||||
* ({@code JwtTokenService#getRefreshExpirationMs},默认 14 天),而不是
|
||||
* {@code getExpirationMs() * 2}(4 小时)。
|
||||
*
|
||||
* <p>此前 AuthService 用 {@code getExpirationMs() * 2} 写入,导致 4h 后 Redis 记录消失、
|
||||
* 刷新即失效,用户被迫频繁重新登录。本测试钉死两处写入点(登录 / 刷新)。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthServiceRefreshTtlTest {
|
||||
|
||||
@Mock private UserMapper userMapper;
|
||||
@Mock private WechatLoginProvider wechatLoginProvider;
|
||||
@Mock private JwtTokenService jwtTokenService;
|
||||
@Mock private StringRedisTemplate redisTemplate;
|
||||
@Mock private com.danyang.match.platform.audit.mapper.AuditLogMapper auditLogMapper;
|
||||
@Mock private com.danyang.match.platform.local_eligibility.mapper.LocalEligibilityMapper localEligibilityMapper;
|
||||
@Mock private com.danyang.match.platform.capability.service.CapabilityService capabilityService;
|
||||
@Mock private com.danyang.match.platform.profile.mapper.UserProfileMapper userProfileMapper;
|
||||
@Mock private com.danyang.match.platform.review.mapper.ReviewTaskMapper reviewTaskMapper;
|
||||
@Mock private ValueOperations<String, String> valueOps;
|
||||
|
||||
@InjectMocks private AuthService authService;
|
||||
|
||||
private static final long ACCESS_MS = 7_200_000L; // 2h
|
||||
private static final long REFRESH_MS = 1_209_600_000L; // 14d
|
||||
|
||||
/** 捕获 refresh token 在 Redis 中的登记 TTL。 */
|
||||
private Duration captureRefreshTtl() {
|
||||
ArgumentCaptor<Duration> cap = ArgumentCaptor.forClass(Duration.class);
|
||||
verify(valueOps).set(eq("auth:refresh_token:u1"), anyString(), cap.capture());
|
||||
return cap.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void wechatLoginStoresRefreshTokenWithRefreshExpiration() {
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOps);
|
||||
when(wechatLoginProvider.getCodeSession("code")).thenReturn(Map.of("openid", "o1"));
|
||||
User user = new User();
|
||||
user.setId("u1");
|
||||
user.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||
user.setPhone(null);
|
||||
when(userMapper.findByWechatOpenid("o1")).thenReturn(Optional.of(user));
|
||||
when(jwtTokenService.generateAccessToken("u1", null)).thenReturn("access");
|
||||
when(jwtTokenService.generateRefreshToken("u1")).thenReturn("refresh");
|
||||
when(jwtTokenService.getRefreshExpirationMs()).thenReturn(REFRESH_MS);
|
||||
when(auditLogMapper.insert(any())).thenReturn(1);
|
||||
when(userMapper.updateById(any())).thenReturn(1);
|
||||
|
||||
authService.wechatLogin("code");
|
||||
|
||||
Duration ttl = captureRefreshTtl();
|
||||
assertEquals(Duration.ofMillis(REFRESH_MS), ttl, "登录:刷新 Token TTL 必须等于 refresh 有效期(14 天)");
|
||||
assertNotEquals(Duration.ofMillis(ACCESS_MS * 2), ttl, "回归:不得再写成 access*2(4h)导致频繁登出");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshTokenStoresRefreshTokenWithRefreshExpiration() {
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOps);
|
||||
when(jwtTokenService.validateRefreshToken("rt")).thenReturn(true);
|
||||
when(jwtTokenService.getUserIdFromRefreshToken("rt")).thenReturn("u1");
|
||||
when(redisTemplate.opsForValue().get("auth:refresh_token:u1")).thenReturn("rt");
|
||||
when(jwtTokenService.generateAccessToken("u1", null)).thenReturn("newAccess");
|
||||
when(jwtTokenService.generateRefreshToken("u1")).thenReturn("newRefresh");
|
||||
when(jwtTokenService.getRefreshExpirationMs()).thenReturn(REFRESH_MS);
|
||||
|
||||
authService.refreshToken("u1", "rt");
|
||||
|
||||
Duration ttl = captureRefreshTtl();
|
||||
assertEquals(Duration.ofMillis(REFRESH_MS), ttl, "刷新:刷新 Token TTL 必须等于 refresh 有效期(14 天)");
|
||||
assertNotEquals(Duration.ofMillis(ACCESS_MS * 2), ttl, "回归:不得再写成 access*2(4h)导致频繁登出");
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,13 @@ class MigrationValidationTest {
|
||||
// V1.0.1 配置与规则纠偏(CFG-001):V051 活体核验配置键归一
|
||||
// —— feature_flag_overrides 清理遗留键(livenessVerification.enabled / livenessEnabled),
|
||||
// 写入 canonical 键 identity.liveness.enabled=false(fail-safe 默认关闭)
|
||||
private static final int LATEST_MIGRATION = 51;
|
||||
// ZC-MM-002(A1 服务对象分配建模):V052 补齐 matchmaker 角色权限(V052 其实早于本轮,漏计);
|
||||
// V053 matchmaker_assignments 建表 + 存量回填;V054 matchmaker_leader 角色与团队分配权限
|
||||
// ZC-MM-006(T01 审计字段扩展):V055 audit_logs 补 purpose_code / service_assignment_id /
|
||||
// actor_role_snapshot / request_trace_id 四列(全可空、存量不回填、幂等)
|
||||
// ZC-MM-003(B1 例外通道立项):V056 matchmaker_contact_authorizations 受控联系授权表
|
||||
// (六态状态机 + active 部分唯一索引)
|
||||
private static final int LATEST_MIGRATION = 56;
|
||||
|
||||
private static final String MIGRATION_DIR =
|
||||
"backend/src/main/resources/db/migration/";
|
||||
|
||||
@@ -44,7 +44,8 @@ class RecommendationEligibilityPhase06Test {
|
||||
void setUp() {
|
||||
config = new MatchRuleConfigProperties();
|
||||
service = new RecommendationEngineService(profileMapper, preferenceMapper, recordMapper,
|
||||
config, redisTemplate, relationMapper, userMapper, privacyMapper, eligibilityMapper);
|
||||
config, redisTemplate, relationMapper, userMapper, privacyMapper, eligibilityMapper,
|
||||
new MatchScoringService());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.danyang.match.platform.match.service;
|
||||
|
||||
import com.danyang.match.platform.profile.entity.UserPreference;
|
||||
import com.danyang.match.platform.profile.entity.UserProfile;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 评分唯一事实源的行为型测试。
|
||||
*
|
||||
* <p>存在意义:修复「推荐恒空」(2026-09-23 UAT 走查)之前的桩 `calculateScore()=50`
|
||||
* 与阈值 60 使「满足条件的候选」也被丢弃,而既有测试只验阈值数学、从不验真实评分能达标 →
|
||||
* 缺陷长期漏网。本测试直接断言**满足条件的候选评分 ≥ 阈值**。
|
||||
*/
|
||||
class MatchScoringServiceTest {
|
||||
|
||||
private final MatchScoringService svc = new MatchScoringService();
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private static final int THRESHOLD = 60; // 与 match.default-score-threshold 默认值一致
|
||||
|
||||
private UserProfile profile(int ageYears, Integer heightCm, String region, String marital) {
|
||||
UserProfile p = new UserProfile();
|
||||
p.setBirthDate(LocalDate.now().minusYears(ageYears));
|
||||
p.setHeightCm(heightCm);
|
||||
p.setRegionCode(region);
|
||||
p.setMaritalStatus(marital);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("修复回归:完全符合条件的候选,评分必须 ≥ 阈值(不再恒 50)")
|
||||
void matchingCandidateScoresAtLeastThreshold() {
|
||||
UserPreference pref = new UserPreference();
|
||||
pref.setMinAge(25);
|
||||
pref.setMaxAge(35);
|
||||
pref.setMinHeightCm(160);
|
||||
pref.setMaxHeightCm(175);
|
||||
pref.setRegionScope(mapper.valueToTree(new String[]{"321181"}));
|
||||
pref.setMaritalStatuses(mapper.valueToTree(new String[]{"never_married"}));
|
||||
|
||||
UserProfile candidate = profile(30, 168, "321181", "never_married");
|
||||
|
||||
double score = svc.scoreDirectionally(pref, candidate);
|
||||
assertTrue(score >= THRESHOLD,
|
||||
"满足全部条件的候选必须过阈值,实际:" + score);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("反向:条件明显不符的候选,评分低于阈值(证明有判别力)")
|
||||
void nonMatchingCandidateBelowThreshold() {
|
||||
UserPreference pref = new UserPreference();
|
||||
pref.setMinAge(25);
|
||||
pref.setMaxAge(35);
|
||||
pref.setMinHeightCm(160);
|
||||
pref.setMaxHeightCm(175);
|
||||
pref.setRegionScope(mapper.valueToTree(new String[]{"321181"}));
|
||||
pref.setMaritalStatuses(mapper.valueToTree(new String[]{"never_married"}));
|
||||
|
||||
// 年龄 48(远超)、身高 150(不足)、地区 320500、离异 —— 四个维度全不符
|
||||
UserProfile candidate = profile(48, 150, "320500", "divorced");
|
||||
|
||||
double score = svc.scoreDirectionally(pref, candidate);
|
||||
assertTrue(score < THRESHOLD, "全不符的候选必须被过滤,实际:" + score);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("未设置任何条件 → 视为无约束,返回 100")
|
||||
void noCriteriaMeansNoConstraint() {
|
||||
assertEquals(100.0, svc.scoreDirectionally(new UserPreference(), profile(30, 170, "321181", "never_married")),
|
||||
0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("候选人身高缺失 → 身高维度计 0(不假定满足),且不阻断其他维度")
|
||||
void missingCandidateHeightCountsZero() {
|
||||
UserPreference pref = new UserPreference();
|
||||
pref.setMinHeightCm(170);
|
||||
pref.setMaxHeightCm(180);
|
||||
UserProfile candidate = profile(30, null, "321181", "never_married");
|
||||
|
||||
double score = svc.scoreDirectionally(pref, candidate);
|
||||
assertEquals(0.0, score, 0.001, "唯一条件是身高而资料缺失 → 0 分");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("INV-001:双向 Required 任一不满足即否")
|
||||
void bidirectionalRequiredEnforced() {
|
||||
UserPreference myPref = new UserPreference();
|
||||
myPref.setAgePriority("required");
|
||||
myPref.setMinAge(25);
|
||||
myPref.setMaxAge(30);
|
||||
|
||||
UserPreference targetPref = new UserPreference(); // 无 Required
|
||||
|
||||
UserProfile me = profile(30, 175, "321181", "never_married");
|
||||
UserProfile inRange = profile(28, 170, "321181", "never_married");
|
||||
UserProfile outOfRange = profile(35, 170, "321181", "never_married");
|
||||
|
||||
assertTrue(svc.bidirectionalRequiredSatisfied(myPref, me, targetPref, inRange));
|
||||
assertFalse(svc.bidirectionalRequiredSatisfied(myPref, me, targetPref, outOfRange));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("推荐理由基于实际达成维度,且非空")
|
||||
void reasonsReflectMatchedDimensions() {
|
||||
UserPreference pref = new UserPreference();
|
||||
pref.setMinAge(25);
|
||||
pref.setMaxAge(35);
|
||||
var reasons = svc.reasons(pref, profile(30, 170, "321181", "never_married"));
|
||||
assertFalse(reasons.isEmpty());
|
||||
assertTrue(reasons.stream().anyMatch(r -> r.contains("年龄")), "应包含年龄维度理由:" + reasons);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.danyang.match.platform.match.service;
|
||||
|
||||
import com.danyang.match.platform.local_eligibility.mapper.LocalEligibilityMapper;
|
||||
import com.danyang.match.platform.match.config.MatchRuleConfigProperties;
|
||||
import com.danyang.match.platform.match.dto.RecommendationCandidateDTO;
|
||||
import com.danyang.match.platform.match.mapper.RecommendationRecordMapper;
|
||||
import com.danyang.match.platform.match.mapper.UserRelationMapper;
|
||||
import com.danyang.match.platform.profile.entity.UserPreference;
|
||||
import com.danyang.match.platform.profile.entity.UserProfile;
|
||||
import com.danyang.match.platform.profile.mapper.UserPreferenceMapper;
|
||||
import com.danyang.match.platform.profile.mapper.UserPrivacySettingsMapper;
|
||||
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.user.entity.User;
|
||||
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 推荐链路的<b>行为型</b>回归守卫。
|
||||
*
|
||||
* <p><b>存在意义</b>:UAT 走查(2026-09-23)在本机真实栈实测
|
||||
* {@code GET /recommendations} 恒返回 {@code {"data":[]}}。根因是评分桩
|
||||
* {@code calculateScore()=50} 而阈值默认 60({@code 50 < 60} 恒真)→ 所有候选被丢弃。
|
||||
* 该缺陷逃过了 757 个后端用例 + 65 个 E2E + 22 个 UI 守卫,因为
|
||||
* <b>没有任何用例断言「推荐非空」</b>(E2E 零推荐用例)。
|
||||
*
|
||||
* <p>本测试在<b>引擎层</b>(候选池查询 → 双向 Required → 评分 → 阈值过滤 → 排序 → 落库)
|
||||
* 断言「存在合格候选时必须产出非空推荐」,并配一条反向用例证明其有判别力。
|
||||
* 这是此类「恒空」缺陷的直接防线 —— 桩式/纯配置断言抓不到它。
|
||||
*/
|
||||
class RecommendationEngineServiceBehaviorTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String ME = "u-me";
|
||||
private static final String CANDIDATE = "u-cand";
|
||||
|
||||
private UserProfileMapper userProfileMapper;
|
||||
private UserPreferenceMapper preferenceMapper;
|
||||
private RecommendationRecordMapper recommendationRecordMapper;
|
||||
private MatchRuleConfigProperties matchConfig;
|
||||
private StringRedisTemplate redisTemplate;
|
||||
private ValueOperations<String, String> valueOps;
|
||||
private UserRelationMapper relationMapper;
|
||||
private UserMapper userMapper;
|
||||
private UserPrivacySettingsMapper privacySettingsMapper;
|
||||
private LocalEligibilityMapper localEligibilityMapper;
|
||||
|
||||
private RecommendationEngineService engine;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
userProfileMapper = mock(UserProfileMapper.class);
|
||||
preferenceMapper = mock(UserPreferenceMapper.class);
|
||||
recommendationRecordMapper = mock(RecommendationRecordMapper.class);
|
||||
matchConfig = mock(MatchRuleConfigProperties.class);
|
||||
redisTemplate = mock(StringRedisTemplate.class);
|
||||
valueOps = mock(ValueOperations.class);
|
||||
relationMapper = mock(UserRelationMapper.class);
|
||||
userMapper = mock(UserMapper.class);
|
||||
privacySettingsMapper = mock(UserPrivacySettingsMapper.class);
|
||||
localEligibilityMapper = mock(LocalEligibilityMapper.class);
|
||||
|
||||
// 用**真实**评分实现(纯函数、无依赖)→ 端到端证明「真实评分能让推荐非空」。
|
||||
// 若用 mock 掉评分,本测试就退化成「只验接线」,无法守住「评分恒 50」这类回归。
|
||||
MatchScoringService scoring = new MatchScoringService();
|
||||
|
||||
engine = new RecommendationEngineService(
|
||||
userProfileMapper, preferenceMapper, recommendationRecordMapper,
|
||||
matchConfig, redisTemplate, relationMapper, userMapper,
|
||||
privacySettingsMapper, localEligibilityMapper, scoring);
|
||||
|
||||
// —— 匹配规则配置(与 application-dev.yml 默认一致)——
|
||||
when(matchConfig.getDefaultDailyLimit()).thenReturn(6);
|
||||
when(matchConfig.getDefaultScoreThreshold()).thenReturn(60);
|
||||
when(matchConfig.getDefaultCooldownDays()).thenReturn(180);
|
||||
when(matchConfig.getRuleVersion()).thenReturn(1);
|
||||
when(matchConfig.isLocalEligibilityRequired()).thenReturn(false);
|
||||
|
||||
// —— Redis:缓存未命中 ——
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOps);
|
||||
when(valueOps.get(anyString())).thenReturn(null);
|
||||
|
||||
// —— 双方账号均正常、可被推荐、无隐私限制 ——
|
||||
when(userMapper.findById(ME)).thenReturn(Optional.of(user(ME)));
|
||||
when(userMapper.findById(CANDIDATE)).thenReturn(Optional.of(user(CANDIDATE)));
|
||||
when(privacySettingsMapper.findByUserId(anyString())).thenReturn(Optional.empty());
|
||||
|
||||
// —— 资料 ——
|
||||
when(userProfileMapper.findByUserId(ME)).thenReturn(Optional.of(myProfile()));
|
||||
when(userProfileMapper.findByUserId(CANDIDATE)).thenReturn(Optional.of(candidateProfile()));
|
||||
when(userProfileMapper.selectList(any())).thenReturn(List.of(candidateProfile()));
|
||||
|
||||
// —— 择偶条件:自己设了条件;候选人未设(方向 B→A 不受约束)——
|
||||
when(preferenceMapper.findByUserId(ME)).thenReturn(Optional.of(myPreference()));
|
||||
when(preferenceMapper.findByUserId(CANDIDATE)).thenReturn(Optional.of(new UserPreference()));
|
||||
|
||||
// —— 无历史推荐 / 无 Pass / 无拉黑 ——
|
||||
when(recommendationRecordMapper.findRecentByUserId(anyString(), any())).thenReturn(List.of());
|
||||
when(relationMapper.findBlockedByUser(anyString())).thenReturn(List.of());
|
||||
when(relationMapper.findByRelation(anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("回归守卫:存在合格候选 → 推荐必须非空(此前评分桩 50<60 导致恒空)")
|
||||
void recommendationsAreNotEmptyWhenEligibleCandidateExists() {
|
||||
List<RecommendationCandidateDTO> result = engine.getDailyRecommendations(ME);
|
||||
|
||||
assertFalse(result.isEmpty(),
|
||||
"存在满足条件的候选人时,推荐不得为空 —— 这正是 UAT 实测暴露的缺陷");
|
||||
assertEquals(CANDIDATE, result.get(0).getUserId());
|
||||
assertNotNull(result.get(0).getRecommendationReasons());
|
||||
assertFalse(result.get(0).getRecommendationReasons().isEmpty(), "应带中文推荐理由");
|
||||
assertEquals("high", result.get(0).getRecommendationLevel(),
|
||||
"完全匹配的候选应落在 high 档(评分 100)");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("判别力:候选各维度均不符 → 被阈值过滤,推荐为空")
|
||||
void ineligibleCandidateIsFilteredOut() {
|
||||
// 候选人年龄 48 / 身高 150 / 地区 320500 / 离异 —— 与择偶条件全不符
|
||||
UserProfile bad = candidateProfile();
|
||||
bad.setBirthDate(LocalDate.now().minusYears(48));
|
||||
bad.setHeightCm(150);
|
||||
bad.setRegionCode("320500");
|
||||
bad.setMaritalStatus("divorced");
|
||||
when(userProfileMapper.findByUserId(CANDIDATE)).thenReturn(Optional.of(bad));
|
||||
when(userProfileMapper.selectList(any())).thenReturn(List.of(bad));
|
||||
|
||||
List<RecommendationCandidateDTO> result = engine.getDailyRecommendations(ME);
|
||||
|
||||
assertTrue(result.isEmpty(), "全维度不符的候选必须被阈值过滤(证明评分确有判别力)");
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private User user(String id) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||
u.setRelationshipStatus(Constants.RELATIONSHIP_STATUS_SEARCHING);
|
||||
u.setRecommendationEnabled(true);
|
||||
return u;
|
||||
}
|
||||
|
||||
private UserProfile myProfile() {
|
||||
UserProfile p = new UserProfile();
|
||||
p.setUserId(ME);
|
||||
p.setGender("male");
|
||||
p.setProfileStatus(Constants.PROFILE_STATUS_APPROVED);
|
||||
p.setBirthDate(LocalDate.now().minusYears(33));
|
||||
p.setHeightCm(175);
|
||||
p.setRegionCode("321181");
|
||||
p.setMaritalStatus("never_married");
|
||||
return p;
|
||||
}
|
||||
|
||||
private UserProfile candidateProfile() {
|
||||
UserProfile p = new UserProfile();
|
||||
p.setUserId(CANDIDATE);
|
||||
p.setGender("female");
|
||||
p.setProfileStatus(Constants.PROFILE_STATUS_APPROVED);
|
||||
p.setBirthDate(LocalDate.now().minusYears(30));
|
||||
p.setHeightCm(168);
|
||||
p.setRegionCode("321181");
|
||||
p.setMaritalStatus("never_married");
|
||||
return p;
|
||||
}
|
||||
|
||||
/** 四个维度均设条件,且默认权重(age .15 / height .05 / region .20 / marital .10)。 */
|
||||
private UserPreference myPreference() {
|
||||
UserPreference p = new UserPreference();
|
||||
p.setMinAge(25);
|
||||
p.setMaxAge(35);
|
||||
p.setMinHeightCm(160);
|
||||
p.setMaxHeightCm(175);
|
||||
p.setRegionScope(MAPPER.valueToTree(new String[]{"321181"}));
|
||||
p.setMaritalStatuses(MAPPER.valueToTree(new String[]{"never_married"}));
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
package com.danyang.match.platform.matchmaker;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.danyang.match.platform.activity.entity.ActivityRegistration;
|
||||
import com.danyang.match.platform.activity.mapper.ActivityRegistrationMapper;
|
||||
import com.danyang.match.platform.auth.token.JwtTokenService;
|
||||
import com.danyang.match.platform.auth.token.TokenBlacklistService;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerRecommendation;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerAssignmentMapper;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerRecommendationMapper;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||
import com.danyang.match.platform.matchmaker.service.MatchmakerServiceService;
|
||||
import com.danyang.match.platform.notification.entity.Notification;
|
||||
import com.danyang.match.platform.notification.mapper.NotificationMapper;
|
||||
import com.danyang.match.platform.referral.service.ReferralService;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.user.entity.User;
|
||||
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||
import com.danyang.match.platform.verification.mapper.UserIdentityMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* ZC-MM-004(禁止代替用户决定复核)+ MM-CONTACT-001 行为锁定
|
||||
* ({@code @SpringBootTest} 走真实安全过滤器链,沿用 MatchmakerReferralPhase13Test 数据构造范式)。
|
||||
*
|
||||
* <p>锁定四条行为不变量(架构师设计 T02):
|
||||
* <ol>
|
||||
* <li><b>MM-ACTION-001 强化(负向)</b>:operator 主体 token 打用户专属决定端点
|
||||
* (推荐 accept / pass、转介 confirm)→ 认证层 403
|
||||
* (SecurityConfig 兜底 {@code hasRole("USER")}:运营身份根本进不到 Controller,
|
||||
* SecurityPathCoverageTest 已机械锁定该兜底不得退回 authenticated()),
|
||||
* 且 recommendation / registration 状态零变化 —— 「红娘不能替用户 Like/Pass/确认转介」。</li>
|
||||
* <li><b>MM-ACTION-002</b>:会话开启端点(POST /conversations/from-match/{matchId})同为
|
||||
* UserPrincipal 路径 → operator token 403(match 的产生同样只在用户 Like 路径,
|
||||
* 无 operator 触达面)。</li>
|
||||
* <li><b>MM-ACTION-003 / must-confirm 语义</b>:红娘创建转介 → 响应
|
||||
* needsUserConfirmation=true、库中 userConfirmedAt=null、status 停留 pending;
|
||||
* 红娘侧 recommend / followup / complete 动作不改变用户确认状态 ——
|
||||
* 「转介代建 = 代填草稿、用户确认」语义被永久锁定。</li>
|
||||
* <li><b>MM-CONTACT-001(正向)</b>:红娘对本人分配对象创建推荐/转介 → notifications 表
|
||||
* 落平台内服务通知(type=matchmaker),title/body 不含手机号/微信号模式;
|
||||
* 通知收件面只有 C 端用户(无 operator 收件行)—— 平台内联系经通知中转,
|
||||
* 红娘与用户之间不存在直连联系方式交换。</li>
|
||||
* </ol>
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@Transactional
|
||||
@AutoConfigureMockMvc
|
||||
class MatchmakerActionGuardTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private JwtTokenService jwtTokenService;
|
||||
/** 测试环境无 Redis:黑名单查询打桩为"未拉黑"(ChatPhase09IntegrationTest 同款) */
|
||||
@MockBean private TokenBlacklistService tokenBlacklistService;
|
||||
/**
|
||||
* ZC-MM-006 / T02 起由真实 DB 路径接管权限装载(schema-h2 已补权限四表),
|
||||
* 此处打桩仅为兼容既有断言口径(本测试只依赖身份类型 403,不依赖具体权限集)。
|
||||
*/
|
||||
@MockBean private com.danyang.match.platform.permission.service.PermissionService permissionService;
|
||||
@Autowired private com.danyang.match.platform.permission.mapper.OperatorMapper operatorMapper;
|
||||
@Autowired private MatchmakerServiceMapper matchmakerServiceMapper;
|
||||
@Autowired private MatchmakerAssignmentMapper matchmakerAssignmentMapper;
|
||||
@Autowired private MatchmakerRecommendationMapper recommendationMapper;
|
||||
@Autowired private ActivityRegistrationMapper activityRegistrationMapper;
|
||||
@Autowired private NotificationMapper notificationMapper;
|
||||
@Autowired private UserMapper userMapper;
|
||||
@Autowired private com.danyang.match.platform.profile.mapper.UserProfileMapper userProfileMapper;
|
||||
@Autowired private UserIdentityMapper userIdentityMapper;
|
||||
@Autowired private MatchmakerServiceService matchmakerServiceService;
|
||||
@Autowired private ReferralService referralService;
|
||||
|
||||
private static final String MATCHMAKER_OWNER = "op-ag-owner";
|
||||
|
||||
private String user;
|
||||
private String target;
|
||||
private String serviceId;
|
||||
private String operatorToken;
|
||||
|
||||
/** 手机号模式(中国大陆 11 位) */
|
||||
private static final Pattern PHONE_PATTERN = Pattern.compile("1[3-9]\\d{9}");
|
||||
/** 微信号/微信引导词模式 */
|
||||
private static final List<String> WECHAT_TOKENS = List.of("wechat", "weixin", "微信", "vx", "加v", "v信");
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
user = createUser("ag-user");
|
||||
target = createUser("ag-target");
|
||||
// 一条归属 MATCHMAKER_OWNER 的红娘服务(assigned),并补生效分配(E1 纯判定器口径)
|
||||
serviceId = createService(user, MATCHMAKER_OWNER, Constants.MATCHMAKER_STATUS_ASSIGNED);
|
||||
MatchmakerAssignment assignment = new MatchmakerAssignment();
|
||||
assignment.setUserId(user);
|
||||
assignment.setMatchmakerOperatorId(MATCHMAKER_OWNER);
|
||||
assignment.setServiceId(serviceId);
|
||||
assignment.setAssignedBy(MATCHMAKER_OWNER);
|
||||
assignment.setAssignmentScope(Constants.ASSIGNMENT_SCOPE_PRIMARY);
|
||||
assignment.setAssignmentReason("003/004 守卫前置分配");
|
||||
assignment.setStatus(Constants.ASSIGNMENT_STATUS_ACTIVE);
|
||||
assignment.setAssignedAt(Instant.now());
|
||||
matchmakerAssignmentMapper.insert(assignment);
|
||||
|
||||
// operator token:type=operator_access → JwtAuthFilter 授 ROLE_OPERATOR
|
||||
// ZC-MM-006 / T02:JwtAuthFilter 实时查 operators.status,须为 token subject 落一条 active 运营行
|
||||
com.danyang.match.platform.permission.entity.Operator op =
|
||||
new com.danyang.match.platform.permission.entity.Operator();
|
||||
op.setId(MATCHMAKER_OWNER);
|
||||
op.setName("003/004 守卫红娘");
|
||||
op.setUsername("ag_mm_owner_" + System.nanoTime());
|
||||
op.setPasswordHash("test-hash");
|
||||
op.setStatus("active");
|
||||
operatorMapper.insert(op);
|
||||
when(permissionService.getPermissions(anyString())).thenReturn(List.of());
|
||||
operatorToken = jwtTokenService.generateOperatorToken(MATCHMAKER_OWNER, null);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
// ==================== 数据构造(Phase13 范式) ====================
|
||||
|
||||
/** 基础资格满足的用户:正常账号 + 实名 + 资料通过(RelationService.like 路径可走) */
|
||||
private String createUser(String tag) {
|
||||
User u = new User();
|
||||
u.setWechatOpenid("ag_" + tag + "_" + System.nanoTime());
|
||||
u.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||
u.setRelationshipStatus(Constants.RELATIONSHIP_STATUS_SEARCHING);
|
||||
u.setRecommendationEnabled(true);
|
||||
userMapper.insert(u);
|
||||
|
||||
var profile = new com.danyang.match.platform.profile.entity.UserProfile();
|
||||
profile.setUserId(u.getId());
|
||||
profile.setDisplayName(tag);
|
||||
profile.setProfileStatus(Constants.PROFILE_STATUS_APPROVED);
|
||||
userProfileMapper.insert(profile);
|
||||
|
||||
var identity = new com.danyang.match.platform.verification.entity.UserIdentity();
|
||||
identity.setUserId(u.getId());
|
||||
identity.setVerificationStatus(Constants.VERIFICATION_STATUS_VERIFIED);
|
||||
userIdentityMapper.insert(identity);
|
||||
return u.getId();
|
||||
}
|
||||
|
||||
private String createService(String userId, String operatorId, String status) {
|
||||
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
||||
svc.setId(UUID.randomUUID().toString());
|
||||
svc.setUserId(userId);
|
||||
svc.setServiceType(Constants.MATCHMAKER_SERVICE_TYPE_RECOMMEND_PARTNER);
|
||||
svc.setStatus(status);
|
||||
svc.setAssignedOperatorId(operatorId);
|
||||
matchmakerServiceMapper.insert(svc);
|
||||
return svc.getId();
|
||||
}
|
||||
|
||||
private MatchmakerRecommendation insertRecommendation(String recUser, String recTarget) {
|
||||
MatchmakerRecommendation rec = new MatchmakerRecommendation();
|
||||
rec.setId(UUID.randomUUID().toString());
|
||||
rec.setServiceId(serviceId);
|
||||
rec.setUserId(recUser);
|
||||
rec.setTargetUserId(recTarget);
|
||||
rec.setOperatorId(MATCHMAKER_OWNER);
|
||||
rec.setReason("004 守卫测试推荐");
|
||||
rec.setStatus(Constants.RECOMMENDATION_STATUS_PENDING_VIEW);
|
||||
recommendationMapper.insert(rec);
|
||||
return rec;
|
||||
}
|
||||
|
||||
private ActivityRegistration insertReferralRegistration(String regUser, String activityId) {
|
||||
ActivityRegistration reg = new ActivityRegistration();
|
||||
reg.setId(UUID.randomUUID().toString());
|
||||
reg.setActivityId(activityId);
|
||||
reg.setUserId(regUser);
|
||||
reg.setStatus(Constants.REGISTRATION_STATUS_PENDING);
|
||||
reg.setSource(Constants.REFERRAL_SOURCE_MATCHMAKER_REFERRAL);
|
||||
reg.setRequestSource(Constants.REFERRAL_SOURCE_MATCHMAKER_REFERRAL);
|
||||
reg.setCreatedByOperatorId(MATCHMAKER_OWNER);
|
||||
reg.setCreatedAt(Instant.now());
|
||||
activityRegistrationMapper.insert(reg);
|
||||
return reg;
|
||||
}
|
||||
|
||||
// ==================== MM-ACTION-001:红娘不能替用户做 Like/Pass/确认决定 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-ACTION-001(负向): operator token 打推荐 accept → 403,推荐状态零变化")
|
||||
void operatorCannotAcceptRecommendationOnBehalfOfUser() throws Exception {
|
||||
MatchmakerRecommendation rec = insertRecommendation(user, target);
|
||||
|
||||
mockMvc.perform(post("/matchmaker/recommendations/{id}/accept", rec.getId())
|
||||
.header("Authorization", "Bearer " + operatorToken))
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
MatchmakerRecommendation after = recommendationMapper.selectById(rec.getId());
|
||||
assertEquals(Constants.RECOMMENDATION_STATUS_PENDING_VIEW, after.getStatus(),
|
||||
"越权 accept 被认证层 403 拒绝后,推荐状态必须零变化");
|
||||
assertNull(after.getRespondedAt(), "越权 accept 不得写入 respondedAt");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-ACTION-001(负向): operator token 打推荐 pass → 403,推荐状态零变化")
|
||||
void operatorCannotPassRecommendationOnBehalfOfUser() throws Exception {
|
||||
MatchmakerRecommendation rec = insertRecommendation(user, target);
|
||||
|
||||
mockMvc.perform(post("/matchmaker/recommendations/{id}/pass", rec.getId())
|
||||
.header("Authorization", "Bearer " + operatorToken))
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
MatchmakerRecommendation after = recommendationMapper.selectById(rec.getId());
|
||||
assertEquals(Constants.RECOMMENDATION_STATUS_PENDING_VIEW, after.getStatus(),
|
||||
"越权 pass 被拒绝后,推荐状态必须零变化(仍 pending_view)");
|
||||
assertNull(after.getRespondedAt(), "越权 pass 不得写入 respondedAt");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-ACTION-001(负向): operator token 打转介 confirm → 403,用户确认状态零变化")
|
||||
void operatorCannotConfirmReferralOnBehalfOfUser() throws Exception {
|
||||
ActivityRegistration reg = insertReferralRegistration(user, "act-ag-001");
|
||||
|
||||
mockMvc.perform(post("/referrals/{id}/confirm", reg.getId())
|
||||
.header("Authorization", "Bearer " + operatorToken)
|
||||
.contentType("application/json")
|
||||
.content("{\"targetType\":\"activity\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
ActivityRegistration after = activityRegistrationMapper.selectById(reg.getId());
|
||||
assertNull(after.getUserConfirmedAt(),
|
||||
"越权 confirm 被拒绝后,userConfirmedAt 必须仍为 null(用户决定权)");
|
||||
assertEquals(Constants.REGISTRATION_STATUS_PENDING, after.getStatus(),
|
||||
"越权 confirm 后报名状态必须停留 pending");
|
||||
}
|
||||
|
||||
// ==================== MM-ACTION-002:会话/关系开启无 operator 触达面 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-ACTION-002(负向): operator token 打会话开启端点 → 403(match/conversation 仅用户路径)")
|
||||
void operatorCannotOpenConversationFromMatch() throws Exception {
|
||||
// 认证层即拒绝(hasRole("USER")),无需真实 match 存在
|
||||
mockMvc.perform(post("/conversations/from-match/{matchId}", "no-such-match")
|
||||
.header("Authorization", "Bearer " + operatorToken))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
// ==================== MM-ACTION-003:must-confirm 语义锁定 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-ACTION-003: 转介代建=代填草稿(needsUserConfirmation=true、userConfirmedAt=null);红娘后续动作不改变确认状态")
|
||||
void referralCreationStaysPendingUntilUserConfirms() {
|
||||
// 红娘创建转介(本人分配对象)
|
||||
Map<String, Object> result = referralService.referToActivity(
|
||||
MATCHMAKER_OWNER, user, "act-ag-002", "紧急联系人", "enc-phone");
|
||||
|
||||
// must-confirm 语义:响应标记待确认,库中确认字段为空、状态停留 pending
|
||||
assertEquals(Boolean.TRUE, result.get("needsUserConfirmation"),
|
||||
"红娘创建转介必须标记 needsUserConfirmation=true(不替用户完成报名)");
|
||||
String regId = (String) result.get("registrationId");
|
||||
ActivityRegistration reg = activityRegistrationMapper.selectById(regId);
|
||||
assertNotNull(reg, "转介必须真实落库");
|
||||
assertNull(reg.getUserConfirmedAt(), "创建时 userConfirmedAt 必须为 null");
|
||||
assertEquals(Constants.REGISTRATION_STATUS_PENDING, reg.getStatus(),
|
||||
"创建时报名状态必须停留 pending");
|
||||
|
||||
// 红娘侧后续动作:recommend / followup / complete —— 均不得改变用户确认状态
|
||||
matchmakerServiceService.recommendPartner(serviceId, MATCHMAKER_OWNER, target, "合适人选");
|
||||
matchmakerServiceService.addFollowup(serviceId, MATCHMAKER_OWNER, "note", "003 守卫跟进", null);
|
||||
|
||||
MatchmakerServiceRecord svc = matchmakerServiceMapper.selectById(serviceId);
|
||||
svc.setStatus(Constants.MATCHMAKER_STATUS_IN_SERVICE);
|
||||
matchmakerServiceMapper.updateById(svc);
|
||||
matchmakerServiceService.completeService(serviceId, MATCHMAKER_OWNER);
|
||||
|
||||
ActivityRegistration after = activityRegistrationMapper.selectById(regId);
|
||||
assertNull(after.getUserConfirmedAt(),
|
||||
"recommend/followup/complete 红娘侧动作不得代替用户确认(userConfirmedAt 必须仍为 null)");
|
||||
assertEquals(Constants.REGISTRATION_STATUS_PENDING, after.getStatus(),
|
||||
"红娘侧动作不得推动报名状态(必须停留 pending 等待用户确认)");
|
||||
}
|
||||
|
||||
// ==================== MM-CONTACT-001:平台内联系 = 通知中转,无联系方式交换 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-CONTACT-001(正向): 推荐/转介经平台通知触达用户,文案无手机号/微信号模式,收件面仅用户")
|
||||
void platformNotificationsCarryNoContactPatternsAndOnlyTargetUsers() {
|
||||
// 推荐路径:recommendPartner → sendAsync(type=matchmaker, businessType=matchmaker_recommendation)
|
||||
matchmakerServiceService.recommendPartner(serviceId, MATCHMAKER_OWNER, target, "003 正向推荐");
|
||||
// 转介路径:referToServiceStation → sendMatchmakerReferralCreated(type=matchmaker, businessType=service_station)
|
||||
referralService.referToServiceStation(MATCHMAKER_OWNER, user, "loc-ag-001",
|
||||
"counselor_consultation", null, "备注");
|
||||
|
||||
List<Notification> notes = notificationMapper.selectList(new LambdaQueryWrapper<Notification>()
|
||||
.eq(Notification::getUserId, user)
|
||||
.eq(Notification::getType, Constants.NOTIFICATION_TYPE_MATCHMAKER));
|
||||
assertFalse(notes.isEmpty(), "推荐/转介必须为用户落平台内服务通知(type=matchmaker)");
|
||||
|
||||
for (Notification note : notes) {
|
||||
String title = note.getTitle() == null ? "" : note.getTitle();
|
||||
String content = note.getContent() == null ? "" : note.getContent();
|
||||
assertFalse(PHONE_PATTERN.matcher(title).find(),
|
||||
"通知标题不得含手机号模式: " + title);
|
||||
assertFalse(PHONE_PATTERN.matcher(content).find(),
|
||||
"通知正文不得含手机号模式: " + content);
|
||||
for (String token : WECHAT_TOKENS) {
|
||||
assertFalse(title.toLowerCase().contains(token),
|
||||
"通知标题不得含微信引导词「" + token + "」: " + title);
|
||||
assertFalse(content.toLowerCase().contains(token),
|
||||
"通知正文不得含微信引导词「" + token + "」: " + content);
|
||||
}
|
||||
}
|
||||
|
||||
// 负向佐证:通知收件面只有 C 端用户 —— 红娘 operatorId 不在 notification 收件面
|
||||
long operatorInbox = notificationMapper.selectCount(new LambdaQueryWrapper<Notification>()
|
||||
.eq(Notification::getUserId, MATCHMAKER_OWNER));
|
||||
assertEquals(0L, operatorInbox,
|
||||
"红娘不得成为通知收件人(联系方式交换无 operator 侧触达面)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
package com.danyang.match.platform.matchmaker;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||
import com.danyang.match.platform.matchmaker.controller.MatchmakerAssignmentController;
|
||||
import com.danyang.match.platform.matchmaker.controller.MatchmakerOperatorController;
|
||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerAssignmentMapper;
|
||||
import com.danyang.match.platform.matchmaker.service.MatchmakerAssignmentService;
|
||||
import com.danyang.match.platform.matchmaker.service.MatchmakerServiceService;
|
||||
import com.danyang.match.platform.matchmaker.service.ServiceAssignmentPolicy;
|
||||
import com.danyang.match.platform.permission.entity.Operator;
|
||||
import com.danyang.match.platform.permission.mapper.OperatorMapper;
|
||||
import com.danyang.match.platform.shared.constant.Constants;
|
||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||
import com.danyang.match.platform.user.entity.User;
|
||||
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* ZC-MM-002(A1 服务对象分配建模)验收测试 —— 真实 H2 数据构造。
|
||||
*
|
||||
* <p>覆盖:
|
||||
* <ul>
|
||||
* <li>MM-AUTH-001:红娘对本人有效分配对象 canAccessUser=true,GET /assignments/my 含该对象;</li>
|
||||
* <li>MM-AUTH-002(负向):访问未分配用户 → DataScopeGuard 拒绝 + DATA_SCOPE_DENIED 审计;</li>
|
||||
* <li>MM-AUTH-003(负向):访问他人(红娘D)分配对象 → 拒绝 + 审计;</li>
|
||||
* <li>MM-AUTH-004(负向):POST /services/{id}/claim → 404(D3:claim 端点已删除);</li>
|
||||
* <li>MM-AUDIT-001:create/transfer/revoke/end 各产生对应 action 审计且 operatorId=操作者;</li>
|
||||
* <li>MM-LIFECYCLE-001:end/revoke 后 canAccessUser=false;expires_at 届满惰性 expired;</li>
|
||||
* <li>负向:组长跨组织分配 → 403 + 审计;普通红娘调 /pending → 403 + 审计。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@Transactional
|
||||
class MatchmakerAssignmentA1Test {
|
||||
|
||||
@Autowired private MatchmakerAssignmentService assignmentService;
|
||||
@Autowired private ServiceAssignmentPolicy assignmentPolicy;
|
||||
@Autowired private MatchmakerAssignmentMapper assignmentMapper;
|
||||
@Autowired private OperatorMapper operatorMapper;
|
||||
@Autowired private UserMapper userMapper;
|
||||
@Autowired private AuditLogMapper auditLogMapper;
|
||||
@Autowired private MatchmakerAssignmentController assignmentController;
|
||||
@Autowired private MatchmakerOperatorController operatorController;
|
||||
|
||||
private String leaderA; // 组长,org X
|
||||
private String mmB; // 红娘,org X
|
||||
private String mmC; // 红娘,org Y
|
||||
private String mmD; // 红娘,org X
|
||||
private String user1; // B 的服务对象
|
||||
private String user2; // 无人分配
|
||||
private String user3; // D 的服务对象
|
||||
|
||||
private static final String ORG_X = "11111111-1111-1111-1111-111111111111";
|
||||
private static final String ORG_Y = "22222222-2222-2222-2222-222222222222";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
leaderA = createOperator("组长A", ORG_X);
|
||||
mmB = createOperator("红娘B", ORG_X);
|
||||
mmC = createOperator("红娘C", ORG_Y);
|
||||
mmD = createOperator("红娘D", ORG_X);
|
||||
user1 = createUser("a1-user1");
|
||||
user2 = createUser("a1-user2");
|
||||
user3 = createUser("a1-user3");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
// ==================== 数据构造 ====================
|
||||
|
||||
private String createOperator(String name, String organizationId) {
|
||||
Operator op = new Operator();
|
||||
op.setName(name);
|
||||
op.setOrganizationId(organizationId);
|
||||
op.setUsername("a1_" + name + "_" + System.nanoTime());
|
||||
op.setPasswordHash("test-hash");
|
||||
op.setStatus("active");
|
||||
operatorMapper.insert(op);
|
||||
return op.getId();
|
||||
}
|
||||
|
||||
private String createUser(String tag) {
|
||||
User u = new User();
|
||||
u.setWechatOpenid("a1_" + tag + "_" + System.nanoTime());
|
||||
u.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||
userMapper.insert(u);
|
||||
return u.getId();
|
||||
}
|
||||
|
||||
/** 以指定操作者身份 + 权限集设置 SecurityContext(方法级 @PreAuthorize 据此判定)。 */
|
||||
private void authenticate(String operatorId, String... permissions) {
|
||||
Set<String> permSet = Set.of(permissions);
|
||||
var authorities = Stream.concat(
|
||||
Stream.of(new SimpleGrantedAuthority("ROLE_OPERATOR")),
|
||||
permSet.stream().map(SimpleGrantedAuthority::new)).toList();
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
UsernamePasswordAuthenticationToken.authenticated(
|
||||
new OperatorPrincipal(operatorId, permSet), null, authorities));
|
||||
}
|
||||
|
||||
private long countAudits(String action, String operatorId) {
|
||||
return auditLogMapper.selectCount(new LambdaQueryWrapper<AuditLog>()
|
||||
.eq(AuditLog::getAction, action)
|
||||
.eq(operatorId != null, AuditLog::getOperatorId, operatorId));
|
||||
}
|
||||
|
||||
// ==================== MM-AUTH-001 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-AUTH-001: 红娘B 对本人有效分配对象 canAccessUser=true,GET /assignments/my 含该对象")
|
||||
void mmAuth001_matchmakerAccessesOwnAssignedUser() {
|
||||
// 组长A(同组织 X,team.assign 路径)创建 B → user1 分配
|
||||
MatchmakerAssignment created = assignmentService.create(
|
||||
leaderA, false, user1, mmB, null, "同一社区,就近服务", null);
|
||||
assertNotNull(created.getId());
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_ACTIVE, created.getStatus());
|
||||
assertEquals(Constants.ASSIGNMENT_SCOPE_PRIMARY, created.getAssignmentScope());
|
||||
|
||||
assertTrue(assignmentPolicy.canAccessUser(mmB, user1),
|
||||
"红娘B 必须能访问其名下生效分配的服务对象");
|
||||
|
||||
// GET /assignments/my(matchmaker.service 权限)包含该对象
|
||||
authenticate(mmB, "matchmaker.view", "matchmaker.service");
|
||||
var result = assignmentController.my(new OperatorPrincipal(mmB,
|
||||
Set.of("matchmaker.view", "matchmaker.service")));
|
||||
assertTrue(result.isSuccess());
|
||||
List<Map<String, Object>> data = result.getData();
|
||||
assertNotNull(data);
|
||||
assertEquals(1, data.size(), "GET /my 应恰好返回红娘B 名下的生效分配");
|
||||
assertEquals(user1, data.get(0).get("userId"));
|
||||
}
|
||||
|
||||
// ==================== MM-AUTH-002 / 003 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-AUTH-002(负向): B 访问未分配用户 → DataScopeGuard 拒绝 + DATA_SCOPE_DENIED 审计")
|
||||
void mmAuth002_accessUnassignedUserDeniedAndAudited() {
|
||||
assertFalse(assignmentPolicy.canAccessUser(mmB, user2));
|
||||
|
||||
long before = countAudits("DATA_SCOPE_DENIED", mmB);
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> assignmentPolicy.assertActiveAssignment(mmB, user2, "matchmaker_user"),
|
||||
"未持有分配的红娘访问用户必须被拒绝");
|
||||
long after = countAudits("DATA_SCOPE_DENIED", mmB);
|
||||
assertEquals(before + 1, after, "拒绝必须落一条 DATA_SCOPE_DENIED 审计行");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-AUTH-003(负向): B 访问他人(红娘D)分配对象 → 拒绝 + 审计")
|
||||
void mmAuth003_accessOthersAssignedUserDeniedAndAudited() {
|
||||
// D 名下分配(组长A 同组织创建)
|
||||
assignmentService.create(leaderA, false, user3, mmD, null, "D 负责该用户", null);
|
||||
|
||||
assertTrue(assignmentPolicy.canAccessUser(mmD, user3));
|
||||
assertFalse(assignmentPolicy.canAccessUser(mmB, user3), "他人的分配对象对 B 不可见");
|
||||
|
||||
long before = countAudits("DATA_SCOPE_DENIED", mmB);
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> assignmentPolicy.assertActiveAssignment(mmB, user3, "matchmaker_user"),
|
||||
"B 访问红娘D 的分配对象必须被拒绝");
|
||||
assertEquals(before + 1, countAudits("DATA_SCOPE_DENIED", mmB),
|
||||
"拒绝必须落 DATA_SCOPE_DENIED 审计");
|
||||
}
|
||||
|
||||
// ==================== MM-AUTH-004 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-AUTH-004(负向): POST /services/{id}/claim → 404(claim 端点已删除)")
|
||||
void mmAuth004_claimEndpointRemoved() throws Exception {
|
||||
// standalone MockMvc:仅注册真实控制器路由,验证 /claim 已不在映射中(D3 决策)
|
||||
MatchmakerServiceService stubService = Mockito.mock(MatchmakerServiceService.class);
|
||||
MockMvc mockMvc = MockMvcBuilders
|
||||
.standaloneSetup(new MatchmakerOperatorController(stubService))
|
||||
.build();
|
||||
|
||||
mockMvc.perform(post("/operator/matchmaker/services/some-id/claim"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// ==================== MM-AUDIT-001 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-AUDIT-001: create/transfer/revoke/end 各产生对应 action 审计且 operatorId=操作者")
|
||||
void mmAudit001_eachOperationWritesAuditWithActor() {
|
||||
// 1) create: A 分配 B → user1
|
||||
MatchmakerAssignment a1 = assignmentService.create(
|
||||
leaderA, false, user1, mmB, null, "初始分配", null);
|
||||
assertTrue(countAudits(Constants.AUDIT_ACTION_ASSIGNMENT_CREATE, leaderA) > 0,
|
||||
"create 必须落 MATCHMAKER_ASSIGNMENT_CREATE 审计");
|
||||
|
||||
// 2) transfer: B → D
|
||||
MatchmakerAssignment a2 = assignmentService.transfer(
|
||||
a1.getId(), leaderA, false, mmD, "B 休假,转给 D");
|
||||
assertEquals(mmD, a2.getMatchmakerOperatorId());
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_TRANSFERRED,
|
||||
assignmentMapper.findById(a1.getId()).orElseThrow().getStatus());
|
||||
assertTrue(countAudits(Constants.AUDIT_ACTION_ASSIGNMENT_TRANSFER, leaderA) > 0,
|
||||
"transfer 必须落 MATCHMAKER_ASSIGNMENT_TRANSFER 审计");
|
||||
|
||||
// 3) revoke: 撤销 D 名下的新分配
|
||||
assignmentService.revoke(a2.getId(), leaderA, false, "用户主动申请更换");
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_REVOKED,
|
||||
assignmentMapper.findById(a2.getId()).orElseThrow().getStatus());
|
||||
assertTrue(countAudits(Constants.AUDIT_ACTION_ASSIGNMENT_REVOKE, leaderA) > 0,
|
||||
"revoke 必须落 MATCHMAKER_ASSIGNMENT_REVOKE 审计");
|
||||
|
||||
// 4) end: 新建再结束
|
||||
MatchmakerAssignment a3 = assignmentService.create(
|
||||
leaderA, false, user2, mmB, null, "第二次分配", null);
|
||||
assignmentService.end(a3.getId(), leaderA, false, "服务完结");
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_ENDED,
|
||||
assignmentMapper.findById(a3.getId()).orElseThrow().getStatus());
|
||||
assertTrue(countAudits(Constants.AUDIT_ACTION_ASSIGNMENT_END, leaderA) > 0,
|
||||
"end 必须落 MATCHMAKER_ASSIGNMENT_END 审计");
|
||||
|
||||
// 审计行 operatorId 必须是操作者(组长A),且 resourceType 正确
|
||||
// 注:本用例共 5 次操作(create×2 + transfer + revoke + end),审计 1:1 对应
|
||||
List<AuditLog> audits = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
||||
.eq(AuditLog::getOperatorId, leaderA)
|
||||
.in(AuditLog::getAction, List.of(
|
||||
Constants.AUDIT_ACTION_ASSIGNMENT_CREATE,
|
||||
Constants.AUDIT_ACTION_ASSIGNMENT_TRANSFER,
|
||||
Constants.AUDIT_ACTION_ASSIGNMENT_REVOKE,
|
||||
Constants.AUDIT_ACTION_ASSIGNMENT_END)));
|
||||
assertEquals(5, audits.size(), "五次操作各产生一条审计(create×2/transfer/revoke/end)");
|
||||
assertEquals(2, audits.stream().filter(a ->
|
||||
Constants.AUDIT_ACTION_ASSIGNMENT_CREATE.equals(a.getAction())).count());
|
||||
assertTrue(audits.stream().allMatch(a -> "matchmaker_assignment".equals(a.getResourceType())),
|
||||
"resourceType 必须是 matchmaker_assignment");
|
||||
// afterData 摘要口径:只含 matchmakerOperatorId/scope/reason
|
||||
assertTrue(audits.stream().allMatch(a -> a.getAfterData() != null
|
||||
&& a.getAfterData().contains("matchmakerOperatorId=")
|
||||
&& a.getAfterData().contains("scope=")
|
||||
&& a.getAfterData().contains("reason=")),
|
||||
"afterData 必须记录 operatorId/scope/reason 摘要");
|
||||
}
|
||||
|
||||
// ==================== MM-LIFECYCLE-001 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("MM-LIFECYCLE-001: end/revoke 后 canAccessUser=false;expires_at 届满惰性置 expired")
|
||||
void mmLifecycle001_terminalStatesRevokeAccessAndLazyExpiry() {
|
||||
// end 之后不可访问
|
||||
MatchmakerAssignment a1 = assignmentService.create(
|
||||
leaderA, false, user1, mmB, null, "待结束分配", null);
|
||||
assertTrue(assignmentPolicy.canAccessUser(mmB, user1));
|
||||
assignmentService.end(a1.getId(), leaderA, false, "服务完结");
|
||||
assertFalse(assignmentPolicy.canAccessUser(mmB, user1), "end 后必须立即失去访问权");
|
||||
|
||||
// revoke 之后不可访问
|
||||
MatchmakerAssignment a2 = assignmentService.create(
|
||||
leaderA, false, user2, mmB, null, "待撤销分配", null);
|
||||
assignmentService.revoke(a2.getId(), leaderA, false, "误分配");
|
||||
assertFalse(assignmentPolicy.canAccessUser(mmB, user2), "revoke 后必须立即失去访问权");
|
||||
|
||||
// expires_at 届满(固定时间注入:写入已过期的 expires_at)→ 读路径惰性置 expired
|
||||
MatchmakerAssignment a3 = assignmentService.create(
|
||||
leaderA, false, user3, mmB, null, "短期分配",
|
||||
Instant.now().minusSeconds(3600));
|
||||
assertTrue(assignmentPolicy.canAccessUser(mmB, user3) == false,
|
||||
"已过有效期的分配必须被视为失效");
|
||||
MatchmakerAssignment after = assignmentMapper.findById(a3.getId()).orElseThrow();
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_EXPIRED, after.getStatus(),
|
||||
"惰性过期必须落库(无定时任务,读路径触发)");
|
||||
assertNotNull(after.getEndedAt());
|
||||
assertNotNull(after.getEndReason());
|
||||
|
||||
// 终态一律拒绝再转换(D5 状态机矩阵)
|
||||
assertThrows(com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.revoke(a3.getId(), leaderA, false, "对已过期分配撤销"),
|
||||
"expired 是终态,不允许再转换");
|
||||
assertThrows(com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.end(a1.getId(), leaderA, false, "对已结束分配再结束"),
|
||||
"ended 是终态,不允许再转换");
|
||||
}
|
||||
|
||||
// ==================== 组长组织边界(负向) ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("负向: 组长A 跨组织分配红娘C(org=Y) → 403 + DATA_SCOPE_DENIED 审计")
|
||||
void leaderCannotAssignCrossOrganization() {
|
||||
long before = countAudits("DATA_SCOPE_DENIED", leaderA);
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> assignmentService.create(leaderA, false, user2, mmC, null, "跨组织分配", null),
|
||||
"组长(org=X)不得分配 org=Y 的红娘");
|
||||
assertEquals(before + 1, countAudits("DATA_SCOPE_DENIED", leaderA),
|
||||
"跨组织分配拒绝必须落 DATA_SCOPE_DENIED 审计");
|
||||
assertTrue(assignmentMapper.selectList(new LambdaQueryWrapper<MatchmakerAssignment>()
|
||||
.eq(MatchmakerAssignment::getUserId, user2)).isEmpty(),
|
||||
"被拒绝的分配不得留下任何分配记录");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("负向: 平台授权人员(matchmaker.assign)可跨组织分配;组长不可分配 org=NULL 红娘")
|
||||
void globalAssignScopeAndNullOrgBoundary() {
|
||||
// matchmaker.assign 持有者不受组织限制(leaderA 只是被用作操作者身份)
|
||||
assertDoesNotThrow(() ->
|
||||
assignmentService.create(leaderA, true, user1, mmC, null, "平台授权分配", null),
|
||||
"matchmaker.assign 持有者不限组织");
|
||||
|
||||
// org=NULL 的红娘:平台直属组长只能分配平台直属红娘(NULL=NULL 规则)
|
||||
String platformLeader = createOperator("平台直属组长", null);
|
||||
String platformMm = createOperator("平台直属红娘", null);
|
||||
assertDoesNotThrow(() ->
|
||||
assignmentService.create(platformLeader, false, user2, platformMm, null, "平台直属互配", null),
|
||||
"NULL=NULL(平台直属 → 平台直属)必须放行");
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> assignmentService.create(platformLeader, false, user3, mmB, null, "平台直属分配有组织红娘", null),
|
||||
"平台直属组长不得分配有组织的红娘(NULL≠org X)");
|
||||
}
|
||||
|
||||
// ==================== /pending 方法级权限(负向) ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("负向: 普通红娘(无分配权限)调 /pending → 403 + AUTHORIZATION_DENIED 审计")
|
||||
void normalMatchmakerCannotListPendingQueue() {
|
||||
authenticate(mmB, "matchmaker.view", "matchmaker.service");
|
||||
|
||||
long before = countAudits("AUTHORIZATION_DENIED", mmB);
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> operatorController.getPending(
|
||||
new OperatorPrincipal(mmB, Set.of("matchmaker.view", "matchmaker.service"))),
|
||||
"/pending 方法级权限收敛后,普通红娘必须 403");
|
||||
assertEquals(before + 1, countAudits("AUTHORIZATION_DENIED", mmB),
|
||||
"方法级授权拒绝必须落 AUTHORIZATION_DENIED 审计");
|
||||
}
|
||||
|
||||
// ==================== QA 验收补充(Edward):边界与异常路径 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("QA补充(负向): 理由为 null/空串/纯空格 → 400 VALIDATION_ERROR,且不落任何分配记录或 CREATE 审计")
|
||||
void blankReasonMustBeRejectedWithValidationError() {
|
||||
// null 理由
|
||||
var ex1 = assertThrows(
|
||||
com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.create(leaderA, false, user1, mmB, null, null, null),
|
||||
"reason=null 必须被拒绝");
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.VALIDATION_ERROR, ex1.getCode(),
|
||||
"理由缺失必须是 400 VALIDATION_ERROR,而非 500/403");
|
||||
|
||||
// 空串理由
|
||||
var ex2 = assertThrows(
|
||||
com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.create(leaderA, false, user1, mmB, null, "", null));
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.VALIDATION_ERROR, ex2.getCode());
|
||||
|
||||
// 纯空格理由(isBlank 语义,防止" "绕过)
|
||||
var ex3 = assertThrows(
|
||||
com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.create(leaderA, false, user1, mmB, null, " ", null));
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.VALIDATION_ERROR, ex3.getCode());
|
||||
|
||||
// revoke/end/transfer 同口径
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.VALIDATION_ERROR,
|
||||
assertThrows(com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.transfer("any-id", leaderA, false, mmB, " ")).getCode(),
|
||||
"转分配理由空白同样必须 VALIDATION_ERROR");
|
||||
|
||||
// 三次被拒的 create 不得留下分配记录,也不得落 CREATE 审计
|
||||
assertTrue(assignmentMapper.selectList(new LambdaQueryWrapper<MatchmakerAssignment>()
|
||||
.eq(MatchmakerAssignment::getUserId, user1)).isEmpty(),
|
||||
"被拒绝的分配不得留下任何分配记录");
|
||||
assertEquals(0, countAudits(Constants.AUDIT_ACTION_ASSIGNMENT_CREATE, leaderA),
|
||||
"被拒绝的分配不得产生 CREATE 审计");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("QA补充: collaborating 分配与 active+primary 共存,不触发主责部分唯一索引冲突")
|
||||
void collaboratingAssignmentMustNotConflictWithActivePrimary() {
|
||||
// 先建立主责分配(组长A → 红娘B)
|
||||
assignmentService.create(leaderA, false, user1, mmB, null, "主责分配", null);
|
||||
|
||||
// 直接落一条同用户、同红娘的 collaborating 生效中分配(协同注记不占主责唯一位)
|
||||
MatchmakerAssignment collab = new MatchmakerAssignment();
|
||||
collab.setUserId(user1);
|
||||
collab.setMatchmakerOperatorId(mmB);
|
||||
collab.setAssignedBy(leaderA);
|
||||
collab.setAssignmentScope(Constants.ASSIGNMENT_SCOPE_COLLABORATING);
|
||||
collab.setAssignmentReason("协同服务(组长指派协同)");
|
||||
collab.setStatus(Constants.ASSIGNMENT_STATUS_ACTIVE);
|
||||
collab.setAssignedAt(Instant.now());
|
||||
assertDoesNotThrow(() -> assignmentMapper.insert(collab),
|
||||
"collaborating 生效中分配不得触发 uq_mm_assignment_active_primary 冲突");
|
||||
|
||||
// 主责仍在、协同也在,两条均为生效中
|
||||
assertEquals(2, assignmentMapper.selectCount(new LambdaQueryWrapper<MatchmakerAssignment>()
|
||||
.eq(MatchmakerAssignment::getUserId, user1)
|
||||
.eq(MatchmakerAssignment::getStatus, Constants.ASSIGNMENT_STATUS_ACTIVE)),
|
||||
"同一用户应同时存在 1 条 active 主责 + 1 条 active 协同");
|
||||
|
||||
// 主责唯一性仍然生效:同用户第二条 primary 必须被拒(对照组)
|
||||
assertThrows(Exception.class,
|
||||
() -> assignmentService.create(leaderA, false, user1, mmD, null, "第二条主责", null),
|
||||
"同用户第二条 active primary 必须被唯一性约束拒绝");
|
||||
// 预检路径的 CONFLICT
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.CONFLICT,
|
||||
assertThrows(com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.create(leaderA, false, user1, mmD, null, "第二条主责", null)).getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("QA补充(负向): 有组织组长分配 org=NULL(平台直属)红娘 → 403(Objects.equals 非对称方向的显式覆盖)")
|
||||
void orgLeaderMustNotAssignPlatformDirectMatchmaker() {
|
||||
// org=NULL 红娘(平台直属)
|
||||
String platformMm = createOperator("平台直属红娘-供拒配", null);
|
||||
long before = countAudits("DATA_SCOPE_DENIED", leaderA);
|
||||
// leaderA(org X)→ org=NULL 红娘:Objects.equals(orgX, null)=false,必须拒绝
|
||||
assertThrows(AccessDeniedException.class,
|
||||
() -> assignmentService.create(leaderA, false, user2, platformMm, null, "有组织组长碰平台直属红娘", null),
|
||||
"有组织组长不得分配 org=NULL(平台直属)红娘");
|
||||
assertEquals(before + 1, countAudits("DATA_SCOPE_DENIED", leaderA),
|
||||
"拒绝必须落 DATA_SCOPE_DENIED 审计");
|
||||
// 同理 transfer 的范围校验也覆盖该方向(ZC-MM-006 / T04:transfer 404 化)
|
||||
MatchmakerAssignment a = assignmentService.create(leaderA, false, user3, mmB, null, "主责", null);
|
||||
var transferDenied = assertThrows(
|
||||
com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.transfer(a.getId(), leaderA, false, platformMm, "转给平台直属红娘"),
|
||||
"有组织组长不得把分配转给 org=NULL 红娘(404 化拒绝)");
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.NOT_FOUND, transferDenied.getCode(),
|
||||
"transfer 范围违规必须 404 化(防探测,T04)");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("P2-1补充(负向): org=X 组长转分配 org=Y 红娘持有的分配 → 404 化拒绝 + DATA_SCOPE_DENIED 审计(原持有人范围校验)")
|
||||
void leaderCannotTransferAssignmentHeldByCrossOrgMatchmaker() {
|
||||
// org=Y 红娘C 持有一条分配(由平台授权路径创建,绕过 create 的范围校验以构造前置状态)
|
||||
MatchmakerAssignment held = assignmentService.create(
|
||||
leaderA, true, user1, mmC, null, "平台授权分配给C", null);
|
||||
assertEquals(mmC, held.getMatchmakerOperatorId());
|
||||
|
||||
long before = countAudits("DATA_SCOPE_DENIED", leaderA);
|
||||
// org=X 组长A 把 C(org=Y)持有的分配转给同组织成员 B:原持有人范围违规,必须拒绝
|
||||
// (ZC-MM-006 / T04:transfer 为资源寻址写端点,拒绝 404 化,审计仍为 DATA_SCOPE_DENIED)
|
||||
var denied = assertThrows(
|
||||
com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException.class,
|
||||
() -> assignmentService.transfer(held.getId(), leaderA, false, mmB, "转回本组织"),
|
||||
"组长不得处置跨组织红娘持有的分配(原持有人范围校验,404 化)");
|
||||
assertEquals(com.danyang.match.platform.shared.enums.ApiResponseCode.NOT_FOUND, denied.getCode(),
|
||||
"transfer 范围违规必须 404 化(防探测,T04)");
|
||||
assertEquals(before + 1, countAudits("DATA_SCOPE_DENIED", leaderA),
|
||||
"拒绝必须落 DATA_SCOPE_DENIED 审计");
|
||||
|
||||
// 被转记录必须原样保留:仍 active 且持有人仍是 C,未产生新分配
|
||||
MatchmakerAssignment after = assignmentMapper.findById(held.getId()).orElseThrow();
|
||||
assertEquals(Constants.ASSIGNMENT_STATUS_ACTIVE, after.getStatus(),
|
||||
"被拒绝的转分配不得改变原分配状态");
|
||||
assertEquals(mmC, after.getMatchmakerOperatorId(),
|
||||
"被拒绝的转分配不得改变原持有人");
|
||||
assertTrue(assignmentMapper.selectList(new LambdaQueryWrapper<MatchmakerAssignment>()
|
||||
.eq(MatchmakerAssignment::getUserId, user1)
|
||||
.eq(MatchmakerAssignment::getMatchmakerOperatorId, mmB))
|
||||
.isEmpty(),
|
||||
"被拒绝的转分配不得给目标红娘留下任何分配记录");
|
||||
}
|
||||
|
||||
// ==================== 分配同事务联动服务单 ====================
|
||||
|
||||
@Autowired
|
||||
private com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper realServiceMapper;
|
||||
|
||||
@Test
|
||||
@DisplayName("联动: 带 serviceId 的分配同事务把服务单置 assigned 并写回 assigned_operator_id")
|
||||
void createWithServiceIdLinksServiceRow() {
|
||||
// 真实落库一条 submitted 服务单
|
||||
var record = new com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord();
|
||||
record.setUserId(user1);
|
||||
record.setServiceType(Constants.MATCHMAKER_SERVICE_TYPE_RECOMMEND_PARTNER);
|
||||
record.setStatus(Constants.MATCHMAKER_STATUS_SUBMITTED);
|
||||
realServiceMapper.insert(record);
|
||||
|
||||
assignmentService.create(leaderA, false, user1, mmB, record.getId(), "带服务单分配", null);
|
||||
|
||||
var updated = realServiceMapper.selectById(record.getId());
|
||||
assertEquals(Constants.MATCHMAKER_STATUS_ASSIGNED, updated.getStatus(),
|
||||
"分配联动必须把服务单置为 assigned");
|
||||
assertEquals(mmB, updated.getAssignedOperatorId(),
|
||||
"服务单 assigned_operator_id 必须写为目标红娘");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.danyang.match.platform.matchmaker;
|
||||
|
||||
import com.danyang.match.platform.matchmaker.controller.MatchmakerAssignmentController;
|
||||
import com.danyang.match.platform.matchmaker.controller.MatchmakerOperatorController;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* ZC-MM-002(A1)权限契约守卫(standalone 反射扫描,无需 Spring 上下文)。
|
||||
*
|
||||
* <p>锁定两条不变量:
|
||||
* <ol>
|
||||
* <li>{@code MatchmakerAssignmentController} 每个端点都有显式 @PreAuthorize;
|
||||
* 写操作(create/transfer/revoke/end/assignable)必须同时包含
|
||||
* {@code matchmaker.assign} 或 {@code matchmaker.team.assign};
|
||||
* 读自己名下(/my)必须是 {@code matchmaker.service}。</li>
|
||||
* <li>{@code MatchmakerOperatorController} 无 claim 残留(D3:claim 端点/方法已删除)。</li>
|
||||
* </ol>
|
||||
*/
|
||||
class MatchmakerAssignmentPermissionTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("AssignmentController:全部端点有 @PreAuthorize,写操作限定分配权限")
|
||||
void assignmentControllerPermissionContract() {
|
||||
List<String> violations = new ArrayList<>();
|
||||
for (Method method : MatchmakerAssignmentController.class.getDeclaredMethods()) {
|
||||
if (paths(method).isEmpty()) {
|
||||
continue; // 非端点方法
|
||||
}
|
||||
PreAuthorize preAuthorize = AnnotatedElementUtils.findMergedAnnotation(method, PreAuthorize.class);
|
||||
if (preAuthorize == null) {
|
||||
violations.add(method.getName() + ": 缺少 @PreAuthorize");
|
||||
continue;
|
||||
}
|
||||
String expr = preAuthorize.value();
|
||||
boolean isReadMy = method.getName().equals("my");
|
||||
boolean isTeamStatistics = method.getName().equals("teamStatistics");
|
||||
if (isReadMy) {
|
||||
if (!expr.contains("matchmaker.service")) {
|
||||
violations.add("my: 读接口必须要求 matchmaker.service,实际=" + expr);
|
||||
}
|
||||
} else if (isTeamStatistics) {
|
||||
// ZC-MM-005/T03:纯组长数据,只要求 team.assign(更强而非更弱)
|
||||
if (!expr.contains("matchmaker.team.assign")) {
|
||||
violations.add("teamStatistics: 必须要求 matchmaker.team.assign,实际=" + expr);
|
||||
}
|
||||
} else {
|
||||
boolean hasAssignPermission = expr.contains("matchmaker.assign")
|
||||
&& expr.contains("matchmaker.team.assign");
|
||||
if (!hasAssignPermission) {
|
||||
violations.add(method.getName()
|
||||
+ ": 写操作必须同时限定 matchmaker.assign / matchmaker.team.assign,实际=" + expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(), violations, "AssignmentController 权限契约被破坏");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("守卫自检:必须真的扫到 AssignmentController 端点(防守卫失效)")
|
||||
void guardMustActuallySeeEndpoints() {
|
||||
long endpointCount = Arrays.stream(MatchmakerAssignmentController.class.getDeclaredMethods())
|
||||
.filter(m -> !paths(m).isEmpty())
|
||||
.count();
|
||||
assertTrue(endpointCount >= 5,
|
||||
"扫描到的端点数异常偏少(" + endpointCount + "),守卫可能失效");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("OperatorController:无 claim 残留(端点路径与方法名均不得含 claim)")
|
||||
void operatorControllerMustNotHaveClaimResidue() {
|
||||
List<String> residue = new ArrayList<>();
|
||||
for (Method method : MatchmakerOperatorController.class.getDeclaredMethods()) {
|
||||
if (method.getName().toLowerCase().contains("claim")) {
|
||||
residue.add("方法名残留: " + method.getName());
|
||||
}
|
||||
if (paths(method).stream().anyMatch(p -> p.toLowerCase().contains("claim"))) {
|
||||
residue.add("路径残留: " + method.getName());
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(), residue,
|
||||
"D3 决策:claim(红娘接单)端点必须彻底删除,归属由 matchmaker_assignments 建模");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ZC-MM-005/E4:OperatorController 无 my-services 残留(死端点已删除)")
|
||||
void operatorControllerMustNotHaveMyServicesResidue() {
|
||||
List<String> residue = new ArrayList<>();
|
||||
for (Method method : MatchmakerOperatorController.class.getDeclaredMethods()) {
|
||||
String lower = method.getName().toLowerCase();
|
||||
if (lower.contains("myservices") || lower.contains("my_services")) {
|
||||
residue.add("方法名残留: " + method.getName());
|
||||
}
|
||||
if (paths(method).stream().anyMatch(p -> p.toLowerCase().contains("my-services"))) {
|
||||
residue.add("路径残留: " + method.getName());
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(), residue,
|
||||
"GET /my-services 是死端点(按 C 端 user_id 查 operator 恒空、前后端零调用),"
|
||||
+ "替代路径为 GET /operator/matchmaker/assignments/my");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ZC-MM-005/T03:team/statistics 端点必须显式限定 matchmaker.team.assign")
|
||||
void teamStatisticsMustRequireTeamAssignPermission() {
|
||||
Method statistics = Arrays.stream(MatchmakerAssignmentController.class.getDeclaredMethods())
|
||||
.filter(m -> m.getName().equals("teamStatistics"))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("teamStatistics 端点不存在"));
|
||||
PreAuthorize preAuthorize = AnnotatedElementUtils.findMergedAnnotation(statistics, PreAuthorize.class);
|
||||
assertNotNull(preAuthorize, "team/statistics 缺少 @PreAuthorize");
|
||||
assertTrue(preAuthorize.value().contains("matchmaker.team.assign"),
|
||||
"team/statistics 必须限定 matchmaker.team.assign(纯组长数据),实际="
|
||||
+ preAuthorize.value());
|
||||
}
|
||||
|
||||
private List<String> paths(java.lang.reflect.AnnotatedElement element) {
|
||||
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
|
||||
return mapping == null ? List.of() : Arrays.asList(mapping.path().length > 0
|
||||
? mapping.path() : mapping.value());
|
||||
}
|
||||
}
|
||||