fix(clearance): 合并复盘渲染与清货池后台生成修复
This commit is contained in:
parent
6564c78396
commit
9629f6edc0
@ -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,
|
||||
)
|
||||
},
|
||||
|
||||
@ -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(
|
||||
<ClearanceReviewAnalysis
|
||||
periodKey="2026-10"
|
||||
compareKey="2026-09"
|
||||
analysis={{
|
||||
channel: empty,
|
||||
channelTaskType: empty,
|
||||
taskType: empty,
|
||||
} as never}
|
||||
taskTypeWeights={undefined}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('月度清货分析汇总')).toBeInTheDocument()
|
||||
expect(screen.getByText('十、清货优先级达成率')).toBeInTheDocument()
|
||||
expect(screen.getByText('十一、SPU负责人 / 运营负责人清货情况')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@ -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 (
|
||||
<section style={{ marginTop: 16 }}>
|
||||
@ -162,12 +177,12 @@ function MatrixTable({
|
||||
<td><b>{row.dimensionLabel}</b></td>
|
||||
{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({
|
||||
<tr>
|
||||
<td><b>总计</b></td>
|
||||
{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 [
|
||||
<td key={`${type.key}-prev`} className="text-end">{renderValue(previous?.[metric])}</td>,
|
||||
<td key={`${type.key}-current`} className="text-end"><b>{renderValue(current?.[metric])}</b></td>,
|
||||
@ -252,7 +268,7 @@ function DetailTable({
|
||||
</thead>
|
||||
<tbody>
|
||||
{detailRows.map((row) => {
|
||||
const [department, director, owner] = row.dimensionKey.split('\u0000')
|
||||
const [department, director, owner] = String(row.dimensionKey ?? '').split('\u0000')
|
||||
return (
|
||||
<tr key={row.dimensionKey}>
|
||||
<td>{monthLabel(row.monthKey)}</td>
|
||||
@ -315,19 +331,20 @@ export function ClearanceReviewAnalysis({
|
||||
periodKey: string
|
||||
compareKey: string
|
||||
analysis: ClearanceReviewAnalysisData
|
||||
taskTypeWeights: Record<TaskType, number>
|
||||
taskTypeWeights?: Record<TaskType, number> | 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('佛山')
|
||||
))
|
||||
|
||||
|
||||
@ -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<PoolGenerationJob>('/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<PoolGenerationJob | null>(
|
||||
`/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 <span className={ui.cellText} title={String(value)}>{String(value)}</span>
|
||||
}
|
||||
|
||||
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 && (
|
||||
<>
|
||||
<div style={{ padding: '0 24px' }}>
|
||||
<div style={{ border: '1px solid #e4e4e7', borderRadius: 8, background: '#fff', padding: '12px 14px' }}>
|
||||
@ -3532,8 +3565,8 @@ export function ClearanceView({
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{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 && (
|
||||
<div className={ui.empty}>
|
||||
<strong>还没有可复盘数据</strong>
|
||||
<span>任务经管确认并产生销售出库进度后,会自动生成清货复盘。</span>
|
||||
|
||||
@ -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'))
|
||||
|
||||
@ -145,6 +145,26 @@ const clearanceReviewArchiveJobs = new Map<string, {
|
||||
summary: unknown
|
||||
warnings: unknown
|
||||
}>()
|
||||
|
||||
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<string, ClearancePoolGenerationJob>()
|
||||
|
||||
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
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user