Load salary details by role with independent data sources

This commit is contained in:
江林铖 2026-11-26 11:23:11 +08:00
parent 7048ce993b
commit 36cd111f52
18 changed files with 1020 additions and 224 deletions

View File

@ -45,3 +45,34 @@ test('历史快照未补齐时返回可重试503且不缓存或返回部分积
expect(response.headers.get('cache-control')).toContain('no-store')
expect(await response.json()).toEqual({ error: '流程积分正在同步,请稍后重新加载。', code: 'WORKFLOW_POINTS_SYNCING' })
})
test('流式接口先发送基础快照,中途分项更新,最后完成;响应禁止缓存和代理缓冲', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
let finish!: () => void
details.mockImplementation(async (_id, _month, { onProgress }) => {
onProgress({ scope: { phase: 'base' } })
await new Promise<void>(resolve => { finish = resolve })
onProgress({ scope: { phase: 'partial' } })
return { scope: { phase: 'full' } }
})
const streamRequest = new NextRequest(`${request().url}&role=management`, { headers: { Accept: 'application/x-ndjson' } })
const response = await GET(streamRequest)
expect(response.headers.get('content-type')).toContain('application/x-ndjson')
expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(response.headers.get('x-accel-buffering')).toBe('no')
const reader = response.body!.getReader()
const nextPhase = async () => JSON.parse(new TextDecoder().decode((await reader.read()).value)).data.scope.phase
expect(await nextPhase()).toBe('base')
finish()
expect(await nextPhase()).toBe('partial')
expect(await nextPhase()).toBe('full')
expect((await reader.read()).done).toBe(true)
})
test('非法岗位和无权限不会打开薪资响应流', async () => {
const streamRequest = new NextRequest(`${request().url}&role=invalid`, { headers: { Accept: 'application/x-ndjson' } })
expect((await GET(streamRequest)).status).toBe(403)
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
expect((await GET(streamRequest)).status).toBe(400)
expect(details).not.toHaveBeenCalled()
})

View File

