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 | const logger = require('../utils/logger'); class RealDataProjectSuggestionService { constructor(databaseService) { this.databaseService = databaseService; } // Få projekt forslag baseret kun på faktiske historiske data async getProjectSuggestions(projectKeywords = '', customerType = 'standard') { try { logger.info(`Getting real project suggestions for keywords: ${projectKeywords}`); // Hent alle projekter fra Ordrestyring (virkelige data) const realProjects = await this.getRealHistoricalProjects(projectKeywords); if (realProjects.length === 0) { return this.getBasicSuggestions(projectKeywords); } // Analyser faktiske data const analysis = this.analyzeRealProjects(realProjects); // Generer forslag baseret på faktiske data const suggestions = { foundProjects: realProjects.length, searchKeywords: projectKeywords, realDataAnalysis: analysis, similarProjects: realProjects.slice(0, 5), // Vis top 5 lignende projekter estimatedRange: this.calculateRealPriceRange(realProjects), recommendations: this.generateRealDataRecommendations(analysis, realProjects) }; return suggestions; } catch (error) { logger.error('Error getting real project suggestions:', error); throw error; } } // Hent faktiske historiske projekter async getRealHistoricalProjects(keywords) { try { let query = ` SELECT external_case_number, customer_name, project_name, project_description, total_amount_excl_vat, total_amount_incl_vat, created_at, status FROM imported_quotes WHERE source = 'ordrestyring' AND total_amount_excl_vat > 0 `; const params = []; // Hvis der er nøgleord, søg efter dem if (keywords && keywords.trim() !== '') { const searchTerms = keywords.toLowerCase().split(' ').filter(term => term.length > 2); if (searchTerms.length > 0) { const searchConditions = searchTerms.map(() => '(LOWER(project_name) LIKE ? OR LOWER(project_description) LIKE ?)' ).join(' OR '); query += ` AND (${searchConditions})`; // Tilføj søgeparametre searchTerms.forEach(term => { params.push(`%${term}%`, `%${term}%`); }); } } query += ' ORDER BY created_at DESC LIMIT 20'; const projects = await this.databaseService.query(query, params); logger.info(`Found ${projects.length} real projects matching criteria`); return projects; } catch (error) { logger.error('Error fetching real historical projects:', error); return []; } } // Analyser faktiske projekter analyzeRealProjects(projects) { if (projects.length === 0) return null; const values = projects.map(p => p.total_amount_excl_vat); const total = values.reduce((sum, val) => sum + val, 0); return { totalProjects: projects.length, averageValue: Math.round(total / projects.length), minValue: Math.min(...values), maxValue: Math.max(...values), medianValue: this.calculateMedian(values), valueDistribution: this.categorizeProjects(projects), commonKeywords: this.extractCommonKeywords(projects) }; } // Beregn median calculateMedian(values) { const sorted = [...values].sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; } // Kategoriser projekter efter størrelse categorizeProjects(projects) { const categories = { small: { count: 0, max: 100000, examples: [] }, // Under 100k medium: { count: 0, max: 200000, examples: [] }, // 100k-200k large: { count: 0, max: 999999, examples: [] } // Over 200k }; projects.forEach(project => { const value = project.total_amount_excl_vat; if (value < categories.small.max) { categories.small.count++; if (categories.small.examples.length < 3) { categories.small.examples.push({ name: project.project_name, value: value, description: project.project_description.substring(0, 100) + '...' }); } } else if (value < categories.medium.max) { categories.medium.count++; if (categories.medium.examples.length < 3) { categories.medium.examples.push({ name: project.project_name, value: value, description: project.project_description.substring(0, 100) + '...' }); } } else { categories.large.count++; if (categories.large.examples.length < 3) { categories.large.examples.push({ name: project.project_name, value: value, description: project.project_description.substring(0, 100) + '...' }); } } }); return categories; } // Udtræk almindelige nøgleord fra projektbeskrivelser extractCommonKeywords(projects) { const wordCounts = {}; const stopWords = ['og', 'i', 'til', 'på', 'af', 'med', 'for', 'er', 'det', 'en', 'et', 'den', 'som']; projects.forEach(project => { const text = `${project.project_name} ${project.project_description}`.toLowerCase(); const words = text.match(/[a-zæøå]+/g) || []; words.forEach(word => { if (word.length > 3 && !stopWords.includes(word)) { wordCounts[word] = (wordCounts[word] || 0) + 1; } }); }); // Returner top 10 mest almindelige ord return Object.entries(wordCounts) .sort(([,a], [,b]) => b - a) .slice(0, 10) .map(([word, count]) => ({ word, count })); } // Beregn prisrange baseret på faktiske data calculateRealPriceRange(projects) { if (projects.length === 0) return null; const values = projects.map(p => p.total_amount_excl_vat); const avg = values.reduce((sum, val) => sum + val, 0) / values.length; const min = Math.min(...values); const max = Math.max(...values); // Beregn konfidensinterval (25% og 75% percentiler) const sorted = [...values].sort((a, b) => a - b); const q1Index = Math.floor(sorted.length * 0.25); const q3Index = Math.floor(sorted.length * 0.75); return { minimum: min, maximum: max, average: Math.round(avg), typical_low: sorted[q1Index], typical_high: sorted[q3Index], confidence: projects.length >= 5 ? 'høj' : projects.length >= 3 ? 'medium' : 'lav' }; } // Generer anbefalinger baseret på rigtige data generateRealDataRecommendations(analysis, projects) { const recommendations = []; if (!analysis || projects.length === 0) { recommendations.push({ type: 'info', message: 'Ingen lignende projekter fundet. Kontakt for individuel vurdering.', priority: 'high' }); return recommendations; } if (analysis.totalProjects >= 5) { recommendations.push({ type: 'success', message: `Baseret på ${analysis.totalProjects} lignende projekter. Høj tillid til estimat.`, priority: 'high' }); } else if (analysis.totalProjects >= 2) { recommendations.push({ type: 'warning', message: `Kun ${analysis.totalProjects} lignende projekter fundet. Estimat er vejledende.`, priority: 'medium' }); } // Anbefaling baseret på projektspredning const spreadPercent = ((analysis.maxValue - analysis.minValue) / analysis.averageValue) * 100; if (spreadPercent > 100) { recommendations.push({ type: 'info', message: 'Stor variation i projektpriser. Endelig pris afhænger meget af specifikke krav.', priority: 'medium' }); } // Anbefaling baseret på projektfordeling const dist = analysis.valueDistribution; if (dist.large.count > dist.small.count + dist.medium.count) { recommendations.push({ type: 'info', message: 'Lignende projekter er typisk store og komplekse.', priority: 'low' }); } // Tilføj information om mest almindelige features if (analysis.commonKeywords.length > 0) { const topKeywords = analysis.commonKeywords.slice(0, 3).map(k => k.word).join(', '); recommendations.push({ type: 'info', message: `Typiske elementer: ${topKeywords}`, priority: 'low' }); } return recommendations; } // Basis forslag hvis ingen historik findes getBasicSuggestions(keywords) { return { foundProjects: 0, searchKeywords: keywords, realDataAnalysis: null, similarProjects: [], estimatedRange: null, recommendations: [ { type: 'info', message: 'Ingen lignende projekter fundet i vores database.', priority: 'high' }, { type: 'info', message: 'Kontakt os for en individuel vurdering og tilbud.', priority: 'high' } ] }; } // Hent alle unikke projekt typer fra rigtige data async getRealProjectTypes() { try { const projects = await this.databaseService.query(` SELECT DISTINCT project_name, project_description, total_amount_excl_vat FROM imported_quotes WHERE source = 'ordrestyring' AND total_amount_excl_vat > 0 ORDER BY total_amount_excl_vat DESC `); // Gruppér projekter efter lignende nøgleord const typeGroups = this.groupProjectsByType(projects); return typeGroups; } catch (error) { logger.error('Error getting real project types:', error); return []; } } // Gruppér projekter efter type baseret på indhold groupProjectsByType(projects) { const groups = {}; projects.forEach(project => { const text = `${project.project_name} ${project.project_description}`.toLowerCase(); // Definer type baseret på nøgleord i rigtige data let type = 'andet'; if (text.includes('tag')) type = 'tagarbejde'; else if (text.includes('køkken')) type = 'køkken'; else if (text.includes('bad')) type = 'badeværelse'; else if (text.includes('terrasse') || text.includes('carport')) type = 'udendørs'; else if (text.includes('vindue')) type = 'vinduer_døre'; else if (text.includes('tilbygning')) type = 'tilbygning'; else if (text.includes('renovering')) type = 'renovering'; if (!groups[type]) { groups[type] = { name: type, projects: [], averageValue: 0, count: 0 }; } groups[type].projects.push(project); groups[type].count++; }); // Beregn gennemsnit for hver gruppe Object.keys(groups).forEach(type => { const values = groups[type].projects.map(p => p.total_amount_excl_vat); groups[type].averageValue = Math.round(values.reduce((sum, val) => sum + val, 0) / values.length); }); return Object.values(groups); } } module.exports = RealDataProjectSuggestionService; |