-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-adapter.js
More file actions
364 lines (304 loc) · 9.06 KB
/
api-adapter.js
File metadata and controls
364 lines (304 loc) · 9.06 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
/**
* API ADAPTER
* Adaptador para consumir la API backend en lugar del CSV estático
* Mantiene compatibilidad con el código existente
*/
class MercadonaAPIAdapter {
constructor(config = {}) {
this.apiBaseURL = config.apiBaseURL || 'http://localhost:8000/api';
this.useAPI = config.useAPI !== false; // Por defecto usa API
this.fallbackToCSV = config.fallbackToCSV !== false; // Fallback a CSV si falla
this.cache = {
products: null,
categories: null,
lastUpdate: null
};
this.cacheTimeout = config.cacheTimeout || 5 * 60 * 1000; // 5 minutos
}
/**
* Carga productos (desde API o CSV como fallback)
*/
async loadProducts() {
if (this.useAPI) {
try {
return await this.loadFromAPI();
} catch (error) {
console.warn('Error cargando desde API, usando fallback a CSV:', error);
if (this.fallbackToCSV) {
return await this.loadFromCSV();
}
throw error;
}
} else {
return await this.loadFromCSV();
}
}
/**
* Carga productos desde la API backend
*/
async loadFromAPI() {
// Verificar cache
if (this.cache.products && this.isCacheValid()) {
console.log('Usando datos cacheados');
return this.cache.products;
}
console.log('Cargando productos desde API...');
const response = await fetch(`${this.apiBaseURL}/products?limit=10000`);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
// Transformar al formato esperado por la app
const products = data.products.map(p => this.transformProduct(p));
// Cachear
this.cache.products = products;
this.cache.lastUpdate = Date.now();
console.log(`✓ Cargados ${products.length} productos desde API`);
return products;
}
/**
* Carga productos desde CSV (modo legacy)
*/
async loadFromCSV() {
console.log('Cargando productos desde CSV...');
const csvPaths = [
'data/processed/products_macro.csv',
'./data/processed/products_macro.csv',
'../data/processed/products_macro.csv'
];
for (const path of csvPaths) {
try {
const response = await fetch(path);
if (response.ok) {
const csvText = await response.text();
return await this.parseCSV(csvText);
}
} catch (error) {
continue;
}
}
throw new Error('No se pudo cargar el archivo CSV');
}
/**
* Parsea CSV usando PapaParse
*/
parseCSV(csvText) {
return new Promise((resolve, reject) => {
Papa.parse(csvText, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
complete: (results) => {
if (results.errors.length > 0) {
console.warn('Errores al parsear CSV:', results.errors);
}
resolve(results.data);
},
error: (error) => reject(error)
});
});
}
/**
* Transforma producto de API al formato CSV esperado por processProductData()
*
* IMPORTANTE: processProductData() espera el formato del CSV original:
* - name: string
* - Category: string (con C mayúscula)
* - price: string (no número)
* - image_url: string
* - novedad: boolean/string
* - discount_price: string (opcional)
*/
transformProduct(apiProduct) {
// Mejorar calidad de imágenes (600x600 en lugar de 300x300)
const improveImageQuality = (url) => {
if (!url) return '';
return url.replace('h=300&w=300', 'h=600&w=600');
};
return {
// ID debe ser el ID de Mercadona (string)
id: apiProduct.id,
// Nombre
name: apiProduct.display_name || '',
subtitle: apiProduct.packaging || '',
// Categoría (con C mayúscula como espera el CSV)
Category: apiProduct.category_name || 'Sin categoría',
// Precio como STRING (como en CSV)
price: apiProduct.unit_price ? apiProduct.unit_price.toString() : '0',
// Descuento (si el precio anterior existe y es diferente)
discount_price: apiProduct.previous_unit_price && apiProduct.previous_unit_price !== apiProduct.unit_price
? apiProduct.previous_unit_price.toString()
: '',
// Imágenes en alta calidad (600x600)
image_url: improveImageQuality(apiProduct.thumbnail),
main_image_url: improveImageQuality(apiProduct.thumbnail),
secondary_image_url: '',
// Flags
novedad: apiProduct.is_new || false,
// Info adicional mejorada
nutritional_info: this._buildProductInfo(apiProduct),
// Datos extra de la API (para referencia)
slug: apiProduct.slug,
share_url: apiProduct.share_url,
packaging: apiProduct.packaging,
bulk_price: apiProduct.bulk_price,
reference_price: apiProduct.reference_price,
unit_size: apiProduct.unit_size,
size_format: apiProduct.size_format,
reference_format: apiProduct.reference_format,
parent_category: apiProduct.parent_category,
is_pack: apiProduct.is_pack,
pack_size: apiProduct.pack_size,
total_units: apiProduct.total_units,
unit_name: apiProduct.unit_name,
tax_percentage: apiProduct.tax_percentage,
price_decreased: apiProduct.price_decreased,
updated_at: apiProduct.updated_at
};
}
/**
* Busca productos (con API es más eficiente)
*/
async searchProducts(query) {
if (!this.useAPI) {
// Si no usa API, que la app haga la búsqueda local
return null;
}
try {
const response = await fetch(
`${this.apiBaseURL}/search?q=${encodeURIComponent(query)}&limit=100`
);
if (!response.ok) return null;
const data = await response.json();
return data.products.map(p => this.transformProduct(p));
} catch (error) {
console.warn('Error en búsqueda por API:', error);
return null;
}
}
/**
* Obtiene categorías
*/
async getCategories() {
if (!this.useAPI) {
return null;
}
try {
const response = await fetch(`${this.apiBaseURL}/categories`);
if (!response.ok) return null;
const data = await response.json();
return data.categories;
} catch (error) {
console.warn('Error obteniendo categorías:', error);
return null;
}
}
/**
* Obtiene detalle de producto
*/
async getProductDetail(productId) {
if (!this.useAPI) {
return null;
}
try {
const response = await fetch(`${this.apiBaseURL}/products/${productId}`);
if (!response.ok) return null;
const product = await response.json();
return this.transformProduct(product);
} catch (error) {
console.warn('Error obteniendo detalle de producto:', error);
return null;
}
}
/**
* Obtiene histórico de precios
*/
async getPriceHistory(productId, days = 30) {
if (!this.useAPI) {
return null;
}
try {
const response = await fetch(
`${this.apiBaseURL}/products/${productId}/history?days=${days}`
);
if (!response.ok) return null;
return await response.json();
} catch (error) {
console.warn('Error obteniendo histórico de precios:', error);
return null;
}
}
/**
* Obtiene estadísticas
*/
async getStats() {
if (!this.useAPI) {
return null;
}
try {
const response = await fetch(`${this.apiBaseURL}/stats`);
if (!response.ok) return null;
return await response.json();
} catch (error) {
console.warn('Error obteniendo estadísticas:', error);
return null;
}
}
/**
* Dispara actualización de datos
*/
async triggerUpdate() {
if (!this.useAPI) {
return false;
}
try {
const response = await fetch(`${this.apiBaseURL}/update`, {
method: 'POST'
});
return response.ok;
} catch (error) {
console.warn('Error disparando actualización:', error);
return false;
}
}
/**
* Construye información detallada del producto
*/
_buildProductInfo(apiProduct) {
const info = [];
// Información de pack
if (apiProduct.is_pack && apiProduct.total_units) {
info.push(`Pack de ${apiProduct.total_units} ${apiProduct.unit_name || 'unidades'}`);
}
// Tamaño/peso
if (apiProduct.unit_size && apiProduct.size_format) {
info.push(`${apiProduct.unit_size} ${apiProduct.size_format}`);
}
// Precio de referencia
if (apiProduct.reference_price && apiProduct.reference_format) {
info.push(`${apiProduct.reference_price}€/${apiProduct.reference_format}`);
}
// IVA
if (apiProduct.tax_percentage) {
info.push(`IVA: ${apiProduct.tax_percentage}%`);
}
return info.join(' • ');
}
/**
* Verifica si el cache es válido
*/
isCacheValid() {
if (!this.cache.lastUpdate) return false;
return (Date.now() - this.cache.lastUpdate) < this.cacheTimeout;
}
/**
* Invalida cache
*/
invalidateCache() {
this.cache.products = null;
this.cache.categories = null;
this.cache.lastUpdate = null;
}
}
// Exportar para uso global
window.MercadonaAPIAdapter = MercadonaAPIAdapter;