Production Documentation

MXCI Fitness Platform

This document describes the current MXCI application as implemented in the codebase: a mobile-first fitness platform with nutrition tracking, workout management, AI-assisted guidance, social engagement, subscription controls, and an admin panel.

Platforms Web, Android, iOS
Backend Firebase + Cloud Functions
AI Provider OpenAI

1. Overview

MXCI is a mobile-first health and fitness application designed to consolidate personal workout planning, nutrition management, progress monitoring, AI-assisted coaching, and community engagement in a single system. The application is delivered as a web application and synchronized to Android and iOS through Capacitor.

Primary Purpose

Provide a unified user experience for managing personal fitness routines, food intake, hydration, AI-driven recommendations, recovery awareness, journaling, and social accountability.

Current Delivery Model

Frontend in React + Vite, cloud data in Firebase Firestore, authentication in Firebase Auth, AI logic in Firebase Cloud Functions, and device capabilities through Capacitor plugins.

2. Scope and Objectives

Business Objectives

  • Centralize fitness, nutrition, and progress workflows in one application.
  • Use AI to improve guidance quality and reduce user friction.
  • Support freemium and subscription-based tier access.
  • Allow administration of users, tiers, suspensions, and subscription periods.

System Scope

  • Authentication and session management
  • Nutrition, hydration, supplements, and BMR setup
  • Workout planning, exercise logging, and form analysis
  • Progress photos, weight tracking, goals, and AI journal
  • Social posting, community features, and backups
  • Admin dashboard for operational control

3. Stakeholders and User Roles

End Users

Individuals using the app to manage workouts, meal logs, hydration, progress, AI coaching, and social interactions.

Subscribed Users

Users with elevated tier entitlements such as higher AI quotas and ad-free or premium access depending on subscription tier.

Administrators

Personnel using the admin dashboard to view users, manage suspension, adjust tiers, update subscription dates, and monitor user account state.

4. Functional Features

Authentication and Session

  • Animated splash and mobile-first login interface
  • Google sign-in
  • Email/password sign-in and registration
  • CAPTCHA on email/password registration
  • Local user bootstrap cache after successful login
  • Per-user cache isolation and cleanup on logout

Navigation and UX

  • Bottom, left, or right menu placement
  • AssistiveTouch-style movable quick menu
  • Tier-aware AdMob banner handling
  • Offline indicators and sync status
  • Mobile-optimized single-shell navigation

Nutrition

  • BMR profile setup and editable targets
  • Daily calories and macro distribution
  • Food logging by date
  • Meal add, edit, delete, and time sorting
  • HydraSupp for water and supplement tracking
  • Nutrition converter
  • AI Coach, AI Food Scanner, and AI Plate Scoring

Workouts

  • AI workout generation
  • Workout save/load by date
  • Live exercise progression and completion tracking
  • Text-to-speech support for coaching prompts
  • Form analysis by camera capture or upload
  • Exercise library and recovery view

Progress

  • Progress photo upload or camera capture
  • Weight logging and trend tracking
  • Goal management
  • AI journal entries and date-based review

Social and Community

  • Community posts with image support
  • Likes, comments, privacy controls, and feed filters
  • Community profiles and workout buddy preference
  • Notifications and profile settings
  • Google Drive backup integration
  • Data export options

5. System Architecture

Architecture Summary

React + Vite Frontend
Firebase Auth
Firestore
Cloud Functions
OpenAI

The client application is the orchestration layer. Firebase Authentication manages identity, Firestore persists user and community data, Cloud Functions implement privileged AI workflows, and Capacitor bridges the same web codebase to native mobile platforms.

Client-Side Layers

  • Presentation layer: React pages and UI components
  • State layer: app context, cached state, route shell
  • Service layer: `api/client.ts` and Firebase adapters
  • Device layer: camera, ads, filesystem, push, share, TTS

Backend Layers

  • Identity: Firebase Authentication
  • Data persistence: Cloud Firestore
  • Business rules: Firestore Security Rules
  • Privileged processing: Firebase Cloud Functions
  • AI engine integration: OpenAI Responses API

6. Technology Stack

Frontend

  • React 18
  • TypeScript
  • Vite
  • React Router
  • Tailwind utilities and custom CSS
  • Radix UI and selected MUI packages

Charts and UX Libraries

  • Recharts
  • Motion
  • Sonner
  • Date-fns

Mobile and Backend

  • Capacitor for Android and iOS packaging
  • Firebase Web SDK
  • Firebase Admin SDK
  • Firebase Functions v2
  • OpenAI Node SDK

7. Module Specifications

Auth Module

Handles sign-in, sign-up, logout, Google OAuth, password authentication, auth timeout protection, local auth tracing, and user bootstrap caching.

App Context Module

Centralizes authenticated state, user settings, tier information, subscription metadata, periodic sync behavior, and cache hydration/reset workflows.

Nutrition Module

Stores BMR profile, nutrition targets, meal entries, hydration values, supplement selections, and AI-assisted food analysis and coaching conversations.

Workout Module

Supports date-based workout plans, AI-generated routines, exercise execution, exercise library access, recovery review, and image-based form checking.

Progress Module

Captures body progress photos, weight records, goals, and AI journal entries with date-oriented retrieval and review.

Social Module

Provides community profile management, posts, likes, comments, privacy-controlled feeds, backup integration, and export utilities.

Admin Dashboard

Standalone HTML/JS admin interface connected to Firebase for user viewing, tier management, subscription date management, AI reset, and suspension control.

Device Integration Module

