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
47 changes: 47 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,53 @@ jobs:
- name: Build
run: npm run build && test -f dist/main.js

food-data:
name: Food data
runs-on: ubuntu-latest
timeout-minutes: 20
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: grit
POSTGRES_PASSWORD: grit
POSTGRES_DB: grit
ports: ['5432:5432']
options: >-
--health-cmd "pg_isready -U grit"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
# A throwaway database with the backend's migrations, for the importers'
# database tests (which work in a schema of their own)
DATABASE_URL: postgresql://grit:grit@localhost:5432/grit
DIRECT_URL: postgresql://grit:grit@localhost:5432/grit
defaults:
run:
working-directory: packages/food-data
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Install
working-directory: .
run: npm install --no-audit --no-fund
- name: Apply the backend's migrations
working-directory: packages/backend
run: npx prisma migrate deploy
- name: Format
run: npx prettier --check "src/**/*.ts"
- name: Lint
run: npm run lint
- name: Typecheck
run: npm run typecheck
- name: Unit tests
run: npm test -- --ci
- name: Database tests
run: npm run test:db -- --ci

mobile:
name: Mobile
runs-on: ubuntu-latest
Expand Down
68 changes: 68 additions & 0 deletions .github/workflows/food-data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
name: Food data

# Imports into GRIT's food database (packages/food-data). Runs by hand for
# full imports (USDA after each release, twice a year; Open Food Facts;
# CoFID), and daily for Open Food Facts' changes to products already in the
# database. Needs the DIRECT_URL repository secret: a session-mode
# connection, not Supabase's transaction pooler on port 6543 (see the
# package README). Without it, the workflow does nothing.

on:
workflow_dispatch:
inputs:
source:
description: What to import
type: choice
options: [off-delta, fdc, off, cofid]
default: off-delta
options:
description: 'Options, e.g. "--dataset foundation,sr,fndds --full", "--min-scans 5 --countries gb,us", "--only-existing", "--dry-run"'
type: string
default: ''
schedule:
# Daily, after OFF publishes its delta (about 06:30 UTC)
- cron: '43 7 * * *'

# One import at a time; a second one waits rather than racing the first
concurrency:
group: food-data
cancel-in-progress: false

permissions:
contents: read

