feat(salary): calculate supervisor metrics from direct department members
This commit is contained in:
parent
e52e0d7785
commit
b3954b64e3
@ -263,3 +263,23 @@ test('核对清单只显示当前入口且不回填冲突人员的缺失调研
|
||||
expect(checklist).not.toHaveTextContent('其他主管')
|
||||
expect(screen.getByText(/调研得分取同月绩效考核的两位小数正式得分/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('主管部门交付率复用原始值明细按钮,展开聚焦标题,收起恢复触发器焦点', async () => {
|
||||
const data = managementPayload(), metric = managementPosition.dimensions[1].metrics[1]
|
||||
const row = { ...payload().roles['ai-planning'][0], values: { nickname: '主管花名', [`${metric.id}RawValue`]: 75, [`${metric.id}Score`]: 9 }, metricEvidence: {
|
||||
[metric.id]: { kind: 'department-on-time-average' as const, month: '2026-10', department: { sourceDeptId: 1, name: 'A部', path: '公司/A部' }, members: [
|
||||
{ employeeProfileId: 'a', employeeLabel: '甲', onTimeCount: 1, totalCount: 1, rate: 100, included: true },
|
||||
{ employeeProfileId: 'b', employeeLabel: '乙', onTimeCount: 5, totalCount: 10, rate: 50, included: true },
|
||||
], includedCount: 2, rawScore: 75 },
|
||||
} }
|
||||
data.roles.management.push(row); data.positionGroups[0].rows.push(row)
|
||||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||||
render(<PerformanceSalaryDetails role="management" month="2026-10" />)
|
||||
const trigger = await screen.findByRole('button', { name: '测试花名部门按时交付率计算明细' })
|
||||
expect(trigger).toHaveTextContent('75.00%')
|
||||
fireEvent.click(trigger)
|
||||
expect(screen.getByRole('heading', { name: '测试花名 · 部门按时交付率计算明细' })).toHaveFocus()
|
||||
expect(screen.getByText('按时完成5条 / 有效交付流程10条')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: '收起明细' }))
|
||||
expect(trigger).toHaveFocus(); expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
})
|
||||
|
||||
@ -6,6 +6,7 @@ import { SALARY_TEMPLATE_BLANK_ROWS, type SalaryTemplateColumn } from '@/lib/per
|
||||
import { salarySourceLabel, type SalaryDetails, type SalaryCell } 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'
|
||||
|
||||
function formatCell(value: SalaryCell | undefined, column: SalaryTemplateColumn) {
|
||||
@ -61,18 +62,23 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
|
||||
<p className="mt-2 text-sm leading-6 text-[#66758b]">所选入口暂无已配置岗位的人员薪资档案。</p>
|
||||
</div>
|
||||
) : <>
|
||||
{role === 'management' && (data?.departmentMatchIssues?.length ?? 0) > 0 && <section aria-label="主管部门待核对" className="mb-5 border-b border-[#e2e8f0] pb-4 text-sm leading-6 text-[#344054]">
|
||||
<h2 className="font-semibold">主管部门待核对</h2>
|
||||
<ul className="mt-2 space-y-1">{data?.departmentMatchIssues?.map(issue => <li key={issue.employeeProfileId} className="break-words">{issue.employeeLabel}:{issue.message}</li>)}</ul>
|
||||
</section>}
|
||||
{surveyMatchIssues.length > 0 && <section aria-label="调研关联待核对" className="mb-5 border-b border-[#e2e8f0] pb-4 text-sm leading-6 text-[#344054]">
|
||||
<h2 className="font-semibold">调研关联待核对({surveyMatchIssues.length}人)</h2>
|
||||
<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>}
|
||||
{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 detailId = `market-details-${position.id}`
|
||||
const detailId = `metric-details-${position.id}`
|
||||
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]">暂无管理岗人员,请在人员薪资配置中新增</p>}
|
||||
@ -100,7 +106,7 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
|
||||
<tr key={row.employeeProfileId}>{template.columns.map((column, index) => (
|
||||
<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}市场验证计算明细`} aria-expanded={expanded?.employeeId === row.employeeProfileId && expanded.metricId === column.key.slice(0, -8)} aria-controls={detailId}
|
||||
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}
|
||||
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)}
|
||||
@ -114,10 +120,13 @@ export default function PerformanceSalaryDetails({ role, month }: { role: Salary
|
||||
))}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{activeEvidence && activeRow && activeMetric && activeDimension && <SalaryMarketIntentDetails id={detailId} employeeLabel={activeRow.employeeLabel} evidence={activeEvidence}
|
||||
{activeEvidence && activeRow && activeMetric && activeDimension && (activeEvidence.kind === 'department-on-time-average' ? <SalaryDepartmentDeliveryDetails id={detailId} employeeLabel={activeRow.employeeLabel} evidence={activeEvidence}
|
||||
overallShare={percentageBasisPoints(activeMetric.weight) * percentageBasisPoints(activeDimension.weight) / 1e8}
|
||||
contribution={typeof activeRow.values[`${activeMetric.id}Score`] === 'number' ? activeRow.values[`${activeMetric.id}Score`] as number : null}
|
||||
close={() => { setExpanded(null); detailTrigger.current?.focus() }} />}
|
||||
close={() => { setExpanded(null); detailTrigger.current?.focus() }} /> : <SalaryMarketIntentDetails id={detailId} employeeLabel={activeRow.employeeLabel} evidence={activeEvidence}
|
||||
overallShare={percentageBasisPoints(activeMetric.weight) * percentageBasisPoints(activeDimension.weight) / 1e8}
|
||||
contribution={typeof activeRow.values[`${activeMetric.id}Score`] === 'number' ? activeRow.values[`${activeMetric.id}Score`] as number : null}
|
||||
close={() => { setExpanded(null); detailTrigger.current?.focus() }} />)}
|
||||
</section>})}
|
||||
</>}
|
||||
</div>
|
||||
|
||||
@ -0,0 +1,29 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import SalaryDepartmentDeliveryDetails from './SalaryDepartmentDeliveryDetails'
|
||||
import type { DepartmentDeliveryEvidence } from '@/lib/salary-department-contract'
|
||||
|
||||
const evidence: DepartmentDeliveryEvidence = {
|
||||
kind: 'department-on-time-average', month: '2026-10', department: { sourceDeptId: 1, name: '品牌创意A部', path: '公司/A部' }, includedCount: 2, rawScore: 50,
|
||||
members: [
|
||||
{ employeeProfileId: 'a', employeeLabel: '主管', onTimeCount: 1, totalCount: 1, rate: 100, included: true },
|
||||
{ employeeProfileId: 'b', employeeLabel: '未建薪资档案成员', onTimeCount: 0, totalCount: 2, rate: 0, included: true },
|
||||
{ employeeProfileId: 'c', employeeLabel: '无流程成员', onTimeCount: 0, totalCount: 0, rate: null, included: false },
|
||||
],
|
||||
}
|
||||
test('完整显示直属成员、0%、无数据排除及未舍入公式,明细标题获得键盘焦点', () => {
|
||||
render(<SalaryDepartmentDeliveryDetails id="delivery" employeeLabel="主管" evidence={evidence} overallShare={.12} contribution={6} close={jest.fn()} />)
|
||||
expect(screen.getByText(/直属在职成员3人,2人参与平均/)).toBeInTheDocument()
|
||||
expect(screen.getAllByRole('listitem')).toHaveLength(3)
|
||||
expect(screen.getByText('个人按时交付率:0.00%')).toBeInTheDocument()
|
||||
expect(screen.getByText('无有效交付流程,不参与平均')).toBeInTheDocument()
|
||||
expect(screen.getByText('50.00%')).toBeInTheDocument()
|
||||
expect(screen.getByText('6.00 分')).toBeInTheDocument()
|
||||
expect(screen.getByRole('heading', { name: '主管 · 部门按时交付率计算明细' })).toHaveFocus()
|
||||
})
|
||||
test('全无数据或主管部门无法关联时明确留空,不展示0%均值', () => {
|
||||
const { rerender } = render(<SalaryDepartmentDeliveryDetails id="delivery" employeeLabel="主管" evidence={{ ...evidence, includedCount: 0, rawScore: null, members: [] }} overallShare={.12} contribution={null} close={jest.fn()} />)
|
||||
expect(screen.getByText(/本部门成员当月均无有效交付流程/)).toBeInTheDocument()
|
||||
expect(screen.queryByText('0.00%')).not.toBeInTheDocument()
|
||||
rerender(<SalaryDepartmentDeliveryDetails id="delivery" employeeLabel="主管" evidence={{ ...evidence, department: null, includedCount: 0, rawScore: null, members: [] }} overallShare={.12} contribution={null} close={jest.fn()} />)
|
||||
expect(screen.getByText(/无法唯一确认主管的组织架构主部门/)).toBeInTheDocument()
|
||||
})
|
||||
@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { SALARY_DEPARTMENT_UNRESOLVED, type DepartmentDeliveryEvidence } from '@/lib/salary-department-contract'
|
||||
import { salaryMonthLabel } from '@/lib/performance-salary-templates'
|
||||
import { salarySecondary } from './SalaryConfigurationUI'
|
||||
|
||||
export default function SalaryDepartmentDeliveryDetails({ id, employeeLabel, evidence, overallShare, contribution, close }: {
|
||||
id: string; employeeLabel: string; evidence: DepartmentDeliveryEvidence; overallShare: number; contribution: number | null; close: () => void
|
||||
}) {
|
||||
const heading = useRef<HTMLHeadingElement>(null)
|
||||
useEffect(() => { heading.current?.focus({ preventScroll: true }); heading.current?.scrollIntoView?.({ block: 'start' }) }, [evidence, employeeLabel])
|
||||
return <section id={id} aria-labelledby={`${id}-title`} className="mt-4 border border-[#e2e8f0] bg-[#f8fafc] p-4 sm:p-5">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0"><h3 ref={heading} tabIndex={-1} id={`${id}-title`} className="scroll-mt-24 rounded text-base font-bold text-[#101828] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">{employeeLabel} · 部门按时交付率计算明细</h3>
|
||||
<p className="mt-2 break-words text-sm leading-6 text-[#66758b]">考核月份:{salaryMonthLabel(evidence.month)}。{evidence.department ? `${evidence.department.name}直属在职成员${evidence.members.length}人,${evidence.includedCount}人参与平均。` : SALARY_DEPARTMENT_UNRESOLVED}</p>
|
||||
</div>
|
||||
<button type="button" className={salarySecondary} onClick={close}>收起明细</button>
|
||||
</div>
|
||||
{evidence.includedCount === 0 && evidence.department && <p className="mt-4 text-sm leading-6 text-[#344054]">本部门成员当月均无有效交付流程,按时交付率及该项考核得分显示“——”。</p>}
|
||||
<ol className="mt-4 divide-y divide-[#e2e8f0]">{evidence.members.map(member => <li key={member.employeeProfileId} className="grid min-w-0 gap-2 py-4 text-sm leading-6 sm:grid-cols-[minmax(0,1fr)_auto]">
|
||||
<div className="min-w-0"><p className="break-words font-semibold text-[#101828]">{member.employeeLabel}</p><p className="text-[#66758b]">按时完成{member.onTimeCount}条 / 有效交付流程{member.totalCount}条</p></div>
|
||||
<div className="sm:text-right"><p className="font-semibold tabular-nums text-[#101828]">个人按时交付率:{member.rate === null ? '——' : `${member.rate.toFixed(2)}%`}</p><p className="text-[#66758b]">{member.included ? '参与平均' : '无有效交付流程,不参与平均'}</p></div>
|
||||
</li>)}</ol>
|
||||
<dl className="mt-3 grid gap-3 border-t border-[#e2e8f0] pt-4 text-sm sm:grid-cols-2">
|
||||
<div><dt className="text-[#66758b]">部门成员交付率均值</dt><dd className="mt-1 font-semibold tabular-nums">{evidence.rawScore === null ? '——' : `${evidence.rawScore.toFixed(2)}%`}</dd></div>
|
||||
<div><dt className="text-[#66758b]">考核得分(综合占比{(overallShare * 100).toFixed(2)}%)</dt><dd className="mt-1 font-semibold tabular-nums">{contribution === null ? '——' : `${contribution.toFixed(2)} 分`}</dd></div>
|
||||
</dl>
|
||||
<p className="mt-4 text-sm leading-6 text-[#66758b]">部门交付率=各有效成员的个人按时交付率之和÷有效成员人数,每人等权。按未舍入的个人比例取平均;0%正常参与,无有效流程的成员不计入平均。使用最新主部门和在职状态,仅统计直属成员,包含主管,不要求已建立薪资档案。有效流程、审核月份和超时免扣判定沿用个人交付率口径。</p>
|
||||
</section>
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { useEffect, useRef } from 'react'
|
||||
import { MARKET_INTENT_EXCLUSION_LABELS, type MarketIntentEvidence } from '@/lib/salary-market-intent-contract'
|
||||
import { salarySecondary } from './SalaryConfigurationUI'
|
||||
import { salaryMonthLabel } from '@/lib/performance-salary-templates'
|
||||
import { SALARY_DEPARTMENT_UNRESOLVED } from '@/lib/salary-department-contract'
|
||||
|
||||
const percent = (value: number | null) => value === null ? '——' : `${(value * 100).toFixed(2)}%`
|
||||
const statusLabels = { selected: '已入选', 'valid-not-selected': '有效但未入选', invalid: '无效' }
|
||||
@ -17,16 +18,18 @@ export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence,
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0"><h3 ref={heading} tabIndex={-1} id={`${id}-title`} className="scroll-mt-24 rounded text-base font-bold text-[#101828] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#5a9ce6]">{employeeLabel} · 市场验证计算明细</h3>
|
||||
<p className="mt-2 text-sm leading-6 text-[#66758b]">考核月份:{salaryMonthLabel(evidence.month)},按该月完结流程关联的商品ID计算。共{evidence.candidateCount}条关联记录,{evidence.validCount}条有效环比,选取最高{evidence.selected.length}条。</p>
|
||||
{evidence.departmentScope && <p className="mt-2 break-words text-sm leading-6 text-[#66758b]">{evidence.departmentScope.department ? `${evidence.departmentScope.department.name}直属在职策划成员${evidence.departmentScope.members.length}人:${evidence.departmentScope.members.map(member => member.employeeLabel).join('、') || '暂无成员'}。合并全部记录并按流程×商品ID去重后统一取最高3条。` : SALARY_DEPARTMENT_UNRESOLVED}</p>}
|
||||
</div>
|
||||
<button type="button" className={salarySecondary} onClick={close}>收起明细</button>
|
||||
</div>
|
||||
{evidence.selected.length === 0 && <p className="mt-4 text-sm leading-6 text-[#344054]">暂无有效意向率环比,市场验证得分显示“——”。{evidence.candidateCount === 0 && `${salaryMonthLabel(evidence.month)}参与的有效已完结美术流程没有可关联的商品ID。`}</p>}
|
||||
{evidence.selected.length === 0 && <p className="mt-4 text-sm leading-6 text-[#344054]">暂无有效意向率环比,市场验证得分显示“——”。{evidence.candidateCount === 0 && `${salaryMonthLabel(evidence.month)}${evidence.departmentScope ? '本部门策划成员' : ''}参与的有效已完结美术流程没有可关联的商品ID。`}</p>}
|
||||
{evidence.selected.length > 0 && evidence.selected.length < 3 && <p className="mt-3 text-sm leading-6 text-[#66758b]">有效记录不足3条,按实际{evidence.selected.length}条取平均。</p>}
|
||||
{evidence.records.length > 0 &&
|
||||
<ol className="mt-4 divide-y divide-[#e2e8f0]">
|
||||
{evidence.records.map((item, index) => <li key={item.key} className="grid min-w-0 gap-3 py-4 sm:grid-cols-[minmax(0,1fr)_auto]">
|
||||
<div className="min-w-0 text-sm leading-6"><div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"><p className="min-w-0 break-all font-semibold text-[#101828]">{index + 1}. {item.approvalNumber || item.workflowId}</p><span className={item.status === 'selected' ? 'font-semibold text-[#0050cb]' : 'text-[#344054]'}>{statusLabels[item.status]}</span></div><p className="break-all text-[#344054]">{item.brand} · 商品ID {item.productId}</p><p className="text-[#66758b]">完结日期:{new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.completedAt))}</p>
|
||||
<div className="flex flex-col text-[#66758b] sm:flex-row sm:flex-wrap sm:gap-x-4"><p>7日均值 {percent(item.sevenDayIntentRate)}</p><p>15日均值 {percent(item.fifteenDayIntentRate)}</p></div>
|
||||
{item.participants && <p className="break-words text-[#66758b]">本部门参与成员:{item.participants.map(member => member.employeeLabel).join('、')}</p>}
|
||||
{item.invalidReason && <p className="mt-1 text-[#344054]">无效原因:{MARKET_INTENT_EXCLUSION_LABELS[item.invalidReason]}</p>}
|
||||
</div>
|
||||
<div className="text-sm sm:text-right"><p className="font-semibold tabular-nums text-[#101828]">意向率环比 {percent(item.intentRateChange)}</p>
|
||||
|
||||
33
lib/__tests__/connect-salary-management-market.test.ts
Normal file
33
lib/__tests__/connect-salary-management-market.test.ts
Normal file
@ -0,0 +1,33 @@
|
||||
/** @jest-environment node */
|
||||
import { prisma } from '../prisma'
|
||||
import { requireSalaryAccess } from '../personnel-salary'
|
||||
import { updateSalaryPosition } from '../salary-positions'
|
||||
import { connectManagementMarketIntent, MANAGEMENT_MARKET_METRIC_ID } from '../connect-salary-management-market'
|
||||
import { INITIAL_SALARY_POSITIONS } from '../salary-position-seeds'
|
||||
jest.mock('../prisma', () => ({ prisma: { salaryPositionConfig: { findUnique: jest.fn() }, salaryPositionConfigAudit: { findMany: jest.fn() } } }))
|
||||
jest.mock('../personnel-salary', () => ({ ...jest.requireActual('../personnel-salary'), requireSalaryAccess: jest.fn() }))
|
||||
jest.mock('../salary-positions', () => ({ ...jest.requireActual('../salary-positions'), updateSalaryPosition: jest.fn() }))
|
||||
const db = prisma as unknown as Record<string, any>, update = updateSalaryPosition as jest.Mock
|
||||
const before = () => ({ ...structuredClone(INITIAL_SALARY_POSITIONS[0].value), id: INITIAL_SALARY_POSITIONS[0].id, revision: 3, updatedAt: new Date(), deletedAt: null })
|
||||
beforeEach(() => { jest.resetAllMocks(); db.salaryPositionConfig.findUnique.mockResolvedValue(before()); db.salaryPositionConfigAudit.findMany.mockResolvedValue([]); update.mockImplementation(async (_id, input) => ({ revision: input.revision + 1 })) })
|
||||
test('只接入稳定市场指标,保留说明、权重及主管专用视觉来源;正常审计版本3→4', async () => {
|
||||
const row = before(); row.dimensions[0].metrics[0].source = { kind: 'survey', templateCode: 'supervisor-specific' }; db.salaryPositionConfig.findUnique.mockResolvedValue(row)
|
||||
expect(await connectManagementMarketIntent('admin', 3)).toEqual({ changed: true, revision: 4 })
|
||||
const input = update.mock.calls[0][1]
|
||||
expect(input.revision).toBe(3)
|
||||
const metric = input.dimensions.flatMap((d: any) => d.metrics).find((m: any) => m.id === MANAGEMENT_MARKET_METRIC_ID)
|
||||
expect(metric.source).toEqual({ kind: 'market-intent-top3' }); metric.source = { kind: 'unavailable' }
|
||||
expect(input.dimensions).toEqual(row.dimensions)
|
||||
})
|
||||
test('重复执行跳过;人工改回、来源改变、版本冲突及权限拒绝不保存', async () => {
|
||||
const applied = before(); applied.dimensions[1].metrics[0].source = { kind: 'market-intent-top3' }; db.salaryPositionConfig.findUnique.mockResolvedValue(applied)
|
||||
expect(await connectManagementMarketIntent('admin', 3)).toEqual({ changed: false, revision: 3 })
|
||||
db.salaryPositionConfig.findUnique.mockResolvedValue(before()); db.salaryPositionConfigAudit.findMany.mockResolvedValue([{ after: applied }])
|
||||
await expect(connectManagementMarketIntent('admin', 3)).rejects.toMatchObject({ status: 409 })
|
||||
await expect(connectManagementMarketIntent('admin', 2)).rejects.toMatchObject({ status: 409 })
|
||||
const manual = before(); manual.dimensions[1].metrics[0].source = { kind: 'survey', templateCode: 'manual' }; db.salaryPositionConfig.findUnique.mockResolvedValue(manual)
|
||||
await expect(connectManagementMarketIntent('admin', 3)).rejects.toMatchObject({ status: 409 })
|
||||
;(requireSalaryAccess as jest.Mock).mockRejectedValue({ status: 403 })
|
||||
await expect(connectManagementMarketIntent('reader', 3)).rejects.toMatchObject({ status: 403 })
|
||||
expect(update).not.toHaveBeenCalled()
|
||||
})
|
||||
@ -6,8 +6,9 @@ import { getPerformanceSalaryDetails } from '../performance-salary-details'
|
||||
import { readSalaryWorkflowMetrics } from '../performance-salary-workflows'
|
||||
import { readSalaryMarketIntent } from '../salary-market-intent'
|
||||
import { INITIAL_SALARY_POSITIONS } from '../salary-position-seeds'
|
||||
import { summarizeMarketIntent, type MarketIntentCandidate } from '../salary-market-intent-contract'
|
||||
|
||||
jest.mock('../prisma', () => ({ prisma: { $transaction: jest.fn(), salaryPositionConfig: { findMany: jest.fn() }, performanceSurveyEmployeeProfile: { findMany: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, performanceSurveyResponse: { count: jest.fn(), findMany: jest.fn() } } }))
|
||||
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('../personnel-salary', () => ({ requireSalaryAccess: jest.fn() }))
|
||||
jest.mock('../performance-salary-workflows', () => ({ readSalaryWorkflowMetrics: jest.fn() }))
|
||||
jest.mock('../salary-market-intent', () => ({ readSalaryMarketIntent: jest.fn() }))
|
||||
@ -23,10 +24,11 @@ beforeEach(() => {
|
||||
db.$transaction.mockImplementation((work: any) => work(prisma))
|
||||
db.performanceSurveyResponse.count.mockResolvedValue(0)
|
||||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 80), response('p1', 'visual_brand_tone', 100), response('p1', 'work_cooperation', 60), response('p1', 'project_result_validation', 100)])
|
||||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'HR名字' }, { id: 'not-configured' }])
|
||||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'HR名字', employmentState: 'ACTIVE', departmentPath: '公司/配置部门' }, { id: 'not-configured' }])
|
||||
db.organizationUnit.findMany.mockResolvedValue([{ sourceDeptId: 1, name: '配置部门', path: '公司/配置部门' }])
|
||||
db.salaryPositionConfig.findMany.mockResolvedValue(positions())
|
||||
db.personnelSalaryBase.findMany.mockResolvedValue([{ positionId: 'job1', employeeProfileId: 'p1', name: '档案名字', flowerName: '档案花名', department: '配置部门', brand: '自由品牌', baseSalary: new Prisma.Decimal('100.01'), gradeSalary: new Prisma.Decimal('20'), performanceSalary: new Prisma.Decimal('30') }])
|
||||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), onTimeRates: new Map([['p1', 90]]) })
|
||||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), deliveryCounts: new Map([['p1', { onTime: 9, total: 10 }]]), onTimeRates: new Map([['p1', 90]]) })
|
||||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p1', { rawScore: 100, selected: [], averageChange: 0, validCount: 1 }]]))
|
||||
})
|
||||
afterAll(() => { Object.assign(process.env, { NODE_ENV: oldEnv }); delete process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK })
|
||||
@ -92,9 +94,10 @@ test('原始零分正常保留,零权重缺失不阻断,贡献与总分不
|
||||
|
||||
test.each(['ai-planning', 'photography', 'spatial-visual', 'management', 'ai-technical'])('%s统一按表中贡献之和、两位系数计算当月薪资', async salaryRole => {
|
||||
const jobs = positions(); jobs[1].salaryRole = salaryRole
|
||||
if (salaryRole === 'management') jobs[1].dimensions[1].metrics[0].source = { kind: 'survey', templateCode: 'project_result_validation' }
|
||||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 88.885), response('p1', 'work_cooperation', 88.885)])
|
||||
workflow.mockResolvedValue({ sourceMonth: '2026-09', points: new Map([['p1', 71]]), onTimeRates: new Map([['p1', 88.885]]) })
|
||||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 88.885), response('p1', 'work_cooperation', 88.885), response('p1', 'project_result_validation', 88.885)])
|
||||
workflow.mockResolvedValue({ sourceMonth: '2026-09', points: new Map([['p1', 71]]), deliveryCounts: new Map([['p1', { onTime: 88885, total: 100000 }]]), onTimeRates: new Map([['p1', 88.885]]) })
|
||||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p1', { rawScore: 88.885, selected: [] }]]))
|
||||
const data = await getPerformanceSalaryDetails('reader', '2026-09')
|
||||
const row = Object.values(data.roles).flat()[0]
|
||||
@ -183,3 +186,44 @@ test('主管终评102先按正式规则汇总,自评103及其他人员109不
|
||||
expect(data.roles.management[0].values[`${metric.id}RawValue`]).toBeNull()
|
||||
expect(data.surveyMatchIssues).toEqual([])
|
||||
})
|
||||
|
||||
test('主管两项使用主部门汇总;批量读取包含未匹配职级的策划成员,其他部门隔离', async () => {
|
||||
const jobs = positions()
|
||||
jobs[0].dimensions[0].weight = '50'; jobs[0].dimensions[1].weight = '40'
|
||||
jobs[0].dimensions[1].metrics[0].source = { kind: 'market-intent-top3' }
|
||||
jobs[0].dimensions[1].metrics[1].weight = '30'; jobs[0].dimensions[1].metrics[2].weight = '30'
|
||||
jobs[1].dimensions = []
|
||||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||||
const supervisor = { ...(await db.personnelSalaryBase.findMany())[0], id: 'manager-base', positionId: 'job0' }
|
||||
db.personnelSalaryBase.findMany.mockResolvedValue([supervisor, ...['p2', 'p3', 'other'].map(id => ({ ...supervisor, id: `base-${id}`, employeeProfileId: id, name: id, flowerName: id, positionId: 'job1', jobGrade: '' }))])
|
||||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([
|
||||
{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'p1', employmentState: 'ACTIVE', departmentPath: '公司/配置部门' },
|
||||
...['p2', 'p3', 'video'].map(id => ({ id, displayName: id, realName: id, employmentState: 'ACTIVE', departmentPath: '公司/配置部门' })),
|
||||
{ id: 'other', displayName: 'other', employmentState: 'ACTIVE', departmentPath: '公司/其他部门' },
|
||||
])
|
||||
db.organizationUnit.findMany.mockResolvedValue([{ sourceDeptId: 1, name: '配置部门', path: '公司/配置部门' }, { sourceDeptId: 2, name: '其他部门', path: '公司/其他部门' }])
|
||||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), onTimeRates: new Map([['p1', 100]]), deliveryCounts: new Map([['p1', { onTime: 1, total: 1 }], ['p2', { onTime: 5, total: 10 }], ['other', { onTime: 0, total: 10 }]]) })
|
||||
const candidate = (key: string, change: number): MarketIntentCandidate => ({ key, workflowId: key, approvalNumber: key, productId: '123456', brand: '测试', completedAt: '2026-09-01T00:00:00Z', invalidReason: null, intentRateChange: change, sevenDayIntentRate: .1, fifteenDayIntentRate: .1 * (1 + change) })
|
||||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p2', summarizeMarketIntent('2026-09', [candidate('shared', .12), candidate('a', .10)])], ['p3', summarizeMarketIntent('2026-09', [candidate('shared', .12), candidate('b', .11)])]]))
|
||||
const data = await getPerformanceSalaryDetails('reader', '2026-10'), row = data.roles.management[0]
|
||||
const marketId = jobs[0].dimensions[1].metrics[0].id, deliveryId = jobs[0].dimensions[1].metrics[1].id
|
||||
expect(readSalaryMarketIntent).toHaveBeenCalledTimes(1)
|
||||
expect(new Set((readSalaryMarketIntent as jest.Mock).mock.calls[0][2])).toEqual(new Set(['p2', 'p3']))
|
||||
expect(row.values[`${marketId}RawValue`]).toBe(111)
|
||||
expect(row.values[`${marketId}Score`]).toBe(17.76)
|
||||
expect(row.values[`${deliveryId}RawValue`]).toBe(75)
|
||||
expect(row.values[`${deliveryId}Score`]).toBe(9)
|
||||
expect(row.metricEvidence?.[marketId]).toMatchObject({ month: '2026-09', candidateCount: 3, departmentScope: { members: expect.any(Array) } })
|
||||
expect(row.metricEvidence?.[deliveryId]).toMatchObject({ month: '2026-10', includedCount: 2, members: expect.arrayContaining([expect.objectContaining({ employeeProfileId: 'video', included: false })]) })
|
||||
expect(data.roles['ai-planning'].every(p => p.performanceMatch === 'unmatched')).toBe(true)
|
||||
expect(data.departmentMatchIssues).toEqual([])
|
||||
})
|
||||
|
||||
test('主管组织归属不明时部门指标留空并提示,不能使用薪资部门文本或个人交付率代替', async () => {
|
||||
const jobs = positions(), base = { ...(await db.personnelSalaryBase.findMany())[0], positionId: 'job0' }
|
||||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs); db.personnelSalaryBase.findMany.mockResolvedValue([base])
|
||||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'p1', employmentState: 'ACTIVE' }])
|
||||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||||
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('主部门') })])
|
||||
})
|
||||
|
||||
@ -30,6 +30,7 @@ test('按审核节点月份统计个人积分和未超时率,排除发起人
|
||||
expect(september.sourceMonth).toBe('2026-09')
|
||||
expect(september.points.has('worker')).toBe(true)
|
||||
expect(september.onTimeRates.get('worker')).toBe(50)
|
||||
expect(september.deliveryCounts.get('worker')).toEqual({ onTime: 1, total: 2 })
|
||||
expect(september.points.has('manager')).toBe(false)
|
||||
expect(september.onTimeRates.has('manager')).toBe(false)
|
||||
expect(september.onTimeRates.has('requester')).toBe(false)
|
||||
|
||||
65
lib/__tests__/salary-department-metrics.test.ts
Normal file
65
lib/__tests__/salary-department-metrics.test.ts
Normal file
@ -0,0 +1,65 @@
|
||||
/** @jest-environment node */
|
||||
import { buildSalaryDepartmentScopes, summarizeDepartmentDelivery, summarizeDepartmentMarketIntent } from '../salary-department-metrics'
|
||||
import { summarizeMarketIntent, type MarketIntentCandidate } from '../salary-market-intent-contract'
|
||||
import { calculatePositionScore } from '../salary-position-contract'
|
||||
|
||||
const units = [{ sourceDeptId: 1, name: 'A部', path: '公司/A部' }, { sourceDeptId: 2, name: 'B部', path: '公司/B部' }, { sourceDeptId: 3, name: 'A部下级', path: '公司/A部/下级' }]
|
||||
const person = (id: string, department = 1, employmentState = 'ACTIVE') => ({ id, displayName: id, flowerName: id, employmentState, departmentMemberships: [{ sourceDeptId: String(department), isPrimary: true }] })
|
||||
const people = [person('manager'), person('p1'), person('p2'), person('no-salary'), person('other', 2), person('child', 3), person('resigned', 1, 'RESIGNED'), person('unknown', 1, 'UNKNOWN'), { ...person('secondary', 2), departmentMemberships: [{ sourceDeptId: '2', isPrimary: true }, { sourceDeptId: '1', isPrimary: false }] }]
|
||||
const scopes = () => buildSalaryDepartmentScopes(['manager'], people, units, new Set(['p1', 'p2', 'other', 'child', 'resigned'])).get('manager')!
|
||||
const record = (key: string, change: number): MarketIntentCandidate => ({ key, workflowId: key.split(':')[0], productId: 'same-product', approvalNumber: key, brand: '测试', completedAt: '2026-08-31T16:00:00Z', invalidReason: null, intentRateChange: change, sevenDayIntentRate: .1, fifteenDayIntentRate: .1 * (1 + change) })
|
||||
|
||||
test('稳定主部门只取直属在职人员,排除兼任、子部门、离职及未知状态,改名不影响范围', () => {
|
||||
const scope = scopes()
|
||||
expect(scope.members.map(p => p.employeeProfileId).sort()).toEqual(['manager', 'no-salary', 'p1', 'p2'])
|
||||
expect(scope.planners.map(p => p.employeeProfileId).sort()).toEqual(['p1', 'p2'])
|
||||
const renamed = buildSalaryDepartmentScopes(['manager'], people, units.map(u => ({ ...u, name: '更名', path: u.path.replace('公司', '新公司') })), new Set(['p1']))
|
||||
expect(renamed.get('manager')!.department?.sourceDeptId).toBe(1)
|
||||
expect(renamed.get('manager')!.members).toEqual(scope.members)
|
||||
})
|
||||
test('主管没有唯一主部门时两项留空,不能回退成个人分数或用部门名称猜测', () => {
|
||||
const scope = buildSalaryDepartmentScopes(['manager'], [{ ...person('manager'), departmentMemberships: [{ sourceDeptId: '1' }, { sourceDeptId: '2' }] }], units, new Set()).get('manager')!
|
||||
expect(scope).toEqual({ department: null, members: [], planners: [] })
|
||||
expect(summarizeDepartmentDelivery('2026-10', scope, new Map([['manager', { onTime: 1, total: 1 }]]))).toMatchObject({ rawScore: null, includedCount: 0 })
|
||||
expect(summarizeDepartmentMarketIntent('2026-09', scope, new Map())).toMatchObject({ rawScore: null, departmentScope: { department: null } })
|
||||
})
|
||||
test('1/1与5/10等权均值75%,无数据不平均,非薪资成员及0%正常计入', () => {
|
||||
const counts = new Map([['manager', { onTime: 1, total: 1 }], ['p1', { onTime: 5, total: 10 }], ['other', { onTime: 0, total: 10 }]])
|
||||
const first = summarizeDepartmentDelivery('2026-10', scopes(), counts)
|
||||
expect(first).toMatchObject({ month: '2026-10', includedCount: 2, rawScore: 75 })
|
||||
expect(first.members.find(p => p.employeeProfileId === 'p2')).toMatchObject({ rate: null, included: false, totalCount: 0 })
|
||||
counts.set('no-salary', { onTime: 0, total: 2 })
|
||||
const withZero = summarizeDepartmentDelivery('2026-10', scopes(), counts)
|
||||
expect(withZero.rawScore).toBe(50)
|
||||
expect(withZero.members.find(p => p.employeeProfileId === 'no-salary')).toMatchObject({ included: true, rate: 0 })
|
||||
expect(summarizeDepartmentDelivery('2026-10', scopes(), new Map()).rawScore).toBeNull()
|
||||
})
|
||||
test('个人比例不提前舍入,部门最终贡献仍由岗位两层权重计算', () => {
|
||||
const evidence = summarizeDepartmentDelivery('2026-08', scopes(), new Map([['manager', { onTime: 1, total: 6 }], ['p1', { onTime: 1, total: 7 }]]))
|
||||
expect(evidence.rawScore).toBeCloseTo((100 / 6 + 100 / 7) / 2, 12)
|
||||
const result = calculatePositionScore([{ id: 'd', name: '定量', weight: '40', metrics: [{ id: 'on-time', name: '按时', description: '', weight: '30', source: { kind: 'on-time' } }] }], { 'on-time': evidence.rawScore })
|
||||
expect(result.contributions['on-time']).toBe(1.86)
|
||||
})
|
||||
test('合并全部关联记录后去重并统一取前三,完整保留未入选与无效记录及多人参与依据', () => {
|
||||
const shared = record('flow1:same-product', .12)
|
||||
const a = summarizeMarketIntent('2026-09', [shared, record('a2', .10), record('a3', .09), record('a4', .08)])
|
||||
const b = summarizeMarketIntent('2026-09', [shared, record('flow2:same-product', .11), { ...record('invalid', 0), invalidReason: 'no-source-data', intentRateChange: null }])
|
||||
const result = summarizeDepartmentMarketIntent('2026-09', scopes(), new Map([['p1', a], ['p2', b], ['other', summarizeMarketIntent('2026-09', [record('other', 99)])]]))
|
||||
expect(result).toMatchObject({ candidateCount: 6, validCount: 5, rawScore: 111, excludedCounts: { 'no-source-data': 1 } })
|
||||
expect(result.averageChange).toBeCloseTo(.11, 12)
|
||||
expect(result.records).toHaveLength(6)
|
||||
expect(result.selected.map(item => item.key)).toEqual(['flow1:same-product', 'flow2:same-product', 'a2'])
|
||||
expect(result.records[0].participants?.map(p => p.employeeProfileId).sort()).toEqual(['p1', 'p2'])
|
||||
expect(a.records[0].participants).toBeUndefined()
|
||||
expect(result.records.filter(item => item.status === 'valid-not-selected')).toHaveLength(2)
|
||||
})
|
||||
test('不足3条、负环比、0%及全无效沿用原映射,8.74%在主管16%占比下得17.40', () => {
|
||||
const personal = new Map([['p1', summarizeMarketIntent('2026-09', [record('x', .0874)])]])
|
||||
const result = summarizeDepartmentMarketIntent('2026-09', scopes(), personal)
|
||||
expect(result.rawScore).toBeCloseTo(108.74)
|
||||
expect(calculatePositionScore([{ id: 'd', name: '定量', weight: '40', metrics: [{ id: 'market', name: '市场', description: '', weight: '40', source: { kind: 'market-intent-top3' } }] }], { market: result.rawScore }).contributions.market).toBe(17.4)
|
||||
personal.set('p1', summarizeMarketIntent('2026-09', [record('zero', 0), record('negative', -.2)]))
|
||||
expect(summarizeDepartmentMarketIntent('2026-09', scopes(), personal).rawScore).toBe(90)
|
||||
personal.set('p1', summarizeMarketIntent('2026-09', [{ ...record('invalid', 0), invalidReason: 'zero-baseline', intentRateChange: null }]))
|
||||
expect(summarizeDepartmentMarketIntent('2026-09', scopes(), personal)).toMatchObject({ rawScore: null, candidateCount: 1, validCount: 0 })
|
||||
})
|
||||
@ -22,7 +22,7 @@ beforeEach(() => {
|
||||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['employee', { rawScore: 100 }]]))
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(work => work({
|
||||
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'] } } } } }))) },
|
||||
performanceSurveyEmployeeProfile: { findMany: async () => [{ id: 'employee', realName: '测试', flowerName: '测试' }] }, personnelSalaryBase: { findMany: async () => [base()] }, salaryPositionConfig: { findMany: async () => positions },
|
||||
organizationUnit: { findMany: async () => [] }, performanceSurveyEmployeeProfile: { findMany: async () => [{ id: 'employee', realName: '测试', flowerName: '测试' }] }, personnelSalaryBase: { findMany: async () => [base()] }, salaryPositionConfig: { findMany: async () => positions },
|
||||
}))
|
||||
})
|
||||
test('人员入口只含父岗,绩效入口只含职级方案;匹配稳定ID,不按岗位名推断', () => {
|
||||
|
||||
29
lib/connect-salary-management-market.ts
Normal file
29
lib/connect-salary-management-market.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { prisma } from './prisma'
|
||||
import { requireSalaryAccess, SalaryError } from './personnel-salary'
|
||||
import { INITIAL_SALARY_POSITIONS } from './salary-position-seeds'
|
||||
import { positionFields, type SalaryPosition } from './salary-position-contract'
|
||||
import { serializePosition, updateSalaryPosition } from './salary-positions'
|
||||
|
||||
export const MANAGEMENT_MARKET_POSITION_ID = INITIAL_SALARY_POSITIONS[0].id
|
||||
export const MANAGEMENT_MARKET_METRIC_ID = INITIAL_SALARY_POSITIONS[0].value.dimensions[1].metrics[0].id
|
||||
|
||||
export function managementMarketFields(position: SalaryPosition) {
|
||||
const fields = structuredClone(positionFields(position))
|
||||
const metric = fields.dimensions.flatMap(d => d.metrics).find(m => m.id === MANAGEMENT_MARKET_METRIC_ID)
|
||||
if (!metric || !['unavailable', 'market-intent-top3'].includes(metric.source.kind)) throw new SalaryError('主管市场验证指标已被移除或人工调整,未覆盖配置。', 409)
|
||||
metric.source = { kind: 'market-intent-top3' }
|
||||
return fields
|
||||
}
|
||||
|
||||
/** Explicit source-only repair through the existing permission, revision and audit path. */
|
||||
export async function connectManagementMarketIntent(actorUserId: string, expectedRevision: number) {
|
||||
await requireSalaryAccess(actorUserId, true)
|
||||
const row = await prisma.salaryPositionConfig.findUnique({ where: { id: MANAGEMENT_MARKET_POSITION_ID } })
|
||||
if (!row || row.deletedAt || row.revision !== expectedRevision) throw new SalaryError('主管配置已变化,请重新核对版本。', 409)
|
||||
const position = serializePosition(row), fields = managementMarketFields(position)
|
||||
if (position.dimensions.flatMap(d => d.metrics).find(m => m.id === MANAGEMENT_MARKET_METRIC_ID)?.source.kind === 'market-intent-top3') return { changed: false, revision: row.revision }
|
||||
const audits = await prisma.salaryPositionConfigAudit.findMany({ where: { positionId: row.id }, select: { after: true } })
|
||||
if (audits.some(audit => (audit.after as unknown as typeof fields | null)?.dimensions?.some(d => d.metrics.some(m => m.id === MANAGEMENT_MARKET_METRIC_ID && m.source.kind === 'market-intent-top3')))) throw new SalaryError('主管市场验证曾接入且已有后续调整,未覆盖配置。', 409)
|
||||
const saved = await updateSalaryPosition(row.id, { ...fields, revision: expectedRevision }, actorUserId)
|
||||
return { changed: true, revision: saved.revision }
|
||||
}
|
||||
@ -2,6 +2,7 @@ import type { SalaryRole } from './performance-salary-roles'
|
||||
import type { SalaryPosition } from './salary-position-contract'
|
||||
import type { SalaryTemplate } from './performance-salary-templates'
|
||||
import type { MarketIntentEvidence } from './salary-market-intent-contract'
|
||||
import type { DepartmentDeliveryEvidence } from './salary-department-contract'
|
||||
import { salaryMonthLabel } from './performance-salary-templates'
|
||||
import type { SurveyMatchReason } from './salary-survey-scores'
|
||||
|
||||
@ -13,7 +14,7 @@ export type SalaryDetailRow = {
|
||||
positionGroupCode: string
|
||||
values: Record<string, SalaryCell>
|
||||
metrics: Record<string, number | null>
|
||||
metricEvidence?: Record<string, MarketIntentEvidence>
|
||||
metricEvidence?: Record<string, MarketIntentEvidence | DepartmentDeliveryEvidence>
|
||||
totalScore: number | null
|
||||
positionId?: string
|
||||
jobGrade?: string
|
||||
@ -28,6 +29,7 @@ export type SalaryDetails = {
|
||||
roles: Record<SalaryRole, SalaryDetailRow[]>
|
||||
positionGroups: Array<{ position: SalaryPosition; template: SalaryTemplate; rows: SalaryDetailRow[] }>
|
||||
surveyMatchIssues?: Array<{ employeeProfileId: string; employeeLabel: string; salaryRole: SalaryRole; reason: SurveyMatchReason; message: string }>
|
||||
departmentMatchIssues?: Array<{ employeeProfileId: string; employeeLabel: string; message: string }>
|
||||
}
|
||||
|
||||
export function salarySourceLabel(data: Pick<SalaryDetails, 'displayMonth' | 'sourceMonth' | 'marketSourceMonth' | 'isFallback'>) {
|
||||
|
||||
@ -8,37 +8,50 @@ import { readSalaryMarketIntent } from './salary-market-intent'
|
||||
import { calculatePositionScore, resolvePersonnelPerformance, personnelPositions, performancePositions } from './salary-position-contract'
|
||||
import { serializePosition } from './salary-positions'
|
||||
import { calculateSalaryPay } from './performance-salary-pay'
|
||||
import { buildSalaryDepartmentScopes, summarizeDepartmentDelivery, summarizeDepartmentMarketIntent } from './salary-department-metrics'
|
||||
import { SALARY_DEPARTMENT_UNRESOLVED } from './salary-department-contract'
|
||||
import type { SalaryDetails, SalaryDetailRow, SalaryCell } from './performance-salary-details-contract'
|
||||
|
||||
export async function getPerformanceSalaryDetails(userId: string, month: unknown): Promise<SalaryDetails> {
|
||||
await requireSalaryAccess(userId)
|
||||
const displayMonth = resolveSalaryMonth(month)
|
||||
// One snapshot owns personnel, configuration revisions and submitted scores.
|
||||
const { state, responses, people, bases, positions } = await prisma.$transaction(async db => {
|
||||
const { state, responses, people, bases, positions, units } = await prisma.$transaction(async db => {
|
||||
const count = await db.performanceSurveyResponse.count({ where: { survey: { assessmentMonth: displayMonth, status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } } })
|
||||
const state = resolveSalarySourceMonth(displayMonth, count, process.env.NODE_ENV, process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK)
|
||||
const [responses, people, bases, positions] = await Promise.all([
|
||||
const [responses, people, bases, positions, units] = await Promise.all([
|
||||
db.performanceSurveyResponse.findMany({ where: { survey: { assessmentMonth: state.sourceMonth, 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 { state, responses, people, bases, positions }
|
||||
return { state, 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)
|
||||
}
|
||||
// Market validation assesses last month's completed flows; other metrics keep their own source month.
|
||||
const marketSourceMonth = previousSalaryMonth(displayMonth)
|
||||
const [workflows, market] = await Promise.all([
|
||||
readSalaryWorkflowMetrics(state.sourceMonth, people),
|
||||
readSalaryMarketIntent(marketSourceMonth, people, bases.filter(base => marketPositionIds.has(matches.get(base.id)?.id ?? '')).map(base => base.employeeProfileId)),
|
||||
readSalaryMarketIntent(marketSourceMonth, people, Array.from(marketEmployeeIds)),
|
||||
])
|
||||
const scores = collectSalarySurveyScores(responses)
|
||||
const matchSurveyPerson = createSalarySurveyPersonMatcher(people)
|
||||
const surveyMatchIssues: NonNullable<SalaryDetails['surveyMatchIssues']> = []
|
||||
const departmentMatchIssues: NonNullable<SalaryDetails['departmentMatchIssues']> = []
|
||||
const roles: SalaryDetails['roles'] = { 'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [] }
|
||||
const roots = personnelPositions(configuration)
|
||||
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 => {
|
||||
@ -55,8 +68,16 @@ export async function getPerformanceSalaryDetails(userId: string, month: unknown
|
||||
surveyMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, salaryRole: group.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' ? workflows.onTimeRates.get(base.employeeProfileId) ?? null : metric.source.kind === 'market-intent-top3' ? market.get(base.employeeProfileId)?.rawScore ?? null : null
|
||||
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 result = calculatePositionScore(group.position.dimensions, metrics)
|
||||
const values: Record<string, SalaryCell> = {
|
||||
@ -73,12 +94,12 @@ export async function getPerformanceSalaryDetails(userId: string, month: unknown
|
||||
}
|
||||
const metricEvidence: NonNullable<SalaryDetailRow['metricEvidence']> = {}
|
||||
for (const dimension of group.position.dimensions) for (const metric of dimension.metrics) {
|
||||
const evidence = market.get(base.employeeProfileId)
|
||||
if (metric.source.kind === 'market-intent-top3' && evidence) metricEvidence[metric.id] = evidence
|
||||
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)
|
||||
}
|
||||
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 }
|
||||
return { ...state, marketSourceMonth, roles, positionGroups, surveyMatchIssues, departmentMatchIssues }
|
||||
}
|
||||
|
||||
@ -91,5 +91,5 @@ export async function readSalaryWorkflowMetrics(sourceMonth: string, people: Art
|
||||
if (id) points.set(id, (points.get(id) ?? 0) + (item.type === 'add' ? 1 : -1) * Math.round((item.points ?? 0) * 100) / 100)
|
||||
}
|
||||
points.forEach((score, id) => points.set(id, Math.round(score * 100) / 100))
|
||||
return { sourceMonth, points, onTimeRates: new Map(Array.from(delivery).map(([id, counts]) => [id, counts.onTime / counts.total * 100])) }
|
||||
return { sourceMonth, points, deliveryCounts: delivery, onTimeRates: new Map(Array.from(delivery).map(([id, counts]) => [id, counts.onTime / counts.total * 100])) }
|
||||
}
|
||||
|
||||
17
lib/salary-department-contract.ts
Normal file
17
lib/salary-department-contract.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import type { SalaryOrganizationUnit } from './salary-organization-department'
|
||||
|
||||
export type SalaryDepartmentMember = { employeeProfileId: string; employeeLabel: string }
|
||||
export type SalaryDepartmentScope = {
|
||||
department: SalaryOrganizationUnit | null
|
||||
members: SalaryDepartmentMember[]
|
||||
planners: SalaryDepartmentMember[]
|
||||
}
|
||||
export const SALARY_DEPARTMENT_UNRESOLVED = '无法唯一确认主管的组织架构主部门,请先核对组织架构。'
|
||||
export type DepartmentDeliveryEvidence = {
|
||||
kind: 'department-on-time-average'
|
||||
month: string
|
||||
department: SalaryOrganizationUnit | null
|
||||
members: Array<SalaryDepartmentMember & { onTimeCount: number; totalCount: number; rate: number | null; included: boolean }>
|
||||
includedCount: number
|
||||
rawScore: number | null
|
||||
}
|
||||
51
lib/salary-department-metrics.ts
Normal file
51
lib/salary-department-metrics.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { resolveSalaryOrganizationUnit, type SalaryOrganizationUnit } from './salary-organization-department'
|
||||
import type { SalaryDepartmentScope, SalaryDepartmentMember, DepartmentDeliveryEvidence } from './salary-department-contract'
|
||||
import { summarizeMarketIntent, type MarketIntentCandidate, type MarketIntentEvidence } from './salary-market-intent-contract'
|
||||
|
||||
type Person = Parameters<typeof resolveSalaryOrganizationUnit>[0] & {
|
||||
id: string; employmentState?: string | null; flowerName?: string | null; realName?: string | null; displayName: string
|
||||
}
|
||||
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>) {
|
||||
const departments = new Map(people.map(person => [person.id, resolveSalaryOrganizationUnit(person, units)]))
|
||||
const members = new Map<number, SalaryDepartmentMember[]>()
|
||||
for (const person of people) {
|
||||
const department = departments.get(person.id)
|
||||
if (person.employmentState !== 'ACTIVE' || !department) continue
|
||||
const list = members.get(department.sourceDeptId) ?? []
|
||||
if (!list.some(member => member.employeeProfileId === person.id)) list.push({ employeeProfileId: person.id, employeeLabel: person.flowerName || person.realName || person.displayName })
|
||||
members.set(department.sourceDeptId, list)
|
||||
}
|
||||
for (const list of Array.from(members.values())) list.sort((a, b) => a.employeeLabel.localeCompare(b.employeeLabel, 'zh-CN') || a.employeeProfileId.localeCompare(b.employeeProfileId))
|
||||
return new Map(managerIds.map(id => {
|
||||
const department = departments.get(id) ?? null
|
||||
const direct = department ? members.get(department.sourceDeptId) ?? [] : []
|
||||
return [id, { department, members: direct, planners: direct.filter(member => plannerIds.has(member.employeeProfileId)) } satisfies SalaryDepartmentScope]
|
||||
}))
|
||||
}
|
||||
|
||||
export function summarizeDepartmentDelivery(month: string, scope: SalaryDepartmentScope, counts: Map<string, SalaryDeliveryCounts>): DepartmentDeliveryEvidence {
|
||||
const members = scope.members.map(member => {
|
||||
const value = counts.get(member.employeeProfileId)
|
||||
const included = !!value && value.total > 0
|
||||
return { ...member, onTimeCount: value?.onTime ?? 0, totalCount: value?.total ?? 0, included, rate: included ? value!.onTime / value!.total * 100 : null }
|
||||
})
|
||||
const included = members.filter(member => member.included)
|
||||
return { kind: 'department-on-time-average', month, department: scope.department, members, includedCount: included.length,
|
||||
rawScore: scope.department && included.length ? included.reduce((sum, member) => sum + member.rate!, 0) / included.length : null }
|
||||
}
|
||||
|
||||
/** Merge ALL records before ranking. Sharing a flow/product never duplicates the department sample. */
|
||||
export function summarizeDepartmentMarketIntent(month: string, scope: SalaryDepartmentScope, personal: Map<string, MarketIntentEvidence>): MarketIntentEvidence {
|
||||
const records = new Map<string, MarketIntentCandidate>()
|
||||
for (const member of scope.planners) for (const record of personal.get(member.employeeProfileId)?.records ?? []) {
|
||||
const prior = records.get(record.key)
|
||||
const { status: _, ...candidate } = record
|
||||
const participants = prior?.participants ?? []
|
||||
if (!participants.some(person => person.employeeProfileId === member.employeeProfileId)) participants.push(member)
|
||||
records.set(record.key, { ...candidate, participants })
|
||||
}
|
||||
return { ...summarizeMarketIntent(month, Array.from(records.values())), departmentScope: { department: scope.department, members: scope.planners } }
|
||||
}
|
||||
@ -1,3 +1,6 @@
|
||||
import type { SalaryDepartmentMember } from './salary-department-contract'
|
||||
import type { SalaryOrganizationUnit } from './salary-organization-department'
|
||||
|
||||
export type MarketIntentExclusion = 'immature-window' | 'zero-baseline' | 'unsupported-platform' | 'no-source-data' | 'invalid-intent'
|
||||
export const MARKET_INTENT_EXCLUSION_LABELS: Record<MarketIntentExclusion, string> = {
|
||||
'immature-window': '完结后未满15个自然日',
|
||||
@ -10,6 +13,7 @@ export type MarketIntentRecord = {
|
||||
key: string; workflowId: string; approvalNumber: string | null; productId: string
|
||||
brand: string; completedAt: string; intentRateChange: number
|
||||
sevenDayIntentRate: number; fifteenDayIntentRate: number
|
||||
participants?: SalaryDepartmentMember[]
|
||||
}
|
||||
export type MarketIntentCandidate = Omit<MarketIntentRecord, 'intentRateChange' | 'sevenDayIntentRate' | 'fifteenDayIntentRate'> & {
|
||||
intentRateChange: number | null; sevenDayIntentRate: number | null; fifteenDayIntentRate: number | null
|
||||
@ -23,6 +27,7 @@ export type MarketIntentEvidence = {
|
||||
excludedCounts: Record<MarketIntentExclusion, number>
|
||||
records: MarketIntentEvidenceRecord[]
|
||||
selected: MarketIntentRecord[]; averageChange: number | null; rawScore: number | null
|
||||
departmentScope?: { department: SalaryOrganizationUnit | null; members: SalaryDepartmentMember[] }
|
||||
}
|
||||
/** Input is a ratio: 0.0874 means 8.74%. Never round before averaging or weighting. */
|
||||
export function marketIntentScore(change: number): number {
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { normalizeOrganizationPath, resolveEmployeeOrganizationPaths, type EmployeeOrganizationPathSource } from './organization-material-permissions'
|
||||
|
||||
type Unit = { sourceDeptId: number; name: string; path: string }
|
||||
export type SalaryOrganizationUnit = { sourceDeptId: number; name: string; path: string }
|
||||
type Profile = Omit<EmployeeOrganizationPathSource, 'departmentMemberships'> & {
|
||||
departmentMemberships?: Array<{ sourceDeptId?: string | number | null; departmentPath?: string | null; isPrimary?: boolean }>
|
||||
}
|
||||
|
||||
// Use the same current department identities and paths as the organization tree.
|
||||
// A primary membership wins; ambiguous or retired departments require correction at the source.
|
||||
export function resolveSalaryOrganizationDepartment(profile: Profile, units: Unit[]): string | null {
|
||||
export function resolveSalaryOrganizationUnit(profile: Profile, units: SalaryOrganizationUnit[]): SalaryOrganizationUnit | null {
|
||||
const byId = new Map(units.map(unit => [String(unit.sourceDeptId), unit]))
|
||||
const paths = resolveEmployeeOrganizationPaths(profile, new Map(units.map(unit => [String(unit.sourceDeptId), unit.path])))
|
||||
const primary = (profile.departmentMemberships ?? []).filter(item => item.isPrimary)
|
||||
@ -17,7 +17,11 @@ export function resolveSalaryOrganizationDepartment(profile: Profile, units: Uni
|
||||
const main = normalizeOrganizationPath(profile.departmentPath)
|
||||
const selected = primaryPaths[0] ?? (paths.includes(main) ? main : paths.length === 1 ? paths[0] : null)
|
||||
const matches = units.filter(unit => unit.path === selected)
|
||||
return matches.length === 1 ? matches[0].name : null
|
||||
return matches.length === 1 ? matches[0] : null
|
||||
}
|
||||
|
||||
export function resolveSalaryOrganizationDepartment(profile: Profile, units: SalaryOrganizationUnit[]): string | null {
|
||||
return resolveSalaryOrganizationUnit(profile, units)?.name ?? null
|
||||
}
|
||||
|
||||
export async function readSalaryOrganizationDepartments(db: Prisma.TransactionClient, employeeProfileIds: string[]) {
|
||||
|
||||
66
scripts/connect-salary-management-market-local.ts
Normal file
66
scripts/connect-salary-management-market-local.ts
Normal file
@ -0,0 +1,66 @@
|
||||
/** Disposable local databases only; audit/apply/restore require an explicit actor and private manifest. */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { prisma } from '../lib/prisma'
|
||||
import { requireSalaryAccess } from '../lib/personnel-salary'
|
||||
import { positionFields } from '../lib/salary-position-contract'
|
||||
import { serializePosition, updateSalaryPosition } from '../lib/salary-positions'
|
||||
import { connectManagementMarketIntent, managementMarketFields, MANAGEMENT_MARKET_POSITION_ID } from '../lib/connect-salary-management-market'
|
||||
|
||||
const mode = process.argv[2], actor = process.env.SALARY_MARKET_ACTOR_ID || ''
|
||||
const canonical = (value: unknown): string => JSON.stringify(value, (_k, v) => v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v)
|
||||
const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex')
|
||||
type Fields = ReturnType<typeof positionFields>
|
||||
type Manifest = { database: string; actor: string; positionId: string; revision: number; before: Fields; after: Fields; snapshot: unknown }
|
||||
async function main() {
|
||||
const database = new URL(process.env.DATABASE_URL!)
|
||||
if (database.protocol !== 'postgresql:' || database.hostname !== '127.0.0.1' || database.port !== '55439' || !/^\/salary_isolated_department_\d+$/.test(database.pathname)) throw new Error('ISOLATED_DEPARTMENT_DATABASE_REQUIRED')
|
||||
const file = process.env.SALARY_MARKET_MANIFEST || ''
|
||||
if (!['audit', 'apply', 'restore'].includes(mode) || !actor || !path.isAbsolute(file)) throw new Error('EXPLICIT_MODE_ACTOR_AND_MANIFEST_REQUIRED')
|
||||
const directory = fs.lstatSync(path.dirname(file))
|
||||
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.mode & 0o077) throw new Error('PRIVATE_DIRECTORY_REQUIRED')
|
||||
await requireSalaryAccess(actor, true)
|
||||
if (mode === 'audit') {
|
||||
const manifest = await prisma.$transaction(async db => {
|
||||
await db.$executeRawUnsafe('SET TRANSACTION READ ONLY')
|
||||
await requireSalaryAccess(actor, true, db)
|
||||
const row = await db.salaryPositionConfig.findUniqueOrThrow({ where: { id: MANAGEMENT_MARKET_POSITION_ID } })
|
||||
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
||||
const position = serializePosition(row)
|
||||
return { database: database.pathname, actor, positionId: row.id, revision: row.revision,
|
||||
before: positionFields(position), after: managementMarketFields(position),
|
||||
snapshot: { position: row, audits: await db.salaryPositionConfigAudit.findMany({ where: { positionId: row.id }, orderBy: { createdAt: 'asc' } }) } }
|
||||
}, { isolationLevel: 'RepeatableRead' })
|
||||
const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n')
|
||||
fs.writeFileSync(file, bytes, { mode: 0o600, flag: 'wx' })
|
||||
console.log(JSON.stringify({ mode, revision: manifest.revision, manifestSha256: sha(bytes) }))
|
||||
return
|
||||
}
|
||||
if (process.env.SALARY_MARKET_CONFIRM !== 'MANAGEMENT_MARKET_SOURCE_ONLY') throw new Error('EXPLICIT_CONFIRMATION_REQUIRED')
|
||||
const stat = fs.lstatSync(file), bytes = fs.readFileSync(file)
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077 || sha(bytes) !== process.env.EXPECTED_MARKET_MANIFEST_SHA256) throw new Error('PRIVATE_MANIFEST_HASH_REQUIRED')
|
||||
const manifest: Manifest = JSON.parse(bytes.toString())
|
||||
if (manifest.database !== database.pathname || manifest.actor !== actor || manifest.positionId !== MANAGEMENT_MARKET_POSITION_ID) throw new Error('MANIFEST_TARGET_MISMATCH')
|
||||
const row = await prisma.salaryPositionConfig.findUniqueOrThrow({ where: { id: manifest.positionId } })
|
||||
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
||||
const fields = positionFields(serializePosition(row)), same = (expected: Fields) => canonical(fields) === canonical(expected)
|
||||
let result: { changed: boolean; revision: number }
|
||||
if (mode === 'apply') {
|
||||
if (same(manifest.after) && [manifest.revision, manifest.revision + 1].includes(row.revision)) result = { changed: false, revision: row.revision }
|
||||
else {
|
||||
if (!same(manifest.before) || row.revision !== manifest.revision) throw new Error('REVISION_CONFLICT')
|
||||
result = await connectManagementMarketIntent(actor, manifest.revision)
|
||||
}
|
||||
} else {
|
||||
if (same(manifest.before) && [manifest.revision, manifest.revision + 2].includes(row.revision)) result = { changed: false, revision: row.revision }
|
||||
else {
|
||||
if (!same(manifest.after) || row.revision !== manifest.revision + 1) throw new Error('REVISION_CONFLICT')
|
||||
const saved = await updateSalaryPosition(row.id, { ...manifest.before, revision: row.revision }, actor)
|
||||
result = { changed: true, revision: saved.revision }
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(file + '.' + mode + '.json', JSON.stringify({ mode, ...result, at: new Date() }, null, 2), { mode: 0o600 })
|
||||
console.log(JSON.stringify({ mode, ...result }))
|
||||
}
|
||||
main().catch(error => { console.error(error.message); process.exitCode = 1 }).finally(() => prisma.$disconnect())
|
||||
80
scripts/connect-salary-management-market.ts
Normal file
80
scripts/connect-salary-management-market.ts
Normal file
@ -0,0 +1,80 @@
|
||||
/** Explicit, versioned configuration repair. Bundle from the exact release commit; never runs on GET. */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { prisma } from '../lib/prisma'
|
||||
import { requireSalaryAccess } from '../lib/personnel-salary'
|
||||
import { connectManagementMarketIntent, managementMarketFields } from '../lib/connect-salary-management-market'
|
||||
import { INITIAL_SALARY_POSITIONS } from '../lib/salary-position-seeds'
|
||||
import { positionFields } from '../lib/salary-position-contract'
|
||||
import { serializePosition, updateSalaryPosition } from '../lib/salary-positions'
|
||||
|
||||
type Fields = ReturnType<typeof positionFields>
|
||||
type Manifest = { format: 1; target: string; actorUserId: string; positionId: string; beforeRevision: number; before: Fields; after: Fields; snapshot: unknown }
|
||||
const mode = process.argv[2], actor = process.env.SALARY_MARKET_ACTOR_ID || '', file = path.resolve(process.env.SALARY_MARKET_MANIFEST || '')
|
||||
const hash = (value: Buffer) => createHash('sha256').update(value).digest('hex')
|
||||
const canonical = (value: unknown): string => JSON.stringify(value, (_k, v) => v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v)
|
||||
async function main() {
|
||||
if (!['audit', 'apply', 'restore'].includes(mode) || !actor || !path.isAbsolute(process.env.SALARY_MARKET_MANIFEST || '')) throw new Error('Explicit mode, actor and absolute manifest required')
|
||||
const url = new URL(process.env.DATABASE_URL!)
|
||||
let target: string
|
||||
if (process.env.SALARY_MARKET_TARGET === 'production') {
|
||||
const guard = await import(pathToFileURL(path.join(process.cwd(), 'scripts/safe-production-migrate.mjs')).href)
|
||||
const commit = guard.requireExactCommit(process.env.EXPECTED_COMMIT_SHA, 'EXPECTED_COMMIT_SHA')
|
||||
if (fs.readFileSync('/app/DEPLOYMENT_COMMIT', 'utf8').trim() !== commit) throw new Error('IMAGE_COMMIT_MISMATCH')
|
||||
const [identity] = await prisma.$queryRawUnsafe<Array<Record<string, unknown>>>('SELECT current_database() AS database,current_user AS "user",inet_server_addr()::text AS server_address,inet_server_port()::text AS server_port')
|
||||
const database = guard.assertExpectedDatabaseIdentity(url, identity)
|
||||
target = JSON.stringify({ commit, database })
|
||||
if (mode !== 'audit') await guard.assertBackupReceipt({ expectedCommit: commit, database })
|
||||
} else {
|
||||
if (process.env.SALARY_MARKET_TARGET !== 'local' || url.hostname !== '127.0.0.1' || url.port !== '55439' || !/^\/salary_isolated_department_\d+$/.test(url.pathname)) throw new Error('ISOLATED_DATABASE_REQUIRED')
|
||||
target = 'local:' + url.pathname
|
||||
}
|
||||
const directory = fs.lstatSync(path.dirname(file))
|
||||
if (!directory.isDirectory() || directory.isSymbolicLink() || (directory.mode & 0o077)) throw new Error('PRIVATE_DIRECTORY_REQUIRED')
|
||||
if (mode === 'audit') {
|
||||
const manifest = await prisma.$transaction(async db => {
|
||||
await db.$executeRawUnsafe('SET TRANSACTION READ ONLY')
|
||||
await requireSalaryAccess(actor, true, db)
|
||||
const seed = INITIAL_SALARY_POSITIONS[0]
|
||||
const row = await db.salaryPositionConfig.findUniqueOrThrow({ where: { id: seed.id } })
|
||||
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
||||
const before = positionFields(serializePosition(row)), after = managementMarketFields(serializePosition(row))
|
||||
return { format: 1 as const, target, actorUserId: actor, positionId: row.id, beforeRevision: row.revision, before, after,
|
||||
snapshot: { position: row, audits: await db.salaryPositionConfigAudit.findMany({ where: { positionId: row.id }, orderBy: { createdAt: 'asc' } }) } }
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })
|
||||
const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n')
|
||||
fs.writeFileSync(file, bytes, { mode: 0o600, flag: 'wx' })
|
||||
console.log(JSON.stringify({ mode, revision: manifest.beforeRevision, changes: canonical(manifest.before) === canonical(manifest.after) ? 0 : 1, manifestSha256: hash(bytes) }))
|
||||
return
|
||||
}
|
||||
if (process.env.SALARY_MARKET_CONFIRM !== 'MANAGEMENT_MARKET_SOURCE_ONLY') throw new Error('EXPLICIT_WRITE_FLAG_REQUIRED')
|
||||
const stat = fs.lstatSync(file), bytes = fs.readFileSync(file)
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) || hash(bytes) !== process.env.EXPECTED_MARKET_MANIFEST_SHA256) throw new Error('PRIVATE_MANIFEST_HASH_REQUIRED')
|
||||
const manifest: Manifest = JSON.parse(bytes.toString('utf8'))
|
||||
if (manifest.format !== 1 || manifest.target !== target || manifest.actorUserId !== actor || manifest.positionId !== INITIAL_SALARY_POSITIONS[0].id) throw new Error('MANIFEST_TARGET_MISMATCH')
|
||||
await requireSalaryAccess(actor, true)
|
||||
const row = await prisma.salaryPositionConfig.findUniqueOrThrow({ where: { id: manifest.positionId } })
|
||||
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
||||
const fields = positionFields(serializePosition(row)), same = (value: Fields) => canonical(fields) === canonical(value)
|
||||
let result: { changed: boolean; revision: number }
|
||||
if (mode === 'apply') {
|
||||
if (same(manifest.after) && [manifest.beforeRevision, manifest.beforeRevision + 1].includes(row.revision)) result = { changed: false, revision: row.revision }
|
||||
else {
|
||||
if (!same(manifest.before) || row.revision !== manifest.beforeRevision) throw new Error('REVISION_CONFLICT')
|
||||
result = await connectManagementMarketIntent(actor, manifest.beforeRevision)
|
||||
}
|
||||
} else {
|
||||
if (same(manifest.before) && [manifest.beforeRevision, manifest.beforeRevision + 2].includes(row.revision)) result = { changed: false, revision: row.revision }
|
||||
else {
|
||||
if (!same(manifest.after) || row.revision !== manifest.beforeRevision + 1) throw new Error('REVISION_CONFLICT')
|
||||
const updated = await updateSalaryPosition(row.id, { ...manifest.before, revision: row.revision }, actor)
|
||||
result = { changed: true, revision: updated.revision }
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(file + '.' + mode + '.json', JSON.stringify({ mode, ...result, positionId: row.id, actorUserId: actor, at: new Date() }, null, 2), { mode: 0o600 })
|
||||
console.log(JSON.stringify({ mode, ...result }))
|
||||
}
|
||||
main().catch(error => { console.error(error.message); process.exitCode = 1 }).finally(() => prisma.$disconnect())
|
||||
Loading…
x
Reference in New Issue
Block a user