Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | const csv = require('csv-parser'); const fs = require('fs'); const logger = require('../utils/logger'); class DynamicImportService { constructor(databaseService) { this.db = databaseService; } // Analyze CSV structure and adapt database accordingly async analyzeAndImportCSV(filePath, options = {}) { try { logger.info('Starting dynamic CSV analysis and import'); // Step 1: Analyze CSV structure const analysis = await this.analyzeCSVStructure(filePath); logger.info('CSV analysis complete:', analysis.summary); // Step 2: Ensure database tables exist and have required columns await this.ensureDatabaseStructure(analysis); // Step 3: Import data with dynamic mapping const importResult = await this.importWithDynamicMapping(filePath, analysis); return { success: true, analysis: analysis.summary, importResult, timestamp: new Date().toISOString() }; } catch (error) { logger.error('Error in dynamic CSV import:', error); throw error; } } // Analyze CSV file structure to understand columns and data types async analyzeCSVStructure(filePath) { return new Promise((resolve, reject) => { const headers = []; const sampleData = []; const columnTypes = {}; const categories = new Set(); const suppliers = new Set(); let isFirstRow = true; let rowCount = 0; fs.createReadStream(filePath) .pipe(csv()) .on('headers', (headerList) => { headers.push(...headerList); logger.info('Detected CSV headers:', headerList); }) .on('data', (data) => { rowCount++; // Store sample data for analysis (first 10 rows) if (sampleData.length < 10) { sampleData.push(data); } // Analyze column types Object.keys(data).forEach(key => { if (!columnTypes[key]) { columnTypes[key] = { numeric: 0, text: 0, total: 0 }; } columnTypes[key].total++; const value = data[key]?.toString().trim(); if (value) { // Check if it's a price/numeric value const numericValue = parseFloat(value.replace(/[^\d.,]/g, '').replace(',', '.')); if (!isNaN(numericValue) && value.match(/[\d.,]/)) { columnTypes[key].numeric++; } else { columnTypes[key].text++; } // Collect categories and suppliers if (key.toLowerCase().includes('kategori') || key.toLowerCase().includes('category')) { categories.add(value); } if (key.toLowerCase().includes('leverandør') || key.toLowerCase().includes('supplier')) { suppliers.add(value); } } }); }) .on('end', () => { // Determine column types based on analysis const detectedTypes = {}; Object.keys(columnTypes).forEach(col => { const stats = columnTypes[col]; const colName = col.toLowerCase(); // Force certain columns to be TEXT regardless of content if (colName.includes('beskrivelse') || colName.includes('description') || colName.includes('navn') || colName.includes('name') || colName.includes('note') || colName.includes('kommentar') || colName.includes('varenummer') || colName.includes('sku') || colName.includes('kvalitet') || colName.includes('quality')) { detectedTypes[col] = 'TEXT'; } // Force price columns to be DECIMAL else if (colName.includes('pris') || colName.includes('price') || colName.includes('enhedspris')) { detectedTypes[col] = 'DECIMAL(10,2)'; } // Force integer columns for quantities else if (colName.includes('antal') || colName.includes('quantity') || colName.includes('lager') || colName.includes('stock')) { detectedTypes[col] = 'INT'; } // Auto-detect based on data else if (stats.numeric > stats.text && stats.numeric > 0) { detectedTypes[col] = 'DECIMAL(10,2)'; } else if (stats.total > 0) { detectedTypes[col] = 'TEXT'; } }); resolve({ headers, sampleData, rowCount, detectedTypes, categories: Array.from(categories), suppliers: Array.from(suppliers), summary: { totalRows: rowCount, columns: headers.length, detectedCategories: categories.size, detectedSuppliers: suppliers.size } }); }) .on('error', reject); }); } // Ensure database has the required structure for the CSV data async ensureDatabaseStructure(analysis) { try { logger.info('Ensuring database structure supports CSV data'); // Create materials table if it doesn't exist await this.ensureMaterialsTable(analysis); // Create categories table and entries await this.ensureCategories(analysis.categories); // Create suppliers table and entries await this.ensureSuppliers(analysis.suppliers); // Add any missing columns to existing tables await this.ensureMaterialColumns(analysis); } catch (error) { logger.error('Error ensuring database structure:', error); throw error; } } async ensureMaterialsTable(analysis) { try { // Check if materials table exists with flexible structure const tableExists = await this.db.query(` SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'dynamic_materials' `); if (tableExists[0].count === 0) { logger.info('Creating dynamic_materials table'); let createTableSQL = ` CREATE TABLE dynamic_materials ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, category VARCHAR(100), supplier VARCHAR(100), price DECIMAL(10,2), unit VARCHAR(50) DEFAULT 'stk', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP `; // Add columns based on detected headers analysis.headers.forEach(header => { const columnName = this.sanitizeColumnName(header); const columnType = analysis.detectedTypes[header] || 'TEXT'; if (!['id', 'name', 'category', 'supplier', 'price', 'unit', 'created_at', 'updated_at'].includes(columnName)) { createTableSQL += `,\n ${columnName} ${columnType}`; } }); createTableSQL += '\n )'; await this.db.query(createTableSQL); logger.info('Dynamic materials table created successfully'); } } catch (error) { logger.error('Error ensuring materials table:', error); throw error; } } async ensureCategories(categories) { try { // Create categories table if it doesn't exist await this.db.query(` CREATE TABLE IF NOT EXISTS material_categories ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) UNIQUE NOT NULL, description TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // Insert new categories for (const category of categories) { try { await this.db.query( 'INSERT IGNORE INTO material_categories (name) VALUES (?)', [category] ); } catch (error) { logger.warn('Could not insert category:', category, error.message); } } logger.info(`Ensured ${categories.length} categories exist`); } catch (error) { logger.error('Error ensuring categories:', error); throw error; } } async ensureSuppliers(suppliers) { try { // Create suppliers table if it doesn't exist await this.db.query(` CREATE TABLE IF NOT EXISTS suppliers ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) UNIQUE NOT NULL, contact_email VARCHAR(255), contact_phone VARCHAR(50), address TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // Insert new suppliers for (const supplier of suppliers) { try { await this.db.query( 'INSERT IGNORE INTO suppliers (name) VALUES (?)', [supplier] ); } catch (error) { logger.warn('Could not insert supplier:', supplier, error.message); } } logger.info(`Ensured ${suppliers.length} suppliers exist`); } catch (error) { logger.error('Error ensuring suppliers:', error); throw error; } } async ensureMaterialColumns(analysis) { try { // Check existing columns in dynamic_materials table const existingColumns = await this.db.query(` SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'dynamic_materials' `); const existingColumnNames = existingColumns.map(row => row.COLUMN_NAME); // Add missing columns for (const header of analysis.headers) { const columnName = this.sanitizeColumnName(header); if (!existingColumnNames.includes(columnName)) { const columnType = analysis.detectedTypes[header] || 'TEXT'; try { await this.db.query(` ALTER TABLE dynamic_materials ADD COLUMN ${columnName} ${columnType} `); logger.info(`Added column: ${columnName} (${columnType})`); } catch (error) { logger.warn(`Could not add column ${columnName}:`, error.message); } } } } catch (error) { logger.error('Error ensuring material columns:', error); throw error; } } // Import CSV data with dynamic column mapping async importWithDynamicMapping(filePath, analysis) { return new Promise((resolve, reject) => { const results = []; const errors = []; const inserted = []; const failed = []; fs.createReadStream(filePath) .pipe(csv()) .on('data', (data) => { try { // Map CSV data to database columns const mappedData = this.mapCSVRowToDatabase(data, analysis); results.push(mappedData); } catch (error) { errors.push(`Error mapping row: ${error.message}`); } }) .on('end', async () => { try { // Bulk insert the mapped data for (const rowData of results) { try { await this.insertDynamicMaterial(rowData); inserted.push(rowData.name || 'Unknown'); } catch (error) { failed.push({ data: rowData, error: error.message }); } } resolve({ totalProcessed: results.length, inserted: inserted.length, failed: failed.length, errors, insertedItems: inserted, failedItems: failed }); } catch (error) { reject(error); } }) .on('error', reject); }); } mapCSVRowToDatabase(csvRow, analysis) { const mapped = {}; Object.keys(csvRow).forEach(csvColumn => { const dbColumn = this.sanitizeColumnName(csvColumn); let value = csvRow[csvColumn]?.toString().trim(); if (value) { // Map common column names to standard database columns const columnMapping = { 'produktnavn': 'name', 'produkt': 'name', 'navn': 'name', 'kategori': 'category', 'category': 'category', 'leverandør': 'supplier', 'leverand_r': 'supplier', // Handle truncated names 'supplier': 'supplier', 'pris': 'price', 'enhedspris': 'price', 'price': 'price', 'enhed': 'unit', 'unit': 'unit' }; const standardColumn = columnMapping[dbColumn] || dbColumn; // Special handling for price columns if (csvColumn.toLowerCase().includes('pris') || csvColumn.toLowerCase().includes('price')) { const numericValue = parseFloat(value.replace(/[^\d.,]/g, '').replace(',', '.')); mapped.price = !isNaN(numericValue) ? numericValue : null; } else { mapped[standardColumn] = value; } } }); // Ensure required fields have values if (!mapped.name && mapped.produktnavn) { mapped.name = mapped.produktnavn; } if (!mapped.category && mapped.kategori) { mapped.category = mapped.kategori; } if (!mapped.supplier && mapped.leverand_r) { mapped.supplier = mapped.leverand_r; } return mapped; } async insertDynamicMaterial(data) { const columns = Object.keys(data).filter(key => data[key] !== null && data[key] !== undefined); const values = columns.map(key => data[key]); const placeholders = columns.map(() => '?').join(', '); const sql = ` INSERT INTO dynamic_materials (${columns.join(', ')}) VALUES (${placeholders}) `; return await this.db.query(sql, values); } sanitizeColumnName(name) { return name .toLowerCase() .replace(/[^a-zA-Z0-9_]/g, '_') .replace(/_{2,}/g, '_') .replace(/^_|_$/g, '') .substring(0, 64); // MySQL column name limit } } module.exports = DynamicImportService; |