diff --git a/scripts/importAgribalyse.mjs b/scripts/importAgribalyse.mjs new file mode 100644 index 0000000..acc5f36 --- /dev/null +++ b/scripts/importAgribalyse.mjs @@ -0,0 +1,79 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import { dirname, resolve } from 'node:path'; + +const datasetUrl = 'https://data.ademe.fr/data-fair/api/v1/datasets/agribalyse-31-synthese'; +const outputPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src/data/agribalyse.js'); +const version = '3.2'; +const fields = { + climate: ['Changement_climatique', 'kg CO2 eq/kg de produit'], + landUse: ['Utilisation_du_sol', 'Pt/kg de produit'], + waterScarcity: ['Épuisement_des_ressources_eau', 'm3 depriv./kg de produit'], + singleScore: ['Score_unique_EF', 'mPt/kg de produit'] +}; + +function finite(value) { + return typeof value === 'number' && Number.isFinite(value) ? value : null; +} + +async function getJson(url) { + const response = await fetch(url, { headers: { Accept: 'application/json' } }); + if (!response.ok) throw new Error(`ADEME request failed: ${response.status} ${url}`); + return response.json(); +} + +export async function importAgribalyse({ fetchJson = getJson, write = writeFile } = {}) { + const metadata = await fetchJson(datasetUrl); + if (!metadata.description?.includes(`AGRIBALYSE® v${version}`)) { + throw new Error('ADEME dataset version changed; review schema and units before importing.'); + } + for (const [key, [column, unit]] of Object.entries(fields)) { + const schema = metadata.schema?.find((item) => item.key === column); + if (!schema || !schema.description?.includes(unit)) { + throw new Error(`Missing or changed ${column} (${unit}); review the ADEME schema.`); + } + } + + const rows = []; + let next = `${datasetUrl}/lines?size=500`; + while (next) { + const page = await fetchJson(next); + if (!Array.isArray(page.results)) throw new Error('Invalid ADEME response.'); + rows.push(...page.results); + next = page.next || null; + } + const products = rows.map((row) => ({ + id: String(row.Code_AGB || ''), + ciqualCode: String(row.Code_CIQUAL || ''), + nameEn: row.LCI_Name || '', + nameFr: row['Nom_du_Produit_en_Français'] || '', + group: row["Groupe_d'aliment"] || '', + subgroup: row["Sous-groupe_d'aliment"] || '', + preparation: row['Préparation'] || '', + delivery: row.Livraison || '', + climate: finite(row[fields.climate[0]]), + landUse: finite(row[fields.landUse[0]]), + waterScarcity: finite(row[fields.waterScarcity[0]]), + singleScore: finite(row[fields.singleScore[0]]) + })).filter((row) => row.id && row.climate !== null); + if (products.length < 2000 || new Set(products.map((row) => row.id)).size !== products.length) { + throw new Error(`Incomplete or duplicate ADEME dataset (${products.length} records).`); + } + const snapshot = { + version, + source: datasetUrl, + sourceId: metadata.id, + dataUpdatedAt: metadata.dataUpdatedAt, + reference: '1 kg of food consumed by the consumer (French-market average)', + units: Object.fromEntries(Object.entries(fields).map(([key, [, unit]]) => [key, unit])), + products + }; + await mkdir(dirname(outputPath), { recursive: true }); + await write(outputPath, `// Generated by scripts/importAgribalyse.mjs from ADEME's public finished-food summary.\nexport default ${JSON.stringify(snapshot)};\n`); + return products.length; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const count = await importAgribalyse(); + console.log(`Imported ${count} AGRIBALYSE ${version} finished-food entries to ${outputPath}`); +} diff --git a/src/services/productApi.js b/src/services/productApi.js index e462567..50cb0fe 100644 --- a/src/services/productApi.js +++ b/src/services/productApi.js @@ -1,6 +1,7 @@ import { enrichEnvironmentalProduct, productSpecificFootprint } from './environmentalService.js'; const openFoodFactsBaseUrl = 'https://world.openfoodfacts.org'; +const CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000; const productFields = [ 'code', 'last_modified_datetime', @@ -25,6 +26,7 @@ const productFields = [ 'ingredients_from_palm_oil_tags', 'additives_tags', 'allergens_tags', + 'traces_tags', 'nutriments', 'nutrient_levels', 'nutriscore_grade', @@ -48,8 +50,8 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline const normalizedBarcode = normalizeBarcode(barcode); const cachedProduct = productCache[normalizedBarcode] || productCache[barcode]; - if (cachedProduct) { - return { status: 'found', product: { ...enrichEnvironmentalProduct(cachedProduct), dataSource: 'cache' }, source: 'cache' }; + if (cachedProduct && (offlineModeEnabled || isFreshCacheEntry(cachedProduct))) { + return cachedResult(cachedProduct); } if (offlineModeEnabled) { @@ -65,6 +67,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline ); if (!response.ok) { + if (cachedProduct) return cachedResult(cachedProduct, true); return { status: 'error', errorMessage: 'Open Food Facts konnte gerade nicht erreicht werden.' @@ -73,6 +76,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline const payload = await response.json(); if (payload?.status !== 1 || !payload.product || typeof payload.product !== 'object' || Array.isArray(payload.product)) { + if (cachedProduct) return cachedResult(cachedProduct, true); return { status: 'notFound', errorMessage: 'Kein Produkt zu diesem Barcode in Open Food Facts gefunden.' @@ -81,10 +85,16 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline return { status: 'found', - product: mapOpenFoodFactsProduct(payload.product, normalizedBarcode), + product: { + ...mapOpenFoodFactsProduct(payload.product, normalizedBarcode), + price: cachedProduct?.price, + currency: cachedProduct?.currency || 'CHF', + createdAt: cachedProduct?.createdAt || new Date().toISOString() + }, source: 'open-food-facts' }; } catch (error) { + if (cachedProduct) return cachedResult(cachedProduct, true); return { status: 'error', errorMessage: 'Netzwerkfehler beim Laden von Open Food Facts.' @@ -92,6 +102,20 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline } } +function isFreshCacheEntry(product) { + const checkedAt = Date.parse(product.fetchedAt || ''); + return Number.isFinite(checkedAt) && Date.now() - checkedAt >= 0 + && Date.now() - checkedAt < CACHE_MAX_AGE_MS; +} + +function cachedResult(product, stale = false) { + return { + status: 'found', + product: { ...enrichEnvironmentalProduct(product), dataSource: 'cache', cacheStale: stale }, + source: 'cache' + }; +} + export async function searchProducts(query, productCache = {}, offlineModeEnabled = false) { const normalizedQuery = query.trim().toLowerCase(); const cachedProducts = Object.values(productCache); @@ -145,6 +169,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { id: `off-${barcode}`, barcode, dataSource: 'open-food-facts', + fetchedAt: now, name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`, brand: firstTextValue(product.brands), category: firstCategory(product.categories, product.categories_tags), @@ -167,6 +192,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { additives: normalizeAdditives(product.additives_tags || []) }, allergens: normalizeAllergens(product.allergens_tags || []), + allergenTraces: normalizeAllergens(product.traces_tags || []), nutrition: { caloriesPer100g: numberOrUndefined(nutriments['energy-kcal_100g']), energyKjPer100g: numberOrUndefined(nutriments['energy-kj_100g'] ?? nutriments.energy_100g), @@ -191,12 +217,17 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { footprint, carbonFootprintKgCo2ePerKg: footprint.status === 'product-specific' ? footprint.valueKgCo2ePerKg : undefined, isBio: Array.isArray(product.labels_tags) ? hasOrganicLabel(product.labels_tags) : undefined, - originCountry: firstOrigin(product.origins, product.origins_tags, product.countries_tags), + originCountry: firstOrigin(product.origins, product.origins_tags), + originSource: firstOrigin(product.origins, product.origins_tags) ? 'ingredient-origin' : undefined, + sellingCountries: normalizeTags(product.countries_tags), packaging: firstTextValue(product.packaging) }, dataCompleteness: { allergens: Array.isArray(product.allergens_tags), - additives: Array.isArray(product.additives_tags), + allergensVerified: false, + traces: Array.isArray(product.traces_tags), + additives: Array.isArray(product.additives_tags) + && (product.additives_tags.length > 0 || Boolean(product.ingredients_text_de || product.ingredients_text || product.ingredients_text_en)), ecoScore: Boolean(ecoScore), ingredients: Boolean(product.ingredients_text_de || product.ingredients_text || product.ingredients_text_en), nutriScore: Boolean(nutriScore), @@ -248,10 +279,9 @@ function firstCategory(categories, categoryTags = []) { return tag ? cleanTag(tag) : undefined; } -function firstOrigin(origins, originTags = [], countryTags = []) { +function firstOrigin(origins, originTags = []) { return firstTextValue(origins) - || cleanTag((Array.isArray(originTags) ? originTags : []).find(Boolean)) - || cleanTag((Array.isArray(countryTags) ? countryTags : []).find(Boolean)); + || cleanTag((Array.isArray(originTags) ? originTags : []).find(Boolean)); } function parseIngredients(ingredientsText) {