@ -1,11 +1,57 @@
import { NextRequest } from 'next/server'
import { salaryIdentity, salaryJson, salaryFailure } from '@/lib/personnel-salary-http'
import { salaryIdentity, salaryJson, salaryFailure, salaryHeaders } from '@/lib/personnel-salary-http'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { SALARY_STREAM_TYPE, type SalaryStreamEvent } from '@/lib/performance-salary-details-contract'
import type { SalaryRole } from '@/lib/performance-salary-roles'
import { SalaryError } from '@/lib/personnel-salary'
import { salaryRoleSchema } from '@/lib/salary-position-contract'
export const dynamic = 'force-dynamic'
function streamDetails(request: NextRequest, userId: string, month: string | null, role: SalaryRole) {
const encoder = new TextEncoder()
const disconnected = new AbortController()
const signal = AbortSignal.any([request.signal, disconnected.signal])
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (event: SalaryStreamEvent) => {
if (!signal.aborted) controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`))
}
try {
const data = await getPerformanceSalaryDetails(userId, month, {
role, phase: 'full', signal, onProgress: data => send({ data }),
})
send({ data })
} catch (error) {
const failure = salaryFailure(error)
const body = await failure.json()
send({ error: body.error, status: failure.status })
} finally {
if (!disconnected.signal.aborted) controller.close()
}
},
cancel() { disconnected.abort() },
})
return new Response(stream, { headers: {
...salaryHeaders, Vary: `${salaryHeaders.Vary}, Accept`, 'Content-Type': `${SALARY_STREAM_TYPE}; charset=utf-8`, 'X-Accel-Buffering': 'no',
} })
}
export async function GET(request: NextRequest) {
try {
const userId = await salaryIdentity()
return salaryJson(await getPerformanceSalaryDetails(userId, request.nextUrl.searchParams.get('month')))
const { searchParams } = request.nextUrl
const month = searchParams.get('month')
const role = searchParams.get('role')
const phase = searchParams.get('phase')
if (role === null && phase === null) return salaryJson(await getPerformanceSalaryDetails(userId, month))
const parsed = salaryRoleSchema.safeParse(role)
if (!parsed.success || (phase !== null && phase !== 'base' && phase !== 'full')) {
throw new SalaryError('请选择有效薪资岗位及查询阶段。', 400, 'INVALID_SALARY_DETAILS_SCOPE')
}
if (phase !== 'base' && request.headers.get('accept') === SALARY_STREAM_TYPE) {
return streamDetails(request, userId, month, parsed.data)
}
return salaryJson(await getPerformanceSalaryDetails(userId, month, { role: parsed.data, phase: phase ?? 'full' }))
} catch (error) { return salaryFailure(error) }
}

View File

@ -363,3 +363,68 @@ test('主管部门交付率复用原始值明细按钮,展开聚焦标题,
fireEvent.click(screen.getByRole('button', { name: '收起明细' }))
expect(trigger).toHaveFocus(); expect(trigger).toHaveAttribute('aria-expanded', 'false')
})
test('分项加载时人员工资先出现,来源失败可在保留已读数据的情况下重试', async () => {
const market = position.dimensions[1].metrics[0]
const survey = position.dimensions[0].metrics[0]
const scoped = (phase: 'base' | 'partial' | 'full', marketStatus: 'pending' | 'failed' | 'ready') => {
const data = payload()
const row = data.roles['ai-planning'][0]
const context = { salaryMonth: '2026-10', sourceMonth: '2026-09', source: 'market-intent-top3' as const }
data.scope = { role: 'ai-planning', phase, sources: phase === 'base' ? [] : [
{ ...context, source: 'survey', sourceMonth: '2026-10', status: 'ready' },
marketStatus === 'failed'
? { ...context, status: marketStatus, code: 'MARKET_INTENT_UNAVAILABLE', message: '经营数据暂时无法读取。' }
: { ...context, status: marketStatus },
] }
if (phase !== 'base') row.values[`${survey.id}RawValue`] = 92.5
if (marketStatus === 'ready') {
row.values[`${market.id}RawValue`] = 108.74
row.values.currentTotal = '2000.00'
}
return data
}
const { TextEncoder, TextDecoder } = await import('node:util')
const originalDecoder = globalThis.TextDecoder
Object.assign(globalThis, { TextDecoder })
const encoder = new TextEncoder()
let receive!: (result: { done: boolean; value?: Uint8Array }) => void
const read = jest.fn(() => new Promise(resolve => { receive = resolve }))
const stream = { ok: true, headers: { get: () => 'application/x-ndjson' }, body: { getReader: () => ({ read, cancel: async () => {}, releaseLock: () => {} }) } }
const emit = (data: SalaryDetails) => receive({ done: false, value: encoder.encode(JSON.stringify({ data }) + '\n') })
const fetchMock = fetch as jest.Mock
fetchMock.mockResolvedValueOnce(stream).mockResolvedValueOnce(stream)
try {
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
await waitFor(() => expect(read).toHaveBeenCalledTimes(1))
emit(scoped('base', 'pending'))
expect(await screen.findByText('1000.01')).toBeInTheDocument()
expect(screen.getAllByText('加载中').length).toBeGreaterThan(1)
emit(scoped('partial', 'pending'))
expect(await screen.findByText('92.50 分')).toBeInTheDocument()
emit(scoped('full', 'failed'))
expect(await screen.findByRole('alert')).toHaveTextContent('市场验证')
expect(screen.getAllByText('读取失败')).toHaveLength(2)
expect(screen.getByText('92.50 分')).toBeInTheDocument()
receive({ done: true })
const retry = screen.getByRole('button', { name: '重试计算' })
retry.focus()
fireEvent.click(retry)
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
expect(screen.getByText('1000.01')).toBeInTheDocument()
expect(screen.getByText('92.50 分')).toBeInTheDocument()
emit(scoped('base', 'pending'))
await waitFor(() => expect(read).toHaveBeenCalledTimes(6))
expect(screen.getByText('92.50 分')).toBeInTheDocument()
emit(scoped('full', 'ready'))
expect(await screen.findByText('2000.00')).toBeInTheDocument()
expect(screen.getByText('108.74 分')).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByText('薪资明细已更新。')).toHaveFocus()
receive({ done: true })
} finally {
Object.assign(globalThis, { TextDecoder: originalDecoder })
}
})

View File

@ -2,13 +2,40 @@
import { useEffect, useRef, useState } from 'react'
import type { SalaryRole } from '@/lib/performance-salary-roles'
import { SALARY_TEMPLATE_BLANK_ROWS, type SalaryTemplateColumn } from '@/lib/performance-salary-templates'
import { salarySourceLabel, type SalaryDetails, type SalaryCell } from '@/lib/performance-salary-details-contract'
import { previousSalaryMonth, SALARY_TEMPLATE_BLANK_ROWS, salaryMonthLabel, type SalaryTemplateColumn } from '@/lib/performance-salary-templates'
import { SALARY_STREAM_TYPE, salarySourceLabel, type SalaryDetails, type SalaryCell, type SalaryStreamEvent, type SalaryDataSource } from '@/lib/performance-salary-details-contract'
import PerformanceSalaryToolbar from './PerformanceSalaryToolbar'
import SalaryMarketIntentDetails from './SalaryMarketIntentDetails'
import SalaryDepartmentDeliveryDetails from './SalaryDepartmentDeliveryDetails'
import { percentageBasisPoints } from '@/lib/salary-position-contract'
const sourceNames: Record<SalaryDataSource, string> = {
survey: '绩效调研', 'on-time': '按时交付率', 'market-intent-top3': '市场验证', points: '积分',
}
const settlementColumns = new Set(['performanceCoefficient', 'currentTotal', 'previousTotal', 'salaryDifference'])
type QueryResult = { attempt: number; data?: SalaryDetails; done?: boolean; error?: string }
async function readSalaryStream(response: Response, receive: (event: SalaryStreamEvent) => void) {
if (!response.body) throw new Error('薪资明细读取失败,请重试。')
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
try {
for (;;) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() ?? ''
for (const line of lines) if (line) receive(JSON.parse(line))
}
if (buffer) receive(JSON.parse(buffer + decoder.decode()))
} finally {
await reader.cancel().catch(() => undefined)
reader.releaseLock()
}
}
function formatCell(value: SalaryCell | undefined, column: SalaryTemplateColumn) {
if (value === null || value === undefined || value === '') return '——'
if (typeof value === 'string') return value
@ -18,45 +45,116 @@ function formatCell(value: SalaryCell | undefined, column: SalaryTemplateColumn)
return `${value.toLocaleString('zh-CN', { maximumFractionDigits: 2, minimumFractionDigits: column.kind === 'money' ? 2 : 0 })}${column.kind === 'percent' ? '%' : ''}`
}
export default function PerformanceSalaryDetails({ role, month }: { role: SalaryRole; month: string }) {
const [result, setResult] = useState<{ month: string; data?: SalaryDetails; error?: string } | null>(null)
export default function PerformanceSalaryDetails(props: { role: SalaryRole; month: string }) {
return <SalaryDetailsView key={`${props.role}:${props.month}`} {...props} />
}
function SalaryDetailsView({ role, month }: { role: SalaryRole; month: string }) {
const [result, setResult] = useState<QueryResult>({ attempt: 0 })
const [retry, setRetry] = useState(0)
const [expanded, setExpanded] = useState<{ employeeId: string; metricId: string } | null>(null)
const detailTrigger = useRef<HTMLButtonElement | null>(null)
const retryTrigger = useRef<HTMLButtonElement | null>(null)
const statusRegion = useRef<HTMLParagraphElement | null>(null)
const restoreRetryFocus = useRef(false)
useEffect(() => {
const controller = new AbortController()
setResult(null)
setExpanded(null)
let done = false
function receive(event: SalaryStreamEvent, streamed = true) {
if (controller.signal.aborted) return
if ('error' in event) {
done = true
setResult(previous => ({
attempt: retry, done, error: event.error,
data: event.status === 401 || event.status === 403 ? undefined : previous.data,
}))
return
}
const data = event.data
if (data.displayMonth !== month || !Array.isArray(data.roles?.[role]) || !Array.isArray(data.positionGroups)
|| (streamed && !data.scope) || (data.scope && (data.scope.role !== role || !Array.isArray(data.scope.sources)))) {
throw new Error('返回的薪资月份或岗位不一致,请重试。')
}
done = !data.scope || data.scope.phase === 'full'
const complete = done
setResult(previous => ({
attempt: retry, done: complete,
data: retry && !complete ? previous.data ?? data : data,
}))
}
async function load() {
try {
const response = await fetch(`/api/organization/performance-salary/details?${new URLSearchParams({ month })}`, { cache: 'no-store', signal: controller.signal })
const body = await response.json()
if (!response.ok) throw new Error(body.error || '薪资明细读取失败,请重试。')
if (body.displayMonth !== month || !body.roles || !Array.isArray(body.positionGroups)) throw new Error('返回的薪资月份或配置不一致,请重试。')
if (!controller.signal.aborted) setResult({ month, data: body })
const response = await fetch(`/api/organization/performance-salary/details?${new URLSearchParams({ month, role })}`, {
cache: 'no-store', signal: controller.signal, headers: { Accept: SALARY_STREAM_TYPE },
})
if (!response.ok) {
const body = await response.json().catch(() => ({}))
receive({ error: body.error || '薪资明细读取失败,请重试。', status: response.status })
} else if (response.headers?.get('content-type')?.startsWith(SALARY_STREAM_TYPE)) {
await readSalaryStream(response, receive)
if (!done) throw new Error('薪资明细连接已中断,请重试。')
} else {
receive({ data: await response.json() }, false)
}
} catch (error) {
if (!controller.signal.aborted) setResult({ month, error: error instanceof Error ? error.message : '薪资明细读取失败,请重试。' })
receive({ error: error instanceof Error ? error.message : '薪资明细读取失败,请重试。', status: 500 })
}
}
void load()
return () => controller.abort()
}, [month, role, retry])
const current = result?.month === month ? result : null
const data = current?.data
const data = result.data
const loading = result.attempt !== retry || !result.done
const error = result.attempt === retry ? result.error : undefined
const activeDetails = expanded
const statuses = data?.scope?.sources ?? []
const failures = statuses.filter(source => source.status === 'failed')
const failureGroups = new Map<string, { label: string; message: string; months: string[] }>()
for (const failure of failures) {
const key = `${failure.source}:${failure.message}`
const group = failureGroups.get(key) ?? { label: sourceNames[failure.source], message: failure.message, months: [] }
group.months.push(salaryMonthLabel(failure.salaryMonth))
failureGroups.set(key, group)
}
const currentSources = new Map(statuses.filter(source => source.salaryMonth === month).map(source => [source.source, source.status]))
const previousSources = new Map(statuses.filter(source => source.salaryMonth === previousSalaryMonth(month)).map(source => [source.source, source.status]))
const retrying = retry > 0 && loading
const retryLoad = () => {
if (retrying) return
restoreRetryFocus.current = document.activeElement === retryTrigger.current
setRetry(value => value + 1)
}
useEffect(() => {
if (!retry || loading || error || failures.length || !restoreRetryFocus.current) return
restoreRetryFocus.current = false
if (document.activeElement === document.body) statusRegion.current?.focus()
}, [retry, loading, error, failures.length])
const rows = data?.roles[role] ?? []
const groups = data?.positionGroups.filter(group => group.position.salaryRole === role) ?? []
const visibleGroups = groups.filter(group => group.rows.length > 0 || role === 'management' || role === 'ai-technical')
const surveyMatchIssues = data?.surveyMatchIssues?.filter(issue => issue.salaryRole === role) ?? []
return (
<>
<PerformanceSalaryToolbar role={role} month={month} sourceLabel={data ? salarySourceLabel(data) : undefined} />
<div className="min-w-0 px-5 py-5 sm:px-6" aria-busy={!current}>
{!current ? <p role="status" className="py-10 text-sm text-[#66758b]">正在读取薪资明细…</p> : current.error ? (
<div className="py-8">
<p role="alert" className="text-sm leading-6 text-[#b42318]">{current.error}</p>
<button type="button" onClick={() => setRetry(value => value + 1)} className="mt-3 min-h-11 rounded-lg border border-[#cfd8e3] px-4 text-sm font-semibold text-[#344054] hover:bg-[#f8fafc] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">重新加载</button>
<PerformanceSalaryToolbar role={role} month={month} sourceLabel={data && data.scope?.phase !== 'base' ? salarySourceLabel(data) : `薪资月份:${salaryMonthLabel(month)}`} />
<div className="min-w-0 px-5 py-5 sm:px-6">
<p ref={statusRegion} role={loading || retry ? 'status' : undefined} tabIndex={-1}
className={loading ? `text-sm leading-6 text-[#66758b] ${data ? 'mb-3' : 'py-10'}` : 'sr-only focus:not-sr-only focus:mb-3 focus:text-sm focus:text-[#344054]'}>
{loading ? retrying ? '正在重试考核及薪资计算…' : data ? '正在读取考核及薪资计算结果…' : '正在读取薪资明细…'
: retry && !error && !failures.length ? '薪资明细已更新。' : ''}
</p>
{(error || failures.length > 0 || retrying) && (
<div className="mb-4 rounded-lg border border-[#e2e8f0] px-4 py-3 text-sm leading-6">
{(error || failures.length > 0) && <div role="alert" className="text-[#b42318]">
{error ? <p>{error}</p> : <ul className="space-y-1">{Array.from(failureGroups, ([key, group]) => (
<li key={key}>{group.months.join('、')}薪资 · {group.label}:{group.message}</li>
))}</ul>}
</div>}
<button ref={retryTrigger} type="button" onClick={retryLoad} aria-disabled={retrying}
className="mt-2 min-h-11 max-w-full rounded-lg border border-[#cfd8e3] px-4 text-sm font-semibold text-[#344054] hover:bg-[#f8fafc] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6] aria-disabled:opacity-60">{retrying ? '正在重试…' : failures.length ? '重试计算' : '重新加载'}</button>
</div>
) : rows.length === 0 && visibleGroups.length === 0 ? (
)}
{data && (rows.length === 0 && visibleGroups.length === 0 ? (
<div className="py-10 text-center">
<h2 className="font-semibold text-[#344054]">暂无薪资明细</h2>
<p className="mt-2 text-sm leading-6 text-[#66758b]">所选入口暂无已配置岗位的人员薪资档案。</p>
@ -71,14 +169,23 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
<p className="mt-1 text-[#66758b]">以下人员的调研得分暂留空,请核对人员薪资档案与绩效考核中的姓名、花名及人员关联。</p>
<ul className="mt-2 space-y-1">{surveyMatchIssues.map(issue => <li key={issue.employeeProfileId} className="break-words">{issue.employeeLabel}:{issue.message}</li>)}</ul>
</section>}
<p id="salary-table-help" className="mb-3 text-sm leading-6 text-[#66758b]">调研得分取同月绩效考核的两位小数正式得分。考核得分=原始指标分×综合占比,逐项保留两位小数后相加为绩效得分。绩效系数=绩效得分÷100,四舍五入保留两位小数;当月总薪资=基本工资+职级工资+绩效工资×绩效系数。上月总薪资按最新档案和配置重新计算,环比上月薪资差值=本月总薪资−上月总薪资;任一月份薪资缺失时差值显示“——”。左右滚动查看完整字段;正占比指标缺失时系数及总薪资显示“——”,导出仅包含空白模板。</p>
{role === 'management' && <p className="mb-3 text-sm leading-6 text-[#66758b]">主管市场验证取本部门策划成员上月完结流程的最高3条有效环比均值;按时交付率取本部门当月有有效流程成员的个人比例均值。均仅统计组织架构主部门直属在职成员,点击原始值查看计算明细。</p>}
<details className="mb-3 text-sm leading-6 text-[#66758b]">
<summary className="min-h-11 cursor-pointer py-2.5 font-semibold text-[#344054] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">薪资计算说明</summary>
<p className="mb-2">调研得分取同月绩效考核的两位小数正式得分。考核得分=原始指标分×综合占比,逐项保留两位小数后相加为绩效得分。绩效系数=绩效得分÷100,四舍五入保留两位小数;当月总薪资=基本工资+职级工资+绩效工资×绩效系数。上月总薪资按最新档案和配置重新计算,环比上月薪资差值=本月总薪资−上月总薪资;任一月份薪资缺失时差值显示“——”。正占比指标缺失时系数及总薪资显示“——”,导出仅包含空白模板。</p>
{role === 'management' && <p className="mb-2">主管市场验证取本部门策划成员上月完结流程的最高3条有效环比均值;按时交付率取本部门当月有有效流程成员的个人比例均值。均仅统计组织架构主部门直属在职成员,点击原始值查看计算明细。</p>}
</details>
<p id="salary-table-help" className="mb-3 text-xs leading-5 text-[#66758b]">左右滚动查看完整字段。</p>
{visibleGroups.map(({ position, template, rows }) => {
const activeRow = rows.find(row => row.employeeProfileId === expanded?.employeeId)
const activeDimension = position.dimensions.find(dimension => dimension.metrics.some(metric => metric.id === expanded?.metricId))
const activeMetric = activeDimension?.metrics.find(metric => metric.id === expanded?.metricId)
const activeEvidence = expanded && activeRow?.metricEvidence?.[expanded.metricId]
const activeRow = rows.find(row => row.employeeProfileId === activeDetails?.employeeId)
const activeDimension = position.dimensions.find(dimension => dimension.metrics.some(metric => metric.id === activeDetails?.metricId))
const activeMetric = activeDimension?.metrics.find(metric => metric.id === activeDetails?.metricId)
const activeEvidence = activeDetails && activeRow?.metricEvidence?.[activeDetails.metricId]
const metricSources = new Map(position.dimensions.flatMap(dimension => dimension.metrics.map(metric => [metric.id, metric.source.kind] as const)))
const detailId = `metric-details-${position.id}`
const hasPendingMetric = (sources: typeof currentSources) => Array.from(metricSources.values()).some(source =>
source !== 'unavailable' && sources.get(source) === 'pending')
const currentPending = hasPendingMetric(currentSources)
const previousPending = hasPendingMetric(previousSources)
return <section key={position.id} className="mb-8" aria-label={`${position.name}薪资明细`}>
<div className="mb-3 flex flex-wrap items-baseline gap-x-3 gap-y-1"><h2 className="text-lg font-bold text-[#101828]">{position.name}</h2><span className="text-sm text-[#66758b]">{rows.length}人 · 配置版本{position.revision} · 最新配置适用于所有月份</span></div>
{rows.length === 0 && <p className="mb-3 text-sm leading-6 text-[#66758b]">{role === 'ai-technical' ? '暂无AI技术设计师岗人员,请在人员薪资配置中新增' : '暂无管理岗人员,请在人员薪资配置中新增'}</p>}
@ -103,16 +210,32 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
))}</tr>
</thead>
<tbody>{rows.map(row => (
<tr key={row.employeeProfileId}>{template.columns.map((column, index) => (
<tr key={row.employeeProfileId}>{template.columns.map((column, index) => {
const metricId = column.key.endsWith('RawValue') ? column.key.slice(0, -8)
: column.key.endsWith('Score') ? column.key.slice(0, -5) : undefined
const source = column.key === 'points' ? 'points' : metricId ? metricSources.get(metricId) : undefined
const availableSource = source !== 'unavailable' ? source : undefined
const value = row.values[column.key]
const salaryPending = settlementColumns.has(column.key) && position.dimensions.length > 0 && (
(column.key !== 'previousTotal' && currentPending) ||
(column.key !== 'currentTotal' && column.key !== 'performanceCoefficient' && previousPending)
)
const waiting = data.scope?.phase === 'base' && (availableSource || (settlementColumns.has(column.key) && position.dimensions.length > 0))
|| (availableSource && currentSources.get(availableSource) === 'pending')
|| (value == null && salaryPending)
const failed = availableSource && currentSources.get(availableSource) === 'failed'
return (
<td key={column.key} className={`h-14 border-b border-r border-[#e2e8f0] bg-white px-3 py-3 text-center tabular-nums ${index === 0 ? 'sticky left-0 z-10 font-semibold' : ''}`}>
{column.key.endsWith('RawValue') && row.metricEvidence?.[column.key.slice(0, -8)] ? <button type="button"
aria-label={`${row.employeeLabel}${row.metricEvidence[column.key.slice(0, -8)].kind === 'department-on-time-average' ? '部门按时交付率' : '市场验证'}计算明细`} aria-expanded={expanded?.employeeId === row.employeeProfileId && expanded.metricId === column.key.slice(0, -8)} aria-controls={detailId}
{waiting && loading ? <span className="text-xs text-[#66758b]">加载中</span>
: failed ? <span className="text-xs text-[#b42318]">读取失败</span>
: column.key.endsWith('RawValue') && row.metricEvidence?.[column.key.slice(0, -8)] ? <button type="button"
aria-label={`${row.employeeLabel}${row.metricEvidence[column.key.slice(0, -8)].kind === 'department-on-time-average' ? '部门按时交付率' : '市场验证'}计算明细`} aria-expanded={activeDetails?.employeeId === row.employeeProfileId && activeDetails.metricId === column.key.slice(0, -8)} aria-controls={detailId}
className="inline-flex min-h-11 min-w-11 items-center justify-center rounded px-2 font-semibold text-[#0050cb] underline underline-offset-4 hover:bg-[#e6edf5] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]"
onClick={event => { detailTrigger.current = event.currentTarget; setExpanded({ employeeId: row.employeeProfileId, metricId: column.key.slice(0, -8) }) }}>
{formatCell(row.values[column.key], column)}
</button> : index === 0 && !row.hasSalaryBase ? <><span>{row.employeeLabel}</span><span className="mt-1 block text-xs font-normal leading-5 text-[#66758b]">薪资档案未配置</span></> : formatCell(row.values[column.key], column)}
</td>
))}</tr>
)})}</tr>
))}{rows.length === 0 && Array.from({ length: SALARY_TEMPLATE_BLANK_ROWS }, (_, rowIndex) => (
<tr key={`blank-${rowIndex}`}>{template.columns.map((column, index) => (
<td key={column.key} className={`h-14 border-b border-r border-[#e2e8f0] bg-white px-3 py-3 ${index === 0 ? 'sticky left-0 z-10' : ''}`} />
@ -128,7 +251,7 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
contribution={typeof activeRow.values[`${activeMetric.id}Score`] === 'number' ? activeRow.values[`${activeMetric.id}Score`] as number : null}
close={() => { setExpanded(null); detailTrigger.current?.focus() }} />)}
</section>})}
</>}
</>)}
</div>
</>
)

View File

@ -144,4 +144,33 @@ describe('source-isolated performance conversion reads', () => {
expect(localRows).not.toHaveBeenCalled()
expect(mockSql.__pool.connect).not.toHaveBeenCalled()
})
it('reads sync metadata once per batch and exposes only affected window failures', async () => {
const original = await workflow()
const make = (key: string, product: string) => performanceConversionWorkflowItems({
...original, processInstanceId: key, formFields: { productId: product, platform: '天猫' },
})[0]
const good = make('good', '1000000000001'), failed = make('failed', '1000000000002')
localRows.mockImplementation(async ({ where }) => {
if (where.productId === failed.productId) throw Error('source offline')
return [metricRow({ productId: good.productId, metricDate: new Date('2026-10-01T00:00:00Z') })]
})
const onWindowFailure = jest.fn()
const result = await readPerformanceConversionWindows([good, failed], { intentWindowOnly: true, onWindowFailure })
expect(state).toHaveBeenCalledTimes(1)
expect(onWindowFailure).toHaveBeenCalledWith([failed.key])
expect(onWindowFailure).toHaveBeenCalledTimes(1)
expect(result.get(good.key)?.sourceDaily).toHaveLength(1)
expect(mockSql.__pool.connect).not.toHaveBeenCalled()
})
it('disconnected readers stop before starting any operating data queries', async () => {
const original = await workflow()
const item = performanceConversionWorkflowItems(original)[0]
const controller = new AbortController()
controller.abort()
await expect(readPerformanceConversionWindows([item], { signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError' })
expect(state).not.toHaveBeenCalled()
expect(localRows).not.toHaveBeenCalled()
})
})

View File

@ -3,22 +3,23 @@ import { Prisma } from '@prisma/client'
import { prisma } from '../prisma'
import { requireSalaryAccess } from '../personnel-salary'
import { getPerformanceSalaryDetails } from '../performance-salary-details'
import type { ArtPointPerson } from '../art-workflow-points'
import { readSalaryWorkflowMetrics } from '../performance-salary-workflows'
import { readSalaryMarketIntent } from '../salary-market-intent'
import { readSalaryMarketIntent, readSalaryMarketIntentBatch } from '../salary-market-intent'
import { readSalaryWorkflowSnapshots } from '../salary-workflow-source'
import { INITIAL_SALARY_POSITIONS } from '../salary-position-seeds'
import { summarizeMarketIntent, type MarketIntentCandidate } from '../salary-market-intent-contract'
jest.mock('../prisma', () => ({ prisma: { $transaction: jest.fn(), organizationUnit: { findMany: jest.fn() }, salaryPositionConfig: { findMany: jest.fn() }, performanceSurveyEmployeeProfile: { findMany: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, performanceSurveyResponse: { count: jest.fn(), findMany: jest.fn() } } }))
jest.mock('../salary-workflow-source', () => ({ readSalaryWorkflowSnapshots: jest.fn().mockResolvedValue([]) }))
jest.mock('../personnel-salary', () => ({ requireSalaryAccess: jest.fn() }))
jest.mock('../personnel-salary', () => ({ ...jest.requireActual('../personnel-salary'), requireSalaryAccess: jest.fn() }))
jest.mock('../performance-salary-workflows', () => {
const readSalaryWorkflowMetrics = jest.fn()
return { readSalaryWorkflowMetrics, readSalaryWorkflowMetricsBatch: async (months: string[], people: import('../art-workflow-points').ArtPointPerson[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryWorkflowMetrics(month, people)] as const))) }
})
jest.mock('../salary-market-intent', () => {
const readSalaryMarketIntent = jest.fn()
return { readSalaryMarketIntent, readSalaryMarketIntentBatch: async (months: string[], people: import('../art-workflow-points').ArtPointPerson[], ids: string[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryMarketIntent(month, people, ids)] as const))) }
return { readSalaryMarketIntent, readSalaryMarketIntentBatch: jest.fn() }
})
const db = prisma as unknown as Record<string, any>
const workflow = readSalaryWorkflowMetrics as jest.Mock
@ -28,6 +29,7 @@ const oldEnv = process.env.NODE_ENV
const positions = () => INITIAL_SALARY_POSITIONS.map((item, index) => ({ ...JSON.parse(JSON.stringify(item.value)), id: `job${index}`, revision: 1, updatedAt: new Date(), createdAt: new Date(), deletedAt: null }))
beforeEach(() => {
jest.resetAllMocks()
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementation(async (months: string[], people: ArtPointPerson[], ids: string[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryMarketIntent(month, people, ids)] as const))))
;(readSalaryWorkflowSnapshots as jest.Mock).mockResolvedValue([])
Object.assign(process.env, { NODE_ENV: 'development', PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK: 'false' })
db.$transaction.mockImplementation((work: any) => work(prisma))
@ -311,3 +313,81 @@ test('主管组织归属不明时部门指标留空并提示,不能使用薪
expect(data.roles.management[0].values[`${jobs[0].dimensions[1].metrics[1].id}RawValue`]).toBeNull()
expect(data.departmentMatchIssues).toEqual([expect.objectContaining({ employeeProfileId: 'p1', message: expect.stringContaining('主部门') })])
})
test('当前岗位基础阶段仅查询人员和岗位快照,不等待调研、流程、经营或组织读取', async () => {
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'base' })
expect(data.scope).toEqual({ role: 'ai-planning', phase: 'base', sources: [] })
expect(data.roles['ai-planning'][0].values.baseSalary).toBe('100.01')
expect(db.salaryPositionConfig.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { deletedAt: null, salaryRole: 'ai-planning' } }))
expect(db.performanceSurveyEmployeeProfile.findMany).not.toHaveBeenCalled()
expect(db.organizationUnit.findMany).not.toHaveBeenCalled()
expect(db.performanceSurveyResponse.findMany).not.toHaveBeenCalled()
expect(db.performanceSurveyResponse.count).not.toHaveBeenCalled()
expect(readSalaryWorkflowSnapshots).not.toHaveBeenCalled()
})
test.each(['ai-technical', 'photography', 'spatial-visual'] as const)('%s只启用正权重来源,不读其他岗位积分或经营数据', async role => {
const job = singleMetricPosition(role)
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role, phase: 'full' })
expect(data.roles[role][0].values).toMatchObject({ currentTotal: '147.01', previousTotal: '147.01', points: null })
expect(data.scope?.sources.map(item => item.source)).toEqual(['survey', 'survey'])
expect(db.performanceSurveyResponse.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({
target: { employeeProfileId: { in: ['p1'] } },
survey: expect.objectContaining({ templateCode: { in: ['visual_brand_tone'] } }),
}),
}))
expect(db.organizationUnit.findMany).not.toHaveBeenCalled()
expect(readSalaryWorkflowSnapshots).not.toHaveBeenCalled()
expect(workflow).not.toHaveBeenCalled()
expect(readSalaryMarketIntentBatch).not.toHaveBeenCalled()
expect(data.positionGroups[0].position.id).toBe(job.id)
})
test('基础数据和调研先到达,慢经营来源独立完成;最终金额与完整计算一致', async () => {
let finishMarket!: (value: Map<string, Map<string, unknown>>) => void
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { finishMarket = resolve }))
const progress: import('../performance-salary-details-contract').SalaryDetails[] = []
const pending = getPerformanceSalaryDetails('reader', '2026-10', {
role: 'ai-planning', phase: 'full', onProgress: data => progress.push(data),
})
for (let i = 0; i < 40 && !progress.some(data => data.scope?.sources.some(source => source.source === 'survey' && source.status === 'ready')); i++) await Promise.resolve()
expect(progress[0].scope?.phase).toBe('base')
expect(progress[0].roles['ai-planning'][0].values.baseSalary).toBe('100.01')
const partial = progress.find(data => data.scope?.sources.some(source => source.source === 'survey' && source.status === 'ready'))!
expect(partial.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', status: 'pending' }))
expect(partial.roles['ai-planning'][0].values.currentTotal).toBeNull()
finishMarket(new Map(['2026-08', '2026-09'].map(month => [month, new Map([['p1', { rawScore: 100 }]])])))
const data = await pending
expect(data.scope?.sources.every(source => source.status === 'ready')).toBe(true)
expect(data.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: '146.71', salaryDifference: '0.00', points: 71 })
})
test('仅上月经营来源失败保留本月工资和成功指标,重试重新计算并恢复上月及差值', async () => {
const { SalaryError } = jest.requireActual('../personnel-salary')
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementationOnce(async (_months, _people, _ids, _rows, onFailure) => {
onFailure('2026-08', new SalaryError('经营数据暂时无法读取。', 503, 'MARKET_INTENT_UNAVAILABLE'))
return new Map([['2026-09', new Map([['p1', { rawScore: 100 }]])]])
})
const scope = { role: 'ai-planning' as const, phase: 'full' as const }
const data = await getPerformanceSalaryDetails('reader', '2026-10', scope)
expect(data.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: null, salaryDifference: null, points: 71 })
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', salaryMonth: '2026-09', status: 'failed' }))
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', salaryMonth: '2026-10', status: 'ready' }))
const retry = await getPerformanceSalaryDetails('reader', '2026-10', scope)
expect(retry.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: '146.71', salaryDifference: '0.00' })
expect(readSalaryWorkflowSnapshots).toHaveBeenCalledTimes(2)
})
test('某月调研读取失败不隐藏基础工资、交付率或另一月结果,也不泄露内部错误', async () => {
db.performanceSurveyResponse.findMany.mockImplementation(async ({ where }: any) => {
if (where.survey.assessmentMonth === '2026-10') throw new Error('SELECT private salary')
return [response('p1', 'visual_brand_tone', 90), response('p1', 'work_cooperation', 60)]
})
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'full' })
const row = data.roles['ai-planning'][0]
expect(row.values).toMatchObject({ baseSalary: '100.01', currentTotal: null, previousTotal: '146.71', salaryDifference: null, points: 71 })
expect(Object.values(row.metrics)).toContain(90)
expect(JSON.stringify(data.scope)).not.toContain('private salary')
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'survey', salaryMonth: '2026-10', status: 'failed' }))
})

