fix(clearance): 保留真实发货量并补齐任务池字段
This commit is contained in:
parent
cf4533644b
commit
2fa5de6faa
@ -13,6 +13,18 @@ describe('clearance task execution metrics', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('never clears the actual shipment quantity when the task target is zero', () => {
|
||||
expect(calculateClearanceTaskExecutionMetrics({
|
||||
taskQty: 0,
|
||||
shipQty: 3,
|
||||
totalStock: 0,
|
||||
})).toEqual({
|
||||
realTaskQty: 0,
|
||||
shipQty: 3,
|
||||
clearanceProgress: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('marks the task complete when there is no remaining total stock', () => {
|
||||
expect(calculateClearanceTaskExecutionMetrics({
|
||||
taskQty: 50,
|
||||
@ -20,7 +32,7 @@ describe('clearance task execution metrics', () => {
|
||||
totalStock: 0,
|
||||
})).toEqual({
|
||||
realTaskQty: 50,
|
||||
shipQty: 50,
|
||||
shipQty: 18,
|
||||
clearanceProgress: 100,
|
||||
})
|
||||
})
|
||||
@ -56,7 +68,7 @@ describe('clearance task execution metrics', () => {
|
||||
totalStock: -5,
|
||||
})).toEqual({
|
||||
realTaskQty: 10,
|
||||
shipQty: 10,
|
||||
shipQty: 4,
|
||||
clearanceProgress: 100,
|
||||
})
|
||||
})
|
||||
|
||||
@ -22,7 +22,7 @@ export function calculateClearanceTaskExecutionMetrics(input: {
|
||||
)
|
||||
|
||||
if (taskQty === 0) {
|
||||
return { realTaskQty: 0, shipQty: 0, clearanceProgress: 0 }
|
||||
return { realTaskQty: 0, shipQty: actualShipQty, clearanceProgress: 0 }
|
||||
}
|
||||
|
||||
if (input.preserveTaskQty) {
|
||||
@ -44,7 +44,7 @@ export function calculateClearanceTaskExecutionMetrics(input: {
|
||||
if (totalStock === 0) {
|
||||
return {
|
||||
realTaskQty: taskQty,
|
||||
shipQty: taskQty,
|
||||
shipQty: actualShipQty,
|
||||
clearanceProgress: 100,
|
||||
}
|
||||
}
|
||||
|
||||
@ -49,6 +49,19 @@ export type ClearanceOutboundProfitCenterSalesProfile = {
|
||||
through: string | null
|
||||
}
|
||||
|
||||
export type ClearancePoolTaskMetadataProfile = {
|
||||
barcode: string
|
||||
clearanceBatch: string
|
||||
priority: string
|
||||
}
|
||||
|
||||
type ClearancePoolTaskMetadataSourceRow = {
|
||||
skuoid: string
|
||||
clearSkuoid: string
|
||||
clearanceBatch: string
|
||||
priority: string
|
||||
}
|
||||
|
||||
export type DiscontinuationLiveProductStatus = {
|
||||
barcode: string
|
||||
productStatus: string
|
||||
@ -146,6 +159,10 @@ function booleanFlag(value: unknown) {
|
||||
|
||||
class SupplyChainDiscontinuationSourceRepository {
|
||||
private pool: sql.ConnectionPool | null = null
|
||||
private clearancePoolTaskMetadataCache = new Map<string, {
|
||||
expiresAt: number
|
||||
rows: ClearancePoolTaskMetadataSourceRow[]
|
||||
}>()
|
||||
|
||||
private async getPool() {
|
||||
if (this.pool?.connected) return this.pool
|
||||
@ -640,9 +657,73 @@ class SupplyChainDiscontinuationSourceRepository {
|
||||
}
|
||||
|
||||
/**
|
||||
* 清货发货数量按任务利润中心归集:
|
||||
* 出库店铺 shop_id 对应 op_ShopConfig_view.code,
|
||||
* 再以视图 Department 作为利润中心匹配任务。
|
||||
* 清货任务缺失本地月度快照时,从人工清货池源表补齐批次和优先级。
|
||||
*/
|
||||
async listClearancePoolTaskMetadataByBarcodes(input: {
|
||||
periodKey: string
|
||||
barcodes: readonly string[]
|
||||
}): Promise<ClearancePoolTaskMetadataProfile[]> {
|
||||
const barcodes = Array.from(new Set(
|
||||
input.barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean),
|
||||
))
|
||||
if (!barcodes.length) return []
|
||||
|
||||
const periodKey = input.periodKey.trim()
|
||||
const cacheKey = periodKey
|
||||
const cached = this.clearancePoolTaskMetadataCache.get(cacheKey)
|
||||
let rows: ClearancePoolTaskMetadataSourceRow[]
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
rows = cached.rows
|
||||
} else {
|
||||
const pool = await this.getPool()
|
||||
const result = await pool.request()
|
||||
.input('periodKey', sql.NVarChar(20), periodKey)
|
||||
.query<ClearancePoolTaskMetadataSourceRow>(`
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(CAST(ISNULL(skuoid, '') AS nvarchar(200))))) AS skuoid,
|
||||
UPPER(LTRIM(RTRIM(CAST(ISNULL(clear_skuoid, '') AS nvarchar(200))))) AS clearSkuoid,
|
||||
LTRIM(RTRIM(CAST(ISNULL(clear_period, '') AS nvarchar(200)))) AS clearanceBatch,
|
||||
LTRIM(RTRIM(CAST(ISNULL(priority, '') AS nvarchar(200)))) AS priority
|
||||
FROM rpt.ope_clear_pool WITH (NOLOCK)
|
||||
WHERE LTRIM(RTRIM(CAST(ISNULL(stat_month, '') AS nvarchar(20)))) = @periodKey
|
||||
`)
|
||||
rows = result.recordset
|
||||
this.clearancePoolTaskMetadataCache.set(cacheKey, {
|
||||
expiresAt: Date.now() + 60_000,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
|
||||
const requested = new Set(barcodes)
|
||||
const exactByBarcode = new Map<string, ClearancePoolTaskMetadataSourceRow>()
|
||||
const clearanceCodeByBarcode = new Map<string, ClearancePoolTaskMetadataSourceRow>()
|
||||
for (const row of rows) {
|
||||
if (row.skuoid && requested.has(row.skuoid) && !exactByBarcode.has(row.skuoid)) {
|
||||
exactByBarcode.set(row.skuoid, row)
|
||||
}
|
||||
if (
|
||||
row.clearSkuoid
|
||||
&& requested.has(row.clearSkuoid)
|
||||
&& !clearanceCodeByBarcode.has(row.clearSkuoid)
|
||||
) {
|
||||
clearanceCodeByBarcode.set(row.clearSkuoid, row)
|
||||
}
|
||||
}
|
||||
return barcodes.flatMap((barcode) => {
|
||||
const row = exactByBarcode.get(barcode) ?? clearanceCodeByBarcode.get(barcode)
|
||||
return row
|
||||
? [{
|
||||
barcode,
|
||||
clearanceBatch: row.clearanceBatch,
|
||||
priority: row.priority,
|
||||
}]
|
||||
: []
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清货发货数量按任务利润中心归集。
|
||||
* 销售全量表已统一承载各渠道实际发货,并提供利润中心和店铺维度。
|
||||
*/
|
||||
async listClearanceOutboundSalesByProfitCenter(input: {
|
||||
periodKey: string
|
||||
@ -661,102 +742,40 @@ class SupplyChainDiscontinuationSourceRepository {
|
||||
const pool = await this.getPool()
|
||||
const totals = new Map<string, ClearanceOutboundProfitCenterSalesProfile>()
|
||||
|
||||
if (subjects.length <= 100) {
|
||||
for (const subject of subjects) {
|
||||
const result = await pool.request()
|
||||
.input('barcode', sql.NVarChar(200), subject.barcode)
|
||||
.input('profitCenter', sql.NVarChar(200), subject.profitCenter)
|
||||
.input('startDate', sql.Date, start)
|
||||
.input('endDate', sql.Date, end)
|
||||
.query<ClearanceOutboundProfitCenterSalesProfile>(`
|
||||
SELECT
|
||||
@barcode AS barcode,
|
||||
@profitCenter AS profitCenter,
|
||||
SUM(CAST(ISNULL(item.qty, 0) AS int)) AS qty,
|
||||
CONVERT(varchar(10), MAX(outbound.io_date), 23) AS through
|
||||
FROM rpt.jst_salesOutboundInfo outbound WITH (NOLOCK)
|
||||
INNER JOIN (
|
||||
SELECT code
|
||||
FROM rpt.op_ShopConfig_view WITH (NOLOCK)
|
||||
WHERE LTRIM(RTRIM(Department)) = @profitCenter
|
||||
GROUP BY code
|
||||
) shop
|
||||
ON shop.code = outbound.shop_id
|
||||
INNER JOIN rpt.jst_OrderItem item WITH (NOLOCK)
|
||||
ON item.o_id = outbound.o_id
|
||||
AND UPPER(LTRIM(RTRIM(CAST(item.sku_id AS nvarchar(200))))) = @barcode
|
||||
WHERE outbound.io_date >= @startDate
|
||||
AND outbound.io_date < @endDate
|
||||
AND outbound.status = N'Confirmed'
|
||||
OPTION (RECOMPILE)
|
||||
`)
|
||||
const row = result.recordset[0]
|
||||
if (!row || !Number(row.qty)) continue
|
||||
totals.set(`${row.barcode}\u0000${row.profitCenter}`, {
|
||||
barcode: row.barcode.trim().toUpperCase(),
|
||||
profitCenter: row.profitCenter.trim(),
|
||||
qty: Math.max(0, Math.trunc(Number(row.qty ?? 0))),
|
||||
through: row.through ?? null,
|
||||
})
|
||||
}
|
||||
return Array.from(totals.values())
|
||||
}
|
||||
|
||||
const subjectsByProfitCenter = new Map<string, string[]>()
|
||||
for (const subject of subjects) {
|
||||
const barcodes = subjectsByProfitCenter.get(subject.profitCenter) ?? []
|
||||
barcodes.push(subject.barcode)
|
||||
subjectsByProfitCenter.set(subject.profitCenter, barcodes)
|
||||
}
|
||||
const groups = Array.from(subjectsByProfitCenter, ([profitCenter, barcodes]) => ({
|
||||
profitCenter,
|
||||
barcodes: Array.from(new Set(barcodes)),
|
||||
}))
|
||||
|
||||
for (let groupOffset = 0; groupOffset < groups.length; groupOffset += 4) {
|
||||
const groupBatch = groups.slice(groupOffset, groupOffset + 4)
|
||||
const groupResults = await Promise.all(groupBatch.map(async ({ profitCenter, barcodes }) => {
|
||||
const groupRows: ClearanceOutboundProfitCenterSalesProfile[] = []
|
||||
for (let offset = 0; offset < barcodes.length; offset += 1_000) {
|
||||
const result = await pool.request()
|
||||
.input('barcodes', sql.NVarChar(sql.MAX), JSON.stringify(barcodes.slice(offset, offset + 1_000)))
|
||||
.input('profitCenter', sql.NVarChar(200), profitCenter)
|
||||
.input('startDate', sql.Date, start)
|
||||
.input('endDate', sql.Date, end)
|
||||
.query<ClearanceOutboundProfitCenterSalesProfile>(`
|
||||
WITH input_codes AS (
|
||||
SELECT UPPER(LTRIM(RTRIM([value]))) AS barcode
|
||||
FROM OPENJSON(@barcodes)
|
||||
)
|
||||
SELECT
|
||||
input.barcode,
|
||||
@profitCenter AS profitCenter,
|
||||
SUM(CAST(ISNULL(item.qty, 0) AS int)) AS qty,
|
||||
CONVERT(varchar(10), MAX(outbound.io_date), 23) AS through
|
||||
FROM rpt.jst_salesOutboundInfo outbound WITH (NOLOCK)
|
||||
INNER JOIN (
|
||||
SELECT code
|
||||
FROM rpt.op_ShopConfig_view WITH (NOLOCK)
|
||||
WHERE LTRIM(RTRIM(Department)) = @profitCenter
|
||||
GROUP BY code
|
||||
) shop
|
||||
ON shop.code = outbound.shop_id
|
||||
INNER JOIN input_codes input
|
||||
ON 1 = 1
|
||||
INNER JOIN rpt.jst_OrderItem item WITH (NOLOCK)
|
||||
ON item.o_id = outbound.o_id
|
||||
AND input.barcode = UPPER(LTRIM(RTRIM(CAST(item.sku_id AS nvarchar(200)))))
|
||||
WHERE outbound.io_date >= @startDate
|
||||
AND outbound.io_date < @endDate
|
||||
AND outbound.status = N'Confirmed'
|
||||
GROUP BY input.barcode
|
||||
OPTION (RECOMPILE)
|
||||
`)
|
||||
groupRows.push(...result.recordset)
|
||||
}
|
||||
return groupRows
|
||||
}))
|
||||
for (const row of groupResults.flat()) {
|
||||
for (let offset = 0; offset < subjects.length; offset += 1_500) {
|
||||
const result = await pool.request()
|
||||
.input('subjects', sql.NVarChar(sql.MAX), JSON.stringify(
|
||||
subjects.slice(offset, offset + 1_500),
|
||||
))
|
||||
.input('startDate', sql.Date, start)
|
||||
.input('endDate', sql.Date, end)
|
||||
.query<ClearanceOutboundProfitCenterSalesProfile>(`
|
||||
WITH input_subjects AS (
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(barcode))) AS barcode,
|
||||
LTRIM(RTRIM(profitCenter)) AS profitCenter
|
||||
FROM OPENJSON(@subjects)
|
||||
WITH (
|
||||
barcode nvarchar(200) '$.barcode',
|
||||
profitCenter nvarchar(200) '$.profitCenter'
|
||||
)
|
||||
)
|
||||
SELECT
|
||||
subjects_input.barcode,
|
||||
subjects_input.profitCenter,
|
||||
SUM(CAST(ISNULL(sales.goods_count, 0) AS bigint)) AS qty,
|
||||
CONVERT(varchar(10), MAX(sales.stat_date), 23) AS through
|
||||
FROM input_subjects subjects_input
|
||||
INNER JOIN rpt.dws_sn_sales_full_info_di sales WITH (NOLOCK)
|
||||
ON UPPER(LTRIM(RTRIM(CAST(sales.skuoid AS nvarchar(200))))) = subjects_input.barcode
|
||||
AND LTRIM(RTRIM(CAST(sales.profit_center AS nvarchar(200)))) = subjects_input.profitCenter
|
||||
WHERE sales.stat_date >= @startDate
|
||||
AND sales.stat_date < @endDate
|
||||
GROUP BY subjects_input.barcode, subjects_input.profitCenter
|
||||
HAVING SUM(CAST(ISNULL(sales.goods_count, 0) AS bigint)) <> 0
|
||||
OPTION (RECOMPILE)
|
||||
`)
|
||||
for (const row of result.recordset) {
|
||||
totals.set(`${row.barcode}\u0000${row.profitCenter}`, {
|
||||
barcode: row.barcode.trim().toUpperCase(),
|
||||
profitCenter: row.profitCenter.trim(),
|
||||
|
||||
@ -88,6 +88,7 @@ jest.mock('@/server/repositories/supply-chain-discontinuation-source.repository'
|
||||
listLiveProductStatusesByBarcodes: jest.fn(),
|
||||
listLatestDiscontinuationDatesByBarcodes: jest.fn(),
|
||||
listLatestPurchaseInboundDatesByBarcodes: jest.fn(),
|
||||
listClearancePoolTaskMetadataByBarcodes: jest.fn(),
|
||||
listClearanceOutboundSalesByProfitCenter: jest.fn(),
|
||||
},
|
||||
}))
|
||||
@ -371,6 +372,7 @@ describe('supply-chain-clearance workflow', () => {
|
||||
sourceRepository.listLiveProductStatusesByBarcodes.mockResolvedValue([])
|
||||
sourceRepository.listLatestDiscontinuationDatesByBarcodes.mockResolvedValue([])
|
||||
sourceRepository.listLatestPurchaseInboundDatesByBarcodes.mockResolvedValue([])
|
||||
sourceRepository.listClearancePoolTaskMetadataByBarcodes.mockResolvedValue([])
|
||||
sourceRepository.listClearanceOutboundSalesByProfitCenter.mockResolvedValue([])
|
||||
mockCalculateRegionFreightsForArchiveRows.mockResolvedValue(new Map())
|
||||
mockNotifyClearanceComboMarks.mockResolvedValue({
|
||||
@ -2780,6 +2782,53 @@ describe('supply-chain-clearance workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps actual shipments and maps missing task metadata from the monthly clearance pool', async () => {
|
||||
repository.listTasks.mockResolvedValue([{
|
||||
...pendingTask,
|
||||
periodKey: '2026-11',
|
||||
status: 'APPROVED',
|
||||
profitCenter: '运营中心A',
|
||||
taskQty: 20,
|
||||
clearedQty: 0,
|
||||
}] as never)
|
||||
repository.listPoolItemsForTaskPeriod.mockResolvedValue([])
|
||||
repository.listClearanceSalesProgress.mockResolvedValue({
|
||||
hasCoverage: false,
|
||||
through: null,
|
||||
byBarcode: new Map(),
|
||||
returnQtyByBarcode: new Map(),
|
||||
})
|
||||
sourceRepository.listClearanceOutboundSalesByProfitCenter.mockResolvedValue([{
|
||||
barcode: 'SKU001',
|
||||
profitCenter: '运营中心A',
|
||||
qty: 1,
|
||||
through: '2026-11-01',
|
||||
}])
|
||||
sourceRepository.listClearancePoolTaskMetadataByBarcodes.mockResolvedValue([{
|
||||
barcode: 'SKU001',
|
||||
clearanceBatch: '第55批',
|
||||
priority: 'D 清货款工厂无库存',
|
||||
}])
|
||||
|
||||
const result = await supplyChainClearanceService.getTasks('2026-11', {
|
||||
includeFreight: false,
|
||||
})
|
||||
|
||||
expect(result.tasks[0]).toMatchObject({
|
||||
taskQty: 20,
|
||||
realTaskQty: 20,
|
||||
shipQty: 1,
|
||||
clearanceProgress: 100,
|
||||
totalStock: 0,
|
||||
clearanceBatch: '第55批',
|
||||
priority: 'D 清货款工厂无库存',
|
||||
})
|
||||
expect(sourceRepository.listClearancePoolTaskMetadataByBarcodes).toHaveBeenCalledWith({
|
||||
periodKey: '2026-11',
|
||||
barcodes: ['SKU001'],
|
||||
})
|
||||
})
|
||||
|
||||
it('lists only approved tasks after the manager has pushed them', async () => {
|
||||
repository.listTasks.mockResolvedValue([
|
||||
{ ...pendingTask, id: 'task-pending', status: 'PENDING' },
|
||||
|
||||
@ -1751,6 +1751,42 @@ class SupplyChainClearanceService {
|
||||
const poolByBarcode = new Map(
|
||||
poolItems.map((item) => [item.barcode.trim().toUpperCase(), item]),
|
||||
)
|
||||
const missingTaskMetadataBarcodes = Array.from(new Set(
|
||||
tasks.flatMap((task) => {
|
||||
const barcode = task.barcode.trim().toUpperCase()
|
||||
const poolItem = poolByBarcode.get(barcode)
|
||||
const extra = poolItem?.extra && typeof poolItem.extra === 'object' && !Array.isArray(poolItem.extra)
|
||||
? poolItem.extra as Record<string, unknown>
|
||||
: {}
|
||||
const clearanceBatch = String(extra.clearanceBatch ?? '').trim()
|
||||
const priority = String(extra.priority ?? '').trim()
|
||||
return barcode && (!clearanceBatch || !priority) ? [barcode] : []
|
||||
}),
|
||||
))
|
||||
const taskMetadataByBarcode = new Map<string, {
|
||||
clearanceBatch: string
|
||||
priority: string
|
||||
}>()
|
||||
if (missingTaskMetadataBarcodes.length) {
|
||||
try {
|
||||
const rows = await supplyChainDiscontinuationSourceRepository
|
||||
.listClearancePoolTaskMetadataByBarcodes({
|
||||
periodKey,
|
||||
barcodes: missingTaskMetadataBarcodes,
|
||||
})
|
||||
for (const row of rows ?? []) {
|
||||
taskMetadataByBarcode.set(row.barcode.trim().toUpperCase(), {
|
||||
clearanceBatch: row.clearanceBatch.trim(),
|
||||
priority: row.priority.trim(),
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[clearance-tasks] monthly pool metadata query failed', {
|
||||
periodKey,
|
||||
error,
|
||||
})
|
||||
}
|
||||
}
|
||||
const clearanceCodeByBarcode = new Map<string, string>()
|
||||
for (const [barcode, item] of poolByBarcode) {
|
||||
const extra = item.extra && typeof item.extra === 'object' && !Array.isArray(item.extra)
|
||||
@ -1872,6 +1908,7 @@ class SupplyChainClearanceService {
|
||||
const dailySales = (
|
||||
archiveItem ? calculateClearanceDailySales(archiveItem) : null
|
||||
) ?? number(poolItem?.dailySales)
|
||||
const taskMetadata = taskMetadataByBarcode.get(barcode)
|
||||
return {
|
||||
...taskWithProgress,
|
||||
image: '',
|
||||
@ -1900,8 +1937,12 @@ class SupplyChainClearanceService {
|
||||
dailySales,
|
||||
availableDays: availableDaysText(totalStock, dailySales),
|
||||
nationwideFreight: number(freightByBarcode.get(barcode)?.freightNationwide),
|
||||
clearanceBatch: String(extra.clearanceBatch ?? ''),
|
||||
priority: String(extra.priority ?? ''),
|
||||
clearanceBatch: String(extra.clearanceBatch ?? '').trim()
|
||||
|| taskMetadata?.clearanceBatch
|
||||
|| '',
|
||||
priority: String(extra.priority ?? '').trim()
|
||||
|| taskMetadata?.priority
|
||||
|| '',
|
||||
actualShipQty: taskWithProgress.clearedQty,
|
||||
componentCost,
|
||||
componentClearancePrice,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user