Commit Graph

55 Commits

Author SHA1 Message Date
dadaloop82 9b51bb606d Fix smart shopping false positives (prodotti appena comprati/sufficienti)
PHP smartShopping():
- Absolute minimum fallback: requires isRegular + buyCount>=2 + pctLeft<80
  (before: ANY product with buyCount>=1 → triggered for newly bought items)
- Add justRestocked guard: skip item if bought within 3 days AND pctLeft>=50%
  and not expiring (prevents items bought yesterday showing as urgent)
- Add daysSinceLastBuy calculation

JS isLowStock():
- pz threshold: <=1 (was <=2) — 2 pezzi rimasti non è già urgente
2026-04-07 15:02:15 +00:00
dadaloop82 b7ed9899fa feat+fix: Bring removal, multi-expiry batches, FIFO in cooking steps
BRING! REMOVAL FIX (latte/aglio not removed after shopping):
- PHP addToInventory: replace exact strcasecmp with token-based fuzzy
  matching (same logic as _productOnBring) so custom Bring item names
  and translated catalog keys both match correctly
- JS submitAdd: add client-side fallback — if PHP removal missed the item,
  use _findSimilarItem against the loaded shoppingItems and call bring_remove

MULTI-EXPIRY BATCHES (when buying conf with different expiry dates):
- Add form (unit=conf): shows '+ Lotto con scadenza diversa' button
- Each extra batch has its own qty + expiry date input with +/- controls
- On submitAdd, extra batches are submitted as additional inventory_add calls
  (separate DB rows, separate expiry dates)
- Multi-batch section hidden in 'Ce l'avevo già' mode and for non-conf units
- Re-shown/hidden when switching unit via onAddUnitChange

RECIPE COOKING STEPS - FIFO ingredient display:
- renderCookingStep: each ingredient row now shows brand chip, location chip,
  and expiry date chip (color-coded: red ≤3d, yellow ≤7d)
- PHP already selected earliest-expiry inventory entry (ORDER BY days_left ASC
  with > not >= ensures first/earliest match wins)
- CSS: .cooking-ing-meta, .cooking-ing-chip, .exp-soon, .exp-close,
  .multi-batch-row, .multi-batch-qty, .multi-batch-date, .btn-icon-sm
2026-04-07 12:10:14 +00:00
dadaloop82 5be62cfbfd fix: low stock detection for rarely-used items
- PHP smart_shopping: add absolute stock fallback that flags conf/pz items
  with <=2 units (medium) or <=1 unit (high) and g/ml at <=20% of default,
  regardless of usage frequency. Fixes products like Panna da cucina that
  are rarely used but running low and were invisible to the frequency-based
  urgency logic (pctLeft was 66% since last purchase was 3 at once).
- JS isLowStock(): return true (not false) when totalRemaining <= 0.
  A fully depleted item is definitely low-stock; the Bring! add prompt
  should fire when you use the very last unit.
2026-04-06 10:53:15 +00:00
dadaloop82 50da545c72 feat: predict expiry date from product history when adding items
- PHP: new 'expiry_history' action computes avg shelf life (expiry_date - added_at)
  from inventory table for the same product_id (last 730 days, valid entries only)
- JS: _fetchExpiryHistoryAndUpdate() fires async after showAddForm() renders
  and replaces the rule-based estimate with the historical average if available