View File

@ -244,3 +244,27 @@ test('远程免扣恢复10月15分并视为按时,其他人员和9月归属不
delete process.env.ART_WORKFLOW_POINTS_DASHBOARD_URL
}
})
test('只读交付率不依赖人工积分文件,仍计算完整分母和免扣', async () => {
process.env.ART_WORKFLOW_POINTS_CONFIG_DIR = '/isolated-point-config'
;(readFile as jest.Mock).mockImplementation(async (path: string) => {
if (path.endsWith('deductions.json')) throw Error('points file unavailable')
return '[]'
})
;(prisma.dingWorkflowSnapshot.findMany as jest.Mock).mockResolvedValue([art('on-time'), art('late', '2026-09-15T02:00:00Z')])
const result = await readSalaryWorkflowMetricsBatch(['2026-09'], people, undefined, { delivery: true, pointsMonths: [] })
expect(result.get('2026-09')!.deliveryCounts.get('worker')).toEqual({ onTime: 1, total: 2 })
expect(result.get('2026-09')!.onTimeRates.get('worker')).toBe(50)
expect(readFile).toHaveBeenCalledTimes(1)
await expect(readSalaryWorkflowMetricsBatch(['2026-09'], people, undefined, { delivery: false, pointsMonths: ['2026-09'] }))
.rejects.toMatchObject({ status: 503, code: 'WORKFLOW_POINTS_CONFIG_UNAVAILABLE' })
})
test('主管交付率不因流程缺少积分负责人而失败,个人积分仍提示等待同步', async () => {
const row = art('old-snapshot')
delete row.formFields.plannerOwner
;(prisma.dingWorkflowSnapshot.findMany as jest.Mock).mockResolvedValue([row])
expect((await readSalaryWorkflowMetricsBatch(['2026-09'], people, undefined, { delivery: true, pointsMonths: [] })).get('2026-09')!.onTimeRates.get('worker')).toBe(100)
await expect(readSalaryWorkflowMetricsBatch(['2026-09'], people, undefined, { delivery: false, pointsMonths: ['2026-09'] }))
.rejects.toMatchObject({ status: 503, code: 'WORKFLOW_POINTS_SYNCING' })
})

