Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahmoud-Saeed-Mahmoud committed Nov 28, 2024
0 parents commit f9bbb18
Show file tree
Hide file tree
Showing 7 changed files with 577 additions and 0 deletions.
76 changes: 76 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
env/
ENV/
.env
.venv
env.bak/
venv.bak/

# SQLite database
*.db
*.sqlite
*.sqlite3

# IDE specific files
.idea/
.vscode/
*.swp
*.swo
.DS_Store
Thumbs.db

# Project specific
instance/
.webassets-cache
.env.local
.env.development.local
.env.test.local
.env.production.local

# Logs
*.log
logs/
log/

# Coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# Pytest
.pytest_cache/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Habit Tracker

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
110 changes: 110 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Habit Tracker

A modern, interactive web application for tracking daily, weekly, and monthly habits with visual progress monitoring and streak tracking.

## Features

- 📊 Visual progress tracking with interactive charts
- 🔥 Streak counting and monitoring
- 📅 Support for daily, weekly, and monthly habits
- ⏰ Customizable reminders
- 📱 Responsive design for desktop and mobile
- ✨ Modern, clean user interface

## Tech Stack

- **Backend**: Python Flask
- **Database**: SQLite with SQLAlchemy
- **Frontend**:
- Bootstrap 5 for UI components
- Chart.js for data visualization
- Vanilla JavaScript for interactivity

## Getting Started

### Prerequisites

- Python 3.8 or higher
- pip (Python package installer)

### Installation

1. Create and activate a virtual environment:
```bash
# Windows
python -m venv venv
venv\Scripts\activate

# Linux/MacOS
python -m venv venv
source venv/bin/activate
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Run the application:
```bash
python app.py
```

4. Open your browser and navigate to:
```
http://localhost:5000
```

## Usage

### Adding a New Habit

1. Click the "Add New Habit" button
2. Fill in the habit details:
- Name (required)
- Description (optional)
- Frequency (daily/weekly/monthly)
- Reminder time (optional)
3. Click "Add Habit" to save

### Tracking Progress

- Click "Mark Complete" to log a habit completion
- View your current streak next to each habit
- Monitor your progress through the visual chart
- Charts show the last 7 days of activity

## Project Structure

```
habit_tracker/
├── app.py # Main Flask application
├── requirements.txt # Python dependencies
├── static/
│ └── js/
│ └── main.js # Frontend JavaScript
├── templates/
│ └── index.html # Main HTML template
└── instance/
└── habits.db # SQLite database
```

## Contributing

1. Fork the repository
2. Create a new branch (`git checkout -b feature/improvement`)
3. Make your changes
4. Commit your changes (`git commit -am 'Add new feature'`)
5. Push to the branch (`git push origin feature/improvement`)
6. Create a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- [Flask](https://flask.palletsprojects.com/) - Web framework
- [Bootstrap](https://getbootstrap.com/) - UI framework
- [Chart.js](https://www.chartjs.org/) - JavaScript charting library
- [SQLAlchemy](https://www.sqlalchemy.org/) - Database ORM
98 changes: 98 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
import os
from dateutil import parser
import json

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///habits.db'
db = SQLAlchemy(app)

class Habit(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(200))
frequency = db.Column(db.String(50), nullable=False) # daily, weekly, monthly
reminder_time = db.Column(db.String(50))
created_at = db.Column(db.DateTime, default=datetime.utcnow)

class HabitLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
habit_id = db.Column(db.Integer, db.ForeignKey('habit.id'), nullable=False)
completed_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

with app.app_context():
db.create_all()

@app.route('/')
def index():
habits = Habit.query.all()
return render_template('index.html', habits=habits)

@app.route('/add_habit', methods=['POST'])
def add_habit():
name = request.form.get('name')
description = request.form.get('description')
frequency = request.form.get('frequency')
reminder_time = request.form.get('reminder_time')

habit = Habit(
name=name,
description=description,
frequency=frequency,
reminder_time=reminder_time
)
db.session.add(habit)
db.session.commit()

return redirect(url_for('index'))

@app.route('/log_completion/<int:habit_id>', methods=['POST'])
def log_completion(habit_id):
log = HabitLog(habit_id=habit_id)
db.session.add(log)
db.session.commit()
return jsonify({'success': True})

@app.route('/get_stats/<int:habit_id>')
def get_stats(habit_id):
habit = Habit.query.get_or_404(habit_id)
logs = HabitLog.query.filter_by(habit_id=habit_id).all()

# Calculate streak
if not logs:
return jsonify({'current_streak': 0, 'longest_streak': 0, 'completion_dates': []})

completion_dates = [log.completed_at.date() for log in logs]
completion_dates.sort()

# Calculate current streak
current_streak = 0
today = datetime.utcnow().date()
check_date = today

while check_date in completion_dates:
current_streak += 1
check_date -= timedelta(days=1)

# Calculate longest streak
longest_streak = current_streak
temp_streak = 0

for i in range(len(completion_dates)-1):
if (completion_dates[i+1] - completion_dates[i]).days == 1:
temp_streak += 1
longest_streak = max(longest_streak, temp_streak)
else:
temp_streak = 0

return jsonify({
'current_streak': current_streak,
'longest_streak': longest_streak,
'completion_dates': [date.strftime('%Y-%m-%d') for date in completion_dates]
})

if __name__ == '__main__':
app.run(debug=True)
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Flask==2.3.3
Flask-SQLAlchemy==3.0.5
Flask-Login==0.6.2
python-dateutil==2.8.2
APScheduler==3.10.4
Loading

0 comments on commit f9bbb18

Please sign in to comment.