- Labeled with '📊 storico' badge on the estimate line (tooltip shows sample count)
- recalculateAddExpiry() and selectPurchaseType('new') both honour window._historyExpiryDays
- Vacuum-sealed multiplier still applied on top of historical base
- Falls back silently to rule-based estimateExpiryDays when no history exists
2026-04-06 09:09:04 +00:00
dadaloop82 da5552e992 fix: hide meal-plan banner on chip uncheck; fix recipe variety (variation counter, temp scaling, client-side title tracking) 2026-04-04 15:29:07 +00:00
dadaloop82 bd6f92f2f3 fix: route TTS through PHP proxy to bypass mixed-content/CORS 2026-04-04 14:44:11 +00:00
dadaloop82 63db7cc114 feat: bring urgency sync, background auto-sync, recipe mealplan chip, screensaver fix 2026-04-04 14:32:25 +00:00
dadaloop82 e18fb5839a Smart shopping: cron ogni 5min pre-calcola cache server-side, API serve da cache (risposta istantanea) 2026-04-01 05:52:17 +00:00
dadaloop82 fb7bb4d675 Modalità cucina: timer multipli persistenti con etichetta, riprendi dal passo salvato, progress dots, pulsante Ricomincia; priorità ricette basata su scadenze con ingredienti obbligatori 2026-03-31 15:55:35 +00:00
dadaloop82 bcddba46d4 Remove kg/l units everywhere — only g (grammi) and ml (millilitri)
- HTML: removed kg/l options from all unit selector dropdowns
- JS detectUnitAndQuantity(): auto-converts kg→g (*1000) and l→ml (*1000)
- JS unit labels: removed all kg/l entries from unitLabels maps
- JS category defaults: frutta 1000g, verdura 500g, bevande 1000ml
- JS step/min logic: simplified for g/ml only (no more 0.01 steps)
- JS getSubUnitStep(): removed kg/l cases
- JS isLowStock(): removed kg/l threshold
- JS spec parser: labels now show g/ml instead of kg/L
- PHP recipe parser: converts kg→g and l→ml immediately on parse
- PHP AI prompt: updated to specify only g/ml/pz/conf units
- PHP migration endpoint available at ?action=migrate_units (no-op if DB already clean)
2026-03-30 14:13:11 +00:00
dadaloop82 b954be4cac Fix smart shopping: skip one-time purchases, better frequency for short history
- Products bought only once (buy_count=1) and out of stock are skipped entirely
  (not enough history to predict repurchase need, e.g. piadelle)
- usesPerMonth for items tracked 7-30 days now normalized instead of using raw count
- usesPerMonth for items tracked <7 days halved to avoid inflation
- Critical urgency now requires buy_count >= 2
2026-03-29 19:58:43 +00:00
dadaloop82 df32fa3441 fix: spesa intelligente - filtro frequenza e recency per urgenze
L'algoritmo ora calcola:
- usesPerMonth: utilizzi al mese (non piu solo useCount totale)
- daysSinceLastUse: giorni dall'ultimo utilizzo
- isFrequent: >= 1.5 utilizzi/mese
- isRegular: >= 0.5 utilizzi/mese (almeno 1 ogni 2 mesi)
- isRecent: usato/comprato negli ultimi 60 giorni

Nuova logica urgenze:
- CRITICAL (esaurito): solo se frequente E recente
- HIGH (esaurito): regolare E recente E storico consistente
- Quasi finito/scorta bassa: solo per prodotti regolari/recenti
- Previsione esaurimento: solo per frequenti E recenti
- Prodotti usati raramente o non di recente vengono esclusi
2026-03-29 19:50:04 +00:00
dadaloop82 a38a5d670f feat: lista spesa con tab Da comprare/In previsione, tag, frequenza, tap-to-scan
- Counter nei tab aggiornati dinamicamente
- Auto-aggiunta prodotti CRITICI a Bring! al caricamento (1x per sessione)
- Badge urgenza e frequenza sugli item in lista (cross-ref smart shopping)
- Tag locali per item (Urgente/Priorità/Verificare) con menu dropdown
- Ordinamento automatico per frequenza utilizzo (item più usati in cima)
- Tap su un item → scanner barcode, con banner 'Trovato! Rimuovi dalla lista'
- Fix pctLeft: usa max(1, qty) come fallback refQty per evitare falsi alert
- Fix daysLeft capped a 365gg per pulire stringhe di previsione
- Back button on action page → torna a shopping se aperto da lista
2026-03-29 14:12:37 +00:00
dadaloop82 11a703d274 20260319a: Auto-refresh recipe archive after save, Bring spec uses product name not brand 2026-03-19 13:18:35 +00:00
dadaloop82 7cc557d4df 20260317c: Torta->Dolce, Bring specification with brand for product variants 2026-03-17 13:55:30 +00:00
dadaloop82 d1df6a6862 20260317b: Replace Comfort Food with Priorita cose aperte in recipe options 2026-03-17 12:06:14 +00:00
dadaloop82 b4b68d6579 20260316i: Low-stock Bring prompt after use
- API returns total_remaining, product_name, unit, default_qty after use
- isLowStock() detects when inventory is running low (pz<=2, conf<=1, weight/vol<=25% of default)
- After using a product, if low stock detected, shows prompt asking to add to Bring shopping list
- Works in main USE form, USE ALL, and recipe ingredient USE
- Prompt chains properly: low-stock then move-after-use (if applicable)
- Skips prompt when product is fully depleted (already auto-added to Bring)
2026-03-16 14:59:55 +00:00
dadaloop82 134e5dfa4e 20260316g: Fix conf anomaly detection + auto-split opened packages
- Fixed isSuspiciousDefaultQty: for conf products, checks package_unit thresholds
  (375g is fine for g-max=10000, not checked against conf-max=50)
