improve product search and barcode scanning
Android Release Build / build-android (push) Failing after 7m42s

This commit is contained in:
2026-11-20 00:51:47 +01:00
parent 460ca60914
commit ab963d8421
8 changed files with 281 additions and 134 deletions
+2 -1
View File
@@ -11,7 +11,8 @@ export default function ManualSearchInput({ value, onChangeText, onSubmit, disab
autoCapitalize="none"
onChangeText={onChangeText}
onSubmitEditing={onSubmit}
editable={!disabled}
accessibilityState={{ busy: disabled }}
editable
placeholder={placeholder}
placeholderTextColor={colors.muted}
returnKeyType="search"
+14 -3
View File
@@ -4,7 +4,7 @@ import { colors } from '../../utils/constants';
import ProductImage from './ProductImage';
import ProductScoreBadge from './ProductScoreBadge';
export default function ProductCard({ product, rating, onPress }) {
export default function ProductCard({ product, rating, onPress, searchMetadata }) {
return (
<Pressable accessibilityRole="button" onPress={onPress} style={styles.card}>
<View style={styles.topRow}>
@@ -24,6 +24,14 @@ export default function ProductCard({ product, rating, onPress }) {
{rating ? <ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} /> : null}
<Text style={styles.openLabel}>Details ansehen ›</Text>
</View>
{searchMetadata ? (
<View style={styles.searchMeta}>
<Text style={styles.matchLabel}>{searchMetadata.matchLabel}</Text>
<Text style={styles.coverageLabel}>
{searchMetadata.dataCoverage}% Produktdaten · {searchMetadata.freshnessLabel}
</Text>
</View>
) : null}
{rating?.allergenReviewRequired ? <Text style={styles.allergenWarning}>{rating.allergenReviewMessage}</Text> : null}
{rating?.staleDataReviewRequired ? <Text style={styles.allergenWarning}>Gespeicherte Produktdaten sind veraltet.</Text> : null}
</Pressable>
@@ -33,7 +41,7 @@ export default function ProductCard({ product, rating, onPress }) {
function sourceLabel(source) {
const labels = {
cache: 'Lokaler Cache',
local: 'Lokale Beispieldaten',
local: 'Lokal erfasst',
'open-food-facts': 'Open Food Facts'
};
@@ -97,5 +105,8 @@ const styles = StyleSheet.create({
paddingHorizontal: 8,
paddingVertical: 4
},
allergenWarning: { color: colors.danger, fontSize: 14, fontWeight: '800' }
allergenWarning: { color: colors.danger, fontSize: 14, fontWeight: '800' },
searchMeta: { backgroundColor: colors.background, borderRadius: 10, gap: 3, padding: 10 },
matchLabel: { color: colors.primaryDark, fontSize: 12, fontWeight: '800' },
coverageLabel: { color: colors.muted, fontSize: 12, lineHeight: 17 }
});
+8 -4
View File
@@ -3,7 +3,13 @@ import { StyleSheet, Text, View } from 'react-native';
import { colors } from '../../utils/constants';
export default function BarcodeScannerView({ isLoadingProduct, isScanning, onBarcodeScanned }) {
export default function BarcodeScannerView({ detectedBarcode, isLoadingProduct, isScanning, onBarcodeScanned }) {
const hint = isLoadingProduct && detectedBarcode
? `Barcode ${detectedBarcode} erkannt. Produkt wird geladen ...`
: !isScanning
? 'Scan pausiert.'
: 'Barcode in den Rahmen halten. Bei Problemen manuell suchen.';
return (
<View style={styles.wrap}>
<CameraView
@@ -15,9 +21,7 @@ export default function BarcodeScannerView({ isLoadingProduct, isScanning, onBar
>
<View style={styles.overlay}>
<View style={styles.frame} />
<Text style={styles.hint}>
{isLoadingProduct ? 'Produkt wird geladen...' : 'Barcode in den Rahmen halten. Bei Problemen manuell suchen.'}
</Text>
<Text accessibilityLiveRegion="polite" style={styles.hint}>{hint}</Text>
</View>
</CameraView>
</View>
+2 -2
View File
@@ -4,12 +4,12 @@ import PrimaryButton from '../PrimaryButton';
import SecondaryButton from '../SecondaryButton';
import { colors } from '../../utils/constants';
export default function ScanErrorModal({ visible, message, onRetry, onManualSearch, onClose, onCreateLocalProduct }) {
export default function ScanErrorModal({ visible, title = 'Scan nicht erfolgreich', message, onRetry, onManualSearch, onClose, onCreateLocalProduct }) {
return (
<Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>
<View style={styles.backdrop}>
<View style={styles.modal}>
<Text style={styles.title}>Scan nicht erfolgreich</Text>
<Text style={styles.title}>{title}</Text>
<Text style={styles.message}>{message}</Text>
<PrimaryButton label="Erneut scannen" onPress={onRetry} />
<SecondaryButton label="Manuell eingeben" onPress={onManualSearch} />
+188 -87
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { useCameraPermissions } from 'expo-camera';
@@ -11,32 +11,58 @@ import SectionTitle from '../components/layout/SectionTitle';
import ProductCard from '../components/product/ProductCard';
import BarcodeScannerView from '../components/scan/BarcodeScannerView';
import ScanErrorModal from '../components/scan/ScanErrorModal';
import { searchProducts } from '../services/productApi';
import { searchProductsWithStatus } from '../services/productApi';
import { calculateProductRating } from '../services/ratingService';
import {
buildSearchResultMetadata,
isDuplicateBarcodeScan,
normalizeScannedBarcode,
shouldApplySearchResponse
} from '../services/searchResultService';
import { colors } from '../utils/constants';
export default function ScanScreen({ preferences, productCache, shoppingList, onScanBarcode, onOpenProduct, onCreateLocalProduct }) {
const [permission, requestPermission] = useCameraPermissions();
const [isScanning, setIsScanning] = useState(true);
const [isLoadingProduct, setIsLoadingProduct] = useState(false);
const [detectedBarcode, setDetectedBarcode] = useState('');
const [scanErrorTitle, setScanErrorTitle] = useState('Scan nicht erfolgreich');
const [scanError, setScanError] = useState('');
const [missingBarcode, setMissingBarcode] = useState('');
const [isErrorModalVisible, setIsErrorModalVisible] = useState(false);
const [manualSearchQuery, setManualSearchQuery] = useState('');
const [lastSearchQuery, setLastSearchQuery] = useState('');
const [manualResults, setManualResults] = useState([]);
const [isSearching, setIsSearching] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [searchError, setSearchError] = useState('');
const [searchFeedback, setSearchFeedback] = useState(null);
const lastScanRef = useRef(null);
const searchRequestRef = useRef({ id: 0, controller: null });
useEffect(() => () => searchRequestRef.current.controller?.abort(), []);
async function handleBarcodeScanned(event) {
if (!isScanning) return;
setMissingBarcode('');
const barcode = normalizeScannedBarcode(event.data);
if (!barcode) {
setIsScanning(false);
setScanErrorTitle('Kein Produktbarcode erkannt');
setScanError('Der erkannte Code ist kein unterstützter Produktbarcode mit 8 bis 14 Ziffern.');
setIsErrorModalVisible(true);
return;
}
const now = Date.now();
if (isDuplicateBarcodeScan(lastScanRef.current, barcode, now)) return;
lastScanRef.current = { barcode, at: now };
setDetectedBarcode(barcode);
setIsScanning(false);
setIsLoadingProduct(true);
let result;
try {
result = await onScanBarcode(event.data);
result = await onScanBarcode(barcode);
} catch (error) {
result = { status: 'error', errorMessage: 'Das Produkt konnte gerade nicht geladen werden.' };
} finally {
@@ -44,44 +70,90 @@ export default function ScanScreen({ preferences, productCache, shoppingList, on
}
if (result?.status !== 'found') {
setMissingBarcode(result?.status === 'notFound' || preferences.offlineModeEnabled ? String(event.data).replace(/\D/g, '') : '');
const canCreateLocally = result?.status === 'notFound' || preferences.offlineModeEnabled;
setMissingBarcode(canCreateLocally ? barcode : '');
setScanErrorTitle(scanErrorHeading(result, preferences.offlineModeEnabled));
setScanError(result?.errorMessage || 'Der Barcode konnte nicht verarbeitet werden.');
setIsErrorModalVisible(true);
}
}
async function handleManualSearch() {
if (!manualSearchQuery.trim() || isSearching) return;
const query = manualSearchQuery.trim();
if (!query) return;
searchRequestRef.current.controller?.abort();
const requestId = searchRequestRef.current.id + 1;
const controller = new AbortController();
searchRequestRef.current = { id: requestId, controller };
setIsSearching(true);
setSearchError('');
setSearchFeedback(null);
setMissingBarcode('');
setLastSearchQuery(query);
try {
const query = manualSearchQuery.trim();
if (/^\d{8,14}$/.test(query)) {
const result = await onScanBarcode(query);
if (result.status !== 'found') {
const result = await onScanBarcode(query, { openWhenFound: false });
if (!shouldApplySearchResponse(searchRequestRef.current.id, requestId)) return;
if (result.status === 'found') {
onOpenProduct(result.product);
} else {
setMissingBarcode(result.status === 'notFound' || preferences.offlineModeEnabled ? query : '');
setManualResults([]);
setHasSearched(false);
setSearchError(result.errorMessage || 'Zu diesem Barcode wurde kein Produkt gefunden.');
setHasSearched(true);
setSearchFeedback({
tone: result.status === 'notFound' ? 'neutral' : 'error',
title: scanErrorHeading(result, preferences.offlineModeEnabled),
message: result.errorMessage || 'Zu diesem Barcode wurde kein Produkt gefunden.'
});
}
return;
}
const results = await searchProducts(query, productCache, preferences.offlineModeEnabled);
setManualResults(results);
const result = await searchProductsWithStatus(
query,
productCache,
preferences.offlineModeEnabled,
{ signal: controller.signal }
);
if (!shouldApplySearchResponse(searchRequestRef.current.id, requestId)) return;
setManualResults(result.products);
setHasSearched(true);
setSearchFeedback(searchFeedbackFor(result));
} catch (error) {
if (error?.name === 'AbortError' || !shouldApplySearchResponse(searchRequestRef.current.id, requestId)) return;
setManualResults([]);
setSearchError('Die Suche ist gerade nicht verfügbar. Bitte versuche es erneut.');
setHasSearched(true);
setSearchFeedback({
tone: 'error',
title: 'Suche nicht verfügbar',
message: 'Die Suche konnte nicht abgeschlossen werden. Bitte versuche es erneut.'
});
} finally {
setIsSearching(false);
if (shouldApplySearchResponse(searchRequestRef.current.id, requestId)) {
setIsSearching(false);
searchRequestRef.current = { id: requestId, controller: null };
}
}
}
function handleSearchQueryChange(value) {
searchRequestRef.current.controller?.abort();
searchRequestRef.current = { id: searchRequestRef.current.id + 1, controller: null };
setManualSearchQuery(value);
setManualResults([]);
setHasSearched(false);
setIsSearching(false);
setSearchFeedback(null);
setMissingBarcode('');
}
function retryScan() {
setIsErrorModalVisible(false);
setScanError('');
setDetectedBarcode('');
setMissingBarcode('');
lastScanRef.current = null;
setIsScanning(true);
}
@@ -94,6 +166,13 @@ export default function ScanScreen({ preferences, productCache, shoppingList, on
subtitle={preferences.offlineModeEnabled ? 'Offline aktiv · nur gespeicherte Produkte' : 'Barcode scannen oder nach einem Produkt suchen'}
/>
{preferences.offlineModeEnabled ? (
<View style={styles.offlineNotice}>
<Text style={styles.offlineTitle}>Offline-Modus</Text>
<Text style={styles.offlineCopy}>Scans und Suche verwenden ausschliesslich Produkte, die bereits lokal gespeichert sind.</Text>
</View>
) : null}
{permission && !permission.granted && Platform.OS !== 'web' ? (
<View style={styles.permissionBox}>
<Text style={styles.permissionTitle}>Kamera für den Scan freigeben</Text>
@@ -108,20 +187,26 @@ export default function ScanScreen({ preferences, productCache, shoppingList, on
{hasCameraAccess ? (
<>
<BarcodeScannerView isLoadingProduct={isLoadingProduct} isScanning={isScanning} onBarcodeScanned={handleBarcodeScanned} />
<BarcodeScannerView
detectedBarcode={detectedBarcode}
isLoadingProduct={isLoadingProduct}
isScanning={isScanning}
onBarcodeScanned={handleBarcodeScanned}
/>
<SecondaryButton
disabled={isLoadingProduct}
label={isScanning ? 'Scan pausieren' : 'Scan fortsetzen'}
onPress={() => setIsScanning((current) => !current)}
onPress={() => {
setDetectedBarcode('');
setIsScanning((current) => !current);
}}
/>
</>
) : (
<View style={styles.permissionBox}>
<Text style={styles.permissionTitle}>Beispielprodukt öffnen</Text>
<Text style={styles.permissionCopy}>
Du kannst einen Beispiel-Barcode ausprobieren oder unten nach einem Produkt suchen.
</Text>
{isLoadingProduct ? <Text style={styles.note}>Produkt wird geladen...</Text> : null}
<Text style={styles.permissionCopy}>Du kannst einen Beispiel-Barcode ausprobieren oder unten nach einem Produkt suchen.</Text>
{isLoadingProduct ? <Text accessibilityLiveRegion="polite" style={styles.note}>Produkt wird geladen ...</Text> : null}
<View style={styles.demoRow}>
<SecondaryButton label="Nutella" onPress={() => handleBarcodeScanned({ data: '3017620422003' })} />
<SecondaryButton label="Weiteres Beispiel" onPress={() => handleBarcodeScanned({ data: '737628064502' })} />
@@ -131,98 +216,114 @@ export default function ScanScreen({ preferences, productCache, shoppingList, on
<SectionTitle>Nach Produkt suchen</SectionTitle>
<ManualSearchInput
onChangeText={(value) => {
setManualSearchQuery(value);
setManualResults([]);
setHasSearched(false);
setSearchError('');
setMissingBarcode('');
}}
onSubmit={handleManualSearch}
disabled={isSearching}
onChangeText={handleSearchQueryChange}
onSubmit={handleManualSearch}
value={manualSearchQuery}
/>
{isSearching ? <Text style={styles.note}>Suche läuft...</Text> : null}
{searchError ? <Text style={styles.errorNote}>{searchError}</Text> : null}
{searchError && /^\d{8,14}$/.test(missingBarcode) ? (
<SecondaryButton label="Produkt lokal erfassen" onPress={() => onCreateLocalProduct(missingBarcode)} />
) : null}
{!isSearching && hasSearched && manualResults.length === 0 ? (
<View style={styles.emptyResults}>
<Text style={styles.permissionTitle}>Kein passendes Produkt gefunden</Text>
<Text style={styles.permissionCopy}>Prüfe die Schreibweise oder suche nach dem Barcode.</Text>
{isSearching ? <Text accessibilityLiveRegion="polite" style={styles.note}>Suche nach „{lastSearchQuery}“ läuft ...</Text> : null}
{searchFeedback ? (
<View style={[
styles.feedback,
searchFeedback.tone === 'error' ? styles.errorFeedback
: searchFeedback.tone === 'warning' ? styles.warningFeedback : styles.neutralFeedback
]}>
<Text style={styles.feedbackTitle}>{searchFeedback.title}</Text>
<Text style={styles.feedbackCopy}>{searchFeedback.message}</Text>
</View>
) : null}
{manualResults.length > 0 ? <Text style={styles.resultsCount}>{manualResults.length} Treffer</Text> : null}
{searchFeedback && /^\d{8,14}$/.test(missingBarcode) ? (
<SecondaryButton label="Produkt lokal erfassen" onPress={() => onCreateLocalProduct(missingBarcode)} />
) : null}
{!isSearching && hasSearched && manualResults.length > 0 ? (
<Text style={styles.resultsCount}>{manualResults.length} Treffer · nach Relevanz sortiert</Text>
) : null}
{manualResults.map((product) => (
<ProductCard
key={product.id}
key={product.barcode || product.id}
onPress={() => onOpenProduct(product)}
product={product}
rating={calculateProductRating(product, preferences, { shoppingList })}
onPress={() => onOpenProduct(product)}
searchMetadata={buildSearchResultMetadata(product, lastSearchQuery)}
/>
))}
<ScanErrorModal
message={scanError}
onClose={retryScan}
onCreateLocalProduct={/^\d{8,14}$/.test(missingBarcode) ? () => {
setIsErrorModalVisible(false);
onCreateLocalProduct(missingBarcode);
} : undefined}
onClose={retryScan}
onManualSearch={() => {
setIsErrorModalVisible(false);
setIsScanning(true);
setDetectedBarcode('');
setMissingBarcode('');
lastScanRef.current = null;
setIsScanning(false);
}}
onRetry={retryScan}
title={scanErrorTitle}
visible={isErrorModalVisible}
/>
</ScreenContainer>
);
}
const styles = StyleSheet.create({
permissionBox: {
backgroundColor: colors.surface,
borderColor: colors.border,
borderRadius: 18,
borderWidth: 1,
gap: 12,
padding: 16
},
emptyResults: {
backgroundColor: colors.surface,
borderColor: colors.border,
borderRadius: 16,
borderWidth: 1,
gap: 6,
padding: 16
},
permissionTitle: {
color: colors.text,
fontSize: 18,
fontWeight: '800'
},
permissionCopy: {
color: colors.muted,
fontSize: 15,
lineHeight: 21
},
demoRow: {
gap: 10
},
note: {
color: colors.muted,
fontSize: 14
},
errorNote: {
color: colors.danger,
fontSize: 14,
fontWeight: '700'
},
resultsCount: {
color: colors.muted,
fontSize: 13,
fontWeight: '700'
function scanErrorHeading(result, offlineModeEnabled) {
if (offlineModeEnabled) return 'Offline nicht gespeichert';
if (result?.status === 'notFound') return 'Produkt nicht gefunden';
return 'Verbindung fehlgeschlagen';
}
function searchFeedbackFor(result) {
if (result.status === 'found' && result.source === 'online') {
return {
tone: 'neutral',
title: 'Online-Ergebnisse',
message: 'Treffer wurden nach Übereinstimmung und Datenvollständigkeit sortiert.'
};
}
if (result.status === 'found' && result.source === 'offline-cache') {
return {
tone: 'warning',
title: 'Offline-Ergebnisse',
message: 'Es werden nur passende lokal gespeicherte Produkte angezeigt.'
};
}
if (result.status === 'found' && result.source === 'cache-only') {
return { tone: 'warning', title: 'Gespeicherte Ergebnisse', message: result.message };
}
if (result.status === 'cache-fallback') {
return { tone: 'warning', title: 'Gespeicherte Ergebnisse', message: result.message };
}
if (result.status === 'offline-miss') {
return { tone: 'warning', title: 'Offline nichts gefunden', message: result.message };
}
if (result.status === 'network-error') {
return { tone: 'error', title: 'Verbindung fehlgeschlagen', message: result.message };
}
return {
tone: 'neutral',
title: 'Kein passendes Produkt gefunden',
message: result.message || 'Prüfe die Schreibweise oder suche nach dem Barcode.'
};
}
const styles = StyleSheet.create({
permissionBox: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 12, padding: 16 },
permissionTitle: { color: colors.text, fontSize: 18, fontWeight: '800' },
permissionCopy: { color: colors.muted, fontSize: 15, lineHeight: 21 },
demoRow: { gap: 10 },
note: { color: colors.muted, fontSize: 14 },
resultsCount: { color: colors.muted, fontSize: 13, fontWeight: '700' },
offlineNotice: { backgroundColor: '#fff7e8', borderColor: '#e9c979', borderRadius: 16, borderWidth: 1, gap: 4, padding: 14 },
offlineTitle: { color: '#8a5914', fontSize: 14, fontWeight: '800' },
offlineCopy: { color: colors.text, fontSize: 13, lineHeight: 18 },
feedback: { borderRadius: 14, borderWidth: 1, gap: 4, padding: 13 },
neutralFeedback: { backgroundColor: colors.surfaceTint, borderColor: colors.border },
warningFeedback: { backgroundColor: '#fff7e8', borderColor: colors.warning },
errorFeedback: { backgroundColor: '#fff1f0', borderColor: colors.danger },
feedbackTitle: { color: colors.text, fontSize: 14, fontWeight: '800' },
feedbackCopy: { color: colors.muted, fontSize: 13, lineHeight: 18 }
});
+63 -35
View File
@@ -1,5 +1,6 @@
import { enrichEnvironmentalProduct, productSpecificFootprint } from './environmentalService.js';
import { mergeManualOverrides } from './manualProduct.js';
import { rankSearchResults } from './searchResultService.js';
const openFoodFactsBaseUrl = 'https://ch.openfoodfacts.org';
const CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -118,28 +119,40 @@ function cachedResult(product, stale = false) {
};
}
export async function searchProducts(query, productCache = {}, offlineModeEnabled = false, { pageSize = 20 } = {}) {
export async function searchProducts(query, productCache = {}, offlineModeEnabled = false, options = {}) {
const result = await searchProductsWithStatus(query, productCache, offlineModeEnabled, options);
return result.products;
}
export async function searchProductsWithStatus(query, productCache = {}, offlineModeEnabled = false, { pageSize = 20, signal } = {}) {
const normalizedQuery = query.trim().toLowerCase();
const cachedProducts = Object.values(productCache);
const cachedProducts = cachedProductsForSearch(Object.values(productCache));
const safePageSize = Number.isInteger(pageSize) ? Math.max(1, Math.min(100, pageSize)) : 20;
if (!normalizedQuery) {
return [];
return { status: 'empty', source: 'none', products: [] };
}
if (offlineModeEnabled) {
return filterProducts(markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache'), normalizedQuery);
const products = rankSearchResults(cachedProducts, normalizedQuery);
return products.length > 0
? { status: 'found', source: 'offline-cache', products }
: {
status: 'offline-miss',
source: 'offline-cache',
products: [],
message: 'Offline-Modus aktiv: Kein passendes Produkt ist im lokalen Cache gespeichert.'
};
}
try {
const response = await fetch(
`${openFoodFactsBaseUrl}/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process&json=1&page_size=${safePageSize}&fields=${productFields}`
`${openFoodFactsBaseUrl}/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process&json=1&page_size=${safePageSize}&fields=${productFields}`,
signal ? { signal } : undefined
);
if (!response.ok) {
return filterProducts([
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery);
return cacheFallbackResult(cachedProducts, normalizedQuery);
}
const payload = await response.json();
@@ -147,14 +160,29 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable
.filter((product) => product && typeof product === 'object' && product.code)
.map((product) => mapOpenFoodFactsProduct(product, product.code));
return uniqueProducts(filterProducts([
const onlineMatches = rankSearchResults(apiProducts, normalizedQuery);
const products = rankSearchResults([
...apiProducts,
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery));
} catch (error) {
return filterProducts([
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
...cachedProducts
], normalizedQuery);
return products.length > 0
? onlineMatches.length > 0
? { status: 'found', source: 'online', products }
: {
status: 'found',
source: 'cache-only',
products,
message: 'Open Food Facts hat keine passenden Treffer geliefert. Es werden lokal gespeicherte Produkte angezeigt.'
}
: {
status: 'not-found',
source: 'online',
products: [],
message: 'Open Food Facts hat keine passenden Produkte gefunden.'
};
} catch (error) {
if (error?.name === 'AbortError') throw error;
return cacheFallbackResult(cachedProducts, normalizedQuery);
}
}
@@ -271,35 +299,35 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
});
}
function markProductsSource(products, source) {
function cachedProductsForSearch(products) {
return products.map((product) => ({
...product,
dataSource: product.dataSource || source
...enrichEnvironmentalProduct(product),
dataSource: product.dataSource === 'local' ? 'local' : 'cache',
cacheStale: product.dataSource === 'local' ? false : !isFreshCacheEntry(product)
}));
}
function cacheFallbackResult(cachedProducts, normalizedQuery) {
const products = rankSearchResults(cachedProducts, normalizedQuery);
return products.length > 0
? {
status: 'cache-fallback',
source: 'cache',
products,
message: 'Open Food Facts ist nicht erreichbar. Es werden passende gespeicherte Produkte angezeigt.'
}
: {
status: 'network-error',
source: 'none',
products: [],
message: 'Open Food Facts ist nicht erreichbar und im lokalen Cache wurde nichts Passendes gefunden.'
};
}
function normalizeBarcode(barcode) {
return String(barcode || '').replace(/[^\d]/g, '');
}
function filterProducts(products, normalizedQuery) {
return uniqueProducts(products).filter((product) => {
const haystack = [
product.name,
product.brand,
product.category,
...(product.categoryTags || []),
product.barcode
].filter(Boolean).join(' ').toLowerCase();
return haystack.includes(normalizedQuery);
});
}
function uniqueProducts(products) {
return Array.from(new Map(products.map((product) => [product.id, product])).values());
}
function firstTextValue(value) {
if (!value) return undefined;
return String(value).split(',').map((item) => item.trim()).filter(Boolean)[0];