jobs:
import:
name: Import
runs-on: ubuntu-latest
timeout-minutes: 350
env:
DIRECT_URL: ${{ secrets.DIRECT_URL }}
SOURCE: ${{ github.event_name == 'schedule' && 'off-delta' || inputs.source }}
OPTIONS: ${{ github.event_name == 'schedule' && '--only-existing' || inputs.options }}
steps:
- name: Check for the database secret
id: secret
run: |
if [ -z "$DIRECT_URL" ]; then
echo "::notice title=Food data::The DIRECT_URL secret isn't set, so nothing was imported."
echo "ready=false" >> "$GITHUB_OUTPUT"
else
echo "ready=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v4
if: steps.secret.outputs.ready == 'true'
- uses: actions/setup-node@v4
if: steps.secret.outputs.ready == 'true'
with:
node-version: 22
- name: Install
if: steps.secret.outputs.ready == 'true'
run: npm install --no-audit --no-fund
- name: Import
if: steps.secret.outputs.ready == 'true'
run: |
# The options are words for the importer, never shell: no globbing
set -f
echo "Importing $SOURCE $OPTIONS"
npm run import -w packages/food-data -- "$SOURCE" $OPTIONS
20 changes: 13 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ grit/
├── apps/
│ └── mobile/ # Expo (React Native) app
└── packages/
└── backend/ # NestJS REST API
├── backend/ # NestJS REST API
└── food-data/ # Importers for GRIT's food database (USDA, Open Food Facts, UK CoFID)
```

---
Expand Down Expand Up @@ -118,8 +119,9 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
|---|---|
| `auth` | Guard that verifies Supabase access tokens, `POST /auth/sync` |
| `users` | `GET/PUT/DELETE /users/me` (delete removes the account and its Supabase sign-in), `POST/DELETE /users/me/ai-consent`; safety rules (18+, calorie floors, no weight-loss goals after a "yes", no pro-eating-disorder names) |
| `food` | `GET/POST /food-logs` (with the day's calorie budget and macro targets), `GET /food-logs/week?date=`, `PATCH/DELETE /food-logs/:id`, Open Food Facts search + barcode proxy, `GET /food/recent`, `GET/POST /food/favorites`, `DELETE /food/favorites/:id`, `POST /food/search-events`; caffeine and alcohol per log |
| `meal-parse` | `POST /food/parse` (text and/or photo → items), `POST /food/parse/log`, `GET /food/memories`, `DELETE /food/memories/:id` |
| `food` | `GET/POST /food-logs` (with the day's calorie budget and macro targets; a database food's log keeps a snapshot of the amount's nutrients), `GET /food-logs/week?date=`, `PATCH/DELETE /food-logs/:id`, `GET /food/search?q=&country=` (GRIT's food database first, Open Food Facts live while it's missing products), `GET /food/barcode/:code?country=` (local first; a product found live is saved), `GET /food/item/:id`, `GET /food/recent`, `GET/POST /food/favorites`, `DELETE /food/favorites/:id`, `POST /food/search-events`; caffeine and alcohol per log |
| `meal-parse` | `POST /food/parse` (text and/or photo → items, matched to measured foods in the database, then branded ones, then estimated), `POST /food/parse/log`, `GET /food/memories`, `DELETE /food/memories/:id` |
| `nutrients` | `GET /nutrients/day?date=` (vitamins, minerals, fibre, sodium and saturated fat against US Dietary Reference Intakes, with how much of the day's calories have data), `GET /nutrients/week?date=` (nutrients low on most days) |
| `health` | `POST /health/import` (workouts with heart rate and distance, daily steps and sleep, weigh-ins, and recovery and cycle metrics from Apple Health / Health Connect; workout calories from heart rate when the device gives none), `GET /health/recent` (with recovery metrics against their 30-day average), `GET /health/cycle` |
| `workouts` | `POST /workouts` (a finished workout, saved once per `clientId`), `GET /workouts`, `GET/PUT/DELETE /workouts/:id`, `POST /workouts/prepare` (last time, records and the progression rules' targets), `POST /workouts/parse` (Say it), `GET /workouts/exercises/:id/history` |
| `activity` | `GET/POST /activity-logs`, `GET /activity-logs/week?date=`, `PATCH/DELETE /activity-logs/:id`, `POST /activity-logs/:id/kudos` |
Expand All @@ -132,9 +134,9 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge`, `GET/POST/DELETE /ai/memories`, `DELETE /ai/memories/:id` — AI coach and its notes |
| `notifications` | `GET /notifications`, `GET /notifications/unread-count`, `POST /notifications/read`, `POST/DELETE /notifications/register` (one row per phone), Expo push sending |
| `app` | `GET /health`, `POST /client-errors` (crash reports from the app, no sign-in, throttled) |
| `alerts` | Hourly job: challenge results, 1pm coach check-ins, 8pm streak-at-risk and Sunday 6pm weekly check-in (with any target suggestion), in each user's local time |
| `alerts` | Hourly job: challenge results, 1pm coach check-ins (including a nutrient low on 5 of the last 7 days), 8pm streak-at-risk and Sunday 6pm weekly check-in (with any target suggestion), in each user's local time |

