Add Olist sync monitor
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
const { createApp } = require('./server');
|
||||
const { initDB } = require('./db');
|
||||
const { OLIST_SYNC_ENABLED, PORT } = require('./config');
|
||||
const { scheduleOlistSync } = require('./services/olistService');
|
||||
const { markInterruptedOlistRuns, scheduleOlistSync } = require('./services/olistService');
|
||||
|
||||
const start = async () => {
|
||||
await initDB();
|
||||
await markInterruptedOlistRuns();
|
||||
|
||||
const app = createApp();
|
||||
if (OLIST_SYNC_ENABLED) scheduleOlistSync();
|
||||
|
||||
@@ -130,6 +130,17 @@ const getProductCacheProgress = async () => {
|
||||
};
|
||||
};
|
||||
|
||||
const markInterruptedOlistRuns = async () => {
|
||||
const result = await pool.query(`
|
||||
UPDATE olist_sync_runs
|
||||
SET status = 'failed',
|
||||
completed_at = CURRENT_TIMESTAMP,
|
||||
error_message = COALESCE(error_message, 'Sincronização interrompida pelo reinício do servidor.')
|
||||
WHERE status = 'running';
|
||||
`);
|
||||
return result.rowCount || 0;
|
||||
};
|
||||
|
||||
const getOlistStatus = async () => {
|
||||
const [connection, runs, productCache] = await Promise.all([getConnection(), listSyncRuns(), getProductCacheProgress()]);
|
||||
return {
|
||||
@@ -372,6 +383,23 @@ const createRun = async ({ trigger, mode }) => {
|
||||
return mapRun(result.rows[0]);
|
||||
};
|
||||
|
||||
const updateRunProgress = async (id, summary) => {
|
||||
const result = await pool.query(`
|
||||
UPDATE olist_sync_runs
|
||||
SET products_scanned = $2,
|
||||
manufactured_products = $3,
|
||||
imported = $4,
|
||||
component_count = $5,
|
||||
reference_count = $6,
|
||||
skipped_reference_count = $7,
|
||||
failed = $8,
|
||||
details = $9::jsonb
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
`, [id, summary.productsScanned, summary.manufacturedProducts, summary.imported, summary.componentCount, summary.referenceCount, summary.skippedReferenceCount, summary.failed, JSON.stringify(summary.details.slice(0, 100))]);
|
||||
return mapRun(result.rows[0]);
|
||||
};
|
||||
|
||||
const finishRun = async (id, summary, error = null) => {
|
||||
const result = await pool.query(`
|
||||
UPDATE olist_sync_runs
|
||||
@@ -454,6 +482,7 @@ const runOlistSync = async ({ trigger = 'manual', fullSync = false } = {}) => {
|
||||
summary.details.push({ productId: product.id, sku: product.sku || '', error: error.message });
|
||||
}
|
||||
}
|
||||
await updateRunProgress(run.id, summary);
|
||||
}
|
||||
return await finishRun(run.id, summary);
|
||||
} catch (error) {
|
||||
@@ -498,6 +527,7 @@ module.exports = {
|
||||
getOlistFrontendRedirect,
|
||||
getOlistStatus,
|
||||
isOlistConfigured,
|
||||
markInterruptedOlistRuns,
|
||||
scheduleOlistSync,
|
||||
startOlistSync
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user