gongxiangp2/components/department-dashboard/SalaryPositionPanel.tsx

160 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client'
import { useEffect, useRef, useState } from 'react'
import { Plus, Download } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { SALARY_ROLES } from '@/lib/performance-salary-roles'
import { currentSalaryMonth } from '@/lib/performance-salary-templates'
import { positionConfigurationHref, positionFields, positionFieldsSchema, sourceFromKey, sourceKey, sourceLabel, percentageBasisPoints, type PositionFields, type SalaryPosition, type ScoreSourceOption } from '@/lib/salary-position-contract'
import { POSITION_ENDPOINT, SalaryRequestError, salaryRequest, useSalaryConfiguration } from './SalaryConfigurationContext'
import { SalaryConfigurationDialog, salaryButton, salarySecondary, salaryPrimary, salaryInput, salaryDanger } from './SalaryConfigurationUI'
const empty = (): PositionFields => ({ name: '', salaryRole: 'ai-planning', description: '', dimensions: [] })
function PositionEditor({ position, sources, saved, close }: { position: SalaryPosition | null; sources: ScoreSourceOption[]; saved: (position: SalaryPosition) => Promise<void>; close: () => void }) {
const [draft, setDraft] = useState<PositionFields>(() => position ? structuredClone(positionFields(position)) : empty())
const [revision, setRevision] = useState(position?.revision), [busy, setBusy] = useState(false)
const [error, setError] = useState(''), [errors, setErrors] = useState<Record<string, string>>({}), [discard, setDiscard] = useState(false)
const [conflict, setConflict] = useState(false), [latest, setLatest] = useState<SalaryPosition | null | undefined>()
const [removeTarget, setRemoveTarget] = useState<{ dimension: number; metric?: number } | null>(null)
const form = useRef<HTMLFormElement>(null), continueButton = useRef<HTMLButtonElement>(null)
const removeConfirmation = useRef<HTMLDivElement>(null)
const errorSummary = useRef<HTMLDivElement>(null)
const dirty = JSON.stringify(draft) !== JSON.stringify(position ? positionFields(position) : empty())
useEffect(() => {
if (!dirty) return
const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
window.addEventListener('beforeunload', warn); return () => window.removeEventListener('beforeunload', warn)
}, [dirty])
useEffect(() => { if (discard) continueButton.current?.focus() }, [discard])
useEffect(() => { if (removeTarget) removeConfirmation.current?.querySelector<HTMLButtonElement>('button')?.focus() }, [removeTarget])
function requestClose() { if (!busy) { if (dirty) setDiscard(true); else close() } }
function change(work: (value: PositionFields) => void) { setDraft(value => { const next = structuredClone(value); work(next); return next }) }
async function loadLatest() {
try { const body = await salaryRequest<{ positions: SalaryPosition[] }>(POSITION_ENDPOINT); setLatest(body.positions.find(item => item.id === position?.id) ?? null) }
catch { setError('最新配置读取失败,草稿已保留,请重试。') }
}
async function save(event: React.FormEvent) {
event.preventDefault(); if (busy || conflict) return
const result = positionFieldsSchema.safeParse(draft), validation: Record<string, string> = {}
if (!result.success) result.error.issues.forEach(issue => { validation[issue.path.join('.')] = issue.message })
setErrors(validation); setError('')
if (!result.success) { requestAnimationFrame(() => { const target = form.current?.querySelector<HTMLElement>('[aria-invalid="true"]') || errorSummary.current; target?.focus(); target?.scrollIntoView?.({ block: 'center' }) }); return }
setBusy(true)
try {
const savedPosition = await salaryRequest<SalaryPosition>(position ? `${POSITION_ENDPOINT}/${position.id}` : POSITION_ENDPOINT, { method: position ? 'PUT' : 'POST', body: JSON.stringify({ ...result.data, ...(position ? { revision } : {}) }) })
await saved(savedPosition); close()
} catch (failure) {
setError(failure instanceof Error ? failure.message : '保存失败,草稿已保留,请重试。')
if (failure instanceof SalaryRequestError && failure.code === 'REVISION_CONFLICT') { setConflict(true); void loadLatest() }
} finally { setBusy(false) }
}
const errorId = (path: string) => `position-error-${path.replaceAll('.', '-')}`
const validationAttributes = (path: string) => ({ 'aria-invalid': !!errors[path], 'aria-describedby': errors[path] ? errorId(path) : undefined })
const fieldError = (path: string) => errors[path] ? <span id={errorId(path)} className="mt-1 block text-sm text-[#b42318]">{errors[path]}</span> : null
return <SalaryConfigurationDialog title={position ? '编辑岗位绩效配置' : '新增岗位'} wide busy={busy} onClose={requestClose}>
<form ref={form} onSubmit={save} noValidate className="p-5 sm:p-6">
<p className="mb-5 text-sm leading-6 text-[#66758b]">修改后适用于所有月份。维度权重及每个维度内的KPI权重分别合计100%;空配置可先保存。</p>
<fieldset disabled={busy} className="min-w-0 space-y-5">
<div className="grid gap-4 sm:grid-cols-2">
<label className="block text-sm font-semibold">岗位名称 *<input autoFocus value={draft.name} maxLength={100} {...validationAttributes('name')} className={`${salaryInput} mt-2`} onChange={event => change(value => { value.name = event.target.value })} />{fieldError('name')}</label>
<label className="block text-sm font-semibold">薪资展示入口 *<select value={draft.salaryRole} className={`${salaryInput} mt-2`} onChange={event => change(value => { value.salaryRole = event.target.value as PositionFields['salaryRole'] })}>{SALARY_ROLES.map(role => <option key={role.key} value={role.key}>{role.title}</option>)}</select></label>
</div>
<label className="block text-sm font-semibold">岗位说明<textarea value={draft.description} maxLength={1000} rows={2} className={`${salaryInput} mt-2 resize-y`} onChange={event => change(value => { value.description = event.target.value })} /></label>
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-[#e2e8f0] pt-5"><h3 className="font-bold">考核维度</h3><span className="text-sm tabular-nums text-[#66758b]">维度权重合计 {draft.dimensions.reduce((sum, item) => sum + (Number(item.weight) || 0), 0).toFixed(2)}%</span></div>
{fieldError('dimensions')}
{!draft.dimensions.length && <p className="text-sm text-[#66758b]">绩效未配置。可新增维度,也可先保存岗位。</p>}
{draft.dimensions.map((dimension, dimensionIndex) => <section key={dimension.id} aria-label={`维度${dimensionIndex + 1}`} aria-describedby={errors[`dimensions.${dimensionIndex}.metrics`] ? errorId(`dimensions.${dimensionIndex}.metrics`) : undefined} className="min-w-0 border-t border-[#e2e8f0] pt-5">
<div className="grid items-end gap-3 sm:grid-cols-[minmax(0,1fr)_144px_auto]">
<label className="block text-sm font-semibold">维度名称 *<input value={dimension.name} maxLength={100} className={`${salaryInput} mt-2`} {...validationAttributes(`dimensions.${dimensionIndex}.name`)} onChange={event => change(value => { value.dimensions[dimensionIndex].name = event.target.value })} />{fieldError(`dimensions.${dimensionIndex}.name`)}</label>
<label className="block text-sm font-semibold">维度权重(%)*<input type="text" inputMode="decimal" value={dimension.weight} className={`${salaryInput} mt-2 tabular-nums`} {...validationAttributes(`dimensions.${dimensionIndex}.weight`)} onChange={event => change(value => { value.dimensions[dimensionIndex].weight = event.target.value })} />{fieldError(`dimensions.${dimensionIndex}.weight`)}</label>
<button type="button" className={salaryDanger} onClick={() => setRemoveTarget({ dimension: dimensionIndex })}>删除维度</button>
</div>
<div className="mt-4 divide-y divide-[#e2e8f0]">
{dimension.metrics.map((metric, metricIndex) => <div key={metric.id} className="py-4 first:pt-0">
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_144px_auto]">
<label className="block text-sm font-medium">KPI名称 *<input value={metric.name} maxLength={100} className={`${salaryInput} mt-2`} {...validationAttributes(`dimensions.${dimensionIndex}.metrics.${metricIndex}.name`)} onChange={event => change(value => { value.dimensions[dimensionIndex].metrics[metricIndex].name = event.target.value })} />{fieldError(`dimensions.${dimensionIndex}.metrics.${metricIndex}.name`)}</label>
<label className="block text-sm font-medium">KPI权重(%)*<input type="text" inputMode="decimal" value={metric.weight} {...validationAttributes(`dimensions.${dimensionIndex}.metrics.${metricIndex}.weight`)} className={`${salaryInput} mt-2 tabular-nums`} onChange={event => change(value => { value.dimensions[dimensionIndex].metrics[metricIndex].weight = event.target.value })} />{fieldError(`dimensions.${dimensionIndex}.metrics.${metricIndex}.weight`)}</label>
<button type="button" aria-label={`删除${metric.name || 'KPI'}`} className={`${salaryDanger} self-end`} onClick={() => setRemoveTarget({ dimension: dimensionIndex, metric: metricIndex })}>删除KPI</button>
</div>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
<label className="block text-sm font-medium">计分来源<select value={sourceKey(metric.source)} className={`${salaryInput} mt-2`} onChange={event => change(value => { value.dimensions[dimensionIndex].metrics[metricIndex].source = sourceFromKey(event.target.value) })}>
<option value="unavailable">待接入</option><option value="on-time">流程按时交付率</option>
{metric.source.kind === 'survey' && !sources.some(item => item.code === (metric.source.kind === 'survey' ? metric.source.templateCode : '')) && <option value={sourceKey(metric.source)}>原来源已停用,请重选</option>}
{sources.map(source => <option key={source.code} value={`survey:${source.code}`}>{source.name}</option>)}
</select></label>
<label className="block text-sm font-medium">KPI说明<textarea value={metric.description} maxLength={2000} rows={2} className={`${salaryInput} mt-2 resize-y`} onChange={event => change(value => { value.dimensions[dimensionIndex].metrics[metricIndex].description = event.target.value })} /></label>
</div>
</div>)}
</div>
<div className="flex flex-wrap items-center justify-between gap-3"><button type="button" className={salarySecondary} onClick={() => change(value => { value.dimensions[dimensionIndex].metrics.push({ id: crypto.randomUUID(), name: '', description: '', weight: dimension.metrics.length ? '0' : '100', source: { kind: 'unavailable' } }) })}><Plus className="h-4 w-4" aria-hidden="true" />新增KPI</button><span className="text-sm tabular-nums text-[#66758b]">KPI权重合计 {dimension.metrics.reduce((sum, metric) => sum + (Number(metric.weight) || 0), 0).toFixed(2)}%</span></div>
{fieldError(`dimensions.${dimensionIndex}.metrics`)}
</section>)}
<button type="button" className={salarySecondary} onClick={() => change(value => { value.dimensions.push({ id: crypto.randomUUID(), name: '', weight: value.dimensions.length ? '0' : '100', metrics: [{ id: crypto.randomUUID(), name: '', weight: '100', description: '', source: { kind: 'unavailable' } }] }) })}><Plus className="h-4 w-4" aria-hidden="true" />新增维度</button>
</fieldset>
{!!Object.keys(errors).length && <div ref={errorSummary} tabIndex={-1} role="alert" className="mt-5 text-sm leading-6 text-[#b42318]"><p className="font-semibold">请检查以下配置:</p><ul className="list-inside list-disc">{Array.from(new Set(Object.values(errors))).map(message => <li key={message}>{message}</li>)}</ul></div>}
{removeTarget && <div ref={removeConfirmation} role="alert" className="mt-5 border-t border-[#e2e8f0] pt-4"><p className="text-sm">确定从草稿删除{removeTarget.metric === undefined ? '该维度及其全部KPI' : '该KPI'}?保存前需重新调整剩余权重。</p><div className="mt-3 flex gap-3"><button type="button" className={salarySecondary} onClick={() => setRemoveTarget(null)}>取消删除</button><button type="button" className={salaryDanger} onClick={() => { change(value => { if (removeTarget.metric === undefined) value.dimensions.splice(removeTarget.dimension, 1); else value.dimensions[removeTarget.dimension].metrics.splice(removeTarget.metric, 1) }); setRemoveTarget(null) }}>确认删除</button></div></div>}
{error && <p role="alert" className="mt-5 text-sm leading-6 text-[#b42318]">{error}</p>}
{conflict && <section aria-label="岗位版本冲突" className="mt-4 border-t border-[#e2e8f0] pt-4 text-sm"><h3 className="font-semibold">请先核对最新配置,当前草稿不会被替换</h3>{latest === undefined ? <button type="button" className={`${salarySecondary} mt-3`} onClick={() => void loadLatest()}>读取最新配置</button> : latest === null ? <p className="mt-2">该岗位已删除,请关闭弹窗并刷新。</p> : <><p className="mt-2">最新名称:{latest.name};版本:{latest.revision};薪资入口:{SALARY_ROLES.find(role => role.key === latest.salaryRole)?.title}</p><dl className="mt-3 space-y-2">{latest.dimensions.map(dimension => <div key={dimension.id}><dt className="font-semibold">{dimension.name} {dimension.weight}%</dt><dd className="break-words leading-6 text-[#66758b]">{dimension.metrics.map(metric => `${metric.name} ${metric.weight}% · ${sourceLabel(metric.source, sources)}`).join(';')}</dd></div>)}</dl><button type="button" className={`${salarySecondary} mt-3`} onClick={() => { setRevision(latest.revision); setConflict(false); setError(''); setLatest(undefined) }}>已核对,基于最新版本继续编辑</button></>}</section>}
{discard && <div role="alert" className="mt-5 border-t border-[#e2e8f0] pt-4"><p className="text-sm font-semibold">修改尚未保存,确定放弃吗?</p><div className="mt-3 flex flex-wrap gap-3"><button ref={continueButton} type="button" className={salarySecondary} onClick={() => setDiscard(false)}>继续编辑</button><button type="button" className={salaryDanger} onClick={close}>放弃修改</button></div></div>}
<footer className="sticky bottom-0 mt-6 flex flex-wrap justify-end gap-3 border-t border-[#e2e8f0] bg-white py-4"><button type="button" className={salarySecondary} disabled={busy} onClick={requestClose}>取消</button><button type="submit" className={salaryPrimary} disabled={busy || conflict || !!removeTarget}>{busy ? '保存中…' : '保存岗位配置'}</button></footer>
</form>
</SalaryConfigurationDialog>
}
export default function SalaryPositionPanel({ selectedId, month = currentSalaryMonth() }: { selectedId?: string; month?: string }) {
const { payload, sources, loading, error, reload } = useSalaryConfiguration()
const router = useRouter()
const [editor, setEditor] = useState<{ position: SalaryPosition | null } | null>(null)
const [deleting, setDeleting] = useState<SalaryPosition | null>(null), [busy, setBusy] = useState(false), [failure, setFailure] = useState(''), [notice, setNotice] = useState('')
const [exporting, setExporting] = useState(false), exportLock = useRef(false)
const heading = useRef<HTMLHeadingElement>(null), focusAfterDelete = useRef(false)
const position = payload?.positions.find(item => item.id === selectedId) || payload?.positions[0]
useEffect(() => {
if (focusAfterDelete.current && !loading && !error) { heading.current?.focus(); focusAfterDelete.current = false }
}, [loading, error, position?.id])
async function exportFile(all: boolean) {
if (exportLock.current || !payload?.positions.length) return
exportLock.current = true; setExporting(true); setFailure(''); setNotice('')
try {
const response = await fetch(`${POSITION_ENDPOINT}/export${all ? '' : `?position=${position!.id}`}`, { cache: 'no-store' })
if (!response.ok) { const body = await response.json().catch(() => ({})); throw new Error(body.error || '导出失败,请重试。') }
const url = URL.createObjectURL(await response.blob()), anchor = document.createElement('a')
anchor.href = url; anchor.download = all ? '岗位绩效配置_全部.xlsx' : '岗位绩效配置_当前岗位.xlsx'; anchor.click(); window.setTimeout(() => URL.revokeObjectURL(url), 1000)
setNotice('岗位配置已生成,请在下载中查看。')
} catch (failure) { setFailure(failure instanceof Error ? failure.message : '导出失败,请重试。') }
finally { exportLock.current = false; setExporting(false) }
}
async function remove() {
if (!deleting || busy) return
setBusy(true); setFailure('')
try {
await salaryRequest(`${POSITION_ENDPOINT}/${deleting.id}`, { method: 'DELETE', body: JSON.stringify({ revision: deleting.revision }) })
const next = payload?.positions.find(item => item.id !== deleting.id)
focusAfterDelete.current = true; setDeleting(null); setNotice('岗位已删除,历史变更记录已保留。')
router.replace(positionConfigurationHref('performance', month, next?.id), { scroll: false })
await reload()
}
catch (failure) { setFailure(failure instanceof Error ? failure.message : '删除失败,请重试。') }
finally { setBusy(false) }
}
if (loading && !payload) return <p role="status" className="px-6 py-10 text-sm text-[#66758b]">正在读取岗位配置…</p>
if (error) return <div role="alert" className="p-6"><p className="text-sm text-[#b42318]">{error}</p><button className={`${salarySecondary} mt-3`} onClick={() => void reload()}>重新加载</button></div>
return <div className="min-w-0 px-5 py-6 sm:px-6">
<div className="flex flex-wrap items-end justify-between gap-4">
<label className="grid min-w-0 flex-1 gap-2 text-sm font-semibold sm:max-w-xs">岗位<select className={salaryInput} value={position?.id || ''} onChange={event => { router.push(positionConfigurationHref('performance', month, event.target.value), { scroll: false }); setNotice(''); setFailure('') }}><option value="" disabled>请选择岗位</option>{payload?.positions.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
<div className="flex flex-wrap gap-2"><button className={salarySecondary} disabled={exporting || !position} onClick={() => void exportFile(false)}><Download className="h-4 w-4" aria-hidden="true" />{exporting ? '正在生成…' : '导出当前岗位'}</button><button className={salarySecondary} disabled={exporting || !position} onClick={() => void exportFile(true)}>导出全部岗位</button>{payload?.canEdit && <button className={salaryPrimary} onClick={() => setEditor({ position: null })}><Plus className="h-4 w-4" aria-hidden="true" />新增岗位</button>}</div>
</div>
<p className="mt-4 text-sm leading-6 text-[#66758b]">修改后适用于所有月份。综合占比=维度权重×KPI权重。{!payload?.canEdit ? ' 当前账号只读,仅超级管理员可维护。' : ''}</p>
{notice && <p role="status" className="mt-3 text-sm text-[#067647]">{notice}</p>}{failure && !deleting && <p role="alert" className="mt-3 text-sm text-[#b42318]">{failure}</p>}
{!position ? <div className="py-14 text-center"><h2 ref={heading} tabIndex={-1} className="font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">暂无岗位配置</h2><p className="mt-2 text-sm text-[#66758b]">{payload?.canEdit ? '新增岗位后可配置人员和绩效。' : '请等待超级管理员配置。'}</p></div> : <section className="mt-6" aria-labelledby="position-config-title">
<div className="flex flex-wrap items-start justify-between gap-3"><div className="min-w-0"><h2 ref={heading} tabIndex={-1} id="position-config-title" className="break-words text-lg font-bold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">{position.name}</h2><p className="mt-2 text-sm leading-6 text-[#66758b]">{SALARY_ROLES.find(role => role.key === position.salaryRole)?.title} · {position.personnelCount}人 · 版本{position.revision}{position.description ? ` · ${position.description}` : ''}</p></div>{payload?.canEdit && <div className="flex gap-1"><button className={`${salaryButton} text-[#0050cb] hover:bg-[#eef6ff]`} onClick={() => setEditor({ position })}>编辑岗位</button><button className={salaryDanger} onClick={() => { setDeleting(position); setFailure('') }}>删除岗位</button></div>}</div>
{position.dimensions.length > 0 && <p className="mt-3 text-sm leading-6 text-[#66758b]">左右滚动查看完整说明与计分来源。</p>}
{!position.dimensions.length ? <p className="py-10 text-sm text-[#66758b]">绩效未配置。请编辑岗位并新增考核维度。</p> : <div role="region" aria-label={`${position.name}绩效配置表`} tabIndex={0} className="mt-4 max-w-full overflow-x-auto border border-[#e2e8f0] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">
<table className="w-full min-w-[920px] text-left text-sm"><caption className="sr-only">{position.name}两层绩效权重与计分来源</caption><thead className="bg-[#f8fafc] text-[#4f6077]"><tr>{['考核维度', '维度权重', 'KPI指标', 'KPI权重', '综合占比', '计分来源'].map(label => <th key={label} scope="col" className="whitespace-nowrap px-4 py-3 font-semibold">{label}</th>)}</tr></thead><tbody className="divide-y divide-[#e2e8f0]">{position.dimensions.flatMap(dimension => dimension.metrics.map((metric, index) => <tr key={metric.id} className="align-top hover:bg-[#f8fafc]">{index === 0 && <><th scope="rowgroup" rowSpan={dimension.metrics.length} className="px-4 py-4 font-semibold">{dimension.name}</th><td rowSpan={dimension.metrics.length} className="px-4 py-4 tabular-nums">{dimension.weight}%</td></>}<th scope="row" className="max-w-80 px-4 py-4 font-medium"><span className="block">{metric.name}</span>{metric.description && <span className="mt-1 block text-xs font-normal leading-5 text-[#66758b]">{metric.description}</span>}</th><td className="px-4 py-4 tabular-nums">{metric.weight}%</td><td className="px-4 py-4 tabular-nums">{(percentageBasisPoints(dimension.weight) * percentageBasisPoints(metric.weight) / 1e6).toFixed(2)}%</td><td className="max-w-60 px-4 py-4 leading-6">{sourceLabel(metric.source, sources)}</td></tr>))}</tbody></table>
</div>}
</section>}
{editor && <PositionEditor position={editor.position} sources={sources} close={() => setEditor(null)} saved={async savedPosition => { setNotice('岗位配置已保存,薪资明细按最新配置计算。'); await reload(); if (!editor.position) router.push(positionConfigurationHref('performance', month, savedPosition.id), { scroll: false }) }} />}
{deleting && <SalaryConfigurationDialog title="删除岗位" busy={busy} onClose={() => { if (!busy) setDeleting(null) }}><div className="p-5"><p className="break-words text-sm leading-6">确定删除“{deleting.name}”及其绩效配置?岗位仍有人员时须先转移人员。</p>{failure && <p role="alert" className="mt-3 text-sm text-[#b42318]">{failure}</p>}<footer className="mt-6 flex flex-wrap justify-end gap-3"><button autoFocus className={salarySecondary} disabled={busy} onClick={() => setDeleting(null)}>取消</button>{failure && <button className={salarySecondary} onClick={() => { setDeleting(null); void reload() }}>关闭并刷新</button>}<button className={salaryDanger} disabled={busy} onClick={() => void remove()}>{busy ? '删除中…' : '确认删除'}</button></footer></div></SalaryConfigurationDialog>}
</div>
}