feat: add native performance survey module
This commit is contained in:
parent
8288e2246f
commit
f4236c44c4
@ -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,
|
||||
|
||||
159
app/api/performance-survey/[...path]/route.ts
Normal file
159
app/api/performance-survey/[...path]/route.ts
Normal file
@ -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)
|
||||
}
|
||||
}
|
||||
1023
app/performance-survey/[[...path]]/page.tsx
Normal file
1023
app/performance-survey/[[...path]]/page.tsx
Normal file
File diff suppressed because it is too large
Load Diff
5
app/teacher/[[...path]]/page.tsx
Normal file
5
app/teacher/[[...path]]/page.tsx
Normal file
@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation'
|
||||
|
||||
export default function LegacyTeacherRedirectPage() {
|
||||
redirect('/performance-survey')
|
||||
}
|
||||
@ -515,6 +515,18 @@ export default function Header({ session }: HeaderProps) {
|
||||
<span>个人中心</span>
|
||||
</Link>
|
||||
|
||||
{/* 考核调研 */}
|
||||
<Link
|
||||
href="/performance-survey"
|
||||
onClick={() => setShowDropdown(false)}
|
||||
className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 transition-all flex items-center space-x-2"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-6m4 6V7m4 10v-3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span>考核调研</span>
|
||||
</Link>
|
||||
|
||||
{/* 更新记录 */}
|
||||
<button
|
||||
onClick={() => {
|
||||
|
||||
133
lib/dingtalk-client.ts
Normal file
133
lib/dingtalk-client.ts
Normal file
@ -0,0 +1,133 @@
|
||||
type DingtalkWorkNoticeInput = {
|
||||
userIds: string[]
|
||||
title: string
|
||||
text: string
|
||||
actionUrl?: string | null
|
||||
}
|
||||
|
||||
type DingtalkWorkNoticeResult = {
|
||||
skipped?: boolean
|
||||
reason?: string
|
||||
taskId?: string
|
||||
requestId?: string
|
||||
raw?: unknown
|
||||
}
|
||||
|
||||
let cachedAppToken: { token: string; expiresAt: number } | null = null
|
||||
|
||||
function getDingtalkAppConfig() {
|
||||
const appKey = process.env.DINGTALK_CLIENT_ID || process.env.DINGTALK_APP_KEY
|
||||
const appSecret = process.env.DINGTALK_CLIENT_SECRET || process.env.DINGTALK_APP_SECRET
|
||||
|
||||
if (!appKey || !appSecret) {
|
||||
throw new Error('钉钉应用未配置 DINGTALK_CLIENT_ID/DINGTALK_CLIENT_SECRET')
|
||||
}
|
||||
|
||||
return { appKey, appSecret }
|
||||
}
|
||||
|
||||
function getDingtalkWorkNoticeAgentId() {
|
||||
return process.env.DINGTALK_WORK_NOTICE_AGENT_ID || process.env.DINGTALK_AGENT_ID || ''
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength = 4800) {
|
||||
const normalized = String(value || '').trim()
|
||||
return normalized.length > maxLength ? `${normalized.slice(0, maxLength)}...` : normalized
|
||||
}
|
||||
|
||||
export async function getDingtalkAppAccessToken() {
|
||||
if (cachedAppToken && cachedAppToken.expiresAt > Date.now() + 60_000) {
|
||||
return cachedAppToken.token
|
||||
}
|
||||
|
||||
const { appKey, appSecret } = getDingtalkAppConfig()
|
||||
const response = await fetch(
|
||||
`https://oapi.dingtalk.com/gettoken?appkey=${encodeURIComponent(appKey)}&appsecret=${encodeURIComponent(appSecret)}`,
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`获取钉钉应用访问令牌失败: HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
if (data.errcode !== 0 || !data.access_token) {
|
||||
throw new Error(`获取钉钉应用访问令牌失败: ${data.errmsg || '返回数据异常'}`)
|
||||
}
|
||||
|
||||
const expiresIn = Number(data.expires_in || 7200)
|
||||
cachedAppToken = {
|
||||
token: String(data.access_token),
|
||||
expiresAt: Date.now() + Math.max(60, expiresIn - 120) * 1000,
|
||||
}
|
||||
|
||||
return cachedAppToken.token
|
||||
}
|
||||
|
||||
export async function sendDingtalkWorkNotice(
|
||||
input: DingtalkWorkNoticeInput,
|
||||
): Promise<DingtalkWorkNoticeResult> {
|
||||
const agentId = getDingtalkWorkNoticeAgentId()
|
||||
if (!agentId) {
|
||||
return {
|
||||
skipped: true,
|
||||
reason: '钉钉工作通知未配置 DINGTALK_WORK_NOTICE_AGENT_ID',
|
||||
}
|
||||
}
|
||||
|
||||
const numericAgentId = Number(agentId)
|
||||
if (!Number.isFinite(numericAgentId) || numericAgentId <= 0) {
|
||||
return {
|
||||
skipped: true,
|
||||
reason: '钉钉工作通知 DINGTALK_WORK_NOTICE_AGENT_ID 必须是正数',
|
||||
}
|
||||
}
|
||||
|
||||
const userIds = Array.from(
|
||||
new Set(input.userIds.map((item) => String(item || '').trim()).filter(Boolean)),
|
||||
)
|
||||
|
||||
if (userIds.length === 0) {
|
||||
return {
|
||||
skipped: true,
|
||||
reason: '没有可投递的钉钉 userId',
|
||||
}
|
||||
}
|
||||
|
||||
const token = await getDingtalkAppAccessToken()
|
||||
const actionText = input.actionUrl ? `\n\n[打开素材库查看](${input.actionUrl})` : ''
|
||||
const markdownText = truncateText(`${input.text}${actionText}`)
|
||||
|
||||
const response = await fetch(
|
||||
`https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=${encodeURIComponent(token)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
agent_id: numericAgentId,
|
||||
userid_list: userIds.join(','),
|
||||
msg: {
|
||||
msgtype: 'markdown',
|
||||
markdown: {
|
||||
title: truncateText(input.title, 120),
|
||||
text: markdownText,
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
)
|
||||
|
||||
const data = await response.json().catch(async () => ({ raw: await response.text() }))
|
||||
if (!response.ok) {
|
||||
throw new Error(`钉钉工作通知发送失败: HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
if (data.errcode !== 0) {
|
||||
throw new Error(`钉钉工作通知发送失败: ${data.errmsg || '未知错误'}`)
|
||||
}
|
||||
|
||||
return {
|
||||
taskId: data.task_id != null ? String(data.task_id) : undefined,
|
||||
requestId: data.request_id != null ? String(data.request_id) : undefined,
|
||||
raw: data,
|
||||
}
|
||||
}
|
||||
@ -64,6 +64,27 @@ const OPTIONAL_ENV_VARS = [
|
||||
'USE_REDIS',
|
||||
'DINGTALK_APP_KEY',
|
||||
'DINGTALK_APP_SECRET',
|
||||
'DINGTALK_CLIENT_ID',
|
||||
'DINGTALK_CLIENT_SECRET',
|
||||
'DINGTALK_WORK_NOTICE_AGENT_ID',
|
||||
'DINGTALK_AGENT_ID',
|
||||
'REPORT_DB_SERVER',
|
||||
'REPORT_DB_DATABASE',
|
||||
'REPORT_DB_USER',
|
||||
'REPORT_DB_PASSWORD',
|
||||
'REPORT_DB_PORT',
|
||||
'REPORT_DB_ENCRYPT',
|
||||
'REPORT_DB_TRUST_SERVER_CERTIFICATE',
|
||||
'REPORT_DB_EMPLOYEE_SCHEMA',
|
||||
'REPORT_DB_EMPLOYEE_TABLE',
|
||||
'REPORT_DB_REGISTER_SCHEMA',
|
||||
'REPORT_DB_REGISTER_TABLE',
|
||||
'REPORT_DB_FLOWER_NAME_SCHEMA',
|
||||
'REPORT_DB_FLOWER_NAME_TABLE',
|
||||
'PERFORMANCE_SURVEY_PROFILE_SYNC_HOURS',
|
||||
'PERFORMANCE_SURVEY_DAILY_SYNC_INTERVAL_HOURS',
|
||||
'PERFORMANCE_SURVEY_DAILY_SYNC_INITIAL_DELAY_SECONDS',
|
||||
'PERFORMANCE_SURVEY_DAILY_SYNC_LIMIT',
|
||||
'DOWNLOAD_TOKEN_SECRET',
|
||||
'DISABLE_CACHE',
|
||||
'ADMIN_API_KEY', // 管理员API密钥(用于外部API调用验证)
|
||||
|
||||
404
lib/performance-survey-notifications.ts
Normal file
404
lib/performance-survey-notifications.ts
Normal file
@ -0,0 +1,404 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
||||
import { sendDingtalkWorkNotice } from '@/lib/dingtalk-client'
|
||||
|
||||
const STATUS = {
|
||||
PENDING: 'pending',
|
||||
PROCESSING: 'processing',
|
||||
RETRYING: 'retrying',
|
||||
SUCCEEDED: 'succeeded',
|
||||
EXHAUSTED: 'exhausted',
|
||||
SKIPPED: 'skipped',
|
||||
} as const
|
||||
|
||||
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
|
||||
|
||||
let workerStarted = false
|
||||
let recoveryTimer: NodeJS.Timeout | null = null
|
||||
let reminderTimer: NodeJS.Timeout | null = null
|
||||
const deliveryTimers = new Map<string, NodeJS.Timeout>()
|
||||
|
||||
type QueueNotificationInput = {
|
||||
surveyId?: string | null
|
||||
targetId?: string | null
|
||||
assignmentId?: string | null
|
||||
recipientEmployeeId?: string | null
|
||||
recipientUserId?: string | null
|
||||
dingtalkUserId?: string | null
|
||||
recipientName: string
|
||||
eventType: string
|
||||
businessKey: string
|
||||
title: string
|
||||
content: string
|
||||
actionUrl?: string | null
|
||||
}
|
||||
|
||||
function truncateBody(value: string | null | undefined, limit = 2000) {
|
||||
const text = String(value || '')
|
||||
return text.length > limit ? text.slice(0, limit) : text
|
||||
}
|
||||
|
||||
function getSurveyUrl(path: string) {
|
||||
return `${getPublicAppOrigin()}${path}`
|
||||
}
|
||||
|
||||
export function ensurePerformanceSurveyNotificationWorkerStarted() {
|
||||
if (workerStarted) return
|
||||
workerStarted = true
|
||||
|
||||
const bootstrap = setTimeout(() => {
|
||||
void recoverDuePerformanceSurveyNotifications()
|
||||
void queueDuePerformanceSurveyReminders()
|
||||
}, 1000)
|
||||
bootstrap.unref?.()
|
||||
|
||||
recoveryTimer = setInterval(() => {
|
||||
void recoverDuePerformanceSurveyNotifications()
|
||||
}, RECOVERY_INTERVAL_MS)
|
||||
recoveryTimer.unref?.()
|
||||
|
||||
reminderTimer = setInterval(() => {
|
||||
void queueDuePerformanceSurveyReminders()
|
||||
}, REMINDER_INTERVAL_MS)
|
||||
reminderTimer.unref?.()
|
||||
}
|
||||
|
||||
function scheduleNotificationProcessing(notificationId: string, delayMs: number) {
|
||||
const existing = deliveryTimers.get(notificationId)
|
||||
if (existing) {
|
||||
clearTimeout(existing)
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
deliveryTimers.delete(notificationId)
|
||||
void processPerformanceSurveyNotification(notificationId)
|
||||
}, Math.max(0, delayMs))
|
||||
timer.unref?.()
|
||||
deliveryTimers.set(notificationId, timer)
|
||||
}
|
||||
|
||||
export async function queuePerformanceSurveyNotification(input: QueueNotificationInput) {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
const existing = await prisma.performanceSurveyNotification.findUnique({
|
||||
where: {
|
||||
eventType_businessKey: {
|
||||
eventType: input.eventType,
|
||||
businessKey: input.businessKey,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
return existing.id
|
||||
}
|
||||
|
||||
const created = await prisma.performanceSurveyNotification.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
surveyId: input.surveyId || null,
|
||||
targetId: input.targetId || null,
|
||||
assignmentId: input.assignmentId || null,
|
||||
recipientEmployeeId: input.recipientEmployeeId || null,
|
||||
recipientUserId: input.recipientUserId || null,
|
||||
dingtalkUserId: input.dingtalkUserId || null,
|
||||
recipientName: input.recipientName,
|
||||
eventType: input.eventType,
|
||||
businessKey: input.businessKey,
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
actionUrl: input.actionUrl || null,
|
||||
status: STATUS.PENDING,
|
||||
maxAttempts: MAX_ATTEMPTS,
|
||||
nextRetryAt: new Date(),
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
scheduleNotificationProcessing(created.id, 0)
|
||||
return created.id
|
||||
}
|
||||
|
||||
export async function queueSurveyAssignmentNotifications(surveyId: string) {
|
||||
const survey = await prisma.performanceSurvey.findUnique({
|
||||
where: { id: surveyId },
|
||||
include: {
|
||||
assignments: {
|
||||
where: { status: 'pending' },
|
||||
include: { target: true, evaluatorEmployee: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!survey) return []
|
||||
|
||||
const ids: string[] = []
|
||||
for (const assignment of survey.assignments) {
|
||||
const targetName = assignment.target.targetName
|
||||
ids.push(
|
||||
await queuePerformanceSurveyNotification({
|
||||
surveyId: survey.id,
|
||||
targetId: assignment.targetId,
|
||||
assignmentId: assignment.id,
|
||||
recipientEmployeeId: assignment.evaluatorEmployeeId,
|
||||
recipientUserId: assignment.evaluatorUserId,
|
||||
dingtalkUserId: assignment.evaluatorDingtalkUserId,
|
||||
recipientName: assignment.evaluatorName,
|
||||
eventType: 'survey.assignment.created',
|
||||
businessKey: `assignment:${assignment.id}`,
|
||||
title: '你有新的考核调研待填写',
|
||||
content: `你有一份新的考核调研需要填写。\n\n调研:${survey.title}\n对象:${targetName}${survey.dueAt ? `\n截止:${formatDateTime(survey.dueAt)}` : ''}`,
|
||||
actionUrl: getSurveyUrl(`/performance-survey/survey/${survey.id}?targetId=${assignment.targetId}`),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return ids
|
||||
}
|
||||
|
||||
export async function queueSurveyResultNotifications(surveyId: string) {
|
||||
const survey = await prisma.performanceSurvey.findUnique({
|
||||
where: { id: surveyId },
|
||||
include: {
|
||||
targets: { include: { employeeProfile: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!survey) return []
|
||||
|
||||
const ids: string[] = []
|
||||
for (const target of survey.targets) {
|
||||
if (target.targetType !== 'employee' || !target.employeeProfile) continue
|
||||
ids.push(
|
||||
await queuePerformanceSurveyNotification({
|
||||
surveyId: survey.id,
|
||||
targetId: target.id,
|
||||
recipientEmployeeId: target.employeeProfileId,
|
||||
dingtalkUserId: target.employeeProfile.dingtalkUserId,
|
||||
recipientName: target.targetName,
|
||||
eventType: 'survey.result.available',
|
||||
businessKey: `result:${survey.id}:${target.id}`,
|
||||
title: '考核调研结果已可查看',
|
||||
content: `你参与的考核调研结果已经生成。\n\n调研:${survey.title}\n对象:${target.targetName}`,
|
||||
actionUrl: getSurveyUrl(`/performance-survey/results/${survey.id}?targetId=${target.id}`),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return ids
|
||||
}
|
||||
|
||||
export async function queueSurveyCreatorNotification(surveyId: string, eventType = 'survey.creator.completed') {
|
||||
const survey = await prisma.performanceSurvey.findUnique({
|
||||
where: { id: surveyId },
|
||||
include: {
|
||||
assignments: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!survey) return null
|
||||
|
||||
const creator = await prisma.user.findUnique({
|
||||
where: { id: survey.creatorUserId },
|
||||
select: { id: true, username: true, realName: true, dingtalkUserId: true },
|
||||
})
|
||||
|
||||
const total = survey.assignments.length
|
||||
const submitted = survey.assignments.filter((assignment) => assignment.status === 'submitted').length
|
||||
|
||||
return queuePerformanceSurveyNotification({
|
||||
surveyId: survey.id,
|
||||
recipientUserId: creator?.id || survey.creatorUserId,
|
||||
dingtalkUserId: creator?.dingtalkUserId || null,
|
||||
recipientName: creator?.realName || creator?.username || survey.creatorName,
|
||||
eventType,
|
||||
businessKey: `${eventType}:${survey.id}`,
|
||||
title: eventType === 'survey.creator.closed' ? '考核调研已关闭' : '考核调研已完成',
|
||||
content: `你发起的考核调研有新的进度。\n\n调研:${survey.title}\n提交进度:${submitted}/${total}`,
|
||||
actionUrl: getSurveyUrl(`/performance-survey/results/${survey.id}`),
|
||||
})
|
||||
}
|
||||
|
||||
export async function queueDuePerformanceSurveyReminders() {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
const now = new Date()
|
||||
const before = new Date(Date.now() + 24 * 60 * 60 * 1000)
|
||||
const surveys = await prisma.performanceSurvey.findMany({
|
||||
where: {
|
||||
status: 'open',
|
||||
dueAt: {
|
||||
gt: now,
|
||||
lte: before,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
assignments: {
|
||||
where: { status: 'pending' },
|
||||
include: { target: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const ids: string[] = []
|
||||
for (const survey of surveys) {
|
||||
const dueKey = survey.dueAt ? survey.dueAt.toISOString().slice(0, 10) : 'no-date'
|
||||
for (const assignment of survey.assignments) {
|
||||
ids.push(
|
||||
await queuePerformanceSurveyNotification({
|
||||
surveyId: survey.id,
|
||||
targetId: assignment.targetId,
|
||||
assignmentId: assignment.id,
|
||||
recipientEmployeeId: assignment.evaluatorEmployeeId,
|
||||
recipientUserId: assignment.evaluatorUserId,
|
||||
dingtalkUserId: assignment.evaluatorDingtalkUserId,
|
||||
recipientName: assignment.evaluatorName,
|
||||
eventType: 'survey.assignment.due_reminder',
|
||||
businessKey: `due:${dueKey}:${assignment.id}`,
|
||||
title: '考核调研即将截止',
|
||||
content: `你还有一份考核调研未填写。\n\n调研:${survey.title}\n对象:${assignment.target.targetName}\n截止:${formatDateTime(survey.dueAt)}`,
|
||||
actionUrl: getSurveyUrl(`/performance-survey/survey/${survey.id}?targetId=${assignment.targetId}`),
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
}
|
||||
|
||||
export async function recoverDuePerformanceSurveyNotifications(limit = 20) {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
const rows = await prisma.performanceSurveyNotification.findMany({
|
||||
where: {
|
||||
status: { in: [STATUS.PENDING, STATUS.RETRYING] },
|
||||
OR: [{ nextRetryAt: null }, { nextRetryAt: { lte: new Date() } }],
|
||||
},
|
||||
select: { id: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: limit,
|
||||
})
|
||||
|
||||
rows.forEach((row) => scheduleNotificationProcessing(row.id, 0))
|
||||
return rows.length
|
||||
}
|
||||
|
||||
export async function retryPerformanceSurveyNotification(notificationId: string) {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: STATUS.PENDING,
|
||||
nextRetryAt: new Date(),
|
||||
completedAt: null,
|
||||
lastError: null,
|
||||
},
|
||||
})
|
||||
|
||||
scheduleNotificationProcessing(notificationId, 0)
|
||||
}
|
||||
|
||||
export async function processPerformanceSurveyNotification(notificationId: string) {
|
||||
ensurePerformanceSurveyNotificationWorkerStarted()
|
||||
|
||||
const notification = await prisma.performanceSurveyNotification.findUnique({
|
||||
where: { id: notificationId },
|
||||
})
|
||||
|
||||
if (!notification) return null
|
||||
if (![STATUS.PENDING, STATUS.RETRYING, STATUS.PROCESSING].includes(notification.status as any)) {
|
||||
return null
|
||||
}
|
||||
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: STATUS.PROCESSING,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
if (!notification.dingtalkUserId) {
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: STATUS.SKIPPED,
|
||||
lastError: '收件人缺少钉钉 userId',
|
||||
completedAt: new Date(),
|
||||
},
|
||||
})
|
||||
return { success: false, status: STATUS.SKIPPED }
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await sendDingtalkWorkNotice({
|
||||
userIds: [notification.dingtalkUserId],
|
||||
title: notification.title,
|
||||
text: notification.content,
|
||||
actionUrl: notification.actionUrl,
|
||||
})
|
||||
|
||||
if (result.skipped) {
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: STATUS.SKIPPED,
|
||||
lastError: result.reason || '钉钉工作通知未发送',
|
||||
completedAt: new Date(),
|
||||
},
|
||||
})
|
||||
return { success: false, status: STATUS.SKIPPED }
|
||||
}
|
||||
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: STATUS.SUCCEEDED,
|
||||
attemptCount: { increment: 1 },
|
||||
providerMessageId: result.taskId || result.requestId || null,
|
||||
lastStatusCode: 200,
|
||||
lastResponseBody: truncateBody(JSON.stringify(result.raw || result)),
|
||||
lastError: null,
|
||||
sentAt: new Date(),
|
||||
completedAt: new Date(),
|
||||
nextRetryAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
return { success: true, status: STATUS.SUCCEEDED }
|
||||
} catch (error) {
|
||||
const nextAttempt = notification.attemptCount + 1
|
||||
const exhausted = nextAttempt >= notification.maxAttempts
|
||||
const retryDelayMs = RETRY_DELAYS_MS[Math.min(nextAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||
const nextRetryAt = new Date(Date.now() + retryDelayMs)
|
||||
|
||||
await prisma.performanceSurveyNotification.update({
|
||||
where: { id: notificationId },
|
||||
data: {
|
||||
status: exhausted ? STATUS.EXHAUSTED : STATUS.RETRYING,
|
||||
attemptCount: { increment: 1 },
|
||||
lastError: error instanceof Error ? error.message : '钉钉工作通知发送失败',
|
||||
nextRetryAt: exhausted ? null : nextRetryAt,
|
||||
completedAt: exhausted ? new Date() : null,
|
||||
},
|
||||
})
|
||||
|
||||
if (!exhausted) {
|
||||
scheduleNotificationProcessing(notificationId, retryDelayMs)
|
||||
}
|
||||
|
||||
return { success: false, status: exhausted ? STATUS.EXHAUSTED : STATUS.RETRYING }
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateTime(value: Date | string | null | undefined) {
|
||||
if (!value) return ''
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return date.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
741
lib/performance-survey-report-sync.ts
Normal file
741
lib/performance-survey-report-sync.ts
Normal file
@ -0,0 +1,741 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
type ReportEmployeeRow = {
|
||||
dingtalkUserId?: string | null
|
||||
dingEmail?: string | null
|
||||
jobNumber?: string | null
|
||||
contactName?: string | null
|
||||
contactTitle?: string | null
|
||||
workPlace?: string | null
|
||||
extension?: string | null
|
||||
registerName?: string | null
|
||||
flowerName?: string | null
|
||||
realName?: string | null
|
||||
registerJobNumber?: string | null
|
||||
positionTitle?: string | null
|
||||
positionLevel?: string | null
|
||||
departmentName?: string | null
|
||||
departmentPath?: string | null
|
||||
employmentStatus?: string | null
|
||||
managerDingtalkUserId?: string | null
|
||||
managerJobNumber?: string | null
|
||||
managerName?: string | null
|
||||
flowerBookName?: string | null
|
||||
flowerBookFlowerName?: string | null
|
||||
flowerBookDept?: string | null
|
||||
flowerBookWorkPlace?: string | null
|
||||
flowerBookJob?: string | null
|
||||
flowerBookJobLevel?: string | null
|
||||
flowerBookRole?: string | null
|
||||
flowerBookDirector?: string | null
|
||||
flowerBookManager?: string | null
|
||||
flowerBookEmployeeStatus?: string | null
|
||||
}
|
||||
|
||||
type ReportIdentity = {
|
||||
dingtalkUserId?: string | null
|
||||
email?: string | null
|
||||
username?: string | null
|
||||
realName?: string | null
|
||||
displayName?: string | null
|
||||
flowerName?: string | null
|
||||
}
|
||||
|
||||
type TableColumns = Map<string, string>
|
||||
|
||||
const EMPLOYEE_TABLE = {
|
||||
schema: process.env.REPORT_DB_EMPLOYEE_SCHEMA || 'rpt',
|
||||
table: process.env.REPORT_DB_EMPLOYEE_TABLE || 'hr_employee',
|
||||
}
|
||||
|
||||
const REGISTER_TABLE = {
|
||||
schema: process.env.REPORT_DB_REGISTER_SCHEMA || 'rpt',
|
||||
table: process.env.REPORT_DB_REGISTER_TABLE || 'hr_employee_register',
|
||||
}
|
||||
|
||||
const FLOWER_TABLE = {
|
||||
schema: process.env.REPORT_DB_FLOWER_NAME_SCHEMA || 'rpt',
|
||||
table: process.env.REPORT_DB_FLOWER_NAME_TABLE || 'hr_flowerName_book',
|
||||
}
|
||||
|
||||
const FIELD_CANDIDATES = {
|
||||
dingtalkUserId: ['userid', 'user_id', 'ding_userid', 'dingtalk_userid', 'dingtalk_user_id', 'userId'],
|
||||
email: ['email', 'org_email', 'work_email', 'mail', '邮箱'],
|
||||
jobNumber: ['job_number', 'jobNumber', 'job_no', 'employee_no', '工号'],
|
||||
name: ['name', 'real_name', 'realName', 'username', '姓名'],
|
||||
title: ['title', 'position', 'job_title', '岗位'],
|
||||
workPlace: ['work_place', 'workPlace', 'workplace', 'office_location', '办公地点'],
|
||||
extension: ['extension', 'ext', 'extattr', 'ext_attr'],
|
||||
active: ['active', 'is_active', 'enabled'],
|
||||
registerName: ['sys00-name', 'name', '姓名'],
|
||||
flowerName: ['sys00-flowerName', 'flower_name', 'flowerName', '花名'],
|
||||
registerRealName: ['sys02-realName', 'real_name', 'realName', '真实姓名'],
|
||||
registerJobNumber: ['sys00-jobNumber', 'job_number', 'jobNumber', '工号'],
|
||||
positionTitle: ['sys00-position', 'position', 'title', '岗位'],
|
||||
positionLevel: ['sys01-positionLevel', 'position_level', 'positionLevel', '岗位职级', '职级'],
|
||||
departmentName: ['sys00-dept', 'department', 'department_name', 'dept_name', '部门'],
|
||||
departmentPath: ['sys00-mainDepts', 'department_path', 'main_departments', '部门路径'],
|
||||
employmentStatus: ['sys01-employeeStatus', 'employee_status', 'employment_status', '在职状态'],
|
||||
managerDingtalkUserId: ['manager_userid', 'managerUserid', 'leader_userid', '主管userid'],
|
||||
managerJobNumber: ['manager_job_number', 'managerJobNumber', 'leader_job_number', '主管工号'],
|
||||
managerName: ['manager_name', 'managerName', 'leader_name', '主管'],
|
||||
flowerBookJobNumber: ['jobNum', 'job_number', 'jobNumber', '工号'],
|
||||
flowerBookName: ['name', '姓名'],
|
||||
flowerBookFlowerName: ['flowerName', 'flower_name', '花名'],
|
||||
flowerBookDept: ['dept', 'department', 'department_name', '部门'],
|
||||
flowerBookWorkPlace: ['workPlace', 'work_place', '办公地点'],
|
||||
flowerBookJob: ['job', 'position', '岗位'],
|
||||
flowerBookJobLevel: ['jobLevel', 'job_level', '岗位职级', '职级'],
|
||||
flowerBookRole: ['role', '角色'],
|
||||
flowerBookDirector: ['director', 'directorName', '主管'],
|
||||
flowerBookManager: ['manager', 'managerName', '经理'],
|
||||
flowerBookEmployeeStatus: ['empStatus', 'employee_status', '在职状态'],
|
||||
}
|
||||
|
||||
let dailyWorkerStarted = false
|
||||
|
||||
export function isPerformanceSurveyReportDbConfigured() {
|
||||
return Boolean(
|
||||
process.env.REPORT_DB_SERVER &&
|
||||
process.env.REPORT_DB_DATABASE &&
|
||||
process.env.REPORT_DB_USER &&
|
||||
process.env.REPORT_DB_PASSWORD,
|
||||
)
|
||||
}
|
||||
|
||||
function getReportDbConfig() {
|
||||
const server = process.env.REPORT_DB_SERVER
|
||||
const database = process.env.REPORT_DB_DATABASE
|
||||
const user = process.env.REPORT_DB_USER
|
||||
const password = process.env.REPORT_DB_PASSWORD
|
||||
const port = Number(process.env.REPORT_DB_PORT || 1433)
|
||||
|
||||
if (!server || !database || !user || !password) {
|
||||
throw new Error('报表库未配置 REPORT_DB_SERVER/REPORT_DB_DATABASE/REPORT_DB_USER/REPORT_DB_PASSWORD')
|
||||
}
|
||||
|
||||
return {
|
||||
server,
|
||||
database,
|
||||
user,
|
||||
password,
|
||||
port: Number.isFinite(port) ? port : 1433,
|
||||
options: {
|
||||
encrypt: process.env.REPORT_DB_ENCRYPT === 'true',
|
||||
trustServerCertificate: process.env.REPORT_DB_TRUST_SERVER_CERTIFICATE !== 'false',
|
||||
enableArithAbort: true,
|
||||
},
|
||||
pool: {
|
||||
max: 4,
|
||||
min: 0,
|
||||
idleTimeoutMillis: 30_000,
|
||||
},
|
||||
requestTimeout: 60_000,
|
||||
connectionTimeout: 15_000,
|
||||
}
|
||||
}
|
||||
|
||||
function clean(value: unknown) {
|
||||
const normalized = String(value ?? '').trim()
|
||||
return normalized.length > 0 ? normalized : null
|
||||
}
|
||||
|
||||
function parseExtension(value?: string | null) {
|
||||
if (!value) return {}
|
||||
try {
|
||||
const parsed = JSON.parse(value)
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function parseDepartmentValue(value?: string | null) {
|
||||
const normalized = clean(value)
|
||||
if (!normalized) return null
|
||||
|
||||
if (normalized.startsWith('[')) {
|
||||
try {
|
||||
const parsed = JSON.parse(normalized)
|
||||
if (Array.isArray(parsed)) {
|
||||
return clean(parsed[parsed.length - 1]) || clean(parsed[0])
|
||||
}
|
||||
} catch {
|
||||
return normalized
|
||||
}
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
function getLevelType(positionLevel?: string | null) {
|
||||
const first = clean(positionLevel)?.slice(0, 1).toUpperCase()
|
||||
if (first === 'P' || first === 'M') return first
|
||||
return null
|
||||
}
|
||||
|
||||
function isLeadershipLevel(positionLevel?: string | null) {
|
||||
return getLevelType(positionLevel) === 'M'
|
||||
}
|
||||
|
||||
function quoteIdentifier(value: string) {
|
||||
return `[${value.replace(/]/g, ']]')}]`
|
||||
}
|
||||
|
||||
function pickColumn(columns: TableColumns, candidates: string[]) {
|
||||
for (const candidate of candidates) {
|
||||
const matched = columns.get(candidate.toLowerCase())
|
||||
if (matched) return matched
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function columnExpr(alias: string, column: string | null, cast = 'nvarchar(4000)') {
|
||||
return column ? `${alias}.${quoteIdentifier(column)}` : `CAST(NULL AS ${cast})`
|
||||
}
|
||||
|
||||
function eqCondition(alias: string, column: string | null, paramName: string) {
|
||||
return column ? `${alias}.${quoteIdentifier(column)} = @${paramName}` : null
|
||||
}
|
||||
|
||||
async function getTableColumns(pool: any, schema: string, table: string): Promise<TableColumns> {
|
||||
const result = await pool
|
||||
.request()
|
||||
.input('schema', schema)
|
||||
.input('table', table)
|
||||
.query(`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table
|
||||
`)
|
||||
|
||||
return new Map(
|
||||
((result.recordset || []) as Array<{ COLUMN_NAME: string }>).map((row) => [
|
||||
String(row.COLUMN_NAME).toLowerCase(),
|
||||
row.COLUMN_NAME,
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
async function getReportSchema(pool: any) {
|
||||
const employeeColumns = await getTableColumns(pool, EMPLOYEE_TABLE.schema, EMPLOYEE_TABLE.table)
|
||||
const registerColumns = await getTableColumns(pool, REGISTER_TABLE.schema, REGISTER_TABLE.table)
|
||||
const flowerColumns = await getTableColumns(pool, FLOWER_TABLE.schema, FLOWER_TABLE.table)
|
||||
|
||||
if (employeeColumns.size === 0) {
|
||||
throw new Error(`报表库未找到人员表 ${EMPLOYEE_TABLE.schema}.${EMPLOYEE_TABLE.table}`)
|
||||
}
|
||||
|
||||
return { employeeColumns, registerColumns, flowerColumns }
|
||||
}
|
||||
|
||||
function buildJoinCondition(employeeColumns: TableColumns, registerColumns: TableColumns) {
|
||||
const employeeUserId = pickColumn(employeeColumns, FIELD_CANDIDATES.dingtalkUserId)
|
||||
const registerUserId = pickColumn(registerColumns, FIELD_CANDIDATES.dingtalkUserId)
|
||||
const employeeJobNumber = pickColumn(employeeColumns, FIELD_CANDIDATES.jobNumber)
|
||||
const registerJobNumber = pickColumn(registerColumns, FIELD_CANDIDATES.registerJobNumber)
|
||||
const conditions = [
|
||||
employeeUserId && registerUserId
|
||||
? `r.${quoteIdentifier(registerUserId)} = e.${quoteIdentifier(employeeUserId)}`
|
||||
: null,
|
||||
employeeJobNumber && registerJobNumber
|
||||
? `r.${quoteIdentifier(registerJobNumber)} = e.${quoteIdentifier(employeeJobNumber)}`
|
||||
: null,
|
||||
].filter(Boolean)
|
||||
|
||||
return conditions.length > 0 ? conditions.join(' OR ') : '1 = 0'
|
||||
}
|
||||
|
||||
function buildSelectSql(
|
||||
employeeColumns: TableColumns,
|
||||
registerColumns: TableColumns,
|
||||
flowerColumns: TableColumns,
|
||||
whereSql: string,
|
||||
limitSql = '@limit',
|
||||
) {
|
||||
const e = {
|
||||
dingtalkUserId: pickColumn(employeeColumns, FIELD_CANDIDATES.dingtalkUserId),
|
||||
email: pickColumn(employeeColumns, FIELD_CANDIDATES.email),
|
||||
jobNumber: pickColumn(employeeColumns, FIELD_CANDIDATES.jobNumber),
|
||||
name: pickColumn(employeeColumns, FIELD_CANDIDATES.name),
|
||||
title: pickColumn(employeeColumns, FIELD_CANDIDATES.title),
|
||||
workPlace: pickColumn(employeeColumns, FIELD_CANDIDATES.workPlace),
|
||||
extension: pickColumn(employeeColumns, FIELD_CANDIDATES.extension),
|
||||
active: pickColumn(employeeColumns, FIELD_CANDIDATES.active),
|
||||
managerDingtalkUserId: pickColumn(employeeColumns, FIELD_CANDIDATES.managerDingtalkUserId),
|
||||
managerJobNumber: pickColumn(employeeColumns, FIELD_CANDIDATES.managerJobNumber),
|
||||
managerName: pickColumn(employeeColumns, FIELD_CANDIDATES.managerName),
|
||||
}
|
||||
const r = {
|
||||
dingtalkUserId: pickColumn(registerColumns, FIELD_CANDIDATES.dingtalkUserId),
|
||||
email: pickColumn(registerColumns, FIELD_CANDIDATES.email),
|
||||
registerName: pickColumn(registerColumns, FIELD_CANDIDATES.registerName),
|
||||
flowerName: pickColumn(registerColumns, FIELD_CANDIDATES.flowerName),
|
||||
realName: pickColumn(registerColumns, FIELD_CANDIDATES.registerRealName),
|
||||
jobNumber: pickColumn(registerColumns, FIELD_CANDIDATES.registerJobNumber),
|
||||
positionTitle: pickColumn(registerColumns, FIELD_CANDIDATES.positionTitle),
|
||||
positionLevel: pickColumn(registerColumns, FIELD_CANDIDATES.positionLevel),
|
||||
departmentName: pickColumn(registerColumns, FIELD_CANDIDATES.departmentName),
|
||||
departmentPath: pickColumn(registerColumns, FIELD_CANDIDATES.departmentPath),
|
||||
employmentStatus: pickColumn(registerColumns, FIELD_CANDIDATES.employmentStatus),
|
||||
managerDingtalkUserId: pickColumn(registerColumns, FIELD_CANDIDATES.managerDingtalkUserId),
|
||||
managerJobNumber: pickColumn(registerColumns, FIELD_CANDIDATES.managerJobNumber),
|
||||
managerName: pickColumn(registerColumns, FIELD_CANDIDATES.managerName),
|
||||
}
|
||||
const f = {
|
||||
jobNumber: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookJobNumber),
|
||||
name: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookName),
|
||||
flowerName: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookFlowerName),
|
||||
dept: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookDept),
|
||||
workPlace: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookWorkPlace),
|
||||
job: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookJob),
|
||||
jobLevel: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookJobLevel),
|
||||
role: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookRole),
|
||||
director: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookDirector),
|
||||
manager: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookManager),
|
||||
employeeStatus: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookEmployeeStatus),
|
||||
}
|
||||
const activeFilter = e.active ? `AND (e.${quoteIdentifier(e.active)} = 1 OR e.${quoteIdentifier(e.active)} = '1')` : ''
|
||||
const joinSql = registerColumns.size > 0
|
||||
? `LEFT JOIN ${quoteIdentifier(REGISTER_TABLE.schema)}.${quoteIdentifier(REGISTER_TABLE.table)} r ON ${buildJoinCondition(employeeColumns, registerColumns)}`
|
||||
: ''
|
||||
const flowerJoinConditions = [
|
||||
f.jobNumber && r.jobNumber ? `f.${quoteIdentifier(f.jobNumber)} = r.${quoteIdentifier(r.jobNumber)}` : null,
|
||||
f.jobNumber && e.jobNumber ? `f.${quoteIdentifier(f.jobNumber)} = e.${quoteIdentifier(e.jobNumber)}` : null,
|
||||
f.flowerName && r.flowerName ? `f.${quoteIdentifier(f.flowerName)} = r.${quoteIdentifier(r.flowerName)}` : null,
|
||||
].filter(Boolean)
|
||||
const flowerJoinSql = flowerColumns.size > 0 && flowerJoinConditions.length > 0
|
||||
? `LEFT JOIN ${quoteIdentifier(FLOWER_TABLE.schema)}.${quoteIdentifier(FLOWER_TABLE.table)} f ON ${flowerJoinConditions.join(' OR ')}`
|
||||
: ''
|
||||
|
||||
return `
|
||||
SELECT TOP (${limitSql})
|
||||
COALESCE(${columnExpr('e', e.dingtalkUserId)}, ${columnExpr('r', r.dingtalkUserId)}) AS "dingtalkUserId",
|
||||
COALESCE(${columnExpr('e', e.email)}, ${columnExpr('r', r.email)}) AS "dingEmail",
|
||||
${columnExpr('e', e.jobNumber)} AS "jobNumber",
|
||||
${columnExpr('e', e.name)} AS "contactName",
|
||||
${columnExpr('e', e.title)} AS "contactTitle",
|
||||
${columnExpr('e', e.workPlace)} AS "workPlace",
|
||||
${columnExpr('e', e.extension)} AS "extension",
|
||||
${columnExpr('r', r.registerName)} AS "registerName",
|
||||
${columnExpr('r', r.flowerName)} AS "flowerName",
|
||||
${columnExpr('r', r.realName)} AS "realName",
|
||||
${columnExpr('r', r.jobNumber)} AS "registerJobNumber",
|
||||
${columnExpr('r', r.positionTitle)} AS "positionTitle",
|
||||
${columnExpr('r', r.positionLevel)} AS "positionLevel",
|
||||
${columnExpr('r', r.departmentName)} AS "departmentName",
|
||||
${columnExpr('r', r.departmentPath)} AS "departmentPath",
|
||||
${columnExpr('r', r.employmentStatus)} AS "employmentStatus",
|
||||
COALESCE(${columnExpr('r', r.managerDingtalkUserId)}, ${columnExpr('e', e.managerDingtalkUserId)}) AS "managerDingtalkUserId",
|
||||
COALESCE(${columnExpr('r', r.managerJobNumber)}, ${columnExpr('e', e.managerJobNumber)}) AS "managerJobNumber",
|
||||
COALESCE(${columnExpr('r', r.managerName)}, ${columnExpr('e', e.managerName)}) AS "managerName",
|
||||
${columnExpr('f', f.name)} AS "flowerBookName",
|
||||
${columnExpr('f', f.flowerName)} AS "flowerBookFlowerName",
|
||||
${columnExpr('f', f.dept)} AS "flowerBookDept",
|
||||
${columnExpr('f', f.workPlace)} AS "flowerBookWorkPlace",
|
||||
${columnExpr('f', f.job)} AS "flowerBookJob",
|
||||
${columnExpr('f', f.jobLevel)} AS "flowerBookJobLevel",
|
||||
${columnExpr('f', f.role)} AS "flowerBookRole",
|
||||
${columnExpr('f', f.director)} AS "flowerBookDirector",
|
||||
${columnExpr('f', f.manager)} AS "flowerBookManager",
|
||||
${columnExpr('f', f.employeeStatus)} AS "flowerBookEmployeeStatus"
|
||||
FROM ${quoteIdentifier(EMPLOYEE_TABLE.schema)}.${quoteIdentifier(EMPLOYEE_TABLE.table)} e
|
||||
${joinSql}
|
||||
${flowerJoinSql}
|
||||
WHERE ${whereSql}
|
||||
${activeFilter}
|
||||
ORDER BY COALESCE(${columnExpr('r', r.flowerName)}, ${columnExpr('r', r.registerName)}, ${columnExpr('e', e.name)}, ${columnExpr('e', e.jobNumber)}) ASC
|
||||
`
|
||||
}
|
||||
|
||||
function buildIdentityWhere(
|
||||
employeeColumns: TableColumns,
|
||||
registerColumns: TableColumns,
|
||||
flowerColumns: TableColumns,
|
||||
identity: ReportIdentity,
|
||||
) {
|
||||
const conditions: string[] = []
|
||||
const e = {
|
||||
dingtalkUserId: pickColumn(employeeColumns, FIELD_CANDIDATES.dingtalkUserId),
|
||||
email: pickColumn(employeeColumns, FIELD_CANDIDATES.email),
|
||||
name: pickColumn(employeeColumns, FIELD_CANDIDATES.name),
|
||||
}
|
||||
const r = {
|
||||
dingtalkUserId: pickColumn(registerColumns, FIELD_CANDIDATES.dingtalkUserId),
|
||||
email: pickColumn(registerColumns, FIELD_CANDIDATES.email),
|
||||
flowerName: pickColumn(registerColumns, FIELD_CANDIDATES.flowerName),
|
||||
realName: pickColumn(registerColumns, FIELD_CANDIDATES.registerRealName),
|
||||
registerName: pickColumn(registerColumns, FIELD_CANDIDATES.registerName),
|
||||
}
|
||||
const f = {
|
||||
flowerName: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookFlowerName),
|
||||
name: pickColumn(flowerColumns, FIELD_CANDIDATES.flowerBookName),
|
||||
}
|
||||
|
||||
if (clean(identity.dingtalkUserId)) {
|
||||
conditions.push(
|
||||
...[
|
||||
eqCondition('e', e.dingtalkUserId, 'dingtalkUserId'),
|
||||
eqCondition('r', r.dingtalkUserId, 'dingtalkUserId'),
|
||||
].filter((item): item is string => Boolean(item)),
|
||||
)
|
||||
}
|
||||
if (clean(identity.email)) {
|
||||
conditions.push(
|
||||
...[
|
||||
eqCondition('e', e.email, 'email'),
|
||||
eqCondition('r', r.email, 'email'),
|
||||
].filter((item): item is string => Boolean(item)),
|
||||
)
|
||||
}
|
||||
|
||||
const nameParam = clean(identity.flowerName) || clean(identity.displayName) || clean(identity.realName) || clean(identity.username)
|
||||
if (nameParam) {
|
||||
conditions.push(
|
||||
...[
|
||||
eqCondition('r', r.flowerName, 'name'),
|
||||
eqCondition('r', r.realName, 'name'),
|
||||
eqCondition('r', r.registerName, 'name'),
|
||||
eqCondition('e', e.name, 'name'),
|
||||
eqCondition('f', f.flowerName, 'name'),
|
||||
eqCondition('f', f.name, 'name'),
|
||||
].filter((item): item is string => Boolean(item)),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
whereSql: conditions.length > 0 ? `(${conditions.join(' OR ')})` : '1 = 0',
|
||||
nameParam,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEmployeeRow(row: ReportEmployeeRow) {
|
||||
const extension = parseExtension(row.extension)
|
||||
const dingtalkUserId = clean(row.dingtalkUserId)
|
||||
const dingEmail = clean(row.dingEmail)
|
||||
const jobNumber = clean(row.registerJobNumber) || clean(row.jobNumber)
|
||||
const flowerName = clean(row.flowerBookFlowerName) || clean(row.flowerName) || clean(extension['花名'])
|
||||
const realName = clean(row.realName) || clean(row.flowerBookName) || clean(row.registerName) || clean(row.contactName)
|
||||
const displayName = flowerName || realName || jobNumber || dingtalkUserId || dingEmail || '未命名员工'
|
||||
const positionLevel = clean(row.flowerBookJobLevel) || clean(row.positionLevel) || clean(extension['岗位职级'])
|
||||
const levelType = getLevelType(positionLevel)
|
||||
const departmentName = parseDepartmentValue(row.flowerBookDept) || clean(row.departmentName)
|
||||
const positionTitle = clean(row.flowerBookJob) || clean(row.positionTitle) || clean(row.contactTitle)
|
||||
const managerName = clean(row.flowerBookManager) || clean(row.flowerBookDirector) || clean(row.managerName) || clean(extension['主管'])
|
||||
const employmentStatus = clean(row.flowerBookEmployeeStatus) || clean(row.employmentStatus)
|
||||
const workPlace = clean(row.flowerBookWorkPlace) || clean(row.workPlace)
|
||||
|
||||
return {
|
||||
dingtalkUserId,
|
||||
dingEmail,
|
||||
jobNumber,
|
||||
flowerName,
|
||||
realName,
|
||||
displayName,
|
||||
departmentName,
|
||||
departmentPath: clean(row.departmentPath),
|
||||
positionTitle,
|
||||
positionLevel,
|
||||
levelType,
|
||||
isLeadership: isLeadershipLevel(positionLevel),
|
||||
managerDingtalkUserId: clean(row.managerDingtalkUserId) || clean(extension['主管userid']),
|
||||
managerJobNumber: clean(row.managerJobNumber) || clean(extension['主管工号']),
|
||||
managerName,
|
||||
employmentStatus,
|
||||
workPlace,
|
||||
sourcePayload: {
|
||||
source: 'JSReportReplica.rpt',
|
||||
syncedFields: {
|
||||
hasDingtalkUserId: Boolean(dingtalkUserId),
|
||||
hasDingEmail: Boolean(dingEmail),
|
||||
jobNumber,
|
||||
displayName,
|
||||
departmentName,
|
||||
positionLevel,
|
||||
levelType,
|
||||
flowerBookRole: clean(row.flowerBookRole),
|
||||
},
|
||||
},
|
||||
syncedAt: new Date(),
|
||||
}
|
||||
}
|
||||
|
||||
async function findExistingEmployeeProfile(data: Partial<ReturnType<typeof normalizeEmployeeRow>>) {
|
||||
const or = [
|
||||
data.dingtalkUserId ? { dingtalkUserId: data.dingtalkUserId } : null,
|
||||
data.jobNumber ? { jobNumber: data.jobNumber } : null,
|
||||
data.dingEmail ? { dingEmail: data.dingEmail } : null,
|
||||
].filter(Boolean) as any[]
|
||||
|
||||
if (or.length === 0) return null
|
||||
return prisma.performanceSurveyEmployeeProfile.findFirst({ where: { OR: or } })
|
||||
}
|
||||
|
||||
async function upsertEmployeeProfile(data: ReturnType<typeof normalizeEmployeeRow>) {
|
||||
const existing = await findExistingEmployeeProfile(data)
|
||||
|
||||
if (existing) {
|
||||
return prisma.performanceSurveyEmployeeProfile.update({
|
||||
where: { id: existing.id },
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
return prisma.performanceSurveyEmployeeProfile.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
...data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function getParentDepartmentName(departmentName?: string | null, departmentPath?: string | null) {
|
||||
const current = clean(departmentName)
|
||||
const parts = String(departmentPath || '')
|
||||
.split(/[/>||,,;;]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
if (!current || parts.length < 2) return null
|
||||
const currentIndex = parts.lastIndexOf(current)
|
||||
return currentIndex > 0 ? parts[currentIndex - 1] : parts[parts.length - 2] || null
|
||||
}
|
||||
|
||||
async function upsertDepartments() {
|
||||
const employees = await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: {
|
||||
departmentName: { not: null },
|
||||
},
|
||||
select: {
|
||||
departmentName: true,
|
||||
departmentPath: true,
|
||||
},
|
||||
})
|
||||
|
||||
const grouped = new Map<string, { name: string; parentName: string | null; count: number }>()
|
||||
for (const employee of employees) {
|
||||
if (!employee.departmentName) continue
|
||||
const existing = grouped.get(employee.departmentName)
|
||||
grouped.set(employee.departmentName, {
|
||||
name: employee.departmentName,
|
||||
parentName: existing?.parentName || getParentDepartmentName(employee.departmentName, employee.departmentPath),
|
||||
count: (existing?.count || 0) + 1,
|
||||
})
|
||||
}
|
||||
|
||||
let count = 0
|
||||
for (const item of Array.from(grouped.values())) {
|
||||
await prisma.performanceSurveyDepartmentProfile.upsert({
|
||||
where: { name: item.name },
|
||||
update: {
|
||||
parentName: item.parentName,
|
||||
employeeCount: item.count,
|
||||
syncedAt: new Date(),
|
||||
},
|
||||
create: {
|
||||
id: randomUUID(),
|
||||
name: item.name,
|
||||
parentName: item.parentName,
|
||||
employeeCount: item.count,
|
||||
syncedAt: new Date(),
|
||||
},
|
||||
})
|
||||
count += 1
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
function shouldRefreshProfile(profile: { syncedAt?: Date | null; departmentName?: string | null; positionLevel?: string | null }) {
|
||||
if (!profile.syncedAt) return true
|
||||
if (!profile.departmentName || !profile.positionLevel) return true
|
||||
const hours = Math.max(1, Number(process.env.PERFORMANCE_SURVEY_PROFILE_SYNC_HOURS || 24))
|
||||
return Date.now() - profile.syncedAt.getTime() > hours * 60 * 60 * 1000
|
||||
}
|
||||
|
||||
async function getReportPool() {
|
||||
const imported = await import('mssql')
|
||||
const sql = (imported.default || imported) as typeof import('mssql')
|
||||
return {
|
||||
sql,
|
||||
pool: await sql.connect(getReportDbConfig() as any),
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncPerformanceSurveyEmployeeByIdentity(identity: ReportIdentity) {
|
||||
if (!isPerformanceSurveyReportDbConfigured()) return null
|
||||
|
||||
const { sql, pool } = await getReportPool()
|
||||
try {
|
||||
const schema = await getReportSchema(pool)
|
||||
const where = buildIdentityWhere(
|
||||
schema.employeeColumns,
|
||||
schema.registerColumns,
|
||||
schema.flowerColumns,
|
||||
identity,
|
||||
)
|
||||
if (where.whereSql === '1 = 0') return null
|
||||
|
||||
const request = pool.request().input('limit', sql.Int, 1)
|
||||
if (clean(identity.dingtalkUserId)) request.input('dingtalkUserId', sql.NVarChar(200), clean(identity.dingtalkUserId))
|
||||
if (clean(identity.email)) request.input('email', sql.NVarChar(320), clean(identity.email))
|
||||
if (where.nameParam) request.input('name', sql.NVarChar(200), where.nameParam)
|
||||
|
||||
const result = await request.query<ReportEmployeeRow>(
|
||||
buildSelectSql(
|
||||
schema.employeeColumns,
|
||||
schema.registerColumns,
|
||||
schema.flowerColumns,
|
||||
where.whereSql,
|
||||
'@limit',
|
||||
),
|
||||
)
|
||||
const row = result.recordset?.[0]
|
||||
if (!row) return null
|
||||
|
||||
const normalized = normalizeEmployeeRow(row)
|
||||
if (!normalized.dingtalkUserId && !normalized.jobNumber && !normalized.dingEmail) return null
|
||||
const profile = await upsertEmployeeProfile(normalized)
|
||||
await upsertDepartments()
|
||||
return profile
|
||||
} finally {
|
||||
await pool.close()
|
||||
}
|
||||
}
|
||||
|
||||
export async function previewPerformanceSurveyEmployeeByIdentity(identity: ReportIdentity) {
|
||||
if (!isPerformanceSurveyReportDbConfigured()) return null
|
||||
|
||||
const { sql, pool } = await getReportPool()
|
||||
try {
|
||||
const schema = await getReportSchema(pool)
|
||||
const where = buildIdentityWhere(
|
||||
schema.employeeColumns,
|
||||
schema.registerColumns,
|
||||
schema.flowerColumns,
|
||||
identity,
|
||||
)
|
||||
if (where.whereSql === '1 = 0') return null
|
||||
|
||||
const request = pool.request().input('limit', sql.Int, 1)
|
||||
if (clean(identity.dingtalkUserId)) request.input('dingtalkUserId', sql.NVarChar(200), clean(identity.dingtalkUserId))
|
||||
if (clean(identity.email)) request.input('email', sql.NVarChar(320), clean(identity.email))
|
||||
if (where.nameParam) request.input('name', sql.NVarChar(200), where.nameParam)
|
||||
|
||||
const result = await request.query<ReportEmployeeRow>(
|
||||
buildSelectSql(
|
||||
schema.employeeColumns,
|
||||
schema.registerColumns,
|
||||
schema.flowerColumns,
|
||||
where.whereSql,
|
||||
'@limit',
|
||||
),
|
||||
)
|
||||
const row = result.recordset?.[0]
|
||||
return row ? normalizeEmployeeRow(row) : null
|
||||
} finally {
|
||||
await pool.close()
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensurePerformanceSurveyEmployeeProfileForUser(identity: ReportIdentity & { userId?: string }) {
|
||||
const existing = await findExistingEmployeeProfile({
|
||||
dingtalkUserId: clean(identity.dingtalkUserId),
|
||||
dingEmail: clean(identity.email),
|
||||
})
|
||||
|
||||
if (isPerformanceSurveyReportDbConfigured() && (!existing || shouldRefreshProfile(existing))) {
|
||||
try {
|
||||
const synced = await syncPerformanceSurveyEmployeeByIdentity(identity)
|
||||
if (synced) return synced
|
||||
} catch (error) {
|
||||
console.warn('[performance-survey] 人员档案同步失败,使用本地兜底档案:', error)
|
||||
}
|
||||
}
|
||||
|
||||
if (existing) return existing
|
||||
|
||||
const fallbackData = {
|
||||
id: randomUUID(),
|
||||
dingtalkUserId: clean(identity.dingtalkUserId),
|
||||
dingEmail: clean(identity.email),
|
||||
displayName: clean(identity.flowerName) || clean(identity.displayName) || clean(identity.realName) || clean(identity.username) || '未知员工',
|
||||
realName: clean(identity.realName) || clean(identity.username),
|
||||
flowerName: clean(identity.flowerName) || null,
|
||||
sourcePayload: { source: 'material_user_fallback', userId: identity.userId || null },
|
||||
syncedAt: new Date(),
|
||||
}
|
||||
|
||||
return prisma.performanceSurveyEmployeeProfile.create({ data: fallbackData })
|
||||
}
|
||||
|
||||
export function ensurePerformanceSurveyDailyEmployeeSyncStarted() {
|
||||
if (dailyWorkerStarted) return
|
||||
dailyWorkerStarted = true
|
||||
|
||||
const intervalHours = Math.max(1, Number(process.env.PERFORMANCE_SURVEY_DAILY_SYNC_INTERVAL_HOURS || 24))
|
||||
const initialDelayMs = Math.max(10, Number(process.env.PERFORMANCE_SURVEY_DAILY_SYNC_INITIAL_DELAY_SECONDS || 300)) * 1000
|
||||
const intervalMs = intervalHours * 60 * 60 * 1000
|
||||
const limit = Math.max(1, Math.min(Number(process.env.PERFORMANCE_SURVEY_DAILY_SYNC_LIMIT || 3000), 10_000))
|
||||
|
||||
const run = async () => {
|
||||
if (!isPerformanceSurveyReportDbConfigured()) return
|
||||
try {
|
||||
await syncPerformanceSurveyEmployees({ limit })
|
||||
} catch (error) {
|
||||
console.warn('[performance-survey] 每日人员档案同步失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const bootstrap = setTimeout(() => void run(), initialDelayMs)
|
||||
bootstrap.unref?.()
|
||||
|
||||
const timer = setInterval(() => void run(), intervalMs)
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
export async function syncPerformanceSurveyEmployees(options?: { limit?: number }) {
|
||||
const limit = Math.max(1, Math.min(Number(options?.limit || 3000), 10_000))
|
||||
const { sql, pool } = await getReportPool()
|
||||
|
||||
try {
|
||||
const schema = await getReportSchema(pool)
|
||||
const result = await pool
|
||||
.request()
|
||||
.input('limit', sql.Int, limit)
|
||||
.query<ReportEmployeeRow>(
|
||||
buildSelectSql(
|
||||
schema.employeeColumns,
|
||||
schema.registerColumns,
|
||||
schema.flowerColumns,
|
||||
'1 = 1',
|
||||
'@limit',
|
||||
),
|
||||
)
|
||||
|
||||
let upserted = 0
|
||||
let skipped = 0
|
||||
for (const row of result.recordset || []) {
|
||||
const normalized = normalizeEmployeeRow(row)
|
||||
if (!normalized.dingtalkUserId && !normalized.jobNumber && !normalized.dingEmail) {
|
||||
skipped += 1
|
||||
continue
|
||||
}
|
||||
await upsertEmployeeProfile(normalized)
|
||||
upserted += 1
|
||||
}
|
||||
|
||||
const departmentCount = await upsertDepartments()
|
||||
|
||||
return {
|
||||
upserted,
|
||||
skipped,
|
||||
departmentCount,
|
||||
syncedAt: new Date().toISOString(),
|
||||
}
|
||||
} finally {
|
||||
await pool.close()
|
||||
}
|
||||
}
|
||||
1049
lib/performance-survey-service.ts
Normal file
1049
lib/performance-survey-service.ts
Normal file
File diff suppressed because it is too large
Load Diff
234
lib/performance-survey-templates.ts
Normal file
234
lib/performance-survey-templates.ts
Normal file
@ -0,0 +1,234 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export type PerformanceSurveyQuestion = {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export type PerformanceSurveyScoreBand = {
|
||||
min: number
|
||||
max: number
|
||||
score: number
|
||||
}
|
||||
|
||||
export type PerformanceSurveyTemplateShape = {
|
||||
code: string
|
||||
name: string
|
||||
description: string
|
||||
surveyType: string
|
||||
weight: number
|
||||
questions: PerformanceSurveyQuestion[]
|
||||
scoreBands: PerformanceSurveyScoreBand[]
|
||||
}
|
||||
|
||||
export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShape[] = [
|
||||
{
|
||||
code: 'course_share',
|
||||
name: '课程/分享调研',
|
||||
description: '适用于课程培训、经验分享、内部活动后的满意度与效果反馈。',
|
||||
surveyType: 'item_course',
|
||||
weight: 1,
|
||||
questions: [
|
||||
{ id: 'content_value', title: '内容价值', description: '内容对工作是否有帮助' },
|
||||
{ id: 'clarity', title: '表达清晰度', description: '讲解逻辑、重点和案例是否清楚' },
|
||||
{ id: 'practicality', title: '可落地程度', description: '是否能转化为实际行动' },
|
||||
{ id: 'interaction', title: '互动与答疑', description: '现场互动和问题回应情况' },
|
||||
],
|
||||
scoreBands: [
|
||||
{ min: 0, max: 12, score: 60 },
|
||||
{ min: 12, max: 15, score: 75 },
|
||||
{ min: 15, max: 18, score: 90 },
|
||||
{ min: 18, max: 20, score: 100 },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: 'cross_department',
|
||||
name: '跨部门协作考核',
|
||||
description: '适用于跨部门项目、流程配合、协同响应等人员周期考核。',
|
||||
surveyType: 'person_period',
|
||||
weight: 1,
|
||||
questions: [
|
||||
{ id: 'response_speed', title: '响应速度', description: '需求响应是否及时' },
|
||||
{ id: 'delivery_quality', title: '交付质量', description: '交付结果是否稳定可靠' },
|
||||
{ id: 'communication', title: '沟通协同', description: '沟通是否主动、清晰、闭环' },
|
||||
{ id: 'ownership', title: '责任意识', description: '是否能主动推进问题解决' },
|
||||
],
|
||||
scoreBands: [
|
||||
{ min: 0, max: 12, score: 60 },
|
||||
{ min: 12, max: 15, score: 75 },
|
||||
{ min: 15, max: 18, score: 90 },
|
||||
{ min: 18, max: 20, score: 100 },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: 'work_cooperation',
|
||||
name: '日常工作配合考核',
|
||||
description: '适用于常规工作协作、服务支持、团队内互评。',
|
||||
surveyType: 'person_period',
|
||||
weight: 1,
|
||||
questions: [
|
||||
{ id: 'professionalism', title: '专业能力', description: '专业判断和处理问题能力' },
|
||||
{ id: 'reliability', title: '可靠程度', description: '承诺事项是否稳定完成' },
|
||||
{ id: 'service_attitude', title: '服务态度', description: '协作态度和服务意识' },
|
||||
{ id: 'improvement', title: '改进意识', description: '是否持续优化工作方式' },
|
||||
],
|
||||
scoreBands: [
|
||||
{ min: 0, max: 12, score: 60 },
|
||||
{ min: 12, max: 15, score: 75 },
|
||||
{ min: 15, max: 18, score: 90 },
|
||||
{ min: 18, max: 20, score: 100 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export async function ensurePerformanceSurveyTemplates() {
|
||||
for (const template of DEFAULT_PERFORMANCE_SURVEY_TEMPLATES) {
|
||||
await prisma.performanceSurveyTemplate.upsert({
|
||||
where: { code: template.code },
|
||||
update: {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
surveyType: template.surveyType,
|
||||
weight: template.weight,
|
||||
questions: template.questions,
|
||||
scoreBands: template.scoreBands,
|
||||
isActive: true,
|
||||
},
|
||||
create: {
|
||||
code: template.code,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
surveyType: template.surveyType,
|
||||
weight: template.weight,
|
||||
questions: template.questions,
|
||||
scoreBands: template.scoreBands,
|
||||
isActive: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function listPerformanceSurveyTemplates() {
|
||||
await ensurePerformanceSurveyTemplates()
|
||||
|
||||
const templates = await prisma.performanceSurveyTemplate.findMany({
|
||||
where: { isActive: true },
|
||||
orderBy: [{ surveyType: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
|
||||
return templates.map((template) => ({
|
||||
code: template.code,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
surveyType: template.surveyType,
|
||||
weight: template.weight,
|
||||
questions: template.questions,
|
||||
scoreBands: template.scoreBands,
|
||||
}))
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyTemplate(code: string) {
|
||||
await ensurePerformanceSurveyTemplates()
|
||||
|
||||
const template = await prisma.performanceSurveyTemplate.findUnique({
|
||||
where: { code },
|
||||
})
|
||||
|
||||
if (!template || !template.isActive) {
|
||||
throw new Error('考核调研模板不存在')
|
||||
}
|
||||
|
||||
return {
|
||||
code: template.code,
|
||||
name: template.name,
|
||||
description: template.description || '',
|
||||
surveyType: template.surveyType,
|
||||
weight: template.weight,
|
||||
questions: template.questions as PerformanceSurveyQuestion[],
|
||||
scoreBands: template.scoreBands as PerformanceSurveyScoreBand[],
|
||||
}
|
||||
}
|
||||
|
||||
export function calculateResponseScores(
|
||||
template: Pick<PerformanceSurveyTemplateShape, 'questions' | 'scoreBands' | 'weight'>,
|
||||
scores: Record<string, unknown>,
|
||||
) {
|
||||
const questionScores = template.questions.map((question) => {
|
||||
const value = Number(scores[question.id])
|
||||
if (!Number.isFinite(value) || value < 0 || value > 20) {
|
||||
throw new Error(`评分项「${question.title}」必须是 0-20 分`)
|
||||
}
|
||||
return value
|
||||
})
|
||||
|
||||
const totalScore =
|
||||
questionScores.length > 0
|
||||
? questionScores.reduce((sum, score) => sum + score, 0) / questionScores.length
|
||||
: 0
|
||||
|
||||
const kpiScore = mapAchievementToKpiScore(totalScore, template.scoreBands)
|
||||
|
||||
return {
|
||||
totalScore: roundScore(totalScore),
|
||||
achievementScore: roundScore(totalScore),
|
||||
kpiScore: roundScore(kpiScore),
|
||||
weightedScore: roundScore(kpiScore * Number(template.weight || 1)),
|
||||
}
|
||||
}
|
||||
|
||||
export function calculateAggregateScore(
|
||||
responses: Array<{ totalScore: number; createdAt: Date | string }>,
|
||||
scoreBands: PerformanceSurveyScoreBand[],
|
||||
weight: number,
|
||||
) {
|
||||
const sorted = [...responses].sort((left, right) => {
|
||||
const scoreDiff = Number(left.totalScore || 0) - Number(right.totalScore || 0)
|
||||
if (scoreDiff !== 0) return scoreDiff
|
||||
return new Date(String(left.createdAt)).getTime() - new Date(String(right.createdAt)).getTime()
|
||||
})
|
||||
|
||||
const effective =
|
||||
sorted.length >= 3
|
||||
? sorted.slice(1, -1)
|
||||
: sorted
|
||||
|
||||
const achievementScore =
|
||||
effective.length > 0
|
||||
? effective.reduce((sum, response) => sum + Number(response.totalScore || 0), 0) / effective.length
|
||||
: 0
|
||||
const kpiScore = mapAchievementToKpiScore(achievementScore, scoreBands)
|
||||
|
||||
return {
|
||||
responseCount: responses.length,
|
||||
effectiveCount: effective.length,
|
||||
droppedHighestLowest: sorted.length >= 3,
|
||||
achievementScore: roundScore(achievementScore),
|
||||
kpiScore: roundScore(kpiScore),
|
||||
weightedScore: roundScore(kpiScore * Number(weight || 1)),
|
||||
}
|
||||
}
|
||||
|
||||
function mapAchievementToKpiScore(value: number, bands: PerformanceSurveyScoreBand[]) {
|
||||
const normalizedBands = [...bands].sort((left, right) => left.min - right.min)
|
||||
const matched = normalizedBands.find((band) => value >= band.min && value <= band.max)
|
||||
if (!matched) {
|
||||
if (value < normalizedBands[0]?.min) return normalizedBands[0]?.score || 0
|
||||
return normalizedBands[normalizedBands.length - 1]?.score || 0
|
||||
}
|
||||
|
||||
const previous = normalizedBands
|
||||
.filter((band) => band.max <= matched.min)
|
||||
.sort((left, right) => right.max - left.max)[0]
|
||||
|
||||
if (!previous || matched.max === matched.min) {
|
||||
return matched.score
|
||||
}
|
||||
|
||||
const ratio = (value - matched.min) / (matched.max - matched.min)
|
||||
return previous.score + ratio * (matched.score - previous.score)
|
||||
}
|
||||
|
||||
function roundScore(value: number) {
|
||||
return Math.round(Number(value || 0) * 100) / 100
|
||||
}
|
||||
704
package-lock.json
generated
704
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -38,6 +38,7 @@
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"jszip": "^3.10.1",
|
||||
"mime-types": "^2.1.35",
|
||||
"mssql": "10.0.4",
|
||||
"music-metadata": "^11.10.3",
|
||||
"next": "^14.2.0",
|
||||
"next-auth": "^4.24.0",
|
||||
|
||||
@ -0,0 +1,285 @@
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_employee_profiles" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"dingtalk_user_id" TEXT,
|
||||
"ding_email" TEXT,
|
||||
"job_number" TEXT,
|
||||
"flower_name" TEXT,
|
||||
"real_name" TEXT,
|
||||
"display_name" TEXT NOT NULL,
|
||||
"department_name" TEXT,
|
||||
"department_path" TEXT,
|
||||
"position_title" TEXT,
|
||||
"position_level" TEXT,
|
||||
"level_type" TEXT,
|
||||
"is_leadership" BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
"manager_dingtalk_user_id" TEXT,
|
||||
"manager_job_number" TEXT,
|
||||
"manager_name" TEXT,
|
||||
"employment_status" TEXT,
|
||||
"work_place" TEXT,
|
||||
"source_payload" JSONB,
|
||||
"synced_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_employee_profiles_dingtalk_user_id_key"
|
||||
ON "performance_survey_employee_profiles" ("dingtalk_user_id");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_employee_profiles_job_number_key"
|
||||
ON "performance_survey_employee_profiles" ("job_number");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_display_name_idx"
|
||||
ON "performance_survey_employee_profiles" ("display_name");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_ding_email_idx"
|
||||
ON "performance_survey_employee_profiles" ("ding_email");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_department_name_idx"
|
||||
ON "performance_survey_employee_profiles" ("department_name");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_position_level_idx"
|
||||
ON "performance_survey_employee_profiles" ("position_level");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_level_type_idx"
|
||||
ON "performance_survey_employee_profiles" ("level_type");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_is_leadership_idx"
|
||||
ON "performance_survey_employee_profiles" ("is_leadership");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_manager_dingtalk_user_id_idx"
|
||||
ON "performance_survey_employee_profiles" ("manager_dingtalk_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_employee_profiles_employment_status_idx"
|
||||
ON "performance_survey_employee_profiles" ("employment_status");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_department_profiles" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"name" TEXT NOT NULL,
|
||||
"parent_name" TEXT,
|
||||
"source_dept_id" TEXT,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 0,
|
||||
"employee_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"synced_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_department_profiles_name_key"
|
||||
ON "performance_survey_department_profiles" ("name");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_department_profiles_parent_name_idx"
|
||||
ON "performance_survey_department_profiles" ("parent_name");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_department_profiles_source_dept_id_idx"
|
||||
ON "performance_survey_department_profiles" ("source_dept_id");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_templates" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"survey_type" TEXT NOT NULL DEFAULT 'person_period',
|
||||
"weight" DOUBLE PRECISION NOT NULL DEFAULT 1,
|
||||
"questions" JSONB NOT NULL,
|
||||
"score_bands" JSONB NOT NULL,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_templates_code_key"
|
||||
ON "performance_survey_templates" ("code");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_templates_survey_type_idx"
|
||||
ON "performance_survey_templates" ("survey_type");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_templates_is_active_idx"
|
||||
ON "performance_survey_templates" ("is_active");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_surveys" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"survey_kind" TEXT NOT NULL DEFAULT 'person_period',
|
||||
"template_code" TEXT NOT NULL,
|
||||
"template_snapshot" JSONB NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'draft',
|
||||
"creator_user_id" TEXT NOT NULL,
|
||||
"creator_name" TEXT NOT NULL,
|
||||
"creator_employee_id" TEXT,
|
||||
"department_name" TEXT,
|
||||
"due_at" TIMESTAMP(3),
|
||||
"opened_at" TIMESTAMP(3),
|
||||
"closed_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_status_idx"
|
||||
ON "performance_surveys" ("status");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_survey_kind_idx"
|
||||
ON "performance_surveys" ("survey_kind");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_template_code_idx"
|
||||
ON "performance_surveys" ("template_code");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_creator_user_id_idx"
|
||||
ON "performance_surveys" ("creator_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_department_name_idx"
|
||||
ON "performance_surveys" ("department_name");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_due_at_idx"
|
||||
ON "performance_surveys" ("due_at");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_targets" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"survey_id" TEXT NOT NULL,
|
||||
"target_type" TEXT NOT NULL DEFAULT 'employee',
|
||||
"employee_profile_id" TEXT,
|
||||
"target_name" TEXT NOT NULL,
|
||||
"target_snapshot" JSONB NOT NULL,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 0,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_targets_survey_id_fkey"
|
||||
FOREIGN KEY ("survey_id") REFERENCES "performance_surveys"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_targets_employee_profile_id_fkey"
|
||||
FOREIGN KEY ("employee_profile_id") REFERENCES "performance_survey_employee_profiles"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_targets_survey_id_idx"
|
||||
ON "performance_survey_targets" ("survey_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_targets_target_type_idx"
|
||||
ON "performance_survey_targets" ("target_type");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_targets_employee_profile_id_idx"
|
||||
ON "performance_survey_targets" ("employee_profile_id");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_assignments" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"survey_id" TEXT NOT NULL,
|
||||
"target_id" TEXT NOT NULL,
|
||||
"evaluator_employee_id" TEXT,
|
||||
"evaluator_user_id" TEXT,
|
||||
"evaluator_dingtalk_user_id" TEXT,
|
||||
"evaluator_key" TEXT NOT NULL,
|
||||
"evaluator_name" TEXT NOT NULL,
|
||||
"evaluator_snapshot" JSONB NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"submitted_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_assignments_survey_id_fkey"
|
||||
FOREIGN KEY ("survey_id") REFERENCES "performance_surveys"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_assignments_target_id_fkey"
|
||||
FOREIGN KEY ("target_id") REFERENCES "performance_survey_targets"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_assignments_evaluator_employee_id_fkey"
|
||||
FOREIGN KEY ("evaluator_employee_id") REFERENCES "performance_survey_employee_profiles"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_assignment_target_evaluator_key"
|
||||
ON "performance_survey_assignments" ("target_id", "evaluator_key");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_survey_id_idx"
|
||||
ON "performance_survey_assignments" ("survey_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_target_id_idx"
|
||||
ON "performance_survey_assignments" ("target_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_evaluator_employee_id_idx"
|
||||
ON "performance_survey_assignments" ("evaluator_employee_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_evaluator_user_id_idx"
|
||||
ON "performance_survey_assignments" ("evaluator_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_evaluator_dingtalk_user_id_idx"
|
||||
ON "performance_survey_assignments" ("evaluator_dingtalk_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_evaluator_key_idx"
|
||||
ON "performance_survey_assignments" ("evaluator_key");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignments_status_idx"
|
||||
ON "performance_survey_assignments" ("status");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_responses" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"survey_id" TEXT NOT NULL,
|
||||
"target_id" TEXT NOT NULL,
|
||||
"assignment_id" TEXT NOT NULL,
|
||||
"respondent_user_id" TEXT NOT NULL,
|
||||
"respondent_employee_id" TEXT,
|
||||
"respondent_name" TEXT NOT NULL,
|
||||
"respondent_snapshot" JSONB NOT NULL,
|
||||
"scores" JSONB NOT NULL,
|
||||
"comment" TEXT,
|
||||
"total_score" DOUBLE PRECISION NOT NULL,
|
||||
"achievement_score" DOUBLE PRECISION NOT NULL,
|
||||
"kpi_score" DOUBLE PRECISION NOT NULL,
|
||||
"weighted_score" DOUBLE PRECISION NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_responses_survey_id_fkey"
|
||||
FOREIGN KEY ("survey_id") REFERENCES "performance_surveys"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_responses_target_id_fkey"
|
||||
FOREIGN KEY ("target_id") REFERENCES "performance_survey_targets"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_responses_assignment_id_fkey"
|
||||
FOREIGN KEY ("assignment_id") REFERENCES "performance_survey_assignments"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_responses_respondent_employee_id_fkey"
|
||||
FOREIGN KEY ("respondent_employee_id") REFERENCES "performance_survey_employee_profiles"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_responses_assignment_id_key"
|
||||
ON "performance_survey_responses" ("assignment_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_responses_survey_id_idx"
|
||||
ON "performance_survey_responses" ("survey_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_responses_target_id_idx"
|
||||
ON "performance_survey_responses" ("target_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_responses_respondent_user_id_idx"
|
||||
ON "performance_survey_responses" ("respondent_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_responses_respondent_employee_id_idx"
|
||||
ON "performance_survey_responses" ("respondent_employee_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_responses_created_at_idx"
|
||||
ON "performance_survey_responses" ("created_at");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_notifications" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"survey_id" TEXT,
|
||||
"target_id" TEXT,
|
||||
"assignment_id" TEXT,
|
||||
"recipient_employee_id" TEXT,
|
||||
"recipient_user_id" TEXT,
|
||||
"dingtalk_user_id" TEXT,
|
||||
"recipient_name" TEXT NOT NULL,
|
||||
"event_type" TEXT NOT NULL,
|
||||
"business_key" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"action_url" TEXT,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"attempt_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"max_attempts" INTEGER NOT NULL DEFAULT 5,
|
||||
"next_retry_at" TIMESTAMP(3),
|
||||
"last_status_code" INTEGER,
|
||||
"last_response_body" TEXT,
|
||||
"last_error" TEXT,
|
||||
"provider_message_id" TEXT,
|
||||
"sent_at" TIMESTAMP(3),
|
||||
"completed_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_notifications_survey_id_fkey"
|
||||
FOREIGN KEY ("survey_id") REFERENCES "performance_surveys"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_notifications_target_id_fkey"
|
||||
FOREIGN KEY ("target_id") REFERENCES "performance_survey_targets"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_notifications_assignment_id_fkey"
|
||||
FOREIGN KEY ("assignment_id") REFERENCES "performance_survey_assignments"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_notifications_recipient_employee_id_fkey"
|
||||
FOREIGN KEY ("recipient_employee_id") REFERENCES "performance_survey_employee_profiles"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_notification_event_key"
|
||||
ON "performance_survey_notifications" ("event_type", "business_key");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_survey_id_idx"
|
||||
ON "performance_survey_notifications" ("survey_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_target_id_idx"
|
||||
ON "performance_survey_notifications" ("target_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_assignment_id_idx"
|
||||
ON "performance_survey_notifications" ("assignment_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_recipient_employee_id_idx"
|
||||
ON "performance_survey_notifications" ("recipient_employee_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_recipient_user_id_idx"
|
||||
ON "performance_survey_notifications" ("recipient_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_dingtalk_user_id_idx"
|
||||
ON "performance_survey_notifications" ("dingtalk_user_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_status_next_retry_idx"
|
||||
ON "performance_survey_notifications" ("status", "next_retry_at");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_notifications_created_at_idx"
|
||||
ON "performance_survey_notifications" ("created_at");
|
||||
@ -487,6 +487,234 @@ model ExternalMaterialImportJob {
|
||||
@@map("external_material_import_jobs")
|
||||
}
|
||||
|
||||
model PerformanceSurveyEmployeeProfile {
|
||||
id String @id @default(uuid())
|
||||
dingtalkUserId String? @unique @map("dingtalk_user_id")
|
||||
dingEmail String? @map("ding_email")
|
||||
jobNumber String? @unique @map("job_number")
|
||||
flowerName String? @map("flower_name")
|
||||
realName String? @map("real_name")
|
||||
displayName String @map("display_name")
|
||||
departmentName String? @map("department_name")
|
||||
departmentPath String? @map("department_path")
|
||||
positionTitle String? @map("position_title")
|
||||
positionLevel String? @map("position_level")
|
||||
levelType String? @map("level_type")
|
||||
isLeadership Boolean @default(false) @map("is_leadership")
|
||||
managerDingtalkUserId String? @map("manager_dingtalk_user_id")
|
||||
managerJobNumber String? @map("manager_job_number")
|
||||
managerName String? @map("manager_name")
|
||||
employmentStatus String? @map("employment_status")
|
||||
workPlace String? @map("work_place")
|
||||
sourcePayload Json? @map("source_payload")
|
||||
syncedAt DateTime? @map("synced_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
evaluatorAssignments PerformanceSurveyAssignment[] @relation("PerformanceSurveyEvaluator")
|
||||
targetRecords PerformanceSurveyTarget[] @relation("PerformanceSurveyTargetEmployee")
|
||||
responses PerformanceSurveyResponse[] @relation("PerformanceSurveyRespondentEmployee")
|
||||
notifications PerformanceSurveyNotification[]
|
||||
|
||||
@@index([displayName])
|
||||
@@index([dingEmail])
|
||||
@@index([departmentName])
|
||||
@@index([positionLevel])
|
||||
@@index([levelType])
|
||||
@@index([isLeadership])
|
||||
@@index([managerDingtalkUserId])
|
||||
@@index([employmentStatus])
|
||||
@@map("performance_survey_employee_profiles")
|
||||
}
|
||||
|
||||
model PerformanceSurveyDepartmentProfile {
|
||||
id String @id @default(uuid())
|
||||
name String @unique
|
||||
parentName String? @map("parent_name")
|
||||
sourceDeptId String? @map("source_dept_id")
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
employeeCount Int @default(0) @map("employee_count")
|
||||
syncedAt DateTime? @map("synced_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@index([parentName])
|
||||
@@index([sourceDeptId])
|
||||
@@map("performance_survey_department_profiles")
|
||||
}
|
||||
|
||||
model PerformanceSurveyTemplate {
|
||||
id String @id @default(uuid())
|
||||
code String @unique
|
||||
name String
|
||||
description String?
|
||||
surveyType String @default("person_period") @map("survey_type")
|
||||
weight Float @default(1)
|
||||
questions Json
|
||||
scoreBands Json @map("score_bands")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@index([surveyType])
|
||||
@@index([isActive])
|
||||
@@map("performance_survey_templates")
|
||||
}
|
||||
|
||||
model PerformanceSurvey {
|
||||
id String @id @default(uuid())
|
||||
title String
|
||||
description String?
|
||||
surveyKind String @default("person_period") @map("survey_kind")
|
||||
templateCode String @map("template_code")
|
||||
templateSnapshot Json @map("template_snapshot")
|
||||
status String @default("draft")
|
||||
creatorUserId String @map("creator_user_id")
|
||||
creatorName String @map("creator_name")
|
||||
creatorEmployeeId String? @map("creator_employee_id")
|
||||
departmentName String? @map("department_name")
|
||||
dueAt DateTime? @map("due_at")
|
||||
openedAt DateTime? @map("opened_at")
|
||||
closedAt DateTime? @map("closed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
targets PerformanceSurveyTarget[]
|
||||
assignments PerformanceSurveyAssignment[]
|
||||
responses PerformanceSurveyResponse[]
|
||||
notifications PerformanceSurveyNotification[]
|
||||
|
||||
@@index([status])
|
||||
@@index([surveyKind])
|
||||
@@index([templateCode])
|
||||
@@index([creatorUserId])
|
||||
@@index([departmentName])
|
||||
@@index([dueAt])
|
||||
@@map("performance_surveys")
|
||||
}
|
||||
|
||||
model PerformanceSurveyTarget {
|
||||
id String @id @default(uuid())
|
||||
surveyId String @map("survey_id")
|
||||
targetType String @default("employee") @map("target_type")
|
||||
employeeProfileId String? @map("employee_profile_id")
|
||||
targetName String @map("target_name")
|
||||
targetSnapshot Json @map("target_snapshot")
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
survey PerformanceSurvey @relation(fields: [surveyId], references: [id], onDelete: Cascade)
|
||||
employeeProfile PerformanceSurveyEmployeeProfile? @relation("PerformanceSurveyTargetEmployee", fields: [employeeProfileId], references: [id])
|
||||
assignments PerformanceSurveyAssignment[]
|
||||
responses PerformanceSurveyResponse[]
|
||||
notifications PerformanceSurveyNotification[]
|
||||
|
||||
@@index([surveyId])
|
||||
@@index([targetType])
|
||||
@@index([employeeProfileId])
|
||||
@@map("performance_survey_targets")
|
||||
}
|
||||
|
||||
model PerformanceSurveyAssignment {
|
||||
id String @id @default(uuid())
|
||||
surveyId String @map("survey_id")
|
||||
targetId String @map("target_id")
|
||||
evaluatorEmployeeId String? @map("evaluator_employee_id")
|
||||
evaluatorUserId String? @map("evaluator_user_id")
|
||||
evaluatorDingtalkUserId String? @map("evaluator_dingtalk_user_id")
|
||||
evaluatorKey String @map("evaluator_key")
|
||||
evaluatorName String @map("evaluator_name")
|
||||
evaluatorSnapshot Json @map("evaluator_snapshot")
|
||||
status String @default("pending")
|
||||
submittedAt DateTime? @map("submitted_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
survey PerformanceSurvey @relation(fields: [surveyId], references: [id], onDelete: Cascade)
|
||||
target PerformanceSurveyTarget @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
evaluatorEmployee PerformanceSurveyEmployeeProfile? @relation("PerformanceSurveyEvaluator", fields: [evaluatorEmployeeId], references: [id])
|
||||
response PerformanceSurveyResponse?
|
||||
notifications PerformanceSurveyNotification[]
|
||||
|
||||
@@unique([targetId, evaluatorKey], map: "performance_survey_assignment_target_evaluator_key")
|
||||
@@index([surveyId])
|
||||
@@index([targetId])
|
||||
@@index([evaluatorEmployeeId])
|
||||
@@index([evaluatorUserId])
|
||||
@@index([evaluatorDingtalkUserId])
|
||||
@@index([evaluatorKey])
|
||||
@@index([status])
|
||||
@@map("performance_survey_assignments")
|
||||
}
|
||||
|
||||
model PerformanceSurveyResponse {
|
||||
id String @id @default(uuid())
|
||||
surveyId String @map("survey_id")
|
||||
targetId String @map("target_id")
|
||||
assignmentId String @unique @map("assignment_id")
|
||||
respondentUserId String @map("respondent_user_id")
|
||||
respondentEmployeeId String? @map("respondent_employee_id")
|
||||
respondentName String @map("respondent_name")
|
||||
respondentSnapshot Json @map("respondent_snapshot")
|
||||
scores Json
|
||||
comment String?
|
||||
totalScore Float @map("total_score")
|
||||
achievementScore Float @map("achievement_score")
|
||||
kpiScore Float @map("kpi_score")
|
||||
weightedScore Float @map("weighted_score")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
survey PerformanceSurvey @relation(fields: [surveyId], references: [id], onDelete: Cascade)
|
||||
target PerformanceSurveyTarget @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
assignment PerformanceSurveyAssignment @relation(fields: [assignmentId], references: [id], onDelete: Cascade)
|
||||
respondentEmployee PerformanceSurveyEmployeeProfile? @relation("PerformanceSurveyRespondentEmployee", fields: [respondentEmployeeId], references: [id])
|
||||
|
||||
@@index([surveyId])
|
||||
@@index([targetId])
|
||||
@@index([respondentUserId])
|
||||
@@index([respondentEmployeeId])
|
||||
@@index([createdAt])
|
||||
@@map("performance_survey_responses")
|
||||
}
|
||||
|
||||
model PerformanceSurveyNotification {
|
||||
id String @id @default(uuid())
|
||||
surveyId String? @map("survey_id")
|
||||
targetId String? @map("target_id")
|
||||
assignmentId String? @map("assignment_id")
|
||||
recipientEmployeeId String? @map("recipient_employee_id")
|
||||
recipientUserId String? @map("recipient_user_id")
|
||||
dingtalkUserId String? @map("dingtalk_user_id")
|
||||
recipientName String @map("recipient_name")
|
||||
eventType String @map("event_type")
|
||||
businessKey String @map("business_key")
|
||||
title String
|
||||
content String
|
||||
actionUrl String? @map("action_url")
|
||||
status String @default("pending")
|
||||
attemptCount Int @default(0) @map("attempt_count")
|
||||
maxAttempts Int @default(5) @map("max_attempts")
|
||||
nextRetryAt DateTime? @map("next_retry_at")
|
||||
lastStatusCode Int? @map("last_status_code")
|
||||
lastResponseBody String? @map("last_response_body")
|
||||
lastError String? @map("last_error")
|
||||
providerMessageId String? @map("provider_message_id")
|
||||
sentAt DateTime? @map("sent_at")
|
||||
completedAt DateTime? @map("completed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
survey PerformanceSurvey? @relation(fields: [surveyId], references: [id], onDelete: Cascade)
|
||||
target PerformanceSurveyTarget? @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
assignment PerformanceSurveyAssignment? @relation(fields: [assignmentId], references: [id], onDelete: Cascade)
|
||||
recipientEmployee PerformanceSurveyEmployeeProfile? @relation(fields: [recipientEmployeeId], references: [id])
|
||||
|
||||
@@unique([eventType, businessKey], map: "performance_survey_notification_event_key")
|
||||
@@index([surveyId])
|
||||
@@index([targetId])
|
||||
@@index([assignmentId])
|
||||
@@index([recipientEmployeeId])
|
||||
@@index([recipientUserId])
|
||||
@@index([dingtalkUserId])
|
||||
@@index([status, nextRetryAt])
|
||||
@@index([createdAt])
|
||||
@@map("performance_survey_notifications")
|
||||
}
|
||||
|
||||
model VideoTranscodeProgress {
|
||||
id String @id @default(uuid())
|
||||
materialId String @map("material_id")
|
||||
|
||||
23
types/mssql.d.ts
vendored
Normal file
23
types/mssql.d.ts
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
declare module 'mssql' {
|
||||
export interface Request {
|
||||
input(name: string, type: unknown, value: unknown): Request
|
||||
query<T = any>(sql: string): Promise<{ recordset: T[] }>
|
||||
}
|
||||
|
||||
export interface ConnectionPool {
|
||||
request(): Request
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
export const Int: unknown
|
||||
export function NVarChar(length?: number): unknown
|
||||
export function connect(config: unknown): Promise<ConnectionPool>
|
||||
|
||||
const sql: {
|
||||
Int: typeof Int
|
||||
NVarChar: typeof NVarChar
|
||||
connect: typeof connect
|
||||
}
|
||||
|
||||
export default sql
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user