|
|
@ -91,27 +91,54 @@ setInterval(async () => { |
|
|
console.log('检查需要自动下架的商品...'); |
|
|
console.log('检查需要自动下架的商品...'); |
|
|
const connection = await pool.getConnection(); |
|
|
const connection = await pool.getConnection(); |
|
|
|
|
|
|
|
|
// 查找所有状态为published且autoOfflineTime已过的商品
|
|
|
|
|
|
const currentTime = new Date(); |
|
|
const currentTime = new Date(); |
|
|
const [productsToOffline] = await connection.query( |
|
|
|
|
|
'SELECT id FROM products WHERE status = ? AND autoOfflineTime <= ? AND autoOfflineTime IS NOT NULL', |
|
|
// 查找所有状态为published的商品
|
|
|
['published', currentTime] |
|
|
const [publishedProducts] = await connection.query( |
|
|
|
|
|
'SELECT id, autoOfflineTime, autoOfflineHours, created_at, updated_at FROM products WHERE status = ?', |
|
|
|
|
|
['published'] |
|
|
); |
|
|
); |
|
|
|
|
|
|
|
|
|
|
|
const productsToOffline = []; |
|
|
|
|
|
|
|
|
|
|
|
// 检查每个商品是否需要自动下架
|
|
|
|
|
|
for (const product of publishedProducts) { |
|
|
|
|
|
let shouldOffline = false; |
|
|
|
|
|
|
|
|
|
|
|
if (product.autoOfflineTime) { |
|
|
|
|
|
// 情况1:有明确的autoOfflineTime
|
|
|
|
|
|
const autoOfflineTime = new Date(product.autoOfflineTime); |
|
|
|
|
|
if (currentTime >= autoOfflineTime) { |
|
|
|
|
|
shouldOffline = true; |
|
|
|
|
|
} |
|
|
|
|
|
} else if (product.autoOfflineHours && !isNaN(product.autoOfflineHours) && product.autoOfflineHours > 0) { |
|
|
|
|
|
// 情况2:只有autoOfflineHours,计算自动下架时间
|
|
|
|
|
|
const baseTime = product.updated_at ? new Date(product.updated_at) : new Date(product.created_at); |
|
|
|
|
|
const offlineTime = new Date(baseTime.getTime() + product.autoOfflineHours * 60 * 60 * 1000); |
|
|
|
|
|
if (currentTime >= offlineTime) { |
|
|
|
|
|
shouldOffline = true; |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
if (shouldOffline) { |
|
|
|
|
|
productsToOffline.push(product.id); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
if (productsToOffline.length > 0) { |
|
|
if (productsToOffline.length > 0) { |
|
|
console.log(`发现${productsToOffline.length}个商品需要自动下架`); |
|
|
console.log(`发现${productsToOffline.length}个商品需要自动下架`); |
|
|
|
|
|
|
|
|
// 批量更新商品状态为sold_out
|
|
|
// 批量更新商品状态为sold_out
|
|
|
for (const product of productsToOffline) { |
|
|
for (const productId of productsToOffline) { |
|
|
await connection.query( |
|
|
await connection.query( |
|
|
'UPDATE products SET status = ?, label = 1, updated_at = NOW() WHERE id = ?', |
|
|
'UPDATE products SET status = ?, label = 1, updated_at = NOW() WHERE id = ?', |
|
|
['sold_out', product.id] |
|
|
['sold_out', productId] |
|
|
); |
|
|
); |
|
|
|
|
|
|
|
|
// 发送WebSocket消息通知所有客户端
|
|
|
// 发送WebSocket消息通知所有客户端
|
|
|
broadcastMessage({ |
|
|
broadcastMessage({ |
|
|
type: 'supply_status_change', |
|
|
type: 'supply_status_change', |
|
|
supplyId: product.id, |
|
|
supplyId: productId, |
|
|
action: 'unpublish', |
|
|
action: 'unpublish', |
|
|
status: 'sold_out' |
|
|
status: 'sold_out' |
|
|
}); |
|
|
}); |
|
|
|