All files / services databaseCleanupService.js

0% Statements 0/83
0% Branches 0/57
0% Functions 0/8
0% Lines 0/79

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
const databaseService = require('./databaseService');
const openaiService = require('./openaiService');
const logger = require('../utils/logger');
 
class DatabaseCleanupService {
  constructor() {
    this.initialized = false;
  }
 
  async initialize() {
    if (this.initialized) return;
    
    logger.info('Initializing Database Cleanup Service...');
    
    // Make sure database service is initialized
    await databaseService.initialize();
    
    this.initialized = true;
    logger.info('Database Cleanup Service initialized successfully');
  }
 
  /**
   * Clean up all materials in the database using OpenAI classification
   */
  async cleanupMaterials(options = {}) {
    await this.initialize();
    
    const {
      limit = 100,
      onlyInvalid = true,  // Only process materials with poor/missing categories
      dryRun = false,       // If true, don't actually update the database
      materialId = null     // If provided, only process this specific material
    } = options;
 
    logger.info('Starting material cleanup process', { limit, onlyInvalid, dryRun, materialId });
 
    try {
      // Get materials that need cleanup
      let query = `
        SELECT m.id, m.name, m.description, m.category, m.subcategory, m.unit,
               mp.price, mp.currency, s.name as supplier_name
        FROM materials m
        LEFT JOIN material_prices mp ON m.id = mp.material_id AND mp.is_active = TRUE
        LEFT JOIN suppliers s ON m.supplier_id = s.id
      `;
      
      let params = [];
      let whereConditions = [];
      
      if (materialId) {
        whereConditions.push('m.id = ?');
        params.push(materialId);
      } else if (onlyInvalid) {
        whereConditions.push(`(m.category IS NULL OR m.category = '' OR m.category = 'other' 
                             OR m.category = 'materialer' OR m.category = 'Unknown')`);
      }
      
      if (whereConditions.length > 0) {
        query += ' WHERE ' + whereConditions.join(' AND ');
      }
      
      query += ` ORDER BY m.id LIMIT ?`;
      params.push(limit);
 
      const [materials] = await databaseService.pool.execute(query, params);
      
      if (materials.length === 0) {
        logger.info('No materials found that need cleanup');
        return {
          success: true,
          processed: 0,
          updated: 0,
          errors: [],
          message: 'No materials needed cleanup'
        };
      }
 
      logger.info(`Found ${materials.length} materials to process`);
 
      const results = {
        processed: 0,
        updated: 0,
        errors: [],
        details: []
      };
 
      // Process materials in batches to avoid overwhelming OpenAI API
      const batchSize = 5;
      for (let i = 0; i < materials.length; i += batchSize) {
        const batch = materials.slice(i, i + batchSize);
        
        logger.info(`Processing batch ${Math.floor(i/batchSize) + 1}/${Math.ceil(materials.length/batchSize)}`);
        
        for (const material of batch) {
          try {
            results.processed++;
            
            // Create a mock OCR data structure for the existing material
            const mockOcrData = {
              items: [{
                name: material.name,
                description: material.description || '',
                price: parseFloat(material.price) || 0,
                unit: material.unit || 'stk',
                currency: material.currency || 'DKK',
                category: material.category,
                subcategory: material.subcategory
              }],
              supplier: material.supplier_name || 'Unknown',
              document_type: 'material'
            };
 
            // Classify using OpenAI
            const classifiedData = await openaiService.classifyOcrData(mockOcrData, 'material');
            
            if (classifiedData && classifiedData.items && classifiedData.items.length > 0) {
              const classifiedItem = classifiedData.items[0];
              
              // Check if classification improved the data
              const needsUpdate = (
                !material.category || 
                material.category === 'other' || 
                material.category === 'materialer' ||
                material.category === 'Unknown' ||
                classifiedItem.category !== material.category ||
                classifiedItem.subcategory !== material.subcategory ||
                !classifiedItem.is_relevant
              );
 
              if (needsUpdate) {
                const updateData = {
                  id: material.id,
                  oldCategory: material.category,
                  oldSubcategory: material.subcategory,
                  newCategory: classifiedItem.category,
                  newSubcategory: classifiedItem.subcategory,
                  isRelevant: classifiedItem.is_relevant !== false,
                  confidence: classifiedItem.confidence || 0.8
                };
 
                if (!dryRun && classifiedItem.is_relevant !== false) {
                  // Update the material in database
                  const updateQuery = `
                    UPDATE materials 
                    SET category = ?, subcategory = ?, updated_at = NOW()
                    WHERE id = ?
                  `;
                  
                  await databaseService.pool.execute(updateQuery, [
                    classifiedItem.category,
                    classifiedItem.subcategory,
                    material.id
                  ]);
                  
                  results.updated++;
                  logger.info('Material updated', {
                    id: material.id,
                    name: material.name,
                    oldCategory: material.category,
                    newCategory: classifiedItem.category
                  });
                } else if (!dryRun && classifiedItem.is_relevant === false) {
                  // Mark irrelevant materials for potential deletion
                  const updateQuery = `
                    UPDATE materials 
                    SET category = 'IRRELEVANT', subcategory = 'FLAGGED_FOR_DELETION', updated_at = NOW()
                    WHERE id = ?
                  `;
                  
                  await databaseService.pool.execute(updateQuery, [material.id]);
                  
                  logger.warn('Material marked as irrelevant', {
                    id: material.id,
                    name: material.name
                  });
                }
 
                results.details.push(updateData);
              }
            } else {
              logger.warn('OpenAI classification failed for material', {
                id: material.id,
                name: material.name
              });
            }
 
            // Small delay to respect API rate limits
            await new Promise(resolve => setTimeout(resolve, 200));
            
          } catch (error) {
            results.errors.push({
              materialId: material.id,
              materialName: material.name,
              error: error.message
            });
            
            logger.error('Error processing material', {
              id: material.id,
              name: material.name,
              error: error.message
            });
          }
        }
        
        // Longer delay between batches
        if (i + batchSize < materials.length) {
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
 
      logger.info('Material cleanup completed', {
        processed: results.processed,
        updated: results.updated,
        errors: results.errors.length,
        dryRun
      });
 
      return {
        success: true,
        ...results,
        message: dryRun ? 
          `Dry run completed: ${results.updated} materials would be updated` :
          `Cleanup completed: ${results.updated} materials updated`
      };
 
    } catch (error) {
      logger.error('Error in material cleanup process:', error);
      throw error;
    }
  }
 
  /**
   * Remove materials that are marked as irrelevant
   */
  async removeIrrelevantMaterials(confirmDelete = false) {
    await this.initialize();
 
    if (!confirmDelete) {
      // First, show what would be deleted
      const [materials] = await databaseService.pool.execute(`
        SELECT id, name, category, subcategory 
        FROM materials 
        WHERE category = 'IRRELEVANT' AND subcategory = 'FLAGGED_FOR_DELETION'
      `);
 
      return {
        success: true,
        action: 'preview',
        materialsToDelete: materials,
        message: `Found ${materials.length} materials flagged for deletion. Call with confirmDelete=true to proceed.`
      };
    }
 
    // Actually delete the materials
    const deleteResult = await databaseService.pool.execute(`
      DELETE FROM materials 
      WHERE category = 'IRRELEVANT' AND subcategory = 'FLAGGED_FOR_DELETION'
    `);
 
    logger.info('Irrelevant materials removed', {
      deletedCount: deleteResult[0].affectedRows
    });
 
    return {
      success: true,
      action: 'deleted',
      deletedCount: deleteResult[0].affectedRows,
      message: `Deleted ${deleteResult[0].affectedRows} irrelevant materials`
    };
  }
 
  /**
   * Get statistics about material categories in the database
   */
  async getMaterialCategoryStats() {
    await this.initialize();
 
    const [categoryStats] = await databaseService.pool.execute(`
      SELECT 
        category,
        COUNT(*) as count,
        COUNT(CASE WHEN subcategory IS NOT NULL AND subcategory != '' THEN 1 END) as with_subcategory
      FROM materials 
      GROUP BY category 
      ORDER BY count DESC
    `);
 
    const [totalCount] = await databaseService.pool.execute(`
      SELECT COUNT(*) as total FROM materials
    `);
 
    const [problemMaterials] = await databaseService.pool.execute(`
      SELECT COUNT(*) as problem_count 
      FROM materials 
      WHERE category IS NULL OR category = '' OR category = 'other' 
         OR category = 'materialer' OR category = 'Unknown'
    `);
 
    return {
      success: true,
      totalMaterials: totalCount[0].total,
      problemMaterials: problemMaterials[0].problem_count,
      categoryBreakdown: categoryStats,
      cleanupRecommended: problemMaterials[0].problem_count > 0
    };
  }
 
  /**
   * Preview what cleanup would do without making changes
   */
  async previewCleanup(limit = 10) {
    return this.cleanupMaterials({ 
      limit, 
      onlyInvalid: true, 
      dryRun: true 
    });
  }
}
 
module.exports = new DatabaseCleanupService();