fix(clearance): 统一复盘任务口径并支持重新生成

This commit is contained in:
居居 2026-12-04 17:36:48 +08:00
parent ba690fd29f
commit e5bdaf07a9
11 changed files with 291 additions and 110 deletions

View File

@ -9,6 +9,7 @@ const mockJsonError = jest.fn()
const mockGetUserAccess = jest.fn()
const mockFetch = jest.fn()
const mockGetPoolForExport = jest.fn()
const mockGetTasks = jest.fn()
jest.mock('@/server/core/response', () => ({
handleRequest: (...args: unknown[]) => mockHandleRequest(...args),
@ -18,6 +19,7 @@ jest.mock('@/server/core/response', () => ({
jest.mock('@/server/services/supply-chain-clearance.service', () => ({
supplyChainClearanceService: {
getPoolForExport: (...args: unknown[]) => mockGetPoolForExport(...args),
getTasks: (...args: unknown[]) => mockGetTasks(...args),
},
}))
@ -98,6 +100,39 @@ describe('POST /api/supply-chain/clearance/export', () => {
expect(sheet?.getCell('A4').value).toBe('5折')
})
it('loads authoritative ungrouped task rows when exporting without a page snapshot', async () => {
mockGetTasks.mockResolvedValue({
tasks: [
{ clearanceCode: 'SKU-A-1', shipQty: 4, taskQty: 4 },
{ clearanceCode: 'SKU-A-2', shipQty: 3, taskQty: 4 },
],
})
const response = await POST({
json: async () => ({
table: 'tasks',
period: '2026-11',
filters: [{ key: 'profitCenter', operator: 'contains', value: '运营中心A' }],
columns: [
{ key: 'clearanceCode', label: '清货商品编码' },
{ key: 'shipQty', label: '发货数量' },
],
}),
} as NextRequest)
expect(mockGetTasks).toHaveBeenCalledWith('2026-11', expect.objectContaining({
filters: [{ key: 'profitCenter', operator: 'contains', value: '运营中心A' }],
groupComponents: false,
liveProgress: false,
}))
const workbook = new ExcelJS.Workbook()
const responseBody = response.body
if (!responseBody) throw new Error('export response body is empty')
await workbook.xlsx.load(Buffer.from(responseBody as never) as never)
const sheet = workbook.getWorksheet('清货任务')
expect(sheet?.getCell('A2').value).toBe('SKU-A-1')
expect(sheet?.getCell('A3').value).toBe('SKU-A-2')
})
it('exports the pool creation time in the same Shanghai display format as the page', async () => {
mockGetPoolForExport.mockResolvedValue({
rows: [{

View File

@ -299,19 +299,11 @@ export async function POST(request: NextRequest) {
].filter(Boolean).join(' ')
}
} else if (input.table === 'tasks') {
if (!input.rows) {
return jsonError(
ErrorCode.VALIDATION_REQUIRED_FIELD,
'清货任务导出缺少页面查询数据,请刷新任务列表后重试',
400,
ctx.requestId,
)
}
const requestedColumns: ExportColumn[] = input.columns?.length
? input.columns
: defaultColumns(TASK_EXPORT_COLUMNS)
const columnsMatchWhitelist = requestedColumns.every(({ key }) => TASK_EXPORT_KEYS.has(key))
const rowsMatchWhitelist = input.rows.every((row) => (
const rowsMatchWhitelist = (input.rows ?? []).every((row) => (
Object.entries(row).every(([key, value]) => (
TASK_EXPORT_KEYS.has(key)
&& (
@ -338,9 +330,23 @@ export async function POST(request: NextRequest) {
width: width ?? definition.width,
}
})
let taskRows = input.rows
let taskRows: Array<Record<string, unknown>>
if (input.rows) {
taskRows = input.rows
} else {
const taskResult = await supplyChainClearanceService.getTasks(input.period, {
filters: input.filters ?? [],
round: input.round,
user: ctx.user,
canReview: reviewAccess.edit,
includeFreight: false,
liveProgress: false,
groupComponents: false,
})
taskRows = taskResult.tasks as unknown as Array<Record<string, unknown>>
}
if (columns.some((column) => column.key === 'nationwideFreight')) {
const barcodes = Array.from(new Set(input.rows.flatMap((row) => {
const barcodes = Array.from(new Set(taskRows.flatMap((row) => {
const barcode = String(row.barcode ?? '').trim().toUpperCase()
return barcode ? [barcode] : []
})))
@ -350,7 +356,7 @@ export async function POST(request: NextRequest) {
input.period,
barcodes,
)
taskRows = input.rows.map((row) => {
taskRows = taskRows.map((row) => {
const barcode = String(row.barcode ?? '').trim().toUpperCase()
const nationwideFreight = freight.values[barcode]
return nationwideFreight == null

View File

@ -76,6 +76,18 @@ describe('/api/supply-chain/clearance/review/archive', () => {
expect(response).toBeDefined()
})
it('forwards an explicit recomputation request for an existing archive', async () => {
await POST({
json: async () => ({ periodKey: '2026-11', replace: true }),
} as NextRequest)
expect(mockStartReviewArchive).toHaveBeenCalledWith({
periodKey: '2026-11',
replace: true,
user: expect.objectContaining({ id: 'manager-1' }),
})
})
it('rejects callers without clearance review edit permission', async () => {
mockGetUserAccess.mockResolvedValue({ edit: false })

View File

@ -20,7 +20,7 @@ type ReviewDetailRow = {
shopName: string
barcode: string
profitCenter: string
profitCenterSource: 'SOURCE' | 'STORE_ACCOUNT' | 'UNMATCHED' | 'TASK_ONLY'
profitCenterSource: 'SOURCE' | 'STORE_ACCOUNT' | 'TASK_CENTER' | 'UNMATCHED' | 'TASK_ONLY'
realPerformance: number | null
sendFreight: number | null
sendQty: number
@ -57,6 +57,7 @@ function fmtMoney(value: number | null | undefined) {
function sourceLabel(value: ReviewDetailRow['profitCenterSource']) {
if (value === 'SOURCE') return '来源利润中心'
if (value === 'STORE_ACCOUNT') return '店铺账户映射'
if (value === 'TASK_CENTER') return '任务利润中心映射'
if (value === 'TASK_ONLY') return '无销售数据'
return '未匹配'
}

View File

@ -51,7 +51,6 @@ import {
DEFAULT_SCORE_FILTER_FIELDS,
DEFAULT_TASK_FILTER_FIELDS,
} from './clearance-filter-defaults'
import { buildClearanceTaskExportSnapshot } from './clearance-task-export-snapshot'
import { ClearanceTaskImageCell } from './ClearanceTaskImageCell'
import {
useClearanceColumnSettings,
@ -1235,9 +1234,12 @@ export function ClearanceView({
const archiveReviewMonth = async () => {
const periodKey = reviewPeriod || review?.periodKey
if (!periodKey || reviewArchiving) return
if (review?.archive?.monthKey === periodKey) return
if (!canReview) return
const replacing = review?.archive?.monthKey === periodKey
if (!window.confirm(
`将冻结${monthLabel(periodKey)}的清货任务、真实业绩、运费、货值和店铺明细。确认生成?`,
replacing
? `将按当前最新数据重新生成并覆盖${monthLabel(periodKey)}月度存档。确认重新生成?`
: `将冻结${monthLabel(periodKey)}的清货任务、真实业绩、运费、货值和店铺明细。确认生成?`,
)) return
setReviewArchiving(true)
setReviewError('')
@ -1248,7 +1250,7 @@ export function ClearanceView({
error: string
}>('/api/supply-chain/clearance/review/archive', {
method: 'POST',
body: JSON.stringify({ periodKey }),
body: JSON.stringify({ periodKey, replace: replacing }),
})
const deadline = Date.now() + 10 * 60 * 1000
while (job.status === 'RUNNING') {
@ -1263,7 +1265,7 @@ export function ClearanceView({
job = nextJob
}
if (job.status === 'FAILED') throw new Error(job.error || '生成月度存档失败')
setToast(`${monthLabel(periodKey)}清货复盘存档已生成`)
setToast(`${monthLabel(periodKey)}清货复盘存档已${replacing ? '重新生成' : '生成'}`)
setReviewRefreshKey((value) => value + 1)
} catch (reason) {
setReviewError((reason as Error).message)
@ -2574,7 +2576,7 @@ export function ClearanceView({
|| !isClearancePeriodFinalizationDue(reviewArchivePeriod)
),
)
const reviewArchiveFrozen = Boolean(
const reviewArchiveExists = Boolean(
reviewArchivePeriod && review?.archive?.monthKey === reviewArchivePeriod,
)
@ -3342,15 +3344,10 @@ export function ClearanceView({
const column = CLEARANCE_TASK_COLUMN_MAP.get(setting.key)
return column ? [{ key: column.key, label: column.label, width: setting.width }] : []
})
const rows = buildClearanceTaskExportSnapshot({
rows: filteredTaskRows,
columns,
freightByBarcode: taskFreightByBarcode,
})
void downloadExport('tasks', {
period: taskPeriod,
rows,
columns,
filters: taskFilters,
})
}}
>
@ -3704,21 +3701,23 @@ export function ClearanceView({
<button
type="button"
className={styles.primaryButton}
disabled={reviewArchiving || !reviewArchivePeriod || reviewArchiveBlocked || reviewArchiveFrozen}
disabled={reviewArchiving || !reviewArchivePeriod || reviewArchiveBlocked || !canReview}
title={reviewArchiveBlocked
? `需在 ${clearancePeriodFinalizeDate(reviewArchivePeriod)} 完成最终数据同步后才能冻结`
: reviewArchiveFrozen
? '该月数据已冻结,不能再重新生成'
: !canReview
? '仅经管可以生成或重新生成月度存档'
: undefined}
onClick={() => void archiveReviewMonth()}
>
{reviewArchiveFrozen
? '已冻结'
: reviewArchiveBlocked
{reviewArchiveBlocked
? '最终数据完成后可存档'
: reviewArchiving
? '生成中…'
: `生成${monthLabel(reviewArchivePeriod)}月度存档`}
: reviewArchiveExists
? canReview
? `重新生成${monthLabel(reviewArchivePeriod)}月度存档`
: '已冻结'
: `生成${monthLabel(reviewArchivePeriod)}月度存档`}
</button>
<span className={styles.resultCount}>
{review?.periodKey

View File

@ -3,7 +3,7 @@ import { rebuildLegacyClearanceReviewSnapshots } from '../supply-chain-clearance
describe('clearance review archive compatibility', () => {
it('reclassifies legacy A fixed-task priorities into fixed task snapshots', () => {
const snapshots = rebuildLegacyClearanceReviewSnapshots({
const rebuild = rebuildLegacyClearanceReviewSnapshots({
monthKey: '2026-11',
sourceSnapshot: {
version: 1,
@ -56,7 +56,8 @@ describe('clearance review archive compatibility', () => {
},
})
expect(snapshots).not.toBeNull()
expect(rebuild).not.toBeNull()
const snapshots = rebuild!.snapshots
expect(snapshots).toContainEqual(expect.objectContaining({
dimension: 'taskType',
dimensionKey: 'fixed',
@ -104,7 +105,7 @@ describe('clearance review archive compatibility', () => {
})
it('uses current owner organization instead of a person-valued legacy department', () => {
const snapshots = rebuildLegacyClearanceReviewSnapshots({
const rebuild = rebuildLegacyClearanceReviewSnapshots({
monthKey: '2026-11',
sourceSnapshot: {
version: 1,
@ -139,12 +140,13 @@ describe('clearance review archive compatibility', () => {
]]),
})
expect(snapshots).toContainEqual(expect.objectContaining({
expect(rebuild).not.toBeNull()
expect(rebuild!.snapshots).toContainEqual(expect.objectContaining({
dimension: 'deptHead',
dimensionKey: buildClearanceReviewKey('事业二部', '苏若兰'),
taskQty: 9,
}))
expect(snapshots).not.toContainEqual(expect.objectContaining({
expect(rebuild!.snapshots).not.toContainEqual(expect.objectContaining({
dimension: 'deptHead',
dimensionKey: buildClearanceReviewKey('苏若兰', '無尘/灵犀'),
}))

View File

@ -157,7 +157,7 @@ describe('clearance review archive builder', () => {
})
})
it('falls back to the store account profit center and marks unmatched mappings', () => {
it('falls back to store mapping and then a unique task profit center', () => {
const result = buildClearanceReviewArchive({
monthKey: '2026-10',
tasks: [task()],
@ -195,7 +195,7 @@ describe('clearance review archive builder', () => {
],
})
expect(result.unmatchedProfitCenterCount).toBe(1)
expect(result.unmatchedProfitCenterCount).toBe(0)
expect(result.details).toEqual(expect.arrayContaining([
expect.objectContaining({
shopName: '淘宝_测试店',
@ -203,6 +203,43 @@ describe('clearance review archive builder', () => {
profitCenterSource: 'STORE_ACCOUNT',
taskMatched: true,
}),
expect.objectContaining({
shopName: '待维护店铺',
profitCenter: '运营中心A',
profitCenterSource: 'TASK_CENTER',
taskMatched: true,
}),
]))
})
it('keeps an unmatched center when the barcode has tasks in multiple centers', () => {
const result = buildClearanceReviewArchive({
monthKey: '2026-10',
tasks: [
task(),
task({
profitCenter: '分销部',
channel: '分销部',
ownerName: '运营乙',
}),
],
sourceRows: [{
shopName: '待维护店铺',
barcode: 'SKU001',
profitCenter: '',
realPerformance: 10,
sendFreight: 1,
sendQty: 1,
refundQty: 0,
goodsCost: 5,
refundCost: 0,
sourceRowCount: 1,
sourceThrough: '2026-10-31',
}],
})
expect(result.unmatchedProfitCenterCount).toBe(1)
expect(result.details).toEqual(expect.arrayContaining([
expect.objectContaining({
shopName: '待维护店铺',
profitCenterSource: 'UNMATCHED',

View File

@ -6861,6 +6861,49 @@ describe('supply-chain-clearance workflow', () => {
expect(repository.findClearanceConfig).toHaveBeenCalledTimes(1)
})
it('includes approved business-support tasks in review totals', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-11-23T08:00:00.000Z'))
const approved = {
...pendingTask,
status: 'APPROVED',
taskQty: 8,
clearedQty: 2,
profitCenter: '业务支持',
department: '业务支持',
ownerName: '刘景刚',
}
repository.listReviewMonths.mockResolvedValue([])
repository.listTaskPeriods.mockResolvedValue(['2026-10'])
repository.listTasks.mockResolvedValue([approved] as never)
repository.listReviewTrendSnapshots.mockResolvedValue([])
repository.listOwnerProfilesByNames.mockResolvedValue([{
operationOwner: '刘景刚',
department: '业务支持',
profitCenter: '业务支持',
departmentOwner: '刘景刚',
generalOwner: '刘景刚',
}] as never)
repository.findPoolItemsByBarcodes.mockResolvedValue([{
barcode: 'SKU001',
department: '业务支持',
ownerName: '刘景刚',
costPrice: null,
extra: { profitCenter: '业务支持', priority: '优先级' },
}] as never)
const result = await supplyChainClearanceService.getReview({
periodKey: '2026-10',
dimension: 'channel',
})
expect(result.current).toContainEqual(expect.objectContaining({
dimensionKey: '业务支持',
reviewTaskCount: 1,
taskQty: 8,
clearedQty: 2,
}))
})
it('keeps both profit centers when one barcode has tasks in multiple centers', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-11-23T08:00:00.000Z'))
const approvedA = {
@ -7307,7 +7350,7 @@ describe('supply-chain-clearance workflow', () => {
expect(repository.replaceReviewArchive).not.toHaveBeenCalled()
})
it('does not allow a frozen monthly source snapshot to be replaced', async () => {
it('allows an explicit regeneration request past the frozen archive guard', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-11-23T08:00:00.000Z'))
repository.findReviewArchive.mockResolvedValue({
id: 'archive-1',
@ -7319,7 +7362,8 @@ describe('supply-chain-clearance workflow', () => {
periodKey: '2026-10',
replace: true,
user,
})).rejects.toThrow('清货周期已冻结')
})).rejects.toThrow('没有经管确认的清货任务')
expect(repository.listTasks).toHaveBeenCalledWith({ periodKey: '2026-10' })
expect(repository.replaceReviewArchive).not.toHaveBeenCalled()
})

View File

@ -86,7 +86,7 @@ function sourceRowsFromSnapshot(source: ArchiveSourceSnapshot): ClearanceReviewS
return [{
shopName: text(row.shopName),
barcode,
profitCenter: text(row.profitCenter),
profitCenter: text(row.profitCenter) === '未匹配利润中心' ? '' : text(row.profitCenter),
realPerformance: number(row.realPerformance) ?? 0,
sendFreight: number(row.sendFreight) ?? 0,
sendQty: number(row.sendQty) ?? 0,
@ -170,5 +170,11 @@ export function rebuildLegacyClearanceReviewSnapshots(input: {
byBarcode: new Map(),
},
})
return result.snapshots as ClearanceReviewSnapshotDraft[]
return {
snapshots: result.snapshots as ClearanceReviewSnapshotDraft[],
taskCount: result.taskCount,
detailCount: result.detailCount,
sourceRowCount: result.sourceRowCount,
unmatchedProfitCenterCount: result.unmatchedProfitCenterCount,
}
}

View File

@ -49,7 +49,7 @@ export type ClearanceReviewDetailDraft = {
shopName: string
barcode: string
profitCenter: string
profitCenterSource: 'SOURCE' | 'STORE_ACCOUNT' | 'UNMATCHED' | 'TASK_ONLY'
profitCenterSource: 'SOURCE' | 'STORE_ACCOUNT' | 'TASK_CENTER' | 'UNMATCHED' | 'TASK_ONLY'
realPerformance: number
sendFreight: number
sendQty: number
@ -184,6 +184,20 @@ export function buildClearanceReviewArchive(input: {
const tasks = latestTaskPerBarcodeProfitCenter(input.tasks)
const taskByScope = new Map(tasks.map((task) => [clearanceReviewTaskKey(task), task]))
const taskBarcodes = new Set(tasks.map((task) => task.barcode.trim().toUpperCase()))
const taskCentersByBarcode = new Map<string, Set<string>>()
for (const task of tasks) {
const barcode = task.barcode.trim().toUpperCase()
const profitCenter = task.profitCenter.trim()
if (!barcode || !profitCenter) continue
const centers = taskCentersByBarcode.get(barcode) ?? new Set<string>()
centers.add(profitCenter)
taskCentersByBarcode.set(barcode, centers)
}
const uniqueTaskCenterByBarcode = new Map(
Array.from(taskCentersByBarcode)
.filter(([, centers]) => centers.size === 1)
.map(([barcode, centers]) => [barcode, Array.from(centers)[0]] as const),
)
const storeCenters = new Map<string, Set<string>>()
for (const row of input.storeProfitCenters ?? []) {
const storeName = normalizedClearanceReviewShopName(row.storeName)
@ -205,14 +219,35 @@ export function buildClearanceReviewArchive(input: {
const barcode = row.barcode.trim().toUpperCase()
if (!taskBarcodes.has(barcode)) continue
const sourceProfitCenter = row.profitCenter.trim()
const mappedProfitCenter = sourceProfitCenter
|| storeCenterByShop.get(normalizedClearanceReviewShopName(row.shopName))
|| ''
const profitCenterSource = sourceProfitCenter
const storeProfitCenter = storeCenterByShop.get(
normalizedClearanceReviewShopName(row.shopName),
) ?? ''
const taskCenter = uniqueTaskCenterByBarcode.get(barcode) ?? ''
const taskCenterMatches = (center: string) => Boolean(
center && taskByScope.has(clearanceReviewTaskKey({ barcode, profitCenter: center })),
)
const matchedProfitCenter = [
sourceProfitCenter,
storeProfitCenter,
taskCenter,
].find(taskCenterMatches) ?? ''
const mappedProfitCenter = matchedProfitCenter
|| sourceProfitCenter
|| storeProfitCenter
|| taskCenter
const profitCenterSource = matchedProfitCenter === sourceProfitCenter && sourceProfitCenter
? 'SOURCE'
: mappedProfitCenter
: matchedProfitCenter === storeProfitCenter && storeProfitCenter
? 'STORE_ACCOUNT'
: 'UNMATCHED'
: matchedProfitCenter === taskCenter && taskCenter
? 'TASK_CENTER'
: sourceProfitCenter
? 'SOURCE'
: storeProfitCenter
? 'STORE_ACCOUNT'
: taskCenter
? 'TASK_CENTER'
: 'UNMATCHED'
if (profitCenterSource === 'UNMATCHED') unmatchedProfitCenterCount += 1
const key = clearanceReviewTaskKey({
barcode,

View File

@ -174,7 +174,10 @@ const clearanceReviewArchiveJobs = new Map<string, {
summary: unknown
warnings: unknown
}>()
const legacyClearanceReviewSnapshotCache = new Map<string, unknown[]>()
const legacyClearanceReviewSnapshotCache = new Map<
string,
NonNullable<ReturnType<typeof rebuildLegacyClearanceReviewSnapshots>>
>()
type ClearancePoolGenerationJob = {
periodKey: string
@ -4176,9 +4179,25 @@ class SupplyChainClearanceService {
canReview?: boolean
includeFreight?: boolean
liveProgress?: boolean
groupComponents?: boolean
}) {
const periodKey = normalizePeriodKey(periodKeyInput)
const tasks = await supplyChainClearanceRepository.listTasks({ periodKey })
const frozenArchive = await this.frozenPeriodArchive(periodKey)
const frozenSnapshot = frozenArchive?.sourceSnapshot
&& typeof frozenArchive.sourceSnapshot === 'object'
&& !Array.isArray(frozenArchive.sourceSnapshot)
? frozenArchive.sourceSnapshot as Record<string, unknown>
: {}
const frozenPoolRows = Array.isArray(frozenSnapshot.poolRows)
? frozenSnapshot.poolRows
: []
const loadPoolItems = () => frozenPoolRows.length
? Promise.resolve(frozenPoolRows as never)
: supplyChainClearanceRepository.listPoolItemsForTaskPeriod(
periodKey,
tasks.map((task) => task.barcode),
)
const liveProgress = input?.liveProgress !== false
let poolItems: Awaited<ReturnType<
typeof supplyChainClearanceRepository.listPoolItemsForTaskPeriod
@ -4186,19 +4205,13 @@ class SupplyChainClearanceService {
let progress: ClearanceProgressSnapshot
if (liveProgress) {
[poolItems, progress] = await Promise.all([
supplyChainClearanceRepository.listPoolItemsForTaskPeriod(
periodKey,
tasks.map((task) => task.barcode),
),
loadPoolItems(),
this.loadTaskProgress(periodKey, tasks),
])
} else {
const taskIds = tasks.map((task) => task.id)
const [nextPoolItems, coverageRows] = await Promise.all([
supplyChainClearanceRepository.listPoolItemsForTaskPeriod(
periodKey,
tasks.map((task) => task.barcode),
),
loadPoolItems(),
supplyChainClearanceRepository.listTaskShipmentCoverage(taskIds),
])
poolItems = nextPoolItems
@ -4505,6 +4518,16 @@ class SupplyChainClearanceService {
})
})
}
const stripInternalTaskRow = (row: (typeof mapped)[number]) => {
const {
actualShipQty: _actualShipQty,
componentCost: _componentCost,
componentClearancePrice: _componentClearancePrice,
hasDiscount: _hasDiscount,
...visibleRow
} = row
return visibleRow
}
const grouped = Array.from(
mapped.reduce((groups, task) => {
const key = [
@ -4521,18 +4544,8 @@ class SupplyChainClearanceService {
return groups
}, new Map<string, Array<(typeof mapped)[number]>>()),
).flatMap(([, rows]) => {
const stripInternal = (row: (typeof mapped)[number]) => {
const {
actualShipQty: _actualShipQty,
componentCost: _componentCost,
componentClearancePrice: _componentClearancePrice,
hasDiscount: _hasDiscount,
...visibleRow
} = row
return visibleRow
}
if (rows.length === 1 || new Set(rows.map((row) => row.barcode)).size === 1) {
return rows.map(stripInternal)
return rows.map(stripInternalTaskRow)
}
const minValue = (values: number[]) => values.length ? Math.min(...values) : 0
const minNullable = (values: Array<number | null>) => {
@ -4569,7 +4582,7 @@ class SupplyChainClearanceService {
}),
})
return [{
...stripInternal(base),
...stripInternalTaskRow(base),
taskIds: Array.from(new Set(rows.flatMap((row) => row.taskIds))),
spu: uniqueText(rows.map((row) => row.spu)),
costPrice,
@ -4596,8 +4609,11 @@ class SupplyChainClearanceService {
: '',
}]
})
const taskRows = input?.groupComponents === false
? mapped.map(stripInternalTaskRow)
: grouped
const selectedRound = input?.round === 1 || input?.round === 2 ? input.round : null
const roundScoped = grouped.filter((task) => !selectedRound || task.round === selectedRound)
const roundScoped = taskRows.filter((task) => !selectedRound || task.round === selectedRound)
const canViewAllApplications = input?.canReview !== false
const operatorVisible = (task: (typeof roundScoped)[number]) => (
canViewAllApplications
@ -7283,15 +7299,11 @@ class SupplyChainClearanceService {
}))
const owners = new Map(tasks.map((task) => [task.id, effectiveClearanceTaskOwner(task)]))
const ownerProfiles = await loadClearanceReviewOwnerProfiles(owners.values())
const reviewTasks = tasks.filter((task) => {
const profile = ownerProfiles.get(owners.get(task.id) || '')
return !profile?.profitCenter || isClearanceTaskProfitCenter(profile.profitCenter)
})
return {
savedAt: reviewTasks.reduce<Date | null>((latest, task) => (
savedAt: tasks.reduce<Date | null>((latest, task) => (
task.lastProgressAt && (!latest || task.lastProgressAt > latest) ? task.lastProgressAt : latest
), null),
tasks: reviewTasks.map((task) => {
tasks: tasks.map((task) => {
const barcode = task.barcode.trim().toUpperCase()
const poolItem = poolByBarcode.get(barcode)
const extra = poolExtra(poolItem ?? {})
@ -7405,10 +7417,6 @@ class SupplyChainClearanceService {
`${periodKey} 已有月度清货复盘存档;如需覆盖,请明确确认重新生成`,
)
}
throw new AppError(
ErrorCode.VALIDATION_INVALID_FORMAT,
`${periodKey} 清货周期已冻结,不能再覆盖月度数据快照`,
)
}
const approvedTasks = tasks.filter((task) => task.status === 'APPROVED')
if (!approvedTasks.length) {
@ -7423,19 +7431,8 @@ class SupplyChainClearanceService {
supplyChainClearanceRepository.listPoolRowsForPeriodSnapshot(periodKey),
loadClearanceReviewOwnerProfiles(owners.values()),
])
const reviewApprovedTasks = approvedTasks.filter((task) => {
const ownerName = owners.get(task.id) || ''
const profile = ownerProfiles.get(ownerName)
return !profile?.profitCenter || isClearanceTaskProfitCenter(profile.profitCenter)
})
if (!reviewApprovedTasks.length) {
throw new AppError(
ErrorCode.RESOURCE_NOT_FOUND,
`${periodKey} 没有可纳入清货复盘的运营利润中心任务`,
)
}
const approvedBarcodeSet = new Set(
reviewApprovedTasks.map((task) => task.barcode.trim().toUpperCase()),
approvedTasks.map((task) => task.barcode.trim().toUpperCase()),
)
const poolByBarcode = new Map(poolItems
.filter((item) => approvedBarcodeSet.has(item.barcode.trim().toUpperCase()))
@ -7454,7 +7451,7 @@ class SupplyChainClearanceService {
priority,
taskType,
}))
const needsOwnerCenter = reviewApprovedTasks.some((task) => (
const needsOwnerCenter = approvedTasks.some((task) => (
!task.profitCenter.trim()
&& !String(poolExtra(poolByBarcode.get(task.barcode.trim().toUpperCase()) ?? {}).profitCenter ?? '').trim()
&& !ownerProfiles.get(owners.get(task.id) || '')?.profitCenter
@ -7465,7 +7462,7 @@ class SupplyChainClearanceService {
const centerByOwner = new Map(ownerCenters.map((row) => [
row.operationOwner.trim(), row.profitCenter.trim(),
]))
const reviewTasks = reviewApprovedTasks.map((task) => {
const reviewTasks = approvedTasks.map((task) => {
const barcode = task.barcode.trim().toUpperCase()
const poolItem = poolByBarcode.get(barcode)
const extra = poolItem?.extra
@ -7509,7 +7506,7 @@ class SupplyChainClearanceService {
const sourceRows = await supplyChainClearanceReviewSourceRepository.listMonthlySales({
startDate: `${periodKey}-01`,
endDateExclusive,
barcodes: reviewApprovedTasks.map((task) => task.barcode),
barcodes: approvedTasks.map((task) => task.barcode),
})
if (!sourceRows.length) {
throw new AppError(
@ -7684,6 +7681,10 @@ class SupplyChainClearanceService {
string,
NonNullable<Awaited<ReturnType<typeof supplyChainClearanceRepository.findReviewArchive>>>
>()
const correctedArchiveByMonth = new Map<
string,
NonNullable<ReturnType<typeof rebuildLegacyClearanceReviewSnapshots>>
>()
if (legacySnapshotMonths.length) {
const loadedArchives = await Promise.all(
legacySnapshotMonths.map((month) => (
@ -7728,14 +7729,6 @@ class SupplyChainClearanceService {
const organizationProfiles = sourceOrganizationNames.length
? await supplyChainClearanceRepository.listOwnerProfilesByNames(sourceOrganizationNames)
: []
const sourceOwnerNames = new Set(sourceOwners)
const excludedDepartments = new Set(organizationProfiles.flatMap((profile) => (
sourceOwnerNames.has(profile.operationOwner.trim())
&& profile.profitCenter
&& !isClearanceTaskProfitCenter(profile.profitCenter)
? [profile.department?.trim() ?? '']
: []
)).filter(Boolean))
const sourceBarcodes = sourceTasks.flatMap((task) => (
task.status === 'APPROVED' && String(task.barcode ?? '').trim()
? [String(task.barcode).trim().toUpperCase()]
@ -7853,7 +7846,6 @@ class SupplyChainClearanceService {
archive.monthKey,
archive.generatedAt.toISOString(),
JSON.stringify(Array.from(taskTypeMappingByPriority)),
JSON.stringify(Array.from(excludedDepartments).sort()),
JSON.stringify(Array.from(organizationByOwner).sort()),
].join('\u0000')
const corrected = legacyClearanceReviewSnapshotCache.get(cacheKey)
@ -7864,16 +7856,16 @@ class SupplyChainClearanceService {
priority,
taskType,
})),
excludedDepartments,
organizationByOwner,
})
if (corrected && !legacyClearanceReviewSnapshotCache.has(cacheKey)) {
legacyClearanceReviewSnapshotCache.set(cacheKey, corrected as unknown[])
legacyClearanceReviewSnapshotCache.set(cacheKey, corrected)
}
if (!corrected) continue
correctedArchiveByMonth.set(archive.monthKey, corrected)
analysisSnapshotRows = [
...analysisSnapshotRows.filter((row) => row.monthKey !== archive.monthKey),
...corrected as never,
...corrected.snapshots as never,
]
}
}
@ -7949,7 +7941,19 @@ class SupplyChainClearanceService {
const trend = Array.from(overallByMonth.values())
.filter((row) => archiveByMonth.has(row.monthKey))
.sort((a, b) => a.monthKey.localeCompare(b.monthKey))
const archive = loadedArchiveByMonth.get(periodKey) ?? archiveByMonth.get(periodKey)
const rawArchive = loadedArchiveByMonth.get(periodKey) ?? archiveByMonth.get(periodKey)
const correctedArchive = rawArchive
? correctedArchiveByMonth.get(periodKey)
: null
const archive = rawArchive && correctedArchive
? {
...rawArchive,
taskCount: correctedArchive.taskCount,
detailCount: correctedArchive.detailCount,
sourceRowCount: correctedArchive.sourceRowCount,
unmatchedProfitCenterCount: correctedArchive.unmatchedProfitCenterCount,
}
: rawArchive
const progressTime = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',