feat(clearance): 优化复盘主体、组织汇总与快照性能

This commit is contained in:
居居 2026-12-02 15:06:38 +08:00
parent cb04310f27
commit c869b876c7
13 changed files with 444 additions and 69 deletions

View File

@ -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);

View File

@ -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

View File

@ -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 {

View File

@ -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()

View File

@ -494,8 +494,8 @@ function MatrixTable({
</tr>
<tr>
{MATRIX_METRICS.flatMap((metric) => [
<th key={`${metric.key}-previous`} className="text-end">{compareLabel}</th>,
<th key={`${metric.key}-current`} className="text-end">{periodLabel}</th>,
<th key={`${metric.key}-previous`} className="text-end">{compareLabel}</th>,
<th key={`${metric.key}-delta`} className="text-end">环比</th>,
])}
</tr>
@ -521,8 +521,8 @@ function MatrixTable({
const format = metricFormatter(metric.key)
const delta = metricDelta(current?.[metric.key], previous?.[metric.key])
return [
<td key={`${metric.key}-previous`} className="text-end">{format(previous?.[metric.key])}</td>,
<td key={`${metric.key}-current`} className={`text-end ${styles.currentCell}`}>{format(current?.[metric.key])}</td>,
<td key={`${metric.key}-previous`} className="text-end">{format(previous?.[metric.key])}</td>,
<td key={`${metric.key}-delta`} className={`text-end ${deltaClass(delta)}`}>{fmtDelta(delta)}</td>,
]
})}
@ -534,8 +534,8 @@ function MatrixTable({
const format = metricFormatter(metric.key)
const delta = metricDelta(row[metric.key], previousBase?.[metric.key])
return [
<td key={`${metric.key}-previous`} className="text-end">{format(previousBase?.[metric.key])}</td>,
<td key={`${metric.key}-current`} className={`text-end ${styles.currentCell}`}>{format(row[metric.key])}</td>,
<td key={`${metric.key}-previous`} className="text-end">{format(previousBase?.[metric.key])}</td>,
<td key={`${metric.key}-delta`} className={`text-end ${deltaClass(delta)}`}>{fmtDelta(delta)}</td>,
]
})}
@ -550,8 +550,8 @@ function MatrixTable({
const format = metricFormatter(metric.key)
const delta = metricDelta(totalCurrent[metric.key], totalCompare?.[metric.key])
return [
<td key={`total-${metric.key}-previous`} className="text-end">{format(totalCompare?.[metric.key])}</td>,
<td key={`total-${metric.key}-current`} className={`text-end ${styles.currentCell}`}>{format(totalCurrent[metric.key])}</td>,
<td key={`total-${metric.key}-previous`} className="text-end">{format(totalCompare?.[metric.key])}</td>,
<td key={`total-${metric.key}-delta`} className={`text-end ${deltaClass(delta)}`}>{fmtDelta(delta)}</td>,
]
})}
@ -596,19 +596,28 @@ export function ClearanceReviewAnalysis({
<header className={styles.hero}>
<div className={styles.heroMain}>
<div>
<span className={styles.eyebrow}>CLEARANCE REVIEW</span>
<h2>月度清货分析汇总</h2>
<p>从整体达成、渠道、部门负责人、折扣、优先级和人员六个层次复盘清货效率与货值质量。</p>
<span className={styles.eyebrow}>月度清货分析汇总</span>
<h2>{periodLabel}清货复盘</h2>
<p>
以{periodLabel}作为本次复盘主体;{compareLabel}仅作为环比对照基准,
不重复纳入本次复盘结论。
</p>
</div>
<div className={styles.periodSwitch} aria-label="分析周期">
<span>{compareLabel}</span>
<i aria-hidden="true">→</i>
<b>{periodLabel}</b>
<div className={styles.periodFocus}>
<small>复盘主体</small>
<b>{periodLabel}</b>
</div>
<div className={styles.periodCompare}>
<small>对照基准</small>
<span>{compareLabel}</span>
</div>
</div>
</div>
<div className={styles.heroMeta}>
<span><b>{sampledTaskCount.toLocaleString('zh-CN')}</b> 条有效任务</span>
<span>主值 {periodLabel},对照 {compareLabel}</span>
<span><b>{sampledTaskCount.toLocaleString('zh-CN')}</b> 条{periodLabel}有效任务</span>
<span>{periodLabel}为复盘主体</span>
<span>{compareLabel}仅用于环比对比</span>
<span>比率环比统一按百分点展示</span>
</div>
</header>

View File

@ -3628,7 +3628,7 @@ export function ClearanceView({
aria-label="复盘清货周期"
>
{(review?.periods?.length ? review.periods : [review?.periodKey ?? '']).filter(Boolean).map((period) => (
<option key={period} value={period}>清货周期:{monthLabel(period)}</option>
<option key={period} value={period}>复盘主体:{monthLabel(period)}</option>
))}
</select>
<select
@ -3637,9 +3637,11 @@ export function ClearanceView({
onChange={(event) => setReviewCompare(event.target.value)}
aria-label="复盘对照周期"
>
{(review?.periods?.length ? review.periods : [review?.compareKey ?? '']).filter(Boolean).map((period) => (
{(review?.periods?.length ? review.periods : [review?.compareKey ?? ''])
.filter((period) => Boolean(period) && period !== (reviewPeriod || review?.periodKey))
.map((period) => (
<option key={period} value={period}>对照周期:{monthLabel(period)}</option>
))}
))}
</select>
<div className={styles.segmented} role="group" aria-label="复盘维度">
{DIMENSIONS.map((dimension) => (
@ -3679,9 +3681,9 @@ export function ClearanceView({
? '最终数据完成后可存档'
: reviewArchiving
? '生成中…'
: '生成月度存档'}
: `生成${monthLabel(reviewArchivePeriod)}月度存档`}
</button>
<span className={styles.resultCount}>{review?.periodKey ? `${monthLabel(review.periodKey)} vs ${monthLabel(review.compareKey)}` : '—'}</span>
<span className={styles.resultCount}>{review?.periodKey ? `复盘主体:${monthLabel(review.periodKey)} · 对照:${monthLabel(review.compareKey)}` : '—'}</span>
</div>
{review?.archive && (
@ -3713,29 +3715,29 @@ export function ClearanceView({
<div className={ui.statGrid}>
<div className={ui.stat}>
<span className={ui.statLabel}>清货完成率</span>
<span className={ui.statLabel}>清货完成率 · {reviewPeriodLabel}</span>
<b className={ui.statValue}>{fmtPct(currentReview?.completionRate ?? null)}</b>
<span className={ui.statSub}>{reviewCompareLabel} {fmtPct(compareReview?.completionRate ?? null)}</span>
<span className={ui.statSub}>对照 {reviewCompareLabel} · {fmtPct(compareReview?.completionRate ?? null)}</span>
</div>
<div className={ui.stat}>
<span className={ui.statLabel}>清货量 / 任务量</span>
<span className={ui.statLabel}>清货量 / 任务量 · {reviewPeriodLabel}</span>
<b className={ui.statValue}>{fmtInt(currentReview?.clearedQty ?? null)}</b>
<span className={ui.statSub}>任务 {fmtInt(currentReview?.taskQty ?? null)} 件 · 来源发出 {fmtInt(currentReview?.sendQty ?? null)} 件</span>
</div>
<div className={ui.stat}>
<span className={ui.statLabel}>实际毛利率</span>
<span className={ui.statLabel}>实际毛利率 · {reviewPeriodLabel}</span>
<b className={ui.statValue}>{fmtPct(currentReview?.actualMargin ?? null)}</b>
<span className={ui.statSub}>{reviewCompareLabel} {fmtPct(compareReview?.actualMargin ?? null)}</span>
<span className={ui.statSub}>对照 {reviewCompareLabel} · {fmtPct(compareReview?.actualMargin ?? null)}</span>
</div>
<div className={ui.stat}>
<span className={ui.statLabel}>结算毛利率</span>
<span className={ui.statLabel}>结算毛利率 · {reviewPeriodLabel}</span>
<b className={ui.statValue}>{fmtPct(currentReview?.settleMargin ?? null)}</b>
<span className={ui.statSub}>{reviewCompareLabel} {fmtPct(compareReview?.settleMargin ?? null)}</span>
<span className={ui.statSub}>对照 {reviewCompareLabel} · {fmtPct(compareReview?.settleMargin ?? null)}</span>
</div>
<div className={ui.stat}>
<span className={ui.statLabel}>货值回收率</span>
<span className={ui.statLabel}>货值回收率 · {reviewPeriodLabel}</span>
<b className={ui.statValue}>{fmtPct(currentReview?.recoveryRate ?? null)}</b>
<span className={ui.statSub}>{reviewCompareLabel} {fmtPct(compareReview?.recoveryRate ?? null)}</span>
<span className={ui.statSub}>对照 {reviewCompareLabel} · {fmtPct(compareReview?.recoveryRate ?? null)}</span>
</div>
<div className={ui.stat}>
<span className={ui.statLabel}>清货完成率环比</span>
@ -3745,6 +3747,11 @@ export function ClearanceView({
</div>
{reviewError && <div className={ui.pageNote} style={{ color: '#c2410c' }}>{reviewError}</div>}
{reviewLoading && (
<div className={ui.pageNote}>
正在汇总 {monthLabel(reviewPeriod || review?.periodKey)} 复盘数据,本次已复用同月任务上下文,请稍候。
</div>
)}
{review?.analysis && (
<ClearanceReviewAnalysis
periodKey={review.periodKey}

View File

@ -399,24 +399,30 @@ class SupplyChainClearanceRepository {
},
select: {
operationOwner: true,
department: true,
profitCenter: true,
departmentOwner: true,
generalOwner: true,
updatedAt: true,
},
orderBy: [{ operationOwner: 'asc' }, { updatedAt: 'desc' }],
})
const byOwner = new Map<string, {
operationOwner: string
department: string
profitCenter: string
departmentOwner: string
generalOwner: string
}>()
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 || '',
})
}
}

View File

@ -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', () => {

View File

@ -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,
})
})
})

View File

@ -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')

View File

@ -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<string, number>(),
}
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))

View File

@ -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<string, {
department: string
directorName: string
score: number
}>()
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<string, ClearanceReviewFinancials>
preferSourceQty?: boolean
}) {
const tasks = latestTaskPerBarcodeProfitCenter(input.tasks)
const tasks = canonicalTasksByOwner(latestTaskPerBarcodeProfitCenter(input.tasks))
const metrics = tasks.map((task) => taskReviewMetrics({
task,
progress: input.progress,

View File

@ -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<typeof supplyChainClearanceRepository.listOwnerProfilesByNames>
>[number]
const REVIEW_OWNER_PROFILE_CACHE_MS = 5 * 60 * 1000
const reviewOwnerProfileCache = new Map<string, {
expiresAt: number
profile: ReviewOwnerProfile
}>()
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<string, ReviewOwnerProfile>()
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<string, number>(),
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<ReturnType<
typeof supplyChainClearanceRepository.findClearanceConfig
>>,
) {
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<ReturnType<SupplyChainClearanceService['loadTaskReviewContext']>>,
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<string>(
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<SupplyChainClearanceService['loadTaskReviewContext']>
>()
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]