Skip to content

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

refactor: share MeatSpace substance event logging (#8419)

[._.]/ Adam Eivy0a50d8f8722a
diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.js
index 37cebaf986..0ff5af2e96 100644
--- a/server/services/meatspaceAlcohol.js
+++ b/server/services/meatspaceAlcohol.js
@@ -5,27 +5,11 @@
* Reads/writes daily-log.json entries for alcohol data.
*/
-import { readFile } from 'fs/promises';
import { join } from 'path';
-import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
-import {
- loadMeatspaceDailyLog,
- mutateDailyLog,
- newDailyLogEvent,
- stampDailyLogEventEdit,
- tombstoneDailyLogEvent
-} from './meatspaceDailyLog.js';
-import {
- isMortalLoomEnabled,
- mlPush,
- mlPatchById,
- mlRemoveById,
- mlIdAtDateIndex
-} from './mortalLoomStore.js';
-
+import { PATHS, readJSONFile, getDateString } from '../lib/fileUtils.js';
+import { createSubstanceLog } from './meatspaceSubstanceLog.js';
const MEATSPACE_DIR = PATHS.meatspace;
const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');
-const CUSTOM_DRINKS_FILE = join(MEATSPACE_DIR, 'custom-drinks.json');
const DEFAULT_DRINK_BUTTONS = [
{ name: 'Modelo Especial (12oz)', oz: 12, abv: 4.4 },
@@ -35,11 +19,6 @@ const DEFAULT_DRINK_BUTTONS = [
{ name: 'N/A Beer (12oz)', oz: 12, abv: 0.4 }
];
-// Cache for rolling averages (invalidated on writes)
-let averageCache = null;
-let averageCacheAt = 0;
-const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
-
// === Pure Functions ===
// 1 standard drink = 0.6 oz pure alcohol = ~14g pure alcohol
@@ -73,7 +52,7 @@ export function computeRollingAverages(entries, sex = 'male') {
.filter(e => e.alcohol?.standardDrinks > 0)
.sort((a, b) => a.date.localeCompare(b.date));
- const allEntries = entries.sort((a, b) => a.date.localeCompare(b.date));
+ const allEntries = [...entries].sort((a, b) => a.date.localeCompare(b.date));
// Today's total
const todayEntry = allEntries.find(e => e.date === today);
@@ -141,251 +120,27 @@ export function computeRollingAverages(entries, sex = 'male') {
};
}
-// === File I/O ===
-
-/**
- * @param {{ strict?: boolean }} [options] - `strict: true` throws when the daily log
- * is present-but-unreadable/corrupt instead of substituting an empty log. Off by
- * default so the UI keeps degrading gracefully; the health-logging COUNT opts in,
- * because a fake 0 there reads as "you have never logged anything" (#2726).
- */
-const loadDailyLog = (options) => loadMeatspaceDailyLog({ ...options, label: 'Alcohol' });
-
-// === Exported Service Functions ===
-
-export async function getAlcoholSummary() {
- const now = Date.now();
- if (averageCache && (now - averageCacheAt < CACHE_TTL_MS)) {
- return averageCache;
- }
-
- const [log, config] = await Promise.all([
- loadDailyLog(),
- // Read-only summary input; mutations of this config belong to meatspace.js.
- readJSONFile(CONFIG_FILE, { sex: 'male' })
- ]);
-
- const averages = computeRollingAverages(log.entries || [], config.sex || 'male');
-
- // Recent drinks (last 7 days)
- const today = getDateString();
- const weekAgo = new Date();
- weekAgo.setDate(weekAgo.getDate() - 7);
- const weekAgoStr = getDateString(weekAgo);
-
- const recentEntries = (log.entries || [])
- .filter(e => e.date >= weekAgoStr && e.date <= today && e.alcohol?.drinks?.length > 0)
- .sort((a, b) => b.date.localeCompare(a.date)); // Newest first
-
- averageCache = { ...averages, recentEntries };
- averageCacheAt = now;
-
- return averageCache;
-}
-
-/**
- * @param {{ strict?: boolean }} [options] - see `loadDailyLog` (#2726).
- */
-export async function getDailyAlcohol(from, to, options) {
- const log = await loadDailyLog(options);
- let entries = (log.entries || []).filter(e => e.alcohol?.drinks?.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 logDrink({ name, oz, abv, count = 1, date }) {
- const targetDate = date || getDateString();
- const standardDrinks = computeStandardDrinks(oz * count, abv);
- const drink = { name: name || '', abv, oz, count };
-
- if (await isMortalLoomEnabled()) {
- await mlPush('alcoholDrinks', { ...drink, date: targetDate });
- averageCache = null;
- const log = await loadDailyLog();
- const entry = log.entries.find(e => e.date === targetDate);
- console.log(`🍺 Logged drink (MortalLoom): ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std) on ${targetDate}`);
- return { drink, standardDrinks, date: targetDate, dayTotal: entry?.alcohol?.standardDrinks || standardDrinks };
- }
-
- const result = await mutateDailyLog((log) => {
- let entry = log.entries.find(e => e.date === targetDate);
- if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }
- if (!entry.alcohol) entry.alcohol = { drinks: [], standardDrinks: 0 };
-
- // Every log is its own event — never fold it into a same-product row. Bumping
- // an existing row's count in place loses one of two concurrent increments when
- // peers merge that row by id (#8143).
- const event = newDailyLogEvent(drink);
- entry.alcohol.drinks.push(event);
-
- recalcAlcoholTotal(entry);
- return { drink: event, standardDrinks, date: targetDate, dayTotal: entry.alcohol.standardDrinks };
- }, { label: 'Alcohol' });
-
- averageCache = null;
- console.log(`🍺 Logged drink: ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std) on ${targetDate}`);
- return result;
-}
-
-function recalcAlcoholTotal(entry) {
- entry.alcohol.standardDrinks = entry.alcohol.drinks.reduce((sum, d) => {
- return sum + computeStandardDrinks((d.oz || 0) * (d.count || 1), d.abv || 0);
- }, 0);
- entry.alcohol.standardDrinks = Math.round(entry.alcohol.standardDrinks * 100) / 100;
-}
-
-export async function updateDrink(date, index, updates) {
- if (await isMortalLoomEnabled()) {
- const id = await mlIdAtDateIndex('alcoholDrinks', date, index);
- if (!id) return null;
- const patch = {};
- for (const k of ['name', 'oz', 'abv', 'count', 'date']) {
- if (updates[k] !== undefined) patch[k] = updates[k];
- }
- const updated = await mlPatchById('alcoholDrinks', id, patch);
- averageCache = null;
- const effectiveDate = updated?.date || date;
- const log = await loadDailyLog();
- const entry = log.entries.find(e => e.date === effectiveDate);
- console.log(`📝 Updated drink (MortalLoom) ${date}[${index}] → ${effectiveDate}: ${updated?.name}`);
- return { drink: { name: updated.name, oz: updated.oz, abv: updated.abv, count: updated.count },
- dayTotal: entry?.alcohol?.standardDrinks || 0,
- date: effectiveDate };
- }
-
- const result = await mutateDailyLog((log) => {
- const entry = log.entries.find(e => e.date === date);
- if (!entry?.alcohol?.drinks?.[index]) return null;
-
- const drink = stampDailyLogEventEdit(entry.alcohol.drinks[index]);
- if (updates.name !== undefined) drink.name = updates.name;
- if (updates.oz !== undefined) drink.oz = updates.oz;
- if (updates.abv !== undefined) drink.abv = updates.abv;
- if (updates.count !== undefined) drink.count = updates.count;
-
- // Move to different date if requested
- const newDate = updates.date;
- if (newDate && newDate !== date) {
- entry.alcohol.drinks.splice(index, 1);
- if (entry.alcohol.drinks.length === 0) {
- delete entry.alcohol;
- // Remove entry entirely if no other data keys remain
- if (Object.keys(entry).length <= 1) {
- log.entries = log.entries.filter(e => e !== entry);
- }
- } else {
- recalcAlcoholTotal(entry);
- }
-
- let targetEntry = log.entries.find(e => e.date === newDate);
- if (!targetEntry) {
- targetEntry = { date: newDate };
- log.entries.push(targetEntry);
- }
- if (!targetEntry.alcohol) targetEntry.alcohol = { drinks: [], standardDrinks: 0 };
- targetEntry.alcohol.drinks.push(drink);
- recalcAlcoholTotal(targetEntry);
-
- log.entries.sort((a, b) => a.date.localeCompare(b.date));
- log.lastEntryDate = log.entries[log.entries.length - 1].date;
-
- return { drink, dayTotal: targetEntry.alcohol.standardDrinks, date: newDate };
- }
-
- recalcAlcoholTotal(entry);
- return { drink, dayTotal: entry.alcohol.standardDrinks };
- }, { label: 'Alcohol' });
-
- if (!result) return null;
- averageCache = null;
- const drinkLabel = `${result.drink?.name || 'unnamed'} ${result.drink?.oz}oz @ ${result.drink?.abv}%`;
- if (result.date && result.date !== date) {
- console.log(`📝 Moved drink from ${date}[${index}] to ${result.date}: ${drinkLabel}`);
- } else {
- console.log(`📝 Updated drink on ${date}[${index}]: ${drinkLabel}`);
- }
- return result;
-}
-
-export async function removeDrink(date, index) {
- if (await isMortalLoomEnabled()) {
- const id = await mlIdAtDateIndex('alcoholDrinks', date, index);
- if (!id) return null;
- const removed = await mlRemoveById('alcoholDrinks', id);
- averageCache = null;
- return removed;
- }
-
- const result = await mutateDailyLog((log) => {
- const entry = log.entries.find(e => e.date === date);
- if (!entry?.alcohol?.drinks?.[index]) return null;
-
- const removed = entry.alcohol.drinks.splice(index, 1)[0];
- tombstoneDailyLogEvent(log, removed);
- if (entry.alcohol.drinks.length === 0) delete entry.alcohol;
- else recalcAlcoholTotal(entry);
- return removed;
- }, { label: 'Alcohol' });
-
- if (!result) return null;
- averageCache = null;
- console.log(`🗑️ Removed drink from ${date}[${index}]: ${result.name || 'unnamed'} ${result.oz}oz @ ${result.abv}%`);
- return result;
-}
-
-// === Custom Drink Buttons ===
-
-async function loadCustomDrinks() {
- const data = await readJSONFile(CUSTOM_DRINKS_FILE, null, { allowArray: false, strict: true });
- if (!data || typeof data !== 'object' || Array.isArray(data)) {
- // Return defaults in-memory without writing — persist only on explicit mutations
- return { drinks: DEFAULT_DRINK_BUTTONS.map(d => ({ ...d })) };
- }
- if (!Array.isArray(data.drinks)) data.drinks = [];
- return data;
-}
-
-async function saveCustomDrinks(data) {
- await ensureDir(MEATSPACE_DIR);
- await atomicWrite(CUSTOM_DRINKS_FILE, data);
-}
-
-export async function getCustomDrinks() {
- const data = await loadCustomDrinks();
- return data.drinks || [];
-}
-
-export async function addCustomDrink({ name, oz, abv }) {
- const data = await loadCustomDrinks();
- const drink = { name, oz, abv };
- data.drinks.push(drink);
- await saveCustomDrinks(data);
- console.log(`🍺 Added custom drink button: ${name} ${oz}oz @ ${abv}%`);
- return drink;
-}
-
-export async function updateCustomDrink(index, updates) {
- if (!Number.isInteger(index)) return null;
- const data = await loadCustomDrinks();
- if (index < 0 || index >= data.drinks.length) return null;
- const drink = data.drinks[index];
- if (updates.name !== undefined) drink.name = updates.name;
- if (updates.oz !== undefined) drink.oz = updates.oz;
- if (updates.abv !== undefined) drink.abv = updates.abv;
- await saveCustomDrinks(data);
- console.log(`📝 Updated custom drink button [${index}]: ${drink.name}`);
- return drink;
-}
-
-export async function removeCustomDrink(index) {
- if (!Number.isInteger(index)) return null;
- const data = await loadCustomDrinks();
- if (index < 0 || index >= data.drinks.length) return null;
- const removed = data.drinks.splice(index, 1)[0];
- await saveCustomDrinks(data);
- console.log(`🗑️ Removed custom drink button: ${removed.name}`);
- return removed;
-}
+const substanceLog = createSubstanceLog({
+ key: 'alcohol', itemsField: 'drinks', totalField: 'standardDrinks', mlCollection: 'alcoholDrinks',
+ itemFields: ['name', 'abv', 'oz', 'count'],
+ computeTotal: item => computeStandardDrinks((item.oz || 0) * (item.count || 1), item.abv || 0),
+ computeLogAmount: item => computeStandardDrinks(item.oz * item.count, item.abv),
+ computeAverages: (entries, config) => computeRollingAverages(entries, config?.sex || 'male'),
+ summaryConfig: () => readJSONFile(CONFIG_FILE, { sex: 'male' }),
+ describe: {
+ icon: '🍺', noun: 'drink', amountUnit: 'std',
+ item: item => `${item.name || 'unnamed'} ${item.oz}oz @ ${item.abv}%`,
+ button: item => `${item.name} ${item.oz}oz @ ${item.abv}%`
+ },
+ customButtons: { file: 'custom-drinks.json', field: 'drinks', defaults: DEFAULT_DRINK_BUTTONS, fields: ['name', 'oz', 'abv'] }
+});
+
+export const getAlcoholSummary = substanceLog.summary;
+export const getDailyAlcohol = substanceLog.daily;
+export const logDrink = substanceLog.log;
+export const updateDrink = substanceLog.update;
+export const removeDrink = substanceLog.remove;
+export const getCustomDrinks = substanceLog.getButtons;
+export const addCustomDrink = substanceLog.addButton;
+export const updateCustomDrink = substanceLog.updateButton;
+export const removeCustomDrink = substanceLog.removeButton;
diff --git a/server/services/meatspaceAlcohol.test.js b/server/services/meatspaceAlcohol.test.js
index 5701516bb0..a602994c23 100644
--- a/server/services/meatspaceAlcohol.test.js
+++ b/server/services/meatspaceAlcohol.test.js
@@ -38,70 +38,6 @@ describe('computeStandardDrinks', () => {
});
});
-// =============================================================================
-// UPDATE DRINK TESTS (inline logic mirroring updateDrink service)
-// =============================================================================
-
-describe('updateDrink logic', () => {
- it('updates oz and recalculates standard drinks for the day', () => {
- // Simulate a day entry with two drinks
- const entry = {
- date: '2024-06-15',
- alcohol: {
- drinks: [
- { name: 'Beer', oz: 12, abv: 5, count: 1 },
- { name: 'Wine', oz: 5, abv: 12, count: 1 }
- ],
- standardDrinks: 2 // 1 + 1
- }
- };
-
- // Update first drink oz from 12 to 24 (doubling it)
- const drink = entry.alcohol.drinks[0];
- drink.oz = 24;
-
- // Recalculate total (same logic as updateDrink)
- entry.alcohol.standardDrinks = entry.alcohol.drinks.reduce((sum, d) => {
- return sum + computeStandardDrinks((d.oz || 0) * (d.count || 1), d.abv || 0);
- }, 0);
- entry.alcohol.standardDrinks = Math.round(entry.alcohol.standardDrinks * 100) / 100;
-
- // 24oz @ 5% = 2 std drinks, 5oz @ 12% = 1 std drink => total 3
- expect(entry.alcohol.standardDrinks).toBe(3);
- expect(drink.oz).toBe(24);
- });
-
- it('updates abv and recalculates correctly', () => {
- const entry = {
- date: '2024-06-15',
- alcohol: {
- drinks: [
- { name: 'Mystery', oz: 12, abv: 5, count: 1 }
- ],
- standardDrinks: 1
- }
- };
-
- // Change ABV from 5% to 10%
- entry.alcohol.drinks[0].abv = 10;
-
- entry.alcohol.standardDrinks = entry.alcohol.drinks.reduce((sum, d) => {
- return sum + computeStandardDrinks((d.oz || 0) * (d.count || 1), d.abv || 0);
- }, 0);
- entry.alcohol.standardDrinks = Math.round(entry.alcohol.standardDrinks * 100) / 100;
-
- // 12oz @ 10% = 1.2 pure oz / 0.6 = 2
- expect(entry.alcohol.standardDrinks).toBe(2);
- });
-
- it('updates name without affecting calculations', () => {
- const drink = { name: 'Old Name', oz: 12, abv: 5, count: 1 };
- drink.name = 'New IPA';
- expect(drink.name).toBe('New IPA');
- expect(computeStandardDrinks(drink.oz * drink.count, drink.abv)).toBe(1);
- });
-});
-
// =============================================================================
// ROLLING AVERAGES TESTS
// =============================================================================
@@ -117,6 +53,13 @@ describe('computeRollingAverages', () => {
return getDateString(d);
};
+ it('does not reorder the caller’s entries', () => {
+ const entries = [{ date: daysAgo(0) }, { date: daysAgo(2) }, { date: daysAgo(1) }];
+ const dates = entries.map(entry => entry.date);
+ computeRollingAverages(entries);
+ expect(entries.map(entry => entry.date)).toEqual(dates);
+ });
+
it('returns zeros for empty entries', () => {
const result = computeRollingAverages([]);
expect(result.today).toBe(0);
diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.js
index 0ad08378c9..f2591ecd99 100644
--- a/server/services/meatspaceNicotine.js
+++ b/server/services/meatspaceNicotine.js
@@ -5,35 +5,13 @@
* Stores data in the shared daily-log.json under the `nicotine` key per entry.
*/
-import { join } from 'path';
-import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
-import {
- loadMeatspaceDailyLog,
- mutateDailyLog,
- newDailyLogEvent,
- stampDailyLogEventEdit,
- tombstoneDailyLogEvent
-} from './meatspaceDailyLog.js';
-import {
- isMortalLoomEnabled,
- mlPush,
- mlPatchById,
- mlRemoveById,
- mlIdAtDateIndex
-} from './mortalLoomStore.js';
-
-const MEATSPACE_DIR = PATHS.meatspace;
-const CUSTOM_PRODUCTS_FILE = join(MEATSPACE_DIR, 'custom-nicotine-products.json');
+import { getDateString } from '../lib/fileUtils.js';
+import { createSubstanceLog } from './meatspaceSubstanceLog.js';
const DEFAULT_PRODUCTS = [
{ name: 'Stokes Pick (5mg)', mgPerUnit: 5 },
];
-// Cache for rolling averages (invalidated on writes)
-let averageCache = null;
-let averageCacheAt = 0;
-const CACHE_TTL_MS = 5 * 60 * 1000;
-
// === Pure Functions ===
/**
@@ -93,243 +71,26 @@ export function computeRollingAverages(entries) {
};
}
-/**
- * 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 ===
-
-/**
- * @param {{ strict?: boolean }} [options] - `strict: true` throws when the daily log
- * is present-but-unreadable/corrupt instead of substituting an empty log. Off by
- * default so the UI keeps degrading gracefully; the health-logging COUNT opts in,
- * because a fake 0 there reads as "you have never logged anything" (#2726).
- */
-const loadDailyLog = (options) => loadMeatspaceDailyLog({ ...options, label: 'Nicotine' });
-
-// === 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 = getDateString();
- const weekAgo = new Date();
- weekAgo.setDate(weekAgo.getDate() - 7);
- const weekAgoStr = getDateString(weekAgo);
-
- 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;
-}
-
-/**
- * @param {{ strict?: boolean }} [options] - see `loadDailyLog` (#2726).
- */
-export async function getDailyNicotine(from, to, options) {
- const log = await loadDailyLog(options);
- 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 targetDate = date || getDateString();
- const totalMg = Math.round(mgPerUnit * count * 100) / 100;
- const item = { product: product || '', mgPerUnit, count };
-
- if (await isMortalLoomEnabled()) {
- await mlPush('nicotineEntries', { ...item, date: targetDate });
- averageCache = null;
- const log = await loadDailyLog();
- const entry = log.entries.find(e => e.date === targetDate);
- console.log(`🚬 Logged nicotine (MortalLoom): ${product || 'unnamed'} ${mgPerUnit}mg x${count} on ${targetDate}`);
- return { item, totalMg, date: targetDate, dayTotal: entry?.nicotine?.totalMg || totalMg };
- }
-
- const result = await mutateDailyLog((log) => {
- let entry = log.entries.find(e => e.date === targetDate);
- if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }
- if (!entry.nicotine) entry.nicotine = { items: [], totalMg: 0 };
-
- // Every log is its own event (see logDrink, #8143).
- const event = newDailyLogEvent(item);
- entry.nicotine.items.push(event);
- recalcDayTotal(entry);
-
- return { item: event, totalMg, date: targetDate, dayTotal: entry.nicotine.totalMg };
- }, { label: 'Nicotine' });
-
- averageCache = null;
- console.log(`🚬 Logged nicotine: ${product || 'unnamed'} ${mgPerUnit}mg x${count} (${totalMg}mg) on ${targetDate}`);
- return result;
-}
-
-export async function updateNicotine(date, index, updates) {
- if (await isMortalLoomEnabled()) {
- const id = await mlIdAtDateIndex('nicotineEntries', date, index);
- if (!id) return null;
- const patch = {};
- for (const k of ['product', 'mgPerUnit', 'count', 'date']) {
- if (updates[k] !== undefined) patch[k] = updates[k];
- }
- const updated = await mlPatchById('nicotineEntries', id, patch);
- averageCache = null;
- const effectiveDate = updated?.date || date;
- const log = await loadDailyLog();
- const entry = log.entries.find(e => e.date === effectiveDate);
- console.log(`📝 Updated nicotine (MortalLoom) ${date}[${index}] → ${effectiveDate}: ${updated?.product}`);
- return { item: { product: updated.product, mgPerUnit: updated.mgPerUnit, count: updated.count },
- dayTotal: entry?.nicotine?.totalMg || 0,
- date: effectiveDate };
- }
-
- const result = await mutateDailyLog((log) => {
- const entry = log.entries.find(e => e.date === date);
- if (!entry?.nicotine?.items?.[index]) return null;
-
- const item = stampDailyLogEventEdit(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;
-
- // Move to different date if requested
- const newDate = updates.date;
- if (newDate && newDate !== date) {
- entry.nicotine.items.splice(index, 1);
- if (entry.nicotine.items.length === 0) {
- delete entry.nicotine;
- // Remove entry entirely if no other data keys remain
- if (Object.keys(entry).length <= 1) {
- log.entries = log.entries.filter(e => e !== entry);
- }
- } else {
- recalcDayTotal(entry);
- }
-
- let targetEntry = log.entries.find(e => e.date === newDate);
- if (!targetEntry) {
- targetEntry = { date: newDate };
- log.entries.push(targetEntry);
- }
- if (!targetEntry.nicotine) targetEntry.nicotine = { items: [], totalMg: 0 };
- targetEntry.nicotine.items.push(item);
- recalcDayTotal(targetEntry);
-
- log.entries.sort((a, b) => a.date.localeCompare(b.date));
- log.lastEntryDate = log.entries[log.entries.length - 1].date;
-
- return { item, dayTotal: targetEntry.nicotine.totalMg, date: newDate };
- }
-
- recalcDayTotal(entry);
- return { item, dayTotal: entry.nicotine.totalMg };
- }, { label: 'Nicotine' });
-
- if (!result) return null;
- averageCache = null;
- const itemLabel = `${result.item?.product || 'unnamed'} ${result.item?.mgPerUnit}mg x${result.item?.count}`;
- if (result.date && result.date !== date) {
- console.log(`📝 Moved nicotine from ${date}[${index}] to ${result.date}: ${itemLabel}`);
- } else {
- console.log(`📝 Updated nicotine on ${date}[${index}]: ${itemLabel}`);
- }
- return result;
-}
-
-export async function removeNicotine(date, index) {
- if (await isMortalLoomEnabled()) {
- const id = await mlIdAtDateIndex('nicotineEntries', date, index);
- if (!id) return null;
- const removed = await mlRemoveById('nicotineEntries', id);
- averageCache = null;
- return removed;
- }
-
- const result = await mutateDailyLog((log) => {
- 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];
- tombstoneDailyLogEvent(log, removed);
- if (entry.nicotine.items.length === 0) delete entry.nicotine;
- else recalcDayTotal(entry);
- return removed;
- }, { label: 'Nicotine' });
-
- if (!result) return null;
- averageCache = null;
- console.log(`🗑️ Removed nicotine from ${date}[${index}]: ${result.product || 'unnamed'} ${result.mgPerUnit}mg x${result.count}`);
- return result;
-}
-
-// === Custom Product Buttons ===
-
-async function loadCustomProducts() {
- const data = await readJSONFile(CUSTOM_PRODUCTS_FILE, null, { allowArray: false, strict: true });
- 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 atomicWrite(CUSTOM_PRODUCTS_FILE, data);
-}
-
-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;
-}
+const substanceLog = createSubstanceLog({
+ key: 'nicotine', itemsField: 'items', totalField: 'totalMg', mlCollection: 'nicotineEntries',
+ itemFields: ['product', 'mgPerUnit', 'count'],
+ computeTotal: item => (item.mgPerUnit ?? 0) * (item.count ?? 1),
+ computeLogAmount: item => item.mgPerUnit * item.count,
+ computeAverages: entries => computeRollingAverages(entries),
+ describe: {
+ icon: '🚬', noun: 'nicotine', amountUnit: 'mg',
+ item: item => `${item.product || 'unnamed'} ${item.mgPerUnit}mg x${item.count}`,
+ button: item => `${item.name} ${item.mgPerUnit}mg`
+ },
+ customButtons: { file: 'custom-nicotine-products.json', field: 'products', defaults: DEFAULT_PRODUCTS, fields: ['name', 'mgPerUnit'] }
+});
+
+export const getNicotineSummary = substanceLog.summary;
+export const getDailyNicotine = substanceLog.daily;
+export const logNicotine = substanceLog.log;
+export const updateNicotine = substanceLog.update;
+export const removeNicotine = substanceLog.remove;
+export const getCustomProducts = substanceLog.getButtons;
+export const addCustomProduct = substanceLog.addButton;
+export const updateCustomProduct = substanceLog.updateButton;
+export const removeCustomProduct = substanceLog.removeButton;
diff --git a/server/services/meatspaceSubstanceLog.js b/server/services/meatspaceSubstanceLog.js
new file mode 100644
index 0000000000..dee95753e7
--- /dev/null
+++ b/server/services/meatspaceSubstanceLog.js
@@ -0,0 +1,185 @@
+/** Shared event-log workflow for MeatSpace substance records. */
+import { join } from 'path';
+import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
+import { loadMeatspaceDailyLog, mutateDailyLog, newDailyLogEvent, stampDailyLogEventEdit, tombstoneDailyLogEvent } from './meatspaceDailyLog.js';
+import { isMortalLoomEnabled, mlPush, mlPatchById, mlRemoveById, mlIdAtDateIndex } from './mortalLoomStore.js';
+
+export function createSubstanceLog({ key, itemsField, totalField, mlCollection, itemFields, computeTotal, computeLogAmount = computeTotal, describe, customButtons, computeAverages, summaryConfig }) {
+ const label = key[0].toUpperCase() + key.slice(1);
+ const loadDailyLog = (options) => loadMeatspaceDailyLog({ ...options, label });
+ const itemName = key === 'alcohol' ? 'drink' : 'item';
+ let averageCache = null;
+ let averageCacheAt = 0;
+ const invalidate = () => { averageCache = null; };
+ const recalc = (entry) => {
+ entry[key][totalField] = Math.round(entry[key][itemsField].reduce((sum, item) => sum + computeTotal(item), 0) * 100) / 100;
+ };
+ const ensureSubstance = (entry) => {
+ if (!entry[key]) entry[key] = { [itemsField]: [], [totalField]: 0 };
+ return entry[key];
+ };
+
+ async function summary() {
+ const now = Date.now();
+ if (averageCache && now - averageCacheAt < 5 * 60 * 1000) return averageCache;
+ const [log, config] = await Promise.all([loadDailyLog(), summaryConfig?.()]);
+ const entries = log.entries || [];
+ const averages = computeAverages(entries, config);
+ const today = getDateString();
+ const weekAgo = new Date();
+ weekAgo.setDate(weekAgo.getDate() - 7);
+ const weekAgoStr = getDateString(weekAgo);
+ const recentEntries = entries.filter(e => e.date >= weekAgoStr && e.date <= today && e[key]?.[itemsField]?.length > 0)
+ .sort((a, b) => b.date.localeCompare(a.date));
+ averageCache = { ...averages, recentEntries };
+ averageCacheAt = now;
+ return averageCache;
+ }
+
+ async function daily(from, to, options) {
+ const log = await loadDailyLog(options);
+ let entries = (log.entries || []).filter(e => e[key]?.[itemsField]?.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));
+ }
+
+ async function log(input) {
+ const targetDate = input.date || getDateString();
+ const item = Object.fromEntries(itemFields.filter(field => field !== 'date').map(field => [field, input[field]]));
+ if (itemFields.includes('count')) item.count = input.count === undefined ? 1 : input.count;
+ const nameField = itemFields[0];
+ item[nameField] = item[nameField] || '';
+ const amount = Math.round(computeLogAmount(item) * 100) / 100;
+ const amountField = key === 'alcohol' ? 'standardDrinks' : 'totalMg';
+ if (await isMortalLoomEnabled()) {
+ await mlPush(mlCollection, { ...item, date: targetDate });
+ invalidate();
+ const dailyLog = await loadDailyLog();
+ const entry = dailyLog.entries.find(e => e.date === targetDate);
+ console.log(`${describe.icon} Logged ${describe.noun} (MortalLoom): ${describe.item(item)} on ${targetDate}`);
+ return { [itemName]: item, [amountField]: amount, date: targetDate, dayTotal: entry?.[key]?.[totalField] || amount };
+ }
+ const result = await mutateDailyLog((dailyLog) => {
+ let entry = dailyLog.entries.find(e => e.date === targetDate);
+ if (!entry) { entry = { date: targetDate }; dailyLog.entries.push(entry); }
+ const substance = ensureSubstance(entry);
+ const event = newDailyLogEvent(item);
+ substance[itemsField].push(event);
+ recalc(entry);
+ return { [itemName]: event, [amountField]: amount, date: targetDate, dayTotal: substance[totalField] };
+ }, { label });
+ invalidate();
+ console.log(`${describe.icon} Logged ${describe.noun}: ${describe.item(item)} (${amount} ${describe.amountUnit}) on ${targetDate}`);
+ return result;
+ }
+
+ async function update(date, index, updates) {
+ if (await isMortalLoomEnabled()) {
+ const id = await mlIdAtDateIndex(mlCollection, date, index);
+ if (!id) return null;
+ const patch = {};
+ for (const field of [...itemFields, 'date']) if (updates[field] !== undefined) patch[field] = updates[field];
+ const updated = await mlPatchById(mlCollection, id, patch);
+ invalidate();
+ const effectiveDate = updated?.date || date;
+ const dailyLog = await loadDailyLog();
+ const entry = dailyLog.entries.find(e => e.date === effectiveDate);
+ console.log(`📝 Updated ${describe.noun} (MortalLoom) ${date}[${index}] → ${effectiveDate}: ${updated?.[itemFields[0]]}`);
+ return { [itemName]: Object.fromEntries(itemFields.map(field => [field, updated[field]])), dayTotal: entry?.[key]?.[totalField] || 0, date: effectiveDate };
+ }
+ const result = await mutateDailyLog((dailyLog) => {
+ const entry = dailyLog.entries.find(e => e.date === date);
+ if (!entry?.[key]?.[itemsField]?.[index]) return null;
+ const item = stampDailyLogEventEdit(entry[key][itemsField][index]);
+ for (const field of itemFields) if (updates[field] !== undefined) item[field] = updates[field];
+ const newDate = updates.date;
+ if (newDate && newDate !== date) {
+ entry[key][itemsField].splice(index, 1);
+ if (entry[key][itemsField].length === 0) {
+ delete entry[key];
+ if (Object.keys(entry).length <= 1) dailyLog.entries = dailyLog.entries.filter(e => e !== entry);
+ } else recalc(entry);
+ let targetEntry = dailyLog.entries.find(e => e.date === newDate);
+ if (!targetEntry) { targetEntry = { date: newDate }; dailyLog.entries.push(targetEntry); }
+ ensureSubstance(targetEntry)[itemsField].push(item);
+ recalc(targetEntry);
+ dailyLog.entries.sort((a, b) => a.date.localeCompare(b.date));
+ dailyLog.lastEntryDate = dailyLog.entries[dailyLog.entries.length - 1].date;
+ return { [itemName]: item, dayTotal: targetEntry[key][totalField], date: newDate };
+ }
+ recalc(entry);
+ return { [itemName]: item, dayTotal: entry[key][totalField] };
+ }, { label });
+ if (!result) return null;
+ invalidate();
+ console.log(`📝 ${result.date && result.date !== date ? 'Moved' : 'Updated'} ${describe.noun} ${result.date && result.date !== date ? `from ${date}[${index}] to ${result.date}` : `on ${date}[${index}]`}: ${describe.item(result[itemName])}`);
+ return result;
+ }
+
+ async function remove(date, index) {
+ if (await isMortalLoomEnabled()) {
+ const id = await mlIdAtDateIndex(mlCollection, date, index);
+ if (!id) return null;
+ const removed = await mlRemoveById(mlCollection, id);
+ invalidate();
+ return removed;
+ }
+ const result = await mutateDailyLog((dailyLog) => {
+ const entry = dailyLog.entries.find(e => e.date === date);
+ if (!entry?.[key]?.[itemsField]?.[index]) return null;
+ const removed = entry[key][itemsField].splice(index, 1)[0];
+ tombstoneDailyLogEvent(dailyLog, removed);
+ if (entry[key][itemsField].length === 0) delete entry[key];
+ else recalc(entry);
+ return removed;
+ }, { label });
+ if (!result) return null;
+ invalidate();
+ console.log(`🗑️ Removed ${describe.noun} from ${date}[${index}]: ${describe.item(result)}`);
+ return result;
+ }
+
+ const buttonsFile = join(PATHS.meatspace, customButtons.file);
+ async function loadButtons() {
+ const data = await readJSONFile(buttonsFile, null, { allowArray: false, strict: true });
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
+ return { [customButtons.field]: customButtons.defaults.map(item => ({ ...item })) };
+ }
+ if (!Array.isArray(data[customButtons.field])) data[customButtons.field] = [];
+ return data;
+ }
+ async function saveButtons(data) {
+ await ensureDir(PATHS.meatspace);
+ await atomicWrite(buttonsFile, data);
+ }
+ async function getButtons() { return (await loadButtons())[customButtons.field] || []; }
+ async function addButton(input) {
+ const data = await loadButtons();
+ const item = Object.fromEntries(customButtons.fields.map(field => [field, input[field]]));
+ data[customButtons.field].push(item);
+ await saveButtons(data);
+ console.log(`${describe.icon} Added custom ${describe.noun} button: ${describe.button(item)}`);
+ return item;
+ }
+ async function updateButton(index, updates) {
+ if (!Number.isInteger(index)) return null;
+ const data = await loadButtons();
+ if (index < 0 || index >= data[customButtons.field].length) return null;
+ const item = data[customButtons.field][index];
+ for (const field of customButtons.fields) if (updates[field] !== undefined) item[field] = updates[field];
+ await saveButtons(data);
+ console.log(`📝 Updated custom ${describe.noun} button [${index}]: ${item.name}`);
+ return item;
+ }
+ async function removeButton(index) {
+ if (!Number.isInteger(index)) return null;
+ const data = await loadButtons();
+ if (index < 0 || index >= data[customButtons.field].length) return null;
+ const removed = data[customButtons.field].splice(index, 1)[0];
+ await saveButtons(data);
+ console.log(`🗑️ Removed custom ${describe.noun} button: ${removed.name}`);
+ return removed;
+ }
+ return { summary, daily, log, update, remove, getButtons, addButton, updateButton, removeButton };
+}
diff --git a/server/services/meatspaceSubstanceLog.test.js b/server/services/meatspaceSubstanceLog.test.js
new file mode 100644
index 0000000000..8a7f553421
--- /dev/null
+++ b/server/services/meatspaceSubstanceLog.test.js
@@ -0,0 +1,119 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ readJSONFile: vi.fn(),
+ getDateString: vi.fn(() => '2024-06-01'),
+ PATHS: { root: '/mock', data: '/mock/data', meatspace: '/mock/data/meatspace' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn().mockResolvedValue(undefined)
+}));
+vi.mock('./mortalLoomStore.js', () => ({
+ isMortalLoomEnabled: vi.fn().mockResolvedValue(false),
+ readDailyLogIfEnabled: vi.fn().mockResolvedValue(null),
+ mlArrayIfEnabled: vi.fn().mockResolvedValue(null),
+ mlPush: vi.fn(), mlPatchById: vi.fn(), mlRemoveById: vi.fn(), mlIdAtDateIndex: vi.fn()
+}));
+
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import { isMortalLoomEnabled, readDailyLogIfEnabled, mlPush, mlPatchById, mlRemoveById, mlIdAtDateIndex } from './mortalLoomStore.js';
+import * as alcohol from './meatspaceAlcohol.js';
+import * as nicotine from './meatspaceNicotine.js';
+
+const cases = [
+ {
+ name: 'alcohol', key: 'alcohol', items: 'drinks', total: 'standardDrinks', result: 'drink',
+ input: { name: 'Example Lager', oz: 12, abv: 5, count: 1, date: '2024-06-01' },
+ update: { oz: 24 }, movedTotal: 2,
+ log: alcohol.logDrink, edit: alcohol.updateDrink, remove: alcohol.removeDrink,
+ persisted: { name: 'Example Lager', abv: 5, oz: 12, count: 1 },
+ buttons: { get: alcohol.getCustomDrinks, add: alcohol.addCustomDrink, edit: alcohol.updateCustomDrink, remove: alcohol.removeCustomDrink, field: 'drinks', input: { name: 'Example Beer', oz: 12, abv: 5 } },
+ collection: 'alcoholDrinks', zeroAmount: 0
+ },
+ {
+ name: 'nicotine', key: 'nicotine', items: 'items', total: 'totalMg', result: 'item',
+ input: { product: 'Example Pouch', mgPerUnit: 3, count: 1, date: '2024-06-01' },
+ update: { mgPerUnit: 4 }, movedTotal: 4,
+ log: nicotine.logNicotine, edit: nicotine.updateNicotine, remove: nicotine.removeNicotine,
+ persisted: { product: 'Example Pouch', mgPerUnit: 3, count: 1 },
+ buttons: { get: nicotine.getCustomProducts, add: nicotine.addCustomProduct, edit: nicotine.updateCustomProduct, remove: nicotine.removeCustomProduct, field: 'products', input: { name: 'Example Pouch', mgPerUnit: 3 } },
+ collection: 'nicotineEntries', zeroAmount: 0
+ }
+];
+
+let store;
+beforeEach(() => {
+ vi.clearAllMocks();
+ store = { entries: [], lastEntryDate: null };
+ readJSONFile.mockImplementation(async () => structuredClone(store));
+ isMortalLoomEnabled.mockResolvedValue(false);
+ readDailyLogIfEnabled.mockResolvedValue(null);
+ atomicWrite.mockImplementation(async (path, data) => {
+ if (String(path).endsWith('daily-log.json')) store = structuredClone(data);
+ });
+});
+
+describe.each(cases)('$name event log', ({ key, items, total, result, input, update, movedTotal, log, edit, remove, persisted, buttons, collection, zeroAmount }) => {
+ it('keeps each repeated log separate, edits one, moves it, and removes it', async () => {
+ const first = await log(input);
+ const second = await log(input);
+ const day = () => store.entries.find(entry => entry.date === input.date);
+ expect(day()[key][items]).toHaveLength(2);
+ expect(first[result].id).not.toBe(second[result].id);
+ expect(day()[key][items][0]).toMatchObject(persisted);
+ expect(Object.keys(day()[key])).toEqual([items, total]);
+
+ await edit(input.date, 1, update);
+ expect(day()[key][items][0]).toEqual(first[result]);
+ expect(day()[key][items][1]).toMatchObject({ ...persisted, ...update, id: second[result].id });
+
+ const moved = await edit(input.date, 1, { date: '2024-06-02' });
+ expect(moved.date).toBe('2024-06-02');
+ expect(moved.dayTotal).toBe(movedTotal);
+ expect(day()[key][items]).toHaveLength(1);
+ expect(store.entries.find(entry => entry.date === '2024-06-02')[key]).toMatchObject({
+ [items]: [expect.objectContaining({ ...persisted, ...update, id: second[result].id })],
+ [total]: movedTotal
+ });
+ expect(store.lastEntryDate).toBe('2024-06-02');
+
+ const removed = await remove('2024-06-02', 0);
+ expect(removed.id).toBe(second[result].id);
+ expect(store.entries.find(entry => entry.date === '2024-06-02')[key]).toBeUndefined();
+ });
+
+ it('preserves the logged amount for an explicit zero count', async () => {
+ const logged = await log({ ...input, count: 0 });
+ expect(logged[key === 'alcohol' ? 'standardDrinks' : 'totalMg']).toBe(zeroAmount);
+ });
+
+ it('keeps the MortalLoom collection and public return shapes', async () => {
+ isMortalLoomEnabled.mockResolvedValue(true);
+ readDailyLogIfEnabled.mockResolvedValue({ entries: [{ date: input.date, [key]: { [total]: movedTotal } }] });
+ mlIdAtDateIndex.mockResolvedValue('event-id');
+ mlPatchById.mockResolvedValue({ ...persisted, date: '2024-06-02' });
+ mlRemoveById.mockResolvedValue({ ...persisted, id: 'event-id' });
+ expect(await log(input)).toMatchObject({ [result]: persisted, date: input.date });
+ expect(mlPush).toHaveBeenCalledWith(collection, { ...persisted, date: input.date });
+ expect(await edit(input.date, 0, { date: '2024-06-02' })).toMatchObject({
+ [result]: persisted, date: '2024-06-02'
+ });
+ expect(mlPatchById).toHaveBeenCalledWith(collection, 'event-id', { date: '2024-06-02' });
+ expect(await remove(input.date, 0)).toMatchObject(persisted);
+ expect(mlRemoveById).toHaveBeenCalledWith(collection, 'event-id');
+ });
+
+ it('round-trips custom buttons in their existing file shape', async () => {
+ let buttonsStore = { [buttons.field]: [] };
+ readJSONFile.mockImplementation(async path => String(path).endsWith('daily-log.json') ? structuredClone(store) : structuredClone(buttonsStore));
+ atomicWrite.mockImplementation(async (path, data) => {
+ if (!String(path).endsWith('daily-log.json')) buttonsStore = structuredClone(data);
+ });
+ expect(await buttons.add(buttons.input)).toEqual(buttons.input);
+ expect(buttonsStore).toEqual({ [buttons.field]: [buttons.input] });
+ expect(await buttons.get()).toEqual([buttons.input]);
+ expect(await buttons.edit(0, { name: 'Renamed' })).toEqual({ ...buttons.input, name: 'Renamed' });
+ expect(await buttons.remove(0)).toEqual({ ...buttons.input, name: 'Renamed' });
+ expect(buttonsStore).toEqual({ [buttons.field]: [] });
+ });
+});