fix(clearance): 补齐月度流程字段与负责人兜底

This commit is contained in:
居居 2026-11-20 14:16:06 +08:00
parent 45c164dd81
commit 7b6cdd1562
6 changed files with 251 additions and 102 deletions

View File

@ -10,6 +10,7 @@ import {
matchesClearanceFilters,
type ClearanceFilterCondition,
} from '@/lib/clearance-filters'
import { clearanceFullGenerationBlockReason } from '@/lib/clearance-generation-guard'
import { formatClearanceDailySales } from '@/lib/clearance-number-format'
import styles from '../custom-table/limit-management.module.css'
import ui from './clearance.module.css'
@ -677,6 +678,11 @@ export function ClearanceView({
const [windowSaving, setWindowSaving] = useState(false)
const [windowError, setWindowError] = useState('')
const [windowGenerateMode, setWindowGenerateMode] = useState<WindowGenerateMode>('NONE')
const fullGenerationBlockReason = clearanceFullGenerationBlockReason({
periodKey: windowPeriod,
currentPeriodKey: currentPeriodKey(),
hasExistingPool: (pool?.periods ?? []).includes(windowPeriod),
})
const [taskPeriod, setTaskPeriod] = useState(() => currentPeriodKey())
const [taskPage, setTaskPage] = useState(1)
@ -1383,6 +1389,10 @@ export function ClearanceView({
setWindowError('结束时间必须晚于开始时间')
return
}
if (windowGenerateMode === 'FULL' && fullGenerationBlockReason) {
setWindowError(fullGenerationBlockReason)
return
}
setWindowSaving(true)
setWindowError('')
let windowSaved = false
@ -3015,7 +3025,9 @@ export function ClearanceView({
onChange={(event) => setWindowGenerateMode(event.target.value as WindowGenerateMode)}
>
<option value="NONE">仅保存时间窗口:不生成或修改清货池</option>
<option value="FULL">常规生成:按产品全量档案完整生成或覆盖该月清货池</option>
<option value="FULL" disabled={Boolean(fullGenerationBlockReason)}>
常规生成:按产品全量档案完整生成或覆盖该月清货池
</option>
<option
value="ROUND2_REFRESH"
disabled={!(pool?.periods ?? []).includes(windowPeriod)}
@ -3046,7 +3058,14 @@ export function ClearanceView({
<span>次月任务制定:目标月前一个月最后 7 天;次月折扣调整:目标月第 8 天起第一个工作日(自动跳过周末,节假日可人工调整)。</span>
</div>
<span className={ui.subline}>保存后立即由经管确认生效;如选择生成,将在窗口保存成功后执行。</span>
{windowError && <div className={styles.formError} role="alert">{windowError}</div>}
{fullGenerationBlockReason ? (
<div className={styles.formError} role="alert">
{fullGenerationBlockReason}
</div>
) : null}
{windowError && windowError !== fullGenerationBlockReason ? (
<div className={styles.formError} role="alert">{windowError}</div>
) : null}
</>
) : configTab === 'score' ? (
<ClearanceScoreConfigEditor />
@ -3067,6 +3086,7 @@ export function ClearanceView({
disabled={
windowSaving
|| windowDialogLoading
|| (windowGenerateMode === 'FULL' && Boolean(fullGenerationBlockReason))
|| (windowGenerateMode === 'ROUND2_REFRESH' && !(pool?.periods ?? []).includes(windowPeriod))
}
onClick={() => void saveApplicationWindow()}

View File

@ -0,0 +1,35 @@
import { clearanceFullGenerationBlockReason } from './clearance-generation-guard'
describe('clearance full generation guard', () => {
it('blocks historical months', () => {
expect(clearanceFullGenerationBlockReason({
periodKey: '2026-10',
currentPeriodKey: '2026-11',
hasExistingPool: false,
})).toContain('历史月份')
})
it('blocks overwriting an already generated current month', () => {
expect(clearanceFullGenerationBlockReason({
periodKey: '2026-11',
currentPeriodKey: '2026-11',
hasExistingPool: true,
})).toContain('当前月清货池已生成')
})
it('allows the first generation of the current month', () => {
expect(clearanceFullGenerationBlockReason({
periodKey: '2026-11',
currentPeriodKey: '2026-11',
hasExistingPool: false,
})).toBe('')
})
it('allows future month generation and repeated full regeneration', () => {
expect(clearanceFullGenerationBlockReason({
periodKey: '2026-12',
currentPeriodKey: '2026-11',
hasExistingPool: true,
})).toBe('')
})
})

View File

@ -0,0 +1,16 @@
export function clearanceFullGenerationBlockReason(input: {
periodKey: string
currentPeriodKey: string
hasExistingPool: boolean
}) {
if (input.periodKey < input.currentPeriodKey) {
return '历史月份清货池不能通过常规生成覆盖'
}
if (
input.periodKey === input.currentPeriodKey
&& input.hasExistingPool
) {
return '当前月清货池已生成,不能通过常规生成覆盖;如需调整请使用二次折扣调整'
}
return ''
}

View File

@ -533,22 +533,6 @@ class SupplyChainClearanceRepository {
})
}
async listPoolRowsForWorkflowSnapshot(periodKey: string) {
const generation = await this.findPoolGeneration(periodKey)
if (!generation) return []
return prisma.supplyChainClearancePoolSnapshot.findMany({
where: {
periodKey,
statDate: generation.statDate,
},
select: {
barcode: true,
extra: true,
},
orderBy: { barcode: 'asc' },
})
}
async updatePoolPriorities(input: {
periodKey: string
updates: Array<{ barcode: string; priority: string }>

View File

@ -60,7 +60,6 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({
listOwnerProfitCenters: jest.fn(),
listLatestVirtualCloudStocks: jest.fn(),
listPoolRowsForBatchCarry: jest.fn(),
listPoolRowsForWorkflowSnapshot: jest.fn(),
updatePoolPriorities: jest.fn(),
replacePoolGeneration: jest.fn(),
listPoolRowsForRefresh: jest.fn(),
@ -454,7 +453,6 @@ describe('supply-chain-clearance workflow', () => {
repository.listOwnerProfitCenters.mockResolvedValue([])
repository.listLatestVirtualCloudStocks.mockResolvedValue([])
repository.listPoolRowsForBatchCarry.mockResolvedValue([])
repository.listPoolRowsForWorkflowSnapshot.mockResolvedValue([])
repository.updatePoolPriorities.mockResolvedValue({
updated: 0,
missingBarcodes: [],
@ -844,7 +842,9 @@ describe('supply-chain-clearance workflow', () => {
})).resolves.toEqual({ values: ['库存积压'] })
})
it('generates a frozen monthly pool from product archive data once', async () => {
it('fully regenerates the monthly pool with the latest data each time', async () => {
jest.useFakeTimers()
jest.setSystemTime(new Date('2026-10-21T02:00:00.000Z'))
repository.listClearanceArchiveRows.mockResolvedValue([
{
barcode: 'sku001',
@ -1023,6 +1023,9 @@ describe('supply-chain-clearance workflow', () => {
dailySales: '7.35',
productStatus: '退市',
salesStatus: '退市',
skuProductionStatus: '退市',
ownerName: '测试运营',
department: '测试部门',
availableDays: '0',
sourceFileName: 'product-archive+clearance-stock+combo',
extra: {
@ -1088,20 +1091,11 @@ describe('supply-chain-clearance workflow', () => {
generationMode: 'FULL',
createdAt: new Date('2026-11-01T10:30:00.000Z'),
} as never)
repository.listPoolRowsForWorkflowSnapshot.mockResolvedValue([{
barcode: 'SKU001',
extra: {
specialInboundRemaining: 41,
applicant: '首月申请人',
ownerProfitCenter: '运营中心B',
inventoryInboundAt: '2026-10-01',
},
}] as never)
mockGetWorkflowClearanceOverview.mockResolvedValue({
overview: {
rows: [{
code: 'SKU001',
applicant: '后续申请人',
applicant: '测试运营',
remainingClearance: 8,
enterStockAt: '2026-10-28',
}],
@ -1116,13 +1110,109 @@ describe('supply-chain-clearance workflow', () => {
user,
})
expect(mockGetWorkflowClearanceOverview).not.toHaveBeenCalled()
expect(repository.listPoolRowsForWorkflowSnapshot).toHaveBeenCalledWith('2026-11')
expect(mockGetWorkflowClearanceOverview).toHaveBeenCalledTimes(1)
expect(repository.replacePoolGeneration.mock.calls[0][0].rows[0].extra).toMatchObject({
specialInboundRemaining: 41,
applicant: '首月申请人',
ownerProfitCenter: '运营中心B',
inventoryInboundAt: '2026-10-01',
specialInboundRemaining: 8,
applicant: '测试运营',
ownerProfitCenter: '运营中心A',
inventoryInboundAt: '2026-10-28',
})
})
it('blocks full generation of an already generated current-month pool', async () => {
jest.useFakeTimers()
jest.setSystemTime(new Date('2026-11-20T02:00:00.000Z'))
repository.findPoolGeneration.mockResolvedValue({
id: 'generation-11',
periodKey: '2026-11',
statDate: new Date('2026-11-01T00:00:00.000Z'),
statTime: new Date('2026-11-01T10:30:00.000Z'),
generatedAt: new Date('2026-11-01T10:30:00.000Z'),
generatedById: user.id,
generatedByName: user.name,
rowCount: 1,
generationMode: 'FULL',
createdAt: new Date('2026-11-01T10:30:00.000Z'),
} as never)
await expect(supplyChainClearanceService.generatePool({
periodKey: '2026-11',
user,
})).rejects.toThrow('当前月清货池已生成')
expect(repository.listClearanceArchiveRows).not.toHaveBeenCalled()
})
it('blocks full generation of historical months', async () => {
jest.useFakeTimers()
jest.setSystemTime(new Date('2026-11-20T02:00:00.000Z'))
await expect(supplyChainClearanceService.generatePool({
periodKey: '2026-10',
user,
})).rejects.toThrow('历史月份清货池不能通过常规生成覆盖')
expect(repository.listClearanceArchiveRows).not.toHaveBeenCalled()
})
it('falls back to the department head when the SPU owner is blank', async () => {
repository.listClearanceArchiveRows.mockResolvedValue([{
barcode: 'OWNER001',
spu: 'SPU-OWNER',
sku: 'SKU-OWNER',
image: null,
productName: '负责人兜底商品',
brand: '测试品牌',
categoryL2: '电脑桌',
productStatus: '销售',
supplierName: '测试供应商',
packType: '双包',
supplierStatus: '合作',
sales7d: '1',
businessCreatedAt: new Date('2026-01-01T00:00:00.000Z'),
opsHead: '',
opsDeptHead: '部门负责人',
opsDirector: '测试总监',
costPrice: '10.00',
}] as never)
repository.listOwnerProfitCenters.mockResolvedValue([{
operationOwner: '部门负责人',
profitCenter: '运营中心D',
}])
sourceRepository.listClearanceWarehouseInventoryByBarcodes.mockResolvedValue([{
barcode: 'OWNER001',
bigWarehouseStock: 10,
frontWarehouseStock: 0,
dedicatedWarehouseStock: 0,
dropshipStock: 0,
}])
sourceRepository.listLiveProductStatusesByBarcodes.mockResolvedValue([{
barcode: 'OWNER001',
productStatus: '销售',
}])
repository.replacePoolGeneration.mockImplementation(async (input) => ({
id: 'generation-owner',
periodKey: input.generation.periodKey,
statDate: input.generation.statDate,
generatedAt: input.generation.generatedAt,
generatedById: input.generation.generatedById ?? '',
generatedByName: input.generation.generatedByName ?? '',
rowCount: input.generation.rowCount ?? 0,
generationMode: input.generation.generationMode ?? 'FULL',
createdAt: new Date(),
}) as never)
await supplyChainClearanceService.generatePool({
periodKey: '2026-11',
user,
})
expect(repository.replacePoolGeneration.mock.calls[0][0].rows[0]).toMatchObject({
barcode: 'OWNER001',
ownerName: '部门负责人',
department: '部门负责人',
skuProductionStatus: '销售',
extra: {
profitCenter: '运营中心D',
},
})
})
@ -1507,6 +1597,8 @@ describe('supply-chain-clearance workflow', () => {
})
it('allows management to regenerate and replace the same month', async () => {
jest.useFakeTimers()
jest.setSystemTime(new Date('2026-10-21T02:00:00.000Z'))
repository.findPoolGeneration.mockResolvedValue({
id: 'generation-1',
periodKey: '2026-11',

View File

@ -7,6 +7,7 @@ import {
matchesClearanceFilters,
type ClearanceFilterCondition,
} from '@/lib/clearance-filters'
import { clearanceFullGenerationBlockReason } from '@/lib/clearance-generation-guard'
import {
evaluateClearanceFixedTaskFormula,
normalizeClearanceFixedTaskRules,
@ -345,32 +346,17 @@ function poolExtra(row: { extra?: unknown }) {
}
type ClearanceWorkflowPoolFields = {
specialInboundRemaining: unknown
specialInboundRemaining: string | number
applicant: string
ownerProfitCenter: string
inventoryInboundAt: string
}
function workflowPoolFieldsFromExtra(extra: unknown): ClearanceWorkflowPoolFields | null {
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) return null
const record = extra as Record<string, unknown>
const keys = [
'specialInboundRemaining',
'applicant',
'ownerProfitCenter',
'inventoryInboundAt',
] as const
if (!keys.some((key) => Object.prototype.hasOwnProperty.call(record, key))) return null
return {
specialInboundRemaining: record.specialInboundRemaining ?? '',
applicant: typeof record.applicant === 'string' ? record.applicant : '',
ownerProfitCenter: typeof record.ownerProfitCenter === 'string'
? record.ownerProfitCenter
: '',
inventoryInboundAt: typeof record.inventoryInboundAt === 'string'
? record.inventoryInboundAt
: '',
}
const EMPTY_CLEARANCE_WORKFLOW_POOL_FIELDS: ClearanceWorkflowPoolFields = {
specialInboundRemaining: '',
applicant: '',
ownerProfitCenter: '',
inventoryInboundAt: '',
}
async function clearanceWorkflowFieldsByBarcode(
@ -378,25 +364,33 @@ async function clearanceWorkflowFieldsByBarcode(
) {
try {
const { overview } = await dingtalkWorkflowClearanceService.getOverview()
return new Map<string, ClearanceWorkflowPoolFields>(overview.rows.flatMap((row) => {
const barcode = row.code.trim().toUpperCase()
if (!barcode) return []
const applicant = row.applicant.trim()
return [[
barcode,
{
specialInboundRemaining: row.remainingClearance,
applicant,
ownerProfitCenter: profitCenterByOwner.get(applicant) ?? '',
inventoryInboundAt: row.enterStockAt,
},
] as const]
}))
return {
captured: true,
fieldsByBarcode: new Map<string, ClearanceWorkflowPoolFields>(
overview.rows.flatMap((row) => {
const barcode = row.code.trim().toUpperCase()
if (!barcode) return []
const applicant = row.applicant.trim()
return [[
barcode,
{
specialInboundRemaining: row.remainingClearance,
applicant,
ownerProfitCenter: profitCenterByOwner.get(applicant) ?? '',
inventoryInboundAt: row.enterStockAt,
},
] as const]
}),
),
}
} catch (error) {
console.warn('[clearance] workflow remaining-clearance fields unavailable', {
error: error instanceof Error ? error.message : String(error),
})
return new Map<string, ClearanceWorkflowPoolFields>()
return {
captured: false,
fieldsByBarcode: new Map<string, ClearanceWorkflowPoolFields>(),
}
}
}
@ -1023,18 +1017,16 @@ class SupplyChainClearanceService {
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '清货月份格式必须为 YYYY-MM')
}
const existing = await supplyChainClearanceRepository.findPoolGeneration(periodKey)
const existingWorkflowSnapshotRows =
mode === 'FULL' && existing
? await supplyChainClearanceRepository.listPoolRowsForWorkflowSnapshot(periodKey)
: []
const existingWorkflowSnapshotByBarcode = new Map(
existingWorkflowSnapshotRows.flatMap((row) => {
const fields = workflowPoolFieldsFromExtra(row.extra)
return fields
? [[row.barcode.trim().toUpperCase(), fields] as const]
: []
}),
)
if (mode === 'FULL') {
const blockReason = clearanceFullGenerationBlockReason({
periodKey,
currentPeriodKey: shanghaiDateKey(new Date()).slice(0, 7),
hasExistingPool: Boolean(existing),
})
if (blockReason) {
throw new AppError(ErrorCode.VALIDATION_OUT_OF_RANGE, blockReason)
}
}
if (mode === 'ROUND2_REFRESH' && !existing) {
throw new AppError(
ErrorCode.RESOURCE_NOT_FOUND,
@ -1300,9 +1292,12 @@ class SupplyChainClearanceService {
const profitCenterByOwner = new Map(
ownerProfitCenters.map((row) => [row.operationOwner.trim(), row.profitCenter]),
)
const workflowFieldsByBarcode = mode === 'FULL' && !existing
const workflowFieldCapture = mode === 'FULL'
? await clearanceWorkflowFieldsByBarcode(profitCenterByOwner)
: new Map<string, ClearanceWorkflowPoolFields>()
: {
captured: false,
fieldsByBarcode: new Map<string, ClearanceWorkflowPoolFields>(),
}
const comboIssueCache = new Map<string, string | null>()
const rows = archiveRows.flatMap((row) => {
const barcode = row.barcode.trim().toUpperCase()
@ -1324,7 +1319,9 @@ class SupplyChainClearanceService {
issueCache: comboIssueCache,
})
const availableDays = availableDaysText(combo.clearanceTotal, dailySales)
const profitCenter = profitCenterByOwner.get(row.opsHead.trim()) ?? ''
const ownerName = row.opsHead.trim() || row.opsDeptHead.trim()
const department = row.opsDeptHead.trim()
const profitCenter = profitCenterByOwner.get(ownerName) ?? ''
const discontinuedAt = isSalesClearanceStatus(productStatus)
? ''
: discontinuedAtByBarcode.get(barcode) ?? ''
@ -1356,9 +1353,13 @@ class SupplyChainClearanceService {
availableDays,
nextBatchNumber,
})
const workflowFields = existing
? existingWorkflowSnapshotByBarcode.get(barcode)
: workflowFieldsByBarcode.get(barcode)
const workflowFields = workflowFieldCapture.captured
? workflowFieldCapture.fieldsByBarcode.get(barcode)
?? EMPTY_CLEARANCE_WORKFLOW_POOL_FIELDS
: null
const skuProductionStatus = skuProductionStatusBySku.get(
row.sku.trim().toUpperCase(),
) ?? ''
const extra = {
bigWarehouseStock: stock.bigWarehouseStock,
frontWarehouseStock: stock.frontWarehouseStock,
@ -1380,10 +1381,12 @@ class SupplyChainClearanceService {
batchStatusBasis: batchAssignment.batchStatusBasis,
taskChannelClosed: batchAssignment.taskChannelClosed,
discountChannelClosed: batchAssignment.discountChannelClosed,
specialInboundRemaining: workflowFields?.specialInboundRemaining ?? '',
applicant: workflowFields?.applicant ?? '',
ownerProfitCenter: workflowFields?.ownerProfitCenter ?? '',
inventoryInboundAt: workflowFields?.inventoryInboundAt ?? '',
...(workflowFields ? {
specialInboundRemaining: workflowFields.specialInboundRemaining,
applicant: workflowFields.applicant,
ownerProfitCenter: workflowFields.ownerProfitCenter,
inventoryInboundAt: workflowFields.inventoryInboundAt,
} : {}),
...poolReviewScoreExtra(reviewScore),
}
const ruleSubject = {
@ -1394,14 +1397,12 @@ class SupplyChainClearanceService {
category: row.categoryL2,
productStatus,
salesStatus: productStatus,
skuProductionStatus: skuProductionStatusBySku.get(
row.sku.trim().toUpperCase(),
) ?? '',
skuProductionStatus,
supplierName: row.supplierName,
packType: combo.packType,
cooperationStatus: row.supplierStatus,
ownerName: row.opsHead,
department: row.opsDeptHead,
ownerName,
department,
stockJianshang: stock.stockJianshang,
stockFactory: stock.stockFactory,
totalStock: stock.totalStock,
@ -1455,14 +1456,15 @@ class SupplyChainClearanceService {
category: row.categoryL2,
productStatus,
salesStatus: productStatus,
skuProductionStatus,
supplierName: row.supplierName,
packType: combo.packType,
cooperationStatus: row.supplierStatus,
dailySales: dailySales?.toFixed(2) ?? null,
availableDays,
businessCreatedAt: row.businessCreatedAt,
ownerName: row.opsHead,
department: row.opsDeptHead,
ownerName,
department,
directorName: row.opsDirector,
costPrice: number(row.costPrice)?.toFixed(2) ?? null,
stockJianshang: stock.stockJianshang,