All files / services documentParserService.js

0% Statements 0/118
0% Branches 0/96
0% Functions 0/13
0% Lines 0/115

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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
const OpenAI = require('openai');
const pdf = require('pdf-parse');
const logger = require('../utils/logger');
const databaseService = require('./databaseService');
const ocrService = require('./ocrService');
const openaiService = require('./openaiService');
 
class DocumentParserService {
  constructor() {
    this.openai = null;
    this.initialized = false;
  }
 
  async initialize() {
    try {
      const apiKey = process.env.OPENAI_API_KEY;
      if (!apiKey) {
        throw new Error('OpenAI API key not found in environment variables');
      }
 
      this.openai = new OpenAI({
        apiKey: apiKey,
        timeout: 60000, // 60 seconds timeout for document parsing
        maxRetries: 2
      });
 
      this.initialized = true;
      logger.info('Document parser service initialized successfully');
    } catch (error) {
      logger.error('Failed to initialize document parser service:', error);
      throw error;
    }
  }
 
  async parseDocument(documentContent, documentType, filename) {
    if (!this.initialized) {
      await this.initialize();
    }
 
    const systemPrompt = `Du er en AI-assistent der parser tilbudsdokumenter for et tømrerfirma.
 
Din opgave er at uddrage struktureret data fra uploadede dokumenter (materialer eller timeløn).
 
For MATERIALER skal du uddrage:
- Leverandør navn
- Varenummer/SKU/Artikelnummer (hvis tilgængelig)
- Produktnavn/beskrivelse
- Beskrivelse
- Enhed (m², m³, stk, kg, løbende meter, etc.)
- Pakningsstørrelse (hvis relevant)
- Pris per enhed/pakke (ekskl. moms hvis angivet)
- Valuta (standard DKK)
- Gyldighedsdato(er)
- Region (hvis angivet)
- Kategori (fx gulv, tag, vinduer, døre, isolering, træ, skruer, beslag)
- Underkategori (fx klik, parket, tegl, træplanker)
 
For TIMELØN skal du uddrage:
- Rolle (svend, mester, lærling, etc.)
- Arbejdsbeskrivelse
- Sats per time
- Valuta (standard DKK)
- Gyldighedsdato(er)
- Region (hvis angivet)
- Kategori/type arbejde
 
VIGTIGE REGLER for parsing:
- Spring over overskrifter, kontaktinfo, og administrative afsnit
- Fokuser kun på produktlinjer med priser
- Ignorer tomme linjer og formateringstekst
- Hvis der er både enhedspris og pakningspris, brug enhedsprisen
- Konverter alle enheder til standard enheder (m², m³, m, kg, stk)
- Hvis prisen er inkl. moms, træk 25% fra for at få ekskl. moms prisen
- Genkend common tømrer materialer: træ, skruer, beslag, isolering, plader, etc.
 
Normaliser enheder til standard enheder:
- Areal: m²
- Volumen: m³
- Længde: m
- Vægt: kg
- Antal: stk
- Løbende: løbm eller m
 
Return data som JSON array med objekter for hver position.
Angiv en confidence score (0.0-1.0) for hver post baseret på hvor sikker du er på data.
Hvis information mangler eller er usikker, marker confidence < 0.8.
 
Eksempel format:
{
  "document_type": "material",
  "supplier": "Leverandør navn",
  "document_date": "2024-09-14",
  "valid_until": "2024-12-31",
  "items": [
    {
      "sku": "ABC123",
      "name": "Træplanker 28x145mm behandlet",
      "description": "Imprægnareret træplanker til udendørs brug",
      "unit": "m",
      "package_size": null,
      "price": 89.50,
      "currency": "DKK",
      "valid_from": "2024-01-01",
      "valid_to": "2024-12-31",
      "region": "Danmark",
      "category": "træ",
      "subcategory": "planker",
      "confidence": 0.95
    }
  ]
}`;
 
    const userPrompt = `Parse følgende ${documentType} dokument og uddrag alle relevante priser og data.
 
FOKUSER KUN PÅ produktlinjer med priser - ignorer overskrifter, kontaktinfo, og andre administrative dele.
 
Filnavn: ${filename}
 
Dokument indhold:
${documentContent}
 
Return struktureret JSON data som beskrevet i system prompt. Vær meget omhyggelig med at genkende og parse kun faktiske produktlinjer med priser.`;
 
    try {
      const completion = await this.openai.chat.completions.create({
        model: 'gpt-4',
        messages: [
          { role: 'system', content: systemPrompt },
          { role: 'user', content: userPrompt }
        ],
        temperature: 0.1, // Low temperature for consistent parsing
        max_tokens: 4000
      });
 
      const parsedContent = completion.choices[0].message.content;
      
      // Try to parse as JSON
      let parsedData;
      try {
        parsedData = JSON.parse(parsedContent);
      } catch (jsonError) {
        // If JSON parsing fails, try to extract JSON from markdown code blocks
        const jsonMatch = parsedContent.match(/```json\n([\s\S]*?)\n```/);
        if (jsonMatch) {
          parsedData = JSON.parse(jsonMatch[1]);
        } else {
          throw new Error('Could not parse AI response as JSON');
        }
      }
 
      logger.info('Document parsed successfully', {
        filename,
        items: parsedData.items?.length || 0,
        tokens: completion.usage.total_tokens
      });
 
      return {
        success: true,
        data: parsedData,
        metadata: {
          tokens: completion.usage.total_tokens,
          model: completion.model,
          timestamp: new Date().toISOString()
        }
      };
 
    } catch (error) {
      logger.error('Error parsing document:', error);
      return {
        success: false,
        error: error.message,
        data: null
      };
    }
  }
 
