feat(clearance): 完善复盘利润中心分析与列宽调整

This commit is contained in:
居居 2026-12-04 15:11:17 +08:00
parent 11f6be8cd6
commit 8a999da508
8 changed files with 673 additions and 49 deletions

View File

@ -166,6 +166,85 @@
line-height: 1.75;
}
.narrativeNumber {
color: #c2410c;
font-weight: 720;
font-variant-numeric: tabular-nums;
}
.profitCenterAnalysis {
border-bottom: 1px solid #edf0ef;
padding: 12px 16px 14px;
}
.profitCenterHeading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
color: #283331;
font-size: 10px;
}
.profitCenterHeading span {
color: #7b8587;
font-size: 9px;
}
.profitCenterGrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(205px, 1fr));
gap: 8px;
}
.profitCenterItem {
border: 1px solid #e4e8e7;
border-radius: 7px;
background: #fbfcfc;
padding: 9px 10px;
}
.profitCenterFocus {
border-color: #9bbab4;
background: #f1f8f6;
box-shadow: inset 0 0 0 1px rgba(31, 95, 86, 0.06);
}
.profitCenterItem > strong {
display: block;
margin-bottom: 7px;
color: #283331;
font-size: 10px;
}
.profitCenterItem dl {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 5px;
margin: 0;
}
.profitCenterItem dl > div {
min-width: 0;
}
.profitCenterItem dt {
overflow: hidden;
color: #8a9193;
font-size: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
.profitCenterItem dd {
margin: 2px 0 0;
color: #c2410c;
font-size: 10px;
font-weight: 720;
font-variant-numeric: tabular-nums;
}
.narrativeGrid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
@ -378,6 +457,10 @@
table-layout: auto;
}
.resizableTable {
table-layout: fixed;
}
.autoTable th,
.autoTable td {
white-space: nowrap;
@ -399,6 +482,36 @@
white-space: nowrap;
}
.columnResizeHandle {
position: absolute;
top: 0;
right: -3px;
z-index: 8;
width: 7px;
height: 100%;
cursor: col-resize;
outline: none;
touch-action: none;
}
.columnResizeHandle::after {
position: absolute;
top: 8px;
right: 3px;
bottom: 8px;
width: 1px;
background: #c7cecc;
content: '';
transition: background 0.15s ease, width 0.15s ease;
}
.columnResizeHandle:hover::after,
.columnResizeHandle:focus-visible::after {
right: 2px;
width: 2px;
background: #1f5f56;
}
.table thead tr:nth-child(2) th {
top: 34px;
z-index: 5;
@ -617,4 +730,8 @@
flex-direction: column;
gap: 6px;
}
.profitCenterItem dl {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}

View File

