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 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 | const axios = require('axios'); const cheerio = require('cheerio'); const logger = require('../utils/logger'); const GoogleSearchService = require('./googleSearchService'); class WebPriceService { constructor() { this.googleSearch = new GoogleSearchService(); this.sources = [ { name: 'Silvan', baseUrl: 'https://www.silvan.dk', searchUrl: 'https://www.silvan.dk/search?q=', selectors: { product: '.product-item', name: '.product-title', price: '.price', unit: '.unit' } }, { name: 'Bauhaus', baseUrl: 'https://www.bauhaus.dk', searchUrl: 'https://www.bauhaus.dk/search?q=', selectors: { product: '.product-tile', name: '.product-name', price: '.price-current', unit: '.price-unit' } }, { name: 'Bygma', baseUrl: 'https://www.bygma.dk', searchUrl: 'https://www.bygma.dk/soeg?q=', selectors: { product: '.product-card, .product-item', name: '.product-title, .product-name, h3', price: '.price, .product-price', priceExVat: '.price-ex-vat, .price-without-vat', priceIncVat: '.price-inc-vat, .price-with-vat', unit: '.unit, .price-unit' } } ]; this.commonMaterials = { 'vinduer': ['termoruder', 'trævindue', 'træ vindue', 'vedligeholdsfrit vindue'], 'døre': ['indvendige døre', 'udvendige døre', 'træ dør', 'fyldningsdør'], 'gulv': ['trægulv', 'laminat', 'parket', 'planker', 'massive trægulv'], 'trægulv': ['massive trægulv', 'parket', 'trægulv', 'gulvplanker'], 'terrasse': ['terrassedæk', 'terrasse planker', 'træterrasse'], 'tag': ['tagplader', 'tagrende', 'tagsten', 'tagpap'], 'isolering': ['mineraluld', 'glasuld', 'isover'], 'beslag': ['skruer', 'søm', 'beslag', 'hængsler'], 'træ': ['konstruktionstræ', 'brædder', 'lægter', 'reglar'] }; } async searchMaterialPrices(materialType, quantity = 1) { try { logger.info(`Searching web prices for: ${materialType}`); const searchTerms = this.getSearchTerms(materialType); const results = []; for (const term of searchTerms) { // First, try specialized Bygma scraper try { const bygmaResults = await this.scrapeBygmaSpecific(term); results.push(...bygmaResults); } catch (error) { logger.warn(`Bygma specialized scraping failed for ${term}:`, error.message); } // Then search other sources for (const source of this.sources) { try { // Skip Bygma in general search since we did specialized scraping if (source.name === 'Bygma') continue; const sourceResults = await this.searchInSource(source, term); results.push(...sourceResults); } catch (error) { logger.warn(`Failed to search ${source.name} for ${term}:`, error.message); } } } return this.processResults(results, materialType); } catch (error) { logger.error('Error searching web prices:', error); throw new Error('Kunne ikke hente priser fra internettet'); } } getSearchTerms(materialType) { const type = materialType.toLowerCase(); // Find matching category for (const [category, terms] of Object.entries(this.commonMaterials)) { if (type.includes(category) || terms.some(term => type.includes(term))) { return terms.slice(0, 2); // Limit to 2 search terms per category } } // Fallback to the material type itself return [materialType]; } async searchInSource(source, searchTerm) { try { const searchUrl = `${source.searchUrl}${encodeURIComponent(searchTerm)}`; const response = await axios.get(searchUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'da-DK,da;q=0.9,en;q=0.8', 'Cache-Control': 'no-cache' }, timeout: 10000 }); const $ = cheerio.load(response.data); const products = []; $(source.selectors.product).slice(0, 5).each((index, element) => { try { const $el = $(element); const name = $el.find(source.selectors.name).text().trim(); const unitText = $el.find(source.selectors.unit).text().trim() || 'stk'; if (name) { // Handle Bygma's dual pricing (with/without VAT) if (source.name === 'Bygma') { const priceExVatText = $el.find(source.selectors.priceExVat).text().trim(); const priceIncVatText = $el.find(source.selectors.priceIncVat).text().trim(); // Try standard price selectors if specific VAT selectors don't work const standardPriceText = $el.find(source.selectors.price).text().trim(); if (priceExVatText) { const priceExVat = this.extractPrice(priceExVatText); if (priceExVat > 0) { products.push({ name: `${name} (ex. moms)`, price: priceExVat, unit: this.normalizeUnit(unitText), source: source.name, searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'ex-vat' }); } } if (priceIncVatText) { const priceIncVat = this.extractPrice(priceIncVatText); if (priceIncVat > 0) { products.push({ name: `${name} (inkl. moms)`, price: priceIncVat, unit: this.normalizeUnit(unitText), source: source.name, searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'inc-vat' }); } } // Fallback to standard price if VAT-specific prices not found if (!priceExVatText && !priceIncVatText && standardPriceText) { const price = this.extractPrice(standardPriceText); if (price > 0) { products.push({ name: name, price: price, unit: this.normalizeUnit(unitText), source: source.name, searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'unknown' }); } } } else { // Standard handling for other sources const priceText = $el.find(source.selectors.price).text().trim(); if (priceText) { const price = this.extractPrice(priceText); if (price > 0) { products.push({ name: name, price: price, unit: this.normalizeUnit(unitText), source: source.name, searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm) }); } } } } } catch (error) { // Skip individual product errors } }); return products; } catch (error) { logger.warn(`Failed to search ${source.name}:`, error.message); return []; } } extractPrice(priceText) { // Extract price from various Danish formats const cleanText = priceText.replace(/[^\d,.-]/g, ''); const matches = cleanText.match(/(\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?)/); if (matches) { let price = matches[1]; // Handle Danish number format (comma as decimal separator) if (price.includes(',') && price.lastIndexOf(',') === price.length - 3) { price = price.replace(/\./g, '').replace(',', '.'); } else { price = price.replace(/,/g, ''); } return parseFloat(price); } return 0; } normalizeUnit(unitText) { const unit = unitText.toLowerCase().trim(); const unitMap = { 'stk': 'stk', 'styk': 'stk', 'pak': 'pakker', 'pakke': 'pakker', 'm2': 'm²', 'm²': 'm²', 'kvm': 'm²', 'm': 'm', 'meter': 'm', 'kg': 'kg', 'liter': 'liter', 'l': 'liter' }; return unitMap[unit] || 'stk'; } calculateConfidence(productName, searchTerm) { const name = productName.toLowerCase(); const term = searchTerm.toLowerCase(); // Exact match if (name.includes(term)) return 0.9; // Partial word matches const nameWords = name.split(/\s+/); const termWords = term.split(/\s+/); let matches = 0; for (const termWord of termWords) { if (nameWords.some(nameWord => nameWord.includes(termWord) || termWord.includes(nameWord))) { matches++; } } return Math.max(0.3, matches / termWords.length * 0.8); } processResults(results, materialType) { // Filter and sort results const filtered = results .filter(item => item.confidence > 0.3) .sort((a, b) => b.confidence - a.confidence) .slice(0, 10); // Top 10 results // Group by source const grouped = {}; for (const item of filtered) { if (!grouped[item.source]) { grouped[item.source] = []; } grouped[item.source].push(item); } return { materialType: materialType, totalResults: filtered.length, results: filtered, groupedBySource: grouped, averagePrice: this.calculateAverage(filtered), priceRange: this.calculatePriceRange(filtered), timestamp: new Date().toISOString() }; } calculateAverage(results) { if (results.length === 0) return 0; const sum = results.reduce((acc, item) => acc + item.price, 0); return Math.round(sum / results.length); } calculatePriceRange(results) { if (results.length === 0) return { min: 0, max: 0 }; const prices = results.map(item => item.price); return { min: Math.min(...prices), max: Math.max(...prices) }; } async getTomrerRates(workType = 'generel tømrerarbejde') { try { logger.info(`Searching web for carpenter rates: ${workType}`); // Search for carpenter hourly rates from various sources const searchTerms = [ 'tømrer timepris', 'tømrer timeløn', 'håndværker timepris', 'tømrerarbejde pris' ]; const results = []; for (const term of searchTerms) { // In a real implementation, you would search job sites, // government statistics, or industry reports // For now, we'll provide estimated ranges based on 2024 Danish market rates results.push({ workType: workType, hourlyRate: this.getEstimatedTomrerRate(workType), source: 'Markedsestimering', confidence: 0.7, notes: 'Baseret på danske markedspriser 2024' }); } return { workType: workType, rates: results, averageRate: this.getEstimatedTomrerRate(workType), timestamp: new Date().toISOString() }; } catch (error) { logger.error('Error getting carpenter rates:', error); throw new Error('Kunne ikke hente tømrersatser'); } } getEstimatedTomrerRate(workType) { const baseRates = { 'gulvlægning': 475, 'tagarbejde': 520, 'terrasse': 450, 'dør/vindue montering': 480, 'køkken/bad renovering': 500, 'isolering': 420, 'tømrer reparationer': 460, 'carport/garage': 440, 'trapper': 550, 'generel tømrerarbejde': 475 }; return baseRates[workType.toLowerCase()] || baseRates['generel tømrerarbejde']; } async enrichMaterialData(materialName, existingData = {}) { try { const webResults = await this.searchMaterialPrices(materialName); if (webResults.results.length === 0) { return { success: false, message: `Ingen priser fundet for ${materialName} på internettet`, data: existingData }; } const enrichedData = { ...existingData, name: materialName, webPrices: webResults.results, suggestedPrice: webResults.averagePrice, priceRange: webResults.priceRange, dataSource: 'web_enriched', lastUpdated: new Date().toISOString(), confidence: webResults.results[0]?.confidence || 0.5 }; return { success: true, message: `Fundet ${webResults.results.length} priser for ${materialName}`, data: enrichedData, webResults: webResults }; } catch (error) { logger.error('Error enriching material data:', error); return { success: false, message: `Fejl ved hentning af webpriser: ${error.message}`, data: existingData }; } } // Smart price estimation when web scraping fails async estimatePrice(materialType, specifications = {}) { try { logger.info(`Estimating price for: ${materialType}`); const { quantity = 1, quality = 'standard', region = 'denmark' } = specifications; // Get base price from database or defaults const basePrices = this.getBasePrices(); const category = this.getCategoryFromMaterial(materialType); let basePrice = basePrices[category] || basePrices['default']; // Apply quality multipliers const qualityMultipliers = { 'budget': 0.7, 'standard': 1.0, 'premium': 1.4, 'luxury': 2.0 }; // Apply quantity discounts const quantityMultiplier = this.getQuantityDiscount(quantity); // Apply regional adjustments const regionalMultiplier = this.getRegionalMultiplier(region); const estimatedPrice = basePrice * qualityMultipliers[quality] * quantityMultiplier * regionalMultiplier; return { success: true, materialType: materialType, estimatedPrice: Math.round(estimatedPrice * 100) / 100, basePrice: basePrice, factors: { quality: quality, qualityMultiplier: qualityMultipliers[quality], quantityMultiplier: quantityMultiplier, regionalMultiplier: regionalMultiplier }, confidence: 0.75, source: 'AI Price Estimation', timestamp: new Date().toISOString() }; } catch (error) { logger.error('Error estimating price:', error); throw new Error('Kunne ikke estimere pris'); } } getBasePrices() { return { 'trægulv': 120, 'gulv': 120, 'træmaterialer': 20, 'træ': 20, 'isolering': 45, 'beslag': 15, 'skruer': 15, 'døre': 2500, 'vinduer': 2800, 'tag': 180, 'terrasse': 150, 'default': 50 }; } getCategoryFromMaterial(materialType) { const type = materialType.toLowerCase(); if (type.includes('gulv') || type.includes('parket') || type.includes('laminat')) return 'trægulv'; if (type.includes('træ') || type.includes('konstruktion') || type.includes('brædder')) return 'træmaterialer'; if (type.includes('isoler')) return 'isolering'; if (type.includes('beslag') || type.includes('skrue') || type.includes('søm')) return 'beslag'; if (type.includes('dør')) return 'døre'; if (type.includes('vindu')) return 'vinduer'; if (type.includes('tag')) return 'tag'; if (type.includes('terrasse')) return 'terrasse'; return 'default'; } getQuantityDiscount(quantity) { if (quantity >= 100) return 0.85; // 15% discount for large orders if (quantity >= 50) return 0.90; // 10% discount for medium orders if (quantity >= 20) return 0.95; // 5% discount for small bulk return 1.0; // No discount for small quantities } getRegionalMultiplier(region) { const multipliers = { 'københavn': 1.15, 'aarhus': 1.05, 'odense': 1.02, 'aalborg': 1.02, 'denmark': 1.0, 'jylland': 0.95, 'fyn': 0.98, 'bornholm': 1.10 }; return multipliers[region.toLowerCase()] || 1.0; } // Enhanced search with Google and fallback to estimation async searchMaterialPricesWithFallback(materialType, specifications = {}) { try { logger.info(`Enhanced material search for: ${materialType}`); // Strategy 1: Google search on Danish building sites try { const googleResults = await this.googleSearch.enhancedSearch(materialType); if (googleResults.length > 0) { logger.info(`Google search found ${googleResults.length} results for ${materialType}`); return { source: 'google_search', success: true, materialType: materialType, results: googleResults, summary: { totalFound: googleResults.length, averagePrice: googleResults.reduce((sum, item) => sum + item.price, 0) / googleResults.length, priceRange: { min: Math.min(...googleResults.map(item => item.price)), max: Math.max(...googleResults.map(item => item.price)) } }, groupedBySource: this.groupResultsBySource(googleResults), timestamp: new Date().toISOString() }; } } catch (error) { logger.warn(`Google search failed for ${materialType}:`, error.message); } // Strategy 2: Traditional web scraping try { const webResults = await this.searchMaterialPrices(materialType); if (webResults.results.length > 0) { logger.info(`Web scraping found ${webResults.results.length} results for ${materialType}`); return { source: 'web_scraping', ...webResults }; } } catch (error) { logger.warn(`Web scraping failed for ${materialType}:`, error.message); } // Strategy 3: Fallback to price estimation logger.info(`All web methods failed, falling back to price estimation for: ${materialType}`); const estimation = await this.estimatePrice(materialType, specifications); return { source: 'estimation', success: true, materialType: materialType, results: [{ name: `${materialType} (estimeret)`, price: estimation.estimatedPrice, unit: this.getDefaultUnit(materialType), source: 'AI Estimering', confidence: estimation.confidence, description: `Intelligent prisestimering baseret på markedsdata`, notes: `Basispris: ${estimation.basePrice} DKK, Kvalitet: ${estimation.factors.quality}`, searchMethod: 'estimation' }], summary: { totalFound: 1, averagePrice: estimation.estimatedPrice, priceRange: { min: estimation.estimatedPrice * 0.8, max: estimation.estimatedPrice * 1.2 } }, estimation: estimation, timestamp: new Date().toISOString() }; } catch (error) { logger.error('Error in enhanced material search:', error); throw error; } } groupResultsBySource(results) { return results.reduce((groups, result) => { const source = result.source; if (!groups[source]) { groups[source] = []; } groups[source].push(result); return groups; }, {}); } getDefaultUnit(materialType) { const type = materialType.toLowerCase(); if (type.includes('gulv') || type.includes('terrasse')) return 'm²'; if (type.includes('isoler')) return 'm²'; if (type.includes('træ') && (type.includes('lægte') || type.includes('bræd'))) return 'm'; if (type.includes('beslag') || type.includes('skrue')) return 'stk'; if (type.includes('søm')) return 'kg'; if (type.includes('dør') || type.includes('vindu')) return 'stk'; return 'stk'; } async scrapeBygmaSpecific(searchTerm) { try { logger.info(`Specialized Bygma scraping for: ${searchTerm}`); const searchUrl = `https://www.bygma.dk/soeg?q=${encodeURIComponent(searchTerm)}`; const response = await axios.get(searchUrl, { 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', 'Pragma': 'no-cache' }, timeout: 15000 }); const $ = cheerio.load(response.data); const products = []; // Try multiple selectors for Bygma products const productSelectors = [ '.product-card', '.product-item', '.product-tile', '[data-product]', '.search-result-item' ]; for (const selector of productSelectors) { $(selector).slice(0, 8).each((index, element) => { try { const $el = $(element); // Try multiple name selectors const nameSelectors = ['.product-title', '.product-name', 'h3', 'h4', '.title', '.name']; let name = ''; for (const nameSelector of nameSelectors) { name = $el.find(nameSelector).text().trim(); if (name) break; } if (name) { // Try to find both VAT and ex-VAT prices const priceSelectors = { exVat: ['.price-ex-vat', '.price-without-vat', '.ex-vat', '[data-price-ex-vat]'], incVat: ['.price-inc-vat', '.price-with-vat', '.inc-vat', '[data-price-inc-vat]'], general: ['.price', '.product-price', '.current-price', '[data-price]'] }; const unitSelectors = ['.unit', '.price-unit', '.per-unit', '[data-unit]']; let unit = 'stk'; for (const unitSelector of unitSelectors) { const unitText = $el.find(unitSelector).text().trim(); if (unitText) { unit = this.normalizeUnit(unitText); break; } } // Check for ex-VAT price for (const selector of priceSelectors.exVat) { const priceText = $el.find(selector).text().trim(); if (priceText) { const price = this.extractPrice(priceText); if (price > 0) { products.push({ name: `${name} (ex. moms)`, price: price, unit: unit, source: 'Bygma', searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'ex-vat', description: 'Pris eksklusive moms fra Bygma' }); } break; } } // Check for inc-VAT price for (const selector of priceSelectors.incVat) { const priceText = $el.find(selector).text().trim(); if (priceText) { const price = this.extractPrice(priceText); if (price > 0) { products.push({ name: `${name} (inkl. moms)`, price: price, unit: unit, source: 'Bygma', searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'inc-vat', description: 'Pris inklusive moms fra Bygma' }); } break; } } // Check general price if no specific VAT prices found if (products.filter(p => p.name.includes(name)).length === 0) { for (const selector of priceSelectors.general) { const priceText = $el.find(selector).text().trim(); if (priceText) { const price = this.extractPrice(priceText); if (price > 0) { products.push({ name: name, price: price, unit: unit, source: 'Bygma', searchTerm: searchTerm, confidence: this.calculateConfidence(name, searchTerm), vatType: 'unknown', description: 'Pris fra Bygma (moms status ukendt)' }); } break; } } } } } catch (error) { // Skip individual product errors } }); if (products.length > 0) break; // Stop if we found products } logger.info(`Bygma specialized scraping found ${products.length} products`); return products; } catch (error) { logger.warn(`Bygma specialized scraping failed:`, error.message); return []; } } } module.exports = new WebPriceService(); |