**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay · HealthMetric · SearchEvent · Exercise · WorkoutSession · WorkoutSet
**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay · HealthMetric · SearchEvent · Exercise · WorkoutSession · WorkoutSet · Food · FoodBarcode · FoodServing · FoodNutrient · FoodName · FoodSource (GRIT's food database: shared, filled by `packages/food-data`, values per 100 g)

See [`docs/ROADMAP.md`](./docs/ROADMAP.md) for what's done and what's next.

Expand Down Expand Up @@ -172,7 +174,7 @@ cd apps/mobile && npm run lint && npm test
cp packages/backend/.env.example packages/backend/.env
```

See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project), `PUSH_DISABLED=true` (don't send pushes, e.g. locally), `RATE_LIMIT_PER_MINUTE` (default 300 per signed-in session) and `CORS_ORIGINS` (comma-separated web origins; default any). The server checks its settings at boot and lists anything missing or malformed.
See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project), `PUSH_DISABLED=true` (don't send pushes, e.g. locally), `RATE_LIMIT_PER_MINUTE` (default 300 per signed-in session), `CORS_ORIGINS` (comma-separated web origins; default any) and `FOOD_LIVE_SEARCH=off` (stop asking Open Food Facts live during search once its products are imported; barcode misses still ask). The server checks its settings at boot and lists anything missing or malformed.

Every response carries an `x-request-id` (also in error bodies), matching one log line per request. Logs are JSON when `NODE_ENV=production`. Sign-in tokens are verified locally against the Supabase project's published signing key. `GET /health` reports the API and database; `POST /client-errors` records crashes reported by the app.

Expand Down Expand Up @@ -239,7 +241,11 @@ A cloud instance can't run a simulator. Use it for type-checking and linting, or

### CI

[`.github/workflows/ci.yml`](./.github/workflows/ci.yml) runs on every pull request and push to `main`: the backend job applies the migrations to a throwaway Postgres, checks they match the schema, and runs prettier, eslint, tsc, unit tests, database tests and the build; the mobile job runs tsc, eslint and unit tests.
[`.github/workflows/ci.yml`](./.github/workflows/ci.yml) runs on every pull request and push to `main`: the backend job applies the migrations to a throwaway Postgres, checks they match the schema, and runs prettier, eslint, tsc, unit tests, database tests and the build; the mobile job runs tsc, eslint and unit tests; the food-data job runs the importers' lint, typecheck, unit tests and database tests.

### Food data

GRIT's food database is filled by the importers in [`packages/food-data`](./packages/food-data/README.md): USDA FoodData Central (public domain), Open Food Facts (ODbL) and the UK's CoFID (Open Government Licence). Each is idempotent, so a re-run changes nothing. The [Food data workflow](./.github/workflows/food-data.yml) runs them against the database in the `DIRECT_URL` repository secret: by hand for full imports, and daily for Open Food Facts' changes. Sources are credited in the app under Profile → Food data sources.

---

Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/__tests__/notificationRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ describe('where an alert opens', () => {
expect(notificationRoute('coach_checkin', { screen: 'food' })).toBe('/(tabs)/food');
expect(notificationRoute('coach_checkin', { screen: 'stats' })).toBe('/(tabs)/activity');
expect(notificationRoute('coach_checkin', {})).toBe('/coach');
expect(notificationRoute('coach_checkin', { screen: 'food', rule: 'nutrient_low', nutrient: 'iron_mg' })).toBe('/nutrients');
expect(notificationRoute('coach_checkin', { screen: 'food', rule: 'nutrient_low', nutrient: '' })).toBe('/(tabs)/food');
});
it('falls back to the inbox when ids are missing or the type is unknown', () => {
expect(notificationRoute('follow')).toBe('/notifications');
Expand Down
119 changes: 119 additions & 0 deletions apps/mobile/__tests__/nutrients.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
amountText, barFraction, barTone, coverageNote, formatAmount, lowDaysText, nutrientA11yLabel, nutrientSections,
percentText, sourcesLine, statusTag, type DayNutrient,
} from '@/lib/nutrients';

const nutrient = (over: Partial<DayNutrient>): DayNutrient => ({
code: 'iron_mg', name: 'Iron', unit: 'mg', group: 'mineral', kind: 'target',
amount: 9.4, target: 18, percent: 52, coverage: 0.8, status: 'low', sources: [],
...over,
});

describe('nutrient amounts', () => {
it('rounds to a sensible precision', () => {
expect(formatAmount(1840.4)).toBe('1,840');
expect(formatAmount(18)).toBe('18');
expect(formatAmount(12.6)).toBe('13');
expect(formatAmount(9.44)).toBe('9.4');
expect(formatAmount(0.354)).toBe('0.35');
expect(formatAmount(0)).toBe('0');
expect(formatAmount(-1)).toBe('0');
});
it('shows amount against target or limit', () => {
expect(amountText(nutrient({}))).toBe('9.4 / 18 mg');
expect(amountText(nutrient({ code: 'sodium_mg', kind: 'limit', amount: 1840, target: 2300 }))).toBe('1,840 / 2,300 mg max');
expect(amountText(nutrient({ unit: 'µg', amount: 2.4, target: null }))).toBe('2.4 µg');
});
it('shows percent and fills the bar up to full', () => {
expect(percentText(52)).toBe('52%');
expect(percentText(null)).toBe('');
expect(barFraction(52)).toBeCloseTo(0.52);
expect(barFraction(140)).toBe(1);
expect(barFraction(null)).toBe(0);
});
});

describe('nutrient status', () => {
it('only calls a nutrient low or over when the server judged it', () => {
expect(statusTag('low')).toEqual({ text: 'Low', tone: 'orange' });
expect(statusTag('over')).toEqual({ text: 'Over the limit', tone: 'error' });
expect(statusTag('ok')).toBeNull();
expect(statusTag(null)).toEqual({ text: 'not enough data', tone: 'muted' });
});
it('colours the bar by status, grey without data', () => {
expect(barTone('low')).toBe('orange');
expect(barTone('ok')).toBe('teal');
expect(barTone('over')).toBe('error');
expect(barTone(null)).toBe('muted');
});
it('tags nothing but a passed limit while today is in progress', () => {
expect(statusTag(null, true)).toBeNull();
expect(statusTag('over', true)).toEqual({ text: 'Over the limit', tone: 'error' });
expect(barTone(null, true)).toBe('blue');
expect(barTone('over', true)).toBe('error');
expect(nutrientA11yLabel(nutrient({ status: null }), true)).toBe('Iron: 9.4 of 18 mg, 52%');
expect(nutrientA11yLabel(nutrient({ status: null }))).toBe('Iron: 9.4 of 18 mg, 52%, not enough data');
});
it('reads out for screen readers', () => {
expect(nutrientA11yLabel(nutrient({}))).toBe('Iron: 9.4 of 18 mg, 52%, low');
expect(nutrientA11yLabel(nutrient({ status: 'ok', percent: 110, amount: 19.8 }))).toBe('Iron: 20 of 18 mg, 110%');
});
it('never uses diagnostic words', () => {
const words = [statusTag('low'), statusTag('over'), statusTag(null)].map((t) => t?.text ?? '').join(' ');
expect(words).not.toMatch(/deficien/i);
});
});

describe('good sources', () => {
const sources = [{ name: 'Spinach, raw', amount: 2.7 }, { name: 'Tea', amount: 0.1 }];
it('lists foods giving a good share of a target', () => {
expect(sourcesLine(nutrient({ sources }), true)).toBe('Good sources today: Spinach, raw (2.7 mg)');
expect(sourcesLine(nutrient({ sources }), false)).toBe('Good sources: Spinach, raw (2.7 mg)');
expect(sourcesLine(nutrient({ sources: [{ name: 'Tea', amount: 0.1 }] }), true)).toBeNull();
expect(sourcesLine(nutrient({ sources: [] }), true)).toBeNull();
});
it('says where a limit came from only when over it', () => {
const sodium = nutrient({ code: 'sodium_mg', name: 'Sodium', group: 'energy', kind: 'limit', sources: [{ name: 'Bacon', amount: 800 }] });
expect(sourcesLine({ ...sodium, status: 'over' }, true)).toBe('Mostly from: Bacon (800 mg)');
expect(sourcesLine({ ...sodium, status: 'ok' }, true)).toBeNull();
});
});

describe('sections', () => {
it('groups vitamins, minerals, then fibre, sodium and saturated fat', () => {
const all = [
nutrient({ code: 'kcal', name: 'Energy', group: 'energy', kind: 'none' }),
nutrient({ code: 'sat_fat_g', name: 'Saturated fat', group: 'energy', kind: 'limit' }),
nutrient({ code: 'fibre_g', name: 'Fibre', group: 'energy', kind: 'target' }),
nutrient({ code: 'sodium_mg', name: 'Sodium', group: 'energy', kind: 'limit' }),
nutrient({ code: 'vit_c_mg', name: 'Vitamin C', group: 'vitamin' }),
nutrient({ code: 'iron_mg', name: 'Iron', group: 'mineral' }),
nutrient({ code: 'caffeine_mg', name: 'Caffeine', group: 'other', kind: 'none' }),
];
expect(nutrientSections(all).map((s) => [s.title, s.items.map((n) => n.name)])).toEqual([
['Vitamins', ['Vitamin C']],
['Minerals', ['Iron']],
['Fibre, sodium and saturated fat', ['Fibre', 'Sodium', 'Saturated fat']],
]);
expect(nutrientSections([nutrient({})]).map((s) => s.title)).toEqual(['Minerals']);
});
});

describe('coverage note', () => {
const today = '2026-11-06';
const yesterday = '2026-11-05';
it("says how much of the day's calories it's based on", () => {
expect(coverageNote(0.64, today, today, yesterday)).toBe("Based on 64% of today's calories");
expect(coverageNote(0.5, yesterday, today, yesterday)).toBe("Based on 50% of yesterday's calories");
expect(coverageNote(0.5, '2026-11-01', today, yesterday)).toBe("Based on 50% of the day's calories");
expect(coverageNote(0.002, today, today, yesterday)).toBe("Based on 1% of today's calories");
expect(coverageNote(1, today, today, yesterday)).toBe("Based on all of today's calories");
});
});

describe('often low', () => {
it('counts the low days', () => {
expect(lowDaysText({ lowDays: 4, days: 4 })).toBe('low on 4 of 4 days');
expect(lowDaysText({ lowDays: 1, days: 1 })).toBe('low on 1 of 1 day');
});
});
Loading
Loading