import units from '@/units.js'; export function mealToShoppingListSources(meal) { const sources = []; for (const recipe of meal.recipes) { for (const ingredient of recipe.ingredients) { sources.push({ ingredient, meal, recipe, }); } } for (const ingredient of meal.extra_ingredients) { sources.push({ ingredient, meal, }); } return sources; } export function requestsToSources(requests) { const sources = []; for (const request of requests) { if (request.ingredient) { sources.push(request); } else if (request.meal) { sources.push(...mealToShoppingListSources(request.meal)); } } return sources; } export function removeMealFromShoppingListSources(sources, meal) { return sources.filter(source => source.meal?.id !== meal.id); } export function groupingToIngredients(grouping) { const product = grouping.product; const totals = []; for (const total of grouping.totals) { totals.push({ id: 0, line: `${total.quantity} ${total.unit} of ${product.name}`, preparation: '', name: product.name, product, ...total }); } return totals; } function calculateTotals(sources) { const totals = {}; for (const source of sources) { const { unit, factor } = units.getConversionFactor(source.ingredient.unit) ?? { unit: source.ingredient.unit, factor: 1 }; const quantity = source.ingredient.quantity / factor; if (!totals[unit]) { totals[unit] = quantity; } else { totals[unit] += quantity; } } const result = []; for (const unit in totals) { result.push({ unit, quantity: totals[unit] }); } return result; } export function groupByProduct(sources) { const noProductKey = "no-product"; const noProduct = { name: "No product", }; const grouped = {}; for (const source of sources) { const key = source.ingredient?.product?.id ?? noProductKey; if (!key) { continue; } if (!grouped[key]) { grouped[key] = { product: source.ingredient.product ?? noProduct, sources: [], }; } grouped[key].sources.push(source); } for (const key in grouped) { grouped[key].totals = calculateTotals(grouped[key].sources); } return Object.values(grouped); }