- Auto-split on use: when using from a conf product with whole+fractional qty,
  automatically separates whole confs from opened part
  e.g. Panna 2.6conf → use 5g → 2conf (sealed) + 0.56conf (opened)
- Move modal now moves only the opened row (via opened_id)
- Use query prefers fractional rows (opened packages) first
- Non-conf products still get standard move-after-use behavior
2026-03-16 08:07:17 +00:00
dadaloop82 c6a3ae6e63 20260316c: Dashboard quick recipe button + waste chart
- Added 'Ricetta veloce' button between stat cards and expired section
  (navigates to chat and auto-asks Gemini for a recipe with expiring products)
- Added waste vs consumption mini chart between expiring and opened sections
  (horizontal bar showing used/wasted ratio from last 30 days)
- API: getStats() now returns used_30d and wasted_30d counts
- Cache busters updated to 20260316c
2026-03-16 07:49:10 +00:00
dadaloop82 eb5ee60dd7 Sposta prodotto dopo l'uso + fix prodotti aperti
- Dopo aver usato un prodotto, se rimane quantità mostra modal con opzione
  di spostarlo in un'altra posizione (es. dispensa→frigo dopo apertura)
- La scadenza viene ricalcolata per la nuova posizione
- Fix marmellata: default_quantity era 0 → non appariva tra prodotti aperti
- Auto-set default_quantity al primo add per prodotti g/ml/kg/l senza pkg size
- Versione: 20260316b
2026-03-16 06:48:48 +00:00
dadaloop82 dc9785c160 Estendi 'Prodotti Aperti' a tutti i tipi (g, ml, l, pz, non solo conf)
- Query SQL ora rileva prodotti aperti per tutte le unità dove la quantità
  non è multiplo della dimensione confezione (soglia 2% per evitare errori arrot.)
- Frontend: rendering differente per conf (X conf + rimanente) e altri (Xg / Yg)
- Versione: 20260315i
2026-03-15 19:05:03 +00:00
dadaloop82 4239e0b204 🫙 Sotto vuoto: flag per estendere scadenza prodotti conservati sotto vuoto 2026-03-15 18:09:38 +00:00
dadaloop82 067a4acb5c Add: mostra totale aggiornato nel toast + auto-rimuovi da Bring dopo acquisto 2026-03-15 17:47:29 +00:00
dadaloop82 17fdc993a5 Bring: non inviare marca/quantità, usa solo nomi generici catalogo. Puliti 27 articoli. 2026-03-15 17:19:36 +00:00
dadaloop82 bd1e5d950f Prodotti aperti: mostra solo conf con capacità nota (latte, panna ecc.) 2026-03-13 15:15:46 +00:00
dadaloop82 f64423296b Prodotti aperti: includi anche non-conf con quantità parziale (19 prodotti) 2026-03-13 15:10:17 +00:00
dadaloop82 948e851b71 Dashboard: sezione Prodotti Aperti (conf parzialmente usate) 2026-03-13 15:02:27 +00:00
dadaloop82 bf7941b0fd Fix: allow 'waste' transaction type for thrown-out items (CHECK constraint) 2026-03-12 18:39:09 +00:00
dadaloop82 53fb85b42b Weekly recipe variety + soften fridge priority (suggestion, not mandatory) 2026-03-12 18:20:47 +00:00
dadaloop82 f2b090f107 Move recipes, chat, settings to shared DB — sync across devices, 1 recipe per meal per day 2026-03-12 18:06:50 +00:00
dadaloop82 a7dabbce87 Fix: prevent save_settings from overwriting .env with empty values 2026-03-12 17:57:59 +00:00
dadaloop82 c5f22fdf42 feat: BarcodeDetector nativo + camera selector + recipe dedup + remote debug logging
- Scanner: usa BarcodeDetector API nativa (Chrome Android) come primario, Quagga come fallback
- Settings: aggiunta tab Fotocamera per scegliere posteriore/anteriore/specifica
- Scanner feedback: barra verde (scansione attiva), gialla (barcode rilevato)
- Ricette: invio titoli ricette del giorno per evitare duplicati nello stesso giorno
- Debug: sistema di logging remoto (client_debug.log) per diagnostica da dispositivi chioscati
- Fix: permessi .env per scrittura da Apache
2026-03-12 17:32:54 +00:00
dadaloop82 3a7fce49a0 Shopping list improvements: dedup Bring items, sync removals, server-side DupliClick token check, redesigned price layout, recipe archive with CSS, fridge/opened priority in recipes, better search with spec in query 2026-03-12 12:06:02 +00:00
dadaloop82 bf2e137502 feat: confezioni (conf) chiede dimensione singola confezione
- Nuovo campo package_unit in DB (migrazione automatica)
- Form aggiungi/modifica: quando si seleziona 'conf', appare campo per
  specificare il contenuto della singola confezione (es. 300g, 2L)
