From 9629f6edc034fe4e1da123d27191920fba554f69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Tue, 24 Nov 2026 09:49:36 +0800 Subject: [PATCH] =?UTF-8?q?fix(clearance):=20=E5=90=88=E5=B9=B6=E5=A4=8D?= =?UTF-8?q?=E7=9B=98=E6=B8=B2=E6=9F=93=E4=B8=8E=E6=B8=85=E8=B4=A7=E6=B1=A0?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E7=94=9F=E6=88=90=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../supply-chain/clearance/generate/route.ts | 20 ++++- .../ClearanceReviewAnalysis.test.tsx | 20 +++++ .../clearance/ClearanceReviewAnalysis.tsx | 67 ++++++++++------ .../management/clearance/ClearanceView.tsx | 61 +++++++++++---- .../supply-chain-clearance.service.test.ts | 42 ++++++++++ .../supply-chain-clearance.service.ts | 77 +++++++++++++++++++ 6 files changed, 246 insertions(+), 41 deletions(-) diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/generate/route.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/generate/route.ts index c9832d53..9f151721 100644 --- a/furniture-3d-system/src/app/api/supply-chain/clearance/generate/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/generate/route.ts @@ -24,12 +24,28 @@ export async function POST(request: NextRequest) { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '清货月份格式必须为 YYYY-MM', 400, ctx.requestId) } return jsonSuccess( - await supplyChainClearanceService.generatePool({ + supplyChainClearanceService.startPoolGeneration({ periodKey: parsed.data.periodKey, mode: parsed.data.mode, user: ctx.user, }), - 201, + 202, + ctx.requestId, + ) + }, + { requireAuth: true }, + ) +} + +export async function GET(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + return jsonSuccess( + supplyChainClearanceService.getPoolGenerationJob( + request.nextUrl.searchParams.get('periodKey'), + ), + 200, ctx.requestId, ) }, 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 a9fb09b5..d8490b92 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 @@ -71,4 +71,24 @@ describe('ClearanceReviewAnalysis', () => { expect(screen.getAllByText('发货结算毛利率').length).toBeGreaterThan(0) expect(screen.getAllByText('环比').length).toBeGreaterThan(0) }) + + it('renders safely when a deployed server returns a partial analysis payload', () => { + const empty = { current: rows(), compare: rows() } + render( + , + ) + + expect(screen.getByText('月度清货分析汇总')).toBeInTheDocument() + expect(screen.getByText('十、清货优先级达成率')).toBeInTheDocument() + expect(screen.getByText('十一、SPU负责人 / 运营负责人清货情况')).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 e457d569..cdb11949 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 @@ -57,9 +57,11 @@ const TASK_TYPES: Array<{ key: TaskType; label: string }> = [ { key: 'normal', label: '非优先任务' }, ] -function monthLabel(value: string) { - const [, month] = value.split('-') - return month ? `${Number(month)}月` : value +function monthLabel(value: string | null | undefined) { + const text = String(value ?? '').trim() + if (!text) return '—' + const [, month] = text.split('-') + return month ? `${Number(month)}月` : text } function fmtInt(value: number | null | undefined) { @@ -81,23 +83,34 @@ function fmtMoney(value: number | null | undefined) { return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) } -function withoutTotal(rows: ClearanceReviewAnalysisRow[]) { - return rows.filter((row) => row.dimensionKey !== 'total') +function withoutTotal(rows: ClearanceReviewAnalysisRow[] | null | undefined) { + return (rows ?? []).filter((row) => row.dimensionKey !== 'total') } function baseRow( - rows: ClearanceReviewAnalysisRow[], + rows: ClearanceReviewAnalysisRow[] | null | undefined, key: string, ) { - return rows.find((row) => row.dimensionKey === key) ?? null + return (rows ?? []).find((row) => row.dimensionKey === key) ?? null } function taskTypeRow( - rows: ClearanceReviewAnalysisRow[], + rows: ClearanceReviewAnalysisRow[] | null | undefined, baseKey: string, taskType: TaskType, ) { - return rows.find((row) => row.dimensionKey === `${baseKey}\u0000${taskType}`) ?? null + return (rows ?? []).find((row) => row.dimensionKey === `${baseKey}\u0000${taskType}`) ?? null +} + +function emptyAnalysisBucket() { + return { current: [] as ClearanceReviewAnalysisRow[], compare: [] as ClearanceReviewAnalysisRow[] } +} + +function analysisBucket( + analysis: ClearanceReviewAnalysisData, + dimension: ClearanceReviewAnalysisDimension, +) { + return analysis[dimension] ?? emptyAnalysisBucket() } function metricDelta( @@ -127,10 +140,12 @@ function MatrixTable({ metric: Metric analysis: ClearanceReviewAnalysisData }) { - const currentBaseRows = withoutTotal(analysis[baseDimension].current) - const compareBaseRows = withoutTotal(analysis[baseDimension].compare) - const totalCurrent = baseRow(analysis[baseDimension].current, 'total') - const totalCompare = baseRow(analysis[baseDimension].compare, 'total') + const baseAnalysis = analysisBucket(analysis, baseDimension) + const compositeAnalysis = analysisBucket(analysis, compositeDimension) + const currentBaseRows = withoutTotal(baseAnalysis.current) + const compareBaseRows = withoutTotal(baseAnalysis.compare) + const totalCurrent = baseRow(baseAnalysis.current, 'total') + const totalCompare = baseRow(baseAnalysis.compare, 'total') const renderValue = metric === 'completionRate' ? fmtPct : fmtPct return (
@@ -162,12 +177,12 @@ function MatrixTable({ {row.dimensionLabel} {TASK_TYPES.flatMap((type) => { const current = taskTypeRow( - analysis[compositeDimension].current, + compositeAnalysis.current, row.dimensionKey, type.key, ) const previous = taskTypeRow( - analysis[compositeDimension].compare, + compositeAnalysis.compare, row.dimensionKey, type.key, ) @@ -187,8 +202,9 @@ function MatrixTable({ 总计 {TASK_TYPES.flatMap((type) => { - const current = baseRow(analysis.taskType.current, type.key) - const previous = baseRow(analysis.taskType.compare, type.key) + const taskTypeAnalysis = analysisBucket(analysis, 'taskType') + const current = baseRow(taskTypeAnalysis.current, type.key) + const previous = baseRow(taskTypeAnalysis.compare, type.key) return [ {renderValue(previous?.[metric])}, {renderValue(current?.[metric])}, @@ -252,7 +268,7 @@ function DetailTable({ {detailRows.map((row) => { - const [department, director, owner] = row.dimensionKey.split('\u0000') + const [department, director, owner] = String(row.dimensionKey ?? '').split('\u0000') return ( {monthLabel(row.monthKey)} @@ -315,19 +331,20 @@ export function ClearanceReviewAnalysis({ periodKey: string compareKey: string analysis: ClearanceReviewAnalysisData - taskTypeWeights: Record + taskTypeWeights?: Record | null }) { - const currentTaskTypes = withoutTotal(analysis.taskType.current) - const compareTaskTypes = withoutTotal(analysis.taskType.compare) + const taskTypeAnalysis = analysisBucket(analysis, 'taskType') + const currentTaskTypes = withoutTotal(taskTypeAnalysis.current) + const compareTaskTypes = withoutTotal(taskTypeAnalysis.compare) const taskTypeRows = TASK_TYPES.flatMap((type) => { const current = baseRow(currentTaskTypes, type.key) const previous = baseRow(compareTaskTypes, type.key) return [previous, current].filter((row): row is ClearanceReviewAnalysisRow => Boolean(row)) - .map((row) => ({ row, weight: taskTypeWeights[type.key] })) + .map((row) => ({ row, weight: taskTypeWeights?.[type.key] ?? 0 })) }) - const priorityRows = analysis.priority.current - const ownerRows = analysis.ownerDetail.current - const foshanRows = withoutTotal(analysis.channelPriority.current).filter((row) => ( + const priorityRows = analysisBucket(analysis, 'priority').current + const ownerRows = analysisBucket(analysis, 'ownerDetail').current + const foshanRows = withoutTotal(analysisBucket(analysis, 'channelPriority').current).filter((row) => ( row.dimensionKey.includes('佛山') )) diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx index 4843ef11..b405861f 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx @@ -86,6 +86,20 @@ type ComboNotificationResult = { message: string } +type PoolGenerationJob = { + periodKey: string + mode: GenerateMode + status: 'RUNNING' | 'COMPLETED' | 'FAILED' + startedAt: string + finishedAt: string | null + error: string + result: { + rowCount: number + regenerated: boolean + comboNotification?: ComboNotificationResult + } | null +} + type PoolRow = { id: string periodKey: string @@ -546,9 +560,11 @@ function clearanceProgressTargetDate(periodKey: string) { return yesterday < monthEnd ? yesterday : monthEnd } -function monthLabel(value: string) { - const [year, month] = value.split('-') - return year && month ? `${year}年${Number(month)}月` : value +function monthLabel(value: string | null | undefined) { + const text = String(value ?? '').trim() + if (!text) return '—' + const [year, month] = text.split('-') + return year && month ? `${year}年${Number(month)}月` : text } function taskRecordLabel(round: number) { @@ -1591,17 +1607,34 @@ export function ClearanceView({ let generationMessage = '' let generationNotification = '' if (windowGenerateMode !== 'NONE') { - const generation = await requestJson<{ - rowCount: number - regenerated: boolean - comboNotification?: ComboNotificationResult - }>('/api/supply-chain/clearance/generate', { + let job = await requestJson('/api/supply-chain/clearance/generate', { method: 'POST', body: JSON.stringify({ periodKey: windowPeriod, mode: windowGenerateMode, }), }) + const deadline = Date.now() + 10 * 60 * 1000 + while (job.status === 'RUNNING') { + if (Date.now() >= deadline) { + throw new Error('清货池生成仍在处理中,请稍后刷新查看结果') + } + await new Promise((resolve) => window.setTimeout(resolve, 2_000)) + const nextJob = await requestJson( + `/api/supply-chain/clearance/generate?periodKey=${encodeURIComponent(windowPeriod)}`, + ) + if (!nextJob) { + throw new Error('清货池生成任务状态已丢失,请刷新页面查看结果') + } + job = nextJob + } + if (job.status === 'FAILED') { + throw new Error(job.error || '清货池生成失败') + } + if (!job.result) { + throw new Error('清货池生成任务未返回结果') + } + const generation = job.result generationMessage = windowGenerateMode === 'ROUND2_REFRESH' ? ',并已刷新二次折扣调整数据' : `,并已${generation.regenerated ? '重新' : ''}生成清货池 ${generation.rowCount} 条` @@ -2317,8 +2350,8 @@ export function ClearanceView({ return {String(value)} } - const currentReview = review?.trend.find((row) => row.monthKey === review.periodKey) ?? null - const compareReview = review?.trend.find((row) => row.monthKey === review.compareKey) ?? null + const currentReview = review?.trend?.find((row) => row.monthKey === review.periodKey) ?? null + const compareReview = review?.trend?.find((row) => row.monthKey === review.compareKey) ?? null const reviewArchivePeriod = reviewPeriod || review?.periodKey || '' const reviewArchiveBlocked = Boolean( reviewArchivePeriod && reviewArchivePeriod >= currentPeriodKey(), @@ -3492,7 +3525,7 @@ export function ClearanceView({ taskTypeWeights={review.taskTypeWeights} /> )} - {review && review.trend.length > 0 && ( + {review && Array.isArray(review.trend) && review.trend.length > 0 && ( <>
@@ -3532,8 +3565,8 @@ export function ClearanceView({ - {review.current.filter((row) => row.dimensionKey !== 'total').map((row) => { - const previous = review.compare.find((item) => item.dimensionKey === row.dimensionKey) + {(review.current ?? []).filter((row) => row.dimensionKey !== 'total').map((row) => { + const previous = (review.compare ?? []).find((item) => item.dimensionKey === row.dimensionKey) const rateDelta = row.completionRate != null && previous?.completionRate != null ? row.completionRate - previous.completionRate : null const settleDelta = row.settleMargin != null && previous?.settleMargin != null ? row.settleMargin - previous.settleMargin : null return ( @@ -3568,7 +3601,7 @@ export function ClearanceView({ /> )} - {!reviewLoading && !review?.trend.length && ( + {!reviewLoading && !review?.trend?.length && (
还没有可复盘数据 任务经管确认并产生销售出库进度后,会自动生成清货复盘。 diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts index e5eed591..b7b761d9 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts @@ -1445,6 +1445,48 @@ describe('supply-chain-clearance workflow', () => { ) }) + it('exposes background pool generation status for polling clients', async () => { + const generation = jest.spyOn(supplyChainClearanceService, 'generatePool').mockResolvedValue({ + rowCount: 3, + regenerated: false, + updatedRows: 3, + preservedRows: 0, + generationMode: 'FULL', + generation: {}, + comboNotification: { + status: 'SENT', + message: '已通知', + recipientName: '测试', + flaggedCount: 1, + abnormalCount: 1, + unequalCount: 0, + batchCount: 1, + sentBatches: 1, + failedBatches: 0, + }, + } as never) + + const started = supplyChainClearanceService.startPoolGeneration({ + periodKey: '2026-12', + user, + }) + expect(started.status).toBe('RUNNING') + + await new Promise((resolve) => setImmediate(resolve)) + expect(supplyChainClearanceService.getPoolGenerationJob('2026-12')).toMatchObject({ + status: 'COMPLETED', + result: { + rowCount: 3, + regenerated: false, + comboNotification: { + status: 'SENT', + message: '已通知', + }, + }, + }) + generation.mockRestore() + }) + it('blocks full generation of an already generated current-month pool', async () => { jest.useFakeTimers() jest.setSystemTime(new Date('2026-11-20T02:00:00.000Z')) 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 dc4f29df..ceb68e35 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 @@ -145,6 +145,26 @@ const clearanceReviewArchiveJobs = new Map() + +type ClearancePoolGenerationJob = { + periodKey: string + mode: ClearancePoolGenerationMode + status: 'RUNNING' | 'COMPLETED' | 'FAILED' + startedAt: string + finishedAt: string | null + error: string + result: { + rowCount: number + regenerated: boolean + comboNotification?: { + status: 'NOT_REQUIRED' | 'SENT' | 'FAILED' + message: string + } + } | null +} + +const clearancePoolGenerationJobs = new Map() + const EXCLUDED_CLEARANCE_BARCODES = new Set([ 'GBGJ-MPWL01N126V01', ]) @@ -1398,6 +1418,63 @@ class SupplyChainClearanceService { return active.round } + startPoolGeneration(input: { + periodKey: string + mode?: ClearancePoolGenerationMode + user: AuthUser + }) { + const periodKey = String(input.periodKey ?? '').trim() + const mode = input.mode ?? 'FULL' + const running = clearancePoolGenerationJobs.get(periodKey) + if (running?.status === 'RUNNING') return running + const job: ClearancePoolGenerationJob = { + periodKey, + mode, + status: 'RUNNING', + startedAt: new Date().toISOString(), + finishedAt: null, + error: '', + result: null, + } + clearancePoolGenerationJobs.set(periodKey, job) + void this.generatePool({ ...input, periodKey, mode }) + .then((result) => { + clearancePoolGenerationJobs.set(periodKey, { + ...job, + status: 'COMPLETED', + finishedAt: new Date().toISOString(), + result: { + rowCount: result.rowCount, + regenerated: result.regenerated, + ...(result.comboNotification ? { + comboNotification: { + status: result.comboNotification.status, + message: result.comboNotification.message, + }, + } : {}), + }, + }) + }) + .catch((error: unknown) => { + console.error('[clearance-generation] background generation failed', { + periodKey, + error, + }) + clearancePoolGenerationJobs.set(periodKey, { + ...job, + status: 'FAILED', + finishedAt: new Date().toISOString(), + error: error instanceof Error ? error.message : '生成清货池失败', + }) + }) + return job + } + + getPoolGenerationJob(periodKeyInput?: string | null) { + const periodKey = String(periodKeyInput ?? '').trim() + return clearancePoolGenerationJobs.get(periodKey) ?? null + } + async generatePool(input: { periodKey: string mode?: ClearancePoolGenerationMode