Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE `WeightGoal` (
`userId` VARCHAR(191) NOT NULL,
`targetKg` DECIMAL(6, 2) NOT NULL,
`startKg` DECIMAL(6, 2) NOT NULL,
`setAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updatedAt` DATETIME(3) NOT NULL,

PRIMARY KEY (`userId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `WeightGoal` ADD CONSTRAINT `WeightGoal_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
12 changes: 12 additions & 0 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ model User {
dailyGoals DailyGoal[]
diaryEntries DiaryEntry[]
weights WeightEntry[]
weightGoal WeightGoal?
foods Food[] @relation("FoodOwner")
verifiedFoods Food[] @relation("VerifiedBy")
fastingSettings FastingSettings?
Expand Down Expand Up @@ -191,6 +192,17 @@ model WeightEntry {
@@index([userId, loggedAt])
}

// The weight the user is working towards. startKg is where they stood when
// the goal was set, so progress can be shown as a share of the way there.
model WeightGoal {
userId String @id
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
targetKg Decimal @db.Decimal(6, 2)
startKg Decimal @db.Decimal(6, 2)
setAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model HealthSettings {
userId String @id
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
Expand Down
81 changes: 81 additions & 0 deletions apps/api/src/domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
validatePassword,
weightChangeKg,
weightForGoal,
weightTrend,
} from "./domain.js";
import { DEFAULT_USER_PERMISSIONS, OPERATIONS, resolvePermissions } from "./rbac.js";
import { changePasswordSchema, fastingSchema, foodSchema, healthSettingsSchema, healthSyncSchema, profileSchema, signupSchema } from "./schemas.js";
Expand Down Expand Up @@ -522,3 +523,83 @@ test("Apple Health sync payloads are validated and default to empty lists", () =
assert.equal(healthSettingsSchema.safeParse({ exerciseGoalMinutes: 30, stepGoal: 10000 }).success, true);
assert.equal(healthSettingsSchema.safeParse({ exerciseGoalMinutes: 0, stepGoal: 10000 }).success, false);
});

const trendNow = new Date("2026-11-15T10:00:00.000Z");
function weighIn(daysAgo: number, weightKg: number) {
return { loggedAt: new Date(trendNow.getTime() - daysAgo * 86400000), weightKg };
}

test("weight trend fits recent weigh-ins and projects when the goal is reached", () => {
// Exactly 0.1 kg lost per day: 82 → 80 over 20 days, 5 kg left to 75.
const trend = weightTrend({
weights: [weighIn(20, 82), weighIn(10, 81), weighIn(0, 80)],
targetKg: 75,
startKg: 82,
now: trendNow,
});
assert.equal(trend.status, "on_track");
assert.equal(trend.currentKg, 80);
assert.equal(trend.remainingKg, 5);
assert.equal(trend.ratePerWeekKg, -0.7);
assert.equal(trend.progress, 0.29);
assert.equal(Math.round((trend.etaAt!.getTime() - trendNow.getTime()) / 86400000), 50);
assert.equal(trend.line!.fromKg, 82);
});

test("weight trend ignores weigh-ins older than the recent window", () => {
// A big drop months ago must not speed up today's slow pace.
const trend = weightTrend({
weights: [weighIn(200, 100), weighIn(28, 81.4), weighIn(14, 81.2), weighIn(0, 81)],
targetKg: 80,
startKg: 100,
now: trendNow,
});
assert.equal(trend.ratePerWeekKg, -0.1);
assert.equal(Math.round((trend.etaAt!.getTime() - trendNow.getTime()) / 86400000), 70);
});

test("weight trend widens the window when the last month is too thin", () => {
const trend = weightTrend({
weights: [weighIn(60, 84), weighIn(2, 81.1)],
targetKg: 78,
startKg: 84,
now: trendNow,
});
assert.equal(trend.status, "on_track");
assert.equal(trend.ratePerWeekKg, -0.35);
});

test("weight trend needs a week of weigh-ins before it estimates", () => {
const few = weightTrend({ weights: [weighIn(3, 81), weighIn(0, 80)], targetKg: 75, startKg: 81, now: trendNow });
assert.equal(few.status, "need_data");
assert.equal(few.etaAt, null);
assert.equal(few.line, null);
const none = weightTrend({ weights: [], targetKg: 75, startKg: 81, now: trendNow });
assert.equal(none.status, "need_data");
assert.equal(none.currentKg, 81);
assert.equal(none.progress, 0);
});

test("weight trend is off track when moving away from, or barely towards, the goal", () => {
const away = weightTrend({ weights: [weighIn(14, 80), weighIn(0, 81)], targetKg: 75, startKg: 80, now: trendNow });
assert.equal(away.status, "off_track");
assert.equal(away.ratePerWeekKg, 0.5);
assert.equal(away.etaAt, null);
assert.equal(away.progress, 0);
const flat = weightTrend({ weights: [weighIn(14, 80), weighIn(0, 80)], targetKg: 75, startKg: 80, now: trendNow });
assert.equal(flat.status, "off_track");
const crawl = weightTrend({ weights: [weighIn(28, 80.04), weighIn(0, 80)], targetKg: 70, startKg: 80.04, now: trendNow });
assert.equal(crawl.status, "off_track");
});

test("weight trend reports a reached goal in either direction", () => {
const lost = weightTrend({ weights: [weighIn(14, 76), weighIn(0, 74.8)], targetKg: 75, startKg: 80, now: trendNow });
assert.equal(lost.status, "reached");
assert.equal(lost.remainingKg, 0);
assert.equal(lost.progress, 1);
const gaining = weightTrend({ weights: [weighIn(14, 60), weighIn(0, 61)], targetKg: 65, startKg: 60, now: trendNow });
assert.equal(gaining.status, "on_track");
assert.equal(gaining.ratePerWeekKg, 0.5);
const gained = weightTrend({ weights: [weighIn(0, 65.2)], targetKg: 65, startKg: 60, now: trendNow });
assert.equal(gained.status, "reached");
});
90 changes: 90 additions & 0 deletions apps/api/src/domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,96 @@ export function weightChangeKg(input: {
return round2(inWeek[0].weightKg - before[0].weightKg);
}

export type WeightTrendStatus = "need_data" | "on_track" | "off_track" | "reached";

export type WeightTrend = {
status: WeightTrendStatus;
/** Latest weigh-in, or the goal's start weight when there is none. */
currentKg: number;
/** Distance left to the target, never negative. */
remainingKg: number;
/** Share of the way from the start weight to the target, 0 to 1. */
progress: number;
/** Signed change per week along the fitted line. Null without enough weigh-ins. */
ratePerWeekKg: number | null;
/** When the fitted line reaches the target. Only set when on track. */
etaAt: Date | null;
/** The fitted line, for drawing: weight at `fromAt` and its change per day. */
line: { fromAt: Date; fromKg: number; perDayKg: number } | null;
};

const DAY_MS = 24 * 60 * 60 * 1000;
/** Recent weigh-ins describe the current pace; widen only when they are too few. */
const TREND_WINDOWS_DAYS = [30, 90];
/** Day-to-day swings (water, food) drown out real change over less than a week. */
const TREND_MIN_SPAN_DAYS = 7;
/** An arrival further out than this is not a useful estimate. */
const TREND_MAX_ETA_DAYS = 3 * 365;

function fitLine(points: { t: number; kg: number }[]): { slope: number; at: (t: number) => number } {
const meanT = points.reduce((sum, point) => sum + point.t, 0) / points.length;
const meanKg = points.reduce((sum, point) => sum + point.kg, 0) / points.length;
let covariance = 0;
let variance = 0;
for (const point of points) {
covariance += (point.t - meanT) * (point.kg - meanKg);
variance += (point.t - meanT) ** 2;
}
const slope = variance === 0 ? 0 : covariance / variance;
return { slope, at: (t) => meanKg + slope * (t - meanT) };
}

/**
* Where the user stands against their weight goal. The pace is a least-squares
* line through recent weigh-ins, so one unusual reading does not swing the ETA.
*/
export function weightTrend(input: {
weights: { loggedAt: Date; weightKg: number }[];
targetKg: number;
startKg: number;
now: Date;
}): WeightTrend {
const now = input.now.getTime();
const past = input.weights
.filter((entry) => entry.loggedAt.getTime() <= now)
.sort((a, b) => a.loggedAt.getTime() - b.loggedAt.getTime());
const currentKg = past.length > 0 ? past[past.length - 1].weightKg : input.startKg;
const direction = Math.sign(input.targetKg - input.startKg);
const reached = direction <= 0 ? currentKg <= input.targetKg : currentKg >= input.targetKg;
const total = Math.abs(input.targetKg - input.startKg);
const remainingKg = reached ? 0 : round2(Math.abs(input.targetKg - currentKg));
const progress = reached || total === 0 ? 1 : Math.min(1, Math.max(0, 1 - Math.abs(input.targetKg - currentKg) / total));

let window: typeof past = [];
for (const days of TREND_WINDOWS_DAYS) {
window = past.filter((entry) => entry.loggedAt.getTime() >= now - days * DAY_MS);
if (window.length >= 2) {
const span = window[window.length - 1].loggedAt.getTime() - window[0].loggedAt.getTime();
if (span >= TREND_MIN_SPAN_DAYS * DAY_MS) break;
}
window = [];
}
const base = { currentKg, remainingKg, progress: round2(progress) };
if (window.length === 0) {
return { ...base, status: reached ? "reached" : "need_data", ratePerWeekKg: null, etaAt: null, line: null };
}

const fromAt = window[0].loggedAt;
// Days since the first weigh-in in the window keep the sums small and exact enough.
const fit = fitLine(window.map((entry) => ({ t: (entry.loggedAt.getTime() - fromAt.getTime()) / DAY_MS, kg: entry.weightKg })));
const line = { fromAt, fromKg: round2(fit.at(0)), perDayKg: fit.slope };
const ratePerWeekKg = round2(fit.slope * 7);
if (reached) return { ...base, status: "reached", ratePerWeekKg, etaAt: null, line };

const nowDays = (now - fromAt.getTime()) / DAY_MS;
const daysLeft = fit.slope === 0 ? Infinity : Math.max(0, (input.targetKg - fit.at(nowDays)) / fit.slope);
const towards = fit.slope * direction > 0;
if (!towards || daysLeft > TREND_MAX_ETA_DAYS) {
return { ...base, status: "off_track", ratePerWeekKg, etaAt: null, line };
}
return { ...base, status: "on_track", ratePerWeekKg, etaAt: new Date(now + daysLeft * DAY_MS), line };
}

export type PasswordChecks = {
length: boolean;
english: boolean;
Expand Down
101 changes: 87 additions & 14 deletions apps/api/src/routes/weights.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,60 @@
import { Router } from "express";
import { currentUser, requireUser } from "../auth.js";
import { prisma } from "../db.js";
import { weightTrend } from "../domain.js";
import { asyncRoute } from "../http.js";
import { num } from "../present.js";
import { requirePermission } from "../rbac.js";
import { weightSchema } from "../schemas.js";
import { weightGoalSchema, weightSchema } from "../schemas.js";
import { jerusalemDay } from "../time.js";

export const weightsRouter = Router();
weightsRouter.use(requireUser);

/** Weigh-ins plus the goal and how the user is trending towards it. */
async function weightOverview(userId: string) {
const [rows, goal] = await Promise.all([
prisma.weightEntry.findMany({ where: { userId }, orderBy: { loggedAt: "asc" } }),
prisma.weightGoal.findUnique({ where: { userId } }),
]);
const weights = rows.map((entry) => ({
id: entry.id,
weightKg: num(entry.weightKg),
loggedAt: entry.loggedAt.toISOString(),
source: entry.source,
}));
if (!goal) return { weights, goal: null, trend: null };
const trend = weightTrend({
weights: rows.map((entry) => ({ loggedAt: entry.loggedAt, weightKg: num(entry.weightKg) })),
targetKg: num(goal.targetKg),
startKg: num(goal.startKg),
now: new Date(),
});
return {
weights,
goal: { targetKg: num(goal.targetKg), startKg: num(goal.startKg), setAt: goal.setAt.toISOString() },
trend: {
status: trend.status,
currentKg: trend.currentKg,
remainingKg: trend.remainingKg,
progress: trend.progress,
ratePerWeekKg: trend.ratePerWeekKg,
etaAt: trend.etaAt?.toISOString() ?? null,
etaDay: trend.etaAt ? jerusalemDay(trend.etaAt) : null,
line: trend.line && {
fromAt: trend.line.fromAt.toISOString(),
fromKg: trend.line.fromKg,
perDayKg: trend.line.perDayKg,
},
},
};
}

weightsRouter.get(
"/",
requirePermission("weights:read"),
asyncRoute(async (_req, res) => {
const user = currentUser(res);
const rows = await prisma.weightEntry.findMany({
where: { userId: user.id },
orderBy: { loggedAt: "asc" },
});
res.json({
weights: rows.map((entry) => ({
id: entry.id,
weightKg: num(entry.weightKg),
loggedAt: entry.loggedAt.toISOString(),
source: entry.source,
})),
});
res.json(await weightOverview(currentUser(res).id));
}),
);

Expand All @@ -52,3 +81,47 @@ weightsRouter.post(
});
}),
);

weightsRouter.put(
"/goal",
requirePermission("weights:create"),
asyncRoute(async (req, res) => {
const user = currentUser(res);
const body = weightGoalSchema.parse(req.body);
const [existing, latest, profile] = await Promise.all([
prisma.weightGoal.findUnique({ where: { userId: user.id } }),
prisma.weightEntry.findFirst({
where: { userId: user.id, loggedAt: { lte: new Date() } },
orderBy: { loggedAt: "desc" },
}),
prisma.profile.findUnique({ where: { userId: user.id } }),
]);
// Moving the target further along the same way keeps the progress made so far;
// a goal in the other direction (or a first goal) starts from today's weight.
const sameWay =
existing != null &&
Math.sign(body.targetKg - num(existing.startKg)) === Math.sign(num(existing.targetKg) - num(existing.startKg)) &&
body.targetKg !== num(existing.startKg);
if (sameWay) {
await prisma.weightGoal.update({ where: { userId: user.id }, data: { targetKg: body.targetKg } });
} else {
const startKg = latest ? num(latest.weightKg) : profile ? num(profile.weightKg) : body.targetKg;
await prisma.weightGoal.upsert({
where: { userId: user.id },
create: { userId: user.id, targetKg: body.targetKg, startKg },
update: { targetKg: body.targetKg, startKg, setAt: new Date() },
});
}
res.json(await weightOverview(user.id));
}),
);

weightsRouter.delete(
"/goal",
requirePermission("weights:create"),
asyncRoute(async (_req, res) => {
const user = currentUser(res);
await prisma.weightGoal.deleteMany({ where: { userId: user.id } });
res.json(await weightOverview(user.id));
}),
);
4 changes: 4 additions & 0 deletions apps/api/src/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ export const weightSchema = z.object({
loggedAt: z.string().datetime().optional(),
});

export const weightGoalSchema = z.object({
targetKg: z.number().gt(0).max(500),
});

export const healthSettingsSchema = z.object({
exerciseGoalMinutes: z.number().int().min(1).max(1440),
stepGoal: z.number().int().min(100).max(200000),
Expand Down
17 changes: 17 additions & 0 deletions apps/mobile/ios/Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,22 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
# libtesseract has no Apple Silicon simulator slice, so nothing that calls it
# can link there. Leave that code out on that one platform so the app still
# runs; label scanning reports itself unavailable (see the plugin's Swift file).
if target.name == 'SwiftyTesseract'
target.build_configurations.each do |config|
config.build_settings['EXCLUDED_SOURCE_FILE_NAMES[sdk=iphonesimulator*][arch=arm64]'] = 'SwiftyTesseract.swift SwiftyTesseractError.swift'
end
end
end
# SwiftyTesseract answers the missing slice by excluding arm64 from every
# simulator build, which leaves an Intel-only app that current simulators
# refuse to install. Drop that exclusion now that the code is left out instead.
support_files = File.join(installer.sandbox.root.to_s, 'Target Support Files')
Dir.glob(File.join(support_files, '{Pods-Runner*,SwiftyTesseract}', '*.xcconfig')).each do |path|
text = File.read(path)
kept = text.gsub(/^EXCLUDED_ARCHS\[sdk=iphonesimulator\*\] = arm64\n/, '')
File.write(path, kept) unless kept == text
end
end
2 changes: 1 addition & 1 deletion apps/mobile/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ SPEC CHECKSUMS:
flutter_tesseract_ocr: fffe5de044967e12d184feaded7fabfb546b6042
SwiftyTesseract: 1f3d96668ae92dc2208d9842c8a59bea9fad2cbb

PODFILE CHECKSUM: 3ba3a73b1b12adcf321a227a745625fe0888cc82
PODFILE CHECKSUM: 91e106dbdd76557d0dc8a0078a8226d344da7b92

COCOAPODS: 1.17.0
Loading
Loading