fix: Zuordnungen zuverlässig speichern und Mengen-Varianten zusammenfassen
Mapping bleibt erhalten, auch wenn der Nährwert-Rebuild länger dauert. Offene Liste führt 1 ml/2 ml Olivenöl als ein Lebensmittel. Dazu JSON-Sicherung, eigener Katalogeintrag und Gramm-pro-Einheit. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
86f15e6957
commit
c1873a47b1
17 files changed
+875
-54
No files matched your search
@@ -1,14 +1,53 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
|
||||
export default function FoodSearchModal({ title, initialQuery, onSelect, onClose }) {
|
||||
const COUNT_UNITS = new Set(['stück', 'scheibe', 'portion', 'becher', 'tasse'])
|
||||
const UNIT_LABEL = {
|
||||
stück: 'Stück', scheibe: 'Scheibe', portion: 'Portion',
|
||||
becher: 'Becher', tasse: 'Tasse', el: 'EL', tl: 'TL', prise: 'Prise',
|
||||
}
|
||||
|
||||
function detectUnit(...texts) {
|
||||
for (const text of texts) {
|
||||
const m = String(text || '').match(
|
||||
/(\d+(?:[.,]\d+)?)\s*(stück|stk|st\.?|scheibe|portion(?:en)?|becher|tasse|el|esslöffel|tl|teelöffel|prise)\b/i
|
||||
)
|
||||
if (!m) continue
|
||||
const raw = m[2].toLowerCase().replace(/\.$/, '')
|
||||
const unit = raw.startsWith('st') && !raw.startsWith('scheibe') ? 'stück'
|
||||
: raw.startsWith('ess') || raw === 'el' ? 'el'
|
||||
: raw.startsWith('tee') || raw === 'tl' ? 'tl'
|
||||
: raw.startsWith('portion') ? 'portion'
|
||||
: raw
|
||||
return unit
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export default function FoodSearchModal({ title, initialQuery, quantityHint, onSelect, onClose }) {
|
||||
const [q, setQ] = useState(initialQuery || '')
|
||||
const [hits, setHits] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [showCreate, setShowCreate] = useState(false)
|
||||
const [manual, setManual] = useState({
|
||||
name_de: initialQuery || '',
|
||||
kcal: '', protein_g: '', fat_g: '', carbs_g: '',
|
||||
})
|
||||
const suggestedUnit = detectUnit(quantityHint, initialQuery)
|
||||
const [gramsPerUnit, setGramsPerUnit] = useState(
|
||||
suggestedUnit === 'el' ? '15' : suggestedUnit === 'tl' ? '5' : ''
|
||||
)
|
||||
const inputRef = useRef(null)
|
||||
const timer = useRef(null)
|
||||
|
||||
const extras = () => {
|
||||
const g = parseFloat(String(gramsPerUnit).replace(',', '.'))
|
||||
if (!suggestedUnit || !g || g <= 0) return {}
|
||||
return { grams_per_unit: g, source_unit: suggestedUnit }
|
||||
}
|
||||
|
||||
const runSearch = async (term) => {
|
||||
const query = (term || '').trim()
|
||||
if (query.length < 2) {
|
||||
@@ -45,6 +84,34 @@ export default function FoodSearchModal({ title, initialQuery, onSelect, onClose
|
||||
timer.current = setTimeout(() => runSearch(value), 250)
|
||||
}
|
||||
|
||||
const createManual = async () => {
|
||||
const name = (manual.name_de || q || '').trim()
|
||||
if (!name) {
|
||||
setError('Name für den Eintrag fehlt')
|
||||
return
|
||||
}
|
||||
setCreating(true)
|
||||
setError(null)
|
||||
try {
|
||||
const food = await api.createUserFood({
|
||||
name_de: name,
|
||||
macros_per_100g: {
|
||||
kcal: parseFloat(String(manual.kcal).replace(',', '.')) || 0,
|
||||
protein_g: parseFloat(String(manual.protein_g).replace(',', '.')) || 0,
|
||||
fat_g: parseFloat(String(manual.fat_g).replace(',', '.')) || 0,
|
||||
carbs_g: parseFloat(String(manual.carbs_g).replace(',', '.')) || 0,
|
||||
},
|
||||
})
|
||||
onSelect(food, extras())
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const unitLabel = UNIT_LABEL[suggestedUnit] || suggestedUnit
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -60,7 +127,7 @@ export default function FoodSearchModal({ title, initialQuery, onSelect, onClose
|
||||
aria-labelledby="food-search-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
width: '100%', maxWidth: 520, maxHeight: 'min(88vh, 640px)',
|
||||
width: '100%', maxWidth: 520, maxHeight: 'min(88vh, 720px)',
|
||||
background: 'var(--surface)', borderRadius: 16,
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.18)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
@@ -80,14 +147,30 @@ export default function FoodSearchModal({ title, initialQuery, onSelect, onClose
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
<p style={{ fontSize: 12, color: 'var(--text3)', margin: '8px 0 0' }}>
|
||||
Suche nach dem Namen. Den BLS-Code brauchst du nicht.
|
||||
Suche nach dem Namen. Fehlt der Treffer, legst du unten einen eigenen Eintrag an.
|
||||
</p>
|
||||
{suggestedUnit && (
|
||||
<label style={{ display: 'block', marginTop: 10, fontSize: 13 }}>
|
||||
1 {unitLabel} ={' '}
|
||||
<input
|
||||
className="form-input"
|
||||
type="number"
|
||||
min="0.1"
|
||||
step="0.1"
|
||||
style={{ width: 90, display: 'inline-block', textAlign: 'left' }}
|
||||
value={gramsPerUnit}
|
||||
onChange={(e) => setGramsPerUnit(e.target.value)}
|
||||
placeholder={COUNT_UNITS.has(suggestedUnit) ? 'z. B. 60' : ''}
|
||||
/>
|
||||
{' '}g
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ overflowY: 'auto', padding: '0 16px 16px', flex: 1 }}>
|
||||
{loading && <p style={{ fontSize: 13, color: 'var(--text2)' }}>Suche…</p>}
|
||||
{error && <p style={{ color: 'var(--danger)', fontSize: 13 }}>{error}</p>}
|
||||
{!loading && q.trim().length >= 2 && hits.length === 0 && (
|
||||
<p style={{ fontSize: 13, color: 'var(--text3)' }}>Kein Treffer. Anderen Suchbegriff versuchen.</p>
|
||||
<p style={{ fontSize: 13, color: 'var(--text3)' }}>Kein Treffer im Katalog.</p>
|
||||
)}
|
||||
{hits.map((h) => (
|
||||
<button
|
||||
@@ -95,7 +178,7 @@ export default function FoodSearchModal({ title, initialQuery, onSelect, onClose
|
||||
type="button"
|
||||
className="btn btn-secondary btn-full"
|
||||
style={{ marginTop: 8, justifyContent: 'flex-start', textAlign: 'left', height: 'auto', padding: '10px 12px' }}
|
||||
onClick={() => onSelect(h)}
|
||||
onClick={() => onSelect(h, extras())}
|
||||
>
|
||||
<span>
|
||||
<strong style={{ display: 'block' }}>{h.name_de}</strong>
|
||||
@@ -107,6 +190,53 @@ export default function FoodSearchModal({ title, initialQuery, onSelect, onClose
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
|
||||
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
|
||||
{!showCreate ? (
|
||||
<button type="button" className="btn btn-secondary btn-full" onClick={() => {
|
||||
setShowCreate(true)
|
||||
setManual((s) => ({ ...s, name_de: s.name_de || q || initialQuery || '' }))
|
||||
}}>
|
||||
Eigenes Lebensmittel anlegen
|
||||
</button>
|
||||
) : (
|
||||
<div>
|
||||
<p style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>Eigener Eintrag (pro 100 g)</p>
|
||||
<input
|
||||
className="form-input"
|
||||
style={{ width: '100%', textAlign: 'left', marginBottom: 8 }}
|
||||
placeholder="Name"
|
||||
value={manual.name_de}
|
||||
onChange={(e) => setManual({ ...manual, name_de: e.target.value })}
|
||||
/>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
|
||||
{[['kcal', 'kcal'], ['protein_g', 'Protein g'], ['fat_g', 'Fett g'], ['carbs_g', 'Kohlenhydrate g']].map(([key, label]) => (
|
||||
<label key={key} style={{ fontSize: 12, color: 'var(--text2)' }}>
|
||||
{label}
|
||||
<input
|
||||
className="form-input"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.1"
|
||||
style={{ width: '100%', textAlign: 'left', marginTop: 4 }}
|
||||
value={manual[key]}
|
||||
onChange={(e) => setManual({ ...manual, [key]: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ marginTop: 10 }}
|
||||
disabled={creating}
|
||||
onClick={createManual}
|
||||
>
|
||||
{creating ? 'Speichere…' : 'Anlegen und zuordnen'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -84,31 +84,43 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
const [searchFor, setSearchFor] = useState(null)
|
||||
const [recipeFor, setRecipeFor] = useState(null)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const listRef = useRef(null)
|
||||
const bundleRef = useRef(null)
|
||||
const loadGen = useRef(0)
|
||||
|
||||
const load = async () => {
|
||||
const gen = ++loadGen.current
|
||||
try {
|
||||
const [u, m, r] = await Promise.all([
|
||||
api.listUnmappedFoods(),
|
||||
api.listMyFoodMappings(),
|
||||
api.listNutritionRecipes().catch(() => []),
|
||||
])
|
||||
if (gen !== loadGen.current) return
|
||||
setUnmapped(u)
|
||||
setLearned(m)
|
||||
setRecipes(Array.isArray(r) ? r : [])
|
||||
} catch (e) {
|
||||
if (gen !== loadGen.current) return
|
||||
setError(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
const assign = async (sourceName, foodId) => {
|
||||
const assign = async (sourceName, foodId, extras = {}) => {
|
||||
setSaving(sourceName)
|
||||
setError(null)
|
||||
try {
|
||||
await api.upsertMyFoodMapping({ source_name: sourceName, food_id: foodId })
|
||||
await api.upsertMyFoodMapping({
|
||||
source_name: sourceName,
|
||||
food_id: foodId,
|
||||
grams_per_unit: extras.grams_per_unit || null,
|
||||
source_unit: extras.source_unit || null,
|
||||
})
|
||||
setSearchFor(null)
|
||||
setNotice(`Zuordnung gespeichert: ${sourceName}`)
|
||||
await load()
|
||||
onChanged?.()
|
||||
} catch (e) {
|
||||
@@ -144,6 +156,39 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
}
|
||||
}
|
||||
|
||||
const exportBundle = async () => {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setNotice(null)
|
||||
try {
|
||||
await api.exportFoodKnowledge()
|
||||
setNotice('Zuordnungen und Listen als JSON heruntergeladen.')
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const importBundle = async (file) => {
|
||||
if (!file) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setNotice(null)
|
||||
try {
|
||||
const res = await api.importFoodKnowledge(file)
|
||||
await load()
|
||||
onChanged?.()
|
||||
const skip = res.mappings_skipped ? `, ${res.mappings_skipped} ohne Katalogtreffer` : ''
|
||||
const lists = (res.inserted || 0) + (res.updated || 0)
|
||||
setNotice(`${res.mappings || 0} Zuordnungen und ${lists} Listen übernommen${skip}.`)
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const importLists = async (file) => {
|
||||
if (!file) return
|
||||
setImporting(true)
|
||||
@@ -167,6 +212,7 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
<p style={{ fontSize: 13, color: 'var(--text2)', lineHeight: 1.6, marginBottom: 12 }}>
|
||||
Tippe auf „Im Katalog suchen“ — du suchst nach dem Namen, nicht nach einem Code.
|
||||
Eigene FDDB-Listen zuerst importieren, dann wird die Tagebuchzeile in Zutaten aufgelöst.
|
||||
Für den Umzug nach Prod: Zuordnungen und Listen als JSON exportieren und dort wieder importieren.
|
||||
</p>
|
||||
{error && <div style={{ color: 'var(--danger)', fontSize: 13, marginBottom: 10 }}>{error}</div>}
|
||||
{notice && <div style={{ fontSize: 13, color: 'var(--accent-dark)', marginBottom: 10 }}>{notice}</div>}
|
||||
@@ -193,6 +239,25 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
{recipes.length > 0 && (
|
||||
<p style={{ fontSize: 12, color: 'var(--text3)', marginTop: 8 }}>{recipes.length} eigene Listen geladen</p>
|
||||
)}
|
||||
<input
|
||||
ref={bundleRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0]
|
||||
e.target.value = ''
|
||||
if (f) importBundle(f)
|
||||
}}
|
||||
/>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={busy} onClick={exportBundle}>
|
||||
Zuordnungen & Listen exportieren
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" disabled={busy} onClick={() => bundleRef.current?.click()}>
|
||||
Zuordnungen & Listen importieren
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<h3 style={{ fontSize: 14, margin: '16px 0 8px' }}>Offen ({unmapped.length})</h3>
|
||||
{unmapped.length === 0 && <p className="muted">Keine offenen Bezeichner.</p>}
|
||||
@@ -200,9 +265,10 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
const key = `${u.kind || 'diary'}-${u.source_name_normalized}`
|
||||
return (
|
||||
<div key={key} style={{ borderTop: '1px solid var(--border)', padding: '10px 0' }}>
|
||||
<div style={{ fontWeight: 600 }}>{u.source_name_raw}</div>
|
||||
<div style={{ fontWeight: 600 }}>{suggestQuery(u.source_name_raw) || u.source_name_raw}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
|
||||
{u.kind === 'recipe_ingredient' ? 'Rezeptzutat' : `${u.count}×`}
|
||||
{u.variant_count > 1 ? ` · ${u.variant_count} Mengen-Varianten` : ''}
|
||||
{u.first_date ? ` · ${u.first_date} – ${u.last_date}` : ''}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
|
||||
@@ -247,6 +313,7 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
|
||||
→ {m.food_name_de}{m.bls_code ? ` · ${m.bls_code}` : ''}
|
||||
{m.catalog_kind !== 'official_bls' ? ' (manuell)' : ''}
|
||||
{m.grams_per_unit ? ` · 1 ${m.source_unit || 'Einheit'} = ${m.grams_per_unit} g` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => remove(m.id)}>Löschen</button>
|
||||
@@ -257,8 +324,9 @@ export default function NutritionFoodMap({ onChanged }) {
|
||||
<FoodSearchModal
|
||||
title={`Suchen: ${searchFor.source_name_raw}`}
|
||||
initialQuery={suggestQuery(searchFor.source_name_raw)}
|
||||
quantityHint={searchFor.sample_quantity_raw || searchFor.source_name_raw}
|
||||
onClose={() => setSearchFor(null)}
|
||||
onSelect={(food) => assign(searchFor.source_name_raw, food.id)}
|
||||
onSelect={(food, extras) => assign(searchFor.source_name_raw, food.id, extras)}
|
||||
/>
|
||||
)}
|
||||
{recipeFor && (
|
||||
|
||||
@@ -248,6 +248,27 @@ export const api = {
|
||||
return readJsonResponse(r)
|
||||
},
|
||||
applyNutritionRecipe: (recipeId, sourceName) => req(`/nutrition/recipes/${recipeId}/apply`, json({ source_name: sourceName })),
|
||||
exportFoodKnowledge: async () => {
|
||||
const r = await fetch(`${BASE}/nutrition/food-knowledge`, { headers: hdrs() })
|
||||
if (!r.ok) {
|
||||
const text = await r.text()
|
||||
throw new Error(text.trim() || `HTTP ${r.status}`)
|
||||
}
|
||||
const blob = await r.blob()
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `mitai-food-knowledge-${new Date().toISOString().split('T')[0]}.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
window.URL.revokeObjectURL(url)
|
||||
},
|
||||
importFoodKnowledge: async (file) => {
|
||||
const fd = new FormData(); fd.append('file', file)
|
||||
const r = await fetch(`${BASE}/nutrition/food-knowledge`, { method: 'POST', body: fd, headers: hdrs() })
|
||||
return readJsonResponse(r)
|
||||
},
|
||||
listNutritionMarks: () => req('/nutrition/marks'),
|
||||
putNutritionDayMark: (date, d) => req(`/nutrition/days/${date}/mark`, jput(d)),
|
||||
deleteNutritionDayMark: (date) => req(`/nutrition/days/${date}/mark`, {method:'DELETE'}),
|
||||
|
||||
Reference in new issue
Block a user