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 | const { getDB } = require('./databaseService');
class PricingService {
constructor() {
this.confidenceThresholds = {
HIGH: 0.8,
MEDIUM: 0.6,
LOW: 0.4
};
}
/**
* Get intelligent price suggestion for a material
* @param {string} materialName - Name of the material
* @param {string} category - Material category (optional)
* @param {string} subcategory - Material subcategory (optional)
* @param {number} quantity - Quantity needed (optional)
* @returns {Promise<Object>} Price suggestion with confidence score
*/
async getPriceSuggestion(materialName, category = null, subcategory = null, quantity = null) {
try {
const db = await getDB();
// 1. Look for exact matches in price database
const exactMatches = await this.findExactMatches(db, materialName);
// 2. Look for similar materials (fuzzy matching)
const similarMatches = await this.findSimilarMaterials(db, materialName, category, subcategory);
// 3. Apply pricing rules
const rulePrices = await this.applyPricingRules(db, materialName, category, subcategory);
// 4. Calculate weighted average and confidence
const suggestion = await this.calculateWeightedSuggestion(exactMatches, similarMatches, rulePrices, quantity);
// 5. Store suggestion for learning
await this.logPriceSuggestion(db, materialName, suggestion);
return suggestion;
} catch (error) {
console.error('Error getting price suggestion:', error);
throw error;
}
}
/**
* Find exact material name matches in price database
*/
async findExactMatches(db, materialName) {
const query = `
SELECT
unit_price,
supplier_name,
extraction_date,
confidence_score,
DATEDIFF(NOW(), extraction_date) as days_old
FROM price_database
WHERE material_name LIKE ?
AND confidence_score >= ?
ORDER BY extraction_date DESC, confidence_score DESC
LIMIT 10
`;
const [results] = await db.execute(query, [`%${materialName}%`, this.confidenceThresholds.LOW]);
return results;
}
/**
* Find similar materials using fuzzy matching
*/
async findSimilarMaterials(db, materialName, category, subcategory) {
const keywords = this.extractKeywords(materialName);
const keywordPattern = keywords.join('|');
let query = `
SELECT
material_name,
unit_price,
supplier_name,
extraction_date,
confidence_score,
category,
subcategory,
DATEDIFF(NOW(), extraction_date) as days_old,
(
CASE
WHEN material_name REGEXP ? THEN 0.8
WHEN category = ? THEN 0.6
WHEN subcategory = ? THEN 0.7
ELSE 0.3
END
) as similarity_score
FROM price_database
WHERE (
material_name REGEXP ?
OR category = ?
OR subcategory = ?
)
AND confidence_score >= ?
ORDER BY similarity_score DESC, extraction_date DESC
LIMIT 20
`;
const [results] = await db.execute(query, [
keywordPattern, category, subcategory,
keywordPattern, category, subcategory,
this.confidenceThresholds.LOW
]);
return results;
}
/**
* Apply pricing rules from the pricing_rules table
*/
async applyPricingRules(db, materialName, category, subcategory) {
const query = `
SELECT
rule_name,
price_adjustment_factor,
data_age_weight,
rule_conditions,
adjustment_formula
FROM pricing_rules
WHERE is_active = TRUE
AND (category = ? OR category IS NULL)
AND (subcategory = ? OR subcategory IS NULL)
ORDER BY
CASE WHEN subcategory = ? THEN 1 ELSE 2 END,
CASE WHEN category = ? THEN 1 ELSE 2 END
`;
const [rules] = await db.execute(query, [category, subcategory, subcategory, category]);
// Apply each rule and calculate suggested prices
const rulePrices = [];
for (const rule of rules) {
const rulePrice = await this.calculateRulePrice(db, rule, materialName, category);
if (rulePrice) {
rulePrices.push(rulePrice);
}
}
return rulePrices;
}
/**
* Calculate price based on a specific pricing rule
*/
async calculateRulePrice(db, rule, materialName, category) {
try {
const conditions = JSON.parse(rule.rule_conditions || '{}');
const formula = JSON.parse(rule.adjustment_formula || '{}');
// Get base price data for this rule
let baseQuery = `
SELECT AVG(unit_price) as avg_price, COUNT(*) as sample_count
FROM price_database
WHERE 1=1
`;
const queryParams = [];
if (conditions.apply_to === 'all_materials' || category) {
if (category && category !== 'all_materials') {
baseQuery += ' AND category = ?';
queryParams.push(category);
}
}
if (conditions.min_samples) {
baseQuery += ' HAVING sample_count >= ?';
queryParams.push(conditions.min_samples);
}
const [baseData] = await db.execute(baseQuery, queryParams);
if (!baseData.length || !baseData[0].avg_price) {
return null;
}
// Calculate suggested price using formula
let suggestedPrice = baseData[0].avg_price;
if (formula.markup) {
suggestedPrice *= formula.markup;
}
if (formula.base === 'median_price') {
// Get median instead of average
const medianQuery = baseQuery.replace('AVG(unit_price)',
'unit_price ORDER BY unit_price LIMIT 1 OFFSET (SELECT COUNT(*)/2 FROM price_database WHERE category = ?)');
const [medianResult] = await db.execute(medianQuery, [...queryParams, category]);
if (medianResult.length) {
suggestedPrice = medianResult[0].unit_price;
}
}
return {
rule_name: rule.rule_name,
suggested_price: Math.round(suggestedPrice * 100) / 100,
confidence: 0.7,
sample_count: baseData[0].sample_count,
adjustment_factor: rule.price_adjustment_factor
};
} catch (error) {
console.error('Error calculating rule price:', error);
return null;
}
}
/**
* Calculate weighted average suggestion from all sources
*/
async calculateWeightedSuggestion(exactMatches, similarMatches, rulePrices, quantity) {
const suggestions = [];
// Process exact matches (highest weight)
exactMatches.forEach(match => {
const ageWeight = Math.max(0.3, 1 - (match.days_old / 365)); // Decay over year
const weight = 0.4 * ageWeight * match.confidence_score;
suggestions.push({
price: match.unit_price,
weight: weight,
source: 'exact_match',
supplier: match.supplier_name,
age_days: match.days_old
});
});
// Process similar matches (medium weight)
similarMatches.forEach(match => {
const ageWeight = Math.max(0.2, 1 - (match.days_old / 365));
const weight = 0.25 * ageWeight * match.confidence_score * match.similarity_score;
suggestions.push({
price: match.unit_price,
weight: weight,
source: 'similar_match',
supplier: match.supplier_name,
similarity: match.similarity_score,
age_days: match.days_old
});
});
// Process rule-based prices (lower weight)
rulePrices.forEach(rulePrice => {
const weight = 0.15 * rulePrice.confidence;
suggestions.push({
price: rulePrice.suggested_price,
weight: weight,
source: 'rule_based',
rule_name: rulePrice.rule_name,
sample_count: rulePrice.sample_count
});
});
if (suggestions.length === 0) {
return {
suggested_price: null,
confidence_score: 0,
source: 'no_data',
message: 'Ingen prisdata fundet - manual indtastning nødvendig'
};
}
// Calculate weighted average
const totalWeight = suggestions.reduce((sum, s) => sum + s.weight, 0);
const weightedPrice = suggestions.reduce((sum, s) => sum + (s.price * s.weight), 0) / totalWeight;
// Calculate confidence based on data quality
const dataQuality = {
exact_matches: exactMatches.length,
similar_matches: similarMatches.length,
rule_matches: rulePrices.length,
total_weight: totalWeight
};
const confidence = this.calculateConfidence(dataQuality, suggestions);
return {
suggested_price: Math.round(weightedPrice * 100) / 100,
confidence_score: Math.round(confidence * 100) / 100,
source: this.determineMainSource(suggestions),
data_quality: dataQuality,
supporting_data: suggestions.slice(0, 5), // Top 5 sources
quantity_adjustment: quantity ? this.calculateQuantityAdjustment(quantity) : null
};
}
/**
* Calculate confidence score based on data quality
*/
calculateConfidence(dataQuality, suggestions) {
let confidence = 0;
// Base confidence from data sources
if (dataQuality.exact_matches > 0) confidence += 0.4;
if (dataQuality.similar_matches > 0) confidence += 0.3;
if (dataQuality.rule_matches > 0) confidence += 0.1;
// Boost for multiple sources
const sourceCount = (dataQuality.exact_matches > 0 ? 1 : 0) +
(dataQuality.similar_matches > 0 ? 1 : 0) +
(dataQuality.rule_matches > 0 ? 1 : 0);
if (sourceCount >= 2) confidence += 0.15;
if (sourceCount >= 3) confidence += 0.05;
// Weight quality bonus
if (dataQuality.total_weight > 1.0) confidence += 0.1;
return Math.min(1.0, confidence);
}
/**
* Determine the main source for the suggestion
*/
determineMainSource(suggestions) {
const sourceWeights = {};
suggestions.forEach(s => {
sourceWeights[s.source] = (sourceWeights[s.source] || 0) + s.weight;
});
return Object.keys(sourceWeights).reduce((a, b) =>
sourceWeights[a] > sourceWeights[b] ? a : b
);
}
/**
* Calculate quantity-based price adjustments
*/
calculateQuantityAdjustment(quantity) {
// Simple quantity discount logic
if (quantity >= 100) return { factor: 0.9, note: '10% volume rabat' };
if (quantity >= 50) return { factor: 0.95, note: '5% volume rabat' };
if (quantity <= 5) return { factor: 1.1, note: '10% småkøb tillæg' };
return { factor: 1.0, note: 'Standard pris' };
}
/**
* Extract keywords from material name for fuzzy matching
*/
extractKeywords(materialName) {
// Remove common words and extract meaningful terms
const commonWords = ['og', 'til', 'med', 'af', 'for', 'i', 'på', 'the', 'and', 'for', 'of', 'with'];
const words = materialName.toLowerCase()
.replace(/[^\w\s]/g, ' ')
.split(/\s+/)
.filter(word => word.length > 2 && !commonWords.includes(word));
return words;
}
/**
* Log price suggestion for machine learning
*/
async logPriceSuggestion(db, materialName, suggestion) {
try {
const query = `
INSERT INTO quote_pricing_history (
material_name,
suggested_price,
suggested_confidence,
pricing_method,
user_choice
) VALUES (?, ?, ?, ?, 'pending')
`;
await db.execute(query, [
materialName,
suggestion.suggested_price,
suggestion.confidence_score,
suggestion.source
]);
} catch (error) {
console.error('Error logging price suggestion:', error);
}
}
/**
* Record user feedback on price suggestions
*/
async recordUserFeedback(suggestionId, actualPrice, userChoice, feedbackRating = null) {
try {
const db = await getDB();
const query = `
UPDATE quote_pricing_history
SET
actual_price_used = ?,
user_choice = ?,
user_feedback_rating = ?,
price_difference = ? - suggested_price
WHERE id = ?
`;
await db.execute(query, [actualPrice, userChoice, feedbackRating, actualPrice, suggestionId]);
return { success: true };
} catch (error) {
console.error('Error recording user feedback:', error);
throw error;
}
}
/**
* Get pricing suggestions for multiple materials at once
*/
async getBulkPriceSuggestions(materials) {
const suggestions = {};
for (const material of materials) {
try {
const suggestion = await this.getPriceSuggestion(
material.name,
material.category,
material.subcategory,
material.quantity
);
suggestions[material.name] = suggestion;
} catch (error) {
console.error(`Error getting suggestion for ${material.name}:`, error);
suggestions[material.name] = {
suggested_price: null,
confidence_score: 0,
source: 'error',
message: 'Fejl ved prisforslag'
};
}
}
return suggestions;
}
}
module.exports = new PricingService();
|