recipes: overhaul nutrition editor UI and defer saves to form submission

- Nutrition mappings and global overwrites are now local-only until
  the recipe is saved, preventing premature DB writes on generate/edit
- Generate endpoint supports ?preview=true for non-persisting previews
- Show existing nutrition data immediately instead of requiring generate
- Replace raw checkboxes with Toggle component for global overwrites,
  initialized from existing NutritionOverwrite records
- Fix search dropdown readability (solid backgrounds, proper theming)
- Use fuzzy search (fzf-style) for manual nutrition ingredient lookup
- Swap ingredient display: German primary, English in brackets
- Allow editing g/u on manually mapped ingredients
- Make translation optional: separate save (FAB) and translate buttons
- "Vollständig neu übersetzen" now triggers actual full retranslation
- Show existing translation inline instead of behind a button
- Replace nord0 dark backgrounds with semantic theme variables
This commit is contained in:
2026-04-02 19:46:01 +02:00
parent 7e1181461e
commit 705a10bb3a
6 changed files with 458 additions and 317 deletions

View File

@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
let { checked = $bindable(false), label = "", accentColor = "var(--color-primary)", href = undefined as string | undefined } = $props<{ checked?: boolean, label?: string, accentColor?: string, href?: string }>(); let { checked = $bindable(false), label = "", accentColor = "var(--color-primary)", href = undefined as string | undefined, onchange = undefined as (() => void) | undefined } = $props<{ checked?: boolean, label?: string, accentColor?: string, href?: string, onchange?: () => void }>();
</script> </script>
<style> <style>
@@ -96,7 +96,7 @@
</a> </a>
{:else} {:else}
<label> <label>
<input type="checkbox" bind:checked /> <input type="checkbox" bind:checked onchange={onchange} />
<span>{label}</span> <span>{label}</span>
</label> </label>
{/if} {/if}

View File

@@ -14,7 +14,6 @@
onapproved?: (event: CustomEvent) => void; onapproved?: (event: CustomEvent) => void;
onskipped?: () => void; onskipped?: () => void;
oncancelled?: () => void; oncancelled?: () => void;
onforceFullRetranslation?: () => void;
} }
let { let {
@@ -26,7 +25,6 @@
onapproved, onapproved,
onskipped, onskipped,
oncancelled, oncancelled,
onforceFullRetranslation
}: Props = $props(); }: Props = $props();
type TranslationState = 'idle' | 'translating' | 'preview' | 'approved' | 'error'; type TranslationState = 'idle' | 'translating' | 'preview' | 'approved' | 'error';
@@ -204,7 +202,7 @@
}); });
// Handle auto-translate button click // Handle auto-translate button click
async function handleAutoTranslate() { async function handleAutoTranslate(fullRetranslation = false) {
translationState = 'translating'; translationState = 'translating';
errorMessage = ''; errorMessage = '';
validationErrors = []; validationErrors = [];
@@ -217,7 +215,7 @@
}, },
body: JSON.stringify({ body: JSON.stringify({
recipe: germanData, recipe: germanData,
fields: isEditMode && changedFields.length > 0 ? changedFields : undefined, fields: isEditMode && !fullRetranslation && changedFields.length > 0 ? changedFields : undefined,
oldRecipe: oldRecipeData, // For granular item-level change detection oldRecipe: oldRecipeData, // For granular item-level change detection
existingTranslation: englishData, // To merge with unchanged items existingTranslation: englishData, // To merge with unchanged items
}), }),
@@ -358,11 +356,6 @@
oncancelled?.(); oncancelled?.();
} }
// Handle force full retranslation
function handleForceFullRetranslation() {
onforceFullRetranslation?.();
}
// Get status badge color // Get status badge color
function getStatusColor(status: string): string { function getStatusColor(status: string): string {
switch (status) { switch (status) {
@@ -921,10 +914,10 @@ button:disabled {
<button class="btn-danger" onclick={handleCancel}> <button class="btn-danger" onclick={handleCancel}>
Cancel Cancel
</button> </button>
<button class="btn-secondary" onclick={handleForceFullRetranslation}> <button class="btn-secondary" onclick={() => handleAutoTranslate(true)}>
Vollständig neu übersetzen Vollständig neu übersetzen
</button> </button>
<button class="btn-secondary" onclick={handleAutoTranslate}> <button class="btn-secondary" onclick={() => handleAutoTranslate()}>
Re-translate Re-translate
</button> </button>
<button class="btn-primary" onclick={handleApprove}> <button class="btn-primary" onclick={handleApprove}>

View File

@@ -1,8 +1,10 @@
import type { Actions, PageServerLoad } from "./$types"; import type { Actions, PageServerLoad } from "./$types";
import { redirect, fail } from "@sveltejs/kit"; import { redirect, fail } from "@sveltejs/kit";
import { Recipe } from '$models/Recipe'; import { Recipe } from '$models/Recipe';
import { NutritionOverwrite } from '$models/NutritionOverwrite';
import { dbConnect } from '$utils/db'; import { dbConnect } from '$utils/db';
import { invalidateRecipeCaches } from '$lib/server/cache'; import { invalidateRecipeCaches } from '$lib/server/cache';
import { invalidateOverwriteCache } from '$lib/server/nutritionMatcher';
import { IMAGE_DIR } from '$env/static/private'; import { IMAGE_DIR } from '$env/static/private';
import { rename, access, unlink } from 'fs/promises'; import { rename, access, unlink } from 'fs/promises';
import { join } from 'path'; import { join } from 'path';
@@ -209,6 +211,44 @@ export const actions = {
}); });
} }
// Save nutrition mappings (deferred from nutrition UI)
const nutritionMappingsJson = formData.get('nutritionMappings_json')?.toString();
if (nutritionMappingsJson) {
try {
const mappings = JSON.parse(nutritionMappingsJson);
if (mappings.length > 0) {
await Recipe.updateOne(
{ short_name: recipeData.short_name },
{ $set: { nutritionMappings: mappings } }
);
}
} catch (e) {
console.error('Failed to save nutrition mappings:', e);
}
}
// Save global nutrition overwrites
const globalOverwritesJson = formData.get('globalOverwrites_json')?.toString();
if (globalOverwritesJson) {
try {
const overwrites = JSON.parse(globalOverwritesJson);
for (const ow of overwrites) {
if (ow.ingredientNameDe) {
await NutritionOverwrite.findOneAndUpdate(
{ ingredientNameDe: ow.ingredientNameDe },
ow,
{ upsert: true, runValidators: true }
);
}
}
if (overwrites.length > 0) {
invalidateOverwriteCache();
}
} catch (e) {
console.error('Failed to save global overwrites:', e);
}
}
// Invalidate recipe caches after successful update // Invalidate recipe caches after successful update
await invalidateRecipeCaches(); await invalidateRecipeCaches();

