This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user