# Frontend integration guide (React Native app → Cognivision backend) **Audience:** the frontend engineer or coding agent connecting the app to the backend. **Goal:** replace the local AsyncStorage store (`src/store`, `AppContext`) with API calls. Every screen keeps calling the same context actions; only the store layer changes. **Status:** all 4 milestones are implemented. They are verified end to end against the real Supabase database and DigitalOcean Spaces bucket (713 QA checks, `backend/e2e/`). The coaching workflow and academy APIs (§14) are implemented and tested locally (465 e2e checks). ## 0. Sources of truth (read in this order) | What | Where | Use it for | |---|---|---| | Machine-readable API | `backend/docs/openapi.json` (also served at `GET /openapi.json` where enabled) | Generate TypeScript types. Errors use the envelope in §3. Swing and pitching report requests/responses are typed, and saved session reports include both kinds plus null. | | Swing report (the analysis result) | `AI-coach-agent/docs/SWING_REPORT_API.md` | How to render scores, ratings, groups, focus area and measurements | | Pitching integration | [Pitching API integration](../../docs/PITCHING_APP_INTEGRATION.md) | Pitching marks/context, `pitch-1.1` ML payload, report groups, unavailable scores and coaching retry | | ML payload the app forwards | `backend/docs/reference/ml_contract_v1.md` | What the ML API returns and the app posts to us, unchanged | | This guide | `backend/docs/FRONTEND_INTEGRATION.md` | Flows, mapping from the old store, rules, edge cases | | Coaching workflow contract | `backend/docs/reference/coaching_workflow_spec.md` and `coaching_workflow_decisions.md` | Spec IDs N01–N50 and C01–C08 used in §14 | When this guide and `openapi.json` disagree, `openapi.json` wins. Please report the mismatch. Regenerate older client models before adding pitching: `POST /v1/sessions/{id}/pitch-report` accepts `pitch-1.1`. `SessionOut.report` is a nullable union of the existing swing/legacy report and the current pitching report. Report `schema_version` remains `1.0` for both; use `discipline` when present and session `mode` for legacy reports. Regular fastballs and unknown contexts are scored; see `AI-coach-agent/docs/PITCH_REPORT_API.md`. When generating with `openapi-typescript`, use `--default-non-nullable false` so optional fields with defaults remain optional. Version 7.13.0 with that setting passed strict TypeScript compilation using current pitching, legacy pitching and hitting fixtures; the pitching guide includes the complete command. ## 1. Conventions - **Base URL:** `https:///v1/...` (deployment owns the host). Local development: `http://127.0.0.1:8000`. - **JSON keys are `snake_case`** in requests and responses. Map them to camelCase in your API adapter if the app wants camelCase, and never send camelCase: unknown fields are rejected with 400. - **Ids** are UUID strings. **Times** are ISO 8601 UTC; convert to local time for display. - **Body measurements are metric** (`height_cm`, `weight_kg`). The account's `unit` only affects display. - **Enums:** - `role`: `player` | `coach` - `focus`: `h` | `p` | `both` - `mode`: `h` | `p` - `bats`: `L` | `R` | `S` - `throws`: `L` | `R` - `level`: `youth` | `high_school` | `college` | `adult`. The old app used "High school" and similar labels; map them in the adapter. - `unit`: `imperial` | `metric` - **Lists** return `{ "items": [...], "next_cursor": "..." | null }`. Ask for the next page with `?cursor=&limit=<1..200>` (default 50). - **Retries:** `POST /v1/sessions` and `POST /v1/drill-logs` accept an `Idempotency-Key: ` header. Retrying with the same key and body returns the original response. The same key with a different body returns 409 `IDEMPOTENCY_KEY_REUSED`. Generate one key per user action and reuse it only for retries of that action. - **Request id:** every response has an `X-Request-Id` header. Attach it to bug reports. You may send your own `X-Request-Id`. ## 2. Authentication and session restore ``` Authorization: Bearer ``` All endpoints except `/v1/auth/*` (other than logout) need it. | Step | Call | Notes | |---|---|---| | Sign up | `POST /v1/auth/register` `{email, password, role}` | 201 `{user, tokens}`. The password must be 8 to 128 characters. 409 `EMAIL_TAKEN`: show its message inline. | | Sign in | `POST /v1/auth/login` `{email, password}` | 200 `{user, tokens}`. 401 `INVALID_CREDENTIALS`: show the message verbatim. 429 `RATE_LIMITED` after 10 failures a minute from one network. | | Apple / Google | `POST /v1/auth/social` `{provider, id_token, role}` | 200 `{user, tokens, is_new}`. If `is_new` is true, route to the Role screen. 401 `INVALID_TOKEN`. | | Restore on launch | `GET /v1/me` | Returns `{user, team, entitlement}`, which seeds Home, Profile, Roster and Team in one call. | | Token expired | `POST /v1/auth/refresh` `{refresh_token}` | Returns new `{access_token, refresh_token, expires_in}`. **Store the new refresh token.** Refresh tokens rotate, and reusing an old one revokes the whole sign-in. | | Sign out | `POST /v1/auth/logout` `{refresh_token}` and `DELETE /v1/devices/{push_token}` | Then clear the keychain and the local cache. | | Forgot password | `POST /v1/auth/password/forgot` `{email}` | Always 202. Show "check your email". | | Delete account | `DELETE /v1/me` | 204. Removes the account, its sessions and its media. Required by the app stores. | **Token rules for the HTTP client:** 1. Keep `access_token` (valid about 30 minutes) in memory and `refresh_token` in the keychain, not AsyncStorage. 2. When a call fails with 401 `UNAUTHENTICATED`, call refresh **once** and retry the original request. 3. If refresh fails with 401 `TOKEN_REVOKED`, sign the user out to Welcome. 4. Allow only one refresh in flight: queue other requests behind it. Two parallel refreshes with the same token count as reuse and revoke the sign-in. ## 3. Errors (one shape everywhere) ```json { "error": { "code": "VALIDATION", "message": "Some fields are not valid.", "fields": { "profile.age": "Input should be less than or equal to 70" } } } ``` `message` is always safe to show. `fields` appears on validation errors, with keys as dotted paths (`marks.contact_frame`, `measurements[1].reasons`). | HTTP | `code` | Where | What the app should do | |---|---|---|---| | 400 | `VALIDATION` | Any write | Show `fields` inline under the inputs | | 400 | `TOKEN_INVALID` | Password reset | "This link has expired" | | 401 | `UNAUTHENTICATED` | Any | Refresh once, then sign out | | 401 | `INVALID_CREDENTIALS` | Login | Show the message | | 401 | `TOKEN_REVOKED` | Refresh | Sign out | | 401 | `INVALID_TOKEN` | Social sign-in | "Sign-in failed, try again" | | 402 | `PLAN_LIMIT` | Create session, swing report | Show the upgrade alert. The message is "The free plan includes 20 analyses a week." | | 403 | `FORBIDDEN` | Any | Not allowed. Coach endpoints called by a player, someone else's session, and so on. | | 404 | `NOT_FOUND` | Any | "This session is gone" and similar | | 404 | `TEAM_NOT_FOUND` | Lookup, join | Show the message | | 404 | `PLAYER_NOT_ON_TEAM` | Coach player page | "Player not on your team" | | 405 | `METHOD_NOT_ALLOWED` | Any | Bug in the client | | 409 | `EMAIL_TAKEN`, `ROLE_LOCKED`, `STALE_REVISION`, `ANALYSIS_MISMATCH`, `IDEMPOTENCY_KEY_REUSED`, `RECEIPT_IN_USE` | See the flows | See the flows | | 413 | `TOO_LARGE` | Uploads, swing report | "Clip too large" | | 422 | `UPLOAD_MISSING`, `UPLOAD_INVALID` | Create session | Upload again, or record again | | 422 | `INVALID_PAYLOAD` | Swing report | The ML payload broke the contract. Log `fields` and show "analysis failed, please re-film". | | 422 | `MODE_NOT_SUPPORTED` | Report route does not match session mode, or unsupported coaching retry | Use `/swing-report` for `mode=h` and `/pitch-report` for `mode=p`; coaching retry requires saved pitch-1.1 evidence. | | 422 | `RECEIPT_INVALID` | Billing | "Purchase could not be verified" | | 429 | `RATE_LIMITED` | Login, forgot password, team lookup | "Too many attempts. Wait a minute." | | 5xx | `INTERNAL` / `UNAVAILABLE` | Any | Generic retry message | ## 4. Store action → endpoint map This replaces the local store behind `AppContext`; screens don't change. | AppContext action (today) | Endpoint | Notes | |---|---|---| | `signUp(email, password, role)` | `POST /v1/auth/register` | | | `signIn(email, password)` | `POST /v1/auth/login`, then `GET /v1/me` | | | `signOut()` | `POST /v1/auth/logout` + `DELETE /v1/devices/{token}` | | | `setRole(role)` | `PATCH /v1/me {role}` | 409 `ROLE_LOCKED` once the account has a team or a session | | `setFocus(focus)` | `PATCH /v1/me {focus}` | | | `updateProfile(patch)`, `setUnit(unit)` | `PATCH /v1/me {profile: {...}, unit}` | Inside `profile`, `null` clears a value. At the top level, `null` is rejected. | | `setPrivateVideos(bool)` | `PATCH /v1/me {private_videos}` | It never blocks the coach (see §8) | | `createTeam(name, coachName, coaching)` | `POST /v1/teams {name, coach_name, coaching}` | 201 the first time. A second call updates the team (200) and keeps the code and the members. | | `findTeam(code)` | `GET /v1/teams/lookup?code=` | Debounce while typing. Matching ignores case and spaces. | | `joinTeam(code)` | `POST /v1/teams/{code}/join` | Players only. Joining another team moves the player. | | `leaveTeam()` | `DELETE /v1/me/team` | | | `addSession(args)` | §5 flow: uploads, session, ML API, swing report | | | `getSession(id)` | `GET /v1/sessions/{id}` | | | `mySessions(mode)` | `GET /v1/sessions?mode=h&self=true` | Newest first | | `deleteSession(id)` | `DELETE /v1/sessions/{id}` | The media is deleted immediately | | `logSet(session, drill, reps)` | `POST /v1/drill-logs {session_id, drill_id, reps, day}` | `day` is the device's local date (YYYY-MM-DD) | | `setsToday(drill)` / the 7-day dots | `GET /v1/drill-logs?from=&to=` | Count logs for the drill and today's date on the client. Range at most 90 days. | | `roster` | `GET /v1/coach/roster` | | | `sessionsOf(playerId)` | `GET /v1/coach/players/{id}/sessions?mode=` | | | `queue` | `GET /v1/coach/queue?since=` | Send `since` so "Reviewed today" matches the coach's day | | `sendReview(sessionId, {cue, drill, verdicts})` | `POST /v1/sessions/{id}/review {cue, drill_id, verdicts}` | | | `analysesLeft`, `setPlan` | `GET /v1/me/entitlement`, `POST /v1/billing/receipts` | | | `loadSample()`, `resetAll()` | none | Dev only. Keep them local or remove them. | Values the client computed before now come from the server: - `team` comes from `GET /v1/me`. - `roster`, `queue` and `analysesLeft` (`entitlement.left`) come from their endpoints. - The session title number comes from `ordinal`, and the delta comes from `previous.overall_score`. ## 5. Recording a swing (the core flow) The app calls the ML API itself. Our backend never calls the ML API: the app forwards the ML result to us. ``` 1. POST /v1/uploads {kind:"video", content_type:"video/mp4"|"video/quicktime", size_bytes, duration_sec} → {upload_id, url, headers, expires_at} PUT with the file bytes and EXACTLY the returned headers (Content-Type) ← straight to storage 2. Same for the thumbnail: {kind:"thumbnail", content_type:"image/jpeg", size_bytes} (optional, recommended) 3. POST /v1/sessions (Idempotency-Key header) {video_upload_id, thumbnail_upload_id, mode:"h", is_self:true, athlete:null, duration_sec, fps, marks:{contact_frame, contact_offset, contact_source:"detected"|"suggested"|"manual", stride_start_frame, stride_end_frame, pitcher_direction:{from:[x,y], to:[x,y]}}} → 201 {session} with status "pending", report null 4. Call the ML API (not ours) → contract 1.0 payload 5. POST /v1/sessions/{session.id}/swing-report with the ML payload, unchanged → 200 swing report (also saved on the session) 6. Show Result from the step 5 response (or GET /v1/sessions/{id}: report is the same object) ``` **Limits and rules:** - **Video:** `video/mp4` or `video/quicktime`, at most 250 MB and 60 s. **Thumbnail:** `image/jpeg`, at most 5 MB. Presigned URLs expire after 15 minutes, so upload right away. - **Uploaded files must match their type.** A JPEG sent as a video is rejected at step 3 with 422 `UPLOAD_INVALID`. If step 3 says `UPLOAD_MISSING`, the PUT never finished: retry the upload. - **Marks:** - `stride_start_frame < stride_end_frame < contact_frame`, all within `0 .. round(duration_sec*fps)-1`. - `pitcher_direction` is optional: omit it or send `null` when no manual direction is available. The session returns it as `null`. When supplied, its points must be fractions of the frame, from 0 to 1, and at least 0.08 apart. This stored annotation does not trigger engine analysis; the motion engine attempts automatic direction estimation independently. - Pitching labels map like this: leg lift is `stride_start_frame`, foot strike is `stride_end_frame`. - **Athlete:** - For `is_self: true`, send `athlete: null`; the server snapshots the profile. - For someone else's swing, send `{name, age, height_cm, weight_kg, bats, throws, level}`; all are required. - **Plan:** the free plan allows 20 analysed swings in a rolling 7 days, counting swings filmed for someone else. Step 3 returns 402 `PLAN_LIMIT` before anything is stored. Pending sessions that never get a report don't count, and are deleted with their media after 24 h. - **Reports are queued (default):** step 5 (`/swing-report` or `/pitch-report`) does not return the report. The player can keep recording swing after swing and does not have to keep the screen open. - The checks run in the request, so 402, 403, 409 and 422 answer immediately. - The response is **202** `{"session_id":"...","status":"queued"}`. The status is `"done"` when this revision already has its report; nothing is queued then. - The backend builds queued reports in the background, oldest first. There is no limit on how many a player can queue, apart from the plan: queued swings count toward the weekly limit as soon as they are queued. - When a report is saved the owner gets a notification of kind `result` with `target: {"session_id", "mode", "outcome":"ready"}` and a push (unless `notify_results` is off). Route it to Result by `session_id` (§14.5), then read the report from `GET /v1/sessions/{id}`. - If the build fails the notification has `outcome:"failed"`, and the session shows `status:"failed"` with `report_error:"REPORT_FAILED"`. Post the payload again to retry. - Session statuses are `pending` (no payload posted yet), `queued`, `done` and `failed`, on `GET /v1/sessions/{id}` and the session list. - **Waiting on screen instead:** add `?queue=false` to step 5. The report is built in the request and returned with **200**, as before; no notification is sent. **App builds released before queueing must add `?queue=false` or handle the 202**, otherwise they receive no report body. - **Pitching:** for a `mode:"p"` session, step 5 is `POST /v1/sessions/{id}/pitch-report` with the ML pitch payload (contract `pitch-1.1`, see `AI-coach-agent/docs/PITCH_REPORT_API.md`). It returns the pitching report, with the groups `gather`, `stride_plant`, `rotation_release` and `release_finish`, and the same revision, plan and consent rules. Posting to the wrong endpoint for the session mode returns 422 `MODE_NOT_SUPPORTED`. The throwing side comes from the payload's `athlete.throwing_hand`, then the session athlete's `throws`. - **Re-analysis:** post a payload with a higher `analysis_revision` and the same `analysis_id`. - Re-posting the same id and revision is safe: it returns the stored report. - A lower revision returns 409 `STALE_REVISION`. - A different `analysis_id` on the same session returns 409 `ANALYSIS_MISMATCH`. - **Batting side:** the report uses the payload's `athlete.batting_hand`. When that is missing, it falls back to the session athlete's `bats`. ## 6. Rendering the swing report (Result, Phase and Recap screens) The full field list is in `SWING_REPORT_API.md`. The app renders; it never computes scores or ratings. ### The old Session shape and the new one | Old local shape | New field | Notes | |---|---|---| | `score` | `report.overall_score` (0–100 or null) | Null when nothing could be rated. Show "Not rated" and never 0. | | `phases: [name, score][]` | `report.groups[]` | Always 4, in a fixed order: `balance_load`, `stride`, `power_move`, `contact_follow_through`. Each has `{display_name, score, rating, rating_label, summary}`. | | `weak` | The lowest-scoring rated group, or `report.focus_area.group` | | | `metrics[]` | `report.measurements[]` | `{metric_id, display_name, group, value, unit, display_value, score, rating, rating_label, rating_is_tentative, benchmark, what_it_means, result_text, coach_tip, limitations[]}` | | `metric.grade` (`g`, `b`, `o`) | `rating`: `on_target`, `satisfactory`, `off_target`, `not_rated` | Colors: green, yellow, red, grey | | `metric.band` / `target` | `benchmark.on_target {lower, upper}` and `benchmark.satisfactory` | Use them for a range bar. `value` sits on the same axis. | | `metric.why` | `what_it_means` (meaning) and `result_text` (what we saw) | | | `fixOrder[0]`, cue, drill | `report.focus_area {display_name, rating, coach_message, practice_feel, drill {drill_id, name, how, cue, reps}}` | Null when nothing needs work: show `overview.headline` instead | | (none) | `report.overview.headline` | Show it as the coach bubble | | (none) | `report.data_quality[] {code, severity, text}` | Always show, as a "Keep in mind" list | | drill name as key | `drill_id` (for example `hit_13`) | Look up names with `GET /v1/catalog/metrics?mode=h`, or use `focus_area.drill` | **Rendering rules:** - **`not_rated`:** the group or measurement shows `rating_label` ("Not measured yet", "Not measured" or "Not rated") in grey. Never show a score. - **`rating_is_tentative: true`:** the value was a model estimate. Show the rating with a "≈" or "approximate" hint, and always show `limitations[].text` under it. - **Text fields are plain text with no numbers.** Numbers appear only in `value`, `display_value` and `benchmark`. Don't reword the text. - **No video highlighting:** the report doesn't point at the video. For Recap timing, use the session's own `marks`. - **`meta`** is for logs and support only. Don't show it. ## 7. Practice and history - **History:** `GET /v1/sessions?mode=h&self=true&since=` gives summaries with `{overall_score, focus {metric_id, display_name, drill_id}, review {coach_name, at}, thumbnail_url, status}`. Compute the trend, best, average and streak on the client from `overall_score` and `created_at`. - **Title and delta:** `GET /v1/sessions/{id}` gives `ordinal` ("Swing 4"; only analysed swings are numbered) and `previous {id, overall_score, created_at}`. If `previous` is null, show the "First rep" badge. - **Drill of the day:** use the latest session's `report.focus_area.drill`, or the coach's `review.drill_id` when the session was reviewed. - **Logging a set:** `POST /v1/drill-logs`. `reps` is 1 to 8, and the 3-sets-a-day rule stays on the client. - **Media URLs** (`media.video_url`, `thumbnail_url`) expire after `media.expires_at` (1 hour). If playback fails, fetch `GET /v1/sessions/{id}` again. ## 8. Coach | Screen | Call | Notes | |---|---|---| | Roster | `GET /v1/coach/roster` | `{items: [{id, name, email, focus, level, pending_count, last: {h, p}, recent: {h: [scores], p: [...]}}]}`. `last.h` is `{session_id, overall_score, delta, created_at, focus_name}` or null ("Not filmed yet"). Compute the "Stuck" flag from `recent.h`. There is never any body data. | | Queue | `GET /v1/coach/queue?since=` | `{open: [...oldest first], reviewed_today: [...]}`. Items are session summaries plus `owner_name`. | | Player page | `GET /v1/coach/players/{id}/sessions?mode=` | Only analysed own swings | | Review | `GET /v1/sessions/{id}` then `POST /v1/sessions/{id}/review` | See below | **Review rules:** - **Request body:** `{cue (1–200 characters), drill_id, verdicts: {metric_id: "agree"|"change"|"later"}}`. - Verdict keys must be the report's `measurements[].metric_id`. - `drill_id` must be a hitting drill for a hitting session. - The first send returns 201. Sending again overwrites and returns 200. - The player gets a push. - **What the coach can see:** only the team's players' own swings, and only once analysed. Someone-else swings and pending swings return 403. - **Body data is hidden:** in coach views of a session, `athlete` has no `age`, `height_cm` or `weight_kg`. - **`private_videos`:** stored on the account, but it does not block the coach. The UI copy says "Only you and your coaches". - **Leaving the team:** when a player leaves, their sessions disappear from the coach's views immediately. ## 9. Push notifications - **Register:** after the user grants permission and after each sign-in, call `POST /v1/devices {platform: "ios"|"android", push_token}` with the FCM token (201, or 200 if already registered). Calling it again is safe. A token registered by another account moves to the current one. - **Unregister:** on sign-out, `DELETE /v1/devices/{push_token}`. - **Payload:** `data: {type: "review.received", session_id}` → open Result for `session_id`. It also carries a title and body notification. There is no `analysis.done` push, because the analysis is synchronous (§5). New pushes also carry `notification_id`, `kind` and `target_json`; see §14.5. ## 10. Plan and billing - **Entitlement:** `GET /v1/me/entitlement` (also inside `GET /v1/me`) returns `{plan: "free"|"pro", weekly_limit, used_this_week, left, window_days}`. `weekly_limit` and `left` are null on pro. - **iOS (StoreKit 2):** after a purchase, `POST /v1/billing/receipts {platform:"ios", product_id:"pro_monthly", signed_transaction:}` returns `{entitlement}`. - **Android:** `POST /v1/billing/receipts {platform:"android", product_id:"pro_monthly", purchase_token}`. The server acknowledges the purchase. - **Errors:** 400 for a product that isn't allowed, 422 `RECEIPT_INVALID`, 409 `RECEIPT_IN_USE` (the purchase belongs to another account). Re-posting the same purchase is safe; use it for "Restore purchases". - **Renewals, cancellations and refunds** come from store webhooks to the server. Refresh entitlement on app foreground. ## 11. Catalog `GET /v1/catalog/metrics?mode=h` returns: - `groups[] {group, display_name}` - `metrics[] {metric_id, display_name, group, unit, what_it_means}` - `drills[] {drill_id, name, how, cue, reps}` Use it for drill names and the review drill picker. `mode=p` returns pitching drills only for now. ## 12. Differences from the original frontend spec | Spec said | Backend does | Why | |---|---|---| | camelCase keys | snake_case | Backend convention; map in the adapter | | `user.plan` | `entitlement.plan` | The plan comes from subscriptions, not from a field on the user | | Session `status` queued, processing, done, failed; poll D3 | `pending` → `done`; synchronous swing report | The app runs the ML step itself | | 10 metrics, 5 phases, grades `g/b/o` | 4 groups, the registered measurements, ratings | Matches the ML contract and the report spec | | Drill names as keys | `drill_id` | Stable ids; names come from the catalog | | Roster `joinedAt` | Not provided | Join time is not stored; show `email` when `name` is empty | | D5 deletes after a lifecycle period | D5 deletes the media immediately | Privacy | | `level` "High school" and similar labels | `high_school` and similar enum values | Map in the adapter | | `pitcherDir` | `marks.pitcher_direction {from, to}` | Optional; omit or send `null` for automatic engine direction estimation. | | `contactSec`, `strideStartSec`, etc. | Not stored | Compute them as `frame / fps` | ## 13. Checklist per milestone 1. **Accounts and teams:** - A1 register, A2 login, A4 refresh, A5 logout, B1 `GET /me`, B2 `PATCH /me`, and team create, lookup, join and leave all wired. - Errors are shown inline. - Tokens are in the keychain, with a single-flight refresh. 2. **Sessions:** - Upload, PUT, session and swing-report flow wired, with an Idempotency-Key. - Result renders from `report`. - History, delete, drill logs and the plan alert on 402. 3. **Coach:** - Roster, queue, player page and review wired. - Device registration and the `review.received` deep link. 4. **Growth:** - Social sign-in, forgot password, account deletion in Profile. - StoreKit and Play purchases posted to `/billing/receipts`; catalog used for drill names. To check the backend at any time: `cd backend && .venv/bin/python e2e/qa_sessions_reports.py` against a running API (see `backend/e2e/README.md`). ## 14. Coaching workflow and academy (settings, consent, notifications, threads, goals, assignments, arm care, staff, groups, library, reporting) This part replaces the `src/mock/*` adapters. Spec IDs (N01–N50, C01–C08) refer to `reference/coaching_workflow_spec.md`. It is covered by integration tests, the black-box suite `e2e/qa_coaching_workflow.py` and a contract test against the spec examples (`tests/integration/test_qa_contract.py`). ### 14.1 Conventions (in addition to §1) - **Wrappers.** A single resource comes wrapped (`{settings:{...}}`, `{goal:{...}}`, `{thread:{...}}`). A list returns `{items, next_cursor}`. Unwrap these in the adapter. - **Pagination.** Pass `?limit=1..200&cursor=`. A screen that needs the full set (badges, Queue Sent, CoachHistory) must follow `next_cursor`. Never treat the first page as the whole list. - **Validation errors are 400 `VALIDATION`** with `fields`, as everywhere else in this API. The spec says 422; the existing client already handles 400. - Named domain rules return 422 or 409 with a specific `code`. Each section below lists them. - **`expected_version`.** Editable resources return `version`. Send it back as `expected_version`. On 409 `STALE_VERSION`, refetch and let the user retry. - **`Idempotency-Key: `** is accepted on every POST that creates something: - consent, exports, messages, assignments, set logs, arm-care outings; - coach-access applications, staff codes, request decisions; - groups, roster adds, library publishing, the consent CSV. - Make one key per user action. Reuse it only when retrying, including after a timeout. - **New HTTP method: PUT.** `src/api/client.ts` must add `PUT` to its method union. Goals, notes and arm feel use it. - **Dates.** A date-only field (`due_date`, `day`, `local_date`) is the device's local `YYYY-MM-DD`. Instants are UTC. Server-side timezones are not modelled yet, so send local dates. - **Media.** Audio and video always arrive as `MediaRef`: `{upload_id, url, expires_at, seconds?}`. - `url` is a short-lived presigned GET. Never store it. - When it expires, refetch the resource that contained it (thread, assignment, library). - **Never show demo data.** Remove the AsyncStorage seed for these features. An absent value is `null`, an empty list or `unavailable_reason`. Render "not available yet", never a made-up number. - **Reads never mark anything as read.** Use the explicit read endpoints. ### 14.2 Account capabilities: what to show (C03) `GET /v1/me` now also returns: ```json { "academy": {"id": "...", "name": "Northside", "role": "admin|coach|assistant", "status": "active", "sees_all": true, "group_ids": ["..."], "permissions": {"review": true, "drills": true, "goals": true, "library": true, "earnings": true}}, "coach_access": {"status": "none|pending|approved|declined", "code": null, "sent_at": null}, "capabilities": {"player": true, "coach": false, "academy_admin": false, "corporate_view": false} } ``` - `academy` is `null` when the account has no active academy role. - An **academy** is the existing team. The coach who created the team is its implicit `admin`. - **Drive navigation from `capabilities`, not from `user.role`:** - `capabilities.coach` shows the coach tabs. - `capabilities.academy_admin` shows the Team admin tools: Dashboard, Earnings, CoachRequests, StaffCodes, CoachManage, Consent and Groups. - `corporate_view` is always false today, so hide CorpDash. - **Dual role.** A player whose coaching application is approved has `capabilities.player` and `capabilities.coach` both true. Offer a mode switch and keep the player tabs working. - Use `academy.permissions` to hide buttons. The server enforces them anyway with 403: - `drills`: assign a drill. - `goals`: set a goal. - `library`: upload a drill video. - `review`: review or message. - **Assistants** always have `drills:false` and `goals:false`. - **Refetch `/me`:** after a coach-access application, after an admin decision and when the app returns to the foreground. - A paused coach gets 403 on coach endpoints. - Route a 403 to a "your access is paused" screen. ### 14.3 Screen → endpoint map | Screen / mock function | Call | Notes | |---|---|---| | Settings, Guide, ReportCard: `settings.get` | `GET /v1/me/settings` | | | Settings toggle: `settings.update` | `PATCH /v1/me/settings` | Send only the changed fields plus `expected_version`. Use the returned values; roll back the toggle on failure. | | Guide consent: `settings.consent` | `POST /v1/me/consent {version:"1.0", accepted:true}` | **Wait for 201 before opening the camera.** Don't continue on error (the mock fails open today). | | Settings, withdraw consent | `DELETE /v1/me/consent` | 204 | | Settings, Download all my videos | `POST /v1/me/exports {scope:"videos"}` | 202 means "queued", not "sent". Toast: "We'll email you the links." | | Home bell | `GET /v1/notifications/unread-count` | | | Notifications list | `GET /v1/notifications` | | | Notification tap | `POST /v1/notifications/{id}/read`, then route by `target` | See §14.5 | | Mark all read | `POST /v1/notifications/read-all {through: }` | | | Messages, Home, CoachThreads, Queue Sent, CoachHistory: `threads.list` | `GET /v1/threads?mode=&unread=&player_id=` | `player_id` is for staff only | | Thread: `threads.get` | `GET /v1/threads/{id}?message_cursor=` | | | Thread open/scroll: `threads.markRead` | `POST /v1/threads/{id}/read {last_message_id}` | The id of the last message actually rendered | | Composer: `threads.send` | `POST /v1/threads/{id}/messages` | See §14.4 | | Result: `threads.forSession` | `GET /v1/sessions/{id}/thread` | 404 `THREAD_NOT_FOUND` means "no review card". Any other error is an error. | | CoachPlayer Message: `threads.ensureForPlayer` | `POST /v1/coach/players/{player_id}/thread {mode}` | 201 new, 200 existing. Navigate to the returned id. | | Review send | `POST /v1/sessions/{id}/review` | Returns `thread_id`. **Delete** the local `upsertReview` and the fake voice message. | | Goal reads (Home, Progress, ReportCard, CoachPlayer, GoalEdit, CoachHistory): `goals.get` | `GET /v1/players/{player_id}/goals?mode=` | A player passes their own `user.id` | | GoalEdit Save: `goals.save` | `PUT /v1/players/{player_id}/goals/{mode}` | | | Progress, GoalEdit, CoachHistory: `goals.past` | `GET /v1/players/{player_id}/goals/history?mode=` | | | Progress: `milestones(mode)` | `GET /v1/me/milestones?mode=` | Empty until goals are evaluated. Keep the locally derived milestones. | | Drills, Drill, Messages, CoachPlayer, Queue, CoachHistory: `assignedDrills.list` | `GET /v1/drill-assignments?mode=&player_id=&status=open\|completed\|all` | | | AssignDrillSheet: `assignedDrills.assign` | `POST /v1/coach/players/{player_id}/drill-assignments` | **The sheet must receive `playerId`.** | | Drill "Mark set done": `assignedDrills.logSet` | `POST /v1/drill-assignments/{id}/sets` | The +/- rep counter stays local | | ArmCare, pitching Home, ReportCard: `armCare.get` | `GET /v1/me/arm-care` | | | ArmCare Add outing: `armCare.addOuting` | `POST /v1/me/arm-care/outings {pitches, local_date}` | | | ArmCare feel: `armCare.setFeel` | `PUT /v1/me/arm-care/feel {feel}` | | | Profile, CoachPending: `coachAccess.get` | `GET /v1/me/coach-access` | | | CoachRequest Send: `coachAccess.request` | `POST /v1/me/coach-access {code}` | May return `approved` straight away (auto codes) | | Roster group selector: `academy.groups` | `GET /v1/academy/groups` | Filter with `GET /v1/coach/roster?group_id=` or client-side on `group_ids` | | CreateGroup: `academy.createGroup` | `POST /v1/academy/groups` | Send the **ids**, not names or a count | | CoachPlayer note: `academy.note` / `saveNote` | `GET` / `PUT /v1/coach/players/{player_id}/note` | | | AddPlayers search | `GET /v1/academy/members?q=` | Replaces the hardcoded `MEMBERS` list. Debounce it. | | AddPlayers Add | `POST /v1/coach/roster/players {player_ids, group_id?}` | | | DrillLib list: `academy.library` | `GET /v1/academy/library?mode=&fault_tag=` | | | DrillLib Upload | `POST /v1/uploads {kind:"drill_video"}`, PUT the bytes, then `POST /v1/academy/library` | Needs a real picker and form | | OwnerDash: `academy.dashboard` | `GET /v1/academy/dashboard?month=YYYY-MM` | | | Earnings: `academy.earnings` | `GET /v1/academy/earnings?month=` | Every money field is null today. See §14.9. | | CorpDash: `academy.corp` | `GET /v1/academy/corp` | Always 403 today. Hide it. | | CoachRequests, CoachManage, CreateGroup: `academy.members` | `GET /v1/academy/coaches?status=` | | | CoachManage: `academy.member` | `GET /v1/academy/coaches/{id}` | Activity is included (no separate endpoint) | | CoachManage Save / Pause / Resume: `updateMember` | `PATCH /v1/academy/coaches/{id}` | | | CoachManage Remove: `removeMember` | `DELETE /v1/academy/coaches/{id}?reassign_to=` | **Pass the selected replacement** | | CoachRequests list, Team badge: `academy.requests` | `GET /v1/academy/coach-requests?status=pending` | The badge uses `total_pending` | | Approve/decline: `academy.decide` | `POST /v1/academy/coach-requests/{id}/decision` | | | StaffCodes: `codes`, `generateCode`, `revokeCode` | `GET`, `POST`, `DELETE /v1/academy/staff-codes[/{code}]` | Copy and share stay native | | Consent list: `academy.consent` | `GET /v1/academy/consent?group_id=` | | | Consent Export | `POST /v1/academy/consent/export {format:"csv"}` | Download `url` natively | ### 14.4 Conversations > **Chat now runs over a WebSocket.** Use `CHAT_SOCKET_INTEGRATION.md` for the transport (commands, live events, reconnecting). The objects and rules below are unchanged; the REST endpoints in this section remain only for released app builds. #### Thread object (N10/N11/N12/N15) ```json {"id":"...","mode":"h","session_id":"...|null","session_label":"Swing 12","score":74,"tone":"g|y|r", "coach_id":"...|null","coach_name":"Jamie","player_id":"...","player_name":"Alex", "status":"waiting_for_coach|reviewed","unread_for_player":true,"unread_for_coach":false, "updated_at":"...","messages":[...],"next_message_cursor":"...|null"} ``` - **Threads per player.** There is one thread per reviewed session, and one general thread per (player, coach, mode). - A general thread has `session_id: null` and `session_label: "Latest session"`. - **`tone`** is derived from `score`: g ≥ 80, y ≥ 60, r below 60. A missing score gives y. - **`session_id` becomes `null`** once the session has been deleted. Show it as "This session was deleted". - **`coach_id` is `null` and `coach_name` is `""`** if the coach deleted their account. The history stays. - **`GET /v1/threads` includes the latest 20 messages per thread.** Open the thread for more. `next_message_cursor` loads **older** messages: `GET /v1/threads/{id}?message_cursor=...`. - Each page comes back oldest first. #### Message union (discriminate on `kind`) Every message has `id`, `author_id`, `from` (`player|coach`) and `at`. | kind | extra fields | |---|---| | `text` | `text` | | `voice` | `seconds`, `audio: MediaRef` | | `image` | `media: MediaRef\|null`; the photo link is `media.url` | | `video` | `seconds`, `media: MediaRef\|null`; the video link is `media.url` | | `session` | `session_id` (null when deleted), `label`, `score` | | `review` | `cue`, `voice_seconds`, `audio: MediaRef\|null`, `findings: [{metric_id, name, verdict: agree\|change\|later}]`, `drill_id`, **`drill_name`**, `assignment_id` (null) | - The review message is produced by the server from the stored review. You can never POST `kind:"review"`. - **`media.url` (and `audio.url`) are signed links that expire after about an hour.** The server issues a new one on every read and every live event; the file itself is kept. Never store the URL: cache the file by `upload_id` and re-read the thread for a fresh link. Details are in `CHAT_SOCKET_INTEGRATION.md` §4.1. - **Re-reviewing updates the same review message.** It moves to the newest position and is unread again for the player. #### Sending (N14) Use one of these bodies: ```json {"kind":"text","text":"1–500 chars"} {"kind":"voice","upload_id":"