diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3979440..08fc151 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/food-data.yml b/.github/workflows/food-data.yml new file mode 100644 index 0000000..217af21 --- /dev/null +++ b/.github/workflows/food-data.yml @@ -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 diff --git a/README.md b/README.md index d523a89..18bddc9 100644 --- a/README.md +++ b/README.md @@ -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) ``` --- @@ -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` | @@ -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. @@ -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. @@ -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. --- diff --git a/apps/mobile/__tests__/notificationRoute.test.ts b/apps/mobile/__tests__/notificationRoute.test.ts index 142edec..9e9c333 100644 --- a/apps/mobile/__tests__/notificationRoute.test.ts +++ b/apps/mobile/__tests__/notificationRoute.test.ts @@ -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'); diff --git a/apps/mobile/__tests__/nutrients.test.ts b/apps/mobile/__tests__/nutrients.test.ts new file mode 100644 index 0000000..4647028 --- /dev/null +++ b/apps/mobile/__tests__/nutrients.test.ts @@ -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 => ({ + 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'); + }); +}); diff --git a/apps/mobile/__tests__/quickFoods.test.ts b/apps/mobile/__tests__/quickFoods.test.ts index 7f63a07..3e73862 100644 --- a/apps/mobile/__tests__/quickFoods.test.ts +++ b/apps/mobile/__tests__/quickFoods.test.ts @@ -1,4 +1,4 @@ -import { foodKey, portionAsFood, portionLabel } from '@/lib/quickFoods'; +import { favoriteBody, foodKey, portionAsFood, portionGrams, portionLabel } from '@/lib/quickFoods'; describe('quick foods', () => { it('matches the server key', () => { @@ -13,5 +13,34 @@ describe('quick foods', () => { it('turns a saved portion into a loggable food', () => { const food = portionAsFood({ name: 'Oats', brand: null, barcode: null, calories: 300, proteinG: 10, carbsG: 50, fatG: 6, servingQty: 80, servingUnit: 'g' }); expect(food).toMatchObject({ portion: true, offId: '', calories: 300, servingQty: 80 }); + expect(food.foodId).toBeUndefined(); + expect(food.portionGrams).toBeUndefined(); + }); + it("keeps a database food's id and grams", () => { + const food = portionAsFood({ name: 'Bread', brand: null, barcode: null, calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56 }); + expect(food).toMatchObject({ portion: true, foodId: 'f1', portionGrams: 56 }); + }); + it('scales grams by the number of portions', () => { + expect(portionGrams(56, 2)).toBe(112); + expect(portionGrams(28, 1.5)).toBe(42); + expect(portionGrams(33.3, 3)).toBe(99.9); + expect(portionGrams(null, 2)).toBeUndefined(); + expect(portionGrams(undefined, 2)).toBeUndefined(); + expect(portionGrams(0, 2)).toBeUndefined(); + }); + it('sends only the fields a favourite takes', () => { + const recent = { + name: 'Bread', brand: null, barcode: '5000000000001', calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, + servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56, + key: 'bread|', timesLogged: 3, lastMealType: 'lunch', lastLoggedAt: '2026-11-05T12:00:00Z', favoriteId: null, + }; + expect(favoriteBody(recent)).toEqual({ + name: 'Bread', brand: undefined, barcode: '5000000000001', calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, + servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56, + }); + const manual = favoriteBody({ ...recent, foodId: null, grams: null }); + expect(manual.foodId).toBeUndefined(); + expect(manual.grams).toBeUndefined(); + expect(favoriteBody({ ...recent, grams: 6000 }).grams).toBeUndefined(); }); }); diff --git a/apps/mobile/__tests__/servings.test.ts b/apps/mobile/__tests__/servings.test.ts new file mode 100644 index 0000000..42b6810 --- /dev/null +++ b/apps/mobile/__tests__/servings.test.ts @@ -0,0 +1,110 @@ +import { + amountEaten, defaultOption, defaultServing, foodUnit, kcalIn, parseQty, qtyAfterSwitch, scalePer100, searchServing, + servingLabel, servingLog, servingOptions, +} from '@/lib/servings'; + +// Wholemeal bread, per 100 g +const bread = { + calories: 265, proteinG: 10, carbsG: 43, fatG: 3.4, + servingQty: 28, servingUnit: 'g', + servings: [ + { label: '1 slice', grams: 28, typical: true }, + { label: '1 thick slice', grams: 44, typical: false }, + ], +}; + +describe('serving labels', () => { + it('shows the grams in brackets', () => { + expect(servingLabel({ label: '1 slice', grams: 28 })).toBe('1 slice (28 g)'); + expect(servingLabel({ label: '1 cup, chopped', grams: 160.4 })).toBe('1 cup, chopped (160 g)'); + expect(servingLabel({ label: '1 tsp', grams: 4.2 })).toBe('1 tsp (4.2 g)'); + expect(servingLabel({ label: '1 can', grams: 330 }, 'ml')).toBe('1 can (330 ml)'); + }); + it('treats only ml as millilitres', () => { + expect(foodUnit({ servingUnit: 'ml' })).toBe('ml'); + expect(foodUnit({ servingUnit: 'g' })).toBe('g'); + expect(foodUnit({ servingUnit: 'serving' })).toBe('g'); + }); +}); + +describe('serving options', () => { + it("lists the food's servings, then 100 g, then grams", () => { + expect(servingOptions(bread).map((o) => o.label)).toEqual(['1 slice (28 g)', '1 thick slice (44 g)', '100 g', 'Grams']); + const direct = servingOptions(bread).at(-1)!; + expect(direct).toMatchObject({ direct: true, grams: 1 }); + }); + it('drops servings with no grams or label', () => { + const food = { ...bread, servings: [{ label: '', grams: 30, typical: false }, { label: '1 pot', grams: 0, typical: true }] }; + expect(servingOptions(food).map((o) => o.key)).toEqual(['serving', '100', 'direct']); + }); + it('offers a plain serving size when there are no named servings', () => { + expect(servingOptions({ servingQty: 30, servingUnit: 'g' }).map((o) => o.label)).toEqual(['1 serving (30 g)', '100 g', 'Grams']); + expect(servingOptions({ servingQty: 100, servingUnit: 'ml' }).map((o) => o.label)).toEqual(['100 ml', 'Millilitres']); + }); +}); + +describe('default serving', () => { + it('starts on the typical serving', () => { + const food = { ...bread, servings: [bread.servings[1], bread.servings[0]] }; + expect(defaultOption(food).label).toBe('1 slice (28 g)'); + }); + it('else on the first serving', () => { + const food = { ...bread, servings: bread.servings.map((s) => ({ ...s, typical: false })) }; + expect(defaultOption(food).label).toBe('1 slice (28 g)'); + }); + it("else on the food's serving size, or 100 g", () => { + expect(defaultOption({ servingQty: 30, servingUnit: 'g' }).label).toBe('1 serving (30 g)'); + expect(defaultOption({ servingQty: 100, servingUnit: 'g' }).label).toBe('100 g'); + expect(defaultOption({ servingQty: 0, servingUnit: 'g' }).label).toBe('100 g'); + expect(defaultServing({ servingQty: 100, servingUnit: 'g' })).toBeNull(); + }); +}); + +describe('search rows', () => { + it('show the typical serving and its kcal', () => { + expect(searchServing(bread)).toEqual({ serving: '1 slice (28 g)', kcal: 74 }); + }); + it('show kcal per 100 g without a serving', () => { + expect(searchServing({ calories: 89.4, servingQty: 100, servingUnit: 'g' })).toEqual({ serving: null, kcal: 89 }); + }); +}); + +describe('serving maths', () => { + it('multiplies servings by the serving grams', () => { + const slice = defaultOption(bread); + expect(amountEaten(2, slice)).toBe(56); + expect(amountEaten(-1, slice)).toBe(0); + expect(amountEaten(45, { grams: 1 })).toBe(45); + }); + it('scales per-100 g values to the grams eaten', () => { + const per = scalePer100({ ...bread, caffeineMg: 10, alcoholG: 1.25 }, 56); + expect(per.calories).toBeCloseTo(148.4); + expect(per.proteinG).toBeCloseTo(5.6); + expect(per.carbsG).toBeCloseTo(24.08); + expect(per.fatG).toBeCloseTo(1.904); + expect(per.caffeineMg).toBe(6); + expect(per.alcoholG).toBe(0.7); + expect(scalePer100(bread, 50).caffeineMg).toBeUndefined(); + expect(kcalIn(bread, 28)).toBe(74); + }); + it('logs a number of servings as grams', () => { + const [slice, , hundred, direct] = servingOptions(bread); + expect(servingLog(bread, slice, '2')).toMatchObject({ grams: 56 }); + expect(servingLog(bread, slice, '2').calories).toBeCloseTo(148.4); + expect(servingLog(bread, hundred, '1.5').grams).toBe(150); + expect(servingLog(bread, direct, '45').grams).toBe(45); + expect(servingLog(bread, direct, '45').calories).toBeCloseTo(119.25); + }); + it('reads the amount field', () => { + expect(parseQty('1.5', false)).toBe(1.5); + expect(parseQty('1,5', false)).toBe(1.5); + expect(parseQty('', false)).toBe(1); + expect(parseQty('', true)).toBe(0); + expect(parseQty('-3', true)).toBe(0); + }); + it('keeps the grams when switching to typing grams, and starts a serving at 1', () => { + expect(qtyAfterSwitch({ direct: true }, 56)).toBe('56'); + expect(qtyAfterSwitch({ direct: true }, 42.04)).toBe('42'); + expect(qtyAfterSwitch({}, 56)).toBe('1'); + }); +}); diff --git a/apps/mobile/app/(tabs)/activity.tsx b/apps/mobile/app/(tabs)/activity.tsx index 67533cf..82e840a 100644 --- a/apps/mobile/app/(tabs)/activity.tsx +++ b/apps/mobile/app/(tabs)/activity.tsx @@ -19,6 +19,7 @@ import { ACTIVITY_LABELS, LogActivitySheet } from '@/components/activity/LogActi import { DateNavigator } from '@/components/ui/DateNavigator'; import { TrendsCard } from '@/components/stats/TrendsCard'; import { AdaptiveCard } from '@/components/stats/AdaptiveCard'; +import { LowNutrientsCard } from '@/components/stats/LowNutrientsCard'; import { LogWeightSheet } from '@/components/stats/LogWeightSheet'; import { usePullToRefresh } from '@/hooks/usePullToRefresh'; import { Colors } from '@/constants/colors'; @@ -129,7 +130,7 @@ export default function ActivityScreen() { const { data: habitSummary } = useHabitSummary(); const [showSheet, setShowSheet] = useState(false); const [showWeight, setShowWeight] = useState(false); - const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive']]); + const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive'], ['nutrients-week']]); useFocusEffect( React.useCallback(() => { @@ -255,6 +256,9 @@ export default function ActivityScreen() { + {/* Vitamins and minerals low on most days of this week (hidden if none) */} + + {/* Activity bar chart */} diff --git a/apps/mobile/app/(tabs)/food.tsx b/apps/mobile/app/(tabs)/food.tsx index a03f094..38a1bba 100644 --- a/apps/mobile/app/(tabs)/food.tsx +++ b/apps/mobile/app/(tabs)/food.tsx @@ -105,7 +105,7 @@ export default function FoodScreen() { const status = useQueriesStatus(foodQuery); const { mutate: deleteLog } = useDeleteFoodLog(); const { data: me } = useMe(); - const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites']]); + const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites'], ['nutrients-day', date]]); const [editingLog, setEditingLog] = useState(null); const [smartOpen, setSmartOpen] = useState(false); const ensureAiConsent = useEnsureAiConsent(); @@ -198,7 +198,7 @@ export default function FoodScreen() { Smart log router.push('/barcode-scanner' as never)} + onPress={() => router.push({ pathname: '/barcode-scanner', params: { date } })} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1, width: 40, height: 40, borderRadius: 12, @@ -268,6 +268,17 @@ export default function FoodScreen() { {alcoholG > 0 ? `🍷 ${alcoholG} g alcohol` : ''} )} + {/* Vitamins, minerals, fibre, sodium and saturated fat for this day */} + router.push({ pathname: '/nutrients', params: { date } })} + accessibilityRole="button" + accessibilityLabel="Nutrients" + accessibilityHint="Vitamins, minerals and fibre for this day" + hitSlop={8} + style={({ pressed }) => ({ alignSelf: 'flex-start', marginTop: 2, opacity: pressed ? 0.6 : 1 })} + > + Nutrients › + diff --git a/apps/mobile/app/(tabs)/profile.tsx b/apps/mobile/app/(tabs)/profile.tsx index f98a030..dc2954d 100644 --- a/apps/mobile/app/(tabs)/profile.tsx +++ b/apps/mobile/app/(tabs)/profile.tsx @@ -147,6 +147,7 @@ const SETTINGS_ROWS = [ { icon: '❤️', color: 'error' as const, label: Platform.OS === 'android' ? 'Health Connect' : Platform.OS === 'ios' ? 'Apple Health' : 'Health data', sub: 'Sync workouts, steps, sleep and weight', href: '/settings/health' as const }, { icon: '🧠', color: 'teal' as const, label: 'What your coach knows', sub: 'Notes from your chats', href: '/settings/coach-memory' as const }, { icon: '✨', color: 'orange' as const, label: 'Foods GRIT knows', sub: 'Portions learned from Smart log', href: '/settings/foods' as const }, + { icon: '📖', color: 'blue' as const, label: 'Food data sources', sub: 'Where nutrition data comes from', href: '/settings/food-sources' as const }, { icon: '🔔', color: 'blue' as const, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const }, { icon: '👤', color: 'muted' as const, label: 'Account', sub: 'Appearance, units, password, delete account', href: '/settings/account' as const }, { icon: '📊', color: 'teal' as const, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const }, diff --git a/apps/mobile/app/barcode-scanner.tsx b/apps/mobile/app/barcode-scanner.tsx index 8d41b4f..61f43b9 100644 --- a/apps/mobile/app/barcode-scanner.tsx +++ b/apps/mobile/app/barcode-scanner.tsx @@ -1,7 +1,7 @@ import React, { useState, useCallback } from 'react'; import { View, Text, Pressable, StyleSheet, Alert } from 'react-native'; import { CameraView, useCameraPermissions } from 'expo-camera'; -import { router } from 'expo-router'; +import { router, useLocalSearchParams } from 'expo-router'; import * as Haptics from 'expo-haptics'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useFoodBarcode } from '@/hooks/useFoodLog'; @@ -10,6 +10,9 @@ import { Colors } from '@/constants/colors'; export default function BarcodeScannerScreen() { const styles = makeStyles(); + // The day the Food tab is showing, so a scan logs to it + const params = useLocalSearchParams<{ date?: string }>(); + const date = typeof params.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(params.date) ? params.date : undefined; const [permission, requestPermission] = useCameraPermissions(); const [scannedCode, setScannedCode] = useState(null); const [showSheet, setShowSheet] = useState(false); @@ -140,6 +143,7 @@ export default function BarcodeScannerScreen() { servingUnit: 'serving', imageUrl: null, }} + date={date} onClose={() => { setShowSheet(false); setScannedCode(null); @@ -153,7 +157,6 @@ export default function BarcodeScannerScreen() { const CORNER_SIZE = 24; const CORNER_THICKNESS = 3; -const CORNER_COLOR = Colors.orange; // Built during render, so it follows the current theme const makeStyles = () => StyleSheet.create({ @@ -187,25 +190,25 @@ const makeStyles = () => StyleSheet.create({ position: 'absolute', top: 0, left: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderTopWidth: CORNER_THICKNESS, borderLeftWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerTR: { position: 'absolute', top: 0, right: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderTopWidth: CORNER_THICKNESS, borderRightWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerBL: { position: 'absolute', bottom: 0, left: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderBottomWidth: CORNER_THICKNESS, borderLeftWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerBR: { position: 'absolute', bottom: 0, right: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderBottomWidth: CORNER_THICKNESS, borderRightWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, permissionView: { flex: 1, diff --git a/apps/mobile/app/nutrients.tsx b/apps/mobile/app/nutrients.tsx new file mode 100644 index 0000000..067f797 --- /dev/null +++ b/apps/mobile/app/nutrients.tsx @@ -0,0 +1,161 @@ +import React, { useState } from 'react'; +import { ActivityIndicator, Pressable, RefreshControl, ScrollView, Text, View } from 'react-native'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import { router, useLocalSearchParams } from 'expo-router'; +import { Colors } from '@/constants/colors'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; +import { DateNavigator } from '@/components/ui/DateNavigator'; +import { ErrorNotice } from '@/components/ui/QueryStatus'; +import { useNutrientsDay } from '@/hooks/useNutrients'; +import { usePullToRefresh } from '@/hooks/usePullToRefresh'; +import { addDaysStr, dayLabel, localDateStr } from '@/lib/date'; +import { + amountText, barFraction, barTone, coverageNote, nutrientA11yLabel, nutrientSections, percentText, sourcesLine, statusTag, + type DayNutrient, +} from '@/lib/nutrients'; + +const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; + +/** One nutrient: amount against its target or limit, as a bar. */ +function NutrientRow({ n, isToday, inProgress }: { n: DayNutrient; isToday: boolean; inProgress: boolean }) { + const tag = statusTag(n.status, inProgress); + const tone = barTone(n.status, inProgress); + // Without enough data the bar stays grey, so nothing reads as low + const fill = tone === 'muted' ? `${Colors.muted}60` : Colors[tone]; + const sources = sourcesLine(n, isToday); + const percent = percentText(n.percent); + return ( + + + {n.name} + {tag && tag.tone === 'muted' && ( + {tag.text} + )} + {tag && tag.tone !== 'muted' && ( + + {tag.text} + + )} + + {!!percent && ( + {percent} + )} + + + + + {amountText(n)} + {!!sources && ( + {sources} + )} + + ); +} + +/** + * Vitamins, minerals, fibre, sodium and saturated fat for a day, against + * targets for the user's age and sex. Only foods from GRIT's database carry + * this data, so the screen says how much of the day it's based on. + */ +/** + * Whether there's anything to show: vitamins and minerals, or sodium, + * saturated fat and fibre (which branded labels carry even without them). + */ +function hasAnyData(data: { coverage: number; nutrients: { kind: string; coverage: number }[] }) { + return data.coverage > 0 || data.nutrients.some((n) => n.kind !== 'none' && n.coverage > 0); +} + +export default function NutrientsScreen() { + const params = useLocalSearchParams<{ date?: string }>(); + const today = localDateStr(); + const yesterday = addDaysStr(today, -1); + const [date, setDate] = useState(() => + typeof params.date === 'string' && DATE_RE.test(params.date) && params.date <= today ? params.date : today, + ); + const { data, isLoading, isError, refetch } = useNutrientsDay(date); + const { refreshing, onRefresh } = usePullToRefresh([['nutrients-day', date]]); + const isToday = date === today; + // Today is still being logged: no Low tags yet (a passed limit still shows) + const inProgress = data?.inProgress === true; + + const card = { backgroundColor: Colors.surface, borderRadius: 18, borderWidth: 1, borderColor: Colors.border, padding: 16, gap: 6 } as const; + + return ( + + + } + > + setDate((d) => addDaysStr(d, -1))} + onNext={() => setDate((d) => addDaysStr(d, 1))} + canGoNext={date < today} + onReset={isToday ? undefined : () => setDate(today)} + /> + + {isError && !data ? ( + refetch()} /> + ) : isLoading || !data ? ( + + ) : !hasAnyData(data) ? ( + + 🥦 + + {data.entries === 0 ? 'Nothing logged yet' : 'No vitamin and mineral data yet'} + + + Log foods from the food database to see vitamins and minerals. + + + ) : ( + <> + + + {data.coverage > 0 + ? coverageNote(data.coverage, date, today, yesterday) + : 'No vitamin and mineral data for this day'} + + {data.coverage < 0.995 && ( + + Vitamins and minerals come from foods in the food database. Foods typed in by hand and Smart log estimates aren't counted. + + )} + {inProgress ? ( + + Today isn't over yet, so nothing is marked low until it is. + + ) : !data.judged && ( + + Nothing is marked low until more of the day is logged. + + )} + + + {nutrientSections(data.nutrients).map((s) => ( +
+ {s.items.map((n) => )} +
+ ))} + + )} + + + + Targets are US Dietary Reference Intakes for your age and sex. They don't cover pregnancy or breastfeeding. + + router.push('/settings/food-sources')} + accessibilityRole="button" + accessibilityLabel="Food data sources" + hitSlop={8} + style={({ pressed }) => ({ alignSelf: 'flex-start', opacity: pressed ? 0.6 : 1 })} + > + Food data sources › + + +
+
+ ); +} diff --git a/apps/mobile/app/settings/food-sources.tsx b/apps/mobile/app/settings/food-sources.tsx new file mode 100644 index 0000000..75a9340 --- /dev/null +++ b/apps/mobile/app/settings/food-sources.tsx @@ -0,0 +1,41 @@ +import React from 'react'; +import { Linking, Pressable, ScrollView, Text, View } from 'react-native'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import { Colors } from '@/constants/colors'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; +import { FOOD_SOURCES, siteName } from '@/lib/foodSources'; + +/** The public food tables and product data GRIT's food database is built from, with their credits. */ +export default function FoodSourcesScreen() { + return ( + + + + + GRIT's food database is built from these public food tables and product data. Foods marked ✓ Verified come from a government table or the manufacturer's own data. + +
+ {FOOD_SOURCES.map((s, i) => ( + + {s.name} + {s.credit} + {!!s.notice && ( + {s.notice} + )} + Licence: {s.licence} + Linking.openURL(s.url).catch(() => {})} + accessibilityRole="link" + accessibilityLabel={`Open the ${s.name} website`} + hitSlop={6} + style={({ pressed }) => ({ alignSelf: 'flex-start', marginTop: 2, opacity: pressed ? 0.6 : 1 })} + > + {siteName(s.url)} › + + + ))} +
+
+
+ ); +} diff --git a/apps/mobile/components/food/FoodSearchBar.tsx b/apps/mobile/components/food/FoodSearchBar.tsx index b82d68e..d0252c9 100644 --- a/apps/mobile/components/food/FoodSearchBar.tsx +++ b/apps/mobile/components/food/FoodSearchBar.tsx @@ -7,82 +7,116 @@ import { Pressable, ActivityIndicator, } from 'react-native'; -import { useFoodSearch, type NormalizedFood } from '@/hooks/useFoodLog'; +import { MIN_SEARCH_LENGTH, useFoodSearch, type NormalizedFood } from '@/hooks/useFoodLog'; import { recordSearch } from '@/lib/searchEvents'; +import { searchServing } from '@/lib/servings'; +import { VerifiedPill } from '@/components/food/VerifiedPill'; import { Colors } from '@/constants/colors'; +/** Wait this long after the last keystroke before searching */ +const DEBOUNCE_MS = 250; + interface FoodSearchBarProps { onSelect: (food: NormalizedFood) => void; } export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { const [query, setQuery] = useState(''); - const { data: results, isLoading } = useFoodSearch(query); + const term = query.trim(); + const [searched, setSearched] = useState(term); + useEffect(() => { + const t = setTimeout(() => setSearched(term), DEBOUNCE_MS); + return () => clearTimeout(t); + }, [term]); + const { data: results, isLoading } = useFoodSearch(searched); + const active = term.length >= MIN_SEARCH_LENGTH && searched.length >= MIN_SEARCH_LENGTH; // A search the user leaves without picking anything counts as a miss const pending = useRef(''); pending.current = query; - useEffect(() => () => recordSearch(pending.current), []); + // What the list shows, for the search events + const shown = useRef<{ term: string; count?: number }>({ term: '' }); + shown.current = { term: searched, count: searched === term ? results?.length : undefined }; + useEffect(() => () => recordSearch(pending.current, undefined, shown.current.count), []); const clear = () => { - recordSearch(query); + recordSearch(query, undefined, shown.current.count); setQuery(''); }; const renderItem = useCallback( - ({ item, index }: { item: NormalizedFood; index: number }) => ( - { - recordSearch(pending.current, { position: index, name: item.name }); - pending.current = ''; - onSelect(item); - setQuery(''); - }} - style={({ pressed }) => ({ - paddingVertical: 12, - paddingHorizontal: 16, - backgroundColor: pressed ? Colors.surface2 : 'transparent', - borderBottomWidth: 1, - borderBottomColor: Colors.border, - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', - })} - > - - - {item.name} - - {item.brand && ( + ({ item, index }: { item: NormalizedFood; index: number }) => { + const { serving, kcal } = searchServing(item); + const sub = [item.brand, serving].filter(Boolean).join(' · '); + return ( + { + recordSearch(shown.current.term, { position: index, name: item.name, foodId: item.foodId }, shown.current.count); + pending.current = ''; + onSelect(item); + setQuery(''); + }} + style={({ pressed }) => ({ + paddingVertical: 12, + paddingHorizontal: 16, + backgroundColor: pressed ? Colors.surface2 : 'transparent', + borderBottomWidth: 1, + borderBottomColor: Colors.border, + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + })} + > + + + + {item.name} + + {item.verified === true && } + + {!!sub && ( + + {sub} + + )} + + - {item.brand} + {kcal} kcal - )} - - - {Math.round(item.calories)} kcal - - - ), + {!serving && ( + per 100 g + )} + + + ); + }, [onSelect], ); @@ -124,7 +158,7 @@ export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { )}
- {query.length >= 2 && results && results.length > 0 && ( + {active && results && results.length > 0 && ( `${item.offId}-${i}`} + keyExtractor={(item, i) => `${item.foodId ?? item.offId}-${i}`} renderItem={renderItem} keyboardShouldPersistTaps="handled" /> )} - {query.length >= 2 && !isLoading && results?.length === 0 && ( + {active && !isLoading && results?.length === 0 && ( No results for "{query}" - { recordSearch(query); pending.current = ''; onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null }); }}> + { recordSearch(query, undefined, 0); pending.current = ''; onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null }); }}> Log "{query}" manually → diff --git a/apps/mobile/components/food/LogFoodSheet.tsx b/apps/mobile/components/food/LogFoodSheet.tsx index 770fd06..62f5eec 100644 --- a/apps/mobile/components/food/LogFoodSheet.tsx +++ b/apps/mobile/components/food/LogFoodSheet.tsx @@ -1,19 +1,26 @@ -import React, { useRef, useState, useCallback } from 'react'; +import React, { useRef, useState, useCallback, useMemo } from 'react'; import { View, Text, Pressable, Alert, } from 'react-native'; -import BottomSheet, { BottomSheetView } from '@gorhom/bottom-sheet'; +import BottomSheet, { BottomSheetScrollView } from '@gorhom/bottom-sheet'; import { SheetTextInput, sheetKeyboardProps } from '@/components/ui/SheetTextInput'; import * as Haptics from 'expo-haptics'; import { useLogFood, type NormalizedFood } from '@/hooks/useFoodLog'; import { foodKey, useFavoriteFoods, useRemoveFavorite, useSaveFavorite } from '@/hooks/useQuickFoods'; import { Button } from '@/components/ui/Button'; +import { VerifiedPill } from '@/components/food/VerifiedPill'; import { useHideTabBar } from '@/stores/uiStore'; import { Colors } from '@/constants/colors'; import { loggedAtFor } from '@/lib/date'; +import { notify } from '@/lib/confirm'; +import { portionGrams } from '@/lib/quickFoods'; +import { + MAX_LOG_GRAMS, defaultOption, foodUnit, formatGrams, qtyAfterSwitch, round1, servingLog, servingOptions, + type ServingOption, +} from '@/lib/servings'; const MEAL_TYPES = ['breakfast', 'lunch', 'dinner', 'snack'] as const; @@ -46,33 +53,51 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP const [mealType, setMealType] = useState(initialMeal ?? 'breakfast'); const [qty, setQty] = useState('1'); - // Foods from the database carry nutrition per 100 g (or ml) plus a serving - // size; manual entries have neither, so the user types values per serving. - // Saved portions (recent or favourite foods) carry amounts for the whole - // portion, so servings multiply them directly. + // Foods from the database carry nutrition per 100 g (or ml) plus servings + // to pick from; manual entries have neither, so the user types values per + // serving. Saved portions (recent or favourite foods) carry amounts for + // the whole portion, so servings multiply them directly. A database food + // can have no Open Food Facts id, so `foodId` also marks it as not manual. const isPortion = !!food?.portion; - const isManual = !food?.offId && !isPortion; + const isManual = !food?.offId && !food?.foodId && !isPortion; + const usesPicker = !!food && !isManual && !isPortion; + const unit = food ? foodUnit(food) : 'g'; const [name, setName] = useState(food?.name ?? ''); const [manual, setManual] = useState({ calories: '', proteinG: '', carbsG: '', fatG: '' }); const num = (v: string) => Math.max(0, parseFloat(v) || 0); + // The serving picker: the food's servings, then 100 g, then grams typed directly + const options = useMemo(() => (food && usesPicker ? servingOptions(food) : []), [food, usesPicker]); + const [optionKey, setOptionKey] = useState(() => (food && options.length ? defaultOption(food, options).key : '')); + const option = options.find((o) => o.key === optionKey) ?? options[0]; + const picked = food && usesPicker && option ? servingLog(food, option, qty) : null; + const servings = parseFloat(qty) > 0 ? parseFloat(qty) : 1; - const amount = servings * (food?.servingQty ?? 100); // grams or ml eaten + const amount = picked ? picked.grams : servings * (food?.servingQty ?? 100); // grams or ml eaten // How much of the food's listed amounts this is const factor = isManual ? servings : isPortion ? servings : amount / 100; - const adjustedCalories = isManual ? num(manual.calories) * servings : (food?.calories ?? 0) * factor; - const adjustedProtein = isManual ? num(manual.proteinG) * servings : (food?.proteinG ?? 0) * factor; - const adjustedCarbs = isManual ? num(manual.carbsG) * servings : (food?.carbsG ?? 0) * factor; - const adjustedFat = isManual ? num(manual.fatG) * servings : (food?.fatG ?? 0) * factor; + const adjustedCalories = isManual ? num(manual.calories) * servings : picked ? picked.calories : (food?.calories ?? 0) * factor; + const adjustedProtein = isManual ? num(manual.proteinG) * servings : picked ? picked.proteinG : (food?.proteinG ?? 0) * factor; + const adjustedCarbs = isManual ? num(manual.carbsG) * servings : picked ? picked.carbsG : (food?.carbsG ?? 0) * factor; + const adjustedFat = isManual ? num(manual.fatG) * servings : picked ? picked.fatG : (food?.fatG ?? 0) * factor; const caffeineMg = food?.caffeineMg != null && !isManual ? Math.round(food.caffeineMg * factor) : undefined; const alcoholG = food?.alcoholG != null && !isManual ? Math.round(food.alcoholG * factor * 10) / 10 : undefined; + // What's logged: database foods as grams, so the server can save their nutrients + const loggedQty = isManual ? servings : picked ? round1(amount) : amount; + const loggedUnit = isManual ? 'serving' : picked ? unit : food?.servingUnit ?? 'g'; + const loggedFoodId = !isManual ? food?.foodId : undefined; + const loggedGrams = picked + ? (unit === 'g' ? round1(amount) : undefined) + : isPortion ? portionGrams(food?.portionGrams, servings) : undefined; + // The star saves exactly what would be logged now const { data: favorites } = useFavoriteFoods(); const { mutate: saveFavorite, isPending: savingFavorite } = useSaveFavorite(); const { mutate: removeFavorite, isPending: removingFavorite } = useRemoveFavorite(); - const favName = isManual ? name.trim() : food?.name ?? ''; + // Logs and favourites take names of up to 200 characters + const favName = isManual ? name.trim() : (food?.name ?? '').slice(0, 200).trim(); const favorite = favorites?.find((f) => f.key === foodKey(favName, food?.brand)); function toggleFavorite() { if (!food || !favName) return; @@ -89,20 +114,38 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP proteinG: Math.round(adjustedProtein * 10) / 10, carbsG: Math.round(adjustedCarbs * 10) / 10, fatG: Math.round(adjustedFat * 10) / 10, - servingQty: isManual ? servings : amount, - servingUnit: isManual ? 'serving' : food.servingUnit, + servingQty: loggedQty, + servingUnit: loggedUnit, + foodId: loggedFoodId ?? null, + grams: loggedGrams ?? null, }); } + function pickOption(o: ServingOption) { + if (o.key === option?.key) return; + Haptics.selectionAsync(); + // Keep the amount when switching to grams; start at 1 of a serving + setQty(qtyAfterSwitch(o, amount)); + setOptionKey(o.key); + } + const handleLog = useCallback(async () => { if (!food) return; if (isManual && (!name.trim() || !manual.calories.trim())) { Alert.alert('Missing details', 'Enter a name and the calories per serving.'); return; } + if (usesPicker && !(amount > 0)) { + notify('How much?', `Enter the ${unit === 'ml' ? 'millilitres' : 'grams'} you had.`); + return; + } + if (loggedGrams != null && loggedGrams > MAX_LOG_GRAMS) { + notify("That's a lot", `Log up to ${MAX_LOG_GRAMS.toLocaleString()} g at a time.`); + return; + } try { await logFood({ - name: isManual ? name.trim() : food.name, + name: isManual ? name.trim() : food.name.slice(0, 200).trim(), brand: food.brand ?? undefined, barcode: food.barcode ?? undefined, mealType, @@ -110,8 +153,10 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP proteinG: adjustedProtein, carbsG: adjustedCarbs, fatG: adjustedFat, - servingQty: isManual ? servings : amount, - servingUnit: isManual ? 'serving' : food.servingUnit, + servingQty: loggedQty, + servingUnit: loggedUnit, + foodId: loggedFoodId, + grams: loggedGrams, caffeineMg, alcoholG, loggedAt: date ? loggedAtFor(date) : undefined, @@ -121,21 +166,30 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP } catch { Alert.alert('Error', 'Could not log food. Please try again.'); } - }, [food, isManual, name, manual.calories, mealType, servings, amount, adjustedCalories, adjustedProtein, adjustedCarbs, adjustedFat, caffeineMg, alcoholG, logFood, onClose, date]); + }, [food, isManual, name, manual.calories, usesPicker, amount, unit, mealType, loggedQty, loggedUnit, loggedFoodId, loggedGrams, adjustedCalories, adjustedProtein, adjustedCarbs, adjustedFat, caffeineMg, alcoholG, logFood, onClose, date]); if (!food) return null; + const directLabel = unit === 'ml' ? 'Millilitres' : 'Grams'; + const qtyLabel = isPortion + ? `Portions (1 = ${Math.round(food.servingQty * 10) / 10} ${food.servingUnit})` + : isManual + ? 'Servings' + : option?.direct + ? directLabel + : `Servings · ${formatGrams(amount)} ${unit}`; + return ( - + {/* Food name */} @@ -172,6 +226,11 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP {food.brand} )} + {food.verified === true && ( + + + + )} + {/* Serving picker (database foods) */} + {usesPicker && options.length > 0 && ( + + Serving + + {options.map((o) => { + const selected = o.key === option?.key; + return ( + pickOption(o)} + accessibilityRole="radio" + accessibilityLabel={o.direct ? `Type the amount in ${directLabel.toLowerCase()}` : o.label} + aria-checked={selected} + style={{ + paddingHorizontal: 12, + paddingVertical: 8, + borderRadius: 999, + backgroundColor: selected ? Colors.orange : Colors.surface2, + borderWidth: 1.5, + borderColor: selected ? Colors.orange : Colors.border, + }} + > + + {o.label} + + + ); + })} + + + )} + {/* Qty + meal type row */} - {isPortion ? `Portions (1 = ${Math.round(food.servingQty * 10) / 10} ${food.servingUnit})` : `Servings${!isManual ? ` (${food.servingQty} ${food.servingUnit})` : ''}`} + {qtyLabel} @@ -296,7 +389,7 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP