Trung tâm thông minh sức khỏe cá nhân - Website tư vấn và theo dõi sức khỏe được xây dựng với MERN Stack
Sinh viên thực hiện:
- Họ tên: Phan Đăng Khoa
- MSSV: 110122227
- Email: [email protected]
- Điện thoại: 0867570650
Giảng viên hướng dẫn:
- Họ tên: ThS.Nguyễn Hoàng Duy Thiện
Trường: Đại học Trà Vinh Khoa: Công nghệ thông tin Năm học: 2025-2026
Repository: https://github.com/KhoaPhanix/cn-da22ttb-phandangkhoa-PHIHub-mernstack
- Thông tin liên hệ
- Cấu trúc dự án
- Giới thiệu
- Tính năng
- Công nghệ
- Kiến trúc
- Cài đặt
- Documentation
- Sử dụng
- API Documentation
- Docker Deploy
PHIHub/
├── README.md # Tài liệu chính (file này)
│
├── setup/ # Hướng dẫn cài đặt và triển khai
│ ├── INSTALL.md # Hướng dẫn cài đặt chi tiết
│ └── sample-data/ # Dữ liệu thử nghiệm
│ ├── articles.json # Dữ liệu bài viết mẫu
│ ├── import.js # Script import dữ liệu
│ ├── package.json
│ └── README.md
│
├── src/ # Mã nguồn chương trình
│ ├── client/ # Frontend (React + Vite)
│ │ ├── src/
│ │ │ ├── components/ # React components
│ │ │ ├── pages/ # Các trang chính
│ │ │ ├── context/ # State management
│ │ │ ├── services/ # API services
│ │ │ └── App.jsx
│ │ ├── public/
│ │ ├── Dockerfile
│ │ ├── nginx.conf
│ │ ├── package.json
│ │ └── vite.config.js
│ │
│ └── server/ # Backend (Node.js + Express)
│ ├── src/
│ │ ├── models/ # Mongoose schemas
│ │ ├── controllers/ # Route handlers
│ │ ├── routes/ # API routes
│ │ ├── middleware/ # Auth, error handling
│ │ ├── services/ # Business logic
│ │ ├── config/ # Database config
│ │ └── server.js # Entry point
│ ├── Dockerfile
│ ├── package.json
│ └── .env.example
│
├── docker/ # Docker deployment
│ └── docker-compose.yml # Container orchestration
│
├── docs/ # Tài liệu dự án
│ ├── API_DOCUMENTATION.md # Tài liệu API đầy đủ
│ ├── USER_GUIDE.md # Hướng dẫn người dùng
│ └── GUIDE_FOR_BOARD.md # Báo cáo cho hội đồng
│
├── progress-report/ # [BẮT BUỘC] Báo cáo tiến độ
│ └── [Các file báo cáo tuần/tháng]
│
├── thesis/ # [BẮT BUỘC] Tài liệu đồ án
│ ├── doc/ # Tài liệu .DOC/.DOCX
│ ├── pdf/ # Tài liệu .PDF
│ ├── html/ # Tài liệu web
│ ├── abs/ # Báo cáo tóm tắt (.PPT, .AVI, ...)
│ └── refs/ # Tài liệu tham khảo
│
└── soft/ # Phần mềm liên quan (nếu có)
└── [Các công cụ, thư viện hỗ trợ]
Chứa tài liệu hướng dẫn cài đặt chi tiết và dữ liệu thử nghiệm:
INSTALL.md: Hướng dẫn setup development và productionsample-data/: Script và dữ liệu mẫu để test hệ thống
Mã nguồn chính của ứng dụng:
client/: Frontend React applicationserver/: Backend API Node.js/Express
Cấu hình triển khai Docker với docker-compose
Tài liệu dự án đầy đủ:
- API Documentation, User Guide, Board Guide
[BẮT BUỘC] Các báo cáo tiến độ theo tuần/tháng
[BẮT BUỘC] Tài liệu đồ án đầy đủ với các định dạng khác nhau
Các phần mềm, công cụ hỗ trợ (nếu có)
PHIHub là một ứng dụng web full-stack giúp người dùng:
- ✅ Theo dõi chỉ số sức khỏe hàng ngày (cân nặng, giấc ngủ, calo, hoạt động thể chất)
- 📊 Trực quan hóa dữ liệu qua biểu đồ tương tác (LineChart, BarChart, PieChart)
- 🤖 Nhận khuyến nghị sức khỏe tự động dựa trên Rule-based AI Engine
- 📚 Truy cập thư viện kiến thức y tế
- 🔐 Xác thực an toàn với JWT (HttpOnly Cookie)
- Đăng ký/Đăng nhập với JWT Authentication
- HttpOnly Cookie (bảo mật cao, chống XSS)
- Quản lý hồ sơ cá nhân đầy đủ với 3 tabs:
- Thông tin cơ bản: Tên, ngày sinh, giới tính, địa chỉ
- Thông tin y tế: Quản lý bệnh lý nền, dị ứng, thuốc đang dùng
- Liên hệ khẩn cấp: Người liên hệ khẩn cấp và thông tin bác sĩ
- Biểu đồ đường (LineChart): Theo dõi biến động cân nặng 30 ngày
- Biểu đồ cột (BarChart): Phân tích giấc ngủ 7 ngày gần nhất
- Thống kê tổng hợp: Trung bình, Min, Max
- Cảnh báo sức khỏe thông minh (AlertBanner) với severity levels
- Hiển thị mục tiêu đang hoạt động (top 3) với progress bars
- Sử dụng Recharts library
- Đặt mục tiêu cho các chỉ số sức khỏe (cân nặng, BMI, huyết áp, giấc ngủ, v.v.)
- Tự động tính toán tiến độ và cập nhật progress
- Hiển thị trực quan với progress bars
- Filter theo status (Active/Completed/Failed/All)
- Thống kê tổng quan về mục tiêu
- Quản lý milestones
- Ghi nhật ký bữa ăn chi tiết (Sáng, Trưa, Tối, Snack)
- Theo dõi nhiều món ăn trong một bữa
- Tự động tính toán tổng calories và macros (protein, carbs, fats)
- Biểu đồ Pie Chart cho phân bố macronutrients
- Thống kê dinh dưỡng theo tuần
- Date picker để xem lịch sử
- Ghi nhật ký tâm trạng hàng ngày với emoji selector
- Theo dõi energy, stress, anxiety levels (sliders 1-10)
- Emotion và activity tags (multi-select)
- Journaling với textarea
- Gratitude list (3 items)
- Biểu đồ Line Chart hiển thị xu hướng tâm trạng 30 ngày
- Thống kê trung bình mood, energy, stress, anxiety
- Nhắc nhở uống thuốc, uống nước, tập luyện
- Lập lịch linh hoạt: daily, weekly, monthly, custom
- Toggle on/off nhanh chóng
- Tự động tính thời gian nhắc tiếp theo
- ReminderCard component với icons
- Phân tích chỉ số và cảnh báo bất thường
- Severity levels: low, medium, high, critical
- Color-coded alerts (blue/yellow/orange/red)
- Mark as read/resolved actions
- Tự động tạo alerts khi metrics vượt ngưỡng
- AlertBanner hiển thị ở đầu Dashboard
- Form nhập liệu thủ công với MetricsEntryPage
- Hỗ trợ 11 loại metrics: weight, height, BMI, blood pressure, heart rate, blood sugar, temperature, sleep, calories, steps, exercise
- Lưu trữ với timestamp
- Date picker để chọn ngày
- HistoryPage với 2 chế độ xem: Charts và Table
- Export dữ liệu ra CSV
- Filter theo loại metric và khoảng thời gian
- Phân tích xu hướng dài hạn
- Rule-based Engine với
json-rules-engine - Phân tích dữ liệu 7 ngày gần nhất
- 15 rules: giấc ngủ, cân nặng, BMI, huyết áp, đường huyết, hoạt động thể chất, calories
- Khuyến nghị tự động hiển thị trên Dashboard
- Thư viện bài viết sức khỏe (KnowledgePage)
- Lọc theo danh mục (Dinh dưỡng, Thể chất, Tinh thần, Chung)
- Chi tiết bài viết với HTML rendering
- Search functionality
- React 18 - UI Library
- Vite - Build tool (cực nhanh)
- React Router DOM 6 - Routing
- Recharts - Data visualization (LineChart, BarChart, PieChart)
- Axios - HTTP client
- Tailwind CSS - Styling (dark theme)
- date-fns - Date utilities
- Node.js - Runtime environment
- Express.js - Web framework
- MongoDB - NoSQL Database
- Mongoose - ODM
- JWT - Authentication
- bcryptjs - Password hashing
- json-rules-engine - Recommendation engine (15 rules)
- cookie-parser - Cookie management
- multer - File uploads (avatars)
- Docker - Containerization
- Docker Compose - Multi-container orchestration
- Nginx - Frontend serving (production)
- Git - Version control
Xem chi tiết trong: setup/INSTALL.md - Phần "Sơ đồ triển khai"
Client (React + Vite)
↓ HTTP/HTTPS
Nginx (Production) → Backend API (Express)
↓
MongoDB
src/
├── client/ # Frontend
│ ├── src/
│ │ ├── components/ # 7 components (Footer, Navbar, AlertBanner, etc.)
│ │ ├── pages/ # 11 pages (Dashboard, Goals, Nutrition, Mood, etc.)
│ │ ├── context/ # AuthContext
│ │ ├── services/ # 11 API services
│ │ └── App.jsx
│ ├── Dockerfile
│ └── nginx.conf
│
└── server/ # Backend
├── src/
│ ├── models/ # 8 Mongoose models
│ ├── controllers/ # 10 controllers
│ ├── routes/ # 10 route files
│ ├── middleware/ # auth.js, errorHandler.js
│ ├── services/ # recommendationService.js (15 rules)
│ └── server.js
└── Dockerfile
Collection: users
{
name: String,
email: String (unique),
password: String (hashed),
dob: Date,
gender: String,
phone: String,
address: String,
avatar: String,
medicalInfo: {
chronicConditions: [...],
allergies: [...],
medications: [...],
emergencyContact: {...},
doctor: {...}
}
}Collection: health_metrics
{
userId: ObjectId (ref: User),
metricType: String (weight/sleep/calories/exercise/bmi/bloodPressure/heartRate/bloodSugar/temperature/steps/height),
value: Number,
unit: String,
timestamp: Date,
notes: String
}Collection: goals
{
userId: ObjectId,
title: String,
description: String,
goalType: String,
startValue: Number,
targetValue: Number,
currentValue: Number,
unit: String,
startDate: Date,
targetDate: Date,
status: String (active/completed/failed/cancelled),
progress: Number (0-100),
milestones: [...],
reminders: {...}
}Collection: nutrition
{
userId: ObjectId,
date: Date,
mealType: String (breakfast/lunch/dinner/snack),
foodItems: [{
name: String,
quantity: Number,
unit: String,
calories: Number,
macros: { protein, carbs, fats, fiber }
}],
totalCalories: Number,
totalMacros: {...},
notes: String
}Collection: mood_logs
{
userId: ObjectId,
date: Date,
mood: String (excellent/good/okay/bad/terrible),
moodScore: Number (1-10),
energy: String,
energyScore: Number,
stress: String,
stressScore: Number,
anxiety: Number,
activities: [String],
emotions: [String],
journal: String,
gratitude: [String],
sleepQuality: Number,
productivity: Number
}Collection: reminders
{
userId: ObjectId,
title: String,
description: String,
type: String (medication/water/exercise/meal/checkup/custom),
time: String (HH:MM),
frequency: String (once/daily/weekly/monthly/custom),
daysOfWeek: [Number],
customDays: [Date],
isActive: Boolean,
lastTriggered: Date,
nextScheduled: Date
}Collection: alerts
{
userId: ObjectId,
title: String,
message: String,
severity: String (low/medium/high/critical),
category: String,
relatedMetric: ObjectId,
isRead: Boolean,
isResolved: Boolean,
resolvedAt: Date,
expiresAt: Date
}Collection: articles
{
title: String,
content: String (HTML),
category: String,
imageUrl: String,
author: String,
publishedAt: Date
}📖 Xem hướng dẫn đầy đủ tại:
setup/INSTALL.md
- Node.js >= 18.x
- npm hoặc yarn
- MongoDB (local hoặc Atlas)
- Docker & Docker Compose (cho deployment)
# 1. Clone repository
git clone https://github.com/KhoaPhanix/cn-da22ttb-phandangkhoa-PHIHub-mernstack.git
cd PHIHub
# 2. Cài đặt Backend
cd src/server
npm install
# Tạo file .env (xem .env.example)
# Điền MONGO_URI, JWT_SECRET, PORT, CLIENT_URL
# 3. Cài đặt Frontend
cd ../client
npm install
# 4. Chạy ứng dụng
# Terminal 1 - Backend (port 5000)
cd src/server
npm run dev
# Terminal 2 - Frontend (port 5173)
cd src/client
npm run devcd docker
docker-compose up -d --build
# Truy cập: http://localhost:8080Xem thêm:
- Hướng dẫn cài đặt chi tiết:
setup/INSTALL.md - Import dữ liệu mẫu:
setup/sample-data/README.md
- API Documentation - Tài liệu API đầy đủ với 60+ endpoints
- User Guide - Hướng dẫn sử dụng chi tiết cho người dùng
- Installation Guide - Hướng dẫn cài đặt và triển khai
- Board Guide - Báo cáo cho hội đồng
- Features Status - Trạng thái triển khai tính năng
- Changelog - Lịch sử phát triển dự án
Cho Người Dùng:
Cho Developers:
Cho Admin:
Backend (Port 5000):
cd src/server
npm run dev # nodemonFrontend (Port 5173):
cd src/client
npm run dev # Vite dev serverTruy cập: http://localhost:5173
# Build Frontend
cd src/client
npm run build # → dist/
# Run Backend
cd ../server
npm startcd docker
docker-compose up -dServices:
- Frontend:
http://localhost:8080 - Backend API:
http://localhost:5000 - MongoDB:
localhost:27017
Xem thêm: setup/INSTALL.md - Xử lý sự cố
📖 Xem tài liệu đầy đủ:
docs/API_DOCUMENTATION.md
http://localhost:5000/api
- Authentication (
/api/auth) - Register, Login, Logout, Get Me - Users (
/api/users) - Profile management, Avatar upload - Health Metrics (
/api/metrics) - CRUD, Statistics, Charts data - Goals (
/api/goals) - CRUD, Progress tracking, Statistics - Nutrition (
/api/nutrition) - Meal logging, Daily summary, Stats - Mood Logs (
/api/mood) - CRUD, Trend analysis, Statistics - Reminders (
/api/reminders) - CRUD, Toggle, Upcoming reminders - Alerts (
/api/alerts) - Auto-generated health alerts, CRUD - Articles (
/api/articles) - Knowledge base (public + admin) - Recommendations (
/api/recommendations) - AI-powered health advice
POST /api/auth/register
Content-Type: application/json
{
"name": "Nguyễn Văn A",
"email": "[email protected]",
"password": "password123",
"dob": "1990-01-01",
"gender": "male"
}GET /api/metrics?metricType=weight&days=30
Authorization: Bearer <token>POST /api/goals
Authorization: Bearer <token>
Content-Type: application/json
{
"title": "Giảm cân",
"goalType": "weight",
"startValue": 75,
"targetValue": 70,
"unit": "kg",
"targetDate": "2025-03-15"
}🔒 = Yêu cầu authentication (JWT token in HttpOnly cookie)
📖 Xem hướng dẫn chi tiết:
setup/INSTALL.md- Phần "Docker"
cd docker
docker-compose up -d --build# Xem logs
docker-compose logs -f
# Xem logs specific service
docker-compose logs -f server
# Dừng containers
docker-compose down
# Xóa volumes
docker-compose down -v
# Rebuild
docker-compose up -d --buildservices:
mongo: # MongoDB 7.0 (port 27017)
server: # Backend API (port 5000)
client: # Frontend Nginx (port 8080)Volumes: mongo-data (persistent storage)
Network: phihub-network (bridge)
Sử dụng json-rules-engine để tạo rule-based AI với 15 rules:
- Sleep - 3 rules (insufficient, good, excessive)
- Weight - 2 rules (rapid loss, rapid gain)
- BMI - 3 rules (underweight, overweight, obese)
- Blood Pressure - 2 rules (high, low)
- Blood Sugar - 2 rules (high, low)
- Exercise - 1 rule (insufficient)
- Calories - 2 rules (excessive, insufficient)
Edit file src/server/src/services/recommendationService.js
engine.addRule({
conditions: {
all: [
{
fact: 'averageSleep',
operator: 'lessThan',
value: 7,
},
],
},
event: {
type: 'sleep_insufficient',
params: {
message: 'Custom message here',
priority: 'high',
category: 'sleep',
},
},
});- Total Files: 200+
- Lines of Code: 25,000+
- Frontend Components: 7 reusable components
- Frontend Pages: 11 pages
- Backend Models: 8 Mongoose schemas
- Backend Controllers: 10 controllers
- Backend Routes: 10 route groups
- API Endpoints: 60+
- AI Rules: 15 health recommendation rules
- React: 18.3.1
- Node.js: >= 18.x
- Express: 4.21.2
- MongoDB: 7.0
- Mongoose: 8.8.4
- Vite: 6.0.3
- Tailwind CSS: 3.4.17
- Recharts: 2.15.0
Backend (100%):
- ✅ 8 Mongoose models với validation
- ✅ 10 controllers với error handling
- ✅ 60+ API endpoints
- ✅ JWT authentication với HttpOnly cookies
- ✅ AI recommendation engine (15 rules)
- ✅ File upload (multer)
- ✅ CORS configuration
- ✅ Error middleware
Frontend (100%):
- ✅ 11 pages hoàn chỉnh
- ✅ 7 reusable components
- ✅ AuthContext state management
- ✅ 11 API service clients
- ✅ Responsive design (Tailwind CSS)
- ✅ Dark theme
- ✅ Charts (Line, Bar, Pie)
- ✅ Form validation
- ✅ Date pickers
- ✅ CSV export
- ✅ Search & Filter
DevOps:
- ✅ Docker setup (3 containers)
- ✅ Docker Compose orchestration
- ✅ Nginx configuration
- ✅ Environment variables
- ✅ Git version control
Documentation:
- ✅ README.md (file này)
- ✅ API Documentation (60+ endpoints)
- ✅ User Guide (13 sections)
- ✅ Installation Guide
- ✅ Board Guide
- ✅ Changelog
-
JWT Authentication
- HttpOnly Cookie (không thể truy cập từ JavaScript → chống XSS)
- Secure flag (HTTPS only in production)
- SameSite strict (chống CSRF)
- 24h expiration
-
Password Security
- bcryptjs hashing (salt rounds: 10)
- Password không bao giờ trả về trong response
- Min length validation
-
CORS Configuration
- Chỉ cho phép client URL cụ thể
- Credentials: true (cho phép cookies)
- Methods: GET, POST, PUT, PATCH, DELETE
-
Input Validation
- Mongoose schema validation
- Email format validation
- Required fields checking
- Enum validation
-
File Upload Security
- File type restriction (images only)
- File size limit (5MB)
- Unique filenames (UUID)
- Responsive Design - Mobile, Tablet, Desktop
- Dark Theme - Tailwind CSS với dark mode
- Loading States - LoadingSpinner component
- Error Handling - User-friendly error messages
- Toast Notifications - Success/Error feedback
- Progress Indicators - Progress bars, percentages
- Charts & Visualizations - Recharts library
- Date Pickers - HTML5 date inputs
- Multi-select Tags - Emotion, Activity tags
- Sliders - Energy, Stress, Anxiety levels
- Tabs Navigation - ProfilePage (3 tabs)
- Modal Forms - Add/Edit dialogs
- Search & Filter - KnowledgePage, HistoryPage
- CSV Export - HistoryPage data export
MIT License - Free to use for personal and commercial projects.
Developed with ❤️ by KhoaPhanix
- GitHub: @KhoaPhanix
- Email: [email protected]
- University: Trà Vinh University
- Major: Information Technology
- Year: 2025-2026
- Recharts - Beautiful charts library
- MongoDB - Flexible NoSQL database
- Tailwind CSS - Utility-first CSS framework
- json-rules-engine - Rule-based decision engine
- React - Powerful UI library
- Express - Fast, minimalist web framework
- Vite - Lightning-fast build tool
- Docker - Containerization platform
Nếu bạn gặp vấn đề hoặc có câu hỏi:
- Email: [email protected]
- GitHub Issues: Create an issue
- Documentation: Xem
docs/folder - FAQ: User Guide - FAQ Section
Happy Coding! 🚀