Abstracts Capacitor plugins for camera, ads, push notifications, filesystem, share, haptics, and text-to-speech.

8. Data Model

Firestore Structure

The platform uses a user-centric Firestore model. Most application data is stored under `users/{uid}` and its subcollections/documents. Community content is stored in shared top-level collections.

users/{uid}
  settings/app
  foodLogs/{date}
  hydration/{date}
  supplements/current
  supplements/{date}
  journal/entries
  weight/entries
  goals/current
  workouts/{date}
  prs/current
  grocery/current
  chat/{channel}
  aiUsage/{date}
  nutrition/{date}
  progressPhotos/timeline
  social/app

communityPosts/{postId}
communityProfiles/{uid}
adminUsers/{uid}

Key User Settings

  • Theme mode
  • Tier
  • Menu placement
  • Menu mode
  • BMR profile
  • Subscription start/end dates
  • Suspension flag on root user document

Shared Social Data

  • Community post content and metadata
  • Author identifiers
  • Comments and engagement fields
  • Community-facing user profile summaries

9. AI Services and Quotas

Callable AI Services

  • `nutritionChat`
  • `analyzeFoodImage`
  • `scorePlateImage`
  • `generateWorkoutPlan`
  • `analyzeFormImage`
  • `analyzeJournalEntry`
  • `generateJournalQuestion`

Tier Limits

Tier Daily AI Limit
Ad5
Ad-Free10
Standard25
Pro100

AI Control Logic

  • Quota enforcement is handled in Cloud Functions.
  • Daily usage is stored per user in `users/{uid}/aiUsage/{date}`.
  • A cooldown value is also defined to reduce rapid repeated AI calls.
  • Responses are constrained to fitness and nutrition support contexts.

10. Security and Access Control

Authentication

  • Firebase Authentication secures user identity.
  • Google and email/password providers are supported in the main app.
  • Admin access depends on authenticated Firebase session.

Authorization

  • Firestore rules enforce owner access for user data.
  • Admins have broader read/write access through `adminUsers/{uid}`.
  • Community collections allow signed-in reads and controlled writes.

Cloud Secret Management

  • OpenAI API key is read from Firebase Functions secret storage.
  • AI requests fail safely when the secret is absent or invalid.

Session Safety

  • Per-user local cache reduces cross-user contamination.
  • Logout clears user-scoped cache entries.
  • Suspension state is periodically checked and can force access restrictions.

11. Performance and Optimization

Implemented Optimizations

  • Single-flight request deduplication for repeated reads
  • Debounced local cache writes
  • Per-user bootstrap cache for faster post-login load
  • Native token request dedupe to reduce repeated `getIdToken` calls
  • Reduced cache warming scope
  • Periodic sync replacing noisy persistent snapshot patterns
  • Tap throttling on mobile navigation

Why These Changes Matter

The application targets mobile devices where repeated route changes, duplicated token requests, aggressive listener creation, and excessive cache writes can create visible lag. The current optimization strategy reduces main-thread churn and minimizes redundant Firebase operations.

12. Deployment and Hosting

Web Build

  • Build command: `npm run build`
  • Output directory: `dist/`
  • Public static assets are copied into build output

Android

  • Web sync command: `npx cap sync`
  • Native project path: `android/`
  • Release for Play Store should use signed `.aab` bundles

iOS

  • Web sync command: `npx cap sync`
  • Native project path: `ios/`
  • Release distribution requires Apple signing and archive flow

Documentation Hosting

This documentation set is stored under `public/system-docs/`. When the web app is built, it becomes available as a static route. It can also be uploaded directly to any static hosting service without modification.

13. Administration and Operations

Admin Functions

  • User listing and profile summary
  • Tier updates
  • Subscription date editing and extension
  • AI usage reset
  • Account suspension and unsuspension
  • Status visibility for active and suspended accounts

Operational Notes

  • Expired subscribed tiers can be reverted to Ad tier by admin workflows.
  • Subscription metadata influences AI limits and ad exposure.
  • Suspension state should be propagated to active sessions.

14. Maintenance Guidelines

Recommended Maintenance Tasks

  • Review Firebase usage and function execution costs
  • Monitor authentication flows after SDK or plugin upgrades
  • Validate mobile sync after each frontend release
  • Verify AI quota logic after subscription changes
  • Audit admin actions after deployment

Testing Priorities

  • Google sign-in on Android and iOS
  • Email/password sign-in and registration
  • Tier-based ads and AI quota enforcement
  • Food/workout/progress save-load consistency
  • Suspension effect on active sessions

15. Risks and Recommendations

Current Risks

  • Mobile auth behavior can diverge from web if native plugin state is not aligned.
  • Frequent UI-triggered fetches can still degrade performance if new pages add redundant requests.
  • Tier logic must stay consistent between app UI, admin dashboard, and Cloud Functions.
  • Admin access currently depends on Firestore rule configuration.

Recommended Next Improvements

  • Add structured automated tests for auth, tier, and AI quota flows.
  • Introduce centralized telemetry for sync failures and cache write errors.
  • Formalize schema documentation and migration policy.
  • Separate admin role policy from client assumptions to avoid drift.

16. Appendix

Important Project Paths

  • `src/app/` – main application source
  • `functions/src/` – Firebase Cloud Functions source
  • `ADMIN/` – standalone admin dashboard
  • `android/` – Android native wrapper
  • `ios/` – iOS native wrapper
  • `public/system-docs/` – this documentation site

Core Commands

npm install
npm run dev
npm run build
npx cap sync
npx cap open android
npx cap open ios