diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.module.css b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.module.css index 449760e6a..f5fb78dac 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.module.css +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.module.css @@ -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)); + } } diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.test.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.test.tsx index 78dd2f819..ebfacb5cd 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.test.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.test.tsx @@ -34,7 +34,11 @@ function row(overrides: Partial = {}): 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() diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.tsx index f8f9bb50c..c2cd1d7f4 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewAnalysis.tsx @@ -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 + : {} + } catch { + return {} + } +} + +function writeColumnWidths(storageKey: string, widths: Record) { + 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, + 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) => ( + 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 = ( + + {columns.map((column) => ( + + ))} + + ) + + 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 ( + + {compact} + + ) + })} + + ) +} + 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 (
{showHeading && ( @@ -343,9 +522,13 @@ function TableShell({ )}
+ {colGroup} {children}
@@ -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} > - 类型 - 清货任务 - 销售件数 - 发货件数 - 清货完成率 - 权重 - 真实业绩 - 发货实际货值 - 发货结算货值 - 发货运费 - 发货实际毛利率 - 发货结算毛利率 - 回收货值(预估) - 货值回收率(预估) + 类型{resizable.resizeHandle(column('type'))} + 清货任务{resizable.resizeHandle(column('taskQty'))} + 销售件数{resizable.resizeHandle(column('clearedQty'))} + 发货件数{resizable.resizeHandle(column('sendQty'))} + 清货完成率{resizable.resizeHandle(column('completionRate'))} + 权重{resizable.resizeHandle(column('weight'))} + 真实业绩{resizable.resizeHandle(column('realPerformance'))} + 发货实际货值{resizable.resizeHandle(column('actualGoodsValue'))} + 发货结算货值{resizable.resizeHandle(column('settleGoodsValue'))} + 发货运费{resizable.resizeHandle(column('sendFreight'))} + 发货实际毛利率{resizable.resizeHandle(column('actualMargin'))} + 发货结算毛利率{resizable.resizeHandle(column('settleMargin'))} + 回收货值(预估){resizable.resizeHandle(column('recoveryValue'))} + 货值回收率(预估){resizable.resizeHandle(column('recoveryRate'))} @@ -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 ( - + {headers.map((header, index) => ( - {header} + + {header}{resizable.resizeHandle(column(`dimension-${index}`))} + ))} - 清货任务 - 销售件数 - 发货件数 - 清货完成率 - 真实业绩 - 发货实际货值 - 发货结算货值 - 发货运费 - 发货实际毛利率 - 发货结算毛利率 - 回收货值(预估) - 货值回收率(预估) + 清货任务{resizable.resizeHandle(column('taskQty'))} + 销售件数{resizable.resizeHandle(column('clearedQty'))} + 发货件数{resizable.resizeHandle(column('sendQty'))} + 清货完成率{resizable.resizeHandle(column('completionRate'))} + 真实业绩{resizable.resizeHandle(column('realPerformance'))} + 发货实际货值{resizable.resizeHandle(column('actualGoodsValue'))} + 发货结算货值{resizable.resizeHandle(column('settleGoodsValue'))} + 发货运费{resizable.resizeHandle(column('sendFreight'))} + 发货实际毛利率{resizable.resizeHandle(column('actualMargin'))} + 发货结算毛利率{resizable.resizeHandle(column('settleMargin'))} + 回收货值(预估){resizable.resizeHandle(column('recoveryValue'))} + 货值回收率(预估){resizable.resizeHandle(column('recoveryRate'))} @@ -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({ - {compositeBase ? '部门' : '维度'} - {compositeBase && 部门负责人} + + {compositeBase ? '部门' : '维度'} + {resizable.resizeHandle(column(compositeBase ? 'dimension-department' : 'dimension-label'))} + + {compositeBase && ( + + 部门负责人{resizable.resizeHandle(column('dimension-director'))} + + )} {splitMetrics.map((metric) => ( ))} {totalOnlyMetrics.map((metric) => ( - - {metric.label} + + {metric.label}{resizable.resizeHandle(column(metric.key))} ))} {splitMetrics.flatMap((metric) => taskTypeColumns.map((type) => ( - {type.label} + + {type.label}{resizable.resizeHandle(column(`${metric.key}.${type.key}`))} + )))} @@ -836,24 +1095,55 @@ export function ClearanceReviewAnalysis({
基于当前复盘汇总自动生成 -

{narrative.overview}

+

+ {narrative.profitCenters.length > 0 && ( +
+
+ 利润中心分析 + 重点分析 {narrative.focusProfitCenter || '运营中心A'} +
+
+ {narrative.profitCenters.map((row) => ( +
+ {row.label} +
+
清货任务
{fmtCompactMetric(row.taskQty)}
+
销量
{fmtCompactMetric(row.clearedQty)}
+
完成率
{fmtCompactMetric(row.completionRate, true)}
+
结算毛利率
{fmtCompactMetric(row.settleMargin, true)}
+
货值回收率
{fmtCompactMetric(row.recoveryRate, true)}
+
+
+ ))} +
+
+ )}
核心结论
    - {narrative.conclusions.map((item) =>
  • {item}
  • )} + {narrative.conclusions.map((item) => ( +
  • + ))}
风险提示
    - {narrative.risks.map((item) =>
  • {item}
  • )} + {narrative.risks.map((item) => ( +
  • + ))}
建议关注
    - {narrative.actions.map((item) =>
  • {item}
  • )} + {narrative.actions.map((item) => ( +
  • + ))}
diff --git a/furniture-3d-system/src/lib/clearance-review-summary.test.ts b/furniture-3d-system/src/lib/clearance-review-summary.test.ts index bbe52bf47..2121ed610 100644 --- a/furniture-3d-system/src/lib/clearance-review-summary.test.ts +++ b/furniture-3d-system/src/lib/clearance-review-summary.test.ts @@ -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) }) diff --git a/furniture-3d-system/src/lib/clearance-review-summary.ts b/furniture-3d-system/src/lib/clearance-review-summary.ts index f122b4215..47d93513d 100644 --- a/furniture-3d-system/src/lib/clearance-review-summary.ts +++ b/furniture-3d-system/src/lib/clearance-review-summary.ts @@ -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, + } } diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive-compat.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive-compat.test.ts index 767a3cbae..1c1bd1453 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive-compat.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive-compat.test.ts @@ -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('苏若兰', '無尘/灵犀'), + })) + }) }) diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive-compat.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive-compat.ts index 5acc7b13e..946f539cc 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive-compat.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive-compat.ts @@ -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() + const result = new Map() 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> | undefined, + fallback: ReadonlyMap, + ownerName: string, + poolRow: Record, +) { + 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 + organizationByOwner?: ReadonlyMap> }) { 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 : {} 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), diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts index 36815522d..e524939c4 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts @@ -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 : {}, ])) + const profileByOwner = new Map(sourceOwnerProfiles.map((profile) => [ + profile.operationOwner.trim(), + profile, + ])) + const departmentByOrganizationName = new Map() + 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() + 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[])