WMS_MAIN/test/app/schedule/notice_stock_remaining.test.js
2026-04-17 19:21:57 +08:00

449 lines
12 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const schedule = require('../../../app/schedule/notice_stock_remaining');
const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified';
const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list';
function createLogger() {
return {
info() {},
warn() {},
error() {},
debug() {},
};
}
function createSequelizeInstanceLikeRecord(values = {}, associations = {}) {
const dataValues = { ...values };
const includedValues = { ...associations };
const prototype = {
getDataValue(fieldName) {
if (Object.prototype.hasOwnProperty.call(dataValues, fieldName)) {
return dataValues[fieldName];
}
return includedValues[fieldName];
},
get(fieldName) {
return this.getDataValue(fieldName);
},
};
for (const fieldName of Object.keys(dataValues)) {
Object.defineProperty(prototype, fieldName, {
enumerable: false,
configurable: true,
get() {
return dataValues[fieldName];
},
});
}
for (const fieldName of Object.keys(includedValues)) {
Object.defineProperty(prototype, fieldName, {
enumerable: false,
configurable: true,
get() {
return includedValues[fieldName];
},
});
}
return Object.create(prototype);
}
function buildLocalDateKey(dateValue) {
const year = String(dateValue.getFullYear());
const month = String(dateValue.getMonth() + 1).padStart(2, '0');
const day = String(dateValue.getDate()).padStart(2, '0');
return `${year}${month}${day}`;
}
async function withFixedDate(fixedDate, handler) {
const OriginalDate = Date;
const fixedTime = fixedDate.getTime();
class FixedDate extends OriginalDate {
constructor(...args) {
if (args.length === 0) {
super(fixedTime);
return;
}
super(...args);
}
static now() {
return fixedTime;
}
}
Object.setPrototypeOf(FixedDate, OriginalDate);
FixedDate.parse = OriginalDate.parse.bind(OriginalDate);
FixedDate.UTC = OriginalDate.UTC.bind(OriginalDate);
global.Date = FixedDate;
try {
return await handler();
} finally {
global.Date = OriginalDate;
}
}
function createScheduleHarness(options = {}) {
const noticePayloads = [];
const cacheWrites = [];
const cacheStore = new Map(Object.entries(options.cacheStore || {}));
const ctx = {
app: {
_noticeStockRemainingRunning: false,
Sequelize: {
Op: {
gt: Symbol('gt'),
in: Symbol('in'),
ne: Symbol('ne'),
lte: Symbol('lte'),
},
},
async getCacheAsync(cacheKey) {
return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null;
},
async setCacheAsync(cacheKey, data, ttl) {
cacheWrites.push({ cacheKey, data, ttl });
cacheStore.set(cacheKey, data);
},
formatDate(dateValue) {
return dateValue.toISOString();
},
},
logger: createLogger(),
model: {
StockWarehouse: {
async findAll() {
return options.stockRows || [];
},
},
Storage: {
async findAll() {
return options.storageRows || [];
},
},
LocationSpace: {},
},
service: {
systems: {
notice: {
async send(payload) {
noticePayloads.push(payload);
if (typeof options.sendHandler === 'function') {
return await options.sendHandler(payload);
}
return {
success: true,
};
},
},
},
},
};
if (options.useNoticeIndexSend) {
delete ctx.service.systems.notice.send;
ctx.service.systems.notice.index = {
async send(payload) {
noticePayloads.push(payload);
if (typeof options.sendHandler === 'function') {
return await options.sendHandler(payload);
}
return {
success: true,
};
},
};
}
return {
ctx,
noticePayloads,
cacheWrites,
cacheStore,
};
}
describe('test/app/schedule/notice_stock_remaining.test.js', () => {
it('should ignore legacy global cache and write back stock-day cache keys', async () => {
const fixedDate = new Date(2026, 3, 14, 9, 0, 0);
const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({
cacheStore: {
[LEGACY_CACHE_KEY]: [ 'stock:2001' ],
},
stockRows: [
{
id: 2001,
item_code: 'SKU-2001',
item_name: '测试商品A',
store_id: 10,
warehouse_id: 20,
remaining_threshold_days: 7,
},
],
storageRows: [
{
id: 9001,
stock_id: 2001,
batch_no: 'BATCH-1',
warehouse_id: 20,
store_id: 10,
quantity: 5,
available_quantity: 5,
expiry_date: new Date(2026, 3, 16, 9, 0, 0),
inbound_time: new Date(2026, 3, 13, 9, 0, 0),
is_enabled: 1,
delete_at: null,
space: {
space_code: 'A-01',
custom_name: '一号位',
},
},
{
id: 9002,
stock_id: 2001,
batch_no: 'BATCH-2',
warehouse_id: 20,
store_id: 10,
quantity: 8,
available_quantity: 8,
expiry_date: new Date(2026, 3, 17, 9, 0, 0),
inbound_time: new Date(2026, 3, 12, 9, 0, 0),
is_enabled: 1,
delete_at: null,
space: {
space_code: 'A-02',
custom_name: '二号位',
},
},
],
});
await withFixedDate(fixedDate, async () => {
await schedule.task(ctx);
});
const dateKey = buildLocalDateKey(fixedDate);
const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`;
assert.equal(noticePayloads.length, 1);
assert.equal(noticePayloads[0].businessId, 2001);
assert.equal(noticePayloads[0].metadata.businessId, 2001);
assert.equal(noticePayloads[0].metadata.stockId, 2001);
assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001');
assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey);
assert.equal(cacheWrites.length, 1);
assert.equal(cacheWrites[0].cacheKey, expectedCacheKey);
assert.deepEqual(cacheWrites[0].data, {
notifiedAt: fixedDate.toISOString(),
stockId: 2001,
notifyKey: 'stock:2001',
});
assert.equal(cacheWrites[0].ttl, 24 * 60 * 60);
assert.equal(ctx.app._noticeStockRemainingRunning, false);
});
it('should keep same-day dedupe per stock without extending other stocks', async () => {
const fixedDate = new Date(2026, 3, 14, 9, 0, 0);
const dateKey = buildLocalDateKey(fixedDate);
const cachedStockKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`;
const otherStockKey = `${CACHE_KEY_PREFIX}:stock:2002:${dateKey}`;
const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({
cacheStore: {
[cachedStockKey]: {
notifiedAt: fixedDate.toISOString(),
stockId: 2001,
notifyKey: 'stock:2001',
},
},
stockRows: [
{
id: 2001,
item_code: 'SKU-2001',
item_name: '测试商品A',
store_id: 10,
warehouse_id: 20,
remaining_threshold_days: 7,
},
{
id: 2002,
item_code: 'SKU-2002',
item_name: '测试商品B',
store_id: 10,
warehouse_id: 20,
remaining_threshold_days: 7,
},
],
storageRows: [
createSequelizeInstanceLikeRecord(
{
id: 9001,
stock_id: 2001,
batch_no: 'BATCH-1',
warehouse_id: 20,
store_id: 10,
quantity: 5,
available_quantity: 5,
expiry_date: new Date(2026, 3, 16, 9, 0, 0),
inbound_time: new Date(2026, 3, 13, 9, 0, 0),
is_enabled: 1,
delete_at: null,
},
{
space: createSequelizeInstanceLikeRecord({
space_code: 'A-01',
custom_name: '一号位',
}),
}
),
createSequelizeInstanceLikeRecord(
{
id: 9002,
stock_id: 2002,
batch_no: 'BATCH-2',
warehouse_id: 20,
store_id: 10,
quantity: 6,
available_quantity: 6,
expiry_date: new Date(2026, 3, 16, 9, 0, 0),
inbound_time: new Date(2026, 3, 13, 9, 0, 0),
is_enabled: 1,
delete_at: null,
},
{
space: createSequelizeInstanceLikeRecord({
space_code: 'B-01',
custom_name: '二号位',
}),
}
),
],
});
await withFixedDate(fixedDate, async () => {
await schedule.task(ctx);
});
assert.equal(noticePayloads.length, 1);
assert.equal(noticePayloads[0].businessId, 2002);
assert.equal(noticePayloads[0].metadata.stockId, 2002);
assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2002');
assert.equal(noticePayloads[0].metadata.cacheKey, otherStockKey);
assert.equal(cacheWrites.length, 1);
assert.equal(cacheWrites[0].cacheKey, otherStockKey);
assert.equal(ctx.app._noticeStockRemainingRunning, false);
});
it('should keep retrying when notice send reports failure', async () => {
const fixedDate = new Date(2026, 3, 14, 9, 0, 0);
const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({
stockRows: [
{
id: 2001,
item_code: 'SKU-2001',
item_name: '测试商品A',
store_id: 10,
warehouse_id: 20,
remaining_threshold_days: 7,
},
],
storageRows: [
{
id: 9001,
stock_id: 2001,
batch_no: 'BATCH-1',
warehouse_id: 20,
store_id: 10,
quantity: 5,
available_quantity: 5,
expiry_date: new Date(2026, 3, 16, 9, 0, 0),
inbound_time: new Date(2026, 3, 13, 9, 0, 0),
is_enabled: 1,
delete_at: null,
space: {
space_code: 'A-01',
custom_name: '一号位',
},
},
],
sendHandler() {
return {
success: false,
};
},
});
await withFixedDate(fixedDate, async () => {
await schedule.task(ctx);
});
const dateKey = buildLocalDateKey(fixedDate);
const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`;
assert.equal(noticePayloads.length, 1);
assert.equal(cacheWrites.length, 0);
assert.equal(ctx.app._noticeStockRemainingRunning, false);
assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey);
});
it('should fallback to notice.index.send when notice.send is missing', async () => {
const fixedDate = new Date(2026, 3, 14, 9, 0, 0);
const { ctx, noticePayloads } = createScheduleHarness({
useNoticeIndexSend: true,
stockRows: [
{
id: 2001,
item_code: 'SKU-2001',
item_name: '测试商品A',
store_id: 10,
warehouse_id: 20,
remaining_threshold_days: 7,
},
],
storageRows: [
{
id: 9001,
stock_id: 2001,
batch_no: 'BATCH-1',
warehouse_id: 20,
store_id: 10,
quantity: 5,
available_quantity: 5,
expiry_date: new Date(2026, 3, 16, 9, 0, 0),
inbound_time: new Date(2026, 3, 13, 9, 0, 0),
is_enabled: 1,
delete_at: null,
space: {
space_code: 'A-01',
custom_name: '一号位',
},
},
],
});
await withFixedDate(fixedDate, async () => {
await schedule.task(ctx);
});
assert.equal(noticePayloads.length, 1);
assert.equal(noticePayloads[0].businessId, 2001);
assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001');
assert.equal(ctx.app._noticeStockRemainingRunning, false);
});
});