-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhancements.js
More file actions
643 lines (559 loc) · 17.9 KB
/
Copy pathenhancements.js
File metadata and controls
643 lines (559 loc) · 17.9 KB
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
/**
* ================================================================================
* MERCADONA AGENT - ENHANCEMENTS MODULE
* ================================================================================
* Description: Funcionalidades mejoradas según plan de mejoras
* Last Updated: 2026-03-22
* ================================================================================
*/
class MercadonaEnhancements {
constructor(app) {
this.app = app;
this.comparisonMode = false;
this.selectedProducts = new Set();
this.priceAlerts = this.loadPriceAlerts();
this.init();
}
init() {
this.checkPriceAlerts();
this.setupComparisonMode();
}
// =====================================================
// ENHANCED PRODUCT CARD RENDERING
// =====================================================
/**
* Calculate savings amount and percentage
*/
calculateSavings(product) {
if (!product.hasDiscount || !product.originalPrice || !product.discountedPrice) {
return null;
}
// Handle both string and number formats
const original = typeof product.originalPrice === 'string'
? parseFloat(product.originalPrice.replace(',', '.'))
: parseFloat(product.originalPrice);
const discounted = typeof product.discountedPrice === 'string'
? parseFloat(product.discountedPrice.replace(',', '.'))
: parseFloat(product.discountedPrice);
if (isNaN(original) || isNaN(discounted) || original <= 0) {
return null;
}
const savings = original - discounted;
const percentage = ((savings / original) * 100).toFixed(0);
return {
amount: savings.toFixed(2),
percentage: parseInt(percentage)
};
}
/**
* Format reference price
*/
formatReferencePrice(product) {
if (!product.reference_price || !product.reference_format) {
return null;
}
// Handle both string and number formats
const price = typeof product.reference_price === 'string'
? product.reference_price
: product.reference_price.toFixed(2);
return `${price}€/${product.reference_format}`;
}
/**
* Format pack info
*/
formatPackInfo(product) {
if (!product.is_pack || !product.total_units) {
return null;
}
const unitName = product.unit_name || 'uds';
return `${product.total_units} ${unitName}`;
}
/**
* Generate savings badge HTML
*/
getSavingsBadgeHTML(savings) {
if (!savings) return '';
return `
<div class="product-savings-badge">
<i class="fas fa-tag"></i> -${savings.percentage}%
</div>
`;
}
/**
* Generate pack badge HTML
*/
getPackBadgeHTML(packInfo) {
if (!packInfo) return '';
return `
<div class="product-pack-badge">
<i class="fas fa-box"></i> Pack ${packInfo}
</div>
`;
}
/**
* Generate best value badge HTML
*/
getBestValueBadgeHTML(product, allProducts) {
// Check if this product has best value in its category
if (!product.reference_price || !product.category) return '';
const categoryProducts = allProducts.filter(p =>
p.category === product.category &&
p.reference_price
);
if (categoryProducts.length < 2) return '';
const prices = categoryProducts.map(p => parseFloat(p.reference_price.replace(',', '.')));
const minPrice = Math.min(...prices);
const productPrice = parseFloat(product.reference_price.replace(',', '.'));
if (productPrice === minPrice) {
return `
<div class="product-best-value-badge">
<i class="fas fa-star"></i> Mejor Valor
</div>
`;
}
return '';
}
/**
* Generate reference price HTML
*/
getReferencePriceHTML(product) {
const refPrice = this.formatReferencePrice(product);
if (!refPrice) return '';
return `<div class="product-reference-price">${refPrice}</div>`;
}
/**
* Generate product info details HTML
*/
getProductInfoHTML(product) {
const details = [];
// Pack info
if (product.is_pack && product.total_units) {
details.push(`<i class="fas fa-box"></i> Pack de ${product.total_units} ${product.unit_name || 'uds'}`);
}
// Size info
if (product.unit_size && product.size_format) {
details.push(`<i class="fas fa-weight"></i> ${product.unit_size} ${product.size_format}`);
}
// Tax info
if (product.tax_percentage) {
details.push(`<i class="fas fa-percentage"></i> IVA ${product.tax_percentage}%`);
}
if (details.length === 0) return '';
return `
<div class="product-info-details">
${details.join(' • ')}
</div>
`;
}
/**
* Generate mini sparkline for price history
*/
async getSparklineHTML(productId) {
// Fetch last 7 days of price history
try {
const response = await fetch(`${this.app.config.apiBaseURL}/products/${productId}/history?days=7`);
if (!response.ok) return '';
const data = await response.json();
if (!data.history || data.history.length < 2) return '';
const prices = data.history.map(h => h.unit_price);
const max = Math.max(...prices);
const min = Math.min(...prices);
const range = max - min;
if (range === 0) return ''; // No price changes
const bars = prices.map((price, index) => {
const height = range > 0 ? ((price - min) / range) * 100 : 50;
const direction = index > 0 && price > prices[index - 1] ? 'up' :
index > 0 && price < prices[index - 1] ? 'down' : '';
return `<div class="sparkline-bar ${direction}" style="height: ${height}%"></div>`;
}).join('');
return `
<div class="product-sparkline-container">
<div class="product-sparkline">${bars}</div>
<div class="sparkline-label">Últ. 7 días</div>
</div>
`;
} catch (error) {
console.warn('Error fetching sparkline:', error);
return '';
}
}
/**
* Generate price alert badge HTML
*/
getPriceAlertBadgeHTML(productId) {
if (!this.priceAlerts[productId]) return '';
return `
<div class="price-alert-badge">
<i class="fas fa-bell"></i>
</div>
`;
}
/**
* Generate price dropped badge HTML
*/
getPriceDroppedBadgeHTML(product) {
if (!product.price_decreased) return '';
const savings = this.calculateSavings(product);
if (!savings) return '';
return `
<div class="price-dropped-badge">
<i class="fas fa-arrow-down"></i> -${savings.amount}€
</div>
`;
}
// =====================================================
// PRICE ALERTS SYSTEM
// =====================================================
/**
* Load price alerts from localStorage
*/
loadPriceAlerts() {
try {
const stored = localStorage.getItem('mercadona_price_alerts');
return stored ? JSON.parse(stored) : {};
} catch (error) {
console.warn('Error loading price alerts:', error);
return {};
}
}
/**
* Save price alerts to localStorage
*/
savePriceAlerts() {
try {
localStorage.setItem('mercadona_price_alerts', JSON.stringify(this.priceAlerts));
} catch (error) {
console.warn('Error saving price alerts:', error);
}
}
/**
* Set price alert for a product
*/
setPriceAlert(productId, currentPrice, threshold = 5) {
this.priceAlerts[productId] = {
price: currentPrice,
threshold: threshold,
setAt: Date.now()
};
this.savePriceAlerts();
}
/**
* Remove price alert
*/
removePriceAlert(productId) {
delete this.priceAlerts[productId];
this.savePriceAlerts();
}
/**
* Check for price drops on favorites
*/
async checkPriceAlerts() {
const favorites = Array.from(this.app.state.favorites);
const droppedPrices = [];
for (const productId of favorites) {
const alert = this.priceAlerts[productId];
if (!alert) continue;
const product = this.app.state.products.find(p => p.id === productId);
if (!product) continue;
const currentPrice = parseFloat(product.price.replace(',', '.'));
const savedPrice = alert.price;
const drop = ((savedPrice - currentPrice) / savedPrice) * 100;
if (drop >= alert.threshold) {
droppedPrices.push({
product,
drop: drop.toFixed(1),
savedPrice: savedPrice.toFixed(2)
});
}
// Update stored price
this.priceAlerts[productId].price = currentPrice;
}
if (droppedPrices.length > 0) {
this.showPriceDropNotification(droppedPrices);
}
this.savePriceAlerts();
}
/**
* Show notification for price drops
*/
showPriceDropNotification(droppedPrices) {
const count = droppedPrices.length;
const message = count === 1
? `¡${droppedPrices[0].product.name} bajó ${droppedPrices[0].drop}%!`
: `¡${count} favoritos bajaron de precio!`;
this.app.utils.showToast(message, 'success');
// Update header badge
this.updatePriceDropBadge(count);
}
/**
* Update header badge for price drops
*/
updatePriceDropBadge(count) {
const badge = document.getElementById('price-drops-badge');
if (!badge) {
// Create badge
const cartBtn = document.getElementById('cart-btn');
if (cartBtn) {
const newBadge = document.createElement('span');
newBadge.id = 'price-drops-badge';
newBadge.className = 'badge badge-alert';
newBadge.textContent = count;
newBadge.style.background = '#22c55e';
newBadge.style.position = 'absolute';
newBadge.style.top = '-4px';
newBadge.style.left = '-4px';
cartBtn.parentElement.style.position = 'relative';
cartBtn.parentElement.appendChild(newBadge);
}
} else {
badge.textContent = count;
badge.style.display = count > 0 ? 'flex' : 'none';
}
}
// =====================================================
// COMPARISON MODE
// =====================================================
/**
* Setup comparison mode
*/
setupComparisonMode() {
// Create compare FAB
const fab = document.createElement('button');
fab.id = 'compare-fab';
fab.className = 'compare-fab';
fab.innerHTML = `
<i class="fas fa-balance-scale"></i>
<span class="compare-fab-count">0</span>
`;
fab.addEventListener('click', () => this.openComparison());
document.body.appendChild(fab);
this.compareFab = fab;
}
/**
* Toggle comparison mode
*/
toggleComparisonMode() {
this.comparisonMode = !this.comparisonMode;
document.body.classList.toggle('comparison-mode', this.comparisonMode);
if (!this.comparisonMode) {
this.selectedProducts.clear();
this.updateCompareFab();
}
}
/**
* Toggle product selection for comparison
*/
toggleProductSelection(productId) {
if (this.selectedProducts.has(productId)) {
this.selectedProducts.delete(productId);
} else {
if (this.selectedProducts.size >= 4) {
this.app.utils.showToast('Máximo 4 productos para comparar', 'warning');
return;
}
this.selectedProducts.add(productId);
}
this.updateCompareFab();
this.updateProductCheckboxes();
}
/**
* Update compare FAB
*/
updateCompareFab() {
const count = this.selectedProducts.size;
this.compareFab.classList.toggle('visible', count >= 2);
this.compareFab.querySelector('.compare-fab-count').textContent = count;
}
/**
* Update product checkboxes
*/
updateProductCheckboxes() {
document.querySelectorAll('.compare-checkbox').forEach(checkbox => {
const productId = checkbox.dataset.productId;
checkbox.classList.toggle('checked', this.selectedProducts.has(productId));
});
}
/**
* Open comparison modal
*/
async openComparison() {
if (this.selectedProducts.size < 2) return;
const products = Array.from(this.selectedProducts).map(id =>
this.app.state.products.find(p => p.id === id)
).filter(Boolean);
// Create comparison modal
const modal = this.createComparisonModal(products);
document.body.appendChild(modal);
// Show modal
setTimeout(() => modal.classList.add('active'), 10);
}
/**
* Create comparison modal
*/
createComparisonModal(products) {
const modal = document.createElement('div');
modal.className = 'modal comparison-modal';
modal.innerHTML = `
<div class="modal-overlay"></div>
<div class="modal-content" style="max-width: 1200px;">
<div class="modal-header">
<h2 class="modal-title">Comparar Productos</h2>
<button class="modal-close" aria-label="Cerrar">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<div class="comparison-table-container">
${this.createComparisonTable(products)}
</div>
</div>
</div>
`;
// Close handlers
modal.querySelector('.modal-close').addEventListener('click', () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
});
modal.querySelector('.modal-overlay').addEventListener('click', () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
});
return modal;
}
/**
* Create comparison table HTML
*/
createComparisonTable(products) {
return `
<table class="comparison-table">
<thead>
<tr>
<th>Característica</th>
${products.map(p => `<th>${p.name}</th>`).join('')}
</tr>
</thead>
<tbody>
<tr>
<td><strong>Imagen</strong></td>
${products.map(p => `
<td><img src="${p.image}" alt="${p.name}" style="max-width: 150px;"></td>
`).join('')}
</tr>
<tr>
<td><strong>Precio</strong></td>
${products.map(p => `<td class="text-gradient">${p.price}€</td>`).join('')}
</tr>
<tr>
<td><strong>Precio/Unidad</strong></td>
${products.map(p => `<td>${p.reference_price ? p.reference_price + '€/' + p.reference_format : '-'}</td>`).join('')}
</tr>
<tr>
<td><strong>Pack</strong></td>
${products.map(p => `<td>${p.is_pack ? `Sí (${p.total_units} ${p.unit_name || 'uds'})` : 'No'}</td>`).join('')}
</tr>
<tr>
<td><strong>IVA</strong></td>
${products.map(p => `<td>${p.tax_percentage ? p.tax_percentage + '%' : '-'}</td>`).join('')}
</tr>
<tr>
<td><strong>Categoría</strong></td>
${products.map(p => `<td>${p.category}</td>`).join('')}
</tr>
</tbody>
</table>
`;
}
// =====================================================
// ADVANCED FILTERS
// =====================================================
/**
* Create advanced filter chips
*/
createAdvancedFilters() {
const container = document.createElement('div');
container.className = 'advanced-filters-section';
container.innerHTML = `
<h3 class="sidebar-title"><i class="fas fa-sliders-h"></i> Filtros Rápidos</h3>
<div class="filter-chips-container">
<button class="filter-chip" data-filter="discounted">
<i class="fas fa-percent"></i> Rebajados
<span class="filter-chip-count" id="filter-count-discounted">0</span>
</button>
<button class="filter-chip" data-filter="new">
<i class="fas fa-star"></i> Novedades
<span class="filter-chip-count" id="filter-count-new">0</span>
</button>
<button class="filter-chip" data-filter="packs">
<i class="fas fa-box"></i> Packs
<span class="filter-chip-count" id="filter-count-packs">0</span>
</button>
</div>
<div class="smart-filters-section">
<div class="smart-filters-title">Filtros Inteligentes</div>
<div class="filter-chips-container">
<button class="filter-chip" data-filter="crazy-deals">
<i class="fas fa-fire"></i> Ofertas Locas (>30%)
<span class="filter-chip-count" id="filter-count-crazy">0</span>
</button>
<button class="filter-chip" data-filter="family-packs">
<i class="fas fa-users"></i> Packs Familiares (>6 uds)
<span class="filter-chip-count" id="filter-count-family">0</span>
</button>
</div>
</div>
`;
return container;
}
/**
* Update filter counts
*/
updateFilterCounts(products) {
const counts = {
discounted: products.filter(p => p.hasDiscount).length,
new: products.filter(p => p.isNovelty).length,
packs: products.filter(p => p.is_pack).length,
crazy: products.filter(p => {
const savings = this.calculateSavings(p);
return savings && savings.percentage >= 30;
}).length,
family: products.filter(p => p.is_pack && p.total_units > 6).length
};
Object.entries(counts).forEach(([key, count]) => {
const el = document.getElementById(`filter-count-${key}`);
if (el) el.textContent = count;
});
}
/**
* Apply advanced filter
*/
applyAdvancedFilter(filterType) {
const products = this.app.state.products;
let filtered = [];
switch (filterType) {
case 'discounted':
filtered = products.filter(p => p.hasDiscount);
break;
case 'new':
filtered = products.filter(p => p.isNovelty);
break;
case 'packs':
filtered = products.filter(p => p.is_pack);
break;
case 'crazy-deals':
filtered = products.filter(p => {
const savings = this.calculateSavings(p);
return savings && savings.percentage >= 30;
});
break;
case 'family-packs':
filtered = products.filter(p => p.is_pack && p.total_units > 6);
break;
}
this.app.state.filteredProducts = filtered;
this.app.updateProductsDisplay();
}
}
// Export for use in main app
if (typeof module !== 'undefined' && module.exports) {
module.exports = MercadonaEnhancements;
}