Initial commit of counter

This commit is contained in:
2026-11-14 17:16:57 +00:00
commit a397c2d3a7
27 changed files with 5196 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { createParser } = require('../public/health');
const XML = `<?xml version="1.0" encoding="UTF-8"?>
<HealthData locale="en_US">
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="iPhone" unit="count"
creationDate="2026-11-06 08:00:00 -0700" startDate="2026-11-06 07:00:00 -0700"
endDate="2026-11-06 08:00:00 -0700" value="1200"/>
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count"
startDate="2026-11-06 09:00:00 -0700" endDate="2026-11-06 10:00:00 -0700" value="800"/>
<Record type="HKQuantityTypeIdentifierActiveEnergyBurned" sourceName="Watch" unit="kcal"
startDate="2026-11-06 09:00:00 -0700" endDate="2026-11-06 10:00:00 -0700" value="450"/>
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="iPhone" unit="count"
startDate="2026-11-05 12:00:00 -0700" endDate="2026-11-05 13:00:00 -0700" value="5000"/>
<Workout workoutActivityType="HKWorkoutActivityTypeRunning" duration="32.5"
totalEnergyBurned="310" startDate="2026-11-06 07:12:00 -0700"
endDate="2026-11-06 07:44:30 -0700"/>
<Workout workoutActivityType="HKWorkoutActivityTypeTraditionalStrengthTraining"
startDate="2026-11-05 18:00:00 -0700" endDate="2026-11-05 18:45:00 -0700"/>
</HealthData>`;
test('sums step records per day and maps workouts', () => {
const parser = createParser({ since: '2026-11-05' });
parser.push(XML);
const result = parser.finish();
assert.deepEqual(
result.days.sort((a, b) => a.date.localeCompare(b.date)),
[{ date: '2026-11-05', steps: 5000 }, { date: '2026-11-06', steps: 2000 }]
);
const running = result.workouts.find((workout) => workout.name === 'Running');
assert.equal(running.kcal, 310);
assert.equal(running.minutes, 32.5);
assert.equal(running.met, 9);
const strength = result.workouts.find((workout) => workout.name === 'Strength training');
assert.equal(strength.kcal, 0);
assert.equal(strength.minutes, 45);
assert.equal(strength.met, 5);
});
test('ignores records before the requested range', () => {
const parser = createParser({ since: '2026-11-06' });
parser.push(XML);
const result = parser.finish();
assert.deepEqual(result.days, [{ date: '2026-11-06', steps: 2000 }]);
assert.equal(result.workouts.length, 1);
});
test('handles tags split across chunks', () => {
const whole = createParser();
whole.push(XML);
const expected = whole.finish();
const chunked = createParser();
for (let offset = 0; offset < XML.length; offset += 97) {
chunked.push(XML.slice(offset, offset + 97));
}
const actual = chunked.finish();
const byDate = (days) => days.sort((a, b) => a.date.localeCompare(b.date));
assert.deepEqual(byDate(actual.days), byDate(expected.days));
assert.equal(actual.workouts.length, expected.workouts.length);
});
+131
View File
@@ -0,0 +1,131 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const {
bmrKcal, kcalFromSteps, kcalFromExercise, dailyTargets,
imperialToMetric, metricToImperial, roundLbWeek,
KCAL_PER_LB, KCAL_PER_KG, LB_PER_KG,
} = require('../server/energy');
test('imperial <-> metric conversions', () => {
const m = imperialToMetric({ feet: 5, inches: 9, pounds: 165 });
assert.equal(m.heightCm, Math.round(69 * 2.54 * 100) / 100);
assert.equal(m.weightKg, Math.round(165 / 2.20462 * 100) / 100);
const imp = metricToImperial({ weightKg: 75, heightCm: 175 });
assert.equal(imp.pounds, Math.round(75 * 2.20462 * 10) / 10);
assert.equal(imp.feet, Math.floor(Math.round(175 / 2.54) / 12));
assert.equal(imp.inches, Math.round(175 / 2.54) % 12);
});
test('Mifflin-St Jeor BMR for men and women (metric inputs)', () => {
assert.equal(bmrKcal({ sex: 'male', weightKg: 75, heightCm: 175, age: 30 }), 1699);
assert.equal(bmrKcal({ sex: 'female', weightKg: 60, heightCm: 165, age: 30 }), 1320);
});
test('BMR from imperial profile rounds to same value', () => {
const m = imperialToMetric({ feet: 5, inches: 9, pounds: 165 });
assert.equal(bmrKcal({ sex: 'male', weightKg: m.weightKg, heightCm: m.heightCm, age: 30 }), 1699);
});
test('step calories scale with body weight', () => {
assert.equal(kcalFromSteps(10000, 75), 375);
assert.equal(kcalFromSteps(10000, 60), 300);
assert.equal(kcalFromSteps(0, 75), 0);
});
test('exercise calories use MET values', () => {
assert.equal(kcalFromExercise({ met: 8, minutes: 45, weightKg: 75 }), 473);
assert.equal(kcalFromExercise({ met: 2.5, minutes: 60, weightKg: 75 }), 197);
});
test('daily targets treat 1.0 lb/week as ~3500 kcal/week deficit', () => {
const profile = {
sex: 'male', weight_kg: 165 * LB_PER_KG, height_cm: (5 * 12 + 9) * 2.54,
age: 30, goal: 'maintain', rate_lb_week: 1.0,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.equal(targets.rateLbWeek, 1);
assert.ok(Math.abs(targets.adjustKcal + 500) <= 1);
});
test('daily targets treat 1.5 lb/week as ~5250 kcal/week deficit', () => {
const profile = {
sex: 'male', weight_kg: 165 * LB_PER_KG, height_cm: (5 * 12 + 9) * 2.54,
age: 30, goal: 'maintain', rate_lb_week: 1.5,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.equal(targets.rateLbWeek, 1.5);
assert.ok(Math.abs(targets.adjustKcal + 750) <= 1);
});
test('daily targets with kg/week still work via rate_kg_week', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'lose', rate_kg_week: 0.5, rate_lb_week: 0, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
// With only rate_kg_week provided, rateLbWeek is the rounded lb equivalent.
assert.ok(Math.abs(targets.rateLbWeek - (0.5 * LB_PER_KG)) < 0.05);
});
test('rate_lb_week is preserved when provided, with kg/week override', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'lose', rate_lb_week: 1.25, rate_kg_week: 0.5, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
// rate_kg_week is also provided, so it wins and rate_lb_week is ignored.
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
assert.ok(Math.abs(targets.rateLbWeek - (0.5 * LB_PER_KG)) < 0.05);
});
test('daily targets add baseline, steps and workouts', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'maintain', rate_lb_week: 0, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 10000, exerciseKcal: 473 });
assert.equal(targets.bmrKcal, 1699);
assert.equal(targets.basalKcal, 2039);
assert.equal(targets.stepKcal, 375);
assert.equal(targets.exerciseKcal, 473);
assert.equal(targets.totalBurnKcal, 2887);
assert.equal(targets.adjustKcal, 0);
assert.equal(targets.targetKcal, 2887);
assert.equal(targets.protein_g, 120);
});
test('a weight-loss goal subtracts the weekly rate and respects the floor', () => {
const profile = {
sex: 'female', weight_kg: 60, height_cm: 165, age: 30,
goal: 'lose', rate_lb_week: 0.5 * 2.20462, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 8000, exerciseKcal: 0 });
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
assert.equal(targets.protein_g, Math.round(60 * 2.0));
assert.ok(targets.targetKcal >= 1200);
});
test('roundLbWeek snaps to nearest 0.5 lb', () => {
assert.equal(roundLbWeek(0.6), 0.5);
assert.equal(roundLbWeek(0.8), 1);
assert.equal(roundLbWeek(1.2), 1);
assert.equal(roundLbWeek(1.3), 1.5);
});
test('KCAL_PER_LB and KCAL_PER_KG are consistent', () => {
assert.equal(KCAL_PER_LB, 3500);
assert.ok(Math.abs(KCAL_PER_KG - 3500 * 2.20462) < 1e-6);
});
test('a custom protein target overrides the default', () => {
const profile = {
sex: 'male', weight_kg: 80, height_cm: 180, age: 40,
goal: 'maintain', rate_lb_week: 0, protein_target_g: 170,
};
assert.equal(dailyTargets(profile).protein_g, 170);
});
+101
View File
@@ -0,0 +1,101 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { parseHealthAutoExport, workoutMeta } = require('../server/health-auto-export');
const PAYLOAD = {
data: {
metrics: [
{
name: 'step_count',
units: 'count',
data: [
{ qty: 1200, date: '2026-11-06 09:00:00 -0700', source: 'iPhone' },
{ qty: 800, date: '2026-11-06 18:30:00 -0700', source: 'Watch' },
{ qty: 5000, date: '2026-11-05 12:00:00 -0700' },
],
},
{
name: 'heart_rate',
units: 'count/min',
data: [{ qty: 70, date: '2026-11-06 09:00:00 -0700' }],
},
],
workouts: [
{
id: '550e8400-e29b-41d4-a716-446655440000',
name: 'Running',
start: '2026-11-06 07:00:00 -0700',
end: '2026-11-06 07:30:00 -0700',
duration: 1800,
activeEnergyBurned: { qty: 350, units: 'kcal' },
},
{
id: 'workout-2',
name: 'Traditional Strength Training',
start: '2026-11-05 18:00:00 -0700',
end: '2026-11-05 18:45:00 -0700',
},
],
},
};
test('sums step samples per local day and ignores other metrics', () => {
const result = parseHealthAutoExport(PAYLOAD);
assert.deepEqual(
result.days.sort((a, b) => a.date.localeCompare(b.date)),
[{ date: '2026-11-05', steps: 5000 }, { date: '2026-11-06', steps: 2000 }]
);
});
test('uses v2 duration seconds and active energy', () => {
const result = parseHealthAutoExport(PAYLOAD);
const running = result.workouts.find((workout) => workout.name === 'Running');
assert.equal(running.minutes, 30);
assert.equal(running.kcal, 350);
assert.equal(running.met, 9);
assert.equal(running.externalId, 'hae:550e8400-e29b-41d4-a716-446655440000');
});
test('derives minutes from start/end and maps strength training', () => {
const result = parseHealthAutoExport(PAYLOAD);
const strength = result.workouts.find((workout) => workout.name === 'Strength training');
assert.equal(strength.minutes, 45);
assert.equal(strength.kcal, 0);
assert.equal(strength.met, 5);
assert.equal(strength.date, '2026-11-05');
});
test('accepts v1 energy fields and an intensity override', () => {
const result = parseHealthAutoExport({
data: {
workouts: [
{
name: 'Indoor Cycling',
start: '2026-11-06 06:00:00 -0800',
end: '2026-11-06 06:20:00 -0800',
activeEnergy: { qty: 180, units: 'kcal' },
intensity: { qty: 7.2, units: 'MET' },
},
],
},
});
assert.equal(result.workouts.length, 1);
assert.equal(result.workouts[0].name, 'Cycling');
assert.equal(result.workouts[0].minutes, 20);
assert.equal(result.workouts[0].kcal, 180);
assert.equal(result.workouts[0].met, 7.2);
});
test('handles payloads without a data wrapper and includes no bogus days', () => {
assert.deepEqual(parseHealthAutoExport({ metrics: [] }), { days: [], workouts: [] });
assert.deepEqual(parseHealthAutoExport(null), { days: [], workouts: [] });
const meta = workoutMeta('Functional Strength Training');
assert.equal(meta.name, 'Strength training');
assert.equal(meta.met, 5);
});
+50
View File
@@ -0,0 +1,50 @@
'use strict';
// Keep the module's SQLite cache out of the project data directory.
process.env.DATA_DIR = `${require('node:os').tmpdir()}/counter-test-${process.pid}`;
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeProduct } = require('../server/nutrition');
test('normalizes a typical Open Food Facts product', () => {
const product = normalizeProduct({
code: '1234567890123',
product_name: 'Test Yogurt',
brands: 'Acme, Other Label',
serving_quantity: '150',
serving_size: '1 pot (150 g)',
nutriments: {
'energy-kcal_100g': 72,
proteins_100g: 8.5,
carbohydrates_100g: 6.2,
fat_100g: 1.4,
fiber_100g: 0.4,
sugars_100g: 5.1,
sodium_100g: 0.05,
},
});
assert.equal(product.name, 'Test Yogurt');
assert.equal(product.brand, 'Acme');
assert.equal(product.servingGrams, 150);
assert.equal(product.per100g.kcal, 72);
assert.equal(product.per100g.protein_g, 8.5);
assert.equal(product.per100g.sodium_mg, 50);
});
test('falls back to kilojoules and salt when needed', () => {
const product = normalizeProduct({
code: '999',
product_name: 'Bread',
nutriments: { 'energy-kj_100g': 418.4, salt_100g: 1 },
});
assert.equal(product.per100g.kcal, 100);
assert.equal(product.per100g.sodium_mg, 400);
});
test('rejects products without usable energy data', () => {
assert.equal(normalizeProduct({ code: '1', product_name: 'Air', nutriments: {} }), null);
assert.equal(normalizeProduct(null), null);
});
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { generatePlan, styleAllows } = require('../server/planner');
const { RECIPES } = require('../server/seed');
test('a plan covers every meal slot with distinct recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2200, proteinTarget: 140, style: 'any', recipes: RECIPES,
});
assert.deepEqual(plan.items.map((item) => item.meal), ['breakfast', 'lunch', 'dinner', 'snack']);
assert.equal(new Set(plan.items.map((item) => item.id)).size, 4);
assert.ok(plan.totals.kcal > 1500 && plan.totals.kcal < 3000, `plan was ${plan.totals.kcal} kcal`);
});
test('the same date always generates the same plan', () => {
const args = {
date: '2026-11-07', targetKcal: 2000, proteinTarget: 120, style: 'any', recipes: RECIPES,
};
assert.deepEqual(
generatePlan(args).items.map((item) => item.id),
generatePlan(args).items.map((item) => item.id)
);
});
test('a vegan plan only contains vegan recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2000, proteinTarget: 100, style: 'vegan', recipes: RECIPES,
});
assert.equal(plan.items.length, 4);
assert.ok(plan.items.every((item) => item.tags.includes('vegan')));
});
test('a high-protein plan favours protein-rich recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2000, proteinTarget: 160, style: 'high_protein', recipes: RECIPES,
});
assert.ok(plan.totals.protein_g > 100);
});
test('style filtering falls back to any recipe when nothing matches', () => {
const onlySnack = RECIPES.filter((recipe) => recipe.meal === 'snack' && recipe.tags.includes('vegan'));
const plan = generatePlan({
date: '2026-11-07', targetKcal: 1800, proteinTarget: 90, style: 'vegetarian', recipes: onlySnack,
});
assert.ok(plan.items.length >= 1);
});
test('styleAllows treats vegan as vegetarian and high protein by macro', () => {
assert.equal(styleAllows({ tags: ['vegan'], protein_g: 10 }, 'vegetarian'), true);
assert.equal(styleAllows({ tags: [], protein_g: 30 }, 'high_protein'), true);
assert.equal(styleAllows({ tags: ['vegetarian'], protein_g: 10 }, 'vegan'), false);
});