  async parseDocumentWithOCR(documentContent, documentType, filename) {
    try {
      logger.info('Starting OCR-based document parsing', { filename, documentType });
 
      // First try to extract structured price data directly from OCR text
      const ocrResult = await ocrService.extractPriceDataFromText(documentContent, documentType);
      
      if (ocrResult.success && ocrResult.items.length > 0) {
        logger.info('OCR found structured price data', { 
          items: ocrResult.items.length,
          filename 
        });
 
        return {
          success: true,
          data: {
            document_type: documentType,
            supplier: this.extractSupplierFromOCR(documentContent),
            document_date: new Date().toISOString().split('T')[0],
            items: ocrResult.items,
            source: 'ocr_direct'
          },
          metadata: {
            method: 'ocr_direct',
            timestamp: new Date().toISOString(),
            confidence: this.calculateAverageConfidence(ocrResult.items)
          }
        };
      }
 
      // If OCR direct parsing didn't work well, fallback to AI parsing
      logger.info('OCR direct parsing yielded few results, trying AI parsing', {
        ocrItems: ocrResult.items.length
      });
 
      return await this.parseDocument(documentContent, documentType, filename);
 
    } catch (error) {
      logger.error('Error in OCR-based document parsing:', error);
      // Fallback to regular AI parsing
      return await this.parseDocument(documentContent, documentType, filename);
    }
  }
 
  extractSupplierFromOCR(text) {
    // Look for common supplier patterns in OCR text
    const lines = text.split('\n').slice(0, 10); // Check first 10 lines
    
    const supplierPatterns = [
      /^([A-ZÆØÅ][a-zæøå\s]+(?:A\/S|ApS|I\/S)?)/,
      /leverandør:?\s*([A-ZÆØÅ][a-zæøå\s]+)/i,
      /fra:?\s*([A-ZÆØÅ][a-zæøå\s]+)/i
    ];
 
    for (const line of lines) {
      for (const pattern of supplierPatterns) {
        const match = line.match(pattern);
        if (match && match[1].trim().length > 3) {
          return match[1].trim();
        }
      }
    }
 
    return 'Ukendt leverandør';
  }
 
  calculateAverageConfidence(items) {
    if (!items || items.length === 0) return 0;
    
    const totalConfidence = items.reduce((sum, item) => sum + (item.confidence || 0), 0);
    return totalConfidence / items.length;
  }
 
  detectOCRText(text) {
    // Check for typical OCR artifacts and errors
    const ocrIndicators = [
      /[A-Z]{3,}\s+[A-Z]{3,}/,  // Multiple consecutive uppercase words
      /\d\s+\d\s+\d/,  // Spaced out numbers
      /[a-z]\s+[a-z]\s+[a-z]/,  // Generally spaced text
    ];
 
    // Check if any regex pattern matches OR if it contains OCR error marker
    return ocrIndicators.some(pattern => pattern.test(text)) || text.includes('(OCR fejlede)');
  }
 
