From f4236c44c44590fb1f37745ed2be0299245bbb31 Mon Sep 17 00:00:00 2001 From: chenpei Date: Fri, 3 Jul 2026 15:12:20 +0800 Subject: [PATCH] feat: add native performance survey module --- app/api/dingtalk/login/route.ts | 50 +- app/api/performance-survey/[...path]/route.ts | 159 +++ app/performance-survey/[[...path]]/page.tsx | 1023 ++++++++++++++++ app/teacher/[[...path]]/page.tsx | 5 + components/Header.tsx | 12 + lib/dingtalk-client.ts | 133 +++ lib/env-validation.ts | 21 + lib/performance-survey-notifications.ts | 404 +++++++ lib/performance-survey-report-sync.ts | 741 ++++++++++++ lib/performance-survey-service.ts | 1049 +++++++++++++++++ lib/performance-survey-templates.ts | 234 ++++ package-lock.json | 704 +++++++++-- package.json | 1 + .../migration.sql | 285 +++++ prisma/schema.prisma | 228 ++++ types/mssql.d.ts | 23 + 16 files changed, 4953 insertions(+), 119 deletions(-) create mode 100644 app/api/performance-survey/[...path]/route.ts create mode 100644 app/performance-survey/[[...path]]/page.tsx create mode 100644 app/teacher/[[...path]]/page.tsx create mode 100644 lib/dingtalk-client.ts create mode 100644 lib/performance-survey-notifications.ts create mode 100644 lib/performance-survey-report-sync.ts create mode 100644 lib/performance-survey-service.ts create mode 100644 lib/performance-survey-templates.ts create mode 100644 prisma/migrations/20260703_add_performance_survey_native/migration.sql create mode 100644 types/mssql.d.ts diff --git a/app/api/dingtalk/login/route.ts b/app/api/dingtalk/login/route.ts index 75928d5c..53c6c627 100644 --- a/app/api/dingtalk/login/route.ts +++ b/app/api/dingtalk/login/route.ts @@ -1,5 +1,7 @@ import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' +import { getDingtalkAppAccessToken } from '@/lib/dingtalk-client' +import { ensurePerformanceSurveyEmployeeProfileForUser } from '@/lib/performance-survey-report-sync' import bcrypt from 'bcryptjs' /** @@ -83,30 +85,26 @@ async function getUserAccessToken(code: string) { // 获取应用访问令牌 async function getAppAccessToken() { - const config = getDingtalkConfig() - const url = 'https://oapi.dingtalk.com/gettoken' - - const response = await fetch(`${url}?appkey=${config.clientId}&appsecret=${config.clientSecret}`) - - if (!response.ok) { - throw new Error('获取应用访问令牌失败') - } - - const data = await response.json() - - // 检查钉钉 API 返回的错误码 - if (data.errcode !== 0) { - console.error('钉钉API错误:', data) - throw new Error(`获取应用访问令牌失败: ${data.errmsg || '未知错误'}`) - } - - // 检查 access_token 是否存在 - if (!data.access_token) { - console.error('获取access_token返回数据异常:', data) - throw new Error('获取应用访问令牌失败: 返回数据中没有access_token') - } - - return data.access_token + return getDingtalkAppAccessToken() +} + +function warmPerformanceSurveyProfile(user: { + id: string + dingtalkUserId: string | null + email: string + username: string + realName: string | null +}) { + void ensurePerformanceSurveyEmployeeProfileForUser({ + userId: user.id, + dingtalkUserId: user.dingtalkUserId, + email: user.email, + username: user.username, + realName: user.realName, + displayName: user.realName || user.username, + }).catch((error) => { + console.warn('[performance-survey] 钉钉登录后预热人员档案失败:', error) + }) } // 根据token获取用户unionId @@ -342,6 +340,7 @@ export async function POST(request: NextRequest) { // 如果需要完善信息(选择部门) if (needCompleteProfile) { + warmPerformanceSurveyProfile(user) return NextResponse.json({ success: true, needCompleteProfile: true, @@ -364,6 +363,7 @@ export async function POST(request: NextRequest) { const isUserActive = userStatus === 'active'; if (!isUserActive) { + warmPerformanceSurveyProfile(user) return NextResponse.json({ success: false, message: '您的账号尚未激活,请联系管理员激活后再登录' @@ -399,6 +399,8 @@ export async function POST(request: NextRequest) { }); // 返回用户信息(不包含敏感信息) + warmPerformanceSurveyProfile(user) + return NextResponse.json({ success: true, needCompleteProfile: false, diff --git a/app/api/performance-survey/[...path]/route.ts b/app/api/performance-survey/[...path]/route.ts new file mode 100644 index 00000000..5ebafccb --- /dev/null +++ b/app/api/performance-survey/[...path]/route.ts @@ -0,0 +1,159 @@ +import { getServerSession } from 'next-auth' +import { NextResponse } from 'next/server' +import { authOptions } from '@/lib/auth' +import { + PerformanceSurveyApiError, + createPerformanceSurvey, + exportPerformanceSurveyCsv, + getPerformanceSurveyDetail, + getPerformanceSurveyMe, + getPerformanceSurveyResults, + getPerformanceSurveyTemplates, + listPerformanceSurveyDepartments, + listPerformanceSurveyNotifications, + listPerformanceSurveys, + retryPerformanceSurveyNotificationById, + runPerformanceSurveyNotificationMaintenance, + searchPerformanceSurveyEmployees, + submitPerformanceSurveyResponse, + syncPerformanceSurveyEmployeeProfiles, + updatePerformanceSurvey, +} from '@/lib/performance-survey-service' + +export const runtime = 'nodejs' +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +type RouteContext = { + params: { + path?: string[] + } +} + +function ok(data: unknown, init?: ResponseInit) { + return NextResponse.json({ success: true, data }, init) +} + +function errorResponse(error: unknown) { + if (error instanceof PerformanceSurveyApiError) { + return NextResponse.json({ success: false, error: error.message }, { status: error.status }) + } + + const message = error instanceof Error ? error.message : '服务器错误' + console.error('[performance-survey] API error:', error) + return NextResponse.json({ success: false, error: message }, { status: 500 }) +} + +async function getSession() { + return getServerSession(authOptions) +} + +function getPath(context: RouteContext) { + return context.params.path || [] +} + +export async function GET(request: Request, context: RouteContext) { + try { + const session = await getSession() + const path = getPath(context) + const url = new URL(request.url) + + if (path.length === 0 || path[0] === 'me') { + return ok(await getPerformanceSurveyMe(session)) + } + + if (path[0] === 'templates') { + return ok(await getPerformanceSurveyTemplates(session)) + } + + if (path[0] === 'employees') { + return ok(await searchPerformanceSurveyEmployees(session, url.searchParams)) + } + + if (path[0] === 'departments') { + return ok(await listPerformanceSurveyDepartments(session)) + } + + if (path[0] === 'surveys' && path.length === 1) { + return ok(await listPerformanceSurveys(session)) + } + + if (path[0] === 'surveys' && path[1] && path.length === 2) { + return ok(await getPerformanceSurveyDetail(session, path[1])) + } + + if (path[0] === 'surveys' && path[1] && path[2] === 'results') { + return ok(await getPerformanceSurveyResults(session, path[1], url.searchParams)) + } + + if (path[0] === 'results' && path[1]) { + return ok(await getPerformanceSurveyResults(session, path[1], url.searchParams)) + } + + if (path[0] === 'admin' && path[1] === 'notifications') { + return ok(await listPerformanceSurveyNotifications(session, url.searchParams)) + } + + if (path[0] === 'admin' && path[1] === 'export') { + const csv = await exportPerformanceSurveyCsv(session) + return new NextResponse(csv, { + headers: { + 'Content-Type': 'text/csv; charset=utf-8', + 'Content-Disposition': 'attachment; filename="performance-survey-export.csv"', + }, + }) + } + + return NextResponse.json({ success: false, error: '接口不存在' }, { status: 404 }) + } catch (error) { + return errorResponse(error) + } +} + +export async function POST(request: Request, context: RouteContext) { + try { + const session = await getSession() + const path = getPath(context) + const body = await request.json().catch(() => ({})) + + if (path[0] === 'surveys' && path.length === 1) { + return ok(await createPerformanceSurvey(session, body), { status: 201 }) + } + + if (path[0] === 'surveys' && path[1] && path[2] === 'responses') { + return ok(await submitPerformanceSurveyResponse(session, path[1], body)) + } + + if (path[0] === 'admin' && path[1] === 'sync-employees') { + return ok(await syncPerformanceSurveyEmployeeProfiles(session, body)) + } + + if (path[0] === 'admin' && path[1] === 'notifications' && path[2] === 'maintenance') { + return ok(await runPerformanceSurveyNotificationMaintenance(session)) + } + + if (path[0] === 'admin' && path[1] === 'notifications' && path[2] && path[3] === 'retry') { + return ok(await retryPerformanceSurveyNotificationById(session, path[2])) + } + + return NextResponse.json({ success: false, error: '接口不存在' }, { status: 404 }) + } catch (error) { + return errorResponse(error) + } +} + +export async function PATCH(request: Request, context: RouteContext) { + try { + const session = await getSession() + const path = getPath(context) + const body = await request.json().catch(() => ({})) + + if (path[0] === 'surveys' && path[1] && path.length === 2) { + return ok(await updatePerformanceSurvey(session, path[1], body)) + } + + return NextResponse.json({ success: false, error: '接口不存在' }, { status: 404 }) + } catch (error) { + return errorResponse(error) + } +} diff --git a/app/performance-survey/[[...path]]/page.tsx b/app/performance-survey/[[...path]]/page.tsx new file mode 100644 index 00000000..f31f502c --- /dev/null +++ b/app/performance-survey/[[...path]]/page.tsx @@ -0,0 +1,1023 @@ +'use client' + +import { useEffect, useMemo, useState, type ReactNode } from 'react' +import Link from 'next/link' +import { useParams, useRouter, useSearchParams } from 'next/navigation' +import { useSession } from 'next-auth/react' +import Header from '@/components/Header' + +type ApiState = { + loading: boolean + data: T | null + error: string | null +} + +type Employee = { + id: string + displayName: string + flowerName?: string | null + realName?: string | null + dingEmail?: string | null + jobNumber?: string | null + departmentName?: string | null + positionTitle?: string | null + positionLevel?: string | null + levelType?: string | null + isLeadership?: boolean | null + managerName?: string | null + dingtalkUserId?: string | null +} + +type Template = { + code: string + name: string + description: string + surveyType: string + weight: number + questions: Array<{ id: string; title: string; description?: string }> +} + +const API_BASE = '/api/performance-survey' + +async function apiRequest(path: string, options?: RequestInit): Promise { + const response = await fetch(`${API_BASE}${path}`, { + ...options, + headers: { + ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), + ...(options?.headers || {}), + }, + }) + const contentType = response.headers.get('content-type') || '' + const payload = contentType.includes('application/json') ? await response.json() : await response.text() + + if (!response.ok || (payload && typeof payload === 'object' && payload.success === false)) { + throw new Error( + payload && typeof payload === 'object' + ? payload.error || payload.message || '请求失败' + : String(payload || '请求失败'), + ) + } + + return (payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload) as T +} + +function useApi(path: string | null, deps: unknown[] = []): ApiState & { refresh: () => Promise } { + const [state, setState] = useState>({ loading: Boolean(path), data: null, error: null }) + + const load = async () => { + if (!path) return + setState((current) => ({ ...current, loading: true, error: null })) + try { + const data = await apiRequest(path) + setState({ loading: false, data, error: null }) + } catch (error) { + setState({ loading: false, data: null, error: error instanceof Error ? error.message : '加载失败' }) + } + } + + useEffect(() => { + void load() + }, deps) + + return { ...state, refresh: load } +} + +export default function PerformanceSurveyPage() { + const { data: session, status } = useSession() + const router = useRouter() + const params = useParams() + const path = Array.isArray((params as any).path) ? ((params as any).path as string[]) : [] + + useEffect(() => { + if (status === 'unauthenticated') { + router.push(`/login?redirect=${encodeURIComponent('/performance-survey')}`) + } + }, [status, router]) + + useEffect(() => { + if (path[0] === 'teacher' || path[0] === 'admin') { + router.replace('/performance-survey') + } + }, [path, router]) + + if (status === 'loading') { + return + } + + if (!session) { + return null + } + + let content = + if (path[0] === 'survey' && path[1]) { + content = + } + if (path[0] === 'results' && path[1]) { + content = + } + + return ( +
+
+ {content} +
+ ) +} + +function Dashboard() { + const [tab, setTab] = useState('pending') + const surveys = useApi('/surveys', []) + const me = useApi('/me', []) + const canManage = Boolean(me.data?.permissions?.isDepartmentAdmin) + + useEffect(() => { + if (canManage && tab === 'pending' && surveys.data?.pending?.length === 0) { + setTab('created') + } + }, [canManage, surveys.data, tab]) + + const tabs = [ + { id: 'pending', label: '待我评价' }, + { id: 'created', label: '我发起的' }, + { id: 'results', label: '我的结果' }, + ...(canManage ? [{ id: 'manage', label: '管理' }] : []), + ] + + return ( +
+
+
+

考核调研

+
+ {me.data?.user?.name || '当前用户'} + {me.data?.employee?.departmentName && {me.data.employee.departmentName}} + {me.data?.employee?.positionLevel && {me.data.employee.positionLevel}} +
+
+
+ {tabs.map((item) => ( + + ))} +
+
+ + {surveys.loading && 加载中...} + {surveys.error && } + {surveys.data && tab === 'pending' && } + {surveys.data && tab === 'created' && ( + + )} + {surveys.data && tab === 'results' && } + {canManage && tab === 'manage' && ( + { + await surveys.refresh() + }} + /> + )} +
+ ) +} + +function PendingList({ items }: { items: any[] }) { + if (items.length === 0) { + return + } + + return ( +
+ {items.map((item) => ( +
+
+
+

{item.title}

+

{item.targetName}

+
+ +
+
+ {item.dueAt ? `截止 ${formatDate(item.dueAt)}` : '无截止时间'} + + 填写 + +
+
+ ))} +
+ ) +} + +function CreatedList({ items, onRefresh }: { items: any[]; onRefresh: () => Promise }) { + const [busyId, setBusyId] = useState(null) + + const changeStatus = async (id: string, status: string) => { + setBusyId(id) + try { + await apiRequest(`/surveys/${id}`, { + method: 'PATCH', + body: JSON.stringify({ status }), + }) + await onRefresh() + } finally { + setBusyId(null) + } + } + + if (items.length === 0) { + return + } + + return ( +
+ + + + {['调研', '状态', '对象/评价/提交', '截止', '操作'].map((item) => ( + + ))} + + + + {items.map((item) => ( + + + + + + + + ))} + +
+ {item} +
+
{item.title}
+
{item.departmentName || '未指定部门'}
+
+ {item.counts?.targets || 0} / {item.counts?.assignments || 0} / {item.counts?.responses || 0} + {item.dueAt ? formatDate(item.dueAt) : '-'} +
+ {item.status === 'draft' && ( + + )} + {item.status !== 'closed' && ( + + )} + + 结果 + +
+
+
+ ) +} + +function MyResults({ items }: { items: any[] }) { + if (items.length === 0) { + return + } + + return ( +
+ {items.map((item) => ( + +

{item.title}

+

{item.targetName}

+

{item.closedAt ? formatDate(item.closedAt) : ''}

+ + ))} +
+ ) +} + +function ManagePanel({ onChanged }: { onChanged: () => Promise }) { + const templates = useApi('/templates', []) + const departments = useApi('/departments', []) + const notifications = useApi('/admin/notifications?limit=30', []) + const [message, setMessage] = useState(null) + + return ( +
+ { + setMessage('已创建考核调研') + await onChanged() + await notifications.refresh() + }} + /> +
+ + {message && {message}} + +
+
+ ) +} + +function CreateSurveyForm({ + templates, + departments, + onCreated, +}: { + templates: Template[] + departments: any[] + onCreated: () => Promise +}) { + const [title, setTitle] = useState('') + const [description, setDescription] = useState('') + const [surveyKind, setSurveyKind] = useState('person_period') + const [templateCode, setTemplateCode] = useState('') + const [dueAt, setDueAt] = useState('') + const [openNow, setOpenNow] = useState(true) + const [targetEmployees, setTargetEmployees] = useState([]) + const [evaluatorEmployees, setEvaluatorEmployees] = useState([]) + const [evaluatorDepartments, setEvaluatorDepartments] = useState([]) + const [itemName, setItemName] = useState('') + const [targetItems, setTargetItems] = useState>([]) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + + const activeTemplates = templates.filter((template) => template.surveyType === surveyKind) + const selectedTemplate = templateCode || activeTemplates[0]?.code || templates[0]?.code || '' + + const submit = async () => { + setSaving(true) + setError(null) + try { + await apiRequest('/surveys', { + method: 'POST', + body: JSON.stringify({ + title, + description, + surveyKind, + templateCode: selectedTemplate, + dueAt: dueAt || null, + openNow, + targetEmployeeIds: targetEmployees.map((employee) => employee.id), + targetItems, + evaluatorEmployeeIds: evaluatorEmployees.map((employee) => employee.id), + evaluatorDepartmentNames: evaluatorDepartments, + }), + }) + setTitle('') + setDescription('') + setTargetEmployees([]) + setEvaluatorEmployees([]) + setEvaluatorDepartments([]) + setTargetItems([]) + setItemName('') + await onCreated() + } catch (err) { + setError(err instanceof Error ? err.message : '创建失败') + } finally { + setSaving(false) + } + } + + return ( +
+

新建考核调研

+
+ + + + + + + {surveyKind === 'person_period' ? ( + + ) : ( +
+
+ setItemName(event.target.value)} + placeholder="课程、事项或活动名称" + className="flex-1 rounded-lg border border-gray-300 px-3 py-2 dark:border-gray-600 dark:bg-gray-900 dark:text-white" + /> + +
+ ({ id: item.name, label: item.name }))} + onRemove={(id) => setTargetItems((current) => current.filter((item) => item.name !== id))} + /> +
+ )} + + + + + + {error &&
{error}
} + +
+
+ ) +} + +function EmployeePicker({ + title, + selected, + onChange, +}: { + title: string + selected: Employee[] + onChange: (employees: Employee[]) => void +}) { + const [keyword, setKeyword] = useState('') + const [items, setItems] = useState([]) + const [loading, setLoading] = useState(false) + + useEffect(() => { + const timer = window.setTimeout(async () => { + if (!keyword.trim()) { + setItems([]) + return + } + setLoading(true) + try { + const data = await apiRequest(`/employees?search=${encodeURIComponent(keyword)}&limit=20`) + setItems(data) + } finally { + setLoading(false) + } + }, 250) + + return () => window.clearTimeout(timer) + }, [keyword]) + + const selectedIds = new Set(selected.map((employee) => employee.id)) + + return ( +
+ + {keyword && ( +
+ {loading ? ( +
搜索中...
+ ) : items.length === 0 ? ( +
无匹配人员
+ ) : ( + items.map((employee) => ( + + )) + )} +
+ )} + ({ id: employee.id, label: employee.displayName }))} + onRemove={(id) => onChange(selected.filter((employee) => employee.id !== id))} + /> +
+ ) +} + +function DepartmentPicker({ + departments, + selected, + onChange, +}: { + departments: any[] + selected: string[] + onChange: (items: string[]) => void +}) { + if (departments.length === 0) return null + + return ( +
+
部门快选评价人
+
+ {departments.map((department) => ( + + ))} +
+
+ ) +} + +function AdminActions({ + onMessage, + onNotificationsChanged, +}: { + onMessage: (message: string | null) => void + onNotificationsChanged: () => Promise +}) { + const [busy, setBusy] = useState(null) + + const run = async (key: string, path: string, success: string) => { + setBusy(key) + onMessage(null) + try { + const data = await apiRequest(path, { method: 'POST', body: JSON.stringify({}) }) + onMessage(`${success}${data?.upserted != null ? `:${data.upserted} 人` : ''}`) + await onNotificationsChanged() + } catch (error) { + onMessage(error instanceof Error ? error.message : '操作失败') + } finally { + setBusy(null) + } + } + + return ( +
+

管理操作

+
+ + + + 导出结果 + +
+
+ ) +} + +function NotificationList({ state }: { state: ApiState & { refresh: () => Promise } }) { + const [busyId, setBusyId] = useState(null) + + const retry = async (id: string) => { + setBusyId(id) + try { + await apiRequest(`/admin/notifications/${id}/retry`, { method: 'POST', body: JSON.stringify({}) }) + await state.refresh() + } finally { + setBusyId(null) + } + } + + return ( +
+
+

钉钉通知

+ +
+
+ {state.loading &&
加载中...
} + {state.error &&
{state.error}
} + {state.data?.length === 0 &&
暂无通知记录
} + {state.data?.map((item) => ( +
+
+
+
{item.title}
+
{item.recipientName} · {item.eventType}
+ {item.lastError &&
{item.lastError}
} +
+ +
+ {['retrying', 'exhausted', 'skipped'].includes(item.status) && ( + + )} +
+ ))} +
+
+ ) +} + +function SurveySubmit({ surveyId }: { surveyId: string }) { + const searchParams = useSearchParams() + const targetIdParam = searchParams.get('targetId') + const detail = useApi(`/surveys/${surveyId}`, [surveyId]) + const [targetId, setTargetId] = useState(targetIdParam || '') + const [scores, setScores] = useState>({}) + const [comment, setComment] = useState('') + const [message, setMessage] = useState(null) + const [submitting, setSubmitting] = useState(false) + + const targets = useMemo( + () => (detail.data?.targets || []).filter((target: any) => target.currentAssignment), + [detail.data], + ) + const activeTargetId = targetId || targets[0]?.id || '' + const template = detail.data?.template as Template | undefined + + useEffect(() => { + if (!targetId && targets[0]?.id) setTargetId(targets[0].id) + }, [targets, targetId]) + + useEffect(() => { + if (template?.questions) { + setScores( + Object.fromEntries( + template.questions.map((question) => [question.id, 16]), + ), + ) + } + }, [template?.code]) + + const submit = async () => { + setSubmitting(true) + setMessage(null) + try { + await apiRequest(`/surveys/${surveyId}/responses`, { + method: 'POST', + body: JSON.stringify({ targetId: activeTargetId, scores, comment }), + }) + setMessage('提交成功') + await detail.refresh() + } catch (error) { + setMessage(error instanceof Error ? error.message : '提交失败') + } finally { + setSubmitting(false) + } + } + + if (detail.loading) return 加载中... + if (detail.error) return + if (!detail.data) return null + + const activeTarget = detail.data.targets.find((target: any) => target.id === activeTargetId) + const submitted = activeTarget?.currentAssignment?.status === 'submitted' + + return ( +
+
+ 返回考核调研 +

{detail.data.title}

+
+ + {detail.data.dueAt && 截止 {formatDate(detail.data.dueAt)}} +
+
+ +
+ {targets.length > 1 && ( + + )} + + {activeTarget && ( +
+ {activeTarget.targetName} +
+ )} + + {submitted ? ( + + ) : detail.data.status !== 'open' ? ( + + ) : ( +
+ {template?.questions?.map((question) => ( +
+
+
+
{question.title}
+ {question.description &&
{question.description}
} +
+ {scores[question.id] ?? 16} +
+ setScores((current) => ({ ...current, [question.id]: Number(event.target.value) }))} + className="w-full" + /> +
+ ))} +