#!/usr/bin/env node require('dotenv').config(); const dayjs = require('dayjs'); const database = require('../src/config/database'); const cloudDb = require('../src/config/cloudDatabase'); const redis = require('../src/config/redis'); const { refreshCourier, refreshAllCache } = require('../src/jobs/dailyRefresh'); function isDateString(value) { return /^\d{4}-\d{2}-\d{2}$/.test(value) && dayjs(value).format('YYYY-MM-DD') === value; } async function backfillRange(startDate, endDate) { const start = dayjs(startDate); const end = dayjs(endDate); const totalDays = end.diff(start, 'day') + 1; if (totalDays <= 0) { throw new Error(`Invalid date range: ${startDate} -> ${endDate}`); } for (let offset = 0; offset < totalDays; offset += 1) { const statDate = start.add(offset, 'day').format('YYYY-MM-DD'); const dayStart = Date.now(); console.log(`[logistics-damage-backfill] start ${statDate} (${offset + 1}/${totalDays})`); await refreshCourier(statDate); console.log(`[logistics-damage-backfill] done ${statDate} elapsed=${Date.now() - dayStart}ms`); } } async function main() { const [startDate, endDate = startDate] = process.argv.slice(2); if (!isDateString(startDate) || !isDateString(endDate)) { throw new Error('Usage: node backend/scripts/backfillLogisticsDamageHistory.js [YYYY-MM-DD]'); } console.log(`[logistics-damage-backfill] range ${startDate} -> ${endDate}`); try { await backfillRange(startDate, endDate); try { await refreshAllCache(); console.log('[logistics-damage-backfill] cache refresh done'); } catch (error) { console.warn(`[logistics-damage-backfill] cache refresh skipped: ${error.message}`); } } finally { await Promise.allSettled([ cloudDb.close(), database.close(), redis.close(), ]); } } main().catch((error) => { console.error('[logistics-damage-backfill] failed'); console.error(error); process.exit(1); });