fix(clearance): 兼容新旧复盘键并校准利润中心

(cherry picked from commit 2f7a80a4f914b5bdcfba447285d1042bb0e79ac3)
This commit is contained in:
居居 2026-12-05 17:33:59 +08:00 committed by WuYongJie
parent a391670c72
commit df02ea1ec6
5 changed files with 142 additions and 63 deletions

View File

@ -113,7 +113,7 @@ describe('ClearanceReviewAnalysis', () => {
(compareSeparator) => {
const department = '样例部门'
const director = '样例负责人'
const currentBaseKey = [department, director].join('\u001f')
const currentBaseKey = [department, director, '运营中心C'].join('\u001f')
const compareBaseKey = [department, director].join(compareSeparator)
render(
<ClearanceReviewAnalysis
@ -122,19 +122,33 @@ describe('ClearanceReviewAnalysis', () => {
analysis={{
deptHead: {
current: [row({
dimension: 'deptHead',
dimensionKey: currentBaseKey,
dimensionLabel: `${department} · ${director}`,
profitCenter: '运营中心C',
completionRate: 81,
})],
compare: [row({
dimension: 'deptHead',
dimensionKey: compareBaseKey,
dimensionLabel: `${department} · ${director}`,
profitCenter: '运营中心C',
completionRate: 70,
})],
},
deptHeadTaskType: {
current: [row({ dimensionKey: [department, director, 'fixed'].join('\u001f'), completionRate: 73 })],
compare: [row({ dimensionKey: [department, director, 'fixed'].join(compareSeparator), completionRate: 67 })],
current: [row({
dimension: 'deptHeadTaskType',
dimensionKey: [department, director, '运营中心C', 'fixed'].join('\u001f'),
profitCenter: '运营中心C',
completionRate: 73,
})],
compare: [row({
dimension: 'deptHeadTaskType',
dimensionKey: [department, director, 'fixed'].join(compareSeparator),
profitCenter: '运营中心C',
completionRate: 67,
})],
},
} as ClearanceReviewAnalysisData}
/>,
@ -149,6 +163,7 @@ describe('ClearanceReviewAnalysis', () => {
)!
const departmentRow = within(matrix).getByText(department).closest('tr')!
const cells = within(departmentRow).getAllByRole('cell')
expect(cells[0].textContent).toBe('运营中心C')
expect(cells[15].textContent).toContain('73.00%')
expect(cells[15].textContent).toContain('67.00%')
expect(cells[15].textContent).toContain('+6.00pp')
@ -229,9 +244,11 @@ describe('ClearanceReviewAnalysis', () => {
})
it('orders profit centers and departments by the configured business order', () => {
const departmentRow = (department: string, director: string) => row({
dimensionKey: [department, director].join('\u001f'),
const departmentRow = (department: string, director: string, profitCenter: string) => row({
dimension: 'deptHead',
dimensionKey: [department, director, profitCenter].join('\u001f'),
dimensionLabel: `${department} · ${director}`,
profitCenter,
taskQty: 10,
})
render(
@ -241,13 +258,13 @@ describe('ClearanceReviewAnalysis', () => {
analysis={{
deptHead: {
current: [
departmentRow('不凡组', '分销负责人'),
departmentRow('运营七部(CZ)', 'G负责人'),
departmentRow('运营一部(江苏简尚品牌管理有限公司 > 运营中心C)', 'C负责人'),
departmentRow('事业四部', 'A四部负责人'),
departmentRow('事业二部', 'A二部负责人'),
departmentRow('事业一部', 'A一部负责人'),
departmentRow('事业三部', 'A三部负责人'),
departmentRow('不凡组', '分销负责人', '分销部'),
departmentRow('运营七部(CZ)', 'G负责人', '运营中心G'),
departmentRow('运营一部(江苏简尚品牌管理有限公司 > 运营中心C)', 'C负责人', '运营中心C'),
departmentRow('事业四部', 'A四部负责人', '运营中心A'),
departmentRow('事业二部', 'A二部负责人', '运营中心A'),
departmentRow('事业一部', 'A一部负责人', '运营中心A'),
departmentRow('事业三部', 'A三部负责人', '运营中心A'),
],
compare: [],
},

View File

@ -119,23 +119,6 @@ const CHINESE_NUMBER: Record<string, number> = {
十: 10,
}
function departmentProfitCenter(department: string) {
if (/^事业[一二三四五六七八九十]+部/.test(department) || department === '未配置部门') {
return '运营中心A'
}
if (department.includes('运营中心C') || /^运营[五六]部/.test(department)) {
return '运营中心C'
}
if (/(?:CZ|HZ)/i.test(department) || /^运营[七八]部/.test(department)) {
return '运营中心G'
}
if (/组$/.test(department) || department.includes('分销')) {
return '分销部'
}
if (department === '运营一部') return '运营中心B'
return '分销部'
}
function departmentNumber(department: string) {
const matched = department.match(/[一二三四五六七八九十]+/)
if (!matched) return 99
@ -161,8 +144,8 @@ function compareDepartmentLeadRows(
) {
const [leftDepartment] = splitClearanceReviewKey(left.dimensionKey)
const [rightDepartment] = splitClearanceReviewKey(right.dimensionKey)
const leftCenter = departmentProfitCenter(leftDepartment || left.dimensionLabel)
const rightCenter = departmentProfitCenter(rightDepartment || right.dimensionLabel)
const leftCenter = reviewRowProfitCenter(left, leftDepartment || left.dimensionLabel)
const rightCenter = reviewRowProfitCenter(right, rightDepartment || right.dimensionLabel)
return profitCenterSortIndex(leftCenter) - profitCenterSortIndex(rightCenter)
|| departmentNumber(leftDepartment) - departmentNumber(rightDepartment)
|| leftDepartment.localeCompare(rightDepartment, 'zh-CN')
@ -425,14 +408,67 @@ function baseRow(
return (rows ?? []).find((row) => row.dimensionKey === key) ?? null
}
function reviewRowProfitCenter(row: ClearanceReviewAnalysisRow, fallbackDepartment = '') {
if (row.profitCenter?.trim()) return row.profitCenter.trim()
const parts = splitClearanceReviewKey(row.dimensionKey)
if (row.dimension === 'deptHead') return parts[2] ?? ''
if (row.dimension === 'ownerDetail') return parts[3] ?? ''
if (row.dimension === 'dept') return parts[1] ?? ''
if (row.dimension === 'deptHeadTaskType') return parts[2] ?? ''
if (row.dimension === 'deptTaskType') return parts[1] ?? ''
if (row.dimension === 'channel' || row.dimension === 'channelTaskType' || row.dimension === 'channelPriority') {
return parts[0] ?? fallbackDepartment
}
return fallbackDepartment
}
function logicalReviewKey(row: ClearanceReviewAnalysisRow) {
if (row.dimensionKey === 'total') return 'total'
const parts = splitClearanceReviewKey(row.dimensionKey)
const center = reviewRowProfitCenter(row)
if (row.dimension === 'deptHead') {
return buildClearanceReviewKey(parts[0] ?? '', parts[1] ?? '', center)
}
if (row.dimension === 'ownerDetail') {
return buildClearanceReviewKey(parts[0] ?? '', parts[1] ?? '', parts[2] ?? '', center)
}
if (row.dimension === 'deptHeadTaskType') {
return buildClearanceReviewKey(
parts[0] ?? '',
parts[1] ?? '',
center,
parts.at(-1) ?? '',
)
}
if (row.dimension === 'deptTaskType') {
return buildClearanceReviewKey(parts[0] ?? '', center, parts.at(-1) ?? '')
}
if (row.dimension === 'dept') {
return buildClearanceReviewKey(parts[0] ?? '', center)
}
return buildClearanceReviewKey(...parts)
}
function logicalTaskTypeKey(row: ClearanceReviewAnalysisRow, taskType: string) {
const parts = splitClearanceReviewKey(row.dimensionKey)
const center = reviewRowProfitCenter(row)
if (row.dimension === 'deptHead' || row.dimension === 'deptHeadTaskType') {
return buildClearanceReviewKey(parts[0] ?? '', parts[1] ?? '', center, taskType)
}
if (row.dimension === 'dept' || row.dimension === 'deptTaskType') {
return buildClearanceReviewKey(parts[0] ?? '', center, taskType)
}
if (row.dimension === 'channel' || row.dimension === 'channelTaskType') {
return buildClearanceReviewKey(center || parts[0] || '', taskType)
}
return buildClearanceReviewKey(...parts, taskType)
}
function rowsByReviewKey(
rows: ClearanceReviewAnalysisRow[] | null | undefined,
composite: boolean,
) {
return new Map((rows ?? []).map((row) => [
composite
? buildClearanceReviewKey(...splitClearanceReviewKey(row.dimensionKey))
: row.dimensionKey,
logicalReviewKey(row),
row,
]))
}
@ -738,7 +774,7 @@ function LedgerTable({
)
const column = (key: string) => columns.find((item) => item.key === key)!
const composite = dimension === 'deptHead' || dimension === 'ownerDetail'
const compareByKey = rowsByReviewKey(compareRows, composite)
const compareByKey = rowsByReviewKey(compareRows)
const rows = currentRows ?? []
const cell = (
current: number | null | undefined,
@ -787,10 +823,7 @@ function LedgerTable({
</thead>
<tbody>
{rows.map((row) => {
const comparisonKey = composite
? buildClearanceReviewKey(...splitClearanceReviewKey(row.dimensionKey))
: row.dimensionKey
const previous = compareByKey.get(comparisonKey) ?? null
const previous = compareByKey.get(logicalReviewKey(row)) ?? null
const cells = dimensionCells(row, dimension)
const isTotal = row.dimensionKey === 'total'
return (
@ -875,9 +908,9 @@ function MatrixTable({
})
const compositeBase = baseDimension === 'deptHead'
const dimensionColumnCount = compositeBase ? 3 : 1
const compareByKey = rowsByReviewKey(baseAnalysis.compare, compositeBase)
const currentByTaskType = rowsByReviewKey(compositeAnalysis.current, true)
const compareByTaskType = rowsByReviewKey(compositeAnalysis.compare, true)
const compareByKey = rowsByReviewKey(baseAnalysis.compare)
const currentByTaskType = rowsByReviewKey(compositeAnalysis.current)
const compareByTaskType = rowsByReviewKey(compositeAnalysis.compare)
const totalCurrent = baseRow(baseAnalysis.current, 'total')
const totalCompare = compareByKey.get('total')
const taskTypeColumns = [...TASK_TYPES, { key: 'subtotal' as const, label: '小计' }]
@ -981,14 +1014,9 @@ function MatrixTable({
</thead>
<tbody>
{currentRows.map((row) => {
const baseParts = compositeBase
? splitClearanceReviewKey(row.dimensionKey)
: [row.dimensionKey]
const previousBase = compareByKey.get(
compositeBase ? buildClearanceReviewKey(...baseParts) : row.dimensionKey,
)
const previousBase = compareByKey.get(logicalReviewKey(row))
const values = TASK_TYPES.map((type) => {
const key = buildClearanceReviewKey(...baseParts, type.key)
const key = logicalTaskTypeKey(row, type.key)
return {
current: currentByTaskType.get(key),
previous: compareByTaskType.get(key),
@ -1000,7 +1028,9 @@ function MatrixTable({
{compositeBase ? (() => {
const [department, director] = splitClearanceReviewKey(row.dimensionKey)
return [
<td key="profit-center" className={styles.stickyColumn}><b>{departmentProfitCenter(department || row.dimensionLabel)}</b></td>,
<td key="profit-center" className={styles.stickyColumn}>
<b>{reviewRowProfitCenter(row, department || row.dimensionLabel)}</b>
</td>,
<td key="department"><b>{compactClearanceDepartmentName(department || row.dimensionLabel)}</b></td>,
<td key="director">{director || '未配置部门负责人'}</td>,
]

View File

@ -2357,6 +2357,21 @@ class SupplyChainClearanceRepository {
})
}
async findReviewArchiveTaskRows(monthKey: string) {
const rows = await prisma.$queryRaw<Array<{ taskRows: unknown }>>`
SELECT COALESCE("sourceSnapshot"->'taskRows', '[]'::jsonb) AS "taskRows"
FROM "SupplyChainClearanceReviewArchive"
WHERE "monthKey" = ${monthKey}
LIMIT 1
`
const taskRows = rows[0]?.taskRows
return Array.isArray(taskRows)
? taskRows.filter((row): row is Record<string, unknown> => (
Boolean(row) && typeof row === 'object' && !Array.isArray(row)
))
: []
}
async listReviewArchives() {
// The source JSON contains the entire frozen month and is only needed for exports.
return prisma.$queryRaw<Array<

View File

@ -138,6 +138,7 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({
listReviewSnapshotsByDimensions: jest.fn(),
listReviewMonths: jest.fn(),
findReviewArchive: jest.fn(),
findReviewArchiveTaskRows: jest.fn(),
listReviewArchives: jest.fn(),
replaceReviewArchive: jest.fn(),
listReviewDetails: jest.fn(),
@ -561,6 +562,7 @@ describe('supply-chain-clearance workflow', () => {
repository.listReviewArchives.mockResolvedValue([])
repository.listReviewSnapshotsByDimensions.mockResolvedValue([])
repository.findReviewArchive.mockResolvedValue(null)
repository.findReviewArchiveTaskRows.mockResolvedValue([])
repository.listReviewDetails.mockResolvedValue({ total: 0, rows: [] })
repository.replaceReviewArchive.mockResolvedValue({
id: 'review-archive-1',
@ -7112,6 +7114,9 @@ describe('supply-chain-clearance workflow', () => {
repository.listTaskPeriods.mockResolvedValue(['2026-11'])
repository.listReviewArchives.mockResolvedValue([archive] as never)
repository.findReviewArchive.mockResolvedValue(archive as never)
repository.findReviewArchiveTaskRows.mockResolvedValue(
archive.sourceSnapshot.taskRows as never,
)
const snapshot = {
reviewTaskCount: 1,
matchedStoreCount: 1,

View File

@ -7972,6 +7972,25 @@ class SupplyChainClearanceService {
archiveByMonth.has(month)
|| analysisSnapshotMap.has(`${month}\u0000${analysisDimension}`)
)
const profitCenterSnapshotMonths = [periodKey, compareKey]
.filter((month): month is string => Boolean(month) && archivedMonthKeys.has(month))
const archiveTaskRowsByMonth = new Map<string, Array<Record<string, unknown>>>()
if (profitCenterSnapshotMonths.length) {
const taskRowsByMonth = await Promise.all(profitCenterSnapshotMonths.map(async (month) => {
const archive = archiveByMonth.get(month)
const cacheKey = archive
? `${month}\u0000${archive.generatedAt.toISOString()}`
: ''
const cached = cacheKey ? frozenClearanceReviewTaskRowsCache.get(cacheKey) : null
if (cached) return [month, cached] as const
const rows = await supplyChainClearanceRepository.findReviewArchiveTaskRows(month)
if (cacheKey && rows.length) frozenClearanceReviewTaskRowsCache.set(cacheKey, rows)
return [month, rows] as const
}))
for (const [month, rows] of taskRowsByMonth) {
archiveTaskRowsByMonth.set(month, rows)
}
}
const archiveProfitCenterAliases = new Map<string, {
byDepartment: Map<string, Set<string>>
byDepartmentHead: Map<string, Set<string>>
@ -7983,23 +8002,16 @@ class SupplyChainClearanceService {
current.add(center)
map.set(key, current)
}
for (const [month, archive] of loadedArchiveByMonth) {
const correctedRows = correctedArchiveByMonth.get(month)?.taskRows
const sourceSnapshot = archive.sourceSnapshot
const sourceRows = (
sourceSnapshot
&& typeof sourceSnapshot === 'object'
&& !Array.isArray(sourceSnapshot)
&& Array.isArray((sourceSnapshot as { taskRows?: unknown }).taskRows)
)
? (sourceSnapshot as { taskRows: Array<Record<string, unknown>> }).taskRows
: []
for (const month of profitCenterSnapshotMonths) {
const sourceRows = correctedArchiveByMonth.get(month)?.taskRows
?? archiveTaskRowsByMonth.get(month)
?? []
const aliases = {
byDepartment: new Map<string, Set<string>>(),
byDepartmentHead: new Map<string, Set<string>>(),
byOwner: new Map<string, Set<string>>(),
}
for (const sourceRow of correctedRows ?? sourceRows) {
for (const sourceRow of sourceRows) {
const center = String(sourceRow.profitCenter ?? '').trim()
const department = compactClearanceDepartmentName(
String(sourceRow.department ?? '').trim() || '未分配部门',