@ -34,7 +34,11 @@ function row(overrides: Partial<ClearanceReviewAnalysisRow> = {}): ClearanceRevi
}
function rows() {
const total = row({ dimensionKey: 'total', dimensionLabel: '总计' })
const total = row({
dimensionKey: 'total',
dimensionLabel: '总计',
realPerformance: 788822.1,
})
return [row(), total]
}
@ -70,6 +74,11 @@ describe('ClearanceReviewAnalysis', () => {
expect(screen.getByText('核心结论')).toBeInTheDocument()
expect(screen.getByText('风险提示')).toBeInTheDocument()
expect(screen.getByText('建议关注')).toBeInTheDocument()
expect(screen.getByText('利润中心分析')).toBeInTheDocument()
expect(screen.getByText('重点分析 运营中心A')).toBeInTheDocument()
expect(screen.getByText('结算毛利率')).toBeInTheDocument()
expect(screen.getAllByText('78.9万').length).toBeGreaterThan(0)
expect(screen.getAllByRole('separator').length).toBeGreaterThan(20)
expect(screen.getByRole('heading', { name: '整体达成' })).toBeInTheDocument()
expect(screen.getByRole('heading', { name: '渠道经营表现' })).toBeInTheDocument()
expect(screen.getByRole('heading', { name: '折扣经营表现' })).toBeInTheDocument()

View File

@ -1,5 +1,6 @@
'use client'
import { useEffect, useRef, useSyncExternalStore } from 'react'
import {
buildClearanceReviewKey,
splitClearanceReviewKey,
@ -68,6 +69,11 @@ type MatrixMetric =
| 'recoveryRate'
type LedgerDimension = 'channel' | 'dept' | 'deptHead' | 'discount' | 'priority' | 'ownerDetail'
type NumberFormatter = (value: number | null | undefined) => string
type TableColumn = {
key: string
label: string
width: number
}
const TASK_TYPES: Array<{ key: TaskType; label: string }> = [
{ key: 'fixed', label: '固定任务' },
@ -180,6 +186,167 @@ function prioritySortValue(label: string): [number, string] {
return [800, normalized]
}
function matrixColumnDefaultWidth(key: string, label: string) {
if (key.startsWith('dimension') || key === 'director') return 120
if (label.includes('业绩') || label.includes('货值') || label.includes('运费')) return 125
if (label.includes('率')) return 105
return 90
}
function tableColumn(key: string, label: string, width = matrixColumnDefaultWidth(key, label)): TableColumn {
return { key, label, width }
}
const columnWidthSubscribers = new Set<() => void>()
function subscribeColumnWidths(listener: () => void) {
columnWidthSubscribers.add(listener)
const handleStorage = (event: StorageEvent) => {
if (event.key?.startsWith('supply-chain.clearance.review-')) listener()
}
window.addEventListener('storage', handleStorage)
return () => {
columnWidthSubscribers.delete(listener)
window.removeEventListener('storage', handleStorage)
}
}
function columnWidthSnapshot(storageKey: string) {
try {
return window.localStorage.getItem(storageKey) ?? ''
} catch {
return ''
}
}
function parseColumnWidths(snapshot: string) {
if (!snapshot) return {}
try {
const parsed = JSON.parse(snapshot)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, number>
: {}
} catch {
return {}
}
}
function writeColumnWidths(storageKey: string, widths: Record<string, number>) {
try {
window.localStorage.setItem(storageKey, JSON.stringify(widths))
} catch {}
for (const listener of columnWidthSubscribers) listener()
}
function useResizableColumns(storageKey: string, columns: TableColumn[]) {
const resizeCleanupRef = useRef<(() => void) | null>(null)
const storedWidths = useSyncExternalStore(
subscribeColumnWidths,
() => columnWidthSnapshot(storageKey),
() => '',
)
const columnWidths = parseColumnWidths(storedWidths)
useEffect(() => () => {
resizeCleanupRef.current?.()
}, [])
const widthOf = (column: TableColumn) => columnWidths[column.key] ?? column.width
const setColumnWidth = (column: TableColumn, width: number) => {
writeColumnWidths(storageKey, {
...columnWidths,
[column.key]: Math.max(60, Math.min(360, Math.round(width))),
})
}
const beginColumnResize = (
event: React.PointerEvent<HTMLSpanElement>,
column: TableColumn,
) => {
event.preventDefault()
event.stopPropagation()
resizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = widthOf(column)
const handle = event.currentTarget
if ('setPointerCapture' in handle) {
handle.setPointerCapture(event.pointerId)
}
const onMove = (moveEvent: PointerEvent) => {
moveEvent.preventDefault()
setColumnWidth(column, startWidth + moveEvent.clientX - startX)
}
const cleanup = () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', cleanup)
window.removeEventListener('pointercancel', cleanup)
resizeCleanupRef.current = null
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', cleanup)
window.addEventListener('pointercancel', cleanup)
resizeCleanupRef.current = cleanup
}
const resizeHandle = (column: TableColumn) => (
<span
className={styles.columnResizeHandle}
role="separator"
tabIndex={0}
aria-label={`调整${column.label}列宽`}
onPointerDown={(event) => beginColumnResize(event, column)}
onDoubleClick={() => {
const next = { ...columnWidths }
delete next[column.key]
writeColumnWidths(storageKey, next)
}}
onKeyDown={(event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
event.preventDefault()
setColumnWidth(column, widthOf(column) + (event.key === 'ArrowLeft' ? -10 : 10))
}}
/>
)
const colGroup = (
<colgroup>
{columns.map((column) => (
<col key={column.key} style={{ width: widthOf(column) }} />
))}
</colgroup>
)
return {
colGroup,
resizeHandle,
totalWidth: columns.reduce((total, column) => total + widthOf(column), 0),
}
}
const NARRATIVE_NUMBER_SPLIT = /(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)/g
const NARRATIVE_NUMBER_ONLY = /^(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)$/
function NarrativeText({ text }: { text: string }) {
return (
<>
{text.split(NARRATIVE_NUMBER_SPLIT).map((part, index) => {
if (!part) return null
if (!NARRATIVE_NUMBER_ONLY.test(part)) return part
const value = Number(part.replaceAll(',', ''))
const compact = Number.isFinite(value) && Math.abs(value) >= 10_000
? `${(value / 10_000).toFixed(1).replace(/\.0$/, '')}万`
: part
return (
<span
key={`${part}-${index}`}
className={styles.narrativeNumber}
title={compact === part ? undefined : part}
>
{compact}
</span>
)
})}
</>
)
}
const NAV_ITEMS = [
{ id: 'review-overall', label: '整体达成' },
{ id: 'review-channel', label: '渠道' },
@ -217,6 +384,13 @@ function fmtMoney(value: number | null | undefined) {
return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}
function fmtCompactMetric(value: number | null | undefined, percent = false) {
if (value == null) return '—'
if (percent) return `${value.toFixed(2)}%`
if (Math.abs(value) >= 10_000) return `${(value / 10_000).toFixed(1)}万`
return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}
function deltaClass(value: number | null | undefined) {
if (value == null || Math.abs(value) < 0.005) return styles.deltaNeutral
return value > 0 ? styles.deltaPositive : styles.deltaNegative
@ -320,6 +494,8 @@ function TableShell({
description,
minWidth,
autoWidth = false,
colGroup,
tableWidth,
showHeading = false,
children,
}: {
@ -327,9 +503,12 @@ function TableShell({
description?: string
minWidth: number
autoWidth?: boolean
colGroup?: React.ReactNode
tableWidth?: number
showHeading?: boolean
children: React.ReactNode
}) {
const effectiveWidth = Math.max(minWidth, tableWidth ?? minWidth)
return (
<div className={styles.tableCard}>
{showHeading && (
@ -343,9 +522,13 @@ function TableShell({
)}
<div className={styles.tableScroller}>
<table
className={`${styles.table} ${autoWidth ? styles.autoTable : ''}`}
style={{ minWidth }}
className={`${styles.table} ${autoWidth ? styles.autoTable : ''} ${colGroup ? styles.resizableTable : ''}`}
style={{
minWidth,
width: colGroup ? `max(100%, ${effectiveWidth}px)` : undefined,
}}
>
{colGroup}
{children}
</table>
</div>
@ -374,6 +557,24 @@ function OverallTable({
compareLabel: string
hasComparison: boolean
}) {
const columns = [
tableColumn('type', '类型', 104),
tableColumn('taskQty', '清货任务', 96),
tableColumn('clearedQty', '销售件数', 96),
tableColumn('sendQty', '发货件数', 96),
tableColumn('completionRate', '清货完成率', 112),
tableColumn('weight', '权重', 80),
tableColumn('realPerformance', '真实业绩', 122),
tableColumn('actualGoodsValue', '发货实际货值', 132),
tableColumn('settleGoodsValue', '发货结算货值', 132),
tableColumn('sendFreight', '发货运费', 112),
tableColumn('actualMargin', '发货实际毛利率', 132),
tableColumn('settleMargin', '发货结算毛利率', 132),
tableColumn('recoveryValue', '回收货值(预估)', 142),
tableColumn('recoveryRate', '货值回收率(预估)', 142),
]
const resizable = useResizableColumns('supply-chain.clearance.review-overall-columns.v1', columns)
const column = (key: string) => columns.find((item) => item.key === key)!
const taskTypeAnalysis = analysisBucket(analysis, 'taskType')
const currentRows = taskTypeAnalysis.current ?? []
const compareRows = taskTypeAnalysis.compare ?? []
@ -404,23 +605,25 @@ function OverallTable({
title="整体清货达成"
description="按固定、优先、非优先三类任务展示核心经营结果"
minWidth={1760}
colGroup={resizable.colGroup}
tableWidth={resizable.totalWidth}
>
<thead>
<tr>
<th className={styles.stickyColumn}>类型</th>
<th className="text-end">清货任务</th>
<th className="text-end">销售件数</th>
<th className="text-end">发货件数</th>
<th className="text-end">清货完成率</th>
<th className="text-end">权重</th>
<th className="text-end">真实业绩</th>
<th className="text-end">发货实际货值</th>
<th className="text-end">发货结算货值</th>
<th className="text-end">发货运费</th>
<th className="text-end">发货实际毛利率</th>
<th className="text-end">发货结算毛利率</th>
<th className="text-end">回收货值(预估)</th>
<th className="text-end">货值回收率(预估)</th>
<th aria-label="类型" className={styles.stickyColumn}>类型{resizable.resizeHandle(column('type'))}</th>
<th aria-label="清货任务" className="text-end">清货任务{resizable.resizeHandle(column('taskQty'))}</th>
<th aria-label="销售件数" className="text-end">销售件数{resizable.resizeHandle(column('clearedQty'))}</th>
<th aria-label="发货件数" className="text-end">发货件数{resizable.resizeHandle(column('sendQty'))}</th>
<th aria-label="清货完成率" className="text-end">清货完成率{resizable.resizeHandle(column('completionRate'))}</th>
<th aria-label="权重" className="text-end">权重{resizable.resizeHandle(column('weight'))}</th>
<th aria-label="真实业绩" className="text-end">真实业绩{resizable.resizeHandle(column('realPerformance'))}</th>
<th aria-label="发货实际货值" className="text-end">发货实际货值{resizable.resizeHandle(column('actualGoodsValue'))}</th>
<th aria-label="发货结算货值" className="text-end">发货结算货值{resizable.resizeHandle(column('settleGoodsValue'))}</th>
<th aria-label="发货运费" className="text-end">发货运费{resizable.resizeHandle(column('sendFreight'))}</th>
<th aria-label="发货实际毛利率" className="text-end">发货实际毛利率{resizable.resizeHandle(column('actualMargin'))}</th>
<th aria-label="发货结算毛利率" className="text-end">发货结算毛利率{resizable.resizeHandle(column('settleMargin'))}</th>
<th aria-label="回收货值(预估)" className="text-end">回收货值(预估){resizable.resizeHandle(column('recoveryValue'))}</th>
<th aria-label="货值回收率(预估)" className="text-end">货值回收率(预估){resizable.resizeHandle(column('recoveryRate'))}</th>
</tr>
</thead>
<tbody>
@ -506,6 +709,19 @@ function LedgerTable({
hasComparison: boolean
}) {
const headers = dimensionHeaders(dimension)
const columns = [
...headers.map((header, index) => tableColumn(
`dimension-${index}`,
header,
index === 0 ? 120 : 108,
)),
...MATRIX_METRICS.map((metric) => tableColumn(metric.key, metric.label)),
]
const resizable = useResizableColumns(
`supply-chain.clearance.review-ledger-columns.v1.${dimension}`,
columns,
)
const column = (key: string) => columns.find((item) => item.key === key)!
const composite = dimension === 'deptHead' || dimension === 'ownerDetail'
const compareByKey = rowsByReviewKey(compareRows, composite)
const rows = currentRows ?? []
@ -526,24 +742,32 @@ function LedgerTable({
)
return (
<TableShell title={title} description={description} minWidth={1900}>
<TableShell
title={title}
description={description}
minWidth={1900}
colGroup={resizable.colGroup}
tableWidth={resizable.totalWidth}
>
<thead>
<tr>
{headers.map((header, index) => (
<th key={header} className={index === 0 ? styles.stickyColumn : undefined}>{header}</th>
<th key={header} aria-label={header} className={index === 0 ? styles.stickyColumn : undefined}>
{header}{resizable.resizeHandle(column(`dimension-${index}`))}
</th>
))}
<th className="text-end">清货任务</th>
<th className="text-end">销售件数</th>
<th className="text-end">发货件数</th>
<th className="text-end">清货完成率</th>
<th className="text-end">真实业绩</th>
<th className="text-end">发货实际货值</th>
<th className="text-end">发货结算货值</th>
<th className="text-end">发货运费</th>
<th className="text-end">发货实际毛利率</th>
<th className="text-end">发货结算毛利率</th>
<th className="text-end">回收货值(预估)</th>
<th className="text-end">货值回收率(预估)</th>
<th aria-label="清货任务" className="text-end">清货任务{resizable.resizeHandle(column('taskQty'))}</th>
<th aria-label="销售件数" className="text-end">销售件数{resizable.resizeHandle(column('clearedQty'))}</th>
<th aria-label="发货件数" className="text-end">发货件数{resizable.resizeHandle(column('sendQty'))}</th>
<th aria-label="清货完成率" className="text-end">清货完成率{resizable.resizeHandle(column('completionRate'))}</th>
<th aria-label="真实业绩" className="text-end">真实业绩{resizable.resizeHandle(column('realPerformance'))}</th>
<th aria-label="发货实际货值" className="text-end">发货实际货值{resizable.resizeHandle(column('actualGoodsValue'))}</th>
<th aria-label="发货结算货值" className="text-end">发货结算货值{resizable.resizeHandle(column('settleGoodsValue'))}</th>
<th aria-label="发货运费" className="text-end">发货运费{resizable.resizeHandle(column('sendFreight'))}</th>
<th aria-label="发货实际毛利率" className="text-end">发货实际毛利率{resizable.resizeHandle(column('actualMargin'))}</th>
<th aria-label="发货结算毛利率" className="text-end">发货结算毛利率{resizable.resizeHandle(column('settleMargin'))}</th>
<th aria-label="回收货值(预估)" className="text-end">回收货值(预估){resizable.resizeHandle(column('recoveryValue'))}</th>
<th aria-label="货值回收率(预估)" className="text-end">货值回收率(预估){resizable.resizeHandle(column('recoveryRate'))}</th>
</tr>
</thead>
<tbody>
@ -652,6 +876,25 @@ function MatrixTable({
const colSpan = splitMetrics.length * taskTypeColumns.length
+ totalOnlyMetrics.length
+ dimensionColumnCount
const columns = [
...(compositeBase
? [
tableColumn('dimension-department', '部门', 120),
tableColumn('dimension-director', '部门负责人', 108),
]
: [tableColumn('dimension-label', baseDimension === 'channel' ? '利润中心' : '折扣', 120)]),
...splitMetrics.flatMap((metric) => taskTypeColumns.map((type) => tableColumn(
`${metric.key}.${type.key}`,
type.key === 'subtotal' ? metric.label : `${metric.label}·${type.label}`,
metric.key === 'completionRate' ? 112 : 96,
))),
...totalOnlyMetrics.map((metric) => tableColumn(metric.key, metric.label)),
]
const resizable = useResizableColumns(
`supply-chain.clearance.review-matrix-columns.v2.${baseDimension}`,
columns,
)
const column = (key: string) => columns.find((item) => item.key === key)!
const comparisonCell = (
current: number | null | undefined,
previous: number | null | undefined,
@ -671,13 +914,22 @@ function MatrixTable({
<TableShell
title={title}
description={description}
minWidth={hasComparison ? 4300 : 3900}
minWidth={resizable.totalWidth}
colGroup={resizable.colGroup}
tableWidth={resizable.totalWidth}
autoWidth
>
<thead>
<tr>
<th rowSpan={2} className={styles.stickyColumn}>{compositeBase ? '部门' : '维度'}</th>
{compositeBase && <th rowSpan={2}>部门负责人</th>}
<th aria-label={compositeBase ? '部门' : '维度'} rowSpan={2} className={styles.stickyColumn}>
{compositeBase ? '部门' : '维度'}
{resizable.resizeHandle(column(compositeBase ? 'dimension-department' : 'dimension-label'))}
</th>
{compositeBase && (
<th aria-label="部门负责人" rowSpan={2}>
部门负责人{resizable.resizeHandle(column('dimension-director'))}
</th>
)}
{splitMetrics.map((metric) => (
<th
key={metric.key}
@ -688,14 +940,21 @@ function MatrixTable({
</th>
))}
{totalOnlyMetrics.map((metric) => (
<th key={metric.key} rowSpan={2} className={`${styles.groupHeader} ${styles.totalMetricHeader}`}>
{metric.label}
<th
key={metric.key}
aria-label={metric.label}
rowSpan={2}
className={`${styles.groupHeader} ${styles.totalMetricHeader}`}
>
{metric.label}{resizable.resizeHandle(column(metric.key))}
</th>
))}
</tr>
<tr>
{splitMetrics.flatMap((metric) => taskTypeColumns.map((type) => (
<th key={`${metric.key}-${type.key}`} className="text-end">{type.label}</th>
<th key={`${metric.key}-${type.key}`} aria-label={type.label} className="text-end">
{type.label}{resizable.resizeHandle(column(`${metric.key}.${type.key}`))}
</th>
)))}
</tr>
</thead>
@ -836,24 +1095,55 @@ export function ClearanceReviewAnalysis({
</div>
<span className={styles.narrativeBadge}>基于当前复盘汇总自动生成</span>
</header>
<p className={styles.narrativeOverview}>{narrative.overview}</p>
<p className={styles.narrativeOverview}><NarrativeText text={narrative.overview} /></p>
{narrative.profitCenters.length > 0 && (
<div className={styles.profitCenterAnalysis}>
<div className={styles.profitCenterHeading}>
<b>利润中心分析</b>
<span>重点分析 {narrative.focusProfitCenter || '运营中心A'}</span>
</div>
<div className={styles.profitCenterGrid}>
{narrative.profitCenters.map((row) => (
<div
key={row.label}
className={`${styles.profitCenterItem} ${row.label === narrative.focusProfitCenter ? styles.profitCenterFocus : ''}`}
>
<strong>{row.label}</strong>
<dl>
<div><dt>清货任务</dt><dd>{fmtCompactMetric(row.taskQty)}</dd></div>
<div><dt>销量</dt><dd>{fmtCompactMetric(row.clearedQty)}</dd></div>
<div><dt>完成率</dt><dd>{fmtCompactMetric(row.completionRate, true)}</dd></div>
<div><dt>结算毛利率</dt><dd>{fmtCompactMetric(row.settleMargin, true)}</dd></div>
<div><dt>货值回收率</dt><dd>{fmtCompactMetric(row.recoveryRate, true)}</dd></div>
</dl>
</div>
))}
</div>
</div>
)}
<div className={styles.narrativeGrid}>
<div className={styles.narrativeBlock}>
<b>核心结论</b>
<ul>
{narrative.conclusions.map((item) => <li key={item}>{item}</li>)}
{narrative.conclusions.map((item) => (
<li key={item}><NarrativeText text={item} /></li>
))}
</ul>
</div>
<div className={styles.narrativeBlock}>
<b>风险提示</b>
<ul>
{narrative.risks.map((item) => <li key={item}>{item}</li>)}
{narrative.risks.map((item) => (
<li key={item}><NarrativeText text={item} /></li>
))}
</ul>
</div>
<div className={styles.narrativeBlock}>
<b>建议关注</b>
<ul>
{narrative.actions.map((item) => <li key={item}>{item}</li>)}
{narrative.actions.map((item) => (
<li key={item}><NarrativeText text={item} /></li>
))}
</ul>
</div>
</div>

View File

@ -80,6 +80,22 @@ describe('clearance review narrative', () => {
expect(narrative.conclusions.join('')).toContain('运营中心A')
expect(narrative.conclusions.join('')).toContain('运营中心B')
expect(narrative.conclusions.join('')).toContain('负责人甲')
expect(narrative.focusProfitCenter).toBe('运营中心A')
expect(narrative.profitCenters).toEqual([
expect.objectContaining({
label: '运营中心A',
taskQty: 100,
clearedQty: 60,
completionRate: 82,
settleMargin: 40,
recoveryRate: 107.5,
}),
expect.objectContaining({
label: '运营中心B',
taskQty: 100,
completionRate: 48,
}),
])
expect(narrative.risks.join('')).toContain('3 条来源记录未匹配利润中心')
expect(narrative.actions.join('')).toContain('补齐未匹配利润中心')
})
@ -92,6 +108,8 @@ describe('clearance review narrative', () => {
})
expect(narrative.overview).toContain('暂无可用于文字总结')
expect(narrative.profitCenters).toEqual([])
expect(narrative.focusProfitCenter).toBe('运营中心A')
expect(narrative.risks).toHaveLength(1)
expect(narrative.actions).toHaveLength(1)
})

View File

@ -30,6 +30,15 @@ export type ClearanceReviewNarrative = {
conclusions: string[]
risks: string[]
actions: string[]
profitCenters: Array<{
label: string
taskQty: number
clearedQty: number
completionRate: number | null
settleMargin: number | null
recoveryRate: number | null
}>
focusProfitCenter: string
}
function monthLabel(value: string) {
@ -114,6 +123,8 @@ export function buildClearanceReviewNarrative(input: {
conclusions: ['请先确认该月已有已确认清货任务,并完成最终销售数据同步。'],
risks: ['当前没有可分析的主体汇总,无法判断完成率、毛利率和货值回收变化。'],
actions: ['检查任务确认状态、月度存档和销售来源数据后重新查询。'],
profitCenters: [],
focusProfitCenter: '运营中心A',
}
}
@ -163,6 +174,15 @@ export function buildClearanceReviewNarrative(input: {
`优先级维度中${weakestPriority.dimensionLabel}的完成率最低,为${fmtPct(weakestPriority.completionRate)},任务量 ${fmtInt(weakestPriority.taskQty)} 件。`,
)
}
const focusProfitCenter = channels.some((row) => row.dimensionLabel === '运营中心A')
? '运营中心A'
: channels[0]?.dimensionLabel ?? ''
const focusRow = channels.find((row) => row.dimensionLabel === focusProfitCenter)
if (focusRow) {
conclusions.unshift(
`${focusProfitCenter}清货任务 ${fmtInt(focusRow.taskQty)} 件,销量 ${fmtInt(focusRow.clearedQty)} 件,清货完成率 ${fmtPct(focusRow.completionRate)},发货结算毛利率 ${fmtPct(focusRow.settleMargin)},货值回收率 ${fmtPct(focusRow.recoveryRate)}。`,
)
}
const risks: string[] = []
if (completionDelta != null && completionDelta < -0.005) {
@ -201,5 +221,30 @@ export function buildClearanceReviewNarrative(input: {
actions.push('继续按渠道和负责人跟踪完成率、毛利率与货值回收率的月度变化。')
}
return { overview, conclusions, risks, actions }
const profitCenterOrder = ['运营中心A', '运营中心B', '运营中心C', '运营中心G', '分销部']
const profitCenters = [...channels]
.sort((left, right) => {
const leftIndex = profitCenterOrder.indexOf(left.dimensionLabel)
const rightIndex = profitCenterOrder.indexOf(right.dimensionLabel)
return (leftIndex < 0 ? profitCenterOrder.length : leftIndex)
- (rightIndex < 0 ? profitCenterOrder.length : rightIndex)
|| left.dimensionLabel.localeCompare(right.dimensionLabel, 'zh-CN')
})
.map((row) => ({
label: row.dimensionLabel,
taskQty: row.taskQty,
clearedQty: row.clearedQty,
completionRate: row.completionRate,
settleMargin: row.settleMargin,
recoveryRate: row.recoveryRate,
}))
return {
overview,
conclusions,
risks,
actions,
profitCenters,
focusProfitCenter,
}
}

View File

@ -102,4 +102,51 @@ describe('clearance review archive compatibility', () => {
excludedDepartments: new Set(['事业一部']),
})).toBeNull()
})
it('uses current owner organization instead of a person-valued legacy department', () => {
const snapshots = rebuildLegacyClearanceReviewSnapshots({
monthKey: '2026-11',
sourceSnapshot: {
version: 1,
tasks: [{
barcode: 'SKU-ORG',
status: 'APPROVED',
round: 1,
taskQty: 9,
clearedQty: 4,
ownerName: '苏若兰',
profitCenter: '运营中心A',
department: '苏若兰',
updatedAt: '2026-11-02T00:00:00.000Z',
}],
poolRows: [{
barcode: 'SKU-ORG',
department: '苏若兰',
directorName: '旧负责人',
extra: { priority: 'A 固定任务' },
}],
review: {
details: [],
snapshots: [{
dimension: 'ownerDetail',
dimensionKey: buildClearanceReviewKey('苏若兰', '無尘/灵犀', '苏若兰'),
}],
},
},
organizationByOwner: new Map([[
'苏若兰',
{ department: '事业二部', directorName: '苏若兰' },
]]),
})
expect(snapshots).toContainEqual(expect.objectContaining({
dimension: 'deptHead',
dimensionKey: buildClearanceReviewKey('事业二部', '苏若兰'),
taskQty: 9,
}))
expect(snapshots).not.toContainEqual(expect.objectContaining({
dimension: 'deptHead',
dimensionKey: buildClearanceReviewKey('苏若兰', '無尘/灵犀'),
}))
})
})

View File

@ -22,6 +22,11 @@ type ArchiveSourceSnapshot = {
}
}
type OwnerOrganization = {
department: string
directorName: string
}
function number(value: unknown) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
@ -38,7 +43,7 @@ function discountLabel(value: unknown) {
}
function ownerOrganizationMap(source: ArchiveSourceSnapshot) {
const result = new Map<string, { department: string; directorName: string }>()
const result = new Map<string, OwnerOrganization>()
for (const snapshot of source.review?.snapshots ?? []) {
if (snapshot.dimension !== 'ownerDetail') continue
const [department, directorName, ownerName] = splitClearanceReviewKey(
@ -49,6 +54,31 @@ function ownerOrganizationMap(source: ArchiveSourceSnapshot) {
return result
}
function usableDepartment(value: string, ownerName: string) {
const department = value.trim()
return department && department !== ownerName ? department : ''
}
function preferredOwnerOrganization(
preferred: ReadonlyMap<string, Partial<OwnerOrganization>> | undefined,
fallback: ReadonlyMap<string, OwnerOrganization>,
ownerName: string,
poolRow: Record<string, unknown>,
) {
const current = preferred?.get(ownerName)
const legacy = fallback.get(ownerName)
return {
department: usableDepartment(current?.department ?? '', ownerName)
|| usableDepartment(text(poolRow.department), ownerName)
|| usableDepartment(legacy?.department ?? '', ownerName)
|| '未配置部门',
directorName: current?.directorName?.trim()
|| legacy?.directorName
|| text(poolRow.directorName)
|| '未配置部门负责人',
}
}
function sourceRowsFromSnapshot(source: ArchiveSourceSnapshot): ClearanceReviewSourceSaleInput[] {
return (source.review?.details ?? []).flatMap((row) => {
const barcode = text(row.barcode).toUpperCase()
@ -74,6 +104,7 @@ export function rebuildLegacyClearanceReviewSnapshots(input: {
sourceSnapshot: unknown
taskTypeMappings?: ClearancePriorityTaskTypeMapping[]
excludedDepartments?: ReadonlySet<string>
organizationByOwner?: ReadonlyMap<string, Partial<OwnerOrganization>>
}) {
const source = input.sourceSnapshot as ArchiveSourceSnapshot | null
if (!source || !Array.isArray(source.tasks) || !Array.isArray(source.poolRows)) {
@ -82,7 +113,7 @@ export function rebuildLegacyClearanceReviewSnapshots(input: {
const poolByBarcode = new Map(
source.poolRows.map((row) => [text(row.barcode).toUpperCase(), row]),
)
const organizationByOwner = ownerOrganizationMap(source)
const legacyOrganizationByOwner = ownerOrganizationMap(source)
const tasks = source.tasks.flatMap((task): ClearanceReviewTask[] => {
if (task.status !== 'APPROVED') return []
const barcode = text(task.barcode).toUpperCase()
@ -92,10 +123,15 @@ export function rebuildLegacyClearanceReviewSnapshots(input: {
? poolRow.extra as Record<string, unknown>
: {}
const ownerName = text(task.ownerName)
const organization = organizationByOwner.get(ownerName)
const organization = preferredOwnerOrganization(
input.organizationByOwner,
legacyOrganizationByOwner,
ownerName,
poolRow,
)
const profitCenter = text(task.profitCenter) || text(extra.profitCenter)
const priority = text(task.priorityOverride) || text(extra.priority)
const department = organization?.department || text(poolRow.department)
const department = organization.department
if (input.excludedDepartments?.has(department)) return []
return [{
barcode,
@ -108,7 +144,7 @@ export function rebuildLegacyClearanceReviewSnapshots(input: {
status: text(task.status),
channel: profitCenter,
department,
directorName: organization?.directorName || text(poolRow.directorName),
directorName: organization.directorName,
ownerName,
priority,
discountLabel: discountLabel(task.discount),

View File

@ -7716,8 +7716,16 @@ class SupplyChainClearanceService {
: []
)),
))
const sourceOwnerProfiles = sourceOwners.length
? await supplyChainClearanceRepository.listOwnerProfilesByNames(sourceOwners)
const sourceOrganizationNames = Array.from(new Set([
...sourceOwners,
...sourceTasks.flatMap((task) => (
task.status === 'APPROVED' && String(task.department ?? '').trim()
? [String(task.department).trim()]
: []
)),
]))
const sourceOwnerProfiles = sourceOrganizationNames.length
? await supplyChainClearanceRepository.listOwnerProfilesByNames(sourceOrganizationNames)
: []
const excludedDepartments = new Set(sourceOwnerProfiles.flatMap((profile) => (
profile.profitCenter && !isClearanceTaskProfitCenter(profile.profitCenter)
@ -7734,12 +7742,64 @@ class SupplyChainClearanceService {
Array.from(new Set(sourceBarcodes)),
)
: []
const currentPoolByBarcode = new Map(currentPoolRows.map((row) => [
row.barcode.trim().toUpperCase(),
row,
]))
const currentExtraByBarcode = new Map(currentPoolRows.map((row) => [
row.barcode.trim().toUpperCase(),
row.extra && typeof row.extra === 'object'
? row.extra as Record<string, unknown>
: {},
]))
const profileByOwner = new Map(sourceOwnerProfiles.map((profile) => [
profile.operationOwner.trim(),
profile,
]))
const departmentByOrganizationName = new Map<string, string>()
for (const profile of sourceOwnerProfiles) {
const department = profile.department?.trim()
if (!department) continue
departmentByOrganizationName.set(profile.operationOwner.trim(), department)
for (const directorName of String(profile.departmentOwner ?? '').split(/[\/、,,\s]+/)) {
const normalized = directorName.trim()
if (normalized) departmentByOrganizationName.set(normalized, department)
}
}
const organizationByOwner = new Map<string, {
department: string
directorName: string
}>()
for (const ownerName of sourceOwners) {
const sourceTask = sourceTasks.find((task) => (
task.status === 'APPROVED'
&& String(task.ownerName ?? '').trim() === ownerName
))
const barcode = String(sourceTask?.barcode ?? '').trim().toUpperCase()
const poolItem = currentPoolByBarcode.get(barcode)
const extra = currentExtraByBarcode.get(barcode) ?? {}
const profile = profileByOwner.get(ownerName)
const organization = clearanceReviewOrganization({
ownerName,
taskDepartment: String(sourceTask?.department ?? '').trim(),
poolDirectorName: poolItem?.directorName,
poolDepartmentOwner: extra.effectiveDepartmentOwner,
profile,
})
const rawDepartment = organization.department
const department = profile?.department?.trim()
|| (
rawDepartment !== ownerName && rawDepartment !== '未配置部门'
? departmentByOrganizationName.get(rawDepartment) ?? rawDepartment
: ''
)
const directorName = organization.directorName === '未配置部门负责人'
? ''
: organization.directorName
if (department || directorName) {
organizationByOwner.set(ownerName, { department, directorName })
}
}
const rawSource = (
archive.sourceSnapshot
&& typeof archive.sourceSnapshot === 'object'
@ -7776,6 +7836,7 @@ class SupplyChainClearanceService {
archive.generatedAt.toISOString(),
JSON.stringify(Array.from(taskTypeMappingByPriority)),
JSON.stringify(Array.from(excludedDepartments).sort()),
JSON.stringify(Array.from(organizationByOwner).sort()),
].join('\u0000')
const corrected = legacyClearanceReviewSnapshotCache.get(cacheKey)
?? rebuildLegacyClearanceReviewSnapshots({
@ -7786,6 +7847,7 @@ class SupplyChainClearanceService {
taskType,
})),
excludedDepartments,
organizationByOwner,
})
if (corrected && !legacyClearanceReviewSnapshotCache.has(cacheKey)) {
legacyClearanceReviewSnapshotCache.set(cacheKey, corrected as unknown[])