feat: AI历史记录、企业信息seed、员工状态自动刷新、风险预测数据准确性优化
- 智能问答/风险预测/合同审查/案例匹配 均支持历史记录保存、加载、删除 - 后端 predict/predict-stream 补充离职记录详情和预计算工龄/天数,避免AI计算错误 - Organization 增加 contactName/contactPhone 字段,seed 企业信息 - Settings 页面修复 orgData/usersData 取值路径错误 - Roster/Termination/Contracts mutation 增加 roster cache invalidation - 员工档案页面 tab 固定、内容区域滚动到窗口底部 - 解聘证据链显示逻辑修复(协商一致离职 vs 员工主动离职)
This commit is contained in:
+150
-12
@@ -1,6 +1,6 @@
|
||||
import { Router } from 'express'
|
||||
import { authMiddleware, AuthRequest } from '../middleware/auth'
|
||||
import { chat, chatStream, reviewContract, matchCase, predictRisks } from '../services/ai.service'
|
||||
import { chat, chatStream, reviewContract, matchCase, predictRisks, predictRisksStream } from '../services/ai.service'
|
||||
import { seedKnowledgeBase, addKnowledge, searchKnowledge, ensureRAGTable } from '../services/rag.service'
|
||||
import prisma from '../lib/prisma'
|
||||
import { z } from 'zod'
|
||||
@@ -48,6 +48,31 @@ async function recordUsage(orgId: string, userId: string, type: 'chat' | 'review
|
||||
})
|
||||
}
|
||||
|
||||
// 日期计算工具:计算两个日期之间的年月日差,以及相对当前的天数差
|
||||
function calcDuration(start: Date, end: Date): string {
|
||||
let years = end.getFullYear() - start.getFullYear()
|
||||
let months = end.getMonth() - start.getMonth()
|
||||
let days = end.getDate() - start.getDate()
|
||||
if (days < 0) {
|
||||
months--
|
||||
const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0)
|
||||
days += prevMonth.getDate()
|
||||
}
|
||||
if (months < 0) {
|
||||
years--
|
||||
months += 12
|
||||
}
|
||||
const parts: string[] = []
|
||||
if (years > 0) parts.push(`${years}年`)
|
||||
if (months > 0) parts.push(`${months}个月`)
|
||||
if (days > 0) parts.push(`${days}天`)
|
||||
return parts.length > 0 ? parts.join('') : '不足1天'
|
||||
}
|
||||
|
||||
function daysFromNow(date: Date): number {
|
||||
return Math.floor((date.getTime() - Date.now()) / (1000 * 60 * 60 * 24))
|
||||
}
|
||||
|
||||
async function buildOrgContext(orgId: string): Promise<string> {
|
||||
const [employees, risks] = await Promise.all([
|
||||
prisma.employee.findMany({
|
||||
@@ -63,14 +88,13 @@ async function buildOrgContext(orgId: string): Promise<string> {
|
||||
const now = new Date()
|
||||
const empSummary = employees.map((e) => {
|
||||
const contract = e.contracts[0]
|
||||
const daysToExpire = contract?.endDate
|
||||
? Math.floor((new Date(contract.endDate).getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
|
||||
: null
|
||||
const daysToExpire = contract?.endDate ? daysFromNow(new Date(contract.endDate)) : null
|
||||
const tenure = calcDuration(new Date(e.hireDate), now)
|
||||
const specialStatus: string[] = []
|
||||
if (e.isPregnant) specialStatus.push('孕期/哺乳期')
|
||||
if (e.isInMedicalPeriod) specialStatus.push('医疗期')
|
||||
if (e.isWorkInjured) specialStatus.push('工伤')
|
||||
return `- ${e.name}(${e.department}),入职${e.hireDate.toISOString().slice(0, 10)},${contract ? `合同:${contract.contractType},${contract.endDate ? `到期${contract.endDate.toISOString().slice(0, 10)}(剩余${daysToExpire}天)` : '无固定期限'}` : '未签合同'}${specialStatus.length > 0 ? `,特殊状态:${specialStatus.join('/')}` : ''}`
|
||||
return `- ${e.name}(${e.department}),入职${e.hireDate.toISOString().slice(0, 10)}(已工作${tenure}),${contract ? `合同:${contract.contractType},${contract.endDate ? `到期${contract.endDate.toISOString().slice(0, 10)}(剩余${daysToExpire}天)` : '无固定期限'}` : '未签合同'}${specialStatus.length > 0 ? `,特殊状态:${specialStatus.join('/')}` : ''}`
|
||||
}).join('\n')
|
||||
|
||||
const riskSummary = risks.map((r) => `- ${r.title}(${r.level}):${r.description || '无详细描述'}`).join('\n')
|
||||
@@ -199,27 +223,48 @@ router.get('/predict', authMiddleware, async (req: AuthRequest, res, next) => {
|
||||
const riskType = req.query.riskType as string
|
||||
|
||||
let orgContext = await buildOrgContext(req.user!.orgId)
|
||||
let scopeHint = ''
|
||||
|
||||
if (employeeId) {
|
||||
const emp = await prisma.employee.findFirst({ where: { id: employeeId, orgId: req.user!.orgId }, include: { contracts: { orderBy: { createdAt: 'desc' }, take: 1 } } })
|
||||
const emp = await prisma.employee.findFirst({ where: { id: employeeId, orgId: req.user!.orgId }, include: { contracts: { orderBy: { createdAt: 'desc' }, take: 1 }, terminations: { orderBy: { createdAt: 'desc' }, take: 1 } } })
|
||||
if (emp) {
|
||||
const contract = emp.contracts[0]
|
||||
orgContext = `员工详情:
|
||||
const term = emp.terminations[0]
|
||||
const statusMap: Record<string, string> = { DRAFT: '草稿', PENDING_APPROVAL: '待审批', APPROVED: '已审批', EXECUTING: '执行中', COMPLETED: '已完成', REJECTED: '已驳回', CANCELLED: '已撤销' }
|
||||
const typeMap: Record<string, string> = { RESIGNATION: '员工离职', TERMINATION: '公司解聘' }
|
||||
const reasonMap: Record<string, string> = { NEGOTIATED: '协商一致', FAULT: '员工过错', NONFAULT: '非过错解除', LAYOFF: '经济性裁员', EXPIRED: '合同到期', RESIGNATION: '员工主动离职' }
|
||||
const checklist = term?.checklist as any || {}
|
||||
const handoverItems = (term?.handoverItems as any[]) || []
|
||||
const handoverDone = handoverItems.length > 0 ? handoverItems.every((h: any) => h.done) : false
|
||||
const agreementSigned = !!checklist.agreement_signed
|
||||
const socialInsEnd = term?.socialInsEndMonth ? `,社保截止${term.socialInsEndMonth}` : ''
|
||||
const housingFundEnd = term?.housingFundEndMonth ? `,公积金截止${term.housingFundEndMonth}` : ''
|
||||
const tenure = calcDuration(new Date(emp.hireDate), term ? new Date(term.terminationDate) : new Date())
|
||||
const contractDaysLeft = contract?.endDate ? daysFromNow(new Date(contract.endDate)) : null
|
||||
orgContext = `当前日期:${new Date().toISOString().slice(0, 10)}
|
||||
员工详情:
|
||||
- 姓名:${emp.name}
|
||||
- 部门:${emp.department}
|
||||
- 入职日期:${emp.hireDate.toISOString().slice(0, 10)}
|
||||
- 入职日期:${emp.hireDate.toISOString().slice(0, 10)}(已工作${tenure})
|
||||
- 状态:${emp.status}
|
||||
- 特殊状态:${emp.isPregnant ? '孕期/哺乳期 ' : ''}${emp.isInMedicalPeriod ? '医疗期 ' : ''}${emp.isWorkInjured ? '工伤' : '无'}
|
||||
- 合同:${contract ? `${contract.contractType},${contract.startDate.toISOString().slice(0, 10)}至${contract.endDate ? contract.endDate.toISOString().slice(0, 10) : '无固定期限'}` : '未签合同'}\n${orgContext}`
|
||||
- 合同:${contract ? `${contract.contractType},${contract.startDate.toISOString().slice(0, 10)}至${contract.endDate ? contract.endDate.toISOString().slice(0, 10) : '无固定期限'}${contractDaysLeft !== null ? `(距到期${contractDaysLeft}天)` : ''}` : '未签合同'}${term ? `\n- 离职/解聘记录:${typeMap[term.type] || term.type},原因:${reasonMap[term.reason] || term.reason},离职日期:${term.terminationDate.toISOString().slice(0, 10)},流程状态:${statusMap[term.status] || term.status},经济补偿金:¥${term.compensation.toFixed(2)}${term.resignationReason ? `,离职原因说明:${term.resignationReason}` : ''}${socialInsEnd}${housingFundEnd},${handoverDone ? '工作交接已完成' : '工作交接未完成'},${agreementSigned ? '已签署解除协议' : '未签署解除协议'}` : ''}`
|
||||
scopeHint = `请只针对员工【${emp.name}】进行风险预测,不要分析其他员工。以上数据中的工龄、天数等均已由系统计算,请直接使用,不要重新计算。`
|
||||
}
|
||||
} else if (department) {
|
||||
const employees = await prisma.employee.findMany({ where: { orgId: req.user!.orgId, department, status: 'ACTIVE' }, include: { contracts: { orderBy: { createdAt: 'desc' }, take: 1 } } })
|
||||
const empSummary = employees.map(e => `- ${e.name},入职${e.hireDate.toISOString().slice(0, 10)},${e.contracts[0] ? e.contracts[0].contractType : '未签合同'}`).join('\n')
|
||||
orgContext = `部门【${department}】员工列表(${employees.length}人):\n${empSummary}\n\n${orgContext}`
|
||||
orgContext = `部门【${department}】员工列表(${employees.length}人):\n${empSummary}`
|
||||
scopeHint = `请只针对【${department}】部门的员工进行风险预测,不要分析其他部门的员工。`
|
||||
}
|
||||
|
||||
if (riskType && riskType !== 'all') {
|
||||
orgContext = `请重点关注【${riskType === 'contract' ? '合同' : riskType === 'salary' ? '薪酬' : riskType === 'termination' ? '解聘' : riskType}】类风险。\n\n${orgContext}`
|
||||
const riskLabel = riskType === 'contract' ? '合同' : riskType === 'salary' ? '薪酬' : riskType === 'termination' ? '解聘' : riskType
|
||||
scopeHint += `\n请重点关注【${riskLabel}】类风险,其他类型风险可简要提及。`
|
||||
}
|
||||
|
||||
if (scopeHint) {
|
||||
orgContext = `${scopeHint}\n\n${orgContext}`
|
||||
}
|
||||
|
||||
const result = await predictRisks(orgContext)
|
||||
@@ -229,12 +274,105 @@ router.get('/predict', authMiddleware, async (req: AuthRequest, res, next) => {
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/predict-stream', authMiddleware, async (req: AuthRequest, res, next) => {
|
||||
try {
|
||||
const department = req.query.department as string
|
||||
const employeeId = req.query.employeeId as string
|
||||
const riskType = req.query.riskType as string
|
||||
|
||||
let orgContext = await buildOrgContext(req.user!.orgId)
|
||||
let scopeHint = ''
|
||||
|
||||
if (employeeId) {
|
||||
const emp = await prisma.employee.findFirst({ where: { id: employeeId, orgId: req.user!.orgId }, include: { contracts: { orderBy: { createdAt: 'desc' }, take: 1 }, terminations: { orderBy: { createdAt: 'desc' }, take: 1 } } })
|
||||
if (emp) {
|
||||
const contract = emp.contracts[0]
|
||||
const term = emp.terminations[0]
|
||||
const statusMap: Record<string, string> = { DRAFT: '草稿', PENDING_APPROVAL: '待审批', APPROVED: '已审批', EXECUTING: '执行中', COMPLETED: '已完成', REJECTED: '已驳回', CANCELLED: '已撤销' }
|
||||
const typeMap: Record<string, string> = { RESIGNATION: '员工离职', TERMINATION: '公司解聘' }
|
||||
const reasonMap: Record<string, string> = { NEGOTIATED: '协商一致', FAULT: '员工过错', NONFAULT: '非过错解除', LAYOFF: '经济性裁员', EXPIRED: '合同到期', RESIGNATION: '员工主动离职' }
|
||||
const checklist = term?.checklist as any || {}
|
||||
const handoverItems = (term?.handoverItems as any[]) || []
|
||||
const handoverDone = handoverItems.length > 0 ? handoverItems.every((h: any) => h.done) : false
|
||||
const agreementSigned = !!checklist.agreement_signed
|
||||
const socialInsEnd = term?.socialInsEndMonth ? `,社保截止${term.socialInsEndMonth}` : ''
|
||||
const housingFundEnd = term?.housingFundEndMonth ? `,公积金截止${term.housingFundEndMonth}` : ''
|
||||
const tenure = calcDuration(new Date(emp.hireDate), term ? new Date(term.terminationDate) : new Date())
|
||||
const contractDaysLeft = contract?.endDate ? daysFromNow(new Date(contract.endDate)) : null
|
||||
orgContext = `当前日期:${new Date().toISOString().slice(0, 10)}
|
||||
员工详情:
|
||||
- 姓名:${emp.name}
|
||||
- 部门:${emp.department}
|
||||
- 入职日期:${emp.hireDate.toISOString().slice(0, 10)}(已工作${tenure})
|
||||
- 状态:${emp.status}
|
||||
- 特殊状态:${emp.isPregnant ? '孕期/哺乳期 ' : ''}${emp.isInMedicalPeriod ? '医疗期 ' : ''}${emp.isWorkInjured ? '工伤' : '无'}
|
||||
- 合同:${contract ? `${contract.contractType},${contract.startDate.toISOString().slice(0, 10)}至${contract.endDate ? contract.endDate.toISOString().slice(0, 10) : '无固定期限'}${contractDaysLeft !== null ? `(距到期${contractDaysLeft}天)` : ''}` : '未签合同'}${term ? `\n- 离职/解聘记录:${typeMap[term.type] || term.type},原因:${reasonMap[term.reason] || term.reason},离职日期:${term.terminationDate.toISOString().slice(0, 10)},流程状态:${statusMap[term.status] || term.status},经济补偿金:¥${term.compensation.toFixed(2)}${term.resignationReason ? `,离职原因说明:${term.resignationReason}` : ''}${socialInsEnd}${housingFundEnd},${handoverDone ? '工作交接已完成' : '工作交接未完成'},${agreementSigned ? '已签署解除协议' : '未签署解除协议'}` : ''}`
|
||||
scopeHint = `请只针对员工【${emp.name}】进行风险预测,不要分析其他员工。以上数据中的工龄、天数等均已由系统计算,请直接使用,不要重新计算。`
|
||||
}
|
||||
} else if (department) {
|
||||
const employees = await prisma.employee.findMany({ where: { orgId: req.user!.orgId, department, status: 'ACTIVE' }, include: { contracts: { orderBy: { createdAt: 'desc' }, take: 1 } } })
|
||||
const empSummary = employees.map(e => `- ${e.name},入职${e.hireDate.toISOString().slice(0, 10)},${e.contracts[0] ? e.contracts[0].contractType : '未签合同'}`).join('\n')
|
||||
orgContext = `部门【${department}】员工列表(${employees.length}人):\n${empSummary}`
|
||||
scopeHint = `请只针对【${department}】部门的员工进行风险预测,不要分析其他部门的员工。`
|
||||
}
|
||||
|
||||
if (riskType && riskType !== 'all') {
|
||||
const riskLabel = riskType === 'contract' ? '合同' : riskType === 'salary' ? '薪酬' : riskType === 'termination' ? '解聘' : riskType
|
||||
scopeHint += `\n请重点关注【${riskLabel}】类风险,其他类型风险可简要提及。`
|
||||
}
|
||||
|
||||
if (scopeHint) {
|
||||
orgContext = `${scopeHint}\n\n${orgContext}`
|
||||
}
|
||||
|
||||
await checkUsageLimit(req.user!.orgId, 'chat')
|
||||
res.setHeader('Content-Type', 'text/event-stream')
|
||||
res.setHeader('Cache-Control', 'no-cache')
|
||||
res.setHeader('Connection', 'keep-alive')
|
||||
res.setHeader('X-Accel-Buffering', 'no')
|
||||
res.flushHeaders()
|
||||
|
||||
let usageRecorded = false
|
||||
try {
|
||||
for await (const delta of predictRisksStream(orgContext)) {
|
||||
res.write(`data: ${JSON.stringify({ delta })}\n\n`)
|
||||
if (typeof (res as any).flush === 'function') (res as any).flush()
|
||||
}
|
||||
res.write('data: [DONE]\n\n')
|
||||
} catch (streamErr: any) {
|
||||
res.write(`data: ${JSON.stringify({ error: streamErr.message || 'AI 服务异常' })}\n\n`)
|
||||
res.write('data: [DONE]\n\n')
|
||||
} finally {
|
||||
if (!usageRecorded) {
|
||||
await recordUsage(req.user!.orgId, req.user!.id, 'chat')
|
||||
usageRecorded = true
|
||||
}
|
||||
}
|
||||
res.end()
|
||||
} catch (err) {
|
||||
if (!res.headersSent) next(err)
|
||||
else res.end()
|
||||
}
|
||||
})
|
||||
|
||||
// ========== AI 会话历史 ==========
|
||||
|
||||
router.get('/conversations', authMiddleware, async (req: AuthRequest, res, next) => {
|
||||
try {
|
||||
const type = req.query.type as string | undefined
|
||||
const where: any = { orgId: req.user!.orgId, userId: req.user!.id }
|
||||
if (type) {
|
||||
const prefixes: Record<string, string> = {
|
||||
chat: 'chat:',
|
||||
predict: 'predict:',
|
||||
review: 'review:',
|
||||
case: 'case:',
|
||||
}
|
||||
const prefix = prefixes[type] || type
|
||||
where.title = { startsWith: prefix }
|
||||
}
|
||||
const conversations = await prisma.aIConversation.findMany({
|
||||
where: { orgId: req.user!.orgId, userId: req.user!.id },
|
||||
where,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 50,
|
||||
select: { id: true, title: true, createdAt: true, updatedAt: true },
|
||||
|
||||
Reference in New Issue
Block a user