Files
2026-11-14 17:16:57 +00:00

575 lines
19 KiB
JavaScript

'use strict';
const crypto = require('node:crypto');
const express = require('express');
const { db, getProfile, updateProfile } = require('./db');
const nutrition = require('./nutrition');
const { kcalFromSteps, kcalFromExercise, dailyTargets, imperialToMetric, roundLbWeek, roundLb } = require('./energy');
const { generatePlan } = require('./planner');
const { parseHealthAutoExport } = require('./health-auto-export');
const { RECIPES, MET_PRESETS, STYLES } = require('./seed');
const { version } = require('../package.json');
const router = express.Router();
const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'];
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
function isDate(value) {
if (typeof value !== 'string' || !DATE_RE.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
}
function bad(res, message, status = 400) {
return res.status(status).json({ error: message });
}
function round1(n) {
return Math.round(n * 10) / 10;
}
function roundLb(n) {
return Math.round(Number(n) * 10) / 10;
}
function number(value, { min = 0, max = 100000, fallback = 0 } = {}) {
const n = Number(value);
if (!Number.isFinite(n)) return fallback;
return Math.min(Math.max(n, min), max);
}
function text(value, max = 120) {
return typeof value === 'string' ? value.trim().slice(0, max) : '';
}
function serverToday() {
return new Intl.DateTimeFormat('en-CA', {
timeZone: process.env.TZ || undefined,
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date());
}
function totalsOf(entries) {
const total = { kcal: 0, protein_g: 0, carbs_g: 0, fat_g: 0, fiber_g: 0, sugar_g: 0, sodium_mg: 0 };
for (const entry of entries) {
total.kcal += Number(entry.kcal) || 0;
total.protein_g += Number(entry.protein_g) || 0;
total.carbs_g += Number(entry.carbs_g) || 0;
total.fat_g += Number(entry.fat_g) || 0;
total.fiber_g += Number(entry.fiber_g) || 0;
total.sugar_g += Number(entry.sugar_g) || 0;
total.sodium_mg += Number(entry.sodium_mg) || 0;
}
return {
kcal: Math.round(total.kcal),
protein_g: round1(total.protein_g),
carbs_g: round1(total.carbs_g),
fat_g: round1(total.fat_g),
fiber_g: round1(total.fiber_g),
sugar_g: round1(total.sugar_g),
sodium_mg: Math.round(total.sodium_mg),
};
}
function readPlan(date) {
const rows = db.prepare('SELECT * FROM plan_items WHERE date = ? ORDER BY sort, id').all(date);
if (!rows.length) return null;
const items = rows.map((row) => {
const recipe = RECIPES.find((r) => r.id === row.recipe_id);
return {
...row,
ingredients: recipe ? recipe.ingredients : [],
prep: recipe ? recipe.prep : null,
tags: recipe ? recipe.tags : [],
};
});
return {
style: rows[0].style,
items,
totals: {
kcal: Math.round(items.reduce((sum, item) => sum + item.kcal, 0)),
protein_g: round1(items.reduce((sum, item) => sum + item.protein_g, 0)),
carbs_g: round1(items.reduce((sum, item) => sum + item.carbs_g, 0)),
fat_g: round1(items.reduce((sum, item) => sum + item.fat_g, 0)),
},
};
}
function buildDay(date) {
const profile = getProfile();
const entries = db.prepare('SELECT * FROM entries WHERE date = ? ORDER BY id').all(date);
const activities = db.prepare('SELECT * FROM activities WHERE date = ? ORDER BY id').all(date);
const weight = Number(profile.weight_kg) || 75;
const steps = activities
.filter((activity) => activity.type === 'steps')
.reduce((sum, activity) => sum + (Number(activity.steps) || 0), 0);
const activitiesOut = activities.map((activity) => {
const stored = Number(activity.kcal) || 0;
let kcal;
if (activity.type === 'steps') {
kcal = kcalFromSteps(activity.steps, weight);
} else if (activity.source !== 'manual' && stored > 0) {
// Imported workouts carry measured calories; do not re-estimate them.
kcal = Math.round(stored);
} else {
kcal = kcalFromExercise({ met: activity.met, minutes: activity.minutes, weightKg: weight });
}
return { ...activity, kcal };
});
const exerciseKcal = activitiesOut
.filter((activity) => activity.type === 'exercise')
.reduce((sum, activity) => sum + activity.kcal, 0);
const totals = totalsOf(entries);
const targets = dailyTargets(profile, { steps, exerciseKcal });
return {
date,
profile,
entries,
activities: activitiesOut,
steps,
totals,
targets,
remainingKcal: targets.targetKcal - totals.kcal,
plan: readPlan(date),
};
}
function replaceSteps(date, steps, source = 'manual') {
const weight = Number(getProfile().weight_kg) || 75;
db.prepare("DELETE FROM activities WHERE date = ? AND type = 'steps'").run(date);
db.prepare(
"INSERT INTO activities (date, type, name, steps, kcal, source, created_at) VALUES (?, 'steps', 'Steps', ?, ?, ?, ?)"
).run(date, steps, kcalFromSteps(steps, weight), source, new Date().toISOString());
}
function importWorkouts(workouts, source) {
const now = new Date().toISOString();
const weight = Number(getProfile().weight_kg) || 75;
const insert = db.prepare(
`INSERT OR IGNORE INTO activities
(date, type, name, minutes, met, kcal, source, external_id, created_at)
VALUES (?, 'exercise', ?, ?, ?, ?, ?, ?, ?)`
);
let imported = 0;
for (const workout of workouts) {
if (!workout || !isDate(workout.date)) continue;
const minutes = number(workout.minutes, { min: 0.1, max: 1440 });
if (minutes <= 0) continue;
const met = number(workout.met, { min: 1, max: 30, fallback: 6 });
const name = text(workout.name, 80) || 'Workout';
const providedKcal = number(workout.kcal, { max: 10000 });
const kcal = providedKcal > 0
? Math.round(providedKcal)
: kcalFromExercise({ met, minutes, weightKg: weight });
const externalId = text(workout.externalId, 140) || `${workout.date}:${name}:${minutes}`;
const result = insert.run(workout.date, name, minutes, met, kcal, source, externalId, now);
if (result.changes > 0) imported += 1;
}
return imported;
}
function requireIngestToken(req, res, next) {
const token = process.env.INGEST_TOKEN;
if (!token) {
return bad(res, 'Ingest is disabled. Set INGEST_TOKEN on the server to enable it.', 403);
}
const provided = String(req.get('authorization') || '').replace(/^Bearer\s+/i, '').trim();
const a = Buffer.from(provided);
const b = Buffer.from(token);
if (!provided || a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return bad(res, 'Unauthorized', 401);
}
next();
}
// ---------------------------------------------------------------- meta/profile
router.get('/health', (req, res) => {
res.json({ ok: true, version, uptime: Math.round(process.uptime()) });
});
router.get('/meta', (req, res) => {
const settings = require('./db').getSettings();
const imperial = settings.default_units === 'imperial';
res.json({
metPresets: MET_PRESETS,
styles: STYLES,
meals: MEALS,
source: 'Open Food Facts',
stepIngest: Boolean(process.env.INGEST_TOKEN),
units: {
weight: imperial ? 'lb' : 'kg',
height: imperial ? 'ft_in' : 'cm',
goalRate: imperial ? 'lb_week' : 'kg_week',
protein: 'g',
},
});
});
router.get('/profile', (req, res) => {
const profile = getProfile();
const targets = dailyTargets(profile);
// Expose imperial equivalents for UIs that use pounds/feet/inches.
const imperial = metricToImperial({
weightKg: profile.weight_kg,
heightCm: profile.height_cm,
});
res.json({
profile,
targets,
imperial: {
pounds: imperial.pounds,
feet: imperial.feet,
inches: imperial.inches,
totalInches: imperial.totalInches,
},
});
});
router.put('/profile', (req, res) => {
const body = req.body || {};
// Accept imperial inputs: feet/inches and pounds, plus lbs/week goal rate.
const metric = imperialToMetric({
feet: number(body.feet, { min: 0, max: 8, fallback: 0 }),
inches: number(body.inches, { min: 0, max: 11, fallback: 0 }),
pounds: number(body.pounds, { min: 80, max: 660, fallback: 0 }),
});
const weightKg = body.weight_kg != null
? round1(number(body.weight_kg, { min: 30, max: 300, fallback: 75 }))
: round1(metric.weightKg || 75);
const heightCm = body.height_cm != null
? round1(number(body.height_cm, { min: 100, max: 250, fallback: 175 }))
: round1(metric.heightCm || 175);
// Goal rate: accept lbs/week (new default) or kg/week (legacy).
const rateLbWeekRaw = number(body.rate_lb_week != null ? body.rate_lb_week : body.rate_kg_week, {
min: 0,
max: 7,
fallback: 0.5,
});
const rateLbWeek = roundLbWeek(rateLbWeekRaw);
const profile = updateProfile({
name: text(body.name, 60),
sex: body.sex === 'female' ? 'female' : 'male',
age: Math.round(number(body.age, { min: 13, max: 120, fallback: 30 })),
height_cm: heightCm,
weight_kg: weightKg,
goal: ['lose', 'maintain', 'gain'].includes(body.goal) ? body.goal : 'maintain',
rate_lb_week: rateLbWeek,
diet: STYLES.some((style) => style.id === body.diet) ? body.diet : 'any',
protein_target_g:
body.protein_target_g === '' || body.protein_target_g == null
? null
: Math.round(number(body.protein_target_g, { min: 0, max: 400 })),
onboarded: 1,
});
res.json({ profile, targets: dailyTargets(profile) });
});
// ---------------------------------------------------------------------- days
router.get('/day/:date', (req, res) => {
if (!isDate(req.params.date)) return bad(res, 'date must be YYYY-MM-DD');
res.json(buildDay(req.params.date));
});
// -------------------------------------------------------------------- entries
router.post('/entries', (req, res) => {
const body = req.body || {};
if (!isDate(body.date)) return bad(res, 'date is required as YYYY-MM-DD');
const meal = MEALS.includes(body.meal) ? body.meal : 'snack';
const name = text(body.name, 160);
if (!name) return bad(res, 'name is required');
let grams = null;
let kcal;
let protein = 0;
let carbs = 0;
let fat = 0;
let fiber = 0;
let sugar = 0;
let sodium = 0;
let source = 'manual';
if (body.per100g && typeof body.per100g === 'object' && body.grams != null) {
grams = round1(number(body.grams, { min: 0, max: 5000 }));
if (grams <= 0) return bad(res, 'grams must be greater than 0');
const factor = grams / 100;
const per = body.per100g;
kcal = number(per.kcal, { max: 900 }) * factor;
protein = number(per.protein_g, { max: 100 }) * factor;
carbs = number(per.carbs_g, { max: 100 }) * factor;
fat = number(per.fat_g, { max: 100 }) * factor;
fiber = number(per.fiber_g, { max: 100 }) * factor;
sugar = number(per.sugar_g, { max: 100 }) * factor;
sodium = number(per.sodium_mg, { max: 100000 }) * factor;
source = 'openfoodfacts';
} else {
kcal = number(body.kcal, { max: 5000 });
protein = number(body.protein_g, { max: 500 });
carbs = number(body.carbs_g, { max: 500 });
fat = number(body.fat_g, { max: 500 });
fiber = number(body.fiber_g, { max: 500 });
sugar = number(body.sugar_g, { max: 500 });
sodium = number(body.sodium_mg, { max: 100000 });
}
const result = db.prepare(
`INSERT INTO entries
(date, meal, name, brand, barcode, grams, kcal, protein_g, carbs_g, fat_g,
fiber_g, sugar_g, sodium_mg, image_url, source, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
body.date, meal, name,
text(body.brand, 80) || null,
/^\d{6,14}$/.test(String(body.barcode || '')) ? String(body.barcode) : null,
grams,
Math.round(kcal),
round1(protein), round1(carbs), round1(fat), round1(fiber), round1(sugar),
Math.round(sodium),
typeof body.image_url === 'string' && /^https?:\/\//.test(body.image_url) ? body.image_url.slice(0, 400) : null,
source,
new Date().toISOString()
);
const entry = db.prepare('SELECT * FROM entries WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ entry, day: buildDay(body.date) });
});
router.delete('/entries/:id', (req, res) => {
const id = Number(req.params.id);
const row = db.prepare('SELECT date FROM entries WHERE id = ?').get(id);
if (!row) return bad(res, 'Entry not found', 404);
db.prepare('DELETE FROM entries WHERE id = ?').run(id);
res.json({ day: buildDay(row.date) });
});
// ----------------------------------------------------------------- activities
router.post('/activities', (req, res) => {
const body = req.body || {};
if (!isDate(body.date)) return bad(res, 'date is required as YYYY-MM-DD');
if (body.type === 'steps') {
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
replaceSteps(body.date, steps);
return res.status(201).json({ day: buildDay(body.date) });
}
if (body.type !== 'exercise') return bad(res, 'type must be "steps" or "exercise"');
const minutes = number(body.minutes, { min: 1, max: 1440 });
if (minutes <= 0) return bad(res, 'minutes must be greater than 0');
const met = number(body.met, { min: 1, max: 30, fallback: 5 });
const name = text(body.name, 80) || 'Exercise';
const weight = Number(getProfile().weight_kg) || 75;
db.prepare(
`INSERT INTO activities (date, type, name, minutes, met, kcal, created_at)
VALUES (?, 'exercise', ?, ?, ?, ?, ?)`
).run(body.date, name, minutes, met, kcalFromExercise({ met, minutes, weightKg: weight }), new Date().toISOString());
res.status(201).json({ day: buildDay(body.date) });
});
router.delete('/activities/:id', (req, res) => {
const id = Number(req.params.id);
const row = db.prepare('SELECT date FROM activities WHERE id = ?').get(id);
if (!row) return bad(res, 'Activity not found', 404);
db.prepare('DELETE FROM activities WHERE id = ?').run(id);
res.json({ day: buildDay(row.date) });
});
// Push steps from a phone shortcut. Requires INGEST_TOKEN.
router.post('/ingest/steps', requireIngestToken, (req, res) => {
const body = req.body || {};
const date = body.date || serverToday();
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
if (steps <= 0) return bad(res, 'steps must be a positive number');
replaceSteps(date, steps, 'shortcut');
res.json({ ok: true, date, steps });
});
// Push steps and workouts from a phone shortcut (Apple Health via Shortcuts).
router.post('/ingest/health', requireIngestToken, (req, res) => {
const body = req.body || {};
const date = body.date || serverToday();
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
const workouts = Array.isArray(body.workouts) ? body.workouts.slice(0, 50) : [];
db.exec('BEGIN');
try {
if (steps > 0) replaceSteps(date, steps, 'shortcut');
const imported = importWorkouts(
workouts.map((workout) => ({ ...workout, date: workout.date || date })),
'shortcut'
);
db.exec('COMMIT');
res.json({ ok: true, date, steps, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// Health Auto Export (iOS) REST automation. Handles metrics and/or workouts.
router.post('/ingest/health-auto-export', requireIngestToken, (req, res) => {
const parsed = parseHealthAutoExport(req.body || {});
const days = parsed.days.filter((day) => isDate(day.date));
db.exec('BEGIN');
try {
for (const day of days) {
replaceSteps(day.date, day.steps, 'health-auto-export');
}
const imported = importWorkouts(parsed.workouts, 'health-auto-export');
db.exec('COMMIT');
res.json({ ok: true, stepsDays: days.length, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// Import a parsed Apple Health export from the web app (same-origin, no token).
router.post('/import/apple-health', (req, res) => {
const body = req.body || {};
const days = Array.isArray(body.days) ? body.days.slice(0, 3650) : [];
const workouts = Array.isArray(body.workouts) ? body.workouts.slice(0, 5000) : [];
db.exec('BEGIN');
try {
let stepsDays = 0;
for (const day of days) {
if (!day || !isDate(day.date)) continue;
const steps = Math.round(number(day.steps, { min: 0, max: 200000 }));
if (steps <= 0) continue;
replaceSteps(day.date, steps, 'apple_health');
stepsDays += 1;
}
const imported = importWorkouts(workouts, 'apple_health');
db.exec('COMMIT');
res.json({ stepsDays, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// -------------------------------------------------------------------- planner
router.post('/plan/:date', (req, res) => {
const date = req.params.date;
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const body = req.body || {};
const profile = getProfile();
const requested = body.style;
const style = STYLES.some((s) => s.id === requested)
? requested
: STYLES.some((s) => s.id === profile.diet)
? profile.diet
: 'any';
const day = buildDay(date);
const plan = generatePlan({
date,
targetKcal: day.targets.targetKcal,
proteinTarget: day.targets.protein_g,
style,
recipes: RECIPES,
});
const now = new Date().toISOString();
const insert = db.prepare(
`INSERT INTO plan_items
(date, meal, recipe_id, name, kcal, protein_g, carbs_g, fat_g, servings, style, sort, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`
);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM plan_items WHERE date = ?').run(date);
plan.items.forEach((recipe, index) => {
insert.run(
date, recipe.meal, recipe.id, recipe.name, recipe.kcal, recipe.protein_g,
recipe.carbs_g, recipe.fat_g, style, index, now
);
});
db.exec('COMMIT');
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
res.status(201).json({ plan: readPlan(date), targets: day.targets });
});
router.delete('/plan/:date', (req, res) => {
if (!isDate(req.params.date)) return bad(res, 'date must be YYYY-MM-DD');
db.prepare('DELETE FROM plan_items WHERE date = ?').run(req.params.date);
res.json({ day: buildDay(req.params.date) });
});
router.post('/plan/items/:id/log', (req, res) => {
const id = Number(req.params.id);
const item = db.prepare('SELECT * FROM plan_items WHERE id = ?').get(id);
if (!item) return bad(res, 'Plan item not found', 404);
db.prepare(
`INSERT INTO entries
(date, meal, name, grams, kcal, protein_g, carbs_g, fat_g, fiber_g, sugar_g, sodium_mg, source, created_at)
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, 0, 0, 0, 'plan', ?)`
).run(
item.date, item.meal, item.name, item.kcal, item.protein_g,
item.carbs_g, item.fat_g, new Date().toISOString()
);
db.prepare('DELETE FROM plan_items WHERE id = ?').run(id);
res.json({ day: buildDay(item.date) });
});
// ----------------------------------------------------------------------- food
router.get('/foods/barcode/:code', async (req, res) => {
const product = await nutrition.getProduct(req.params.code);
if (!product) return bad(res, 'No product with that barcode in Open Food Facts.', 404);
res.json({ product });
});
router.get('/foods/search', async (req, res) => {
const query = text(req.query.q, 100);
if (query.length < 2) return bad(res, 'Search needs at least 2 characters.');
const products = await nutrition.searchFoods(query);
res.json({ products, query });
});
module.exports = router;