gongxiangp2/components/department-dashboard/SalaryPositionPanel.tsx

268 lines
33 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 { MARKET_INTENT_SOURCE_LABEL } from '@/lib/salary-market-intent-contract'
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, isSalaryMonth } from '@/lib/performance-salary-templates'
import { PERFORMANCE_BASELINE, monthBefore, performanceVersionLabel, performanceVersionRange, positionAtMonth, positionConfigurationHref, personnelPositions, performancePositions, positionFields, positionFieldsSchema, sharedSalaryGradeLabel, 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 => ({ personnelPositionId: null, jobGrade: '', name: '', salaryRole: 'ai-planning', description: '', dimensions: [] })
type EditorMode = 'position' | 'create-version' | 'update-version'
function PositionEditor({ position, mode, month, sources, saved, close }: {
position: SalaryPosition | null; mode: EditorMode; month: string; sources: ScoreSourceOption[]
saved: (position: SalaryPosition) => Promise<void>; close: () => void
}) {
const configuration = useSalaryConfiguration()
const parents = personnelPositions(configuration.payload?.positions ?? []).filter(item => item.id !== position?.id)
const metadataOnly = mode === 'position' && !!position?.performanceVersions
const initial = position ? { ...positionFields(position), ...(metadataOnly && { dimensions: [] }) } : empty()
const [draft, setDraft] = useState<PositionFields>(() => structuredClone(initial))
const initialMonth = mode === 'update-version' ? position!.performanceVersion!.effectiveMonth : month
const [effectiveMonth, setEffectiveMonth] = useState(initialMonth)
const [confirming, setConfirming] = useState(false)
const confirmSave = useRef<HTMLButtonElement>(null)
const [version, setVersion] = useState(position?.performanceVersion)
const [versions, setVersions] = useState(position?.performanceVersions ?? [])
const gradeCutoff = versions.find(item => !item.dimensions.length)?.effectiveMonth
const endsBeforeMonth = mode === 'update-version' ? version?.endsBeforeMonth ?? null
: versions.filter(item => item.effectiveMonth > effectiveMonth).at(-1)?.effectiveMonth ?? null
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 = effectiveMonth !== initialMonth || JSON.stringify(draft) !== JSON.stringify(initial)
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 (confirming) confirmSave.current?.focus() }, [confirming])
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) {
setConfirming(false)
setDraft(value => { const next = structuredClone(value); work(next); return next })
}
async function loadLatest() {
try {
const body = await salaryRequest<{ positions: SalaryPosition[] }>(`${POSITION_ENDPOINT}?month=${month}`)
setLatest(body.positions.find(item => item.id === position?.id) ?? null)
}
catch { setError('最新配置读取失败,草稿已保留,请重试。') }
}
async function save(event: React.FormEvent<HTMLFormElement>) {
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 })
const createsVersion = mode === 'create-version' || (!position && draft.dimensions.length > 0)
const selectedMonth = createsVersion
? String(new FormData(event.currentTarget).get('effectiveMonth') ?? '') : effectiveMonth
if (selectedMonth !== effectiveMonth) {
setEffectiveMonth(selectedMonth)
setConfirming(false)
}
if (createsVersion && !isSalaryMonth(selectedMonth)) validation.effectiveMonth = '请选择有效实施月份'
if (mode === 'create-version' && versions.some(item => item.effectiveMonth === selectedMonth)) validation.effectiveMonth = '该岗位已有此实施月份的版本'
if (mode === 'create-version' && gradeCutoff && selectedMonth >= gradeCutoff) validation.effectiveMonth = '此月份请为对应职级新增绩效版本'
if (mode !== 'position' && !draft.dimensions.length) validation.dimensions = '请至少设置一个考核维度'
setErrors(validation); setError('')
if (!result.success || Object.keys(validation).length) { requestAnimationFrame(() => { const target = form.current?.querySelector<HTMLElement>('[aria-invalid="true"]') || errorSummary.current; target?.focus(); target?.scrollIntoView?.({ block: 'center' }) }); return }
const requiresConfirmation = (mode !== 'position' || createsVersion) && selectedMonth <= currentSalaryMonth()
if (requiresConfirmation && (!confirming || selectedMonth !== effectiveMonth)) { setConfirming(true); return }
const confirmedImpact = requiresConfirmation ? { effectiveMonth: selectedMonth, endsBeforeMonth } : undefined
const { description, dimensions } = result.data
const body = mode === 'update-version'
? { operation: mode, versionId: version!.id, versionRevision: version!.revision, revision, description, dimensions, confirmedImpact }
: mode === 'create-version'
? { operation: mode, effectiveMonth: selectedMonth, copyFromVersionId: version?.id, revision, description, dimensions, confirmedImpact }
: { ...result.data, ...(position ? { revision, ...(metadataOnly && { operation: 'update-position' }) } : createsVersion ? { effectiveMonth: selectedMonth, confirmedImpact } : {}) }
setBusy(true)
try {
const savedPosition = await salaryRequest<SalaryPosition>(position ? `${POSITION_ENDPOINT}/${position.id}` : POSITION_ENDPOINT, { method: position ? 'PUT' : 'POST', body: JSON.stringify(body) })
await saved(savedPosition); close()
} catch (failure) {
setError(failure instanceof Error ? failure.message : '保存失败,草稿已保留,请重试。')
setConfirming(false)
if (failure instanceof SalaryRequestError && ['REVISION_CONFLICT', 'PERFORMANCE_IMPACT_REQUIRED'].includes(failure.code ?? '')) { 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
const latestVersion = latest?.performanceVersions?.find(item => item.id === version?.id)
return <SalaryConfigurationDialog title={mode === 'create-version' ? '新增绩效版本' : mode === 'update-version' ? '编辑绩效版本' : position ? '编辑岗位' : '新增岗位'} wide busy={busy} onClose={requestClose}>
<form ref={form} onSubmit={save} noValidate className="p-5 sm:p-6">
{!metadataOnly && <p className="mb-5 text-sm leading-6 text-[#66758b]">维度权重及每个维度内的KPI权重分别合计100%。</p>}
<fieldset disabled={busy} className="min-w-0 space-y-5">
{mode === 'position' && <><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']; value.personnelPositionId = null; value.jobGrade = '' })}>{SALARY_ROLES.map(role => <option key={role.key} value={role.key}>{role.title}</option>)}</select></label>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block text-sm font-semibold">关联人员岗位<select value={draft.personnelPositionId || ''} {...validationAttributes('personnelPositionId')} className={`${salaryInput} mt-2`} onChange={event => change(value => { value.personnelPositionId = event.target.value || null; if (!value.personnelPositionId) value.jobGrade = '' })}><option value="">独立岗位(不区分职级)</option>{parents.filter(item => item.salaryRole === draft.salaryRole).map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select>{fieldError('personnelPositionId')}</label>
<label className="block text-sm font-semibold">适用职级{draft.personnelPositionId ? ' *' : ''}<input value={draft.jobGrade || ''} disabled={!draft.personnelPositionId} maxLength={3} placeholder="例如P3、P4" {...validationAttributes('jobGrade')} className={`${salaryInput} mt-2`} onChange={event => change(value => { value.jobGrade = event.target.value.toUpperCase() })} />{fieldError('jobGrade')}</label>
</div>
<p className="text-sm leading-6 text-[#66758b]">职级方案使用关联人员岗位及适用职级匹配。</p></>}
{(mode === 'create-version' || (!position && draft.dimensions.length > 0)) && <label className="block text-sm font-semibold">实施月份 *<input name="effectiveMonth" type="month" value={effectiveMonth} autoFocus={mode === 'create-version'} min="0001-01" max="9999-12" {...validationAttributes('effectiveMonth')} className={`${salaryInput} mt-2 sm:max-w-xs`} onChange={event => { setEffectiveMonth(event.target.value); setConfirming(false) }} />{fieldError('effectiveMonth')}</label>}
{mode === 'update-version' && <p className="text-sm font-semibold">{performanceVersionLabel(version!)}</p>}
<label className="block text-sm font-semibold">{mode === 'position' ? '岗位说明' : '方案说明'}<textarea value={draft.description} autoFocus={mode === 'update-version'} maxLength={1000} rows={2} className={`${salaryInput} mt-2 resize-y`} onChange={event => change(value => { value.description = event.target.value })} /></label>
{!metadataOnly && <>
<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>
<option value="market-intent-top3">{MARKET_INTENT_SOURCE_LABEL}</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 || (mode === 'update-version' && !latestVersion) ? <p className="mt-2">该岗位或版本已移除,请关闭弹窗并刷新。</p> : <><p className="mt-2">最新配置 · {latest.name} · {latestVersion ? performanceVersionRange(latestVersion) : SALARY_ROLES.find(role => role.key === latest.salaryRole)?.title}</p><dl className="mt-3 space-y-2">{(latestVersion?.dimensions ?? 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); setVersion(latestVersion); setVersions(latest.performanceVersions ?? []); 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 border-t border-[#e2e8f0] bg-white py-4">
{confirming && <p role="status" className="mb-3 text-sm leading-6 text-[#344054]">保存将重新计算{performanceVersionRange({ effectiveMonth, endsBeforeMonth })}的薪资,请确认影响范围。</p>}
<div className="flex flex-wrap justify-end gap-3"><button type="button" className={salarySecondary} disabled={busy} onClick={confirming ? () => setConfirming(false) : requestClose}>{confirming ? '返回编辑' : '取消'}</button><button ref={confirmSave} type="submit" className={salaryPrimary} disabled={busy || conflict || !!removeTarget}>{busy ? '保存中…' : confirming ? '确认影响并保存' : mode === 'position' ? '保存岗位配置' : '保存绩效版本'}</button></div>
</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; mode?: EditorMode } | 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 [monthDraft, setMonthDraft] = useState(month)
useEffect(() => { setMonthDraft(month) }, [month])
const schemes = performancePositions(payload?.positions.map(item => positionAtMonth(item, month)) ?? [])
const position = schemes.find(item => item.id === selectedId) || schemes[0]
const version = position?.performanceVersion
const availableVersions = position?.performanceVersions?.filter(item => item.dimensions.length) ?? []
const hasGradeSchemes = payload?.positions.some(item => item.personnelPositionId === position?.id) ?? false
const gradeCutoff = position?.performanceVersions?.find(item => !item.dimensions.length)?.effectiveMonth
const canAddVersion = position?.performanceVersions && (gradeCutoff ? month < gradeCutoff : !hasGradeSchemes)
const navigate = (nextMonth: string, id = position?.id) => {
router.push(positionConfigurationHref('performance', nextMonth, id), { scroll: false })
setNotice('')
setFailure('')
}
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 query = new URLSearchParams({ month, ...(!all && { position: position!.id }) })
const response = await fetch(`${POSITION_ENDPOINT}/export?${query}`, { 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 = schemes.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">
<div className="grid w-full min-w-0 gap-3 sm:grid-cols-2 lg:max-w-2xl">
<form className="flex min-w-0 items-end gap-2" onSubmit={event => {
event.preventDefault()
const selectedMonth = String(new FormData(event.currentTarget).get('month') ?? '')
if (isSalaryMonth(selectedMonth) && selectedMonth !== month) navigate(selectedMonth)
}}>
<label className="grid min-w-0 flex-1 gap-2 text-sm font-semibold">薪资月份<input name="month" type="month" min="0001-01" max="9999-12" required value={monthDraft} className={salaryInput} onChange={event => setMonthDraft(event.target.value)} /></label>
<button type="submit" className={`${salarySecondary} shrink-0`}>查询</button>
</form>
<label className="grid min-w-0 gap-2 text-sm font-semibold">岗位<select className={salaryInput} value={position?.id || ''} onChange={event => navigate(month, event.target.value)}><option value="" disabled>请选择岗位</option>{schemes.map(item => <option key={item.id} value={item.id}>{[item.name, sharedSalaryGradeLabel(item, month)].filter(Boolean).join(' · ')}</option>)}</select></label>
</div>
<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.personnelPositionId ? `${payload?.positions.find(item => item.id === position.personnelPositionId)?.name || '人员岗位'} · ${sharedSalaryGradeLabel(position, month) ?? `职级${position.jobGrade}`} · ` : ''}{position.personnelCount}人</p>
</div>
{payload?.canEdit && <div className="flex flex-wrap gap-1"><button className={`${salaryButton} text-[#0050cb] hover:bg-[#eef6ff]`} onClick={() => setEditor({ position })}>编辑岗位</button><button className={salaryDanger} onClick={() => { setDeleting(position); setFailure('') }}>删除岗位</button></div>}
</div>
<div className="mt-4 flex flex-wrap items-end gap-3">
{!!availableVersions.length && <label className="grid w-full min-w-0 gap-2 text-sm font-semibold sm:max-w-xs">绩效版本
<select className={salaryInput} value={version?.id ?? ''} onChange={event => {
const selected = availableVersions.find(item => item.id === event.target.value)
if (selected) navigate(selected.effectiveMonth === PERFORMANCE_BASELINE ? selected.endsBeforeMonth ? monthBefore(selected.endsBeforeMonth) : month : selected.effectiveMonth)
}}><option value="" disabled>该月份暂无绩效版本</option>
{availableVersions.map(item => <option key={item.id} value={item.id}>{performanceVersionLabel(item)}</option>)}
</select>
</label>}
{payload?.canEdit && version && <button className={salarySecondary} onClick={() => setEditor({ position, mode: 'update-version' })}>编辑此版本</button>}
{payload?.canEdit && canAddVersion && <button className={salaryPrimary} onClick={() => setEditor({ position, mode: 'create-version' })}><Plus className="h-4 w-4" aria-hidden="true" />新增版本</button>}
</div>
{version && <p className="mt-3 text-sm leading-6 text-[#66758b]">适用期间 {performanceVersionRange(version)}{position.description ? ` · ${position.description}` : ''}</p>}
{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]">该月份暂无绩效方案。{payload?.canEdit && canAddVersion ? '可新增实施月份版本。' : ''}</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} mode={editor.mode ?? 'position'} month={month} sources={sources} close={() => setEditor(null)} saved={async savedPosition => {
await reload()
if (!editor.position || editor.mode === 'create-version') navigate(savedPosition.performanceVersion?.effectiveMonth ?? month, savedPosition.id)
setNotice(editor.mode ? '绩效版本已保存。' : '岗位配置已保存。')
}} />}
{deleting && <SalaryConfigurationDialog title="删除岗位" busy={busy} onClose={() => { if (!busy) setDeleting(null) }}><div className="p-5"><p className="break-words text-sm leading-6">确定删除“{deleting.name}”及其绩效配置?{deleting.personnelPositionId ? '删除后对应职级人员将显示未匹配绩效方案,人员档案保留。' : '岗位仍有人员时须先转移人员。'}</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>
}