All files / services googleSearchService.js

0% Statements 0/114
0% Branches 0/39
0% Functions 0/19
0% Lines 0/108

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
const axios = require('axios');
const cheerio = require('cheerio');
const logger = require('../utils/logger');
 
class GoogleSearchService {
  constructor() {
    this.danishSites = [
      'silvan.dk',
      'bauhaus.dk', 
      'bygma.dk',
      'jysk.dk',
      'xl-byg.dk',
      'byggecentrum.dk',
      'stark.dk',
      'brødrene-a-o-johansen.dk',
      'gibon.dk'
    ];
  }
 
  async searchMaterialPrices(materialQuery) {
    try {
      logger.info(`Google searching for: ${materialQuery}`);
      
      // Build Google search query targeting Danish sites
      const siteQuery = this.danishSites.map(site => `site:${site}`).join(' OR ');
      const searchQuery = `${materialQuery} pris (${siteQuery})`;
      
      const googleUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}&hl=da&gl=dk`;
      
      const response = await axios.get(googleUrl, {
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
          'Accept-Language': 'da-DK,da;q=0.9,en;q=0.8',
          'Accept-Encoding': 'gzip, deflate, br',
          'Cache-Control': 'no-cache'
        },
        timeout: 15000
      });
 
      const $ = cheerio.load(response.data);
      const results = [];
      
      // Parse Google search results
      $('.g, .tF2Cxc').slice(0, 5).each((index, element) => {
        try {
          const $result = $(element);
          
          // Extract title and URL
          const titleElement = $result.find('h3').first();
          const linkElement = $result.find('a[href]').first();
          const snippetElement = $result.find('.VwiC3b, .s3v9rd, .aCOpRe');
          
          const title = titleElement.text().trim();
          const url = linkElement.attr('href');
          const snippet = snippetElement.text().trim();
          
          if (title && url && this.isDanishBuildingSite(url)) {
            const extractedPrice = this.extractPriceFromText(title + ' ' + snippet);
            
            if (extractedPrice) {
              results.push({
                name: title,
                price: extractedPrice.price,
                unit: extractedPrice.unit,
                source: this.getSourceFromUrl(url),
                url: url,
                snippet: snippet,
                confidence: this.calculateConfidence(title, materialQuery),
                searchMethod: 'google'
              });
            }
          }
        } catch (error) {
          // Skip failed result parsing
        }
      });
 
      return results;
      
    } catch (error) {
      logger.warn('Google search failed:', error.message);
      return [];
    }
  }
 
  isDanishBuildingSite(url) {
    return this.danishSites.some(site => url.includes(site));
  }
 
  getSourceFromUrl(url) {
    for (const site of this.danishSites) {
      if (url.includes(site)) {
        return site.split('.')[0].charAt(0).toUpperCase() + site.split('.')[0].slice(1);
      }
    }
    return 'Dansk byggesite';
  }
 
  extractPriceFromText(text) {
    try {
      // Look for Danish price patterns
      const pricePatterns = [
        // "179,50 kr/m²", "89 DKK pr. stk"
        /(\d{1,4}[.,]?\d{0,2})\s*(?:kr|dkk|kroner)\s*(?:pr\.?|per|\/)\s*([a-zA-Z²³]+)/gi,
        // "Kr. 125,50 per m²"
        /(?:kr\.?|dkk)\s*(\d{1,4}[.,]?\d{0,2})\s*(?:pr\.?|per|\/)\s*([a-zA-Z²³]+)/gi,
        // "125,50 kr" with unit nearby
        /(\d{1,4}[.,]?\d{0,2})\s*(?:kr|dkk|kroner)/gi,
        // Just numbers with possible units
        /(\d{1,4}[.,]?\d{0,2})\s*(m²|stk|meter|kg|liter)/gi
      ];
 
      for (const pattern of pricePatterns) {
        const matches = text.match(pattern);
        if (matches) {
          const match = matches[0];
          const priceMatch = match.match(/(\d{1,4}[.,]?\d{0,2})/);
          const unitMatch = match.match(/(m²|stk|meter|kg|liter|pr\.?\s*([a-zA-Z²³]+))/i);
          
          if (priceMatch) {
            const price = parseFloat(priceMatch[1].replace(',', '.'));
            let unit = 'stk';
            
            if (unitMatch) {
              if (unitMatch[2]) {
                unit = unitMatch[2];
              } else {
                unit = unitMatch[1];
              }
            }
            
            if (price > 0 && price < 50000) { // Reasonable price range
              return {
                price: price,
                unit: this.normalizeUnit(unit)
              };
            }
          }
        }
      }
      
      return null;
    } catch (error) {
      return null;
    }
  }
 
  normalizeUnit(unit) {
    const unitMap = {
      'meter': 'm',
      'kvadratmeter': 'm²',
      'styk': 'stk',
      'stykker': 'stk',
      'kilogram': 'kg',
      'liter': 'l',
      'pr': 'stk'
    };
    
    const normalized = unit.toLowerCase().replace(/[^a-zA-Z²³]/g, '');
    return unitMap[normalized] || normalized || 'stk';
  }
 
  calculateConfidence(title, searchTerm) {
    const titleLower = title.toLowerCase();
    const searchLower = searchTerm.toLowerCase();
    
    // Higher confidence if exact match
    if (titleLower.includes(searchLower)) {
      return 0.9;
    }
    
    // Check for partial matches
    const searchWords = searchLower.split(' ');
    const matchedWords = searchWords.filter(word => 
      word.length > 2 && titleLower.includes(word)
    );
    
    const matchRatio = matchedWords.length / searchWords.length;
    return Math.max(0.4, matchRatio * 0.8);
  }
 
  // Enhanced search with multiple strategies
  async enhancedSearch(materialQuery) {
    try {
      logger.info(`Enhanced Google search for: ${materialQuery}`);
      
      const searchStrategies = [
        `${materialQuery} pris byggematerialer`,
        `${materialQuery} køb pris`,
        `${materialQuery} byggevarehouse`,
        `træ ${materialQuery} pris` // Add "træ" for wood materials
      ];
      
      const allResults = [];
      
      for (const strategy of searchStrategies) {
        try {
          const results = await this.searchMaterialPrices(strategy);
          allResults.push(...results);
          
          if (allResults.length >= 3) break; // Stop when we have enough results
          
          // Small delay between searches
          await new Promise(resolve => setTimeout(resolve, 1000));
        } catch (error) {
          logger.warn(`Search strategy failed: ${strategy}`, error.message);
        }
      }
      
      // Remove duplicates and sort by confidence
      const uniqueResults = this.removeDuplicates(allResults);
      return uniqueResults.sort((a, b) => b.confidence - a.confidence).slice(0, 5);
      
    } catch (error) {
      logger.error('Enhanced Google search failed:', error);
      return [];
    }
  }
 
  removeDuplicates(results) {
    const seen = new Set();
    return results.filter(result => {
      const key = `${result.name}-${result.price}-${result.source}`;
      if (seen.has(key)) {
        return false;
      }
      seen.add(key);
      return true;
    });
  }
 
  // Fallback to DuckDuckGo if Google blocks
  async duckDuckGoSearch(materialQuery) {
    try {
      logger.info(`DuckDuckGo search for: ${materialQuery}`);
      
      const siteQuery = this.danishSites.map(site => `site:${site}`).slice(0, 3).join(' OR ');
      const searchQuery = `${materialQuery} pris (${siteQuery})`;
      
      const ddgUrl = `https://duckduckgo.com/html/?q=${encodeURIComponent(searchQuery)}&kl=dk-da`;
      
      const response = await axios.get(ddgUrl, {
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
          'Accept-Language': 'da-DK,da;q=0.9'
        },
        timeout: 10000
      });
 
      const $ = cheerio.load(response.data);
      const results = [];
      
      $('.result').slice(0, 3).each((index, element) => {
        try {
          const $result = $(element);
          const title = $result.find('.result__title').text().trim();
          const url = $result.find('.result__url').attr('href');
          const snippet = $result.find('.result__snippet').text().trim();
          
          if (title && url && this.isDanishBuildingSite(url)) {
            const extractedPrice = this.extractPriceFromText(title + ' ' + snippet);
            
            if (extractedPrice) {
              results.push({
                name: title,
                price: extractedPrice.price,
                unit: extractedPrice.unit,
                source: this.getSourceFromUrl(url),
                url: url,
                snippet: snippet,
                confidence: this.calculateConfidence(title, materialQuery),
                searchMethod: 'duckduckgo'
              });
            }
          }
        } catch (error) {
          // Skip failed result
        }
      });
 
      return results;
      
    } catch (error) {
      logger.warn('DuckDuckGo search failed:', error.message);
      return [];
    }
  }
}
 
module.exports = GoogleSearchService;