fix(intake): complete inventory tasks when either flow succeeds
Check current SKU barcode success before enqueueing, sending inventory requests, retrying, and recording failure alerts. Keep genuine unresolved failures visible.
This commit is contained in:
parent
6a61f37518
commit
f79dfd05a9
@ -367,7 +367,7 @@ describe('POST /api/intake/non-integrated/jushuitan-virtual-inventory-push', ()
|
||||
expect(mockProcessFixedDue).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the fixed-inventory queue on the authenticated cron path', async () => {
|
||||
it('keeps the warehouse cron separate from the fixed-inventory cron', async () => {
|
||||
process.env.JST_VIRTUAL_INVENTORY_CRON_SECRET = 'cron-secret'
|
||||
mockHandleRequest.mockImplementation(
|
||||
async (_request: NextRequest, handler: (ctx: unknown) => unknown) =>
|
||||
@ -377,9 +377,7 @@ describe('POST /api/intake/non-integrated/jushuitan-virtual-inventory-push', ()
|
||||
|
||||
await POST(createCronRequest())
|
||||
|
||||
expect(mockProcessFixedDue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ source: 'SYSTEM' }),
|
||||
)
|
||||
expect(mockProcessFixedDue).not.toHaveBeenCalled()
|
||||
delete process.env.JST_VIRTUAL_INVENTORY_CRON_SECRET
|
||||
})
|
||||
})
|
||||
|
||||
@ -0,0 +1,66 @@
|
||||
/** @jest-environment node */
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: {
|
||||
intakeNonIntegratedSkuItem: { findMany: jest.fn() },
|
||||
intakeNonIntegratedPricingRow: { findMany: jest.fn(), updateMany: jest.fn() },
|
||||
intakeJushuitanFixedVirtualInventoryTask: { findMany: jest.fn(), updateMany: jest.fn() },
|
||||
$transaction: jest.fn(async (queries) => Promise.all(queries)),
|
||||
} }))
|
||||
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { JST_VIRTUAL_INVENTORY_IN_FLIGHT_ERROR } from '@/app/intake/non-integrated/nonIntegratedStorage'
|
||||
import { JushuitanInventoryCompletionRepository } from './jushuitan-inventory-completion.repository'
|
||||
|
||||
describe('inventory completion persistence boundaries', () => {
|
||||
beforeEach(() => jest.clearAllMocks())
|
||||
|
||||
it('only accepts success for the exact product, SKU and barcode in an active product', async () => {
|
||||
const target = { productId: 'p-1', skuItemId: 's-1', barcode: 'current-barcode' }
|
||||
jest.mocked(prisma.intakeNonIntegratedSkuItem.findMany).mockResolvedValue([target] as never)
|
||||
jest.mocked(prisma.intakeNonIntegratedPricingRow.findMany).mockResolvedValue([target] as never)
|
||||
jest.mocked(prisma.intakeJushuitanFixedVirtualInventoryTask.findMany).mockResolvedValue([])
|
||||
const actual = await new JushuitanInventoryCompletionRepository().findSucceeded([target])
|
||||
expect(actual).toEqual([{ ...target, flow: 'warehouse' }])
|
||||
expect(prisma.intakeNonIntegratedPricingRow.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ OR: [target], jstVirtualInventoryStatus: 'pushed', product: { is: { deletedAt: null } } }),
|
||||
}))
|
||||
expect(prisma.intakeJushuitanFixedVirtualInventoryTask.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ OR: [target], status: 'pushed' }),
|
||||
}))
|
||||
})
|
||||
|
||||
it('does not accept an old task barcode after the current SKU barcode changes', async () => {
|
||||
jest.mocked(prisma.intakeNonIntegratedSkuItem.findMany).mockResolvedValue([
|
||||
{ productId: 'p-1', skuItemId: 's-1', barcode: 'new-barcode' },
|
||||
] as never)
|
||||
const actual = await new JushuitanInventoryCompletionRepository().findSucceeded([
|
||||
{ productId: 'p-1', skuItemId: 's-1', barcode: 'old-barcode' },
|
||||
])
|
||||
expect(actual).toEqual([])
|
||||
expect(prisma.intakeNonIntegratedPricingRow.findMany).not.toHaveBeenCalled()
|
||||
expect(prisma.intakeJushuitanFixedVirtualInventoryTask.findMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves a failure log without a barcode against the current SKU barcode', async () => {
|
||||
const current = { productId: 'p-1', skuItemId: 's-1', barcode: 'new-barcode' }
|
||||
jest.mocked(prisma.intakeNonIntegratedSkuItem.findMany).mockResolvedValue([current] as never)
|
||||
jest.mocked(prisma.intakeNonIntegratedPricingRow.findMany).mockResolvedValue([])
|
||||
jest.mocked(prisma.intakeJushuitanFixedVirtualInventoryTask.findMany).mockResolvedValue([])
|
||||
await new JushuitanInventoryCompletionRepository().findSucceeded([{ productId: 'p-1', skuItemId: 's-1' }])
|
||||
expect(prisma.intakeJushuitanFixedVirtualInventoryTask.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ OR: [current] }),
|
||||
}))
|
||||
})
|
||||
|
||||
it('finishes only pending tasks and never overwrites successful rows or an active factory request lease', async () => {
|
||||
const target = { productId: 'p-1', skuItemId: 's-1', barcode: 'current-barcode' }
|
||||
await new JushuitanInventoryCompletionRepository().finishPending([target])
|
||||
expect(prisma.intakeJushuitanFixedVirtualInventoryTask.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ OR: [target], status: 'pending' }),
|
||||
data: expect.objectContaining({ status: 'skipped' }),
|
||||
}))
|
||||
expect(prisma.intakeNonIntegratedPricingRow.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ OR: [target], jstVirtualInventoryStatus: 'pending', jstVirtualInventoryError: { not: JST_VIRTUAL_INVENTORY_IN_FLIGHT_ERROR } }),
|
||||
data: expect.objectContaining({ jstVirtualInventoryStatus: 'skipped' }),
|
||||
}))
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,68 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { JST_VIRTUAL_INVENTORY_IN_FLIGHT_ERROR } from '@/app/intake/non-integrated/nonIntegratedStorage'
|
||||
|
||||
export type InventoryTarget = {
|
||||
productId: string
|
||||
skuItemId: string
|
||||
barcode?: string
|
||||
}
|
||||
|
||||
export type InventorySuccess = InventoryTarget & { flow: 'warehouse' | 'fixed' }
|
||||
export const INVENTORY_ALREADY_SATISFIED = '同一 SKU 已有库存推送成功,无需重复推送'
|
||||
|
||||
export class JushuitanInventoryCompletionRepository {
|
||||
async findSucceeded(targets: InventoryTarget[]): Promise<InventorySuccess[]> {
|
||||
if (targets.length === 0) return []
|
||||
const currentSkus = await prisma.intakeNonIntegratedSkuItem.findMany({
|
||||
where: {
|
||||
OR: targets.map(({ productId, skuItemId }) => ({ productId, skuItemId })),
|
||||
product: { is: { deletedAt: null } },
|
||||
},
|
||||
select: { productId: true, skuItemId: true, barcode: true },
|
||||
})
|
||||
const OR = currentSkus.filter((sku) => sku.barcode.trim() && targets.some((target) =>
|
||||
target.productId === sku.productId && target.skuItemId === sku.skuItemId &&
|
||||
(target.barcode === undefined || target.barcode === sku.barcode)))
|
||||
if (OR.length === 0) return []
|
||||
const [warehouse, fixed] = await Promise.all([
|
||||
prisma.intakeNonIntegratedPricingRow.findMany({
|
||||
where: { OR, jstVirtualInventoryStatus: 'pushed', product: { is: { deletedAt: null } } },
|
||||
select: { productId: true, skuItemId: true, barcode: true },
|
||||
}),
|
||||
prisma.intakeJushuitanFixedVirtualInventoryTask.findMany({
|
||||
where: { OR, status: 'pushed', product: { is: { deletedAt: null } } },
|
||||
select: { productId: true, skuItemId: true, barcode: true },
|
||||
}),
|
||||
])
|
||||
return [
|
||||
...warehouse.map((row) => ({ ...row, flow: 'warehouse' as const })),
|
||||
...fixed.map((row) => ({ ...row, flow: 'fixed' as const })),
|
||||
]
|
||||
}
|
||||
|
||||
async finishPending(targets: InventoryTarget[]) {
|
||||
if (targets.length === 0) return
|
||||
const OR = targets.filter((target) => target.barcode).map(({ productId, skuItemId, barcode }) => ({
|
||||
productId, skuItemId, barcode,
|
||||
}))
|
||||
if (OR.length === 0) return
|
||||
await prisma.$transaction([
|
||||
prisma.intakeJushuitanFixedVirtualInventoryTask.updateMany({
|
||||
where: { OR, status: 'pending' },
|
||||
data: { status: 'skipped', error: INVENTORY_ALREADY_SATISFIED },
|
||||
}),
|
||||
prisma.intakeNonIntegratedPricingRow.updateMany({
|
||||
where: {
|
||||
OR,
|
||||
jstVirtualInventoryStatus: 'pending',
|
||||
// An active external request must still persist its own result through its lease.
|
||||
jstVirtualInventoryError: { not: JST_VIRTUAL_INVENTORY_IN_FLIGHT_ERROR },
|
||||
},
|
||||
data: { jstVirtualInventoryStatus: 'skipped', jstVirtualInventoryError: INVENTORY_ALREADY_SATISFIED },
|
||||
}),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
export type InventoryCompletionRepository = Pick<JushuitanInventoryCompletionRepository, 'findSucceeded' | 'finishPending'>
|
||||
export const jushuitanInventoryCompletionRepository = new JushuitanInventoryCompletionRepository()
|
||||
@ -1,4 +1,5 @@
|
||||
import { OperationLogAction, OperationLogStatus } from '@prisma/client'
|
||||
import { jushuitanInventoryCompletionRepository as completionRepository } from '@/server/repositories/jushuitan-inventory-completion.repository'
|
||||
|
||||
const mockNotify = jest.fn()
|
||||
const mockCreate = jest.fn()
|
||||
@ -28,6 +29,8 @@ function flushBackgroundTasks() {
|
||||
|
||||
describe('OperationLogService 失败日志通知挂载', () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(completionRepository, 'findSucceeded').mockResolvedValue([])
|
||||
jest.spyOn(completionRepository, 'finishPending').mockResolvedValue(undefined)
|
||||
mockNotify.mockReset().mockResolvedValue({ outcome: 'sent' })
|
||||
mockCreate.mockReset().mockResolvedValue({ id: 'log-1' })
|
||||
// 绕过测试环境静默守卫,验证挂载逻辑本身。
|
||||
@ -35,6 +38,7 @@ describe('OperationLogService 失败日志通知挂载', () => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
;(process.env as Record<string, string>).NODE_ENV = ORIGINAL_NODE_ENV as string
|
||||
})
|
||||
|
||||
@ -79,6 +83,29 @@ describe('OperationLogService 失败日志通知挂载', () => {
|
||||
expect(mockNotify).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('库存已由另一条链路成功时记录收口结果且不发送失败通知', async () => {
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([
|
||||
{ productId: 'product-1', skuItemId: 'sku-1', barcode: 'BAR-1', flow: 'warehouse' },
|
||||
])
|
||||
await operationLogService.record({
|
||||
...failureInput, action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH,
|
||||
productId: 'product-1', skuId: 'sku-1', errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED',
|
||||
})
|
||||
await flushBackgroundTasks()
|
||||
expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ status: 'SUCCESS', errorCode: null }))
|
||||
expect(mockNotify).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('两条库存都未成功时仍发送未开通库存的失败通知', async () => {
|
||||
await operationLogService.record({
|
||||
...failureInput, action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH,
|
||||
productId: 'product-1', skuId: 'sku-1', errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED',
|
||||
})
|
||||
await flushBackgroundTasks()
|
||||
expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ status: 'FAILED' }))
|
||||
expect(mockNotify).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('RETRY 状态同样触发通知', async () => {
|
||||
await operationLogService.record({
|
||||
...failureInput,
|
||||
|
||||
@ -0,0 +1,61 @@
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import type {
|
||||
JushuitanFixedVirtualInventoryTaskRepositoryContract,
|
||||
JushuitanFixedVirtualInventoryTaskRecord,
|
||||
} from '@/server/repositories/jushuitan-fixed-virtual-inventory-task.repository'
|
||||
import { OperationLogAction, OperationLogStatus, operationLogService } from './operation-log.service'
|
||||
import { jushuitanInventoryCompletionService } from './jushuitan-inventory-completion.service'
|
||||
import {
|
||||
FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS,
|
||||
JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY,
|
||||
JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID,
|
||||
} from './jushuitan-fixed-virtual-inventory.helpers'
|
||||
|
||||
export type FixedVirtualInventoryRunInput = {
|
||||
actor: AuthUser
|
||||
source: 'USER' | 'SYSTEM'
|
||||
actorId?: string
|
||||
requestId: string
|
||||
now?: Date
|
||||
}
|
||||
|
||||
export async function recordFixedVirtualInventoryFailure(
|
||||
repository: JushuitanFixedVirtualInventoryTaskRepositoryContract,
|
||||
tasks: JushuitanFixedVirtualInventoryTaskRecord[],
|
||||
input: FixedVirtualInventoryRunInput,
|
||||
attemptedAt: Date,
|
||||
reason: string,
|
||||
nonRetryable: boolean,
|
||||
) {
|
||||
const { pending } = await jushuitanInventoryCompletionService.partition(tasks)
|
||||
if (pending.length === 0) return 0
|
||||
const scheduledAt = new Date(attemptedAt.getTime() + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS)
|
||||
const change = { ids: pending.map((task) => task.id), attemptedAt, error: reason, requestId: input.requestId }
|
||||
if (nonRetryable) await repository.markManySkipped(change)
|
||||
else await repository.scheduleManyRetry({ ...change, scheduledAt })
|
||||
|
||||
await Promise.allSettled(pending.map((task) => operationLogService.record({
|
||||
action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH,
|
||||
status: OperationLogStatus.FAILED,
|
||||
source: input.source,
|
||||
actorId: input.actorId,
|
||||
actorName: input.actor.name,
|
||||
productId: task.productId,
|
||||
productSpu: task.productSpu,
|
||||
skuId: task.skuItemId,
|
||||
skuCode: task.skuCode,
|
||||
errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED',
|
||||
message: nonRetryable
|
||||
? `Jushuitan fixed virtual inventory push skipped without retry: ${reason}`
|
||||
: `Jushuitan fixed virtual inventory push failed; retry at ${scheduledAt.toISOString()}: ${reason}`,
|
||||
requestId: input.requestId,
|
||||
details: {
|
||||
flow: 'fixed-wms-virtual-inventory', path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY,
|
||||
barcode: task.barcode, batchSize: pending.length, reason,
|
||||
...(nonRetryable ? { skipped: true } : { scheduledAt: scheduledAt.toISOString() }),
|
||||
},
|
||||
})))
|
||||
return pending.length
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import type { AuthUser } from "@/server/core/types";
|
||||
import { jushuitanInventoryCompletionRepository as completionRepository } from '@/server/repositories/jushuitan-inventory-completion.repository';
|
||||
import type {
|
||||
JushuitanFixedVirtualInventoryTaskRepositoryContract,
|
||||
JushuitanFixedVirtualInventoryTaskRecord,
|
||||
@ -81,6 +82,8 @@ function successfulResponse(requestId: string) {
|
||||
|
||||
describe("Jushuitan fixed virtual inventory service", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(completionRepository, 'findSucceeded').mockResolvedValue([]);
|
||||
jest.spyOn(completionRepository, 'finishPending').mockResolvedValue(undefined);
|
||||
jest
|
||||
.spyOn(operationLogService, "record")
|
||||
.mockResolvedValue(undefined);
|
||||
@ -149,6 +152,56 @@ describe("Jushuitan fixed virtual inventory service", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('does not enqueue SKUs already satisfied by either inventory flow', async () => {
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([
|
||||
{ productId: 'product-1', skuItemId: 'sku-1', barcode: 'BARCODE-1', flow: 'warehouse' },
|
||||
]);
|
||||
const repository = createRepository([]);
|
||||
await new JushuitanFixedVirtualInventoryService(repository).enqueueForProduct({
|
||||
id: 'product-1', spu: 'SPU-1', skuItems: [1, 2].map((n) => ({
|
||||
id: `sku-${n}`, skuCode: `SKU-${n}`, barcode: `BARCODE-${n}`,
|
||||
} as never)),
|
||||
}, ['sku-1', 'sku-2']);
|
||||
expect(repository.createMissing).toHaveBeenCalledWith([expect.objectContaining({ skuItemId: 'sku-2' })]);
|
||||
});
|
||||
|
||||
it.each(['warehouse', 'fixed'] as const)('closes due tasks already satisfied by the %s flow without a request or failure', async (flow) => {
|
||||
const task = createTask();
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([{ ...task, flow }]);
|
||||
const repository = createRepository([[task]]);
|
||||
const post = jest.fn();
|
||||
await expect(new JushuitanFixedVirtualInventoryService(repository, post).processDue(runInput))
|
||||
.resolves.toEqual({ processed: 1, pushed: 0, failed: 0 });
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
expect(repository.scheduleManyRetry).not.toHaveBeenCalled();
|
||||
expect(operationLogService.record).not.toHaveBeenCalled();
|
||||
expect(completionRepository.finishPending).toHaveBeenCalledWith([task]);
|
||||
});
|
||||
|
||||
it('rechecks success after waiting for a request turn', async () => {
|
||||
const task = createTask();
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValueOnce([])
|
||||
.mockResolvedValue([{ ...task, flow: 'warehouse' }]);
|
||||
const post = jest.fn();
|
||||
await expect(new JushuitanFixedVirtualInventoryService(createRepository([[task]]), post).processDue(runInput))
|
||||
.resolves.toEqual({ processed: 1, pushed: 0, failed: 0 });
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('only retries and logs unsatisfied SKUs when the other flow completes during a failed batch', async () => {
|
||||
const tasks = [createTask(1), createTask(2)];
|
||||
const repository = createRepository([tasks]);
|
||||
const post = jest.fn(async () => {
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([{ ...tasks[0], flow: 'warehouse' }]);
|
||||
throw new Error('network timeout');
|
||||
});
|
||||
await expect(new JushuitanFixedVirtualInventoryService(repository, post).processDue(runInput))
|
||||
.resolves.toEqual({ processed: 2, pushed: 0, failed: 1 });
|
||||
expect(repository.scheduleManyRetry).toHaveBeenCalledWith(expect.objectContaining({ ids: ['task-2'] }));
|
||||
expect(operationLogService.record).toHaveBeenCalledTimes(1);
|
||||
expect(operationLogService.record).toHaveBeenCalledWith(expect.objectContaining({ skuId: 'sku-2', status: 'FAILED' }));
|
||||
});
|
||||
|
||||
it("shares one active run when the scheduler is triggered twice", async () => {
|
||||
const repository = createRepository([]);
|
||||
const task = createTask();
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
import type { AuthUser } from "@/server/core/types";
|
||||
import type { NonIntegratedSkuItem } from "@/app/intake/non-integrated/nonIntegratedStorage";
|
||||
import { jushuitanInventoryCompletionService } from './jushuitan-inventory-completion.service';
|
||||
import {
|
||||
recordFixedVirtualInventoryFailure,
|
||||
type FixedVirtualInventoryRunInput,
|
||||
} from './jushuitan-fixed-virtual-inventory-result.service';
|
||||
import {
|
||||
postJushuitanWithDefaultCredentials,
|
||||
type JushuitanApiResult,
|
||||
@ -18,7 +22,6 @@ import {
|
||||
buildFixedVirtualInventoryPayload,
|
||||
DEFAULT_FIXED_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS,
|
||||
FIXED_VIRTUAL_INVENTORY_BATCH_SIZE,
|
||||
FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS,
|
||||
isFixedVirtualInventoryNonRetryable,
|
||||
isFixedVirtualInventoryRateLimited,
|
||||
JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
@ -35,13 +38,6 @@ type FixedVirtualInventoryProduct = {
|
||||
spu: string;
|
||||
skuItems: NonIntegratedSkuItem[];
|
||||
};
|
||||
type FixedVirtualInventoryRunInput = {
|
||||
actor: AuthUser;
|
||||
source: "USER" | "SYSTEM";
|
||||
actorId?: string;
|
||||
requestId: string;
|
||||
now?: Date;
|
||||
};
|
||||
type FixedVirtualInventoryApi = (
|
||||
path: string,
|
||||
biz: Record<string, unknown>,
|
||||
@ -83,7 +79,8 @@ export class JushuitanFixedVirtualInventoryService {
|
||||
scheduledAt: now,
|
||||
}));
|
||||
|
||||
return this.repository.createMissing(tasks);
|
||||
const { pending } = await jushuitanInventoryCompletionService.partition(tasks);
|
||||
return this.repository.createMissing(pending);
|
||||
}
|
||||
|
||||
async processDue(input: FixedVirtualInventoryRunInput) {
|
||||
@ -132,35 +129,40 @@ export class JushuitanFixedVirtualInventoryService {
|
||||
input: FixedVirtualInventoryRunInput,
|
||||
) {
|
||||
const attemptedAt = input.now ?? new Date();
|
||||
const missingBarcodeTasks = tasks.filter((task) => !task.barcode.trim());
|
||||
const pushableTasks = tasks.filter((task) => task.barcode.trim());
|
||||
const { pending } = await jushuitanInventoryCompletionService.partition(tasks);
|
||||
const missingBarcodeTasks = pending.filter((task) => !task.barcode.trim());
|
||||
let pushableTasks = pending.filter((task) => task.barcode.trim());
|
||||
let missingBarcodeFailures = 0;
|
||||
|
||||
if (missingBarcodeTasks.length > 0) {
|
||||
await this.scheduleRetry(
|
||||
missingBarcodeFailures = await recordFixedVirtualInventoryFailure(
|
||||
this.repository,
|
||||
missingBarcodeTasks,
|
||||
input,
|
||||
attemptedAt,
|
||||
"SKU barcode is empty",
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
if (pushableTasks.length === 0) {
|
||||
return {
|
||||
pushed: 0,
|
||||
failed: missingBarcodeTasks.length,
|
||||
failed: missingBarcodeFailures,
|
||||
rateLimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
const payload = buildFixedVirtualInventoryPayload(
|
||||
pushableTasks.map((task) => task.barcode.trim()),
|
||||
);
|
||||
|
||||
try {
|
||||
await this.waitForRequestTurn();
|
||||
// The other flow can complete while this batch waits for its request turn.
|
||||
({ pending: pushableTasks } = await jushuitanInventoryCompletionService.partition(pushableTasks));
|
||||
if (pushableTasks.length === 0) {
|
||||
return { pushed: 0, failed: missingBarcodeFailures, rateLimited: false };
|
||||
}
|
||||
const response = await this.post(
|
||||
JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
payload,
|
||||
buildFixedVirtualInventoryPayload(pushableTasks.map((task) => task.barcode.trim())),
|
||||
);
|
||||
const requestId = readFixedVirtualInventoryRequestId(response.raw);
|
||||
if (!requestId) {
|
||||
@ -200,112 +202,23 @@ export class JushuitanFixedVirtualInventoryService {
|
||||
);
|
||||
return {
|
||||
pushed: pushableTasks.length,
|
||||
failed: missingBarcodeTasks.length,
|
||||
failed: missingBarcodeFailures,
|
||||
rateLimited: false,
|
||||
};
|
||||
} catch (error) {
|
||||
const reason = normalizeFixedVirtualInventoryError(error);
|
||||
if (isFixedVirtualInventoryNonRetryable(error)) {
|
||||
await this.markSkipped(pushableTasks, input, attemptedAt, reason);
|
||||
} else {
|
||||
await this.scheduleRetry(pushableTasks, input, attemptedAt, reason);
|
||||
}
|
||||
const failed = await recordFixedVirtualInventoryFailure(
|
||||
this.repository, pushableTasks, input, attemptedAt, reason,
|
||||
isFixedVirtualInventoryNonRetryable(error),
|
||||
);
|
||||
return {
|
||||
pushed: 0,
|
||||
failed: tasks.length,
|
||||
rateLimited: isFixedVirtualInventoryRateLimited(error),
|
||||
failed: missingBarcodeFailures + failed,
|
||||
rateLimited: failed > 0 && isFixedVirtualInventoryRateLimited(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async markSkipped(
|
||||
tasks: JushuitanFixedVirtualInventoryTaskRecord[],
|
||||
input: FixedVirtualInventoryRunInput,
|
||||
attemptedAt: Date,
|
||||
reason: string,
|
||||
) {
|
||||
await this.repository.markManySkipped({
|
||||
ids: tasks.map((task) => task.id),
|
||||
attemptedAt,
|
||||
error: reason,
|
||||
requestId: input.requestId,
|
||||
});
|
||||
await Promise.allSettled(
|
||||
tasks.map((task) =>
|
||||
operationLogService.record({
|
||||
action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH,
|
||||
status: OperationLogStatus.FAILED,
|
||||
source: input.source,
|
||||
actorId: input.actorId,
|
||||
actorName: input.actor.name,
|
||||
productId: task.productId,
|
||||
productSpu: task.productSpu,
|
||||
skuId: task.skuItemId,
|
||||
skuCode: task.skuCode,
|
||||
errorCode: "JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED",
|
||||
message: `Jushuitan fixed virtual inventory push skipped without retry: ${reason}`,
|
||||
requestId: input.requestId,
|
||||
details: {
|
||||
flow: "fixed-wms-virtual-inventory",
|
||||
path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID,
|
||||
qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY,
|
||||
barcode: task.barcode,
|
||||
batchSize: tasks.length,
|
||||
skipped: true,
|
||||
reason,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async scheduleRetry(
|
||||
tasks: JushuitanFixedVirtualInventoryTaskRecord[],
|
||||
input: FixedVirtualInventoryRunInput,
|
||||
attemptedAt: Date,
|
||||
reason: string,
|
||||
) {
|
||||
const scheduledAt = new Date(
|
||||
attemptedAt.getTime() + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS,
|
||||
);
|
||||
await this.repository.scheduleManyRetry({
|
||||
ids: tasks.map((task) => task.id),
|
||||
attemptedAt,
|
||||
scheduledAt,
|
||||
error: reason,
|
||||
requestId: input.requestId,
|
||||
});
|
||||
await Promise.allSettled(
|
||||
tasks.map((task) =>
|
||||
operationLogService.record({
|
||||
action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH,
|
||||
status: OperationLogStatus.FAILED,
|
||||
source: input.source,
|
||||
actorId: input.actorId,
|
||||
actorName: input.actor.name,
|
||||
productId: task.productId,
|
||||
productSpu: task.productSpu,
|
||||
skuId: task.skuItemId,
|
||||
skuCode: task.skuCode,
|
||||
errorCode: "JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED",
|
||||
message: `Jushuitan fixed virtual inventory push failed; retry at ${scheduledAt.toISOString()}: ${reason}`,
|
||||
requestId: input.requestId,
|
||||
details: {
|
||||
flow: "fixed-wms-virtual-inventory",
|
||||
path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH,
|
||||
wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID,
|
||||
qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY,
|
||||
barcode: task.barcode,
|
||||
batchSize: tasks.length,
|
||||
scheduledAt: scheduledAt.toISOString(),
|
||||
reason,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async waitForRequestTurn() {
|
||||
const intervalMs = this.getRequestIntervalMs();
|
||||
const waitMs = Math.max(
|
||||
|
||||
@ -0,0 +1,136 @@
|
||||
import { JushuitanInventoryCompletionService } from './jushuitan-inventory-completion.service'
|
||||
import type { InventorySuccess, InventoryTarget } from '@/server/repositories/jushuitan-inventory-completion.repository'
|
||||
import type { JushuitanVirtualInventoryPushInput, JushuitanVirtualInventoryPushResult } from './jushuitan-product-pricing-push.service'
|
||||
import type { CreateOperationLogInput } from '@/server/repositories/operation-log.repository'
|
||||
|
||||
const target = (id: string): InventoryTarget => ({ productId: 'product-1', skuItemId: id, barcode: `BAR-${id}` })
|
||||
const success = (id: string, flow: InventorySuccess['flow'] = 'fixed'): InventorySuccess => ({ ...target(id), flow })
|
||||
|
||||
function setup() {
|
||||
const repository = {
|
||||
findSucceeded: jest.fn<Promise<InventorySuccess[]>, [InventoryTarget[]]>().mockResolvedValue([]),
|
||||
finishPending: jest.fn(async () => undefined),
|
||||
}
|
||||
return { repository, service: new JushuitanInventoryCompletionService(repository) }
|
||||
}
|
||||
|
||||
function input(ids = ['1', '2']): JushuitanVirtualInventoryPushInput {
|
||||
return {
|
||||
product: {
|
||||
id: 'product-1', spu: 'SPU-1', brand: 'test',
|
||||
skuItems: ids.map((id) => ({ id, skuCode: `SKU-${id}`, barcode: `BAR-${id}` } as never)),
|
||||
factoryRows: ids.map((id) => ({ skuId: id, warehouse: 'factory' } as never)),
|
||||
pricingRows: [], sampleMeasurementRows: [],
|
||||
},
|
||||
targetSkuIds: ids,
|
||||
}
|
||||
}
|
||||
|
||||
function result(): JushuitanVirtualInventoryPushResult {
|
||||
return {
|
||||
pushedSkuIds: [], virtualInventoryCount: 0, virtualInventorySkippedCount: 0,
|
||||
virtualInventoryFailedCount: 0, virtualInventorySkipped: [], virtualInventoryFailed: [], results: [],
|
||||
}
|
||||
}
|
||||
|
||||
const failure = {
|
||||
action: 'JUSHUITAN_VIRTUAL_INVENTORY_PUSH', status: 'FAILED',
|
||||
productId: 'product-1', skuId: '1', actorName: 'cron',
|
||||
errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED',
|
||||
message: 'code=100,未开通了分仓虚拟库存!',
|
||||
} satisfies CreateOperationLogInput
|
||||
|
||||
describe('inventory success completes either flow', () => {
|
||||
it('matches product, SKU and barcode instead of completing unrelated or older barcodes', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockResolvedValue([
|
||||
success('1'), { ...success('2'), productId: 'other-product' },
|
||||
{ ...success('3'), barcode: 'older-barcode' },
|
||||
])
|
||||
const partition = await service.partition(['1', '2', '3'].map(target))
|
||||
expect(partition.completed).toEqual([target('1')])
|
||||
expect(partition.pending).toEqual([target('2'), target('3')])
|
||||
expect(repository.finishPending).toHaveBeenCalledWith([target('1')])
|
||||
})
|
||||
|
||||
it.each(['fixed', 'warehouse'] as const)('skips factory requests already satisfied by %s inventory', async (flow) => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockResolvedValue([success('1', flow), success('2', flow)])
|
||||
const execute = jest.fn()
|
||||
const actual = await service.runWarehouse(input(), execute)
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
expect(actual).toMatchObject({ pushedSkuIds: [], virtualInventoryCount: 0, virtualInventoryFailedCount: 0, virtualInventorySkippedCount: 2 })
|
||||
})
|
||||
|
||||
it('pushes only unsatisfied factory SKUs and preserves their actual result', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockResolvedValue([success('1')])
|
||||
const execute = jest.fn(async () => ({ ...result(), pushedSkuIds: ['2'], virtualInventoryCount: 1 }))
|
||||
const actual = await service.runWarehouse(input(), execute)
|
||||
expect(execute).toHaveBeenCalledWith(['2'])
|
||||
expect(actual).toMatchObject({ pushedSkuIds: ['2'], virtualInventoryCount: 1, virtualInventorySkippedCount: 1, virtualInventoryFailedCount: 0 })
|
||||
})
|
||||
|
||||
it('rechecks a failed factory request when fixed inventory succeeds during the call', async () => {
|
||||
const { service, repository } = setup()
|
||||
const execute = jest.fn(async () => {
|
||||
repository.findSucceeded.mockResolvedValue([success('1')])
|
||||
return { ...result(), virtualInventoryFailedCount: 2, virtualInventoryFailed: ['1', '2'].map((id) => ({
|
||||
skuId: id, skuCode: `SKU-${id}`, barcode: `BAR-${id}`, warehouse: 'factory', reason: 'timeout',
|
||||
})) }
|
||||
})
|
||||
const actual = await service.runWarehouse(input(), execute)
|
||||
expect(actual).toMatchObject({ virtualInventorySkippedCount: 1, virtualInventoryFailedCount: 1 })
|
||||
expect(actual.virtualInventoryFailed.map((row) => row.skuId)).toEqual(['2'])
|
||||
expect(actual.virtualInventorySkipped.map((row) => row.skuId)).toEqual(['1'])
|
||||
})
|
||||
|
||||
it('handles a thrown request with a concurrent partial success without hiding the other failure', async () => {
|
||||
const { service, repository } = setup()
|
||||
const actual = await service.runWarehouse(input(), async () => {
|
||||
repository.findSucceeded.mockResolvedValue([success('1')])
|
||||
throw new Error('network timeout')
|
||||
})
|
||||
expect(actual).toMatchObject({ virtualInventorySkippedCount: 1, virtualInventoryFailedCount: 1 })
|
||||
expect(actual.virtualInventoryFailed).toEqual([expect.objectContaining({ skuId: '2', reason: 'network timeout' })])
|
||||
})
|
||||
|
||||
it('preserves a thrown request error when neither flow has succeeded', async () => {
|
||||
const { service } = setup()
|
||||
await expect(service.runWarehouse(input(), async () => { throw new Error('network timeout') }))
|
||||
.rejects.toThrow('network timeout')
|
||||
})
|
||||
|
||||
it.each(['JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED', 'JUSHUITAN_VIRTUAL_INVENTORY_FAILED'])('records a satisfied %s as an audit outcome and retains its original cause', async (errorCode) => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockResolvedValue([success('1')])
|
||||
const actual = await service.resolveFailureLog({ ...failure, errorCode, details: { barcode: 'BAR-1' } })
|
||||
expect(actual).toMatchObject({
|
||||
status: 'SUCCESS', errorCode: null,
|
||||
details: { barcode: 'BAR-1', inventorySatisfiedBy: 'fixed', redundantInventoryFailure: { errorCode, message: failure.message } },
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the unconfigured error as a real failure when no inventory flow succeeded', async () => {
|
||||
const { service } = setup()
|
||||
expect(await service.resolveFailureLog(failure)).toBe(failure)
|
||||
})
|
||||
|
||||
it('does not suppress persistence failures or unrelated actions', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockResolvedValue([success('1')])
|
||||
const persistence = { ...failure, errorCode: 'JUSHUITAN_VIRTUAL_INVENTORY_STATUS_PERSIST_FAILED' }
|
||||
expect(await service.resolveFailureLog(persistence)).toBe(persistence)
|
||||
const other = { ...failure, action: 'JUSHUITAN_PRODUCT_PUSH' as const }
|
||||
expect(await service.resolveFailureLog(other)).toBe(other)
|
||||
expect(repository.findSucceeded).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retains the failure and alert when the completion lookup fails', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.findSucceeded.mockRejectedValue(new Error('lookup unavailable'))
|
||||
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
try { expect(await service.resolveFailureLog(failure)).toBe(failure) }
|
||||
finally { consoleSpy.mockRestore() }
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,117 @@
|
||||
import {
|
||||
INVENTORY_ALREADY_SATISFIED,
|
||||
jushuitanInventoryCompletionRepository,
|
||||
type InventoryCompletionRepository,
|
||||
type InventoryTarget,
|
||||
} from '@/server/repositories/jushuitan-inventory-completion.repository'
|
||||
import type { CreateOperationLogInput } from '@/server/repositories/operation-log.repository'
|
||||
import type {
|
||||
JushuitanVirtualInventoryPushInput,
|
||||
JushuitanVirtualInventoryPushResult,
|
||||
} from './jushuitan-product-pricing-push.service'
|
||||
|
||||
const INVENTORY_FAILURE_CODES = new Set([
|
||||
'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED',
|
||||
'JUSHUITAN_VIRTUAL_INVENTORY_FAILED',
|
||||
])
|
||||
|
||||
function matches(target: InventoryTarget, success: InventoryTarget) {
|
||||
return target.productId === success.productId && target.skuItemId === success.skuItemId &&
|
||||
(target.barcode === undefined || target.barcode === success.barcode)
|
||||
}
|
||||
|
||||
export class JushuitanInventoryCompletionService {
|
||||
constructor(private readonly repository: InventoryCompletionRepository = jushuitanInventoryCompletionRepository) {}
|
||||
|
||||
async partition<T extends InventoryTarget>(targets: T[]) {
|
||||
if (targets.length === 0) return { pending: targets, completed: [] as T[], successes: [] }
|
||||
const successes = await this.repository.findSucceeded(targets)
|
||||
const completed = targets.filter((target) => successes.some((success) => matches(target, success)))
|
||||
const completedSet = new Set(completed)
|
||||
await this.repository.finishPending(completed.map((target) => ({
|
||||
...target, barcode: successes.find((success) => matches(target, success))!.barcode,
|
||||
})))
|
||||
return { pending: targets.filter((target) => !completedSet.has(target)), completed, successes }
|
||||
}
|
||||
|
||||
async resolveFailureLog(input: CreateOperationLogInput): Promise<CreateOperationLogInput> {
|
||||
if (input.action !== 'JUSHUITAN_VIRTUAL_INVENTORY_PUSH' ||
|
||||
!['FAILED', 'RETRY'].includes(input.status) ||
|
||||
!INVENTORY_FAILURE_CODES.has(input.errorCode ?? '') || !input.productId || !input.skuId) return input
|
||||
|
||||
try {
|
||||
const { completed, successes } = await this.partition([{ productId: input.productId, skuItemId: input.skuId }])
|
||||
if (completed.length === 0) return input
|
||||
const originalDetails = input.details && typeof input.details === 'object' && !Array.isArray(input.details)
|
||||
? input.details : {}
|
||||
return {
|
||||
...input,
|
||||
status: 'SUCCESS',
|
||||
errorCode: null,
|
||||
message: INVENTORY_ALREADY_SATISFIED,
|
||||
details: {
|
||||
...originalDetails,
|
||||
inventorySatisfiedBy: successes[0].flow,
|
||||
redundantInventoryFailure: { status: input.status, errorCode: input.errorCode ?? '', message: input.message },
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
// A lookup failure must never silence a real inventory failure.
|
||||
console.error('[InventoryCompletion] Failed to verify inventory before logging', error)
|
||||
return input
|
||||
}
|
||||
}
|
||||
|
||||
async runWarehouse(
|
||||
input: JushuitanVirtualInventoryPushInput,
|
||||
execute: (targetSkuIds: string[]) => Promise<JushuitanVirtualInventoryPushResult>,
|
||||
): Promise<JushuitanVirtualInventoryPushResult> {
|
||||
const selected = new Set(input.targetSkuIds)
|
||||
const targets = input.product.skuItems.filter((sku) => selected.has(sku.id)).map((sku) => ({
|
||||
productId: input.product.id, skuItemId: sku.id, barcode: sku.barcode,
|
||||
}))
|
||||
const { pending, completed } = await this.partition(targets)
|
||||
let result: JushuitanVirtualInventoryPushResult = {
|
||||
pushedSkuIds: [], virtualInventoryCount: 0, virtualInventorySkippedCount: 0,
|
||||
virtualInventoryFailedCount: 0, virtualInventorySkipped: [], virtualInventoryFailed: [], results: [],
|
||||
}
|
||||
let satisfied = completed
|
||||
if (pending.length > 0) {
|
||||
try {
|
||||
result = await execute(pending.map((target) => target.skuItemId))
|
||||
} catch (error) {
|
||||
const checked = await this.partition(pending)
|
||||
if (checked.completed.length === 0) throw error
|
||||
satisfied = [...satisfied, ...checked.completed]
|
||||
result.virtualInventoryFailed = checked.pending.map((target) => ({
|
||||
...this.warehouseItem(input, target.skuItemId),
|
||||
reason: error instanceof Error ? error.message : '聚水潭虚拟库存推送失败',
|
||||
}))
|
||||
}
|
||||
const failedIds = new Set(result.virtualInventoryFailed.map((item) => item.skuId))
|
||||
const checked = await this.partition(pending.filter((target) => failedIds.has(target.skuItemId)))
|
||||
const satisfiedIds = new Set(checked.completed.map((target) => target.skuItemId))
|
||||
satisfied = [...satisfied, ...checked.completed]
|
||||
result.virtualInventoryFailed = result.virtualInventoryFailed.filter((item) => !satisfiedIds.has(item.skuId ?? ''))
|
||||
}
|
||||
const skipped = satisfied.map((target) => ({
|
||||
...this.warehouseItem(input, target.skuItemId), reason: INVENTORY_ALREADY_SATISFIED,
|
||||
}))
|
||||
return {
|
||||
...result,
|
||||
virtualInventorySkipped: [...result.virtualInventorySkipped, ...skipped],
|
||||
virtualInventorySkippedCount: result.virtualInventorySkipped.length + skipped.length,
|
||||
virtualInventoryFailedCount: result.virtualInventoryFailed.length,
|
||||
}
|
||||
}
|
||||
|
||||
private warehouseItem(input: JushuitanVirtualInventoryPushInput, skuId: string) {
|
||||
const sku = input.product.skuItems.find((item) => item.id === skuId)!
|
||||
return {
|
||||
skuId, skuCode: sku.skuCode, barcode: sku.barcode,
|
||||
warehouse: input.product.factoryRows.find((row) => row.skuId === skuId)?.warehouse ?? '',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const jushuitanInventoryCompletionService = new JushuitanInventoryCompletionService()
|
||||
@ -4,6 +4,7 @@ import type {
|
||||
NonIntegratedSampleMeasurementRow,
|
||||
NonIntegratedSkuItem,
|
||||
} from '@/app/intake/non-integrated/nonIntegratedStorage'
|
||||
import { jushuitanInventoryCompletionRepository as completionRepository } from '@/server/repositories/jushuitan-inventory-completion.repository'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
@ -169,6 +170,15 @@ describe('JushuitanProductPricingPushService', () => {
|
||||
const originalFetch = global.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(completionRepository, 'findSucceeded').mockResolvedValue([])
|
||||
jest.spyOn(completionRepository, 'finishPending').mockResolvedValue(undefined)
|
||||
const filesystem = jest.requireActual<typeof import('node:fs')>('node:fs')
|
||||
const exists = filesystem.existsSync
|
||||
jest.spyOn(filesystem, 'existsSync').mockImplementation((path) => {
|
||||
// Credential fixtures must not fall back to this machine's actual credentials.
|
||||
const normalized = String(path).replace(/\//g, '\\')
|
||||
return /^(?:D|C):\\ChanPing\\jushuitan\\/i.test(normalized) ? false : exists(path)
|
||||
})
|
||||
process.env = {
|
||||
...originalEnv,
|
||||
JST_APP_KEY: 'app-key',
|
||||
@ -891,6 +901,51 @@ describe('JushuitanProductPricingPushService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('简尚库存已成功时不再发送工厂库存请求', async () => {
|
||||
const sku = createSku({ id: 'already-completed' })
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([{
|
||||
productId: 'product-1', skuItemId: sku.id, barcode: sku.barcode, flow: 'fixed',
|
||||
}])
|
||||
const fetchMock = createSuccessFetchMock()
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
const result = await new JushuitanProductPricingPushService().pushVirtualInventory({
|
||||
product: createProduct([sku]), targetSkuIds: [sku.id],
|
||||
})
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(result).toMatchObject({ virtualInventoryCount: 0, virtualInventorySkippedCount: 1, virtualInventoryFailedCount: 0 })
|
||||
})
|
||||
|
||||
it('工厂请求等待期间简尚库存刚成功时取消多余请求', async () => {
|
||||
const sku = createSku({ id: 'completed-during-wait' })
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValueOnce([]).mockResolvedValue([{
|
||||
productId: 'product-1', skuItemId: sku.id, barcode: sku.barcode, flow: 'fixed',
|
||||
}])
|
||||
const fetchMock = jest.fn(async () => ({
|
||||
ok: true, status: 200, text: async () => JSON.stringify({
|
||||
code: 0, data: { datas: [{ name: '测试仓', wms_co_id: 101, remark2: '成品代发仓-虚拟库存' }] },
|
||||
}),
|
||||
} as Response))
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
const result = await new JushuitanProductPricingPushService().pushVirtualInventory({
|
||||
product: createProduct([sku]), targetSkuIds: [sku.id],
|
||||
})
|
||||
expect(findCallIndex(fetchMock, '/open/jushuitan/inventoryv2/upload')).toBe(-1)
|
||||
expect(result).toMatchObject({ virtualInventoryCount: 0, virtualInventorySkippedCount: 1, virtualInventoryFailedCount: 0 })
|
||||
})
|
||||
|
||||
it('已有库存成功记录时商品资料推送不再规划待推库存', async () => {
|
||||
const sku = createSku({ id: 'completed-before-planning' })
|
||||
jest.mocked(completionRepository.findSucceeded).mockResolvedValue([{
|
||||
productId: 'product-1', skuItemId: sku.id, barcode: sku.barcode, flow: 'fixed',
|
||||
}])
|
||||
global.fetch = createSuccessFetchMock() as unknown as typeof fetch
|
||||
const result = await new JushuitanProductPricingPushService().pushProductPricing({
|
||||
product: createProduct([sku]), targetSkuIds: [sku.id],
|
||||
})
|
||||
expect(result.virtualInventoryPendingCount).toBe(0)
|
||||
expect(result.virtualInventoryPlans).toEqual([expect.objectContaining({ skuId: sku.id, status: 'skipped' })])
|
||||
})
|
||||
|
||||
it('重试虚拟库存时复用认领阶段持久化的 so_id', async () => {
|
||||
const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input)
|
||||
|
||||
@ -15,6 +15,8 @@ import {
|
||||
resolveNonIntegratedSharedProductTagValue,
|
||||
} from '@/app/intake/non-integrated/core/nonIntegratedStorage'
|
||||
import { SPU_RULE_LIBRARY_SEED_RULES } from '@/app/intake/product-development/spuRuleLibrarySeed'
|
||||
import { jushuitanInventoryCompletionService } from './jushuitan-inventory-completion.service'
|
||||
import { INVENTORY_ALREADY_SATISFIED } from '@/server/repositories/jushuitan-inventory-completion.repository'
|
||||
|
||||
type JushuitanCredentials = {
|
||||
appKey: string
|
||||
@ -1207,6 +1209,13 @@ async function pushVirtualInventoryItems(
|
||||
|
||||
try {
|
||||
await waitForVirtualInventoryRequestInterval()
|
||||
const { completed } = await jushuitanInventoryCompletionService.partition([{
|
||||
productId: product.id, skuItemId: row.sku.id, barcode: row.sku.barcode,
|
||||
}])
|
||||
if (completed.length > 0) {
|
||||
skipped.push({ ...skippedBase, reason: INVENTORY_ALREADY_SATISFIED })
|
||||
continue
|
||||
}
|
||||
results.push(
|
||||
await postJushuitan(credentials, INVENTORY_V2_UPLOAD_PATH, {
|
||||
wms_co_id: warehouseInfo.wmsCoId,
|
||||
@ -1235,13 +1244,19 @@ async function pushVirtualInventoryItems(
|
||||
}
|
||||
|
||||
async function planVirtualInventoryItems(
|
||||
productId: string,
|
||||
rows: NormalizedPushRow[],
|
||||
credentials: JushuitanCredentials,
|
||||
now = new Date(),
|
||||
): Promise<JushuitanVirtualInventoryPlanItem[]> {
|
||||
const warehouses = await queryWarehouseInfosForVirtualInventory(
|
||||
const { completed } = await jushuitanInventoryCompletionService.partition(rows.map((row) => ({
|
||||
productId, skuItemId: row.sku.id, barcode: row.sku.barcode,
|
||||
})))
|
||||
const completedIds = new Set(completed.map((target) => target.skuItemId))
|
||||
const pendingRows = rows.filter((row) => !completedIds.has(row.sku.id))
|
||||
const warehouses = pendingRows.length === 0 ? [] : await queryWarehouseInfosForVirtualInventory(
|
||||
credentials,
|
||||
rows.map((row) => row.factoryRow.warehouse),
|
||||
pendingRows.map((row) => row.factoryRow.warehouse),
|
||||
)
|
||||
const virtualInventoryRemarkKeyword = getVirtualInventoryRemarkKeyword()
|
||||
const normalizedVirtualInventoryRemarkKeyword =
|
||||
@ -1257,6 +1272,10 @@ async function planVirtualInventoryItems(
|
||||
warehouse: warehouseName,
|
||||
}
|
||||
|
||||
if (completedIds.has(row.sku.id)) {
|
||||
return { ...base, status: 'skipped', reason: INVENTORY_ALREADY_SATISFIED } satisfies JushuitanVirtualInventoryPlanItem
|
||||
}
|
||||
|
||||
if (!warehouseName) {
|
||||
return {
|
||||
...base,
|
||||
@ -1444,6 +1463,7 @@ class JushuitanProductPricingPushService {
|
||||
: credentials
|
||||
// 先完成仓库规划,避免商品资料已远程成功后才发现规划失败,留下无法可靠落锁的半完成状态。
|
||||
const virtualInventoryPlans = await planVirtualInventoryItems(
|
||||
input.product.id,
|
||||
normalRows,
|
||||
credentials,
|
||||
)
|
||||
@ -1547,6 +1567,13 @@ class JushuitanProductPricingPushService {
|
||||
|
||||
async pushVirtualInventory(
|
||||
input: JushuitanVirtualInventoryPushInput,
|
||||
): Promise<JushuitanVirtualInventoryPushResult> {
|
||||
return jushuitanInventoryCompletionService.runWarehouse(input, (targetSkuIds) =>
|
||||
this.pushPendingVirtualInventory({ ...input, targetSkuIds }))
|
||||
}
|
||||
|
||||
private async pushPendingVirtualInventory(
|
||||
input: JushuitanVirtualInventoryPushInput,
|
||||
): Promise<JushuitanVirtualInventoryPushResult> {
|
||||
const rows = resolveVirtualInventoryTargetRows(input)
|
||||
const credentials = readJushuitanCredentials()
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
type OperationLogWithActor,
|
||||
} from '@/server/repositories/operation-log.repository'
|
||||
import { operationLogFailureNotificationService } from './operation-log-failure-notification.service'
|
||||
import { jushuitanInventoryCompletionService } from './jushuitan-inventory-completion.service'
|
||||
|
||||
export { OperationLogAction, OperationLogStatus }
|
||||
export type OperationLogInput = CreateOperationLogInput
|
||||
@ -40,6 +41,7 @@ export interface OperationLogListOptions extends OperationLogFilter {
|
||||
class OperationLogService {
|
||||
async record(input: OperationLogInput): Promise<void> {
|
||||
try {
|
||||
input = await jushuitanInventoryCompletionService.resolveFailureLog(input)
|
||||
await operationLogRepository.create(input)
|
||||
this.notifyFailureInBackground(input)
|
||||
} catch (error) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user