View File

@ -28,10 +28,12 @@ const base = () => ({ id: 'base', employeeProfileId: 'employee', positionId: roo
beforeEach(() => {
grade = ''; jest.clearAllMocks()
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['employee', { rawScore: 100 }]]))
;(prisma.$transaction as jest.Mock).mockImplementation(work => work({
const db = {
performanceSurveyResponse: { count: async () => 1, findMany: async () => ['visual_brand_tone', 'cross_department', 'course_share', 'work_cooperation'].flatMap(templateCode => [80, 100].map(totalScore => ({ id: `${templateCode}-${totalScore}`, totalScore, scores: {}, createdAt: new Date(), assignment: { workflowStageKey: 'review' }, target: { employeeProfileId: 'employee' }, survey: { templateCode, templateSnapshot: { code: templateCode, questions: [], workflow: { scoring: { mode: 'average_reviewers', stageKeys: ['review'] } } } } }))) },
organizationUnit: { findMany: async () => [] }, performanceSurveyEmployeeProfile: { findMany: async () => [{ id: 'employee', realName: '测试', flowerName: '测试' }] }, personnelSalaryBase: { findMany: async () => [base()] }, salaryPositionConfig: { findMany: async () => positions },
}))
}
Object.assign(prisma, db)
;(prisma.$transaction as jest.Mock).mockImplementation(work => work(db))
})
test('人员入口只含父岗,绩效入口只含职级方案;匹配稳定ID,不按岗位名推断', () => {
const config = positions.map(p => ({ ...p, updatedAt: p.updatedAt.toISOString() }))

View File

@ -157,3 +157,21 @@ test('来源失败整体503,不能跳过失败候选或当作0分;恢复后
windows.mockResolvedValue(new Map([['one:123456', windowValue(0)]]))
expect((await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')?.rawScore).toBe(100)
})
test('一个窗口失败使关联月份整体待重试,不能丢弃失败记录后用剩余记录计分;其他月份正常', async () => {
db.mockResolvedValue([
flow('august-failed', { sourceFinishedAtRaw: '2026-08-10T00:00:00Z' }),
flow('august-valid', { sourceFinishedAtRaw: '2026-08-12T00:00:00Z' }),
flow('september-valid'),
])
windows.mockImplementation(async (items: any[], options) => {
options.onWindowFailure([items.find(item => item.workflowId === 'august-failed').key])
return new Map(items.map(item => [item.key, windowValue(.1)]))
})
const onFailure = jest.fn()
const result = await readSalaryMarketIntentBatch(['2026-08', '2026-09'], people, ['p'], undefined, onFailure)
expect(onFailure).toHaveBeenCalledTimes(1)
expect(onFailure).toHaveBeenCalledWith('2026-08', expect.objectContaining({ status: 503, code: 'MARKET_INTENT_UNAVAILABLE' }))
expect(result.get('2026-08')?.get('p')?.rawScore).toBeNull()
expect(result.get('2026-09')?.get('p')?.rawScore).toBeCloseTo(110)
})

View File

@ -65,19 +65,31 @@ async function readRemoteExemptions(url: string): Promise<ArtPointAdjustment[]>
}
/** Remote contributions are authoritative for exemptions; local manual adjustments stay independent. */
export async function readArtPointConfiguration(): Promise<ArtPointConfiguration> {
async function readLocalAdjustments(file: string) {
const directory = process.env.ART_WORKFLOW_POINTS_CONFIG_DIR
return directory ? configRows.parse(JSON.parse(await readFile(join(directory, file), 'utf8'))) : []
}
export async function readArtPointOvertimeExemptions(): Promise<ArtPointAdjustment[]> {
const remote = process.env.ART_WORKFLOW_POINTS_DASHBOARD_URL?.trim()
const readLocal = async (file: string) => directory
? configRows.parse(JSON.parse(await readFile(join(directory, file), 'utf8')))
: []
try {
const [deductions, overtimeExemptions] = await Promise.all([
readLocal('deductions.json'),
remote ? readRemoteExemptions(remote) : readLocal('overtime_exemptions.json'),
])
return { deductions, overtimeExemptions }
return await (remote ? readRemoteExemptions(remote) : readLocalAdjustments('overtime_exemptions.json'))
} catch {
throw new SalaryError('流程积分免扣配置暂时无法读取,请稍后重试。', 503, 'WORKFLOW_POINTS_CONFIG_UNAVAILABLE')
throw unavailableConfiguration()
}
}
const unavailableConfiguration = () => new SalaryError('流程积分免扣配置暂时无法读取,请稍后重试。', 503, 'WORKFLOW_POINTS_CONFIG_UNAVAILABLE')
export async function readArtPointDeductions(): Promise<ArtPointAdjustment[]> {
try {
return await readLocalAdjustments('deductions.json')
} catch {
throw unavailableConfiguration()
}
}
export async function readArtPointConfiguration(): Promise<ArtPointConfiguration> {
const [deductions, overtimeExemptions] = await Promise.all([readArtPointDeductions(), readArtPointOvertimeExemptions()])
return { deductions, overtimeExemptions }
}

View File

@ -92,8 +92,7 @@ export function artPointPersonResolver(people: ArtPointPerson[]) {
export function calculateArtWorkflowPoints(input: {
workflowKey: string; planningRows: StatRow[]; graphicRows: StatRow[]; imageRows: StatRow[]
plannerId: string | null; assessment: DingWorkflowDeliveryAssessment
}, people: ArtPointPerson[], config = EMPTY_ART_POINT_CONFIG) {
const resolve = artPointPersonResolver(people)
}, people: ArtPointPerson[], config = EMPTY_ART_POINT_CONFIG, resolve = artPointPersonResolver(people)) {
const roles = new Map<string, { planner: number; fullCase: number }>()
const add = (id: string, role: 'planner' | 'fullCase', value: number) => {
const row = roles.get(id) ?? { planner: 0, fullCase: 0 }; row[role] += value; roles.set(id, row)

View File

@ -74,6 +74,7 @@ type SnapshotRow = {
type CachedSourceRows = { expiresAt: number; rows: SourceMetricRow[] }
const sourceCache = new Map<string, CachedSourceRows>()
const upstreamReads = new Map<string, Promise<SourceMetricRow[]>>()
type PerformanceConversionSourceCursor = {
version: 2
@ -304,31 +305,35 @@ function normalizePerformanceConversionSyncStatus(state: { status: string; lastC
return 'ready'
}
export async function getPerformanceConversionSyncMetadata(brand?: PerformanceConversionBrand): Promise<PerformanceConversionSyncMetadata> {
async function readConversionSyncState() {
// Keep isolated unit tests and pre-migration local shells readable while the
// additive table is being introduced. Production Prisma clients always have
// this delegate after the migration has been applied.
const syncState = (prisma as typeof prisma & {
performanceConversionSyncState?: typeof prisma.performanceConversionSyncState
}).performanceConversionSyncState
if (!syncState) {
return { status: 'pending', lastCompletedAt: null, lastSourceDate: null }
}
try {
const state = await syncState.findUnique({
return syncState ? syncState.findUnique({
where: { id: PERFORMANCE_CONVERSION_SYNC_STATE_ID },
select: { status: true, lastCompletedAt: true, sourceCursorRaw: true },
})
const cursor = parsePerformanceConversionSourceCursor(state?.sourceCursorRaw || null)
const source = brand ? metricSourceForBrand(brand) : { kind: 'legacy' as const }
if (source.kind === 'tmall-store' && !(source.brand in cursor.tmallStoreDates)) {
return { status: state?.status === 'error' ? 'error' : state?.status === 'syncing' ? 'syncing' : 'pending', lastCompletedAt: null, lastSourceDate: null }
}
return {
status: normalizePerformanceConversionSyncStatus(state),
lastCompletedAt: state?.lastCompletedAt?.toISOString() || null,
lastSourceDate: source.kind === 'tmall-store' ? cursor.tmallStoreDates[source.brand] || null : cursor.lastSourceDate,
}
}) : null
}
function conversionSyncMetadata(state: Awaited<ReturnType<typeof readConversionSyncState>>, brand?: PerformanceConversionBrand): PerformanceConversionSyncMetadata {
const cursor = parsePerformanceConversionSourceCursor(state?.sourceCursorRaw || null)
const source = brand ? metricSourceForBrand(brand) : { kind: 'legacy' as const }
if (source.kind === 'tmall-store' && !(source.brand in cursor.tmallStoreDates)) {
return { status: state?.status === 'error' ? 'error' : state?.status === 'syncing' ? 'syncing' : 'pending', lastCompletedAt: null, lastSourceDate: null }
}
return {
status: normalizePerformanceConversionSyncStatus(state),
lastCompletedAt: state?.lastCompletedAt?.toISOString() || null,
lastSourceDate: source.kind === 'tmall-store' ? cursor.tmallStoreDates[source.brand] || null : cursor.lastSourceDate,
}
}
export async function getPerformanceConversionSyncMetadata(brand?: PerformanceConversionBrand): Promise<PerformanceConversionSyncMetadata> {
try {
return conversionSyncMetadata(await readConversionSyncState(), brand)
} catch (error) {
console.warn('[performance-conversion-sync] 同步状态读取失败,暂按首次同步处理:', error)
return { status: 'pending', lastCompletedAt: null, lastSourceDate: null }
@ -376,14 +381,24 @@ async function readUpstreamSourceRows(source: MetricSource, productId: string, s
const cached = sourceCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) return cached.rows
const pool = new mssql.ConnectionPool(sourceConfig())
const running = upstreamReads.get(cacheKey)
if (running) return running
const read = (async () => {
const pool = new mssql.ConnectionPool(sourceConfig())
try {
await pool.connect()
const rows = await fetchPerformanceSourceRows(pool, source, productId, startDate, endDate)
sourceCache.set(cacheKey, { rows, expiresAt: Date.now() + SOURCE_CACHE_TTL_MS })
return rows
} finally {
await pool.close().catch(() => undefined)
}
})()
upstreamReads.set(cacheKey, read)
try {
await pool.connect()
const rows = await fetchPerformanceSourceRows(pool, source, productId, startDate, endDate)
sourceCache.set(cacheKey, { rows, expiresAt: Date.now() + SOURCE_CACHE_TTL_MS })
return rows
return await read
} finally {
await pool.close().catch(() => undefined)
upstreamReads.delete(cacheKey)
}
}
@ -767,8 +782,9 @@ function latestClean(rows: SourceMetricRow[], field: keyof SourceMetricRow) {
/** Shared source and calendar-window reader. Callers must enforce their own access boundary. */
export async function readPerformanceConversionWindows(
workflows: PerformanceConversionWorkflowItem[],
options: { intentWindowOnly?: boolean; now?: Date } = {},
options: { intentWindowOnly?: boolean; now?: Date; onWindowFailure?: (keys: string[]) => void; signal?: AbortSignal } = {},
) {
options.signal?.throwIfAborted()
const today = toShanghaiDateKey(options.now ?? new Date())!
const requests = workflows.map(workflow => {
const source = metricSourceForBrand(workflow.brand)
@ -789,26 +805,45 @@ export async function readPerformanceConversionWindows(
} else groups.set(key, { brand: workflow.brand, productId: workflow.productId, start: workflow.monitorStartDate, end, requests: [{ workflow, source, end, supported }] })
}
const queue = Array.from(groups.values())
const syncState = queue.length ? await readConversionSyncState().catch(error => {
if (options.onWindowFailure) {
options.onWindowFailure(queue.flatMap(group => group.requests.map(request => request.workflow.key)))
queue.length = 0
} else console.warn('[performance-conversion-sync] 同步状态读取失败,暂按首次同步处理:', error)
return null
}) : null
let cursor = 0
await Promise.all(Array.from({ length: Math.min(4, queue.length) }, async () => {
while (cursor < queue.length) {
while (!options.signal?.aborted && cursor < queue.length) {
const group = queue[cursor++]
const source = metricSourceForBrand(group.brand)
const sync = await getPerformanceConversionSyncMetadata(group.brand)
group.rows = sync.lastCompletedAt ? await readSnapshotRows(source, group.productId, group.start, group.end) : []
const sync = conversionSyncMetadata(syncState, group.brand)
try {
group.rows = sync.lastCompletedAt ? await readSnapshotRows(source, group.productId, group.start, group.end) : []
} catch (error) {
if (!options.onWindowFailure) throw error
options.onWindowFailure(group.requests.map(request => request.workflow.key))
continue
}
// Preserve the existing per-window bootstrap fallback when merged reads
// include both an already-synced flow and a newly discovered flow.
const missing = group.requests.filter(request => !group.rows!.some(row => {
const date = metricDateKey(row.metricDate)
return date !== null && date >= request.workflow.monitorStartDate && date <= request.end
}))
if (missing.length) {
if (missing.length && !options.signal?.aborted) {
const start = missing.reduce((value, request) => value < request.workflow.monitorStartDate ? value : request.workflow.monitorStartDate, missing[0].workflow.monitorStartDate)
const end = missing.reduce((value, request) => maxDateKey(value, request.end), missing[0].end)
group.upstreamRows = await readUpstreamSourceRows(source, group.productId, start, end)
try {
group.upstreamRows = await readUpstreamSourceRows(source, group.productId, start, end)
} catch (error) {
if (!options.onWindowFailure) throw error
options.onWindowFailure(missing.map(request => request.workflow.key))
}
}
}
}))
options.signal?.throwIfAborted()
return new Map(requests.map(({ workflow, source, end, supported }) => {
const group = groups.get(groupKey(source, workflow.productId))
const inWindow = (row: SourceMetricRow) => {

View File

@ -7,6 +7,13 @@ import { salaryMonthLabel } from './performance-salary-templates'
import type { SurveyMatchReason } from './salary-survey-scores'
export type SalaryCell = string | number | null
export type SalaryPhase = 'base' | 'partial' | 'full'
export type SalaryDataSource = 'survey' | 'on-time' | 'market-intent-top3' | 'points'
export type SalarySourceStatus = {
source: SalaryDataSource
salaryMonth: string
sourceMonth: string
} & ({ status: 'pending' } | { status: 'ready' } | { status: 'failed'; code: string; message: string })
export type SalaryDetailRow = {
employeeProfileId: string
employeeLabel: string
@ -22,6 +29,7 @@ export type SalaryDetailRow = {
performanceMatch?: 'matched' | 'unmatched'
}
export type SalaryDetails = {
scope?: { role: SalaryRole; phase: SalaryPhase; sources: SalarySourceStatus[] }
displayMonth: string
sourceMonth: string
marketSourceMonth: string
@ -32,6 +40,9 @@ export type SalaryDetails = {
departmentMatchIssues?: Array<{ employeeProfileId: string; employeeLabel: string; message: string }>
}
export const SALARY_STREAM_TYPE = 'application/x-ndjson'
export type SalaryStreamEvent = { data: SalaryDetails } | { error: string; status: number }
export function salarySourceLabel(data: Pick<SalaryDetails, 'displayMonth' | 'sourceMonth' | 'marketSourceMonth' | 'isFallback'>) {
const source = data.isFallback
? `${Number(data.displayMonth.slice(5))}月暂无调研数据,当前使用${salaryMonthLabel(data.sourceMonth)}数据测试`

View File

@ -1,123 +1,359 @@
import type { Prisma } from '@prisma/client'
import { prisma } from './prisma'
import { requireSalaryAccess } from './personnel-salary'
import { requireSalaryAccess, SalaryError } from './personnel-salary'
import { resolveSalaryMonth, previousSalaryMonth, getPositionSalaryTemplate } from './performance-salary-templates'
import { resolveSalarySourceMonth, roundSalaryScore } from './performance-salary-calculation'
import { collectSalarySurveyScores, createSalarySurveyPersonMatcher, surveyMatchMessages } from './salary-survey-scores'
import { readSalaryWorkflowMetricsBatch, type SalaryWorkflowMetrics } from './performance-salary-workflows'
import { readSalaryMarketIntentBatch } from './salary-market-intent'
import { readSalaryWorkflowSnapshots } from './salary-workflow-source'
import { calculatePositionScore, resolvePersonnelPerformance, personnelPositions, performancePositions } from './salary-position-contract'
import { readArtPointOvertimeExemptions } from './art-workflow-point-configuration'
import {
calculatePositionScore, resolvePersonnelPerformance, personnelPositions, performancePositions, percentageBasisPoints,
type SalaryPosition,
} from './salary-position-contract'
import { serializePosition } from './salary-positions'
import { calculateSalaryPay, calculateSalaryDifference } from './performance-salary-pay'
import { buildSalaryDepartmentScopes, summarizeDepartmentDelivery, summarizeDepartmentMarketIntent } from './salary-department-metrics'
import { SALARY_DEPARTMENT_UNRESOLVED } from './salary-department-contract'
import { SALARY_DEPARTMENT_UNRESOLVED, type SalaryDepartmentScope } from './salary-department-contract'
import type { MarketIntentEvidence } from './salary-market-intent-contract'
import type { SalaryDetails, SalaryDetailRow, SalaryCell } from './performance-salary-details-contract'
import type { SalaryDetails, SalaryDetailRow, SalaryCell, SalaryDataSource, SalarySourceStatus, SalaryPhase } from './performance-salary-details-contract'
import type { SalaryRole } from './performance-salary-roles'
export async function getPerformanceSalaryDetails(userId: string, month: unknown): Promise<SalaryDetails> {
type DetailsScope = {
role: SalaryRole
phase: 'base' | 'full'
onProgress?: (details: SalaryDetails) => void
signal?: AbortSignal
}
type MonthState = ReturnType<typeof resolveSalarySourceMonth>
type SalaryBase = Prisma.PersonnelSalaryBaseGetPayload<{ select: typeof baseFields }>
type AssignedSalary = { base: SalaryBase; position: SalaryPosition; matched: boolean }
const baseFields = {
id: true, employeeProfileId: true, positionId: true, jobGrade: true, name: true, flowerName: true,
department: true, brand: true, baseSalary: true, gradeSalary: true, performanceSalary: true,
} as const
const identityFields = { id: true, realName: true, flowerName: true, displayName: true, dingtalkUserId: true } as const
const departmentFields = {
departmentPath: true, sourcePayload: true, employmentState: true,
departmentMemberships: { select: { sourceDeptId: true, departmentPath: true, isPrimary: true } },
} as const
const surveyFilter = (month: string) => ({
survey: { assessmentMonth: month, status: { notIn: ['draft', 'cancelled'] } },
assignment: { status: 'submitted' },
})
const surveyFields = {
id: true, totalScore: true, createdAt: true, scores: true,
assignment: { select: { workflowStageKey: true, reviewerSource: true, evaluatorSnapshot: true } },
target: { select: { employeeProfileId: true } },
survey: { select: { templateCode: true, templateSnapshot: true } },
} as const
const emptyWorkflowMetrics = (): SalaryWorkflowMetrics => ({
sourceMonth: '', points: new Map(), deliveryCounts: new Map(), onTimeRates: new Map(),
})
const emptyRoles = (): SalaryDetails['roles'] => ({
'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [],
})
const monthFallbackEnabled = () => process.env.NODE_ENV === 'development' && process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK === 'true'
const sourceFallbacks: Record<SalaryDataSource, { code: string; message: string }> = {
survey: { code: 'SALARY_SURVEY_UNAVAILABLE', message: '绩效调研暂时无法读取。' },
'on-time': { code: 'SALARY_DELIVERY_UNAVAILABLE', message: '按时交付率暂时无法读取。' },
'market-intent-top3': { code: 'MARKET_INTENT_UNAVAILABLE', message: '市场验证数据暂时无法读取。' },
points: { code: 'SALARY_POINTS_UNAVAILABLE', message: '积分暂时无法读取。' },
}
function assignedSalaries(bases: SalaryBase[], configuration: SalaryPosition[], role?: SalaryRole) {
const matches = bases.map(base => ({ base, match: resolvePersonnelPerformance(base.positionId, base.jobGrade, configuration) }))
const unmatchedIds = new Set(matches.filter(({ match }) => !match).map(({ base }) => base.positionId))
const groupPositions = [
...performancePositions(configuration).filter(position => !unmatchedIds.has(position.id)),
...personnelPositions(configuration).filter(position => unmatchedIds.has(position.id)).map(position => ({ ...position, dimensions: [] })),
].filter(position => !role || position.salaryRole === role)
const byId = new Map(groupPositions.map(position => [position.id, position]))
const assigned = matches.flatMap(({ base, match }) => {
const position = byId.get(match?.id ?? base.positionId ?? '')
return position ? [{ base, position, matched: Boolean(match) }] : []
})
return { groupPositions, assigned }
}
function visitMetrics(assignment: AssignedSalary, scope?: DetailsScope) {
return assignment.position.dimensions.flatMap(dimension => dimension.metrics.filter(metric =>
!scope || (percentageBasisPoints(dimension.weight) > 0 && percentageBasisPoints(metric.weight) > 0)))
}
function makeSalaryDetails(state: MonthState, groupPositions: SalaryPosition[], rows: SalaryDetailRow[]): SalaryDetails {
const roles = emptyRoles()
const positionGroups = groupPositions.map(position => ({
position: { ...position }, template: getPositionSalaryTemplate(position, state.displayMonth), rows: [] as SalaryDetailRow[],
}))
const byId = new Map(positionGroups.map(group => [group.position.id, group]))
for (const row of rows) {
const group = byId.get(row.performancePositionId ?? row.positionId ?? '')!
group.rows.push(row)
roles[group.position.salaryRole].push(row)
}
for (const group of positionGroups) {
group.rows.sort((a, b) => String(a.values.name).localeCompare(String(b.values.name), 'zh-CN'))
group.position.personnelCount = group.rows.length
}
return { ...state, marketSourceMonth: previousSalaryMonth(state.displayMonth), roles, positionGroups }
}
function makeSalaryRow({ base, position, matched }: AssignedSalary): SalaryDetailRow {
return {
employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name,
hasSalaryBase: true, positionGroupCode: `salary:${position.id}`, positionId: base.positionId ?? undefined,
jobGrade: base.jobGrade, performancePositionId: matched ? position.id : null,
performanceMatch: matched ? 'matched' : 'unmatched', metrics: {}, metricEvidence: {}, totalScore: null,
values: {
name: base.name, nickname: base.flowerName, jobGrade: base.jobGrade, department: base.department, brand: base.brand,
baseSalary: base.baseSalary.toFixed(2), gradeSalary: base.gradeSalary.toFixed(2),
performanceSalary: base.performanceSalary.toFixed(2), baseSalaryBasis: base.baseSalary.toFixed(2),
performanceSalaryBasis: base.performanceSalary.toFixed(2),
},
}
}
export async function getPerformanceSalaryDetails(userId: string, month: unknown, scope?: DetailsScope): Promise<SalaryDetails> {
await requireSalaryAccess(userId)
const displayMonth = resolveSalaryMonth(month)
const previousMonth = previousSalaryMonth(displayMonth)
// Both months use exactly the same personnel, grade and configuration snapshot.
const { states, responsesByMonth, people, bases, positions, units } = await prisma.$transaction(async db => {
const monthStates = await Promise.all([displayMonth, previousMonth].map(async month => {
const count = await db.performanceSurveyResponse.count({ where: { survey: { assessmentMonth: month, status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } } })
return resolveSalarySourceMonth(month, count, process.env.NODE_ENV, process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK)
}))
const [monthlyResponses, people, bases, positions, units] = await Promise.all([
Promise.all(Array.from(new Set(monthStates.map(state => state.sourceMonth)), async month => ({ month, responses: await db.performanceSurveyResponse.findMany({ where: { survey: { assessmentMonth: month, status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } }, select: { id: true, totalScore: true, createdAt: true, scores: true, assignment: { select: { workflowStageKey: true, reviewerSource: true, evaluatorSnapshot: true } }, target: { select: { employeeProfileId: true } }, survey: { select: { templateCode: true, templateSnapshot: true } } } }) }))),
db.performanceSurveyEmployeeProfile.findMany({ include: { departmentMemberships: true } }),
db.personnelSalaryBase.findMany({ where: { deletedAt: null }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] }),
db.salaryPositionConfig.findMany({ where: { deletedAt: null }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] }),
db.organizationUnit.findMany({ where: { isActive: true }, select: { sourceDeptId: true, name: true, path: true } }),
])
return { states: monthStates, responsesByMonth: new Map(monthlyResponses.map(item => [item.month, item.responses])), people, bases, positions, units }
}, { isolationLevel: 'RepeatableRead' })
const configuration = positions.map(serializePosition)
const matches = new Map(bases.map(base => [base.id, resolvePersonnelPerformance(base.positionId, base.jobGrade, configuration)]))
const marketPositionIds = new Set(configuration.filter(position => position.dimensions.some(dimension => dimension.metrics.some(metric => metric.source.kind === 'market-intent-top3'))).map(position => position.id))
const roots = personnelPositions(configuration)
const plannerPositionIds = new Set(roots.filter(position => position.salaryRole === 'ai-planning').map(position => position.id))
const managerPositionIds = new Set(roots.filter(position => position.salaryRole === 'management').map(position => position.id))
const managerBases = bases.filter(base => managerPositionIds.has(base.positionId ?? ''))
const departmentScopes = buildSalaryDepartmentScopes(managerBases.map(base => base.employeeProfileId), people, units,
new Set(bases.filter(base => plannerPositionIds.has(base.positionId ?? '')).map(base => base.employeeProfileId)))
const marketEmployeeIds = new Set(bases.filter(base => marketPositionIds.has(matches.get(base.id)?.id ?? '') && !managerPositionIds.has(base.positionId ?? '')).map(base => base.employeeProfileId))
for (const base of managerBases) if (marketPositionIds.has(matches.get(base.id)?.id ?? '')) {
for (const member of departmentScopes.get(base.employeeProfileId)!.planners) marketEmployeeIds.add(member.employeeProfileId)
const sourceStatuses = new Map<string, SalarySourceStatus>()
function recordSource(source: SalaryDataSource, state: MonthState, status: 'pending' | 'ready' | 'failed', error?: unknown) {
if (!scope) return
const sourceMonth = source === 'market-intent-top3' ? previousSalaryMonth(state.displayMonth) : state.sourceMonth
const identity = { source, salaryMonth: state.displayMonth, sourceMonth }
const key = `${source}:${state.displayMonth}`
if (sourceStatuses.get(key)?.status === 'failed') return
sourceStatuses.set(key, status === 'failed' ? {
...identity, status, ...(error instanceof SalaryError ? { code: error.code, message: error.message } : sourceFallbacks[source]),
} : { ...identity, status })
}
// Current and previous salaries share one workflow/configuration read and one market-window batch.
const workflowSnapshots = await readSalaryWorkflowSnapshots()
const [workflowsByMonth, marketByMonth] = await Promise.all([
readSalaryWorkflowMetricsBatch(Array.from(new Set(states.map(state => state.sourceMonth))).reverse(), people, workflowSnapshots),
readSalaryMarketIntentBatch(states.map(state => previousSalaryMonth(state.displayMonth)).reverse(), people, Array.from(marketEmployeeIds), workflowSnapshots),
])
function calculateMonth(state: typeof states[number], workflows: SalaryWorkflowMetrics, market: Map<string, MarketIntentEvidence>): SalaryDetails {
const { displayMonth } = state
const marketSourceMonth = previousSalaryMonth(displayMonth)
const responses = responsesByMonth.get(state.sourceMonth)!
const scores = collectSalarySurveyScores(responses)
const matchSurveyPerson = createSalarySurveyPersonMatcher(people)
const withScope = (data: SalaryDetails, phase: SalaryPhase) => scope
? { ...data, scope: { role: scope.role, phase, sources: Array.from(sourceStatuses.values()) } }
: data
const snapshot = await prisma.$transaction(async db => {
const positions = await db.salaryPositionConfig.findMany({
where: { deletedAt: null, ...(scope ? { salaryRole: scope.role } : {}) },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
})
const configuration = positions.map(serializePosition)
const bases = await db.personnelSalaryBase.findMany({
where: {
deletedAt: null,
...(scope ? { positionId: { in: personnelPositions(configuration).map(position => position.id) } } : {}),
},
select: baseFields,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
})
const assignments = assignedSalaries(bases, configuration, scope?.role)
return { ...assignments, configuration, bases }
}, { isolationLevel: 'RepeatableRead' })
const { assigned, groupPositions, configuration, bases } = snapshot
const base = withScope(makeSalaryDetails({ displayMonth, sourceMonth: displayMonth, isFallback: false },
groupPositions, assigned.map(makeSalaryRow)), 'base')
if (scope?.phase === 'base') return base
scope?.onProgress?.(base)
scope?.signal?.throwIfAborted()
const metrics = assigned.map(assignment => ({ ...assignment, metrics: visitMetrics(assignment, scope) }))
const surveyCodes = Array.from(new Set(metrics.flatMap(({ metrics }) => metrics.flatMap(metric =>
metric.source.kind === 'survey' ? [metric.source.templateCode] : []))))
const surveyAssignments = metrics.filter(({ metrics }) => metrics.some(metric => metric.source.kind === 'survey'))
const wantsSurvey = !scope || surveyCodes.length > 0
const wantsDelivery = !scope || metrics.some(({ metrics }) => metrics.some(metric => metric.source.kind === 'on-time'))
const wantsPoints = !scope || assigned.some(({ position }) => position.salaryRole === 'ai-planning')
const marketAssignments = metrics.filter(({ metrics }) => metrics.some(metric => metric.source.kind === 'market-intent-top3'))
const managerIds = metrics.filter(({ position, metrics }) => position.salaryRole === 'management'
&& metrics.some(metric => metric.source.kind === 'on-time' || metric.source.kind === 'market-intent-top3'))
.map(({ base }) => base.employeeProfileId)
const departmentNeeded = !scope || managerIds.length > 0
const wantsPeople = wantsSurvey || wantsDelivery || wantsPoints || marketAssignments.length > 0
const states = await Promise.all([displayMonth, previousMonth].map(async salaryMonth => {
const count = monthFallbackEnabled() && salaryMonth === '2026-10'
? await prisma.performanceSurveyResponse.count({ where: surveyFilter(salaryMonth) }) : 0
return resolveSalarySourceMonth(salaryMonth, count, process.env.NODE_ENV, process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK)
}))
// Only personnel and position configuration need a single database snapshot for both salary months.
const peopleTask = wantsPeople ? prisma.performanceSurveyEmployeeProfile.findMany({
select: { ...identityFields, ...(departmentNeeded ? departmentFields : {}) },
}) : Promise.resolve([])
const unitsTask = departmentNeeded ? prisma.organizationUnit.findMany({
where: { isActive: true }, select: { sourceDeptId: true, name: true, path: true },
}) : Promise.resolve([])
const plannerPositions = new Set(personnelPositions(configuration).filter(position => position.salaryRole === 'ai-planning').map(position => position.id))
const plannerTask = scope?.role === 'management' && marketAssignments.length
? prisma.personnelSalaryBase.findMany({
where: { deletedAt: null, position: { deletedAt: null, personnelPositionId: null, salaryRole: 'ai-planning' } },
select: { employeeProfileId: true },
}) : Promise.resolve(bases.filter(row => plannerPositions.has(row.positionId ?? '')))
const pointsStates = scope ? states.slice(0, 1) : states
const workflowMonths = Array.from(new Set(states.map(state => state.sourceMonth))).reverse()
const marketMonths = states.map(state => previousSalaryMonth(state.displayMonth)).reverse()
let matchSurveyPerson = createSalarySurveyPersonMatcher([])
let deliveryDepartments = new Map<string, SalaryDepartmentScope>()
let marketDepartments = new Map(deliveryDepartments)
const scores = new Map<string, ReturnType<typeof collectSalarySurveyScores>>()
let workflowsByMonth = new Map<string, SalaryWorkflowMetrics>()
let pointsByMonth = new Map<string, SalaryWorkflowMetrics>()
let marketByMonth = new Map<string, Map<string, MarketIntentEvidence>>()
const wantsMarket = !scope || marketAssignments.length > 0
for (const state of states) {
if (wantsSurvey) recordSource('survey', state, 'pending')
if (wantsDelivery) recordSource('on-time', state, 'pending')
if (wantsMarket) recordSource('market-intent-top3', state, 'pending')
}
if (wantsPoints) recordSource('points', states[0], 'pending')
async function loadSource(source: SalaryDataSource, sourceStates: MonthState[], read: () => Promise<void>) {
try {
await read()
for (const state of sourceStates) recordSource(source, state, 'ready')
} catch (error) {
if (!scope) throw error
for (const state of sourceStates) recordSource(source, state, 'failed', error)
}
if (scope?.onProgress && !scope.signal?.aborted && Array.from(sourceStatuses.values()).some(item => item.status === 'pending')) {
scope.onProgress(buildResult('partial'))
}
}
const surveys = wantsSurvey ? loadSource('survey', states, async () => {
matchSurveyPerson = createSalarySurveyPersonMatcher(await peopleTask)
const surveyTargets = Array.from(new Set(surveyAssignments.flatMap(({ base }) => {
const id = matchSurveyPerson(base).employeeProfileId
return id ? [id] : []
})))
if (scope && !surveyTargets.length) return
await Promise.all(Array.from(new Set(states.map(state => state.sourceMonth)), async sourceMonth => {
const where = surveyFilter(sourceMonth)
try {
const responses = await prisma.performanceSurveyResponse.findMany({
where: scope ? {
...where, target: { employeeProfileId: { in: surveyTargets } },
survey: { ...where.survey, templateCode: { in: surveyCodes } },
} : where,
select: surveyFields,
})
scores.set(sourceMonth, collectSalarySurveyScores(responses))
} catch (error) {
if (!scope) throw error
for (const state of states.filter(state => state.sourceMonth === sourceMonth)) recordSource('survey', state, 'failed', error)
}
}))
}) : undefined
const snapshots = wantsDelivery || wantsPoints || wantsMarket
? readSalaryWorkflowSnapshots(Boolean(scope && !wantsDelivery)) : undefined
// Both workflow metrics use the same exemption read, but a points-only failure cannot hide delivery.
const exemptions = scope && (wantsDelivery || wantsPoints) ? readArtPointOvertimeExemptions() : undefined
const workflows = !scope ? [(async () => {
const [people, units] = await Promise.all([peopleTask, unitsTask])
deliveryDepartments = buildSalaryDepartmentScopes(managerIds, people, units, new Set())
workflowsByMonth = await readSalaryWorkflowMetricsBatch(workflowMonths, people, snapshots)
pointsByMonth = workflowsByMonth
})()] : [
wantsDelivery && loadSource('on-time', states, async () => {
const [people, units, rows, overtimeExemptions] = await Promise.all([peopleTask, unitsTask, snapshots, exemptions])
deliveryDepartments = buildSalaryDepartmentScopes(managerIds, people, units, new Set())
workflowsByMonth = await readSalaryWorkflowMetricsBatch(workflowMonths, people, rows, {
delivery: true, pointsMonths: [], overtimeExemptions,
})
}),
wantsPoints && loadSource('points', pointsStates, async () => {
const [people, rows, overtimeExemptions] = await Promise.all([peopleTask, snapshots, exemptions])
pointsByMonth = await readSalaryWorkflowMetricsBatch(pointsStates.map(state => state.sourceMonth), people, rows, {
delivery: false, pointsMonths: pointsStates.map(state => state.sourceMonth), overtimeExemptions,
})
}),
]
const market = wantsMarket ? loadSource('market-intent-top3', states, async () => {
const [people, units, plannerBases, rows] = await Promise.all([peopleTask, unitsTask, plannerTask, snapshots])
marketDepartments = buildSalaryDepartmentScopes(managerIds, people, units, new Set(plannerBases.map(item => item.employeeProfileId)))
const marketEmployeeIds = new Set(marketAssignments.flatMap(({ base, position }) => position.salaryRole === 'management'
? (marketDepartments.get(base.employeeProfileId)?.planners ?? []).map(member => member.employeeProfileId)
: [base.employeeProfileId]))
marketByMonth = await readSalaryMarketIntentBatch(marketMonths, people, Array.from(marketEmployeeIds), rows, scope ? (month, error) => {
for (const state of states.filter(state => previousSalaryMonth(state.displayMonth) === month)) recordSource('market-intent-top3', state, 'failed', error)
} : undefined, scope?.signal)
}) : undefined
function calculateMonth(state: MonthState): SalaryDetails {
const marketSourceMonth = previousSalaryMonth(state.displayMonth)
const ready = (source: SalaryDataSource) => !scope || sourceStatuses.get(`${source}:${state.displayMonth}`)?.status === 'ready'
const workflows = workflowsByMonth.get(state.sourceMonth) ?? emptyWorkflowMetrics()
const market = marketByMonth.get(marketSourceMonth) ?? new Map<string, MarketIntentEvidence>()
const surveyMatchIssues: NonNullable<SalaryDetails['surveyMatchIssues']> = []
const departmentMatchIssues: NonNullable<SalaryDetails['departmentMatchIssues']> = []
const roles: SalaryDetails['roles'] = { 'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [] }
const unmatchedIds = new Set(bases.filter(base => !matches.get(base.id)).map(base => base.positionId))
const groupPositions = [...performancePositions(configuration).filter(position => !unmatchedIds.has(position.id)), ...roots.filter(position => unmatchedIds.has(position.id)).map(position => ({ ...position, dimensions: [] }))]
const positionGroups = groupPositions.map(position => {
return { position, template: getPositionSalaryTemplate(position, displayMonth), rows: [] as SalaryDetailRow[] }
})
const groupById = new Map(positionGroups.map(group => [group.position.id, group]))
for (const base of bases) {
const match = matches.get(base.id)
const group = groupById.get(match?.id ?? base.positionId ?? '')
if (!group) continue
const rows = assigned.map(assignment => {
const { base, position } = assignment
const row = makeSalaryRow(assignment)
const surveyPerson = matchSurveyPerson(base)
const raw = surveyPerson.employeeProfileId ? scores.get(surveyPerson.employeeProfileId) : undefined
if (surveyPerson.reason && group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'survey'))) {
surveyMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, salaryRole: group.position.salaryRole, reason: surveyPerson.reason, message: surveyMatchMessages[surveyPerson.reason] })
const raw = surveyPerson.employeeProfileId ? scores.get(state.sourceMonth)?.get(surveyPerson.employeeProfileId) : undefined
const relevant = visitMetrics(assignment, scope)
if (surveyPerson.reason && ready('survey') && relevant.some(metric => metric.source.kind === 'survey')) {
surveyMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: row.employeeLabel, salaryRole: position.salaryRole,
reason: surveyPerson.reason, message: surveyMatchMessages[surveyPerson.reason] })
}
const metrics: Record<string, number | null> = {}
const scope = group.position.salaryRole === 'management' ? departmentScopes.get(base.employeeProfileId) : undefined
const hasMarket = group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'market-intent-top3'))
const hasDelivery = group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'on-time'))
const marketEvidence = scope && hasMarket ? summarizeDepartmentMarketIntent(marketSourceMonth, scope, market) : market.get(base.employeeProfileId)
const deliveryEvidence = scope && hasDelivery ? summarizeDepartmentDelivery(state.sourceMonth, scope, workflows.deliveryCounts) : undefined
if (scope && !scope.department && (hasMarket || hasDelivery)) departmentMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, message: SALARY_DEPARTMENT_UNRESOLVED })
for (const dimension of group.position.dimensions) for (const metric of dimension.metrics) {
metrics[metric.id] = metric.source.kind === 'survey' ? raw?.get(metric.source.templateCode) ?? null
: metric.source.kind === 'on-time' ? (deliveryEvidence ? deliveryEvidence.rawScore : workflows.onTimeRates.get(base.employeeProfileId) ?? null)
: metric.source.kind === 'market-intent-top3' ? marketEvidence?.rawScore ?? null : null
const deliveryDepartment = deliveryDepartments.get(base.employeeProfileId)
const marketDepartment = marketDepartments.get(base.employeeProfileId)
const hasMarket = relevant.some(metric => metric.source.kind === 'market-intent-top3')
const hasDelivery = relevant.some(metric => metric.source.kind === 'on-time')
const marketEvidence = !ready('market-intent-top3') ? undefined : marketDepartment && hasMarket
? summarizeDepartmentMarketIntent(marketSourceMonth, marketDepartment, market) : market.get(base.employeeProfileId)
const deliveryEvidence = ready('on-time') && deliveryDepartment && hasDelivery
? summarizeDepartmentDelivery(state.sourceMonth, deliveryDepartment, workflows.deliveryCounts) : undefined
if ((hasMarket && marketDepartment?.department === null) || (hasDelivery && deliveryDepartment?.department === null)) {
departmentMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: row.employeeLabel, message: SALARY_DEPARTMENT_UNRESOLVED })
}
const result = calculatePositionScore(group.position.dimensions, metrics)
const values: Record<string, SalaryCell> = {
name: base.name, nickname: base.flowerName, jobGrade: base.jobGrade, department: base.department, brand: base.brand,
baseSalary: base.baseSalary.toFixed(2), gradeSalary: base.gradeSalary.toFixed(2), performanceSalary: base.performanceSalary.toFixed(2),
baseSalaryBasis: base.baseSalary.toFixed(2), performanceSalaryBasis: base.performanceSalary.toFixed(2),
points: workflows.points.has(base.employeeProfileId) ? roundSalaryScore(workflows.points.get(base.employeeProfileId)!) : null,
performanceScore: result.totalScore,
...calculateSalaryPay(result.totalScore, base),
for (const metric of relevant) {
const source = metric.source
if (source.kind === 'survey') row.metrics[metric.id] = ready('survey') ? raw?.get(source.templateCode) ?? null : null
else if (source.kind === 'on-time') {
row.metrics[metric.id] = !ready('on-time') ? null : deliveryEvidence ? deliveryEvidence.rawScore : workflows.onTimeRates.get(base.employeeProfileId) ?? null
if (deliveryEvidence) row.metricEvidence![metric.id] = deliveryEvidence
} else if (source.kind === 'market-intent-top3') {
row.metrics[metric.id] = marketEvidence?.rawScore ?? null
if (marketEvidence) row.metricEvidence![metric.id] = marketEvidence
} else row.metrics[metric.id] = null
}
for (const key of Object.keys(metrics)) {
values[`${key}RawValue`] = metrics[key]
values[`${key}Score`] = result.contributions[key]
const { totalScore, contributions } = calculatePositionScore(position.dimensions, row.metrics)
row.totalScore = totalScore
const points = pointsByMonth.get(state.sourceMonth)?.points.get(base.employeeProfileId)
Object.assign(row.values, {
points: points === undefined || (scope && position.salaryRole !== 'ai-planning') ? null : roundSalaryScore(points),
performanceScore: totalScore,
...calculateSalaryPay(totalScore, base),
})
for (const id of Object.keys(row.metrics)) {
row.values[`${id}RawValue`] = row.metrics[id]
row.values[`${id}Score`] = contributions[id]
}
const metricEvidence: NonNullable<SalaryDetailRow['metricEvidence']> = {}
for (const dimension of group.position.dimensions) for (const metric of dimension.metrics) {
if (metric.source.kind === 'market-intent-top3' && marketEvidence) metricEvidence[metric.id] = marketEvidence
if (metric.source.kind === 'on-time' && deliveryEvidence) metricEvidence[metric.id] = deliveryEvidence
}
const row: SalaryDetailRow = { employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, hasSalaryBase: true, positionGroupCode: `salary:${group.position.id}`, positionId: base.positionId ?? undefined, jobGrade: base.jobGrade, performancePositionId: match?.id ?? null, performanceMatch: match ? 'matched' : 'unmatched', metrics, metricEvidence, values, totalScore: result.totalScore }
group.rows.push(row); roles[group.position.salaryRole].push(row)
return row
})
return { ...makeSalaryDetails(state, groupPositions, rows), surveyMatchIssues, departmentMatchIssues }
}
function buildResult(phase: SalaryPhase) {
const [current, previous] = states.map(calculateMonth)
const previousByEmployee = new Map(Object.values(previous.roles).flat().map(row => [row.employeeProfileId, row.values.currentTotal as string | null]))
for (const row of Object.values(current.roles).flat()) {
const previousTotal = previousByEmployee.get(row.employeeProfileId) ?? null
row.values.previousTotal = previousTotal
row.values.salaryDifference = calculateSalaryDifference(row.values.currentTotal as string | null, previousTotal)
}
for (const group of positionGroups) { group.rows.sort((a, b) => String(a.values.name).localeCompare(String(b.values.name), 'zh-CN')); group.position.personnelCount = group.rows.length }
return { ...state, marketSourceMonth, roles, positionGroups, surveyMatchIssues, departmentMatchIssues }
return withScope(current, phase)
}
const [current, previous] = states.map(state => calculateMonth(state, workflowsByMonth.get(state.sourceMonth)!, marketByMonth.get(previousSalaryMonth(state.displayMonth))!))
const previousByEmployee = new Map(Object.values(previous.roles).flat().map(row => [row.employeeProfileId, row.values.currentTotal as string | null]))
for (const row of Object.values(current.roles).flat()) {
const previousTotal = previousByEmployee.get(row.employeeProfileId) ?? null
row.values.previousTotal = previousTotal
row.values.salaryDifference = calculateSalaryDifference(row.values.currentTotal as string | null, previousTotal)
}
return current
await Promise.all([surveys, market, ...workflows])
return buildResult('full')
}

View File

@ -1,12 +1,11 @@
import { SalaryError } from './personnel-salary'
import { readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { readArtPointConfiguration } from './art-workflow-point-configuration'
import { prepareSalaryWorkflow, readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { readArtPointConfiguration, readArtPointDeductions, readArtPointOvertimeExemptions } from './art-workflow-point-configuration'
import { assessDingWorkflowDeliveryBatch } from './ding-workflow-delivery'
import { applyDeliveryExemption, deliveryExemptWorkflowKeys } from './workflow-delivery-exemptions'
import {
DING_WORKFLOW_ALLOWED_PROCESS_CODES,
getShanghaiMonthRangeForValue, isDingWorkflowApprovedCompletion, isDingWorkflowDeliveryAssessmentInRange,
normalizeDetailFormFields, normalizeWorkflowTasks, storedWorkflowTimestampToIso,
} from './ding-workflow-sync'
import {
artPointPersonResolver, assessArtWorkflowPoints, calculateArtWorkflowPoints, independentArtAdjustmentDate,
@ -20,32 +19,62 @@ export async function readSalaryWorkflowMetrics(sourceMonth: string, people: Art
return (await readSalaryWorkflowMetricsBatch([sourceMonth], people)).get(sourceMonth)!
}
type WorkflowMetricOptions = {
delivery: boolean
pointsMonths: string[]
overtimeExemptions?: Awaited<ReturnType<typeof readArtPointOvertimeExemptions>>
}
/** One workflow/configuration read and one SLA assessment for every requested month. */
export async function readSalaryWorkflowMetricsBatch(sourceMonths: string[], people: ArtPointPerson[], snapshots?: SalaryWorkflowSnapshot[]) {
export async function readSalaryWorkflowMetricsBatch(
sourceMonths: string[], people: ArtPointPerson[], snapshots?: SalaryWorkflowSnapshot[] | Promise<SalaryWorkflowSnapshot[]>,
options?: WorkflowMetricOptions,
) {
const pointMonths = new Set(options?.pointsMonths ?? sourceMonths)
const configuration = () => {
if (!options) return readArtPointConfiguration()
return Promise.all([
options.overtimeExemptions ?? readArtPointOvertimeExemptions(),
pointMonths.size ? readArtPointDeductions() : [],
]).then(([overtimeExemptions, deductions]) => ({ overtimeExemptions, deductions }))
}
const [rows, config] = await Promise.all([
snapshots ?? readSalaryWorkflowSnapshots(),
readArtPointConfiguration(),
configuration(),
])
const workflowInput = (row: typeof rows[number]) => ({
processCode: row.processCode!.toUpperCase(), workflowStatus: row.status, workflowId: row.processInstanceId, businessId: row.businessId,
sourceCreatedAt: storedWorkflowTimestampToIso(row.sourceCreatedAtRaw), sourceFinishedAt: storedWorkflowTimestampToIso(row.sourceFinishedAtRaw),
tasks: normalizeWorkflowTasks(row.activeTasks), formFields: normalizeDetailFormFields(row.formFields),
})
const readDelivery = options?.delivery ?? true
const workflows = rows.map(prepareSalaryWorkflow)
// Keep the delivery population and queue calculation; only override a judged overtime result.
const candidates = rows.filter(row => row.status.trim().toUpperCase() !== 'COMPLETED' || isDingWorkflowApprovedCompletion(row.status, row.result, row.bizAction))
const inputs = candidates.map(workflowInput)
const candidates = readDelivery ? workflows.filter(({ row }) => row.status.trim().toUpperCase() !== 'COMPLETED'
|| isDingWorkflowApprovedCompletion(row.status, row.result, row.bizAction)) : []
const exemptKeys = deliveryExemptWorkflowKeys(config)
const assessments = assessDingWorkflowDeliveryBatch(inputs).map((assessment, index) =>
applyDeliveryExemption(assessment, candidates[index].businessId || candidates[index].processInstanceId, exemptKeys))
const assessments = assessDingWorkflowDeliveryBatch(candidates.map(({ input }) => input)).map((assessment, index) => {
const { row } = candidates[index]
return applyDeliveryExemption(assessment, row.businessId || row.processInstanceId, exemptKeys)
})
const byDingId = new Map(people.filter(person => person.dingtalkUserId).map(person => [person.dingtalkUserId, person.id]))
const resolve = artPointPersonResolver(people)
const artRows = pointMonths.size ? workflows.filter(({ input }) => input.processCode === DING_WORKFLOW_ALLOWED_PROCESS_CODES[0]) : []
const workflowKeys = new Set(artRows.map(({ row }) => row.businessId || row.processInstanceId))
const pointRanges = Array.from(pointMonths, month => ({ month, ...getShanghaiMonthRangeForValue(month) }))
const pointsByMonth = new Map<string, Array<(typeof artRows)[number] & { assessment: ReturnType<typeof assessArtWorkflowPoints> }>>()
for (const workflow of artRows) {
const { input } = workflow
const assessment = assessArtWorkflowPoints(input.tasks, input.formFields)
const finishedAt = assessment.finishedAt ? Date.parse(assessment.finishedAt) : NaN
const range = pointRanges.find(item => finishedAt >= item.start.getTime() && finishedAt < item.end.getTime())
if (!range) continue
const list = pointsByMonth.get(range.month) ?? []
list.push({ ...workflow, assessment })
pointsByMonth.set(range.month, list)
}
const byMonth = new Map<string, SalaryWorkflowMetrics>()
for (const sourceMonth of Array.from(new Set(sourceMonths))) {
const range = getShanghaiMonthRangeForValue(sourceMonth)
const byDingId = new Map(people.filter(person => person.dingtalkUserId).map(person => [person.dingtalkUserId, person.id]))
const points = new Map<string, number>()
const delivery = new Map<string, { onTime: number; total: number }>()
const resolve = artPointPersonResolver(people)
candidates.forEach((row, index) => {
const input = inputs[index], assessment = assessments[index]
candidates.forEach(({ row, input }, index) => {
const assessment = assessments[index]
if (!isDingWorkflowApprovedCompletion(row.status, row.result, row.bizAction) || !isDingWorkflowDeliveryAssessmentInRange(assessment, range)) return
const art = input.processCode === DING_WORKFLOW_ALLOWED_PROCESS_CODES[0]
const owners = new Set(input.tasks.filter(task => art
@ -65,18 +94,13 @@ export async function readSalaryWorkflowMetricsBatch(sourceMonths: string[], peo
})
})
// Points follow the source dashboard's review-month filter, independently of final completion/SLA availability.
const artRows = rows.filter(row => row.processCode?.toUpperCase() === DING_WORKFLOW_ALLOWED_PROCESS_CODES[0])
const workflowKeys = new Set(artRows.map(row => row.businessId || row.processInstanceId))
const pointRows = pointsByMonth.get(sourceMonth) ?? []
if (pointRows.some(({ input }) => !Object.prototype.hasOwnProperty.call(input.formFields, 'plannerOwner'))) {
throw new SalaryError('流程积分正在同步,请稍后重新加载。', 503, 'WORKFLOW_POINTS_SYNCING')
}
const selectedWorkflowKeys = new Set<string>()
const scoredWorkflowKeys = new Set<string>()
for (const row of artRows) {
const input = workflowInput(row)
const assessment = assessArtWorkflowPoints(input.tasks, input.formFields)
const finishedAt = assessment.finishedAt ? Date.parse(assessment.finishedAt) : NaN
if (!(finishedAt >= range.start.getTime() && finishedAt < range.end.getTime())) continue
if (!Object.prototype.hasOwnProperty.call(input.formFields, 'plannerOwner')) {
throw new SalaryError('流程积分正在同步,请稍后重新加载。', 503, 'WORKFLOW_POINTS_SYNCING')
}
for (const { row, input, assessment } of pointRows) {
const workflowKey = row.businessId || row.processInstanceId
selectedWorkflowKeys.add(workflowKey)
if (isRejectedArtPointWorkflow(row.status, row.result)) continue
@ -84,13 +108,13 @@ export async function readSalaryWorkflowMetricsBatch(sourceMonths: string[], peo
const scores = calculateArtWorkflowPoints({
workflowKey, plannerId, planningRows: parseArtPointRows(input.formFields.planningTaskStats),
graphicRows: parseArtPointRows(input.formFields.graphicTaskStats), imageRows: parseArtPointRows(input.formFields.imageTaskStats), assessment,
}, people, config)
}, people, config, resolve)
scores.forEach((score, id) => { points.set(id, (points.get(id) ?? 0) + score) })
scoredWorkflowKeys.add(workflowKey)
}
// Known workflows use their selected review month; unknown keys use their encoded date.
// Adjustments already applied to contributions must not be counted a second time.
for (const item of config.deductions) {
for (const item of pointMonths.has(sourceMonth) ? config.deductions : []) {
const date = independentArtAdjustmentDate(item.workflowKey)
if (item.enabled === false || !date || scoredWorkflowKeys.has(item.workflowKey)) continue
if (workflowKeys.has(item.workflowKey) ? !selectedWorkflowKeys.has(item.workflowKey) : date.slice(0, 7) !== sourceMonth) continue

View File

@ -9,6 +9,7 @@ export type SalaryDeliveryCounts = { onTime: number; total: number }
/** Main department identities only: no descendant, secondary membership or salary text matching. */
export function buildSalaryDepartmentScopes(managerIds: string[], people: Person[], units: SalaryOrganizationUnit[], plannerIds: Set<string>) {
if (!managerIds.length) return new Map<string, SalaryDepartmentScope>()
const departments = new Map(people.map(person => [person.id, resolveSalaryOrganizationUnit(person, units)]))
const members = new Map<number, SalaryDepartmentMember[]>()
for (const person of people) {

View File

@ -1,5 +1,5 @@
import { SalaryError } from './personnel-salary'
import { readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { prepareSalaryWorkflow, readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source'
import { artPointPersonResolver, parseArtPointRows, type ArtPointPerson } from './art-workflow-points'
import { normalizeDetailFormFields, normalizeWorkflowTasks } from './ding-workflow-sync'
import { performanceConversionWorkflowItems, readPerformanceConversionWindows } from './performance-conversion'
@ -8,7 +8,13 @@ import { summarizeMarketIntent, type MarketIntentEvidence, type MarketIntentCand
const PRODUCTION_ACTIVITIES = new Set(['31cf_5b23', 'a9e1_5be0', 'de46_708d', '2f9e_36f0', 'b306_c849', 'f073_738b', '6864_5429', '162b_23ea', 'c9fe_a6b8'])
export function marketIntentParticipants(formFields: unknown, activeTasks: unknown, people: ArtPointPerson[]) {
const resolve = artPointPersonResolver(people), fields = normalizeDetailFormFields(formFields)
return resolveMarketParticipants(normalizeDetailFormFields(formFields), normalizeWorkflowTasks(activeTasks), artPointPersonResolver(people))
}
function resolveMarketParticipants(
fields: ReturnType<typeof normalizeDetailFormFields>, tasks: ReturnType<typeof normalizeWorkflowTasks>,
resolve: ReturnType<typeof artPointPersonResolver>,
) {
const ids = new Set<string>()
const add = (value: unknown): void => {
if (Array.isArray(value)) { value.forEach(add); return }
@ -18,7 +24,7 @@ export function marketIntentParticipants(formFields: unknown, activeTasks: unkno
const id = resolve(value); if (id) ids.add(id)
}
add(fields.plannerOwner)
for (const task of normalizeWorkflowTasks(activeTasks)) if (PRODUCTION_ACTIVITIES.has(task.activityId ?? '')) add(task.assigneeUserId)
for (const task of tasks) if (PRODUCTION_ACTIVITIES.has(task.activityId ?? '')) add(task.assigneeUserId)
for (const value of [fields.planningTaskStats, fields.graphicTaskStats, fields.imageTaskStats]) {
for (const row of parseArtPointRows(value)) for (const label of ['全案策划', '策划案负责人']) add(row[label])
}
@ -30,28 +36,56 @@ export async function readSalaryMarketIntent(month: string, people: ArtPointPers
return (await readSalaryMarketIntentBatch([month], people, employeeIds)).get(month)!
}
const marketUnavailable = () => new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE')
type MarketFailure = (month: string, error: SalaryError) => void
/** Merge both months' product windows into the existing batched source reader. */
export async function readSalaryMarketIntentBatch(months: string[], people: ArtPointPerson[], employeeIds: string[], snapshots?: SalaryWorkflowSnapshot[]) {
try { return await readMarketIntentBatch(months, people, employeeIds, snapshots) }
export async function readSalaryMarketIntentBatch(
months: string[], people: ArtPointPerson[], employeeIds: string[],
snapshots?: SalaryWorkflowSnapshot[], onFailure?: MarketFailure, signal?: AbortSignal,
) {
try { return await readMarketIntentBatch(months, people, employeeIds, snapshots, onFailure, signal) }
catch (error) {
if (error instanceof SalaryError) throw error
throw new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE')
throw marketUnavailable()
}
}
async function readMarketIntentBatch(months: string[], people: ArtPointPerson[], employeeIds: string[], snapshots?: SalaryWorkflowSnapshot[]) {
async function readMarketIntentBatch(
months: string[], people: ArtPointPerson[], employeeIds: string[],
snapshots?: SalaryWorkflowSnapshot[], onFailure?: MarketFailure, signal?: AbortSignal,
) {
const employeeSet = new Set(employeeIds), monthSet = new Set(months)
const byMonth = new Map(Array.from(monthSet, month => [month, new Map<string, MarketIntentEvidence>()]))
if (!employeeSet.size) return byMonth
const rows = snapshots ?? await readSalaryWorkflowSnapshots()
const candidates = rows.filter(row => row.sourceFinishedAtRaw && monthSet.has(toShanghaiDateKey(row.sourceFinishedAtRaw)?.slice(0, 7) ?? '')).flatMap(row => {
const participants = Array.from(marketIntentParticipants(row.formFields, row.activeTasks, people)).filter(id => employeeSet.has(id))
return participants.length ? performanceConversionWorkflowItems(row).map(workflow => ({ workflow, participants, month: toShanghaiDateKey(row.sourceFinishedAtRaw!)!.slice(0, 7) })) : []
const rows = await (snapshots ?? readSalaryWorkflowSnapshots())
const resolve = artPointPersonResolver(people)
const candidates = rows.flatMap(row => {
const month = row.sourceFinishedAtRaw ? toShanghaiDateKey(row.sourceFinishedAtRaw)?.slice(0, 7) : undefined
if (!month || !monthSet.has(month)) return []
const items = performanceConversionWorkflowItems(row)
if (!items.length) return []
const { input } = prepareSalaryWorkflow(row)
const participants = Array.from(resolveMarketParticipants(input.formFields, input.tasks, resolve)).filter(id => employeeSet.has(id))
return participants.length ? items.map(workflow => ({ workflow, participants, month })) : []
})
const failedMonths = new Set<string>()
const monthByKey = new Map(candidates.map(item => [item.workflow.key, item.month]))
const windows = await readPerformanceConversionWindows(candidates.map(item => item.workflow), {
intentWindowOnly: true,
signal,
...(onFailure ? {
onWindowFailure(keys) {
for (const key of keys) {
const month = monthByKey.get(key)!
if (!failedMonths.has(month)) onFailure(month, marketUnavailable())
failedMonths.add(month)
}
},
} : {}),
})
let windows: Awaited<ReturnType<typeof readPerformanceConversionWindows>>
try { windows = await readPerformanceConversionWindows(candidates.map(item => item.workflow), { intentWindowOnly: true }) }
catch { throw new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE') }
const recordsByMonth = new Map(Array.from(monthSet, month => [month, new Map<string, MarketIntentCandidate[]>()]))
for (const { workflow, participants, month } of candidates) {
if (failedMonths.has(month)) continue
const records = recordsByMonth.get(month)!
const window = windows.get(workflow.key)!, summary = buildIntentRateWindowSummary(window.daily)
const reason: MarketIntentExclusion | null = !window.supported ? 'unsupported-platform' : window.daily.length < 15 ? 'immature-window'

View File

@ -1,12 +1,22 @@
import { prisma } from './prisma'
import { SalaryError } from './personnel-salary'
import { DING_WORKFLOW_ALLOWED_PROCESS_CODES, DING_WORKFLOW_STARTED_AT_CUTOFF_ISO } from './ding-workflow-sync'
import {
DING_WORKFLOW_ALLOWED_PROCESS_CODES, DING_WORKFLOW_STARTED_AT_CUTOFF_ISO,
normalizeDetailFormFields, normalizeWorkflowTasks, storedWorkflowTimestampToIso,
} from './ding-workflow-sync'
/** One immutable input set for both months' points, delivery and market calculations. */
export async function readSalaryWorkflowSnapshots() {
export async function readSalaryWorkflowSnapshots(artOnly = false) {
try {
return await prisma.dingWorkflowSnapshot.findMany({
where: { processCode: { in: [...DING_WORKFLOW_ALLOWED_PROCESS_CODES] }, sourceCreatedAtRaw: { gte: DING_WORKFLOW_STARTED_AT_CUTOFF_ISO } },
where: {
processCode: artOnly ? DING_WORKFLOW_ALLOWED_PROCESS_CODES[0] : { in: [...DING_WORKFLOW_ALLOWED_PROCESS_CODES] },
sourceCreatedAtRaw: { gte: DING_WORKFLOW_STARTED_AT_CUTOFF_ISO },
},
select: {
processInstanceId: true, businessId: true, title: true, status: true, result: true, bizAction: true,
processCode: true, brand: true, sourceCreatedAtRaw: true, sourceFinishedAtRaw: true, formFields: true, activeTasks: true,
},
})
} catch {
throw new SalaryError('流程数据暂时无法读取,请稍后重新加载。', 503, 'SALARY_WORKFLOWS_UNAVAILABLE')
@ -14,3 +24,19 @@ export async function readSalaryWorkflowSnapshots() {
}
export type SalaryWorkflowSnapshot = Awaited<ReturnType<typeof readSalaryWorkflowSnapshots>>[number]
export function prepareSalaryWorkflow(row: SalaryWorkflowSnapshot) {
return {
row,
input: {
processCode: row.processCode!.toUpperCase(),
workflowStatus: row.status,
workflowId: row.processInstanceId,
businessId: row.businessId,
sourceCreatedAt: storedWorkflowTimestampToIso(row.sourceCreatedAtRaw),
sourceFinishedAt: storedWorkflowTimestampToIso(row.sourceFinishedAtRaw),
tasks: normalizeWorkflowTasks(row.activeTasks),
formFields: normalizeDetailFormFields(row.formFields),
},
}
}