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">
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>
<style>
@@ -96,7 +96,7 @@
</a>
{:else}
<label>
<input type="checkbox" bind:checked />
<input type="checkbox" bind:checked onchange={onchange} />
<span>{label}</span>
</label>
{/if}

View File

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

View File

@@ -1,8 +1,10 @@
import type { Actions, PageServerLoad } from "./$types";
import { redirect, fail } from "@sveltejs/kit";
import { Recipe } from '$models/Recipe';
import { NutritionOverwrite } from '$models/NutritionOverwrite';
import { dbConnect } from '$utils/db';
import { invalidateRecipeCaches } from '$lib/server/cache';
import { invalidateOverwriteCache } from '$lib/server/nutritionMatcher';
import { IMAGE_DIR } from '$env/static/private';
import { rename, access, unlink } from 'fs/promises';
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
await invalidateRecipeCaches();

View File

@@ -170,33 +170,40 @@
return changed;
}
// Show translation workflow before submission
function prepareSubmit() {
// Client-side validation
// Save recipe directly (no translation workflow)
async function saveRecipe() {
if (!short_name.trim()) {
toast.error('Bitte geben Sie einen Kurznamen ein');
toast.error('Bitte einen Kurznamen eingeben');
return;
}
if (!card_data.name) {
toast.error('Bitte geben Sie einen Namen ein');
toast.error('Bitte einen Namen eingeben');
return;
}
// Only detect changed fields if there's an existing translation
changedFields = translationData ? detectChangedFields() : [];
showTranslationWorkflow = true;
// Scroll to translation section
setTimeout(() => {
document.getElementById('translation-section')?.scrollIntoView({ behavior: 'smooth' });
}, 100);
// Mark translation as needing update if fields changed
if (translationData) {
const changed = detectChangedFields();
if (changed.length > 0) {
translationData.translationStatus = 'needs_update';
translationData.changedFields = changed;
}
}
await tick();
formElement.requestSubmit();
}
// Force full retranslation of entire recipe
function forceFullRetranslation() {
changedFields = [];
// Open translation workflow (optional)
function openTranslation() {
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;
setTimeout(() => {
document.getElementById('translation-section')?.scrollIntoView({ behavior: 'smooth' });
}, 100);
@@ -237,22 +244,77 @@
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 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() {
generatingNutrition = true;
nutritionResult = null;
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) {
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;
// Merge: keep local manual edits, use auto for the rest
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`);
} catch (e: any) {
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) {
searchQueries[key] = value;
if (searchTimers[key]) clearTimeout(searchTimers[key]);
@@ -287,115 +338,55 @@
}, 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 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;
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] = '';
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);
mapping.excluded = true;
mapping.matchMethod = 'manual';
mapping.manuallyEdited = true;
searchResults[key] = [];
searchQueries[key] = '';
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;
}
toast.success(`${mapping.ingredientNameDe} übersprungen${isGlobal ? ' (global)' : ''}`);
}
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;
}
mapping.manuallyEdited = false;
mapping.excluded = false;
await generateNutrition();
}
function getGlobalOverwrites() {
return nutritionMappings
.filter((m: any) => globalToggle[mappingKey(m)])
.map((m: any) => ({
ingredientNameDe: (m.ingredientNameDe || m.ingredientName).toLowerCase().trim(),
ingredientNameEn: m.ingredientName,
source: m.excluded ? 'skip' : (m.source || 'usda'),
fdcId: m.fdcId,
blsCode: m.blsCode,
nutritionDbName: m.nutritionDbName,
excluded: m.excluded || false,
}));
}
// Display form errors if any
@@ -488,6 +479,34 @@
font-size: 1.3rem;
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 {
display: flex;
margin-inline: auto;
@@ -497,11 +516,6 @@
align-items: center;
gap: 2rem;
}
.submit_buttons p {
padding: 0;
padding-right: 0.5em;
margin: 0;
}
@media (prefers-color-scheme: dark) {
:global(:root:not([data-theme="light"])) .title {
background-color: var(--nord6-dark);
@@ -542,98 +556,122 @@
max-width: 800px;
text-align: center;
}
.nutrition-generate {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
margin: 1.5rem auto;
.nutrition-section {
max-width: 1000px;
margin: 1.5rem auto;
}
.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;
.nutrition-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.75rem;
}
.nutrition-header h3 {
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;
max-height: 400px;
overflow-y: auto;
cursor: pointer;
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 {
margin: 0 0 0.5rem;
font-weight: bold;
margin: 0 0 0.75rem;
font-weight: 600;
color: var(--color-text-secondary);
font-size: 0.9rem;
}
.nutrition-result-table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.nutrition-result-table th,
.nutrition-result-table td {
text-align: left;
padding: 0.3rem 0.6rem;
border-bottom: 1px solid var(--nord3, #4c566a);
padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--color-bg-elevated);
}
.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 {
opacity: 0.7;
opacity: 0.6;
}
.usda-search-cell {
.search-cell {
position: relative;
}
.usda-search-input {
.search-input {
display: inline !important;
width: 100%;
padding: 0.2rem 0.4rem !important;
padding: 0.3rem 0.5rem !important;
margin: 0 !important;
border: 1px solid var(--nord3) !important;
border-radius: 3px !important;
background: var(--nord1, #3b4252) !important;
color: inherit !important;
border: 1px solid var(--color-bg-elevated) !important;
border-radius: 6px !important;
background: var(--color-bg-primary) !important;
color: var(--color-text-primary) !important;
font-size: 0.85rem !important;
scale: 1 !important;
}
.usda-search-input:hover,
.usda-search-input:focus-visible {
.search-input:hover,
.search-input:focus-visible {
scale: 1 !important;
border-color: var(--color-primary) !important;
}
.usda-search-dropdown {
.search-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
z-index: 10;
list-style: none;
margin: 0;
margin: 2px 0 0;
padding: 0;
background: var(--nord1, #3b4252);
border: 1px solid var(--nord3);
border-radius: 3px;
max-height: 200px;
background: var(--color-bg-primary);
border: 1px solid var(--color-bg-elevated);
border-radius: 8px;
max-height: 240px;
overflow-y: auto;
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;
width: 100%;
text-align: left;
padding: 0.35rem 0.5rem;
padding: 0.4rem 0.6rem;
border: none;
background: none;
color: inherit;
color: var(--color-text-primary);
font-size: 0.8rem;
cursor: pointer;
font-family: monospace;
}
.usda-search-dropdown li button:hover {
background: var(--nord2, #434c5e);
.search-dropdown li button:hover {
background: var(--color-bg-tertiary);
}
.usda-cal {
color: var(--nord9, #81a1c1);
.search-cal {
color: var(--color-text-secondary);
margin-left: 0.5rem;
font-size: 0.75rem;
}
@@ -641,64 +679,67 @@
display: inline-block;
font-size: 0.6rem;
font-weight: 700;
padding: 0.1rem 0.3rem;
border-radius: 2px;
padding: 0.1rem 0.35rem;
border-radius: 4px;
margin-right: 0.3rem;
background: var(--nord10, #5e81ac);
color: var(--nord6, #eceff4);
background: var(--nord10);
color: white;
vertical-align: middle;
}
.source-badge.bls {
background: var(--nord14, #a3be8c);
color: var(--nord0, #2e3440);
background: var(--nord14);
color: var(--nord0);
}
.source-badge.skip {
background: var(--nord11, #bf616a);
background: var(--nord11);
color: white;
}
.manual-indicator {
display: inline-block;
font-size: 0.55rem;
font-weight: 700;
color: var(--nord13, #ebcb8b);
color: var(--nord13);
margin-left: 0.2rem;
vertical-align: super;
}
.excluded-row {
opacity: 0.45;
opacity: 0.4;
}
.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) {
.excluded-row td:nth-last-child(3),
.excluded-row td:nth-last-child(4) {
text-decoration: none;
}
.manual-row {
border-left: 2px solid var(--nord13, #ebcb8b);
border-left: 2px solid var(--nord13);
}
.excluded-label {
font-style: italic;
color: var(--nord11, #bf616a);
color: var(--nord11);
font-size: 0.8rem;
}
.de-name {
color: var(--nord9, #81a1c1);
.en-name {
color: var(--color-text-secondary);
font-size: 0.75rem;
}
.current-match {
display: block;
font-size: 0.8rem;
margin-bottom: 0.2rem;
color: var(--color-text-primary);
}
.current-match.manual-match {
color: var(--nord13, #ebcb8b);
color: var(--nord13);
}
.usda-search-input.has-match {
.search-input.has-match {
opacity: 0.5;
font-size: 0.75rem !important;
}
.usda-search-input.has-match:focus {
.search-input.has-match:focus {
opacity: 1;
font-size: 0.85rem !important;
}
@@ -706,60 +747,110 @@
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 0.25rem;
margin-top: 0.3rem;
}
.global-toggle {
display: flex;
align-items: center;
gap: 0.3rem;
font-size: 0.7rem;
color: var(--nord9, #81a1c1);
cursor: pointer;
.row-controls :global(.toggle-wrapper) {
font-size: 0.75rem;
}
.global-toggle input {
display: inline !important;
width: auto !important;
margin: 0 !important;
padding: 0 !important;
scale: 1 !important;
.row-controls :global(.toggle-wrapper label) {
gap: 0.4rem;
}
.row-controls :global(.toggle-track),
.row-controls :global(input[type="checkbox"]) {
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 {
background: none;
border: 1px solid var(--nord3, #4c566a);
border-radius: 3px;
color: var(--nord9, #81a1c1);
border: 1px solid var(--color-bg-elevated);
border-radius: 4px;
color: var(--color-text-secondary);
cursor: pointer;
padding: 0.1rem 0.35rem;
padding: 0.15rem 0.4rem;
font-size: 0.65rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
transition: all var(--transition-fast);
}
.revert-btn:hover {
background: var(--nord9, #81a1c1);
color: var(--nord0, #2e3440);
background: var(--color-primary);
color: var(--color-text-on-primary);
border-color: var(--color-primary);
}
.skip-btn {
background: none;
border: 1px solid var(--nord3, #4c566a);
border-radius: 3px;
color: var(--nord11, #bf616a);
border: 1px solid var(--color-bg-elevated);
border-radius: 4px;
color: var(--nord11);
cursor: pointer;
padding: 0.15rem 0.4rem;
font-size: 0.8rem;
line-height: 1;
transition: all var(--transition-fast);
}
.skip-btn:hover {
background: var(--nord11, #bf616a);
color: var(--nord6, #eceff4);
background: var(--nord11);
color: white;
}
.skip-btn.active {
background: var(--nord11, #bf616a);
color: var(--nord6, #eceff4);
background: var(--nord11);
color: white;
}
.skip-btn.active:hover {
background: var(--nord14, #a3be8c);
color: var(--nord0, #2e3440);
background: var(--nord14);
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>
@@ -915,33 +1006,33 @@
<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">
<!-- Nutrition section -->
<input type="hidden" name="nutritionMappings_json" value={JSON.stringify(nutritionMappings)} />
<input type="hidden" name="globalOverwrites_json" value={JSON.stringify(getGlobalOverwrites())} />
{#if nutritionMappings.length > 0}
<div class="nutrition-section">
<div class="nutrition-header">
<h3>Nährwerte</h3>
<button type="button" class="regenerate-btn" onclick={generateNutrition} disabled={generatingNutrition || !short_name.trim()}>
{generatingNutrition ? 'Generiere…' : 'Neu generieren'}
</button>
</div>
<div class="nutrition-table-wrapper">
<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>
<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}
{#each nutritionMappings as m, i (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}>
<td>{i + 1}</td>
<td>
{m.ingredientName}
{#if m.ingredientNameDe && m.ingredientNameDe !== m.ingredientName}
<span class="de-name">({m.ingredientNameDe})</span>
{m.ingredientNameDe || m.ingredientName}
{#if m.ingredientName && m.ingredientName !== m.ingredientNameDe}
<span class="en-name">({m.ingredientName})</span>
{/if}
</td>
<td>
@@ -955,7 +1046,7 @@
{/if}
</td>
<td>
<div class="usda-search-cell">
<div class="search-cell">
{#if m.excluded}
<span class="excluded-label">Übersprungen</span>
{:else if m.matchMethod !== 'none' && !searchQueries[key]}
@@ -963,48 +1054,49 @@
{/if}
<input
type="text"
class="usda-search-input"
class="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}
<ul class="search-dropdown">
{#each searchResults[key] as result (result.id)}
<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>
<span class="search-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>
<Toggle checked={globalToggle[key] ?? false} label="global" onchange={() => { globalToggle[key] = !globalToggle[key]; }} />
{#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}
</div>
</div>
</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>
<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'}
>
@@ -1016,38 +1108,31 @@
</tbody>
</table>
</div>
{/if}
</div>
{#if !showTranslationWorkflow}
<div class="submit_buttons">
<button
type="button"
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" />
</div>
{:else}
<div class="nutrition-section">
<h3>Nährwerte</h3>
<div class="section-actions">
<button type="button" class="section-btn" onclick={generateNutrition} disabled={generatingNutrition || !short_name.trim()}>
{generatingNutrition ? 'Generiere…' : 'Generieren'}
</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>
{/if}
</form>
{#if showTranslationWorkflow}
{#if translationData || showTranslationWorkflow}
<div id="translation-section">
<TranslationApproval
germanData={currentRecipeData}
@@ -1058,7 +1143,17 @@
onapproved={handleTranslationApproved}
onskipped={handleTranslationSkipped}
oncancelled={handleTranslationCancelled}
onforceFullRetranslation={forceFullRetranslation}
/>
</div>
{/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 { generateNutritionMappings } from '$lib/server/nutritionMatcher';
export const POST: RequestHandler = async ({ params, locals }) => {
export const POST: RequestHandler = async ({ params, locals, url }) => {
await locals.auth();
await dbConnect();
@@ -19,6 +19,14 @@ export const POST: RequestHandler = async ({ params, locals }) => {
const ingredients = recipe.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
const existingMappings = recipe.nutritionMappings || [];
const manualMappings = new Map(
@@ -27,8 +35,6 @@ export const POST: RequestHandler = async ({ params, locals }) => {
.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}`;

View File

@@ -1,41 +1,48 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { NUTRITION_DB } from '$lib/data/nutritionDb';
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 }) => {
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 }[] = [];
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) {
if (results.length >= 30) break;
if (entry.nameDe.toLowerCase().includes(q) || entry.nameEn.toLowerCase().includes(q)) {
results.push({
const scoreDe = fuzzyScore(q, entry.nameDe.toLowerCase());
const scoreEn = entry.nameEn ? fuzzyScore(q, entry.nameEn.toLowerCase()) : 0;
const best = Math.max(scoreDe, scoreEn);
if (best > 0) {
scored.push({
source: 'bls',
id: entry.blsCode,
name: `${entry.nameDe}${entry.nameEn ? ` (${entry.nameEn})` : ''}`,
category: entry.category,
calories: entry.per100g.calories,
score: best,
});
}
}
// Then USDA
// Search USDA
for (const entry of NUTRITION_DB) {
if (results.length >= 40) break;
if (entry.name.toLowerCase().includes(q)) {
results.push({
const s = fuzzyScore(q, entry.name.toLowerCase());
if (s > 0) {
scored.push({
source: 'usda',
id: String(entry.fdcId),
name: entry.name,
category: entry.category,
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));
};