-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
2207 lines (1943 loc) · 96.6 KB
/
server.ts
File metadata and controls
2207 lines (1943 loc) · 96.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dotenv/config';
import express from 'express';
import http from 'http';
import https from 'https';
import { createServer as createViteServer } from 'vite';
import { db } from './server/db/database';
import { runMigrations } from './server/db/migrations';
import { mapCategory } from './server/utils/categories';
import { normalizeUnit, convertToSmallestUnit } from './server/utils/units';
import { getAIResponse, checkRateLimit } from './server/services/ai.service';
import { syncToBring } from './server/services/bring.service';
import { SCAN_PROMPT, SCAN_SCHEMA, MHD_PROMPT, MHD_SCHEMA } from './server/services/prompts';
import { Type } from '@google/genai';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import Parser from 'rss-parser';
const app = express();
const PORT = 3000;
// No CORS middleware: FoodAI is designed for self-hosted, trusted local networks only.
// If you need cross-origin access, add a reverse proxy with appropriate CORS headers.
app.use(express.json({ limit: '10mb' }));
// Larger body limit for image upload endpoints (base64 photos)
const largeBody = express.json({ limit: '50mb' });
// --- HTML escaping for XSS prevention ---
const escapeHtml = (s: string) => String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
// --- LIKE metacharacter escaping for SQL injection prevention ---
const escapeLike = (s: string) => s.replace(/%/g, '\\%').replace(/_/g, '\\_');
// --- SSRF prevention: validate URLs before fetching ---
function isAllowedUrl(url: string): boolean {
try {
const u = new URL(url);
if (!['http:', 'https:'].includes(u.protocol)) return false;
// Block cloud metadata endpoints
if (u.hostname === '169.254.169.254') return false;
return true;
} catch { return false; }
}
// --- Settings key allowlist ---
const ALLOWED_SETTINGS = ['ai_provider', 'ai_model', 'ai_api_key', 'ollama_url', 'bring_email', 'bring_password', 'advisor_model', 'language', 'image_provider', 'image_model', 'image_api_key'];
// --- Ingredient Matching (alias map + fuzzy matching) ---
const normalizeIngredient = (s: string) => s.toLowerCase().replace(/\(.*?\)/g, '').replace(/[,\.]/g, '').replace(/\s+/g, ' ').trim();
const germanStem = (s: string): string => {
if (s.length <= 3) return s;
for (const suffix of ['flöckchen', 'flocken', 'chen', 'lein', 'eln', 'ern', 'en', 'er', 'es', 'em', 'el', 'n', 'e', 's']) {
if (s.length - suffix.length >= 3 && s.endsWith(suffix)) {
return s.slice(0, -suffix.length);
}
}
return s;
};
// Resolve directory for ESM compatibility
const serverDir = process.cwd();
// Load alias file once at startup
let ingredientAliasMap: Record<string, string[]> = {};
for (const tryPath of [
path.join(serverDir, 'ingredient-aliases.json'),
path.join(serverDir, 'src', 'data', 'ingredient-aliases.json'),
path.join(process.cwd(), 'ingredient-aliases.json'),
'/app/ingredient-aliases.json'
]) {
try {
ingredientAliasMap = JSON.parse(fs.readFileSync(tryPath, 'utf-8'));
console.log(`Loaded ${Object.keys(ingredientAliasMap).length} ingredient aliases from ${tryPath}`);
break;
} catch {}
}
if (Object.keys(ingredientAliasMap).length === 0) {
console.warn('WARNING: ingredient-aliases.json not found — ingredient matching will be degraded');
}
const ingredientAliasLookup: Record<string, string> = {};
const ingredientAliasGroups: Record<string, string[]> = {};
for (const [canonical, aliases] of Object.entries(ingredientAliasMap)) {
const canonLower = canonical.toLowerCase();
ingredientAliasGroups[canonLower] = aliases;
for (const alias of aliases) {
ingredientAliasLookup[alias] = canonLower;
}
ingredientAliasLookup[canonLower] = canonLower;
}
function getCanonicalNames(name: string): Set<string> {
const n = normalizeIngredient(name);
const results = new Set<string>();
results.add(n);
if (ingredientAliasLookup[n]) results.add(ingredientAliasLookup[n]);
const words = n.split(' ');
if (words.length > 1 && ingredientAliasLookup[words[0]]) results.add(ingredientAliasLookup[words[0]]);
const stemmed = germanStem(n);
if (stemmed !== n && ingredientAliasLookup[stemmed]) results.add(ingredientAliasLookup[stemmed]);
const stemmedFirst = germanStem(words[0]);
if (stemmedFirst !== words[0] && ingredientAliasLookup[stemmedFirst]) results.add(ingredientAliasLookup[stemmedFirst]);
for (const [alias, canonical] of Object.entries(ingredientAliasLookup)) {
if (alias.length >= 4 && n.includes(alias)) results.add(canonical);
}
return results;
}
function isIngredientInInventory(ingredientName: string, inventoryItems: { name: string; generic_name?: string | null }[]): boolean {
const ingCanonicals = getCanonicalNames(ingredientName);
const ingNorm = normalizeIngredient(ingredientName);
return inventoryItems.some(item => {
const itemCanonicals = getCanonicalNames(item.name);
const genericCanonicals = item.generic_name ? getCanonicalNames(item.generic_name) : new Set<string>();
const allItemCanonicals = new Set([...itemCanonicals, ...genericCanonicals]);
for (const ic of ingCanonicals) { if (allItemCanonicals.has(ic)) return true; }
const itemNorm = normalizeIngredient(item.name);
const genericNorm = item.generic_name ? normalizeIngredient(item.generic_name) : '';
if (ingNorm.length >= 4 && (itemNorm.includes(ingNorm) || genericNorm.includes(ingNorm))) return true;
if (itemNorm.length >= 4 && ingNorm.includes(itemNorm)) return true;
if (genericNorm.length >= 4 && ingNorm.includes(genericNorm)) return true;
const ingStem = germanStem(ingNorm.split(' ')[0]);
const itemStem = germanStem(itemNorm.split(' ')[0]);
if (ingStem.length >= 3 && itemStem.length >= 3 && ingStem === itemStem) return true;
for (const itemCanon of allItemCanonicals) {
const group = ingredientAliasGroups[itemCanon];
if (group) {
for (const ic of ingCanonicals) {
if (ic.length >= 4) {
for (const alias of group) { if (alias.includes(ic)) return true; }
}
}
}
}
return false;
});
}
function matchRecipeIngredients(ingredients: { name: string; in_inventory?: boolean }[], inventoryItems: { name: string; generic_name?: string | null }[]): void {
for (const ing of ingredients) { ing.in_inventory = isIngredientInInventory(ing.name, inventoryItems); }
}
runMigrations(db);
// --- API Routes ---
app.get('/api/settings/models', async (req, res) => {
try {
const provider = (db.prepare('SELECT value FROM settings WHERE key = ?').get('ai_provider') as any)?.value || 'gemini';
const apiKey = (db.prepare('SELECT value FROM settings WHERE key = ?').get('ai_api_key') as any)?.value || process.env.GEMINI_API_KEY || '';
const ollamaUrl = (db.prepare('SELECT value FROM settings WHERE key = ?').get('ollama_url') as any)?.value || 'http://localhost:11434';
const models: Record<string, string[]> = {
gemini: [], openai: [], anthropic: [], moonshot: [], deepseek: [], ollama: []
};
// Fetch live model lists from providers with API key
if (apiKey) {
try {
if (provider === 'gemini') {
const r = await fetch('https://generativelanguage.googleapis.com/v1beta/models', {
headers: { 'x-goog-api-key': apiKey }
});
if (r.ok) {
const data = await r.json();
models.gemini = (data.models || [])
.map((m: any) => m.name?.replace('models/', '') || '')
.filter((id: string) => id && !id.includes('embedding') && !id.includes('aqa'))
.sort();
}
} else if (provider === 'openai') {
const r = await fetch('https://api.openai.com/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` } });
if (r.ok) {
const data = await r.json();
models.openai = (data.data || [])
.map((m: any) => m.id)
.filter((id: string) => id.includes('gpt') || id.includes('o1') || id.includes('o3') || id.includes('chatgpt'))
.sort();
}
} else if (provider === 'anthropic') {
const r = await fetch('https://api.anthropic.com/v1/models', {
headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' }
});
if (r.ok) {
const data = await r.json();
models.anthropic = (data.data || []).map((m: any) => m.id).sort();
}
} else if (provider === 'deepseek') {
const r = await fetch('https://api.deepseek.com/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` } });
if (r.ok) {
const data = await r.json();
models.deepseek = (data.data || []).map((m: any) => m.id).sort();
}
} else if (provider === 'moonshot') {
const r = await fetch('https://api.moonshot.cn/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` } });
if (r.ok) {
const data = await r.json();
models.moonshot = (data.data || []).map((m: any) => m.id).sort();
}
}
} catch (e) {
console.error(`Failed to fetch ${provider} models:`, e);
}
}
// Ollama: always try (no API key needed)
try {
if (!isAllowedUrl(ollamaUrl)) throw new Error('Invalid Ollama URL');
const r = await fetch(`${ollamaUrl}/api/tags`);
if (r.ok) {
const data = await r.json();
models.ollama = (data.models || []).map((m: any) => m.name).sort();
}
} catch (e) { /* Ollama not running */ }
res.json(models);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch models' });
}
});
// Image model list with recommended markers
const RECOMMENDED_IMAGE_MODELS = new Set(['gpt-image-1.5', 'imagen-4.0-generate-001', 'sd3.5-large', 'gemini-2.5-flash-image']);
app.get('/api/settings/image-models', async (req, res) => {
try {
const provider = (db.prepare('SELECT value FROM settings WHERE key = ?').get('image_provider') as any)?.value || 'openai';
const apiKey = (db.prepare('SELECT value FROM settings WHERE key = ?').get('image_api_key') as any)?.value;
let models: { id: string; recommended: boolean }[] = [];
if (apiKey) {
try {
if (provider === 'openai') {
const r = await fetch('https://api.openai.com/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` } });
if (r.ok) {
const data = await r.json();
models = (data.data || [])
.map((m: any) => m.id)
.filter((id: string) => id.includes('dall-e') || id.includes('gpt-image'))
.sort()
.map((id: string) => ({ id, recommended: RECOMMENDED_IMAGE_MODELS.has(id) }));
}
} else if (provider === 'gemini') {
const r = await fetch('https://generativelanguage.googleapis.com/v1beta/models', {
headers: { 'x-goog-api-key': apiKey }
});
if (r.ok) {
const data = await r.json();
models = (data.models || [])
.map((m: any) => m.name?.replace('models/', '') || '')
.filter((id: string) => id.includes('imagen') || id.includes('image'))
.sort()
.map((id: string) => ({ id, recommended: RECOMMENDED_IMAGE_MODELS.has(id) }));
}
} else if (provider === 'stability') {
// Stability doesn't have a v2 model list — use known models
models = [
{ id: 'sd3.5-large', recommended: true },
{ id: 'sd3.5-medium', recommended: false },
{ id: 'sd3.5-large-turbo', recommended: false },
];
}
} catch (e) {
console.error(`Failed to fetch ${provider} image models:`, e);
}
}
// Fallback to static list if API returned nothing
if (models.length === 0) {
if (provider === 'openai') models = [{ id: 'gpt-image-1.5', recommended: true }, { id: 'gpt-image-1', recommended: false }, { id: 'dall-e-3', recommended: false }];
else if (provider === 'gemini') models = [{ id: 'imagen-4.0-generate-001', recommended: true }, { id: 'gemini-2.5-flash-image', recommended: true }, { id: 'gemini-3-pro-image-preview', recommended: false }];
else if (provider === 'stability') models = [{ id: 'sd3.5-large', recommended: true }, { id: 'sd3.5-medium', recommended: false }];
}
res.json({ provider, models });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch image models' });
}
});
app.get("/api/inventory", (req, res) => {
try {
const items = db.prepare("SELECT * FROM items ORDER BY category ASC, expiry_date ASC").all();
res.json(items);
} catch (error) {
console.error("Inventory Fetch Error:", error);
res.status(500).json({ error: "Failed to fetch inventory" });
}
});
app.get("/api/dashboard", (req, res) => {
try {
const today = new Date().toISOString().split("T")[0];
const threeDaysLater = new Date();
threeDaysLater.setDate(threeDaysLater.getDate() + 3);
const threeDaysLaterStr = threeDaysLater.toISOString().split("T")[0];
const expiringSoon = db.prepare("SELECT * FROM items WHERE expiry_date <= ? AND quantity > 0 AND category != 'Gewürze' ORDER BY expiry_date ASC").all(threeDaysLaterStr);
const openedItems = db.prepare("SELECT * FROM items WHERE is_open = 1 AND quantity > 0 ORDER BY opened_at DESC").all();
const todaysRecipes = db.prepare("SELECT * FROM planned_recipes WHERE date = ?").all(today).map((r: any) => ({
...r,
ingredients: JSON.parse(r.ingredients),
instructions: JSON.parse(r.instructions),
cooked: r.cooked === 1
}));
const totalValueResult = db.prepare("SELECT SUM(price * quantity) as value FROM items WHERE price IS NOT NULL").get() as any;
const lowStockCount = db.prepare(`
SELECT COUNT(*) as count FROM (
SELECT name, unit, SUM(quantity) as total, MAX(min_stock) as min
FROM items
GROUP BY name, unit
) WHERE min > 0 AND total < min
`).get() as any;
res.json({
expiringSoon,
openedItems,
todaysRecipes,
totalValue: totalValueResult?.value || 0,
lowStockCount: lowStockCount?.count || 0
});
} catch (error) {
console.error("Dashboard Fetch Error:", error);
res.status(500).json({ error: "Failed to fetch dashboard data" });
}
});
app.post('/api/recipes/missing-ingredients', (req, res) => {
const { ingredients, portions, base_portions } = req.body;
if (!ingredients || !Array.isArray(ingredients)) return res.status(400).json({ error: 'Ingredients required' });
try {
const required: Record<string, { amount: number, unit: string, name: string }> = {};
const ratio = (portions || 2) / (base_portions || 2);
ingredients.forEach((ing: any) => {
const smallest = convertToSmallestUnit(ing.amount * ratio, ing.unit);
const key = `${ing.name.toLowerCase()}_${smallest.unit}`;
if (!required[key]) {
required[key] = { amount: 0, unit: smallest.unit, name: ing.name };
}
required[key].amount += smallest.amount;
});
const inventory = db.prepare('SELECT name, generic_name, quantity, unit, category FROM items WHERE quantity > 0').all() as any[];
const missingIngredients: any[] = [];
Object.values(required).forEach((reqIng: any) => {
// Spices with any stock: always available regardless of unit
const spiceMatch = inventory.find(inv => isIngredientInInventory(reqIng.name, [inv]));
if (spiceMatch?.category === 'Gewürze' && spiceMatch.quantity > 0) return;
// Use canonical alias matching (same as recipe ingredient checking)
const matchingItems = inventory.filter(inv => {
if (!isIngredientInInventory(reqIng.name, [inv])) return false;
const invSmallest = convertToSmallestUnit(inv.quantity, inv.unit);
return invSmallest.unit === reqIng.unit;
});
const totalInInventory = matchingItems.reduce((sum, inv) => {
const invSmallest = convertToSmallestUnit(inv.quantity, inv.unit);
return sum + invSmallest.amount;
}, 0);
if (totalInInventory < reqIng.amount) {
let diff = reqIng.amount - totalInInventory;
let displayAmount = diff;
let displayUnit = reqIng.unit;
if (displayUnit === 'g' && displayAmount >= 1000) { displayAmount /= 1000; displayUnit = 'kg'; }
else if (displayUnit === 'ml' && displayAmount >= 1000) { displayAmount /= 1000; displayUnit = 'l'; }
missingIngredients.push({
name: reqIng.name,
amountNeeded: Math.round(displayAmount * 100) / 100,
unit: displayUnit
});
}
});
res.json({ missingIngredients });
} catch (error) {
console.error('Missing ingredients error:', error);
res.status(500).json({ error: 'Failed to calculate missing ingredients' });
}
});
app.get('/api/shopping-list', (req, res) => {
try {
const today = new Date().toISOString().split('T')[0];
const upcomingRecipes = db.prepare('SELECT * FROM planned_recipes WHERE date >= ? AND cooked = 0').all(today);
const required: Record<string, { amount: number, unit: string, name: string }> = {};
upcomingRecipes.forEach((recipe: any) => {
const ingredients = JSON.parse(recipe.ingredients);
const ratio = recipe.portions / recipe.base_portions;
ingredients.forEach((ing: any) => {
const smallest = convertToSmallestUnit(ing.amount * ratio, ing.unit);
const key = `${ing.name.toLowerCase()}_${smallest.unit}`;
if (!required[key]) {
required[key] = { amount: 0, unit: smallest.unit, name: ing.name };
}
required[key].amount += smallest.amount;
});
});
const inventory = db.prepare('SELECT name, generic_name, quantity, unit, min_stock, category FROM items WHERE quantity > 0').all() as any[];
// Add items that are below minimum stock
const allKnownItems = db.prepare('SELECT name, generic_name, quantity, unit, min_stock, category FROM items').all() as any[];
const lowStockItems: Record<string, { amount: number, unit: string, name: string }> = {};
// Group by name and unit for min_stock check
const stockLevels: Record<string, { total: number, min: number, unit: string }> = {};
allKnownItems.forEach(item => {
const key = `${item.name.toLowerCase()}_${normalizeUnit(item.unit)}`;
if (!stockLevels[key]) {
stockLevels[key] = { total: 0, min: item.min_stock || 0, unit: normalizeUnit(item.unit) };
}
const smallest = convertToSmallestUnit(item.quantity, item.unit);
stockLevels[key].total += smallest.amount;
});
// Min-stock: for spices show as "1 Packung", for others show deficit amount
Object.entries(stockLevels).forEach(([key, level]) => {
if (level.min > 0 && level.total < level.min) {
const name = key.split('_')[0];
const item = allKnownItems.find(i => i.name.toLowerCase() === name);
if (item?.category === 'Gewürze') {
// Spices: add as "1 Packung"
const spiceKey = `${name}_Stück`;
if (!required[spiceKey]) {
required[spiceKey] = { amount: 0, unit: 'Stück', name: name.charAt(0).toUpperCase() + name.slice(1) };
}
required[spiceKey].amount = 1;
} else {
const missing = level.min - level.total;
if (!required[key]) {
required[key] = { amount: 0, unit: level.unit, name: name.charAt(0).toUpperCase() + name.slice(1) };
}
required[key].amount += missing;
}
}
});
const missingIngredients: any[] = [];
Object.values(required).forEach((reqIng: any) => {
// Spices: if any matching item exists with quantity > 0, it's available (regardless of unit mismatch g vs %)
const anyMatchInInventory = inventory.some(inv => isIngredientInInventory(reqIng.name, [inv]));
if (anyMatchInInventory) {
const matchedItem = inventory.find(inv => isIngredientInInventory(reqIng.name, [inv]));
if (matchedItem?.category === 'Gewürze' && matchedItem.quantity > 0) {
return; // Spice is in stock, skip
}
}
// Standard matching with unit awareness
const matchingItems = inventory.filter(inv => {
if (!isIngredientInInventory(reqIng.name, [inv])) return false;
const invSmallest = convertToSmallestUnit(inv.quantity, inv.unit);
return invSmallest.unit === reqIng.unit;
});
const totalInInventory = matchingItems.reduce((sum, inv) => {
const invSmallest = convertToSmallestUnit(inv.quantity, inv.unit);
return sum + invSmallest.amount;
}, 0);
if (totalInInventory < reqIng.amount) {
let diff = reqIng.amount - totalInInventory;
let displayAmount = diff;
let displayUnit = reqIng.unit;
// Convert back to larger units for display if appropriate
if (displayUnit === 'g' && displayAmount >= 1000) {
displayAmount /= 1000;
displayUnit = 'kg';
} else if (displayUnit === 'ml' && displayAmount >= 1000) {
displayAmount /= 1000;
displayUnit = 'l';
}
missingIngredients.push({
name: reqIng.name,
amountNeeded: Math.round(displayAmount * 100) / 100,
unit: displayUnit
});
}
});
res.json({ missingIngredients });
} catch (error) {
console.error('Shopping list error:', error);
res.status(500).json({ error: 'Failed to generate shopping list' });
}
});
app.get('/api/barcode/lookup/:barcode', async (req, res) => {
const { barcode } = req.params;
try {
// 1. Check local database first
const product = db.prepare('SELECT * FROM product_lookup WHERE barcode = ?').get(barcode) as any;
if (product) {
return res.json(product);
}
// 2. Fallback to OpenFoodFacts (Free, good for EAN/European products)
console.log(`Barcode ${barcode} not in local DB, checking OpenFoodFacts...`);
try {
const offRes = await fetch(`https://world.openfoodfacts.org/api/v0/product/${barcode}.json`);
if (offRes.ok) {
const offData = await offRes.json() as any;
if (offData.status === 1 && offData.product) {
const p = offData.product;
const rawCategory = p.categories_tags?.join(' ') || '';
const mappedCategory = mapCategory(rawCategory, p.product_name || '');
let parsedQuantity = 1;
let parsedUnit = p.serving_quantity_unit || 'Stück';
if (p.quantity) {
const qMatch = p.quantity.match(/([\d.,]+)\s*([a-zA-Z%]+)/);
if (qMatch) {
parsedQuantity = parseFloat(qMatch[1].replace(',', '.'));
parsedUnit = qMatch[2].toLowerCase();
if (!['g', 'kg', 'ml', 'l', '%'].includes(parsedUnit)) {
parsedUnit = 'Stück';
}
}
}
let genericName = p.generic_name || p.product_name || 'Unbekanntes Produkt';
// Extended brand list based on user feedback
genericName = genericName.replace(/^(Ja!|Gut & Günstig|K-Classic|Milbona|Alnatura|Barilla|Mutti|Oro di Parma|Rewe Beste Wahl|Edeka|Dr\. Oetker|Maggi|Knorr|Nestle|Kellogg's|Haribo|Lindt|Milka|Coca-Cola|Pepsi|Heinz|Kraft|Uncle Ben's|Mirácoli|Buitoni|Wagner|Iglo|Frosta|McCain|Coppenrath & Wiese|Langnese|Mövenpick|Landliebe|Weihenstephan|Müller|Danone|Zott|Ehrmann|Bauer|Andechser|Söbbeke|Rügenwalder Mühle|Herta|Meica|Wiesenhof|Gutfried|Rasting|Wilhelm Brandenburg|Kölln|Brüggen|Seitenbacher|Dr\. Karg|Wasa|Leibniz|Bahlsen|Griesson|De Beukelaer|Prinzen Rolle|Ritter Sport|Milka|Lindt|Ferrero|Kinder|Nutella|Hanuta|Duplo|Knoppers|Toffifee|Yogurette|Mon Chéri|Raffaello|Giotto|Rocher|Küchenmeister|Aurora|Diamant|Südzucker|Nordzucker|Bad Reichenhaller|Fuchs|Ostmann|Ubena|Kühne|Hengstenberg|Thomy|Homann|Nadler|Popp|Dahlhoff|Bautz'ner|Born|Werder|Hela|Kraft|Heinz|Bull's Eye|Knorr|Maggi|Erasco|Sonnen Bassermann|Buss|Stührk|Appel|Hawesta|Saupiquet|Thunfisch|Dose|Konserve)\s+/i, '').trim();
const newProduct = {
barcode,
name: p.product_name || genericName,
generic_name: genericName,
category: mappedCategory,
default_quantity: parsedQuantity,
unit: parsedUnit,
pieces_per_pack: 1
};
// If unit is 'g' but quantity is 1 and no weight info, default to Stück
if (newProduct.unit === 'g' && newProduct.default_quantity === 1 && !p.quantity?.match(/1\s*g/i)) {
newProduct.unit = 'Stück';
}
// Convert "Packung" to actual content unit
if (newProduct.unit === 'Packung' || newProduct.unit === 'packung') {
newProduct.unit = 'Stück';
}
// Try to extract pieces per pack from product name or quantity if possible
// e.g. "15 Stück"
const piecesMatch = p.quantity?.match(/(\d+)\s*(Stück|pcs|pieces)/i);
if (piecesMatch) {
newProduct.pieces_per_pack = parseInt(piecesMatch[1]);
}
db.prepare('INSERT OR IGNORE INTO product_lookup (barcode, name, generic_name, category, default_quantity, unit, pieces_per_pack) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(newProduct.barcode, newProduct.name, newProduct.generic_name, newProduct.category, newProduct.default_quantity, newProduct.unit, newProduct.pieces_per_pack);
return res.json(newProduct);
}
}
} catch (e) {
console.error('OpenFoodFacts error:', e);
}
// 3. Fallback to upcitemdb trial
console.log(`Barcode ${barcode} not in OpenFoodFacts, checking upcitemdb...`);
try {
const upcRes = await fetch(`https://api.upcitemdb.com/prod/trial/lookup?upc=${barcode}`);
if (upcRes.ok) {
const upcData = await upcRes.json();
if (upcData.items && upcData.items.length > 0) {
const item = upcData.items[0];
let genericName = item.title || 'Unbekanntes Produkt';
// Clean up brand names (same list as above)
genericName = genericName.replace(/^(Ja!|Gut & Günstig|K-Classic|Milbona|Alnatura|Barilla|Mutti|Oro di Parma|Rewe Beste Wahl|Edeka|Dr\. Oetker|Maggi|Knorr|Nestle|Kellogg's|Haribo|Lindt|Milka|Coca-Cola|Pepsi|Heinz|Kraft|Uncle Ben's|Mirácoli|Buitoni|Wagner|Iglo|Frosta|McCain|Coppenrath & Wiese|Langnese|Mövenpick|Landliebe|Weihenstephan|Müller|Danone|Zott|Ehrmann|Bauer|Andechser|Söbbeke|Rügenwalder Mühle|Herta|Meica|Wiesenhof|Gutfried|Rasting|Wilhelm Brandenburg|Kölln|Brüggen|Seitenbacher|Dr\. Karg|Wasa|Leibniz|Bahlsen|Griesson|De Beukelaer|Prinzen Rolle|Ritter Sport|Milka|Lindt|Ferrero|Kinder|Nutella|Hanuta|Duplo|Knoppers|Toffifee|Yogurette|Mon Chéri|Raffaello|Giotto|Rocher|Küchenmeister|Aurora|Diamant|Südzucker|Nordzucker|Bad Reichenhaller|Fuchs|Ostmann|Ubena|Kühne|Hengstenberg|Thomy|Homann|Nadler|Popp|Dahlhoff|Bautz'ner|Born|Werder|Hela|Kraft|Heinz|Bull's Eye|Knorr|Maggi|Erasco|Sonnen Bassermann|Buss|Stührk|Appel|Hawesta|Saupiquet|Thunfisch|Dose|Konserve)\s+/i, '').trim();
const mappedCategory = mapCategory(item.category || '', item.title || '');
// Try to parse quantity from title/description if not explicit
let parsedQuantity = 1;
let parsedUnit = 'Stück';
const qMatch = item.title.match(/(\d+)\s*(g|kg|ml|l|oz|lb)/i);
if (qMatch) {
parsedQuantity = parseFloat(qMatch[1]);
parsedUnit = qMatch[2].toLowerCase();
if (parsedUnit === 'oz') { parsedQuantity = Math.round(parsedQuantity * 28.35); parsedUnit = 'g'; }
if (parsedUnit === 'lb') { parsedQuantity = Math.round(parsedQuantity * 453.59); parsedUnit = 'g'; }
}
const newProduct = {
barcode,
name: genericName,
generic_name: genericName,
category: mappedCategory,
default_quantity: parsedQuantity,
unit: parsedUnit,
pieces_per_pack: 1
};
db.prepare('INSERT OR IGNORE INTO product_lookup (barcode, name, generic_name, category, default_quantity, unit, pieces_per_pack) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(newProduct.barcode, newProduct.name, newProduct.generic_name, newProduct.category, newProduct.default_quantity, newProduct.unit, newProduct.pieces_per_pack);
return res.json(newProduct);
}
}
} catch (e) {
console.error('UPCItemDB error:', e);
}
res.status(404).json({ error: 'Product not found' });
} catch (error) {
console.error('Barcode lookup error:', error);
res.status(500).json({ error: 'Database or API error' });
}
});
app.post('/api/recipes/weekly', async (req, res) => {
if (!checkRateLimit(req.ip || 'unknown')) return res.status(429).json({ error: 'Rate limit exceeded. Try again in a minute.' });
const { preferences, portions } = req.body;
try {
const items = db.prepare('SELECT generic_name, name, quantity, unit, expiry_date, category FROM items').all();
// Group items by generic_name and unit, but keep track of open status and expiry
const groupedInventory: Record<string, { quantity: number, unit: string, details: string[], category: string }> = {};
items.forEach((i: any) => {
const key = `${i.generic_name || i.name}_${i.unit}`;
if (!groupedInventory[key]) {
groupedInventory[key] = { quantity: 0, unit: i.unit, details: [], category: i.category };
}
groupedInventory[key].quantity += i.quantity;
let detail = `${i.quantity} ${i.unit}`;
if (i.is_open) detail += ' (geöffnet)';
if (i.expiry_date) detail += ` MHD: ${i.expiry_date}`;
groupedInventory[key].details.push(detail);
});
const inventoryList = Object.entries(groupedInventory).map(([key, data]) => {
const name = key.split('_')[0];
// Summarize details if too many
const detailsStr = data.details.length > 3 ? `${data.details.length} Packungen/Einheiten` : data.details.join(', ');
return `- ${name}: ${data.quantity} ${data.unit} gesamt [${detailsStr}]`;
}).join('\n');
const prompt = `
You are a professional meal planner. Create a 7-day meal plan (Monday to Sunday) for ${portions || 2} portions using the following ingredients from my inventory.
PRIORITIZE ingredients that are expiring soon (MHD) or are already opened (geöffnet).
Include all available sauces and spices in your reasoning, and use them where appropriate.
Inventory:
${inventoryList}
User preferences: ${preferences || 'None'}
Return a JSON object with a key "plan" which is an array of 7 objects. Each object must have:
- day: "Montag", "Dienstag", etc.
- title: Recipe title
- description: Short description
- ingredients: Array of objects { name, amount, unit, in_inventory (boolean) }
- instructions: Array of strings (steps)
`;
const schema = {
type: Type.OBJECT,
properties: {
plan: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
day: { type: Type.STRING },
title: { type: Type.STRING },
description: { type: Type.STRING },
ingredients: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
amount: { type: Type.NUMBER },
unit: { type: Type.STRING },
in_inventory: { type: Type.BOOLEAN }
},
required: ["name", "amount", "unit", "in_inventory"]
}
},
instructions: {
type: Type.ARRAY,
items: { type: Type.STRING }
}
},
required: ["day", "title", "description", "ingredients", "instructions"]
}
}
},
required: ["plan"]
};
const result = await getAIResponse(prompt, undefined, schema);
// Save to DB
db.prepare('DELETE FROM weekly_plan').run();
const insert = db.prepare('INSERT INTO weekly_plan (day_of_week, recipe_title, recipe_content) VALUES (?, ?, ?)');
for (const day of result.plan) {
insert.run(day.day, day.title, JSON.stringify(day));
}
res.json(result);
} catch (error) {
console.error('Weekly plan error:', error);
res.status(500).json({ error: 'Failed to generate weekly plan' });
}
});
app.get('/api/recipes/weekly', (req, res) => {
try {
const plan = db.prepare('SELECT * FROM weekly_plan ORDER BY id ASC').all();
const result = plan.map((row: any) => JSON.parse(row.recipe_content));
res.json({ plan: result });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch weekly plan' });
}
});
app.post('/api/inventory', (req, res) => {
const { name, generic_name, quantity, unit, expiry_date, category, barcode, pieces_per_pack, location, price, min_stock } = req.body;
const finalCategory = mapCategory(category || '', name);
try {
// Save to product_lookup for future barcode scans
if (barcode) {
db.prepare('INSERT OR IGNORE INTO product_lookup (barcode, name, generic_name, category, default_quantity, unit, pieces_per_pack, location, price, min_stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
.run(barcode, name, generic_name || name, finalCategory, quantity, unit, pieces_per_pack || 1, location, price, min_stock);
}
// Sanitize expiry_date — AI sometimes returns "null" string
const cleanExpiry = (expiry_date && expiry_date !== 'null' && expiry_date !== 'undefined') ? expiry_date : null;
// Always create a new item — each physical package is its own row
const stmt = db.prepare('INSERT INTO items (name, generic_name, quantity, unit, expiry_date, category, barcode, pieces_per_pack, package_size, is_open, location, price, min_stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)');
const info = stmt.run(name, generic_name || name, quantity, unit, cleanExpiry, finalCategory, barcode, pieces_per_pack || 1, quantity, location || 'Vorratsschrank', price || 0, min_stock || 0);
res.json({ id: info.lastInsertRowid, name, generic_name: generic_name || name, quantity, unit, expiry_date, category: finalCategory, barcode, package_size: quantity, location: location || 'Vorratsschrank', price, min_stock });
// Trigger async sync
syncToBring().catch(console.error);
} catch (error) {
console.error('Inventory add error:', error);
res.status(500).json({ error: 'Failed to add item' });
}
});
app.put('/api/inventory/:id', (req, res) => {
const { id } = req.params;
const { name, generic_name, quantity, unit, expiry_date, category, package_size, location, price, min_stock } = req.body;
try {
// If quantity exceeds package_size, update package_size too
const existing = db.prepare('SELECT package_size FROM items WHERE id = ?').get(id) as any;
let newPackageSize = package_size || existing?.package_size || quantity;
if (quantity > newPackageSize) {
newPackageSize = quantity;
}
const stmt = db.prepare('UPDATE items SET name = ?, generic_name = ?, quantity = ?, unit = ?, expiry_date = ?, category = ?, package_size = ?, location = ?, price = ?, min_stock = ? WHERE id = ?');
stmt.run(name, generic_name || name, quantity, unit, expiry_date, category, newPackageSize, location, price, min_stock, id);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to update item' });
}
});
app.delete('/api/inventory/:id', (req, res) => {
const { id } = req.params;
try {
const stmt = db.prepare('DELETE FROM items WHERE id = ?');
stmt.run(id);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to delete item' });
}
});
app.post('/api/inventory/bulk-delete', (req, res) => {
const { ids } = req.body;
if (!Array.isArray(ids) || ids.length === 0) return res.status(400).json({ error: 'No IDs provided' });
try {
const stmt = db.prepare('DELETE FROM items WHERE id = ?');
db.transaction(() => {
for (const id of ids) {
stmt.run(id);
}
})();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to bulk delete items' });
}
});
app.post('/api/inventory/bulk-update', (req, res) => {
const { ids, updates } = req.body;
if (!Array.isArray(ids) || ids.length === 0) return res.status(400).json({ error: 'No IDs provided' });
try {
const fields = Object.keys(updates).map(k => `${k} = ?`).join(', ');
const values = Object.values(updates);
const stmt = db.prepare(`UPDATE items SET ${fields} WHERE id = ?`);
db.transaction(() => {
for (const id of ids) {
stmt.run(...values, id);
}
})();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to bulk update items' });
}
});
app.post('/api/inventory/:id/open', async (req, res) => {
const { id } = req.params;
try {
const item = db.prepare('SELECT * FROM items WHERE id = ?').get(id) as any;
if (!item) return res.status(404).json({ error: 'Item not found' });
db.prepare('UPDATE items SET is_open = 1, opened_at = CURRENT_TIMESTAMP WHERE id = ?').run(id);
// Skip expiry logic for spices (they don't go bad)
if (item.category !== 'Gewürze') {
const prompt = `The user opened: "${item.name}" (Category: ${item.category}, Unit: ${item.unit}, Current MHD: ${item.expiry_date || 'none'}).
After opening, how many days until this goes bad? Guidelines:
- Fresh dairy (milk, cream, yogurt): 3-5 days
- Canned goods (tomatoes, beans, corn): 2-3 days in fridge
- Cold cuts, sausages: 3-5 days
- Sauces (ketchup, mustard, mayo): 30-90 days
- Jams, honey, vinegar: 60-180 days
- Dry goods (flour, rice, pasta): no change
Return JSON: needs_new_expiry (boolean), days_until_spoiled (number or null)`;
const schema = {
type: Type.OBJECT,
properties: {
needs_new_expiry: { type: Type.BOOLEAN },
days_until_spoiled: { type: Type.NUMBER }
},
required: ["needs_new_expiry"]
};
try {
const aiResult = await getAIResponse(prompt, undefined, schema, true);
if (aiResult.needs_new_expiry && aiResult.days_until_spoiled) {
const newExpiry = new Date();
newExpiry.setDate(newExpiry.getDate() + aiResult.days_until_spoiled);
const expiryDate = newExpiry.toISOString().split('T')[0];
// Only update if new expiry is sooner than existing
if (!item.expiry_date || expiryDate < item.expiry_date) {
db.prepare('UPDATE items SET expiry_date = ? WHERE id = ?').run(expiryDate, id);
}
}
} catch (e: any) {
console.error('AI expiry check failed (non-critical):', e.message);
}
}
const updatedItem = db.prepare('SELECT * FROM items WHERE id = ?').get(id);
res.json(updatedItem);
} catch (error) {
console.error('Open item error:', error);
res.status(500).json({ error: 'Failed to open item' });
}
});
app.post('/api/ha/inventory/update', (req, res) => {
const { id, barcode, name, action, value } = req.body;
// action: 'set' (e.g. value=75 for 75%), 'deduct' (e.g. value=15 for 15g)
try {
let item;
if (id) {
item = db.prepare('SELECT * FROM items WHERE id = ?').get(id) as any;
} else if (barcode) {
item = db.prepare('SELECT * FROM items WHERE barcode = ?').get(barcode) as any;
} else if (name) {
const allItems = db.prepare('SELECT * FROM items').all() as any[];
item = allItems.find((inv: any) => isIngredientInInventory(name, [inv]));
}
if (!item) return res.status(404).json({ error: 'Item not found' });
let newQuantity = item.quantity;
if (action === 'set') {
newQuantity = value;
} else if (action === 'deduct') {
newQuantity = Math.max(0, item.quantity - value);
}
db.prepare('UPDATE items SET quantity = ? WHERE id = ?').run(newQuantity, item.id);
res.json({ success: true, item: { ...item, quantity: newQuantity } });
} catch (error) {
console.error('HA update error:', error);
res.status(500).json({ error: 'HA update failed' });
}
});
app.post('/api/scan/mhd', largeBody, async (req, res) => {
if (!checkRateLimit(req.ip || 'unknown')) return res.status(429).json({ error: 'Rate limit exceeded. Try again in a minute.' });
const { imageBase64 } = req.body;
if (!imageBase64) return res.status(400).json({ error: 'No image provided' });
try {
const prompt = 'Extract the expiry date (MHD - Mindesthaltbarkeitsdatum) from this image. Return a JSON object with key "expiry_date" (format YYYY-MM-DD) or null if not found. Only return a date if you are very sure.';
const schema = {
type: Type.OBJECT,
properties: {
expiry_date: { type: Type.STRING, description: "YYYY-MM-DD format or null" }
},
required: ["expiry_date"]
};
const result = await getAIResponse(prompt, imageBase64, schema);
res.json(result);
} catch (error) {
console.error('MHD AI Scan error:', error);
res.status(500).json({ error: 'Failed to analyze MHD' });
}
});
app.post('/api/scan', largeBody, async (req, res) => {
if (!checkRateLimit(req.ip || 'unknown')) return res.status(429).json({ error: 'Rate limit exceeded. Try again in a minute.' });
const { imageBase64 } = req.body;
if (!imageBase64) return res.status(400).json({ error: 'No image provided' });
try {
const prompt = 'Analyze this image of a food product, barcode, or label. 1. Identify the product name. IMPORTANT: Remove brand names (e.g., "Iglo", "Barilla", "Gut & Günstig") but KEEP the variant/type (e.g., "Rahmspinat", "Lasagne", "Dunkler Saucenbinder", "Hähnchenschnitzel"). Example: "Iglo Rahmspinat Blubb" -> "Rahmspinat". "Knorr Saucenbinder Dunkel" -> "Dunkler Saucenbinder". 2. Determine a generic_name for grouping (e.g., "Rahmspinat (TK)"). IMPORTANT: For spices, seasonings, and spice mixes, the generic_name MUST be the specific spice/mix name (e.g., "Curry gemahlen", "Magic Dust", "Burger Gewürz"). NEVER use generic terms like "Gewürzmischung", "Spice Mix", or "Seasoning" as generic_name. 3. If a barcode is visible, try to decode it. 4. Estimate the CONTENT quantity and unit — always use the actual content unit, never "Packung". A 2L bottle = quantity:2000 unit:"ml". A 500g pack of pasta = quantity:500 unit:"g". A pack of 10 eggs = quantity:10 unit:"Stück". For spices/oils where exact weight is hard to track, use quantity:100 unit:"%". 5. Identify an expiry date if visible (YYYY-MM-DD). ONLY return a date if you are VERY sure. If unsure or not visible, return null. 6. Estimate the price in EUR if visible or common. 7. Suggest a storage location (e.g., Fridge, Freezer, Pantry). Return a JSON object with keys: name (string), generic_name (string), quantity (number), unit (string), category (string), expiry_date (string or null), price (number or null), location (string). The category MUST be one of: "Obst & Gemüse", "Kühlregal", "Tiefkühl", "Vorratsschrank", "Getränke", "Backwaren", "Fleisch & Fisch", "Snacks & Süßigkeiten", "Gewürze", "Saucen", "Haushalt & Drogerie", "Sonstiges". The unit MUST be one of: "Stück", "g", "kg", "ml", "l", "%".';
const schema = {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
generic_name: { type: Type.STRING },
quantity: { type: Type.NUMBER },
unit: { type: Type.STRING, enum: ["Stück", "g", "kg", "ml", "l", "%"] },
category: { type: Type.STRING, enum: ["Obst & Gemüse", "Kühlregal", "Tiefkühl", "Vorratsschrank", "Getränke", "Backwaren", "Fleisch & Fisch", "Snacks & Süßigkeiten", "Gewürze", "Saucen", "Haushalt & Drogerie", "Sonstiges"] },
expiry_date: { type: Type.STRING, description: "YYYY-MM-DD format or null" },
price: { type: Type.NUMBER },
location: { type: Type.STRING }
},
required: ["name", "generic_name", "quantity", "unit", "category"]
};
const result = await getAIResponse(prompt, imageBase64, schema);
res.json(result);
} catch (error) {
console.error('Scan error:', error);
res.status(500).json({ error: 'Failed to analyze image' });
}
});
app.post('/api/cook/analyze-photo', largeBody, async (req, res) => {
if (!checkRateLimit(req.ip || 'unknown')) return res.status(429).json({ error: 'Rate limit exceeded. Try again in a minute.' });
const { imageBase64 } = req.body;
if (!imageBase64) return res.status(400).json({ error: 'No image provided' });
try {
const items = db.prepare('SELECT id, generic_name, name, quantity, unit, category FROM items WHERE quantity > 0').all();
const inventoryList = items.map((i: any) => `ID: ${i.id} | ${i.generic_name || i.name} (${i.quantity} ${i.unit})`).join('\n');
const prompt = `
Analyze this image of food ingredients that the user is about to cook.
Match the visible ingredients with the following inventory list:
${inventoryList}
For each matched ingredient, estimate how much the user is likely to use for a typical meal (or based on what's visible).
If it's a full package of pasta, maybe they use 250g or 500g. If it's a can of tomatoes, maybe 100% (the whole can).
If it's a single piece of vegetable (like an onion), maybe 1 Stück.
Return a JSON object with a key "ingredients" containing an array of objects:
- id: The ID from the inventory list
- name: The name of the ingredient
- unit: The unit from the inventory list
- estimated_deduction: A number representing the estimated amount to deduct
- reasoning: A short explanation of why this amount (e.g., "Standard portion for 2 people" or "Whole can visible")
`;
const schema = {
type: Type.OBJECT,
properties: {
ingredients: {