File size: 13,676 Bytes
bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e bcb3d07 18fa70e | 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 | import { localProducts } from "@/data/products";
import { cacheProduct, getCachedProduct, getCustomProduct } from "@/lib/storage";
import type { Product, ProductInsight, ProductSource, UserProfile } from "@/types";
type OffResponse = {
status: number;
product?: {
product_name?: string;
product_name_en?: string;
generic_name?: string;
brands?: string;
categories?: string;
image_url?: string;
image_front_url?: string;
ingredients_text?: string;
ingredients_text_en?: string;
ingredients_tags?: string[];
allergens_tags?: string[];
traces_tags?: string[];
additives_tags?: string[];
labels_tags?: string[];
countries?: string;
origins?: string;
packaging?: string;
packaging_tags?: string[];
quantity?: string;
nutriments?: Record<string, number | string | undefined>;
nutriscore_grade?: string;
nova_group?: number;
ecoscore_grade?: string;
};
};
const sourceUrls: Record<Exclude<ProductSource, "Community DB">, string> = {
"Open Food Facts": "https://world.openfoodfacts.org/api/v0/product",
"Open Products Facts": "https://world.openproductsfacts.org/api/v0/product",
};
function normalizeBarcode(barcode: string): string {
return barcode.trim().replace(/\s+/g, "");
}
function normalizeNumber(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function cleanText(value: string): string {
return value
.replace(/^en:/i, "")
.replace(/^fr:/i, "")
.replace(/^es:/i, "")
.replace(/-/g, " ")
.replace(/_/g, " ")
.trim();
}
function unique(values: Array<string | null | undefined>): string[] {
return [...new Set(values.map((value) => (value ? cleanText(value).toLowerCase() : "")).filter(Boolean))];
}
function titleize(value: string): string {
return value.replace(/\b\w/g, (char) => char.toUpperCase());
}
function splitIngredients(text: string): string[] {
return text
.split(/[,.;]/)
.map((item) => item.trim())
.filter(Boolean)
.slice(0, 25);
}
function mapCategory(raw?: string): Product["category"] {
const value = (raw ?? "").toLowerCase();
if (value.includes("beverage") || value.includes("drink")) return "beverages";
if (value.includes("dairy") || value.includes("milk") || value.includes("yogurt")) return "dairy";
if (value.includes("grain") || value.includes("cereal") || value.includes("rice")) return "grains";
if (value.includes("meat") || value.includes("chicken") || value.includes("beef")) return "meat";
if (value.includes("fruit") || value.includes("vegetable") || value.includes("produce")) return "produce";
if (value.includes("frozen")) return "frozen";
if (value.includes("condiment") || value.includes("sauce")) return "condiments";
if (value.includes("bread") || value.includes("bakery")) return "bakery";
if (value.includes("snack") || value.includes("biscuit") || value.includes("chip")) return "snacks";
return "other";
}
function mapPackagingType(raw: string[]): Product["packaging_type"] {
const joined = raw.join(" ");
if (joined.includes("glass")) return "glass";
if (joined.includes("cardboard") || joined.includes("paper")) return "cardboard";
if (joined.includes("metal") || joined.includes("aluminium") || joined.includes("steel")) return "metal";
if (joined.includes("biodegradable") || joined.includes("compostable")) return "biodegradable";
if (joined.includes("plastic")) return "plastic";
return "mixed";
}
function asNutri(letter?: string): Product["nutri_score"] {
const normalized = (letter ?? "C").toUpperCase();
if (["A", "B", "C", "D", "E"].includes(normalized)) return normalized as Product["nutri_score"];
return "C";
}
function scoreFromNutri(letter: Product["nutri_score"]): number {
const map: Record<Product["nutri_score"], number> = { A: 90, B: 76, C: 58, D: 36, E: 18 };
return map[letter];
}
function scoreFromEco(eco?: string): number {
const map: Record<string, number> = { a: 90, b: 75, c: 58, d: 40, e: 22 };
return map[(eco ?? "c").toLowerCase()] ?? 58;
}
function inferInsights(args: {
nutriScore: Product["nutri_score"];
novaGroup: Product["nova_group"];
sugarPer100g: number | null;
fiber: number | null;
protein: number | null;
preservatives: string[];
labels: string[];
allergens: string[];
traces: string[];
packagingDetails: string[];
ingredients: string[];
}): ProductInsight {
const summary: string[] = [];
const positives: string[] = [];
const cautions: string[] = [];
const fitTags: string[] = [];
if (args.nutriScore === "A" || args.nutriScore === "B") {
summary.push("Nutrition profile looks relatively strong for a packaged product.");
positives.push(`Nutri-Score ${args.nutriScore} suggests a stronger overall nutritional balance.`);
} else if (args.nutriScore === "D" || args.nutriScore === "E") {
summary.push("Nutrition profile is weaker and worth checking closely.");
cautions.push(`Nutri-Score ${args.nutriScore} suggests this may be harder to fit into everyday healthy choices.`);
}
if (args.novaGroup === 4) {
cautions.push("NOVA 4 means this is likely ultra-processed.");
} else if (args.novaGroup === 1 || args.novaGroup === 2) {
positives.push("Lower processing level than many packaged alternatives.");
}
if (args.sugarPer100g !== null) {
if (args.sugarPer100g >= 15) cautions.push(`High sugar at ${args.sugarPer100g}g per 100g.`);
else if (args.sugarPer100g <= 5) positives.push(`Lower sugar at ${args.sugarPer100g}g per 100g.`);
}
if (args.fiber !== null && args.fiber >= 5) positives.push(`Useful fiber content at ${args.fiber}g per 100g.`);
if (args.protein !== null && args.protein >= 10) positives.push(`Higher protein content at ${args.protein}g per 100g.`);
if (args.preservatives.length >= 3) cautions.push("Contains multiple additives or preservatives.");
if (args.allergens.length > 0) cautions.push(`Declared allergens: ${args.allergens.join(", ")}.`);
if (args.traces.length > 0) cautions.push(`May contain traces of ${args.traces.join(", ")}.`);
const joinedLabels = args.labels.join(" ");
if (joinedLabels.includes("vegan")) fitTags.push("vegan");
if (joinedLabels.includes("vegetarian")) fitTags.push("vegetarian");
if (joinedLabels.includes("organic")) positives.push("Carries organic-related labelling.");
const joinedPackaging = args.packagingDetails.join(" ");
if (joinedPackaging.includes("recyclable")) positives.push("Packaging appears to include recyclable materials.");
if (joinedPackaging.includes("plastic")) cautions.push("Packaging includes plastic.");
if (!summary.length) {
summary.push("This product has enough metadata to screen for ingredients, allergens, and general nutrition fit.");
}
if (!args.ingredients.length) {
cautions.push("Ingredient list is incomplete in the source data.");
}
return { summary, positives, cautions, fit_tags: fitTags };
}
function mapApiProduct(barcode: string, data: OffResponse, source: Exclude<ProductSource, "Community DB">): Product {
const product = data.product ?? {};
const nutriments = product.nutriments ?? {};
const nutriScore = asNutri(product.nutriscore_grade);
const ingredientText = product.ingredients_text_en ?? product.ingredients_text ?? "";
const ingredients = ingredientText
? splitIngredients(ingredientText)
: unique(product.ingredients_tags ?? []).map(titleize);
const allergens = unique(product.allergens_tags ?? []).map(titleize);
const traces = unique(product.traces_tags ?? []).map(titleize);
const preservatives = unique(product.additives_tags ?? []).map(titleize);
const labels = unique(product.labels_tags ?? []).map(titleize);
const packagingDetails = unique([...(product.packaging_tags ?? []), product.packaging]).map(titleize);
const quantity = product.quantity?.trim() || "Unknown";
const nutritionalInfo = {
serving_size: quantity !== "Unknown" ? quantity : "100g",
calories: normalizeNumber(nutriments["energy-kcal_100g"] ?? nutriments["energy-kcal"]),
sugar_per_100g: normalizeNumber(nutriments["sugars_100g"]),
protein: normalizeNumber(nutriments["proteins_100g"]),
fat: normalizeNumber(nutriments["fat_100g"]),
carbs: normalizeNumber(nutriments["carbohydrates_100g"]),
fiber: normalizeNumber(nutriments["fiber_100g"]),
sodium: normalizeNumber(nutriments["sodium_100g"]),
salt: normalizeNumber(nutriments["salt_100g"]),
};
const insights = inferInsights({
nutriScore,
novaGroup: [1, 2, 3, 4].includes(Number(product.nova_group)) ? (Number(product.nova_group) as 1 | 2 | 3 | 4) : null,
sugarPer100g: nutritionalInfo.sugar_per_100g,
fiber: nutritionalInfo.fiber,
protein: nutritionalInfo.protein,
preservatives,
labels,
allergens,
traces,
packagingDetails: packagingDetails.map((item) => item.toLowerCase()),
ingredients,
});
return {
id: `prod-${barcode}`,
barcode,
name: product.product_name_en ?? product.product_name ?? product.generic_name ?? "Unknown product",
brand: product.brands ?? "Unknown brand",
category: mapCategory(product.categories),
image_url: product.image_front_url ?? product.image_url ?? "",
quantity,
ingredient_text: ingredientText,
nutritional_info: nutritionalInfo,
ingredients,
allergens,
traces,
preservatives,
labels,
health_score: scoreFromNutri(nutriScore),
environmental_score: scoreFromEco(product.ecoscore_grade),
certifications: labels.slice(0, 6),
country_of_origin: product.origins?.split(",")[0]?.trim() || product.countries?.split(",")[0]?.trim() || "Unknown",
packaging_type: mapPackagingType(packagingDetails.map((item) => item.toLowerCase())),
packaging_details: packagingDetails,
nutri_score: nutriScore,
nova_group: [1, 2, 3, 4].includes(Number(product.nova_group)) ? (Number(product.nova_group) as 1 | 2 | 3 | 4) : null,
ecoscore_grade: product.ecoscore_grade?.toUpperCase() ?? null,
source_url: `${sourceUrls[source]}/${barcode}.json`,
lookup_sources: [source],
fetched_at: new Date().toISOString(),
data_source: source,
insights,
};
}
async function fetchSource(
barcode: string,
source: Exclude<ProductSource, "Community DB">
): Promise<Product | null> {
const response = await fetch(`${sourceUrls[source]}/${barcode}.json`);
if (!response.ok) return null;
const data = (await response.json()) as OffResponse;
if (data.status !== 1) return null;
return mapApiProduct(barcode, data, source);
}
export function findLocalByBarcode(barcode: string): Product | null {
const normalized = normalizeBarcode(barcode);
return localProducts.find((product) => product.barcode === normalized) ?? null;
}
export async function fetchBarcodeProduct(barcode: string): Promise<Product | null> {
const normalized = normalizeBarcode(barcode);
if (!normalized) return null;
const local = findLocalByBarcode(normalized);
if (local) return local;
const custom = getCustomProduct(normalized);
if (custom) return custom;
const cached = getCachedProduct(normalized);
if (cached) return cached;
const sources: Array<Exclude<ProductSource, "Community DB">> = ["Open Food Facts", "Open Products Facts"];
for (const source of sources) {
try {
const product = await fetchSource(normalized, source);
if (product) {
cacheProduct(product);
return product;
}
} catch {
continue;
}
}
return null;
}
export function getUserProductSignals(product: Product, user: UserProfile) {
const userAllergens = user.allergens.map((item) => item.toLowerCase());
const dietary = user.dietary_restrictions.map((item) => item.toLowerCase());
const productTerms = [
...product.ingredients.map((item) => item.toLowerCase()),
...product.allergens.map((item) => item.toLowerCase()),
...product.labels.map((item) => item.toLowerCase()),
product.category.toLowerCase(),
];
const warnings: string[] = [];
const positives: string[] = [];
const allergenHits = product.allergens.filter((item) => userAllergens.includes(item.toLowerCase()));
const traceHits = product.traces.filter((item) => userAllergens.includes(item.toLowerCase()));
if (allergenHits.length) warnings.push(`Contains your allergen: ${allergenHits.join(", ")}.`);
if (traceHits.length) warnings.push(`May contain your allergen: ${traceHits.join(", ")}.`);
if (product.nutritional_info.sugar_per_100g !== null) {
if (product.nutritional_info.sugar_per_100g > user.sugar_limit) {
warnings.push(
`Sugar per 100g (${product.nutritional_info.sugar_per_100g}g) exceeds your daily target (${user.sugar_limit}g).`
);
} else {
positives.push(`Sugar per 100g stays within your current target (${user.sugar_limit}g).`);
}
}
if (dietary.includes("vegan") && productTerms.some((term) => ["milk", "egg", "honey", "beef", "chicken"].includes(term))) {
warnings.push("This may conflict with a vegan preference.");
}
if (dietary.includes("vegetarian") && productTerms.some((term) => ["beef", "chicken", "pork", "fish", "gelatin"].includes(term))) {
warnings.push("This may conflict with a vegetarian preference.");
}
if (dietary.includes("gluten-free") && productTerms.some((term) => ["wheat", "barley", "rye", "gluten"].includes(term))) {
warnings.push("This may conflict with a gluten-free preference.");
}
return { warnings, positives };
}
|