diff --git a/README.md b/README.md index 9cb57a2..68d1161 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # GRIT -A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated dark-mode mobile experience. +A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated mobile experience, in dark or light. --- @@ -36,18 +36,22 @@ grit/ | `/onboarding/advanced` | Earnback calories toggle, rollover toggle | | `/onboarding/notifications` | Notification preferences | | `/onboarding/reveal` | Personalised TDEE + macro plan reveal | -| `/onboarding/signup` | Account creation (email + password) | -| `/(auth)/login` | Returning user login | +| `/onboarding/signup` | Account creation (email + password, or Google / Apple) | +| `/(auth)/login` | Returning user login (email, Google or Apple) | | `/(tabs)/` | Home — daily calorie budget, macro progress, today's workout | -| `/(tabs)/food` | Food log — any day, meal sections, edit entries, barcode scanner | +| `/(tabs)/food` | Food log — any day, meal sections, edit entries, barcode scanner, ✨ Smart log (describe or photograph a meal) | | `/(tabs)/habits` | Habit tracker — check-ins, undo, 30-day history and back-fill | -| `/(tabs)/activity` | Stats — 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts | +| `/(tabs)/activity` | Stats — adaptive calorie target, 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts | | `/(tabs)/social` | Feed, challenges and leaderboard | | `/(tabs)/profile` | User profile + settings | | `/settings/goals` | Goals & Targets — goal, body stats, calories, macros, earnback/rollover | | `/settings/notifications` | Daily reminders and alert preferences | -| `/settings/account` | Units, password reset, log out, delete account | +| `/settings/account` | Appearance (system, light, dark), units, password reset, log out, delete account | | `/settings/privacy` | Private account and blocked people | +| `/settings/health` | Apple Health / Health Connect: connect, sync now, what was imported | +| `/settings/foods` | Foods GRIT knows: portions learned from Smart log | +| `/settings/coach-memory` | What your coach knows: notes from chats, add or delete | +| `/auth-callback` | Finishes Google or Apple sign-in | | `/plan` | Weekly workout plan built by the coach | | `/friends` | Search people, follow requests, followers and following | | `/profile/[id]` | Someone's profile: follow state, this week's stats and recent activity (if allowed) | @@ -107,18 +111,20 @@ 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) | | `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` | +| `meal-parse` | `POST /food/parse` (text and/or photo → items), `POST /food/parse/log`, `GET /food/memories`, `DELETE /food/memories/:id` | +| `health` | `POST /health/import` (workouts, daily steps and sleep, weigh-ins from Apple Health / Health Connect), `GET /health/recent` | | `activity` | `GET/POST /activity-logs`, `GET /activity-logs/week?date=`, `PATCH/DELETE /activity-logs/:id`, `POST /activity-logs/:id/kudos` | | `habits` | `GET/POST/PUT/DELETE /habits`, `POST/DELETE /habits/:id/log?date=`, `GET /habits/streaks`, `GET /habits/:id/streak` | | `workout-plan` | `GET /workout-plan`, `POST /workout-plan/generate`, `PUT /workout-plan/days/:day` | | `challenges` | `GET/POST /challenges` (steps, active minutes or workouts; progress from logged workouts), `GET/DELETE /challenges/:id`, `POST /challenges/join/:code`, `DELETE /challenges/:id/participants/me` | | `social` | `GET /feed`, `GET /leaderboard/weekly`, `GET /search/users?q=`, `POST/DELETE /follow/:userId`, `GET /follow-requests`, `POST /follow-requests/:userId/accept`, `DELETE /follow-requests/:userId`, `DELETE /followers/:userId`, `GET /users/:id/{profile,followers,following}`, `GET/POST/DELETE /blocks` | -| `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90` | -| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge` — AI coach | +| `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90`, `GET /targets/adaptive`, `POST /targets/adaptive/apply`, `POST /targets/adaptive/snooze` | +| `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, 8pm streak-at-risk and Sunday 6pm weekly check-in, in each user's local time | +| `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 | -**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood +**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay See [`docs/ROADMAP.md`](./docs/ROADMAP.md) for what's done and what's next. diff --git a/apps/mobile/__tests__/healthTransform.test.ts b/apps/mobile/__tests__/healthTransform.test.ts new file mode 100644 index 0000000..2ee57cd --- /dev/null +++ b/apps/mobile/__tests__/healthTransform.test.ts @@ -0,0 +1,57 @@ +import { androidExerciseType, appleWorkoutType, latestWeightPerDay, sleepByNight, toImportPayload } from '@/lib/health/transform'; + +const at = (iso: string) => new Date(iso); + +describe('health transform', () => { + it('maps workout types from both platforms', () => { + expect(appleWorkoutType(37)).toBe('running'); + expect(appleWorkoutType(50)).toBe('strength_training'); + expect(appleWorkoutType(9999)).toBe('other'); + expect(androidExerciseType(79)).toBe('walking'); + expect(androidExerciseType(54)).toBe('rowing'); + expect(androidExerciseType(-1)).toBe('other'); + }); + + it('counts overlapping sleep once and removes awake time', () => { + const nights = sleepByNight([ + // Phone and watch both recorded 23:00–07:00 + { start: at('2026-11-03T23:00:00'), end: at('2026-11-04T07:00:00'), asleep: true }, + { start: at('2026-11-04T00:00:00'), end: at('2026-11-04T06:30:00'), asleep: true }, + // 30 minutes awake in the middle + { start: at('2026-11-04T03:00:00'), end: at('2026-11-04T03:30:00'), asleep: false }, + ]); + expect(nights).toEqual({ '2026-11-04': 450 }); + }); + + it('keeps the last weigh-in of each day and drops silly values', () => { + expect( + latestWeightPerDay([ + { at: at('2026-11-04T07:00:00'), kg: 80.2 }, + { at: at('2026-11-04T20:00:00'), kg: 80.9 }, + { at: at('2026-11-03T07:00:00'), kg: 81 }, + { at: at('2026-11-02T07:00:00'), kg: 2 }, + ]), + ).toEqual([ + { date: '2026-11-03', weightKg: 81 }, + { date: '2026-11-04', weightKg: 80.9 }, + ]); + }); + + it('builds the import body, merging steps and sleep per day', () => { + const now = at('2026-11-04T12:00:00'); + const body = toImportPayload('healthkit', { + workouts: [ + { id: 'hk:1', activityType: 'running', start: at('2026-11-04T07:00:00'), end: at('2026-11-04T07:32:30'), kcal: 310.6 }, + { id: 'hk:future', activityType: 'yoga', start: at('2026-11-05T07:00:00'), end: at('2026-11-05T08:00:00') }, + ], + steps: [{ date: '2026-11-04', steps: 6400.4 }, { date: '2026-11-05', steps: 10 }], + sleep: [{ start: at('2026-11-03T23:30:00'), end: at('2026-11-04T06:30:00'), asleep: true }], + weights: [{ at: at('2026-11-04T07:00:00'), kg: 80.21 }], + }, now); + expect(body.workouts).toEqual([ + { externalId: 'hk:1', activityType: 'running', startedAt: at('2026-11-04T07:00:00').toISOString(), durationMin: 33, caloriesBurned: 311 }, + ]); + expect(body.days).toEqual([{ date: '2026-11-04', steps: 6400, sleepMinutes: 420 }]); + expect(body.weights).toEqual([{ date: '2026-11-04', weightKg: 80.21 }]); + }); +}); diff --git a/apps/mobile/__tests__/notificationRoute.test.ts b/apps/mobile/__tests__/notificationRoute.test.ts index 4b3b499..142edec 100644 --- a/apps/mobile/__tests__/notificationRoute.test.ts +++ b/apps/mobile/__tests__/notificationRoute.test.ts @@ -7,6 +7,9 @@ describe('where an alert opens', () => { expect(notificationRoute('challenge_ended', { challengeId: 'c1' })).toEqual({ pathname: '/challenge/[id]', params: { id: 'c1' } }); expect(notificationRoute('streak_at_risk')).toBe('/(tabs)/habits'); expect(notificationRoute('weekly_progress')).toBe('/(tabs)/activity'); + expect(notificationRoute('coach_checkin', { screen: 'food' })).toBe('/(tabs)/food'); + expect(notificationRoute('coach_checkin', { screen: 'stats' })).toBe('/(tabs)/activity'); + expect(notificationRoute('coach_checkin', {})).toBe('/coach'); }); 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__/smartLog.test.ts b/apps/mobile/__tests__/smartLog.test.ts new file mode 100644 index 0000000..403a1f6 --- /dev/null +++ b/apps/mobile/__tests__/smartLog.test.ts @@ -0,0 +1,9 @@ +import { mealForHour } from '@/lib/meals'; + +describe('mealForHour', () => { + it('picks the meal for the time of day', () => { + expect([6, 10, 11, 14, 15, 16, 17, 21, 22, 2].map(mealForHour)).toEqual([ + 'breakfast', 'breakfast', 'lunch', 'lunch', 'snack', 'snack', 'dinner', 'dinner', 'snack', 'snack', + ]); + }); +}); diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 55b4126..e541b2f 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -6,7 +6,7 @@ "scheme": "grit", "orientation": "portrait", "icon": "./assets/icon.png", - "userInterfaceStyle": "dark", + "userInterfaceStyle": "automatic", "splash": { "image": "./assets/splash-icon.png", "resizeMode": "contain", @@ -57,7 +57,11 @@ "foregroundImage": "./assets/android-icon-foreground.png" }, "permissions": [ - "android.permission.CAMERA" + "android.permission.CAMERA", + "android.permission.health.READ_EXERCISE", + "android.permission.health.READ_STEPS", + "android.permission.health.READ_WEIGHT", + "android.permission.health.READ_SLEEP" ], "blockedPermissions": [ "android.permission.RECORD_AUDIO" @@ -74,7 +78,7 @@ [ "expo-camera", { - "cameraPermission": "GRIT uses your camera to scan food barcodes.", + "cameraPermission": "GRIT uses your camera to scan food barcodes and photograph meals.", "microphonePermission": false, "recordAudioAndroid": false } @@ -90,10 +94,31 @@ [ "expo-image-picker", { - "photosPermission": "GRIT uses your photos so you can choose a profile picture.", - "cameraPermission": false, + "photosPermission": "GRIT uses your photos so you can choose a profile picture or log a meal from a photo.", + "cameraPermission": "GRIT uses your camera to photograph meals so it can estimate what's in them.", "microphonePermission": false } + ], + "expo-apple-authentication", + "expo-web-browser", + [ + "@kingstinct/react-native-healthkit", + { + "NSHealthShareUsageDescription": "GRIT reads your workouts, steps, sleep and weight so they count toward your goals and challenges, and so your coach can see how you're recovering.", + "NSHealthUpdateUsageDescription": false, + "background": false + } + ], + "react-native-health-connect", + [ + "expo-build-properties", + { + "android": { + "compileSdkVersion": 36, + "targetSdkVersion": 36, + "minSdkVersion": 26 + } + } ] ], "extra": { diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx index bdd7568..1c6c9fa 100644 --- a/apps/mobile/app/(auth)/login.tsx +++ b/apps/mobile/app/(auth)/login.tsx @@ -1,29 +1,27 @@ import React, { useState } from 'react'; import { View, + Platform, Text, KeyboardAvoidingView, - Platform, ScrollView, Pressable, Alert, } from 'react-native'; import { Link, router } from 'expo-router'; import { supabase } from '@/lib/supabase'; -import { api } from '@/lib/api'; -import { useAuthStore } from '@/stores/authStore'; -import { syncOnboardingProfile } from '@/lib/onboardingProfile'; import { Button } from '@/components/ui/Button'; import { Input } from '@/components/ui/Input'; import { notify } from '@/lib/confirm'; import { sendPasswordReset } from '@/lib/passwordReset'; import { Colors } from '@/constants/colors'; +import { afterSignIn } from '@/lib/postSignIn'; +import { SocialSignIn } from '@/components/auth/SocialSignIn'; export default function LoginScreen() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); - const { setOnboardingComplete } = useAuthStore(); async function handleEmailLogin() { if (!email || !password) { @@ -32,15 +30,11 @@ export default function LoginScreen() { } setLoading(true); try { - const { error } = await supabase.auth.signInWithPassword({ email, password }); + const { data, error } = await supabase.auth.signInWithPassword({ email, password }); if (error) throw error; - await setOnboardingComplete(); - // Sync user record with backend (creates if first login) - await api.post('/auth/sync'); - // Save any plan answered before signing up (e.g. pending email confirmation) - await syncOnboardingProfile().catch(() => { - // Kept on the device and retried at the next login - }); + // Creates the backend user on first login and saves any plan answered + // before signing up (e.g. while the email was being confirmed) + await afterSignIn(data.session); router.replace('/(tabs)/'); } catch (err: any) { Alert.alert('Login failed', err.message ?? 'Something went wrong.'); @@ -126,36 +120,8 @@ export default function LoginScreen() { /> - {/* Divider */} - - - - or - - - - - {/* OAuth */} - -