Repository files navigation # Study Wellness Companion - Mood Journaling System
A comprehensive mood tracking and stress analysis system built with Node.js, Express, React, and Firebase. Students can log their mood, stress levels, and receive AI-powered insights about their wellness patterns.
## 🚀 Features
### Core Functionality
- **Mood Journaling**: Log daily moods with emoji selection (🙂 😐 😞 😡 😴 😰)
- **Stress Tracking**: Rate stress levels on a 0-10 slider
- **Smart Stress Calculation**: Algorithm combines mood and stress slider
- **Privacy-First**: Each user can only access their own data
### Analytics & Insights
- **Weekly History**: View mood entries in a calendar-style layout
- **Interactive Charts**: Line charts for stress trends, bar charts for mood distribution
- **Heatmap Visualization**: Color-coded stress scores by day
- **AI-Generated Summaries**: Weekly wellness insights (extensible)
### User Experience
- **Responsive Design**: Works on desktop, tablet, and mobile
- **Real-time Updates**: Instant feedback and data synchronization
- **Intuitive UI**: Clean, modern interface with Tailwind CSS
- **Authentication**: Secure Firebase Auth with Google OAuth
## 🏗️ Architecture
### Backend (Express + Node.js)
```
backend/
├── config/
│ └── firebase.js # Firebase Admin SDK setup
├── middleware/
│ └── auth.js # JWT token verification
├── routes/
│ └── mood.js # Mood CRUD endpoints
├── utils/
│ └── stressCalculator.js # Stress score algorithm
├── validation/
│ └── moodValidation.js # Input validation schemas
└── server.js # Express server setup
```
### Frontend (React)
```
frontend/src/
├── components/
│ ├── AuthProvider.jsx # Firebase auth context
│ ├── Dashboard.jsx # Main dashboard layout
│ ├── LoginForm.jsx # Authentication UI
│ ├── MoodQuickLog.jsx # Mood entry form
│ ├── WeeklyHistory.jsx # Calendar view
│ └── StressCharts.jsx # Analytics charts
├── services/
│ └── api.js # API client
└── config/
### Database (Firestore)
```
/users/{uid}
├── mood_entries/{entryId} # Mood logs with stress scores
├── summaries/{weekId} # Weekly AI summaries
└── tasks/{taskId} # Future task tracking
```
## 🧮 Stress Score Algorithm
The system calculates a comprehensive stress score (0-100) using two factors:
```javascript
// Stress Slider Score (0-1)
sliderScore = stressSlider / 10
// Mood Score (0-1)
moodScore = {
happy: 0, neutral: 0.4, tired: 0.5,
sad: 0.7, anxious: 0.8, angry: 0.9
}
// Final Stress Score (80% weight on slider, 20% on mood)
stressScore = 100 * (0.8*sliderScore + 0.2*moodScore)
// Stress Level Classification
stressLevel = {
0-39: 'low',
40-69: 'moderate',
70-100: 'high'
}
```
## 🛠️ Setup Instructions
### Prerequisites
- Node.js 18+
- Firebase project with Authentication and Firestore enabled
- Google Cloud account
### Backend Setup
1. **Install Dependencies**
```bash
cd backend
npm install
```
2. **Environment Configuration**
```bash
cp env.example .env
```
Fill in your Firebase Admin SDK credentials:
```env
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYour private key here\n-----END PRIVATE KEY-----"
PORT=3001
CORS_ORIGIN=http://localhost:3000
```
3. **Start Development Server**
```bash
npm run dev
```
### Frontend Setup
1. **Install Dependencies**
```bash
cd frontend
npm install
```
2. **Environment Configuration**
```bash
cp env.example .env
```
Fill in your Firebase client configuration:
```env
REACT_APP_FIREBASE_API_KEY=your-api-key
REACT_APP_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
REACT_APP_FIREBASE_PROJECT_ID=your-project-id
REACT_APP_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=123456789
REACT_APP_FIREBASE_APP_ID=your-app-id
REACT_APP_API_URL=http://localhost:3001
```
3. **Start Development Server**
```bash
npm start
```
### Firebase Configuration
1. **Enable Authentication**
- Go to Firebase Console → Authentication → Sign-in method
- Enable Email/Password and Google providers
2. **Setup Firestore**
- Go to Firestore Database
- Create database in production mode
- Deploy the security rules from `firestore.rules`
3. **Deploy Indexes**
```bash
firebase deploy --only firestore:indexes
```
## 📊 API Endpoints
### Authentication Required
All endpoints require a Firebase ID token in the Authorization header:
```
Authorization: Bearer
```
### Mood Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/mood` | Create mood entry with stress calculation |
| `GET` | `/api/mood` | List entries with optional date filtering |
| `PATCH` | `/api/mood/:id` | Update existing entry |
| `DELETE` | `/api/mood/:id` | Delete entry |
| `GET` | `/api/mood/stats` | Get aggregated statistics |
### Example Request/Response
**Create Mood Entry**
```bash
POST /api/mood
{
"mood": "anxious",
"stressSlider": 7,
"note": "Big exam tomorrow",
"tags": ["exam", "sleep"]
}
```
**Response**
```json
{
"success": true,
"data": {
"id": "entry-id",
"uid": "user-id",
"ts": "2025-01-15T18:30:00.000Z",
"dayKey": "2025-01-15",
"mood": "anxious",
"stressSlider": 7,
"note": "Big exam tomorrow",
"tags": ["exam", "sleep"],
"stressScore": 73,
"stressLevel": "high",
"source": "manual"
}
}
```
## 🔒 Security Features
### Firestore Security Rules
- Users can only access their own data (`uid == request.auth.uid`)
- Input validation for mood values, stress slider (0-10), and note length (≤240 chars)
- Server-side stress score calculation prevents client manipulation
### API Security
- JWT token verification on all endpoints
- Rate limiting (100 requests per 15 minutes)
- CORS protection
- Input validation with Joi schemas
## 🎨 UI Components
### MoodQuickLog
- Emoji picker for mood selection
- Interactive stress slider (0-10)
- Note textarea with character limit
- Tag selection chips
- Real-time form validation
### WeeklyHistory
- Calendar-style weekly view
- Entry cards with mood and stress data
- Edit/delete functionality
- Date navigation
### StressCharts
- Line chart for stress score trends
- Stacked bar chart for mood distribution
- Pie charts for overview statistics
- Interactive tooltips and legends
## 🚀 Deployment
### Backend (Vercel/Netlify Functions)
```bash
# Install Vercel CLI
npm i -g vercel
# Deploy
vercel --prod
```
### Frontend (Vercel/Netlify)
```bash
# Build
npm run build
# Deploy
vercel --prod
```
### Environment Variables
Set the following in your deployment platform:
- Firebase Admin SDK credentials
- Firebase client configuration
- CORS origins for production
## 🔮 Future Enhancements
- **AI Weekly Summaries**: Generate insights using OpenAI/Claude
- **Task Integration**: Link mood entries to study tasks
- **Social Features**: Anonymous peer comparison (optional)
- **Export Data**: CSV/PDF export for personal records
- **Mobile App**: React Native version
- **Advanced Analytics**: Machine learning stress prediction
## 📝 License
MIT License - see LICENSE file for details
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
## 📞 Support
For issues and questions:
1. Check the Firebase documentation
2. Review the API documentation
3. Open an issue in this repository
---
**Built with ❤️ for student wellness**
## 🚀 **How to Run the Study Wellness Companion Project**
### **📋 Prerequisites**
Before starting, make sure you have:
- **Node.js 18+** installed ([Download here](https://nodejs.org/ ))
- **Firebase project** set up ([Firebase Console](https://console.firebase.google.com/ ))
- **Google Cloud account** (for Firebase)
---
## **🔧 Step 1: Firebase Project Setup**
### **1.1 Create Firebase Project**
1. Go to [Firebase Console](https://console.firebase.google.com/ )
2. Click "Create a project" or select existing project
3. Follow the setup wizard
### **1.2 Enable Authentication**
1. In Firebase Console → **Authentication** → **Sign-in method**
2. Enable **Email/Password** provider
3. Enable **Google** provider (add your domain to authorized domains)
### **1.3 Setup Firestore Database**
1. Go to **Firestore Database**
2. Click "Create database"
3. Choose **Production mode** (we'll add security rules later)
4. Select a location close to you
### **1.4 Get Firebase Configuration**
1. Go to **Project Settings** → **General**
2. Scroll to "Your apps" section
3. Click the web app icon () to add a web app
4. Copy the Firebase config object
---
## **⚙️ Step 2: Backend Setup**
### **2.1 Install Backend Dependencies**
```bash
```
### **2.2 Configure Backend Environment**
```bash
cp env.example .env
```
Edit the `.env` file with your Firebase Admin SDK credentials:
```env
# Firebase Admin SDK Configuration
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYour private key here\n-----END PRIVATE KEY-----"
# Server Configuration
PORT=3001
NODE_ENV=development
# CORS Configuration
CORS_ORIGIN=http://localhost:3000
# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
```
**To get Firebase Admin SDK credentials:**
1. Go to Firebase Console → **Project Settings** → **Service Accounts**
2. Click "Generate new private key"
3. Download the JSON file
4. Extract `project_id`, `private_key`, and `client_email`
### **2.3 Start Backend Server**
```bash
npm run dev
```
**Expected output:**
```
🚀 Study Wellness Backend running on port 3001
📊 Environment: development
🔗 CORS Origin: http://localhost:3000
```
---
## **🎨 Step 3: Frontend Setup**
### **3.1 Install Frontend Dependencies**
```bash
cd frontend
npm install
```
### **3.2 Configure Frontend Environment**
```bash
cp env.example .env
```
Edit the `.env` file with your Firebase client configuration:
```env
# Firebase Configuration
REACT_APP_FIREBASE_API_KEY=your-api-key
REACT_APP_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
REACT_APP_FIREBASE_PROJECT_ID=your-project-id
REACT_APP_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=123456789
REACT_APP_FIREBASE_APP_ID=your-app-id
# API Configuration
REACT_APP_API_URL=http://localhost:3001
```
### **3.3 Start Frontend Development Server**
```bash
npm start
```
**Expected output:**
```
Compiled successfully!
You can now view study-wellness-frontend in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.x.x:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
```
---
## **🔒 Step 4: Deploy Firestore Security Rules**
### **4.1 Install Firebase CLI**
```bash
npm install -g firebase-tools
```
### **4.2 Login to Firebase**
```bash
firebase login
```
### **4.3 Initialize Firebase in Project**
```bash
firebase init firestore
```
- Select your Firebase project
- Use existing `firestore.rules` file
- Use existing `firestore.indexes.json` file
### **4.4 Deploy Security Rules**
```bash
firebase deploy --only firestore:rules
firebase deploy --only firestore:indexes
```
---
## **🌐 Step 5: Access the Application**
### **5.1 Open Your Browser**
Navigate to: **http://localhost:3000**
### **5.2 What You'll See**
1. **Login Page**: Sign in with Google or email/password
2. **Dashboard**: After login, you'll see:
- **Quick Mood Log**: Emoji picker, stress slider, notes, tags
- **Stress & Mood Analytics**: Interactive charts
- **Weekly History**: Calendar view of mood entries
---
## **📱 Step 6: Test the Application**
### **6.1 Create Your First Mood Entry**
1. Select a mood emoji (🙂 😐 😞 😡 😴 😰)
2. Adjust stress slider (0-10)
3. Add optional notes and tags
4. Click "Save Mood Entry"
### **6.2 View Analytics**
1. Check the **Stress Charts** section
2. Navigate between weeks
3. View different chart types (Stress Trends, Mood Distribution, Overview)
### **6.3 Review History**
1. Check the **Weekly History** section
2. Navigate between weeks
3. Edit or delete entries
---
## **🔧 Troubleshooting**
### **Common Issues:**
**Backend won't start:**
- Check if port 3001 is available
- Verify Firebase credentials in `.env`
- Ensure all dependencies are installed
**Frontend won't connect:**
- Verify backend is running on port 3001
- Check `REACT_APP_API_URL` in frontend `.env`
- Ensure CORS is configured correctly
**Authentication errors:**
- Verify Firebase Authentication is enabled
- Check Firebase config in frontend `.env`
- Ensure domain is authorized in Firebase Console
**Database errors:**
- Verify Firestore security rules are deployed
- Check Firebase project ID matches in both environments
- Ensure Firestore indexes are deployed
---
## **🎯 Expected Output**
When everything is working correctly, you should see:
1. **Backend running**: `🚀 Study Wellness Backend running on port 3001`
2. **Frontend running**: `http://localhost:3000` opens in browser
3. **Login page**: Clean authentication interface
4. **Dashboard**: Full mood tracking interface with:
- Interactive mood logging form
- Real-time stress calculation
- Beautiful analytics charts
- Weekly history calendar
- Responsive design
The application will be fully functional for mood journaling, stress tracking, and data visualization!
# student-wellness-tracker
You can’t perform that action at this time.