Files
2025-10-30 18:28:58 +00:00

151 lines
4.7 KiB
JavaScript

#!/usr/bin/env node
const axios = require('axios');
const mysql = require('mysql2/promise');
// Load environment
require('dotenv').config({ path: '.env.ordrestyring' });
const API_BASE = 'https://v2.api.ordrestyring.dk';
const TOKEN = process.env.ORDRESTYRING_TOKEN;
const DB_CONFIG = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT) || 3306,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
};
const REMAINING_ENDPOINTS = [
{ endpoint: '/debtors', table: 'debtors', limit: 1335 },
{ endpoint: '/debtor-invoices', table: 'debtor_invoices', limit: 2441 }
];
async function makeAPIRequest(endpoint, limit) {
try {
const config = {
method: 'GET',
url: `${API_BASE}${endpoint}`,
auth: {
username: TOKEN,
password: 'x'
},
params: {
pagesize: limit
}
};
const response = await axios(config);
const dataKeys = Object.keys(response.data);
const isArrayLike = dataKeys.length > 0 && dataKeys.every(key => !isNaN(key));
if (isArrayLike) {
return Object.values(response.data);
}
return [];
} catch (error) {
console.error(`❌ Error fetching ${endpoint}:`, error.message);
return [];
}
}
async function insertRecords(connection, tableName, records) {
if (records.length === 0) return 0;
const [columns] = await connection.execute(`SHOW COLUMNS FROM ${tableName}`);
const columnNames = columns.map(col => col.Field).filter(name => name !== 'id');
let insertedCount = 0;
let errorCount = 0;
for (const record of records) {
try {
const values = columnNames.map(col => {
let value = record[col];
if (value === null || value === undefined || value === '') {
return null;
}
if (Array.isArray(value)) {
return JSON.stringify(value);
}
if (typeof value === 'boolean' || typeof value === 'number') {
return value;
}
return String(value);
});
const placeholders = columnNames.map(() => '?').join(', ');
const updatePart = columnNames.map(col => `${col} = VALUES(${col})`).join(', ');
const query = `INSERT INTO ${tableName} (${columnNames.join(', ')}) VALUES (${placeholders})
ON DUPLICATE KEY UPDATE ${updatePart}`;
await connection.execute(query, values);
insertedCount++;
} catch (error) {
errorCount++;
if (errorCount <= 2) {
console.error(`❌ Error inserting into ${tableName}:`, error.message);
}
}
}
if (errorCount > 2) {
console.log(` ... and ${errorCount - 2} more errors`);
}
return insertedCount;
}
async function completeImport() {
console.log('📦 Completing Ordrestyring Import - Remaining Data');
console.log('================================================');
let connection;
try {
connection = await mysql.createConnection(DB_CONFIG);
console.log('✅ Database connection established');
for (const { endpoint, table, limit } of REMAINING_ENDPOINTS) {
console.log(`\n📊 Importing: ${endpoint} -> ${table}`);
const records = await makeAPIRequest(endpoint, limit);
console.log(`📥 Fetched ${records.length} records`);
if (records.length > 0) {
const insertedCount = await insertRecords(connection, table, records);
console.log(`✅ Inserted ${insertedCount}/${records.length} records`);
}
}
// Final count
console.log('\n🎉 Complete Import Finished!');
console.log('\n📊 Final Database Summary:');
const tables = ['cases', 'case_materials', 'hours', 'debtors', 'debtor_invoices', 'users', 'case_types', 'case_statuses', 'employee_types'];
for (const table of tables) {
const [rows] = await connection.execute(`SELECT COUNT(*) as count FROM ${table}`);
console.log(` ${table}: ${rows[0].count} records`);
}
} catch (error) {
console.error('❌ Import failed:', error);
} finally {
if (connection) {
await connection.end();
}
}
}
completeImport().catch(console.error);