Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afee993626 | ||
|
|
d51c4c6a76 | ||
|
|
69ebf33e18 | ||
|
|
8b505d9133 | ||
|
|
3c2b967274 | ||
|
|
827c23db1d | ||
|
|
ef61d51f61 | ||
|
|
02bc01f9c9 | ||
|
|
16c82739db | ||
|
|
f73a116a10 | ||
|
|
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
|
working-directory: backend
|
||||||
run: mvn verify -B
|
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
|
- name: Upload Test Results
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
|
|||||||
@@ -61,6 +61,9 @@ tests/fixtures/*.json
|
|||||||
.worktrees/
|
.worktrees/
|
||||||
.zcode/
|
.zcode/
|
||||||
.workbuddy/
|
.workbuddy/
|
||||||
|
.mimosa/
|
||||||
|
.trae/
|
||||||
|
.wb_tmp_bcrypt/
|
||||||
project.private.config.json
|
project.private.config.json
|
||||||
/nul
|
/nul
|
||||||
/infrastructure/nul
|
/infrastructure/nul
|
||||||
|
|||||||
@@ -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/>
|
||||||
@@ -32,8 +32,12 @@ server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# API proxy to backend
|
# API proxy to backend
|
||||||
|
# 用 resolver + 变量 proxy_pass:避免 nginx 启动时 backend DNS 还没就绪就 [emerg] 退出
|
||||||
|
# Docker Compose 默认网络的内置 DNS resolver 是 127.0.0.11
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
set $backend_upstream "http://backend:8080";
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://backend:8080;
|
proxy_pass $backend_upstream;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -42,7 +46,7 @@ server {
|
|||||||
|
|
||||||
# WebSocket proxy for chat
|
# WebSocket proxy for chat
|
||||||
location /ws/ {
|
location /ws/ {
|
||||||
proxy_pass http://backend:8080;
|
proxy_pass $backend_upstream;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "danyang-match-admin",
|
"name": "danyang-match-admin",
|
||||||
"version": "1.0.0-rc.2",
|
"version": "1.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -19,6 +19,9 @@
|
|||||||
# 后者生成 Vue 版本桥接),允许它们执行。
|
# 后者生成 Vue 版本桥接),允许它们执行。
|
||||||
packages:
|
packages:
|
||||||
- '.'
|
- '.'
|
||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
|
vue-demi: true
|
||||||
onlyBuiltDependencies:
|
onlyBuiltDependencies:
|
||||||
- esbuild
|
- esbuild
|
||||||
- vue-demi
|
- vue-demi
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 672 KiB |
@@ -1,14 +1,18 @@
|
|||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import router from '@/router'
|
import router from '@/router'
|
||||||
|
import { getAccessToken, setAccessToken, clearAccessToken } from '@/utils/token'
|
||||||
|
|
||||||
const client = axios.create({
|
const client = axios.create({
|
||||||
baseURL: '/api/v1',
|
baseURL: '/api/v1',
|
||||||
timeout: 10000,
|
timeout: 10000,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 防止 401 时并发触发多次刷新
|
||||||
|
let refreshing = false
|
||||||
|
|
||||||
client.interceptors.request.use((config) => {
|
client.interceptors.request.use((config) => {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
}
|
}
|
||||||
@@ -17,11 +21,45 @@ client.interceptors.request.use((config) => {
|
|||||||
|
|
||||||
client.interceptors.response.use(
|
client.interceptors.response.use(
|
||||||
(res) => res.data,
|
(res) => res.data,
|
||||||
(err) => {
|
async (err) => {
|
||||||
if (err.response?.status === 401) {
|
const status = err.response?.status
|
||||||
localStorage.removeItem('accessToken')
|
const original = err.config
|
||||||
router.push('/login')
|
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('登录已过期,请重新登录')
|
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) {
|
} else if (err.response?.data?.message) {
|
||||||
ElMessage.error(err.response.data.message)
|
ElMessage.error(err.response.data.message)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,26 +1,52 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="admin-scene" :class="{ 'sidebar-collapsed': isCollapse }">
|
<div class="admin-scene" :class="{ 'sidebar-collapsed': isCollapse }">
|
||||||
<header class="scene-header" aria-label="善缘丹阳公益服务品牌信息">
|
<header class="scene-header" aria-label="爱在丹阳公益服务品牌信息">
|
||||||
|
<!-- 背景装饰层:粉渐变兜底 + 丹阳剪影底图 + 爱心点缀 -->
|
||||||
|
<div class="header-bg" aria-hidden="true"></div>
|
||||||
|
<div class="header-hearts" aria-hidden="true">
|
||||||
|
<span>♡</span><span>♡</span><span>♡</span><span>♡</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="scene-brand">
|
<div class="scene-brand">
|
||||||
<img :src="BRAND_LOGO" alt="善缘丹阳" />
|
<div class="brand-logo-wrap">
|
||||||
|
<img :src="BRAND_LOGO" alt="爱在丹阳" />
|
||||||
|
<span class="brand-dot" aria-hidden="true"></span>
|
||||||
|
</div>
|
||||||
<div class="scene-brand-copy">
|
<div class="scene-brand-copy">
|
||||||
<strong>善缘丹阳</strong>
|
<div class="brand-name-row">
|
||||||
<span>公益婚恋服务平台</span>
|
<strong>爱在丹阳</strong>
|
||||||
|
<em class="brand-badge">公益运营</em>
|
||||||
|
</div>
|
||||||
|
<span class="brand-tagline">公益婚恋服务平台</span>
|
||||||
|
<span class="brand-ornament" aria-hidden="true">❖ ● ❖ ● ❖</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="scene-title">
|
<div class="scene-title">
|
||||||
<h1>管理端(运营后台)</h1>
|
<h1>管理端(运营后台)</h1>
|
||||||
<p>用专业的服务,帮助更多人遇见对的人</p>
|
<p class="title-sub">
|
||||||
|
<span>公益婚恋服务平台</span>
|
||||||
|
<span class="sep">·</span>
|
||||||
|
<span>用爱连接美好姻缘</span>
|
||||||
|
<span class="sep">·</span>
|
||||||
|
<span>让更多人在丹阳遇见幸福</span>
|
||||||
|
</p>
|
||||||
|
<p class="title-meta">
|
||||||
|
<span class="meta-chip" title="当前权限范围内今日新增、分配、跟进或完成的红娘服务单,按北京时间去重">今日服务 {{ todayStats?.total ?? '—' }} 单</span>
|
||||||
|
<span class="meta-chip" title="当前权限范围内尚未完成的红娘服务单">待处理 {{ todayStats?.pending ?? '—' }} 件</span>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scene-slogan" aria-hidden="true">
|
<div class="scene-slogan" aria-hidden="true">
|
||||||
<span>善缘相牵</span>
|
<span class="slogan-top">爱在丹阳</span>
|
||||||
<strong>爱在丹阳</strong>
|
<strong class="slogan-main">原来是你</strong>
|
||||||
|
<em class="slogan-en">Love In Danyang</em>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scene-benefits" aria-label="平台服务原则">
|
<div class="scene-benefits" aria-label="平台服务原则">
|
||||||
<span><el-icon><StarFilled /></el-icon><b>公益为本</b><small>不以营利为目的</small></span>
|
<span><i class="benefit-icon"><el-icon><StarFilled /></el-icon></i><b>公益为本</b><small>不以营利为目的</small></span>
|
||||||
<span><el-icon><Lock /></el-icon><b>真实可靠</b><small>严格审核 多重保障</small></span>
|
<span><i class="benefit-icon"><el-icon><Lock /></el-icon></i><b>真实可靠</b><small>严格审核·多重保障</small></span>
|
||||||
<span><el-icon><LocationFilled /></el-icon><b>本地服务</b><small>深耕丹阳 服务家乡</small></span>
|
<span><i class="benefit-icon"><el-icon><LocationFilled /></el-icon></i><b>本地服务</b><small>深耕丹阳·服务家乡</small></span>
|
||||||
<span><el-icon><Opportunity /></el-icon><b>成就幸福</b><small>让爱在丹阳生根发芽</small></span>
|
<span><i class="benefit-icon"><el-icon><Opportunity /></el-icon></i><b>成就幸福</b><small>让爱在丹阳生根发芽</small></span>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -29,7 +55,7 @@
|
|||||||
<div class="brand" :class="{ compact: isCollapse }">
|
<div class="brand" :class="{ compact: isCollapse }">
|
||||||
<img class="brand-mark" :src="BRAND_LOGO" alt="" />
|
<img class="brand-mark" :src="BRAND_LOGO" alt="" />
|
||||||
<div v-if="!isCollapse" class="brand-copy">
|
<div v-if="!isCollapse" class="brand-copy">
|
||||||
<strong>善缘丹阳</strong>
|
<strong>爱在丹阳</strong>
|
||||||
<span>公益婚恋服务平台</span>
|
<span>公益婚恋服务平台</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -121,14 +147,16 @@
|
|||||||
</el-container>
|
</el-container>
|
||||||
|
|
||||||
<footer class="scene-footer">
|
<footer class="scene-footer">
|
||||||
<strong>善缘丹阳</strong><span>公益婚恋服务平台</span>
|
<strong>爱在丹阳</strong><span>公益婚恋服务平台</span>
|
||||||
<small>真实 · 真诚 · 公益 · 幸福</small>
|
<small>真实 · 真诚 · 公益 · 幸福</small>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { get } from '@/api/client'
|
||||||
|
import { summarizeMatchmakerServices } from '@/services/dashboard'
|
||||||
import { BRAND_BACKDROP, BRAND_LOGO } from '@/brand'
|
import { BRAND_BACKDROP, BRAND_LOGO } from '@/brand'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
@@ -174,8 +202,8 @@ const navigation: NavigationItem[] = [
|
|||||||
{ label: '用户管理', path: '/users', permissions: ['user.view'], icon: User },
|
{ label: '用户管理', path: '/users', permissions: ['user.view'], icon: User },
|
||||||
{ label: '资料审核', path: '/review', permissions: ['review.view'], icon: DocumentChecked },
|
{ label: '资料审核', path: '/review', permissions: ['review.view'], icon: DocumentChecked },
|
||||||
{ label: '匹配管理', path: '/activities/interests', permissions: ['activity.review_registration'], icon: StarFilled },
|
{ label: '匹配管理', path: '/activities/interests', permissions: ['activity.review_registration'], icon: StarFilled },
|
||||||
{ label: '公益红娘', path: '/referral', permissions: ['referral.manage'], icon: Connection },
|
{ label: '公益红娘', path: '/referral', permissions: ['matchmaker.service'], icon: Connection },
|
||||||
{ label: '红娘服务', path: '/matchmaker', permissions: ['matchmaker.service.view'], icon: Connection },
|
{ label: '红娘服务', path: '/matchmaker', permissions: ['matchmaker.view'], icon: Connection },
|
||||||
{ label: '公益咨询', path: '/counseling', permissions: ['counseling.service.view'], icon: ChatDotRound },
|
{ label: '公益咨询', path: '/counseling', permissions: ['counseling.service.view'], icon: ChatDotRound },
|
||||||
{ label: '活动管理', path: '/activities', permissions: ['activity.view'], icon: Calendar },
|
{ label: '活动管理', path: '/activities', permissions: ['activity.view'], icon: Calendar },
|
||||||
{ label: '活动签到', path: '/activities/checkin', permissions: ['activity.checkin'], icon: Calendar },
|
{ label: '活动签到', path: '/activities/checkin', permissions: ['activity.checkin'], icon: Calendar },
|
||||||
@@ -199,6 +227,25 @@ const isCollapse = ref(false)
|
|||||||
const globalSearch = ref('')
|
const globalSearch = ref('')
|
||||||
const notificationCount = ref(0)
|
const notificationCount = ref(0)
|
||||||
|
|
||||||
|
const todayStats = ref<{ total: number; pending: number } | null>(null)
|
||||||
|
|
||||||
|
watch(() => route.fullPath, async () => {
|
||||||
|
todayStats.value = null
|
||||||
|
const perms = authStore.permissions
|
||||||
|
if (authStore.token === 'ui-preview-only') return
|
||||||
|
try {
|
||||||
|
if (perms.includes('matchmaker.assign') || perms.includes('matchmaker.team.assign')) {
|
||||||
|
const response: any = await get('/operator/matchmaker/management/services')
|
||||||
|
if (response.success && Array.isArray(response.data)) todayStats.value = summarizeMatchmakerServices(response.data)
|
||||||
|
} else if (perms.includes('matchmaker.view')) {
|
||||||
|
const response: any = await get('/operator/matchmaker/dashboard')
|
||||||
|
if (response.success) todayStats.value = { total: response.data.todayCount, pending: response.data.pendingCount + response.data.inProgressCount }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
todayStats.value = null
|
||||||
|
}
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
const activeMenu = computed(() => {
|
const activeMenu = computed(() => {
|
||||||
if (route.path === '/users/detail') return '/users'
|
if (route.path === '/users/detail') return '/users'
|
||||||
return route.path
|
return route.path
|
||||||
@@ -217,7 +264,7 @@ const currentRoleName = computed(() => {
|
|||||||
if (perms.includes('counseling.service.view')) return '公益咨询人员'
|
if (perms.includes('counseling.service.view')) return '公益咨询人员'
|
||||||
if (perms.includes('service_appointment.view')) return '服务站运营人员'
|
if (perms.includes('service_appointment.view')) return '服务站运营人员'
|
||||||
if (perms.includes('review.view')) return '资料审核人员'
|
if (perms.includes('review.view')) return '资料审核人员'
|
||||||
if (perms.includes('matchmaker.service.view')) return '公益红娘'
|
if (perms.includes('matchmaker.view')) return '公益红娘'
|
||||||
return '运营人员'
|
return '运营人员'
|
||||||
})
|
})
|
||||||
const visibleNavigation = computed(() => navigation.filter((item) => item.permissions.every(hasPerm)))
|
const visibleNavigation = computed(() => navigation.filter((item) => item.permissions.every(hasPerm)))
|
||||||
@@ -258,137 +305,307 @@ function handleLogout() {
|
|||||||
<style scoped>
|
<style scoped>
|
||||||
.admin-scene {
|
.admin-scene {
|
||||||
min-width: 1100px;
|
min-width: 1100px;
|
||||||
min-height: 100vh;
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
padding: 18px 34px 14px;
|
padding: 18px 34px 14px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
/* 背景图是 public/ 下的运行时资源,必须带 BASE_URL 前缀:
|
/* 外层:纯色粉渐变兜底,再叠加背景图。
|
||||||
写死品牌目录的绝对路径,在产物部署于 /admin/ 子路径时会 404(页面背景变纯色)。
|
原实现把 background 和 background-image 拆两行在某些浏览器会覆盖 —— 这里统一写一条,
|
||||||
用 v-bind 把常量注入 CSS,避免在样式里各写一遍拼接。 */
|
并显式声明 position/size/repeat/attachment,确保 cover 全区域。 */
|
||||||
/* 先给纯色兜底,避免图未加载完成时闪白 */
|
background:
|
||||||
background: var(--admin-coral-lighter) center / cover fixed no-repeat;
|
linear-gradient(180deg, var(--admin-scene-bg-start) 0%, var(--admin-scene-bg-mid) 40%, var(--admin-scene-bg-end) 100%),
|
||||||
background-image: url(v-bind('BRAND_BACKDROP'));
|
url(v-bind('BRAND_BACKDROP')) center / cover fixed no-repeat;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-header {
|
.scene-header {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
display: grid;
|
display: grid;
|
||||||
max-width: var(--admin-shell-max-width);
|
/* 100vw 撑满浏览器:用负 margin 抵消 admin-scene 的 padding */
|
||||||
height: 188px;
|
width: 100vw;
|
||||||
margin: 0 auto;
|
max-width: none;
|
||||||
grid-template-columns: minmax(640px, 1fr) auto;
|
height: 105px;
|
||||||
grid-template-rows: 112px 76px;
|
margin: -18px -34px 12px;
|
||||||
|
padding: 0 34px;
|
||||||
|
grid-template-columns: auto 1fr auto;
|
||||||
|
grid-template-rows: 1fr 36px;
|
||||||
|
grid-template-areas:
|
||||||
|
"brand title slogan"
|
||||||
|
"benefits benefits benefits";
|
||||||
align-items: center;
|
align-items: center;
|
||||||
column-gap: var(--space-8);
|
column-gap: 20px;
|
||||||
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== 背景装饰层 ===== */
|
||||||
|
.header-bg {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background:
|
||||||
|
linear-gradient(135deg, var(--admin-scene-bg-start) 0%, var(--admin-scene-bg-mid) 55%, var(--admin-scene-bg-end) 100%),
|
||||||
|
url(v-bind('BRAND_BACKDROP')) center / cover no-repeat;
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
/* 左上角柔光晕 */
|
||||||
|
.header-bg::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: -60px;
|
||||||
|
left: -40px;
|
||||||
|
width: 300px;
|
||||||
|
height: 180px;
|
||||||
|
background: radial-gradient(ellipse at center, var(--admin-scene-glow) 0%, transparent 70%);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
/* 右下角柔光晕 */
|
||||||
|
.header-bg::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
right: 40px;
|
||||||
|
bottom: -30px;
|
||||||
|
width: 280px;
|
||||||
|
height: 140px;
|
||||||
|
background: radial-gradient(ellipse at center, var(--admin-scene-glow-soft) 0%, transparent 70%);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 爱心点缀 */
|
||||||
|
.header-hearts {
|
||||||
|
position: absolute;
|
||||||
|
top: 18px;
|
||||||
|
right: 34px;
|
||||||
|
display: flex;
|
||||||
|
gap: 14px;
|
||||||
|
font-size: 16px;
|
||||||
|
color: var(--admin-coral-border);
|
||||||
|
z-index: 1;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.header-hearts span {
|
||||||
|
animation: heartbeat 3s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
.header-hearts span:nth-child(2) { animation-delay: .4s; }
|
||||||
|
.header-hearts span:nth-child(3) { animation-delay: .8s; }
|
||||||
|
.header-hearts span:nth-child(4) { animation-delay: 1.2s; }
|
||||||
|
@keyframes heartbeat {
|
||||||
|
0%, 100% { transform: scale(1); opacity: .5; }
|
||||||
|
50% { transform: scale(1.25); opacity: 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 所有 header 内容浮在背景层之上 ===== */
|
||||||
|
.scene-brand,
|
||||||
|
.scene-slogan,
|
||||||
|
.scene-benefits {
|
||||||
|
position: relative;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 品牌区 ===== */
|
||||||
.scene-brand,
|
.scene-brand,
|
||||||
.scene-benefits,
|
|
||||||
.scene-benefits span,
|
|
||||||
.scene-brand-copy {
|
.scene-brand-copy {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-brand > img {
|
.scene-brand {
|
||||||
width: 64px;
|
grid-area: brand;
|
||||||
height: 64px;
|
gap: 10px;
|
||||||
object-fit: contain;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-slogan {
|
/* Logo + 装饰圆点 */
|
||||||
|
.brand-logo-wrap {
|
||||||
|
position: relative;
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
flex: none;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
}
|
||||||
|
.brand-logo-wrap img {
|
||||||
|
width: 42px;
|
||||||
|
height: 42px;
|
||||||
|
object-fit: contain;
|
||||||
|
border-radius: 50%;
|
||||||
|
clip-path: circle(50%);
|
||||||
|
filter: drop-shadow(0 2px 6px rgba(244,95,104,0.25));
|
||||||
|
}
|
||||||
|
.brand-dot {
|
||||||
|
position: absolute;
|
||||||
|
top: -2px;
|
||||||
|
right: -2px;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
background: var(--gradient-brand-solid);
|
||||||
|
border-radius: 50%;
|
||||||
|
box-shadow: 0 2px 4px rgba(200, 74, 83, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 品牌名 + 徽章 — tagline/ornament 在 105px 高度里塞不下,隐藏 */
|
||||||
|
.scene-brand-copy {
|
||||||
|
min-width: 0;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
color: var(--admin-coral-strong);
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.brand-name-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
padding-right: var(--space-6);
|
align-items: center;
|
||||||
align-items: flex-end;
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.brand-name-row strong {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
background: var(--gradient-brand-text);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
text-shadow: none;
|
||||||
|
}
|
||||||
|
.brand-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 500;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
background: var(--gradient-brand-solid);
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 2px 6px rgba(200, 74, 83, 0.3);
|
||||||
|
}
|
||||||
|
.brand-tagline,
|
||||||
|
.brand-ornament {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 标题区 */
|
||||||
|
.scene-title {
|
||||||
|
min-width: 0;
|
||||||
|
margin-left: 20px;
|
||||||
|
padding-left: 16px;
|
||||||
|
border-left: 2px solid var(--admin-scene-divider);
|
||||||
|
}
|
||||||
|
.scene-title h1 {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.05;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
color: var(--color-text-primary);
|
||||||
|
}
|
||||||
|
.title-sub {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0;
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
letter-spacing: .2px;
|
||||||
|
}
|
||||||
|
.title-sub .sep {
|
||||||
|
margin: 0 5px;
|
||||||
|
color: var(--admin-coral-solid);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.title-meta {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 3px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.meta-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 8px;
|
||||||
|
height: 18px;
|
||||||
|
color: var(--admin-coral-strong);
|
||||||
|
background: var(--admin-scene-surface);
|
||||||
|
border: 1px solid var(--admin-coral-border);
|
||||||
|
border-radius: 9px;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 书法 slogan ===== */
|
||||||
|
.scene-slogan {
|
||||||
|
grid-area: slogan;
|
||||||
|
display: flex;
|
||||||
|
padding-right: 0;
|
||||||
|
align-items: center;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
color: var(--admin-coral-strong);
|
color: var(--admin-coral-strong);
|
||||||
font-family: var(--font-family-brand);
|
font-family: var(--font-family-brand);
|
||||||
line-height: 1.05;
|
line-height: 1;
|
||||||
transform: rotate(-7deg);
|
text-align: center;
|
||||||
|
gap: 0;
|
||||||
}
|
}
|
||||||
|
.slogan-top {
|
||||||
.scene-slogan span {
|
font-size: 12px;
|
||||||
font-size: var(--font-size-lg);
|
letter-spacing: 6px;
|
||||||
}
|
|
||||||
|
|
||||||
.scene-slogan strong {
|
|
||||||
margin-top: var(--space-1);
|
|
||||||
font-size: var(--font-size-3xl);
|
|
||||||
font-weight: var(--font-weight-medium);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-brand-copy {
|
|
||||||
min-width: 172px;
|
|
||||||
margin-left: 10px;
|
|
||||||
align-items: flex-start;
|
|
||||||
flex-direction: column;
|
|
||||||
color: var(--admin-coral-strong);
|
color: var(--admin-coral-strong);
|
||||||
|
opacity: .8;
|
||||||
}
|
}
|
||||||
|
.slogan-main {
|
||||||
.scene-brand-copy strong {
|
font-size: 26px;
|
||||||
font-size: var(--font-size-4xl);
|
font-weight: 500;
|
||||||
line-height: 1.15;
|
|
||||||
letter-spacing: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-brand-copy span {
|
|
||||||
margin-top: 5px;
|
|
||||||
font-size: var(--font-size-xs);
|
|
||||||
letter-spacing: 4px;
|
letter-spacing: 4px;
|
||||||
|
background: var(--gradient-brand-text);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
}
|
||||||
|
.slogan-en {
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-title {
|
/* ===== 公益原则行 ===== */
|
||||||
min-width: 370px;
|
|
||||||
margin-left: 28px;
|
|
||||||
padding-left: 28px;
|
|
||||||
border-left: 1px solid var(--admin-coral-border);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-title h1 {
|
|
||||||
font-size: clamp(var(--font-size-3xl), 2.2vw, var(--font-size-display));
|
|
||||||
line-height: 1.1;
|
|
||||||
letter-spacing: 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-title p {
|
|
||||||
margin-top: 9px;
|
|
||||||
color: var(--color-text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-benefits {
|
.scene-benefits {
|
||||||
grid-column: 1 / -1;
|
grid-area: benefits;
|
||||||
align-self: start;
|
align-self: center;
|
||||||
justify-content: flex-start;
|
justify-content: center;
|
||||||
gap: clamp(38px, 5vw, 92px);
|
flex-wrap: nowrap;
|
||||||
padding: var(--space-1) 0 0 50px;
|
gap: clamp(10px, 1.6vw, 28px);
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-benefits span {
|
.scene-benefits span {
|
||||||
display: grid;
|
flex: none;
|
||||||
grid-template-columns: 36px auto;
|
display: inline-flex;
|
||||||
column-gap: var(--space-2);
|
align-items: center;
|
||||||
/* 13px 文字压在摄影背景图上,必须用 -strong 档(5.13:1),基础色只有 3.14:1 */
|
gap: 8px;
|
||||||
color: var(--admin-coral-strong);
|
padding: 4px 14px 4px 8px;
|
||||||
}
|
|
||||||
|
|
||||||
.scene-benefits .el-icon {
|
|
||||||
grid-row: 1 / 3;
|
|
||||||
font-size: var(--font-size-4xl);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-benefits b {
|
|
||||||
font-size: var(--font-size-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-benefits small {
|
|
||||||
margin-top: 2px;
|
|
||||||
color: var(--color-text-tertiary);
|
|
||||||
font-size: var(--font-size-micro);
|
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
background: var(--admin-scene-surface);
|
||||||
|
border: 1px solid var(--admin-coral-border);
|
||||||
|
border-radius: 18px;
|
||||||
|
color: var(--admin-coral-strong);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
box-shadow: 0 1px 4px rgba(200, 74, 83, 0.06);
|
||||||
|
}
|
||||||
|
.scene-benefits b {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
line-height: 1.1;
|
||||||
|
}
|
||||||
|
.scene-benefits small {
|
||||||
|
color: var(--color-text-tertiary);
|
||||||
|
font-size: 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
white-space: nowrap;
|
||||||
|
line-height: 1.1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-shell {
|
.admin-shell {
|
||||||
width: min(var(--admin-shell-max-width), 100%);
|
width: min(var(--admin-shell-max-width), 100%);
|
||||||
height: calc(100vh - 238px);
|
flex: 1;
|
||||||
min-height: 560px;
|
min-height: 0;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--admin-shell-bg);
|
background: var(--admin-shell-bg);
|
||||||
@@ -427,6 +644,8 @@ function handleLogout() {
|
|||||||
height: 42px;
|
height: 42px;
|
||||||
flex: none;
|
flex: none;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
|
border-radius: 50%;
|
||||||
|
clip-path: circle(50%);
|
||||||
}
|
}
|
||||||
|
|
||||||
.brand-copy {
|
.brand-copy {
|
||||||
@@ -629,10 +848,15 @@ function handleLogout() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-content {
|
.admin-content {
|
||||||
|
height: 100%;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
background: var(--color-bg-page);
|
scrollbar-width: none; /* Firefox */
|
||||||
|
-ms-overflow-style: none; /* IE/Edge 旧版 */
|
||||||
|
/* 暖色调背景,与整体品牌粉调一致;冷灰蓝 --color-bg-page 仅用于通用组件 */
|
||||||
|
background: var(--admin-scene-bg-end);
|
||||||
}
|
}
|
||||||
|
.admin-content::-webkit-scrollbar { display: none; } /* Chrome/Safari/Edge */
|
||||||
|
|
||||||
.scene-footer {
|
.scene-footer {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -656,62 +880,49 @@ function handleLogout() {
|
|||||||
letter-spacing: 4px;
|
letter-spacing: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 1450px), (max-height: 820px) {
|
@media (max-width: 1280px), (max-height: 780px) {
|
||||||
.admin-scene {
|
.admin-scene {
|
||||||
padding: 12px 24px 10px;
|
padding: 12px 24px 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-header {
|
.scene-header {
|
||||||
display: grid;
|
height: 160px;
|
||||||
height: 120px;
|
grid-template-columns: minmax(480px, 1fr) auto;
|
||||||
grid-template-columns: minmax(520px, 1fr) auto;
|
grid-template-rows: 92px 64px;
|
||||||
grid-template-rows: 66px 54px;
|
padding-top: 14px;
|
||||||
column-gap: 18px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.scene-slogan {
|
.brand-logo-wrap { width: 64px; height: 64px; }
|
||||||
padding-right: var(--space-3);
|
.brand-logo-wrap img { width: 56px; height: 56px; }
|
||||||
}
|
.brand-dot { display: none; }
|
||||||
|
|
||||||
.scene-slogan span {
|
.brand-name-row strong { font-size: 30px; letter-spacing: 3px; }
|
||||||
font-size: var(--font-size-base);
|
.brand-badge { display: none; }
|
||||||
}
|
.brand-tagline { font-size: 12px; letter-spacing: 2px; }
|
||||||
|
.brand-ornament { display: none; }
|
||||||
.scene-slogan strong {
|
|
||||||
font-size: var(--font-size-2xl);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-brand > img {
|
|
||||||
width: 52px;
|
|
||||||
height: 52px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-brand-copy strong {
|
|
||||||
font-size: var(--font-size-2xl);
|
|
||||||
}
|
|
||||||
|
|
||||||
.scene-title {
|
.scene-title {
|
||||||
min-width: 310px;
|
min-width: 280px;
|
||||||
margin-left: 18px;
|
margin-left: 20px;
|
||||||
padding-left: 18px;
|
padding-left: 20px;
|
||||||
}
|
}
|
||||||
|
.scene-title h1 { font-size: 22px; letter-spacing: 1px; }
|
||||||
|
.title-sub { font-size: 12px; }
|
||||||
|
.title-meta { display: none; }
|
||||||
|
|
||||||
/* 紧凑态下正文标题略大于品牌字号,层级保持「页面 → 品牌」的正确指向 */
|
.slogan-top { font-size: 13px; letter-spacing: 6px; }
|
||||||
.scene-title h1 {
|
.slogan-main { font-size: 34px; letter-spacing: 4px; }
|
||||||
font-size: var(--font-size-3xl);
|
.slogan-en { display: none; }
|
||||||
}
|
|
||||||
|
|
||||||
.scene-benefits {
|
.benefit-icon { width: 34px; height: 34px; }
|
||||||
padding: 0 0 0 28px;
|
.benefit-icon .el-icon { font-size: 16px; }
|
||||||
gap: clamp(22px, 4vw, 54px);
|
|
||||||
}
|
.scene-benefits { gap: clamp(10px, 2vw, 28px); }
|
||||||
|
.scene-benefits b { font-size: 12px; }
|
||||||
|
.scene-benefits small { display: none; font-size: 12px; }
|
||||||
|
|
||||||
.admin-shell {
|
.admin-shell {
|
||||||
height: calc(100vh - 170px);
|
height: calc(100vh - 200px);
|
||||||
}
|
|
||||||
|
|
||||||
.scene-footer {
|
|
||||||
height: 28px;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,9 +49,9 @@
|
|||||||
<el-col :span="12">
|
<el-col :span="12">
|
||||||
<el-card shadow="never" class="inner-card">
|
<el-card shadow="never" class="inner-card">
|
||||||
<template #header><span>手工签到(特殊情形)</span></template>
|
<template #header><span>手工签到(特殊情形)</span></template>
|
||||||
<el-input v-model="manualUserId" placeholder="输入用户 ID" />
|
<el-input v-model="manualUserNumber" placeholder="输入13位用户编号" />
|
||||||
<div class="btn-row">
|
<div class="btn-row">
|
||||||
<el-button type="primary" :loading="saving" :disabled="!manualUserId"
|
<el-button type="primary" :loading="saving" :disabled="!manualUserNumber"
|
||||||
@click="manual">手工签到</el-button>
|
@click="manual">手工签到</el-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-hint">
|
<div class="form-hint">
|
||||||
@@ -65,8 +65,8 @@
|
|||||||
<el-card v-if="lastResult" shadow="never" class="inner-card result-card">
|
<el-card v-if="lastResult" shadow="never" class="inner-card result-card">
|
||||||
<template #header><span>最近一次签到</span></template>
|
<template #header><span>最近一次签到</span></template>
|
||||||
<el-descriptions :column="2" border size="small">
|
<el-descriptions :column="2" border size="small">
|
||||||
<el-descriptions-item label="用户 ID">{{ lastResult.userId }}</el-descriptions-item>
|
<el-descriptions-item label="用户编号">{{ lastResult.userDisplayNumber }}</el-descriptions-item>
|
||||||
<el-descriptions-item label="活动 ID">{{ lastResult.activityId }}</el-descriptions-item>
|
<el-descriptions-item label="活动编号">{{ lastResult.activityDisplayId }}</el-descriptions-item>
|
||||||
<el-descriptions-item label="本次是否为重复签到">
|
<el-descriptions-item label="本次是否为重复签到">
|
||||||
<el-tag :type="lastResult.alreadyCheckedIn ? 'warning' : 'success'" size="small">
|
<el-tag :type="lastResult.alreadyCheckedIn ? 'warning' : 'success'" size="small">
|
||||||
{{ lastResult.alreadyCheckedIn ? '是(已幂等,未重复记录)' : '否' }}
|
{{ lastResult.alreadyCheckedIn ? '是(已幂等,未重复记录)' : '否' }}
|
||||||
@@ -80,6 +80,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
/**
|
/**
|
||||||
* U32 活动签到工作台(Phase 15)
|
* U32 活动签到工作台(Phase 15)
|
||||||
*
|
*
|
||||||
@@ -95,7 +96,7 @@ import { get, post } from '@/api/client'
|
|||||||
const activities = ref<any[]>([])
|
const activities = ref<any[]>([])
|
||||||
const activityId = ref('')
|
const activityId = ref('')
|
||||||
const token = ref('')
|
const token = ref('')
|
||||||
const manualUserId = ref('')
|
const manualUserNumber = ref('')
|
||||||
const stats = ref<any>(null)
|
const stats = ref<any>(null)
|
||||||
const lastResult = ref<any>(null)
|
const lastResult = ref<any>(null)
|
||||||
const scanning = ref(false)
|
const scanning = ref(false)
|
||||||
@@ -111,7 +112,7 @@ const TYPE_TEXT: Record<string, string> = {
|
|||||||
}
|
}
|
||||||
const typeText = (t: string) => TYPE_TEXT[t] || t || '未分类'
|
const typeText = (t: string) => TYPE_TEXT[t] || t || '未分类'
|
||||||
|
|
||||||
const authHeader = () => ({ Authorization: `Bearer ${localStorage.getItem('accessToken') || ''}` })
|
const authHeader = () => ({ Authorization: `Bearer ${getAccessToken() || ''}` })
|
||||||
|
|
||||||
const formatTime = (v: any) => {
|
const formatTime = (v: any) => {
|
||||||
if (!v) return '-'
|
if (!v) return '-'
|
||||||
@@ -150,15 +151,15 @@ async function scan() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function manual() {
|
async function manual() {
|
||||||
if (!activityId.value || !manualUserId.value.trim()) return
|
if (!activityId.value || !manualUserNumber.value.trim()) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const res: any = await post(
|
const res: any = await post(
|
||||||
`/activities/operator/${activityId.value}/checkin/manual`,
|
`/activities/operator/${activityId.value}/checkin/manual`,
|
||||||
{ userId: manualUserId.value.trim() },
|
{ userId: manualUserNumber.value.trim() },
|
||||||
authHeader())
|
authHeader())
|
||||||
lastResult.value = { ...res.data, userId: manualUserId.value.trim(), activityId: activityId.value }
|
lastResult.value = { ...res.data, userDisplayNumber: res.data?.userDisplayNumber || manualUserNumber.value.trim(), activityDisplayId: activities.value.find((item: any) => item.id === activityId.value)?.displayId }
|
||||||
manualUserId.value = ''
|
manualUserNumber.value = ''
|
||||||
ElMessage.success(res.data?.alreadyCheckedIn ? '该用户已签到(未重复记录)' : '手工签到成功')
|
ElMessage.success(res.data?.alreadyCheckedIn ? '该用户已签到(未重复记录)' : '手工签到成功')
|
||||||
await loadStats()
|
await loadStats()
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
<template #header>
|
<template #header>
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<span>活动互选管理</span>
|
<span>活动互选管理</span>
|
||||||
<el-input v-model="searchActivityId" placeholder="活动ID搜索" clearable style="width:260px" />
|
<el-input v-model="searchActivityNumber" placeholder="活动编号搜索" clearable style="width:260px" />
|
||||||
<el-button type="primary" @click="loadData" :loading="loading">查询</el-button>
|
<el-button type="primary" @click="loadData" :loading="loading">查询</el-button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<el-table :data="tableData" v-loading="loading" border stripe>
|
<el-table :data="tableData" v-loading="loading" border stripe>
|
||||||
<el-table-column prop="activityId" label="活动ID" width="160" />
|
<el-table-column prop="activityDisplayId" label="活动编号" width="160" />
|
||||||
<el-table-column prop="activityTitle" label="活动名称" min-width="180" />
|
<el-table-column prop="activityTitle" label="活动名称" min-width="180" />
|
||||||
<el-table-column label="双向互选对数" width="140">
|
<el-table-column label="双向互选对数" width="140">
|
||||||
<template #default="{row}">{{ row.mutualPairs }} 对</template>
|
<template #default="{row}">{{ row.mutualPairs }} 对</template>
|
||||||
@@ -31,8 +31,8 @@
|
|||||||
<div v-if="currentActivity">
|
<div v-if="currentActivity">
|
||||||
<h4>{{ currentActivity.title }} — 双向互选列表</h4>
|
<h4>{{ currentActivity.title }} — 双向互选列表</h4>
|
||||||
<el-table :data="mutualList" border size="small" style="margin-top:16px">
|
<el-table :data="mutualList" border size="small" style="margin-top:16px">
|
||||||
<el-table-column prop="sourceUserId" label="表达者ID" min-width="180" />
|
<el-table-column prop="sourceUserDisplayNumber" label="表达者编号" min-width="180" />
|
||||||
<el-table-column prop="targetUserId" label="被表达者ID" min-width="180" />
|
<el-table-column prop="targetUserDisplayNumber" label="被表达者编号" min-width="180" />
|
||||||
<el-table-column prop="confirmedAt" label="确认时间" width="180" />
|
<el-table-column prop="confirmedAt" label="确认时间" width="180" />
|
||||||
</el-table>
|
</el-table>
|
||||||
<el-empty v-if="!mutualList.length" description="暂无双向互选记录" />
|
<el-empty v-if="!mutualList.length" description="暂无双向互选记录" />
|
||||||
@@ -42,10 +42,11 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get } from '@/api/client'
|
import { get } from '@/api/client'
|
||||||
|
|
||||||
const searchActivityId = ref('')
|
const searchActivityNumber = ref('')
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const tableData = ref<any[]>([])
|
const tableData = ref<any[]>([])
|
||||||
const drawerVisible = ref(false)
|
const drawerVisible = ref(false)
|
||||||
@@ -55,11 +56,11 @@ const mutualList = ref<any[]>([])
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/activities/operator/activity-interest-summary', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/activities/operator/activity-interest-summary', {}, { Authorization: `Bearer ${token}` })
|
||||||
const rows = res.data || []
|
const rows = res.data || []
|
||||||
tableData.value = searchActivityId.value
|
tableData.value = searchActivityNumber.value
|
||||||
? rows.filter((row: any) => row.activityId.includes(searchActivityId.value.trim()))
|
? rows.filter((row: any) => (row.activityDisplayId || '').includes(searchActivityNumber.value.trim()))
|
||||||
: rows
|
: rows
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
@@ -72,7 +73,7 @@ async function viewMutuals(activityId: string) {
|
|||||||
drawerVisible.value = true
|
drawerVisible.value = true
|
||||||
currentActivity.value = tableData.value.find(row => row.activityId === activityId)
|
currentActivity.value = tableData.value.find(row => row.activityId === activityId)
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const mutualRes: any = await get(`/activities/operator/${activityId}/mutuals`, {}, { Authorization: `Bearer ${token}` })
|
const mutualRes: any = await get(`/activities/operator/${activityId}/mutuals`, {}, { Authorization: `Bearer ${token}` })
|
||||||
mutualList.value = mutualRes.data || []
|
mutualList.value = mutualRes.data || []
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<el-table :data="tableData" v-loading="loading" border stripe>
|
<el-table :data="tableData" v-loading="loading" border stripe>
|
||||||
|
<el-table-column prop="displayId" label="活动编号" min-width="180" />
|
||||||
<el-table-column prop="title" label="活动名称" min-width="180" />
|
<el-table-column prop="title" label="活动名称" min-width="180" />
|
||||||
<el-table-column prop="activityType" label="活动类型" width="130">
|
<el-table-column prop="activityType" label="活动类型" width="130">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
@@ -128,7 +129,6 @@
|
|||||||
<el-dialog v-model="orgVisible" title="活动组织与容量分组" width="640px">
|
<el-dialog v-model="orgVisible" title="活动组织与容量分组" width="640px">
|
||||||
<h4>组织关系</h4>
|
<h4>组织关系</h4>
|
||||||
<el-table :data="orgs" border size="small">
|
<el-table :data="orgs" border size="small">
|
||||||
<el-table-column prop="organizationId" label="组织ID" min-width="160" />
|
|
||||||
<el-table-column prop="name" label="名称" min-width="140" />
|
<el-table-column prop="name" label="名称" min-width="140" />
|
||||||
<el-table-column prop="role" label="角色" width="120">
|
<el-table-column prop="role" label="角色" width="120">
|
||||||
<template #default="{ row }">{{ roleText(row.role) }}</template>
|
<template #default="{ row }">{{ roleText(row.role) }}</template>
|
||||||
@@ -168,6 +168,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
/**
|
/**
|
||||||
* 活动管理(V1.1 Phase 14)
|
* 活动管理(V1.1 Phase 14)
|
||||||
*
|
*
|
||||||
@@ -259,7 +260,7 @@ function emptyForm() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function authHeader() {
|
function authHeader() {
|
||||||
return { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
|
return { Authorization: `Bearer ${getAccessToken()}` }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
|
|||||||
@@ -213,6 +213,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, computed, onMounted } from 'vue'
|
import { ref, computed, onMounted } from 'vue'
|
||||||
import { get } from '@/api/client'
|
import { get } from '@/api/client'
|
||||||
import { token } from '@/theme/tokens'
|
import { token } from '@/theme/tokens'
|
||||||
@@ -302,7 +303,7 @@ async function loadFunnel() {
|
|||||||
try {
|
try {
|
||||||
// 注意:这里曾是 `const token = ...`,与顶部从 @/theme/tokens 导入的**颜色助手**
|
// 注意:这里曾是 `const token = ...`,与顶部从 @/theme/tokens 导入的**颜色助手**
|
||||||
// `token` 同名(函数内遮蔽)。现已改名 authToken,避免后续在函数内误用颜色助手。
|
// `token` 同名(函数内遮蔽)。现已改名 authToken,避免后续在函数内误用颜色助手。
|
||||||
const authToken = localStorage.getItem('accessToken')
|
const authToken = getAccessToken()
|
||||||
if (dateRange.value[0] && dateRange.value[1]) {
|
if (dateRange.value[0] && dateRange.value[1]) {
|
||||||
const [userRes, matchRes, safetyRes, v11Res]: any[] = await Promise.all([
|
const [userRes, matchRes, safetyRes, v11Res]: any[] = await Promise.all([
|
||||||
get('/operator/analytics/user-funnel', {
|
get('/operator/analytics/user-funnel', {
|
||||||
@@ -328,7 +329,7 @@ async function loadFunnel() {
|
|||||||
|
|
||||||
async function loadDailySummary() {
|
async function loadDailySummary() {
|
||||||
try {
|
try {
|
||||||
const authToken = localStorage.getItem('accessToken')
|
const authToken = getAccessToken()
|
||||||
const res: any = await get('/operator/analytics/daily-summary', { days: 30 }, { Authorization: `Bearer ${authToken}` })
|
const res: any = await get('/operator/analytics/daily-summary', { days: 30 }, { Authorization: `Bearer ${authToken}` })
|
||||||
dailySummary.value = res.data || []
|
dailySummary.value = res.data || []
|
||||||
} catch (e) { console.error(e) }
|
} catch (e) { console.error(e) }
|
||||||
|
|||||||
@@ -84,6 +84,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get, post } from '@/api/client'
|
import { get, post } from '@/api/client'
|
||||||
import { token as tokenColor } from '@/theme/tokens'
|
import { token as tokenColor } from '@/theme/tokens'
|
||||||
@@ -109,7 +110,7 @@ const STATUS_MAP: Record<string, { text: string; type: string }> = {
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/appeals/pending', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/operator/appeals/pending', {}, { Authorization: `Bearer ${token}` })
|
||||||
tableData.value = res.data || []
|
tableData.value = res.data || []
|
||||||
loadStats()
|
loadStats()
|
||||||
@@ -119,7 +120,7 @@ async function loadData() {
|
|||||||
|
|
||||||
async function loadStats() {
|
async function loadStats() {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/appeals/stats', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/operator/appeals/stats', {}, { Authorization: `Bearer ${token}` })
|
||||||
const data = res.data || {}
|
const data = res.data || {}
|
||||||
stats.value = [
|
stats.value = [
|
||||||
@@ -138,7 +139,7 @@ async function openDetail(id: string) {
|
|||||||
decision.value = 'approve'
|
decision.value = 'approve'
|
||||||
decisionNote.value = ''
|
decisionNote.value = ''
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get(`/operator/appeals/${id}`, {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get(`/operator/appeals/${id}`, {}, { Authorization: `Bearer ${token}` })
|
||||||
detail.value = res.data
|
detail.value = res.data
|
||||||
} catch (e) { console.error(e) }
|
} catch (e) { console.error(e) }
|
||||||
@@ -148,7 +149,7 @@ async function handleProcess() {
|
|||||||
if (!decision.value) return
|
if (!decision.value) return
|
||||||
processing.value = true
|
processing.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
await post(`/operator/appeals/${currentId.value}/process`,
|
await post(`/operator/appeals/${currentId.value}/process`,
|
||||||
{ decision: decision.value, decisionNote: decisionNote.value },
|
{ decision: decision.value, decisionNote: decisionNote.value },
|
||||||
{ Authorization: `Bearer ${token}` })
|
{ Authorization: `Bearer ${token}` })
|
||||||
|
|||||||
@@ -16,14 +16,14 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<el-table :data="tableData" v-loading="loading" border stripe>
|
<el-table :data="tableData" v-loading="loading" border stripe>
|
||||||
<el-table-column prop="operatorId" label="操作人ID" width="140" />
|
<el-table-column prop="operatorDisplayId" label="操作人编号" min-width="180" />
|
||||||
<el-table-column prop="action" label="操作" width="160">
|
<el-table-column prop="action" label="操作" width="160">
|
||||||
<template #default="{row}">{{ actionText(row.action) }}</template>
|
<template #default="{row}">{{ actionText(row.action) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="resourceType" label="资源类型" width="120">
|
<el-table-column prop="resourceType" label="资源类型" width="120">
|
||||||
<template #default="{row}">{{ row.resourceType }}</template>
|
<template #default="{row}">{{ row.resourceType }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="resourceId" label="资源ID" width="140" show-overflow-tooltip />
|
<el-table-column prop="resourceDisplayId" label="业务编号" min-width="180" show-overflow-tooltip><template #default="{ row }">{{ row.resourceDisplayId || '未公开编号(已脱敏)' }}</template></el-table-column>
|
||||||
<el-table-column prop="ip" label="IP地址" width="140" />
|
<el-table-column prop="ip" label="IP地址" width="140" />
|
||||||
<el-table-column prop="createdAt" label="时间" width="180">
|
<el-table-column prop="createdAt" label="时间" width="180">
|
||||||
<template #default="{row}">{{ formatTime(row.createdAt) }}</template>
|
<template #default="{row}">{{ formatTime(row.createdAt) }}</template>
|
||||||
@@ -38,6 +38,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get } from '@/api/client'
|
import { get } from '@/api/client'
|
||||||
|
|
||||||
@@ -70,7 +71,7 @@ const ACTION_TEXT: Record<string, string> = {
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/audit/logs', {
|
const res: any = await get('/operator/audit/logs', {
|
||||||
resourceType: resourceFilter.value || undefined,
|
resourceType: resourceFilter.value || undefined,
|
||||||
page: page.value,
|
page: page.value,
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ function isExternalLink(value: string) {
|
|||||||
function previewTargetText(banner: any) {
|
function previewTargetText(banner: any) {
|
||||||
const dest = TARGET_TYPE_DEST[banner.targetType] || banner.targetType || '无'
|
const dest = TARGET_TYPE_DEST[banner.targetType] || banner.targetType || '无'
|
||||||
if (!banner.targetValue) return dest
|
if (!banner.targetValue) return dest
|
||||||
return `${dest} · ${banner.targetValue}`
|
return `${dest} · 已配置站内目标`
|
||||||
}
|
}
|
||||||
function assignForm(source: any) {
|
function assignForm(source: any) {
|
||||||
form.value = {
|
form.value = {
|
||||||
|
|||||||
@@ -88,7 +88,7 @@
|
|||||||
<el-dialog v-model="assignDialogVisible" title="分配咨询师" width="400px">
|
<el-dialog v-model="assignDialogVisible" title="分配咨询师" width="400px">
|
||||||
<el-form label-width="80px">
|
<el-form label-width="80px">
|
||||||
<el-form-item label="咨询师">
|
<el-form-item label="咨询师">
|
||||||
<el-input v-model="assignForm.counselorId" placeholder="请输入咨询师工号 / ID" />
|
<el-input v-model="assignForm.counselorNumber" placeholder="请输入13位工作人员编号" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -143,7 +143,7 @@ const assignedServices = ref<any[]>([])
|
|||||||
const assignDialogVisible = ref(false)
|
const assignDialogVisible = ref(false)
|
||||||
const followupDialogVisible = ref(false)
|
const followupDialogVisible = ref(false)
|
||||||
const currentId = ref('')
|
const currentId = ref('')
|
||||||
const assignForm = ref({ counselorId: '' })
|
const assignForm = ref({ counselorNumber: '' })
|
||||||
const followupForm = ref({ type: 'phone_call', content: '' })
|
const followupForm = ref({ type: 'phone_call', content: '' })
|
||||||
|
|
||||||
const SERVICE_TYPE_LABEL: Record<string, string> = {
|
const SERVICE_TYPE_LABEL: Record<string, string> = {
|
||||||
@@ -211,19 +211,19 @@ function onTabChange(name: string | number) {
|
|||||||
|
|
||||||
function openAssign(row: any) {
|
function openAssign(row: any) {
|
||||||
currentId.value = row.id
|
currentId.value = row.id
|
||||||
assignForm.value.counselorId = ''
|
assignForm.value.counselorNumber = ''
|
||||||
assignDialogVisible.value = true
|
assignDialogVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
async function doAssign() {
|
async function doAssign() {
|
||||||
if (!assignForm.value.counselorId) {
|
if (!assignForm.value.counselorNumber) {
|
||||||
ElMessage.warning('请填写咨询师 ID')
|
ElMessage.warning('请填写咨询师编号')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
await post(`/counseling/services/operator/${currentId.value}/assign`,
|
await post(`/counseling/services/operator/${currentId.value}/assign`,
|
||||||
{ counselorId: assignForm.value.counselorId })
|
{ counselorId: assignForm.value.counselorNumber })
|
||||||
ElMessage.success('分配成功')
|
ElMessage.success('分配成功')
|
||||||
assignDialogVisible.value = false
|
assignDialogVisible.value = false
|
||||||
loadQueue()
|
loadQueue()
|
||||||
|
|||||||
@@ -2,10 +2,24 @@
|
|||||||
<div class="matchmaker-management">
|
<div class="matchmaker-management">
|
||||||
<el-card>
|
<el-card>
|
||||||
<template #header><div class="card-header"><span>公益红娘管理</span></div></template>
|
<template #header><div class="card-header"><span>公益红娘管理</span></div></template>
|
||||||
<el-tabs v-model="activeTab">
|
<el-tabs v-model="activeTab" @tab-change="refresh">
|
||||||
<el-tab-pane label="服务请求队列" name="services">
|
<el-tab-pane v-if="canAssign" label="服务进展与跟进" name="management">
|
||||||
|
<el-table :data="managedServices" stripe v-loading="loading">
|
||||||
|
<el-table-column prop="userDisplayNumber" label="用户编号" min-width="150" />
|
||||||
|
<el-table-column prop="operatorDisplayId" label="红娘编号" min-width="150" />
|
||||||
|
<el-table-column label="服务状态" width="120"><template #default="{ row }">{{ statusLabel(row.status) }}</template></el-table-column>
|
||||||
|
<el-table-column prop="latestFollowupContent" label="最新跟进" min-width="230" show-overflow-tooltip />
|
||||||
|
<el-table-column label="操作" width="110"><template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="openServiceDetail(row.serviceId, true)">查看记录</el-button>
|
||||||
|
</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-tab-pane>
|
||||||
|
<!-- 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 :data="services" stripe v-loading="loading">
|
||||||
<el-table-column prop="userId" label="用户ID" width="120" />
|
<el-table-column prop="userDisplayNumber" label="用户编号" width="190">
|
||||||
|
<template #default="{ row }">{{ row.userDisplayNumber || '实名后生成' }}</template>
|
||||||
|
</el-table-column>
|
||||||
<el-table-column prop="serviceType" label="服务类型" width="160">
|
<el-table-column prop="serviceType" label="服务类型" width="160">
|
||||||
<template #default="{ row }">{{ serviceTypeLabel(row.serviceType) }}</template>
|
<template #default="{ row }">{{ serviceTypeLabel(row.serviceType) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
@@ -19,7 +33,8 @@
|
|||||||
<el-table-column label="操作" width="200">
|
<el-table-column label="操作" width="200">
|
||||||
<template #default="{ row }">
|
<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==='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>
|
||||||
|
<el-button v-if="row.status!=='submitted'" size="small" @click="openServiceDetail(row.serviceId || row.id)">查看服务</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
</el-table>
|
</el-table>
|
||||||
@@ -27,8 +42,8 @@
|
|||||||
|
|
||||||
<el-tab-pane label="推荐列表" name="recommendations">
|
<el-tab-pane label="推荐列表" name="recommendations">
|
||||||
<el-table :data="recommendations" stripe v-loading="loading">
|
<el-table :data="recommendations" stripe v-loading="loading">
|
||||||
<el-table-column prop="userId" label="用户" width="110" />
|
<el-table-column prop="userDisplayNumber" label="用户" width="110" />
|
||||||
<el-table-column prop="targetUserId" label="推荐对象" width="110" />
|
<el-table-column prop="targetUserDisplayNumber" label="推荐对象" width="110" />
|
||||||
<el-table-column prop="reason" label="推荐理由" show-overflow-tooltip />
|
<el-table-column prop="reason" label="推荐理由" show-overflow-tooltip />
|
||||||
<el-table-column prop="status" label="状态" width="130">
|
<el-table-column prop="status" label="状态" width="130">
|
||||||
<template #default="{ row }"><el-tag :type="recStatusTag(row.status)">{{ recStatusLabel(row.status) }}</el-tag></template>
|
<template #default="{ row }"><el-tag :type="recStatusTag(row.status)">{{ recStatusLabel(row.status) }}</el-tag></template>
|
||||||
@@ -38,16 +53,80 @@
|
|||||||
</el-table-column>
|
</el-table-column>
|
||||||
</el-table>
|
</el-table>
|
||||||
</el-tab-pane>
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<!-- ZC-MM-002 新增:服务对象分配(本人名下生效中的分配 + 转分配/撤销/结束) -->
|
||||||
|
<el-tab-pane label="服务对象分配" name="assignments">
|
||||||
|
<el-table :data="assignments" stripe v-loading="assignmentsLoading">
|
||||||
|
<el-table-column prop="userDisplayNumber" label="用户编号" width="190">
|
||||||
|
<template #default="{ row }">{{ row.userDisplayNumber || '实名后生成' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<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 v-if="row.serviceId" size="small" @click="openServiceDetail(row.serviceId)">查看服务</el-button>
|
||||||
|
<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="operatorDisplayId" label="红娘编号" width="120" />
|
||||||
|
<el-table-column prop="userDisplayNumber" label="用户编号" 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-tabs>
|
||||||
</el-card>
|
</el-card>
|
||||||
|
|
||||||
<!-- 分配弹窗 -->
|
<!-- 分配弹窗(ZC-MM-002:去硬编码红娘名单,改为加载可分配红娘接口;理由必填) -->
|
||||||
<el-dialog v-model="assignDialogVisible" title="分配红娘服务" width="400px">
|
<el-dialog v-model="assignDialogVisible" title="分配红娘服务" width="440px">
|
||||||
<el-form label-width="80px">
|
<el-form label-width="90px">
|
||||||
<el-form-item label="红娘"><el-select v-model="assignForm.operatorId" placeholder="选择红娘">
|
<el-form-item label="红娘">
|
||||||
<el-option label="王红娘" value="operator_wang" />
|
<el-select v-model="assignForm.matchmakerOperatorId" placeholder="选择红娘" style="width: 100%">
|
||||||
<el-option label="陈红娘" value="operator_chen" />
|
<el-option v-for="op in assignableMatchmakers" :key="op.id" :label="op.name" :value="op.id" />
|
||||||
</el-select></el-form-item>
|
</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>
|
</el-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<el-button @click="assignDialogVisible=false">取消</el-button>
|
<el-button @click="assignDialogVisible=false">取消</el-button>
|
||||||
@@ -55,11 +134,42 @@
|
|||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</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-dialog v-model="recDialogVisible" title="创建红娘推荐" width="480px">
|
||||||
<el-form label-width="100px">
|
<el-form label-width="100px">
|
||||||
<el-form-item label="推荐给用户"><el-input v-model="recForm.userId" disabled /></el-form-item>
|
<el-form-item label="推荐给用户"><el-input v-model="recForm.userDisplayNumber" disabled /></el-form-item>
|
||||||
<el-form-item label="推荐对象ID"><el-input v-model="recForm.targetUserId" placeholder="输入被推荐对象的用户ID" /></el-form-item>
|
<el-form-item label="推荐对象编号"><el-input v-model="recForm.targetUserDisplayNumber" placeholder="输入13位用户编号" /></el-form-item>
|
||||||
<el-form-item label="推荐理由"><el-input v-model="recForm.reason" type="textarea" :rows="3" placeholder="说明为什么这个对象适合该用户" /></el-form-item>
|
<el-form-item label="推荐理由"><el-input v-model="recForm.reason" type="textarea" :rows="3" placeholder="说明为什么这个对象适合该用户" /></el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -67,33 +177,108 @@
|
|||||||
<el-button type="primary" @click="doCreateRecommendation">发送推荐</el-button>
|
<el-button type="primary" @click="doCreateRecommendation">发送推荐</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog v-model="serviceDetailVisible" title="服务详情" width="620px">
|
||||||
|
<el-descriptions v-if="serviceDetail" :column="2" border>
|
||||||
|
<el-descriptions-item label="服务编号">{{ serviceDetail.serviceDisplayId }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="状态">{{ statusLabel(serviceDetail.status) }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="服务类型">{{ serviceTypeLabel(serviceDetail.serviceType) }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="创建时间">{{ formatDateTime(serviceDetail.createdAt) }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="服务需求" :span="2">{{ serviceDetail.description || '未填写' }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
<el-divider content-position="left">服务历史</el-divider>
|
||||||
|
<el-empty v-if="!serviceDetail?.followups?.length" description="暂无服务记录" />
|
||||||
|
<el-timeline v-else>
|
||||||
|
<el-timeline-item v-for="item in serviceDetail.followups" :key="item.id" :timestamp="formatDateTime(item.createdAt)">
|
||||||
|
{{ item.content }}
|
||||||
|
</el-timeline-item>
|
||||||
|
</el-timeline>
|
||||||
|
<template v-if="serviceDetail && !managementDetail">
|
||||||
|
<el-divider />
|
||||||
|
<el-button type="primary" @click="openFollowup">添加跟进记录</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="['completed', 'cancelled'].indexOf(serviceDetail.status) < 0"
|
||||||
|
type="success"
|
||||||
|
plain
|
||||||
|
@click="completeCurrentService"
|
||||||
|
>完成服务</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog v-model="followupDialogVisible" title="添加跟进记录" width="520px">
|
||||||
|
<el-form label-width="90px">
|
||||||
|
<el-form-item label="跟进方式">
|
||||||
|
<el-select v-model="followupForm.followupType" style="width: 100%">
|
||||||
|
<el-option label="电话沟通" value="phone_call" />
|
||||||
|
<el-option label="微信沟通" value="wechat" />
|
||||||
|
<el-option label="面对面" value="face_to_face" />
|
||||||
|
<el-option label="其他" value="other" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="跟进内容" required>
|
||||||
|
<el-input v-model="followupForm.content" type="textarea" :rows="4" placeholder="记录本次服务进展" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="followupDialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="submitFollowup">保存记录</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, computed, onActivated } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
import { get, post } from '@/api/client'
|
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()
|
||||||
|
const route = useRoute()
|
||||||
|
const managementDetail = ref(false)
|
||||||
|
const managedServices = ref<any[]>([])
|
||||||
|
// 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 loading = ref(false)
|
||||||
const services = ref<any[]>([])
|
const services = ref<any[]>([])
|
||||||
const recommendations = ref<any[]>([])
|
const recommendations = ref<any[]>([])
|
||||||
|
const assignments = ref<any[]>([])
|
||||||
|
const assignmentsLoading = ref(false)
|
||||||
|
const assignableMatchmakers = ref<any[]>([])
|
||||||
const assignDialogVisible = ref(false)
|
const assignDialogVisible = ref(false)
|
||||||
|
const transferDialogVisible = ref(false)
|
||||||
|
const terminateDialogVisible = ref(false)
|
||||||
const recDialogVisible = ref(false)
|
const recDialogVisible = ref(false)
|
||||||
const currentServiceId = ref('')
|
const currentServiceId = ref('')
|
||||||
const assignForm = ref({ operatorId: '' })
|
const currentUserId = ref('')
|
||||||
const recForm = ref({ userId: '', targetUserId: '', reason: '' })
|
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({ userDisplayNumber: '', targetUserDisplayNumber: '', reason: '' })
|
||||||
|
const serviceDetailVisible = ref(false)
|
||||||
|
const serviceDetail = ref<any>(null)
|
||||||
|
const followupDialogVisible = ref(false)
|
||||||
|
const followupForm = ref({ followupType: 'phone_call', content: '' })
|
||||||
|
|
||||||
const SERVICE_TYPE_LABEL: Record<string, string> = {
|
const SERVICE_TYPE_LABEL: Record<string, string> = {
|
||||||
recommendation: '推荐对象', referral_counseling: '转介咨询',
|
recommendation: '推荐对象', referral_counseling: '转介咨询',
|
||||||
referral_activity: '转介活动', referral_station: '转介服务站'
|
referral_activity: '转介活动', referral_station: '转介服务站'
|
||||||
}
|
}
|
||||||
const STATUS_LABEL: Record<string, string> = {
|
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> = {
|
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> = {
|
const REC_STATUS_LABEL: Record<string, string> = {
|
||||||
pending_view: '待用户查看', viewed: '已查看', liked: '已喜欢',
|
pending_view: '待用户查看', viewed: '已查看', liked: '已喜欢',
|
||||||
@@ -103,18 +288,128 @@ const REC_STATUS_TAG: Record<string, string> = {
|
|||||||
pending_view: 'warning', viewed: 'info', liked: 'primary',
|
pending_view: 'warning', viewed: 'info', liked: 'primary',
|
||||||
passed: 'info', confirmed_mutual: 'success', rejected: 'danger', expired: 'info'
|
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 serviceTypeLabel(t: string) { return SERVICE_TYPE_LABEL[t] || t }
|
||||||
function statusLabel(s: string) { return STATUS_LABEL[s] || s }
|
function statusLabel(s: string) { return STATUS_LABEL[s] || s }
|
||||||
function statusTag(s: string) { return STATUS_TAG[s] || 'info' }
|
function statusTag(s: string) { return STATUS_TAG[s] || 'info' }
|
||||||
function recStatusLabel(s: string) { return REC_STATUS_LABEL[s] || s }
|
function recStatusLabel(s: string) { return REC_STATUS_LABEL[s] || s }
|
||||||
function recStatusTag(s: string) { return REC_STATUS_TAG[s] || 'info' }
|
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 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' }
|
||||||
|
|
||||||
|
async function openServiceDetail(serviceId: string, management = false) {
|
||||||
|
managementDetail.value = management
|
||||||
|
if (!serviceId) return
|
||||||
|
try {
|
||||||
|
const res: any = await get(`/operator/matchmaker/${management ? 'management/' : ''}services/${serviceId}`)
|
||||||
|
serviceDetail.value = res?.data || null
|
||||||
|
serviceDetailVisible.value = true
|
||||||
|
} catch { serviceDetail.value = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function openFollowup() {
|
||||||
|
followupForm.value = { followupType: 'phone_call', content: '' }
|
||||||
|
followupDialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitFollowup() {
|
||||||
|
if (!followupForm.value.content.trim() || !serviceDetail.value?.serviceId) {
|
||||||
|
ElMessage.warning('请填写跟进内容')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await post(`/operator/matchmaker/services/${serviceDetail.value.serviceId}/followup`, followupForm.value)
|
||||||
|
ElMessage.success('跟进记录已保存')
|
||||||
|
followupDialogVisible.value = false
|
||||||
|
await openServiceDetail(serviceDetail.value.serviceId)
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.response?.data?.message || '保存跟进记录失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function completeCurrentService() {
|
||||||
|
if (!serviceDetail.value?.serviceId) return
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('确认将该红娘服务标记为已完成吗?', '完成服务', { type: 'warning' })
|
||||||
|
await post(`/operator/matchmaker/services/${serviceDetail.value.serviceId}/complete`, {})
|
||||||
|
ElMessage.success('服务已完成')
|
||||||
|
await openServiceDetail(serviceDetail.value.serviceId)
|
||||||
|
await loadAssignments()
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e !== 'cancel' && e !== 'close') ElMessage.error(e?.response?.data?.message || '完成服务失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 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 endpoint = canApprove.value
|
||||||
|
? '/operator/matchmaker/contact-authorizations/pending'
|
||||||
|
: '/operator/matchmaker/contact-authorizations/my'
|
||||||
|
const res: any = await get(endpoint)
|
||||||
|
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() {
|
async function loadServices() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
// Phase 13 契约修复:原 `/matchmaker/services/operator/queue` 后端不存在(404)。
|
// 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 }
|
try { const res: any = await get('/operator/matchmaker/pending'); services.value = res?.data || [] } finally { loading.value = false }
|
||||||
}
|
}
|
||||||
async function loadRecommendations() {
|
async function loadRecommendations() {
|
||||||
@@ -123,36 +418,109 @@ async function loadRecommendations() {
|
|||||||
// 后端新增 GET /operator/matchmaker/recommendations(限本人名下服务的推荐)。
|
// 后端新增 GET /operator/matchmaker/recommendations(限本人名下服务的推荐)。
|
||||||
try { const res: any = await get('/operator/matchmaker/recommendations'); recommendations.value = res?.data || [] } finally { loading.value = false }
|
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() {
|
async function refresh() {
|
||||||
if (activeTab.value === 'services') await loadServices(); else await loadRecommendations()
|
if (activeTab.value === 'management') {
|
||||||
|
loading.value = true
|
||||||
|
try { const res: any = await get('/operator/matchmaker/management/services'); managedServices.value = res?.data || [] }
|
||||||
|
finally { loading.value = false }
|
||||||
|
}
|
||||||
|
else 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() {
|
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 {
|
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()
|
ElMessage.success('分配成功'); assignDialogVisible.value = false; loadServices()
|
||||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
} 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) {
|
function openRecommendation(row: any) {
|
||||||
currentServiceId.value = row.id
|
currentServiceId.value = row.id
|
||||||
recForm.value = { userId: row.userId, targetUserId: '', reason: '' }
|
recForm.value = { userDisplayNumber: row.userDisplayNumber || '实名后生成', targetUserDisplayNumber: '', reason: '' }
|
||||||
recDialogVisible.value = true
|
recDialogVisible.value = true
|
||||||
}
|
}
|
||||||
async function doCreateRecommendation() {
|
async function doCreateRecommendation() {
|
||||||
if (!recForm.value.targetUserId || !recForm.value.reason) { ElMessage.warning('请填写推荐对象和理由'); return }
|
if (!recForm.value.targetUserDisplayNumber || !recForm.value.reason) { ElMessage.warning('请填写推荐对象和理由'); return }
|
||||||
// Phase 13 契约修复:原 POST /matchmaker/services/{id}/recommendation → 后端为 /operator/matchmaker/services/{id}/recommend
|
// Phase 13 契约修复:原 POST /matchmaker/services/{id}/recommendation → 后端为 /operator/matchmaker/services/{id}/recommend
|
||||||
try {
|
try {
|
||||||
await post(`/operator/matchmaker/services/${currentServiceId.value}/recommend`, {
|
await post(`/operator/matchmaker/services/${currentServiceId.value}/recommend`, {
|
||||||
targetUserId: recForm.value.targetUserId, reason: recForm.value.reason
|
targetUserId: recForm.value.targetUserDisplayNumber, reason: recForm.value.reason
|
||||||
})
|
})
|
||||||
ElMessage.success('推荐已发送给用户'); recDialogVisible.value = false; loadRecommendations()
|
ElMessage.success('推荐已发送给用户'); recDialogVisible.value = false; loadRecommendations()
|
||||||
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
} catch (e: any) { ElMessage.error(e?.response?.data?.message || '操作失败') }
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(refresh)
|
onActivated(async () => {
|
||||||
|
if (canAssign.value && typeof route.query.serviceId === 'string') {
|
||||||
|
activeTab.value = 'management'
|
||||||
|
await openServiceDetail(route.query.serviceId, true)
|
||||||
|
}
|
||||||
|
await refresh()
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
<el-table :data="tableData" v-loading="loading" border stripe>
|
<el-table :data="tableData" v-loading="loading" border stripe>
|
||||||
<el-table-column prop="username" label="用户名" width="140" />
|
<el-table-column prop="username" label="用户名" width="140" />
|
||||||
|
<el-table-column prop="displayId" label="人员编号" width="150" />
|
||||||
<el-table-column prop="name" label="姓名" width="120" />
|
<el-table-column prop="name" label="姓名" width="120" />
|
||||||
<el-table-column prop="organizationId" label="所属机构" width="160">
|
<el-table-column prop="organizationId" label="所属机构" width="160">
|
||||||
<template #default="{row}">{{ orgMap[row.organizationId] || '-' }}</template>
|
<template #default="{row}">{{ orgMap[row.organizationId] || '-' }}</template>
|
||||||
@@ -62,6 +63,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get, post, put } from '@/api/client'
|
import { get, post, put } from '@/api/client'
|
||||||
|
|
||||||
@@ -79,7 +81,7 @@ const orgMap = ref<Record<string, string>>({})
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
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}` })
|
const res: any = await get('/operator/operators', { page: page.value, pageSize: pageSize.value }, { Authorization: `Bearer ${token}` })
|
||||||
tableData.value = res.data?.list || []
|
tableData.value = res.data?.list || []
|
||||||
total.value = res.data?.total || 0
|
total.value = res.data?.total || 0
|
||||||
@@ -89,7 +91,7 @@ async function loadData() {
|
|||||||
|
|
||||||
async function loadOrgs() {
|
async function loadOrgs() {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/operators/organizations', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/operator/operators/organizations', {}, { Authorization: `Bearer ${token}` })
|
||||||
orgList.value = res.data || []
|
orgList.value = res.data || []
|
||||||
orgList.value.forEach(o => { orgMap.value[o.id] = o.name })
|
orgList.value.forEach(o => { orgMap.value[o.id] = o.name })
|
||||||
@@ -105,7 +107,7 @@ async function save() {
|
|||||||
if (!form.value.username || !form.value.password) return
|
if (!form.value.username || !form.value.password) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
await post('/operator/operators', form.value, { Authorization: `Bearer ${token}` })
|
await post('/operator/operators', form.value, { Authorization: `Bearer ${token}` })
|
||||||
formVisible.value = false
|
formVisible.value = false
|
||||||
loadData()
|
loadData()
|
||||||
@@ -115,7 +117,7 @@ async function save() {
|
|||||||
|
|
||||||
async function toggleStatus(row: any) {
|
async function toggleStatus(row: any) {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const action = row.status === 'normal' ? 'disable' : 'enable'
|
const action = row.status === 'normal' ? 'disable' : 'enable'
|
||||||
await put(`/operator/operators/${row.id}/${action}`, {}, { Authorization: `Bearer ${token}` })
|
await put(`/operator/operators/${row.id}/${action}`, {}, { Authorization: `Bearer ${token}` })
|
||||||
loadData()
|
loadData()
|
||||||
@@ -126,7 +128,7 @@ async function resetPwd(id: string) {
|
|||||||
const pwd = prompt('请输入新密码(至少8位)')
|
const pwd = prompt('请输入新密码(至少8位)')
|
||||||
if (!pwd || pwd.length < 8) return
|
if (!pwd || pwd.length < 8) return
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
await put(`/operator/operators/${id}/reset-password`, { newPassword: pwd }, { Authorization: `Bearer ${token}` })
|
await put(`/operator/operators/${id}/reset-password`, { newPassword: pwd }, { Authorization: `Bearer ${token}` })
|
||||||
} catch (e) { console.error(e) }
|
} catch (e) { console.error(e) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get, post, put } from '@/api/client'
|
import { get, post, put } from '@/api/client'
|
||||||
|
|
||||||
@@ -78,7 +79,7 @@ const ORG_TYPE_TEXT: Record<string, string> = {
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/organizations', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/operator/organizations', {}, { Authorization: `Bearer ${token}` })
|
||||||
tableData.value = res.data || []
|
tableData.value = res.data || []
|
||||||
} catch (e) { console.error(e) }
|
} catch (e) { console.error(e) }
|
||||||
@@ -101,7 +102,7 @@ async function save() {
|
|||||||
if (!form.value.name) return
|
if (!form.value.name) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
if (editId.value) {
|
if (editId.value) {
|
||||||
await put(`/operator/organizations/${editId.value}`, form.value, {
|
await put(`/operator/organizations/${editId.value}`, form.value, {
|
||||||
Authorization: `Bearer ${token}`
|
Authorization: `Bearer ${token}`
|
||||||
@@ -119,7 +120,7 @@ async function save() {
|
|||||||
|
|
||||||
async function toggleStatus(row: any) {
|
async function toggleStatus(row: any) {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const action = row.status === 'normal' ? 'disable' : 'enable'
|
const action = row.status === 'normal' ? 'disable' : 'enable'
|
||||||
await put(`/operator/organizations/${row.id}/${action}`, {}, {
|
await put(`/operator/organizations/${row.id}/${action}`, {}, {
|
||||||
Authorization: `Bearer ${token}`
|
Authorization: `Bearer ${token}`
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<el-table-column prop="type" label="类型" width="120">
|
<el-table-column prop="type" label="类型" width="120">
|
||||||
<template #default="{ row }"><el-tag>{{ typeLabel(row.type) }}</el-tag></template>
|
<template #default="{ row }"><el-tag>{{ typeLabel(row.type) }}</el-tag></template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="id" label="关联ID" width="120" />
|
<el-table-column prop="referralDisplayId" label="转介编号" min-width="180" />
|
||||||
<el-table-column prop="status" label="状态" width="100">
|
<el-table-column prop="status" label="状态" width="100">
|
||||||
<template #default="{ row }"><el-tag :type="row.status==='confirmed'?'success':'warning'">{{ row.status }}</el-tag></template>
|
<template #default="{ row }"><el-tag :type="row.status==='confirmed'?'success':'warning'">{{ row.status }}</el-tag></template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|||||||
@@ -20,7 +20,8 @@
|
|||||||
<el-tabs v-model="activeTab">
|
<el-tabs v-model="activeTab">
|
||||||
<el-tab-pane :label="`待审核队列(${pendingTasks.length})`" name="pending">
|
<el-tab-pane :label="`待审核队列(${pendingTasks.length})`" name="pending">
|
||||||
<el-table :data="pendingTasks" v-loading="loading" row-key="taskId">
|
<el-table :data="pendingTasks" v-loading="loading" row-key="taskId">
|
||||||
<el-table-column prop="userId" label="用户编号" min-width="170" show-overflow-tooltip />
|
<el-table-column prop="displayId" label="任务编号" min-width="180" />
|
||||||
|
<el-table-column prop="userDisplayNumber" label="用户编号" min-width="170" show-overflow-tooltip />
|
||||||
<el-table-column prop="reviewType" label="审核类型" min-width="130">
|
<el-table-column prop="reviewType" label="审核类型" min-width="130">
|
||||||
<template #default="{ row }">{{ reviewTypeText(row.reviewType) }}</template>
|
<template #default="{ row }">{{ reviewTypeText(row.reviewType) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
@@ -42,7 +43,8 @@
|
|||||||
|
|
||||||
<el-tab-pane :label="`我的审核(${myTasks.length})`" name="my">
|
<el-tab-pane :label="`我的审核(${myTasks.length})`" name="my">
|
||||||
<el-table :data="myTasks" v-loading="loading" row-key="taskId">
|
<el-table :data="myTasks" v-loading="loading" row-key="taskId">
|
||||||
<el-table-column prop="userId" label="用户编号" min-width="170" show-overflow-tooltip />
|
<el-table-column prop="displayId" label="任务编号" min-width="180" />
|
||||||
|
<el-table-column prop="userDisplayNumber" label="用户编号" min-width="170" show-overflow-tooltip />
|
||||||
<el-table-column prop="reviewType" label="审核类型" min-width="130">
|
<el-table-column prop="reviewType" label="审核类型" min-width="130">
|
||||||
<template #default="{ row }">{{ reviewTypeText(row.reviewType) }}</template>
|
<template #default="{ row }">{{ reviewTypeText(row.reviewType) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
@@ -65,7 +67,7 @@
|
|||||||
<div v-if="detailLoading" v-loading="true" class="drawer-loading"></div>
|
<div v-if="detailLoading" v-loading="true" class="drawer-loading"></div>
|
||||||
<template v-else-if="currentTask">
|
<template v-else-if="currentTask">
|
||||||
<el-descriptions :column="1" border>
|
<el-descriptions :column="1" border>
|
||||||
<el-descriptions-item label="用户编号">{{ currentTask.userId }}</el-descriptions-item>
|
<el-descriptions-item label="用户编号">{{ currentTask.userDisplayNumber }}</el-descriptions-item>
|
||||||
<el-descriptions-item label="审核类型">{{ reviewTypeText(currentTask.reviewType) }}</el-descriptions-item>
|
<el-descriptions-item label="审核类型">{{ reviewTypeText(currentTask.reviewType) }}</el-descriptions-item>
|
||||||
<el-descriptions-item label="提交时间">{{ formatTime(currentTask.submittedAt) }}</el-descriptions-item>
|
<el-descriptions-item label="提交时间">{{ formatTime(currentTask.submittedAt) }}</el-descriptions-item>
|
||||||
<el-descriptions-item label="当前状态">
|
<el-descriptions-item label="当前状态">
|
||||||
|
|||||||
@@ -25,7 +25,8 @@
|
|||||||
|
|
||||||
<el-table :data="tableData" v-loading="loading" border stripe>
|
<el-table :data="tableData" v-loading="loading" border stripe>
|
||||||
<el-table-column prop="reasonText" label="举报原因" width="140" />
|
<el-table-column prop="reasonText" label="举报原因" width="140" />
|
||||||
<el-table-column prop="reportedUserId" label="被举报人ID" width="140" />
|
<el-table-column prop="displayId" label="举报编号" min-width="180" />
|
||||||
|
<el-table-column prop="reportedUserDisplayNumber" label="被举报人编号" width="140" />
|
||||||
<el-table-column prop="description" label="说明" min-width="200" show-overflow-tooltip />
|
<el-table-column prop="description" label="说明" min-width="200" show-overflow-tooltip />
|
||||||
<el-table-column prop="status" label="状态" width="100">
|
<el-table-column prop="status" label="状态" width="100">
|
||||||
<template #default="{row}">
|
<template #default="{row}">
|
||||||
@@ -98,6 +99,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { getAccessToken } from '@/utils/token'
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { get, post } from '@/api/client'
|
import { get, post } from '@/api/client'
|
||||||
import { token as tokenColor } from '@/theme/tokens'
|
import { token as tokenColor } from '@/theme/tokens'
|
||||||
@@ -124,7 +126,7 @@ const STATUS_MAP: Record<string, { text: string; type: string }> = {
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get(`/operator/risk/reports/${statusFilter.value}`, {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get(`/operator/risk/reports/${statusFilter.value}`, {}, { Authorization: `Bearer ${token}` })
|
||||||
tableData.value = res.data || []
|
tableData.value = res.data || []
|
||||||
loadStats()
|
loadStats()
|
||||||
@@ -134,7 +136,7 @@ async function loadData() {
|
|||||||
|
|
||||||
async function loadStats() {
|
async function loadStats() {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get('/operator/risk/reports/stats', {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get('/operator/risk/reports/stats', {}, { Authorization: `Bearer ${token}` })
|
||||||
const data = res.data || {}
|
const data = res.data || {}
|
||||||
stats.value = [
|
stats.value = [
|
||||||
@@ -152,7 +154,7 @@ async function openDetail(reportId: string) {
|
|||||||
processResult.value = 'no_action'
|
processResult.value = 'no_action'
|
||||||
processNote.value = ''
|
processNote.value = ''
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
const res: any = await get(`/operator/risk/reports/${reportId}`, {}, { Authorization: `Bearer ${token}` })
|
const res: any = await get(`/operator/risk/reports/${reportId}`, {}, { Authorization: `Bearer ${token}` })
|
||||||
detail.value = res.data
|
detail.value = res.data
|
||||||
} catch (e) { console.error(e) }
|
} catch (e) { console.error(e) }
|
||||||
@@ -162,7 +164,7 @@ async function handleProcess() {
|
|||||||
if (!processResult.value) return
|
if (!processResult.value) return
|
||||||
processing.value = true
|
processing.value = true
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('accessToken')
|
const token = getAccessToken()
|
||||||
await post(`/operator/risk/reports/${currentReportId.value}/process`,
|
await post(`/operator/risk/reports/${currentReportId.value}/process`,
|
||||||
{ processResult: processResult.value, processNote: processNote.value },
|
{ processResult: processResult.value, processNote: processNote.value },
|
||||||
{ Authorization: `Bearer ${token}` })
|
{ Authorization: `Bearer ${token}` })
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
</el-radio-group>
|
</el-radio-group>
|
||||||
</div></template>
|
</div></template>
|
||||||
<el-table :data="appointments" stripe v-loading="loading">
|
<el-table :data="appointments" stripe v-loading="loading">
|
||||||
<el-table-column prop="id" label="ID" width="100" />
|
<el-table-column prop="displayId" label="预约编号" min-width="180" />
|
||||||
<el-table-column prop="userId" label="用户ID" width="120" />
|
<el-table-column prop="userDisplayNumber" label="用户编号" min-width="180" />
|
||||||
<el-table-column prop="serviceType" label="服务类型" width="150" />
|
<el-table-column prop="serviceType" label="服务类型" width="150" />
|
||||||
<el-table-column prop="source" label="来源" width="140">
|
<el-table-column prop="source" label="来源" width="140">
|
||||||
<template #default="{ row }"><el-tag size="small">{{ sourceLabel(row.source) }}</el-tag></template>
|
<template #default="{ row }"><el-tag size="small">{{ sourceLabel(row.source) }}</el-tag></template>
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
<template #default="{ row }"><el-tag :type="statusTag(row.status)">{{ statusLabel(row.status) }}</el-tag></template>
|
<template #default="{ row }"><el-tag :type="statusTag(row.status)">{{ statusLabel(row.status) }}</el-tag></template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="preferredDate" label="预约日期" width="110" />
|
<el-table-column prop="preferredDate" label="预约日期" width="110" />
|
||||||
<el-table-column prop="assignedOperatorId" label="分配人员" width="100" />
|
<el-table-column prop="assignedOperatorDisplayId" label="分配人员" width="100" />
|
||||||
<el-table-column prop="createdAt" label="创建时间" width="160">
|
<el-table-column prop="createdAt" label="创建时间" width="160">
|
||||||
<template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
<template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|||||||
@@ -74,7 +74,7 @@
|
|||||||
<el-descriptions-item label="合计">{{ stats.total }}</el-descriptions-item>
|
<el-descriptions-item label="合计">{{ stats.total }}</el-descriptions-item>
|
||||||
</el-descriptions>
|
</el-descriptions>
|
||||||
<el-table :data="members" stripe v-loading="memberLoading">
|
<el-table :data="members" stripe v-loading="memberLoading">
|
||||||
<el-table-column prop="userId" label="用户ID" width="200" show-overflow-tooltip />
|
<el-table-column prop="userDisplayNumber" label="用户编号" width="200" show-overflow-tooltip />
|
||||||
<el-table-column prop="status" label="状态" width="110">
|
<el-table-column prop="status" label="状态" width="110">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-tag :type="memberStatusTag(row.status)">{{ memberStatusLabel(row.status) }}</el-tag>
|
<el-tag :type="memberStatusTag(row.status)">{{ memberStatusLabel(row.status) }}</el-tag>
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
<section v-else-if="user" class="surface-card detail-card">
|
<section v-else-if="user" class="surface-card detail-card">
|
||||||
<div class="identity-summary">
|
<div class="identity-summary">
|
||||||
<el-avatar :size="58">{{ (user.displayName || '用')[0] }}</el-avatar>
|
<el-avatar :size="58">{{ (user.displayName || '用')[0] }}</el-avatar>
|
||||||
<div><h2>{{ user.displayName || '未设置显示名称' }}</h2><span>用户编号:{{ user.id }}</span></div>
|
<div><h2>{{ user.displayName || '未设置显示名称' }}</h2><span>用户编号:{{ user.displayNumber || '实名后生成' }}</span></div>
|
||||||
<el-progress class="completion" type="dashboard" :percentage="user.profileCompletion || 0" :width="72" :stroke-width="7" color="var(--admin-coral-solid)" />
|
<el-progress class="completion" type="dashboard" :percentage="user.profileCompletion || 0" :width="72" :stroke-width="7" color="var(--admin-coral-solid)" />
|
||||||
</div>
|
</div>
|
||||||
<el-tabs v-model="activeTab" class="detail-tabs">
|
<el-tabs v-model="activeTab" class="detail-tabs">
|
||||||
|
|||||||
@@ -42,7 +42,9 @@
|
|||||||
</el-alert>
|
</el-alert>
|
||||||
|
|
||||||
<el-table v-else :data="tableData" v-loading="loading" row-key="id">
|
<el-table v-else :data="tableData" v-loading="loading" row-key="id">
|
||||||
<el-table-column prop="id" label="用户编号" min-width="170" show-overflow-tooltip />
|
<el-table-column prop="displayNumber" label="用户编号" min-width="190" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">{{ row.displayNumber || '实名后生成' }}</template>
|
||||||
|
</el-table-column>
|
||||||
<el-table-column prop="displayName" label="显示名称" min-width="110">
|
<el-table-column prop="displayName" label="显示名称" min-width="110">
|
||||||
<template #default="{ row }">{{ row.displayName || '未设置' }}</template>
|
<template #default="{ row }">{{ row.displayName || '未设置' }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|||||||
@@ -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-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: '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: '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: '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.service.view'] } },
|
{ 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 会因路由匹配基准不符而白屏。
|
// 否则部署在 /admin/ 子路径下时,刷新或直达 /admin/xxx 会因路由匹配基准不符而白屏。
|
||||||
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes })
|
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes })
|
||||||
|
|
||||||
router.beforeEach((to) => {
|
router.beforeEach(async (to) => {
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
const requiredPerms = (to.meta.permissions as string[]) || []
|
const requiredPerms = (to.meta.permissions as string[]) || []
|
||||||
|
|
||||||
|
// 0. 页面刷新后内存态清空,先凭 HttpOnly refresh Cookie 静默恢复会话(无则跳登录)
|
||||||
|
await authStore.initializeSession()
|
||||||
|
|
||||||
// 1. 登录检查
|
// 1. 登录检查
|
||||||
if (to.path !== '/login' && !authStore.isLoggedIn) {
|
if (to.path !== '/login' && !authStore.isLoggedIn) {
|
||||||
return { path: '/login', query: { redirect: to.fullPath } }
|
return { path: '/login', query: { redirect: to.fullPath } }
|
||||||
|
|||||||
@@ -18,6 +18,20 @@ interface ApiEnvelope<T> {
|
|||||||
|
|
||||||
const REQUEST_TIMEOUT = 8000
|
const REQUEST_TIMEOUT = 8000
|
||||||
|
|
||||||
|
export function summarizeMatchmakerServices(rows: JsonRecord[]) {
|
||||||
|
const day = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' })
|
||||||
|
const today = day.format(new Date())
|
||||||
|
return {
|
||||||
|
pending: rows.filter(row => ['submitted', 'assigned', 'in_service', 'waiting_user'].includes(String(row.status))).length,
|
||||||
|
completed: rows.filter(row => row.status === 'completed').length,
|
||||||
|
total: rows.filter(row => ['createdAt', 'assignedAt', 'completedAt', 'latestFollowupAt'].some(key => {
|
||||||
|
if (!row[key]) return false
|
||||||
|
const date = new Date(String(row[key]))
|
||||||
|
return !Number.isNaN(date.getTime()) && day.format(date) === today
|
||||||
|
})).length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const numberOf = (source: JsonRecord | undefined, key: string) => {
|
const numberOf = (source: JsonRecord | undefined, key: string) => {
|
||||||
const value = source?.[key]
|
const value = source?.[key]
|
||||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
||||||
@@ -45,9 +59,10 @@ const emptyMetric = (
|
|||||||
|
|
||||||
export function createEmptyDashboard(notice = '当前账号暂无可展示的工作台数据'): DashboardModel {
|
export function createEmptyDashboard(notice = '当前账号暂无可展示的工作台数据'): DashboardModel {
|
||||||
return {
|
return {
|
||||||
|
followups: [],
|
||||||
metrics: [
|
metrics: [
|
||||||
emptyMetric('pending_reviews', '待审核资料', 'rose', '/review'),
|
emptyMetric('pending_reviews', '待审核资料', 'rose', '/review'),
|
||||||
emptyMetric('matchmaker_todos', '红娘服务待办', 'amber', '/referral'),
|
emptyMetric('matchmaker_todos', '红娘服务待办', 'amber', '/matchmaker'),
|
||||||
emptyMetric('counseling_todos', '咨询服务待办', 'blue', '/counseling'),
|
emptyMetric('counseling_todos', '咨询服务待办', 'blue', '/counseling'),
|
||||||
emptyMetric('station_appointments', '服务站预约', 'green', '/service-appointment'),
|
emptyMetric('station_appointments', '服务站预约', 'green', '/service-appointment'),
|
||||||
emptyMetric('effective_matches', '有效匹配', 'purple', '/analytics'),
|
emptyMetric('effective_matches', '有效匹配', 'purple', '/analytics'),
|
||||||
@@ -65,8 +80,11 @@ export function createEmptyDashboard(notice = '当前账号暂无可展示的工
|
|||||||
export async function loadDashboard(permissions: string[]): Promise<DashboardModel> {
|
export async function loadDashboard(permissions: string[]): Promise<DashboardModel> {
|
||||||
const canViewAnalytics = permissions.includes('analytics.view')
|
const canViewAnalytics = permissions.includes('analytics.view')
|
||||||
const canViewActivities = permissions.includes('activity.view')
|
const canViewActivities = permissions.includes('activity.view')
|
||||||
|
const canViewMatchmaker = permissions.includes('matchmaker.view')
|
||||||
|
const canManageMatchmaker = permissions.includes('matchmaker.assign') || permissions.includes('matchmaker.team.assign')
|
||||||
|
const canViewReviews = permissions.includes('review.view')
|
||||||
|
|
||||||
const [coreResult, serviceResult, activityResult] = await Promise.allSettled([
|
const [coreResult, serviceResult, activityResult, matchmakerResult, reviewResult, managementResult] = await Promise.allSettled([
|
||||||
canViewAnalytics
|
canViewAnalytics
|
||||||
? client.get('/operator/analytics/dashboard', { timeout: REQUEST_TIMEOUT })
|
? client.get('/operator/analytics/dashboard', { timeout: REQUEST_TIMEOUT })
|
||||||
: Promise.resolve(null),
|
: Promise.resolve(null),
|
||||||
@@ -76,14 +94,33 @@ export async function loadDashboard(permissions: string[]): Promise<DashboardMod
|
|||||||
canViewActivities
|
canViewActivities
|
||||||
? client.get('/operator/activities', { timeout: REQUEST_TIMEOUT })
|
? client.get('/operator/activities', { timeout: REQUEST_TIMEOUT })
|
||||||
: Promise.resolve(null),
|
: Promise.resolve(null),
|
||||||
|
canViewMatchmaker
|
||||||
|
? client.get('/operator/matchmaker/dashboard', { timeout: REQUEST_TIMEOUT })
|
||||||
|
: Promise.resolve(null),
|
||||||
|
canViewReviews ? client.get('/operator/reviews/stats', { timeout: REQUEST_TIMEOUT }) : Promise.resolve(null),
|
||||||
|
canManageMatchmaker ? client.get('/operator/matchmaker/management/services', { timeout: REQUEST_TIMEOUT }) : Promise.resolve(null),
|
||||||
])
|
])
|
||||||
|
|
||||||
const core = fulfilledData<JsonRecord>(coreResult)
|
const core = fulfilledData<JsonRecord>(coreResult)
|
||||||
const service = fulfilledData<JsonRecord>(serviceResult)
|
const service = fulfilledData<JsonRecord>(serviceResult)
|
||||||
const activityRows = fulfilledData<JsonRecord[]>(activityResult)
|
const activityRows = fulfilledData<JsonRecord[]>(activityResult)
|
||||||
|
const matchmaker = fulfilledData<JsonRecord>(matchmakerResult)
|
||||||
|
const reviews = fulfilledData<JsonRecord>(reviewResult)
|
||||||
|
const managedServices = fulfilledData<JsonRecord[]>(managementResult)
|
||||||
|
const managedStats = summarizeMatchmakerServices(managedServices || [])
|
||||||
|
const matchmakerAvailable = canManageMatchmaker ? Boolean(managedServices) : Boolean(matchmaker)
|
||||||
|
const matchmakerPending = canManageMatchmaker
|
||||||
|
? managedStats.pending
|
||||||
|
: numberOf(matchmaker || undefined, 'pendingCount') + numberOf(matchmaker || undefined, 'inProgressCount')
|
||||||
|
const matchmakerCompleted = canManageMatchmaker
|
||||||
|
? managedStats.completed
|
||||||
|
: numberOf(matchmaker || undefined, 'completedCount')
|
||||||
|
const followups = (managedServices || []).filter(row => row.latestFollowupContent)
|
||||||
|
.sort((a, b) => String(b.latestFollowupAt).localeCompare(String(a.latestFollowupAt)))
|
||||||
|
.slice(0, 5).map(row => ({ serviceId: String(row.serviceId), userDisplayNumber: String(row.userDisplayNumber || '未生成编号'),
|
||||||
|
content: String(row.latestFollowupContent), createdAt: String(row.latestFollowupAt || '') }))
|
||||||
const analyticsAvailable = Boolean(core || service)
|
const analyticsAvailable = Boolean(core || service)
|
||||||
|
|
||||||
const eligibility = recordOf(service || undefined, 'localEligibility')
|
|
||||||
const counseling = recordOf(service || undefined, 'counseling')
|
const counseling = recordOf(service || undefined, 'counseling')
|
||||||
const appointments = recordOf(service || undefined, 'serviceAppointments')
|
const appointments = recordOf(service || undefined, 'serviceAppointments')
|
||||||
const effectiveConnections = recordOf(service || undefined, 'effectiveConnections')
|
const effectiveConnections = recordOf(service || undefined, 'effectiveConnections')
|
||||||
@@ -92,12 +129,13 @@ export async function loadDashboard(permissions: string[]): Promise<DashboardMod
|
|||||||
|
|
||||||
const metrics: DashboardMetric[] = [
|
const metrics: DashboardMetric[] = [
|
||||||
{
|
{
|
||||||
key: 'pending_reviews', label: '待审核资料', value: numberOf(eligibility, 'pending'),
|
key: 'pending_reviews', label: '待审核资料', value: numberOf(reviews || undefined, 'pending') + numberOf(reviews || undefined, 'processing'),
|
||||||
trendText: service ? '本地资格待核验' : '暂无授权数据', tone: 'rose', available: Boolean(service), route: '/review',
|
trendText: reviews ? '待领取与审核中资料' : '暂无授权数据', tone: 'rose', available: Boolean(reviews), route: '/review',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'matchmaker_todos', label: '红娘服务待办', value: 0,
|
key: 'matchmaker_todos', label: '红娘服务待办',
|
||||||
trendText: '当前接口未提供待办数', tone: 'amber', available: false, route: '/referral',
|
value: matchmakerPending,
|
||||||
|
trendText: matchmakerAvailable ? (canManageMatchmaker ? '管理范围内待完成服务' : '本人服务对象待跟进') : '暂无授权数据', tone: 'amber', available: matchmakerAvailable, route: '/matchmaker',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'counseling_todos', label: '咨询服务待办',
|
key: 'counseling_todos', label: '咨询服务待办',
|
||||||
@@ -120,9 +158,10 @@ export async function loadDashboard(permissions: string[]): Promise<DashboardMod
|
|||||||
]
|
]
|
||||||
|
|
||||||
const todos = ([
|
const todos = ([
|
||||||
{ key: 'review', title: '资料审核', description: '本地资格材料等待核验', count: metrics[0].value, actionText: '立即审核', route: '/review', tone: 'rose', available: metrics[0].available },
|
{ key: 'review', title: '资料审核', description: '待领取与审核中资料', count: metrics[0].value, actionText: '立即审核', route: '/review', tone: 'rose', available: metrics[0].available },
|
||||||
{ key: 'counseling', title: '咨询预约', description: '咨询申请等待受理或跟进', count: metrics[2].value, actionText: '查看服务', route: '/counseling', tone: 'blue', available: metrics[2].available },
|
{ key: 'counseling', title: '咨询预约', description: '咨询申请等待受理或跟进', count: metrics[2].value, actionText: '查看服务', route: '/counseling', tone: 'blue', available: metrics[2].available },
|
||||||
{ key: 'appointment', title: '到站预约', description: '线下服务预约等待确认', count: metrics[3].value, actionText: '管理预约', route: '/service-appointment', tone: 'green', available: metrics[3].available },
|
{ key: 'appointment', title: '到站预约', description: '线下服务预约等待确认', count: metrics[3].value, actionText: '管理预约', route: '/service-appointment', tone: 'green', available: metrics[3].available },
|
||||||
|
{ key: 'matchmaker', title: '红娘服务', description: metrics[1].trendText, count: metrics[1].value, actionText: '查看服务', route: '/matchmaker', tone: 'amber', available: metrics[1].available },
|
||||||
{ key: 'risk', title: '举报处理', description: '风险举报等待工作人员处理', count: numberOf(core || undefined, 'pendingReports'), actionText: '去处理', route: '/risk/reports', tone: 'amber', available: Boolean(core) },
|
{ key: 'risk', title: '举报处理', description: '风险举报等待工作人员处理', count: numberOf(core || undefined, 'pendingReports'), actionText: '去处理', route: '/risk/reports', tone: 'amber', available: Boolean(core) },
|
||||||
] as DashboardTodo[]).filter((item) => item.available)
|
] as DashboardTodo[]).filter((item) => item.available)
|
||||||
|
|
||||||
@@ -142,6 +181,7 @@ export async function loadDashboard(permissions: string[]): Promise<DashboardMod
|
|||||||
{ key: 'approved', label: '资料审核通过', value: numberOf(core || undefined, 'approvedProfiles'), compareText: '已通过资料', tone: 'blue', available: Boolean(core) },
|
{ key: 'approved', label: '资料审核通过', value: numberOf(core || undefined, 'approvedProfiles'), compareText: '已通过资料', tone: 'blue', available: Boolean(core) },
|
||||||
{ key: 'served', label: '公益服务用户', value: numberOf(uniqueUsers, 'totalUniqueServiceUsers'), compareText: '去重服务人数', tone: 'green', available: Boolean(service) },
|
{ key: 'served', label: '公益服务用户', value: numberOf(uniqueUsers, 'totalUniqueServiceUsers'), compareText: '去重服务人数', tone: 'green', available: Boolean(service) },
|
||||||
{ key: 'success', label: '成功牵手', value: numberOf(core || undefined, 'successPairs'), compareText: '双方确认成功', tone: 'amber', available: Boolean(core) },
|
{ key: 'success', label: '成功牵手', value: numberOf(core || undefined, 'successPairs'), compareText: '双方确认成功', tone: 'amber', available: Boolean(core) },
|
||||||
|
{ key: 'matchmaker_completed', label: '红娘服务完成', value: matchmakerCompleted, compareText: canManageMatchmaker ? '管理范围内已完成服务' : '本人已完成服务', tone: 'amber', available: matchmakerAvailable },
|
||||||
] as DashboardOverviewItem[]).filter((item) => item.available)
|
] as DashboardOverviewItem[]).filter((item) => item.available)
|
||||||
|
|
||||||
const effectiveness = ([
|
const effectiveness = ([
|
||||||
@@ -152,12 +192,14 @@ export async function loadDashboard(permissions: string[]): Promise<DashboardMod
|
|||||||
{ key: 'offline_success', label: '线下牵手成功', value: numberOf(effectiveConnections, 'successConnections'), max: numberOf(effectiveConnections, 'activeMatches'), unit: '对', available: Boolean(service) },
|
{ key: 'offline_success', label: '线下牵手成功', value: numberOf(effectiveConnections, 'successConnections'), max: numberOf(effectiveConnections, 'activeMatches'), unit: '对', available: Boolean(service) },
|
||||||
] as DashboardEffectivenessItem[]).filter((item) => item.available)
|
] as DashboardEffectivenessItem[]).filter((item) => item.available)
|
||||||
|
|
||||||
const rejectedCount = [coreResult, serviceResult, activityResult].filter((item) => item.status === 'rejected').length
|
const rejectedCount = [coreResult, serviceResult, activityResult, matchmakerResult, reviewResult, managementResult].filter((item) => item.status === 'rejected').length
|
||||||
const notice = !analyticsAvailable && !activityRows
|
const anyData = analyticsAvailable || Boolean(activityRows) || matchmakerAvailable || Boolean(reviews)
|
||||||
|
const notice = !anyData
|
||||||
? (rejectedCount ? '工作台数据加载失败,请稍后重试' : '当前账号暂无工作台统计权限')
|
? (rejectedCount ? '工作台数据加载失败,请稍后重试' : '当前账号暂无工作台统计权限')
|
||||||
: (rejectedCount ? '部分模块暂时不可用,其余数据已正常加载' : '')
|
: (rejectedCount ? '部分模块暂时不可用,其余数据已正常加载' : '')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
followups,
|
||||||
metrics,
|
metrics,
|
||||||
todos,
|
todos,
|
||||||
activities,
|
activities,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref, computed } from 'vue'
|
import { ref, computed } from 'vue'
|
||||||
import { post } from '@/api/client'
|
import { post } from '@/api/client'
|
||||||
|
import { setAccessToken, clearAccessToken } from '@/utils/token'
|
||||||
|
|
||||||
interface OperatorInfo {
|
interface OperatorInfo {
|
||||||
operatorId: string
|
operatorId: string
|
||||||
@@ -12,9 +13,9 @@ interface OperatorInfo {
|
|||||||
|
|
||||||
const previewRolePermissions: Record<string, string[]> = {
|
const previewRolePermissions: Record<string, string[]> = {
|
||||||
reviewer: ['review.view', 'user.view'],
|
reviewer: ['review.view', 'user.view'],
|
||||||
counselor: ['counseling.service.view', 'referral.manage'],
|
counselor: ['counseling.service.view', 'matchmaker.service'],
|
||||||
station: ['service_location.view', 'service_appointment.view'],
|
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', () => {
|
export const useAuthStore = defineStore('auth', () => {
|
||||||
@@ -23,38 +24,70 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
const previewOperator: OperatorInfo | null = previewRolePermissions[previewRole]
|
const previewOperator: OperatorInfo | null = previewRolePermissions[previewRole]
|
||||||
? { operatorId: 'ui-preview', name: '界面验收员', username: 'preview', permissions: previewRolePermissions[previewRole], organizationId: null }
|
? { operatorId: 'ui-preview', name: '界面验收员', username: 'preview', permissions: previewRolePermissions[previewRole], organizationId: null }
|
||||||
: 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 || [])
|
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) {
|
async function login(username: string, password: string) {
|
||||||
const res: any = await post('/auth/operator/login', { username, password })
|
const res: any = await post('/auth/operator/login', { username, password })
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
token.value = res.data.accessToken
|
applyAuthData(res.data)
|
||||||
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))
|
|
||||||
return res.data
|
return res.data
|
||||||
}
|
}
|
||||||
throw new Error(res.message || '登录失败')
|
throw new Error(res.message || '登录失败')
|
||||||
}
|
}
|
||||||
|
|
||||||
function logout() {
|
/**
|
||||||
token.value = ''
|
* 静默恢复会话:页面刷新后内存态清空,凭 HttpOnly refresh Cookie(dy_op_rt)刷新令牌,
|
||||||
operator.value = null
|
* 无需用户重新登录。refresh token 不落地、不可被 JS 读取,抗 XSS。
|
||||||
localStorage.removeItem('accessToken')
|
* 开发跨端口代理下 Cookie 不共享,刷新将失败并回落到登录页(符合预期)。
|
||||||
localStorage.removeItem('operator')
|
*/
|
||||||
|
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 }
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -37,8 +37,18 @@
|
|||||||
--admin-coral-soft: #FFF0F1; /* 品牌浅底(角标 / 选中态底) */
|
--admin-coral-soft: #FFF0F1; /* 品牌浅底(角标 / 选中态底) */
|
||||||
--admin-coral-lighter: #FFF8F7; /* 更浅一档,hover 底 */
|
--admin-coral-lighter: #FFF8F7; /* 更浅一档,hover 底 */
|
||||||
--admin-coral-border: rgba(244, 95, 104, 0.22);
|
--admin-coral-border: rgba(244, 95, 104, 0.22);
|
||||||
|
--admin-scene-bg-start: #FFEDEE;
|
||||||
|
--admin-scene-bg-mid: #FFF6F4;
|
||||||
|
--admin-scene-bg-end: #FBF5F4;
|
||||||
|
--admin-scene-glow: rgba(244, 95, 104, 0.28);
|
||||||
|
--admin-scene-glow-soft: rgba(255, 150, 170, 0.22);
|
||||||
|
--admin-scene-surface: rgba(255, 255, 255, 0.65);
|
||||||
|
--admin-scene-border: rgba(244, 95, 104, 0.18);
|
||||||
|
--admin-scene-divider: rgba(244, 95, 104, 0.30);
|
||||||
/* 承载白字的品牌渐变(两端均 ≥4.5:1)。基础色渐变见 --gradient-brand-vivid。 */
|
/* 承载白字的品牌渐变(两端均 ≥4.5:1)。基础色渐变见 --gradient-brand-vivid。 */
|
||||||
--gradient-brand-solid: linear-gradient(135deg, #C84A53 0%, #B8434A 100%);
|
--gradient-brand-solid: linear-gradient(135deg, #C84A53 0%, #B8434A 100%);
|
||||||
|
/* 文字用渐变(background-clip:text):比 solid 更鲜亮,用于「善缘丹阳」等大字号品牌标题 */
|
||||||
|
--gradient-brand-text: linear-gradient(135deg, #FF7D6E 0%, #E8475D 60%, #B8434A 100%);
|
||||||
/* 鲜亮品牌渐变:只允许用在「无文字覆盖」的装饰,或预览态还原(如 Banner 预览)。 */
|
/* 鲜亮品牌渐变:只允许用在「无文字覆盖」的装饰,或预览态还原(如 Banner 预览)。 */
|
||||||
--gradient-brand-vivid: linear-gradient(135deg, #FF7D6E 0%, #FF5C82 100%);
|
--gradient-brand-vivid: linear-gradient(135deg, #FF7D6E 0%, #FF5C82 100%);
|
||||||
--gradient-brand-soft: linear-gradient(135deg, #FFE9DF 0%, #FFF7F2 100%);
|
--gradient-brand-soft: linear-gradient(135deg, #FFE9DF 0%, #FFF7F2 100%);
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ export interface DashboardEffectivenessItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface DashboardModel {
|
export interface DashboardModel {
|
||||||
|
followups: { serviceId: string; userDisplayNumber: string; content: string; createdAt: string }[]
|
||||||
metrics: DashboardMetric[]
|
metrics: DashboardMetric[]
|
||||||
todos: DashboardTodo[]
|
todos: DashboardTodo[]
|
||||||
activities: DashboardActivity[]
|
activities: DashboardActivity[]
|
||||||
|
|||||||
@@ -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 = ''
|
||||||
|
}
|
||||||
@@ -106,6 +106,17 @@
|
|||||||
</article>
|
</article>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<article v-if="dashboard.followups.length" class="dashboard-panel">
|
||||||
|
<header class="panel-header"><div><h2>最新红娘跟进记录</h2></div></header>
|
||||||
|
<div class="todo-list">
|
||||||
|
<button v-for="item in dashboard.followups" :key="item.serviceId" type="button" class="todo-row"
|
||||||
|
@click="goTo(`/matchmaker?serviceId=${encodeURIComponent(item.serviceId)}`)">
|
||||||
|
<span class="todo-copy"><strong>{{ item.userDisplayNumber }}</strong><small>{{ item.content }}</small></span>
|
||||||
|
<em>{{ formatDateTime(item.createdAt) }} · 查看服务</em>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
<section class="dashboard-grid dashboard-grid-bottom">
|
<section class="dashboard-grid dashboard-grid-bottom">
|
||||||
<article class="dashboard-panel service-overview-panel">
|
<article class="dashboard-panel service-overview-panel">
|
||||||
<header class="panel-header"><div><h2>服务数据概览</h2></div><span>当前累计</span></header>
|
<header class="panel-header"><div><h2>服务数据概览</h2></div><span>当前累计</span></header>
|
||||||
@@ -136,7 +147,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onActivated, ref } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import {
|
import {
|
||||||
@@ -277,15 +288,19 @@ async function retryLoad() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(retryLoad)
|
onActivated(retryLoad)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.dashboard-page {
|
.dashboard-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
min-height: 100%;
|
||||||
max-width: var(--admin-content-max-width);
|
max-width: var(--admin-content-max-width);
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: var(--space-5) 26px 28px;
|
padding: var(--space-5) 26px 28px;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard-welcome {
|
.dashboard-welcome {
|
||||||
@@ -478,6 +493,19 @@ onMounted(retryLoad)
|
|||||||
margin-top: 14px;
|
margin-top: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dashboard-grid-top {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-grid-bottom {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-grid-bottom .dashboard-panel {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
.dashboard-panel {
|
.dashboard-panel {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 14px var(--space-4);
|
padding: 14px var(--space-4);
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
<template>
|
<template>
|
||||||
<main class="login-shell">
|
<main class="login-shell">
|
||||||
<section class="brand-panel" aria-label="善缘丹阳公益婚恋服务平台">
|
<section class="brand-panel" aria-label="爱在丹阳公益婚恋服务平台">
|
||||||
<img class="brand-scene" :src="BRAND_LOGIN_SCENE" alt="" />
|
<img class="brand-scene" :src="BRAND_LOGIN_SCENE" alt="" />
|
||||||
<div class="brand-overlay">
|
<div class="brand-overlay">
|
||||||
<div class="brand-title">
|
<div class="brand-title">
|
||||||
<img :src="BRAND_LOGO" alt="" />
|
<img :src="BRAND_LOGO" alt="" />
|
||||||
<div>
|
<div>
|
||||||
<strong>善缘丹阳</strong>
|
<strong>爱在丹阳</strong>
|
||||||
<span>公益婚恋服务平台</span>
|
<span>公益婚恋服务平台</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
<span>敏感数据按权限访问,所有关键操作均记录审计日志。</span>
|
<span>敏感数据按权限访问,所有关键操作均记录审计日志。</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<footer>善缘丹阳 · 公益婚恋服务平台</footer>
|
<footer>爱在丹阳 · 公益婚恋服务平台</footer>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</template>
|
</template>
|
||||||
@@ -135,6 +135,8 @@ async function handleLogin() {
|
|||||||
.brand-title img {
|
.brand-title img {
|
||||||
width: 54px;
|
width: 54px;
|
||||||
height: 54px;
|
height: 54px;
|
||||||
|
border-radius: 50%;
|
||||||
|
clip-path: circle(50%);
|
||||||
}
|
}
|
||||||
|
|
||||||
.brand-title div {
|
.brand-title div {
|
||||||
|
|||||||
|
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>
|
<groupId>com.danyang.match</groupId>
|
||||||
<artifactId>danyang-match-platform</artifactId>
|
<artifactId>danyang-match-platform</artifactId>
|
||||||
<version>1.0.0-RC.1</version>
|
<version>1.2.0</version>
|
||||||
<name>Danyang Match Platform</name>
|
<name>Danyang Match Platform</name>
|
||||||
<description>丹阳公益婚恋服务平台 V1.0 - Backend</description>
|
<description>丹阳公益婚恋服务平台 V1.1 - Backend</description>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>21</java.version>
|
<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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.danyang.match.platform.shared.idempotency.Idempotent;
|
import com.danyang.match.platform.shared.idempotency.Idempotent;
|
||||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
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.dto.ApiResponse;
|
||||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -30,7 +30,8 @@ import java.util.Map;
|
|||||||
public class ActivityInterestController {
|
public class ActivityInterestController {
|
||||||
|
|
||||||
private final ActivityInterestService interestService;
|
private final ActivityInterestService interestService;
|
||||||
private final RelationshipService relationshipService;
|
/** 二阶段同意(INV-014/015):`interests/confirm` 与 `/mutual/*` 共用同一实现,避免越权旁路。 */
|
||||||
|
private final ActivityMutualConsentService consentService;
|
||||||
private final ActivityMapper activityMapper;
|
private final ActivityMapper activityMapper;
|
||||||
|
|
||||||
@GetMapping("/operator/activity-interest-summary")
|
@GetMapping("/operator/activity-interest-summary")
|
||||||
@@ -105,7 +106,12 @@ public class ActivityInterestController {
|
|||||||
/**
|
/**
|
||||||
* 确认开启线上沟通(V1.1 Phase 08)
|
* 确认开启线上沟通(V1.1 Phase 08)
|
||||||
* POST /api/v1/activities/{id}/interests/confirm
|
* 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
|
@Idempotent
|
||||||
@PostMapping("/{id}/interests/confirm")
|
@PostMapping("/{id}/interests/confirm")
|
||||||
@@ -120,13 +126,16 @@ public class ActivityInterestController {
|
|||||||
com.danyang.match.platform.shared.enums.ApiResponseCode.BAD_REQUEST,
|
com.danyang.match.platform.shared.enums.ApiResponseCode.BAD_REQUEST,
|
||||||
"partnerId不能为空");
|
"partnerId不能为空");
|
||||||
}
|
}
|
||||||
// 验证互选状态
|
// 验证互选状态(保留原前置条件:无双向互选不进入确认环节)
|
||||||
if (!interestService.hasMutualInterest(userId, partnerId, id)) {
|
if (!interestService.hasMutualInterest(userId, partnerId, id)) {
|
||||||
return ApiResponse.error(
|
return ApiResponse.error(
|
||||||
com.danyang.match.platform.shared.enums.ApiResponseCode.CONFLICT,
|
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 java.util.stream.Collectors;
|
||||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
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.BusinessException;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 活动互选服务
|
* 活动互选服务
|
||||||
@@ -69,7 +70,7 @@ public class ActivityInterestService {
|
|||||||
|
|
||||||
// 2. 验证用户已报名且通过审核
|
// 2. 验证用户已报名且通过审核
|
||||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||||
.orElseThrow(() -> new RuntimeException("您未报名该活动"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.FORBIDDEN, "您未报名该活动"));
|
||||||
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||||
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名未通过审核,无法提交反馈");
|
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名未通过审核,无法提交反馈");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import java.util.*;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
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.BusinessException;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -407,7 +408,7 @@ public class ActivityService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public ActivityRegistration cancelRegistration(String userId, String activityId) {
|
public ActivityRegistration cancelRegistration(String userId, String activityId) {
|
||||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||||
.orElseThrow(() -> new RuntimeException("没有找到报名记录"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到报名记录"));
|
||||||
if (!Constants.REGISTRATION_STATUS_PENDING.equals(registration.getStatus()) &&
|
if (!Constants.REGISTRATION_STATUS_PENDING.equals(registration.getStatus()) &&
|
||||||
!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不能取消");
|
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.enums.ApiResponseCode;
|
||||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||||
import com.danyang.match.platform.shared.exception.ServerErrorException;
|
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) {
|
public Map<String, Object> generateCheckinToken(String userId, String activityId) {
|
||||||
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
ActivityRegistration registration = registrationMapper.findByActivityAndUser(activityId, userId)
|
||||||
.orElseThrow(() -> new RuntimeException("您没有报名该活动"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.FORBIDDEN, "您没有报名该活动"));
|
||||||
|
|
||||||
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
if (!Constants.REGISTRATION_STATUS_APPROVED.equals(registration.getStatus())) {
|
||||||
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名尚未审核通过,无法签到");
|
throw new BusinessException(ApiResponseCode.FORBIDDEN, "报名尚未审核通过,无法签到");
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -67,7 +69,7 @@ public class ActivityMutualConsentService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public Map<String, Object> confirmConnection(String userId, String activityId, String partnerId) {
|
public Map<String, Object> confirmConnection(String userId, String activityId, String partnerId) {
|
||||||
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
||||||
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到该活动的互选记录"));
|
||||||
|
|
||||||
// 原子确认本方(Phase 16 核心):仅当本方 pending、未过期、未软删时写入 accepted,
|
// 原子确认本方(Phase 16 核心):仅当本方 pending、未过期、未软删时写入 accepted,
|
||||||
// 并借助 both_confirmed_at 从 NULL→非NULL 的原子 UPDATE 实现 exactly-once。
|
// 并借助 both_confirmed_at 从 NULL→非NULL 的原子 UPDATE 实现 exactly-once。
|
||||||
@@ -76,7 +78,7 @@ public class ActivityMutualConsentService {
|
|||||||
|
|
||||||
// 回读权威状态(可能受并发另一方提交影响)
|
// 回读权威状态(可能受并发另一方提交影响)
|
||||||
consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
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 aAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserAStatus());
|
||||||
boolean bAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus());
|
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) {
|
public Map<String, Object> declineConnection(String userId, String activityId, String partnerId) {
|
||||||
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
|
||||||
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "没有找到该活动的互选记录"));
|
||||||
if (userId.equals(consent.getUserAId())) {
|
if (userId.equals(consent.getUserAId())) {
|
||||||
consent.setUserAStatus(Constants.MUTUAL_CONSENT_STATUS_DECLINED);
|
consent.setUserAStatus(Constants.MUTUAL_CONSENT_STATUS_DECLINED);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import com.danyang.match.platform.profile.entity.UserProfile;
|
|||||||
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||||
import com.danyang.match.platform.risk.entity.RiskAction;
|
import com.danyang.match.platform.risk.entity.RiskAction;
|
||||||
import com.danyang.match.platform.risk.mapper.RiskActionMapper;
|
import com.danyang.match.platform.risk.mapper.RiskActionMapper;
|
||||||
|
import com.danyang.match.platform.user.entity.User;
|
||||||
|
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||||
import com.danyang.match.platform.shared.config.FeatureFlagConfig;
|
import com.danyang.match.platform.shared.config.FeatureFlagConfig;
|
||||||
import com.danyang.match.platform.shared.constant.Constants;
|
import com.danyang.match.platform.shared.constant.Constants;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
@@ -46,6 +48,7 @@ public class AppealService {
|
|||||||
|
|
||||||
private final AppealMapper appealMapper;
|
private final AppealMapper appealMapper;
|
||||||
private final RiskActionMapper riskActionMapper;
|
private final RiskActionMapper riskActionMapper;
|
||||||
|
private final UserMapper userMapper;
|
||||||
private final UserProfileMapper userProfileMapper;
|
private final UserProfileMapper userProfileMapper;
|
||||||
private final AuditLogMapper auditLogMapper;
|
private final AuditLogMapper auditLogMapper;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
@@ -281,6 +284,11 @@ public class AppealService {
|
|||||||
log.info("申诉批准,已解除处置: appealId={}, actionId={}", appeal.getId(), appeal.getRelatedActionId());
|
log.info("申诉批准,已解除处置: appealId={}, actionId={}", appeal.getId(), appeal.getRelatedActionId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 解除处置后同步账号状态:若该用户已无其他生效中的封禁 / 暂停,把账号恢复为 normal。
|
||||||
|
// 否则会出现「申诉已通过、账号仍被锁死」的死锁 —— ReportService 处置时写入的
|
||||||
|
// users.account_status=banned/suspended 无人回滚。
|
||||||
|
restoreAccountStatusIfNoActiveRestriction(appeal.getUserId());
|
||||||
|
|
||||||
// 通知用户
|
// 通知用户
|
||||||
notificationService.send(appeal.getUserId(), Constants.NOTIFICATION_TYPE_ACCOUNT,
|
notificationService.send(appeal.getUserId(), Constants.NOTIFICATION_TYPE_ACCOUNT,
|
||||||
"申诉审核通过",
|
"申诉审核通过",
|
||||||
@@ -371,6 +379,38 @@ public class AppealService {
|
|||||||
return "limited";
|
return "limited";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解除处置后同步账号状态:若该用户已无其他生效中的封禁 / 暂停,把 users.account_status 恢复为 normal。
|
||||||
|
*
|
||||||
|
* <p>否则会出现「申诉已通过、账号仍被锁死」的死锁 —— ReportService 处置时写入的
|
||||||
|
* users.account_status=banned/suspended 无人回滚,登录门禁 / 推荐 / 匹配资格仍按旧状态拒绝用户。
|
||||||
|
*
|
||||||
|
* <p>仅回滚由处置写入的 banned / suspended,避免误改 closed(注销)等其他业务状态。
|
||||||
|
*/
|
||||||
|
private void restoreAccountStatusIfNoActiveRestriction(String userId) {
|
||||||
|
boolean stillRestricted = riskActionMapper.findActiveByUserId(userId).stream()
|
||||||
|
.anyMatch(a -> Constants.RISK_ACTION_BAN.equals(a.getActionType())
|
||||||
|
|| Constants.RISK_ACTION_TEMPORARY_SUSPEND.equals(a.getActionType()));
|
||||||
|
if (stillRestricted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
User user = userMapper.selectById(userId);
|
||||||
|
if (user == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String oldStatus = user.getAccountStatus();
|
||||||
|
if (!Constants.ACCOUNT_STATUS_BANNED.equals(oldStatus)
|
||||||
|
&& !Constants.ACCOUNT_STATUS_SUSPENDED.equals(oldStatus)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
user.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||||
|
userMapper.updateById(user);
|
||||||
|
// audit_logs.before_data/after_data 为 JSONB:必须写合法 JSON,裸字符串会被 PG 拒绝。
|
||||||
|
saveAuditLog(null, "ACCOUNT_STATUS_RESTORE", "user", userId,
|
||||||
|
"{\"accountStatus\":\"" + oldStatus + "\"}",
|
||||||
|
"{\"accountStatus\":\"" + Constants.ACCOUNT_STATUS_NORMAL + "\"}");
|
||||||
|
}
|
||||||
|
|
||||||
private void saveAuditLog(String operatorId, String action, String resourceType,
|
private void saveAuditLog(String operatorId, String action, String resourceType,
|
||||||
String resourceId, String beforeData, String afterData) {
|
String resourceId, String beforeData, String afterData) {
|
||||||
AuditLog auditLog = new AuditLog();
|
AuditLog auditLog = new AuditLog();
|
||||||
@@ -378,6 +418,10 @@ public class AppealService {
|
|||||||
auditLog.setAction(action);
|
auditLog.setAction(action);
|
||||||
auditLog.setResourceType(resourceType);
|
auditLog.setResourceType(resourceType);
|
||||||
auditLog.setResourceId(resourceId);
|
auditLog.setResourceId(resourceId);
|
||||||
|
// 此前忽略 beforeData/afterData → 账号状态恢复等变更审计丢失前后值;补齐后需注意
|
||||||
|
// audit_logs 的 before_data/after_data 为 JSONB,调用方必须传合法 JSON 文本。
|
||||||
|
auditLog.setBeforeData(beforeData);
|
||||||
|
auditLog.setAfterData(afterData);
|
||||||
auditLogMapper.insert(auditLog);
|
auditLogMapper.insert(auditLog);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,4 +19,20 @@ public class AuditLog extends BaseEntity {
|
|||||||
private String afterData;
|
private String afterData;
|
||||||
private String ip;
|
private String ip;
|
||||||
private String userAgent;
|
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;
|
||||||
|
|
||||||
|
// ==================== V057 / 运行时实测修复:C 端用户主体维度 ====================
|
||||||
|
|
||||||
|
/** 用户主体 ID(C 端触发的审计写此列且 operator_id=null;两者恰有一者非空)。 */
|
||||||
|
private String subjectUserId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.danyang.match.platform.audit.service;
|
||||||
|
|
||||||
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.transaction.annotation.Propagation;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拒绝类审计的独立事务写入器(运行时实测修复)。
|
||||||
|
*
|
||||||
|
* <p>背景:拒绝审计(DATA_SCOPE_DENIED / AUTHORIZATION_DENIED)原先与业务方法同一事务——
|
||||||
|
* 拒绝时抛异常必然触发业务事务回滚,审计 insert(已执行 Updates:1)随之被回滚吞掉:
|
||||||
|
* 生产全量 deny 审计零落库。H2 集成测试因测试类 @Transactional(测试事务内可见未提交行)
|
||||||
|
* 结构性假绿。运行时实测(outsider consent → deny 行 0 条)抓到。
|
||||||
|
*
|
||||||
|
* <p>语义:REQUIRES_NEW 独立事务提交——外层业务事务回滚与否均不影响拒绝审计落库;
|
||||||
|
* 内层失败仍由调用方 catch 记日志后照常拒绝(审计失败不阻断拒绝响应)。
|
||||||
|
* 成功路径审计(SENSITIVE_ACCESS / 业务动作)保持与业务同事务(业务回滚审计一并消失,语义正确),
|
||||||
|
* 不走本写入器。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuditDenyWriter {
|
||||||
|
|
||||||
|
private final AuditLogMapper auditLogMapper;
|
||||||
|
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void insertIndependent(AuditLog auditLog) {
|
||||||
|
auditLogMapper.insert(auditLog);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,6 +52,11 @@ public class AuditLogService {
|
|||||||
m.put("ip", log.getIp());
|
m.put("ip", log.getIp());
|
||||||
m.put("userAgent", log.getUserAgent());
|
m.put("userAgent", log.getUserAgent());
|
||||||
m.put("createdAt", log.getCreatedAt());
|
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;
|
return m;
|
||||||
}).collect(java.util.stream.Collectors.toList());
|
}).collect(java.util.stream.Collectors.toList());
|
||||||
|
|
||||||
@@ -73,11 +78,48 @@ public class AuditLogService {
|
|||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void recordSensitiveAccess(String operatorId, String resourceType, String resourceId) {
|
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 auditLog = new AuditLog();
|
||||||
auditLog.setOperatorId(operatorId);
|
auditLog.setOperatorId(operatorId);
|
||||||
auditLog.setAction("SENSITIVE_ACCESS");
|
auditLog.setAction("SENSITIVE_ACCESS");
|
||||||
auditLog.setResourceType(resourceType);
|
auditLog.setResourceType(resourceType);
|
||||||
auditLog.setResourceId(resourceId);
|
auditLog.setResourceId(resourceId);
|
||||||
|
auditLog.setPurposeCode(purposeCode);
|
||||||
|
auditLog.setServiceAssignmentId(serviceAssignmentId);
|
||||||
|
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs) {
|
||||||
|
HttpServletRequest req = attrs.getRequest();
|
||||||
|
auditLog.setIp(req.getRemoteAddr());
|
||||||
|
String ua = req.getHeader("User-Agent");
|
||||||
|
auditLog.setUserAgent(ua != null ? (ua.length() > 512 ? ua.substring(0, 512) : ua) : null);
|
||||||
|
}
|
||||||
|
auditLogMapper.insert(auditLog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V057 / 运行时实测修复:C 端用户主体的审计入口。
|
||||||
|
* operator 主体照旧走 recordSensitiveAccess/saveAuditLog(operator_id 维度);
|
||||||
|
* user 主体(consent/decline 等用户动作)写 subject_user_id 且 operator_id=null——
|
||||||
|
* 否则 userId 撞 audit_logs_operator_id_fkey(→operators) 必 FK violation(H2 无 FK 假绿)。
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void recordUserAction(String userId, String action, String resourceType, String resourceId,
|
||||||
|
String purposeCode, String afterData) {
|
||||||
|
AuditLog auditLog = new AuditLog();
|
||||||
|
auditLog.setSubjectUserId(userId);
|
||||||
|
auditLog.setAction(action);
|
||||||
|
auditLog.setResourceType(resourceType);
|
||||||
|
auditLog.setResourceId(resourceId);
|
||||||
|
auditLog.setAfterData(afterData);
|
||||||
|
auditLog.setPurposeCode(purposeCode);
|
||||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs) {
|
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs) {
|
||||||
HttpServletRequest req = attrs.getRequest();
|
HttpServletRequest req = attrs.getRequest();
|
||||||
auditLog.setIp(req.getRemoteAddr());
|
auditLog.setIp(req.getRemoteAddr());
|
||||||
|
|||||||
@@ -33,6 +33,15 @@ public class AuthController {
|
|||||||
return ApiResponse.ok(authService.wechatLogin(code));
|
return ApiResponse.ok(authService.wechatLogin(code));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/demo/login")
|
||||||
|
public ApiResponse<Map<String, Object>> demoLogin(@RequestBody Map<String, String> body) {
|
||||||
|
String code = body.get("code");
|
||||||
|
if (code == null || code.isBlank()) {
|
||||||
|
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "演示账号不能为空");
|
||||||
|
}
|
||||||
|
return ApiResponse.ok(authService.demoLogin(code));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 绑定手机号
|
* 绑定手机号
|
||||||
* POST /api/v1/auth/phone/bind
|
* POST /api/v1/auth/phone/bind
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
package com.danyang.match.platform.auth.controller;
|
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.auth.service.OperatorAuthService;
|
||||||
import com.danyang.match.platform.shared.dto.ApiResponse;
|
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
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 lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -17,14 +23,80 @@ import java.util.Map;
|
|||||||
public class OperatorAuthController {
|
public class OperatorAuthController {
|
||||||
|
|
||||||
private final OperatorAuthService operatorAuthService;
|
private final OperatorAuthService operatorAuthService;
|
||||||
|
private final OperatorCookieWriter cookieWriter;
|
||||||
|
|
||||||
@PostMapping("/login")
|
@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 username = body.get("username");
|
||||||
String password = body.get("password");
|
String password = body.get("password");
|
||||||
if (username == null || username.isBlank() || password == null || password.isBlank()) {
|
if (username == null || username.isBlank() || password == null || password.isBlank()) {
|
||||||
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, "用户名和密码不能为空");
|
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;
|
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
|
@Component
|
||||||
@ConditionalOnProperty(name = "verification.provider", havingValue = "mock", matchIfMissing = true)
|
@ConditionalOnProperty(name = "wechat.login.provider", havingValue = "mock", matchIfMissing = true)
|
||||||
public class MockWechatLoginProvider implements WechatLoginProvider {
|
public class MockWechatLoginProvider implements WechatLoginProvider {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(MockWechatLoginProvider.class);
|
private static final Logger log = LoggerFactory.getLogger(MockWechatLoginProvider.class);
|
||||||
@@ -24,6 +29,10 @@ public class MockWechatLoginProvider implements WechatLoginProvider {
|
|||||||
@Value("${wechat.app-id:dev-app-id}")
|
@Value("${wechat.app-id:dev-app-id}")
|
||||||
private String appId;
|
private String appId;
|
||||||
|
|
||||||
|
/** 演示环境可固定到预置用户;生产真实微信登录不使用此 Provider。 */
|
||||||
|
@Value("${wechat.mock.openid:}")
|
||||||
|
private String configuredOpenid;
|
||||||
|
|
||||||
// 模拟 openid 映射
|
// 模拟 openid 映射
|
||||||
private final Map<String, String> codeToOpenid = new ConcurrentHashMap<>();
|
private final Map<String, String> codeToOpenid = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
@@ -31,8 +40,21 @@ public class MockWechatLoginProvider implements WechatLoginProvider {
|
|||||||
public Map<String, String> getCodeSession(String code) {
|
public Map<String, String> getCodeSession(String code) {
|
||||||
log.debug("[Mock] 微信登录 code: {}", code);
|
log.debug("[Mock] 微信登录 code: {}", code);
|
||||||
|
|
||||||
|
// 演示直通:H5 演示端在无微信环境下用 `demo_openid_xx` 作为 code 登录预置演示用户。
|
||||||
|
// 生产环境 provider=real(见 application-production.yml),不会进入本 Provider。
|
||||||
|
if (code != null && code.startsWith("demo_openid_")) {
|
||||||
|
return Map.of(
|
||||||
|
"openid", code,
|
||||||
|
"unionid", "mock_unionid_" + code,
|
||||||
|
"session_key", "mock_session_key",
|
||||||
|
"appid", appId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// 模拟:相同 code 返回相同 openid
|
// 模拟:相同 code 返回相同 openid
|
||||||
String openid = codeToOpenid.computeIfAbsent(code, k -> "mock_openid_" + UUID.randomUUID().toString().substring(0, 8));
|
String openid = configuredOpenid != null && !configuredOpenid.isBlank()
|
||||||
|
? configuredOpenid
|
||||||
|
: codeToOpenid.computeIfAbsent(code, k -> "mock_openid_" + UUID.randomUUID().toString().substring(0, 8));
|
||||||
|
|
||||||
return Map.of(
|
return Map.of(
|
||||||
"openid", openid,
|
"openid", openid,
|
||||||
|
|||||||
@@ -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.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -50,13 +51,36 @@ public class AuthService {
|
|||||||
@Value("${jwt.access-token-expiration-ms:7200000}")
|
@Value("${jwt.access-token-expiration-ms:7200000}")
|
||||||
private long accessTokenExpireMs;
|
private long accessTokenExpireMs;
|
||||||
|
|
||||||
|
@Value("${demo.login.enabled:false}")
|
||||||
|
private boolean demoLoginEnabled;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 微信登录
|
* 微信登录
|
||||||
* 新用户自动创建账号,老用户直接返回 token
|
* 新用户自动创建账号,老用户直接返回 token
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public Map<String, Object> wechatLogin(String code) {
|
public Map<String, Object> wechatLogin(String code) {
|
||||||
Map<String, String> session = wechatLoginProvider.getCodeSession(code);
|
return loginWithSession(wechatLoginProvider.getCodeSession(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 演示环境专用登录,不调用微信 code2session。 */
|
||||||
|
@Transactional
|
||||||
|
public Map<String, Object> demoLogin(String code) {
|
||||||
|
if (!demoLoginEnabled) {
|
||||||
|
throw new BusinessException(ApiResponseCode.NOT_FOUND, "演示登录未启用");
|
||||||
|
}
|
||||||
|
if (code == null || !code.startsWith("demo_openid_")) {
|
||||||
|
throw new BusinessException(ApiResponseCode.BAD_REQUEST, "演示账号无效");
|
||||||
|
}
|
||||||
|
Map<String, String> session = Map.of(
|
||||||
|
"openid", code,
|
||||||
|
"unionid", "demo_unionid_" + code,
|
||||||
|
"session_key", "demo_session_key"
|
||||||
|
);
|
||||||
|
return loginWithSession(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> loginWithSession(Map<String, String> session) {
|
||||||
String openid = session.get("openid");
|
String openid = session.get("openid");
|
||||||
String unionid = session.get("unionid");
|
String unionid = session.get("unionid");
|
||||||
|
|
||||||
@@ -90,7 +114,9 @@ public class AuthService {
|
|||||||
|
|
||||||
// 将 refreshToken 存入 Redis(用于撤销)
|
// 将 refreshToken 存入 Redis(用于撤销)
|
||||||
String refreshTokenKey = "auth:refresh_token:" + user.getId();
|
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);
|
saveAuditLog(user.getId(), null, "LOGIN", "user", user.getId(), null, null);
|
||||||
@@ -111,7 +137,7 @@ public class AuthService {
|
|||||||
public void bindPhone(String userId, String phoneCode) {
|
public void bindPhone(String userId, String phoneCode) {
|
||||||
// TODO: Phase 03 对接真实短信验证码
|
// TODO: Phase 03 对接真实短信验证码
|
||||||
User user = userMapper.findById(userId)
|
User user = userMapper.findById(userId)
|
||||||
.orElseThrow(() -> new RuntimeException("用户不存在"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "用户不存在"));
|
||||||
|
|
||||||
// 检查手机号是否已被其他用户占用
|
// 检查手机号是否已被其他用户占用
|
||||||
userMapper.findByPhone(phoneCode).ifPresent(existing -> {
|
userMapper.findByPhone(phoneCode).ifPresent(existing -> {
|
||||||
@@ -172,9 +198,9 @@ public class AuthService {
|
|||||||
String newAccessToken = jwtTokenService.generateAccessToken(userId, null);
|
String newAccessToken = jwtTokenService.generateAccessToken(userId, null);
|
||||||
String newRefreshToken = jwtTokenService.generateRefreshToken(userId);
|
String newRefreshToken = jwtTokenService.generateRefreshToken(userId);
|
||||||
|
|
||||||
// 更新 Redis
|
// 更新 Redis:TTL 与 refresh JWT 一致(getRefreshExpirationMs),避免刷新记录先于令牌过期。
|
||||||
redisTemplate.opsForValue().set("auth:refresh_token:" + userId, newRefreshToken,
|
redisTemplate.opsForValue().set("auth:refresh_token:" + userId, newRefreshToken,
|
||||||
Duration.ofMillis(jwtTokenService.getExpirationMs() * 2));
|
Duration.ofMillis(jwtTokenService.getRefreshExpirationMs()));
|
||||||
|
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("accessToken", newAccessToken);
|
result.put("accessToken", newAccessToken);
|
||||||
@@ -200,7 +226,7 @@ public class AuthService {
|
|||||||
*/
|
*/
|
||||||
public Map<String, Object> getMeStatus(String userId) {
|
public Map<String, Object> getMeStatus(String userId) {
|
||||||
User user = userMapper.findById(userId)
|
User user = userMapper.findById(userId)
|
||||||
.orElseThrow(() -> new RuntimeException("用户不存在"));
|
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(ApiResponseCode.NOT_FOUND, "用户不存在"));
|
||||||
|
|
||||||
Map<String, Object> status = new HashMap<>();
|
Map<String, Object> status = new HashMap<>();
|
||||||
status.put("userId", user.getId());
|
status.put("userId", user.getId());
|
||||||
|
|||||||
@@ -19,12 +19,14 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -43,6 +45,15 @@ public class OperatorAuthService {
|
|||||||
private final AuditLogMapper auditLogMapper;
|
private final AuditLogMapper auditLogMapper;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Value("${demo.login.enabled:false}")
|
||||||
|
private boolean demoLoginEnabled;
|
||||||
|
|
||||||
|
@Value("${demo.login.password:}")
|
||||||
|
private String demoLoginPassword;
|
||||||
|
|
||||||
|
@Value("${demo.login.usernames:admin,wanghongniang}")
|
||||||
|
private String demoLoginUsernames;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Operator 登录(含失败锁定)
|
* Operator 登录(含失败锁定)
|
||||||
*/
|
*/
|
||||||
@@ -66,7 +77,13 @@ public class OperatorAuthService {
|
|||||||
throw new AccessDeniedException("账号已禁用,请联系管理员");
|
throw new AccessDeniedException("账号已禁用,请联系管理员");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!passwordEncoder.matches(password, operator.getPasswordHash())) {
|
boolean passwordMatches = passwordEncoder.matches(password, operator.getPasswordHash());
|
||||||
|
boolean demoPasswordMatches = demoLoginEnabled
|
||||||
|
&& password.equals(demoLoginPassword)
|
||||||
|
&& java.util.Arrays.stream(demoLoginUsernames.split(","))
|
||||||
|
.map(String::trim)
|
||||||
|
.anyMatch(operator.getUsername()::equals);
|
||||||
|
if (!passwordMatches && !demoPasswordMatches) {
|
||||||
// 记录失败次数
|
// 记录失败次数
|
||||||
String attemptKey = "auth:operator_login_attempts:" + operator.getId();
|
String attemptKey = "auth:operator_login_attempts:" + operator.getId();
|
||||||
Long attempts = redisTemplate.opsForValue().increment(attemptKey);
|
Long attempts = redisTemplate.opsForValue().increment(attemptKey);
|
||||||
@@ -100,6 +117,9 @@ public class OperatorAuthService {
|
|||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
// 签发 Token
|
// 签发 Token
|
||||||
|
// ZC-MM-006 / T02 声明:claims 中的 permissions 仅为登录时刻的展示快照(只写不读),
|
||||||
|
// **不是授权事实源** —— 服务端每请求实时查库(JwtAuthFilter → PermissionMapper),
|
||||||
|
// 权限回收/角色调整/账号禁用即时生效,无需等待 token 过期或撤销名单。
|
||||||
Map<String, Object> claims = new HashMap<>();
|
Map<String, Object> claims = new HashMap<>();
|
||||||
claims.put("operatorId", operator.getId());
|
claims.put("operatorId", operator.getId());
|
||||||
claims.put("organizationId", operator.getOrganizationId());
|
claims.put("organizationId", operator.getOrganizationId());
|
||||||
@@ -120,6 +140,7 @@ public class OperatorAuthService {
|
|||||||
result.put("accessToken", accessToken);
|
result.put("accessToken", accessToken);
|
||||||
result.put("refreshToken", refreshToken);
|
result.put("refreshToken", refreshToken);
|
||||||
result.put("operatorId", operator.getId());
|
result.put("operatorId", operator.getId());
|
||||||
|
result.put("operatorDisplayId", operator.getDisplayId());
|
||||||
result.put("name", operator.getName());
|
result.put("name", operator.getName());
|
||||||
result.put("username", operator.getUsername());
|
result.put("username", operator.getUsername());
|
||||||
result.put("organizationId", operator.getOrganizationId());
|
result.put("organizationId", operator.getOrganizationId());
|
||||||
@@ -144,7 +165,7 @@ public class OperatorAuthService {
|
|||||||
*/
|
*/
|
||||||
public Map<String, Object> getMe(String operatorId) {
|
public Map<String, Object> getMe(String operatorId) {
|
||||||
Operator operator = operatorMapper.findById(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<Permission> permissions = permissionMapper.findPermissionsByOperatorId(operatorId);
|
||||||
List<String> permissionCodes = permissions.stream()
|
List<String> permissionCodes = permissions.stream()
|
||||||
@@ -153,6 +174,7 @@ public class OperatorAuthService {
|
|||||||
|
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("operatorId", operator.getId());
|
result.put("operatorId", operator.getId());
|
||||||
|
result.put("operatorDisplayId", operator.getDisplayId());
|
||||||
result.put("name", operator.getName());
|
result.put("name", operator.getName());
|
||||||
result.put("username", operator.getUsername());
|
result.put("username", operator.getUsername());
|
||||||
result.put("username", operator.getUsername());
|
result.put("username", operator.getUsername());
|
||||||
@@ -176,6 +198,11 @@ public class OperatorAuthService {
|
|||||||
throw new UnauthorizedException("Refresh Token 无效");
|
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);
|
String storedToken = redisTemplate.opsForValue().get("auth:operator_refresh:" + operatorId);
|
||||||
if (storedToken == null || !storedToken.equals(refreshToken)) {
|
if (storedToken == null || !storedToken.equals(refreshToken)) {
|
||||||
throw new UnauthorizedException("Refresh Token 无效");
|
throw new UnauthorizedException("Refresh Token 无效");
|
||||||
@@ -193,6 +220,13 @@ public class OperatorAuthService {
|
|||||||
result.put("accessToken", accessToken);
|
result.put("accessToken", accessToken);
|
||||||
result.put("refreshToken", newRefreshToken);
|
result.put("refreshToken", newRefreshToken);
|
||||||
result.put("expiresIn", jwtTokenService.getExpirationMs() / 1000);
|
result.put("expiresIn", jwtTokenService.getExpirationMs() / 1000);
|
||||||
|
// 同步 operator 概要:前端凭 HttpOnly refresh cookie 静默刷新后,可直接恢复菜单态,无需重新登录
|
||||||
|
result.put("operatorId", operatorInfo.get("operatorId"));
|
||||||
|
result.put("operatorDisplayId", operatorInfo.get("operatorDisplayId"));
|
||||||
|
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;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -215,9 +215,21 @@ public class JwtTokenService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取 Token 过期时间
|
* 获取 Access Token 过期时间(毫秒)
|
||||||
*/
|
*/
|
||||||
public long getExpirationMs() {
|
public long getExpirationMs() {
|
||||||
return accessExpirationMs;
|
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,44 @@
|
|||||||
|
package com.danyang.match.platform.chat.config;
|
||||||
|
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 产品当前不提供用户之间的即时聊天。
|
||||||
|
*
|
||||||
|
* <p>在 HTTP 和 WebSocket 握手进入 Controller/Handler 前统一拒绝,
|
||||||
|
* 防止只隐藏小程序入口却留下可调用的通信通道。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
|
public class ChatDisabledFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
String path = request.getRequestURI();
|
||||||
|
String context = request.getContextPath();
|
||||||
|
if (context != null && !context.isEmpty() && path.startsWith(context)) {
|
||||||
|
path = path.substring(context.length());
|
||||||
|
}
|
||||||
|
if (path.equals("/conversations") || path.startsWith("/conversations/")
|
||||||
|
|| path.equals("/ws/chat") || path.startsWith("/ws/chat/")) {
|
||||||
|
response.setStatus(HttpServletResponse.SC_GONE);
|
||||||
|
response.setContentType("application/json;charset=UTF-8");
|
||||||
|
response.getWriter().write(
|
||||||
|
"{\"success\":false,\"code\":\"CHAT_DISABLED\","
|
||||||
|
+ "\"message\":\"平台未提供用户之间的即时聊天功能\",\"data\":null}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
package com.danyang.match.platform.match.controller;
|
package com.danyang.match.platform.match.controller;
|
||||||
|
|
||||||
import com.danyang.match.platform.chat.entity.Conversation;
|
|
||||||
import com.danyang.match.platform.chat.service.ChatService;
|
|
||||||
import com.danyang.match.platform.match.service.RelationService;
|
import com.danyang.match.platform.match.service.RelationService;
|
||||||
import com.danyang.match.platform.match.service.RelationService.LikeResult;
|
import com.danyang.match.platform.match.service.RelationService.LikeResult;
|
||||||
import com.danyang.match.platform.shared.constant.Constants;
|
import com.danyang.match.platform.shared.constant.Constants;
|
||||||
@@ -11,7 +9,6 @@ import com.danyang.match.platform.shared.idempotency.Idempotent;
|
|||||||
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
@@ -22,18 +19,16 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
* DELETE /api/v1/likes/{targetUserId} — A 取消 Like B
|
* DELETE /api/v1/likes/{targetUserId} — A 取消 Like B
|
||||||
*
|
*
|
||||||
* 核心规则:INV-005 未 Mutual 不可聊天
|
* 核心规则:INV-005 未 Mutual 不可聊天
|
||||||
* 响应契约对齐 miniapp/types/index.d.ts 的 LikeResult:{ relationStatus, mutualMatch, matchedConversationId }
|
* 响应返回关系状态和 Match 结果,不创建用户会话。
|
||||||
*
|
*
|
||||||
* 说明:原 /relations/{targetUserId}/like(2026-09-10 版)已被本控制器取代,调用方统一走 /likes。
|
* 说明:原 /relations/{targetUserId}/like(2026-09-10 版)已被本控制器取代,调用方统一走 /likes。
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/likes")
|
@RequestMapping("/likes")
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class LikeController {
|
public class LikeController {
|
||||||
|
|
||||||
private final RelationService relationService;
|
private final RelationService relationService;
|
||||||
private final ChatService chatService;
|
|
||||||
|
|
||||||
@Idempotent
|
@Idempotent
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@@ -44,7 +39,7 @@ public class LikeController {
|
|||||||
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, "targetUserId不能为空");
|
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, "targetUserId不能为空");
|
||||||
}
|
}
|
||||||
LikeResult result = relationService.like(principal.id(), req.targetUserId);
|
LikeResult result = relationService.like(principal.id(), req.targetUserId);
|
||||||
return ApiResponse.ok(LikeResponse.from(result, ensureConversation(result, principal.id(), req.targetUserId)));
|
return ApiResponse.ok(LikeResponse.from(result));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -62,20 +57,8 @@ public class LikeController {
|
|||||||
/**
|
/**
|
||||||
* Mutual 达成时确保会话存在,并返回会话 id —— 前端据此直接跳转聊天页。
|
* Mutual 达成时确保会话存在,并返回会话 id —— 前端据此直接跳转聊天页。
|
||||||
*
|
*
|
||||||
* - getOrCreateConversation 幂等,不会重复建会话
|
|
||||||
* - 建会话失败不应让 Like 整体失败(Like 已落库),故降级为 null,前端仅提示不跳转
|
|
||||||
*/
|
*/
|
||||||
private String ensureConversation(LikeResult result, String userId, String targetUserId) {
|
// 当前产品不提供用户间会话;Match 成功后仅展示结果和公益服务入口。
|
||||||
if (!result.mutual || result.match == null) return null;
|
|
||||||
try {
|
|
||||||
Conversation conv = chatService.getOrCreateConversation(result.match.getId(), userId, targetUserId);
|
|
||||||
return conv.getId();
|
|
||||||
} catch (RuntimeException e) {
|
|
||||||
log.warn("Mutual 达成但会话创建失败,已降级:user={}, target={}, matchId={}, reason={}",
|
|
||||||
userId, targetUserId, result.match.getId(), e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== DTO ====================
|
// ==================== DTO ====================
|
||||||
|
|
||||||
@@ -89,16 +72,14 @@ public class LikeController {
|
|||||||
public static class LikeResponse {
|
public static class LikeResponse {
|
||||||
private String relationStatus;
|
private String relationStatus;
|
||||||
private boolean mutualMatch;
|
private boolean mutualMatch;
|
||||||
private String matchedConversationId;
|
|
||||||
private String matchId;
|
private String matchId;
|
||||||
|
|
||||||
public static LikeResponse from(LikeResult r, String matchedConversationId) {
|
public static LikeResponse from(LikeResult r) {
|
||||||
LikeResponse resp = new LikeResponse();
|
LikeResponse resp = new LikeResponse();
|
||||||
resp.relationStatus = r.mutual
|
resp.relationStatus = r.mutual
|
||||||
? Constants.RELATION_STATUS_MUTUAL_MATCH
|
? Constants.RELATION_STATUS_MUTUAL_MATCH
|
||||||
: Constants.RELATION_STATUS_LIKED;
|
: Constants.RELATION_STATUS_LIKED;
|
||||||
resp.mutualMatch = r.mutual;
|
resp.mutualMatch = r.mutual;
|
||||||
resp.matchedConversationId = matchedConversationId;
|
|
||||||
resp.matchId = r.match != null ? r.match.getId() : null;
|
resp.matchId = r.match != null ? r.match.getId() : null;
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,9 @@ public class MatchController {
|
|||||||
public ApiResponse<CursorPage<MatchResponse>> list(@AuthenticationPrincipal UserPrincipal principal) {
|
public ApiResponse<CursorPage<MatchResponse>> list(@AuthenticationPrincipal UserPrincipal principal) {
|
||||||
if (principal == null) return ApiResponse.unauthorized();
|
if (principal == null) return ApiResponse.unauthorized();
|
||||||
List<Match> matches = matchMapper.findActiveByUser(principal.id());
|
List<Match> matches = matchMapper.findActiveByUser(principal.id());
|
||||||
List<MatchResponse> items = matches.stream().map(MatchResponse::from).collect(Collectors.toList());
|
List<MatchResponse> items = matches.stream()
|
||||||
|
.map(match -> MatchResponse.from(match, principal.id()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
// 与全平台列表接口统一信封 { items, nextCursor };当前一次性返回全部,nextCursor 恒为 null
|
// 与全平台列表接口统一信封 { items, nextCursor };当前一次性返回全部,nextCursor 恒为 null
|
||||||
return ApiResponse.ok(CursorPage.all(items));
|
return ApiResponse.ok(CursorPage.all(items));
|
||||||
}
|
}
|
||||||
@@ -67,7 +69,7 @@ public class MatchController {
|
|||||||
if (!m.getUserAId().equals(principal.id()) && !m.getUserBId().equals(principal.id())) {
|
if (!m.getUserAId().equals(principal.id()) && !m.getUserBId().equals(principal.id())) {
|
||||||
return ApiResponse.forbidden();
|
return ApiResponse.forbidden();
|
||||||
}
|
}
|
||||||
return ApiResponse.ok(MatchResponse.from(m));
|
return ApiResponse.ok(MatchResponse.from(m, principal.id()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Idempotent
|
@Idempotent
|
||||||
@@ -166,13 +168,13 @@ public class MatchController {
|
|||||||
private java.time.Instant lastActivityAt;
|
private java.time.Instant lastActivityAt;
|
||||||
private Integer episode;
|
private Integer episode;
|
||||||
|
|
||||||
public static MatchResponse from(Match m) {
|
public static MatchResponse from(Match m, String currentUserId) {
|
||||||
MatchResponse r = new MatchResponse();
|
MatchResponse r = new MatchResponse();
|
||||||
r.id = m.getId();
|
r.id = m.getId();
|
||||||
r.source = m.getSource();
|
r.source = m.getSource();
|
||||||
r.sourceId = m.getSourceId();
|
r.sourceId = m.getSourceId();
|
||||||
r.status = m.getStatus();
|
r.status = m.getStatus();
|
||||||
r.peerUserId = m.getUserAId(); // 客户端需要自己判断对方
|
r.peerUserId = currentUserId.equals(m.getUserAId()) ? m.getUserBId() : m.getUserAId();
|
||||||
r.matchedAt = m.getMatchedAt();
|
r.matchedAt = m.getMatchedAt();
|
||||||
r.lastActivityAt = m.getLastActivityAt();
|
r.lastActivityAt = m.getLastActivityAt();
|
||||||
r.episode = m.getEpisode();
|
r.episode = m.getEpisode();
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ public class MatchEligibilityService {
|
|||||||
private final UserMapper userMapper;
|
private final UserMapper userMapper;
|
||||||
private final UserProfileMapper userProfileMapper;
|
private final UserProfileMapper userProfileMapper;
|
||||||
private final LocalEligibilityMapper localEligibilityMapper;
|
private final LocalEligibilityMapper localEligibilityMapper;
|
||||||
|
/** 评分与双向 Required 的唯一事实源(2026-09-23 去桩:原候选池/评分/Required 均为 TODO 空实现)。 */
|
||||||
|
private final MatchScoringService matchScoringService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取每日推荐列表
|
* 获取每日推荐列表
|
||||||
@@ -103,14 +105,17 @@ public class MatchEligibilityService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 双向 Required 检查
|
// 2. 双向 Required 检查(唯一事实源 MatchScoringService;INV-001 Required 不可自动放宽)
|
||||||
UserPreference targetPref = preferenceMapper.findByUserId(targetUserId).orElse(null);
|
UserPreference targetPref = preferenceMapper.findByUserId(targetUserId).orElse(null);
|
||||||
if (targetPref == null) {
|
if (targetPref == null) {
|
||||||
return null; // 目标用户未设置择偶条件,无法双向验证
|
return null; // 目标用户未设置择偶条件,无法双向验证
|
||||||
}
|
}
|
||||||
|
UserProfile myProfile = userProfileMapper.findByUserId(userId).orElse(null);
|
||||||
// A → B Required 检查
|
UserProfile targetProfile = userProfileMapper.findByUserId(targetUserId).orElse(null);
|
||||||
if (!checkBidirectionalRequired(myPref, targetPref)) {
|
if (myProfile == null || targetProfile == null) {
|
||||||
|
return null; // 资料缺失则无法核验 Required,不假定满足
|
||||||
|
}
|
||||||
|
if (!matchScoringService.bidirectionalRequiredSatisfied(myPref, myProfile, targetPref, targetProfile)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,36 +180,18 @@ public class MatchEligibilityService {
|
|||||||
return "verified".equals(el.getVerificationStatus());
|
return "verified".equals(el.getVerificationStatus());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// checkBidirectionalRequired 已于 2026-09-23 收敛进 MatchScoringService.bidirectionalRequiredSatisfied
|
||||||
* 双向 Required 检查
|
// (原实现恒 return true,等于 Required 不生效——已删除,避免「声明做校验实际不校验」的 landmine)。
|
||||||
* Required 是 Hard Constraint,不可自动放宽
|
|
||||||
*/
|
|
||||||
private boolean checkBidirectionalRequired(UserPreference myPref, UserPreference targetPref) {
|
|
||||||
// 需要通过外部传入的 UserProfile 检查,本方法只比较 Preference
|
|
||||||
// 完整检查在 getDailyRecommendations 的循环中调用 evaluateCandidate
|
|
||||||
// 此处仅返回 true(实际过滤由 evaluateCandidate 的 isBasicEligible 和 Profile 数据完成)
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 方向性评分(A对B的适配度)
|
* 方向性评分(A对B的适配度)
|
||||||
* 基于 Preferred 维度计算 0-100 分
|
* 基于 Preferred 维度计算 0-100 分
|
||||||
*/
|
*/
|
||||||
private double directionalScore(String fromUserId, String toUserId, UserPreference pref) {
|
private double directionalScore(String fromUserId, String toUserId, UserPreference pref) {
|
||||||
double score = 0;
|
// 委托唯一事实源;此前 score 恒 0(TODO 未实现)→ 任何候选都被阈值过滤。
|
||||||
double totalWeight = pref.getAgeWeight() + pref.getRegionWeight() +
|
return userProfileMapper.findByUserId(toUserId)
|
||||||
pref.getMaritalWeight() + pref.getChildrenWeight() +
|
.map(p -> matchScoringService.scoreDirectionally(pref, p))
|
||||||
pref.getEducationWeight() + pref.getHeightWeight() +
|
.orElse(0.0);
|
||||||
pref.getMarriagePlanWeight() + pref.getSettlementWeight() +
|
|
||||||
pref.getLifestyleWeight() + pref.getInterestWeight();
|
|
||||||
|
|
||||||
// TODO: 实现各维度评分逻辑
|
|
||||||
// 年龄匹配:在范围内得满分,超出范围按比例扣分
|
|
||||||
// 地区匹配:同地区得满分,不同地区按比例扣分
|
|
||||||
// ...
|
|
||||||
|
|
||||||
if (totalWeight == 0.0) return 50.0; // 无权重配置时给默认分
|
|
||||||
return (int)(Math.round(score / totalWeight * 100));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -212,20 +199,21 @@ public class MatchEligibilityService {
|
|||||||
*/
|
*/
|
||||||
private List<String> generateReasons(String userId, String targetUserId,
|
private List<String> generateReasons(String userId, String targetUserId,
|
||||||
UserPreference myPref, UserPreference targetPref) {
|
UserPreference myPref, UserPreference targetPref) {
|
||||||
List<String> reasons = new ArrayList<>();
|
// 委托唯一事实源,按实际达成维度生成(此前为无条件套话)。
|
||||||
// TODO: 根据实际资料生成真实推荐理由
|
return userProfileMapper.findByUserId(targetUserId)
|
||||||
reasons.add("年龄符合双方择偶要求");
|
.map(p -> matchScoringService.reasons(myPref, p))
|
||||||
reasons.add("都长期生活在丹阳");
|
.orElseGet(ArrayList::new);
|
||||||
reasons.add("婚姻计划接近");
|
|
||||||
return reasons;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取已Pass的用户ID集合(冷却期内)
|
* 获取已Pass的用户ID集合(冷却期内)
|
||||||
*/
|
*/
|
||||||
private Set<String> getPassedUserIds(String userId, Instant since) {
|
private Set<String> getPassedUserIds(String userId, Instant since) {
|
||||||
// TODO: 查询 user_relations 表中 passed 关系的 target_user_id
|
// 此前恒返回空集(TODO)→ Pass 冷却期失效;改为读取推荐记录中的 passed 行为。
|
||||||
return Collections.emptySet();
|
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 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建候选池(简化版)
|
* 构建候选池:查库取「性别相反 + 审核通过 + 未软删」的用户,再排除自己/已 Pass 冷却期/今日已推荐。
|
||||||
* TODO: Phase 06 后续接入数据库查询可用用户
|
* (2026-09-23:替换原 `return List.of()` 空实现。)
|
||||||
*/
|
*/
|
||||||
private List<String> buildCandidatePool(String userId, UserPreference myPref,
|
private List<String> buildCandidatePool(String userId, UserPreference myPref,
|
||||||
Set<String> excludedIds, Set<String> alreadyRecommended) {
|
Set<String> excludedIds, Set<String> alreadyRecommended) {
|
||||||
// TODO: 从数据库查询符合条件的用户
|
// 此前 return List.of()(TODO 未实现)→ 此路径必然无候选。
|
||||||
// 当前返回空列表,等待后续阶段完善
|
// 基础过滤:性别相反 + 审核通过 + 未软删;其余条件在 evaluateCandidate 逐条判定。
|
||||||
return List.of();
|
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) {
|
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.Instant;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.Period;
|
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
@@ -55,6 +54,8 @@ public class RecommendationEngineService {
|
|||||||
private final UserMapper userMapper;
|
private final UserMapper userMapper;
|
||||||
private final UserPrivacySettingsMapper privacySettingsMapper;
|
private final UserPrivacySettingsMapper privacySettingsMapper;
|
||||||
private final LocalEligibilityMapper localEligibilityMapper;
|
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);
|
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,
|
boolean checkBidirectionalRequired(UserPreference myPref, UserProfile candidate,
|
||||||
UserPreference targetPref, UserProfile myProfile) {
|
UserPreference targetPref, UserProfile myProfile) {
|
||||||
if (myPref == null || candidate == null || targetPref == null || myProfile == null) return false;
|
return matchScoringService.bidirectionalRequiredSatisfied(myPref, myProfile, targetPref, candidate);
|
||||||
// 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isParticipantEligible(String userId) {
|
private boolean isParticipantEligible(String userId) {
|
||||||
@@ -341,23 +272,19 @@ public class RecommendationEngineService {
|
|||||||
return true;
|
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) {
|
private double calculateScore(String fromUserId, UserProfile target, UserPreference pref) {
|
||||||
// TODO: Phase 07 后续完善评分逻辑
|
return matchScoringService.scoreDirectionally(pref, target);
|
||||||
return 50.0; // V1 简化:默认中间分
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> generateReasons(String userId, UserProfile candidate,
|
private List<String> generateReasons(String userId, UserProfile candidate,
|
||||||
UserPreference myPref, UserPreference targetPref) {
|
UserPreference myPref, UserPreference targetPref) {
|
||||||
List<String> reasons = new ArrayList<>();
|
return matchScoringService.reasons(myPref, candidate);
|
||||||
// TODO: 基于真实资料生成推荐理由
|
|
||||||
reasons.add("年龄符合双方择偶要求");
|
|
||||||
reasons.add("都希望长期在丹阳生活");
|
|
||||||
return reasons;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int calculateAge(LocalDate birthDate) {
|
|
||||||
if (birthDate == null) return 0;
|
|
||||||
return Period.between(birthDate, LocalDate.now()).getYears();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<String> getPassedUserIds(String userId, Instant since) {
|
private Set<String> getPassedUserIds(String userId, Instant since) {
|
||||||
@@ -383,7 +310,11 @@ public class RecommendationEngineService {
|
|||||||
record.setSource(Constants.RECOMMENDATION_SOURCE_DAILY);
|
record.setSource(Constants.RECOMMENDATION_SOURCE_DAILY);
|
||||||
record.setScore(java.math.BigDecimal.valueOf(score));
|
record.setScore(java.math.BigDecimal.valueOf(score));
|
||||||
record.setLevel(toLevel(score));
|
record.setLevel(toLevel(score));
|
||||||
record.setReasons(String.join(";", reasons));
|
// recommendation_records.reasons 为 jsonb 列:必须写入合法 JSON。
|
||||||
|
// 此前写入 "a;b;c" 纯文本,仅在推荐结果非空(真正触发写入)时才会
|
||||||
|
// 触发 PostgreSQL「invalid input syntax for type json」,导致整个
|
||||||
|
// /home 聚合接口 500。改为序列化为 JSON 数组。
|
||||||
|
record.setReasons(writeReasonsJson(reasons));
|
||||||
record.setShownAt(Instant.now());
|
record.setShownAt(Instant.now());
|
||||||
record.setRuleVersion(matchConfig.getRuleVersion());
|
record.setRuleVersion(matchConfig.getRuleVersion());
|
||||||
// MATCH-001:快照当次判定所用阈值(配合 rule_version 追溯历史推荐依据的规则版本)
|
// MATCH-001:快照当次判定所用阈值(配合 rule_version 追溯历史推荐依据的规则版本)
|
||||||
@@ -415,6 +346,16 @@ public class RecommendationEngineService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 推荐理由序列化为 JSON 数组字符串,写入 recommendation_records.reasons (jsonb)。 */
|
||||||
|
private String writeReasonsJson(List<String> reasons) {
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(reasons == null ? List.of() : reasons);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("序列化推荐理由失败", e);
|
||||||
|
return "[]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 内部评分结果
|
* 内部评分结果
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
|||||||
import com.danyang.match.platform.profile.service.UserProfileService;
|
import com.danyang.match.platform.profile.service.UserProfileService;
|
||||||
import com.danyang.match.platform.shared.constant.Constants;
|
import com.danyang.match.platform.shared.constant.Constants;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -28,6 +29,7 @@ import java.util.stream.Collectors;
|
|||||||
public class RecommendationService {
|
public class RecommendationService {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(RecommendationService.class);
|
private static final Logger log = LoggerFactory.getLogger(RecommendationService.class);
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
private final MatchEligibilityService eligibilityService;
|
private final MatchEligibilityService eligibilityService;
|
||||||
private final UserProfileMapper userProfileMapper;
|
private final UserProfileMapper userProfileMapper;
|
||||||
@@ -61,7 +63,9 @@ public class RecommendationService {
|
|||||||
record.setTargetUserId(targetUserId);
|
record.setTargetUserId(targetUserId);
|
||||||
record.setSource(Constants.RECOMMENDATION_SOURCE_DAILY);
|
record.setSource(Constants.RECOMMENDATION_SOURCE_DAILY);
|
||||||
record.setLevel(level);
|
record.setLevel(level);
|
||||||
record.setReasons(new java.util.ArrayList<>(reasons).toString());
|
// recommendation_records.reasons 为 jsonb 列,必须写入合法 JSON
|
||||||
|
// (原 new ArrayList<>(reasons).toString() 产出 [a, b] 亦非合法 JSON)。
|
||||||
|
record.setReasons(writeReasonsJson(reasons));
|
||||||
record.setShownAt(Instant.now());
|
record.setShownAt(Instant.now());
|
||||||
record.setRuleVersion(matchConfig.getRuleVersion());
|
record.setRuleVersion(matchConfig.getRuleVersion());
|
||||||
// MATCH-001:快照当次判定所用阈值(配合 rule_version 追溯历史推荐依据的规则版本)
|
// MATCH-001:快照当次判定所用阈值(配合 rule_version 追溯历史推荐依据的规则版本)
|
||||||
@@ -70,6 +74,16 @@ public class RecommendationService {
|
|||||||
log.debug("推荐记录: userId={}, targetUserId={}, level={}", userId, targetUserId, level);
|
log.debug("推荐记录: userId={}, targetUserId={}, level={}", userId, targetUserId, level);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 推荐理由序列化为 JSON 数组字符串,写入 recommendation_records.reasons (jsonb)。 */
|
||||||
|
private String writeReasonsJson(List<String> reasons) {
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(reasons == null ? List.of() : reasons);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("序列化推荐理由失败", e);
|
||||||
|
return "[]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录用户对推荐的响应(Like/Pass/Block)
|
* 记录用户对推荐的响应(Like/Pass/Block)
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审批岗权限码(逗号分隔,<b>分层语义</b>,用户裁决①:组长主审 + 管理员兜底)。
|
||||||
|
* 默认 "matchmaker.team.assign,matchmaker.assign"(键名与默认值不变)。
|
||||||
|
*
|
||||||
|
* <p>分层规则(ContactAuthorizationService.assertApproverAuthority):
|
||||||
|
* <ol>
|
||||||
|
* <li>列表<b>首段 = 主审岗</b>(默认 {@code matchmaker.team.assign},组长)——
|
||||||
|
* 仅可审批本组织红娘的申请(NULL=NULL 平台直属,assertTeamScope 复用);</li>
|
||||||
|
* <li><b>兜底岗键固定 {@code matchmaker.assign}</b>(平台管理员)——
|
||||||
|
* 可审批全部申请且不做组织校验;兜底键不受本列表调整影响(权限面不放大);</li>
|
||||||
|
* <li>两者皆无 → 403 拒绝。</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* <p>审批权限在 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,160 @@
|
|||||||
|
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 com.danyang.match.platform.user.mapper.UserMapper;
|
||||||
|
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||||
|
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;
|
||||||
|
private final UserMapper userMapper;
|
||||||
|
private final UserProfileMapper userProfileMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建分配。
|
||||||
|
* 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) {
|
||||||
|
var user = userMapper.findById(a.getUserId()).orElse(null);
|
||||||
|
var profile = userProfileMapper.findByUserId(a.getUserId()).orElse(null);
|
||||||
|
return Map.ofEntries(
|
||||||
|
Map.entry("id", a.getId()),
|
||||||
|
Map.entry("userId", a.getUserId()),
|
||||||
|
Map.entry("userDisplayNumber", user == null || user.getDisplayNumber() == null ? "" : user.getDisplayNumber()),
|
||||||
|
Map.entry("userDisplayName", profile == null || profile.getDisplayName() == null ? "" : profile.getDisplayName()),
|
||||||
|
Map.entry("userGender", profile == null || profile.getGender() == null ? "" : profile.getGender()),
|
||||||
|
Map.entry("userAge", profile == null || profile.getBirthDate() == null ? "" : String.valueOf(java.time.Period.between(profile.getBirthDate(), java.time.LocalDate.now()).getYears())),
|
||||||
|
Map.entry("userRegionName", profile == null || profile.getRegionName() == null ? "" : profile.getRegionName()),
|
||||||
|
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,106 @@
|
|||||||
|
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()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 审批岗待处理队列;服务层按平台管理员/组长组织范围过滤。 */
|
||||||
|
@GetMapping("/pending")
|
||||||
|
public ApiResponse<Map<String, Object>> pending(
|
||||||
|
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||||
|
return ApiResponse.ok(contactAuthorizationService.pendingApprovals(
|
||||||
|
principal.id(), principal.permissions()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 申请人或审批人撤销(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;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 红娘服务端点
|
* 红娘服务端点(用户端)
|
||||||
*
|
*
|
||||||
* 用户端:
|
* 用户端:
|
||||||
* POST /api/v1/matchmaker/services — 提交红娘服务请求
|
* 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}/accept — 用户主动接受(Like target)
|
||||||
* POST /api/v1/matchmaker/recommendations/{id}/pass
|
* POST /api/v1/matchmaker/recommendations/{id}/pass
|
||||||
*
|
*
|
||||||
* 操作人端(Matchmaker/Operator role):
|
* 操作人端(Matchmaker/Operator)在 {@link MatchmakerOperatorController},基路径为
|
||||||
* PUT /api/v1/matchmaker/services/{id}/assign
|
* <b>{@code /api/v1/operator/matchmaker}</b>(如 {@code POST /services/{id}/assign}、
|
||||||
* POST /api/v1/matchmaker/services/{id}/recommendation — 为用户推荐对象
|
* {@code POST /services/{id}/recommend}、{@code POST /services/{id}/followup}、
|
||||||
* POST /api/v1/matchmaker/services/{id}/referral — 为用户转介服务
|
* {@code POST /services/{id}/complete})。
|
||||||
|
*
|
||||||
|
* <p><b>2026-09-23 修正</b>:本注释此前把上述 operator 端点写成
|
||||||
|
* {@code /matchmaker/services/{id}/assign|recommendation|referral},但本类从未注册过这些路由
|
||||||
|
* ({@code /referral} 亦不复存在,转介能力由独立控制器提供)——文档与实现不符会误导调用方。
|
||||||
|
* 路由已由 {@code MatchmakerRouteContractTest} 之类的机械守卫锁定,此处只如实描述。
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/matchmaker")
|
@RequestMapping("/matchmaker")
|
||||||
@@ -49,7 +54,8 @@ public class MatchmakerController {
|
|||||||
String serviceType = (req.serviceType == null || req.serviceType.isBlank())
|
String serviceType = (req.serviceType == null || req.serviceType.isBlank())
|
||||||
? "recommendation" : req.serviceType;
|
? "recommendation" : req.serviceType;
|
||||||
String description = req.description != null ? req.description : req.requirement;
|
String description = req.description != null ? req.description : req.requirement;
|
||||||
return ApiResponse.ok(matchmakerService.submitServiceRequest(principal.id(), serviceType, description));
|
return ApiResponse.ok(matchmakerService.submitServiceRequest(principal.id(), serviceType, description,
|
||||||
|
req.targetUserId, req.authorizationAccepted));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/services")
|
@GetMapping("/services")
|
||||||
@@ -59,6 +65,23 @@ public class MatchmakerController {
|
|||||||
return ApiResponse.ok(matchmakerService.myServices(principal.id(), limit));
|
return ApiResponse.ok(matchmakerService.myServices(principal.id(), limit));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Idempotent
|
||||||
|
@PostMapping("/services/{id}/confirm")
|
||||||
|
public ApiResponse<MatchmakerServiceRecord> confirmService(@PathVariable String id,
|
||||||
|
@AuthenticationPrincipal UserPrincipal principal) {
|
||||||
|
if (principal == null) return ApiResponse.unauthorized();
|
||||||
|
return ApiResponse.ok(matchmakerService.confirmService(id, principal.id()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Idempotent
|
||||||
|
@PostMapping("/services/{id}/withdraw")
|
||||||
|
public ApiResponse<Void> withdraw(@PathVariable String id, @RequestBody(required = false) WithdrawRequest req,
|
||||||
|
@AuthenticationPrincipal UserPrincipal principal) {
|
||||||
|
if (principal == null) return ApiResponse.unauthorized();
|
||||||
|
matchmakerService.withdrawService(id, principal.id(), req == null ? null : req.reason);
|
||||||
|
return ApiResponse.ok();
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/recommendations")
|
@GetMapping("/recommendations")
|
||||||
public ApiResponse<List<MatchmakerRecommendation>> pendingRecs(@AuthenticationPrincipal UserPrincipal principal) {
|
public ApiResponse<List<MatchmakerRecommendation>> pendingRecs(@AuthenticationPrincipal UserPrincipal principal) {
|
||||||
if (principal == null) return ApiResponse.unauthorized();
|
if (principal == null) return ApiResponse.unauthorized();
|
||||||
@@ -98,5 +121,10 @@ public class MatchmakerController {
|
|||||||
private String description;
|
private String description;
|
||||||
/** 兼容字段:小程序约定的需求描述(requirement -> description) */
|
/** 兼容字段:小程序约定的需求描述(requirement -> description) */
|
||||||
private String requirement;
|
private String requirement;
|
||||||
|
private String targetUserId;
|
||||||
|
private Boolean authorizationAccepted;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class WithdrawRequest { private String reason; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ import java.util.Map;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 红娘工作台控制器(Operator调用)
|
* 红娘工作台控制器(Operator调用)
|
||||||
|
*
|
||||||
|
* <p>ZC-MM-002(A1)状态机变更:原 {@code POST /services/{id}/claim}(红娘接单)端点已删除。
|
||||||
|
* 服务对象归属统一由 matchmaker_assignments 建模(D3 决策:不保留组长认领),
|
||||||
|
* 分配入口收敛为 {@code MatchmakerAssignmentController}(POST /operator/matchmaker/assignments),
|
||||||
|
* 服务单状态由分配动作同事务联动(submitted → assigned)。
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/operator/matchmaker")
|
@RequestMapping("/operator/matchmaker")
|
||||||
@@ -21,6 +26,20 @@ import java.util.Map;
|
|||||||
public class MatchmakerOperatorController {
|
public class MatchmakerOperatorController {
|
||||||
|
|
||||||
private final MatchmakerServiceService matchmakerServiceService;
|
private final MatchmakerServiceService matchmakerServiceService;
|
||||||
|
private final com.danyang.match.platform.matchmaker.service.MatchmakerManagementService managementService;
|
||||||
|
|
||||||
|
@GetMapping("/management/services")
|
||||||
|
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||||
|
public ApiResponse<List<Map<String, Object>>> managementServices(@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||||
|
return ApiResponse.ok(managementService.list(principal));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/management/services/{id}")
|
||||||
|
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||||
|
public ApiResponse<Map<String, Object>> managementDetail(@AuthenticationPrincipal OperatorPrincipal principal,
|
||||||
|
@PathVariable String id) {
|
||||||
|
return ApiResponse.ok(managementService.detail(principal, id));
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/dashboard")
|
@GetMapping("/dashboard")
|
||||||
public ApiResponse<Map<String, Object>> getDashboard(
|
public ApiResponse<Map<String, Object>> getDashboard(
|
||||||
@@ -29,42 +48,57 @@ public class MatchmakerOperatorController {
|
|||||||
return ApiResponse.ok(matchmakerServiceService.getDashboard(operatorId));
|
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")
|
@GetMapping("/pending")
|
||||||
|
@PreAuthorize("hasAuthority('matchmaker.assign') or hasAuthority('matchmaker.team.assign')")
|
||||||
public ApiResponse<List<Map<String, Object>>> getPending(
|
public ApiResponse<List<Map<String, Object>>> getPending(
|
||||||
@AuthenticationPrincipal OperatorPrincipal principal) {
|
@AuthenticationPrincipal OperatorPrincipal principal) {
|
||||||
return ApiResponse.ok(matchmakerServiceService.getPendingServices());
|
return ApiResponse.ok(matchmakerServiceService.getPendingServices());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分配服务给红娘(兼容入口)。ZC-MM-002(D4):
|
||||||
|
* 同事务联动「创建 matchmaker_assignments 分配 + 服务单置 assigned」。
|
||||||
|
*/
|
||||||
@PostMapping("/services/{id}/assign")
|
@PostMapping("/services/{id}/assign")
|
||||||
@PreAuthorize("hasAuthority('matchmaker.assign')")
|
@PreAuthorize("hasAuthority('matchmaker.assign')")
|
||||||
public ApiResponse<?> assignService(
|
public ApiResponse<?> assignService(
|
||||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||||
@PathVariable String id,
|
@PathVariable String id,
|
||||||
@RequestBody Map<String, String> body) {
|
@RequestBody Map<String, String> body) {
|
||||||
String operatorId = principal.id();
|
String assignerOperatorId = principal.id();
|
||||||
String assignOperatorId = body.get("operatorId");
|
String targetOperatorId = body.get("operatorId");
|
||||||
return ApiResponse.ok(matchmakerServiceService.assignService(id, assignOperatorId, null));
|
String reason = body.getOrDefault("reason", "红娘服务单分配");
|
||||||
|
return ApiResponse.ok(matchmakerServiceService.assignService(
|
||||||
|
id, assignerOperatorId, targetOperatorId, reason));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/services/{id}/claim")
|
// GET /my-services 已删除(ZC-MM-005 / E4 死端点清理):
|
||||||
@PreAuthorize("hasAuthority('matchmaker.service')")
|
// 原实现把 operatorId 误当 user_id 传给 getMyServices(按 C 端 user_id 查询,恒空),
|
||||||
public ApiResponse<?> claimService(
|
// 且 admin-web / miniapp 零调用。运营端"我的服务对象"替代路径:
|
||||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
// GET /operator/matchmaker/assignments/my(ZC-MM-002 A1 新增)。
|
||||||
@PathVariable String id) {
|
// getMyServices 服务方法保留,供 C 端 GET /matchmaker/services 使用。
|
||||||
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));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Phase 13:红娘名下服务的全部推荐列表(运营端工作台用)。
|
* 红娘名下服务的全部推荐列表(运营端工作台用)。
|
||||||
* 补此前 admin-web 调用 `/matchmaker/recommendations/operator` 404 的契约缺口。
|
* 补此前 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")
|
@GetMapping("/recommendations")
|
||||||
public ApiResponse<List<Map<String, Object>>> getRecommendations(
|
public ApiResponse<List<Map<String, Object>>> getRecommendations(
|
||||||
@@ -72,16 +106,19 @@ public class MatchmakerOperatorController {
|
|||||||
return ApiResponse.ok(matchmakerServiceService.getRecommendationsByOperator(principal.id()));
|
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}")
|
@GetMapping("/services/{id}")
|
||||||
public ApiResponse<Map<String, Object>> getServiceDetail(
|
public ApiResponse<Map<String, Object>> getServiceDetail(
|
||||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||||
@PathVariable String id) {
|
@PathVariable String id) {
|
||||||
// Phase 13 D4:传入调用者身份,Service 层按归属决定返回完整/脱敏详情
|
return ApiResponse.ok(matchmakerServiceService.getServiceDetail(id, principal.id()));
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/services/{id}/recommend")
|
@PostMapping("/services/{id}/recommend")
|
||||||
@@ -114,7 +151,8 @@ public class MatchmakerOperatorController {
|
|||||||
public ApiResponse<?> completeService(
|
public ApiResponse<?> completeService(
|
||||||
@AuthenticationPrincipal OperatorPrincipal principal,
|
@AuthenticationPrincipal OperatorPrincipal principal,
|
||||||
@PathVariable String id) {
|
@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;
|
||||||
|
}
|
||||||
@@ -25,6 +25,10 @@ public class MatchmakerServiceRecord extends BaseEntity {
|
|||||||
private String userId;
|
private String userId;
|
||||||
private String serviceType;
|
private String serviceType;
|
||||||
private String description;
|
private String description;
|
||||||
|
private String targetUserId;
|
||||||
|
private java.time.Instant authorizationAt;
|
||||||
|
private java.time.Instant withdrawnAt;
|
||||||
|
private String withdrawReason;
|
||||||
private String status;
|
private String status;
|
||||||
private String organizationId;
|
private String organizationId;
|
||||||
private String assignedOperatorId;
|
private String assignedOperatorId;
|
||||||
|
|||||||
@@ -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,65 @@
|
|||||||
|
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);
|
||||||
|
|
||||||
|
/** 审批队列:仅返回待审批申请,组织范围由服务层按审批权限过滤。 */
|
||||||
|
@Select("SELECT * FROM matchmaker_contact_authorizations WHERE status = 'pending_approval' " +
|
||||||
|
"AND deleted_at IS NULL ORDER BY created_at ASC")
|
||||||
|
List<MatchmakerContactAuthorization> findPendingApproval();
|
||||||
|
|
||||||
|
/** 用户待同意队列(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);
|
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 " +
|
@Select("SELECT r.* FROM matchmaker_recommendations r " +
|
||||||
"JOIN matchmaker_services s ON s.id = r.service_id " +
|
"JOIN matchmaker_services s ON s.id = r.service_id AND s.deleted_at IS NULL " +
|
||||||
"WHERE s.assigned_operator_id = #{operatorId} 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")
|
"ORDER BY r.created_at DESC")
|
||||||
List<MatchmakerRecommendation> findByOperatorId(@Param("operatorId") String operatorId);
|
List<MatchmakerRecommendation> findByOperatorId(@Param("operatorId") String operatorId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
|||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -12,6 +13,23 @@ import java.util.Optional;
|
|||||||
@Mapper
|
@Mapper
|
||||||
public interface MatchmakerServiceMapper extends BaseMapper<MatchmakerServiceRecord> {
|
public interface MatchmakerServiceMapper extends BaseMapper<MatchmakerServiceRecord> {
|
||||||
|
|
||||||
|
@Select("<script>SELECT s.id AS \"serviceId\", s.status, s.service_type AS \"serviceType\", " +
|
||||||
|
"s.description, s.target_user_id AS \"targetUserId\", s.authorization_at AS \"authorizationAt\", " +
|
||||||
|
"s.created_at AS \"createdAt\", s.assigned_at AS \"assignedAt\", s.completed_at AS \"completedAt\", " +
|
||||||
|
"u.display_number AS \"userDisplayNumber\", o.display_id AS \"operatorDisplayId\", " +
|
||||||
|
"tu.display_number AS \"targetUserDisplayNumber\", " +
|
||||||
|
"(SELECT f.content FROM matchmaker_followups f WHERE f.service_id=s.id AND f.deleted_at IS NULL " +
|
||||||
|
"ORDER BY f.created_at DESC LIMIT 1) AS \"latestFollowupContent\", " +
|
||||||
|
"(SELECT f.created_at FROM matchmaker_followups f WHERE f.service_id=s.id AND f.deleted_at IS NULL " +
|
||||||
|
"ORDER BY f.created_at DESC LIMIT 1) AS \"latestFollowupAt\" " +
|
||||||
|
"FROM matchmaker_services s LEFT JOIN users u ON u.id=s.user_id " +
|
||||||
|
"LEFT JOIN users tu ON tu.id=s.target_user_id " +
|
||||||
|
"LEFT JOIN operators o ON o.id=s.assigned_operator_id AND o.deleted_at IS NULL " +
|
||||||
|
"WHERE s.deleted_at IS NULL <if test='!global'>AND o.id IS NOT NULL " +
|
||||||
|
"AND o.organization_id IS NOT DISTINCT FROM #{organizationId}</if> ORDER BY s.created_at DESC</script>")
|
||||||
|
List<java.util.Map<String, Object>> findManagementServices(@Param("global") boolean global,
|
||||||
|
@Param("organizationId") String organizationId);
|
||||||
|
|
||||||
@Select("SELECT * FROM matchmaker_services WHERE id = #{id} AND deleted_at IS NULL LIMIT 1")
|
@Select("SELECT * FROM matchmaker_services WHERE id = #{id} AND deleted_at IS NULL LIMIT 1")
|
||||||
Optional<MatchmakerServiceRecord> findById(@Param("id") String id);
|
Optional<MatchmakerServiceRecord> findById(@Param("id") String id);
|
||||||
|
|
||||||
@@ -26,35 +44,64 @@ public interface MatchmakerServiceMapper extends BaseMapper<MatchmakerServiceRec
|
|||||||
@Select("SELECT COUNT(*) FROM matchmaker_services WHERE status = 'submitted' AND deleted_at IS NULL")
|
@Select("SELECT COUNT(*) FROM matchmaker_services WHERE status = 'submitted' AND deleted_at IS NULL")
|
||||||
long countSubmitted();
|
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);
|
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}")
|
@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);
|
List<MatchmakerServiceRecord> findByUser(@Param("userId") String userId, @Param("limit") int limit);
|
||||||
|
|
||||||
/** 某红娘名下全部服务(含历史)—— 红娘工作台 */
|
@Select("SELECT COUNT(*) FROM matchmaker_services WHERE user_id=#{userId} AND target_user_id=#{targetUserId} " +
|
||||||
@Select("SELECT * FROM matchmaker_services WHERE assigned_operator_id = #{operatorId} " +
|
"AND service_type='recommendation_assistance' AND status NOT IN ('completed','cancelled') AND deleted_at IS NULL")
|
||||||
"AND deleted_at IS NULL ORDER BY created_at DESC")
|
long countActiveAssistance(@Param("userId") String userId, @Param("targetUserId") String targetUserId);
|
||||||
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")
|
@Update("UPDATE matchmaker_services SET status='cancelled', withdrawn_at=NOW(), withdraw_reason=#{reason}, updated_at=NOW() " +
|
||||||
List<MatchmakerServiceRecord> findAssignedTo(@Param("operatorId") String operatorId);
|
"WHERE id=#{serviceId} AND user_id=#{userId} AND status IN ('submitted','assigned','in_service','waiting_user') AND deleted_at IS NULL")
|
||||||
|
int withdraw(@Param("serviceId") String serviceId, @Param("userId") String userId, @Param("reason") String reason);
|
||||||
|
|
||||||
/**
|
/** 用户确认红娘服务方案:仅允许本人将 waiting_user 恢复为 in_service。 */
|
||||||
* Phase 13:查该红娘名下、且服务对象为该用户的进行中服务(转介授权校验用)。
|
@Update("UPDATE matchmaker_services SET status = 'in_service', updated_at = NOW() " +
|
||||||
* 转介必须挂在真实存在的服务关系上,否则等于任意红娘可代任意用户操作。
|
"WHERE id = #{serviceId} AND user_id = #{userId} AND status = 'waiting_user' AND deleted_at IS NULL")
|
||||||
*/
|
int confirmWaitingForUser(@Param("serviceId") String serviceId, @Param("userId") String userId);
|
||||||
@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):该用户仍处于非终态的红娘服务数。
|
* 注销前检查(P16 收尾 2e):该用户仍处于非终态的红娘服务数。
|
||||||
* 状态口径与 {@link #findActiveByOperatorAndUser} 一致(submitted/assigned/in_service/waiting_user)。
|
* 状态口径(submitted/assigned/in_service/waiting_user)。
|
||||||
* ⚠️ 勿用 {@code Constants.MATCHMAKER_STATUS_PENDING} / {@code IN_PROGRESS} ——
|
* ⚠️ 勿用 {@code Constants.MATCHMAKER_STATUS_PENDING} / {@code IN_PROGRESS} ——
|
||||||
* 这两个常量不在生产 chk_matchmaker_status 白名单(V009),该表永不出现这两个值。
|
* 这两个常量不在生产 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,516 @@
|
|||||||
|
package com.danyang.match.platform.matchmaker.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
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 com.danyang.match.platform.permission.entity.Operator;
|
||||||
|
import com.danyang.match.platform.permission.mapper.OperatorMapper;
|
||||||
|
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.LinkedHashMap;
|
||||||
|
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 : 审批岗分层判定(用户裁决①:组长主审 + 管理员兜底,见
|
||||||
|
* {@link #assertApproverAuthority})pending_approval → pending_consent;
|
||||||
|
* 违规 403(无资源枚举面维持 403)
|
||||||
|
* reject : 审批岗(分层同 approve)拒绝 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";
|
||||||
|
/**
|
||||||
|
* 兜底审批岗权限键(用户裁决① 固定):持有者可审批全部申请且不做组织校验。
|
||||||
|
* 主审岗权限键仍由 approver-authorities 列表首段配置(默认 matchmaker.team.assign)。
|
||||||
|
*/
|
||||||
|
private static final String FALLBACK_APPROVER_AUTHORITY = "matchmaker.assign";
|
||||||
|
|
||||||
|
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;
|
||||||
|
private final OperatorMapper operatorMapper;
|
||||||
|
|
||||||
|
/** afterData JSON 序列化(静态初始化,不参与构造注入,避免测试桩连带改动)。 */
|
||||||
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
// ==================== ① request:红娘发起申请 ====================
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public MatchmakerContactAuthorization request(String operatorId, String userId,
|
||||||
|
String channel, String purpose) {
|
||||||
|
// fail-safe 最先(与 disclose 同口径):机制关闭(配置缺失/显式关闭)→ 404 化拒绝。
|
||||||
|
// ZC-MM-003 裁决落地 T-C:request 原实现漏查 enabled(真实缺口,本轮补齐)。
|
||||||
|
if (!config.isEnabled()) {
|
||||||
|
dataScopeGuard.denyAsNotFound(operatorId, RESOURCE_TYPE, userId,
|
||||||
|
"服务不存在", null, null);
|
||||||
|
}
|
||||||
|
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", jsonOf("channel", channel, "purpose", auth.getPurpose()));
|
||||||
|
return auth;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== ② approve / ③ reject:审批岗(分层) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审批岗分层判定(用户裁决①:组长主审 + 管理员兜底)。
|
||||||
|
*
|
||||||
|
* <p>分层规则:
|
||||||
|
* <ol>
|
||||||
|
* <li>持 {@code matchmaker.assign}(兜底岗,平台管理员)→ 可审批全部申请,
|
||||||
|
* <b>不做组织校验</b>(见 {@link #assertOrgScopeForApprover});</li>
|
||||||
|
* <li>否则持主审岗权限键(approver-authorities 列表首段,默认
|
||||||
|
* {@code matchmaker.team.assign},组长)→ 主审,须通过
|
||||||
|
* {@code assertTeamScope} 组织范围校验(NULL=NULL 平台直属,现状维持);</li>
|
||||||
|
* <li>两者皆无 → 403 deny(不变)。</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* <p>主审岗键仍由配置驱动(列表首段),兜底岗键固定为 {@code matchmaker.assign}
|
||||||
|
* —— 配置只能收紧/调整主审岗,不能扩大兜底岗权限面。
|
||||||
|
*/
|
||||||
|
private void assertApproverAuthority(String approverOperatorId, String authId,
|
||||||
|
Set<String> principalPermissions) {
|
||||||
|
boolean authorized = isFallbackApprover(principalPermissions)
|
||||||
|
|| isPrimaryApprover(principalPermissions);
|
||||||
|
if (!authorized) {
|
||||||
|
// 非审批岗 → 403(approve 无资源枚举面,维持 403;边界登记 T06 OQ-MATCHMAKER-009)
|
||||||
|
dataScopeGuard.deny(approverOperatorId, RESOURCE_TYPE, authId,
|
||||||
|
"非审批岗,禁止审批受控联系授权");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 兜底岗判定:持固定键 matchmaker.assign(平台管理员)→ 全量审批、无组织校验。 */
|
||||||
|
private boolean isFallbackApprover(Set<String> principalPermissions) {
|
||||||
|
return principalPermissions != null && principalPermissions.contains(FALLBACK_APPROVER_AUTHORITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 主审岗判定:principal 权限 ∈ approver-authorities 任一(默认首段 team.assign 组长)。 */
|
||||||
|
private boolean isPrimaryApprover(Set<String> principalPermissions) {
|
||||||
|
Set<String> approverAuthorities = Arrays.stream(config.getApproverAuthorities().split(","))
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(s -> !s.isEmpty())
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
return principalPermissions != null
|
||||||
|
&& principalPermissions.stream().anyMatch(approverAuthorities::contains);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分层组织范围校验(用户裁决①):兜底岗(持 matchmaker.assign)跳过组织校验;
|
||||||
|
* 主审岗(组长)固定走 {@code assertTeamScope}(hasGlobalAssign=false ——
|
||||||
|
* 是否兜底由本层判定,不再向底层传组织豁免,防止权限面双通道扩大)。
|
||||||
|
*/
|
||||||
|
private void assertOrgScopeForApprover(String approverOperatorId, String authId,
|
||||||
|
Set<String> principalPermissions, String targetOperatorId) {
|
||||||
|
if (isFallbackApprover(principalPermissions)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
matchmakerAssignmentService.assertTeamScope(approverOperatorId, false,
|
||||||
|
targetOperatorId, 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() + ")不允许审批");
|
||||||
|
}
|
||||||
|
// 分层组织范围校验(用户裁决①):管理员兜底全量 / 组长主审限同组织(NULL=NULL 平台直属)
|
||||||
|
assertOrgScopeForApprover(approverOperatorId, authId, principalPermissions,
|
||||||
|
auth.getOperatorId());
|
||||||
|
|
||||||
|
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",
|
||||||
|
jsonOf("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() + ")不允许拒绝");
|
||||||
|
}
|
||||||
|
// 分层组织范围校验(用户裁决①,与 approve 同口径)
|
||||||
|
assertOrgScopeForApprover(approverOperatorId, authId, principalPermissions,
|
||||||
|
auth.getOperatorId());
|
||||||
|
|
||||||
|
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",
|
||||||
|
jsonOf("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);
|
||||||
|
saveUserAudit(userId, Constants.CONTACT_AUDIT_ACTION_CONSENT, authId,
|
||||||
|
"matchmaker.contact.consent", jsonOf("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);
|
||||||
|
saveUserAudit(userId, Constants.CONTACT_AUDIT_ACTION_DECLINE, authId,
|
||||||
|
"matchmaker.contact.decline", jsonOf("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",
|
||||||
|
jsonOf("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", jsonOf("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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 审批队列:平台管理员全量可见,组长仅可见本组织申请。 */
|
||||||
|
public Map<String, Object> pendingApprovals(String approverOperatorId, Set<String> permissions) {
|
||||||
|
assertApproverAuthority(approverOperatorId, "pending", permissions);
|
||||||
|
List<MatchmakerContactAuthorization> rows = authorizationMapper.findPendingApproval();
|
||||||
|
if (!isFallbackApprover(permissions)) {
|
||||||
|
String approverOrg = operatorMapper.findById(approverOperatorId)
|
||||||
|
.map(Operator::getOrganizationId).orElse(null);
|
||||||
|
rows = rows.stream().filter(row -> operatorMapper.findById(row.getOperatorId())
|
||||||
|
.map(Operator::getOrganizationId)
|
||||||
|
.map(org -> java.util.Objects.equals(org, approverOrg)).orElse(false))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("list", rows.stream().map(this::toView).collect(Collectors.toList()));
|
||||||
|
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)) {
|
||||||
|
// V057:C 端主体走 denyUser(subject_user_id 维度)——userId 写 operator_id 维度
|
||||||
|
// 必撞 audit_logs_operator_id_fkey(→operators),H2 无 FK 假绿、生产零审计
|
||||||
|
dataScopeGuard.denyUser(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V057 / 运行时实测修复:C 端用户主体的审计写入(consent/decline)。
|
||||||
|
* subject_user_id 维度(operator_id=null)——userId 写 operator_id 必撞
|
||||||
|
* audit_logs_operator_id_fkey(→operators):H2 无 FK 假绿,生产 FK violation 500。
|
||||||
|
* service_assignment_id 不适用(用户动作不经分配),purpose_code 照旧落。
|
||||||
|
*/
|
||||||
|
private void saveUserAudit(String userId, String action, String authId,
|
||||||
|
String purposeCode, String afterData) {
|
||||||
|
AuditLog auditLog = new AuditLog();
|
||||||
|
auditLog.setSubjectUserId(userId);
|
||||||
|
auditLog.setAction(action);
|
||||||
|
auditLog.setResourceType(RESOURCE_TYPE);
|
||||||
|
auditLog.setResourceId(authId);
|
||||||
|
auditLog.setAfterData(afterData);
|
||||||
|
auditLog.setPurposeCode(purposeCode);
|
||||||
|
auditLog.setRequestTraceId(MDC.get("requestId"));
|
||||||
|
auditLogMapper.insert(auditLog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* afterData 必须是合法 JSON(PG audit_logs.after_data 为 jsonb 严格解析;
|
||||||
|
* H2 测试库 CLOB 不校验——裸 key=value 拼接在测试侧假绿、生产侧 500)。
|
||||||
|
* kv 成对传入,Jackson 负责用户输入(purpose/reason)的 JSON 转义,防 JSON 注入。
|
||||||
|
*/
|
||||||
|
private String jsonOf(Object... kvPairs) {
|
||||||
|
if (kvPairs.length % 2 != 0) {
|
||||||
|
throw new IllegalStateException("jsonOf requires key-value pairs");
|
||||||
|
}
|
||||||
|
Map<String, Object> data = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < kvPairs.length; i += 2) {
|
||||||
|
data.put(String.valueOf(kvPairs[i]), kvPairs[i + 1]);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return OBJECT_MAPPER.writeValueAsString(data);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new IllegalStateException("audit afterData JSON serialization failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
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 com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
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 static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
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 -> {
|
||||||
|
// 历史服务已完成/取消时,旧分配只是残留状态,不应阻塞用户再次申请服务。
|
||||||
|
// 仍在进行中的服务继续按唯一主责约束返回 409。
|
||||||
|
MatchmakerServiceRecord linked = existing.getServiceId() == null
|
||||||
|
? null : serviceMapper.selectById(existing.getServiceId());
|
||||||
|
if (linked != null && (Constants.MATCHMAKER_STATUS_COMPLETED.equals(linked.getStatus())
|
||||||
|
|| Constants.MATCHMAKER_STATUS_CANCELLED.equals(linked.getStatus()))) {
|
||||||
|
existing.setStatus(Constants.ASSIGNMENT_STATUS_ENDED);
|
||||||
|
existing.setEndedAt(Instant.now());
|
||||||
|
existing.setEndReason("关联服务已完成或取消,自动结束旧分配");
|
||||||
|
assignmentMapper.updateById(existing);
|
||||||
|
saveAudit(assignerOperatorId, Constants.AUDIT_ACTION_ASSIGNMENT_END, existing.getId(),
|
||||||
|
auditSummary(existing.getMatchmakerOperatorId(), existing.getAssignmentScope(), existing.getEndReason()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
Map<String, String> summary = Map.of(
|
||||||
|
"matchmakerOperatorId", matchmakerOperatorId == null ? "" : matchmakerOperatorId,
|
||||||
|
"scope", scope == null ? "" : scope,
|
||||||
|
"reason", reason == null ? "" : reason);
|
||||||
|
try {
|
||||||
|
return OBJECT_MAPPER.writeValueAsString(summary);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new IllegalStateException("audit afterData JSON serialization failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
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.mapper.MatchmakerFollowupMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||||
|
import com.danyang.match.platform.permission.mapper.OperatorMapper;
|
||||||
|
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||||
|
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 管理岗位只读服务进展;不复用普通红娘的本人分配权限,也不授予代操作权限。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MatchmakerManagementService {
|
||||||
|
private final MatchmakerServiceMapper serviceMapper;
|
||||||
|
private final MatchmakerFollowupMapper followupMapper;
|
||||||
|
private final OperatorMapper operatorMapper;
|
||||||
|
private final AuditLogMapper auditLogMapper;
|
||||||
|
|
||||||
|
public List<Map<String, Object>> list(OperatorPrincipal principal) {
|
||||||
|
boolean global = principal.hasPermission("matchmaker.assign");
|
||||||
|
if (!global && !principal.hasPermission("matchmaker.team.assign")) {
|
||||||
|
throw new AccessDeniedException("无红娘服务管理权限");
|
||||||
|
}
|
||||||
|
String org = global ? null : operatorMapper.findById(principal.id())
|
||||||
|
.orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "操作者不存在"))
|
||||||
|
.getOrganizationId();
|
||||||
|
return serviceMapper.findManagementServices(global, org);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> detail(OperatorPrincipal principal, String serviceId) {
|
||||||
|
Map<String, Object> summary = list(principal).stream()
|
||||||
|
.filter(row -> serviceId.equals(String.valueOf(row.get("serviceId"))))
|
||||||
|
.findFirst().orElseThrow(() -> new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在"));
|
||||||
|
var detail = new HashMap<>(summary);
|
||||||
|
detail.put("followups", followupMapper.findByServiceId(serviceId));
|
||||||
|
AuditLog audit = new AuditLog();
|
||||||
|
audit.setOperatorId(principal.id());
|
||||||
|
audit.setAction("MATCHMAKER_MANAGEMENT_VIEW");
|
||||||
|
audit.setResourceType("matchmaker_service");
|
||||||
|
audit.setResourceId(serviceId);
|
||||||
|
audit.setPurposeCode("matchmaker.management.view");
|
||||||
|
auditLogMapper.insert(audit);
|
||||||
|
return detail;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,6 +48,8 @@ public class MatchmakerService {
|
|||||||
private final RelationService relationService;
|
private final RelationService relationService;
|
||||||
private final MatchMapper matchMapper;
|
private final MatchMapper matchMapper;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
|
private final com.danyang.match.platform.matchmaker.mapper.MatchmakerFollowupMapper followupMapper;
|
||||||
|
private final com.danyang.match.platform.shared.id.PublicIdMapper publicIdMapper;
|
||||||
|
|
||||||
// ==================== 用户端:提交红娘服务请求 ====================
|
// ==================== 用户端:提交红娘服务请求 ====================
|
||||||
|
|
||||||
@@ -62,22 +64,57 @@ public class MatchmakerService {
|
|||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public MatchmakerServiceRecord submitServiceRequest(String userId, String serviceType, String description) {
|
public MatchmakerServiceRecord submitServiceRequest(String userId, String serviceType, String description) {
|
||||||
|
return submitServiceRequest(userId, serviceType, description, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public MatchmakerServiceRecord submitServiceRequest(String userId, String serviceType, String description,
|
||||||
|
String targetUserId, Boolean authorizationAccepted) {
|
||||||
|
boolean assistance = "recommendation_assistance".equals(serviceType);
|
||||||
|
if (assistance) {
|
||||||
|
if (targetUserId == null || targetUserId.isBlank()) throw new IllegalArgumentException("请选择需要协助的对象");
|
||||||
|
if (!Boolean.TRUE.equals(authorizationAccepted)) throw new IllegalArgumentException("请先确认授权红娘查看必要公开资料");
|
||||||
|
if (userId.equals(targetUserId)) throw new IllegalArgumentException("不能申请协助了解自己");
|
||||||
|
if (!relationService.canInteract(userId, targetUserId)) throw new IllegalStateException("该对象当前不可申请红娘协助");
|
||||||
|
if (serviceMapper.countActiveAssistance(userId, targetUserId) > 0) throw new IllegalStateException("已提交过该对象的红娘协助申请");
|
||||||
|
}
|
||||||
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
||||||
svc.setId(UUID.randomUUID().toString());
|
svc.setId(UUID.randomUUID().toString());
|
||||||
svc.setUserId(userId);
|
svc.setUserId(userId);
|
||||||
svc.setServiceType(serviceType);
|
svc.setServiceType(serviceType);
|
||||||
svc.setDescription(description);
|
svc.setDescription(description);
|
||||||
|
svc.setTargetUserId(targetUserId);
|
||||||
|
if (assistance) svc.setAuthorizationAt(Instant.now());
|
||||||
svc.setStatus("submitted");
|
svc.setStatus("submitted");
|
||||||
serviceMapper.insert(svc);
|
serviceMapper.insert(svc);
|
||||||
log.info("Matchmaker service submitted: userId={}, type={}", userId, serviceType);
|
log.info("Matchmaker service submitted: userId={}, type={}", userId, serviceType);
|
||||||
return svc;
|
return svc;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void withdrawService(String serviceId, String userId, String reason) {
|
||||||
|
if (serviceMapper.withdraw(serviceId, userId, reason) != 1) throw new IllegalStateException("服务不存在或当前状态不可撤回");
|
||||||
|
}
|
||||||
|
|
||||||
/** 查询我的红娘服务历史 */
|
/** 查询我的红娘服务历史 */
|
||||||
public List<MatchmakerServiceRecord> myServices(String userId, int limit) {
|
public List<MatchmakerServiceRecord> myServices(String userId, int limit) {
|
||||||
return serviceMapper.findByUser(userId, Math.min(limit, 50));
|
return serviceMapper.findByUser(userId, Math.min(limit, 50));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 用户本人确认红娘方案,服务恢复为进行中。 */
|
||||||
|
@Transactional
|
||||||
|
public MatchmakerServiceRecord confirmService(String serviceId, String userId) {
|
||||||
|
if (serviceId == null || userId == null) {
|
||||||
|
throw new IllegalArgumentException("服务和用户不能为空");
|
||||||
|
}
|
||||||
|
int updated = serviceMapper.confirmWaitingForUser(serviceId, userId);
|
||||||
|
if (updated != 1) {
|
||||||
|
throw new IllegalStateException("服务不存在或当前状态无需确认");
|
||||||
|
}
|
||||||
|
return serviceMapper.findById(serviceId)
|
||||||
|
.orElseThrow(() -> new IllegalStateException("服务不存在"));
|
||||||
|
}
|
||||||
|
|
||||||
// ==================== 操作人端:分配 + 推荐 + 转介 ====================
|
// ==================== 操作人端:分配 + 推荐 + 转介 ====================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -157,9 +194,7 @@ public class MatchmakerService {
|
|||||||
throw new IllegalStateException("您不是此服务的负责人");
|
throw new IllegalStateException("您不是此服务的负责人");
|
||||||
}
|
}
|
||||||
|
|
||||||
// referral 记录写进 MatchmakerServiceRecord.description 的扩展 JSON
|
// 转介建议复用跟进记录持久化,独立 ZF 编号不替用户创建申请。
|
||||||
// + 单独一条 Followup 记录(DB V009 已有 matchmaker_followups)
|
|
||||||
// 这里用 Map 简单记录,不引入新实体
|
|
||||||
ReferralRecord record = new ReferralRecord(
|
ReferralRecord record = new ReferralRecord(
|
||||||
UUID.randomUUID().toString(),
|
UUID.randomUUID().toString(),
|
||||||
serviceId,
|
serviceId,
|
||||||
@@ -171,11 +206,22 @@ public class MatchmakerService {
|
|||||||
Instant.now()
|
Instant.now()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
var followup = new com.danyang.match.platform.matchmaker.entity.MatchmakerFollowup();
|
||||||
|
followup.setId(record.id());
|
||||||
|
followup.setServiceId(serviceId);
|
||||||
|
followup.setOperatorId(operatorId);
|
||||||
|
followup.setFollowupType("system");
|
||||||
|
followup.setContent("转介建议:" + referralLabel(referralType) + (note == null ? "" : "," + note));
|
||||||
|
followup.setCreatedAt(record.createdAt());
|
||||||
|
followupMapper.insert(followup);
|
||||||
|
String referralNumber = publicIdMapper.nextReferral(record.createdAt());
|
||||||
|
if (publicIdMapper.saveReferral(record.id(), referralNumber) != 1) throw new IllegalStateException("转介编号写入失败");
|
||||||
|
|
||||||
// 通知用户被转介了
|
// 通知用户被转介了
|
||||||
notificationService.send(userId, "matchmaker_referral",
|
notificationService.send(userId, "matchmaker_referral",
|
||||||
"红娘为你转介了一个" + referralLabel(referralType),
|
"红娘为你转介了一个" + referralLabel(referralType),
|
||||||
"公益红娘为你转介了" + referralLabel(referralType) +
|
"公益红娘为你转介了" + referralLabel(referralType) +
|
||||||
"(" + (referralTarget != null ? referralTarget : "") + "),你可以在" +
|
"(转介编号:" + referralNumber + "),你可以在" +
|
||||||
serviceLabel(referralType) + "页面申请。",
|
serviceLabel(referralType) + "页面申请。",
|
||||||
"matchmaker_service", serviceId);
|
"matchmaker_service", serviceId);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package com.danyang.match.platform.matchmaker.service;
|
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.AuditLog;
|
||||||
|
import com.danyang.match.platform.audit.entity.SensitiveAccessLog;
|
||||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
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.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.MatchmakerFollowup;
|
||||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerRecommendation;
|
import com.danyang.match.platform.matchmaker.entity.MatchmakerRecommendation;
|
||||||
import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
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.MatchmakerRecommendationMapper;
|
||||||
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||||
import com.danyang.match.platform.notification.service.NotificationService;
|
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.entity.UserProfile;
|
||||||
|
import com.danyang.match.platform.profile.mapper.UserPrivacySettingsMapper;
|
||||||
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||||
import com.danyang.match.platform.shared.constant.Constants;
|
import com.danyang.match.platform.shared.constant.Constants;
|
||||||
import lombok.RequiredArgsConstructor;
|
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.enums.ApiResponseCode;
|
||||||
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
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
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class MatchmakerServiceService {
|
public class MatchmakerServiceService {
|
||||||
@@ -37,8 +66,12 @@ public class MatchmakerServiceService {
|
|||||||
private final MatchmakerRecommendationMapper recommendationMapper;
|
private final MatchmakerRecommendationMapper recommendationMapper;
|
||||||
private final MatchmakerFollowupMapper followupMapper;
|
private final MatchmakerFollowupMapper followupMapper;
|
||||||
private final UserProfileMapper userProfileMapper;
|
private final UserProfileMapper userProfileMapper;
|
||||||
|
private final UserPrivacySettingsMapper userPrivacySettingsMapper;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
private final AuditLogMapper auditLogMapper;
|
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
|
@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);
|
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||||
if (!Constants.MATCHMAKER_STATUS_SUBMITTED.equals(service.getStatus())) {
|
if (!Constants.MATCHMAKER_STATUS_SUBMITTED.equals(service.getStatus())) {
|
||||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不允许分配");
|
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不允许分配");
|
||||||
}
|
}
|
||||||
|
if (targetOperatorId == null || targetOperatorId.isBlank()) {
|
||||||
service.setAssignedOperatorId(operatorId);
|
throw new BusinessException(ApiResponseCode.VALIDATION_ERROR, "目标红娘必填");
|
||||||
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, "当前状态不允许接单");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
service.setStatus(Constants.MATCHMAKER_STATUS_IN_SERVICE);
|
// ① 创建分配(matchmaker.assign 入口为平台授权,hasGlobalAssign=true)
|
||||||
serviceMapper.updateById(service);
|
MatchmakerAssignment createdAssignment = matchmakerAssignmentService.create(assignerOperatorId, true,
|
||||||
|
service.getUserId(), targetOperatorId, serviceId, reason, null);
|
||||||
|
|
||||||
log.info("红娘接单: operatorId={}, serviceId={}", operatorId, serviceId);
|
// ② 服务单联动(create 内已对 submitted 服务单置 assigned;此处再校验一次确保联动生效)
|
||||||
return service;
|
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 归属校验。
|
* Phase 13 复验修复(D3):补归属校验。
|
||||||
* 此前只校验 service 存在,任何持 matchmaker.service 权限的 operator
|
* ZC-MM-002(D4):归属判定切换到 {@link ServiceAssignmentPolicy}(matchmaker_assignments
|
||||||
* 都能对**任意** serviceId 创建推荐(越权)。与
|
* 是服务对象归属的唯一事实源,无任何 assigned_operator_id 回退);拒绝统一走
|
||||||
* MatchmakerService.createRecommendation:118-121 的校验保持同一口径。
|
* DataScopeGuard(DATA_SCOPE_DENIED 审计 + 403),不再抛裸 IllegalStateException。
|
||||||
*
|
*
|
||||||
* AGENTS.md #5:红娘只创建 pending_view 推荐记录,不替用户 Like。
|
* AGENTS.md #5:红娘只创建 pending_view 推荐记录,不替用户 Like。
|
||||||
*/
|
*/
|
||||||
@@ -145,10 +181,8 @@ public class MatchmakerServiceService {
|
|||||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||||
|
|
||||||
// Phase 13 D3:归属校验 —— 只有该服务的负责人才能推荐
|
// D4:归属校验 —— 只有该服务对象的负责人(分配持有人)才能推荐
|
||||||
if (!operatorId.equals(service.getAssignedOperatorId())) {
|
MatchmakerAssignment assignment = assertServiceAccess(operatorId, service);
|
||||||
throw new IllegalStateException("您不是此服务的负责人");
|
|
||||||
}
|
|
||||||
// 不能推荐给自己(服务申请人)
|
// 不能推荐给自己(服务申请人)
|
||||||
if (service.getUserId() != null && service.getUserId().equals(targetUserId)) {
|
if (service.getUserId() != null && service.getUserId().equals(targetUserId)) {
|
||||||
throw new IllegalArgumentException("不能推荐用户给自己");
|
throw new IllegalArgumentException("不能推荐用户给自己");
|
||||||
@@ -171,7 +205,9 @@ public class MatchmakerServiceService {
|
|||||||
"matchmaker_recommendation", rec.getId().toString());
|
"matchmaker_recommendation", rec.getId().toString());
|
||||||
|
|
||||||
log.info("红娘推荐: serviceId={}, operatorId={}, targetUserId={}", serviceId, operatorId, targetUserId);
|
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<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("recommendationId", rec.getId());
|
result.put("recommendationId", rec.getId());
|
||||||
@@ -182,11 +218,18 @@ public class MatchmakerServiceService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 红娘添加跟进记录
|
* 红娘添加跟进记录
|
||||||
|
*
|
||||||
|
* ZC-MM-002(D4):补归属校验(此前无任何校验,任何持 matchmaker.service 权限的
|
||||||
|
* operator 可对任意 serviceId 写跟进 → 越权写)。判定口径同 recommendPartner。
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public MatchmakerFollowup addFollowup(String serviceId, String operatorId,
|
public MatchmakerFollowup addFollowup(String serviceId, String operatorId,
|
||||||
String followupType, String content,
|
String followupType, String content,
|
||||||
String nextFollowupAt) {
|
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();
|
MatchmakerFollowup followup = new MatchmakerFollowup();
|
||||||
followup.setServiceId(serviceId);
|
followup.setServiceId(serviceId);
|
||||||
followup.setOperatorId(operatorId);
|
followup.setOperatorId(operatorId);
|
||||||
@@ -198,17 +241,23 @@ public class MatchmakerServiceService {
|
|||||||
followupMapper.insert(followup);
|
followupMapper.insert(followup);
|
||||||
|
|
||||||
log.info("红娘跟进: serviceId={}, operatorId={}, type={}", serviceId, operatorId, followupType);
|
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;
|
return followup;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 完成服务
|
* 完成服务
|
||||||
|
*
|
||||||
|
* ZC-MM-002(D4):补归属校验(判定口径同 recommendPartner);
|
||||||
|
* operatorId 由 Controller 传入 principal,不信任请求参数。
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public MatchmakerServiceRecord completeService(String serviceId) {
|
public MatchmakerServiceRecord completeService(String serviceId, String operatorId) {
|
||||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
||||||
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
if (service == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "服务不存在");
|
||||||
|
MatchmakerAssignment completeAssignment = assertServiceAccess(operatorId, service);
|
||||||
if (!Constants.MATCHMAKER_STATUS_IN_SERVICE.equals(service.getStatus()) &&
|
if (!Constants.MATCHMAKER_STATUS_IN_SERVICE.equals(service.getStatus()) &&
|
||||||
!Constants.MATCHMAKER_STATUS_WAITING_USER.equals(service.getStatus())) {
|
!Constants.MATCHMAKER_STATUS_WAITING_USER.equals(service.getStatus())) {
|
||||||
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不能完成");
|
throw new BusinessException(ApiResponseCode.CONFLICT, "当前状态不能完成");
|
||||||
@@ -219,7 +268,9 @@ public class MatchmakerServiceService {
|
|||||||
serviceMapper.updateById(service);
|
serviceMapper.updateById(service);
|
||||||
|
|
||||||
log.info("红娘服务完成: serviceId={}", serviceId);
|
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;
|
return service;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +308,24 @@ public class MatchmakerServiceService {
|
|||||||
.collect(java.util.stream.Collectors.toList());
|
.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) {
|
public Map<String, Object> getDashboard(String operatorId) {
|
||||||
long pendingCount = serviceMapper.countSubmitted();
|
long pendingCount = serviceMapper.countSubmitted();
|
||||||
long inProgressCount = serviceMapper.countInProgressByOperator(operatorId);
|
long inProgressCount = serviceMapper.countInProgressByOperator(operatorId);
|
||||||
@@ -264,57 +333,69 @@ public class MatchmakerServiceService {
|
|||||||
Map<String, Object> dashboard = new HashMap<>();
|
Map<String, Object> dashboard = new HashMap<>();
|
||||||
dashboard.put("pendingCount", pendingCount);
|
dashboard.put("pendingCount", pendingCount);
|
||||||
dashboard.put("inProgressCount", inProgressCount);
|
dashboard.put("inProgressCount", inProgressCount);
|
||||||
long todayCount = serviceMapper.selectCount(
|
// 本人口径:今天新流转到该红娘名下(按 assigned_at)的服务数
|
||||||
new LambdaQueryWrapper<MatchmakerServiceRecord>()
|
long todayCount = serviceMapper.countTodayByOperator(operatorId);
|
||||||
.eq(MatchmakerServiceRecord::getStatus, "submitted"));
|
|
||||||
dashboard.put("todayCount", todayCount);
|
dashboard.put("todayCount", todayCount);
|
||||||
long completedCount = serviceMapper.selectCount(
|
// 本人口径:该红娘名下已完成的服务数
|
||||||
new LambdaQueryWrapper<MatchmakerServiceRecord>()
|
long completedCount = serviceMapper.countCompletedByOperator(operatorId);
|
||||||
.eq(MatchmakerServiceRecord::getStatus, "completed"));
|
|
||||||
dashboard.put("completedCount", completedCount);
|
dashboard.put("completedCount", completedCount);
|
||||||
return dashboard;
|
return dashboard;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取我的服务列表(红娘工作台)
|
* 获取服务详情(ZC-MM-005 / E1+E2 重构)。
|
||||||
*/
|
|
||||||
public List<MatchmakerServiceRecord> getOperatorServices(String operatorId) {
|
|
||||||
return serviceMapper.findByOperatorId(operatorId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取服务详情
|
|
||||||
*
|
*
|
||||||
* Phase 13 复验修复(D4):改为按调用者授权范围返回。
|
* <p>此前(002 双轨)语义:负责人 → 完整详情;其他 operator → 脱敏详情(含 viewerIsOwner
|
||||||
* 此前无任何归属校验,任何持 matchmaker.view 的 operator 都能读取
|
* 双态)。该设计有两个问题:① assigned_operator_id 回退分支在分配 revoke/end 后仍放行
|
||||||
* **任意** serviceId 的详情,其中包含该用户的完整资料
|
* (服务单残留该列);② 脱敏详情响应可被用于按 serviceId 枚举探测资源存在性。
|
||||||
* (displayName/gender/age/regionName/education/occupation/maritalStatus)→ 越权读。
|
|
||||||
*
|
*
|
||||||
* 现语义:
|
* <p>现语义(判定器唯一事实源,无回退):
|
||||||
* - 服务负责人(assigned_operator_id)→ 返回完整详情(含 userProfile + followups)
|
* <ul>
|
||||||
* - 其他 operator(如仅需了解队列的中台人员)→ 返回脱敏详情
|
* <li>查无此 serviceId → 抛 BusinessException(NOT_FOUND, "服务不存在");</li>
|
||||||
* (不含 userProfile;followups 正文也不返回,仅给条数)
|
* <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
|
* @param requesterId 调用者 operator ID
|
||||||
*/
|
*/
|
||||||
public Map<String, Object> getServiceDetail(String serviceId, String requesterId) {
|
public Map<String, Object> getServiceDetail(String serviceId, String requesterId) {
|
||||||
MatchmakerServiceRecord service = serviceMapper.selectById(serviceId);
|
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<>();
|
Map<String, Object> detail = new HashMap<>();
|
||||||
detail.put("serviceId", service.getId());
|
detail.put("serviceId", service.getId());
|
||||||
detail.put("serviceType", service.getServiceType());
|
detail.put("serviceType", service.getServiceType());
|
||||||
detail.put("status", service.getStatus());
|
detail.put("status", service.getStatus());
|
||||||
detail.put("assignedOperatorId", service.getAssignedOperatorId());
|
|
||||||
detail.put("createdAt", service.getCreatedAt());
|
detail.put("createdAt", service.getCreatedAt());
|
||||||
detail.put("assignedAt", service.getAssignedAt());
|
detail.put("assignedAt", service.getAssignedAt());
|
||||||
detail.put("completedAt", service.getCompletedAt());
|
detail.put("completedAt", service.getCompletedAt());
|
||||||
detail.put("viewerIsOwner", isOwner);
|
|
||||||
|
|
||||||
// 加载推荐列表(推荐是服务进展的必要摘要,两者都可见)
|
// 推荐列表(服务进展摘要)
|
||||||
List<MatchmakerRecommendation> recs = recommendationMapper.findByService(serviceId);
|
List<MatchmakerRecommendation> recs = recommendationMapper.findByService(serviceId);
|
||||||
detail.put("recommendations", recs.stream().map(r -> {
|
detail.put("recommendations", recs.stream().map(r -> {
|
||||||
Map<String, Object> map = new HashMap<>();
|
Map<String, Object> map = new HashMap<>();
|
||||||
@@ -326,35 +407,78 @@ public class MatchmakerServiceService {
|
|||||||
return map;
|
return map;
|
||||||
}).collect(Collectors.toList()));
|
}).collect(Collectors.toList()));
|
||||||
|
|
||||||
if (isOwner) {
|
// 仅持有人可见:申请人 userId / 诉求描述 / 白名单用户资料 / 跟进正文
|
||||||
// 仅服务负责人可见:申请人 userId / 诉求描述 / 用户资料 / 跟进正文
|
detail.put("userId", service.getUserId());
|
||||||
detail.put("userId", service.getUserId());
|
detail.put("description", service.getDescription());
|
||||||
detail.put("description", service.getDescription());
|
UserPrivacySettings privacy = userPrivacySettingsMapper.findByUserId(service.getUserId())
|
||||||
userProfileMapper.findByUserId(service.getUserId()).ifPresent(profile -> {
|
.orElse(null);
|
||||||
Map<String, Object> userProfile = new HashMap<>();
|
userProfileMapper.findByUserId(service.getUserId()).ifPresent(profile ->
|
||||||
userProfile.put("displayName", profile.getDisplayName());
|
detail.put("userProfile", assembleMatchmakerUserProfile(profile, privacy)));
|
||||||
userProfile.put("gender", profile.getGender());
|
detail.put("followups", followupMapper.findByServiceId(serviceId));
|
||||||
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());
|
|
||||||
}
|
|
||||||
|
|
||||||
return detail;
|
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) {
|
private int calculateAge(java.time.LocalDate birthDate) {
|
||||||
if (birthDate == null) return 0;
|
if (birthDate == null) return 0;
|
||||||
return java.time.Period.between(birthDate, java.time.LocalDate.now()).getYears();
|
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,
|
private void saveAuditLog(String operatorId, String action, String resourceType,
|
||||||
String resourceId, String beforeData, String afterData) {
|
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 auditLog = new AuditLog();
|
||||||
auditLog.setOperatorId(operatorId);
|
auditLog.setOperatorId(operatorId);
|
||||||
auditLog.setAction(action);
|
auditLog.setAction(action);
|
||||||
auditLog.setResourceType(resourceType);
|
auditLog.setResourceType(resourceType);
|
||||||
auditLog.setResourceId(resourceId);
|
auditLog.setResourceId(resourceId);
|
||||||
|
auditLog.setBeforeData(beforeData);
|
||||||
|
auditLog.setAfterData(afterData);
|
||||||
|
auditLog.setPurposeCode(purposeCode);
|
||||||
|
auditLog.setServiceAssignmentId(serviceAssignmentId);
|
||||||
auditLogMapper.insert(auditLog);
|
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));
|
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)。
|
* 删除本人照片(REST §32)。
|
||||||
* DELETE /api/v1/me/photos/{photoId}
|
* DELETE /api/v1/me/photos/{photoId}
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ public class OperatorManagementService {
|
|||||||
List<Map<String, Object>> items = operators.stream().map(op -> {
|
List<Map<String, Object>> items = operators.stream().map(op -> {
|
||||||
Map<String, Object> m = new HashMap<>();
|
Map<String, Object> m = new HashMap<>();
|
||||||
m.put("id", op.getId());
|
m.put("id", op.getId());
|
||||||
|
m.put("displayId", op.getDisplayId());
|
||||||
m.put("name", op.getName());
|
m.put("name", op.getName());
|
||||||
m.put("username", op.getUsername());
|
m.put("username", op.getUsername());
|
||||||
m.put("status", op.getStatus());
|
m.put("status", op.getStatus());
|
||||||
@@ -62,6 +63,7 @@ public class OperatorManagementService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public Operator createOperator(String name, String username, String password, String organizationId) {
|
public Operator createOperator(String name, String username, String password, String organizationId) {
|
||||||
Operator operator = new Operator();
|
Operator operator = new Operator();
|
||||||
|
operator.setId(UUID.randomUUID().toString());
|
||||||
operator.setName(name);
|
operator.setName(name);
|
||||||
operator.setUsername(username);
|
operator.setUsername(username);
|
||||||
operator.setPasswordHash(passwordEncoder.encode(password));
|
operator.setPasswordHash(passwordEncoder.encode(password));
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import com.danyang.match.platform.shared.enums.ApiResponseCode;
|
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.BusinessException;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Operator 管理服务
|
* Operator 管理服务
|
||||||
@@ -53,6 +54,7 @@ public class OperatorService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Operator operator = new Operator();
|
Operator operator = new Operator();
|
||||||
|
operator.setId(java.util.UUID.randomUUID().toString());
|
||||||
operator.setName(name);
|
operator.setName(name);
|
||||||
operator.setUsername(username);
|
operator.setUsername(username);
|
||||||
operator.setPasswordHash(passwordEncoder.encode(password));
|
operator.setPasswordHash(passwordEncoder.encode(password));
|
||||||
@@ -85,7 +87,7 @@ public class OperatorService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public void disableOperator(String operatorId) {
|
public void disableOperator(String operatorId) {
|
||||||
Operator operator = operatorMapper.findById(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.setStatus(Constants.ACCOUNT_STATUS_SUSPENDED);
|
||||||
operator.setUpdatedAt(Instant.now());
|
operator.setUpdatedAt(Instant.now());
|
||||||
@@ -101,7 +103,7 @@ public class OperatorService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public void enableOperator(String operatorId) {
|
public void enableOperator(String operatorId) {
|
||||||
Operator operator = operatorMapper.findById(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.setStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||||
operator.setUpdatedAt(Instant.now());
|
operator.setUpdatedAt(Instant.now());
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ public class Operator extends BaseEntity {
|
|||||||
private String phoneEnc;
|
private String phoneEnc;
|
||||||
private String phoneHash;
|
private String phoneHash;
|
||||||
private String username;
|
private String username;
|
||||||
|
/** 对外展示编号,内部 id 仍为 UUID。 */
|
||||||
|
private String displayId;
|
||||||
private String passwordHash;
|
private String passwordHash;
|
||||||
private String status;
|
private String status;
|
||||||
private java.time.Instant lastLoginAt;
|
private java.time.Instant lastLoginAt;
|
||||||
|
|||||||
@@ -187,6 +187,33 @@ public class PhotoService {
|
|||||||
return photo;
|
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 → 保存记录
|
* 处理后端直传:接收文件 → 上传到 MinIO → 保存记录
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
package com.danyang.match.platform.profile.entity;
|
package com.danyang.match.platform.profile.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.TableName;
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.danyang.match.platform.shared.typehandler.JsonNodeTypeHandler;
|
||||||
import com.danyang.match.platform.shared.base.BaseEntity;
|
import com.danyang.match.platform.shared.base.BaseEntity;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
@TableName("user_preferences")
|
@TableName(value = "user_preferences", autoResultMap = true)
|
||||||
public class UserPreference extends BaseEntity {
|
public class UserPreference extends BaseEntity {
|
||||||
|
|
||||||
private String userId;
|
private String userId;
|
||||||
@@ -17,8 +19,10 @@ public class UserPreference extends BaseEntity {
|
|||||||
private Integer minHeightCm;
|
private Integer minHeightCm;
|
||||||
private Integer maxHeightCm;
|
private Integer maxHeightCm;
|
||||||
private String heightPriority;
|
private String heightPriority;
|
||||||
|
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||||
private com.fasterxml.jackson.databind.JsonNode regionScope;
|
private com.fasterxml.jackson.databind.JsonNode regionScope;
|
||||||
private String regionPriority;
|
private String regionPriority;
|
||||||
|
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||||
private com.fasterxml.jackson.databind.JsonNode maritalStatuses;
|
private com.fasterxml.jackson.databind.JsonNode maritalStatuses;
|
||||||
private String maritalPriority;
|
private String maritalPriority;
|
||||||
private String minEducationCode;
|
private String minEducationCode;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
|||||||
import com.danyang.match.platform.profile.entity.UserPreference;
|
import com.danyang.match.platform.profile.entity.UserPreference;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.ResultMap;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@@ -20,5 +21,6 @@ public interface UserPreferenceMapper extends BaseMapper<UserPreference> {
|
|||||||
* <p>{@code deleted_at IS NULL}:V037 已为 user_preferences 补上软删列。
|
* <p>{@code deleted_at IS NULL}:V037 已为 user_preferences 补上软删列。
|
||||||
*/
|
*/
|
||||||
@Select("SELECT * FROM user_preferences WHERE user_id = #{userId} AND deleted_at IS NULL LIMIT 1")
|
@Select("SELECT * FROM user_preferences WHERE user_id = #{userId} AND deleted_at IS NULL LIMIT 1")
|
||||||
|
@ResultMap("mybatis-plus_UserPreference")
|
||||||
Optional<UserPreference> findByUserId(String userId);
|
Optional<UserPreference> findByUserId(String userId);
|
||||||
}
|
}
|
||||||
|
|||||||