-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-integration-patch.js
More file actions
131 lines (111 loc) · 4.02 KB
/
api-integration-patch.js
File metadata and controls
131 lines (111 loc) · 4.02 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
/**
* PARCHE DE INTEGRACIÓN API
* Integra el adaptador API con la aplicación existente
*
* Este archivo parchea el método loadData() de MercadonaApp
* para usar el adaptador API en lugar de cargar directamente el CSV.
*
* IMPORTANTE: Este script se carga con 'defer' ANTES de script.js
* para garantizar que el patch se aplique antes de que MercadonaApp se inicialice
*/
(function() {
'use strict';
// Verificar que todo esté disponible
if (typeof MercadonaAPIAdapter === 'undefined') {
console.error('❌ MercadonaAPIAdapter no está definido. Asegúrate de que api-adapter.js se carga primero.');
return;
}
// Inicializar el adaptador API
const apiAdapter = new MercadonaAPIAdapter({
apiBaseURL: window.AppConfig?.api?.baseURL || 'http://localhost:8000/api',
useAPI: window.AppConfig?.api?.enabled !== false,
fallbackToCSV: window.AppConfig?.api?.fallbackToCSV !== false,
cacheTimeout: window.AppConfig?.api?.cacheTimeout || 5 * 60 * 1000
});
// Guardar referencia global para debugging
window.apiAdapter = apiAdapter;
// Guardar función para parchear cuando MercadonaApp esté definido
window.applyMercadonaAPIPatch = function() {
if (typeof MercadonaApp === 'undefined') {
console.warn('⚠️ MercadonaApp aún no está definido');
return false;
}
// Parchear el prototipo de MercadonaApp
const originalLoadData = MercadonaApp.prototype.loadData;
MercadonaApp.prototype.loadData = async function() {
try {
this.setLoading(true);
// Usar el adaptador para cargar productos
console.log('📡 Cargando productos mediante adaptador API...');
const data = await apiAdapter.loadProducts();
console.log(`✅ Productos cargados: ${data.length}`);
// Procesar datos como siempre
this.processProductData(data);
this.setLoading(false);
} catch (error) {
console.error('❌ Error al cargar datos:', error);
this.utils.showToast('Error al cargar los productos', 'error');
this.setLoading(false);
}
};
// Extender con métodos adicionales para funcionalidades de API
/**
* Obtiene histórico de precios de un producto
*/
MercadonaApp.prototype.getPriceHistory = async function(productId) {
try {
const history = await apiAdapter.getPriceHistory(productId, 30);
return history;
} catch (error) {
console.error('Error obteniendo histórico:', error);
return null;
}
};
/**
* Obtiene estadísticas de la app
*/
MercadonaApp.prototype.getStats = async function() {
try {
const stats = await apiAdapter.getStats();
return stats;
} catch (error) {
console.error('Error obteniendo estadísticas:', error);
return null;
}
};
/**
* Refresca los datos desde la API
*/
MercadonaApp.prototype.refreshData = async function() {
apiAdapter.invalidateCache();
this.utils.showToast('Actualizando productos...', 'info');
await this.loadData();
this.utils.showToast('Productos actualizados', 'success');
};
/**
* Dispara actualización en el backend
*/
MercadonaApp.prototype.triggerBackendUpdate = async function() {
try {
const success = await apiAdapter.triggerUpdate();
if (success) {
this.utils.showToast('Actualización iniciada en el servidor', 'success');
return true;
} else {
this.utils.showToast('No se pudo iniciar la actualización', 'error');
return false;
}
} catch (error) {
console.error('Error disparando actualización:', error);
this.utils.showToast('Error al comunicarse con el servidor', 'error');
return false;
}
};
console.log('✅ Parche de integración API aplicado correctamente');
return true;
};
// Intentar aplicar inmediatamente (por si MercadonaApp ya existe)
if (typeof MercadonaApp !== 'undefined') {
window.applyMercadonaAPIPatch();
}
})();