  async processAndSaveDocument(documentId, documentContent, documentType, filename) {
    try {
      await databaseService.updateDocumentParseStatus(documentId, 'processing');
 
      // Determine if this looks like OCR text (contains OCR artifacts)
      const looksLikeOCR = this.detectOCRText(documentContent);
      
      let parseResult;
      if (looksLikeOCR) {
        logger.info('Detected OCR text, using OCR-optimized parsing', { filename });
        parseResult = await this.parseDocumentWithOCR(documentContent, documentType, filename);
      } else {
        parseResult = await this.parseDocument(documentContent, documentType, filename);
      }
 
      if (!parseResult.success) {
        await databaseService.updateDocumentParseStatus(documentId, 'failed', {
          error: parseResult.error
        });
        return parseResult;
      }
 
      // NEW: Classify and clean the extracted data using OpenAI
      logger.info('Classifying extracted data with OpenAI', { 
        filename, 
        itemCount: parseResult.data.items?.length || 0 
      });
      
      let classifiedData;
      try {
        classifiedData = await openaiService.classifyOcrData(parseResult.data, documentType);
        
        // If classification failed, fall back to original data but log it
        if (!classifiedData || classifiedData.classification_status === 'failed') {
          logger.warn('OpenAI classification failed, using original data', { 
            filename,
            error: classifiedData?.error 
          });
          classifiedData = parseResult.data;
        } else {
          logger.info('OpenAI classification successful', {
            filename,
            originalItems: parseResult.data.items?.length || 0,
            classifiedItems: classifiedData.items?.length || 0,
            itemsRemoved: classifiedData.items_removed || 0
          });
        }
      } catch (classificationError) {
        logger.warn('OpenAI classification error, using original data:', classificationError);
        classifiedData = parseResult.data;
      }
 
      const savedItems = [];
 
      // Save supplier if it's a material document
      let supplierId = null;
      if (documentType === 'material' && (classifiedData.supplier || parseResult.data.supplier)) {
        try {
          const supplierName = classifiedData.supplier || parseResult.data.supplier;
          const supplierResult = await databaseService.saveSupplier({
            name: supplierName,
            contactInfo: {},
            notes: `Imported from document: ${filename}`
          });
          supplierId = supplierResult.id;
        } catch (error) {
          logger.warn('Could not save supplier, may already exist:', error.message);
        }
      }
 
      // Process each classified item
      const itemsToProcess = classifiedData.items || parseResult.data.items || [];
      for (const item of itemsToProcess) {
        try {
          // Skip items marked as irrelevant by classification
          if (item.is_relevant === false) {
            logger.debug('Skipping irrelevant item', { name: item.name });
            continue;
          }
 
          if (documentType === 'material') {
            // Save material with classified data
            const materialResult = await databaseService.saveMaterial({
              supplierId: supplierId,
              sku: item.sku,
              name: item.name,
              description: item.description,
              unit: item.unit,
              packageSize: item.package_size,
              category: item.category,
              subcategory: item.subcategory
            });
 
            // Save material price
            const validFromDate = item.valid_from && item.valid_from !== 'Unknown' && item.valid_from !== 'null' 
              ? item.valid_from 
              : new Date().toISOString().split('T')[0];
            
            const validToDate = item.valid_to && item.valid_to !== 'Unknown' && item.valid_to !== 'null' 
              ? item.valid_to 
              : null;
 
            await databaseService.saveMaterialPrice({
              materialId: materialResult.id,
              price: item.price,
              currency: item.currency || 'DKK',
              validFrom: validFromDate,
              validTo: validToDate,
              region: item.region,
              confidenceScore: item.confidence || 1.0,
              sourceDocument: filename,
              parseLog: JSON.stringify(item),
              isActive: true
            });
 
            savedItems.push({
              type: 'material',
              materialId: materialResult.id,
              name: item.name,
              confidence: item.confidence
            });
 
          } else if (documentType === 'labor') {
            // Save labor task
            const laborResult = await databaseService.saveLaborTask({
              role: item.role || 'tømrer',
              taskDescription: item.name || item.description,
              unit: item.unit || 'time',
              category: item.category,
              subcategory: item.subcategory
            });
 
            // Save labor price
            const validFromDate = item.valid_from && item.valid_from !== 'Unknown' && item.valid_from !== 'null' 
              ? item.valid_from 
              : new Date().toISOString().split('T')[0];
            
            const validToDate = item.valid_to && item.valid_to !== 'Unknown' && item.valid_to !== 'null' 
              ? item.valid_to 
              : null;
 
            await databaseService.saveLaborPrice({
              laborTaskId: laborResult.id,
              ratePerHour: item.price || item.rate_per_hour,
              currency: item.currency || 'DKK',
              validFrom: validFromDate,
              validTo: validToDate,
              region: item.region,
              confidenceScore: item.confidence || 1.0,
              sourceDocument: filename,
              parseLog: JSON.stringify(item),
              isActive: true
            });
 
            savedItems.push({
              type: 'labor',
              laborTaskId: laborResult.id,
              role: item.role,
              confidence: item.confidence
            });
          }
        } catch (itemError) {
          logger.error('Error saving item from parsed document:', itemError);
          savedItems.push({
            type: 'error',
            item: item,
            error: itemError.message
          });
        }
      }
 
      const finalResult = {
        success: true,
        itemsProcessed: classifiedData.items?.length || 0,
        itemsSaved: savedItems.filter(item => item.type !== 'error').length,
        errors: savedItems.filter(item => item.type === 'error'),
        lowConfidenceItems: savedItems.filter(item => (item.confidence || 1.0) < 0.8),
        savedItems: savedItems
      };
 
      await databaseService.updateDocumentParseStatus(documentId, 'completed', finalResult);
 
      logger.info('Document processed and saved successfully', {
        documentId,
        filename,
        itemsProcessed: finalResult.itemsProcessed,
        itemsSaved: finalResult.itemsSaved
      });
 
      return finalResult;
 
    } catch (error) {
      logger.error('Error processing document:', error);
      await databaseService.updateDocumentParseStatus(documentId, 'failed', {
        error: error.message
      });
      throw error;
    }
  }
}
 
module.exports = new DocumentParserService();