优化考核调研钉钉通知和移动端问卷
This commit is contained in:
parent
4bde670f85
commit
3e42ca3104
@ -40,7 +40,7 @@ function createCookieLandingResponse(redirectPath: string, loginResponse: Respon
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>正在进入素材库</title>
|
||||
<title>正在打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f8fafc;color:#0f172a;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -50,8 +50,8 @@ function createCookieLandingResponse(redirectPath: string, loginResponse: Respon
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>登录成功</h1>
|
||||
<p>正在进入考核调研...</p>
|
||||
<h1>正在打开问卷</h1>
|
||||
<p>正在打开问卷...</p>
|
||||
</main>
|
||||
<script>
|
||||
window.location.replace(${escapedPath});
|
||||
@ -72,14 +72,14 @@ function createCookieLandingResponse(redirectPath: string, loginResponse: Respon
|
||||
}
|
||||
|
||||
function createDingtalkDirectErrorPage(message: string) {
|
||||
const safeMessage = JSON.stringify(message || '钉钉免登失败,请联系管理员检查配置').replace(/</g, '\\u003c')
|
||||
const safeMessage = JSON.stringify(message || '暂时无法打开问卷,请联系管理员检查钉钉配置').replace(/</g, '\\u003c')
|
||||
return new NextResponse(
|
||||
`<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>钉钉免登失败</title>
|
||||
<title>无法打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f8fafc;color:#0f172a;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -90,7 +90,7 @@ function createDingtalkDirectErrorPage(message: string) {
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>钉钉免登失败</h1>
|
||||
<h1>无法打开问卷</h1>
|
||||
<p id="message"></p>
|
||||
</main>
|
||||
<script>
|
||||
@ -115,7 +115,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (!code) {
|
||||
if (source === DINGTALK_DIRECT_LOGIN_SOURCE) {
|
||||
return createDingtalkDirectErrorPage('钉钉授权缺少授权码,请从钉钉工作通知重新打开')
|
||||
return createDingtalkDirectErrorPage('暂时无法打开问卷,请从最新通知重新进入。')
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL(buildDingtalkAutoLoginPath(redirectPath), publicOrigin))
|
||||
@ -135,7 +135,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (!loginResponse.ok || !data?.success || data.needCompleteProfile) {
|
||||
if (source === DINGTALK_DIRECT_LOGIN_SOURCE) {
|
||||
return createDingtalkDirectErrorPage(data?.message || '钉钉登录未能创建素材库会话')
|
||||
return createDingtalkDirectErrorPage('暂时无法打开问卷,请稍后重试或联系管理员。')
|
||||
}
|
||||
|
||||
const loginPath = buildDingtalkAutoLoginPath(redirectPath)
|
||||
@ -157,7 +157,7 @@ export async function GET(request: NextRequest) {
|
||||
} catch (error) {
|
||||
console.error('[Dingtalk] 服务端授权回调失败:', error)
|
||||
if (source === DINGTALK_DIRECT_LOGIN_SOURCE) {
|
||||
return createDingtalkDirectErrorPage('钉钉服务端授权失败,请稍后重试或联系管理员')
|
||||
return createDingtalkDirectErrorPage('暂时无法打开问卷,请稍后重试或联系管理员。')
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL(buildDingtalkAutoLoginPath(redirectPath), publicOrigin))
|
||||
|
||||
@ -66,7 +66,7 @@ function createSessionTicketTransferPage({
|
||||
const cookies = getLoginSetCookies(loginResponse)
|
||||
if (cookies.length === 0) {
|
||||
console.error('[Dingtalk H5] 登录成功但没有生成会话Cookie', { redirectPath })
|
||||
return createH5LoginErrorPage('素材库登录状态生成失败,请联系管理员检查登录配置')
|
||||
return createH5LoginErrorPage('暂时无法打开问卷,请稍后重试或联系管理员。')
|
||||
}
|
||||
|
||||
const redirectUrl = buildPublicUrl(redirectPath, request)
|
||||
@ -76,7 +76,7 @@ function createSessionTicketTransferPage({
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>正在进入素材库</title>
|
||||
<title>正在打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -90,8 +90,8 @@ function createSessionTicketTransferPage({
|
||||
<body>
|
||||
<main>
|
||||
<div class="spinner" aria-hidden="true"></div>
|
||||
<h1>正在进入素材库</h1>
|
||||
<p id="message">钉钉身份已确认,正在写入素材库登录状态...</p>
|
||||
<h1>正在打开问卷</h1>
|
||||
<p id="message">正在打开问卷...</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
@ -113,7 +113,7 @@ function createSessionTicketTransferPage({
|
||||
async function confirmSessionThenEnter() {
|
||||
while (attempts < maxAttempts) {
|
||||
attempts += 1;
|
||||
setMessage('正在确认素材库登录状态...' + attempts + '/' + maxAttempts);
|
||||
setMessage('正在打开问卷...');
|
||||
|
||||
try {
|
||||
var response = await fetch('/api/auth/session?source=dingtalk_h5_entry&attempt=' + attempts + '&_=' + Date.now(), {
|
||||
@ -123,7 +123,7 @@ function createSessionTicketTransferPage({
|
||||
var data = response.ok ? await response.json().catch(function () { return null; }) : null;
|
||||
|
||||
if (data && data.user) {
|
||||
setMessage('登录状态已确认,正在打开考核调研...');
|
||||
setMessage('正在打开问卷...');
|
||||
window.location.replace(targetUrl);
|
||||
return;
|
||||
}
|
||||
@ -134,7 +134,7 @@ function createSessionTicketTransferPage({
|
||||
await wait(450);
|
||||
}
|
||||
|
||||
setMessage('登录状态写入后未被钉钉容器读取,请关闭当前页面后从最新通知重新进入。');
|
||||
setMessage('暂时无法打开问卷,请关闭当前页面后从最新通知重新进入。');
|
||||
}
|
||||
|
||||
window.setTimeout(confirmSessionThenEnter, 250);
|
||||
@ -183,7 +183,7 @@ function createPerformanceSurveySessionTransferPage({
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>正在进入素材库</title>
|
||||
<title>正在打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -197,8 +197,8 @@ function createPerformanceSurveySessionTransferPage({
|
||||
<body>
|
||||
<main>
|
||||
<div class="spinner" aria-hidden="true"></div>
|
||||
<h1>正在进入素材库</h1>
|
||||
<p id="message">钉钉身份已确认,正在打开考核调研...</p>
|
||||
<h1>正在打开问卷</h1>
|
||||
<p id="message">正在打开问卷...</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
@ -215,11 +215,11 @@ function createPerformanceSurveySessionTransferPage({
|
||||
window.sessionStorage.setItem(storageKey, token);
|
||||
window.localStorage.setItem(storageKey, token);
|
||||
} catch (error) {
|
||||
setMessage('钉钉容器无法保存考核调研访问凭证,请关闭当前页面后从最新通知重新进入。');
|
||||
setMessage('暂时无法打开问卷,请关闭当前页面后从最新通知重新进入。');
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage('身份已确认,正在进入考核调研...');
|
||||
setMessage('正在打开问卷...');
|
||||
window.setTimeout(function () {
|
||||
window.location.replace(targetUrl);
|
||||
}, 120);
|
||||
@ -251,14 +251,14 @@ function createPublicRedirectResponse({
|
||||
}
|
||||
|
||||
function createH5LoginErrorPage(message: string) {
|
||||
const safeMessage = JSON.stringify(message || '钉钉免登失败,请联系管理员检查配置').replace(/</g, '\\u003c')
|
||||
const safeMessage = JSON.stringify(message || '暂时无法打开问卷,请联系管理员检查钉钉配置').replace(/</g, '\\u003c')
|
||||
return new NextResponse(
|
||||
`<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>钉钉免登失败</title>
|
||||
<title>无法打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f8fafc;color:#0f172a;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -269,7 +269,7 @@ function createH5LoginErrorPage(message: string) {
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>钉钉免登失败</h1>
|
||||
<h1>无法打开问卷</h1>
|
||||
<p id="message"></p>
|
||||
</main>
|
||||
<script>
|
||||
@ -327,7 +327,7 @@ async function handleH5LoginPage(request: NextRequest, code: string) {
|
||||
})
|
||||
|
||||
if (!code) {
|
||||
return createH5LoginErrorPage('缺少钉钉免登授权码,请从钉钉工作通知重新打开')
|
||||
return createH5LoginErrorPage('暂时无法打开问卷,请从最新通知重新进入。')
|
||||
}
|
||||
|
||||
try {
|
||||
@ -355,7 +355,7 @@ async function handleH5LoginPage(request: NextRequest, code: string) {
|
||||
redirectPath,
|
||||
message: data?.message || '',
|
||||
})
|
||||
return createH5LoginErrorPage(data?.message || '钉钉登录未能创建素材库会话')
|
||||
return createH5LoginErrorPage('暂时无法打开问卷,请稍后重试或联系管理员。')
|
||||
}
|
||||
|
||||
if (data.needCompleteProfile) {
|
||||
@ -369,7 +369,7 @@ async function handleH5LoginPage(request: NextRequest, code: string) {
|
||||
return createSessionTicketTransferPage({ request, redirectPath, loginResponse })
|
||||
} catch (error: any) {
|
||||
console.error('钉钉H5免登页面跳转失败:', error)
|
||||
return createH5LoginErrorPage(error.message || '钉钉免登失败,请稍后再试')
|
||||
return createH5LoginErrorPage('暂时无法打开问卷,请稍后重试或联系管理员。')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -47,7 +47,7 @@ function createErrorPage(message: string, status = 410) {
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>正在进入素材库</title>
|
||||
<title>无法打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -58,7 +58,7 @@ function createErrorPage(message: string, status = 410) {
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>正在进入素材库</h1>
|
||||
<h1>无法打开问卷</h1>
|
||||
<p id="message"></p>
|
||||
</main>
|
||||
<script>
|
||||
@ -92,7 +92,7 @@ function createSessionRedirectResponse({
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>正在进入素材库</title>
|
||||
<title>正在打开问卷</title>
|
||||
<meta http-equiv="Cache-Control" content="no-store" />
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
@ -106,8 +106,8 @@ function createSessionRedirectResponse({
|
||||
<body>
|
||||
<main>
|
||||
<div class="spinner" aria-hidden="true"></div>
|
||||
<h1>正在进入素材库</h1>
|
||||
<p id="message">登录状态已写入,正在确认素材库登录状态...</p>
|
||||
<h1>正在打开问卷</h1>
|
||||
<p id="message">正在打开问卷...</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
@ -129,7 +129,7 @@ function createSessionRedirectResponse({
|
||||
async function confirmSessionThenEnter() {
|
||||
while (attempts < maxAttempts) {
|
||||
attempts += 1;
|
||||
setMessage('正在确认素材库登录状态...' + attempts + '/' + maxAttempts);
|
||||
setMessage('正在打开问卷...');
|
||||
|
||||
try {
|
||||
var response = await fetch('/api/auth/session?source=dingtalk_session_ticket&attempt=' + attempts + '&_=' + Date.now(), {
|
||||
@ -139,7 +139,7 @@ function createSessionRedirectResponse({
|
||||
var data = response.ok ? await response.json().catch(function () { return null; }) : null;
|
||||
|
||||
if (data && data.user) {
|
||||
setMessage('登录状态已确认,正在打开考核调研...');
|
||||
setMessage('正在打开问卷...');
|
||||
window.location.replace(targetUrl);
|
||||
return;
|
||||
}
|
||||
@ -150,7 +150,7 @@ function createSessionRedirectResponse({
|
||||
await wait(450);
|
||||
}
|
||||
|
||||
setMessage('登录状态写入后未被钉钉容器读取,请关闭当前页面后从最新通知重新进入。');
|
||||
setMessage('暂时无法打开问卷,请关闭当前页面后从最新通知重新进入。');
|
||||
}
|
||||
|
||||
window.setTimeout(confirmSessionThenEnter, 250);
|
||||
@ -182,7 +182,7 @@ function createSessionRedirectResponse({
|
||||
export async function GET(request: NextRequest) {
|
||||
const ticket = consumeDingtalkSessionTicket(request.nextUrl.searchParams.get('ticket'))
|
||||
if (!ticket) {
|
||||
return createErrorPage('登录票据已失效,请返回钉钉重新打开通知。')
|
||||
return createErrorPage('暂时无法打开问卷,请从最新通知重新进入。')
|
||||
}
|
||||
|
||||
return createSessionRedirectResponse({
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
exportPerformanceSurveyCsv,
|
||||
getPerformanceSurveyDetail,
|
||||
getPerformanceSurveyMe,
|
||||
getPerformanceSurveyNotificationStatus,
|
||||
getPerformanceSurveyResults,
|
||||
getPerformanceSurveyTemplates,
|
||||
listPerformanceSurveyDepartments,
|
||||
@ -76,6 +77,7 @@ async function getSession(request: Request): Promise<Session | null> {
|
||||
id: payload.userId,
|
||||
email: payload.email,
|
||||
name: payload.name,
|
||||
avatar: payload.avatar || null,
|
||||
role: payload.role,
|
||||
department: payload.department || '',
|
||||
managedDepartment: payload.managedDepartment || null,
|
||||
@ -127,6 +129,10 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
return ok(await getPerformanceSurveyResults(session, path[1], url.searchParams))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'notifications' && path[2] === 'status') {
|
||||
return ok(await getPerformanceSurveyNotificationStatus(session))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'notifications') {
|
||||
return ok(await listPerformanceSurveyNotifications(session, url.searchParams))
|
||||
}
|
||||
|
||||
@ -124,7 +124,7 @@ async function hasActiveSession() {
|
||||
|
||||
export default function DingtalkEntryClient({ corpId, redirectPath }: DingtalkEntryClientProps) {
|
||||
const startedRef = useRef(false)
|
||||
const [message, setMessage] = useState('正在通过钉钉确认身份...')
|
||||
const [message, setMessage] = useState('正在打开问卷...')
|
||||
|
||||
useEffect(() => {
|
||||
if (startedRef.current) return
|
||||
@ -132,32 +132,30 @@ export default function DingtalkEntryClient({ corpId, redirectPath }: DingtalkEn
|
||||
|
||||
const run = async () => {
|
||||
if (!corpId) {
|
||||
setMessage('钉钉免登配置缺少 CorpId,请联系管理员检查应用配置。')
|
||||
setMessage('暂时无法打开问卷,请联系管理员检查钉钉应用配置。')
|
||||
return
|
||||
}
|
||||
|
||||
if (!/DingTalk/i.test(window.navigator.userAgent || '')) {
|
||||
setMessage('请在钉钉客户端内重新打开通知。')
|
||||
setMessage('请在钉钉客户端内打开这条通知。')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setMessage('正在检查素材库登录状态...')
|
||||
setMessage('正在打开问卷...')
|
||||
if (await hasActiveSession()) {
|
||||
window.location.replace(redirectPath)
|
||||
return
|
||||
}
|
||||
|
||||
setMessage('正在加载钉钉免登组件...')
|
||||
await loadDingtalkJsApi()
|
||||
|
||||
setMessage('正在向钉钉获取免登授权码...')
|
||||
const authCode = await requestDingtalkAuthCode(corpId)
|
||||
|
||||
setMessage('正在进入素材库后端免登通道...')
|
||||
navigateDingtalkH5Login(authCode, redirectPath)
|
||||
} catch (error) {
|
||||
setMessage(`钉钉免登失败:${formatDingtalkError(error)}`)
|
||||
console.error('[Dingtalk Entry] 打开问卷失败:', error)
|
||||
setMessage('暂时无法打开问卷,请返回钉钉从最新通知重新进入。')
|
||||
}
|
||||
}
|
||||
|
||||
@ -168,7 +166,7 @@ export default function DingtalkEntryClient({ corpId, redirectPath }: DingtalkEn
|
||||
<main className="flex min-h-screen items-center justify-center bg-slate-950 px-6 text-slate-50">
|
||||
<section className="w-full max-w-sm text-center">
|
||||
<div className="mx-auto mb-5 h-10 w-10 animate-spin rounded-full border-4 border-white/25 border-t-sky-400" />
|
||||
<h1 className="mb-3 text-2xl font-semibold">正在进入素材库</h1>
|
||||
<h1 className="mb-3 text-2xl font-semibold">正在打开问卷</h1>
|
||||
<p className="text-sm leading-7 text-slate-300">{message}</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@ -82,6 +82,32 @@ function clearStoredDingtalkPerformanceToken() {
|
||||
}
|
||||
}
|
||||
|
||||
function decodeStoredDingtalkPerformanceSession() {
|
||||
const token = getStoredDingtalkPerformanceToken()
|
||||
const encodedPayload = token?.split('.')[0]
|
||||
if (!encodedPayload) return null
|
||||
|
||||
try {
|
||||
const normalized = encodedPayload.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padding = normalized.length % 4 === 0 ? '' : '='.repeat(4 - (normalized.length % 4))
|
||||
const binary = window.atob(normalized + padding)
|
||||
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0))
|
||||
const payload = JSON.parse(new TextDecoder().decode(bytes))
|
||||
return {
|
||||
id: String(payload.userId || ''),
|
||||
name: String(payload.name || ''),
|
||||
email: String(payload.email || ''),
|
||||
avatar: payload.avatar ? String(payload.avatar) : null,
|
||||
role: String(payload.role || 'USER'),
|
||||
department: String(payload.department || ''),
|
||||
managedDepartment: payload.managedDepartment ? String(payload.managedDepartment) : null,
|
||||
isSuperAdmin: Boolean(payload.isSuperAdmin),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePickerSearch(value: unknown) {
|
||||
return String(value ?? '')
|
||||
.trim()
|
||||
@ -172,9 +198,14 @@ export default function PerformanceSurveyPage() {
|
||||
const path = Array.isArray((params as any).path) ? ((params as any).path as string[]) : []
|
||||
const [dingtalkSessionChecked, setDingtalkSessionChecked] = useState(false)
|
||||
const [hasDingtalkPerformanceSession, setHasDingtalkPerformanceSession] = useState(false)
|
||||
const [dingtalkUserProfile, setDingtalkUserProfile] = useState<any>(null)
|
||||
const canLoadCurrentUser = Boolean(session || hasDingtalkPerformanceSession)
|
||||
const currentUser = useApi<any>(canLoadCurrentUser ? '/me' : null, [canLoadCurrentUser])
|
||||
|
||||
useEffect(() => {
|
||||
setHasDingtalkPerformanceSession(Boolean(getStoredDingtalkPerformanceToken()))
|
||||
const hasToken = Boolean(getStoredDingtalkPerformanceToken())
|
||||
setHasDingtalkPerformanceSession(hasToken)
|
||||
setDingtalkUserProfile(hasToken ? decodeStoredDingtalkPerformanceSession() : null)
|
||||
setDingtalkSessionChecked(true)
|
||||
}, [])
|
||||
|
||||
@ -202,16 +233,29 @@ export default function PerformanceSurveyPage() {
|
||||
return null
|
||||
}
|
||||
|
||||
const effectiveSession = session || ({
|
||||
const currentUserProfile = currentUser.data?.user || null
|
||||
const sessionUser = session?.user as any
|
||||
const effectiveSession = ({
|
||||
...(session || { expires: '' }),
|
||||
user: {
|
||||
name: '钉钉用户',
|
||||
email: '',
|
||||
role: 'USER',
|
||||
department: '',
|
||||
managedDepartment: null,
|
||||
isSuperAdmin: false,
|
||||
...(sessionUser || {}),
|
||||
id: currentUserProfile?.id || sessionUser?.id || dingtalkUserProfile?.id || '',
|
||||
name: currentUserProfile?.name || session?.user?.name || dingtalkUserProfile?.name || '当前用户',
|
||||
email: currentUserProfile?.email || session?.user?.email || dingtalkUserProfile?.email || '',
|
||||
avatar: currentUserProfile?.avatar || sessionUser?.avatar || dingtalkUserProfile?.avatar || null,
|
||||
role: currentUserProfile?.role || sessionUser?.role || dingtalkUserProfile?.role || 'USER',
|
||||
department: currentUserProfile?.department || sessionUser?.department || dingtalkUserProfile?.department || '',
|
||||
managedDepartment:
|
||||
currentUserProfile?.managedDepartment ||
|
||||
sessionUser?.managedDepartment ||
|
||||
dingtalkUserProfile?.managedDepartment ||
|
||||
null,
|
||||
isSuperAdmin:
|
||||
currentUserProfile?.isSuperAdmin ??
|
||||
sessionUser?.isSuperAdmin ??
|
||||
dingtalkUserProfile?.isSuperAdmin ??
|
||||
false,
|
||||
},
|
||||
expires: '',
|
||||
} as any)
|
||||
|
||||
let content = <Dashboard />
|
||||
@ -452,7 +496,11 @@ function ManagePanel({ onChanged, templateStats }: { onChanged: () => Promise<vo
|
||||
const templates = useApi<Template[]>('/templates', [])
|
||||
const departments = useApi<DepartmentOption[]>('/departments?purpose=evaluator', [])
|
||||
const notifications = useApi<any[]>('/admin/notifications?limit=30', [])
|
||||
const notificationStatus = useApi<any>('/admin/notifications/status', [])
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const refreshNotifications = async () => {
|
||||
await Promise.all([notifications.refresh(), notificationStatus.refresh()])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
@ -472,11 +520,11 @@ function ManagePanel({ onChanged, templateStats }: { onChanged: () => Promise<vo
|
||||
<div className="space-y-5">
|
||||
<AdminActions
|
||||
onMessage={setMessage}
|
||||
onNotificationsChanged={notifications.refresh}
|
||||
onNotificationsChanged={refreshNotifications}
|
||||
/>
|
||||
{message && <Panel><span className="text-sm text-green-700 dark:text-green-300">{message}</span></Panel>}
|
||||
</div>
|
||||
<NotificationList state={notifications} />
|
||||
<NotificationList state={notifications} statusState={notificationStatus} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@ -1082,8 +1130,16 @@ function AdminActions({
|
||||
)
|
||||
}
|
||||
|
||||
function NotificationList({ state }: { state: ApiState<any[]> & { refresh: () => Promise<void> } }) {
|
||||
function NotificationList({
|
||||
state,
|
||||
statusState,
|
||||
}: {
|
||||
state: ApiState<any[]> & { refresh: () => Promise<void> }
|
||||
statusState: ApiState<any> & { refresh: () => Promise<void> }
|
||||
}) {
|
||||
const [busyId, setBusyId] = useState<string | null>(null)
|
||||
const workNotice = statusState.data?.workNotice
|
||||
const counts = statusState.data?.counts || {}
|
||||
|
||||
const retry = async (id: string) => {
|
||||
setBusyId(id)
|
||||
@ -1099,8 +1155,32 @@ function NotificationList({ state }: { state: ApiState<any[]> & { refresh: () =>
|
||||
<div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-semibold text-gray-900 dark:text-white">钉钉通知</h2>
|
||||
<button onClick={state.refresh} className="text-sm text-gray-600 hover:text-gray-900 dark:text-gray-300">刷新</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await Promise.all([state.refresh(), statusState.refresh()])
|
||||
}}
|
||||
className="text-sm text-gray-600 hover:text-gray-900 dark:text-gray-300"
|
||||
>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
{workNotice && !workNotice.ready && (
|
||||
<div className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-700 dark:bg-amber-900/30 dark:text-amber-100">
|
||||
钉钉工作通知未就绪:缺少 {workNotice.missing?.join('、') || '必要配置'}
|
||||
</div>
|
||||
)}
|
||||
{workNotice?.ready && (
|
||||
<div className="mt-3 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-100">
|
||||
钉钉工作通知已就绪
|
||||
</div>
|
||||
)}
|
||||
{Object.keys(counts).length > 0 && (
|
||||
<div className="mt-3 flex flex-wrap gap-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
{Object.entries(counts).map(([status, count]) => (
|
||||
<span key={status} className="rounded-md bg-gray-100 px-2 py-1 dark:bg-gray-700">{status}: {String(count)}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3 space-y-2">
|
||||
{state.loading && <div className="text-sm text-gray-500">加载中...</div>}
|
||||
{state.error && <div className="text-sm text-red-600">{state.error}</div>}
|
||||
@ -1147,20 +1227,21 @@ function SurveySubmit({ surveyId }: { surveyId: string }) {
|
||||
)
|
||||
const activeTargetId = targetId || targets[0]?.id || ''
|
||||
const template = detail.data?.template as Template | undefined
|
||||
const questions = useMemo(() => template?.questions || [], [template])
|
||||
|
||||
useEffect(() => {
|
||||
if (!targetId && targets[0]?.id) setTargetId(targets[0].id)
|
||||
}, [targets, targetId])
|
||||
|
||||
useEffect(() => {
|
||||
if (template?.questions) {
|
||||
if (questions.length > 0) {
|
||||
setScores(
|
||||
Object.fromEntries(
|
||||
template.questions.map((question) => [question.id, 16]),
|
||||
questions.map((question) => [question.id, 16]),
|
||||
),
|
||||
)
|
||||
}
|
||||
}, [template?.code])
|
||||
}, [questions])
|
||||
|
||||
const submit = async () => {
|
||||
setSubmitting(true)
|
||||
@ -1179,32 +1260,61 @@ function SurveySubmit({ surveyId }: { surveyId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
if (detail.loading) return <MainPanel>加载中...</MainPanel>
|
||||
if (detail.loading) return <MainPanel>正在打开问卷...</MainPanel>
|
||||
if (detail.error) return <MainPanel><ErrorPanel message={detail.error} /></MainPanel>
|
||||
if (!detail.data) return null
|
||||
|
||||
const activeTarget = detail.data.targets.find((target: any) => target.id === activeTargetId)
|
||||
const submitted = activeTarget?.currentAssignment?.status === 'submitted'
|
||||
const scoreValues = questions.map((question) => Number(scores[question.id] ?? 16))
|
||||
const scoreTotal = scoreValues.reduce((sum, value) => sum + value, 0)
|
||||
const averageScore = questions.length > 0 ? (scoreTotal / questions.length).toFixed(1) : '-'
|
||||
const ratedCount = questions.filter((question) => typeof scores[question.id] === 'number').length
|
||||
const progressPercent = questions.length > 0 ? Math.round((ratedCount / questions.length) * 100) : 0
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-6">
|
||||
<main className="mx-auto max-w-3xl px-3 pb-24 pt-4 sm:px-4 sm:pb-8 sm:pt-6">
|
||||
<div className="mb-4">
|
||||
<Link href="/performance-survey" className="text-sm text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white">返回考核调研</Link>
|
||||
<h1 className="mt-3 text-2xl font-semibold text-gray-900 dark:text-white">{detail.data.title}</h1>
|
||||
<div className="mt-2 flex flex-wrap gap-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
<h1 className="mt-3 text-xl font-semibold leading-snug text-gray-900 dark:text-white sm:text-2xl">{detail.data.title}</h1>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
<StatusBadge status={detail.data.status} />
|
||||
{detail.data.dueAt && <span>截止 {formatDate(detail.data.dueAt)}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-800">
|
||||
<section className="mb-4 rounded-lg border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">评价对象</div>
|
||||
<div className="mt-1 truncate text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{activeTarget?.targetName || '待选择'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-gray-50 px-3 py-2 text-right dark:bg-gray-900/40">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">平均分</div>
|
||||
<div className="mt-0.5 text-lg font-semibold text-gray-900 dark:text-white">{averageScore}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<div className="mb-1.5 flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>评分进度</span>
|
||||
<span>{ratedCount}/{questions.length || 0}</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-gray-100 dark:bg-gray-700">
|
||||
<div
|
||||
className="h-full rounded-full bg-gray-900 transition-all dark:bg-white"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{targets.length > 1 && (
|
||||
<label className="mb-4 grid gap-1 text-sm">
|
||||
<label className="mt-4 grid gap-1.5 text-sm">
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300">评价对象</span>
|
||||
<select
|
||||
value={activeTargetId}
|
||||
onChange={(event) => setTargetId(event.target.value)}
|
||||
className="rounded-lg border border-gray-300 bg-white px-3 py-2 dark:border-gray-600 dark:bg-gray-900 dark:text-white"
|
||||
className="min-h-11 rounded-lg border border-gray-300 bg-white px-3 py-2 text-base text-gray-900 dark:border-gray-600 dark:bg-gray-900 dark:text-white sm:text-sm"
|
||||
>
|
||||
{targets.map((target: any) => (
|
||||
<option key={target.id} value={target.id}>{target.targetName}</option>
|
||||
@ -1212,58 +1322,66 @@ function SurveySubmit({ surveyId }: { surveyId: string }) {
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{activeTarget && (
|
||||
<div className="mb-4 rounded-lg bg-gray-50 px-3 py-2 text-sm text-gray-700 dark:bg-gray-900/40 dark:text-gray-200">
|
||||
{activeTarget.targetName}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{submitted ? (
|
||||
<EmptyState title="你已提交该评价" />
|
||||
) : detail.data.status !== 'open' ? (
|
||||
<EmptyState title="该调研未开放或已关闭" />
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
{template?.questions?.map((question) => (
|
||||
<div key={question.id}>
|
||||
<div className="mb-2 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-white">{question.title}</div>
|
||||
{question.description && <div className="text-sm text-gray-500 dark:text-gray-400">{question.description}</div>}
|
||||
</div>
|
||||
<span className="w-10 text-right text-sm font-semibold text-gray-900 dark:text-white">{scores[question.id] ?? 16}</span>
|
||||
{submitted ? (
|
||||
<EmptyState title="你已提交该评价" />
|
||||
) : detail.data.status !== 'open' ? (
|
||||
<EmptyState title="该调研未开放或已关闭" />
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{questions.map((question, index) => (
|
||||
<section key={question.id} className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs font-medium text-gray-400 dark:text-gray-500">问题 {index + 1}</div>
|
||||
<div className="mt-1 font-medium leading-snug text-gray-900 dark:text-white">{question.title}</div>
|
||||
{question.description && <div className="mt-1 text-sm leading-6 text-gray-500 dark:text-gray-400">{question.description}</div>}
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={20}
|
||||
value={scores[question.id] ?? 16}
|
||||
onChange={(event) => setScores((current) => ({ ...current, [question.id]: Number(event.target.value) }))}
|
||||
className="w-full"
|
||||
/>
|
||||
<span className="shrink-0 rounded-md bg-gray-900 px-2.5 py-1 text-sm font-semibold text-white dark:bg-white dark:text-gray-900">{scores[question.id] ?? 16}/20</span>
|
||||
</div>
|
||||
))}
|
||||
<label className="grid gap-1 text-sm">
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={20}
|
||||
value={scores[question.id] ?? 16}
|
||||
onChange={(event) => setScores((current) => ({ ...current, [question.id]: Number(event.target.value) }))}
|
||||
className="h-8 w-full accent-gray-900 dark:accent-white"
|
||||
/>
|
||||
<div className="mt-1 flex justify-between text-[11px] text-gray-400 dark:text-gray-500">
|
||||
<span>0</span>
|
||||
<span>10</span>
|
||||
<span>20</span>
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<section className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||||
<label className="grid gap-1.5 text-sm">
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300">补充评价</span>
|
||||
<textarea
|
||||
value={comment}
|
||||
onChange={(event) => setComment(event.target.value)}
|
||||
rows={4}
|
||||
className="rounded-lg border border-gray-300 px-3 py-2 dark:border-gray-600 dark:bg-gray-900 dark:text-white"
|
||||
placeholder="可以补充具体建议或说明"
|
||||
className="min-h-28 rounded-lg border border-gray-300 px-3 py-2 text-base text-gray-900 dark:border-gray-600 dark:bg-gray-900 dark:text-white sm:text-sm"
|
||||
/>
|
||||
</label>
|
||||
{message && <div className="text-sm text-gray-600 dark:text-gray-300">{message}</div>}
|
||||
</section>
|
||||
|
||||
{message && <div className="rounded-lg bg-gray-100 px-3 py-2 text-sm text-gray-700 dark:bg-gray-800 dark:text-gray-200">{message}</div>}
|
||||
|
||||
<div className="sticky bottom-0 -mx-3 border-t border-gray-200 bg-gray-50/95 p-3 backdrop-blur dark:border-gray-700 dark:bg-gray-900/95 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:p-0 sm:backdrop-blur-none">
|
||||
<button
|
||||
disabled={submitting || !activeTargetId}
|
||||
onClick={submit}
|
||||
className="rounded-lg bg-gray-900 px-4 py-2 text-white hover:bg-gray-700 disabled:opacity-50 dark:bg-white dark:text-gray-900"
|
||||
className="min-h-11 w-full rounded-lg bg-gray-900 px-4 py-2.5 text-base font-medium text-white hover:bg-gray-700 disabled:opacity-50 dark:bg-white dark:text-gray-900 sm:w-auto sm:text-sm"
|
||||
>
|
||||
{submitting ? '提交中...' : '提交评价'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@ -1418,8 +1536,17 @@ function EmptyState({ title }: { title: string }) {
|
||||
|
||||
function LoadingPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-400">
|
||||
加载中...
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 px-6 text-gray-500 dark:bg-gray-900 dark:text-gray-300">
|
||||
<div className="w-full max-w-xs text-center">
|
||||
<div className="mx-auto mb-5 h-10 w-10 animate-spin rounded-full border-4 border-gray-200 border-t-gray-900 dark:border-gray-700 dark:border-t-white" />
|
||||
<h1 className="text-xl font-semibold text-gray-900 dark:text-white">正在打开问卷</h1>
|
||||
<p className="mt-2 text-sm">请稍候</p>
|
||||
<div className="mt-6 space-y-2 rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-700 dark:bg-gray-800">
|
||||
<div className="h-3 w-2/3 rounded bg-gray-100 dark:bg-gray-700" />
|
||||
<div className="h-3 w-full rounded bg-gray-100 dark:bg-gray-700" />
|
||||
<div className="h-3 w-5/6 rounded bg-gray-100 dark:bg-gray-700" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@ -279,30 +279,34 @@ export default function Header({ session }: HeaderProps) {
|
||||
className="sticky top-0 z-50 shadow-sm"
|
||||
style={{ backgroundColor: headerBgColor }}
|
||||
>
|
||||
<div className="container mx-auto px-4 py-4 max-w-7xl">
|
||||
<div className="container mx-auto max-w-7xl px-3 py-3 sm:px-4 sm:py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
{/* Logo */}
|
||||
<Link href="/" onClick={handleLogoHomeClick} className="flex items-center space-x-3">
|
||||
<Link href="/" onClick={handleLogoHomeClick} className="flex min-w-0 items-center space-x-2 sm:space-x-3">
|
||||
<Image
|
||||
src={headerLogoUrl}
|
||||
alt={siteName}
|
||||
width={40}
|
||||
height={40}
|
||||
width={36}
|
||||
height={36}
|
||||
unoptimized
|
||||
className="rounded-lg"
|
||||
className="h-9 w-9 rounded-lg sm:h-10 sm:w-10"
|
||||
/>
|
||||
<span className="text-2xl font-semibold text-white">
|
||||
<span className="max-w-[11rem] truncate text-base font-semibold text-white sm:max-w-none sm:text-2xl">
|
||||
{siteName}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex items-center space-x-4">
|
||||
{session && <HeaderTaobaoSearch />}
|
||||
<nav className="flex items-center space-x-2 sm:space-x-4">
|
||||
{session && (
|
||||
<div className="hidden sm:block">
|
||||
<HeaderTaobaoSearch />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Network Status Indicator + 性能监控悬停卡片 */}
|
||||
{networkChecked && (
|
||||
<div className="relative" onMouseEnter={handlePerfMouseEnter} onMouseLeave={handlePerfMouseLeave}>
|
||||
<div className="relative hidden sm:block" onMouseEnter={handlePerfMouseEnter} onMouseLeave={handlePerfMouseLeave}>
|
||||
<div
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
|
||||
isInternalNetwork
|
||||
|
||||
162
lib/__tests__/performance-survey-notifications.test.ts
Normal file
162
lib/__tests__/performance-survey-notifications.test.ts
Normal file
@ -0,0 +1,162 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import {
|
||||
processPerformanceSurveyNotification,
|
||||
recoverDuePerformanceSurveyNotifications,
|
||||
retryPerformanceSurveyNotification,
|
||||
} from '@/lib/performance-survey-notifications'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { sendDingtalkWorkNotice } from '@/lib/dingtalk-client'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
performanceSurveyNotification: {
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
performanceSurveyEmployeeProfile: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/dingtalk-client', () => ({
|
||||
sendDingtalkWorkNotice: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/public-app-url', () => ({
|
||||
getPublicAppOrigin: jest.fn(() => 'https://sc.jiansun.vip'),
|
||||
}))
|
||||
|
||||
function notification(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'notification-1',
|
||||
dingtalkUserId: null,
|
||||
recipientUserId: null,
|
||||
recipientEmployeeId: null,
|
||||
title: '你有新的考核调研待填写',
|
||||
content: '请填写考核调研',
|
||||
actionUrl: 'https://sc.jiansun.vip/performance-survey/survey/survey-1',
|
||||
status: 'pending',
|
||||
attemptCount: 0,
|
||||
maxAttempts: 5,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('performance survey notifications', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.useFakeTimers()
|
||||
;(prisma.performanceSurveyNotification.update as jest.Mock).mockResolvedValue({})
|
||||
;(prisma.performanceSurveyNotification.updateMany as jest.Mock).mockResolvedValue({ count: 0 })
|
||||
;(prisma.performanceSurveyNotification.findMany as jest.Mock).mockResolvedValue([])
|
||||
;(prisma.performanceSurveyEmployeeProfile.findUnique as jest.Mock).mockResolvedValue(null)
|
||||
;(prisma.user.findUnique as jest.Mock).mockResolvedValue(null)
|
||||
;(prisma.user.findFirst as jest.Mock).mockResolvedValue(null)
|
||||
;(sendDingtalkWorkNotice as jest.Mock).mockResolvedValue({
|
||||
taskId: 'task-1',
|
||||
raw: { errcode: 0, task_id: 'task-1' },
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
test('发送前会从素材库用户绑定补齐钉钉 userId', async () => {
|
||||
;(prisma.performanceSurveyNotification.findUnique as jest.Mock).mockResolvedValue(
|
||||
notification({ recipientUserId: 'user-1' }),
|
||||
)
|
||||
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ dingtalkUserId: 'ding-user-1' })
|
||||
|
||||
const result = await processPerformanceSurveyNotification('notification-1')
|
||||
|
||||
expect(result).toEqual({ success: true, status: 'succeeded' })
|
||||
expect(sendDingtalkWorkNotice).toHaveBeenCalledWith({
|
||||
userIds: ['ding-user-1'],
|
||||
title: '你有新的考核调研待填写',
|
||||
text: '请填写考核调研',
|
||||
actionUrl: 'https://sc.jiansun.vip/performance-survey/survey/survey-1',
|
||||
})
|
||||
expect(prisma.performanceSurveyNotification.update).toHaveBeenCalledWith({
|
||||
where: { id: 'notification-1' },
|
||||
data: expect.objectContaining({ dingtalkUserId: 'ding-user-1' }),
|
||||
})
|
||||
})
|
||||
|
||||
test('人员档案缺 userId 时会通过邮箱匹配素材库用户', async () => {
|
||||
;(prisma.performanceSurveyNotification.findUnique as jest.Mock).mockResolvedValue(
|
||||
notification({ recipientEmployeeId: 'employee-1' }),
|
||||
)
|
||||
;(prisma.performanceSurveyEmployeeProfile.findUnique as jest.Mock).mockResolvedValue({
|
||||
dingtalkUserId: null,
|
||||
dingEmail: 'user@example.com',
|
||||
})
|
||||
;(prisma.user.findFirst as jest.Mock).mockResolvedValue({ dingtalkUserId: 'ding-user-2' })
|
||||
|
||||
await processPerformanceSurveyNotification('notification-1')
|
||||
|
||||
expect(sendDingtalkWorkNotice).toHaveBeenCalledWith(expect.objectContaining({
|
||||
userIds: ['ding-user-2'],
|
||||
}))
|
||||
})
|
||||
|
||||
test('缺少钉钉 userId 时记录为 skipped,不调用钉钉接口', async () => {
|
||||
;(prisma.performanceSurveyNotification.findUnique as jest.Mock).mockResolvedValue(notification())
|
||||
|
||||
const result = await processPerformanceSurveyNotification('notification-1')
|
||||
|
||||
expect(result).toEqual({ success: false, status: 'skipped' })
|
||||
expect(sendDingtalkWorkNotice).not.toHaveBeenCalled()
|
||||
expect(prisma.performanceSurveyNotification.update).toHaveBeenCalledWith({
|
||||
where: { id: 'notification-1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'skipped',
|
||||
lastError: '收件人缺少钉钉 userId',
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
test('手工补发会重置重试次数和历史发送结果', async () => {
|
||||
await retryPerformanceSurveyNotification('notification-1')
|
||||
|
||||
expect(prisma.performanceSurveyNotification.update).toHaveBeenCalledWith({
|
||||
where: { id: 'notification-1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'pending',
|
||||
attemptCount: 0,
|
||||
maxAttempts: 5,
|
||||
lastStatusCode: null,
|
||||
lastResponseBody: null,
|
||||
lastError: null,
|
||||
providerMessageId: null,
|
||||
sentAt: null,
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
test('维护任务会把长时间 processing 的通知重新入队', async () => {
|
||||
;(prisma.performanceSurveyNotification.findMany as jest.Mock).mockResolvedValue([{ id: 'notification-1' }])
|
||||
|
||||
const recovered = await recoverDuePerformanceSurveyNotifications()
|
||||
|
||||
expect(recovered).toBe(1)
|
||||
expect(prisma.performanceSurveyNotification.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
status: 'processing',
|
||||
updatedAt: { lte: expect.any(Date) },
|
||||
},
|
||||
data: expect.objectContaining({
|
||||
status: 'retrying',
|
||||
lastError: '上次投递处理中断,已重新入队',
|
||||
}),
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -10,6 +10,7 @@ export type DingtalkPerformanceSessionPayload = {
|
||||
userId: string
|
||||
email: string
|
||||
name: string
|
||||
avatar?: string | null
|
||||
role: DingtalkPerformanceRole
|
||||
department?: string | null
|
||||
managedDepartment?: string | null
|
||||
@ -23,6 +24,7 @@ type DingtalkPerformanceUser = {
|
||||
id: string
|
||||
email: string
|
||||
username: string
|
||||
avatar?: string | null
|
||||
role: string
|
||||
department?: string | null
|
||||
managedDepartment?: string | null
|
||||
@ -86,6 +88,7 @@ export function createDingtalkPerformanceSessionToken(user: DingtalkPerformanceU
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.username,
|
||||
avatar: user.avatar || null,
|
||||
role: normalizeRole(user.role),
|
||||
department: user.department || '',
|
||||
managedDepartment: user.managedDepartment || null,
|
||||
|
||||
@ -17,6 +17,7 @@ const MAX_ATTEMPTS = 5
|
||||
const RETRY_DELAYS_MS = [0, 60_000, 5 * 60_000, 15 * 60_000, 30 * 60_000, 60 * 60_000]
|
||||
const RECOVERY_INTERVAL_MS = 60_000
|
||||
const REMINDER_INTERVAL_MS = 10 * 60_000
|
||||
const STALE_PROCESSING_MS = 5 * 60_000
|
||||
|
||||
let workerStarted = false
|
||||
let recoveryTimer: NodeJS.Timeout | null = null
|
||||
@ -47,6 +48,49 @@ function getSurveyUrl(path: string) {
|
||||
return `${getPublicAppOrigin()}${buildDingtalkEntryPath(path)}`
|
||||
}
|
||||
|
||||
function clean(value: unknown) {
|
||||
const normalized = String(value ?? '').trim()
|
||||
return normalized.length > 0 ? normalized : null
|
||||
}
|
||||
|
||||
async function resolveNotificationDingtalkUserId(notification: {
|
||||
dingtalkUserId?: string | null
|
||||
recipientUserId?: string | null
|
||||
recipientEmployeeId?: string | null
|
||||
}) {
|
||||
const current = clean(notification.dingtalkUserId)
|
||||
if (current) return current
|
||||
|
||||
const recipientUserId = clean(notification.recipientUserId)
|
||||
if (recipientUserId) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: recipientUserId },
|
||||
select: { dingtalkUserId: true },
|
||||
})
|
||||
const userDingtalkUserId = clean(user?.dingtalkUserId)
|
||||
if (userDingtalkUserId) return userDingtalkUserId
|
||||
}
|
||||
|
||||
const recipientEmployeeId = clean(notification.recipientEmployeeId)
|
||||
if (!recipientEmployeeId) return null
|
||||
|
||||
const employee = await prisma.performanceSurveyEmployeeProfile.findUnique({
|
||||
where: { id: recipientEmployeeId },
|
||||
select: { dingtalkUserId: true, dingEmail: true },
|
||||
})
|
||||
const employeeDingtalkUserId = clean(employee?.dingtalkUserId)
|
||||
if (employeeDingtalkUserId) return employeeDingtalkUserId
|
||||
|
||||
const email = clean(employee?.dingEmail)
|
||||
if (!email) return null
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { email },
|
||||
select: { dingtalkUserId: true },
|
||||
})
|
||||
return clean(user?.dingtalkUserId)
|
||||
}
|
||||
|
||||
export function ensurePerformanceSurveyNotificationWorkerStarted() {
|
||||
if (workerStarted) return
|
||||
workerStarted = true
|
||||
@ -274,6 +318,18 @@ export async function queueDuePerformanceSurveyReminders() {
|
||||
export async function recoverDuePerformanceSurveyNotifications(limit = 20) {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
await prisma.performanceSurveyNotification.updateMany({
|
||||
where: {
|
||||
status: STATUS.PROCESSING,
|
||||
updatedAt: { lte: new Date(Date.now() - STALE_PROCESSING_MS) },
|
||||
},
|
||||
data: {
|
||||
status: STATUS.RETRYING,
|
||||
nextRetryAt: new Date(),
|
||||
lastError: '上次投递处理中断,已重新入队',
|
||||
},
|
||||
})
|
||||
|
||||
const rows = await prisma.performanceSurveyNotification.findMany({
|
||||
where: {
|
||||
status: { in: [STATUS.PENDING, STATUS.RETRYING] },
|
||||
@ -297,7 +353,13 @@ export async function retryPerformanceSurveyNotification(notificationId: string)
|
||||
status: STATUS.PENDING,
|
||||
nextRetryAt: new Date(),
|
||||
completedAt: null,
|
||||
attemptCount: 0,
|
||||
maxAttempts: MAX_ATTEMPTS,
|
||||
lastStatusCode: null,
|
||||
lastResponseBody: null,
|
||||
lastError: null,
|
||||
providerMessageId: null,
|
||||
sentAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
@ -324,7 +386,8 @@ export async function processPerformanceSurveyNotification(notificationId: strin
|
||||
},
|
||||
})
|
||||
|
||||
if (!notification.dingtalkUserId) {
|
||||
const resolvedDingtalkUserId = await resolveNotificationDingtalkUserId(notification)
|
||||
if (!resolvedDingtalkUserId) {
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
@ -336,9 +399,19 @@ export async function processPerformanceSurveyNotification(notificationId: strin
|
||||
return { success: false, status: STATUS.SKIPPED }
|
||||
}
|
||||
|
||||
if (resolvedDingtalkUserId !== notification.dingtalkUserId) {
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
dingtalkUserId: resolvedDingtalkUserId,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await sendDingtalkWorkNotice({
|
||||
userIds: [notification.dingtalkUserId],
|
||||
userIds: [resolvedDingtalkUserId],
|
||||
title: notification.title,
|
||||
text: notification.content,
|
||||
actionUrl: notification.actionUrl,
|
||||
|
||||
@ -2,6 +2,7 @@ import { randomUUID } from 'crypto'
|
||||
import type { Session } from 'next-auth'
|
||||
import { pinyin } from 'pinyin-pro'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getDingtalkWorkNoticeConfigStatus } from '@/lib/dingtalk-client'
|
||||
import {
|
||||
calculateAggregateScore,
|
||||
calculateResponseScores,
|
||||
@ -45,6 +46,7 @@ type UserContext = {
|
||||
isSuperAdmin: boolean
|
||||
dingtalkUserId: string | null
|
||||
realName: string | null
|
||||
avatar: string | null
|
||||
}
|
||||
employee: any | null
|
||||
isSystemAdmin: boolean
|
||||
@ -301,6 +303,7 @@ export async function getPerformanceSurveyContext(session: Session | null): Prom
|
||||
isSuperAdmin: true,
|
||||
dingtalkUserId: true,
|
||||
realName: true,
|
||||
avatar: true,
|
||||
},
|
||||
})
|
||||
|
||||
@ -348,6 +351,7 @@ export async function getPerformanceSurveyMe(session: Session | null) {
|
||||
department: ctx.user.department,
|
||||
managedDepartment: ctx.user.managedDepartment,
|
||||
dingtalkUserId: ctx.user.dingtalkUserId,
|
||||
avatar: ctx.user.avatar,
|
||||
},
|
||||
employee: ctx.employee ? getEmployeeSnapshot(ctx.employee) : null,
|
||||
permissions: {
|
||||
@ -1235,6 +1239,27 @@ export async function listPerformanceSurveyNotifications(session: Session | null
|
||||
}))
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyNotificationStatus(session: Session | null) {
|
||||
const ctx = await getPerformanceSurveyContext(session)
|
||||
ensureManager(ctx)
|
||||
|
||||
const where: any = {}
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
||||
where.survey = { departmentName: ctx.scopeDepartment }
|
||||
}
|
||||
|
||||
const grouped = await prisma.performanceSurveyNotification.groupBy({
|
||||
by: ['status'],
|
||||
where,
|
||||
_count: { _all: true },
|
||||
})
|
||||
|
||||
return {
|
||||
workNotice: getDingtalkWorkNoticeConfigStatus(),
|
||||
counts: Object.fromEntries(grouped.map((row) => [row.status, row._count._all])),
|
||||
}
|
||||
}
|
||||
|
||||
export async function retryPerformanceSurveyNotificationById(session: Session | null, notificationId: string) {
|
||||
const ctx = await getPerformanceSurveyContext(session)
|
||||
ensureManager(ctx)
|
||||
@ -1341,14 +1366,16 @@ async function resolveSurveyEvaluators(body: any, ctx: UserContext) {
|
||||
select: { id: true, dingtalkUserId: true, email: true },
|
||||
})
|
||||
: []
|
||||
const userIdByDing = new Map(users.map((user) => [user.dingtalkUserId, user.id]).filter(([dingtalkUserId]) => Boolean(dingtalkUserId)) as Array<[string, string]>)
|
||||
const userIdByEmail = new Map(users.map((user) => [user.email, user.id]))
|
||||
const userByDing = new Map(users.map((user) => [user.dingtalkUserId, user]).filter(([dingtalkUserId]) => Boolean(dingtalkUserId)) as Array<[string, (typeof users)[number]]>)
|
||||
const userByEmail = new Map(users.map((user) => [user.email, user]))
|
||||
|
||||
const deduped = new Map<string, any>()
|
||||
for (const employee of employees) {
|
||||
const dingtalkUserId = employee.dingtalkUserId || null
|
||||
const userId = (dingtalkUserId ? userIdByDing.get(dingtalkUserId) || null : null)
|
||||
|| (employee.dingEmail ? userIdByEmail.get(employee.dingEmail) || null : null)
|
||||
const profileDingtalkUserId = clean(employee.dingtalkUserId)
|
||||
const matchedUser = (profileDingtalkUserId ? userByDing.get(profileDingtalkUserId) || null : null)
|
||||
|| (employee.dingEmail ? userByEmail.get(employee.dingEmail) || null : null)
|
||||
const dingtalkUserId = profileDingtalkUserId || clean(matchedUser?.dingtalkUserId)
|
||||
const userId = matchedUser?.id || null
|
||||
const evaluatorKey = getEvaluatorKey({
|
||||
employeeId: employee.id,
|
||||
userId,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user