- Visualizzazione: '3 conf (da 300g)' in inventario, dettaglio, butta
- formatQuantity aggiornato con supporto package_unit
- API: salva/restituisce package_unit in tutti gli endpoint
- Ricette e chat: contesto arricchito con info confezione
- CSS: stili per il nuovo campo conf-size
2026-03-11 15:43:44 +00:00
dadaloop82 af3b5941a0 Add Gemini Chat: conversational AI assistant for kitchen help
- Gemini star icon button next to camera in header
- Full chat page with message bubbles, typing indicator
- Conversation history persisted in localStorage (last 50 messages)
- System context includes: full inventory with expiry dates, appliances, dietary restrictions
- Multi-turn conversation with Gemini 2.0 Flash
- Pre-built suggestion chips: snack, juice/smoothie, light meal, use expiring items
- Clear chat button for fresh conversations
- Indigo/purple themed UI matching Gemini branding
- PHP gemini_chat API endpoint with inventory context injection
2026-03-11 15:26:19 +00:00
dadaloop82 df56d8dc76 Fix conversione unità ricette + indicatore confezione
- Fix qty_number nelle ricette: validazione e conversione automatica
  delle unità di misura (g↔kg, ml↔L, g→pz con default_quantity)
- Sanity check: cap qty_number al disponibile, correzione valori
  assurdamente piccoli dovuti a errori di Gemini
- Aggiunto indicatore confezione (¼, ½, ¾, pieno) vicino alla
  quantità nell'inventario e nella barra stato dopo scansione
- Aggiunto default_quantity nella query inventory_list
- Nuova funzione formatPackageFraction() per calcolo frazioni
2026-03-11 13:36:21 +00:00
dadaloop82 469aadb8fc Aggiunta pagina impostazioni, preview prodotto migliorata, gestione inventario smart e ricette avanzate
- Icona ingranaggio nella navbar, salvataggio su localStorage e .env
- Preview prodotto più grande dopo scansione barcode
- Controllo inventario dopo scan: mostra quantità disponibile in grande
- 3 pulsanti contestuali (AGGIUNGI/USA/BUTTA) se prodotto già presente
- Funzionalità BUTTA con modale per quantità parziale o totale
- Quantità prominenti nella lista inventario
- Quantità visibili negli alert scadenza/scaduti in dashboard
- Unità di misura modificabile nella modale di modifica inventario
- Opzioni ricetta: Pasto Veloce, Poca Fame, Priorità Scadenze, ecc.
- Gestione smart quantità ricette (evita rimasugli inutilizzabili)
- Elettrodomestici configurabili per suggerimenti ricette
- Restrizioni alimentari nel prompt ricette
- Endpoint API: save_settings, get_settings
2026-03-11 13:08:02 +00:00
dadaloop82 78e0fddf04 fix: 4 miglioramenti - scan→usa, icona camera, log colori, log Bring!
1. Bug scan→usa: ora auto-seleziona la posizione corretta (frigo/dispensa/freezer)
   dove il prodotto è effettivamente presente, non più sempre 'dispensa'
2. Icona telecamera header: più grande (1.8rem/52px) e più centrata nel cerchio
3. Log: icone/colori differenziati -  verde aggiunte,  rosso uscite,
   🛒 blu Bring! - sfondo tintato per ogni tipo
