Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add nicotine tracking tab to MeatSpace
Adam Eivy27f51f36fd9f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..534af1666f--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,16 @@+# Unreleased Changes++## Added+- Nicotine tracking tab in MeatSpace with consumption logging, daily totals, rolling averages, custom product quick-add buttons, inline editing, and entry history+- Nicotine chart (7d/30d/90d bar chart) and nicotine vs heart rate correlation visualization+- Nicotine data integrated into health correlation endpoint (HR, resting HR alongside nicotine mg)+- Server-side nicotine service with daily log persistence, custom product management, and caching++## Changed+- Extracted shared `dayOfWeek` utility and `DAY_LABELS` constant to meatspace constants (deduplicated from AlcoholTab)+- Health correlation endpoint now includes heart rate, resting heart rate, and nicotine data alongside existing HRV/alcohol/steps+- NicotineHealthCorrelation tooltip uses Tailwind classes instead of inline styles for consistency++## Fixed++## Removeddiff --git a/client/src/components/meatspace/NicotineChart.jsx b/client/src/components/meatspace/NicotineChart.jsxnew file mode 100644index 0000000000..e8f239e839--- /dev/null+++ b/client/src/components/meatspace/NicotineChart.jsx@@ -0,0 +1,117 @@+import { useState, useEffect, useCallback } from 'react';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer+} from 'recharts';+import * as api from '../../services/api';+import BrailleSpinner from '../BrailleSpinner';++const VIEWS = [+ { id: '7d', label: '7 Days', days: 7 },+ { id: '30d', label: '30 Days', days: 30 },+ { id: '90d', label: '90 Days', days: 90 }+];++const CustomTooltip = ({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ const mg = payload[0].payload.mg;+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-2 text-sm">+ <p className="text-gray-400">{label}</p>+ <p className={`font-semibold ${mg > 20 ? 'text-port-warning' : 'text-white'}`}>+ {mg} mg+ </p>+ </div>+ );+};++export default function NicotineChart({ onRefreshKey, onViewChange }) {+ const [data, setData] = useState([]);+ const [loading, setLoading] = useState(true);+ const [view, setView] = useState('30d');++ const fetchData = useCallback(async () => {+ const days = VIEWS.find(v => v.id === view)?.days || 30;+ const from = new Date();+ from.setDate(from.getDate() - days);+ const fromStr = from.toISOString().split('T')[0];+ const toStr = new Date().toISOString().split('T')[0];++ const entries = await api.getDailyNicotine(fromStr, toStr).catch(() => []);++ const chartData = [];+ const dateMap = {};+ for (const entry of entries) {+ dateMap[entry.date] = entry.nicotine?.totalMg || 0;+ }++ const cursor = new Date(from);+ const end = new Date(toStr);+ while (cursor <= end) {+ const dateStr = cursor.toISOString().split('T')[0];+ const mg = dateMap[dateStr] || 0;+ chartData.push({+ date: dateStr,+ label: `${cursor.getMonth() + 1}/${cursor.getDate()}`,+ mg+ });+ cursor.setDate(cursor.getDate() + 1);+ }++ setData(chartData);+ setLoading(false);+ }, [view]);++ useEffect(() => {+ fetchData();+ }, [fetchData, onRefreshKey]);++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Daily Consumption+ </h3>+ <div className="flex gap-1">+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => { setView(v.id); onViewChange?.(v.id); }}+ className={`px-2 py-1 min-h-[40px] text-xs rounded transition-colors ${+ view === v.id+ ? 'bg-port-accent/10 text-port-accent'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {v.label}+ </button>+ ))}+ </div>+ </div>++ {loading ? (+ <div className="flex justify-center py-8">+ <BrailleSpinner text="Loading chart" />+ </div>+ ) : (+ <ResponsiveContainer width="100%" height={250}>+ <BarChart data={data} margin={{ top: 5, right: 5, bottom: 5, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />+ <XAxis+ dataKey="label"+ tick={{ fill: '#6b7280', fontSize: 11 }}+ interval={view === '7d' ? 0 : view === '30d' ? 2 : 6}+ />+ <YAxis tick={{ fill: '#6b7280', fontSize: 11 }} label={{ value: 'mg', angle: -90, position: 'insideLeft', fill: '#6b7280', fontSize: 10 }} />+ <Tooltip content={<CustomTooltip />} />+ <Bar+ dataKey="mg"+ radius={[2, 2, 0, 0]}+ fill="#9ca3af"+ maxBarSize={view === '7d' ? 40 : view === '30d' ? 16 : 8}+ />+ </BarChart>+ </ResponsiveContainer>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/NicotineHealthCorrelation.jsx b/client/src/components/meatspace/NicotineHealthCorrelation.jsxnew file mode 100644index 0000000000..c2f474f1bb--- /dev/null+++ b/client/src/components/meatspace/NicotineHealthCorrelation.jsx@@ -0,0 +1,130 @@+import { HeartPulse, Cigarette } from 'lucide-react';+import {+ ComposedChart, Line, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer+} from 'recharts';++const CustomTooltip = ({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-2 text-sm text-white">+ <p className="text-gray-400 mb-1">{label}</p>+ {payload.map((entry) => (+ <p key={entry.dataKey} style={{ color: entry.color ?? entry.fill }} className="my-0.5">+ {entry.name}: {entry.value != null ? Math.round(entry.value * 100) / 100 : '\u2014'}+ {entry.dataKey === 'hr' || entry.dataKey === 'restingHr' ? ' bpm' : ' mg'}+ </p>+ ))}+ </div>+ );+};++function computeSummary(dailyData) {+ const nicotineDays = dailyData.filter(d => d.nicotineMg != null && d.nicotineMg > 0 && d.hr != null);+ const cleanDays = dailyData.filter(d => (d.nicotineMg == null || d.nicotineMg === 0) && d.hr != null);++ if (nicotineDays.length === 0) return 'No nicotine data recorded in this period.';+ if (cleanDays.length === 0) return 'No nicotine-free days recorded in this period.';++ const avgHrNicotine = Math.round(nicotineDays.reduce((sum, d) => sum + d.hr, 0) / nicotineDays.length);+ const avgHrClean = Math.round(cleanDays.reduce((sum, d) => sum + d.hr, 0) / cleanDays.length);+ const percentDiff = avgHrClean > 0+ ? Math.abs(((avgHrNicotine - avgHrClean) / avgHrClean) * 100).toFixed(0)+ : '0';++ const direction = avgHrNicotine > avgHrClean ? 'higher' : 'lower';++ return `Avg heart rate is ${avgHrNicotine} bpm on nicotine days vs ${avgHrClean} bpm on clean days (${percentDiff}% ${direction})`;+}++export default function NicotineHealthCorrelation({ data, range }) {+ const dailyData = data?.dailyData ?? [];++ if (dailyData.length < 14) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-3">+ <HeartPulse size={16} className="text-port-error" />+ <Cigarette size={16} className="text-gray-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Nicotine vs Heart Rate</h3>+ </div>+ <p className="text-gray-400 text-sm">+ Need 14+ days of data for correlations — {dailyData.length} days so far.+ </p>+ </div>+ );+ }++ const chartData = dailyData.map(d => ({+ date: d.date?.slice(5) ?? '',+ hr: d.hr,+ restingHr: d.restingHr,+ nicotine: d.nicotineMg+ }));++ const summary = computeSummary(dailyData);++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <HeartPulse size={16} className="text-port-error" />+ <Cigarette size={16} className="text-gray-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Nicotine vs Heart Rate</h3>+ <span className="text-xs text-gray-600 ml-1">({range})</span>+ </div>++ <ResponsiveContainer width="100%" height={220}>+ <ComposedChart data={chartData} margin={{ top: 5, right: 40, bottom: 5, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />+ <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />+ <YAxis+ yAxisId="hr"+ orientation="left"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ width={40}+ label={{ value: 'HR (bpm)', angle: -90, position: 'insideLeft', fill: '#9ca3af', fontSize: 10 }}+ />+ <YAxis+ yAxisId="nicotine"+ orientation="right"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ width={40}+ label={{ value: 'Nicotine (mg)', angle: 90, position: 'insideRight', fill: '#9ca3af', fontSize: 10 }}+ />+ <Tooltip content={<CustomTooltip />} />+ <Legend wrapperStyle={{ fontSize: 11, color: '#9ca3af' }} />+ <Line+ yAxisId="hr"+ type="monotone"+ dataKey="hr"+ name="Heart Rate"+ stroke="#ef4444"+ strokeWidth={2}+ dot={false}+ connectNulls+ />+ <Line+ yAxisId="hr"+ type="monotone"+ dataKey="restingHr"+ name="Resting HR"+ stroke="#f87171"+ strokeWidth={1}+ strokeDasharray="4 2"+ dot={false}+ connectNulls+ />+ <Bar+ yAxisId="nicotine"+ dataKey="nicotine"+ name="Nicotine"+ fill="#9ca3af"+ opacity={0.7}+ maxBarSize={12}+ />+ </ComposedChart>+ </ResponsiveContainer>++ <p className="text-sm text-gray-400 mt-3 border-t border-port-border pt-3">{summary}</p>+ </div>+ );+}diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.jsindex 6600c74dcd..81a8560585 100644--- a/client/src/components/meatspace/constants.js+++ b/client/src/components/meatspace/constants.js@@ -1,5 +1,6 @@import {Beer,+ Cigarette,Clock,Dna,HeartPulse,@@ -20,6 +21,7 @@ export const TABS = [{ id: 'health', label: 'Health', icon: Stethoscope },{ id: 'import', label: 'Import', icon: Upload },{ id: 'lifestyle', label: 'Lifestyle', icon: ClipboardList },+ { id: 'nicotine', label: 'Nicotine', icon: Cigarette },];// Lifestyle adjustment table for death clock@@ -105,6 +107,14 @@ export const STATUS_COLORS = {unknown: 'text-gray-500'};+// Shared day-of-week helpers (used by AlcoholTab, NicotineTab, etc.)+export const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];++export function dayOfWeek(dateStr) {+ const [y, m, d] = dateStr.split('-').map(Number);+ return DAY_LABELS[new Date(y, m - 1, d).getDay()];+}+// LEV 2045 constantsexport const LEV_TARGET_YEAR = 2045;export const LEV_BIRTH_YEAR = 1979;diff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsxindex c8208d38ce..0823aaa41c 100644--- a/client/src/components/meatspace/tabs/AlcoholTab.jsx+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx@@ -6,6 +6,7 @@ import BrailleSpinner from '../../BrailleSpinner';import AlcoholChart from '../AlcoholChart';import AlcoholHrvCorrelation from '../AlcoholHrvCorrelation';import StandardDrinkCalculator from '../StandardDrinkCalculator';+import { dayOfWeek } from '../constants';const ML_PER_OZ = 29.5735;@@ -32,12 +33,6 @@ const RISK_BG = {};const DAYS_PER_PAGE = 50;-const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];--function dayOfWeek(dateStr) {- const [y, m, d] = dateStr.split('-').map(Number);- return DAY_LABELS[new Date(y, m - 1, d).getDay()];-}function computeStdDrinks(oz, abv, count) {const pureOz = (oz || 0) * (count || 1) * ((abv || 0) / 100);diff --git a/client/src/components/meatspace/tabs/NicotineTab.jsx b/client/src/components/meatspace/tabs/NicotineTab.jsxnew file mode 100644index 0000000000..bce28b909f--- /dev/null+++ b/client/src/components/meatspace/tabs/NicotineTab.jsx@@ -0,0 +1,490 @@+import { useState, useEffect, useCallback, useMemo } from 'react';+import { Cigarette, Plus, Trash2, Pencil, Check, X, Settings } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';+import NicotineChart from '../NicotineChart';+import NicotineHealthCorrelation from '../NicotineHealthCorrelation';+import { dayOfWeek } from '../constants';++const DAYS_PER_PAGE = 50;++export default function NicotineTab() {+ const [summary, setSummary] = useState(null);+ const [allEntries, setAllEntries] = useState(null);+ const [loading, setLoading] = useState(true);+ const [logging, setLogging] = useState(false);+ const [refreshKey, setRefreshKey] = useState(0);+ const [visibleDays, setVisibleDays] = useState(DAYS_PER_PAGE);++ // Custom product buttons+ const [productButtons, setProductButtons] = useState([]);+ const [managingButtons, setManagingButtons] = useState(false);+ const [editingButtonIdx, setEditingButtonIdx] = useState(null);+ const [buttonForm, setButtonForm] = useState({ name: '', mgPerUnit: '' });++ // Form state+ const today = useMemo(() => new Date().toISOString().split('T')[0], []);+ const [product, setProduct] = useState('');+ const [mgPerUnit, setMgPerUnit] = useState('3');+ const [count, setCount] = useState(1);+ const [date, setDate] = useState(today);++ // Inline edit state+ const [editingKey, setEditingKey] = useState(null);+ const [editForm, setEditForm] = useState({ product: '', mgPerUnit: '', count: 1 });++ // Correlation chart state+ const [chartView, setChartView] = useState('30d');+ const [correlationData, setCorrelationData] = useState(null);++ const fetchProductButtons = useCallback(async () => {+ const buttons = await api.getCustomNicotineProducts().catch(() => null);+ if (Array.isArray(buttons)) {+ setProductButtons(buttons);+ }+ }, []);++ const fetchData = useCallback(async () => {+ const [summaryData, entries] = await Promise.all([+ api.getNicotineSummary().catch(() => null),+ api.getDailyNicotine().catch(() => [])+ ]);+ setSummary(summaryData);+ setAllEntries(entries);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchProductButtons();+ }, [fetchProductButtons]);++ useEffect(() => {+ fetchData();+ }, [fetchData, refreshKey]);++ // Fetch correlation data — memoize date range to avoid refetch on every render+ const { correlationFrom, correlationTo } = useMemo(() => {+ const days = { '7d': 7, '30d': 30, '90d': 90 }[chartView] || 30;+ const d = new Date();+ d.setDate(d.getDate() - days);+ return { correlationFrom: d.toISOString().split('T')[0], correlationTo: new Date().toISOString().split('T')[0] };+ }, [chartView]);++ useEffect(() => {+ api.getAppleHealthCorrelation(correlationFrom, correlationTo)+ .then(setCorrelationData)+ .catch(() => setCorrelationData(null));+ }, [correlationFrom, correlationTo]);++ const handleQuickAdd = async (prod) => {+ setLogging(true);+ await api.logNicotine({+ product: prod.name,+ mgPerUnit: prod.mgPerUnit,+ count: 1,+ date: date || undefined+ }).catch(() => null);+ setLogging(false);+ setRefreshKey(k => k + 1);+ };++ const handleCustomAdd = async (e) => {+ e.preventDefault();+ if (!mgPerUnit) return;+ setLogging(true);+ await api.logNicotine({+ product: product || '',+ mgPerUnit: parseFloat(mgPerUnit),+ count: count || 1,+ date: date || undefined+ }).catch(() => null);+ setLogging(false);+ setProduct('');+ setMgPerUnit('3');+ setCount(1);+ setRefreshKey(k => k + 1);+ };++ const handleRemove = async (entryDate, index) => {+ await api.removeNicotineEntry(entryDate, index).catch(() => null);+ setRefreshKey(k => k + 1);+ };++ const startEdit = (entryDate, index, item) => {+ setEditingKey(`${entryDate}:${index}`);+ setEditForm({+ product: item.product || '',+ mgPerUnit: String(item.mgPerUnit || ''),+ count: item.count || 1+ });+ };++ const cancelEdit = () => {+ setEditingKey(null);+ };++ const saveEdit = async () => {+ if (!editingKey) return;+ const [entryDate, indexStr] = editingKey.split(':');+ const index = parseInt(indexStr, 10);+ await api.updateNicotineEntry(entryDate, index, {+ product: editForm.product,+ mgPerUnit: parseFloat(editForm.mgPerUnit),+ count: parseInt(editForm.count, 10) || 1+ }).catch(() => null);+ setEditingKey(null);+ setRefreshKey(k => k + 1);+ };++ // === Custom product button management ===++ const validateProductButton = (form) => {+ if (!form.name) return 'Name is required';+ const parsed = parseFloat(form.mgPerUnit);+ if (isNaN(parsed) || parsed < 0.1 || parsed > 100) return 'mg must be between 0.1 and 100';+ return null;+ };++ const handleAddButton = async (e) => {+ e.preventDefault();+ const error = validateProductButton(buttonForm);+ if (error) { toast.error(error); return; }+ const result = await api.addCustomNicotineProduct({ name: buttonForm.name, mgPerUnit: parseFloat(buttonForm.mgPerUnit) }).catch(() => null);+ if (!result) { toast.error('Failed to add product button'); return; }+ setButtonForm({ name: '', mgPerUnit: '' });+ fetchProductButtons();+ };++ const startEditButton = (idx) => {+ const btn = productButtons[idx];+ setEditingButtonIdx(idx);+ setButtonForm({ name: btn.name, mgPerUnit: String(btn.mgPerUnit) });+ };++ const saveEditButton = async () => {+ if (editingButtonIdx === null) return;+ const error = validateProductButton(buttonForm);+ if (error) { toast.error(error); return; }+ const result = await api.updateCustomNicotineProduct(editingButtonIdx, { name: buttonForm.name, mgPerUnit: parseFloat(buttonForm.mgPerUnit) }).catch(() => null);+ if (!result) { toast.error('Failed to update product button'); return; }+ setEditingButtonIdx(null);+ setButtonForm({ name: '', mgPerUnit: '' });+ fetchProductButtons();+ };++ const cancelEditButton = () => {+ setEditingButtonIdx(null);+ setButtonForm({ name: '', mgPerUnit: '' });+ };++ const handleRemoveButton = async (idx) => {+ await api.removeCustomNicotineProduct(idx).catch(() => null);+ fetchProductButtons();+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <BrailleSpinner text="Loading" />+ </div>+ );+ }++ const visibleEntries = allEntries?.slice(0, visibleDays) || [];+ const hasMore = allEntries?.length > visibleDays;++ return (+ <div className="space-y-6">+ {/* Summary */}+ {summary && (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-4">+ <Cigarette size={18} className="text-gray-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Nicotine Summary+ </h3>+ </div>++ <div className="grid grid-cols-2 md:grid-cols-5 gap-4">+ <div>+ <span className="text-xs text-gray-500">Today</span>+ <p className="text-2xl font-bold text-white">+ {summary.today ?? 0} mg+ </p>+ <span className="text-xs text-gray-600">{summary.todayCount ?? 0} units</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">7-Day Avg</span>+ <p className="text-2xl font-bold text-white">+ {summary.avg7day ?? 0} mg+ </p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">30-Day Avg</span>+ <p className="text-2xl font-bold text-white">+ {summary.avg30day ?? 0} mg+ </p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">Weekly Total</span>+ <p className="text-2xl font-bold text-white">+ {summary.weeklyTotal ?? 0} mg+ </p>+ </div>+ <div>+ <span className="text-xs text-gray-500">All-Time Avg</span>+ <p className="text-2xl font-bold text-white">+ {summary.allTimeAvg ?? 0} mg+ </p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ </div>+ </div>+ )}++ {/* Quick Add Buttons */}+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Quick Add+ </h3>+ <button+ onClick={() => setManagingButtons(!managingButtons)}+ className="p-1 text-gray-500 hover:text-white transition-colors"+ title="Manage product buttons"+ >+ <Settings size={14} />+ </button>+ </div>++ {managingButtons ? (+ <div className="space-y-3">+ {productButtons.map((btn, idx) => (+ <div key={idx} className="flex items-center gap-2 bg-port-bg rounded-lg p-2">+ {editingButtonIdx === idx ? (+ <>+ <input+ type="text"+ value={buttonForm.name}+ onChange={e => setButtonForm({ ...buttonForm, name: e.target.value })}+ className="flex-1 bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ placeholder="Name"+ />+ <input+ type="number"+ value={buttonForm.mgPerUnit}+ onChange={e => setButtonForm({ ...buttonForm, mgPerUnit: e.target.value })}+ className="w-20 bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ placeholder="mg"+ step="0.1"+ />+ <button onClick={saveEditButton} className="p-1 text-port-success hover:text-white"><Check size={14} /></button>+ <button onClick={cancelEditButton} className="p-1 text-gray-500 hover:text-white"><X size={14} /></button>+ </>+ ) : (+ <>+ <span className="flex-1 text-sm text-white">{btn.name}</span>+ <span className="text-xs text-gray-500">{btn.mgPerUnit} mg</span>+ <button onClick={() => startEditButton(idx)} className="p-1 text-gray-500 hover:text-white"><Pencil size={12} /></button>+ <button onClick={() => handleRemoveButton(idx)} className="p-1 text-gray-500 hover:text-port-error"><Trash2 size={12} /></button>+ </>+ )}+ </div>+ ))}+ <form onSubmit={handleAddButton} className="flex items-center gap-2 pt-2 border-t border-port-border">+ <input+ type="text"+ value={buttonForm.name}+ onChange={e => setButtonForm({ ...buttonForm, name: e.target.value })}+ className="flex-1 bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ placeholder="New product name"+ />+ <input+ type="number"+ value={buttonForm.mgPerUnit}+ onChange={e => setButtonForm({ ...buttonForm, mgPerUnit: e.target.value })}+ className="w-20 bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ placeholder="mg"+ step="0.1"+ />+ <button type="submit" className="px-3 py-1 min-h-[40px] bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20">+ <Plus size={14} />+ </button>+ </form>+ </div>+ ) : (+ <div className="flex flex-wrap gap-2">+ {productButtons.map((btn, idx) => (+ <button+ key={idx}+ onClick={() => handleQuickAdd(btn)}+ disabled={logging}+ className="px-3 py-2 min-h-[40px] bg-port-bg border border-port-border rounded-lg text-sm text-white hover:border-port-accent transition-colors disabled:opacity-50"+ >+ {btn.name}+ </button>+ ))}+ </div>+ )}++ {/* Date selector */}+ <div className="flex items-center gap-2 mt-3">+ <span className="text-xs text-gray-500">Date:</span>+ <input+ type="date"+ value={date}+ onChange={e => setDate(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ />+ {date !== today && (+ <button+ onClick={() => setDate(today)}+ className="text-xs text-port-accent hover:underline"+ >+ Reset to today+ </button>+ )}+ </div>+ </div>++ {/* Custom Entry Form */}+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">+ Custom Entry+ </h3>+ <form onSubmit={handleCustomAdd} className="flex flex-wrap items-end gap-3">+ <div className="flex-1 min-w-[120px]">+ <label className="block text-xs text-gray-500 mb-1">Product</label>+ <input+ type="text"+ value={product}+ onChange={e => setProduct(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white"+ placeholder="e.g. Stokes Pick"+ />+ </div>+ <div className="w-24">+ <label className="block text-xs text-gray-500 mb-1">mg/unit</label>+ <input+ type="number"+ value={mgPerUnit}+ onChange={e => setMgPerUnit(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white"+ step="0.1"+ min="0.1"+ required+ />+ </div>+ <div className="w-20">+ <label className="block text-xs text-gray-500 mb-1">Count</label>+ <input+ type="number"+ value={count}+ onChange={e => setCount(parseInt(e.target.value, 10) || 1)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white"+ min="1"+ />+ </div>+ <button+ type="submit"+ disabled={logging || !mgPerUnit}+ className="px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 flex items-center gap-1"+ >+ <Plus size={14} />+ Log+ </button>+ </form>+ </div>++ {/* Chart */}+ <NicotineChart onRefreshKey={refreshKey} onViewChange={setChartView} />++ {/* Correlation Chart */}+ {correlationData && (+ <NicotineHealthCorrelation data={correlationData} range={chartView} />+ )}++ {/* Entry History */}+ {visibleEntries.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">+ History+ </h3>+ <div className="space-y-4">+ {visibleEntries.map(entry => (+ <div key={entry.date} className="border-b border-port-border pb-3 last:border-0 last:pb-0">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-white">{entry.date}</span>+ <span className="text-xs text-gray-600">{dayOfWeek(entry.date)}</span>+ </div>+ <span className="text-sm font-bold text-white">+ {entry.nicotine?.totalMg ?? 0} mg+ </span>+ </div>++ {entry.nicotine?.items?.map((item, idx) => {+ const key = `${entry.date}:${idx}`;+ const isEditing = editingKey === key;++ return (+ <div key={idx} className="flex items-center gap-2 py-1 pl-4 text-sm">+ {isEditing ? (+ <>+ <input+ type="text"+ value={editForm.product}+ onChange={e => setEditForm({ ...editForm, product: e.target.value })}+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ />+ <input+ type="number"+ value={editForm.mgPerUnit}+ onChange={e => setEditForm({ ...editForm, mgPerUnit: e.target.value })}+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ step="0.1"+ />+ <span className="text-gray-500">x</span>+ <input+ type="number"+ value={editForm.count}+ onChange={e => setEditForm({ ...editForm, count: e.target.value })}+ className="w-16 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ min="1"+ />+ <button onClick={saveEdit} className="p-1 text-port-success hover:text-white"><Check size={14} /></button>+ <button onClick={cancelEdit} className="p-1 text-gray-500 hover:text-white"><X size={14} /></button>+ </>+ ) : (+ <>+ <span className="flex-1 text-gray-300">{item.product || 'Unnamed'}</span>+ <span className="text-gray-500">{item.mgPerUnit} mg</span>+ {item.count > 1 && <span className="text-gray-600">x{item.count}</span>}+ <span className="text-white font-medium">{Math.round(item.mgPerUnit * (item.count || 1) * 100) / 100} mg</span>+ <button onClick={() => startEdit(entry.date, idx, item)} className="p-1 text-gray-600 hover:text-white"><Pencil size={12} /></button>+ <button onClick={() => handleRemove(entry.date, idx)} className="p-1 text-gray-600 hover:text-port-error"><Trash2 size={12} /></button>+ </>+ )}+ </div>+ );+ })}+ </div>+ ))}+ </div>++ {hasMore && (+ <button+ onClick={() => setVisibleDays(v => v + DAYS_PER_PAGE)}+ className="mt-4 w-full py-2 text-sm text-port-accent hover:underline"+ >+ Load more...+ </button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsxindex 703b9efbb5..a876f95b21 100644--- a/client/src/pages/MeatSpace.jsx+++ b/client/src/pages/MeatSpace.jsx@@ -12,6 +12,7 @@ import GenomeTab from '../components/meatspace/tabs/GenomeTab';import HealthTab from '../components/meatspace/tabs/HealthTab';import ImportTab from '../components/meatspace/tabs/ImportTab';import LifestyleTab from '../components/meatspace/tabs/LifestyleTab';+import NicotineTab from '../components/meatspace/tabs/NicotineTab';export default function MeatSpace() {const { tab } = useParams();@@ -42,6 +43,8 @@ export default function MeatSpace() {return <ImportTab />;case 'lifestyle':return <LifestyleTab />;+ case 'nicotine':+ return <NicotineTab />;default:return <OverviewTab />;}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 943ed5662d..95a98c90f9 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1455,6 +1455,36 @@ export const updateCustomDrink = (index, data) => request(`/meatspace/alcohol/cuexport const removeCustomDrink = (index) => request(`/meatspace/alcohol/custom-drinks/${index}`, {method: 'DELETE'});+export const getNicotineSummary = () => request('/meatspace/nicotine');+export const getDailyNicotine = (from, to) => {+ const params = new URLSearchParams();+ if (from) params.set('from', from);+ if (to) params.set('to', to);+ return request(`/meatspace/nicotine/daily?${params}`);+};+export const logNicotine = (data) => request('/meatspace/nicotine/log', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateNicotineEntry = (date, index, data) => request(`/meatspace/nicotine/log/${date}/${index}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const removeNicotineEntry = (date, index) => request(`/meatspace/nicotine/log/${date}/${index}`, {+ method: 'DELETE'+});+export const getCustomNicotineProducts = () => request('/meatspace/nicotine/custom-products');+export const addCustomNicotineProduct = (data) => request('/meatspace/nicotine/custom-products', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateCustomNicotineProduct = (index, data) => request(`/meatspace/nicotine/custom-products/${index}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const removeCustomNicotineProduct = (index) => request(`/meatspace/nicotine/custom-products/${index}`, {+ method: 'DELETE'+});export const getBloodTests = () => request('/meatspace/blood');export const addBloodTest = (data) => request('/meatspace/blood', {method: 'POST',diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.jsindex 34b1fbff45..405dbfb9a4 100644--- a/server/lib/meatspaceValidation.js+++ b/server/lib/meatspaceValidation.js@@ -85,6 +85,30 @@ export const customDrinkSchema = z.object({export const customDrinkUpdateSchema = customDrinkSchema.partial();+// =============================================================================+// NICOTINE+// =============================================================================++export const nicotineLogSchema = z.object({+ product: z.string().max(200).optional().default(''),+ mgPerUnit: z.number().min(0.1).max(100),+ count: z.number().int().min(1).max(100).optional().default(1),+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()+});++export const nicotineUpdateSchema = z.object({+ product: z.string().max(200).optional(),+ mgPerUnit: z.number().min(0.1).max(100).optional(),+ count: z.number().int().min(1).max(100).optional()+});++export const customNicotineProductSchema = z.object({+ name: z.string().min(1).max(200),+ mgPerUnit: z.number().min(0.1).max(100)+});++export const customNicotineProductUpdateSchema = customNicotineProductSchema.partial();+// =============================================================================// BLOOD TESTS// =============================================================================diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex 16468cf7bb..9d7b957bad 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -8,6 +8,10 @@ import {drinkUpdateSchema,customDrinkSchema,customDrinkUpdateSchema,+ nicotineLogSchema,+ nicotineUpdateSchema,+ customNicotineProductSchema,+ customNicotineProductUpdateSchema,bloodTestSchema,bodyEntrySchema,epigeneticTestSchema,@@ -34,6 +38,7 @@ import {} from '../lib/postValidation.js';import * as meatspaceService from '../services/meatspace.js';import * as alcoholService from '../services/meatspaceAlcohol.js';+import * as nicotineService from '../services/meatspaceNicotine.js';import * as healthService from '../services/meatspaceHealth.js';import * as postService from '../services/meatspacePost.js';import * as memoryService from '../services/meatspacePostMemory.js';@@ -257,6 +262,129 @@ router.delete('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) =>res.json(removed);}));+// =============================================================================+// NICOTINE+// =============================================================================++/**+ * GET /api/meatspace/nicotine+ * Nicotine summary with rolling averages+ */+router.get('/nicotine', asyncHandler(async (req, res) => {+ const summary = await nicotineService.getNicotineSummary();+ res.json(summary);+}));++/**+ * GET /api/meatspace/nicotine/daily+ * Daily nicotine entries with optional date range+ */+router.get('/nicotine/daily', asyncHandler(async (req, res) => {+ const entries = await nicotineService.getDailyNicotine(req.query.from, req.query.to);+ res.json(entries);+}));++/**+ * POST /api/meatspace/nicotine/log+ * Log nicotine consumption+ */+router.post('/nicotine/log', asyncHandler(async (req, res) => {+ const data = validateRequest(nicotineLogSchema, req.body);+ const result = await nicotineService.logNicotine(data);+ res.status(201).json(result);+}));++/**+ * PUT /api/meatspace/nicotine/log/:date/:index+ * Update a specific nicotine entry+ */+router.put('/nicotine/log/:date/:index', asyncHandler(async (req, res) => {+ const { date, index } = req.params;+ const data = validateRequest(nicotineUpdateSchema, req.body);+ const parsedIndex = parseInt(index, 10);+ if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });+ }+ const result = await nicotineService.updateNicotine(date, parsedIndex, data);+ if (!result) {+ throw new ServerError('Nicotine entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++/**+ * DELETE /api/meatspace/nicotine/log/:date/:index+ * Remove a specific nicotine entry+ */+router.delete('/nicotine/log/:date/:index', asyncHandler(async (req, res) => {+ const { date, index } = req.params;+ const parsedIndex = parseInt(index, 10);+ if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });+ }+ const removed = await nicotineService.removeNicotine(date, parsedIndex);+ if (!removed) {+ throw new ServerError('Nicotine entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(removed);+}));++// =============================================================================+// CUSTOM NICOTINE PRODUCTS+// =============================================================================++/**+ * GET /api/meatspace/nicotine/custom-products+ * List custom nicotine product quick-add buttons+ */+router.get('/nicotine/custom-products', asyncHandler(async (req, res) => {+ const products = await nicotineService.getCustomProducts();+ res.json(products);+}));++/**+ * POST /api/meatspace/nicotine/custom-products+ * Add a custom nicotine product button+ */+router.post('/nicotine/custom-products', asyncHandler(async (req, res) => {+ const data = validateRequest(customNicotineProductSchema, req.body);+ const product = await nicotineService.addCustomProduct(data);+ res.status(201).json(product);+}));++/**+ * PUT /api/meatspace/nicotine/custom-products/:index+ * Update a custom nicotine product button+ */+router.put('/nicotine/custom-products/:index', asyncHandler(async (req, res) => {+ const index = Number(req.params.index);+ if (!Number.isInteger(index) || index < 0) {+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });+ }+ const data = validateRequest(customNicotineProductUpdateSchema, req.body);+ const product = await nicotineService.updateCustomProduct(index, data);+ if (!product) {+ throw new ServerError('Custom product not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(product);+}));++/**+ * DELETE /api/meatspace/nicotine/custom-products/:index+ * Remove a custom nicotine product button+ */+router.delete('/nicotine/custom-products/:index', asyncHandler(async (req, res) => {+ const index = Number(req.params.index);+ if (!Number.isInteger(index) || index < 0) {+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });+ }+ const removed = await nicotineService.removeCustomProduct(index);+ if (!removed) {+ throw new ServerError('Custom product not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(removed);+}));+// =============================================================================// BLOOD & BODY// =============================================================================diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.jsindex 4ca319c8d0..fc1db697f1 100644--- a/server/services/appleHealthQuery.js+++ b/server/services/appleHealthQuery.js@@ -9,6 +9,7 @@ import { readdir } from 'fs/promises';import { PATHS } from '../lib/fileUtils.js';import { readDayFile } from './appleHealthIngest.js';import { getDailyAlcohol } from './meatspaceAlcohol.js';+import { getDailyNicotine } from './meatspaceNicotine.js';import { getBloodTests } from './meatspaceHealth.js';// Fallback aliases for metrics stored under old names (e.g. JSON ingest before normalization)@@ -271,35 +272,46 @@ export async function getLatestMetricValues(metricNames) {// === Correlation Data ===/**- * Get merged health + alcohol + blood data for correlation analysis.- * Reads HRV, steps, and alcohol data by day, plus blood tests for date range.+ * Get merged health + alcohol + nicotine + blood data for correlation analysis.+ * Reads HRV, HR, resting HR, steps, alcohol, and nicotine data by day, plus blood tests for date range.** @param {string} [from] - Start date YYYY-MM-DD* @param {string} [to] - End date YYYY-MM-DD- * @returns {Promise<Object>} { dailyData: Array<{ date, hrv, alcoholGrams, steps }>, bloodTests }+ * @returns {Promise<Object>} { dailyData: Array<{ date, hrv, hr, restingHr, alcoholGrams, nicotineMg, steps }>, bloodTests }*/export async function getCorrelationData(from, to) {const range = from && to ? { from, to } : defaultDateRange();- const [hrvData, stepsData, alcoholEntries, bloodData] = await Promise.all([+ const [hrvData, hrData, restingHrData, stepsData, alcoholEntries, nicotineEntries, bloodData] = await Promise.all([getDailyAggregates('heart_rate_variability_sdnn', range.from, range.to),+ getDailyAggregates('heart_rate', range.from, range.to),+ getDailyAggregates('resting_heart_rate', range.from, range.to),getDailyAggregates('step_count', range.from, range.to),getDailyAlcohol(range.from, range.to),+ getDailyNicotine(range.from, range.to),getBloodTests()]);// Build lookup maps for O(1) accessconst hrvByDate = new Map(hrvData.map(d => [d.date, d.value]));+ const hrByDate = new Map(hrData.map(d => [d.date, d.value]));+ const restingHrByDate = new Map(restingHrData.map(d => [d.date, d.value]));const stepsByDate = new Map(stepsData.map(d => [d.date, d.value]));const alcoholByDate = new Map(alcoholEntries.map(e => [e.date, e.alcohol?.standardDrinks ?? 0]));+ const nicotineByDate = new Map(+ nicotineEntries.map(e => [e.date, e.nicotine?.totalMg ?? 0])+ );// Collect all unique dates across all sourcesconst allDates = new Set([...hrvByDate.keys(),+ ...hrByDate.keys(),+ ...restingHrByDate.keys(),...stepsByDate.keys(),- ...alcoholByDate.keys()+ ...alcoholByDate.keys(),+ ...nicotineByDate.keys()]);const dailyData = Array.from(allDates)@@ -307,9 +319,12 @@ export async function getCorrelationData(from, to) {.map(date => ({date,hrv: hrvByDate.get(date) ?? null,+ hr: hrByDate.get(date) != null ? Math.round(hrByDate.get(date)) : null,+ restingHr: restingHrByDate.get(date) != null ? Math.round(restingHrByDate.get(date)) : null,alcoholGrams: alcoholByDate.get(date) != null? Math.round(alcoholByDate.get(date) * 14 * 100) / 100 // std drinks to grams: null,+ nicotineMg: nicotineByDate.get(date) ?? null,steps: stepsByDate.get(date) ?? null}));diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsnew file mode 100644index 0000000000..7b50fc05a7--- /dev/null+++ b/server/services/meatspaceNicotine.js@@ -0,0 +1,272 @@+/**+ * MeatSpace Nicotine Service+ *+ * Nicotine consumption logging, daily totals, and rolling averages.+ * Stores data in the shared daily-log.json under the `nicotine` key per entry.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');+const CUSTOM_PRODUCTS_FILE = join(MEATSPACE_DIR, 'custom-nicotine-products.json');++const DEFAULT_PRODUCTS = [+ { name: 'Stokes Pick (3mg)', mgPerUnit: 3 },+];++// Cache for rolling averages (invalidated on writes)+let averageCache = null;+let averageCacheAt = 0;+const CACHE_TTL_MS = 5 * 60 * 1000;++// === Pure Functions ===++/**+ * Compute rolling averages from daily entries for nicotine consumption.+ */+export function computeRollingAverages(entries) {+ const now = new Date();+ const today = now.toISOString().split('T')[0];++ const allEntries = [...entries].sort((a, b) => a.date.localeCompare(b.date));++ // Today's total+ const todayEntry = allEntries.find(e => e.date === today);+ const todayMg = todayEntry?.nicotine?.totalMg ?? 0;+ const todayCount = todayEntry?.nicotine?.items?.length ?? 0;++ // Helper: average over last N days+ const rollingAverage = (days) => {+ const cutoff = new Date(now);+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];++ let totalMg = 0;+ for (const entry of allEntries) {+ if (entry.date >= cutoffStr && entry.date <= today) {+ totalMg += entry.nicotine?.totalMg ?? 0;+ }+ }+ return Math.round((totalMg / days) * 100) / 100;+ };++ // All-time average+ let allTimeAvg = 0;+ if (allEntries.length > 0) {+ const firstDate = new Date(allEntries[0].date);+ const totalDays = Math.max(1, Math.ceil((now - firstDate) / (24 * 60 * 60 * 1000)));+ const totalMg = allEntries.reduce((sum, e) => sum + (e.nicotine?.totalMg || 0), 0);+ allTimeAvg = Math.round((totalMg / totalDays) * 100) / 100;+ }++ const avg7day = rollingAverage(7);+ const avg30day = rollingAverage(30);+ const weeklyTotal = Math.round(avg7day * 7 * 100) / 100;++ const nicotineDays = entries.filter(e => e.nicotine?.totalMg > 0).length;++ return {+ today: todayMg,+ todayCount,+ avg7day,+ avg30day,+ allTimeAvg,+ weeklyTotal,+ nicotineDays,+ totalEntries: allEntries.length+ };+}++/**+ * Recalculate total nicotine mg for a daily entry from its items.+ */+function recalcDayTotal(entry) {+ entry.nicotine.totalMg = Math.round(+ entry.nicotine.items.reduce((sum, d) => sum + (d.mgPerUnit ?? 0) * (d.count ?? 1), 0) * 100+ ) / 100;+}++// === File I/O ===++async function loadDailyLog() {+ const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false });+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { entries: [], lastEntryDate: null };+ if (!Array.isArray(raw.entries)) raw.entries = [];+ return raw;+}++async function saveDailyLog(log) {+ await ensureDir(MEATSPACE_DIR);+ await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));+ averageCache = null;+}++// === Exported Service Functions ===++export async function getNicotineSummary() {+ const now = Date.now();+ if (averageCache && (now - averageCacheAt < CACHE_TTL_MS)) {+ return averageCache;+ }++ const log = await loadDailyLog();+ const averages = computeRollingAverages(log.entries || []);++ // Recent entries (last 7 days)+ const today = new Date().toISOString().split('T')[0];+ const weekAgo = new Date();+ weekAgo.setDate(weekAgo.getDate() - 7);+ const weekAgoStr = weekAgo.toISOString().split('T')[0];++ const recentEntries = (log.entries || [])+ .filter(e => e.date >= weekAgoStr && e.date <= today && e.nicotine?.items?.length > 0)+ .sort((a, b) => b.date.localeCompare(a.date));++ averageCache = { ...averages, recentEntries };+ averageCacheAt = now;++ return averageCache;+}++export async function getDailyNicotine(from, to) {+ const log = await loadDailyLog();+ let entries = (log.entries || []).filter(e => e.nicotine?.items?.length > 0);++ if (from) entries = entries.filter(e => e.date >= from);+ if (to) entries = entries.filter(e => e.date <= to);++ return entries.sort((a, b) => b.date.localeCompare(a.date));+}++export async function logNicotine({ product, mgPerUnit, count = 1, date }) {+ const log = await loadDailyLog();+ const targetDate = date || new Date().toISOString().split('T')[0];++ const totalMg = Math.round(mgPerUnit * count * 100) / 100;+ const item = { product: product || '', mgPerUnit, count };++ // Find or create daily entry+ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) {+ entry = { date: targetDate };+ log.entries.push(entry);+ }++ // Initialize nicotine section+ if (!entry.nicotine) {+ entry.nicotine = { items: [], totalMg: 0 };+ }++ entry.nicotine.items.push(item);+ recalcDayTotal(entry);++ // Re-sort and update lastEntryDate+ log.entries.sort((a, b) => a.date.localeCompare(b.date));+ log.lastEntryDate = log.entries[log.entries.length - 1].date;++ await saveDailyLog(log);+ console.log(`🚬 Logged nicotine: ${product || 'unnamed'} ${mgPerUnit}mg x${count} (${totalMg}mg) on ${targetDate}`);++ return { item, totalMg, date: targetDate, dayTotal: entry.nicotine.totalMg };+}++export async function updateNicotine(date, index, updates) {+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === date);+ if (!entry?.nicotine?.items?.[index]) return null;++ const item = entry.nicotine.items[index];+ if (updates.product !== undefined) item.product = updates.product;+ if (updates.mgPerUnit !== undefined) item.mgPerUnit = updates.mgPerUnit;+ if (updates.count !== undefined) item.count = updates.count;++ recalcDayTotal(entry);++ await saveDailyLog(log);+ console.log(`📝 Updated nicotine on ${date}[${index}]: ${item.product || 'unnamed'} ${item.mgPerUnit}mg x${item.count}`);+ return { item, dayTotal: entry.nicotine.totalMg };+}++export async function removeNicotine(date, index) {+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === date);+ if (!entry?.nicotine?.items?.[index]) return null;++ const removed = entry.nicotine.items.splice(index, 1)[0];++ // Remove nicotine section if empty, else recalculate total+ if (entry.nicotine.items.length === 0) {+ delete entry.nicotine;+ } else {+ recalcDayTotal(entry);+ }++ await saveDailyLog(log);+ return removed;+}++// === Custom Product Buttons ===++async function loadCustomProducts() {+ const data = await readJSONFile(CUSTOM_PRODUCTS_FILE, null, { allowArray: false });+ if (!data || typeof data !== 'object' || Array.isArray(data)) {+ return { products: DEFAULT_PRODUCTS.map(p => ({ ...p })) };+ }+ if (!Array.isArray(data.products)) data.products = [];+ return data;+}++async function saveCustomProducts(data) {+ await ensureDir(MEATSPACE_DIR);+ await writeFile(CUSTOM_PRODUCTS_FILE, JSON.stringify(data, null, 2));+}++export async function getCustomProducts() {+ const data = await loadCustomProducts();+ return data.products || [];+}++export async function addCustomProduct({ name, mgPerUnit }) {+ const data = await loadCustomProducts();+ const product = { name, mgPerUnit };+ data.products.push(product);+ await saveCustomProducts(data);+ console.log(`🚬 Added custom nicotine product: ${name} ${mgPerUnit}mg`);+ return product;+}++export async function updateCustomProduct(index, updates) {+ if (!Number.isInteger(index)) return null;+ const data = await loadCustomProducts();+ if (index < 0 || index >= data.products.length) return null;+ const product = data.products[index];+ if (updates.name !== undefined) product.name = updates.name;+ if (updates.mgPerUnit !== undefined) product.mgPerUnit = updates.mgPerUnit;+ await saveCustomProducts(data);+ console.log(`📝 Updated custom nicotine product [${index}]: ${product.name}`);+ return product;+}++export async function removeCustomProduct(index) {+ if (!Number.isInteger(index)) return null;+ const data = await loadCustomProducts();+ if (index < 0 || index >= data.products.length) return null;+ const removed = data.products.splice(index, 1)[0];+ await saveCustomProducts(data);+ console.log(`🗑️ Removed custom nicotine product: ${removed.name}`);+ return removed;+}++export async function reorderCustomProducts(fromIndex, toIndex) {+ if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex)) return null;+ const data = await loadCustomProducts();+ if (fromIndex < 0 || fromIndex >= data.products.length) return null;+ if (toIndex < 0 || toIndex >= data.products.length) return null;+ const [moved] = data.products.splice(fromIndex, 1);+ data.products.splice(toIndex, 0, moved);+ await saveCustomProducts(data);+ return data.products;+}