From c869b876c727fdbb7a6cd24d2676cbd1e2ff02f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Wed, 2 Dec 2026 15:06:38 +0800 Subject: [PATCH] =?UTF-8?q?feat(clearance):=20=E4=BC=98=E5=8C=96=E5=A4=8D?= =?UTF-8?q?=E7=9B=98=E4=B8=BB=E4=BD=93=E3=80=81=E7=BB=84=E7=BB=87=E6=B1=87?= =?UTF-8?q?=E6=80=BB=E4=B8=8E=E5=BF=AB=E7=85=A7=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migration.sql | 5 + furniture-3d-system/prisma/schema.prisma | 8 +- .../ClearanceReviewAnalysis.module.css | 45 +++- .../ClearanceReviewAnalysis.test.tsx | 4 + .../clearance/ClearanceReviewAnalysis.tsx | 33 +-- .../management/clearance/ClearanceView.tsx | 35 ++-- .../supply-chain-clearance.repository.ts | 8 + ...n-clearance-review-archive.builder.test.ts | 7 + ...ply-chain-clearance-review.builder.test.ts | 29 +++ .../supply-chain-clearance.service.test.ts | 94 +++++++++ ...-chain-clearance-review-archive.builder.ts | 13 +- .../supply-chain-clearance-review.builder.ts | 40 +++- .../supply-chain-clearance.service.ts | 192 +++++++++++++++--- 13 files changed, 444 insertions(+), 69 deletions(-) create mode 100644 furniture-3d-system/prisma/migrations/20261202150000_expand_clearance_review_snapshot_rates/migration.sql diff --git a/furniture-3d-system/prisma/migrations/20261202150000_expand_clearance_review_snapshot_rates/migration.sql b/furniture-3d-system/prisma/migrations/20261202150000_expand_clearance_review_snapshot_rates/migration.sql new file mode 100644 index 000000000..f18e82fb9 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261202150000_expand_clearance_review_snapshot_rates/migration.sql @@ -0,0 +1,5 @@ +ALTER TABLE "SupplyChainClearanceReviewSnapshot" + ALTER COLUMN "completionRate" TYPE DECIMAL(14, 2), + ALTER COLUMN "actualMargin" TYPE DECIMAL(14, 2), + ALTER COLUMN "settleMargin" TYPE DECIMAL(14, 2), + ALTER COLUMN "recoveryRate" TYPE DECIMAL(14, 2); diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index 2c8967434..49fb4b73a 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -6891,7 +6891,7 @@ model SupplyChainClearanceReviewSnapshot { clearedQty Int @default(0) sendQty Int @default(0) refundQty Int @default(0) - completionRate Decimal? @db.Decimal(6, 2) + completionRate Decimal? @db.Decimal(14, 2) realPerformance Decimal? @db.Decimal(18, 4) sendFreight Decimal? @db.Decimal(18, 4) goodsCost Decimal? @db.Decimal(18, 4) @@ -6899,9 +6899,9 @@ model SupplyChainClearanceReviewSnapshot { actualGoodsValue Decimal? @db.Decimal(18, 4) settleGoodsValue Decimal? @db.Decimal(18, 4) recoveryValue Decimal? @db.Decimal(18, 4) - actualMargin Decimal? @db.Decimal(6, 2) - settleMargin Decimal? @db.Decimal(6, 2) - recoveryRate Decimal? @db.Decimal(6, 2) + actualMargin Decimal? @db.Decimal(14, 2) + settleMargin Decimal? @db.Decimal(14, 2) + recoveryRate Decimal? @db.Decimal(14, 2) sourceFile String @default("") createdAt DateTime @default(now()) updatedAt DateTime @updatedAt 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 b2a32baf0..a70bb9cef 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 @@ -51,28 +51,51 @@ } .periodSwitch { - display: inline-flex; - height: 34px; + display: inline-grid; + min-height: 48px; flex: 0 0 auto; - align-items: center; - gap: 9px; + grid-template-columns: minmax(94px, auto) minmax(82px, auto); + overflow: hidden; border: 1px solid #cfdad7; border-radius: 8px; background: rgba(255, 255, 255, 0.86); - padding: 0 12px; color: var(--review-muted); - font-size: 11px; font-variant-numeric: tabular-nums; } -.periodSwitch i { - color: #9ca3af; - font-style: normal; +.periodFocus, +.periodCompare { + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + padding: 6px 12px; } -.periodSwitch b { +.periodFocus { + background: rgba(31, 95, 86, 0.08); +} + +.periodCompare { + border-left: 1px solid #dfe7e5; +} + +.periodSwitch small { + color: #7b8587; + font-size: 8px; + font-weight: 650; +} + +.periodSwitch b, +.periodSwitch span { color: var(--review-accent); - font-size: 12px; + font-size: 13px; + font-weight: 700; +} + +.periodCompare span { + color: #60696b; + font-size: 11px; } .heroMeta { 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 4e03188dc..4ec466c58 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 @@ -64,6 +64,10 @@ describe('ClearanceReviewAnalysis', () => { ) expect(screen.getByText('月度清货分析汇总')).toBeInTheDocument() + expect(screen.getByRole('heading', { name: '10月清货复盘' })).toBeInTheDocument() + expect(screen.getByText('复盘主体')).toBeInTheDocument() + expect(screen.getByText('对照基准')).toBeInTheDocument() + expect(screen.getByText(/仅作为环比对照基准/)).toBeInTheDocument() 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 14021572f..e01f1027d 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 @@ -494,8 +494,8 @@ function MatrixTable({ {MATRIX_METRICS.flatMap((metric) => [ - {compareLabel}, {periodLabel}, + {compareLabel}, 环比, ])} @@ -521,8 +521,8 @@ function MatrixTable({ const format = metricFormatter(metric.key) const delta = metricDelta(current?.[metric.key], previous?.[metric.key]) return [ - {format(previous?.[metric.key])}, {format(current?.[metric.key])}, + {format(previous?.[metric.key])}, {fmtDelta(delta)}, ] })} @@ -534,8 +534,8 @@ function MatrixTable({ const format = metricFormatter(metric.key) const delta = metricDelta(row[metric.key], previousBase?.[metric.key]) return [ - {format(previousBase?.[metric.key])}, {format(row[metric.key])}, + {format(previousBase?.[metric.key])}, {fmtDelta(delta)}, ] })} @@ -550,8 +550,8 @@ function MatrixTable({ const format = metricFormatter(metric.key) const delta = metricDelta(totalCurrent[metric.key], totalCompare?.[metric.key]) return [ - {format(totalCompare?.[metric.key])}, {format(totalCurrent[metric.key])}, + {format(totalCompare?.[metric.key])}, {fmtDelta(delta)}, ] })} @@ -596,19 +596,28 @@ export function ClearanceReviewAnalysis({
- CLEARANCE REVIEW -

月度清货分析汇总

-

从整体达成、渠道、部门负责人、折扣、优先级和人员六个层次复盘清货效率与货值质量。

+ 月度清货分析汇总 +

{periodLabel}清货复盘

+

+ 以{periodLabel}作为本次复盘主体;{compareLabel}仅作为环比对照基准, + 不重复纳入本次复盘结论。 +

- {compareLabel} - - {periodLabel} +
+ 复盘主体 + {periodLabel} +
+
+ 对照基准 + {compareLabel} +
- {sampledTaskCount.toLocaleString('zh-CN')} 条有效任务 - 主值 {periodLabel},对照 {compareLabel} + {sampledTaskCount.toLocaleString('zh-CN')} 条{periodLabel}有效任务 + {periodLabel}为复盘主体 + {compareLabel}仅用于环比对比 比率环比统一按百分点展示
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 03e494921..42e1735e5 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 @@ -3628,7 +3628,7 @@ export function ClearanceView({ aria-label="复盘清货周期" > {(review?.periods?.length ? review.periods : [review?.periodKey ?? '']).filter(Boolean).map((period) => ( - + ))}
{DIMENSIONS.map((dimension) => ( @@ -3679,9 +3681,9 @@ export function ClearanceView({ ? '最终数据完成后可存档' : reviewArchiving ? '生成中…' - : '生成月度存档'} + : `生成${monthLabel(reviewArchivePeriod)}月度存档`} - {review?.periodKey ? `${monthLabel(review.periodKey)} vs ${monthLabel(review.compareKey)}` : '—'} + {review?.periodKey ? `复盘主体:${monthLabel(review.periodKey)} · 对照:${monthLabel(review.compareKey)}` : '—'}
{review?.archive && ( @@ -3713,29 +3715,29 @@ export function ClearanceView({
- 清货完成率 + 清货完成率 · {reviewPeriodLabel} {fmtPct(currentReview?.completionRate ?? null)} - {reviewCompareLabel} {fmtPct(compareReview?.completionRate ?? null)} + 对照 {reviewCompareLabel} · {fmtPct(compareReview?.completionRate ?? null)}
- 清货量 / 任务量 + 清货量 / 任务量 · {reviewPeriodLabel} {fmtInt(currentReview?.clearedQty ?? null)} 任务 {fmtInt(currentReview?.taskQty ?? null)} 件 · 来源发出 {fmtInt(currentReview?.sendQty ?? null)} 件
- 实际毛利率 + 实际毛利率 · {reviewPeriodLabel} {fmtPct(currentReview?.actualMargin ?? null)} - {reviewCompareLabel} {fmtPct(compareReview?.actualMargin ?? null)} + 对照 {reviewCompareLabel} · {fmtPct(compareReview?.actualMargin ?? null)}
- 结算毛利率 + 结算毛利率 · {reviewPeriodLabel} {fmtPct(currentReview?.settleMargin ?? null)} - {reviewCompareLabel} {fmtPct(compareReview?.settleMargin ?? null)} + 对照 {reviewCompareLabel} · {fmtPct(compareReview?.settleMargin ?? null)}
- 货值回收率 + 货值回收率 · {reviewPeriodLabel} {fmtPct(currentReview?.recoveryRate ?? null)} - {reviewCompareLabel} {fmtPct(compareReview?.recoveryRate ?? null)} + 对照 {reviewCompareLabel} · {fmtPct(compareReview?.recoveryRate ?? null)}
清货完成率环比 @@ -3745,6 +3747,11 @@ export function ClearanceView({
{reviewError &&
{reviewError}
} + {reviewLoading && ( +
+ 正在汇总 {monthLabel(reviewPeriod || review?.periodKey)} 复盘数据,本次已复用同月任务上下文,请稍候。 +
+ )} {review?.analysis && ( () for (const row of rows) { const owner = row.operationOwner.trim() if (!owner || byOwner.has(owner)) continue byOwner.set(owner, { operationOwner: owner, + department: row.department.trim(), profitCenter: row.profitCenter.trim(), departmentOwner: row.departmentOwner.trim(), + generalOwner: row.generalOwner.trim(), }) } const fallbackNames = normalized.filter((name) => ( @@ -495,8 +501,10 @@ class SupplyChainClearanceRepository { const existing = byOwner.get(name) byOwner.set(name, { operationOwner: name, + department: existing?.department || department.fullPath, profitCenter: existing?.profitCenter || profitCenter, departmentOwner: existing?.departmentOwner || departmentOwner, + generalOwner: existing?.generalOwner || '', }) } } diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive.builder.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive.builder.test.ts index c4e068b9a..11d3cc735 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive.builder.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review-archive.builder.test.ts @@ -123,6 +123,13 @@ describe('clearance review archive builder', () => { (row) => row.dimensionKey.includes(CLEARANCE_REVIEW_KEY_SEPARATOR) && !row.dimensionKey.includes('\u0000'), )).toBe(true) + expect(result.snapshots.filter((row) => row.dimension === 'overall')).toEqual([ + expect.objectContaining({ + dimensionKey: 'total', + taskQty: 120, + clearedQty: 55, + }), + ]) }) it('uses cost as the settlement unit price when no clearance price was approved', () => { diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review.builder.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review.builder.test.ts index 50f05968f..4fc655c45 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review.builder.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-review.builder.test.ts @@ -8,6 +8,7 @@ import { type ClearanceProgressSnapshot, type ClearanceReviewTask, } from '../supply-chain-clearance-review.builder' +import { buildClearanceReviewKey } from '@/lib/clearance-review-key' const progress: ClearanceProgressSnapshot = { hasCoverage: true, @@ -198,4 +199,32 @@ describe('supply-chain clearance review builder', () => { expect(result.recoveryValue).toBe(645) expect(result.recoveryRate).toBe(107.5) }) + + it('merges an operator into one owner-detail row using the most complete organization snapshot', () => { + const rows = buildTaskReviewRows({ + tasks: [ + task({ + barcode: 'SKU001', + department: '王也', + directorName: '', + ownerName: '王也', + }), + task({ + barcode: 'SKU002', + department: '事业四部', + directorName: '王也', + ownerName: '王也', + }), + ], + dimension: 'ownerDetail', + progress, + }) + const ownerRows = rows.filter((row) => row.dimensionKey !== 'total') + + expect(ownerRows).toHaveLength(1) + expect(ownerRows[0]).toMatchObject({ + dimensionKey: buildClearanceReviewKey('事业四部', '王也', '王也'), + reviewTaskCount: 2, + }) + }) }) 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 d483aa7e0..06eb41da8 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 @@ -6744,6 +6744,13 @@ describe('supply-chain-clearance workflow', () => { through: '2026-10-31', }]) repository.listReviewSnapshots.mockResolvedValue([]) + repository.listOwnerProfilesByNames.mockResolvedValue([{ + operationOwner: '测试运营', + department: '事业一部', + profitCenter: '运营中心A', + departmentOwner: '比干', + generalOwner: '比干', + }] as never) repository.findPoolItemsByBarcodes.mockResolvedValue([{ barcode: 'SKU001', department: '事业一部', @@ -6776,11 +6783,19 @@ describe('supply-chain-clearance workflow', () => { clearedQty: 64, completionRate: 64, })) + expect(result.analysis.ownerDetail.current).toContainEqual(expect.objectContaining({ + dimensionKey: buildClearanceReviewKey('事业一部', '比干', '测试运营'), + reviewTaskCount: 1, + })) expect(result.trend).toContainEqual(expect.objectContaining({ monthKey: '2026-10', taskQty: 100, clearedQty: 64, })) + expect(repository.listTasks.mock.calls.map(([input]) => input.periodKey).sort()).toEqual([ + '2026-09', + '2026-10', + ]) }) it('keeps both profit centers when one barcode has tasks in multiple centers', async () => { @@ -6888,6 +6903,84 @@ describe('supply-chain-clearance workflow', () => { periodKey: '2026-11', compareKey: '2026-10', }) + await expect(supplyChainClearanceService.getReview({ + periodKey: '2026-11', + compareKey: '2026-11', + dimension: 'channel', + })).resolves.toMatchObject({ + periodKey: '2026-11', + compareKey: '2026-10', + }) + }) + + it('reads an archived review month from snapshots without recalculating its tasks', async () => { + jest.useFakeTimers().setSystemTime(new Date('2026-12-02T02:00:00.000Z')) + repository.listReviewMonths.mockResolvedValue(['2026-11']) + repository.listTaskPeriods.mockResolvedValue(['2026-11', '2026-10']) + repository.listReviewArchives.mockResolvedValue([{ + id: 'archive-11', + monthKey: '2026-11', + periodStart: new Date('2026-11-01T00:00:00.000Z'), + periodEnd: new Date('2026-11-30T00:00:00.000Z'), + dataThrough: new Date('2026-11-30T00:00:00.000Z'), + taskCount: 1, + sourceRowCount: 1, + detailCount: 1, + unmatchedProfitCenterCount: 0, + sourceFile: 'dws_sn_sales_full_info_di', + generatedById: user.id, + generatedByName: user.name, + generatedAt: new Date('2026-12-02T01:00:00.000Z'), + createdAt: new Date('2026-12-02T01:00:00.000Z'), + sourceSnapshot: { version: 1 }, + }] as never) + repository.listReviewSnapshotsByDimensions.mockResolvedValue([{ + id: 'snapshot-11-channel', + monthKey: '2026-11', + dimension: 'channel', + dimensionKey: '运营中心A', + dimensionLabel: '运营中心A', + reviewTaskCount: 1, + matchedStoreCount: 1, + sourceRowCount: 1, + taskQty: 100, + clearedQty: 80, + sendQty: 80, + completionRate: '80.00', + realPerformance: '1000.0000', + sendFreight: '100.0000', + refundQty: 0, + goodsCost: '500.0000', + refundCost: '0.0000', + actualGoodsValue: '800.0000', + settleGoodsValue: '600.0000', + recoveryValue: '645.0000', + actualMargin: '10.00', + settleMargin: '30.00', + recoveryRate: '80.63', + createdAt: new Date('2026-12-02T01:00:00.000Z'), + updatedAt: new Date('2026-12-02T01:00:00.000Z'), + }] as never) + repository.listReviewSnapshots.mockResolvedValue([]) + repository.listTasks.mockResolvedValue([]) + + const result = await supplyChainClearanceService.getReview({ + periodKey: '2026-11', + compareKey: '2026-10', + dimension: 'channel', + }) + + expect(result).toMatchObject({ + periodKey: '2026-11', + compareKey: '2026-10', + source: 'REVIEW', + }) + expect(result.analysis.channel.current).toContainEqual(expect.objectContaining({ + dimensionKey: '运营中心A', + taskQty: 100, + clearedQty: 80, + })) + expect(repository.listTasks.mock.calls.map(([input]) => input.periodKey)).not.toContain('2026-11') }) it('archives monthly task, store and financial results atomically from the report source', async () => { @@ -6983,6 +7076,7 @@ describe('supply-chain-clearance workflow', () => { 'channelPriority', 'ownerDetail', 'deptHead', + 'overall', ])) expect(archiveInput.snapshots.every((row) => !row.dimensionKey.includes('\u0000'))).toBe(true) expect(JSON.stringify(archiveInput.sourceSnapshot)).not.toContain('\\u0000') diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive.builder.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive.builder.ts index c7681b5bb..c47d2a11e 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive.builder.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-review-archive.builder.ts @@ -65,7 +65,7 @@ export type ClearanceReviewDetailDraft = { export type ClearanceReviewSnapshotDraft = ClearanceReviewRow & { monthKey: string - dimension: ClearanceReviewDimension + dimension: ClearanceReviewDimension | 'overall' } export function normalizedClearanceReviewShopName(value: unknown) { @@ -282,7 +282,7 @@ export function buildClearanceReviewArchive(input: { through: null, byBarcode: new Map(), } - const snapshots = CLEARANCE_REVIEW_DIMENSIONS.flatMap((dimension) => ( + const dimensionSnapshots = CLEARANCE_REVIEW_DIMENSIONS.flatMap((dimension) => ( buildTaskReviewRows({ tasks, dimension, @@ -298,6 +298,15 @@ export function buildClearanceReviewArchive(input: { financialsByScope, preferSourceQty: true, })[0] + if (!overall) throw new Error('月度复盘整体汇总生成失败') + const snapshots: ClearanceReviewSnapshotDraft[] = [ + ...dimensionSnapshots, + { + ...overall, + monthKey: input.monthKey, + dimension: 'overall', + }, + ] const dataThrough = details .map((row) => row.sourceThrough) .filter((value): value is string => Boolean(value)) diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-review.builder.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-review.builder.ts index 9843fab68..9e6bc3ce2 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-review.builder.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-review.builder.ts @@ -190,6 +190,44 @@ export function latestTaskPerBarcode(tasks: readonly ClearanceReviewTask[]) { return latestTaskPerBarcodeProfitCenter(tasks) } +function reviewOrganizationScore(task: ClearanceReviewTask) { + const director = task.directorName.trim() + const department = task.department.trim() + return (director && !director.includes('未配置') ? 4 : 0) + + (department && !department.includes('未分配') && !department.includes('未配置') ? 2 : 0) +} + +function canonicalTasksByOwner(tasks: readonly ClearanceReviewTask[]) { + const organizationByOwner = new Map() + for (const task of tasks) { + const owner = task.ownerName.trim() || '未分配运营' + const score = reviewOrganizationScore(task) + const current = organizationByOwner.get(owner) + if (!current || score > current.score) { + organizationByOwner.set(owner, { + department: task.department, + directorName: task.directorName, + score, + }) + } + } + return tasks.map((task) => { + const organization = organizationByOwner.get(task.ownerName.trim() || '未分配运营') + return organization + ? { + ...task, + department: organization.department, + directorName: organization.directorName, + ownerName: task.ownerName.trim() || '未分配运营', + } + : task + }) +} + export function clearanceReviewTaskTypeLabel(type: ClearanceScoreTaskType) { if (type === 'fixed') return '固定' if (type === 'priority') return '优先' @@ -384,7 +422,7 @@ export function buildTaskReviewRows(input: { financialsByScope?: ReadonlyMap preferSourceQty?: boolean }) { - const tasks = latestTaskPerBarcodeProfitCenter(input.tasks) + const tasks = canonicalTasksByOwner(latestTaskPerBarcodeProfitCenter(input.tasks)) const metrics = tasks.map((task) => taskReviewMetrics({ task, progress: input.progress, 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 f4d8630d9..990e1f1fc 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 @@ -1582,7 +1582,9 @@ function reviewTaskInput( taskType?: ClearanceScoreTaskType costPrice?: number | null clearancePrice?: number | null + department?: string directorName?: string + ownerName?: string }, ): ClearanceReviewTask { const profitCenter = metadata?.profitCenter @@ -1599,9 +1601,9 @@ function reviewTaskInput( clearancePrice: metadata?.clearancePrice ?? number(task.clearancePrice), status: task.status, channel: metadata?.channel || profitCenter, - department: task.department, + department: metadata?.department || task.department, directorName: metadata?.directorName ?? '', - ownerName: importedClearanceOwner(task) || task.ownerName, + ownerName: metadata?.ownerName || importedClearanceOwner(task) || task.ownerName, priority: metadata?.priority ?? '', discountLabel: discountLabel(number(task.discount) ?? 0), taskType: metadata?.taskType ?? classifyClearanceTaskType({ @@ -1611,11 +1613,74 @@ function reviewTaskInput( totalStock: metadata?.totalStock, preserveTaskQty: isDistributionClearanceGroup({ profitCenter, - department: task.department, + department: metadata?.department || task.department, }), } } +type ReviewOwnerProfile = Awaited< + ReturnType +>[number] + +const REVIEW_OWNER_PROFILE_CACHE_MS = 5 * 60 * 1000 +const reviewOwnerProfileCache = new Map() + +async function reviewOwnerProfilesByTask(tasks: readonly RepositoryTask[]) { + const ownerNames = Array.from(new Set(tasks.flatMap((task) => [ + effectiveClearanceTaskOwner(task), + task.ownerName.trim(), + ]).filter(Boolean))) + const now = Date.now() + const profiles = new Map() + const missing: string[] = [] + for (const name of ownerNames) { + const cached = reviewOwnerProfileCache.get(name) + if (cached && cached.expiresAt > now) { + profiles.set(name, cached.profile) + } else { + missing.push(name) + } + } + if (missing.length) { + const rows = await supplyChainClearanceRepository.listOwnerProfilesByNames(missing) + for (const profile of rows) { + const name = profile.operationOwner.trim() + profiles.set(name, profile) + reviewOwnerProfileCache.set(name, { + expiresAt: now + REVIEW_OWNER_PROFILE_CACHE_MS, + profile, + }) + } + } + return profiles +} + +function reviewOrganizationMetadata(input: { + task: RepositoryTask + poolItem?: { directorName: string; extra?: unknown } | null + profile?: ReviewOwnerProfile +}) { + const ownerName = effectiveClearanceTaskOwner(input.task) + || input.task.ownerName.trim() + const extra = input.poolItem ? poolExtra(input.poolItem) : {} + const department = input.profile?.department.trim() + || '未配置部门' + const directorName = input.profile?.departmentOwner.trim() + || input.profile?.generalOwner.trim() + || String(extra.effectiveDepartmentOwner ?? '').trim() + || input.poolItem?.directorName?.trim() + || input.task.department.trim() + || '未配置部门负责人' + return { + ownerName, + department, + directorName, + } +} + function applicationWindowType(round: number) { return round === 2 ? '次月折扣调整' : '次月任务制定' } @@ -3956,7 +4021,11 @@ class SupplyChainClearanceService { return clearanceSkuFamilySalesKeySet(rows).has(clearanceSkuFamilyKey(sku)) } - private async loadTaskProgress(periodKey: string, tasks: readonly RepositoryTask[]) { + private async loadTaskProgress( + periodKey: string, + tasks: readonly RepositoryTask[], + options: { skipOutboundQuery?: boolean } = {}, + ) { const barcodes = Array.from(new Set( tasks.map((task) => task.barcode.trim().toUpperCase()).filter(Boolean), )) @@ -4019,15 +4088,16 @@ class SupplyChainClearanceService { ) const progressWithoutOutbound = { ...auxiliaryProgress, - hasCoverage: false, periodStarted, - through: null, - byBarcode: new Map(), + through: auxiliaryProgress.through, profitCenterByBarcode, } if (!subjects.length) { return progressWithoutOutbound } + if (options.skipOutboundQuery) { + return progressWithoutOutbound + } const endDateExclusive = clearanceShipmentEndDateExclusive(periodKey) const through = addDateDays(endDateExclusive, -1) if (through < `${periodKey}-01`) return progressWithoutOutbound @@ -7174,16 +7244,20 @@ class SupplyChainClearanceService { } } - private async taskReviewRows(periodKey: string, dimension: ClearanceReviewDimension | 'overall') { - const [tasks, clearanceConfig] = await Promise.all([ - supplyChainClearanceRepository.listTasks({ periodKey }), - supplyChainClearanceRepository.findClearanceConfig(), - ]) - const progress = await this.loadTaskProgress(periodKey, tasks) + private async loadTaskReviewContext( + periodKey: string, + clearanceConfig: Awaited>, + ) { + const tasks = await supplyChainClearanceRepository.listTasks({ periodKey }) const approvedBarcodes = tasks .filter((task) => task.status === 'APPROVED') .map((task) => task.barcode) - const poolItems = await supplyChainClearanceRepository.findPoolItemsByBarcodes(approvedBarcodes) + const [progress, poolItems] = await Promise.all([ + this.loadTaskProgress(periodKey, tasks, { skipOutboundQuery: true }), + supplyChainClearanceRepository.findPoolItemsByBarcodes(approvedBarcodes), + ]) const poolByBarcode = new Map(poolItems.map((item) => [ item.barcode.trim().toUpperCase(), item, @@ -7199,7 +7273,9 @@ class SupplyChainClearanceService { priority, taskType, })) - return buildTaskReviewRows({ + const ownerProfileByTask = await reviewOwnerProfilesByTask(tasks) + return { + progress, tasks: tasks.map((task) => { const barcode = task.barcode.trim().toUpperCase() const poolItem = poolByBarcode.get(barcode) @@ -7214,13 +7290,21 @@ class SupplyChainClearanceService { || String(extra.profitCenter ?? '').trim() || progress.profitCenterByBarcode?.get(barcode) || '' + const ownerName = effectiveClearanceTaskOwner(task) || task.ownerName.trim() + const organization = reviewOrganizationMetadata({ + task, + poolItem, + profile: ownerProfileByTask.get(ownerName), + }) return reviewTaskInput(task, progress, { profitCenter, channel: profitCenter, priority, totalStock: poolItem?.totalStock, costPrice: number(poolItem?.costPrice), - directorName: poolItem?.directorName ?? '', + department: organization.department, + directorName: organization.directorName, + ownerName: organization.ownerName, taskType: classifyClearanceTaskType({ fixedTaskQty: extra.fixedTaskQty, priority, @@ -7228,8 +7312,17 @@ class SupplyChainClearanceService { }), }) }), + } + } + + private taskReviewRowsFromContext( + context: Awaited>, + dimension: ClearanceReviewDimension | 'overall', + ) { + return buildTaskReviewRows({ + tasks: context.tasks, dimension, - progress, + progress: context.progress, }) } @@ -7320,7 +7413,9 @@ class SupplyChainClearanceService { `${periodKey} 没有经管确认的清货任务,无法生成复盘存档`, ) } - const progress = await this.loadTaskProgress(periodKey, tasks) + const progress = await this.loadTaskProgress(periodKey, tasks, { + skipOutboundQuery: true, + }) const poolItems = await supplyChainClearanceRepository.listPoolRowsForPeriodSnapshot( periodKey, ) @@ -7344,6 +7439,7 @@ class SupplyChainClearanceService { priority, taskType, })) + const ownerProfileByTask = await reviewOwnerProfilesByTask(tasks) const reviewTasks = tasks.map((task) => { const barcode = task.barcode.trim().toUpperCase() const poolItem = poolByBarcode.get(barcode) @@ -7358,13 +7454,21 @@ class SupplyChainClearanceService { || String(extra.profitCenter ?? '').trim() || progress.profitCenterByBarcode?.get(barcode) || '' + const ownerName = effectiveClearanceTaskOwner(task) || task.ownerName.trim() + const organization = reviewOrganizationMetadata({ + task, + poolItem, + profile: ownerProfileByTask.get(ownerName), + }) return reviewTaskInput(task, progress, { profitCenter, channel: profitCenter, priority, totalStock: poolItem?.totalStock, costPrice: number(poolItem?.costPrice), - directorName: poolItem?.directorName ?? '', + department: organization.department, + directorName: organization.directorName, + ownerName: organization.ownerName, taskType: classifyClearanceTaskType({ fixedTaskQty: extra.fixedTaskQty, priority, @@ -7406,6 +7510,19 @@ class SupplyChainClearanceService { storeProfitCenters, progress, }) + const snapshotDimensions = new Set( + result.snapshots.map((row) => row.dimension), + ) + const missingSnapshotDimensions = [ + ...REVIEW_ANALYSIS_DIMENSIONS, + 'overall', + ].filter((dimension) => !snapshotDimensions.has(dimension)) + if (missingSnapshotDimensions.length) { + throw new AppError( + ErrorCode.VALIDATION_FAILED, + `月度复盘快照不完整,缺少:${missingSnapshotDimensions.join('、')}`, + ) + } const periodEnd = addDateDays(endDateExclusive, -1) if (input.requireCompletePeriod && result.dataThrough !== periodEnd) { throw new AppError( @@ -7500,7 +7617,9 @@ class SupplyChainClearanceService { const periodKey = input.periodKey && closedMonths.includes(input.periodKey) ? input.periodKey : closedMonths[0] - const compareKey = input.compareKey && closedMonths.includes(input.compareKey) + const compareKey = input.compareKey + && input.compareKey !== periodKey + && closedMonths.includes(input.compareKey) ? input.compareKey : closedMonths.find((month) => month < periodKey) ?? previousPeriodKey(periodKey) const dimension = DIMENSIONS.has(input.dimension as ClearanceDimension) @@ -7523,14 +7642,31 @@ class SupplyChainClearanceService { rows.push(row) analysisSnapshotMap.set(key, rows) } + const archiveByMonth = new Map( + archives.map((archive) => [archive.monthKey, archive]), + ) + const taskReviewContextCache = new Map< + string, + ReturnType + >() + const taskReviewContextFor = (monthKey: string) => { + const cached = taskReviewContextCache.get(monthKey) + if (cached) return cached + const pending = this.loadTaskReviewContext(monthKey, clearanceConfig) + taskReviewContextCache.set(monthKey, pending) + return pending + } const reviewRowsFor = async ( monthKey: string, analysisDimension: ClearanceReviewDimension, ) => { const snapshots = analysisSnapshotMap.get(`${monthKey}\u0000${analysisDimension}`) ?? [] - return snapshots.length - ? snapshots.map(reviewDto) - : this.taskReviewRows(monthKey, analysisDimension) + if (snapshots.length) return snapshots.map(reviewDto) + if (archiveByMonth.has(monthKey)) return [] + return this.taskReviewRowsFromContext( + await taskReviewContextFor(monthKey), + analysisDimension, + ) } const analysisEntries = await Promise.all(REVIEW_ANALYSIS_DIMENSIONS.map(async ( analysisDimension, @@ -7549,10 +7685,16 @@ class SupplyChainClearanceService { const compareRows = analysis[dimension].compare const currentSnapshotRows = analysisSnapshotMap.get(`${periodKey}\u0000${dimension}`) ?? [] const overallByMonth = new Map(overallSnapshotRows.map((row) => [row.monthKey, reviewDto(row)])) - const missingOverallMonths = closedMonths.filter((month) => !overallByMonth.has(month)) + const missingOverallMonths = Array.from(new Set([periodKey, compareKey])) + .filter((month) => ( + !overallByMonth.has(month) && !archiveByMonth.has(month) + )) const derivedOverall = await Promise.all(missingOverallMonths.map(async (month) => ({ month, - rows: await this.taskReviewRows(month, 'overall'), + rows: this.taskReviewRowsFromContext( + await taskReviewContextFor(month), + 'overall', + ), }))) for (const entry of derivedOverall) { const row = entry.rows[0]