Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b505d9133 | ||
|
|
3c2b967274 | ||
|
|
827c23db1d | ||
|
|
ef61d51f61 | ||
|
|
02bc01f9c9 | ||
|
|
16c82739db | ||
|
|
f73a116a10 | ||
|
|
21275ef770 | ||
|
|
d3735e3afa |
@@ -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";
|
||||||
|
|||||||
@@ -20,8 +20,8 @@
|
|||||||
packages:
|
packages:
|
||||||
- '.'
|
- '.'
|
||||||
allowBuilds:
|
allowBuilds:
|
||||||
esbuild: set this to true or false
|
esbuild: true
|
||||||
vue-demi: set this to true or false
|
vue-demi: true
|
||||||
onlyBuiltDependencies:
|
onlyBuiltDependencies:
|
||||||
- esbuild
|
- esbuild
|
||||||
- vue-demi
|
- vue-demi
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 672 KiB |
@@ -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'
|
||||||
@@ -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
|
||||||
@@ -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 ? '是(已幂等,未重复记录)' : '否' }}
|
||||||
@@ -96,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)
|
||||||
@@ -151,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="暂无双向互选记录" />
|
||||||
@@ -46,7 +46,7 @@ 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)
|
||||||
@@ -59,8 +59,8 @@ async function loadData() {
|
|||||||
const token = getAccessToken()
|
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)
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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,11 +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 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) -->
|
<!-- ZC-MM-002:服务请求队列仅分配权持有者可见(matchmaker.assign 或 matchmaker.team.assign) -->
|
||||||
<el-tab-pane v-if="canAssign" label="服务请求队列" name="services">
|
<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>
|
||||||
@@ -21,6 +34,7 @@
|
|||||||
<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==='in_service'" 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>
|
||||||
@@ -28,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>
|
||||||
@@ -43,7 +57,9 @@
|
|||||||
<!-- ZC-MM-002 新增:服务对象分配(本人名下生效中的分配 + 转分配/撤销/结束) -->
|
<!-- ZC-MM-002 新增:服务对象分配(本人名下生效中的分配 + 转分配/撤销/结束) -->
|
||||||
<el-tab-pane label="服务对象分配" name="assignments">
|
<el-tab-pane label="服务对象分配" name="assignments">
|
||||||
<el-table :data="assignments" stripe v-loading="assignmentsLoading">
|
<el-table :data="assignments" stripe v-loading="assignmentsLoading">
|
||||||
<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="assignmentScope" label="范围" width="90">
|
<el-table-column prop="assignmentScope" label="范围" width="90">
|
||||||
<template #default="{ row }">{{ assignmentScopeLabel(row.assignmentScope) }}</template>
|
<template #default="{ row }">{{ assignmentScopeLabel(row.assignmentScope) }}</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
@@ -59,6 +75,7 @@
|
|||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column label="操作" width="220">
|
<el-table-column label="操作" width="220">
|
||||||
<template #default="{ row }">
|
<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" type="primary" @click="openTransfer(row)">转分配</el-button>
|
||||||
<el-button size="small" @click="openTerminate(row, 'revoke')">撤销</el-button>
|
<el-button size="small" @click="openTerminate(row, 'revoke')">撤销</el-button>
|
||||||
<el-button size="small" @click="openTerminate(row, 'end')">结束</el-button>
|
<el-button size="small" @click="openTerminate(row, 'end')">结束</el-button>
|
||||||
@@ -66,6 +83,36 @@
|
|||||||
</el-table-column>
|
</el-table-column>
|
||||||
</el-table>
|
</el-table>
|
||||||
</el-tab-pane>
|
</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>
|
||||||
|
|
||||||
@@ -121,8 +168,8 @@
|
|||||||
<!-- 创建推荐弹窗 -->
|
<!-- 创建推荐弹窗 -->
|
||||||
<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>
|
||||||
@@ -130,16 +177,67 @@
|
|||||||
<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, computed, 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'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
|
const route = useRoute()
|
||||||
|
const managementDetail = ref(false)
|
||||||
|
const managedServices = ref<any[]>([])
|
||||||
// ZC-MM-002:分配权 = matchmaker.assign(平台授权)或 matchmaker.team.assign(红娘组长)
|
// ZC-MM-002:分配权 = matchmaker.assign(平台授权)或 matchmaker.team.assign(红娘组长)
|
||||||
const canAssign = computed(() => {
|
const canAssign = computed(() => {
|
||||||
const perms: string[] = authStore.permissions || []
|
const perms: string[] = authStore.permissions || []
|
||||||
@@ -156,6 +254,7 @@ const assignableMatchmakers = ref<any[]>([])
|
|||||||
const assignDialogVisible = ref(false)
|
const assignDialogVisible = ref(false)
|
||||||
const transferDialogVisible = ref(false)
|
const transferDialogVisible = ref(false)
|
||||||
const terminateDialogVisible = ref(false)
|
const terminateDialogVisible = ref(false)
|
||||||
|
const recDialogVisible = ref(false)
|
||||||
const currentServiceId = ref('')
|
const currentServiceId = ref('')
|
||||||
const currentUserId = ref('')
|
const currentUserId = ref('')
|
||||||
const currentAssignmentId = ref('')
|
const currentAssignmentId = ref('')
|
||||||
@@ -163,7 +262,11 @@ const terminateAction = ref<'revoke' | 'end'>('revoke')
|
|||||||
const assignForm = ref({ matchmakerOperatorId: '', reason: '' })
|
const assignForm = ref({ matchmakerOperatorId: '', reason: '' })
|
||||||
const transferForm = ref({ newMatchmakerOperatorId: '', reason: '' })
|
const transferForm = ref({ newMatchmakerOperatorId: '', reason: '' })
|
||||||
const terminateForm = ref({ reason: '' })
|
const terminateForm = ref({ reason: '' })
|
||||||
const recForm = ref({ userId: '', targetUserId: '', 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: '转介咨询',
|
||||||
@@ -192,6 +295,19 @@ const ASSIGNMENT_STATUS_TAG: Record<string, string> = {
|
|||||||
active: 'success', ended: 'info', revoked: 'danger', transferred: 'info', expired: 'info'
|
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' }
|
||||||
@@ -201,6 +317,94 @@ function assignmentStatusLabel(s: string) { return ASSIGNMENT_STATUS_LABEL[s] ||
|
|||||||
function assignmentStatusTag(s: string) { return ASSIGNMENT_STATUS_TAG[s] || 'info' }
|
function assignmentStatusTag(s: string) { return ASSIGNMENT_STATUS_TAG[s] || 'info' }
|
||||||
function assignmentScopeLabel(s: string) { return s === 'primary' ? '主责' : '协同' }
|
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
|
||||||
@@ -224,8 +428,14 @@ async function loadAssignableMatchmakers() {
|
|||||||
try { const res: any = await get('/operator/matchmaker/assignments/assignable-matchmakers'); assignableMatchmakers.value = res?.data || [] } catch { assignableMatchmakers.value = [] }
|
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()
|
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 === 'assignments') await loadAssignments()
|
||||||
|
else if (activeTab.value === 'contactAuths') await loadContactAuths()
|
||||||
else await loadRecommendations()
|
else await loadRecommendations()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,21 +500,27 @@ async function doTerminate() {
|
|||||||
|
|
||||||
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>
|
||||||
|
|||||||
@@ -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}">
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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[]
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -30,4 +30,9 @@ public class AuditLog extends BaseEntity {
|
|||||||
private String actorRoleSnapshot;
|
private String actorRoleSnapshot;
|
||||||
/** 请求追踪 ID(RequestIdFilter 写入 MDC 的 requestId)。 */
|
/** 请求追踪 ID(RequestIdFilter 写入 MDC 的 requestId)。 */
|
||||||
private String requestTraceId;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -103,4 +103,29 @@ public class AuditLogService {
|
|||||||
}
|
}
|
||||||
auditLogMapper.insert(auditLog);
|
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) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-1
@@ -29,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<>();
|
||||||
|
|
||||||
@@ -37,7 +41,9 @@ public class MockWechatLoginProvider implements WechatLoginProvider {
|
|||||||
log.debug("[Mock] 微信登录 code: {}", code);
|
log.debug("[Mock] 微信登录 code: {}", code);
|
||||||
|
|
||||||
// 模拟:相同 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,
|
||||||
|
|||||||
@@ -124,6 +124,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());
|
||||||
@@ -157,6 +158,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());
|
||||||
@@ -204,6 +206,7 @@ public class OperatorAuthService {
|
|||||||
result.put("expiresIn", jwtTokenService.getExpirationMs() / 1000);
|
result.put("expiresIn", jwtTokenService.getExpirationMs() / 1000);
|
||||||
// 同步 operator 概要:前端凭 HttpOnly refresh cookie 静默刷新后,可直接恢复菜单态,无需重新登录
|
// 同步 operator 概要:前端凭 HttpOnly refresh cookie 静默刷新后,可直接恢复菜单态,无需重新登录
|
||||||
result.put("operatorId", operatorInfo.get("operatorId"));
|
result.put("operatorId", operatorInfo.get("operatorId"));
|
||||||
|
result.put("operatorDisplayId", operatorInfo.get("operatorDisplayId"));
|
||||||
result.put("name", operatorInfo.get("name"));
|
result.put("name", operatorInfo.get("name"));
|
||||||
result.put("username", operatorInfo.get("username"));
|
result.put("username", operatorInfo.get("username"));
|
||||||
result.put("organizationId", operatorInfo.get("organizationId"));
|
result.put("organizationId", operatorInfo.get("organizationId"));
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-23
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-4
@@ -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();
|
||||||
|
|||||||
+67
@@ -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;
|
||||||
|
}
|
||||||
+11
@@ -4,6 +4,8 @@ import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
|||||||
import com.danyang.match.platform.matchmaker.service.MatchmakerAssignmentService;
|
import com.danyang.match.platform.matchmaker.service.MatchmakerAssignmentService;
|
||||||
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 com.danyang.match.platform.user.mapper.UserMapper;
|
||||||
|
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
@@ -31,6 +33,8 @@ import java.util.Map;
|
|||||||
public class MatchmakerAssignmentController {
|
public class MatchmakerAssignmentController {
|
||||||
|
|
||||||
private final MatchmakerAssignmentService assignmentService;
|
private final MatchmakerAssignmentService assignmentService;
|
||||||
|
private final UserMapper userMapper;
|
||||||
|
private final UserProfileMapper userProfileMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建分配。
|
* 创建分配。
|
||||||
@@ -132,9 +136,16 @@ public class MatchmakerAssignmentController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> assignmentView(MatchmakerAssignment a) {
|
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(
|
return Map.ofEntries(
|
||||||
Map.entry("id", a.getId()),
|
Map.entry("id", a.getId()),
|
||||||
Map.entry("userId", a.getUserId()),
|
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("matchmakerOperatorId", a.getMatchmakerOperatorId()),
|
||||||
Map.entry("serviceId", a.getServiceId() == null ? "" : a.getServiceId()),
|
Map.entry("serviceId", a.getServiceId() == null ? "" : a.getServiceId()),
|
||||||
Map.entry("assignmentScope", a.getAssignmentScope()),
|
Map.entry("assignmentScope", a.getAssignmentScope()),
|
||||||
|
|||||||
+106
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -64,6 +64,14 @@ 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()));
|
||||||
|
}
|
||||||
|
|
||||||
@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();
|
||||||
|
|||||||
+14
@@ -26,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(
|
||||||
|
|||||||
+42
@@ -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;
|
||||||
|
}
|
||||||
+65
@@ -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();
|
||||||
|
}
|
||||||
+20
@@ -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,20 @@ 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.created_at AS \"createdAt\", s.assigned_at AS \"assignedAt\", s.completed_at AS \"completedAt\", " +
|
||||||
|
"u.display_number AS \"userDisplayNumber\", o.display_id AS \"operatorDisplayId\", " +
|
||||||
|
"(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 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);
|
||||||
|
|
||||||
@@ -68,6 +83,11 @@ public interface MatchmakerServiceMapper extends BaseMapper<MatchmakerServiceRec
|
|||||||
@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);
|
||||||
|
|
||||||
|
/** 用户确认红娘服务方案:仅允许本人将 waiting_user 恢复为 in_service。 */
|
||||||
|
@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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 注销前检查(P16 收尾 2e):该用户仍处于非终态的红娘服务数。
|
* 注销前检查(P16 收尾 2e):该用户仍处于非终态的红娘服务数。
|
||||||
* 状态口径(submitted/assigned/in_service/waiting_user)。
|
* 状态口径(submitted/assigned/in_service/waiting_user)。
|
||||||
|
|||||||
+55
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+516
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -291,6 +291,23 @@ public class MatchmakerAssignmentService {
|
|||||||
return assignment;
|
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)不限组织;
|
* 组织范围判定(D2):hasGlobalAssign(matchmaker.assign)不限组织;
|
||||||
* team.assign 时校验操作者与目标红娘 organization_id 一致。
|
* team.assign 时校验操作者与目标红娘 organization_id 一致。
|
||||||
|
|||||||
+53
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
-4
@@ -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;
|
||||||
|
|
||||||
// ==================== 用户端:提交红娘服务请求 ====================
|
// ==================== 用户端:提交红娘服务请求 ====================
|
||||||
|
|
||||||
@@ -78,6 +80,20 @@ public class MatchmakerService {
|
|||||||
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 +173,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 +185,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);
|
||||||
|
|
||||||
|
|||||||
+2
@@ -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));
|
||||||
|
|||||||
@@ -54,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));
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
+2
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -227,9 +227,10 @@ public class ReferralService {
|
|||||||
private String getOperatorName(String operatorId) {
|
private String getOperatorName(String operatorId) {
|
||||||
try {
|
try {
|
||||||
var operator = operatorMapper.selectById(operatorId);
|
var operator = operatorMapper.selectById(operatorId);
|
||||||
return operator != null ? operator.getName() : operatorId;
|
return operator != null ? operator.getName() : "公益红娘";
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return operatorId;
|
log.warn("转介操作员名称查询失败", e);
|
||||||
|
return "公益红娘";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-21
@@ -251,16 +251,7 @@ public class RelationshipService {
|
|||||||
matchMapper.insert(match);
|
matchMapper.insert(match);
|
||||||
}
|
}
|
||||||
|
|
||||||
// V1.1: 活动互选不自动创建Conversation,需双方确认后由confirmActivityInterest处理
|
// 当前产品不提供用户间聊天;Match 仅用于结果判定和公益服务引导。
|
||||||
if (autoCreateConversation) {
|
|
||||||
try {
|
|
||||||
chatService.getOrCreateConversation(match.getId(), userId, targetUserId);
|
|
||||||
log.info("Match后自动创建会话: matchId={}, users={}", match.getId(), userId + "," + targetUserId);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("创建会话失败,Match已创建但聊天可能不可用: matchId={}, error={}",
|
|
||||||
match.getId(), e.toString(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return match;
|
return match;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,7 +277,6 @@ public class RelationshipService {
|
|||||||
result.put("matchReused", true);
|
result.put("matchReused", true);
|
||||||
result.put("matchId", existingMatch.get().getId());
|
result.put("matchId", existingMatch.get().getId());
|
||||||
result.put("status", existingMatch.get().getStatus());
|
result.put("status", existingMatch.get().getStatus());
|
||||||
result.put("conversationAutoCreated", true);
|
|
||||||
log.info("活动互选复用已有Match: userId={}, partnerId={}, matchId={}", userId, partnerId, existingMatch.get().getId());
|
log.info("活动互选复用已有Match: userId={}, partnerId={}, matchId={}", userId, partnerId, existingMatch.get().getId());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -299,20 +289,10 @@ public class RelationshipService {
|
|||||||
// 3. 创建新 Match Episode(source=activity_mutual,不自动创建 Conversation)
|
// 3. 创建新 Match Episode(source=activity_mutual,不自动创建 Conversation)
|
||||||
Match match = createMatch(userId, partnerId, Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, false);
|
Match match = createMatch(userId, partnerId, Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, false);
|
||||||
|
|
||||||
// V1.1 Phase 16 修复(Gate:互选确认后双方可沟通):双确认后必须开启会话。
|
|
||||||
// 此前此处未建会话,仅靠首条消息惰性创建,导致「双方可沟通」的入口不可见。
|
|
||||||
// 现显式开启,保证互选成功后聊天入口立即可见。
|
|
||||||
try {
|
|
||||||
chatService.getOrCreateConversation(match.getId(), match.getUserAId(), match.getUserBId());
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("活动互选开启会话失败(Match 已创建): matchId={}, error={}", match.getId(), e.toString(), e);
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("matchCreated", true);
|
result.put("matchCreated", true);
|
||||||
result.put("matchId", match.getId());
|
result.put("matchId", match.getId());
|
||||||
result.put("priorUnmatch", priorUnmatchExists);
|
result.put("priorUnmatch", priorUnmatchExists);
|
||||||
result.put("conversationAutoCreated", true);
|
|
||||||
log.info("活动互选创建新Match Episode: userId={}, partnerId={}, priorUnmatch={}, matchId={}",
|
log.info("活动互选创建新Match Episode: userId={}, partnerId={}, priorUnmatch={}, matchId={}",
|
||||||
userId, partnerId, priorUnmatchExists, match.getId());
|
userId, partnerId, priorUnmatchExists, match.getId());
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
+1
@@ -38,6 +38,7 @@ import java.util.stream.Collectors;
|
|||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
|
@org.springframework.core.annotation.Order(0)
|
||||||
public class ApiResponseStatusAdvice implements ResponseBodyAdvice<ApiResponse> {
|
public class ApiResponseStatusAdvice implements ResponseBodyAdvice<ApiResponse> {
|
||||||
|
|
||||||
private static final Map<String, ApiResponseCode> BY_CODE =
|
private static final Map<String, ApiResponseCode> BY_CODE =
|
||||||
|
|||||||
@@ -100,7 +100,9 @@ public class SecurityConfig {
|
|||||||
"/activities/operator/**",
|
"/activities/operator/**",
|
||||||
"/service-appointments/operator/**",
|
"/service-appointments/operator/**",
|
||||||
"/service-programs/operator/**",
|
"/service-programs/operator/**",
|
||||||
"/referrals/operator/**")
|
"/referrals/operator/**",
|
||||||
|
"/referrals/service-station",
|
||||||
|
"/referrals/activity")
|
||||||
.hasRole("OPERATOR")
|
.hasRole("OPERATOR")
|
||||||
/**
|
/**
|
||||||
* 其余接口必须持用户身份(ROLE_USER),不再只是"已认证"。
|
* 其余接口必须持用户身份(ROLE_USER),不再只是"已认证"。
|
||||||
|
|||||||
@@ -362,4 +362,36 @@ public final class Constants {
|
|||||||
public static final String SENSITIVE_ACCESS_RESULT_SUCCESS = "success";
|
public static final String SENSITIVE_ACCESS_RESULT_SUCCESS = "success";
|
||||||
/** 红娘查看服务对象详情的访问理由文案 */
|
/** 红娘查看服务对象详情的访问理由文案 */
|
||||||
public static final String SENSITIVE_ACCESS_REASON_MATCHMAKER_DETAIL = "matchmaker 工作台查看服务对象详情";
|
public static final String SENSITIVE_ACCESS_REASON_MATCHMAKER_DETAIL = "matchmaker 工作台查看服务对象详情";
|
||||||
|
|
||||||
|
// ========== ZC-MM-003 / B1 立项:受控联系授权(V056) ==========
|
||||||
|
/** 授权状态:待审批 */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_PENDING_APPROVAL = "pending_approval";
|
||||||
|
/** 授权状态:待用户同意 */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_PENDING_CONSENT = "pending_consent";
|
||||||
|
/** 授权状态:生效中 */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_ACTIVE = "active";
|
||||||
|
/** 授权状态:用户已拒绝 */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_REJECTED = "rejected";
|
||||||
|
/** 授权状态:已过期(有效期/同意窗口届满,双态惰性收敛) */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_EXPIRED = "expired";
|
||||||
|
/** 授权状态:已撤销 */
|
||||||
|
public static final String CONTACT_AUTH_STATUS_REVOKED = "revoked";
|
||||||
|
/** 渠道:电话联系 */
|
||||||
|
public static final String CONTACT_CHANNEL_PHONE = "phone";
|
||||||
|
/** 渠道:线下见面 */
|
||||||
|
public static final String CONTACT_CHANNEL_OFFLINE_MEETING = "offline_meeting";
|
||||||
|
/** 渠道:完整联系方式 */
|
||||||
|
public static final String CONTACT_CHANNEL_FULL_CONTACT = "full_contact";
|
||||||
|
/** 审计动作:红娘发起授权申请 */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_REQUEST = "MATCHMAKER_CONTACT_REQUEST";
|
||||||
|
/** 审计动作:审批岗批准/拒绝申请 */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_APPROVE = "MATCHMAKER_CONTACT_APPROVE";
|
||||||
|
/** 审计动作:用户单独同意 */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_CONSENT = "MATCHMAKER_CONTACT_CONSENT";
|
||||||
|
/** 审计动作:用户拒绝 */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_DECLINE = "MATCHMAKER_CONTACT_DECLINE";
|
||||||
|
/** 审计动作:披露联系方式(H4 唯一披露出口) */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_DISCLOSE = "MATCHMAKER_CONTACT_DISCLOSE";
|
||||||
|
/** 审计动作:撤销授权 */
|
||||||
|
public static final String CONTACT_AUDIT_ACTION_REVOKE = "MATCHMAKER_CONTACT_REVOKE";
|
||||||
}
|
}
|
||||||
@@ -78,7 +78,7 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (token == null) {
|
if (token == null) {
|
||||||
chain.doFilter(request, response);
|
sendUnauthorized(response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!jwtTokenService.validateToken(token)) {
|
if (!jwtTokenService.validateToken(token)) {
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.danyang.match.platform.shared.id;
|
||||||
|
|
||||||
|
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 com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
|
||||||
|
import java.io.*;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 仅解析已有写接口的人员/活动编号;业务层仍校验原 UUID 的权限与数据范围。 */
|
||||||
|
@RestControllerAdvice
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PublicIdInputAdvice extends RequestBodyAdviceAdapter {
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final PublicIdMapper mapper;
|
||||||
|
private static final Map<String, String> TYPES = Map.of(
|
||||||
|
"userId", "users", "targetUserId", "users", "reportedUserId", "users",
|
||||||
|
"counselorId", "operators", "assignedOperatorId", "operators",
|
||||||
|
"matchmakerOperatorId", "operators", "newMatchmakerOperatorId", "operators",
|
||||||
|
"activityId", "activities");
|
||||||
|
@Override
|
||||||
|
public boolean supports(MethodParameter method, Type targetType, Class<? extends HttpMessageConverter<?>> converter) {
|
||||||
|
return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converter);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public HttpInputMessage beforeBodyRead(HttpInputMessage message, MethodParameter method, Type targetType,
|
||||||
|
Class<? extends HttpMessageConverter<?>> converter) throws IOException {
|
||||||
|
JsonNode body = objectMapper.readTree(message.getBody());
|
||||||
|
resolve(body);
|
||||||
|
byte[] bytes = objectMapper.writeValueAsBytes(body);
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.putAll(message.getHeaders());
|
||||||
|
headers.setContentLength(bytes.length);
|
||||||
|
return new HttpInputMessage() {
|
||||||
|
public InputStream getBody() { return new ByteArrayInputStream(bytes); }
|
||||||
|
public HttpHeaders getHeaders() { return headers; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
void resolve(JsonNode node) {
|
||||||
|
if (node == null) return;
|
||||||
|
if (node.isArray()) { node.forEach(this::resolve); return; }
|
||||||
|
if (!node.isObject()) return;
|
||||||
|
ObjectNode object = (ObjectNode) node;
|
||||||
|
for (var entry : TYPES.entrySet()) {
|
||||||
|
JsonNode value = object.get(entry.getKey());
|
||||||
|
if (value == null || !value.isTextual() || !value.asText().matches("[A-Z]{2}[0-9]{11}")) continue;
|
||||||
|
String id = mapper.resolve(value.asText(), entry.getValue());
|
||||||
|
if (id == null) throw new BusinessException(ApiResponseCode.NOT_FOUND, "编号对应的对象不存在或不可用");
|
||||||
|
object.put(entry.getKey(), id);
|
||||||
|
}
|
||||||
|
object.elements().forEachRemaining(child -> { if (child.isContainerNode()) resolve(child); });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.danyang.match.platform.shared.id;
|
||||||
|
|
||||||
|
import org.apache.ibatis.annotations.*;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface PublicIdMapper {
|
||||||
|
@Select({"<script>SELECT id AS \"id\", display_id AS \"displayId\", entity_type AS \"entityType\", referral_display_id AS \"referralDisplayId\" FROM public_display_ids WHERE id IN",
|
||||||
|
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>CAST(#{id} AS text)</foreach></script>"})
|
||||||
|
List<Map<String, Object>> findAll(@Param("ids") List<String> ids);
|
||||||
|
|
||||||
|
@Select("SELECT id FROM public_display_ids WHERE display_id=#{number} AND entity_type=#{entityType}")
|
||||||
|
String resolve(@Param("number") String number, @Param("entityType") String entityType);
|
||||||
|
|
||||||
|
@Select("SELECT public_next_display_id('ZF', (#{createdAt}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date)")
|
||||||
|
String nextReferral(@Param("createdAt") java.time.Instant createdAt);
|
||||||
|
|
||||||
|
@Update("UPDATE matchmaker_followups SET referral_display_id=#{number} WHERE id=#{id}::uuid AND referral_display_id IS NULL")
|
||||||
|
int saveReferral(@Param("id") String id, @Param("number") String number);
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.danyang.match.platform.shared.id;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/** 只补充原响应已允许返回的对象编号;不加载资料,不改变 UUID 与权限。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PublicIdResponse {
|
||||||
|
private final PublicIdMapper mapper;
|
||||||
|
private static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}");
|
||||||
|
private static boolean reference(String name) {
|
||||||
|
return "id".equals(name) || name.endsWith("Id");
|
||||||
|
}
|
||||||
|
public void enrich(JsonNode data) {
|
||||||
|
Set<String> ids = new LinkedHashSet<>();
|
||||||
|
collect(data, ids);
|
||||||
|
if (ids.isEmpty()) return;
|
||||||
|
Map<String, Map<String, Object>> numbers = new HashMap<>();
|
||||||
|
for (var row : mapper.findAll(new ArrayList<>(ids))) {
|
||||||
|
String id = row.get("id").toString();
|
||||||
|
if (numbers.putIfAbsent(id, row) != null) throw new IllegalStateException("跨实体 UUID 冲突,不能确定公开编号");
|
||||||
|
}
|
||||||
|
apply(data, numbers);
|
||||||
|
}
|
||||||
|
private void collect(JsonNode node, Set<String> ids) {
|
||||||
|
if (node.isObject()) node.fields().forEachRemaining(field -> {
|
||||||
|
if (reference(field.getKey()) && field.getValue().isTextual() && UUID.matcher(field.getValue().asText()).matches()) ids.add(field.getValue().asText());
|
||||||
|
else if (field.getValue().isContainerNode()) collect(field.getValue(), ids);
|
||||||
|
});
|
||||||
|
else if (node.isArray()) node.forEach(child -> collect(child, ids));
|
||||||
|
}
|
||||||
|
private void apply(JsonNode node, Map<String, Map<String, Object>> numbers) {
|
||||||
|
if (node.isArray()) { node.forEach(child -> apply(child, numbers)); return; }
|
||||||
|
if (!node.isObject()) return;
|
||||||
|
var object = (ObjectNode) node;
|
||||||
|
List<Map.Entry<String, JsonNode>> fields = new ArrayList<>();
|
||||||
|
object.fields().forEachRemaining(fields::add);
|
||||||
|
for (var field : fields) {
|
||||||
|
String name = field.getKey();
|
||||||
|
JsonNode value = field.getValue();
|
||||||
|
if (value.isContainerNode()) { apply(value, numbers); continue; }
|
||||||
|
if (!reference(name) || !value.isTextual() || !UUID.matcher(value.asText()).matches()) continue;
|
||||||
|
var row = numbers.get(value.asText());
|
||||||
|
String stem = name.equals("id") ? "" : name.substring(0, name.length()-2);
|
||||||
|
boolean user = stem.toLowerCase(Locale.ROOT).endsWith("user") || (row != null && "users".equals(row.get("entityType")));
|
||||||
|
String key = stem.isEmpty() ? "displayId" : stem + (user ? "DisplayNumber" : "DisplayId");
|
||||||
|
Object number = row == null ? null : row.get("displayId");
|
||||||
|
if (row != null && row.get("referralDisplayId") != null && "matchmaker_followups".equals(row.get("entityType"))) number = row.get("referralDisplayId");
|
||||||
|
if (number == null) object.putNull(key); else object.put(key, number.toString());
|
||||||
|
if (stem.isEmpty() && user) object.put("displayNumber", number == null ? null : number.toString());
|
||||||
|
if (stem.isEmpty() && row != null && row.get("referralDisplayId") != null) object.put("referralDisplayId", row.get("referralDisplayId").toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package com.danyang.match.platform.shared.id;
|
||||||
|
|
||||||
|
import com.danyang.match.platform.shared.dto.ApiResponse;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||||
|
import org.springframework.http.server.*;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||||
|
|
||||||
|
@RestControllerAdvice
|
||||||
|
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PublicIdResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final PublicIdResponse publicIds;
|
||||||
|
@Override
|
||||||
|
public boolean supports(MethodParameter method, Class<? extends HttpMessageConverter<?>> converter) {
|
||||||
|
return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converter);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||||
|
public Object beforeBodyWrite(Object body, MethodParameter method, MediaType type,
|
||||||
|
Class<? extends HttpMessageConverter<?>> converter, ServerHttpRequest request, ServerHttpResponse response) {
|
||||||
|
if (body instanceof ApiResponse api && api.isSuccess() && api.getData() != null) {
|
||||||
|
var data = objectMapper.valueToTree(api.getData());
|
||||||
|
publicIds.enrich(data);
|
||||||
|
api.setData(data);
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -2,6 +2,7 @@ package com.danyang.match.platform.shared.security;
|
|||||||
|
|
||||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import com.danyang.match.platform.audit.service.AuditDenyWriter;
|
||||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -21,6 +22,7 @@ import java.util.UUID;
|
|||||||
public class AuthorizationAuditListener {
|
public class AuthorizationAuditListener {
|
||||||
|
|
||||||
private final AuditLogMapper auditLogMapper;
|
private final AuditLogMapper auditLogMapper;
|
||||||
|
private final AuditDenyWriter auditDenyWriter;
|
||||||
|
|
||||||
@EventListener
|
@EventListener
|
||||||
public void onAuthorizationDenied(AuthorizationDeniedEvent<?> event) {
|
public void onAuthorizationDenied(AuthorizationDeniedEvent<?> event) {
|
||||||
@@ -46,7 +48,8 @@ public class AuthorizationAuditListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
auditLogMapper.insert(audit);
|
// 拒绝审计独立事务提交:@PreAuthorize 拒绝若发生在业务事务内,同事务写入会被回滚吞掉
|
||||||
|
auditDenyWriter.insertIndependent(audit);
|
||||||
} catch (RuntimeException exception) {
|
} catch (RuntimeException exception) {
|
||||||
log.error("写入授权拒绝审计失败: operatorId={}", principal.id(), exception);
|
log.error("写入授权拒绝审计失败: operatorId={}", principal.id(), exception);
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-2
@@ -2,6 +2,7 @@ package com.danyang.match.platform.shared.security;
|
|||||||
|
|
||||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import com.danyang.match.platform.audit.service.AuditDenyWriter;
|
||||||
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 lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -22,6 +23,7 @@ import org.slf4j.MDC;
|
|||||||
public class DataScopeGuard {
|
public class DataScopeGuard {
|
||||||
|
|
||||||
private final AuditLogMapper auditLogMapper;
|
private final AuditLogMapper auditLogMapper;
|
||||||
|
private final AuditDenyWriter auditDenyWriter;
|
||||||
|
|
||||||
public void deny(String operatorId, String resourceType, String resourceId, String message) {
|
public void deny(String operatorId, String resourceType, String resourceId, String message) {
|
||||||
// ZC-MM-006 / T01 兼容性:缺省调用(不带 purposeCode/assignmentId)仍可写
|
// ZC-MM-006 / T01 兼容性:缺省调用(不带 purposeCode/assignmentId)仍可写
|
||||||
@@ -48,7 +50,8 @@ public class DataScopeGuard {
|
|||||||
audit.setRequestTraceId(MDC.get("requestId"));
|
audit.setRequestTraceId(MDC.get("requestId"));
|
||||||
audit.setCreatedAt(Instant.now());
|
audit.setCreatedAt(Instant.now());
|
||||||
try {
|
try {
|
||||||
auditLogMapper.insert(audit);
|
// 拒绝审计必须独立事务提交:与业务同事务会被拒绝异常的回滚吞掉(运行时实测缺陷)
|
||||||
|
auditDenyWriter.insertIndependent(audit);
|
||||||
} catch (RuntimeException exception) {
|
} catch (RuntimeException exception) {
|
||||||
log.error("写入数据范围拒绝审计失败: operatorId={}, resourceType={}, resourceId={}",
|
log.error("写入数据范围拒绝审计失败: operatorId={}, resourceType={}, resourceId={}",
|
||||||
operatorId, resourceType, resourceId, exception);
|
operatorId, resourceType, resourceId, exception);
|
||||||
@@ -81,7 +84,8 @@ public class DataScopeGuard {
|
|||||||
audit.setRequestTraceId(MDC.get("requestId"));
|
audit.setRequestTraceId(MDC.get("requestId"));
|
||||||
audit.setCreatedAt(Instant.now());
|
audit.setCreatedAt(Instant.now());
|
||||||
try {
|
try {
|
||||||
auditLogMapper.insert(audit);
|
// 拒绝审计必须独立事务提交:与业务同事务会被拒绝异常的回滚吞掉(运行时实测缺陷)
|
||||||
|
auditDenyWriter.insertIndependent(audit);
|
||||||
} catch (RuntimeException exception) {
|
} catch (RuntimeException exception) {
|
||||||
log.error("写入数据范围拒绝审计失败: operatorId={}, resourceType={}, resourceId={}",
|
log.error("写入数据范围拒绝审计失败: operatorId={}, resourceType={}, resourceId={}",
|
||||||
operatorId, resourceType, resourceId, exception);
|
operatorId, resourceType, resourceId, exception);
|
||||||
@@ -89,6 +93,31 @@ public class DataScopeGuard {
|
|||||||
throw new BusinessException(ApiResponseCode.NOT_FOUND, message);
|
throw new BusinessException(ApiResponseCode.NOT_FOUND, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V057 / 运行时实测修复:C 端用户主体的数据范围拒绝。
|
||||||
|
* 与 {@link #deny} 同「先审计后拒绝」语义,但审计主体写 subject_user_id
|
||||||
|
* (operator_id 置 null)——userId 写 operator_id 维度必撞
|
||||||
|
* audit_logs_operator_id_fkey(→operators),H2 无 FK 假绿、生产零审计。
|
||||||
|
*/
|
||||||
|
public void denyUser(String userId, String resourceType, String resourceId, String message) {
|
||||||
|
AuditLog audit = new AuditLog();
|
||||||
|
audit.setId(UUID.randomUUID().toString());
|
||||||
|
audit.setSubjectUserId(userId);
|
||||||
|
audit.setAction("DATA_SCOPE_DENIED");
|
||||||
|
audit.setResourceType(resourceType);
|
||||||
|
audit.setResourceId(resourceId);
|
||||||
|
audit.setRequestTraceId(MDC.get("requestId"));
|
||||||
|
audit.setCreatedAt(Instant.now());
|
||||||
|
try {
|
||||||
|
// 拒绝审计必须独立事务提交:与业务同事务会被拒绝异常的回滚吞掉(运行时实测缺陷)
|
||||||
|
auditDenyWriter.insertIndependent(audit);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
log.error("写入用户主体数据范围拒绝审计失败: subjectUserId={}, resourceType={}, resourceId={}",
|
||||||
|
userId, resourceType, resourceId, exception);
|
||||||
|
}
|
||||||
|
throw new AccessDeniedException(message);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当前操作者权限快照(与 {@link AuthorizationAuditListener} 同口径):
|
* 当前操作者权限快照(与 {@link AuthorizationAuditListener} 同口径):
|
||||||
* OperatorPrincipal.permissions() 逗号拼接,截断 128。
|
* OperatorPrincipal.permissions() 逗号拼接,截断 128。
|
||||||
|
|||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package com.danyang.match.platform.shared.typehandler;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.apache.ibatis.type.BaseTypeHandler;
|
||||||
|
import org.apache.ibatis.type.JdbcType;
|
||||||
|
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||||
|
import org.apache.ibatis.type.MappedTypes;
|
||||||
|
|
||||||
|
import java.sql.CallableStatement;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Types;
|
||||||
|
|
||||||
|
/** PostgreSQL JSONB 与 Jackson JsonNode 的参数/结果转换。 */
|
||||||
|
@MappedTypes(JsonNode.class)
|
||||||
|
@MappedJdbcTypes(JdbcType.OTHER)
|
||||||
|
public class JsonNodeTypeHandler extends BaseTypeHandler<JsonNode> {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType)
|
||||||
|
throws SQLException {
|
||||||
|
String json = parameter.toString();
|
||||||
|
if ("PostgreSQL".equalsIgnoreCase(ps.getConnection().getMetaData().getDatabaseProductName())) {
|
||||||
|
ps.setObject(i, json, Types.OTHER);
|
||||||
|
} else {
|
||||||
|
ps.setString(i, json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||||
|
return parse(rs.getString(columnName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||||
|
return parse(rs.getString(columnIndex));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||||
|
return parse(cs.getString(columnIndex));
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode parse(String value) throws SQLException {
|
||||||
|
if (value == null || value.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
return MAPPER.readTree(value);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new SQLException("JSONB 数据格式无效", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.danyang.match.platform.user;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/** 用户对外展示编号;内部 UUID 仍是唯一主键。 */
|
||||||
|
public final class UserDisplayNumber {
|
||||||
|
private static final DateTimeFormatter DATE = DateTimeFormatter.BASIC_ISO_DATE;
|
||||||
|
|
||||||
|
private UserDisplayNumber() {}
|
||||||
|
|
||||||
|
public static String format(String gender, LocalDate registeredDate, int genderRank) {
|
||||||
|
if ((!"male".equals(gender) && !"female".equals(gender)) || registeredDate == null || genderRank < 1) {
|
||||||
|
throw new IllegalArgumentException("性别、注册日期或排名无效");
|
||||||
|
}
|
||||||
|
if (genderRank > ("male".equals(gender) ? 500 : 499)) throw new IllegalArgumentException("当日同性序号超过三位编号容量");
|
||||||
|
int sequence = genderRank * 2 - ("male".equals(gender) ? 1 : 0);
|
||||||
|
if (sequence > 999) throw new IllegalArgumentException("当日同性交序超过三位编号容量");
|
||||||
|
return "YH" + DATE.format(registeredDate) + String.format("%03d", sequence);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ package com.danyang.match.platform.user.dto;
|
|||||||
*/
|
*/
|
||||||
public class UserDetailDTO {
|
public class UserDetailDTO {
|
||||||
private String id;
|
private String id;
|
||||||
|
private String displayNumber;
|
||||||
private String displayName;
|
private String displayName;
|
||||||
private String gender;
|
private String gender;
|
||||||
private Integer age;
|
private Integer age;
|
||||||
@@ -34,6 +35,8 @@ public class UserDetailDTO {
|
|||||||
|
|
||||||
public String getId() { return id; }
|
public String getId() { return id; }
|
||||||
public void setId(String id) { this.id = id; }
|
public void setId(String id) { this.id = id; }
|
||||||
|
public String getDisplayNumber() { return displayNumber; }
|
||||||
|
public void setDisplayNumber(String displayNumber) { this.displayNumber = displayNumber; }
|
||||||
public String getDisplayName() { return displayName; }
|
public String getDisplayName() { return displayName; }
|
||||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||||
public String getGender() { return gender; }
|
public String getGender() { return gender; }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package com.danyang.match.platform.user.dto;
|
|||||||
*/
|
*/
|
||||||
public class UserListItemDTO {
|
public class UserListItemDTO {
|
||||||
private String id;
|
private String id;
|
||||||
|
private String displayNumber;
|
||||||
private String displayName;
|
private String displayName;
|
||||||
private String gender;
|
private String gender;
|
||||||
private Integer age;
|
private Integer age;
|
||||||
@@ -19,6 +20,8 @@ public class UserListItemDTO {
|
|||||||
|
|
||||||
public String getId() { return id; }
|
public String getId() { return id; }
|
||||||
public void setId(String id) { this.id = id; }
|
public void setId(String id) { this.id = id; }
|
||||||
|
public String getDisplayNumber() { return displayNumber; }
|
||||||
|
public void setDisplayNumber(String displayNumber) { this.displayNumber = displayNumber; }
|
||||||
public String getDisplayName() { return displayName; }
|
public String getDisplayName() { return displayName; }
|
||||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||||
public String getGender() { return gender; }
|
public String getGender() { return gender; }
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ public class User extends BaseEntity {
|
|||||||
|
|
||||||
@TableField("phone")
|
@TableField("phone")
|
||||||
private String phone;
|
private String phone;
|
||||||
|
@TableField("display_number")
|
||||||
|
private String displayNumber;
|
||||||
@TableField("account_status")
|
@TableField("account_status")
|
||||||
private String accountStatus;
|
private String accountStatus;
|
||||||
|
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ public class UserService {
|
|||||||
|
|
||||||
if (keyword != null && !keyword.isBlank()) {
|
if (keyword != null && !keyword.isBlank()) {
|
||||||
query.and(q -> q.like(User::getId, keyword)
|
query.and(q -> q.like(User::getId, keyword)
|
||||||
|
.or().like(User::getDisplayNumber, keyword)
|
||||||
.or().like(User::getWechatOpenid, keyword));
|
.or().like(User::getWechatOpenid, keyword));
|
||||||
}
|
}
|
||||||
if (accountStatus != null && !accountStatus.isBlank()) {
|
if (accountStatus != null && !accountStatus.isBlank()) {
|
||||||
@@ -71,7 +72,7 @@ public class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
LambdaQueryWrapper<User> countQuery = new LambdaQueryWrapper<User>();
|
LambdaQueryWrapper<User> countQuery = new LambdaQueryWrapper<User>();
|
||||||
if (keyword != null && !keyword.isBlank()) countQuery.and(q -> q.like(User::getId, keyword).or().like(User::getWechatOpenid, keyword));
|
if (keyword != null && !keyword.isBlank()) countQuery.and(q -> q.like(User::getId, keyword).or().like(User::getDisplayNumber, keyword).or().like(User::getWechatOpenid, keyword));
|
||||||
if (accountStatus != null && !accountStatus.isBlank()) countQuery.eq(User::getAccountStatus, accountStatus);
|
if (accountStatus != null && !accountStatus.isBlank()) countQuery.eq(User::getAccountStatus, accountStatus);
|
||||||
if (profileStatus != null && !profileStatus.isBlank()) {
|
if (profileStatus != null && !profileStatus.isBlank()) {
|
||||||
List<String> userIds = userProfileMapper.selectList(
|
List<String> userIds = userProfileMapper.selectList(
|
||||||
@@ -155,6 +156,7 @@ public class UserService {
|
|||||||
private UserListItemDTO toListItemDTO(User user) {
|
private UserListItemDTO toListItemDTO(User user) {
|
||||||
UserListItemDTO dto = new UserListItemDTO();
|
UserListItemDTO dto = new UserListItemDTO();
|
||||||
dto.setId(user.getId());
|
dto.setId(user.getId());
|
||||||
|
dto.setDisplayNumber(user.getDisplayNumber());
|
||||||
dto.setAccountStatus(user.getAccountStatus());
|
dto.setAccountStatus(user.getAccountStatus());
|
||||||
dto.setRegisteredAt(user.getCreatedAt());
|
dto.setRegisteredAt(user.getCreatedAt());
|
||||||
dto.setRelationshipStatus(user.getRelationshipStatus());
|
dto.setRelationshipStatus(user.getRelationshipStatus());
|
||||||
@@ -189,6 +191,7 @@ public class UserService {
|
|||||||
int reportCount, boolean hasSensitiveView) {
|
int reportCount, boolean hasSensitiveView) {
|
||||||
UserDetailDTO dto = new UserDetailDTO();
|
UserDetailDTO dto = new UserDetailDTO();
|
||||||
dto.setId(user.getId());
|
dto.setId(user.getId());
|
||||||
|
dto.setDisplayNumber(user.getDisplayNumber());
|
||||||
dto.setAccountStatus(user.getAccountStatus());
|
dto.setAccountStatus(user.getAccountStatus());
|
||||||
dto.setRelationshipStatus(user.getRelationshipStatus());
|
dto.setRelationshipStatus(user.getRelationshipStatus());
|
||||||
dto.setRegisteredAt(user.getCreatedAt());
|
dto.setRegisteredAt(user.getCreatedAt());
|
||||||
|
|||||||
+12
@@ -7,10 +7,22 @@ import org.apache.ibatis.annotations.Param;
|
|||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public interface UserIdentityMapper extends BaseMapper<UserIdentity> {
|
public interface UserIdentityMapper extends BaseMapper<UserIdentity> {
|
||||||
|
|
||||||
|
@Select("SELECT pg_advisory_xact_lock(hashtext(#{gender} || ':' || ((#{registeredAt}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date)::text))")
|
||||||
|
void lockDisplayNumberSlot(@Param("gender") String gender, @Param("registeredAt") Instant registeredAt);
|
||||||
|
|
||||||
|
@Select("SELECT COUNT(*) FROM user_identities i JOIN users u ON u.id = i.user_id "
|
||||||
|
+ "WHERE i.gender = #{gender} AND i.verification_status = 'verified' "
|
||||||
|
+ "AND (u.created_at AT TIME ZONE 'Asia/Shanghai')::date = (#{registeredAt}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date "
|
||||||
|
+ "AND (u.created_at < #{registeredAt} OR (u.created_at = #{registeredAt} AND u.id < #{userId}::uuid))")
|
||||||
|
int countEarlierSameDayGender(@Param("gender") String gender,
|
||||||
|
@Param("registeredAt") Instant registeredAt,
|
||||||
|
@Param("userId") String userId);
|
||||||
|
|
||||||
@Select("SELECT * FROM user_identities WHERE user_id = #{userId} AND deleted_at IS NULL LIMIT 1")
|
@Select("SELECT * FROM user_identities WHERE user_id = #{userId} AND deleted_at IS NULL LIMIT 1")
|
||||||
Optional<UserIdentity> findByUserId(@Param("userId") String userId);
|
Optional<UserIdentity> findByUserId(@Param("userId") String userId);
|
||||||
|
|
||||||
|
|||||||
+2
@@ -119,6 +119,8 @@ public class IdentityVerificationService {
|
|||||||
identity.setVerifiedAt(java.time.Instant.now());
|
identity.setVerifiedAt(java.time.Instant.now());
|
||||||
userIdentityMapper.insert(identity);
|
userIdentityMapper.insert(identity);
|
||||||
|
|
||||||
|
// V060 在实名记录写入事务中通过数据库原子计数器生成展示编号。
|
||||||
|
|
||||||
// 11. 更新用户表的认证状态标记
|
// 11. 更新用户表的认证状态标记
|
||||||
saveAuditLog(userId, null, "IDENTITY_VERIFY", "user", userId, null, null);
|
saveAuditLog(userId, null, "IDENTITY_VERIFY", "user", userId, null, null);
|
||||||
log.info("用户实名认证成功: userId={}, age={}, gender={}", userId, age, gender);
|
log.info("用户实名认证成功: userId={}, age={}, gender={}", userId, age, gender);
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ spring:
|
|||||||
wechat:
|
wechat:
|
||||||
app-id: ${WECHAT_APP_ID:}
|
app-id: ${WECHAT_APP_ID:}
|
||||||
app-secret: ${WECHAT_APP_SECRET:}
|
app-secret: ${WECHAT_APP_SECRET:}
|
||||||
|
mock:
|
||||||
|
openid: ${WECHAT_MOCK_OPENID:}
|
||||||
|
|
||||||
encryption:
|
encryption:
|
||||||
key: ${ENCRYPTION_KEY}
|
key: ${ENCRYPTION_KEY}
|
||||||
|
|||||||
@@ -92,3 +92,13 @@ spring.security:
|
|||||||
rate-limit:
|
rate-limit:
|
||||||
max-requests-per-window: 20
|
max-requests-per-window: 20
|
||||||
window-seconds: 60
|
window-seconds: 60
|
||||||
|
|
||||||
|
# 受控联系授权(ZC-MM-003 / B1 立项,canonical key 见 ContactAuthorizationConfig;治理登记 T06 config-register)
|
||||||
|
# 注意:代码缺省 enabled=false(fail-safe),生产显式开启;新环境漏配时机制整体关闭而非意外开放。
|
||||||
|
matchmaker:
|
||||||
|
contact:
|
||||||
|
enabled: true
|
||||||
|
approver-authorities: matchmaker.team.assign,matchmaker.assign
|
||||||
|
consent-deadline-hours: 72
|
||||||
|
default-validity-days: 7
|
||||||
|
retention-days: 365
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- V056: 受控联系授权表 matchmaker_contact_authorizations
|
||||||
|
-- (ZC-MM-003 / B1 例外通道立项,架构师设计 H4/G4)
|
||||||
|
--
|
||||||
|
-- 语义:红娘对分配对象发起联系方式/线下见面授权申请,经审批岗批准、
|
||||||
|
-- 用户单独明示同意(独立端点,无预同意参数)后方可生效;
|
||||||
|
-- 唯一披露出口为 ContactAuthorizationService.disclose(每次落敏感访问审计)。
|
||||||
|
--
|
||||||
|
-- 状态机(六态):
|
||||||
|
-- pending_approval → pending_consent(审批岗批准)
|
||||||
|
-- pending_consent → active(用户单独同意)/ rejected(用户拒绝)
|
||||||
|
-- active / pending_consent → expired(双态惰性收敛:有效期/同意窗口届满)
|
||||||
|
-- active → revoked(申请人或审批人撤销)
|
||||||
|
--
|
||||||
|
-- 幂等:CREATE TABLE / INDEX 全部 IF NOT EXISTS,可重放。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS matchmaker_contact_authorizations (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
operator_id UUID NOT NULL REFERENCES operators(id),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
channel VARCHAR(32) NOT NULL,
|
||||||
|
purpose VARCHAR(200) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'pending_approval',
|
||||||
|
approved_by UUID,
|
||||||
|
approved_at TIMESTAMPTZ,
|
||||||
|
user_consented_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
revoked_at TIMESTAMPTZ,
|
||||||
|
revoked_by UUID,
|
||||||
|
revoke_reason VARCHAR(500),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
CONSTRAINT chk_contact_auth_channel CHECK (channel IN ('phone', 'offline_meeting', 'full_contact')),
|
||||||
|
CONSTRAINT chk_contact_auth_status CHECK (status IN (
|
||||||
|
'pending_approval', 'pending_consent', 'active', 'rejected', 'expired', 'revoked'
|
||||||
|
))
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 同一 (红娘, 用户, 渠道) 同时最多一条 active(防重复生效授权)
|
||||||
|
-- H2 测试库以生成列 + 唯一索引等价实现(见 schema-h2.sql 注释)。
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_mm_contact_auth_active
|
||||||
|
ON matchmaker_contact_authorizations(operator_id, user_id, channel)
|
||||||
|
WHERE status = 'active';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_contact_auth_operator_status
|
||||||
|
ON matchmaker_contact_authorizations(operator_id, status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_contact_auth_user_status
|
||||||
|
ON matchmaker_contact_authorizations(user_id, status);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- V057 (ZC-MM-003 B1 运行时实测修复): audit_logs 增加 C 端用户主体维度
|
||||||
|
--
|
||||||
|
-- 背景:运行时实测(本地栈真 PostgreSQL)发现 audit_logs.operator_id 存在
|
||||||
|
-- FK → operators(id)(audit_logs_operator_id_fkey)。受控联系 C 端
|
||||||
|
-- (/contact-authorizations/**)以「用户身份」触发的审计(consent/decline 成功、
|
||||||
|
-- 越权 deny)把 userId 写进 operator_id → FK violation:
|
||||||
|
-- * consent/decline 成功路径:审计 insert 无兜底 → 事务回滚 → C 端同意必然 500;
|
||||||
|
-- * deny 路径:写失败被 catch 吞掉 → C 端越权尝试零审计(违反 DEC-006 全程留痕)。
|
||||||
|
-- H2 测试库 audit_logs 无 FK → 集成测试假绿(测试库缺约束类假绿第二例)。
|
||||||
|
--
|
||||||
|
-- 方案:审计主体双维度——operator 主体照旧写 operator_id(FK operators);
|
||||||
|
-- user 主体写 subject_user_id(FK users)且 operator_id 置 null(本就可空)。
|
||||||
|
-- DEC-006 第八节 actor 语义扩展:operator_id 与 subject_user_id 恰有一者非空。
|
||||||
|
|
||||||
|
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS subject_user_id UUID REFERENCES users(id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_logs_subject_user ON audit_logs (subject_user_id);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS display_number VARCHAR(32);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uk_users_display_number ON users(display_number)
|
||||||
|
WHERE display_number IS NOT NULL AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- 历史用户的编号由实名性别、注册日和当日同性交序生成;未实名或 gender=other 暂不生成。
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT u.id, i.gender, (u.created_at AT TIME ZONE 'Asia/Shanghai')::date AS registered_date,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY (u.created_at AT TIME ZONE 'Asia/Shanghai')::date, i.gender
|
||||||
|
ORDER BY u.created_at, u.id
|
||||||
|
) AS gender_rank
|
||||||
|
FROM users u
|
||||||
|
JOIN user_identities i ON i.user_id = u.id
|
||||||
|
WHERE u.display_number IS NULL
|
||||||
|
AND i.verification_status = 'verified'
|
||||||
|
AND i.gender IN ('male', 'female')
|
||||||
|
AND u.deleted_at IS NULL
|
||||||
|
)
|
||||||
|
UPDATE users u
|
||||||
|
SET display_number = '321181' || TO_CHAR(r.registered_date, 'YYYYMMDD') ||
|
||||||
|
LPAD((r.gender_rank * 2 - CASE WHEN r.gender = 'male' THEN 1 ELSE 0 END)::text, 4, '0')
|
||||||
|
FROM ranked r
|
||||||
|
WHERE u.id = r.id;
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
ALTER TABLE operators ADD COLUMN IF NOT EXISTS display_id VARCHAR(32);
|
||||||
|
|
||||||
|
-- 历史用户编号统一为 YH + 注册日期 + 当日性别序号(男奇女偶)。
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT u.id, i.gender,
|
||||||
|
(u.created_at AT TIME ZONE 'Asia/Shanghai')::date AS registered_date,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY (u.created_at AT TIME ZONE 'Asia/Shanghai')::date, i.gender
|
||||||
|
ORDER BY u.created_at, u.id
|
||||||
|
) AS gender_rank
|
||||||
|
FROM users u JOIN user_identities i ON i.user_id = u.id
|
||||||
|
WHERE u.display_number IS NOT NULL AND i.verification_status = 'verified'
|
||||||
|
AND i.gender IN ('male', 'female') AND u.deleted_at IS NULL
|
||||||
|
)
|
||||||
|
UPDATE users u SET display_number = 'YH' || TO_CHAR(r.registered_date, 'YYYYMMDD') ||
|
||||||
|
LPAD((r.gender_rank * 2 - CASE WHEN r.gender = 'male' THEN 1 ELSE 0 END)::text, 2, '0')
|
||||||
|
FROM ranked r WHERE u.id = r.id AND r.gender_rank <= 50;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uk_operators_display_id ON operators(display_id)
|
||||||
|
WHERE display_id IS NOT NULL AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- 运营人员:红娘前缀 HN,其他管理员/运营人员前缀 GL。
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT o.id,
|
||||||
|
CASE WHEN EXISTS (
|
||||||
|
SELECT 1 FROM operator_roles ort JOIN roles r ON r.id = ort.role_id
|
||||||
|
WHERE ort.operator_id = o.id AND r.code IN ('matchmaker', 'matchmaker_leader')
|
||||||
|
) THEN 'HN' ELSE 'GL' END AS prefix,
|
||||||
|
(o.created_at AT TIME ZONE 'Asia/Shanghai')::date AS created_date,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY (o.created_at AT TIME ZONE 'Asia/Shanghai')::date,
|
||||||
|
CASE WHEN EXISTS (
|
||||||
|
SELECT 1 FROM operator_roles ort JOIN roles r ON r.id = ort.role_id
|
||||||
|
WHERE ort.operator_id = o.id AND r.code IN ('matchmaker', 'matchmaker_leader')
|
||||||
|
) THEN 'HN' ELSE 'GL' END
|
||||||
|
ORDER BY o.created_at, o.id
|
||||||
|
) AS seq
|
||||||
|
FROM operators o WHERE o.display_id IS NULL AND o.deleted_at IS NULL
|
||||||
|
)
|
||||||
|
UPDATE operators o SET display_id = r.prefix || TO_CHAR(r.created_date, 'YYYYMMDD') || LPAD(r.seq::text, 2, '0')
|
||||||
|
FROM ranked r WHERE o.id = r.id AND r.seq <= 99;
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
-- 公开编号由 PostgreSQL 与领域写入同事务分配;所有 UUID 主外键保持不变。
|
||||||
|
CREATE TABLE public_display_id_counters (
|
||||||
|
prefix VARCHAR(2) NOT NULL,
|
||||||
|
local_date DATE NOT NULL,
|
||||||
|
sequence_group VARCHAR(8) NOT NULL DEFAULT '',
|
||||||
|
last_sequence INTEGER NOT NULL CHECK (last_sequence BETWEEN 1 AND 999),
|
||||||
|
PRIMARY KEY (prefix, local_date, sequence_group)
|
||||||
|
);
|
||||||
|
CREATE TABLE public_display_id_aliases (
|
||||||
|
entity_type VARCHAR(64) NOT NULL,
|
||||||
|
entity_id UUID NOT NULL,
|
||||||
|
old_display_id VARCHAR(64) NOT NULL,
|
||||||
|
new_display_id VARCHAR(13),
|
||||||
|
PRIMARY KEY (entity_type, entity_id, old_display_id)
|
||||||
|
);
|
||||||
|
INSERT INTO public_display_id_aliases(entity_type, entity_id, old_display_id)
|
||||||
|
SELECT 'users', id, display_number FROM users WHERE display_number IS NOT NULL
|
||||||
|
UNION ALL SELECT 'operators', id, display_id FROM operators WHERE display_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE FUNCTION public_next_display_id(p_prefix TEXT, p_date DATE, p_group TEXT DEFAULT '')
|
||||||
|
RETURNS TEXT LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE n INTEGER; step INTEGER; first_value INTEGER;
|
||||||
|
BEGIN
|
||||||
|
IF p_prefix NOT IN ('YH','HN','GL','RW','HD','FW','TJ','LX','FP','GJ','JB','ZF','YY')
|
||||||
|
OR p_date IS NULL OR p_group IS NULL
|
||||||
|
OR (p_prefix = 'YH' AND p_group NOT IN ('male','female'))
|
||||||
|
OR (p_prefix <> 'YH' AND p_group <> '') THEN
|
||||||
|
RAISE EXCEPTION '公开编号类型、日期或性别无效';
|
||||||
|
END IF;
|
||||||
|
step := CASE WHEN p_prefix = 'YH' THEN 2 ELSE 1 END;
|
||||||
|
first_value := CASE WHEN p_group = 'female' THEN 2 ELSE 1 END;
|
||||||
|
INSERT INTO public_display_id_counters(prefix, local_date, sequence_group, last_sequence)
|
||||||
|
VALUES (p_prefix, p_date, p_group, first_value)
|
||||||
|
ON CONFLICT (prefix, local_date, sequence_group) DO UPDATE
|
||||||
|
SET last_sequence = public_display_id_counters.last_sequence + step
|
||||||
|
WHERE public_display_id_counters.last_sequence + step <= 999
|
||||||
|
RETURNING last_sequence INTO n;
|
||||||
|
IF n IS NULL THEN RAISE EXCEPTION '当日公开编号容量已满'; END IF;
|
||||||
|
RETURN p_prefix || TO_CHAR(p_date, 'YYYYMMDD') || LPAD(n::TEXT, 3, '0');
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 历史数据预检先于回填;包含软删除记录,避免编号复用。
|
||||||
|
DO $$
|
||||||
|
DECLARE item RECORD; overflow_count INTEGER;
|
||||||
|
BEGIN
|
||||||
|
FOR item IN SELECT * FROM (VALUES
|
||||||
|
('activities','HD'),('review_tasks','RW'),('reports','JB'),
|
||||||
|
('matchmaker_services','FW'),('matchmaker_recommendations','TJ'),
|
||||||
|
('matchmaker_contact_authorizations','LX'),('matchmaker_assignments','FP'),
|
||||||
|
('matchmaker_followups','GJ'),('service_appointments','YY')) AS t(tab,prefix)
|
||||||
|
LOOP
|
||||||
|
EXECUTE FORMAT('SELECT COUNT(*) FROM (SELECT 1 FROM %I GROUP BY (created_at AT TIME ZONE ''Asia/Shanghai'')::date HAVING COUNT(*) > 999) s', item.tab) INTO overflow_count;
|
||||||
|
IF overflow_count > 0 THEN RAISE EXCEPTION '历史编号超出容量: %', item.tab; END IF;
|
||||||
|
EXECUTE FORMAT('ALTER TABLE %I ADD COLUMN display_id VARCHAR(13)', item.tab);
|
||||||
|
EXECUTE FORMAT('WITH ranked AS (SELECT id, (created_at AT TIME ZONE ''Asia/Shanghai'')::date AS d, ROW_NUMBER() OVER (PARTITION BY (created_at AT TIME ZONE ''Asia/Shanghai'')::date ORDER BY created_at,id) AS n FROM %I) UPDATE %I t SET display_id = %L || TO_CHAR(r.d,''YYYYMMDD'') || LPAD(r.n::text,3,''0'') FROM ranked r WHERE t.id=r.id', item.tab, item.tab, item.prefix);
|
||||||
|
EXECUTE FORMAT('ALTER TABLE %I ALTER COLUMN display_id SET NOT NULL', item.tab);
|
||||||
|
EXECUTE FORMAT('CREATE UNIQUE INDEX %I ON %I(display_id)', 'uk_' || item.tab || '_public_display_id', item.tab);
|
||||||
|
EXECUTE FORMAT('ALTER TABLE %I ADD CONSTRAINT %I CHECK (display_id ~ %L)', item.tab, 'ck_' || item.tab || '_public_display_id', '^' || item.prefix || '[0-9]{11}$');
|
||||||
|
EXECUTE FORMAT('INSERT INTO public_display_id_counters SELECT %L, (created_at AT TIME ZONE ''Asia/Shanghai'')::date, '''', MAX(RIGHT(display_id,3)::int) FROM %I GROUP BY (created_at AT TIME ZONE ''Asia/Shanghai'')::date', item.prefix, item.tab);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
WITH identities AS (
|
||||||
|
SELECT DISTINCT ON (user_id) user_id, gender FROM user_identities
|
||||||
|
WHERE verification_status='verified' AND gender IN ('male','female')
|
||||||
|
ORDER BY user_id, verified_at DESC NULLS LAST, id
|
||||||
|
), ranked AS (
|
||||||
|
SELECT u.id, i.gender, (u.created_at AT TIME ZONE 'Asia/Shanghai')::date AS d,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY (u.created_at AT TIME ZONE 'Asia/Shanghai')::date,i.gender ORDER BY u.created_at,u.id) * 2
|
||||||
|
- CASE WHEN i.gender='male' THEN 1 ELSE 0 END AS n
|
||||||
|
FROM users u JOIN identities i ON i.user_id=u.id
|
||||||
|
)
|
||||||
|
UPDATE users u SET display_number='YH'||TO_CHAR(r.d,'YYYYMMDD')||LPAD(r.n::text,3,'0')
|
||||||
|
FROM ranked r WHERE u.id=r.id AND r.n<=999;
|
||||||
|
|
||||||
|
-- 未实名者允许无编号;已有旧号不能静默丢失或截断。
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM users WHERE display_number IS NOT NULL AND display_number !~ '^YH[0-9]{11}$') THEN
|
||||||
|
RAISE EXCEPTION '用户历史编号或性别异常,需核对后再迁移';
|
||||||
|
END IF;
|
||||||
|
IF EXISTS (SELECT 1 FROM (
|
||||||
|
SELECT u.id, ROW_NUMBER() OVER (PARTITION BY (u.created_at AT TIME ZONE 'Asia/Shanghai')::date, i.gender ORDER BY u.created_at,u.id)*2-CASE WHEN i.gender='male' THEN 1 ELSE 0 END n
|
||||||
|
FROM users u JOIN (SELECT DISTINCT ON(user_id) user_id,gender FROM user_identities WHERE verification_status='verified' AND gender IN ('male','female') ORDER BY user_id,verified_at DESC NULLS LAST,id) i ON i.user_id=u.id
|
||||||
|
) x WHERE n>999) THEN RAISE EXCEPTION '历史用户编号容量不足'; END IF;
|
||||||
|
END $$;
|
||||||
|
CREATE UNIQUE INDEX uk_users_public_display_number ON users(display_number) WHERE display_number IS NOT NULL;
|
||||||
|
ALTER TABLE users ADD CONSTRAINT ck_users_public_display_number CHECK (display_number IS NULL OR display_number ~ '^YH[0-9]{11}$');
|
||||||
|
INSERT INTO public_display_id_counters
|
||||||
|
SELECT 'YH', (created_at AT TIME ZONE 'Asia/Shanghai')::date,
|
||||||
|
CASE WHEN RIGHT(display_number,3)::int % 2=1 THEN 'male' ELSE 'female' END,
|
||||||
|
MAX(RIGHT(display_number,3)::int)
|
||||||
|
FROM users WHERE display_number IS NOT NULL GROUP BY 2,3;
|
||||||
|
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT o.id, (o.created_at AT TIME ZONE 'Asia/Shanghai')::date AS d,
|
||||||
|
CASE WHEN EXISTS(SELECT 1 FROM operator_roles ort JOIN roles r ON r.id=ort.role_id WHERE ort.operator_id=o.id AND r.code IN ('matchmaker','matchmaker_leader')) THEN 'HN' ELSE 'GL' END AS prefix
|
||||||
|
FROM operators o
|
||||||
|
), numbered AS (
|
||||||
|
SELECT *, ROW_NUMBER() OVER (PARTITION BY d,prefix ORDER BY (SELECT created_at FROM operators WHERE id=ranked.id),id) AS n FROM ranked
|
||||||
|
)
|
||||||
|
UPDATE operators o SET display_id=r.prefix||TO_CHAR(r.d,'YYYYMMDD')||LPAD(r.n::text,3,'0') FROM numbered r WHERE o.id=r.id AND r.n<=999;
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS(SELECT 1 FROM operators WHERE display_id IS NULL OR display_id !~ '^(HN|GL)[0-9]{11}$') THEN RAISE EXCEPTION '工作人员历史编号容量或日期异常'; END IF;
|
||||||
|
END $$;
|
||||||
|
ALTER TABLE operators ALTER COLUMN display_id SET NOT NULL;
|
||||||
|
ALTER TABLE operators ADD CONSTRAINT ck_operators_public_display_id CHECK (display_id ~ '^(HN|GL)[0-9]{11}$');
|
||||||
|
CREATE UNIQUE INDEX uk_operators_public_display_id ON operators(display_id);
|
||||||
|
INSERT INTO public_display_id_counters SELECT LEFT(display_id,2), (created_at AT TIME ZONE 'Asia/Shanghai')::date,'',MAX(RIGHT(display_id,3)::int) FROM operators GROUP BY 1,2;
|
||||||
|
UPDATE public_display_id_aliases a SET new_display_id=u.display_number FROM users u WHERE a.entity_type='users' AND a.entity_id=u.id;
|
||||||
|
UPDATE public_display_id_aliases a SET new_display_id=o.display_id FROM operators o WHERE a.entity_type='operators' AND a.entity_id=o.id;
|
||||||
|
|
||||||
|
ALTER TABLE service_appointments ADD COLUMN referral_display_id VARCHAR(13);
|
||||||
|
ALTER TABLE activity_registrations ADD COLUMN referral_display_id VARCHAR(13);
|
||||||
|
ALTER TABLE matchmaker_followups ADD COLUMN referral_display_id VARCHAR(13);
|
||||||
|
WITH referrals AS (
|
||||||
|
SELECT 'service_appointments' tab,id,created_at FROM service_appointments WHERE source='matchmaker_referral'
|
||||||
|
UNION ALL SELECT 'activity_registrations',id,created_at FROM activity_registrations WHERE source='matchmaker_referral'
|
||||||
|
), numbered AS (
|
||||||
|
SELECT *, ROW_NUMBER() OVER(PARTITION BY (created_at AT TIME ZONE 'Asia/Shanghai')::date ORDER BY created_at,tab,id) n FROM referrals
|
||||||
|
)
|
||||||
|
INSERT INTO public_display_id_aliases(entity_type,entity_id,old_display_id,new_display_id)
|
||||||
|
SELECT tab,id,'referral:'||id::text,'ZF'||TO_CHAR(created_at AT TIME ZONE 'Asia/Shanghai','YYYYMMDD')||LPAD(n::text,3,'0') FROM numbered WHERE n<=999;
|
||||||
|
UPDATE service_appointments t SET referral_display_id=a.new_display_id FROM public_display_id_aliases a WHERE a.entity_type='service_appointments' AND a.entity_id=t.id;
|
||||||
|
UPDATE activity_registrations t SET referral_display_id=a.new_display_id FROM public_display_id_aliases a WHERE a.entity_type='activity_registrations' AND a.entity_id=t.id;
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM service_appointments WHERE source='matchmaker_referral' AND referral_display_id IS NULL)
|
||||||
|
OR EXISTS (SELECT 1 FROM activity_registrations WHERE source='matchmaker_referral' AND referral_display_id IS NULL) THEN RAISE EXCEPTION '历史转介编号容量不足'; END IF;
|
||||||
|
END $$;
|
||||||
|
INSERT INTO public_display_id_counters SELECT 'ZF',TO_DATE(SUBSTRING(new_display_id,3,8),'YYYYMMDD'),'',MAX(RIGHT(new_display_id,3)::int) FROM public_display_id_aliases WHERE new_display_id LIKE 'ZF%' GROUP BY 2;
|
||||||
|
|
||||||
|
CREATE FUNCTION public_assign_display_id() RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE prefix TEXT;
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP='UPDATE' THEN
|
||||||
|
IF OLD.display_id IS DISTINCT FROM NEW.display_id THEN RAISE EXCEPTION '公开编号不可更改'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
prefix:=TG_ARGV[0];
|
||||||
|
IF prefix='operator' THEN
|
||||||
|
prefix:=CASE WHEN EXISTS(SELECT 1 FROM operator_roles ort JOIN roles r ON r.id=ort.role_id WHERE ort.operator_id=NEW.id AND r.code IN ('matchmaker','matchmaker_leader')) THEN 'HN' ELSE 'GL' END;
|
||||||
|
END IF;
|
||||||
|
NEW.display_id:=public_next_display_id(prefix,(COALESCE(NEW.created_at,NOW()) AT TIME ZONE 'Asia/Shanghai')::date);
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
DO $$ DECLARE item RECORD; BEGIN
|
||||||
|
FOR item IN SELECT * FROM (VALUES ('activities','HD'),('review_tasks','RW'),('reports','JB'),('matchmaker_services','FW'),('matchmaker_recommendations','TJ'),('matchmaker_contact_authorizations','LX'),('matchmaker_assignments','FP'),('matchmaker_followups','GJ'),('service_appointments','YY'),('operators','operator')) t(tab,prefix)
|
||||||
|
LOOP EXECUTE FORMAT('CREATE TRIGGER assign_public_display_id BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION public_assign_display_id(%L)',item.tab,item.prefix); END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE FUNCTION public_assign_user_number() RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE d DATE; number TEXT;
|
||||||
|
BEGIN
|
||||||
|
IF NEW.verification_status='verified' AND NEW.gender IN ('male','female') THEN
|
||||||
|
SELECT display_number,(created_at AT TIME ZONE 'Asia/Shanghai')::date INTO number,d FROM users WHERE id=NEW.user_id FOR UPDATE;
|
||||||
|
IF number IS NULL THEN UPDATE users SET display_number=public_next_display_id('YH',d,NEW.gender) WHERE id=NEW.user_id; END IF;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER assign_public_user_number AFTER INSERT OR UPDATE ON user_identities FOR EACH ROW EXECUTE FUNCTION public_assign_user_number();
|
||||||
|
|
||||||
|
CREATE FUNCTION public_assign_referral_number() RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP='UPDATE' AND OLD.referral_display_id IS NOT NULL AND OLD.referral_display_id IS DISTINCT FROM NEW.referral_display_id THEN RAISE EXCEPTION '转介编号不可更改'; END IF;
|
||||||
|
IF NEW.source='matchmaker_referral' AND NEW.referral_display_id IS NULL THEN NEW.referral_display_id:=public_next_display_id('ZF',(COALESCE(NEW.created_at,NOW()) AT TIME ZONE 'Asia/Shanghai')::date); END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER assign_referral_number BEFORE INSERT OR UPDATE ON service_appointments FOR EACH ROW EXECUTE FUNCTION public_assign_referral_number();
|
||||||
|
CREATE TRIGGER assign_referral_number BEFORE INSERT OR UPDATE ON activity_registrations FOR EACH ROW EXECUTE FUNCTION public_assign_referral_number();
|
||||||
|
CREATE UNIQUE INDEX uk_appointments_referral_number ON service_appointments(referral_display_id);
|
||||||
|
CREATE UNIQUE INDEX uk_registrations_referral_number ON activity_registrations(referral_display_id);
|
||||||
|
CREATE UNIQUE INDEX uk_followups_referral_number ON matchmaker_followups(referral_display_id);
|
||||||
|
ALTER TABLE service_appointments ADD CONSTRAINT ck_appointments_referral_number CHECK (referral_display_id IS NULL OR referral_display_id ~ '^ZF[0-9]{11}$');
|
||||||
|
ALTER TABLE activity_registrations ADD CONSTRAINT ck_registrations_referral_number CHECK (referral_display_id IS NULL OR referral_display_id ~ '^ZF[0-9]{11}$');
|
||||||
|
ALTER TABLE matchmaker_followups ADD CONSTRAINT ck_followups_referral_number CHECK (referral_display_id IS NULL OR referral_display_id ~ '^ZF[0-9]{11}$');
|
||||||
|
|
||||||
|
CREATE FUNCTION public_keep_user_number() RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF OLD.display_number IS NOT NULL AND OLD.display_number IS DISTINCT FROM NEW.display_number THEN RAISE EXCEPTION '用户公开编号不可更改'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER keep_public_user_number BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION public_keep_user_number();
|
||||||
|
|
||||||
|
CREATE VIEW public_display_ids AS
|
||||||
|
SELECT id::text id,display_number display_id,'users'::text entity_type,NULL::text referral_display_id FROM users
|
||||||
|
UNION ALL SELECT id::text,display_id,'operators',NULL FROM operators
|
||||||
|
UNION ALL SELECT id::text,display_id,'activities',NULL FROM activities
|
||||||
|
UNION ALL SELECT id::text,display_id,'review_tasks',NULL FROM review_tasks
|
||||||
|
UNION ALL SELECT id::text,display_id,'reports',NULL FROM reports
|
||||||
|
UNION ALL SELECT id::text,display_id,'matchmaker_services',NULL FROM matchmaker_services
|
||||||
|
UNION ALL SELECT id::text,display_id,'matchmaker_recommendations',NULL FROM matchmaker_recommendations
|
||||||
|
UNION ALL SELECT id::text,display_id,'matchmaker_contact_authorizations',NULL FROM matchmaker_contact_authorizations
|
||||||
|
UNION ALL SELECT id::text,display_id,'matchmaker_assignments',NULL FROM matchmaker_assignments
|
||||||
|
UNION ALL SELECT id::text,display_id,'matchmaker_followups',referral_display_id FROM matchmaker_followups
|
||||||
|
UNION ALL SELECT id::text,display_id,'service_appointments',referral_display_id FROM service_appointments
|
||||||
|
UNION ALL SELECT id::text,referral_display_id,'activity_registrations',referral_display_id FROM activity_registrations WHERE referral_display_id IS NOT NULL;
|
||||||
+3
-3
@@ -73,7 +73,7 @@ class ActivityMutualConsentServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Gate: 双确认后形成 Match 并开启 Conversation(此前只打日志,Gate 失败)")
|
@DisplayName("Gate: 双确认后形成 Match 并开启 Conversation(此前只打日志,Gate 失败)")
|
||||||
void doubleConfirmCreatesMatchAndConversation() {
|
void doubleConfirmCreatesMatchWithoutConversation() {
|
||||||
// 第一阶段:建立互选同意记录(二阶段同意)
|
// 第一阶段:建立互选同意记录(二阶段同意)
|
||||||
consentService.createMutualConsent(activityId, userA, userB);
|
consentService.createMutualConsent(activityId, userA, userB);
|
||||||
|
|
||||||
@@ -95,8 +95,8 @@ class ActivityMutualConsentServiceTest {
|
|||||||
assertEquals(Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, match.getSource());
|
assertEquals(Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, match.getSource());
|
||||||
|
|
||||||
// 会话必须已开启(Gate:互选确认后双方可沟通)
|
// 会话必须已开启(Gate:互选确认后双方可沟通)
|
||||||
assertTrue(conversationMapper.findByMatchId(match.getId()).isPresent(),
|
assertTrue(conversationMapper.findByMatchId(match.getId()).isEmpty(),
|
||||||
"双确认后必须已开启 Conversation");
|
"双确认后不得创建用户聊天 Conversation");
|
||||||
|
|
||||||
// 溯源字段:consent 记录应绑定 match_id
|
// 溯源字段:consent 记录应绑定 match_id
|
||||||
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userA, userB).orElseThrow();
|
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userA, userB).orElseThrow();
|
||||||
|
|||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.danyang.match.platform.auth.provider;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class MockWechatLoginProviderTest {
|
||||||
|
@Test
|
||||||
|
void configuredDemoOpenidAlwaysResolvesToTheExistingDemoUser() {
|
||||||
|
MockWechatLoginProvider provider = new MockWechatLoginProvider();
|
||||||
|
ReflectionTestUtils.setField(provider, "configuredOpenid", "demo_openid_f06");
|
||||||
|
ReflectionTestUtils.setField(provider, "appId", "dev");
|
||||||
|
|
||||||
|
assertEquals("demo_openid_f06", provider.getCodeSession("wx-code-1").get("openid"));
|
||||||
|
assertEquals("demo_openid_f06", provider.getCodeSession("wx-code-2").get("openid"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,6 +71,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
@ActiveProfiles("test")
|
@ActiveProfiles("test")
|
||||||
@AutoConfigureMockMvc
|
@AutoConfigureMockMvc
|
||||||
|
@Disabled("用户端即时聊天已按产品方案下线")
|
||||||
class ChatPhase09IntegrationTest {
|
class ChatPhase09IntegrationTest {
|
||||||
|
|
||||||
@Autowired private MockMvc mockMvc;
|
@Autowired private MockMvc mockMvc;
|
||||||
|
|||||||
+1
-1
@@ -493,7 +493,7 @@ class EntityMigrationParityTest {
|
|||||||
|
|
||||||
for (Path f : entityFiles) {
|
for (Path f : entityFiles) {
|
||||||
String src = Files.readString(f);
|
String src = Files.readString(f);
|
||||||
Matcher tm = Pattern.compile("@TableName\\(\\s*\"([^\"]+)\"").matcher(src);
|
Matcher tm = Pattern.compile("@TableName\\(\\s*(?:value\\s*=\\s*)?\"([^\"]+)\"").matcher(src);
|
||||||
if (!tm.find()) {
|
if (!tm.find()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-1
@@ -36,7 +36,11 @@ class MigrationValidationTest {
|
|||||||
// V053 matchmaker_assignments 建表 + 存量回填;V054 matchmaker_leader 角色与团队分配权限
|
// V053 matchmaker_assignments 建表 + 存量回填;V054 matchmaker_leader 角色与团队分配权限
|
||||||
// ZC-MM-006(T01 审计字段扩展):V055 audit_logs 补 purpose_code / service_assignment_id /
|
// ZC-MM-006(T01 审计字段扩展):V055 audit_logs 补 purpose_code / service_assignment_id /
|
||||||
// actor_role_snapshot / request_trace_id 四列(全可空、存量不回填、幂等)
|
// actor_role_snapshot / request_trace_id 四列(全可空、存量不回填、幂等)
|
||||||
private static final int LATEST_MIGRATION = 55;
|
// ZC-MM-003(B1 例外通道立项):V056 matchmaker_contact_authorizations 受控联系授权表
|
||||||
|
// (六态状态机 + active 部分唯一索引)
|
||||||
|
// 用户展示编号:V058 users.display_number 及历史数据回填。
|
||||||
|
// 公共身份展示编号:V059 operators.display_id 及历史数据回填。
|
||||||
|
private static final int LATEST_MIGRATION = 60;
|
||||||
|
|
||||||
private static final String MIGRATION_DIR =
|
private static final String MIGRATION_DIR =
|
||||||
"backend/src/main/resources/db/migration/";
|
"backend/src/main/resources/db/migration/";
|
||||||
|
|||||||
+2
-1
@@ -94,6 +94,7 @@ class P0FixVerificationTest {
|
|||||||
// ==================== P0-1: Block不变量验证 ====================
|
// ==================== P0-1: Block不变量验证 ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@Disabled("用户端即时聊天已按产品方案下线")
|
||||||
@DisplayName("INV-003: Block后A不可向B发送消息")
|
@DisplayName("INV-003: Block后A不可向B发送消息")
|
||||||
void testBlockPreventsChat() {
|
void testBlockPreventsChat() {
|
||||||
relationshipService.like(userA, userB);
|
relationshipService.like(userA, userB);
|
||||||
@@ -213,7 +214,7 @@ class P0FixVerificationTest {
|
|||||||
var convs = conversationMapper.selectList(
|
var convs = conversationMapper.selectList(
|
||||||
new LambdaQueryWrapper<com.danyang.match.platform.chat.entity.Conversation>()
|
new LambdaQueryWrapper<com.danyang.match.platform.chat.entity.Conversation>()
|
||||||
.eq(com.danyang.match.platform.chat.entity.Conversation::getMatchId, match.getId()));
|
.eq(com.danyang.match.platform.chat.entity.Conversation::getMatchId, match.getId()));
|
||||||
assertFalse(convs.isEmpty(), "Match后应自动创建Conversation");
|
assertTrue(convs.isEmpty(), "Match 后不得自动创建 Conversation");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== P1-1: Required全字段过滤验证 ====================
|
// ==================== P1-1: Required全字段过滤验证 ====================
|
||||||
|
|||||||
+4
-4
@@ -95,7 +95,7 @@ class MatchmakerActionGuardTest {
|
|||||||
@Autowired private MatchmakerServiceService matchmakerServiceService;
|
@Autowired private MatchmakerServiceService matchmakerServiceService;
|
||||||
@Autowired private ReferralService referralService;
|
@Autowired private ReferralService referralService;
|
||||||
|
|
||||||
private static final String MATCHMAKER_OWNER = "op-ag-owner";
|
private static final String MATCHMAKER_OWNER = "00000000-0000-0000-0000-000000000103";
|
||||||
|
|
||||||
private String user;
|
private String user;
|
||||||
private String target;
|
private String target;
|
||||||
@@ -258,12 +258,12 @@ class MatchmakerActionGuardTest {
|
|||||||
// ==================== MM-ACTION-002:会话/关系开启无 operator 触达面 ====================
|
// ==================== MM-ACTION-002:会话/关系开启无 operator 触达面 ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("MM-ACTION-002(负向): operator token 打会话开启端点 → 403(match/conversation 仅用户路径)")
|
@DisplayName("MM-ACTION-002(负向): operator token 打已下线会话端点 → 410")
|
||||||
void operatorCannotOpenConversationFromMatch() throws Exception {
|
void operatorCannotOpenConversationFromMatch() throws Exception {
|
||||||
// 认证层即拒绝(hasRole("USER")),无需真实 match 存在
|
// 用户间会话已全局下线,先于角色鉴权返回 CHAT_DISABLED。
|
||||||
mockMvc.perform(post("/conversations/from-match/{matchId}", "no-such-match")
|
mockMvc.perform(post("/conversations/from-match/{matchId}", "no-such-match")
|
||||||
.header("Authorization", "Bearer " + operatorToken))
|
.header("Authorization", "Bearer " + operatorToken))
|
||||||
.andExpect(status().isForbidden());
|
.andExpect(status().isGone());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== MM-ACTION-003:must-confirm 语义锁定 ====================
|
// ==================== MM-ACTION-003:must-confirm 语义锁定 ====================
|
||||||
|
|||||||
+2
-1
@@ -202,7 +202,8 @@ class MatchmakerAssignmentA1Test {
|
|||||||
// standalone MockMvc:仅注册真实控制器路由,验证 /claim 已不在映射中(D3 决策)
|
// standalone MockMvc:仅注册真实控制器路由,验证 /claim 已不在映射中(D3 决策)
|
||||||
MatchmakerServiceService stubService = Mockito.mock(MatchmakerServiceService.class);
|
MatchmakerServiceService stubService = Mockito.mock(MatchmakerServiceService.class);
|
||||||
MockMvc mockMvc = MockMvcBuilders
|
MockMvc mockMvc = MockMvcBuilders
|
||||||
.standaloneSetup(new MatchmakerOperatorController(stubService))
|
.standaloneSetup(new MatchmakerOperatorController(stubService,
|
||||||
|
org.mockito.Mockito.mock(com.danyang.match.platform.matchmaker.service.MatchmakerManagementService.class)))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
mockMvc.perform(post("/operator/matchmaker/services/some-id/claim"))
|
mockMvc.perform(post("/operator/matchmaker/services/some-id/claim"))
|
||||||
|
|||||||
+535
@@ -0,0 +1,535 @@
|
|||||||
|
package com.danyang.match.platform.matchmaker;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
|
import com.danyang.match.platform.audit.entity.SensitiveAccessLog;
|
||||||
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import com.danyang.match.platform.audit.mapper.SensitiveAccessLogMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.entity.MatchmakerAssignment;
|
||||||
|
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||||
|
import com.danyang.match.platform.matchmaker.entity.MatchmakerServiceRecord;
|
||||||
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerAssignmentMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerContactAuthorizationMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerServiceMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.service.ContactAuthorizationService;
|
||||||
|
import com.danyang.match.platform.matchmaker.service.MatchmakerAssignmentService;
|
||||||
|
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.user.entity.User;
|
||||||
|
import com.danyang.match.platform.user.mapper.UserMapper;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.MDC;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ZC-MM-003 / B1 立项验收:受控联系授权机制(V056 + Policy/Service 六操作)。
|
||||||
|
*
|
||||||
|
* <p>覆盖:
|
||||||
|
* <ul>
|
||||||
|
* <li>正例全生命周期:request → approve → consent → disclose(phone 返回 +
|
||||||
|
* SensitiveAccessLog success 行)→ revoke → 再 disclose 404;</li>
|
||||||
|
* <li>负向×6:无分配申请 403 / 非审批岗 approve 403 / 未同意 disclose 404 /
|
||||||
|
* decline 后 404 / 过期后 404+审计 / 非本人 consent 403;</li>
|
||||||
|
* <li>状态机非法转换 CONFLICT(approve 二次 / 越状态 consent / 终态 revoke);</li>
|
||||||
|
* <li>purpose_code 断言:request/approve/consent/disclose/revoke 审计行均含
|
||||||
|
* matchmaker.contact.* + service_assignment_id + request_trace_id。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
class MatchmakerContactAuthorizationTest {
|
||||||
|
|
||||||
|
@Autowired private ContactAuthorizationService contactAuthorizationService;
|
||||||
|
@Autowired private MatchmakerAssignmentService assignmentService;
|
||||||
|
@Autowired private MatchmakerContactAuthorizationMapper authorizationMapper;
|
||||||
|
@Autowired private MatchmakerAssignmentMapper assignmentMapper;
|
||||||
|
@Autowired private MatchmakerServiceMapper serviceMapper;
|
||||||
|
@Autowired private OperatorMapper operatorMapper;
|
||||||
|
@Autowired private UserMapper userMapper;
|
||||||
|
@Autowired private AuditLogMapper auditLogMapper;
|
||||||
|
@Autowired private SensitiveAccessLogMapper sensitiveAccessLogMapper;
|
||||||
|
@Autowired private org.mybatis.spring.SqlSessionTemplate sqlSessionTemplate;
|
||||||
|
|
||||||
|
private String mmOwner; // 分配持有人(红娘,org X)
|
||||||
|
private String leaderA; // 组长,org X(team.assign 审批岗)
|
||||||
|
private String leaderY; // 组长,org Y(跨组织)
|
||||||
|
private String user;
|
||||||
|
private String userPhone;
|
||||||
|
private String assignmentId;
|
||||||
|
|
||||||
|
private static final String ORG_X = "55555555-5555-5555-5555-555555555551";
|
||||||
|
private static final String ORG_Y = "55555555-5555-5555-5555-555555555552";
|
||||||
|
private static final Set<String> P_LEADER = Set.of("matchmaker.view", "matchmaker.team.assign");
|
||||||
|
private static final Set<String> P_PLATFORM = Set.of("matchmaker.view", "matchmaker.assign");
|
||||||
|
/** 双岗:team.assign(主审)+ assign(兜底)——按分层规则含 assign 即兜底全量 */
|
||||||
|
private static final Set<String> P_DUAL =
|
||||||
|
Set.of("matchmaker.view", "matchmaker.team.assign", "matchmaker.assign");
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
mmOwner = createOperator("联系授权红娘", ORG_X);
|
||||||
|
leaderA = createOperator("联系授权组长X", ORG_X);
|
||||||
|
leaderY = createOperator("联系授权组长Y", ORG_Y);
|
||||||
|
userPhone = "13800001234";
|
||||||
|
user = createUser(userPhone);
|
||||||
|
|
||||||
|
// 前置:红娘持分配
|
||||||
|
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
||||||
|
svc.setUserId(user);
|
||||||
|
svc.setServiceType(Constants.MATCHMAKER_SERVICE_TYPE_RECOMMEND_PARTNER);
|
||||||
|
svc.setDescription("联系授权测试服务单");
|
||||||
|
svc.setStatus(Constants.MATCHMAKER_STATUS_SUBMITTED);
|
||||||
|
svc.setAssignedOperatorId(mmOwner);
|
||||||
|
serviceMapper.insert(svc);
|
||||||
|
MatchmakerAssignment assignment = assignmentService.create(leaderA, true,
|
||||||
|
user, mmOwner, svc.getId(), "联系授权前置分配", null);
|
||||||
|
assignmentId = assignment.getId();
|
||||||
|
MDC.put("requestId", "contacttest0001");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void cleanUp() {
|
||||||
|
MDC.remove("requestId");
|
||||||
|
org.springframework.security.core.context.SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 数据构造 ====================
|
||||||
|
|
||||||
|
private String createOperator(String name, String organizationId) {
|
||||||
|
Operator op = new Operator();
|
||||||
|
op.setName(name);
|
||||||
|
op.setOrganizationId(organizationId);
|
||||||
|
op.setUsername("ca_" + name + "_" + System.nanoTime());
|
||||||
|
op.setPasswordHash("test-hash");
|
||||||
|
op.setStatus("active");
|
||||||
|
operatorMapper.insert(op);
|
||||||
|
return op.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createUser(String phone) {
|
||||||
|
User u = new User();
|
||||||
|
u.setWechatOpenid("ca_user_" + System.nanoTime());
|
||||||
|
u.setAccountStatus(Constants.ACCOUNT_STATUS_NORMAL);
|
||||||
|
u.setPhone(phone);
|
||||||
|
userMapper.insert(u);
|
||||||
|
return u.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private long deniedAudits(String operatorId, String resourceId) {
|
||||||
|
return auditLogMapper.selectCount(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, "DATA_SCOPE_DENIED")
|
||||||
|
.eq(AuditLog::getOperatorId, operatorId)
|
||||||
|
.eq(AuditLog::getResourceId, resourceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AuditLog latestContactAudit(String action, String authId) {
|
||||||
|
return auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, action)
|
||||||
|
.eq(AuditLog::getResourceId, authId)
|
||||||
|
.orderByDesc(AuditLog::getCreatedAt))
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 正例:全生命周期 ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 正例: request→approve→consent→disclose(phone+敏感审计)→revoke→再 disclose 404")
|
||||||
|
void fullLifecycleRequestApproveConsentDiscloseRevoke() {
|
||||||
|
// ① request → pending_approval
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "安排线下初次见面,需电话沟通时间地点");
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_PENDING_APPROVAL, auth.getStatus());
|
||||||
|
assertNotNull(auth.getId());
|
||||||
|
assertNotNull(auth.getExpiresAt(), "pending 期 expires_at 承载同意窗口上界");
|
||||||
|
|
||||||
|
// ② approve(组长 X,team.assign)→ pending_consent
|
||||||
|
MatchmakerContactAuthorization approved = contactAuthorizationService.approve(
|
||||||
|
auth.getId(), leaderA, P_LEADER);
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT, approved.getStatus());
|
||||||
|
assertEquals(leaderA, approved.getApprovedBy());
|
||||||
|
|
||||||
|
// ③ consent(用户本人)→ active,有效期 = consent + 7d
|
||||||
|
Instant beforeConsent = Instant.now();
|
||||||
|
MatchmakerContactAuthorization consented = contactAuthorizationService.consent(auth.getId(), user);
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_ACTIVE, consented.getStatus());
|
||||||
|
assertNotNull(consented.getUserConsentedAt());
|
||||||
|
long days = ChronoUnit.HOURS.between(beforeConsent, consented.getExpiresAt());
|
||||||
|
assertTrue(days >= 24 * 7 - 1 && days <= 24 * 7 + 1,
|
||||||
|
"有效期应为 consent + 7 天,实际小时数=" + days);
|
||||||
|
|
||||||
|
// ④ disclose(H4 唯一出口)→ phone + SensitiveAccessLog success 行
|
||||||
|
Map<String, Object> disclosed = contactAuthorizationService.disclose(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话约定见面时间");
|
||||||
|
assertEquals(userPhone, disclosed.get("phone"));
|
||||||
|
assertEquals(auth.getId(), disclosed.get("authorizationId"));
|
||||||
|
assertNotNull(disclosed.get("disclosedAt"));
|
||||||
|
// H4 唯一披露出口返回体必须收敛为恰好三键(phone/disclosedAt/authorizationId),
|
||||||
|
// 严禁夹带任何其他字段(含联系方式或用户资料面)——守卫①对本文件白名单放行,
|
||||||
|
// 键收敛只能由本行为断言锁定(独立验收补充,QA 严过关)。
|
||||||
|
assertEquals(Set.of("phone", "disclosedAt", "authorizationId"),
|
||||||
|
disclosed.keySet(), "disclose 返回体必须恰好三键,不得夹带额外字段");
|
||||||
|
List<SensitiveAccessLog> accessRows = sensitiveAccessLogMapper.selectList(
|
||||||
|
new LambdaQueryWrapper<SensitiveAccessLog>()
|
||||||
|
.eq(SensitiveAccessLog::getDataType, "user_phone_disclosure")
|
||||||
|
.eq(SensitiveAccessLog::getAccessTarget, auth.getId()));
|
||||||
|
assertEquals(1, accessRows.size(), "披露必须落 user_phone_disclosure 敏感访问行");
|
||||||
|
assertEquals("success", accessRows.get(0).getAccessResult());
|
||||||
|
assertEquals(mmOwner, accessRows.get(0).getOperatorId());
|
||||||
|
|
||||||
|
// ⑤ revoke(申请人)→ revoked
|
||||||
|
contactAuthorizationService.revoke(auth.getId(), mmOwner, "服务关系结束");
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_REVOKED,
|
||||||
|
authorizationMapper.findById(auth.getId()).orElseThrow().getStatus());
|
||||||
|
|
||||||
|
// ⑥ 再 disclose → 404 + DATA_SCOPE_DENIED 审计(G4 防探测)
|
||||||
|
long before = deniedAudits(mmOwner, user);
|
||||||
|
BusinessException e = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.disclose(mmOwner, user,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "再次获取"));
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e.getCode());
|
||||||
|
assertEquals("服务不存在", e.getMessage());
|
||||||
|
assertEquals(before + 1, deniedAudits(mmOwner, user), "失效后披露必须 404 化拒绝并落审计");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== purpose_code 审计断言 ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 审计: request/approve/consent/disclose/revoke 各落行含 matchmaker.contact.* + assignment_id + trace")
|
||||||
|
void auditRowsCarryPurposeCodeAssignmentIdAndTraceId() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通服务安排");
|
||||||
|
contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER);
|
||||||
|
contactAuthorizationService.consent(auth.getId(), user);
|
||||||
|
contactAuthorizationService.disclose(mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "联系用户");
|
||||||
|
contactAuthorizationService.revoke(auth.getId(), mmOwner, "测试撤销");
|
||||||
|
|
||||||
|
String[][] expected = {
|
||||||
|
{Constants.CONTACT_AUDIT_ACTION_REQUEST, "matchmaker.contact.request"},
|
||||||
|
{Constants.CONTACT_AUDIT_ACTION_APPROVE, "matchmaker.contact.approve"},
|
||||||
|
{Constants.CONTACT_AUDIT_ACTION_CONSENT, "matchmaker.contact.consent"},
|
||||||
|
{Constants.CONTACT_AUDIT_ACTION_DISCLOSE, "matchmaker.contact.disclose"},
|
||||||
|
{Constants.CONTACT_AUDIT_ACTION_REVOKE, "matchmaker.contact.revoke"},
|
||||||
|
};
|
||||||
|
for (String[] pair : expected) {
|
||||||
|
AuditLog audit = latestContactAudit(pair[0], auth.getId());
|
||||||
|
assertNotNull(audit, pair[0] + " 审计行必须存在");
|
||||||
|
assertEquals(pair[1], audit.getPurposeCode(), pair[0] + " purpose_code 必须落库");
|
||||||
|
assertEquals("contacttest0001", audit.getRequestTraceId(),
|
||||||
|
pair[0] + " 必须携带请求追踪 ID");
|
||||||
|
assertFalse(String.valueOf(audit.getAfterData()).contains(userPhone),
|
||||||
|
pair[0] + " 审计内容不得含 phone");
|
||||||
|
// afterData 必须是合法 JSON(PG audit_logs.after_data 为 jsonb 严格解析;
|
||||||
|
// H2 CLOB 不校验——裸 key=value 拼接在测试侧假绿、生产侧 500,此断言为运行时事故回归守卫)
|
||||||
|
com.fasterxml.jackson.databind.JsonNode afterJson =
|
||||||
|
assertDoesNotThrow(() -> new com.fasterxml.jackson.databind.ObjectMapper()
|
||||||
|
.readTree(String.valueOf(audit.getAfterData())),
|
||||||
|
pair[0] + " afterData 必须可 JSON 解析(PG jsonb 严格校验口径)");
|
||||||
|
assertTrue(afterJson.isObject(), pair[0] + " afterData 必须是 JSON 对象");
|
||||||
|
// V057 主体维度分流:C 端用户动作(consent)写 subject_user_id 且 operator_id=null;
|
||||||
|
// operator 动作写 operator_id + service_assignment_id。混写必撞 audit_logs_operator_id_fkey。
|
||||||
|
if (Constants.CONTACT_AUDIT_ACTION_CONSENT.equals(pair[0])) {
|
||||||
|
assertNull(audit.getOperatorId(), pair[0] + " 用户主体审计 operator_id 必须为 null");
|
||||||
|
assertEquals(user, audit.getSubjectUserId(), pair[0] + " 必须写 subject_user_id 维度");
|
||||||
|
assertNull(audit.getServiceAssignmentId(), pair[0] + " 用户动作无分配关联");
|
||||||
|
} else {
|
||||||
|
assertEquals(assignmentId, audit.getServiceAssignmentId(),
|
||||||
|
pair[0] + " 必须关联 service_assignment_id");
|
||||||
|
assertNull(audit.getSubjectUserId(), pair[0] + " operator 审计不得写 subject_user_id");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 运行时回归:拒绝审计独立事务(REQUIRES_NEW) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行时实测缺陷回归(判别性用例):NOT_SUPPORTED 挂起测试事务,让 service 跑真事务——
|
||||||
|
* deny 抛异常触发业务回滚后,拒绝审计必须仍然落库(REQUIRES_NEW 独立提交)。
|
||||||
|
* 旧实现(同事务写入)在本用例必红:回滚吞掉审计。类级 @Transactional 用例对此结构性假绿
|
||||||
|
* (测试事务内可见未提交行),故本用例独立夹具+显式清理。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED)
|
||||||
|
@DisplayName("B1 运行时回归: 业务事务回滚不得吞掉拒绝审计(REQUIRES_NEW 独立提交)")
|
||||||
|
void denyAuditSurvivesBusinessRollback() {
|
||||||
|
String opOwner = createOperator("独立事务红娘", ORG_X);
|
||||||
|
String opLeader = createOperator("独立事务组长", ORG_X);
|
||||||
|
String ownUser = createUser("13811112222");
|
||||||
|
String otherUser = createUser("13811113333");
|
||||||
|
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
||||||
|
svc.setUserId(ownUser);
|
||||||
|
svc.setServiceType(Constants.MATCHMAKER_SERVICE_TYPE_RECOMMEND_PARTNER);
|
||||||
|
svc.setDescription("独立事务验证服务单");
|
||||||
|
svc.setStatus(Constants.MATCHMAKER_STATUS_SUBMITTED);
|
||||||
|
svc.setAssignedOperatorId(opOwner);
|
||||||
|
serviceMapper.insert(svc);
|
||||||
|
MatchmakerAssignment assignment = assignmentService.create(opLeader, true,
|
||||||
|
ownUser, opOwner, svc.getId(), "独立事务前置分配", null);
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
opOwner, ownUser, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
contactAuthorizationService.approve(auth.getId(), opLeader, P_LEADER);
|
||||||
|
try {
|
||||||
|
assertThrows(AccessDeniedException.class,
|
||||||
|
() -> contactAuthorizationService.consent(auth.getId(), otherUser));
|
||||||
|
AuditLog denyAudit = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, "DATA_SCOPE_DENIED")
|
||||||
|
.eq(AuditLog::getSubjectUserId, otherUser)
|
||||||
|
.eq(AuditLog::getResourceId, auth.getId()))
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
assertNotNull(denyAudit, "业务回滚后拒绝审计必须独立事务落库(REQUIRES_NEW)");
|
||||||
|
} finally {
|
||||||
|
// 显式清理(本用例数据真实提交,不随测试事务回滚)
|
||||||
|
auditLogMapper.delete(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getSubjectUserId, otherUser));
|
||||||
|
authorizationMapper.deleteById(auth.getId());
|
||||||
|
assignmentMapper.deleteById(assignment.getId());
|
||||||
|
serviceMapper.deleteById(svc.getId());
|
||||||
|
operatorMapper.deleteById(opOwner);
|
||||||
|
operatorMapper.deleteById(opLeader);
|
||||||
|
userMapper.deleteById(ownUser);
|
||||||
|
userMapper.deleteById(otherUser);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 负向×6 ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向①: 未持分配申请 → 403 + DATA_SCOPE_DENIED 审计")
|
||||||
|
void requestWithoutAssignmentDenied403() {
|
||||||
|
String outsiderUser = createUser("13900009999");
|
||||||
|
long before = deniedAudits(mmOwner, outsiderUser);
|
||||||
|
assertThrows(AccessDeniedException.class,
|
||||||
|
() -> contactAuthorizationService.request(mmOwner, outsiderUser,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "无分配申请"),
|
||||||
|
"未持分配的红娘不得发起授权申请");
|
||||||
|
assertEquals(before + 1, deniedAudits(mmOwner, outsiderUser));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向②: 非审批岗 approve → 403(权限码动态判定)")
|
||||||
|
void nonApproverCannotApprove() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
long before = deniedAudits(leaderA, auth.getId());
|
||||||
|
// leaderA 只有 matchmaker.view(无 team.assign/assign)→ 非审批岗
|
||||||
|
assertThrows(AccessDeniedException.class,
|
||||||
|
() -> contactAuthorizationService.approve(auth.getId(), leaderA, Set.of("matchmaker.view")),
|
||||||
|
"非审批岗不得 approve");
|
||||||
|
sqlSessionTemplate.clearCache();
|
||||||
|
assertEquals(before + 1, deniedAudits(leaderA, auth.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向③: 仅 team.assign 组长审他组织 → 403 + DATA_SCOPE_DENIED 审计(分层·主审岗)")
|
||||||
|
void crossOrgLeaderCannotApprove() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
long before = deniedAudits(leaderY, auth.getId());
|
||||||
|
assertThrows(AccessDeniedException.class,
|
||||||
|
() -> contactAuthorizationService.approve(auth.getId(), leaderY, P_LEADER),
|
||||||
|
"跨组织组长(仅主审岗)不得审批");
|
||||||
|
sqlSessionTemplate.clearCache();
|
||||||
|
assertEquals(before + 1, deniedAudits(leaderY, auth.getId()),
|
||||||
|
"跨组织组长审批拒绝必须落 DATA_SCOPE_DENIED 审计");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 分层审批语义(用户裁决①:组长主审 + 管理员兜底) ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("分层正例①: 仅 assign 管理员(兜底岗)审批跨组织申请 → 成功 + 审计行")
|
||||||
|
void platformFallbackApproverCanApproveCrossOrg() {
|
||||||
|
// 管理员挂任意组织(org Y)——兜底岗不做组织校验
|
||||||
|
String admin = createOperator("联系授权平台管理员", ORG_Y);
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "跨组织管理员兜底审批");
|
||||||
|
MatchmakerContactAuthorization approved = contactAuthorizationService.approve(
|
||||||
|
auth.getId(), admin, P_PLATFORM);
|
||||||
|
// 结果码断言:approve 成功 → pending_consent
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT, approved.getStatus());
|
||||||
|
assertEquals(admin, approved.getApprovedBy());
|
||||||
|
// 审计行断言:approve 审计行存在且 purpose_code 正确、操作者=管理员
|
||||||
|
AuditLog audit = latestContactAudit(Constants.CONTACT_AUDIT_ACTION_APPROVE, auth.getId());
|
||||||
|
assertNotNull(audit, "兜底审批成功必须落 MATCHMAKER_CONTACT_APPROVE 审计行");
|
||||||
|
assertEquals("matchmaker.contact.approve", audit.getPurposeCode());
|
||||||
|
assertEquals(admin, audit.getOperatorId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("分层正例②: 平台直属组长(org NULL)审平台直属红娘申请 → 成功 + 审计行")
|
||||||
|
void platformDirectLeaderCanApproveNullOrgMatchmaker() {
|
||||||
|
// 平台直属链路:org=NULL 组长 + org=NULL 红娘(NULL=NULL 视为平台直属,现状⑤维持)
|
||||||
|
String leaderN = createOperator("平台直属组长", null);
|
||||||
|
String mmNull = createOperator("平台直属红娘", null);
|
||||||
|
String userNull = createUser("13600009998");
|
||||||
|
MatchmakerServiceRecord svc = new MatchmakerServiceRecord();
|
||||||
|
svc.setUserId(userNull);
|
||||||
|
svc.setServiceType(Constants.MATCHMAKER_SERVICE_TYPE_RECOMMEND_PARTNER);
|
||||||
|
svc.setDescription("平台直属联系授权测试服务单");
|
||||||
|
svc.setStatus(Constants.MATCHMAKER_STATUS_SUBMITTED);
|
||||||
|
svc.setAssignedOperatorId(mmNull);
|
||||||
|
serviceMapper.insert(svc);
|
||||||
|
// 主审组长(hasGlobalAssign=false)走 NULL=NULL 组织校验创建分配
|
||||||
|
assignmentService.create(leaderN, false, userNull, mmNull, svc.getId(),
|
||||||
|
"平台直属分配", null);
|
||||||
|
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmNull, userNull, Constants.CONTACT_CHANNEL_PHONE, "平台直属电话沟通");
|
||||||
|
MatchmakerContactAuthorization approved = contactAuthorizationService.approve(
|
||||||
|
auth.getId(), leaderN, P_LEADER);
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT, approved.getStatus());
|
||||||
|
assertEquals(leaderN, approved.getApprovedBy());
|
||||||
|
AuditLog audit = latestContactAudit(Constants.CONTACT_AUDIT_ACTION_APPROVE, auth.getId());
|
||||||
|
assertNotNull(audit, "平台直属组长审批成功必须落 MATCHMAKER_CONTACT_APPROVE 审计行");
|
||||||
|
assertEquals("matchmaker.contact.approve", audit.getPurposeCode());
|
||||||
|
assertEquals(leaderN, audit.getOperatorId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("分层正例③: 双岗(team.assign+assign)审他组织 → 含 assign 即兜底全量 + 审计行")
|
||||||
|
void dualRoleApproverFallsBackToFullScope() {
|
||||||
|
// 用户裁决①分层规则的既定语义:兜底岗键固定 matchmaker.assign,
|
||||||
|
// 双岗持有者按兜底全量处理(不做组织校验)——权限面以最高档收敛,不叠加受限。
|
||||||
|
String dual = createOperator("双岗审批人", ORG_Y);
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "双岗跨组织审批");
|
||||||
|
MatchmakerContactAuthorization approved = contactAuthorizationService.approve(
|
||||||
|
auth.getId(), dual, P_DUAL);
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_PENDING_CONSENT, approved.getStatus());
|
||||||
|
assertEquals(dual, approved.getApprovedBy());
|
||||||
|
AuditLog audit = latestContactAudit(Constants.CONTACT_AUDIT_ACTION_APPROVE, auth.getId());
|
||||||
|
assertNotNull(audit, "双岗兜底审批成功必须落 MATCHMAKER_CONTACT_APPROVE 审计行");
|
||||||
|
assertEquals("matchmaker.contact.approve", audit.getPurposeCode());
|
||||||
|
assertEquals(dual, audit.getOperatorId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向④: 未同意 disclose → 404 + DATA_SCOPE_DENIED(G4 防探测)")
|
||||||
|
void discloseBeforeConsentNotFound() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER);
|
||||||
|
|
||||||
|
long before = deniedAudits(mmOwner, user);
|
||||||
|
BusinessException e = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.disclose(mmOwner, user,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "尚未同意"));
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e.getCode());
|
||||||
|
assertEquals("服务不存在", e.getMessage());
|
||||||
|
assertEquals(before + 1, deniedAudits(mmOwner, user));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向⑤: decline 后 disclose → 404;过期后 disclose → 404 + 审计")
|
||||||
|
void discloseAfterDeclineOrExpiryNotFound() {
|
||||||
|
// decline 后
|
||||||
|
MatchmakerContactAuthorization auth1 = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通A");
|
||||||
|
contactAuthorizationService.approve(auth1.getId(), leaderA, P_LEADER);
|
||||||
|
contactAuthorizationService.decline(auth1.getId(), user);
|
||||||
|
BusinessException e1 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.disclose(mmOwner, user,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "被拒后披露"));
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e1.getCode());
|
||||||
|
|
||||||
|
// 过期后(直接注入已过期的 expires_at,模拟窗口/有效期届满)
|
||||||
|
MatchmakerContactAuthorization auth2 = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通B");
|
||||||
|
contactAuthorizationService.approve(auth2.getId(), leaderA, P_LEADER);
|
||||||
|
contactAuthorizationService.consent(auth2.getId(), user);
|
||||||
|
MatchmakerContactAuthorization expired = authorizationMapper.findById(auth2.getId()).orElseThrow();
|
||||||
|
expired.setExpiresAt(Instant.now().minusSeconds(60));
|
||||||
|
authorizationMapper.updateById(expired);
|
||||||
|
|
||||||
|
long before = deniedAudits(mmOwner, user);
|
||||||
|
BusinessException e2 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.disclose(mmOwner, user,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "过期后披露"));
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e2.getCode());
|
||||||
|
assertEquals(before + 1, deniedAudits(mmOwner, user), "过期披露必须 404 化拒绝并落审计");
|
||||||
|
// 惰性收敛必须落库
|
||||||
|
assertEquals(Constants.CONTACT_AUTH_STATUS_EXPIRED,
|
||||||
|
authorizationMapper.findById(auth2.getId()).orElseThrow().getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 负向⑥: 非本人 consent → 403")
|
||||||
|
void nonOwnerCannotConsent() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER);
|
||||||
|
|
||||||
|
String otherUser = createUser("13700009999");
|
||||||
|
assertThrows(AccessDeniedException.class,
|
||||||
|
() -> contactAuthorizationService.consent(auth.getId(), otherUser),
|
||||||
|
"仅本人可同意授权");
|
||||||
|
// V057:C 端越权尝试的 deny 审计必须落 subject_user_id 维度
|
||||||
|
//(此前写 operator_id 维度撞 FK 被吞 → 生产零审计)
|
||||||
|
AuditLog denyAudit = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, "DATA_SCOPE_DENIED")
|
||||||
|
.eq(AuditLog::getSubjectUserId, otherUser)
|
||||||
|
.eq(AuditLog::getResourceId, auth.getId())
|
||||||
|
.orderByDesc(AuditLog::getCreatedAt))
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
assertNotNull(denyAudit, "非本人 consent 的越权尝试必须落 DATA_SCOPE_DENIED(subject_user_id 维度)");
|
||||||
|
assertNull(denyAudit.getOperatorId(), "用户主体 deny 审计 operator_id 必须为 null");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 状态机非法转换 CONFLICT ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 状态机: approve 二次 / 越状态 consent / 终态 revoke 一律 CONFLICT")
|
||||||
|
void illegalTransitionsAreConflict() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
|
||||||
|
// pending_approval 直接 consent → CONFLICT
|
||||||
|
BusinessException e1 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.consent(auth.getId(), user));
|
||||||
|
assertEquals(ApiResponseCode.CONFLICT, e1.getCode());
|
||||||
|
|
||||||
|
// approve → pending_consent 后再 approve → CONFLICT
|
||||||
|
contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER);
|
||||||
|
BusinessException e2 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER));
|
||||||
|
assertEquals(ApiResponseCode.CONFLICT, e2.getCode());
|
||||||
|
|
||||||
|
// consent → active 后 revoke → revoked,再 revoke → CONFLICT
|
||||||
|
contactAuthorizationService.consent(auth.getId(), user);
|
||||||
|
contactAuthorizationService.revoke(auth.getId(), mmOwner, "一次撤销");
|
||||||
|
BusinessException e3 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.revoke(auth.getId(), mmOwner, "二次撤销"));
|
||||||
|
assertEquals(ApiResponseCode.CONFLICT, e3.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("B1 request 防重: 同渠道生效授权存在时再申请 → CONFLICT")
|
||||||
|
void duplicateRequestConflict() {
|
||||||
|
MatchmakerContactAuthorization auth = contactAuthorizationService.request(
|
||||||
|
mmOwner, user, Constants.CONTACT_CHANNEL_PHONE, "电话沟通");
|
||||||
|
contactAuthorizationService.approve(auth.getId(), leaderA, P_LEADER);
|
||||||
|
contactAuthorizationService.consent(auth.getId(), user);
|
||||||
|
|
||||||
|
BusinessException e = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.request(mmOwner, user,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "重复申请"));
|
||||||
|
assertEquals(ApiResponseCode.CONFLICT, e.getCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
package com.danyang.match.platform.matchmaker;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
|
import com.danyang.match.platform.audit.entity.SensitiveAccessLog;
|
||||||
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import com.danyang.match.platform.audit.mapper.SensitiveAccessLogMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.entity.MatchmakerContactAuthorization;
|
||||||
|
import com.danyang.match.platform.matchmaker.mapper.MatchmakerContactAuthorizationMapper;
|
||||||
|
import com.danyang.match.platform.matchmaker.service.ContactAuthorizationService;
|
||||||
|
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 org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OQ-010 验收:机制总开关关闭(matchmaker.contact.enabled=false)时的 fail-safe 行为。
|
||||||
|
*
|
||||||
|
* <p>fail-safe 语义(ContactAuthorizationConfig.enabled Java 缺省 false,配置缺失=机制关闭):
|
||||||
|
* <ul>
|
||||||
|
* <li>disclose → 404 化拒绝(fail-safe 校验最先,G4 防探测:与"资源不存在"同响应);</li>
|
||||||
|
* <li>request → 404 化拒绝(ZC-MM-003 裁决落地 T-C 补齐:原实现漏查 enabled,
|
||||||
|
* 属真实缺口,本轮在 Service 层补 fail-safe 校验,口径与 disclose 一致);</li>
|
||||||
|
* <li>拒绝时<b>不落</b> SensitiveAccessLog、<b>不落</b>任何 matchmaker.contact.* 成功审计行
|
||||||
|
* (DATA_SCOPE_DENIED deny 审计可有,用于事后追责)。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
@SpringBootTest(properties = "matchmaker.contact.enabled=false")
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
class MatchmakerContactDisabledTest {
|
||||||
|
|
||||||
|
private static final String OPERATOR_ID = "00000000-0000-0000-0000-000000000101";
|
||||||
|
private static final String USER_ID = "00000000-0000-0000-0000-000000000102";
|
||||||
|
|
||||||
|
@Autowired private ContactAuthorizationService contactAuthorizationService;
|
||||||
|
@Autowired private MatchmakerContactAuthorizationMapper authorizationMapper;
|
||||||
|
@Autowired private AuditLogMapper auditLogMapper;
|
||||||
|
@Autowired private SensitiveAccessLogMapper sensitiveAccessLogMapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("开关关闭: disclose → 404 化拒绝,不落 SensitiveAccessLog / 成功审计行")
|
||||||
|
void discloseRejectedWhenDisabled() {
|
||||||
|
BusinessException e = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.disclose(OPERATOR_ID, USER_ID,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "机制关闭后披露"),
|
||||||
|
"机制关闭时披露必须 fail-safe 拒绝");
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e.getCode(), "fail-safe 必须 404 化(G4 防探测)");
|
||||||
|
assertEquals("服务不存在", e.getMessage());
|
||||||
|
|
||||||
|
// 不落 SensitiveAccessLog(成功行)
|
||||||
|
Long sensitiveCount = sensitiveAccessLogMapper.selectCount(new LambdaQueryWrapper<SensitiveAccessLog>()
|
||||||
|
.eq(SensitiveAccessLog::getOperatorId, OPERATOR_ID)
|
||||||
|
.eq(SensitiveAccessLog::getDataType,
|
||||||
|
ContactAuthorizationService.SENSITIVE_DATA_TYPE_PHONE_DISCLOSURE));
|
||||||
|
assertEquals(0L, sensitiveCount, "机制关闭的拒绝披露不得落 SensitiveAccessLog");
|
||||||
|
|
||||||
|
// 不落 matchmaker.contact.disclose 成功审计行(DATA_SCOPE_DENIED deny 审计可有)
|
||||||
|
Long discloseAuditCount = auditLogMapper.selectCount(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, Constants.CONTACT_AUDIT_ACTION_DISCLOSE)
|
||||||
|
.eq(AuditLog::getOperatorId, OPERATOR_ID));
|
||||||
|
assertEquals(0L, discloseAuditCount, "机制关闭的拒绝披露不得落成功审计行");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("开关关闭: request → 404 化拒绝(T-C 补齐真实缺口),不落任何成功审计行")
|
||||||
|
void requestRejectedWhenDisabled() {
|
||||||
|
BusinessException e = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.request(OPERATOR_ID, USER_ID,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, "机制关闭后申请"),
|
||||||
|
"机制关闭时申请必须 fail-safe 拒绝");
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e.getCode(), "fail-safe 必须 404 化(与 disclose 同口径)");
|
||||||
|
assertEquals("服务不存在", e.getMessage());
|
||||||
|
|
||||||
|
// 不产生任何授权记录(fail-safe 校验先于一切业务逻辑)
|
||||||
|
Long authCount = authorizationMapper.selectCount(new LambdaQueryWrapper<MatchmakerContactAuthorization>()
|
||||||
|
.eq(MatchmakerContactAuthorization::getOperatorId, OPERATOR_ID));
|
||||||
|
assertEquals(0L, authCount, "机制关闭的拒绝申请不得产生授权记录");
|
||||||
|
|
||||||
|
// 不落 matchmaker.contact.request 成功审计行(DATA_SCOPE_DENIED deny 审计可有)
|
||||||
|
Long requestAuditCount = auditLogMapper.selectCount(new LambdaQueryWrapper<AuditLog>()
|
||||||
|
.eq(AuditLog::getAction, Constants.CONTACT_AUDIT_ACTION_REQUEST)
|
||||||
|
.eq(AuditLog::getOperatorId, OPERATOR_ID));
|
||||||
|
assertEquals(0L, requestAuditCount, "机制关闭的拒绝申请不得落成功审计行");
|
||||||
|
|
||||||
|
// fail-safe 必须先于 purpose/channel 业务校验(缺目的的申请同样 404 化拒绝)
|
||||||
|
BusinessException e2 = assertThrows(BusinessException.class,
|
||||||
|
() -> contactAuthorizationService.request(OPERATOR_ID, USER_ID,
|
||||||
|
Constants.CONTACT_CHANNEL_PHONE, null));
|
||||||
|
assertEquals(ApiResponseCode.NOT_FOUND, e2.getCode(),
|
||||||
|
"fail-safe 必须最先判定,不得让业务校验异常(400/422)穿透");
|
||||||
|
assertNotNull(e2.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
+260
-140
@@ -18,25 +18,26 @@ import java.util.stream.Stream;
|
|||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ZC-MM-003(B1 联系规则护栏)+ ZC-MM-004 佐证 —— standalone 源码扫描守卫
|
* ZC-MM-003(B1 例外通道立项)守卫 —— standalone 源码扫描
|
||||||
* (沿用 {@code MatchmakerFieldPrivacyGuardTest} 范式,无需 Spring 上下文)。
|
* (沿用 {@code MatchmakerFieldPrivacyGuardTest} 范式,无需 Spring 上下文)。
|
||||||
*
|
*
|
||||||
* <p>锁定四条不变量(架构师设计 T01):
|
* <p><b>ZC-MM-006→003 守卫翻转说明</b>:受控联系授权机制(V056 + ContactAuthorizationPolicy/
|
||||||
|
* Service,架构师设计 H4/G4)立项后,本守卫从「锁机制不存在」翻转为「锁新契约」:
|
||||||
* <ol>
|
* <ol>
|
||||||
* <li><b>MM-CONTACT-002</b>:ReferralService 全部响应 put 键 ⊆ 白名单(逐键对照实际代码
|
* <li><b>① 联系回显文件收敛</b>:全仓响应装配中含 phone/mobile/wechat 等联系方式字样的
|
||||||
* 核定,见 {@link #RESPONSE_KEY_WHITELIST}),且键名不得含 emergencyContact / phone /
|
* put 键,仅允许出现在白名单文件(受控联系披露出口 + 既有合法落点,见
|
||||||
* mobile / wechat / address / idNumber 等联系方式字样 —— 锁定「红娘侧零联系方式回显」;
|
* {@link #CONTACT_ECHO_ALLOWED_FILES});其余文件出现即红;</li>
|
||||||
* emergencyContact* 是纯入口 write-only(写入 activity_registration 的紧急联系人字段),
|
* <li><b>② 联系类端点前缀收敛</b>:contact/phone/channel/offline 字样端点仅限
|
||||||
* 连红娘本人都无读回面。</li>
|
* {@code /operator/matchmaker/contact-authorizations/**} 与
|
||||||
* <li><b>MM-CONTACT-003</b>:matchmaker / referral Controller 无 contact / call / phone /
|
* {@code /contact-authorizations/**} 两前缀;</li>
|
||||||
* channel / offline 类端点;全仓无 ContactAuthorization 类、无
|
* <li><b>③ 到期语义完整契约</b>:双态惰性收敛(active 过期 / pending_consent 超窗 → expired)
|
||||||
* matchmaker_contact_authorizations 建表迁移 —— 锁定「不存在联系授权机制」。
|
* 机制必须存在,disclose 必须走 assertContactAllowed(404 化拒绝)+ 落敏感访问审计;
|
||||||
* 契约:未来新增联系功能必须连同本守卫 + 007 治理登记同步更新,守卫即红。</li>
|
* 行为面(未同意/已拒绝/已过期/已撤销 disclose → 404+审计)由
|
||||||
* <li><b>MM-CONTACT-004</b>:无联系授权机制即无授权到期场景 —— 与 MM-CONTACT-003 同源断言
|
* {@code MatchmakerContactAuthorizationTest} 行为锁定;</li>
|
||||||
* 承载(若未来引入 ContactAuthorization / matchmaker_contact_authorizations,
|
* <li><b>④ consent 独立性</b>:同意/拒绝必须是独立 POST 端点、无 @RequestBody、
|
||||||
* 003/004 两条守卫同时判红,迫使开发者补「到期 + 审计」语义并过 007 评审)。</li>
|
* 全仓无预同意/预勾选参数 —— PIPL 单独同意动作不可被捆绑;</li>
|
||||||
* <li><b>ZC-MM-004 佐证</b>:matchmaker / referral 包无 @Scheduled —— 全仓无批处理
|
* <li><b>⑤ 保留不变</b>:ReferralService 16 键白名单 + 联系字样禁词(红娘侧转介仍零联系回显)
|
||||||
* 代操作面(禁止代替用户决定的自动化通道不存在)。</li>
|
* 与 matchmaker/referral 包无 @Scheduled(无批处理代操作面)。</li>
|
||||||
* </ol>
|
* </ol>
|
||||||
*/
|
*/
|
||||||
class MatchmakerContactGuardTest {
|
class MatchmakerContactGuardTest {
|
||||||
@@ -44,27 +45,24 @@ class MatchmakerContactGuardTest {
|
|||||||
private static final Path SRC_ROOT = resolveSourceRoot();
|
private static final Path SRC_ROOT = resolveSourceRoot();
|
||||||
private static final Path REFERRAL_SERVICE =
|
private static final Path REFERRAL_SERVICE =
|
||||||
SRC_ROOT.resolve("com/danyang/match/platform/referral/service/ReferralService.java");
|
SRC_ROOT.resolve("com/danyang/match/platform/referral/service/ReferralService.java");
|
||||||
|
private static final Path CONTACT_AUTH_CONTROLLER =
|
||||||
|
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker/controller/MatchmakerContactAuthorizationController.java");
|
||||||
|
private static final Path CONTACT_USER_CONTROLLER =
|
||||||
|
SRC_ROOT.resolve("com/danyang/match/platform/contactauth/controller/ContactAuthorizationUserController.java");
|
||||||
|
private static final Path CONTACT_AUTH_MAPPER =
|
||||||
|
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker/mapper/MatchmakerContactAuthorizationMapper.java");
|
||||||
|
private static final Path CONTACT_AUTH_SERVICE =
|
||||||
|
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker/service/ContactAuthorizationService.java");
|
||||||
private static final List<Path> CONTROLLER_DIRS = List.of(
|
private static final List<Path> CONTROLLER_DIRS = List.of(
|
||||||
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker/controller"),
|
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker/controller"),
|
||||||
SRC_ROOT.resolve("com/danyang/match/platform/referral/controller"));
|
SRC_ROOT.resolve("com/danyang/match/platform/referral/controller"),
|
||||||
|
SRC_ROOT.resolve("com/danyang/match/platform/contactauth/controller"));
|
||||||
private static final List<Path> PACKAGE_DIRS = List.of(
|
private static final List<Path> PACKAGE_DIRS = List.of(
|
||||||
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker"),
|
SRC_ROOT.resolve("com/danyang/match/platform/matchmaker"),
|
||||||
SRC_ROOT.resolve("com/danyang/match/platform/referral"));
|
SRC_ROOT.resolve("com/danyang/match/platform/referral"));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ReferralService 响应键白名单(ZC-MM-003 / T01:以实际代码逐键核对后核定):
|
* ReferralService 响应键白名单(ZC-MM-003 原契约,053 阶段逐键核定,本阶段保留不变)。
|
||||||
* <ul>
|
|
||||||
* <li>referToServiceStation → appointmentId / status / referralType /
|
|
||||||
* referralFromOperatorId / needsUserConfirmation</li>
|
|
||||||
* <li>referToActivity → registrationId / activityId / status / referralType /
|
|
||||||
* referralFromOperatorId / needsUserConfirmation</li>
|
|
||||||
* <li>confirmReferral → id / status / confirmedAt</li>
|
|
||||||
* <li>getReferralHistory → type / id / serviceType|activityId / status /
|
|
||||||
* createdByOperatorId / userConfirmedAt / createdAt|registeredAt</li>
|
|
||||||
* <li>getReferralHistoryByOperator → 同上 + userId(operator 查看本人发起的
|
|
||||||
* 转介记录需要 userId 标识服务对象;userId 是内部标识符,非联系方式,
|
|
||||||
* 不落入 B1 禁放范畴)</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
*/
|
||||||
private static final Set<String> RESPONSE_KEY_WHITELIST = Set.of(
|
private static final Set<String> RESPONSE_KEY_WHITELIST = Set.of(
|
||||||
"appointmentId", "registrationId", "activityId", "id", "status", "type",
|
"appointmentId", "registrationId", "activityId", "id", "status", "type",
|
||||||
@@ -72,170 +70,292 @@ class MatchmakerContactGuardTest {
|
|||||||
"confirmedAt", "userConfirmedAt", "createdByOperatorId", "createdAt",
|
"confirmedAt", "userConfirmedAt", "createdByOperatorId", "createdAt",
|
||||||
"registeredAt", "userId");
|
"registeredAt", "userId");
|
||||||
|
|
||||||
/** 联系方式字样(出现在响应键名中即违规;emergencyContact* 仅允许作为入口 write-only 存在) */
|
/** 联系方式字样(出现在响应键名中即触发收敛判定) */
|
||||||
private static final List<String> FORBIDDEN_KEY_TOKENS = List.of(
|
private static final List<String> FORBIDDEN_KEY_TOKENS = List.of(
|
||||||
"emergencycontact", "phone", "mobile", "wechat", "weixin", "address",
|
"emergencycontact", "phone", "mobile", "wechat", "weixin", "address",
|
||||||
"idnumber", "id_card");
|
"idnumber", "id_card");
|
||||||
|
|
||||||
/** MM-CONTACT-003:联系/触达类禁用端点词 */
|
/** 联系/触达类端点词(出现在 mapping 路径中即触发前缀收敛判定) */
|
||||||
private static final List<String> FORBIDDEN_ENDPOINT_TOKENS = List.of(
|
private static final List<String> CONTACT_ENDPOINT_TOKENS = List.of(
|
||||||
"contact", "call", "phone", "channel", "offline");
|
"contact", "phone", "channel", "offline");
|
||||||
|
|
||||||
// ==================== MM-CONTACT-002:红娘侧零联系方式回显 ====================
|
/** 联系类端点仅允许的两个前缀(受控联系授权机制专属) */
|
||||||
|
private static final List<String> CONTACT_ENDPOINT_ALLOWED_PREFIXES = List.of(
|
||||||
|
"/operator/matchmaker/contact-authorizations",
|
||||||
|
"/contact-authorizations");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ① 联系回显白名单文件(逐个核定,出现新落点必须显式登记于此并过 007 评审):
|
||||||
|
* <ul>
|
||||||
|
* <li>ContactAuthorizationService —— H4 唯一披露出口(disclose 返回 phone 三键);</li>
|
||||||
|
* <li>MatchmakerContactAuthorizationController —— 受控联系授权运营端控制器(授权数据通道);</li>
|
||||||
|
* <li>AuthService —— {@code phoneBound} 布尔标志(是否已绑手机号,非号码本体);</li>
|
||||||
|
* <li>ActivityService —— {@code emergencyContactName}(用户报名数据本人可见);</li>
|
||||||
|
* <li>RealIdentityVerificationProvider —— {@code idNumber}/{@code idNumberHash}
|
||||||
|
* (服务端 → 实名核验 provider 请求体,非 C 端响应回显)。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
private static final Set<String> CONTACT_ECHO_ALLOWED_FILES = Set.of(
|
||||||
|
"ContactAuthorizationService.java",
|
||||||
|
"MatchmakerContactAuthorizationController.java",
|
||||||
|
"AuthService.java",
|
||||||
|
"ActivityService.java",
|
||||||
|
"RealIdentityVerificationProvider.java");
|
||||||
|
|
||||||
|
// ==================== ① 联系回显文件收敛 ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("MM-CONTACT-002: ReferralService 全部响应 put 键 ⊆ 白名单,无任何联系方式回显")
|
@DisplayName("① 联系回显收敛: 含联系方式字样的响应装配仅允许白名单文件(披露出口 + 既有合法落点)")
|
||||||
void referralResponseKeysAreWhitelistedWithNoContactEcho() throws IOException {
|
void contactEchoConfinedToWhitelistedFiles() throws IOException {
|
||||||
String src = stripComments(Files.readString(REFERRAL_SERVICE, StandardCharsets.UTF_8));
|
|
||||||
|
|
||||||
Set<String> keys = new LinkedHashSet<>();
|
|
||||||
Matcher put = Pattern.compile("\\.put\\(\"([^\"]+)\"").matcher(src);
|
|
||||||
while (put.find()) {
|
|
||||||
keys.add(put.group(1));
|
|
||||||
}
|
|
||||||
// 防止"装配被搬空后守卫永真":核心语义键必须仍在
|
|
||||||
assertTrue(keys.contains("needsUserConfirmation"),
|
|
||||||
"must-confirm 语义键必须存在(守卫非永真自检)");
|
|
||||||
assertTrue(keys.contains("referralFromOperatorId"),
|
|
||||||
"来源追溯键必须存在(守卫非永真自检)");
|
|
||||||
assertTrue(keys.contains("status"), "状态键必须存在(守卫非永真自检)");
|
|
||||||
|
|
||||||
List<String> violations = new ArrayList<>();
|
List<String> violations = new ArrayList<>();
|
||||||
for (String key : keys) {
|
try (Stream<Path> files = Files.walk(SRC_ROOT)) {
|
||||||
if (!RESPONSE_KEY_WHITELIST.contains(key)) {
|
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
||||||
violations.add("非白名单响应键: " + key);
|
String fileName = f.getFileName().toString();
|
||||||
}
|
String src = stripComments(Files.readString(f, StandardCharsets.UTF_8));
|
||||||
String lower = key.toLowerCase();
|
Matcher put = Pattern.compile("\\.put\\(\"([^\"]+)\"").matcher(src);
|
||||||
for (String token : FORBIDDEN_KEY_TOKENS) {
|
while (put.find()) {
|
||||||
if (lower.contains(token)) {
|
String key = put.group(1);
|
||||||
violations.add("响应键含联系方式 token: " + key + "(含 " + token + ")");
|
String lower = key.toLowerCase();
|
||||||
|
for (String token : FORBIDDEN_KEY_TOKENS) {
|
||||||
|
if (lower.contains(token) && !CONTACT_ECHO_ALLOWED_FILES.contains(fileName)) {
|
||||||
|
violations.add(fileName + " 装配联系字段响应键: " + key
|
||||||
|
+ "(含 " + token + ")—— 联系方式回显必须收敛到受控联系披露出口,"
|
||||||
|
+ "新增落点须登记白名单并过 007 评审");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertEquals(List.of(), violations,
|
assertEquals(List.of(), violations,
|
||||||
"B1 联系规则契约被破坏(MM-CONTACT-002):响应键出现白名单外键或联系方式字样。\n"
|
"联系方式回显出现白名单外落点(守卫①)。\n违规项:\n - "
|
||||||
+ "实际输出键=" + keys + "\n违规项:\n - " + String.join("\n - ", violations));
|
+ String.join("\n - ", violations));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== MM-CONTACT-003:无联系端点 / 无授权机制 ====================
|
// ==================== ② 联系类端点前缀收敛 ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("MM-CONTACT-003: matchmaker/referral Controller 无 contact 类端点;全仓无 ContactAuthorization 机制")
|
@DisplayName("② 端点收敛: 受治理域内 contact/phone/channel/offline 字样端点仅限受控联系授权两前缀")
|
||||||
void noContactEndpointsAndNoContactAuthorizationMechanism() throws IOException {
|
void contactEndpointsConfinedToAuthorizationPrefixes() throws IOException {
|
||||||
List<String> violations = new ArrayList<>();
|
List<String> violations = new ArrayList<>();
|
||||||
|
// 扫描面 = B1 联系规则受治理域(matchmaker / referral / contactauth 三包的 Controller)。
|
||||||
// a) 端点扫描:matchmaker / referral Controller 无联系/触达类路径
|
// 域外既有端点(如 /auth/phone/bind 用户本人绑手机号、/content/.../offline 内容下线)
|
||||||
|
// 由各自域的规则治理,不在本守卫职责内。
|
||||||
for (Path dir : CONTROLLER_DIRS) {
|
for (Path dir : CONTROLLER_DIRS) {
|
||||||
assertTrue(Files.isDirectory(dir), "Controller 目录不存在: " + dir);
|
assertTrue(Files.isDirectory(dir), "Controller 目录不存在: " + dir);
|
||||||
try (Stream<Path> files = Files.list(dir)) {
|
try (Stream<Path> files = Files.list(dir)) {
|
||||||
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
||||||
String src = Files.readString(f, StandardCharsets.UTF_8);
|
String src = stripComments(Files.readString(f, StandardCharsets.UTF_8));
|
||||||
|
String classPrefix = classMappingPrefix(src);
|
||||||
|
// 类级前缀 + 方法级路径任一含联系字样 → 完整路径必须落在白名单前缀内
|
||||||
Matcher mapping = Pattern.compile(
|
Matcher mapping = Pattern.compile(
|
||||||
"@(Get|Post|Put|Delete)Mapping\\(([^)]*)\\)", Pattern.DOTALL).matcher(src);
|
"@(Get|Post|Put|Delete|Patch)Mapping\\(([^)]*)\\)", Pattern.DOTALL).matcher(src);
|
||||||
while (mapping.find()) {
|
while (mapping.find()) {
|
||||||
String args = mapping.group(2).toLowerCase();
|
String rawArgs = mapping.group(2).replaceAll("\"", "").trim();
|
||||||
for (String banned : FORBIDDEN_ENDPOINT_TOKENS) {
|
String fullPath = compose(classPrefix, rawArgs);
|
||||||
if (args.contains(banned)) {
|
String lowerPath = fullPath.toLowerCase();
|
||||||
violations.add(f.getFileName() + " → " + mapping.group(0)
|
for (String token : CONTACT_ENDPOINT_TOKENS) {
|
||||||
.replaceAll("\\s+", " ") + " 含联系类端点: " + banned);
|
if (lowerPath.contains(token)
|
||||||
|
&& CONTACT_ENDPOINT_ALLOWED_PREFIXES.stream().noneMatch(lowerPath::startsWith)) {
|
||||||
|
violations.add(f.getFileName() + " → " + fullPath
|
||||||
|
+ "(含 " + token + ")—— 联系类端点仅限受控联系授权前缀");
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// b) 机制扫描:全仓 main 源码无 ContactAuthorization 类;迁移目录无建表
|
|
||||||
violations.addAll(scanForContactAuthorizationMechanism());
|
|
||||||
|
|
||||||
assertEquals(List.of(), violations,
|
assertEquals(List.of(), violations,
|
||||||
"B1 联系规则契约被破坏(MM-CONTACT-003):出现联系类端点或联系授权机制。\n"
|
"联系类端点出现收敛前缀外落点(守卫②)。\n违规项:\n - "
|
||||||
+ "契约:未来新增联系功能必须连同本守卫 + 007 治理登记同步更新。\n违规项:\n - "
|
|
||||||
+ String.join("\n - ", violations));
|
+ String.join("\n - ", violations));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== MM-CONTACT-004:无机制即无到期场景 ====================
|
// ==================== ③ 到期语义完整契约 ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("MM-CONTACT-004: 无联系授权机制 ⇒ 不存在授权到期场景(同源断言承载)")
|
@DisplayName("③ 到期语义: 双态惰性收敛(active/pending_consent→expired)+ disclose 走判定器 + 敏感审计")
|
||||||
void noContactAuthorizationMechanismImpliesNoExpiryScenario() throws IOException {
|
void expirySemanticsContractPresent() throws IOException {
|
||||||
/*
|
|
||||||
* ZC-MM-003(B1)「临时授权到期」场景的守卫:授权机制本身不存在(MM-CONTACT-003),
|
|
||||||
* 因此不存在"到期后权限回收"场景。本用例与 MM-CONTACT-003 共享同一底层断言 ——
|
|
||||||
* 若未来引入 ContactAuthorizationPolicy / matchmaker_contact_authorizations 表,
|
|
||||||
* 两条守卫同时判红,迫使实现者补齐「授权期限 + 到期回收 + 审计」语义,
|
|
||||||
* 并同步 007 治理登记(安全默认 = 不开放完整联系方式 / 未授权线下联系)。
|
|
||||||
*/
|
|
||||||
List<String> violations = scanForContactAuthorizationMechanism();
|
|
||||||
assertEquals(List.of(), violations,
|
|
||||||
"MM-CONTACT-004:联系授权机制出现 ⇒ 必须同步实现到期回收与审计,并过 007 评审。\n违规项:\n - "
|
|
||||||
+ String.join("\n - ", violations));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== ZC-MM-004 佐证:无批处理代操作面 ====================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("ZC-MM-004 佐证: matchmaker/referral 包无 @Scheduled(无批处理代操作通道)")
|
|
||||||
void noScheduledTasksInMatchmakerAndReferralPackages() throws IOException {
|
|
||||||
List<String> violations = new ArrayList<>();
|
List<String> violations = new ArrayList<>();
|
||||||
|
|
||||||
|
// a) Mapper:expireOverdue 必须同时收敛 active 与 pending_consent 两个态
|
||||||
|
String mapperSrc = stripComments(Files.readString(CONTACT_AUTH_MAPPER, StandardCharsets.UTF_8));
|
||||||
|
int expireIdx = mapperSrc.indexOf("int expireOverdue()");
|
||||||
|
assertTrue(expireIdx > 0, "expireOverdue 双态惰性收敛方法必须存在(守卫③非永真自检)");
|
||||||
|
String expireSql = mapperSrc.substring(Math.max(0, expireIdx - 600), expireIdx);
|
||||||
|
if (!(expireSql.contains("'active'") && expireSql.contains("'pending_consent'")
|
||||||
|
&& expireSql.contains("'expired'"))) {
|
||||||
|
violations.add("expireOverdue SQL 必须同时收敛 active 与 pending_consent 两态为 expired");
|
||||||
|
}
|
||||||
|
|
||||||
|
// b) Service:disclose 必须走判定器(404 化拒绝)+ 每次落敏感访问审计
|
||||||
|
String serviceSrc = stripComments(Files.readString(CONTACT_AUTH_SERVICE, StandardCharsets.UTF_8));
|
||||||
|
if (!serviceSrc.contains("assertContactAllowed")) {
|
||||||
|
violations.add("disclose 必须经 ContactAuthorizationPolicy.assertContactAllowed(404 化拒绝)");
|
||||||
|
}
|
||||||
|
if (!serviceSrc.contains("SENSITIVE_DATA_TYPE_PHONE_DISCLOSURE")
|
||||||
|
|| !serviceSrc.contains("sensitiveAccessLogMapper.insert")) {
|
||||||
|
violations.add("disclose 必须每次落 SensitiveAccessLog(user_phone_disclosure)");
|
||||||
|
}
|
||||||
|
if (!serviceSrc.contains("config.isEnabled()")) {
|
||||||
|
violations.add("disclose 必须含 enabled fail-safe 检查(配置缺失→机制关闭)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// c) 行为面交叉引用:404+审计的完整行为契约由 MatchmakerContactAuthorizationTest 锁定
|
||||||
|
Path integrationTest = Path.of("src/test/java/com/danyang/match/platform/matchmaker/MatchmakerContactAuthorizationTest.java");
|
||||||
|
if (!Files.exists(integrationTest)) {
|
||||||
|
integrationTest = Path.of("backend/src/test/java/com/danyang/match/platform/matchmaker/MatchmakerContactAuthorizationTest.java");
|
||||||
|
}
|
||||||
|
assertTrue(Files.exists(integrationTest),
|
||||||
|
"行为面集成测试 MatchmakerContactAuthorizationTest 必须存在(到期语义行为契约承载)");
|
||||||
|
|
||||||
|
assertEquals(List.of(), violations,
|
||||||
|
"受控联系授权到期/披露语义契约被破坏(守卫③)。\n违规项:\n - "
|
||||||
|
+ String.join("\n - ", violations));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== ④ consent 独立性(PIPL 单独同意) ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("④ consent 独立性: 独立 POST 端点、无 @RequestBody、全仓无预同意参数")
|
||||||
|
void consentMustBeIndependentAction() throws IOException {
|
||||||
|
List<String> violations = new ArrayList<>();
|
||||||
|
|
||||||
|
String src = stripComments(Files.readString(CONTACT_USER_CONTROLLER, StandardCharsets.UTF_8));
|
||||||
|
if (!src.contains("@PostMapping(\"/{id}/consent\")")) {
|
||||||
|
violations.add("consent 必须是独立 POST /{id}/consent 端点(不可捆绑到其他操作)");
|
||||||
|
}
|
||||||
|
if (!src.contains("@PostMapping(\"/{id}/decline\")")) {
|
||||||
|
violations.add("decline 必须是独立 POST /{id}/decline 端点");
|
||||||
|
}
|
||||||
|
// consent/decline 不得有 @RequestBody(无预同意/勾选参数载体)
|
||||||
|
Matcher methodBlocks = Pattern.compile(
|
||||||
|
"@PostMapping\\(\"/\\{id\\}/(consent|decline)\"\\)[^}]*?\\)", Pattern.DOTALL).matcher(src);
|
||||||
|
while (methodBlocks.find()) {
|
||||||
|
if (methodBlocks.group().contains("@RequestBody")) {
|
||||||
|
violations.add("consent/decline 端点不得携带 @RequestBody(杜绝预同意参数载体)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 全仓不得出现预同意/预勾选参数命名(后端 main 源码 + miniapp 小程序 + admin-web 管理端
|
||||||
|
// —— PIPL 单独同意的动作面横跨三端,任一端出现预同意参数即红)
|
||||||
|
List<Path> scanRoots = new ArrayList<>();
|
||||||
|
scanRoots.add(SRC_ROOT);
|
||||||
|
Path repoRoot = null;
|
||||||
|
// 从 SRC_ROOT 绝对路径逐级上溯,找到含 miniapp/ 的仓库根
|
||||||
|
// (相对路径 "src/main/java" 上溯到 "src" 即 null,必须 toAbsolutePath 后再走)
|
||||||
|
for (Path p = SRC_ROOT.toAbsolutePath().getParent(); p != null; p = p.getParent()) {
|
||||||
|
if (Files.isDirectory(p.resolve("miniapp"))) {
|
||||||
|
repoRoot = p;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (repoRoot != null) {
|
||||||
|
Path miniapp = repoRoot.resolve("miniapp");
|
||||||
|
Path adminWeb = repoRoot.resolve("admin-web/src");
|
||||||
|
if (Files.isDirectory(miniapp)) scanRoots.add(miniapp);
|
||||||
|
if (Files.isDirectory(adminWeb)) scanRoots.add(adminWeb);
|
||||||
|
}
|
||||||
|
for (Path scanRoot : scanRoots) {
|
||||||
|
try (Stream<Path> files = Files.walk(scanRoot)) {
|
||||||
|
for (Path f : files.filter(p -> {
|
||||||
|
String n = p.toString();
|
||||||
|
return n.endsWith(".java") || n.endsWith(".js") || n.endsWith(".ts") || n.endsWith(".vue");
|
||||||
|
}).toList()) {
|
||||||
|
String body = stripComments(Files.readString(f, StandardCharsets.UTF_8)).toLowerCase();
|
||||||
|
for (String token : new String[]{"preconsent", "pre_consent", "preagree", "pre_agree",
|
||||||
|
"autoconsent", "auto_consent"}) {
|
||||||
|
if (body.contains(token)) {
|
||||||
|
violations.add(f.getFileName() + " 出现预同意参数字样: " + token
|
||||||
|
+ "(PIPL 单独同意不可被捆绑/预勾选)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(List.of(), violations,
|
||||||
|
"用户单独同意独立性被破坏(守卫④)。\n违规项:\n - "
|
||||||
|
+ String.join("\n - ", violations));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== ⑤ 保留不变:转介白名单 + 无批处理 ====================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("⑤ 保留: ReferralService 16 键白名单+联系禁词 与 matchmaker/referral 无 @Scheduled")
|
||||||
|
void referralWhitelistAndNoScheduledPreserved() throws IOException {
|
||||||
|
List<String> violations = new ArrayList<>();
|
||||||
|
|
||||||
|
// a) ReferralService 响应键白名单(B1 立项后红娘侧转介仍零联系回显)
|
||||||
|
String referralSrc = stripComments(Files.readString(REFERRAL_SERVICE, StandardCharsets.UTF_8));
|
||||||
|
Set<String> keys = new LinkedHashSet<>();
|
||||||
|
Matcher put = Pattern.compile("\\.put\\(\"([^\"]+)\"").matcher(referralSrc);
|
||||||
|
while (put.find()) {
|
||||||
|
keys.add(put.group(1));
|
||||||
|
}
|
||||||
|
assertTrue(keys.contains("needsUserConfirmation"), "must-confirm 语义键必须存在(守卫非永真自检)");
|
||||||
|
for (String key : keys) {
|
||||||
|
if (!RESPONSE_KEY_WHITELIST.contains(key)) {
|
||||||
|
violations.add("ReferralService 非白名单响应键: " + key);
|
||||||
|
}
|
||||||
|
String lower = key.toLowerCase();
|
||||||
|
for (String token : FORBIDDEN_KEY_TOKENS) {
|
||||||
|
if (lower.contains(token)) {
|
||||||
|
violations.add("ReferralService 响应键含联系方式 token: " + key + "(含 " + token + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// b) matchmaker/referral 包无 @Scheduled(无批处理代操作面)
|
||||||
for (Path dir : PACKAGE_DIRS) {
|
for (Path dir : PACKAGE_DIRS) {
|
||||||
assertTrue(Files.isDirectory(dir), "包目录不存在: " + dir);
|
assertTrue(Files.isDirectory(dir), "包目录不存在: " + dir);
|
||||||
try (Stream<Path> files = Files.walk(dir)) {
|
try (Stream<Path> files = Files.walk(dir)) {
|
||||||
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
||||||
String src = stripComments(Files.readString(f, StandardCharsets.UTF_8));
|
String body = stripComments(Files.readString(f, StandardCharsets.UTF_8));
|
||||||
if (src.contains("@Scheduled")) {
|
if (body.contains("@Scheduled")) {
|
||||||
violations.add(f.getFileName() + " 含 @Scheduled 定时任务"
|
violations.add(f.getFileName() + " 含 @Scheduled 定时任务"
|
||||||
+ "(ZC-MM-004:禁止引入代替用户决定/代操作的自动化通道)");
|
+ "(禁止引入代替用户决定/代操作的自动化通道)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertEquals(List.of(), violations,
|
assertEquals(List.of(), violations,
|
||||||
"红娘/转介域出现定时任务必须先过「禁止代用户决定」评审(ZC-MM-004)");
|
"既有 B1 契约(转介白名单/无批处理)被破坏(守卫⑤)。\n违规项:\n - "
|
||||||
|
+ String.join("\n - ", violations));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== 解析实现 ====================
|
// ==================== 解析实现 ====================
|
||||||
|
|
||||||
/** 全仓 main 源码 + 迁移脚本扫描 ContactAuthorization 机制(003/004 共享)。 */
|
/** 提取类级 @RequestMapping 路径前缀(无则空串)。 */
|
||||||
private List<String> scanForContactAuthorizationMechanism() throws IOException {
|
private String classMappingPrefix(String src) {
|
||||||
List<String> violations = new ArrayList<>();
|
Matcher classMapping = Pattern.compile("@RequestMapping\\(([^)]*)\\)").matcher(src);
|
||||||
try (Stream<Path> files = Files.walk(SRC_ROOT)) {
|
if (!classMapping.find()) {
|
||||||
for (Path f : files.filter(p -> p.toString().endsWith(".java")).toList()) {
|
return "";
|
||||||
String name = f.getFileName().toString();
|
}
|
||||||
if (name.contains("ContactAuthorization")) {
|
String args = classMapping.group(1).replaceAll("\"", "").trim();
|
||||||
violations.add("出现联系授权类(机制被引入): " + name);
|
// 去掉 value=/path= 前缀写法,取第一段路径
|
||||||
continue;
|
for (String part : args.split(",")) {
|
||||||
}
|
String candidate = part.trim();
|
||||||
String src = stripComments(Files.readString(f, StandardCharsets.UTF_8));
|
if (candidate.startsWith("value=") || candidate.startsWith("path=")) {
|
||||||
if (src.contains("ContactAuthorization")) {
|
candidate = candidate.substring(candidate.indexOf('=') + 1).trim();
|
||||||
violations.add("源码引用联系授权机制: " + f.getFileName());
|
}
|
||||||
}
|
if (candidate.startsWith("/")) {
|
||||||
|
return candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Path migrationDir : migrationDirCandidates()) {
|
return "";
|
||||||
if (!Files.isDirectory(migrationDir)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try (Stream<Path> files = Files.list(migrationDir)) {
|
|
||||||
for (Path f : files.filter(p -> p.toString().endsWith(".sql")).toList()) {
|
|
||||||
String src = Files.readString(f, StandardCharsets.UTF_8).toLowerCase();
|
|
||||||
if (src.contains("matchmaker_contact_authorizations")) {
|
|
||||||
violations.add("出现 matchmaker_contact_authorizations 建表迁移: " + f.getFileName()
|
|
||||||
+ "(安全默认=不开放;仅当产品确认开放联系功能时随 006 评审引入)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return violations;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 迁移脚本目录(兼容仓库根与单模块两种布局)。 */
|
/** 类级前缀 + 方法路径合成完整路径(Spring mapping 拼接语义)。 */
|
||||||
private List<Path> migrationDirCandidates() {
|
private String compose(String classPrefix, String methodPath) {
|
||||||
Path parent = SRC_ROOT.getParent();
|
if (methodPath == null || methodPath.isEmpty() || methodPath.startsWith("(")) {
|
||||||
return List.of(
|
return classPrefix;
|
||||||
parent != null ? parent.resolve("resources/db/migration") : Path.of("backend/src/main/resources/db/migration"),
|
}
|
||||||
Path.of("backend/src/main/resources/db/migration"),
|
if (classPrefix.isEmpty()) {
|
||||||
Path.of("src/main/resources/db/migration"));
|
return methodPath;
|
||||||
|
}
|
||||||
|
if (methodPath.startsWith("/")) {
|
||||||
|
return classPrefix + methodPath;
|
||||||
|
}
|
||||||
|
return classPrefix + "/" + methodPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String stripComments(String src) {
|
private static String stripComments(String src) {
|
||||||
|
|||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
package com.danyang.match.platform.matchmaker;
|
||||||
|
|
||||||
|
import com.danyang.match.platform.matchmaker.service.MatchmakerManagementService;
|
||||||
|
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||||
|
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
class MatchmakerManagementReadTest {
|
||||||
|
@Autowired MatchmakerManagementService service;
|
||||||
|
@Autowired JdbcTemplate jdbc;
|
||||||
|
String manager, leader, otherLeader, user, serviceId;
|
||||||
|
|
||||||
|
@BeforeEach void seed() {
|
||||||
|
manager = UUID.randomUUID().toString();
|
||||||
|
leader = UUID.randomUUID().toString();
|
||||||
|
otherLeader = UUID.randomUUID().toString();
|
||||||
|
String org = UUID.randomUUID().toString();
|
||||||
|
String mm = UUID.randomUUID().toString();
|
||||||
|
user = UUID.randomUUID().toString();
|
||||||
|
serviceId = UUID.randomUUID().toString();
|
||||||
|
for (String id : new String[]{manager, leader, otherLeader, mm}) {
|
||||||
|
jdbc.update("INSERT INTO operators(id,name,username,password_hash,organization_id) VALUES(?,?,?,?,?)",
|
||||||
|
id, "验收人员", id, "test", id.equals(otherLeader) ? UUID.randomUUID().toString() : org);
|
||||||
|
}
|
||||||
|
jdbc.update("INSERT INTO users(id,wechat_openid,display_number) VALUES(?,?,?)", user, user, "YH2026101302");
|
||||||
|
jdbc.update("INSERT INTO matchmaker_services(id,user_id,service_type,status,assigned_operator_id) VALUES(?,?,?,?,?)",
|
||||||
|
serviceId, user, "other", "waiting_user", mm);
|
||||||
|
jdbc.update("INSERT INTO matchmaker_followups(id,service_id,operator_id,content) VALUES(?,?,?,?)",
|
||||||
|
UUID.randomUUID().toString(), serviceId, mm, "验收跟进");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void managerReadsPersistedFollowupAndAuditsAccess() {
|
||||||
|
var principal = new OperatorPrincipal(manager, Set.of("matchmaker.assign"));
|
||||||
|
var row = service.list(principal).stream().filter(r -> serviceId.equals(r.get("serviceId"))).findFirst().orElseThrow();
|
||||||
|
assertEquals("验收跟进", row.get("latestFollowupContent"));
|
||||||
|
assertEquals("YH2026101302", row.get("userDisplayNumber"));
|
||||||
|
assertFalse(row.containsKey("phone"));
|
||||||
|
var detail = service.detail(principal, serviceId);
|
||||||
|
assertEquals(1, ((java.util.List<?>) detail.get("followups")).size());
|
||||||
|
assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM audit_logs WHERE resource_id=? AND action='MATCHMAKER_MANAGEMENT_VIEW'", Integer.class, serviceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void leaderCanOnlyReadOwnOrganization() {
|
||||||
|
assertNotNull(service.detail(new OperatorPrincipal(leader, Set.of("matchmaker.team.assign")), serviceId));
|
||||||
|
var other = new OperatorPrincipal(otherLeader, Set.of("matchmaker.team.assign"));
|
||||||
|
assertTrue(service.list(other).isEmpty());
|
||||||
|
assertThrows(BusinessException.class, () -> service.detail(other, serviceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void ordinaryMatchmakerCannotUseManagementRead() {
|
||||||
|
var ordinary = new OperatorPrincipal(manager, Set.of("matchmaker.view", "matchmaker.service"));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.list(ordinary));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.detail(ordinary, serviceId));
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -61,8 +61,8 @@ class MatchmakerReferralPhase13Test {
|
|||||||
@Autowired private ActivityRegistrationMapper activityRegistrationMapper;
|
@Autowired private ActivityRegistrationMapper activityRegistrationMapper;
|
||||||
@Autowired private ServiceAppointmentMapper appointmentMapper;
|
@Autowired private ServiceAppointmentMapper appointmentMapper;
|
||||||
|
|
||||||
private static final String MATCHMAKER_OWNER = "op-mm-owner";
|
private static final String MATCHMAKER_OWNER = "00000000-0000-0000-0000-000000000104";
|
||||||
private static final String MATCHMAKER_OTHER = "op-mm-other";
|
private static final String MATCHMAKER_OTHER = "00000000-0000-0000-0000-000000000105";
|
||||||
|
|
||||||
private String user;
|
private String user;
|
||||||
private String target;
|
private String target;
|
||||||
|
|||||||
+2
-1
@@ -39,7 +39,8 @@ class NotificationPhase11IntegrationTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private PlatformTransactionManager txManager;
|
private PlatformTransactionManager txManager;
|
||||||
|
|
||||||
private static final String USER = "u-notif-p11";
|
// 与生产 users.id 类型保持一致,避免该通知夹具污染共享 H2 库后触发 UUID 转换告警。
|
||||||
|
private static final String USER = "22222222-2222-4222-8222-222222222222";
|
||||||
|
|
||||||
private List<Notification> allFor(String userId, String type) {
|
private List<Notification> allFor(String userId, String type) {
|
||||||
return notificationMapper.selectList(
|
return notificationMapper.selectList(
|
||||||
|
|||||||
+2
-1
@@ -38,7 +38,8 @@ class NotificationTemplateTypeGuardTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private NotificationMapper notificationMapper;
|
private NotificationMapper notificationMapper;
|
||||||
|
|
||||||
private static final String USER = "u-notif-guard";
|
// 必须使用与生产 users.id 一致的 UUID;否则该夹具写入 H2 后,后续 UUID 条件查询会触发类型转换告警。
|
||||||
|
private static final String USER = "11111111-1111-4111-8111-111111111111";
|
||||||
|
|
||||||
private void assertPersisted(String type, String businessId, String label) {
|
private void assertPersisted(String type, String businessId, String label) {
|
||||||
List<Notification> rows = notificationMapper.selectList(
|
List<Notification> rows = notificationMapper.selectList(
|
||||||
|
|||||||
+13
-10
@@ -52,7 +52,7 @@ class OrganizationServiceTest {
|
|||||||
@Autowired private AuditLogMapper auditLogMapper;
|
@Autowired private AuditLogMapper auditLogMapper;
|
||||||
|
|
||||||
/** 审计归属断言用的操作人 id(模拟已认证的运营主体) */
|
/** 审计归属断言用的操作人 id(模拟已认证的运营主体) */
|
||||||
private static final String OPERATOR_ID = "op-audit-e2e";
|
private static final String OPERATOR_ID = "00000000-0000-0000-0000-000000000106";
|
||||||
|
|
||||||
private static Map<String, Object> params(String name, String type) {
|
private static Map<String, Object> params(String name, String type) {
|
||||||
Map<String, Object> params = new HashMap<>();
|
Map<String, Object> params = new HashMap<>();
|
||||||
@@ -76,9 +76,12 @@ class OrganizationServiceTest {
|
|||||||
void createOrganizationRecordsOperatorInAuditLog() {
|
void createOrganizationRecordsOperatorInAuditLog() {
|
||||||
Organization org = createAndReload("审计归属机构-" + System.nanoTime(), "other");
|
Organization org = createAndReload("审计归属机构-" + System.nanoTime(), "other");
|
||||||
|
|
||||||
|
// resource_id 同时承载授权拒绝事件的方法签名,H2 会按 UUID 参数比较时拒绝混合值;
|
||||||
|
// 先按稳定动作取行,再在 Java 侧核对资源,保持测试语义且不改变生产字段。
|
||||||
List<AuditLog> logs = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
List<AuditLog> logs = auditLogMapper.selectList(new LambdaQueryWrapper<AuditLog>()
|
||||||
.eq(AuditLog::getResourceId, org.getId())
|
.eq(AuditLog::getAction, "CREATE_ORGANIZATION")).stream()
|
||||||
.eq(AuditLog::getAction, "CREATE_ORGANIZATION"));
|
.filter(log -> org.getId().equals(log.getResourceId()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
assertEquals(1, logs.size(), "创建机构应恰好留下 1 条 CREATE_ORGANIZATION 审计");
|
assertEquals(1, logs.size(), "创建机构应恰好留下 1 条 CREATE_ORGANIZATION 审计");
|
||||||
assertEquals(OPERATOR_ID, logs.get(0).getOperatorId(),
|
assertEquals(OPERATOR_ID, logs.get(0).getOperatorId(),
|
||||||
@@ -103,7 +106,7 @@ class OrganizationServiceTest {
|
|||||||
void disableOrganizationPersistsInactiveStatus() {
|
void disableOrganizationPersistsInactiveStatus() {
|
||||||
Organization org = createAndReload("待停用机构-" + System.nanoTime(), "charity_center");
|
Organization org = createAndReload("待停用机构-" + System.nanoTime(), "charity_center");
|
||||||
|
|
||||||
organizationService.disableOrganization(org.getId(), "op-1");
|
organizationService.disableOrganization(org.getId(), OPERATOR_ID);
|
||||||
|
|
||||||
Organization after = organizationMapper.selectById(org.getId());
|
Organization after = organizationMapper.selectById(org.getId());
|
||||||
assertEquals(Constants.ORG_STATUS_INACTIVE, after.getStatus(),
|
assertEquals(Constants.ORG_STATUS_INACTIVE, after.getStatus(),
|
||||||
@@ -114,9 +117,9 @@ class OrganizationServiceTest {
|
|||||||
@DisplayName("启用机构:落库状态回到 active(原写 'normal' —— 不在白名单)")
|
@DisplayName("启用机构:落库状态回到 active(原写 'normal' —— 不在白名单)")
|
||||||
void enableOrganizationPersistsActiveStatus() {
|
void enableOrganizationPersistsActiveStatus() {
|
||||||
Organization org = createAndReload("待启用机构-" + System.nanoTime(), "volunteer_team");
|
Organization org = createAndReload("待启用机构-" + System.nanoTime(), "volunteer_team");
|
||||||
organizationService.disableOrganization(org.getId(), "op-1");
|
organizationService.disableOrganization(org.getId(), OPERATOR_ID);
|
||||||
|
|
||||||
organizationService.enableOrganization(org.getId(), "op-1");
|
organizationService.enableOrganization(org.getId(), OPERATOR_ID);
|
||||||
|
|
||||||
Organization after = organizationMapper.selectById(org.getId());
|
Organization after = organizationMapper.selectById(org.getId());
|
||||||
assertEquals(Constants.ORG_STATUS_ACTIVE, after.getStatus(),
|
assertEquals(Constants.ORG_STATUS_ACTIVE, after.getStatus(),
|
||||||
@@ -128,8 +131,8 @@ class OrganizationServiceTest {
|
|||||||
void disableThenEnableRoundTripKeepsRecordReadable() {
|
void disableThenEnableRoundTripKeepsRecordReadable() {
|
||||||
Organization org = createAndReload("往返机构-" + System.nanoTime(), "trade_union");
|
Organization org = createAndReload("往返机构-" + System.nanoTime(), "trade_union");
|
||||||
|
|
||||||
organizationService.disableOrganization(org.getId(), "op-1");
|
organizationService.disableOrganization(org.getId(), OPERATOR_ID);
|
||||||
organizationService.enableOrganization(org.getId(), "op-1");
|
organizationService.enableOrganization(org.getId(), OPERATOR_ID);
|
||||||
|
|
||||||
assertEquals(1, organizationService.listOrganizations().stream()
|
assertEquals(1, organizationService.listOrganizations().stream()
|
||||||
.filter(o -> org.getId().equals(o.getId())).count(),
|
.filter(o -> org.getId().equals(o.getId())).count(),
|
||||||
@@ -196,8 +199,8 @@ class OrganizationServiceTest {
|
|||||||
@DisplayName("机构不存在时:停用 / 启用 / 更新返回 NOT_FOUND 业务码,而非 500")
|
@DisplayName("机构不存在时:停用 / 启用 / 更新返回 NOT_FOUND 业务码,而非 500")
|
||||||
void missingOrganizationYieldsNotFoundCode() {
|
void missingOrganizationYieldsNotFoundCode() {
|
||||||
for (Runnable call : java.util.List.<Runnable>of(
|
for (Runnable call : java.util.List.<Runnable>of(
|
||||||
() -> organizationService.disableOrganization("no-such-org-id", "op-1"),
|
() -> organizationService.disableOrganization("no-such-org-id", OPERATOR_ID),
|
||||||
() -> organizationService.enableOrganization("no-such-org-id", "op-1"),
|
() -> organizationService.enableOrganization("no-such-org-id", OPERATOR_ID),
|
||||||
() -> organizationService.updateOrganization("no-such-org-id",
|
() -> organizationService.updateOrganization("no-such-org-id",
|
||||||
params("新名称", "other")))) {
|
params("新名称", "other")))) {
|
||||||
BusinessException ex = assertThrows(BusinessException.class, call::run);
|
BusinessException ex = assertThrows(BusinessException.class, call::run);
|
||||||
|
|||||||
+4
-4
@@ -237,7 +237,7 @@ class RelationshipProgressPhase12Test {
|
|||||||
// 旧 Match 有会话
|
// 旧 Match 有会话
|
||||||
Long oldConvCount = conversationMapper.selectCount(
|
Long oldConvCount = conversationMapper.selectCount(
|
||||||
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, first.getId()));
|
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, first.getId()));
|
||||||
assertEquals(1L, oldConvCount, "首个 Match 应有 1 个会话");
|
assertEquals(0L, oldConvCount, "首个 Match 不应有用户聊天会话");
|
||||||
|
|
||||||
// Unmatch
|
// Unmatch
|
||||||
Match m1 = matchMapper.findById(first.getId()).orElseThrow();
|
Match m1 = matchMapper.findById(first.getId()).orElseThrow();
|
||||||
@@ -255,10 +255,10 @@ class RelationshipProgressPhase12Test {
|
|||||||
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, second.getId())),
|
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, second.getId())),
|
||||||
"新 Match 不应自动继承旧会话(旧聊天权限不恢复)");
|
"新 Match 不应自动继承旧会话(旧聊天权限不恢复)");
|
||||||
|
|
||||||
// 且旧会话仍挂在旧 Match 上,不会被新 Match 复用
|
// 历史数据为空:本产品不再创建用户聊天会话
|
||||||
assertEquals(1L, conversationMapper.selectCount(
|
assertEquals(0L, conversationMapper.selectCount(
|
||||||
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, first.getId())),
|
new LambdaQueryWrapper<Conversation>().eq(Conversation::getMatchId, first.getId())),
|
||||||
"旧会话应仍属于旧 Match");
|
"旧 Match 也不应存在用户聊天会话");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== 拒绝 / 恢复 / 退出 ====================
|
// ==================== 拒绝 / 恢复 / 退出 ====================
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.danyang.match.platform.review;
|
||||||
|
|
||||||
|
import com.danyang.match.platform.review.service.ReviewService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
class ReviewDashboardCountTest {
|
||||||
|
@Autowired ReviewService service;
|
||||||
|
@Autowired JdbcTemplate jdbc;
|
||||||
|
|
||||||
|
@Test void approvingTaskReducesOutstandingCountAndRemovesItFromQueue() {
|
||||||
|
String task = UUID.randomUUID().toString();
|
||||||
|
String operator = UUID.randomUUID().toString();
|
||||||
|
String user = UUID.randomUUID().toString();
|
||||||
|
jdbc.update("INSERT INTO operators(id,name,username,password_hash) VALUES(?,?,?,?)", operator, "测试审核员", operator, "test");
|
||||||
|
jdbc.update("INSERT INTO users(id,wechat_openid) VALUES(?,?)", user, user);
|
||||||
|
jdbc.update("INSERT INTO review_tasks(id,user_id,review_type,status,created_at) VALUES(?,?,?,'pending',NOW())", task, user, "profile");
|
||||||
|
var before = service.getPendingStats();
|
||||||
|
assertTrue(service.claimTask(operator, task).isPresent());
|
||||||
|
var claimed = service.getPendingStats();
|
||||||
|
assertEquals(before.get("pending") - 1, claimed.get("pending"));
|
||||||
|
assertEquals(before.get("processing") + 1, claimed.get("processing"));
|
||||||
|
service.approve(task, operator, "验收通过");
|
||||||
|
var after = service.getPendingStats();
|
||||||
|
assertEquals(before.get("pending") + before.get("processing") - 1, after.get("pending") + after.get("processing"));
|
||||||
|
assertFalse(service.listPendingTasks(0, 1000).stream().anyMatch(row -> task.equals(row.getId())));
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -2,6 +2,7 @@ package com.danyang.match.platform.security;
|
|||||||
|
|
||||||
import com.danyang.match.platform.audit.entity.AuditLog;
|
import com.danyang.match.platform.audit.entity.AuditLog;
|
||||||
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
|
||||||
|
import com.danyang.match.platform.audit.service.AuditDenyWriter;
|
||||||
import com.danyang.match.platform.shared.security.AuthorizationAuditListener;
|
import com.danyang.match.platform.shared.security.AuthorizationAuditListener;
|
||||||
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
import com.danyang.match.platform.shared.security.principal.OperatorPrincipal;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -20,7 +21,7 @@ class AuthorizationAuditListenerTest {
|
|||||||
@Test
|
@Test
|
||||||
void deniedOperatorAuthorizationIsWrittenToAuditLog() {
|
void deniedOperatorAuthorizationIsWrittenToAuditLog() {
|
||||||
AuditLogMapper mapper = mock(AuditLogMapper.class);
|
AuditLogMapper mapper = mock(AuditLogMapper.class);
|
||||||
AuthorizationAuditListener listener = new AuthorizationAuditListener(mapper);
|
AuthorizationAuditListener listener = new AuthorizationAuditListener(mapper, new AuditDenyWriter(mapper));
|
||||||
OperatorPrincipal principal = new OperatorPrincipal("operator-1", Set.of("content.view"));
|
OperatorPrincipal principal = new OperatorPrincipal("operator-1", Set.of("content.view"));
|
||||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(principal, null, java.util.List.of());
|
var authentication = UsernamePasswordAuthenticationToken.authenticated(principal, null, java.util.List.of());
|
||||||
var event = new AuthorizationDeniedEvent<>(() -> authentication,
|
var event = new AuthorizationDeniedEvent<>(() -> authentication,
|
||||||
|
|||||||
+4
@@ -7,6 +7,8 @@ import com.danyang.match.platform.appeal.controller.AppealOperatorController;
|
|||||||
import com.danyang.match.platform.audit.controller.AuditLogController;
|
import com.danyang.match.platform.audit.controller.AuditLogController;
|
||||||
import com.danyang.match.platform.content.controller.ContentController;
|
import com.danyang.match.platform.content.controller.ContentController;
|
||||||
import com.danyang.match.platform.counseling.controller.CounselingController;
|
import com.danyang.match.platform.counseling.controller.CounselingController;
|
||||||
|
import com.danyang.match.platform.matchmaker.controller.MatchmakerAssignmentController;
|
||||||
|
import com.danyang.match.platform.matchmaker.controller.MatchmakerContactAuthorizationController;
|
||||||
import com.danyang.match.platform.matchmaker.controller.MatchmakerOperatorController;
|
import com.danyang.match.platform.matchmaker.controller.MatchmakerOperatorController;
|
||||||
import com.danyang.match.platform.operator.controller.OperatorController;
|
import com.danyang.match.platform.operator.controller.OperatorController;
|
||||||
import com.danyang.match.platform.organization.controller.OrganizationController;
|
import com.danyang.match.platform.organization.controller.OrganizationController;
|
||||||
@@ -41,6 +43,8 @@ class OperatorEndpointPermissionCoverageTest {
|
|||||||
CheckinController.class, AnalyticsController.class,
|
CheckinController.class, AnalyticsController.class,
|
||||||
AppealOperatorController.class, AuditLogController.class,
|
AppealOperatorController.class, AuditLogController.class,
|
||||||
ContentController.class, CounselingController.class,
|
ContentController.class, CounselingController.class,
|
||||||
|
MatchmakerAssignmentController.class,
|
||||||
|
MatchmakerContactAuthorizationController.class,
|
||||||
MatchmakerOperatorController.class, OperatorController.class,
|
MatchmakerOperatorController.class, OperatorController.class,
|
||||||
OrganizationController.class, ReviewController.class,
|
OrganizationController.class, ReviewController.class,
|
||||||
ReferralController.class,
|
ReferralController.class,
|
||||||
|
|||||||
+2
-1
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
import org.springframework.context.ApplicationEventPublisher;
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import com.danyang.match.platform.audit.service.AuditDenyWriter;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
@@ -76,7 +77,7 @@ class V11MethodSecurityMatrixTest {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
AuthorizationAuditListener authorizationAuditListener(AuditLogMapper mapper) {
|
AuthorizationAuditListener authorizationAuditListener(AuditLogMapper mapper) {
|
||||||
return new AuthorizationAuditListener(mapper);
|
return new AuthorizationAuditListener(mapper, new AuditDenyWriter(mapper));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+2
-1
@@ -8,6 +8,7 @@ import com.danyang.match.platform.service_appointment.mapper.ServiceAppointmentM
|
|||||||
import com.danyang.match.platform.service_appointment.mapper.ServiceLocationMapper;
|
import com.danyang.match.platform.service_appointment.mapper.ServiceLocationMapper;
|
||||||
import com.danyang.match.platform.service_appointment.service.ServiceAppointmentService;
|
import com.danyang.match.platform.service_appointment.service.ServiceAppointmentService;
|
||||||
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
import com.danyang.match.platform.shared.security.DataScopeGuard;
|
||||||
|
import com.danyang.match.platform.audit.service.AuditDenyWriter;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -34,7 +35,7 @@ class ServiceAppointmentDataScopeTest {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
service = new ServiceAppointmentService(appointmentMapper, locationMapper,
|
service = new ServiceAppointmentService(appointmentMapper, locationMapper,
|
||||||
notificationService, riskReferralService, new DataScopeGuard(auditLogMapper));
|
notificationService, riskReferralService, new DataScopeGuard(auditLogMapper, new AuditDenyWriter(auditLogMapper)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user