<div align="center">
<img src="../project-files/shape-shift/ShapeShiftLogo.png" width="300"/>

[![React](https://img.shields.io/badge/React-18.2.0-blue.svg)](https://reactjs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-4.9.5-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-Express-green.svg)](https://nodejs.org/)
[![MongoDB](https://img.shields.io/badge/MongoDB-Atlas-green.svg)](https://www.mongodb.com/)
[![Docker](https://img.shields.io/badge/Docker-Containerized-blue.svg)](https://www.docker.com/)

_A comprehensive full-stack fitness tracking application built by a 4-person development team_

</div>

---

## 🎯 Project Overview

**Shape Shift** is a modern, full-stack fitness tracking application designed to help users monitor their fitness journey through comprehensive tracking capabilities. The application provides tools for workout planning, nutrition tracking, progress monitoring, and fitness calculations.

### Team Information

-   **Team Size**: 4 developers
-   **Development Period**: Academic semester project
-   **Contributors**: Parker, Diego, Jeremy, and Alex

---

## 🚀 Technology Stack

### Frontend

-   **Framework**: React 18.2.0
-   **Language**: JavaScript (ES6+)
-   **Routing**: React Router DOM 6.10.0
-   **State Management**: Redux Toolkit with React-Redux
-   **UI Framework**: Material-UI (MUI) 5.14.3 + React Bootstrap 2.7.4
-   **Styling**: CSS3 with component-scoped styles
-   **Charts & Visualization**: Chart.js 4.4.0 with React-ChartJS-2, D3.js 7.8.5
-   **HTTP Client**: Axios 1.4.0
-   **Animations**: Framer Motion 9.0.7
-   **Icons**: React Icons 4.7.1

### Backend

-   **Runtime**: Node.js with TypeScript 4.9.5
-   **Framework**: Express.js 4.18.2
-   **Database**: MongoDB with native MongoDB driver 5.0.1
-   **Authentication**: Express-Session with custom crypto implementation
-   **Security**: CORS enabled, password hashing with scrypt
-   **Development**: ts-node for TypeScript execution
-   **Testing**: Mocha 10.2.0 with Chai 4.3.7 and Supertest 6.3.3

### DevOps & Deployment

-   **Containerization**: Docker with Alpine Linux base
-   **Web Server**: Nginx (reverse proxy)
-   **Build Tools**: Custom shell scripts
-   **Environment Management**: dotenv for configuration

### Development Tools

-   **Package Management**: npm
-   **Type Safety**: TypeScript with strict configuration
-   **Testing**: Unit tests with Mocha/Chai
-   **Code Organization**: Modular architecture with separation of concerns

---

## 🏗️ Architecture

### System Architecture

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   React Client  │────│   Nginx Proxy    │────│  Express API    │
│   (Port 3000)   │    │   (Port 80)      │    │  (Port 3001)    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                         │
                                                         ▼
                                               ┌─────────────────┐
                                               │  MongoDB Atlas  │
                                               │   (Cloud DB)    │
                                               └─────────────────┘
```

### Project Structure

```
fitness-tracker/
├── frontend/                 # React application
│   ├── src/
│   │   ├── components/       # Reusable UI components
│   │   ├── pages/           # Route-based page components
│   │   ├── redux/           # State management
│   │   ├── styles/          # CSS stylesheets
│   │   └── test-data/       # Mock data for development
│   └── public/              # Static assets
├── api/                     # Express.js backend
│   ├── src/
│   │   ├── models/          # Data models (TypeScript classes)
│   │   ├── routes/          # API endpoint handlers
│   │   ├── tests/           # Unit tests
│   │   ├── app.ts           # Application entry point
│   │   ├── config.ts        # Database and server configuration
│   │   └── middleware.ts    # Custom middleware functions
│   └── schema/              # MongoDB validation schemas
├── etc/                     # Configuration files
│   ├── nginx.conf          # Nginx configuration
│   └── entrypoint.sh       # Docker startup script
├── Dockerfile              # Container definition
└── build.sh               # Build automation script
```

---

## ✨ Core Features

### 1. User Management

-   **User Registration & Authentication**: Secure account creation with password hashing
-   **Session Management**: Persistent login sessions using Express-Session
-   **User Profiles**: Personalized user data and preferences

### 2. Dashboard & Analytics

-   **User Dashboard**: Comprehensive overview of fitness metrics
-   **Data Visualization**: Interactive charts showing progress over time
-   **Macro Tracking**: Detailed nutritional information display
-   **Progress Monitoring**: Visual representation of fitness journey

### 3. Workout Management

-   **Workout Library**: Extensive database of exercises with descriptions and diagrams
-   **Custom Workout Creation**: Build personalized workout routines
-   **Workout Splits**: Organize workouts by muscle groups or training days
-   **Exercise Search**: Find specific workouts by muscle group or equipment

### 4. Calendar Integration

-   **Workout Scheduling**: Plan workouts across weekly schedules
-   **Split Management**: Assign different workout groups to specific days
-   **Progress Tracking**: View historical workout data

### 5. Fitness Journal

-   **Daily Entries**: Record daily fitness activities and measurements
-   **Macro Tracking**: Log nutritional intake with calorie counting
-   **Personal Records**: Track lifting PRs and fitness milestones
-   **Body Measurements**: Monitor physical progress over time
-   **Notes System**: Add personal observations and goals

### 6. Fitness Calculators

-   **BMI Calculator**: Body Mass Index computation
-   **BMR Calculator**: Basal Metabolic Rate estimation
-   **Body Fat Percentage**: Body composition analysis
-   **Protein Intake Calculator**: Nutritional requirement estimation

### 7. Data Management

-   **Export Capabilities**: Save calculator results and progress data
-   **Historical Data**: Access to past entries and measurements
-   **Data Visualization**: Charts and graphs for trend analysis

---

## 🔌 API Documentation

### Base URL

```
Production: http://localhost/api
Development: http://localhost:3001/api
```

### Authentication Endpoints

| Method | Endpoint    | Description            | Body                                   |
| ------ | ----------- | ---------------------- | -------------------------------------- |
| POST   | `/sign-in`  | User authentication    | `{username: string, password: string}` |
| POST   | `/sign-out` | Session termination    | None                                   |
| GET    | `/`         | Get current user info  | None (requires auth)                   |
| GET    | `/calendar` | Get user calendar data | None (requires auth)                   |

### User Management

| Method | Endpoint        | Description             | Body                                   |
| ------ | --------------- | ----------------------- | -------------------------------------- |
| POST   | `/users/create` | Create new user account | `{username: string, password: string}` |

### Workout Endpoints

| Method | Endpoint    | Description          | Query Parameters                |
| ------ | ----------- | -------------------- | ------------------------------- |
| GET    | `/workouts` | Get workout database | `skip?: number, limit?: number` |

### Workout Split Management

| Method | Endpoint          | Description               | Body                 |
| ------ | ----------------- | ------------------------- | -------------------- |
| GET    | `/split`          | Get user's workout split  | None (requires auth) |
| GET    | `/split/workouts` | Get user's workout groups | None (requires auth) |
| POST   | `/split`          | Update workout split      | Split configuration  |

### Journal Endpoints

| Method | Endpoint                   | Description                   | Body                               |
| ------ | -------------------------- | ----------------------------- | ---------------------------------- |
| GET    | `/journal`                 | Get journal entries (last 30) | None (requires auth)               |
| POST   | `/journal/macro`           | Add macro entry               | `{macros: Macro[]}`                |
| POST   | `/journal/measurement`     | Add body measurement          | `{measurement: Measurement}`       |
| POST   | `/journal/personal-record` | Add personal record           | `{personalRecord: PersonalRecord}` |
| POST   | `/journal/note`            | Add journal note              | `{note: Note}`                     |

---

## 🗄️ Database Schema

### User Model

```typescript
class User {
    username: string; // Unique identifier
    password: string; // Hashed password
    salt: string; // Password salt
    journalEntries: JournalEntry[]; // Daily fitness logs
    workoutGroups: WorkoutGroup[]; // Custom workout collections
    workoutSplit: string[]; // 7-day workout schedule
    _id?: ObjectId; // MongoDB document ID
}
```

### Workout Model

```typescript
class Workout {
    workoutName: string; // Exercise name
    description: string; // Exercise instructions
    diagram: string; // Visual guide
    muscle: string; // Target muscle group
    equipment: string; // Required equipment
    images: string[]; // Reference images
    videos: string[]; // Tutorial videos
}
```

### Journal Entry Model

```typescript
class JournalEntry {
    measurements: Measurement[]; // Body measurements
    personalRecords: PersonalRecord[]; // Fitness PRs
    calculatorResult: CalculatorResult[]; // Saved calculations
    macros: Macro[]; // Nutritional data
    notes: Note[]; // Personal notes
    split: string; // Workout performed
    date: string; // Entry date
}
```

---

## 🛠️ Development Setup

### Prerequisites

-   Node.js (v16+)
-   npm
-   MongoDB Atlas account (or local MongoDB instance)
-   Git

### Local Development

```bash
# Clone the repository
git clone <repository-url>
cd fitness-tracker

# Install dependencies
npm install --prefix ./api
npm install --prefix ./frontend

# Configure environment variables
# Create ./api/.env with:
# API_DB_HOST=your-mongodb-host
# API_DB_USERNAME=your-username
# API_DB_PASSWORD=your-password
# API_DB_NAMESPACE=your-database-name
# API_HOST=127.0.0.1
# API_PORT=3001

# Start the backend server
npm run start --prefix ./api

# In a new terminal, start the frontend
npm run start --prefix ./frontend
```

### Frontend Configuration

Create `./frontend/.env`:

```env
REACT_APP_API_URL=http://localhost:3001/api
```

### Running Tests

```bash
# Backend tests
npm run test --prefix ./api

# Frontend tests
npm run test --prefix ./frontend
```

---

## 🚀 Deployment

### Docker Deployment

```bash
# Build the application
chmod +x ./build.sh
./build.sh

# Run the container
docker run -it -p 80:80 --rm shapeshift:latest
```

### Docker Architecture

-   **Base Image**: Alpine Linux (lightweight)
-   **Web Server**: Nginx (serves React build + API proxy)
-   **Application Server**: Node.js with Express
-   **Port Mapping**: Container port 80 → Host port 80

### Production Considerations

-   Environment variables properly configured
-   MongoDB connection string secured
-   CORS origins restricted to production domains
-   SSL/TLS termination at load balancer level
-   Container orchestration with Docker Compose or Kubernetes

---

## 🎓 Skills Demonstrated

### Technical Skills

#### Frontend Development

-   **React Ecosystem Mastery**: Hooks, Context, Router, lifecycle methods
-   **State Management**: Redux Toolkit implementation with proper action/reducer patterns
-   **Component Architecture**: Reusable components with proper prop handling
-   **Responsive Design**: Mobile-first CSS with Bootstrap integration
-   **Data Visualization**: Chart.js and D3.js integration for analytics
-   **Performance Optimization**: Component memoization and lazy loading

#### Backend Development

-   **RESTful API Design**: Proper HTTP methods, status codes, and resource modeling
-   **TypeScript Proficiency**: Strong typing, interfaces, and class-based architecture
-   **Database Integration**: MongoDB operations with aggregation pipelines
-   **Authentication & Security**: Session management, password hashing, CORS configuration
-   **Middleware Development**: Custom authentication and logging middleware
-   **Error Handling**: Comprehensive error responses and logging

#### Database Design

-   **NoSQL Modeling**: Document-based schema design for MongoDB
-   **Data Relationships**: Embedded documents and references
-   **Query Optimization**: Efficient data retrieval patterns
-   **Schema Validation**: JSON schema implementation

#### DevOps & Deployment

-   **Containerization**: Multi-stage Docker builds with Alpine Linux
-   **Reverse Proxy Configuration**: Nginx setup for SPA routing and API proxying
-   **Build Automation**: Shell scripting for deployment processes
-   **Environment Management**: Configuration separation for different environments

### Software Engineering Practices

#### Code Organization

-   **Modular Architecture**: Separation of concerns with clear module boundaries
-   **Design Patterns**: MVC pattern implementation, middleware pattern
-   **Code Reusability**: DRY principles with shared utilities and components
-   **Type Safety**: Comprehensive TypeScript usage throughout the stack

#### Testing & Quality Assurance

-   **Unit Testing**: Mocha/Chai test suites for backend functionality
-   **API Testing**: Supertest for endpoint validation
-   **Code Standards**: Consistent naming conventions and code structure

#### Version Control & Collaboration

-   **Git Workflow**: Feature branches, merge strategies
-   **Team Collaboration**: Multi-developer codebase management
-   **Documentation**: Comprehensive README and API documentation

---

## 👥 Team Collaboration

### Development Methodology

-   **Agile Practices**: Iterative development with regular team synchronization
-   **Task Distribution**: Clear separation of frontend/backend responsibilities
-   **Code Reviews**: Peer review process for quality assurance
-   **Integration Testing**: Regular testing of combined frontend/backend functionality

### Communication & Project Management

-   **Discord Integration**: Team communication and file sharing
-   **Version Control**: Collaborative Git workflow with conflict resolution
-   **Documentation**: Shared technical documentation and API specifications

### Individual Contributions

The project demonstrates effective teamwork with:

-   **Frontend Specialists**: React component development and UI/UX implementation
-   **Backend Specialists**: API development and database integration
-   **Full-Stack Integration**: Seamless frontend-backend communication
-   **DevOps Implementation**: Containerization and deployment automation

---

## 🔮 Future Enhancements

### Technical Improvements

-   **TypeScript Migration**: Complete frontend migration to TypeScript
-   **Testing Coverage**: Comprehensive unit and integration test suites
-   **Performance Optimization**: Code splitting, lazy loading, caching strategies
-   **Security Enhancements**: JWT authentication, rate limiting, input validation
-   **Real-time Features**: WebSocket integration for live updates

### Feature Additions

-   **Social Features**: User connections, workout sharing, community challenges
-   **Mobile Application**: React Native or Progressive Web App implementation
-   **Advanced Analytics**: Machine learning for progress prediction and recommendations
-   **Third-party Integrations**: Fitness tracker APIs, nutrition databases
-   **Offline Capabilities**: Service worker implementation for offline functionality

### Scalability Considerations

-   **Microservices Architecture**: Service decomposition for better scalability
-   **Database Optimization**: Indexing strategies, read replicas
-   **CDN Integration**: Static asset delivery optimization
-   **Load Balancing**: Horizontal scaling preparation

---

## 📊 Project Statistics

-   **Total Lines of Code**: ~15,000+ lines
-   **Components**: 50+ React components
-   **API Endpoints**: 15+ RESTful endpoints
-   **Database Collections**: 2 main collections (users, workouts)
-   **Pages/Routes**: 15+ application routes
-   **Development Time**: Full academic semester
-   **Team Size**: 4 developers

---

## 🏆 Conclusion

The Shape Shift fitness tracker represents a comprehensive full-stack application that demonstrates proficiency in modern web development technologies and practices. The project showcases the team's ability to:

-   Design and implement complex user interfaces with React
-   Build scalable RESTful APIs with Node.js and Express
-   Integrate with NoSQL databases using MongoDB
-   Implement secure authentication and session management
-   Deploy applications using containerization technologies
-   Collaborate effectively in a team environment
-   Apply software engineering best practices

This project serves as an excellent portfolio piece demonstrating real-world application development skills and the ability to deliver a complete, functional software solution from concept to deployment.

---

_This technical documentation was created to provide a comprehensive overview of the Shape Shift fitness tracker project, highlighting both the technical implementation and the learning outcomes achieved through this collaborative development effort._
