- Remove process.exit(1) that caused PM2 to restart in an infinite loop - Fix && false bug that forced Turn14 token refresh on every run - Remove global SHOP/ACCESS_TOKEN to eliminate race conditions - Make shop loop sequential (for...of + await) to prevent Turn14 429s - Add early return when Turn14 credentials are missing for a shop - Guard non-JSON Turn14 responses (429 plain text) before calling .json() - Ensure logs/ and exports/ dirs exist before writing - Pass shop/accessToken as params to all helper functions Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
62 lines
2.0 KiB
JavaScript
Executable File
62 lines
2.0 KiB
JavaScript
Executable File
const fs = require('fs');
|
|
const path = require('path');
|
|
const { syncTurn14Inventory } = require('./InventorySync');
|
|
|
|
const filePath = path.join(__dirname, '..', 'data', 'tokens.json');
|
|
const logDir = path.join(__dirname, '..', 'logs');
|
|
const logFilePath = path.join(logDir, 'BulkInventorySyncJob.log');
|
|
|
|
function ensureDir(dir) {
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
}
|
|
|
|
function logStep(step, message) {
|
|
ensureDir(logDir);
|
|
const logMessage = `[${new Date().toISOString()}] [${step}] ${message}`;
|
|
console.log(logMessage);
|
|
fs.appendFileSync(logFilePath, logMessage + '\n', 'utf8');
|
|
}
|
|
|
|
async function runBulkInventorySyncJob() {
|
|
logStep('Bulk Caller Job', 'JOB STARTED');
|
|
|
|
const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
const shops = Object.entries(jsonData);
|
|
|
|
// Process shops sequentially to avoid hammering Turn14 with parallel requests
|
|
for (const [shopDomain, details] of shops) {
|
|
const SHOP = shopDomain.trim();
|
|
const ACCESS_TOKEN = details.accessToken;
|
|
const fulfillmentServiceTokens = details.fulfillmentService || {};
|
|
const FULFILLMENTSERVICEID = fulfillmentServiceTokens.id || null;
|
|
const LOCATIONID = details.locationId || null;
|
|
|
|
logStep('Bulk Caller Job', `Syncing inventory for: ${SHOP} (locationId: ${LOCATIONID})`);
|
|
|
|
try {
|
|
await syncTurn14Inventory(SHOP, ACCESS_TOKEN, FULFILLMENTSERVICEID, LOCATIONID);
|
|
} catch (err) {
|
|
logStep('Bulk Caller Job', `❌ Unexpected error for ${SHOP}: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
logStep('Bulk Caller Job', 'JOB COMPLETED');
|
|
}
|
|
|
|
// Schedule: every 3 hours and 50 minutes
|
|
const INTERVAL_MS = (3 * 60 + 50) * 60 * 1000;
|
|
|
|
function scheduleEvery3Hrs50Mins() {
|
|
runBulkInventorySyncJob().catch(err => {
|
|
console.error('[Scheduler] Unhandled error in job run:', err.message);
|
|
});
|
|
|
|
setInterval(() => {
|
|
runBulkInventorySyncJob().catch(err => {
|
|
console.error('[Scheduler] Unhandled error in job run:', err.message);
|
|
});
|
|
}, INTERVAL_MS);
|
|
}
|
|
|
|
scheduleEvery3Hrs50Mins();
|