Improve ratings and alternatives
Android Release Build / build-android (push) Successful in 13m20s

This commit is contained in:
Frederik Spirgi
2026-10-26 15:20:52 +01:00
parent 1d32aeaf29
commit 77fe952c83
12 changed files with 542 additions and 216 deletions
+163 -8
View File
@@ -25,7 +25,8 @@ test('missing budget and allergen data do not contribute neutral placeholder sco
});
test('profile priorities actually change the category weighting', () => {
const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' } };
const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' },
ingredientAnalysis: { palmOil: false, additives: [] }, ingredients: ['Hafer'], dataCompleteness: { additives: true } };
const nutritionFirst = rate(item, { nutritionPriority: 'high', sustainabilityPriority: 'low' });
const sustainabilityFirst = rate(item, { nutritionPriority: 'low', sustainabilityPriority: 'high' });
assert.ok(nutritionFirst.overallScore > sustainabilityFirst.overallScore);
@@ -124,10 +125,13 @@ test('missing values for personal goals do not invent a penalty', () => {
assert.equal(highProtein.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
});
test('a critical additive in ingredient text counts without additive tags', () => {
test('a flagged additive in ingredient text counts without additive tags but has no global cap', () => {
const rating = rate({ ingredients: ['Farbstoff E171'] });
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, true);
assert.ok(rating.categoryScores.ingredients.score <= 24);
assert.equal(rating.categoryScores.ingredients.score, 55);
const complete = rate({ ingredients: ['Farbstoff E171'], nutrition: { nutriScore: 'A' },
sustainability: { ecoScore: 'A' }, price: 1 }, { maxBudgetPerShoppingTrip: 100 });
assert.ok(complete.overallScore > 47);
});
test('flavoured water with sugar is not treated as plain water', () => {
@@ -148,11 +152,11 @@ test('flavoured water with sugar is not treated as plain water', () => {
assert.notEqual(rating.categoryScores.nutrition.score, 98);
});
test('country names containing eu are not mistaken for the EU', () => {
test('country of origin alone cannot establish sustainability', () => {
const peru = rate({ sustainability: { originCountry: 'Peru' } });
const swiss = rate({ sustainability: { originCountry: 'Schweiz' } });
assert.equal(peru.categoryScores.sustainability.score, 35);
assert.equal(swiss.categoryScores.sustainability.score, 92);
assert.equal(peru.categoryScores.sustainability.score, null);
assert.equal(swiss.categoryScores.sustainability.score, null);
});
test('Eco-Score is not counted again through its environmental indicators', () => {
@@ -163,7 +167,7 @@ test('Eco-Score is not counted again through its environmental indicators', () =
assert.equal(rating.categoryScores.sustainability.score, 15);
});
test('alternatives exclude products whose allergens need review', async () => {
test('alternatives present unverified allergens only with a clear review path', async () => {
const source = {
id: 'source', barcode: '1', name: 'Original', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Milch'], dataCompleteness: { allergens: true }
@@ -179,5 +183,156 @@ test('alternatives exclude products whose allergens need review', async () => {
const alternatives = await findAlternatives(source, {
...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true
}, { unknown, verified });
assert.deepEqual(alternatives.map((item) => item.product.id), ['verified']);
assert.deepEqual(alternatives.map((item) => item.product.id), ['verified', 'unknown']);
assert.equal(alternatives[0].requiresAllergenCheck, false);
assert.equal(alternatives[1].requiresAllergenCheck, true);
assert.match(alternatives[1].reason, /Allergenfreiheit ist nicht bestätigt/);
});
test('allergy-review alternatives remain discoverable when both displayed scores are capped', async () => {
const source = { id: 'source', barcode: '10', name: 'Original', categoryTags: ['en:snacks'],
nutrition: { nutriScore: 'C' }, sustainability: { ecoScore: 'A' }, allergens: [] };
const candidate = { id: 'candidate', barcode: '11', name: 'Besser', categoryTags: ['en:snacks'],
nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'A' }, allergens: [] };
const pref = { ...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true };
const alternatives = await findAlternatives(source, pref, { candidate });
assert.deepEqual(alternatives.map((item) => item.product.id), ['candidate']);
assert.equal(alternatives[0].requiresAllergenCheck, true);
});
test('a confirmed vegan conflict blocks a green recommendation', () => {
const rating = rate({ price: 1, ingredients: ['Milch', 'Hafer'],
ingredientAnalysis: { vegan: false, palmOil: false, additives: [] },
dataCompleteness: { additives: true }, nutrition: { nutriScore: 'A' },
sustainability: { ecoScore: 'A' } }, { preferredDiet: 'vegan', maxBudgetPerShoppingTrip: 100 });
assert.equal(rating.goalConflict, true);
assert.equal(rating.overallStatus, 'critical');
assert.ok(rating.overallScore <= 47);
});
test('missing sugar for a low-sugar goal limits the recommendation', () => {
const rating = rate({ nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'A' } },
{ preferredDiet: 'lowSugar' });
assert.equal(rating.goalReviewRequired, true);
assert.notEqual(rating.overallStatus, 'good');
});
test('coverage counts underlying facts and ignores packaging as a score', () => {
const rating = rate({ nutrition: { nutriScore: 'A' }, ingredientAnalysis: { palmOil: false },
sustainability: { packaging: 'Glas' } });
assert.ok(rating.dataCoverage < 80);
assert.equal(rating.categoryScores.sustainability.score, null);
assert.notEqual(rating.overallStatus, 'good');
});
test('budget includes open list prices and treats unknown prices as uncertainty', () => {
const item = { price: 5, nutrition: { nutriScore: 'A' } };
const pref = { maxBudgetPerShoppingTrip: 20, budgetPeriod: 'shoppingTrip' };
const list = { items: [{ estimatedPrice: 18, quantity: 1, checked: false }] };
const exceeded = calculateProductRating(item, { ...preferences, ...pref }, { shoppingList: list });
assert.equal(exceeded.categoryScores.budget.status, 'critical');
assert.match(exceeded.categoryScores.budget.message, /überschreitet/);
const missing = calculateProductRating(item, { ...preferences, ...pref },
{ shoppingList: { items: [{ quantity: 1, checked: false }] } });
assert.equal(missing.budgetReviewRequired, true);
assert.notEqual(missing.overallStatus, 'good');
});
test('a category-average footprint has partial coverage', () => {
const rating = rate({ sustainability: { carbonFootprintKgCo2ePerKg: 0.5,
footprint: { status: 'estimated' } } });
assert.ok(rating.dataCoverage > 0);
assert.ok(rating.dataCoverage < 50);
});
test('online alternatives search category pages for healthier drinks', async () => {
const source = { id: 'source', barcode: '100', name: 'Süsse Cola',
category: 'Sodas', categoryTags: ['en:beverages', 'en:sodas'],
nutrition: { nutriScore: 'D' }, sustainability: { ecoScore: 'A' }, price: 2 };
const responses = {
'en:sodas:1': [101, 102],
'en:beverages:1': [103, 104, 105, 999],
'en:sodas:2': [106, 107, 108]
};
const requests = [];
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async (url) => {
const parsed = new URL(url);
requests.push(parsed);
const tag = parsed.searchParams.get('categories_tags');
const page = parsed.searchParams.get('page');
const products = (responses[`${tag}:${page}`] || []).map((code) => ({
code: String(code), product_name: `Drink ${code}`, categories_tags: ['en:beverages', 'en:sodas'],
nutriscore_grade: 'a'
}));
const unrelated = products.find((item) => item.code === '999');
if (unrelated) unrelated.categories_tags = ['en:plant-based-foods-and-beverages', 'en:snacks'];
return { ok: true, json: async () => ({ products }) };
};
const alternatives = await findAlternatives(source,
{ ...preferences, maxBudgetPerShoppingTrip: 20, offlineModeEnabled: false }, {});
assert.equal(alternatives.length, 8);
assert.ok(!alternatives.some((item) => item.product.barcode === '999'));
assert.ok(alternatives.every((item) => item.product.categoryTags.includes('en:beverages')));
assert.ok(alternatives.every((item) => item.nutritionImprovement > 0));
assert.ok(requests.some((url) => url.searchParams.get('page') === '2'));
assert.ok(requests.every((url) => url.pathname === '/api/v2/search'
&& url.searchParams.get('nutrition_grades_tags') === 'a|b'
&& Number(url.searchParams.get('page_size')) >= 40));
} finally {
globalThis.fetch = originalFetch;
}
});
test('offline alternatives use only saved products', async () => {
const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'],
nutrition: { nutriScore: 'E' } };
const cached = { id: 'cached', barcode: '2', name: 'Wasser', categoryTags: ['en:beverages'],
nutrition: { nutriScore: 'A' } };
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async () => { throw new Error('Network must not be used in offline mode.'); };
const alternatives = await findAlternatives(source,
{ ...preferences, offlineModeEnabled: true }, { cached });
assert.deepEqual(alternatives.map((item) => item.product.id), ['cached']);
} finally {
globalThis.fetch = originalFetch;
}
});
test('different brands with the same product name remain separate alternatives', async () => {
const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'],
nutrition: { nutriScore: 'E' } };
const first = { id: 'first', barcode: '2', name: 'Mineralwasser', brand: 'A',
categoryTags: ['en:beverages'], nutrition: { nutriScore: 'A' } };
const second = { ...first, id: 'second', barcode: '3', brand: 'B' };
const alternatives = await findAlternatives(source,
{ ...preferences, offlineModeEnabled: true }, { first, second });
assert.deepEqual(alternatives.map((item) => item.product.id), ['first', 'second']);
});
test('online search broadens to products without an official grade and reports a complete outage', async () => {
const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'],
nutrition: { nutriScore: 'E' } };
const originalFetch = globalThis.fetch;
const requests = [];
try {
globalThis.fetch = async (url) => {
const parsed = new URL(url);
requests.push(parsed);
return { ok: true, json: async () => ({ products: parsed.searchParams.has('nutrition_grades_tags')
? [] : [{ code: '2', product_name: 'Wasser', categories_tags: ['en:beverages'],
nutriscore_grade: 'a' }] }) };
};
const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: false });
assert.deepEqual(alternatives.map((item) => item.product.barcode), ['2']);
assert.ok(requests.some((url) => !url.searchParams.has('nutrition_grades_tags')));
globalThis.fetch = async () => { throw new Error('offline'); };
await assert.rejects(findAlternatives(source, { ...preferences, offlineModeEnabled: false }),
/nicht erreichbar/);
} finally {
globalThis.fetch = originalFetch;
}
});