recipes: nutrition calculator with BLS/USDA matching, manual overwrites, and skip
Dual-source nutrition system using BLS (German, primary) and USDA (English, fallback) with ML embedding matching (multilingual-e5-small / all-MiniLM-L6-v2), hybrid substring-first search, and position-aware scoring heuristics. Includes per-recipe and global manual ingredient overwrites, ingredient skip/exclude, referenced recipe nutrition (base refs + anchor tags), section-name dedup, amino acid tracking, and reactive client-side calculator with NutritionSummary component.
This commit is contained in:
308
src/routes/[recipeLang=recipeLang]/admin/nutrition/+page.svelte
Normal file
308
src/routes/[recipeLang=recipeLang]/admin/nutrition/+page.svelte
Normal file
@@ -0,0 +1,308 @@
|
||||
<script>
|
||||
let { data } = $props();
|
||||
const isEnglish = data.lang === 'en';
|
||||
const recipeLang = data.recipeLang;
|
||||
|
||||
let processing = $state(false);
|
||||
let singleProcessing = $state('');
|
||||
/** @type {any} */
|
||||
let batchResult = $state(null);
|
||||
/** @type {any} */
|
||||
let singleResult = $state(null);
|
||||
let errorMsg = $state('');
|
||||
let recipeName = $state('');
|
||||
|
||||
async function generateAll() {
|
||||
processing = true;
|
||||
errorMsg = '';
|
||||
batchResult = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/${recipeLang}/nutrition/generate-all`, {
|
||||
method: 'POST',
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.message || 'Failed to generate nutrition mappings');
|
||||
}
|
||||
|
||||
batchResult = result;
|
||||
} catch (err) {
|
||||
errorMsg = err instanceof Error ? err.message : 'An error occurred';
|
||||
} finally {
|
||||
processing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function generateSingle() {
|
||||
if (!recipeName.trim()) return;
|
||||
singleProcessing = recipeName.trim();
|
||||
singleResult = null;
|
||||
errorMsg = '';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/${recipeLang}/nutrition/generate/${encodeURIComponent(recipeName.trim())}`, {
|
||||
method: 'POST',
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.message || 'Failed to generate nutrition mappings');
|
||||
}
|
||||
|
||||
singleResult = result;
|
||||
} catch (err) {
|
||||
errorMsg = err instanceof Error ? err.message : 'An error occurred';
|
||||
} finally {
|
||||
singleProcessing = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
h1 {
|
||||
color: var(--nord0);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:global(:root:not([data-theme="light"])) h1 { color: white; }
|
||||
}
|
||||
:global(:root[data-theme="dark"]) h1 { color: white; }
|
||||
|
||||
.subtitle {
|
||||
color: var(--nord3);
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: var(--nord6, #eceff4);
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:global(:root:not([data-theme="light"])) .section { background: var(--nord1); }
|
||||
}
|
||||
:global(:root[data-theme="dark"]) .section { background: var(--nord1); }
|
||||
|
||||
.section h2 {
|
||||
margin-top: 0;
|
||||
font-size: 1.3rem;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.input-row input {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--color-border, #ccc);
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0.5rem 1.25rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
background: var(--nord10, #5e81ac);
|
||||
color: white;
|
||||
transition: opacity 150ms;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
opacity: 0.85;
|
||||
}
|
||||
.btn-danger {
|
||||
background: var(--nord11, #bf616a);
|
||||
}
|
||||
|
||||
.result-box {
|
||||
margin-top: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 6px;
|
||||
background: var(--nord0, #2e3440);
|
||||
color: var(--nord6, #eceff4);
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.result-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.result-table th,
|
||||
.result-table td {
|
||||
text-align: left;
|
||||
padding: 0.3rem 0.6rem;
|
||||
border-bottom: 1px solid var(--nord3, #4c566a);
|
||||
}
|
||||
.result-table th {
|
||||
color: var(--nord9, #81a1c1);
|
||||
}
|
||||
|
||||
.coverage-bar {
|
||||
display: inline-block;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--nord14, #a3be8c);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.coverage-bar-bg {
|
||||
display: inline-block;
|
||||
width: 60px;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--nord3, #4c566a);
|
||||
vertical-align: middle;
|
||||
margin-right: 0.4rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--nord11, #bf616a);
|
||||
margin-top: 0.75rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.summary {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.75rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.summary-stat {
|
||||
text-align: center;
|
||||
}
|
||||
.summary-stat .value {
|
||||
font-size: 1.8rem;
|
||||
font-weight: bold;
|
||||
color: var(--nord10, #5e81ac);
|
||||
}
|
||||
.summary-stat .label {
|
||||
font-size: 0.85rem;
|
||||
color: var(--nord3);
|
||||
}
|
||||
</style>
|
||||
|
||||
<svelte:head>
|
||||
<title>{isEnglish ? 'Nutrition Mappings' : 'Nährwert-Zuordnungen'}</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="container">
|
||||
<h1>{isEnglish ? 'Nutrition Mappings' : 'Nährwert-Zuordnungen'}</h1>
|
||||
<p class="subtitle">
|
||||
{isEnglish
|
||||
? 'Generate ingredient-to-calorie mappings using ML embeddings. Manually edited mappings are preserved.'
|
||||
: 'Zutatenzuordnungen zu Kaloriendaten mittels ML-Embeddings generieren. Manuell bearbeitete Zuordnungen bleiben erhalten.'}
|
||||
</p>
|
||||
|
||||
<!-- Single recipe -->
|
||||
<div class="section">
|
||||
<h2>{isEnglish ? 'Single Recipe' : 'Einzelnes Rezept'}</h2>
|
||||
<div class="input-row">
|
||||
<input
|
||||
type="text"
|
||||
placeholder={isEnglish ? 'Recipe short_name (e.g., maccaroni)' : 'Rezept short_name (z.B. maccaroni)'}
|
||||
bind:value={recipeName}
|
||||
onkeydown={(e) => e.key === 'Enter' && generateSingle()}
|
||||
/>
|
||||
<button disabled={!!singleProcessing || !recipeName.trim()} onclick={generateSingle}>
|
||||
{singleProcessing ? (isEnglish ? 'Processing...' : 'Verarbeite...') : (isEnglish ? 'Generate' : 'Generieren')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if singleResult}
|
||||
<div class="result-box">
|
||||
<p>{singleResult.count} {isEnglish ? 'ingredients mapped' : 'Zutaten zugeordnet'}</p>
|
||||
<table class="result-table">
|
||||
<thead><tr><th>#</th><th>{isEnglish ? 'Ingredient' : 'Zutat'}</th><th>{isEnglish ? 'Match' : 'Treffer'}</th><th>{isEnglish ? 'Confidence' : 'Konfidenz'}</th><th>g/unit</th></tr></thead>
|
||||
<tbody>
|
||||
{#each singleResult.mappings as m, i}
|
||||
<tr>
|
||||
<td>{i + 1}</td>
|
||||
<td>{m.ingredientName}</td>
|
||||
<td>{m.nutritionDbName || '—'}</td>
|
||||
<td>{m.matchConfidence ? (m.matchConfidence * 100).toFixed(0) + '%' : '—'}</td>
|
||||
<td>{m.gramsPerUnit || '—'}</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Batch all recipes -->
|
||||
<div class="section">
|
||||
<h2>{isEnglish ? 'Batch: All Recipes' : 'Batch: Alle Rezepte'}</h2>
|
||||
<p>{isEnglish
|
||||
? 'Regenerate nutrition mappings for all recipes. This may take a few minutes on first run (ML model loading).'
|
||||
: 'Nährwertzuordnungen für alle Rezepte neu generieren. Beim ersten Durchlauf kann dies einige Minuten dauern (ML-Modell wird geladen).'}
|
||||
</p>
|
||||
<button class="btn-danger" disabled={processing} onclick={generateAll}>
|
||||
{processing ? (isEnglish ? 'Processing all recipes...' : 'Verarbeite alle Rezepte...') : (isEnglish ? 'Generate All' : 'Alle generieren')}
|
||||
</button>
|
||||
|
||||
{#if batchResult}
|
||||
<div class="summary">
|
||||
<div class="summary-stat">
|
||||
<div class="value">{batchResult.recipes}</div>
|
||||
<div class="label">{isEnglish ? 'Recipes' : 'Rezepte'}</div>
|
||||
</div>
|
||||
<div class="summary-stat">
|
||||
<div class="value">{batchResult.totalMapped}/{batchResult.totalIngredients}</div>
|
||||
<div class="label">{isEnglish ? 'Ingredients Mapped' : 'Zutaten zugeordnet'}</div>
|
||||
</div>
|
||||
<div class="summary-stat">
|
||||
<div class="value">{batchResult.coverage}</div>
|
||||
<div class="label">{isEnglish ? 'Coverage' : 'Abdeckung'}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="result-box">
|
||||
<table class="result-table">
|
||||
<thead><tr><th>{isEnglish ? 'Recipe' : 'Rezept'}</th><th>{isEnglish ? 'Mapped' : 'Zugeordnet'}</th><th>{isEnglish ? 'Coverage' : 'Abdeckung'}</th></tr></thead>
|
||||
<tbody>
|
||||
{#each batchResult.details as detail}
|
||||
<tr>
|
||||
<td>{detail.name}</td>
|
||||
<td>{detail.mapped}/{detail.total}</td>
|
||||
<td>
|
||||
<span class="coverage-bar-bg">
|
||||
<span class="coverage-bar" style="width: {detail.total ? (detail.mapped / detail.total * 60) : 0}px"></span>
|
||||
</span>
|
||||
{detail.total ? Math.round(detail.mapped / detail.total * 100) : 0}%
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if errorMsg}
|
||||
<p class="error">{errorMsg}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -33,6 +33,14 @@
|
||||
: 'Dominante Farben aus Rezeptbildern für Ladeplatzhalter extrahieren',
|
||||
href: `/${data.recipeLang}/admin/image-colors`,
|
||||
icon: '🎨'
|
||||
},
|
||||
{
|
||||
title: isEnglish ? 'Nutrition Mappings' : 'Nährwert-Zuordnungen',
|
||||
description: isEnglish
|
||||
? 'Generate or regenerate calorie and nutrition data for all recipes'
|
||||
: 'Kalorien- und Nährwertdaten für alle Rezepte generieren oder aktualisieren',
|
||||
href: `/${data.recipeLang}/admin/nutrition`,
|
||||
icon: '🥗'
|
||||
}
|
||||
];
|
||||
</script>
|
||||
|
||||
@@ -237,6 +237,167 @@
|
||||
showTranslationWorkflow = false;
|
||||
}
|
||||
|
||||
// Nutrition generation
|
||||
let generatingNutrition = $state(false);
|
||||
let nutritionResult = $state<{ count: number; mappings: any[] } | null>(null);
|
||||
|
||||
async function generateNutrition() {
|
||||
generatingNutrition = true;
|
||||
nutritionResult = null;
|
||||
try {
|
||||
const res = await fetch(`/api/rezepte/nutrition/generate/${encodeURIComponent(short_name.trim())}`, { method: 'POST' });
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new Error(err.message || `HTTP ${res.status}`);
|
||||
}
|
||||
const result = await res.json();
|
||||
nutritionResult = result;
|
||||
const mapped = result.mappings.filter((/** @type {any} */ m) => m.matchMethod !== 'none').length;
|
||||
toast.success(`Nährwerte generiert: ${mapped}/${result.count} Zutaten zugeordnet`);
|
||||
} catch (e: any) {
|
||||
toast.error(`Fehler: ${e.message}`);
|
||||
} finally {
|
||||
generatingNutrition = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Manual nutrition search
|
||||
let searchQueries = $state<Record<string, string>>({});
|
||||
let searchResults = $state<Record<string, { source: 'bls' | 'usda'; id: string; name: string; category: string; calories: number }[]>>({});
|
||||
let searchTimers = $state<Record<string, ReturnType<typeof setTimeout>>>({});
|
||||
let savingMapping = $state<string | null>(null);
|
||||
let globalToggle = $state<Record<string, boolean>>({});
|
||||
|
||||
function mappingKey(m: any) {
|
||||
return `${m.sectionIndex}-${m.ingredientIndex}`;
|
||||
}
|
||||
|
||||
function handleSearchInput(key: string, value: string) {
|
||||
searchQueries[key] = value;
|
||||
if (searchTimers[key]) clearTimeout(searchTimers[key]);
|
||||
if (value.length < 2) {
|
||||
searchResults[key] = [];
|
||||
return;
|
||||
}
|
||||
searchTimers[key] = setTimeout(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/nutrition/search?q=${encodeURIComponent(value)}`);
|
||||
if (res.ok) searchResults[key] = await res.json();
|
||||
} catch { /* ignore */ }
|
||||
}, 250);
|
||||
}
|
||||
|
||||
async function assignNutritionEntry(mapping: any, entry: { source: 'bls' | 'usda'; id: string; name: string }) {
|
||||
const key = mappingKey(mapping);
|
||||
const isGlobal = globalToggle[key] || false;
|
||||
savingMapping = key;
|
||||
try {
|
||||
const patchBody: Record<string, any> = {
|
||||
sectionIndex: mapping.sectionIndex,
|
||||
ingredientIndex: mapping.ingredientIndex,
|
||||
ingredientName: mapping.ingredientName,
|
||||
ingredientNameDe: mapping.ingredientNameDe,
|
||||
source: entry.source,
|
||||
nutritionDbName: entry.name,
|
||||
matchMethod: 'manual',
|
||||
matchConfidence: 1,
|
||||
excluded: false,
|
||||
global: isGlobal,
|
||||
};
|
||||
if (entry.source === 'bls') {
|
||||
patchBody.blsCode = entry.id;
|
||||
} else {
|
||||
patchBody.fdcId = parseInt(entry.id);
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/rezepte/nutrition/${encodeURIComponent(short_name.trim())}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([patchBody]),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save');
|
||||
if (entry.source === 'bls') {
|
||||
mapping.blsCode = entry.id;
|
||||
mapping.source = 'bls';
|
||||
} else {
|
||||
mapping.fdcId = parseInt(entry.id);
|
||||
mapping.source = 'usda';
|
||||
}
|
||||
mapping.nutritionDbName = entry.name;
|
||||
mapping.matchMethod = 'manual';
|
||||
mapping.matchConfidence = 1;
|
||||
mapping.excluded = false;
|
||||
mapping.manuallyEdited = true;
|
||||
searchResults[key] = [];
|
||||
searchQueries[key] = '';
|
||||
toast.success(`${mapping.ingredientName} → ${entry.name}${isGlobal ? ' (global)' : ''}`);
|
||||
} catch (e: any) {
|
||||
toast.error(`Fehler: ${e.message}`);
|
||||
} finally {
|
||||
savingMapping = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function skipIngredient(mapping: any) {
|
||||
const key = mappingKey(mapping);
|
||||
const isGlobal = globalToggle[key] || false;
|
||||
savingMapping = key;
|
||||
try {
|
||||
const res = await fetch(`/api/rezepte/nutrition/${encodeURIComponent(short_name.trim())}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{
|
||||
sectionIndex: mapping.sectionIndex,
|
||||
ingredientIndex: mapping.ingredientIndex,
|
||||
ingredientName: mapping.ingredientName,
|
||||
ingredientNameDe: mapping.ingredientNameDe,
|
||||
matchMethod: 'manual',
|
||||
matchConfidence: 1,
|
||||
excluded: true,
|
||||
global: isGlobal,
|
||||
}]),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save');
|
||||
mapping.excluded = true;
|
||||
mapping.matchMethod = 'manual';
|
||||
mapping.manuallyEdited = true;
|
||||
searchResults[key] = [];
|
||||
searchQueries[key] = '';
|
||||
toast.success(`${mapping.ingredientName} übersprungen${isGlobal ? ' (global)' : ''}`);
|
||||
} catch (e: any) {
|
||||
toast.error(`Fehler: ${e.message}`);
|
||||
} finally {
|
||||
savingMapping = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function revertToAuto(mapping: any) {
|
||||
const key = mappingKey(mapping);
|
||||
savingMapping = key;
|
||||
try {
|
||||
const res = await fetch(`/api/rezepte/nutrition/${encodeURIComponent(short_name.trim())}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{
|
||||
sectionIndex: mapping.sectionIndex,
|
||||
ingredientIndex: mapping.ingredientIndex,
|
||||
ingredientName: mapping.ingredientName,
|
||||
ingredientNameDe: mapping.ingredientNameDe,
|
||||
manuallyEdited: false,
|
||||
excluded: false,
|
||||
}]),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save');
|
||||
// Re-generate to get the auto match
|
||||
await generateNutrition();
|
||||
toast.success(`${mapping.ingredientName} → automatisch`);
|
||||
} catch (e: any) {
|
||||
toast.error(`Fehler: ${e.message}`);
|
||||
} finally {
|
||||
savingMapping = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Display form errors if any
|
||||
$effect(() => {
|
||||
if (form?.error) {
|
||||
@@ -381,6 +542,225 @@
|
||||
max-width: 800px;
|
||||
text-align: center;
|
||||
}
|
||||
.nutrition-generate {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin: 1.5rem auto;
|
||||
max-width: 1000px;
|
||||
}
|
||||
.nutrition-result-box {
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
padding: 1rem;
|
||||
border-radius: 6px;
|
||||
background: var(--nord0, #2e3440);
|
||||
color: var(--nord6, #eceff4);
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.nutrition-result-summary {
|
||||
margin: 0 0 0.5rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
.nutrition-result-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.nutrition-result-table th,
|
||||
.nutrition-result-table td {
|
||||
text-align: left;
|
||||
padding: 0.3rem 0.6rem;
|
||||
border-bottom: 1px solid var(--nord3, #4c566a);
|
||||
}
|
||||
.nutrition-result-table th {
|
||||
color: var(--nord9, #81a1c1);
|
||||
}
|
||||
.unmapped-row {
|
||||
opacity: 0.7;
|
||||
}
|
||||
.usda-search-cell {
|
||||
position: relative;
|
||||
}
|
||||
.usda-search-input {
|
||||
display: inline !important;
|
||||
width: 100%;
|
||||
padding: 0.2rem 0.4rem !important;
|
||||
margin: 0 !important;
|
||||
border: 1px solid var(--nord3) !important;
|
||||
border-radius: 3px !important;
|
||||
background: var(--nord1, #3b4252) !important;
|
||||
color: inherit !important;
|
||||
font-size: 0.85rem !important;
|
||||
scale: 1 !important;
|
||||
}
|
||||
.usda-search-input:hover,
|
||||
.usda-search-input:focus-visible {
|
||||
scale: 1 !important;
|
||||
}
|
||||
.usda-search-dropdown {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--nord1, #3b4252);
|
||||
border: 1px solid var(--nord3);
|
||||
border-radius: 3px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
min-width: 300px;
|
||||
}
|
||||
.usda-search-dropdown li button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
font-family: monospace;
|
||||
}
|
||||
.usda-search-dropdown li button:hover {
|
||||
background: var(--nord2, #434c5e);
|
||||
}
|
||||
.usda-cal {
|
||||
color: var(--nord9, #81a1c1);
|
||||
margin-left: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.source-badge {
|
||||
display: inline-block;
|
||||
font-size: 0.6rem;
|
||||
font-weight: 700;
|
||||
padding: 0.1rem 0.3rem;
|
||||
border-radius: 2px;
|
||||
margin-right: 0.3rem;
|
||||
background: var(--nord10, #5e81ac);
|
||||
color: var(--nord6, #eceff4);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.source-badge.bls {
|
||||
background: var(--nord14, #a3be8c);
|
||||
color: var(--nord0, #2e3440);
|
||||
}
|
||||
.source-badge.skip {
|
||||
background: var(--nord11, #bf616a);
|
||||
}
|
||||
.manual-indicator {
|
||||
display: inline-block;
|
||||
font-size: 0.55rem;
|
||||
font-weight: 700;
|
||||
color: var(--nord13, #ebcb8b);
|
||||
margin-left: 0.2rem;
|
||||
vertical-align: super;
|
||||
}
|
||||
.excluded-row {
|
||||
opacity: 0.45;
|
||||
}
|
||||
.excluded-row td {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.excluded-row td:last-child,
|
||||
.excluded-row td:nth-last-child(2),
|
||||
.excluded-row td:nth-last-child(3) {
|
||||
text-decoration: none;
|
||||
}
|
||||
.manual-row {
|
||||
border-left: 2px solid var(--nord13, #ebcb8b);
|
||||
}
|
||||
.excluded-label {
|
||||
font-style: italic;
|
||||
color: var(--nord11, #bf616a);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.de-name {
|
||||
color: var(--nord9, #81a1c1);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.current-match {
|
||||
display: block;
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
.current-match.manual-match {
|
||||
color: var(--nord13, #ebcb8b);
|
||||
}
|
||||
.usda-search-input.has-match {
|
||||
opacity: 0.5;
|
||||
font-size: 0.75rem !important;
|
||||
}
|
||||
.usda-search-input.has-match:focus {
|
||||
opacity: 1;
|
||||
font-size: 0.85rem !important;
|
||||
}
|
||||
.row-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.global-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
font-size: 0.7rem;
|
||||
color: var(--nord9, #81a1c1);
|
||||
cursor: pointer;
|
||||
}
|
||||
.global-toggle input {
|
||||
display: inline !important;
|
||||
width: auto !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
scale: 1 !important;
|
||||
}
|
||||
.revert-btn {
|
||||
background: none;
|
||||
border: 1px solid var(--nord3, #4c566a);
|
||||
border-radius: 3px;
|
||||
color: var(--nord9, #81a1c1);
|
||||
cursor: pointer;
|
||||
padding: 0.1rem 0.35rem;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
.revert-btn:hover {
|
||||
background: var(--nord9, #81a1c1);
|
||||
color: var(--nord0, #2e3440);
|
||||
}
|
||||
.skip-btn {
|
||||
background: none;
|
||||
border: 1px solid var(--nord3, #4c566a);
|
||||
border-radius: 3px;
|
||||
color: var(--nord11, #bf616a);
|
||||
cursor: pointer;
|
||||
padding: 0.15rem 0.4rem;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.skip-btn:hover {
|
||||
background: var(--nord11, #bf616a);
|
||||
color: var(--nord6, #eceff4);
|
||||
}
|
||||
.skip-btn.active {
|
||||
background: var(--nord11, #bf616a);
|
||||
color: var(--nord6, #eceff4);
|
||||
}
|
||||
.skip-btn.active:hover {
|
||||
background: var(--nord14, #a3be8c);
|
||||
color: var(--nord0, #2e3440);
|
||||
}
|
||||
</style>
|
||||
|
||||
<svelte:head>
|
||||
@@ -535,6 +915,110 @@
|
||||
<input type="hidden" name="addendum" value={addendum} />
|
||||
</div>
|
||||
|
||||
<!-- Nutrition generation -->
|
||||
<div class="nutrition-generate">
|
||||
<button
|
||||
type="button"
|
||||
class="action_button"
|
||||
onclick={generateNutrition}
|
||||
disabled={generatingNutrition || !short_name.trim()}
|
||||
style="background-color: var(--nord10);"
|
||||
>
|
||||
<p>{generatingNutrition ? 'Generiere…' : 'Nährwerte generieren'}</p>
|
||||
</button>
|
||||
{#if nutritionResult}
|
||||
<div class="nutrition-result-box">
|
||||
<p class="nutrition-result-summary">
|
||||
{nutritionResult.mappings.filter((m) => m.matchMethod !== 'none').length}/{nutritionResult.count} Zutaten zugeordnet
|
||||
</p>
|
||||
<table class="nutrition-result-table">
|
||||
<thead><tr><th>#</th><th>Zutat</th><th>Quelle</th><th>Treffer / Suche</th><th>Konf.</th><th>g/u</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each nutritionResult.mappings as m, i}
|
||||
{@const key = mappingKey(m)}
|
||||
<tr class:unmapped-row={m.matchMethod === 'none' && !m.excluded} class:excluded-row={m.excluded} class:manual-row={m.manuallyEdited && !m.excluded}>
|
||||
<td>{i + 1}</td>
|
||||
<td>
|
||||
{m.ingredientName}
|
||||
{#if m.ingredientNameDe && m.ingredientNameDe !== m.ingredientName}
|
||||
<span class="de-name">({m.ingredientNameDe})</span>
|
||||
{/if}
|
||||
</td>
|
||||
<td>
|
||||
{#if m.excluded}
|
||||
<span class="source-badge skip">SKIP</span>
|
||||
{:else if m.matchMethod !== 'none'}
|
||||
<span class="source-badge" class:bls={m.source === 'bls'}>{(m.source || 'usda').toUpperCase()}</span>
|
||||
{#if m.manuallyEdited}<span class="manual-indicator" title="Manuell zugeordnet">M</span>{/if}
|
||||
{:else}
|
||||
—
|
||||
{/if}
|
||||
</td>
|
||||
<td>
|
||||
<div class="usda-search-cell">
|
||||
{#if m.excluded}
|
||||
<span class="excluded-label">Übersprungen</span>
|
||||
{:else if m.matchMethod !== 'none' && !searchQueries[key]}
|
||||
<span class="current-match" class:manual-match={m.manuallyEdited}>{m.nutritionDbName || '—'}</span>
|
||||
{/if}
|
||||
<input
|
||||
type="text"
|
||||
class="usda-search-input"
|
||||
class:has-match={m.matchMethod !== 'none' && !m.excluded && !searchQueries[key]}
|
||||
placeholder={m.excluded ? 'Suche für neuen Treffer…' : (m.matchMethod !== 'none' ? 'Überschreiben…' : 'BLS/USDA suchen…')}
|
||||
value={searchQueries[key] || ''}
|
||||
oninput={(e) => handleSearchInput(key, e.currentTarget.value)}
|
||||
/>
|
||||
{#if searchResults[key]?.length > 0}
|
||||
<ul class="usda-search-dropdown">
|
||||
{#each searchResults[key] as result}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingMapping === key}
|
||||
onclick={() => assignNutritionEntry(m, result)}
|
||||
>
|
||||
<span class="source-badge" class:bls={result.source === 'bls'}>{result.source.toUpperCase()}</span>
|
||||
{result.name}
|
||||
<span class="usda-cal">{Math.round(result.calories)} kcal</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
<div class="row-controls">
|
||||
<label class="global-toggle">
|
||||
<input type="checkbox" checked={globalToggle[key] || false} onchange={() => { globalToggle[key] = !globalToggle[key]; }} />
|
||||
global
|
||||
</label>
|
||||
{#if m.manuallyEdited || m.excluded}
|
||||
<button type="button" class="revert-btn" disabled={savingMapping === key} onclick={() => revertToAuto(m)} title="Zurück auf automatisch">auto</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>{m.matchConfidence ? (m.matchConfidence * 100).toFixed(0) + '%' : '—'}</td>
|
||||
<td>{m.gramsPerUnit || '—'}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
class="skip-btn"
|
||||
class:active={m.excluded}
|
||||
disabled={savingMapping === key}
|
||||
onclick={() => m.excluded ? revertToAuto(m) : skipIngredient(m)}
|
||||
title={m.excluded ? 'Wieder aktivieren' : 'Überspringen'}
|
||||
>
|
||||
{m.excluded ? '↩' : '✕'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !showTranslationWorkflow}
|
||||
<div class="submit_buttons">
|
||||
<button
|
||||
|
||||
@@ -4,6 +4,7 @@ import { dbConnect } from '$utils/db';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import type { RecipeModelType, IngredientItem, InstructionItem } from '$types/types';
|
||||
import { isEnglish } from '$lib/server/recipeHelpers';
|
||||
import { getNutritionEntryByFdcId, getBlsEntryByCode, computeRecipeNutritionTotals } from '$lib/server/nutritionMatcher';
|
||||
|
||||
/** Recursively map populated baseRecipeRef to resolvedRecipe field */
|
||||
function mapBaseRecipeRefs(items: any[]): any[] {
|
||||
@@ -22,6 +23,91 @@ function mapBaseRecipeRefs(items: any[]): any[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve per100g nutrition data into mappings so client doesn't need the full DB */
|
||||
function resolveNutritionData(mappings: any[]): any[] {
|
||||
if (!mappings || mappings.length === 0) return [];
|
||||
return mappings.map((m: any) => {
|
||||
if (m.matchMethod === 'none') return m;
|
||||
// BLS source: look up by blsCode
|
||||
if (m.blsCode && m.source === 'bls') {
|
||||
const entry = getBlsEntryByCode(m.blsCode);
|
||||
if (entry) return { ...m, per100g: entry.per100g };
|
||||
}
|
||||
// USDA source: look up by fdcId
|
||||
if (m.fdcId) {
|
||||
const entry = getNutritionEntryByFdcId(m.fdcId);
|
||||
if (entry) return { ...m, per100g: entry.per100g };
|
||||
}
|
||||
return m;
|
||||
});
|
||||
}
|
||||
|
||||
/** Parse anchor href from ingredient name, return short_name or null */
|
||||
function parseAnchorRecipeRef(ingredientName: string): string | null {
|
||||
const match = ingredientName.match(/<a\s+href=["']?([^"' >]+)["']?[^>]*>/i);
|
||||
if (!match) return null;
|
||||
let href = match[1].trim();
|
||||
// Strip query params (e.g., ?multiplier={{multiplier}})
|
||||
href = href.split('?')[0];
|
||||
// Skip external links
|
||||
if (href.startsWith('http') || href.includes('://')) return null;
|
||||
// Strip leading path components like /rezepte/ or ./
|
||||
href = href.replace(/^(\.?\/?rezepte\/|\.\/|\/)/, '');
|
||||
// Skip if contains a dot (file extensions, external domains)
|
||||
if (href.includes('.')) return null;
|
||||
return href || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build nutrition totals for referenced recipes:
|
||||
* 1. Base recipe references (type='reference' with populated baseRecipeRef)
|
||||
* 2. Anchor-tag references in ingredient names (<a href=...>)
|
||||
*/
|
||||
async function resolveReferencedNutrition(
|
||||
ingredients: any[],
|
||||
): Promise<{ shortName: string; name: string; nutrition: Record<string, number>; baseMultiplier: number }[]> {
|
||||
const results: { shortName: string; name: string; nutrition: Record<string, number>; baseMultiplier: number }[] = [];
|
||||
const processedSlugs = new Set<string>();
|
||||
|
||||
for (const section of ingredients) {
|
||||
// Type 1: Base recipe references
|
||||
if (section.type === 'reference' && section.baseRecipeRef) {
|
||||
const ref = section.baseRecipeRef;
|
||||
const slug = ref.short_name;
|
||||
if (processedSlugs.has(slug)) continue;
|
||||
processedSlugs.add(slug);
|
||||
|
||||
if (ref.nutritionMappings?.length > 0) {
|
||||
const mult = section.baseMultiplier || 1;
|
||||
const nutrition = computeRecipeNutritionTotals(ref.ingredients || [], ref.nutritionMappings, 1);
|
||||
results.push({ shortName: slug, name: ref.name, nutrition, baseMultiplier: mult });
|
||||
}
|
||||
}
|
||||
|
||||
// Type 2: Anchor-tag references in ingredient names
|
||||
if (section.list) {
|
||||
for (const item of section.list) {
|
||||
const refSlug = parseAnchorRecipeRef(item.name || '');
|
||||
if (!refSlug || processedSlugs.has(refSlug)) continue;
|
||||
processedSlugs.add(refSlug);
|
||||
|
||||
// Look up the referenced recipe
|
||||
const refRecipe = await Recipe.findOne({ short_name: refSlug })
|
||||
.select('short_name name ingredients nutritionMappings portions')
|
||||
.lean();
|
||||
if (!refRecipe?.nutritionMappings?.length) continue;
|
||||
|
||||
const nutrition = computeRecipeNutritionTotals(
|
||||
refRecipe.ingredients || [], refRecipe.nutritionMappings, 1
|
||||
);
|
||||
results.push({ shortName: refSlug, name: refRecipe.name, nutrition, baseMultiplier: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
await dbConnect();
|
||||
const en = isEnglish(params.recipeLang!);
|
||||
@@ -34,25 +120,25 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
? [
|
||||
{
|
||||
path: 'translations.en.ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations',
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations',
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations'
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'translations.en.instructions.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations',
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'instructions.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations',
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'instructions.baseRecipeRef',
|
||||
select: 'short_name name ingredients instructions translations'
|
||||
select: 'short_name name ingredients instructions translations nutritionMappings portions'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,13 +146,13 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
: [
|
||||
{
|
||||
path: 'ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients translations',
|
||||
select: 'short_name name ingredients translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients translations',
|
||||
select: 'short_name name ingredients translations nutritionMappings portions',
|
||||
populate: {
|
||||
path: 'ingredients.baseRecipeRef',
|
||||
select: 'short_name name ingredients translations'
|
||||
select: 'short_name name ingredients translations nutritionMappings portions'
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -126,6 +212,7 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
total_time: t.total_time || rawRecipe.total_time || '',
|
||||
translationStatus: t.translationStatus,
|
||||
germanShortName: rawRecipe.short_name,
|
||||
nutritionMappings: resolveNutritionData(rawRecipe.nutritionMappings || []),
|
||||
};
|
||||
|
||||
if (recipe.ingredients) {
|
||||
@@ -135,6 +222,9 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
recipe.instructions = mapBaseRecipeRefs(recipe.instructions as any[]);
|
||||
}
|
||||
|
||||
// Resolve nutrition from referenced recipes (base refs + anchor tags)
|
||||
recipe.referencedNutrition = await resolveReferencedNutrition(rawRecipe.ingredients || []);
|
||||
|
||||
// Merge English alt/caption with original image paths
|
||||
const imagesArray = Array.isArray(rawRecipe.images) ? rawRecipe.images : (rawRecipe.images ? [rawRecipe.images] : []);
|
||||
if (imagesArray.length > 0) {
|
||||
@@ -152,11 +242,14 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
|
||||
// German: pass through with base recipe ref mapping
|
||||
let recipe = JSON.parse(JSON.stringify(rawRecipe));
|
||||
recipe.nutritionMappings = resolveNutritionData(recipe.nutritionMappings || []);
|
||||
if (recipe.ingredients) {
|
||||
recipe.ingredients = mapBaseRecipeRefs(recipe.ingredients);
|
||||
}
|
||||
if (recipe.instructions) {
|
||||
recipe.instructions = mapBaseRecipeRefs(recipe.instructions);
|
||||
}
|
||||
// Resolve nutrition from referenced recipes (base refs + anchor tags)
|
||||
recipe.referencedNutrition = await resolveReferencedNutrition(rawRecipe.ingredients || []);
|
||||
return json(recipe);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { json, error, type RequestHandler } from '@sveltejs/kit';
|
||||
import { Recipe } from '$models/Recipe';
|
||||
import { dbConnect } from '$utils/db';
|
||||
import { isEnglish } from '$lib/server/recipeHelpers';
|
||||
import { getNutritionEntryByFdcId, getBlsEntryByCode, invalidateOverwriteCache } from '$lib/server/nutritionMatcher';
|
||||
import { NutritionOverwrite } from '$models/NutritionOverwrite';
|
||||
import { canonicalizeUnit, resolveGramsPerUnit } from '$lib/data/unitConversions';
|
||||
import type { NutritionMapping } from '$types/types';
|
||||
|
||||
/** PATCH: Update individual nutrition mappings (manual edit UI) */
|
||||
export const PATCH: RequestHandler = async ({ params, request, locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
|
||||
const en = isEnglish(params.recipeLang!);
|
||||
const query = en
|
||||
? { 'translations.en.short_name': params.name }
|
||||
: { short_name: params.name };
|
||||
|
||||
const recipe = await Recipe.findOne(query);
|
||||
if (!recipe) throw error(404, 'Recipe not found');
|
||||
|
||||
const updates: (Partial<NutritionMapping> & { global?: boolean; ingredientNameDe?: string })[] = await request.json();
|
||||
const mappings: any[] = recipe.nutritionMappings || [];
|
||||
|
||||
for (const update of updates) {
|
||||
// If global flag is set, also create/update a NutritionOverwrite
|
||||
if (update.global && update.ingredientNameDe) {
|
||||
const owData: Record<string, any> = {
|
||||
ingredientNameDe: update.ingredientNameDe.toLowerCase().trim(),
|
||||
source: update.excluded ? 'skip' : (update.source || 'usda'),
|
||||
excluded: update.excluded || false,
|
||||
};
|
||||
if (update.ingredientName) owData.ingredientNameEn = update.ingredientName;
|
||||
if (update.fdcId) owData.fdcId = update.fdcId;
|
||||
if (update.blsCode) owData.blsCode = update.blsCode;
|
||||
if (update.nutritionDbName) owData.nutritionDbName = update.nutritionDbName;
|
||||
|
||||
await NutritionOverwrite.findOneAndUpdate(
|
||||
{ ingredientNameDe: owData.ingredientNameDe },
|
||||
owData,
|
||||
{ upsert: true, runValidators: true },
|
||||
);
|
||||
invalidateOverwriteCache();
|
||||
}
|
||||
|
||||
// Resolve gramsPerUnit from source DB portions if not provided
|
||||
if (!update.gramsPerUnit && !update.excluded) {
|
||||
if (update.blsCode && update.source === 'bls') {
|
||||
update.gramsPerUnit = 1;
|
||||
update.unitConversionSource = update.unitConversionSource || 'manual';
|
||||
} else if (update.fdcId) {
|
||||
const entry = getNutritionEntryByFdcId(update.fdcId);
|
||||
if (entry) {
|
||||
const resolved = resolveGramsPerUnit('g', entry.portions);
|
||||
update.gramsPerUnit = resolved.grams;
|
||||
update.unitConversionSource = resolved.source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up non-schema fields before saving
|
||||
delete update.global;
|
||||
delete update.ingredientNameDe;
|
||||
|
||||
const idx = mappings.findIndex(
|
||||
(m: any) => m.sectionIndex === update.sectionIndex && m.ingredientIndex === update.ingredientIndex
|
||||
);
|
||||
if (idx >= 0) {
|
||||
Object.assign(mappings[idx], update, { manuallyEdited: true });
|
||||
} else {
|
||||
mappings.push({ ...update, manuallyEdited: true });
|
||||
}
|
||||
}
|
||||
|
||||
recipe.nutritionMappings = mappings;
|
||||
await recipe.save();
|
||||
|
||||
return json({ updated: updates.length });
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||
import { Recipe } from '$models/Recipe';
|
||||
import { dbConnect } from '$utils/db';
|
||||
import { generateNutritionMappings } from '$lib/server/nutritionMatcher';
|
||||
|
||||
export const POST: RequestHandler = async ({ locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
|
||||
const recipes = await Recipe.find({}).lean();
|
||||
const results: { name: string; mapped: number; total: number }[] = [];
|
||||
|
||||
for (const recipe of recipes) {
|
||||
const ingredients = recipe.ingredients || [];
|
||||
const translatedIngredients = recipe.translations?.en?.ingredients;
|
||||
|
||||
// Preserve manually edited mappings
|
||||
const existingMappings = recipe.nutritionMappings || [];
|
||||
const manualMappings = new Map(
|
||||
existingMappings
|
||||
.filter((m: any) => m.manuallyEdited)
|
||||
.map((m: any) => [`${m.sectionIndex}-${m.ingredientIndex}`, m])
|
||||
);
|
||||
|
||||
const newMappings = await generateNutritionMappings(ingredients, translatedIngredients);
|
||||
|
||||
const finalMappings = newMappings.map(m => {
|
||||
const key = `${m.sectionIndex}-${m.ingredientIndex}`;
|
||||
return manualMappings.get(key) || m;
|
||||
});
|
||||
|
||||
await Recipe.updateOne(
|
||||
{ _id: recipe._id },
|
||||
{ $set: { nutritionMappings: finalMappings } }
|
||||
);
|
||||
|
||||
const mapped = finalMappings.filter(m => m.matchMethod !== 'none').length;
|
||||
results.push({ name: recipe.name, mapped, total: finalMappings.length });
|
||||
}
|
||||
|
||||
const totalMapped = results.reduce((sum, r) => sum + r.mapped, 0);
|
||||
const totalIngredients = results.reduce((sum, r) => sum + r.total, 0);
|
||||
|
||||
return json({
|
||||
recipes: results.length,
|
||||
totalIngredients,
|
||||
totalMapped,
|
||||
coverage: totalIngredients ? (totalMapped / totalIngredients * 100).toFixed(1) + '%' : '0%',
|
||||
details: results,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import { json, error, type RequestHandler } from '@sveltejs/kit';
|
||||
import { Recipe } from '$models/Recipe';
|
||||
import { dbConnect } from '$utils/db';
|
||||
import { isEnglish } from '$lib/server/recipeHelpers';
|
||||
import { generateNutritionMappings } from '$lib/server/nutritionMatcher';
|
||||
|
||||
export const POST: RequestHandler = async ({ params, locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
|
||||
const en = isEnglish(params.recipeLang!);
|
||||
const query = en
|
||||
? { 'translations.en.short_name': params.name }
|
||||
: { short_name: params.name };
|
||||
|
||||
const recipe = await Recipe.findOne(query).lean();
|
||||
if (!recipe) throw error(404, 'Recipe not found');
|
||||
|
||||
const ingredients = recipe.ingredients || [];
|
||||
const translatedIngredients = recipe.translations?.en?.ingredients;
|
||||
|
||||
// Preserve manually edited mappings
|
||||
const existingMappings = recipe.nutritionMappings || [];
|
||||
const manualMappings = new Map(
|
||||
existingMappings
|
||||
.filter((m: any) => m.manuallyEdited)
|
||||
.map((m: any) => [`${m.sectionIndex}-${m.ingredientIndex}`, m])
|
||||
);
|
||||
|
||||
const newMappings = await generateNutritionMappings(ingredients, translatedIngredients);
|
||||
|
||||
// Merge: keep manual edits, use new auto-matches for the rest
|
||||
const finalMappings = newMappings.map(m => {
|
||||
const key = `${m.sectionIndex}-${m.ingredientIndex}`;
|
||||
return manualMappings.get(key) || m;
|
||||
});
|
||||
|
||||
await Recipe.updateOne(
|
||||
{ _id: recipe._id },
|
||||
{ $set: { nutritionMappings: finalMappings } }
|
||||
);
|
||||
|
||||
return json({ mappings: finalMappings, count: finalMappings.length });
|
||||
};
|
||||
60
src/routes/api/nutrition/overwrites/+server.ts
Normal file
60
src/routes/api/nutrition/overwrites/+server.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { json, error, type RequestHandler } from '@sveltejs/kit';
|
||||
import { dbConnect } from '$utils/db';
|
||||
import { NutritionOverwrite } from '$models/NutritionOverwrite';
|
||||
import { invalidateOverwriteCache } from '$lib/server/nutritionMatcher';
|
||||
|
||||
/** GET: List all global nutrition overwrites */
|
||||
export const GET: RequestHandler = async ({ locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
const overwrites = await NutritionOverwrite.find({}).sort({ ingredientNameDe: 1 }).lean();
|
||||
return json(overwrites);
|
||||
};
|
||||
|
||||
/** POST: Create a new global nutrition overwrite */
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
|
||||
const body = await request.json();
|
||||
if (!body.ingredientNameDe || !body.source) {
|
||||
throw error(400, 'ingredientNameDe and source are required');
|
||||
}
|
||||
|
||||
const data: Record<string, any> = {
|
||||
ingredientNameDe: body.ingredientNameDe.toLowerCase().trim(),
|
||||
source: body.source,
|
||||
};
|
||||
if (body.ingredientNameEn) data.ingredientNameEn = body.ingredientNameEn;
|
||||
if (body.fdcId) data.fdcId = body.fdcId;
|
||||
if (body.blsCode) data.blsCode = body.blsCode;
|
||||
if (body.nutritionDbName) data.nutritionDbName = body.nutritionDbName;
|
||||
if (body.source === 'skip') data.excluded = true;
|
||||
|
||||
const overwrite = await NutritionOverwrite.findOneAndUpdate(
|
||||
{ ingredientNameDe: data.ingredientNameDe },
|
||||
data,
|
||||
{ upsert: true, new: true, runValidators: true },
|
||||
).lean();
|
||||
|
||||
invalidateOverwriteCache();
|
||||
return json(overwrite, { status: 201 });
|
||||
};
|
||||
|
||||
/** DELETE: Remove a global nutrition overwrite by ingredientNameDe */
|
||||
export const DELETE: RequestHandler = async ({ request, locals }) => {
|
||||
await locals.auth();
|
||||
await dbConnect();
|
||||
|
||||
const body = await request.json();
|
||||
if (!body.ingredientNameDe) {
|
||||
throw error(400, 'ingredientNameDe is required');
|
||||
}
|
||||
|
||||
const result = await NutritionOverwrite.deleteOne({
|
||||
ingredientNameDe: body.ingredientNameDe.toLowerCase().trim(),
|
||||
});
|
||||
|
||||
invalidateOverwriteCache();
|
||||
return json({ deleted: result.deletedCount });
|
||||
};
|
||||
41
src/routes/api/nutrition/search/+server.ts
Normal file
41
src/routes/api/nutrition/search/+server.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||
import { NUTRITION_DB } from '$lib/data/nutritionDb';
|
||||
import { BLS_DB } from '$lib/data/blsDb';
|
||||
|
||||
/** GET: Search BLS + USDA nutrition databases by name substring */
|
||||
export const GET: RequestHandler = async ({ url }) => {
|
||||
const q = (url.searchParams.get('q') || '').toLowerCase().trim();
|
||||
if (q.length < 2) return json([]);
|
||||
|
||||
const results: { source: 'bls' | 'usda'; id: string; name: string; category: string; calories: number }[] = [];
|
||||
|
||||
// Search BLS first (primary)
|
||||
for (const entry of BLS_DB) {
|
||||
if (results.length >= 30) break;
|
||||
if (entry.nameDe.toLowerCase().includes(q) || entry.nameEn.toLowerCase().includes(q)) {
|
||||
results.push({
|
||||
source: 'bls',
|
||||
id: entry.blsCode,
|
||||
name: `${entry.nameDe}${entry.nameEn ? ` (${entry.nameEn})` : ''}`,
|
||||
category: entry.category,
|
||||
calories: entry.per100g.calories,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Then USDA
|
||||
for (const entry of NUTRITION_DB) {
|
||||
if (results.length >= 40) break;
|
||||
if (entry.name.toLowerCase().includes(q)) {
|
||||
results.push({
|
||||
source: 'usda',
|
||||
id: String(entry.fdcId),
|
||||
name: entry.name,
|
||||
category: entry.category,
|
||||
calories: entry.per100g.calories,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return json(results.slice(0, 30));
|
||||
};
|
||||
Reference in New Issue
Block a user