baseball-engine / backend /docs /FRONTEND_INTEGRATION.md
github-actions[bot]
Automated Deploy: a36ad9fbaf2a4b4a2efb7feea50aa69986cf59d3
e980186
|
Raw History Blame Contribute Delete
52.4 kB

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 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://<api host>/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=<next_cursor>&limit=<1..200> (default 50).
  • Retries: POST /v1/sessions and POST /v1/drill-logs accept an Idempotency-Key: <uuid> 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 <access_token>

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)

{ "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=<local midnight as UTC ISO> 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 <url> 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=<ISO> 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:<jwsRepresentation>} 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=<next_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: <uuid> 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:

{
  "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: <newest loaded at>}
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=<id> 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)

{"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:

{"kind":"text","text":"1–500 chars"}
{"kind":"voice","upload_id":"<audio upload>","seconds":12}
{"kind":"image","upload_id":"<image upload>"}
{"kind":"video","upload_id":"<video upload>","seconds":8.4}
{"kind":"session","session_id":"<one of the THREAD PLAYER's sessions, same mode>"}
  • The response is 201 {message, thread_status, updated_at}.
    • A player's message sets waiting_for_coach. A coach's message sets reviewed.
  • Sending also marks the thread read for the sender.
  • Keep the draft until 201. The current Composer clears it before the request finishes.
  • Session picker. On the coach side, list the thread player's sessions (GET /v1/coach/players/{id}/sessions), not the coach's own sessions.
Error Meaning
409 UPLOAD_NOT_READY The audio PUT hasn't finished. Retry.
422 UPLOAD_ALREADY_USED Each audio upload can be sent only once. Upload again.
422 INVALID_UPLOAD The upload isn't the caller's, or it isn't audio
422 MODE_MISMATCH The session is from the other mode
403 A coach attached a session but the player has turned off coach sharing
404 The thread isn't accessible, or the session isn't the player's or has been deleted

Read state (N13)

POST /v1/threads/{id}/read {"last_message_id": "<last rendered id>"} returns 204.

  • The watermark only moves forward, and only for the caller's own side.
  • A message that arrives after that id stays unread.
  • Call it on open and whenever new messages render.
  • If staff other than the thread's coach (for example the admin) read a thread, the coach's unread flag stays as it is.

Voice notes: recording to playback

  1. Record a real file: audio/mp4 (m4a), audio/aac or audio/mpeg, at most 5 MB and 120 s.
  2. POST /v1/uploads {kind:"audio", content_type, size_bytes, duration_sec} returns {upload_id, url, headers, expires_at}.
  3. PUT the bytes to url with headers.
  4. Send it, either as a message {kind:"voice", upload_id, seconds} or with a review voice_note_upload_id plus voice_note_seconds.
  5. Play audio.url. When it expires, refetch the thread.

Remove the fixed 12-second sends and the timer-based fake playback.

14.5 Notifications and push (N06–N09, C05)

{"id":"...","kind":"review|drill|armcare|result|report","title":"...","body":"...","at":"...","read":false,
 "target":{"thread_id":"..."}}

Routing target

target Route to
thread_id Thread
session_id Result (review notifications carry both thread_id and session_id; prefer thread_id)
month ReportCard
{} with kind drill Drills (assignments and new goals)
{} with kind armcare ArmCare

Re-check access when you fetch the destination. On 403 or 404, show "no longer available".

Push data (FCM)

  • New pushes carry notification_id, kind and target_json, which is a JSON-encoded target.
  • Review pushes also keep the old type:"review.received" and session_id, so older builds still work.
  • Update src/push/index.ts:
    • parse target_json;
    • hold a tap until the user is signed in and navigation is ready;
    • then mark the notification read and route.

Preferences

  • notify_coach turns off pushes for coach messages and reviews.
  • notify_drills turns off pushes for assignments and goals.
  • notify_results and notify_weekly cover their own kinds.
  • The in-app inbox always records everything.

14.6 Settings and consent (N01–N05, C07)

Settings object

  • Settings has 12 preference booleans: coach_can_see_sessions, share_with_parent, auto_monthly_report, private_links, clips_as_examples, help_improve_ai, notify_* (four) and skip_filming_guide.
  • It also has parent_email (null) and the read-only consented_at, consent_version and version.

Defaults

  • Coach sharing and every notification flag are on.
  • All external sharing and AI or example opt-ins are off.

Settings rules

  • Turning share_with_parent off also turns auto_monthly_report off. Always render the returned values.
  • auto_monthly_report: true without sharing and a parent_email gives 422.
  • PATCH cannot set parent_email yet: recipient setup is not designed.
  • coach_can_see_sessions: false is enforced on the server. Coaches stop seeing the player's sessions, queue items and media, and cannot review.
    • The player still appears on the roster, with empty scores.
    • Existing conversations stay.

Consent errors

  • POST /v1/me/consent gives 409 TERMS_CHANGED when the version is no longer current. Fetch the new terms.
  • After a withdrawal (DELETE /v1/me/consent), these return 403 CONSENT_REQUIRED:
    • POST /v1/sessions;
    • POST /v1/sessions/{id}/swing-report.
    • Catch it and route to the consent screen.
    • Saved sessions stay viewable.

14.7 Goals, assignments, progress (N16–N22, C08)

Goals

PUT /v1/players/{player_id}/goals/{mode}, body:

{"type":"groups|param|score","target":3,"metric_id":null,"due":"1 week|2 weeks|End of month",
 "weekly":{"practice_days":1-7,"drill_sets":1-30},"note":"≤160","expected_version":1}

Target rules

  • groups: an integer from 1 to the number of catalog groups. Hitting only.
  • score: an integer from 50 to 100.
  • param: a number from -50 to 500, and it needs a catalog metric_id. Hitting only.

Behaviour

  • Only staff with the goals permission can set a goal. Players get 403.
  • Sending the same goal again is a no-op and sends no notification.
  • A changed goal replaces the old one, which moves to history with outcome: "superseded".

History

  • met is null unless the goal was evaluated as met or not met. Render null as "not assessed", not as failed.
  • ReportCard for a past month: history items have start_at and end_at. Pick the goal whose window covers that month, instead of showing the current goal.

Assignments

Assigning: POST /v1/coach/players/{player_id}/drill-assignments, body:

{"mode":"h","drill_source":"catalog|library","drill_id":"hit_13 | <library uuid>","due_date":"2026-10-31",
 "source_session_id":null}
  • Due date. Convert the sheet's "Tomorrow / Saturday / Next week" into a real date before sending. The response's due is a display label.
  • Defaults are 3 sets of 8 reps.
Error Meaning
404 DRILL_NOT_FOUND Unknown drill
422 MODE_MISMATCH The drill is for the other mode
400 due_date is in the past

Logging a set: POST /v1/drill-assignments/{id}/sets {set_number, reps_done, day}.

  • set_number is the next ordinal (done + 1). reps_done is the real counter value, from 1 to reps.
  • Keep the same Idempotency-Key when retrying after a timeout.
  • Reset the counter only after 201, and use the returned assignment.done.
Error Meaning
422 SET_OUT_OF_RANGE set_number is above sets
422 REPS_OUT_OF_RANGE reps_done is above reps
409 SET_ALREADY_LOGGED That set was already logged with different values (refetch)

Matching assignments to players

  • Queue Sent, CoachHistory and Drill must match by assignment id and player_id, never by drill name.
  • GET /v1/drill-assignments without player_id returns every visible player's assignments for staff.

Progress totals. Each logged set also creates one drill log with assignment_id. Home, Progress and ReportCard already add up GET /v1/drill-logs, so they now include assigned sets exactly once. Don't add assignment progress on top.

14.8 Arm care (N23–N25)

  • rest_status is always "unknown" and unavailable_reason is set, because no age-specific pitch policy has been approved.
    • daily_max, innings_* and next_eligible_date are null.
    • Remove the client's hardcoded rest thresholds (restFor) and the "Cleared to pitch" copy.
    • Show "Rest guidance not available yet".
  • feel is null until the player reports one. Don't default it to "good".
  • Outings
    • pitches is an integer from 1 to 200.
    • local_date defaults to today and may be up to one day ahead (timezones). Older than a year gives 400.
  • Logging an outing notifies the player's coaches in the in-app inbox. Change the copy to "Your coach can see this", not "Coach alerted".

14.9 Academy administration

Staff codes

  • Codes look like CV-XXXX-XX. You choose role (coach or assistant), expires_days (1, 7 or 30), max_uses (1, 5 or 20) and approval (admin or auto).
  • A use is consumed when someone applies. Declining does not give it back.
  • An exhausted code still lists as active, with uses == max_uses. Show it as full.

Application errors (POST /v1/me/coach-access)

Error Meaning
422 CODE_INVALID Unknown code
409 CODE_UNAVAILABLE Revoked, expired or full
409 REQUEST_PENDING A pending request with a different code already exists
409 ALREADY_MEMBER Already a member of that academy
429 Too many attempts
  • A removed coach who reapplies always needs admin approval, even with an auto code.

Decisions

  • Approve: {decision:"approve", role:"coach|assistant", sees_all, group_ids}. Decline: {decision:"decline"}.
  • 409 REQUEST_ALREADY_DECIDED means someone else decided first. Refetch.
  • Remove the hardcoded "12U" default and let the admin pick groups from GET /v1/academy/groups.

Coach list and editing

  • GET /v1/academy/coaches includes the owner as role: admin.
  • For non-admin callers, joined_with, permissions and activity are null. Use the list only for pickers there.
  • PATCH /v1/academy/coaches/{id} changes role, sees_all, group_ids, permissions and status (active or paused).
  • The owner cannot be edited or removed: 409 OWNER_IMMUTABLE.
  • A role change without permissions resets to the role's defaults. Render the returned permissions.
  • Removing a coach. reassign_to is required and must be an active colleague or the owner, otherwise 409 INVALID_REPLACEMENT.
    • Their roster and groups move to the replacement. Private notes do not.
    • Don't offer paused or removed coaches as replacements.

Visibility

  • Admins and sees_all coaches see every player.
  • Other coaches see their own roster (AddPlayers) plus the players in the groups they coach.

Groups

  • POST /v1/academy/groups is admin only. Duplicate names give 409 GROUP_NAME_TAKEN.
  • Any id from another academy rejects the whole request with 404.

Notes

  • A note is private to the coach who wrote it. Admins can't read other coaches' notes.
  • No note gives {text:"", updated_at:null, version:0}.

Library

  • Upload with kind:"drill_video" (mp4 or mov, up to 300 s), PUT the bytes, then publish with {upload_id, name, mode, fault_tags[1..10], fixes}.
  • Tags are lowercased.
  • One upload can be published once: 409 UPLOAD_ALREADY_USED.
  • 409 UPLOAD_NOT_READY means the PUT hasn't finished.
  • Publishing needs the library permission.

Dashboard

  • These numbers are real. Definitions are in app/modules/reporting/service.py and summarised here:
    • active_players: players with an analysed session this month.
    • improving_pct: latest score above the first, among players with two or more scored sessions. Null if there are none.
    • cards: g ≥ 80, y 60–79, r < 60, from each player's latest score.
    • not_filmed_7d: players with no session in the last 7 days.
  • Money: currency, every *_minor field and paying_players are null. earnings_bars is [] and unavailable_reason is "Revenue ledger not configured".
    • Handle empty bars, since the current UI assumes a non-empty list.
    • When money arrives later it will be integer minor units plus an ISO currency code.

Consent list and export

  • accepted and ai_opt_in are totals over the whole academy, not the current page.
  • The export returns a ready url (a CSV with an expiry). Download it with native file handling.
  • More than 5000 rows gives 409 EXPORT_TOO_LARGE.

14.10 Differences from the spec examples (code against these)

Where Spec Actual What to do
Validation errors 422 400 VALIDATION with fields Same handler as the rest of the app
C01 review submit 200 201 on the first review, 200 on update Treat both as success
Review message drill name drill_id/name (ambiguous) drill_id + drill_name Read drill_name
N06 review target one key thread_id + session_id Prefer thread_id
N32 member focus h|p h|p|both Map both
MediaRef {upload_id,url,expires_at} extra seconds (nullable) Ignore it, or use it for audio length
N37/N38 money values null + unavailable_reason Show "not available yet"
N39 corp 200 with a grant always 403 (no corporate grants exist) Hide CorpDash
N40 for non-admins full object joined_with, permissions, activity null Admin screens only
N15 Idempotency-Key not needed It is get-or-create already
Roster filter not specified GET /v1/coach/roster?group_id= Optional; group_ids are on every item

14.11 Not built (needs a product decision first)

  • Direct email or SMS invites (N34). Keep native team-code sharing in AddPlayers.
  • Parent email setup, automatic monthly reports and private share links. ReportCard's Send options should stay native text share.
  • Automatic goal evaluation and milestones, age-specific arm-care rules, the revenue ledger and corporate grants.
  • Drill-due and weekly reminders. The notification preference flags exist, but no scheduler sends these yet.
  • The video export emails presigned links, not a zip archive.

14.12 Integration checklist

  • HTTP client: add PUT, Idempotency-Key per action, and 400/409/422 error handling with code.
  • Adapters: snake_case ↔ camelCase, unwrap {x:{...}}, follow next_cursor, allow nulls. Never cast new shapes to the old mock types.
  • Remove the mock seed for these features. Replace useMockVersion with refetch after each mutation. Use real empty and error states.
  • Navigation from capabilities, the dual-role switch, and refetching /me after access changes.
  • Guide: wait for the consent call and stop on errors. Handle CONSENT_REQUIRED from session create and swing-report.
  • Review: real audio record, upload and send. Use the returned thread_id. Delete the local upsertReview and the fake voice bubble.
  • Thread: pagination, read watermark, playback, deleted-session tombstone, drafts kept on failure, and the player-scoped session picker.
  • AssignDrillSheet gets playerId, a real due date and drill_source. Set logging sends real reps and a retry key.
  • Queue, CoachHistory and Drill match by assignment id and player id.
  • ArmCare: remove restFor, render unknown, allow a null feel.
  • Groups use ids. The roster filter is applied. CoachManage loads real groups and passes reassign_to.
  • StaffCodes, CoachRequests and CoachPending show every outcome: invalid, expired, full, pending, approved and declined.
  • Reporting: null money, empty bars, as_of labels. Hide CorpDash.
  • Push: parse target_json, route every kind, queue taps until ready, keep the old review payload working.
  • Library upload form, consent CSV download and video export trigger.