View File

@@ -170,33 +170,40 @@
return changed; return changed;
} }
// Show translation workflow before submission // Save recipe directly (no translation workflow)
function prepareSubmit() { async function saveRecipe() {
// Client-side validation
if (!short_name.trim()) { if (!short_name.trim()) {
toast.error('Bitte geben Sie einen Kurznamen ein'); toast.error('Bitte einen Kurznamen eingeben');
return; return;
} }
if (!card_data.name) { if (!card_data.name) {
toast.error('Bitte geben Sie einen Namen ein'); toast.error('Bitte einen Namen eingeben');
return; return;
} }
// Mark translation as needing update if fields changed
// Only detect changed fields if there's an existing translation if (translationData) {
changedFields = translationData ? detectChangedFields() : []; const changed = detectChangedFields();
showTranslationWorkflow = true; if (changed.length > 0) {
translationData.translationStatus = 'needs_update';
// Scroll to translation section translationData.changedFields = changed;
setTimeout(() => { }
document.getElementById('translation-section')?.scrollIntoView({ behavior: 'smooth' }); }
}, 100); await tick();
formElement.requestSubmit();
} }
// Force full retranslation of entire recipe // Open translation workflow (optional)
function forceFullRetranslation() { function openTranslation() {
changedFields = []; if (!short_name.trim()) {
toast.error('Bitte einen Kurznamen eingeben');
return;
}
if (!card_data.name) {
toast.error('Bitte einen Namen eingeben');
return;
}
changedFields = translationData ? detectChangedFields() : [];
showTranslationWorkflow = true; showTranslationWorkflow = true;
setTimeout(() => { setTimeout(() => {
document.getElementById('translation-section')?.scrollIntoView({ behavior: 'smooth' }); document.getElementById('translation-section')?.scrollIntoView({ behavior: 'smooth' });
}, 100); }, 100);
@@ -237,22 +244,77 @@
showTranslationWorkflow = false; showTranslationWorkflow = false;
} }
// Nutrition generation // Nutrition state — all edits are local until form save
let nutritionMappings = $state<any[]>(data.recipe.nutritionMappings || []);
let generatingNutrition = $state(false); let generatingNutrition = $state(false);
let nutritionResult = $state<{ count: number; mappings: any[] } | null>(null); 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 globalToggle = $state<Record<string, boolean>>({});
function mappingKey(m: any) {
return `${m.sectionIndex}-${m.ingredientIndex}`;
}
// Global overwrites loaded from DB — used to init toggle state
let globalOverwriteNames = $state<Set<string>>(new Set());
async function loadGlobalOverwrites() {
try {
const res = await fetch('/api/nutrition/overwrites');
if (res.ok) {
const overwrites: any[] = await res.json();
globalOverwriteNames = new Set(overwrites.map((o: any) => o.ingredientNameDe));
}
} catch { /* ignore */ }
}
// Ensure globalToggle entries exist for all mappings, init from DB overwrites
function initGlobalToggles() {
for (const m of nutritionMappings) {
const key = mappingKey(m);
if (!(key in globalToggle)) {
const deName = (m.ingredientNameDe || m.ingredientName || '').toLowerCase().trim();
globalToggle[key] = globalOverwriteNames.has(deName);
}
}
}
// Pre-init all toggles to false (prevents bind:checked={undefined}), then load real state
initGlobalToggles();
if (nutritionMappings.length > 0) {
loadGlobalOverwrites().then(() => {
// Re-init with real overwrite data (overwrite the false defaults)
for (const m of nutritionMappings) {
const key = mappingKey(m);
const deName = (m.ingredientNameDe || m.ingredientName || '').toLowerCase().trim();
globalToggle[key] = globalOverwriteNames.has(deName);
}
});
}
async function generateNutrition() { async function generateNutrition() {
generatingNutrition = true; generatingNutrition = true;
nutritionResult = null;
try { try {
const res = await fetch(`/api/rezepte/nutrition/generate/${encodeURIComponent(short_name.trim())}`, { method: 'POST' }); const res = await fetch(`/api/rezepte/nutrition/generate/${encodeURIComponent(short_name.trim())}?preview=true`, { method: 'POST' });
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({ message: res.statusText })); const err = await res.json().catch(() => ({ message: res.statusText }));
throw new Error(err.message || `HTTP ${res.status}`); throw new Error(err.message || `HTTP ${res.status}`);
} }
const result = await res.json(); const result = await res.json();
nutritionResult = result; // Merge: keep local manual edits, use auto for the rest
const mapped = result.mappings.filter((/** @type {any} */ m) => m.matchMethod !== 'none').length; const manualMap = new Map(
nutritionMappings
.filter((m: any) => m.manuallyEdited)
.map((m: any) => [mappingKey(m), m])
);
nutritionMappings = result.mappings.map((m: any) => {
const key = mappingKey(m);
return manualMap.get(key) || m;
});
await loadGlobalOverwrites();
initGlobalToggles();
const mapped = nutritionMappings.filter((m: any) => m.matchMethod !== 'none').length;
toast.success(`Nährwerte generiert: ${mapped}/${result.count} Zutaten zugeordnet`); toast.success(`Nährwerte generiert: ${mapped}/${result.count} Zutaten zugeordnet`);
} catch (e: any) { } catch (e: any) {
toast.error(`Fehler: ${e.message}`); toast.error(`Fehler: ${e.message}`);
@@ -261,17 +323,6 @@
} }
} }
// 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) { function handleSearchInput(key: string, value: string) {
searchQueries[key] = value; searchQueries[key] = value;
if (searchTimers[key]) clearTimeout(searchTimers[key]); if (searchTimers[key]) clearTimeout(searchTimers[key]);
@@ -287,115 +338,55 @@
}, 250); }, 250);
} }
async function assignNutritionEntry(mapping: any, entry: { source: 'bls' | 'usda'; id: string; name: string }) { function assignNutritionEntry(mapping: any, entry: { source: 'bls' | 'usda'; id: string; name: string }) {
const key = mappingKey(mapping); const key = mappingKey(mapping);
const isGlobal = globalToggle[key] || false; if (entry.source === 'bls') {
savingMapping = key; mapping.blsCode = entry.id;
try { mapping.source = 'bls';
const patchBody: Record<string, any> = { } else {
sectionIndex: mapping.sectionIndex, mapping.fdcId = parseInt(entry.id);
ingredientIndex: mapping.ingredientIndex, mapping.source = 'usda';
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;
} }
mapping.nutritionDbName = entry.name;
mapping.matchMethod = 'manual';
mapping.matchConfidence = 1;
mapping.excluded = false;
mapping.manuallyEdited = true;
searchResults[key] = [];
searchQueries[key] = '';
const isGlobal = globalToggle[key] || false;
toast.success(`${mapping.ingredientNameDe}${entry.name}${isGlobal ? ' (global)' : ''}`);
} }
async function skipIngredient(mapping: any) { function skipIngredient(mapping: any) {
const key = mappingKey(mapping); const key = mappingKey(mapping);
mapping.excluded = true;
mapping.matchMethod = 'manual';
mapping.manuallyEdited = true;
searchResults[key] = [];
searchQueries[key] = '';
const isGlobal = globalToggle[key] || false; const isGlobal = globalToggle[key] || false;
savingMapping = key; toast.success(`${mapping.ingredientNameDe} übersprungen${isGlobal ? ' (global)' : ''}`);
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) { async function revertToAuto(mapping: any) {
const key = mappingKey(mapping); mapping.manuallyEdited = false;
savingMapping = key; mapping.excluded = false;
try { await generateNutrition();
const res = await fetch(`/api/rezepte/nutrition/${encodeURIComponent(short_name.trim())}`, { }
method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, function getGlobalOverwrites() {
body: JSON.stringify([{ return nutritionMappings
sectionIndex: mapping.sectionIndex, .filter((m: any) => globalToggle[mappingKey(m)])
ingredientIndex: mapping.ingredientIndex, .map((m: any) => ({
ingredientName: mapping.ingredientName, ingredientNameDe: (m.ingredientNameDe || m.ingredientName).toLowerCase().trim(),
ingredientNameDe: mapping.ingredientNameDe, ingredientNameEn: m.ingredientName,
manuallyEdited: false, source: m.excluded ? 'skip' : (m.source || 'usda'),
excluded: false, fdcId: m.fdcId,
}]), blsCode: m.blsCode,
}); nutritionDbName: m.nutritionDbName,
if (!res.ok) throw new Error('Failed to save'); excluded: m.excluded || false,
// 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 // Display form errors if any
@@ -488,6 +479,34 @@
font-size: 1.3rem; font-size: 1.3rem;
color: white; color: white;
} }
.fab-save {
position: fixed;
bottom: 0;
right: 0;
width: 1rem;
height: 1rem;
padding: 2rem;
margin: 2rem;
border-radius: var(--radius-pill);
background-color: var(--red);
display: grid;
justify-content: center;
align-content: center;
z-index: 100;
animation: unset !important;
}
.fab-save:hover, .fab-save:focus {
background-color: var(--nord0) !important;
}
.fab-save:disabled {
opacity: 0.5;
cursor: not-allowed;
}
@media screen and (max-width: 500px) {
.fab-save {
margin: 1rem;
}
}
.submit_buttons { .submit_buttons {
display: flex; display: flex;
margin-inline: auto; margin-inline: auto;
@@ -497,11 +516,6 @@
align-items: center; align-items: center;
gap: 2rem; gap: 2rem;
} }
.submit_buttons p {
padding: 0;
padding-right: 0.5em;
margin: 0;
}
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:global(:root:not([data-theme="light"])) .title { :global(:root:not([data-theme="light"])) .title {
background-color: var(--nord6-dark); background-color: var(--nord6-dark);
@@ -542,98 +556,122 @@
max-width: 800px; max-width: 800px;
text-align: center; text-align: center;
} }
.nutrition-generate { .nutrition-section {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
margin: 1.5rem auto;
max-width: 1000px; max-width: 1000px;
margin: 1.5rem auto;
} }
.nutrition-result-box { .nutrition-header {
width: 100%; display: flex;
margin-top: 0.5rem; align-items: center;
padding: 1rem; justify-content: space-between;
border-radius: 6px; margin-bottom: 0.75rem;
background: var(--nord0, #2e3440); }
color: var(--nord6, #eceff4); .nutrition-header h3 {
font-family: monospace; margin: 0;
}
.regenerate-btn {
background: var(--color-primary);
color: var(--color-text-on-primary);
border: none;
border-radius: var(--radius-pill);
padding: 0.4rem 1rem;
font-size: 0.85rem; font-size: 0.85rem;
max-height: 400px; cursor: pointer;
overflow-y: auto; transition: opacity var(--transition-fast);
}
.regenerate-btn:hover {
opacity: 0.85;
}
.regenerate-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.nutrition-table-wrapper {
background: var(--color-bg-secondary);
border-radius: 12px;
padding: 1rem;
overflow-x: auto;
} }
.nutrition-result-summary { .nutrition-result-summary {
margin: 0 0 0.5rem; margin: 0 0 0.75rem;
font-weight: bold; font-weight: 600;
color: var(--color-text-secondary);
font-size: 0.9rem;
} }
.nutrition-result-table { .nutrition-result-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
font-size: 0.85rem;
} }
.nutrition-result-table th, .nutrition-result-table th,
.nutrition-result-table td { .nutrition-result-table td {
text-align: left; text-align: left;
padding: 0.3rem 0.6rem; padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--nord3, #4c566a); border-bottom: 1px solid var(--color-bg-elevated);
} }
.nutrition-result-table th { .nutrition-result-table th {
color: var(--nord9, #81a1c1); color: var(--color-text-secondary);
font-weight: 600;
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.03em;
} }
.unmapped-row { .unmapped-row {
opacity: 0.7; opacity: 0.6;
} }
.usda-search-cell { .search-cell {
position: relative; position: relative;
} }
.usda-search-input { .search-input {
display: inline !important; display: inline !important;
width: 100%; width: 100%;
padding: 0.2rem 0.4rem !important; padding: 0.3rem 0.5rem !important;
margin: 0 !important; margin: 0 !important;
border: 1px solid var(--nord3) !important; border: 1px solid var(--color-bg-elevated) !important;
border-radius: 3px !important; border-radius: 6px !important;
background: var(--nord1, #3b4252) !important; background: var(--color-bg-primary) !important;
color: inherit !important; color: var(--color-text-primary) !important;
font-size: 0.85rem !important; font-size: 0.85rem !important;
scale: 1 !important; scale: 1 !important;
} }
.usda-search-input:hover, .search-input:hover,
.usda-search-input:focus-visible { .search-input:focus-visible {
scale: 1 !important; scale: 1 !important;
border-color: var(--color-primary) !important;
} }
.usda-search-dropdown { .search-dropdown {
position: absolute; position: absolute;
top: 100%; top: 100%;
left: 0; left: 0;
right: 0; right: 0;
z-index: 10; z-index: 10;
list-style: none; list-style: none;
margin: 0; margin: 2px 0 0;
padding: 0; padding: 0;
background: var(--nord1, #3b4252); background: var(--color-bg-primary);
border: 1px solid var(--nord3); border: 1px solid var(--color-bg-elevated);
border-radius: 3px; border-radius: 8px;
max-height: 200px; max-height: 240px;
overflow-y: auto; overflow-y: auto;
min-width: 300px; min-width: 300px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
} }
.usda-search-dropdown li button { .search-dropdown li button {
display: block; display: block;
width: 100%; width: 100%;
text-align: left; text-align: left;
padding: 0.35rem 0.5rem; padding: 0.4rem 0.6rem;
border: none; border: none;
background: none; background: none;
color: inherit; color: var(--color-text-primary);
font-size: 0.8rem; font-size: 0.8rem;
cursor: pointer; cursor: pointer;
font-family: monospace;
} }
.usda-search-dropdown li button:hover { .search-dropdown li button:hover {
background: var(--nord2, #434c5e); background: var(--color-bg-tertiary);
} }
.usda-cal { .search-cal {
color: var(--nord9, #81a1c1); color: var(--color-text-secondary);
margin-left: 0.5rem; margin-left: 0.5rem;
font-size: 0.75rem; font-size: 0.75rem;
} }
@@ -641,64 +679,67 @@
display: inline-block; display: inline-block;
font-size: 0.6rem; font-size: 0.6rem;
font-weight: 700; font-weight: 700;
padding: 0.1rem 0.3rem; padding: 0.1rem 0.35rem;
border-radius: 2px; border-radius: 4px;
margin-right: 0.3rem; margin-right: 0.3rem;
background: var(--nord10, #5e81ac); background: var(--nord10);
color: var(--nord6, #eceff4); color: white;
vertical-align: middle; vertical-align: middle;
} }
.source-badge.bls { .source-badge.bls {
background: var(--nord14, #a3be8c); background: var(--nord14);
color: var(--nord0, #2e3440); color: var(--nord0);
} }
.source-badge.skip { .source-badge.skip {
background: var(--nord11, #bf616a); background: var(--nord11);
color: white;
} }
.manual-indicator { .manual-indicator {
display: inline-block; display: inline-block;
font-size: 0.55rem; font-size: 0.55rem;
font-weight: 700; font-weight: 700;
color: var(--nord13, #ebcb8b); color: var(--nord13);
margin-left: 0.2rem; margin-left: 0.2rem;
vertical-align: super; vertical-align: super;
} }
.excluded-row { .excluded-row {
opacity: 0.45; opacity: 0.4;
} }
.excluded-row td { .excluded-row td {
text-decoration: line-through; text-decoration: line-through;
} }
.excluded-row td:last-child, .excluded-row td:last-child,
.excluded-row td:nth-last-child(2), .excluded-row td:nth-last-child(2),
.excluded-row td:nth-last-child(3) { .excluded-row td:nth-last-child(3),
.excluded-row td:nth-last-child(4) {
text-decoration: none; text-decoration: none;
} }
.manual-row { .manual-row {
border-left: 2px solid var(--nord13, #ebcb8b); border-left: 2px solid var(--nord13);
} }
.excluded-label { .excluded-label {
font-style: italic; font-style: italic;
color: var(--nord11, #bf616a); color: var(--nord11);
font-size: 0.8rem; font-size: 0.8rem;
} }
.de-name { .en-name {
color: var(--nord9, #81a1c1); color: var(--color-text-secondary);
font-size: 0.75rem; font-size: 0.75rem;
} }
.current-match { .current-match {
display: block; display: block;
font-size: 0.8rem; font-size: 0.8rem;
margin-bottom: 0.2rem; margin-bottom: 0.2rem;
color: var(--color-text-primary);
} }
.current-match.manual-match { .current-match.manual-match {
color: var(--nord13, #ebcb8b); color: var(--nord13);
} }
.usda-search-input.has-match { .search-input.has-match {
opacity: 0.5; opacity: 0.5;
font-size: 0.75rem !important; font-size: 0.75rem !important;
} }
.usda-search-input.has-match:focus { .search-input.has-match:focus {
opacity: 1; opacity: 1;
font-size: 0.85rem !important; font-size: 0.85rem !important;
} }
@@ -706,60 +747,110 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
margin-top: 0.25rem; margin-top: 0.3rem;
} }
.global-toggle { .row-controls :global(.toggle-wrapper) {
display: flex; font-size: 0.75rem;
align-items: center;
gap: 0.3rem;
font-size: 0.7rem;
color: var(--nord9, #81a1c1);
cursor: pointer;
} }
.global-toggle input { .row-controls :global(.toggle-wrapper label) {
display: inline !important; gap: 0.4rem;
width: auto !important; }
margin: 0 !important; .row-controls :global(.toggle-track),
padding: 0 !important; .row-controls :global(input[type="checkbox"]) {
scale: 1 !important; width: 32px !important;
height: 18px !important;
}
.row-controls :global(.toggle-track::before),
.row-controls :global(input[type="checkbox"]::before) {
width: 14px !important;
height: 14px !important;
}
.row-controls :global(.toggle-track.checked::before),
.row-controls :global(input[type="checkbox"]:checked::before) {
transform: translateX(14px) !important;
} }
.revert-btn { .revert-btn {
background: none; background: none;
border: 1px solid var(--nord3, #4c566a); border: 1px solid var(--color-bg-elevated);
border-radius: 3px; border-radius: 4px;
color: var(--nord9, #81a1c1); color: var(--color-text-secondary);
cursor: pointer; cursor: pointer;
padding: 0.1rem 0.35rem; padding: 0.15rem 0.4rem;
font-size: 0.65rem; font-size: 0.65rem;
font-weight: 600; font-weight: 600;
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.03em; letter-spacing: 0.03em;
transition: all var(--transition-fast);
} }
.revert-btn:hover { .revert-btn:hover {
background: var(--nord9, #81a1c1); background: var(--color-primary);
color: var(--nord0, #2e3440); color: var(--color-text-on-primary);
border-color: var(--color-primary);
} }
.skip-btn { .skip-btn {
background: none; background: none;
border: 1px solid var(--nord3, #4c566a); border: 1px solid var(--color-bg-elevated);
border-radius: 3px; border-radius: 4px;
color: var(--nord11, #bf616a); color: var(--nord11);
cursor: pointer; cursor: pointer;
padding: 0.15rem 0.4rem; padding: 0.15rem 0.4rem;
font-size: 0.8rem; font-size: 0.8rem;
line-height: 1; line-height: 1;
transition: all var(--transition-fast);
} }
.skip-btn:hover { .skip-btn:hover {
background: var(--nord11, #bf616a); background: var(--nord11);
color: var(--nord6, #eceff4); color: white;
} }
.skip-btn.active { .skip-btn.active {
background: var(--nord11, #bf616a); background: var(--nord11);
color: var(--nord6, #eceff4); color: white;
} }
.skip-btn.active:hover { .skip-btn.active:hover {
background: var(--nord14, #a3be8c); background: var(--nord14);
color: var(--nord0, #2e3440); color: var(--nord0);
}
.gpu-input {
display: inline !important;
width: 4em !important;
padding: 0.2rem 0.3rem !important;
margin: 0 !important;
border: 1px solid var(--color-bg-elevated) !important;
border-radius: 4px !important;
background: var(--color-bg-primary) !important;
color: var(--color-text-primary) !important;
font-size: 0.8rem !important;
scale: 1 !important;
text-align: right;
}
.gpu-input:hover, .gpu-input:focus-visible {
scale: 1 !important;
}
.section-actions {
display: flex;
gap: 0.75rem;
}
.section-btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all var(--transition-fast);
background: var(--color-primary);
color: var(--color-text-on-primary);
}
.section-btn:hover {
opacity: 0.85;
}
.section-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.translation-section-trigger {
max-width: 1000px;
margin: 1.5rem auto;
} }
</style> </style>
@@ -915,33 +1006,33 @@
<input type="hidden" name="addendum" value={addendum} /> <input type="hidden" name="addendum" value={addendum} />
</div> </div>
<!-- Nutrition generation --> <!-- Nutrition section -->
<div class="nutrition-generate"> <input type="hidden" name="nutritionMappings_json" value={JSON.stringify(nutritionMappings)} />
<button <input type="hidden" name="globalOverwrites_json" value={JSON.stringify(getGlobalOverwrites())} />
type="button"
class="action_button" {#if nutritionMappings.length > 0}
onclick={generateNutrition} <div class="nutrition-section">
disabled={generatingNutrition || !short_name.trim()} <div class="nutrition-header">
style="background-color: var(--nord10);" <h3>Nährwerte</h3>
> <button type="button" class="regenerate-btn" onclick={generateNutrition} disabled={generatingNutrition || !short_name.trim()}>
<p>{generatingNutrition ? 'Generiere…' : 'Nährwerte generieren'}</p> {generatingNutrition ? 'Generiere…' : 'Neu generieren'}
</button> </button>
{#if nutritionResult} </div>
<div class="nutrition-result-box"> <div class="nutrition-table-wrapper">
<p class="nutrition-result-summary"> <p class="nutrition-result-summary">
{nutritionResult.mappings.filter((m) => m.matchMethod !== 'none').length}/{nutritionResult.count} Zutaten zugeordnet {nutritionMappings.filter((m) => m.matchMethod !== 'none').length}/{nutritionMappings.length} Zutaten zugeordnet
</p> </p>
<table class="nutrition-result-table"> <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> <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> <tbody>
{#each nutritionResult.mappings as m, i} {#each nutritionMappings as m, i (mappingKey(m))}
{@const key = mappingKey(m)} {@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}> <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>{i + 1}</td>
<td> <td>
{m.ingredientName} {m.ingredientNameDe || m.ingredientName}
{#if m.ingredientNameDe && m.ingredientNameDe !== m.ingredientName} {#if m.ingredientName && m.ingredientName !== m.ingredientNameDe}
<span class="de-name">({m.ingredientNameDe})</span> <span class="en-name">({m.ingredientName})</span>
{/if} {/if}
</td> </td>
<td> <td>
@@ -955,7 +1046,7 @@
{/if} {/if}
</td> </td>
<td> <td>
<div class="usda-search-cell"> <div class="search-cell">
{#if m.excluded} {#if m.excluded}
<span class="excluded-label">Übersprungen</span> <span class="excluded-label">Übersprungen</span>
{:else if m.matchMethod !== 'none' && !searchQueries[key]} {:else if m.matchMethod !== 'none' && !searchQueries[key]}
@@ -963,48 +1054,49 @@
{/if} {/if}
<input <input
type="text" type="text"
class="usda-search-input" class="search-input"
class:has-match={m.matchMethod !== 'none' && !m.excluded && !searchQueries[key]} 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…')} placeholder={m.excluded ? 'Suche für neuen Treffer…' : (m.matchMethod !== 'none' ? 'Überschreiben…' : 'BLS/USDA suchen…')}
value={searchQueries[key] || ''} value={searchQueries[key] || ''}
oninput={(e) => handleSearchInput(key, e.currentTarget.value)} oninput={(e) => handleSearchInput(key, e.currentTarget.value)}
/> />
{#if searchResults[key]?.length > 0} {#if searchResults[key]?.length > 0}
<ul class="usda-search-dropdown"> <ul class="search-dropdown">
{#each searchResults[key] as result} {#each searchResults[key] as result (result.id)}
<li> <li>
<button <button
type="button" type="button"
disabled={savingMapping === key}
onclick={() => assignNutritionEntry(m, result)} onclick={() => assignNutritionEntry(m, result)}
> >
<span class="source-badge" class:bls={result.source === 'bls'}>{result.source.toUpperCase()}</span> <span class="source-badge" class:bls={result.source === 'bls'}>{result.source.toUpperCase()}</span>
{result.name} {result.name}
<span class="usda-cal">{Math.round(result.calories)} kcal</span> <span class="search-cal">{Math.round(result.calories)} kcal</span>
</button> </button>
</li> </li>
{/each} {/each}
</ul> </ul>
{/if} {/if}
<div class="row-controls"> <div class="row-controls">
<label class="global-toggle"> <Toggle checked={globalToggle[key] ?? false} label="global" onchange={() => { globalToggle[key] = !globalToggle[key]; }} />
<input type="checkbox" checked={globalToggle[key] || false} onchange={() => { globalToggle[key] = !globalToggle[key]; }} />
global
</label>
{#if m.manuallyEdited || m.excluded} {#if m.manuallyEdited || m.excluded}
<button type="button" class="revert-btn" disabled={savingMapping === key} onclick={() => revertToAuto(m)} title="Zurück auf automatisch">auto</button> <button type="button" class="revert-btn" onclick={() => revertToAuto(m)} title="Zurück auf automatisch">auto</button>
{/if} {/if}
</div> </div>
</div> </div>
</td> </td>
<td>{m.matchConfidence ? (m.matchConfidence * 100).toFixed(0) + '%' : '—'}</td> <td>{m.matchConfidence ? (m.matchConfidence * 100).toFixed(0) + '%' : '—'}</td>
<td>{m.gramsPerUnit || '—'}</td> <td>
{#if m.manuallyEdited}
<input type="number" class="gpu-input" min="0" step="0.1" bind:value={m.gramsPerUnit} />
{:else}
{m.gramsPerUnit || '—'}
{/if}
</td>
<td> <td>
<button <button
type="button" type="button"
class="skip-btn" class="skip-btn"
class:active={m.excluded} class:active={m.excluded}
disabled={savingMapping === key}
onclick={() => m.excluded ? revertToAuto(m) : skipIngredient(m)} onclick={() => m.excluded ? revertToAuto(m) : skipIngredient(m)}
title={m.excluded ? 'Wieder aktivieren' : 'Überspringen'} title={m.excluded ? 'Wieder aktivieren' : 'Überspringen'}
> >
@@ -1016,38 +1108,31 @@
</tbody> </tbody>
</table> </table>
</div> </div>
{/if} </div>
</div> {:else}
<div class="nutrition-section">
{#if !showTranslationWorkflow} <h3>Nährwerte</h3>
<div class="submit_buttons"> <div class="section-actions">
<button <button type="button" class="section-btn" onclick={generateNutrition} disabled={generatingNutrition || !short_name.trim()}>
type="button" {generatingNutrition ? 'Generiere…' : 'Generieren'}
class="action_button"
onclick={prepareSubmit}
disabled={submitting}
style="background-color: var(--nord14);"
>
<p>Speichern & Übersetzung aktualisieren</p>
<Check fill="white" width="2rem" height="2rem" />
</button>
{#if translationData}
<button
type="button"
class="action_button"
onclick={forceFullRetranslation}
disabled={submitting}
style="background-color: var(--nord12);"
>
<p>Komplett neu übersetzen</p>
<Check fill="white" width="2rem" height="2rem" />
</button> </button>
{/if} </div>
</div>
{/if}
{#if !translationData && !showTranslationWorkflow}
<div class="translation-section-trigger">
<h3>Übersetzung</h3>
<div class="section-actions">
<button type="button" class="section-btn" onclick={openTranslation} disabled={submitting}>
Übersetzen
</button>
</div>
</div> </div>
{/if} {/if}
</form> </form>
{#if showTranslationWorkflow} {#if translationData || showTranslationWorkflow}
<div id="translation-section"> <div id="translation-section">
<TranslationApproval <TranslationApproval
germanData={currentRecipeData} germanData={currentRecipeData}
@@ -1058,7 +1143,17 @@
onapproved={handleTranslationApproved} onapproved={handleTranslationApproved}
onskipped={handleTranslationSkipped} onskipped={handleTranslationSkipped}
oncancelled={handleTranslationCancelled} oncancelled={handleTranslationCancelled}
onforceFullRetranslation={forceFullRetranslation}
/> />
</div> </div>
{/if} {/if}
<!-- FAB save button -->
<button
type="button"
class="fab-save action_button"
onclick={saveRecipe}
disabled={submitting}
aria-label="Rezept speichern"
>
<Check fill="white" width="2rem" height="2rem" />
</button>

View File

@@ -4,7 +4,7 @@ import { dbConnect } from '$utils/db';
import { isEnglish } from '$lib/server/recipeHelpers'; import { isEnglish } from '$lib/server/recipeHelpers';
import { generateNutritionMappings } from '$lib/server/nutritionMatcher'; import { generateNutritionMappings } from '$lib/server/nutritionMatcher';
export const POST: RequestHandler = async ({ params, locals }) => { export const POST: RequestHandler = async ({ params, locals, url }) => {
await locals.auth(); await locals.auth();
await dbConnect(); await dbConnect();
@@ -19,6 +19,14 @@ export const POST: RequestHandler = async ({ params, locals }) => {
const ingredients = recipe.ingredients || []; const ingredients = recipe.ingredients || [];
const translatedIngredients = recipe.translations?.en?.ingredients; const translatedIngredients = recipe.translations?.en?.ingredients;
const newMappings = await generateNutritionMappings(ingredients, translatedIngredients);
const preview = url.searchParams.get('preview') === 'true';
// In preview mode, return pure auto-matches without saving (client merges manual edits)
if (preview) {
return json({ mappings: newMappings, count: newMappings.length });
}
// Preserve manually edited mappings // Preserve manually edited mappings
const existingMappings = recipe.nutritionMappings || []; const existingMappings = recipe.nutritionMappings || [];
const manualMappings = new Map( const manualMappings = new Map(
@@ -27,8 +35,6 @@ export const POST: RequestHandler = async ({ params, locals }) => {
.map((m: any) => [`${m.sectionIndex}-${m.ingredientIndex}`, m]) .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 // Merge: keep manual edits, use new auto-matches for the rest
const finalMappings = newMappings.map(m => { const finalMappings = newMappings.map(m => {
const key = `${m.sectionIndex}-${m.ingredientIndex}`; const key = `${m.sectionIndex}-${m.ingredientIndex}`;

View File

@@ -1,41 +1,48 @@
import { json, type RequestHandler } from '@sveltejs/kit'; import { json, type RequestHandler } from '@sveltejs/kit';
import { NUTRITION_DB } from '$lib/data/nutritionDb'; import { NUTRITION_DB } from '$lib/data/nutritionDb';
import { BLS_DB } from '$lib/data/blsDb'; import { BLS_DB } from '$lib/data/blsDb';
import { fuzzyScore } from '$lib/js/fuzzy';
/** GET: Search BLS + USDA nutrition databases by name substring */ /** GET: Search BLS + USDA nutrition databases by fuzzy name match */
export const GET: RequestHandler = async ({ url }) => { export const GET: RequestHandler = async ({ url }) => {
const q = (url.searchParams.get('q') || '').toLowerCase().trim(); const q = (url.searchParams.get('q') || '').toLowerCase().trim();
if (q.length < 2) return json([]); if (q.length < 2) return json([]);
const results: { source: 'bls' | 'usda'; id: string; name: string; category: string; calories: number }[] = []; const scored: { source: 'bls' | 'usda'; id: string; name: string; category: string; calories: number; score: number }[] = [];
// Search BLS first (primary) // Search BLS (primary)
for (const entry of BLS_DB) { for (const entry of BLS_DB) {
if (results.length >= 30) break; const scoreDe = fuzzyScore(q, entry.nameDe.toLowerCase());
if (entry.nameDe.toLowerCase().includes(q) || entry.nameEn.toLowerCase().includes(q)) { const scoreEn = entry.nameEn ? fuzzyScore(q, entry.nameEn.toLowerCase()) : 0;
results.push({ const best = Math.max(scoreDe, scoreEn);
if (best > 0) {
scored.push({
source: 'bls', source: 'bls',
id: entry.blsCode, id: entry.blsCode,
name: `${entry.nameDe}${entry.nameEn ? ` (${entry.nameEn})` : ''}`, name: `${entry.nameDe}${entry.nameEn ? ` (${entry.nameEn})` : ''}`,
category: entry.category, category: entry.category,
calories: entry.per100g.calories, calories: entry.per100g.calories,
score: best,
}); });
} }
} }
// Then USDA // Search USDA
for (const entry of NUTRITION_DB) { for (const entry of NUTRITION_DB) {
if (results.length >= 40) break; const s = fuzzyScore(q, entry.name.toLowerCase());
if (entry.name.toLowerCase().includes(q)) { if (s > 0) {
results.push({ scored.push({
source: 'usda', source: 'usda',
id: String(entry.fdcId), id: String(entry.fdcId),
name: entry.name, name: entry.name,
category: entry.category, category: entry.category,
calories: entry.per100g.calories, calories: entry.per100g.calories,
score: s,
}); });
} }
} }
return json(results.slice(0, 30)); // Sort by score descending, return top 30 (without score field)
scored.sort((a, b) => b.score - a.score);
return json(scored.slice(0, 30).map(({ score, ...rest }) => rest));
}; };