103 lines
2.8 KiB
JavaScript
103 lines
2.8 KiB
JavaScript
const mysql = require('mysql2/promise');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
|
|
|
|
const dbConfig = {
|
|
host: process.env.DB_HOST,
|
|
user: process.env.DB_USER,
|
|
password: process.env.DB_PASSWORD,
|
|
database: process.env.DB_NAME,
|
|
multipleStatements: true
|
|
};
|
|
|
|
function outputProgress(data) {
|
|
console.log(JSON.stringify(data));
|
|
}
|
|
|
|
// Explicitly define all metrics-related tables
|
|
const METRICS_TABLES = [
|
|
'brand_metrics',
|
|
'brand_time_metrics',
|
|
'category_forecasts',
|
|
'category_metrics',
|
|
'category_sales_metrics',
|
|
'category_time_metrics',
|
|
'product_metrics',
|
|
'product_time_aggregates',
|
|
'sales_forecasts',
|
|
'sales_seasonality',
|
|
'temp_purchase_metrics',
|
|
'temp_sales_metrics',
|
|
'vendor_metrics', //before vendor_details for foreign key
|
|
'vendor_time_metrics', //before vendor_details for foreign key
|
|
'vendor_details'
|
|
];
|
|
|
|
// Config tables that must exist
|
|
const CONFIG_TABLES = [
|
|
'stock_thresholds',
|
|
'lead_time_thresholds',
|
|
'sales_velocity_config',
|
|
'abc_classification_config',
|
|
'safety_stock_config',
|
|
'turnover_config'
|
|
];
|
|
|
|
// Core tables that must exist
|
|
const REQUIRED_CORE_TABLES = [
|
|
'products',
|
|
'orders',
|
|
'purchase_orders'
|
|
];
|
|
|
|
async function resetMetrics() {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
await connection.beginTransaction();
|
|
|
|
// Drop all metrics tables
|
|
for (const table of METRICS_TABLES) {
|
|
console.log(`Dropping table: ${table}`);
|
|
try {
|
|
await connection.query(`DROP TABLE IF EXISTS ${table}`);
|
|
console.log(`Successfully dropped: ${table}`);
|
|
} catch (err) {
|
|
console.error(`Error dropping ${table}:`, err.message);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
// Recreate all metrics tables from schema
|
|
const schemaSQL = fs.readFileSync(path.resolve(__dirname, '../db/metrics-schema.sql'), 'utf8');
|
|
await connection.query(schemaSQL);
|
|
console.log('All metrics tables recreated successfully');
|
|
|
|
await connection.commit();
|
|
console.log('All metrics tables reset successfully');
|
|
} catch (error) {
|
|
if (connection) {
|
|
await connection.rollback();
|
|
}
|
|
console.error('Error resetting metrics:', error);
|
|
throw error;
|
|
} finally {
|
|
if (connection) {
|
|
await connection.end();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Export if required as a module
|
|
if (typeof module !== 'undefined' && module.exports) {
|
|
module.exports = resetMetrics;
|
|
}
|
|
|
|
// Run if called from command line
|
|
if (require.main === module) {
|
|
resetMetrics().catch(error => {
|
|
console.error('Error:', error);
|
|
process.exit(1);
|
|
});
|
|
}
|