merge(clearance): 合入审核确认推送性能优化
This commit is contained in:
commit
146c5bbcf1
@ -92,7 +92,7 @@
|
||||
- 任务量不能超过该商品的清货总量;超过简尚库存时按简尚库存保留。
|
||||
- 销售状态商品不允许申请折扣,也不允许填写折扣原因。
|
||||
- 同一货号去掉 `GBGJ-`、`GBSFY-`、`GBPM-` 前缀后视为同款;只要同款中任一编码为销售状态,其他退市或停产编码也不允许申请折扣。
|
||||
- 固定任务可绕过任务通道关闭、简尚无库存但仅有代发库存、以及配置禁折限制;但商品本身或同款族存在销售状态时,固定任务仍不允许申请折扣。
|
||||
- 固定任务可绕过任务通道关闭、简尚无库存但仅有代发库存、以及配置禁折限制;但商品本身或同款族存在销售状态时,固定任务仍不允许申请折扣。优先级为“A 固定任务”或“A 固定任务-特殊入库”时,固定任务也不允许申请折扣。
|
||||
- 非销售状态商品填写折扣时,必须先填写有效任务量并填写原因。
|
||||
- 多包异常商品不允许填写任务或申请折扣。
|
||||
- 当前商品必须存在于对应月份清货池中。
|
||||
|
||||
@ -145,7 +145,7 @@
|
||||
|
||||
同一货号按品牌前缀归为同款族:去掉 `GBGJ-`、`GBSFY-`、`GBPM-` 后货号相同即视为同款;只要族内任一商品编码为销售状态,其他退市或停产编码也不能申请折扣,但任务量仍可正常制定。
|
||||
|
||||
固定任务可以绕过任务通道关闭、仅代发库存和配置禁折限制,可填写任务并申请折扣;但商品本身或同款族存在销售状态时,固定任务仍不允许申请折扣。
|
||||
固定任务可以绕过任务通道关闭、仅代发库存和配置禁折限制,可填写任务并申请折扣;但商品本身或同款族存在销售状态时,固定任务仍不允许申请折扣。优先级为“A 固定任务”或“A 固定任务-特殊入库”时,固定任务也不允许申请折扣。
|
||||
|
||||
申请折扣时必须填写申请原因;没有折扣需求时折扣留空。历史草稿和单条接口仅为兼容旧数据保留,不构成当前任务入口。
|
||||
|
||||
|
||||
@ -658,7 +658,11 @@ export function ClearanceReviewWorkbench({
|
||||
onClick={() => void review('approve')}
|
||||
>
|
||||
<Check size={14} />
|
||||
{selectedStage === 'CONFIRMED' ? '终审通过并推送' : '审核并推送确认'}
|
||||
{busy
|
||||
? '处理中…'
|
||||
: selectedStage === 'CONFIRMED'
|
||||
? '终审通过并推送'
|
||||
: '审核并推送确认'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@ -671,7 +675,7 @@ export function ClearanceReviewWorkbench({
|
||||
}
|
||||
onClick={() => void review('reject')}
|
||||
>
|
||||
批量退回
|
||||
{busy ? '处理中…' : '批量退回'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@ -11,6 +11,7 @@ import {
|
||||
type ClearanceFilterCondition,
|
||||
} from '@/lib/clearance-filters'
|
||||
import { clearanceFullGenerationBlockReason } from '@/lib/clearance-generation-guard'
|
||||
import { isClearanceDiscountBlockedPriority } from '@/lib/clearance-discount-restrictions'
|
||||
import { formatClearanceDailySales } from '@/lib/clearance-number-format'
|
||||
import styles from '../custom-table/limit-management.module.css'
|
||||
import ui from './clearance.module.css'
|
||||
@ -592,8 +593,8 @@ function isFixedTaskRow(row: { extra?: Record<string, unknown> }) {
|
||||
return Number.isFinite(fixedTaskQty) && fixedTaskQty > 0
|
||||
}
|
||||
|
||||
function isAFixedTaskRow(row: { extra?: Record<string, unknown> }) {
|
||||
return String(row.extra?.priority ?? '').trim() === 'A 固定任务'
|
||||
function isDiscountBlockedFixedTaskRow(row: { extra?: Record<string, unknown> }) {
|
||||
return isClearanceDiscountBlockedPriority(row.extra?.priority)
|
||||
}
|
||||
|
||||
function rowComboStatus(row: { extra?: Record<string, unknown> }) {
|
||||
@ -1428,7 +1429,7 @@ export function ClearanceView({
|
||||
const clearanceTotal = rowClearanceTotal(row)
|
||||
const fixedTask = isFixedTaskRow(row)
|
||||
const salesNoDiscount = rowSalesStatusDisallowsDiscount(row)
|
||||
const aFixedNoDiscount = isAFixedTaskRow(row)
|
||||
const aFixedNoDiscount = isDiscountBlockedFixedTaskRow(row)
|
||||
const discountDisabled = salesNoDiscount || aFixedNoDiscount || (!fixedTask && (
|
||||
row.discountRestricted
|
||||
|| row.discountChannelClosed
|
||||
@ -2112,7 +2113,7 @@ export function ClearanceView({
|
||||
if (column.kind === 'discount') {
|
||||
const fixedTask = isFixedTaskRow(row)
|
||||
const salesNoDiscount = rowSalesStatusDisallowsDiscount(row)
|
||||
const aFixedNoDiscount = isAFixedTaskRow(row)
|
||||
const aFixedNoDiscount = isDiscountBlockedFixedTaskRow(row)
|
||||
const discountDisabled = salesNoDiscount || aFixedNoDiscount || (!fixedTask && (
|
||||
row.discountRestricted
|
||||
|| row.discountChannelClosed
|
||||
@ -2123,7 +2124,7 @@ export function ClearanceView({
|
||||
? '同货号有销售,不可折扣'
|
||||
: '销售状态无需折扣'
|
||||
: aFixedNoDiscount
|
||||
? 'A 固定任务不可申请折扣'
|
||||
? '固定任务优先级不可申请折扣'
|
||||
: fixedTask
|
||||
? '如 5折,可留空'
|
||||
: row.dropshipOnlyStock
|
||||
@ -2138,7 +2139,7 @@ export function ClearanceView({
|
||||
? '同货号的其他商品编码为销售状态,本商品不允许申请折扣'
|
||||
: '销售状态商品不允许申请折扣'
|
||||
: aFixedNoDiscount
|
||||
? '优先级为“A 固定任务”的固定任务不允许申请折扣'
|
||||
? '优先级为“A 固定任务”或“A 固定任务-特殊入库”的固定任务不允许申请折扣'
|
||||
: fixedTask
|
||||
? undefined
|
||||
: row.dropshipOnlyStock
|
||||
@ -2171,7 +2172,7 @@ export function ClearanceView({
|
||||
}
|
||||
if (column.kind === 'reason') {
|
||||
const salesNoReason = rowSalesStatusDisallowsDiscount(row)
|
||||
const aFixedNoReason = isAFixedTaskRow(row)
|
||||
const aFixedNoReason = isDiscountBlockedFixedTaskRow(row)
|
||||
const reasonDisabled = salesNoReason || aFixedNoReason
|
||||
return (
|
||||
<input
|
||||
@ -2191,14 +2192,14 @@ export function ClearanceView({
|
||||
? row.skuFamilyHasSalesStatus
|
||||
? '同货号存在销售商品,不可填写原因'
|
||||
: aFixedNoReason
|
||||
? 'A 固定任务无需填写折扣原因'
|
||||
? '固定任务优先级无需填写折扣原因'
|
||||
: '销售状态无需原因'
|
||||
: '有折扣时必填原因'}
|
||||
title={reasonDisabled
|
||||
? row.skuFamilyHasSalesStatus
|
||||
? '同货号的其他商品编码为销售状态,本商品不允许填写折扣原因'
|
||||
: aFixedNoReason
|
||||
? '优先级为“A 固定任务”的固定任务不允许申请折扣'
|
||||
? '优先级为“A 固定任务”或“A 固定任务-特殊入库”的固定任务不允许申请折扣'
|
||||
: '销售状态商品不允许填写折扣原因'
|
||||
: undefined}
|
||||
aria-label={`${row.productName || row.barcode} 折扣原因`}
|
||||
|
||||
@ -1,9 +1,17 @@
|
||||
import {
|
||||
isClearanceDiscountBlockedPriority,
|
||||
matchingClearanceDiscountRestriction,
|
||||
normalizeClearanceDiscountRestrictions,
|
||||
} from './clearance-discount-restrictions'
|
||||
|
||||
describe('clearance discount restrictions', () => {
|
||||
it('blocks both A fixed-task priorities without blocking other fixed tasks', () => {
|
||||
expect(isClearanceDiscountBlockedPriority(' A 固定任务 ')).toBe(true)
|
||||
expect(isClearanceDiscountBlockedPriority('A 固定任务-特殊入库')).toBe(true)
|
||||
expect(isClearanceDiscountBlockedPriority('A 固定任务-其他')).toBe(false)
|
||||
expect(isClearanceDiscountBlockedPriority('普通清货')).toBe(false)
|
||||
})
|
||||
|
||||
it('converts legacy barcode and SPU restrictions into conditions', () => {
|
||||
expect(normalizeClearanceDiscountRestrictions([
|
||||
{ type: 'barcode', value: ' sku001 ' },
|
||||
|
||||
@ -10,6 +10,17 @@ export type ClearanceDiscountRestriction = {
|
||||
conditions: ClearancePriorityRuleCondition[]
|
||||
}
|
||||
|
||||
const CLEARANCE_DISCOUNT_BLOCKED_PRIORITIES = new Set([
|
||||
'A 固定任务',
|
||||
'A 固定任务-特殊入库',
|
||||
])
|
||||
|
||||
export function isClearanceDiscountBlockedPriority(...values: unknown[]) {
|
||||
return values.some((value) => (
|
||||
CLEARANCE_DISCOUNT_BLOCKED_PRIORITIES.has(String(value ?? '').trim())
|
||||
))
|
||||
}
|
||||
|
||||
export function normalizedRestrictionValue(value: unknown) {
|
||||
return String(value ?? '').trim().toUpperCase()
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import { supplyChainClearanceRepository } from '../supply-chain-clearance.reposi
|
||||
const mockTransaction = jest.fn()
|
||||
const mockTaskUpdate = jest.fn()
|
||||
const mockEventCreate = jest.fn()
|
||||
const mockEventCreateMany = jest.fn()
|
||||
const mockTaskFindMany = jest.fn()
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
@ -15,6 +16,7 @@ jest.mock('@/lib/prisma', () => ({
|
||||
},
|
||||
supplyChainClearanceTaskEvent: {
|
||||
create: (...args: unknown[]) => mockEventCreate(...args),
|
||||
createMany: (...args: unknown[]) => mockEventCreateMany(...args),
|
||||
},
|
||||
},
|
||||
}))
|
||||
@ -27,6 +29,7 @@ describe('clearance batch review writes', () => {
|
||||
data: Record<string, unknown>
|
||||
}) => ({ id: where.id, ...data }))
|
||||
mockEventCreate.mockResolvedValue({})
|
||||
mockEventCreateMany.mockResolvedValue({ count: 2 })
|
||||
mockTaskFindMany.mockResolvedValue([
|
||||
{ id: 'task-a', status: 'READY', events: [] },
|
||||
{ id: 'task-b', status: 'READY', events: [] },
|
||||
@ -61,9 +64,30 @@ describe('clearance batch review writes', () => {
|
||||
])
|
||||
|
||||
expect(mockTaskUpdate).toHaveBeenCalledTimes(2)
|
||||
expect(mockEventCreate).toHaveBeenCalledTimes(2)
|
||||
expect(mockEventCreate).not.toHaveBeenCalled()
|
||||
expect(mockEventCreateMany).toHaveBeenCalledTimes(1)
|
||||
expect(mockEventCreateMany.mock.calls[0][0].data).toHaveLength(2)
|
||||
expect(mockTransaction).toHaveBeenCalledTimes(1)
|
||||
expect(mockTransaction.mock.calls[0][0]).toHaveLength(4)
|
||||
expect(mockTransaction.mock.calls[0][0]).toHaveLength(3)
|
||||
expect(rows.map((row) => row.id)).toEqual(['task-a', 'task-b'])
|
||||
})
|
||||
|
||||
it('can commit update events without reading every task history back', async () => {
|
||||
const rows = await supplyChainClearanceRepository.writeTasksWithEvents([
|
||||
{
|
||||
id: 'task-a',
|
||||
update: { status: 'APPROVED', revision: 3 },
|
||||
event: {
|
||||
action: 'FINAL_APPROVE',
|
||||
actorId: 'reviewer-1',
|
||||
actorName: '审核人',
|
||||
note: '终审通过',
|
||||
},
|
||||
},
|
||||
], { returnRows: false })
|
||||
|
||||
expect(rows).toEqual([])
|
||||
expect(mockTransaction).toHaveBeenCalledTimes(1)
|
||||
expect(mockTaskFindMany).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@ -1666,31 +1666,35 @@ class SupplyChainClearanceRepository {
|
||||
})
|
||||
}
|
||||
|
||||
async writeTasksWithEvents(inputs: Array<
|
||||
| {
|
||||
create: Prisma.SupplyChainClearanceTaskUncheckedCreateInput
|
||||
event: {
|
||||
action: string
|
||||
actorId: string
|
||||
actorName: string
|
||||
note: string
|
||||
after?: Prisma.InputJsonValue
|
||||
async writeTasksWithEvents(
|
||||
inputs: Array<
|
||||
| {
|
||||
create: Prisma.SupplyChainClearanceTaskUncheckedCreateInput
|
||||
event: {
|
||||
action: string
|
||||
actorId: string
|
||||
actorName: string
|
||||
note: string
|
||||
after?: Prisma.InputJsonValue
|
||||
}
|
||||
}
|
||||
}
|
||||
| {
|
||||
id: string
|
||||
update: Prisma.SupplyChainClearanceTaskUncheckedUpdateInput
|
||||
event: {
|
||||
action: string
|
||||
actorId: string
|
||||
actorName: string
|
||||
note: string
|
||||
before?: Prisma.InputJsonValue
|
||||
after?: Prisma.InputJsonValue
|
||||
| {
|
||||
id: string
|
||||
update: Prisma.SupplyChainClearanceTaskUncheckedUpdateInput
|
||||
event: {
|
||||
action: string
|
||||
actorId: string
|
||||
actorName: string
|
||||
note: string
|
||||
before?: Prisma.InputJsonValue
|
||||
after?: Prisma.InputJsonValue
|
||||
}
|
||||
}
|
||||
}
|
||||
>) {
|
||||
>,
|
||||
options: { returnRows?: boolean } = {},
|
||||
) {
|
||||
if (!inputs.length) return []
|
||||
const shouldReturnRows = options.returnRows !== false
|
||||
const updateInputs = inputs.filter((input): input is Extract<
|
||||
(typeof inputs)[number],
|
||||
{ id: string }
|
||||
@ -1702,8 +1706,8 @@ class SupplyChainClearanceRepository {
|
||||
where: { id: input.id },
|
||||
data: input.update,
|
||||
})),
|
||||
...updateInputs.map((input) => prisma.supplyChainClearanceTaskEvent.create({
|
||||
data: {
|
||||
prisma.supplyChainClearanceTaskEvent.createMany({
|
||||
data: updateInputs.map((input) => ({
|
||||
taskId: input.id,
|
||||
action: input.event.action,
|
||||
actorId: input.event.actorId,
|
||||
@ -1711,9 +1715,10 @@ class SupplyChainClearanceRepository {
|
||||
note: input.event.note,
|
||||
before: input.event.before,
|
||||
after: input.event.after,
|
||||
},
|
||||
})),
|
||||
})),
|
||||
}),
|
||||
])
|
||||
if (!shouldReturnRows) return []
|
||||
const rows = await prisma.supplyChainClearanceTask.findMany({
|
||||
where: { id: { in: taskIds } },
|
||||
include: { events: { orderBy: { createdAt: 'asc' } } },
|
||||
@ -1748,6 +1753,7 @@ class SupplyChainClearanceRepository {
|
||||
}
|
||||
return ids
|
||||
}, { maxWait: 10_000, timeout: 120_000 })
|
||||
if (!shouldReturnRows) return []
|
||||
const rows = await prisma.supplyChainClearanceTask.findMany({
|
||||
where: { id: { in: taskIds } },
|
||||
include: { events: { orderBy: { createdAt: 'asc' } } },
|
||||
|
||||
@ -141,7 +141,25 @@ describe('SupplyChainClearanceTaskDirectImportService', () => {
|
||||
buffer: await workbookBuffer([
|
||||
['2026-11', 'SKU-A', 60, 100, '运营中心A', '运营A', '部门A', 'A 固定任务'],
|
||||
]),
|
||||
})).rejects.toThrow('优先级为“A 固定任务”,不允许申请折扣')
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”,不允许申请折扣')
|
||||
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a reviewer-imported discount for A fixed-task special inbound priority', async () => {
|
||||
const repo = repository()
|
||||
repo.listTasksForManualImport.mockResolvedValue([])
|
||||
const service = new SupplyChainClearanceTaskDirectImportService(
|
||||
repo as never,
|
||||
jest.fn(),
|
||||
)
|
||||
|
||||
await expect(service.importTasks({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await workbookBuffer([
|
||||
['2026-11', 'SKU-A', 60, 100, '运营中心A', '运营A', '部门A', 'A 固定任务-特殊入库'],
|
||||
]),
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”,不允许申请折扣')
|
||||
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@ -218,11 +218,11 @@ describe('SupplyChainClearanceTaskImportService', () => {
|
||||
buffer: await workbookBuffer([
|
||||
['SKU-A', '铁心兰', 20, '5折', '固定任务测试折扣'],
|
||||
]),
|
||||
})).rejects.toThrow('优先级为“A 固定任务”,不允许申请折扣')
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”,不允许申请折扣')
|
||||
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('allows discounts for fixed tasks whose priority only contains the A fixed-task text', async () => {
|
||||
it('rejects discounts for A fixed-task special inbound priority', async () => {
|
||||
const repo = repository()
|
||||
repo.listTasksForManualImport.mockResolvedValue([])
|
||||
repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue([
|
||||
@ -242,17 +242,8 @@ describe('SupplyChainClearanceTaskImportService', () => {
|
||||
buffer: await workbookBuffer([
|
||||
['SKU-A', '铁心兰', 20, '5折', '特殊入库清货折扣'],
|
||||
]),
|
||||
})).resolves.toMatchObject({
|
||||
importedCount: 1,
|
||||
createdCount: 1,
|
||||
})
|
||||
expect(repo.writeTasksWithEvents).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
discount: '0.50',
|
||||
}),
|
||||
}),
|
||||
])
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”')
|
||||
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports sales-status barcodes that try to apply a discount', async () => {
|
||||
|
||||
@ -564,6 +564,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
createdAt: new Date('2026-11-23T00:00:00.000Z'),
|
||||
} as never)
|
||||
repository.listLatestApprovedTaskDiscountsBefore.mockResolvedValue([])
|
||||
sourceRepository.listComboCatalog.mockResolvedValue({ combos: [], items: [] })
|
||||
repository.listClearanceSalesProgress.mockResolvedValue({
|
||||
hasCoverage: false,
|
||||
through: null,
|
||||
@ -2837,7 +2838,30 @@ describe('supply-chain-clearance workflow', () => {
|
||||
discount: 0.5,
|
||||
reason: 'A 固定任务折扣',
|
||||
user,
|
||||
})).rejects.toThrow('优先级为“A 固定任务”的固定任务不允许申请折扣')
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”的固定任务不允许申请折扣')
|
||||
expect(repository.createTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never allows a discount for A fixed-task special inbound priority', async () => {
|
||||
repository.findPoolItem.mockResolvedValue({
|
||||
...poolItem,
|
||||
productStatus: '退市',
|
||||
salesStatus: '退市',
|
||||
extra: {
|
||||
profitCenter: '运营中心A',
|
||||
fixedTaskQty: 10,
|
||||
priority: 'A 固定任务-特殊入库',
|
||||
clearanceTotal: 100,
|
||||
},
|
||||
} as never)
|
||||
|
||||
await expect(supplyChainClearanceService.submitTask({
|
||||
barcode: 'SKU001',
|
||||
taskQty: 10,
|
||||
discount: 0.5,
|
||||
reason: '特殊入库固定任务折扣',
|
||||
user,
|
||||
})).rejects.toThrow('优先级为“A 固定任务”或“A 固定任务-特殊入库”')
|
||||
expect(repository.createTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -4117,7 +4141,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
status: 'READY',
|
||||
submittedById: user.id,
|
||||
})
|
||||
repository.transitionTask.mockResolvedValue({
|
||||
repository.transitionTaskWithLatestEvent.mockResolvedValue({
|
||||
...pendingTask,
|
||||
status: 'CONFIRMED',
|
||||
submittedById: user.id,
|
||||
@ -4144,12 +4168,15 @@ describe('supply-chain-clearance workflow', () => {
|
||||
expect(result?.reviewDecisionLabel).toBe('已重新提交,待经管终审')
|
||||
expect(result?.reviewAdjustment?.summary).toBe('任务量 100→80;折扣 3折→5折')
|
||||
expect(repository.listClearanceSalesProgress).not.toHaveBeenCalled()
|
||||
expect(repository.transitionTask).toHaveBeenCalledWith(
|
||||
expect(repository.transitionTaskWithLatestEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ status: 'CONFIRMED' }),
|
||||
event: expect.objectContaining({ action: 'CONFIRM_RESUBMIT' }),
|
||||
}),
|
||||
)
|
||||
expect(repository.listPoolItemsForTaskPeriod).not.toHaveBeenCalled()
|
||||
expect(repository.findClearanceConfig).not.toHaveBeenCalled()
|
||||
expect(sourceRepository.listComboCatalog).not.toHaveBeenCalled()
|
||||
expect(mockSyncClearancePricePush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -4165,7 +4192,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
id: 'task-1',
|
||||
user,
|
||||
})).rejects.toThrow('只能确认清货负责人为本人的任务申请')
|
||||
expect(repository.transitionTask).not.toHaveBeenCalled()
|
||||
expect(repository.transitionTaskWithLatestEvent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets the clearance owner delete a task waiting for confirmation', async () => {
|
||||
@ -4240,17 +4267,20 @@ describe('supply-chain-clearance workflow', () => {
|
||||
ids: ['task-1'],
|
||||
stage: 'CONFIRMED',
|
||||
})
|
||||
expect(repository.writeTasksWithEvents).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
id: 'task-1',
|
||||
update: expect.objectContaining({
|
||||
taskQty: 60,
|
||||
discount: '0.60',
|
||||
status: 'CONFIRMED',
|
||||
expect(repository.writeTasksWithEvents).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({
|
||||
id: 'task-1',
|
||||
update: expect.objectContaining({
|
||||
taskQty: 60,
|
||||
discount: '0.60',
|
||||
status: 'CONFIRMED',
|
||||
}),
|
||||
event: expect.objectContaining({ action: 'OPERATOR_RESUBMIT' }),
|
||||
}),
|
||||
event: expect.objectContaining({ action: 'OPERATOR_RESUBMIT' }),
|
||||
}),
|
||||
])
|
||||
],
|
||||
{ returnRows: false },
|
||||
)
|
||||
expect(sourceRepository.listComboCatalog).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -6132,7 +6162,8 @@ describe('supply-chain-clearance workflow', () => {
|
||||
}),
|
||||
event: expect.objectContaining({ action: 'APPROVE' }),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
expect(sourceRepository.listComboCatalog).toHaveBeenCalledWith(['SKU-A', 'SKU-B'])
|
||||
expect(mockSyncClearancePricePush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -6171,7 +6202,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
after: expect.objectContaining({ status: 'READY' }),
|
||||
}),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
expect(mockNotifyClearanceTaskRejected).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -6221,7 +6252,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
after: expect.objectContaining({ taskQty: 80, discount: 0.5 }),
|
||||
}),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
})
|
||||
|
||||
it('moves operator-confirmed tasks through final approval and deletes rejected non-resubmissions', async () => {
|
||||
@ -6231,6 +6262,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
status: 'CONFIRMED',
|
||||
taskQty: 80,
|
||||
discount: 0.5 as never,
|
||||
costPrice: 100 as never,
|
||||
barcode: 'SKU-ADJUST',
|
||||
events: [{ action: 'APPROVE_ADJUST' }],
|
||||
}
|
||||
@ -6256,8 +6288,10 @@ describe('supply-chain-clearance workflow', () => {
|
||||
update: expect.objectContaining({ status: 'APPROVED' }),
|
||||
event: expect.objectContaining({ action: 'FINAL_APPROVE' }),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
expect(mockSyncClearancePricePush).toHaveBeenCalledWith('2026-10')
|
||||
expect(sourceRepository.listComboCatalog).not.toHaveBeenCalled()
|
||||
expect(repository.listLatestApprovedTaskDiscountsBefore).not.toHaveBeenCalled()
|
||||
|
||||
})
|
||||
|
||||
@ -6268,6 +6302,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
status: 'CONFIRMED',
|
||||
taskQty: 80,
|
||||
discount: 0.5 as never,
|
||||
costPrice: 100 as never,
|
||||
barcode: 'SKU-ADJUST',
|
||||
}
|
||||
repository.findTasksByIds.mockResolvedValue([confirmed] as never)
|
||||
@ -6301,8 +6336,9 @@ describe('supply-chain-clearance workflow', () => {
|
||||
after: expect.objectContaining({ taskQty: 70, discount: 0.4 }),
|
||||
}),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
expect(mockSyncClearancePricePush).toHaveBeenCalledWith('2026-10')
|
||||
expect(sourceRepository.listComboCatalog).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('allows fixed-task applications in batch review to bypass channel and discount restrictions', async () => {
|
||||
@ -6365,7 +6401,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
id: 'task-fixed',
|
||||
update: expect.objectContaining({ status: 'READY' }),
|
||||
}),
|
||||
])
|
||||
], { returnRows: false })
|
||||
})
|
||||
|
||||
it('keeps the confirmed task cost price when the current archive cost changes', async () => {
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
parseClearanceTaskDirectImport,
|
||||
type ClearanceTaskDirectImportRow,
|
||||
} from '@/lib/clearance-task-direct-import'
|
||||
import { isClearanceDiscountBlockedPriority } from '@/lib/clearance-discount-restrictions'
|
||||
import { isClearanceTaskProfitCenter } from '@/lib/clearance-profit-centers'
|
||||
import { supplyChainClearanceRepository } from '@/server/repositories/supply-chain-clearance.repository'
|
||||
import { syncClearancePricePushFromApprovedTasks } from './clearance-price-push-sync-hook'
|
||||
@ -220,10 +221,10 @@ export class SupplyChainClearanceTaskDirectImportService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (discount < 0.995 && effectivePriority.trim() === 'A 固定任务') {
|
||||
if (discount < 0.995 && isClearanceDiscountBlockedPriority(effectivePriority)) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
`第 ${row.rowNumber} 行优先级为“A 固定任务”,不允许申请折扣`,
|
||||
`第 ${row.rowNumber} 行优先级为“A 固定任务”或“A 固定任务-特殊入库”,不允许申请折扣`,
|
||||
)
|
||||
}
|
||||
const roundedDiscount = discount.toFixed(2)
|
||||
|
||||
@ -7,6 +7,7 @@ import {
|
||||
parseClearanceTaskManualImport,
|
||||
type ClearanceTaskManualImportRow,
|
||||
} from '@/lib/clearance-task-manual-import'
|
||||
import { isClearanceDiscountBlockedPriority } from '@/lib/clearance-discount-restrictions'
|
||||
import { supplyChainClearanceRepository } from '@/server/repositories/supply-chain-clearance.repository'
|
||||
|
||||
const PERIOD_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/
|
||||
@ -71,10 +72,6 @@ function salesDiscountError(item: {
|
||||
return ''
|
||||
}
|
||||
|
||||
function isAFixedTaskPriority(...values: unknown[]) {
|
||||
return values.some((value) => String(value ?? '').trim() === 'A 固定任务')
|
||||
}
|
||||
|
||||
function barcodeList(values: readonly string[]) {
|
||||
return Array.from(new Set(values)).slice(0, 30).join('、')
|
||||
}
|
||||
@ -124,7 +121,7 @@ export class SupplyChainClearanceTaskImportService {
|
||||
'折扣填写 1–10 折或留空;支持“五折”自动转换为“5折”,申请折扣时必须填写原因。',
|
||||
'清货负责人即任务运营负责人,与执行导入的账号无关。',
|
||||
'销售状态商品不允许申请折扣,系统会按清货商品编码和原因拒绝导入。',
|
||||
'优先级精确为“A 固定任务”的商品不允许申请折扣;其他固定任务仍可申请折扣。',
|
||||
'优先级为“A 固定任务”或“A 固定任务-特殊入库”的商品不允许申请折扣;其他固定任务仍可申请折扣。',
|
||||
'导入成功后直接进入批量审核的待审核状态,不会直接进入已确认任务。',
|
||||
'运营只能看到清货负责人等于本人账号的任务审核反馈。',
|
||||
'单次最多 5000 行、10MB,仅支持 .xlsx;清货商品编码按文本保存。',
|
||||
@ -328,13 +325,13 @@ export class SupplyChainClearanceTaskImportService {
|
||||
row.profitCenter,
|
||||
row.clearanceOwner,
|
||||
))
|
||||
if (!isAFixedTaskPriority(row.priority, existing?.priorityOverride)) return []
|
||||
if (!isClearanceDiscountBlockedPriority(row.priority, existing?.priorityOverride)) return []
|
||||
return [`${row.importCode}(${row.clearanceOwner})`]
|
||||
})
|
||||
if (fixedTaskDiscountErrors.length) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
`以下清货商品编码的优先级为“A 固定任务”,不允许申请折扣,请将折扣留空:${barcodeList(fixedTaskDiscountErrors)}`,
|
||||
`以下清货商品编码的优先级为“A 固定任务”或“A 固定任务-特殊入库”,不允许申请折扣,请将折扣留空:${barcodeList(fixedTaskDiscountErrors)}`,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@ -20,6 +20,7 @@ import {
|
||||
resolveClearancePriority,
|
||||
} from '@/lib/clearance-priority-rules'
|
||||
import {
|
||||
isClearanceDiscountBlockedPriority,
|
||||
matchingClearanceDiscountRestriction,
|
||||
normalizeClearanceDiscountRestrictions,
|
||||
} from '@/lib/clearance-discount-restrictions'
|
||||
@ -460,13 +461,11 @@ function isFixedClearanceTaskItem(row: { extra?: unknown }) {
|
||||
return integer(poolExtra(row).fixedTaskQty) > 0
|
||||
}
|
||||
|
||||
function isAFixedClearanceTaskItem(
|
||||
function isDiscountBlockedClearanceTaskItem(
|
||||
row: { extra?: unknown },
|
||||
priorityOverride?: string | null,
|
||||
) {
|
||||
return [priorityOverride, poolExtra(row).priority].some((value) => (
|
||||
String(value ?? '').trim() === 'A 固定任务'
|
||||
))
|
||||
return isClearanceDiscountBlockedPriority(priorityOverride, poolExtra(row).priority)
|
||||
}
|
||||
|
||||
const NONNEGATIVE_POOL_DISPLAY_EXTRA_KEYS = [
|
||||
@ -767,21 +766,23 @@ async function clearanceTaskCostPriceByBarcode(
|
||||
})
|
||||
if (!normalizedItems.length) return new Map<string, number>()
|
||||
|
||||
const clearanceCodeByBarcode = new Map(normalizedItems.map((item) => [
|
||||
item.barcode,
|
||||
String(poolExtra(item).clearanceCode ?? '').trim().toUpperCase() || item.barcode,
|
||||
]))
|
||||
let comboCatalog: Awaited<
|
||||
ReturnType<typeof supplyChainDiscontinuationSourceRepository.listComboCatalog>
|
||||
> = { combos: [], items: [] }
|
||||
try {
|
||||
comboCatalog = await supplyChainDiscontinuationSourceRepository.listComboCatalog()
|
||||
comboCatalog = await supplyChainDiscontinuationSourceRepository.listComboCatalog(
|
||||
Array.from(new Set(clearanceCodeByBarcode.values())),
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn('[clearance-task-cost] combo catalog unavailable', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
const comboIndex = buildClearanceComboIndex(comboCatalog)
|
||||
const clearanceCodeByBarcode = new Map(normalizedItems.map((item) => [
|
||||
item.barcode,
|
||||
String(poolExtra(item).clearanceCode ?? '').trim().toUpperCase() || item.barcode,
|
||||
]))
|
||||
const componentCodes = new Set<string>()
|
||||
for (const clearanceCode of clearanceCodeByBarcode.values()) {
|
||||
for (const componentCode of collectComboComponents(clearanceCode, comboIndex)) {
|
||||
@ -1215,10 +1216,10 @@ function assertFixedPriorityDiscountAllowed(
|
||||
discount: number,
|
||||
priorityOverride?: string | null,
|
||||
) {
|
||||
if (discount < 0.995 && isAFixedClearanceTaskItem(row, priorityOverride)) {
|
||||
if (discount < 0.995 && isDiscountBlockedClearanceTaskItem(row, priorityOverride)) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
'优先级为“A 固定任务”的固定任务不允许申请折扣,请将折扣留空',
|
||||
'优先级为“A 固定任务”或“A 固定任务-特殊入库”的固定任务不允许申请折扣,请将折扣留空',
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -4192,10 +4193,12 @@ class SupplyChainClearanceService {
|
||||
Array.from(new Set(tasks.map((task) => task.barcode))),
|
||||
),
|
||||
supplyChainClearanceRepository.findClearanceConfig(),
|
||||
supplyChainClearanceRepository.listLatestApprovedTaskDiscountsBefore({
|
||||
periodKey: periods[0],
|
||||
barcodes: Array.from(new Set(tasks.map((task) => task.barcode))),
|
||||
}),
|
||||
tasks.some((task) => !task.auditScoredAt)
|
||||
? supplyChainClearanceRepository.listLatestApprovedTaskDiscountsBefore({
|
||||
periodKey: periods[0],
|
||||
barcodes: Array.from(new Set(tasks.map((task) => task.barcode))),
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
])
|
||||
poolByBarcode = new Map(
|
||||
poolItems.map((item) => [item.barcode.trim().toUpperCase(), item]),
|
||||
@ -4261,8 +4264,21 @@ class SupplyChainClearanceService {
|
||||
}
|
||||
}
|
||||
}
|
||||
const approvedCostPriceByBarcode = input.action === 'approve'
|
||||
? await clearanceTaskCostPriceByBarcode(Array.from(poolByBarcode.values()))
|
||||
const missingCostPoolItems = input.action === 'approve'
|
||||
? Array.from(new Map(
|
||||
tasks
|
||||
.filter((task) => {
|
||||
const costPrice = number(task.costPrice)
|
||||
return costPrice == null || costPrice <= 0
|
||||
})
|
||||
.flatMap((task) => {
|
||||
const poolItem = poolByBarcode.get(task.barcode.trim().toUpperCase())
|
||||
return poolItem ? [[poolItem.barcode.trim().toUpperCase(), poolItem] as const] : []
|
||||
}),
|
||||
).values())
|
||||
: []
|
||||
const approvedCostPriceByBarcode = missingCostPoolItems.length
|
||||
? await clearanceTaskCostPriceByBarcode(missingCostPoolItems)
|
||||
: new Map<string, number>()
|
||||
const reviewedAt = new Date()
|
||||
await supplyChainClearanceRepository.writeTasksWithEvents(
|
||||
@ -4336,6 +4352,7 @@ class SupplyChainClearanceService {
|
||||
},
|
||||
}
|
||||
}),
|
||||
{ returnRows: false },
|
||||
)
|
||||
if (input.action === 'approve' && tasks.every((task) => task.status === 'CONFIRMED')) {
|
||||
void Promise.resolve(syncClearancePricePushFromApprovedTasks(periods[0])).catch((error) => {
|
||||
@ -5181,49 +5198,10 @@ class SupplyChainClearanceService {
|
||||
if (!['READY', 'REJECTED'].includes(task.status)) {
|
||||
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '只有待运营确认的任务可以确认')
|
||||
}
|
||||
const [clearanceConfig, poolItems] = await Promise.all([
|
||||
supplyChainClearanceRepository.findClearanceConfig(),
|
||||
supplyChainClearanceRepository.listPoolItemsForTaskPeriod(task.periodKey, [task.barcode]),
|
||||
])
|
||||
const poolItem = poolItems[0]
|
||||
const fixedTask = poolItem ? isFixedClearanceTaskItem(poolItem) : false
|
||||
const discount = number(task.discount) ?? 0
|
||||
assertSalesStatusDiscountAllowed(
|
||||
effectiveClearanceSalesStatus(
|
||||
poolItem?.salesStatus,
|
||||
poolItem?.productStatus,
|
||||
task.productStatus,
|
||||
),
|
||||
discount,
|
||||
poolItem?.skuFamilyHasSalesStatus,
|
||||
)
|
||||
if (poolItem) {
|
||||
assertFixedPriorityDiscountAllowed(poolItem, discount, task.priorityOverride)
|
||||
}
|
||||
assertTaskReasonAllowed(
|
||||
effectiveClearanceSalesStatus(
|
||||
poolItem?.salesStatus,
|
||||
poolItem?.productStatus,
|
||||
task.productStatus,
|
||||
),
|
||||
discount,
|
||||
task.reason,
|
||||
poolItem?.skuFamilyHasSalesStatus,
|
||||
)
|
||||
assertDiscountRestrictionAllowed(
|
||||
poolItem ?? { barcode: task.barcode },
|
||||
normalizeClearanceDiscountRestrictions(clearanceConfig?.discountRestrictions),
|
||||
discount,
|
||||
fixedTask,
|
||||
)
|
||||
const costPrice = (await clearanceTaskCostPriceByBarcode(poolItems)).get(task.barcode.trim().toUpperCase())
|
||||
?? number(task.costPrice)
|
||||
?? null
|
||||
const updated = await supplyChainClearanceRepository.transitionTask({
|
||||
const updated = await supplyChainClearanceRepository.transitionTaskWithLatestEvent({
|
||||
id: task.id,
|
||||
data: {
|
||||
status: 'CONFIRMED',
|
||||
costPrice,
|
||||
revision: task.revision + 1,
|
||||
},
|
||||
event: {
|
||||
@ -5235,7 +5213,10 @@ class SupplyChainClearanceService {
|
||||
after: { status: 'CONFIRMED' },
|
||||
},
|
||||
})
|
||||
return taskDto(updated)
|
||||
return taskDto({
|
||||
...updated,
|
||||
events: [...task.events, ...updated.events],
|
||||
})
|
||||
}
|
||||
|
||||
async cancelReviewedTask(input: { id: string; user: AuthUser }) {
|
||||
@ -5350,7 +5331,7 @@ class SupplyChainClearanceService {
|
||||
)))
|
||||
: new Map<string, number>()
|
||||
const updatedAt = new Date()
|
||||
const updated = await supplyChainClearanceRepository.writeTasksWithEvents(
|
||||
await supplyChainClearanceRepository.writeTasksWithEvents(
|
||||
tasks.map((task) => {
|
||||
const item = itemById.get(task.id)!
|
||||
const costPrice = costPrices.get(task.barcode.trim().toUpperCase())
|
||||
@ -5388,10 +5369,11 @@ class SupplyChainClearanceService {
|
||||
},
|
||||
}
|
||||
}),
|
||||
{ returnRows: false },
|
||||
)
|
||||
return {
|
||||
count: updated.length,
|
||||
ids: updated.map((task) => task.id),
|
||||
count: tasks.length,
|
||||
ids: tasks.map((task) => task.id),
|
||||
stage: 'CONFIRMED' as const,
|
||||
reviewedAt: updatedAt.toISOString(),
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user