4. Operazioni Bring! loggate come transazioni tipo 'bring' nel diario
2026-03-10 18:25:32 +00:00
dadaloop82 2abcec6fe5 feat: pagina Log con diario operazioni
- Nuova sezione 'Log' nella bottom nav con icona 📒
- Mostra tutte le transazioni (entrate/uscite) raggruppate per data
- Ogni voce: icona 📥/📤, nome prodotto, marca, quantità, posizione, orario
- Bordo verde per aggiunte, rosso per uscite
- Paginazione con 'Carica altri...' (50 per pagina)
- Backend: aggiunto supporto offset a listTransactions
2026-03-10 18:20:31 +00:00
dadaloop82 77ed2d6964 feat: auto-aggiunta a Bring! quando un prodotto finisce
- useFromInventory controlla se il prodotto è esaurito ovunque (qty=0 in tutte le location)
- Se finito, lo aggiunge automaticamente alla lista Bring! con nome e marca
- Toast notifica '🛒 Prodotto finito → aggiunto a Bring!' in tutte le UI (ricetta, uso diretto, usa tutto)
- Prosciutto crudo light e Philadelphia Light aggiunti manualmente a Bring!
2026-03-10 18:18:40 +00:00
dadaloop82 8650b377a4 feat: mostra marca, scadenza e posizione negli ingredienti ricetta
- Backend: aggiunge brand e expiry_date all'arricchimento ingredienti
- Frontend: sotto ogni ingrediente dalla dispensa mostra:
  - Marca in corsivo (se presente)
  - Icona posizione (🧊 Frigo/Freezer, 🗄️ Dispensa)
  - Scadenza con colore urgenza ( scaduto, 🔴 <3gg, 🟡 <7gg, 📅 data)
- Nuovo stile CSS per riga dettaglio ingrediente
2026-03-10 17:39:49 +00:00
dadaloop82 bae9af0fe5 feat: ricetta persistente + quantità corretta per scalare ingredienti
- Ricetta cachata in localStorage: riaprendo mostra la stessa ricetta
- Si rigenera solo se cambia tipo pasto (colazione/pranzo/cena) o bottone 'Generane un'altra'
- Prompt Gemini aggiornato: richiede qty_number nella stessa unità di misura dell'inventario
- Bottone 'Usa' ora scala la quantità effettiva della ricetta (non più sempre 1)
- Estratta renderRecipe() per riutilizzo con cache
- Aggiunto bottone '🔄 Generane un'altra' nel risultato ricetta
2026-03-10 17:36:34 +00:00
dadaloop82 fa4dc6ae88 feat: bottone 'Usa' per ogni ingrediente ricetta - scala dalla dispensa
- Backend: arricchisce risposta ricetta con product_id, location per ingredienti from_pantry
- Matching fuzzy nome ingrediente AI → prodotto inventario (exact/contains/word overlap)
- Frontend: bottone '📦 Usa' per ogni ingrediente catalogato in dispensa
- Click → chiama inventory_use API → scala 1 unità → feedback visivo (barrato + verde)
- Ingredienti non in dispensa (🛒) mostrati senza bottone
2026-03-10 17:29:49 +00:00
dadaloop82 5258c11f51 Bring! suggerimenti: priorità con emoji + quantità precise
- Specification inviata a Bring! include emoji priorità (🔴/🟡/🟢) + dettagli
- AI prompt aggiornato: specification deve sempre indicare quantità consigliata
- In Bring! si vede es: '🔴 500g, bio' per urgenza alta
2026-03-10 16:47:59 +00:00
dadaloop82 6e673963c9 Bring! catalogo IT↔DE: nomi riconosciuti con icone e categorie 2026-03-10 13:46:40 +00:00
dadaloop82 7a99c7e9c3 Prompt AI migliorato: salute, stagionalità, scadenze, inventario dettagliato 2026-03-10 13:39:09 +00:00
dadaloop82 9b1a933f10 Fix: suggerimenti AI ora escludono prodotti già nella lista Bring! 2026-03-10 13:37:22 +00:00
dadaloop82 514d5f3143 Lista della Spesa con integrazione Bring! e suggerimenti AI 2026-03-10 13:32:57 +00:00
dadaloop82 c6c000bbc2 Make expired/expiring items clickable for edit/delete
- Tap on any expired or expiring item opens the detail modal
- From the modal: edit quantity/location/expiry, delete, or use
- Same behavior as regular inventory items
- Added showAlertItemDetail() function (loads inventory then shows modal)
- Visual feedback on tap (scale + highlight)
2026-03-10 12:27:53 +00:00
dadaloop82 cc9fd2cbed Add safety badges for expired products
- 🗑️ Buttare (red): perishable items (latticini, carne, pesce, frutta,
  verdura) expired >2 days, or any items expired >6 months
- 👀 Controlla (yellow): semi-perishable (pane, surgelati) within 30 days,
  or long-shelf items 1-6 months past, or fresh items just expired in frigo
-  OK (green): long-shelf items (pasta, conserve, condimenti, cereali,
  snack) within 30 days of TMC date
- Tooltip on hover explains the safety recommendation
- Added p.category to expired items SQL query
- Safety logic uses mapToLocalCategory + location + days expired
2026-03-10 12:25:23 +00:00