Start the timeman project, initial commit.
This commit is contained in:
parent
945fa039c4
commit
15b5bd63e1
4 changed files with 301 additions and 0 deletions
137
app.py
Normal file
137
app.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_socketio import SocketIO, emit
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
db = SQLAlchemy(app)
|
||||
socketio = SocketIO(app)
|
||||
|
||||
# Database models
|
||||
class Task(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(100), nullable=False)
|
||||
priority = db.Column(db.String(1), nullable=False) # A, B, C, or D
|
||||
duration = db.Column(db.Integer, nullable=False) # Duration in minutes
|
||||
status = db.Column(db.String(10), default='pending')
|
||||
due_date = db.Column(db.Date, nullable=True) # Due date for the task
|
||||
completed_at = db.Column(db.DateTime, nullable=True) # Timestamp for when the task was completed
|
||||
|
||||
def format_duration(minutes):
|
||||
"""Convert duration in minutes to 'H M' format."""
|
||||
hours = minutes // 60
|
||||
remaining_minutes = minutes % 60
|
||||
if hours > 0:
|
||||
return f"{hours}H {remaining_minutes}M" if remaining_minutes > 0 else f"{hours}H"
|
||||
return f"{remaining_minutes}M"
|
||||
|
||||
@app.context_processor
|
||||
def utility_processor():
|
||||
return dict(format_duration=format_duration)
|
||||
|
||||
def cleanup_completed_tasks():
|
||||
"""Remove tasks that have been completed for more than 1 hour."""
|
||||
expiration_time = datetime.utcnow() - timedelta(hours=1)
|
||||
old_tasks = Task.query.filter(Task.status == 'completed', Task.completed_at < expiration_time).all()
|
||||
for task in old_tasks:
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
|
||||
# Routes
|
||||
@app.route('/')
|
||||
def index():
|
||||
cleanup_completed_tasks() # Remove old completed tasks
|
||||
|
||||
# Get the sorting parameter from the query string (default is "priority")
|
||||
sort_by = request.args.get('sort_by', 'priority')
|
||||
|
||||
# Dynamically sort tasks based on the parameter
|
||||
if sort_by == 'priority':
|
||||
tasks = Task.query.filter(Task.status == 'pending').order_by(Task.priority).all()
|
||||
elif sort_by == 'due_date':
|
||||
tasks = Task.query.filter(Task.status == 'pending').order_by(Task.due_date).all()
|
||||
elif sort_by == 'duration':
|
||||
tasks = Task.query.filter(Task.status == 'pending').order_by(Task.duration).all()
|
||||
else:
|
||||
tasks = Task.query.filter(Task.status == 'pending').all() # Default: no sorting
|
||||
|
||||
return render_template('index.html', tasks=tasks, sort_by=sort_by)
|
||||
|
||||
@app.route('/add_task', methods=['POST'])
|
||||
def add_task():
|
||||
name = request.form['name']
|
||||
priority = request.form['priority']
|
||||
duration_input = request.form['duration']
|
||||
due_date_input = request.form['due_date']
|
||||
|
||||
# Parse duration (e.g., "10M" -> 10 minutes, "2H" -> 120 minutes)
|
||||
if duration_input.endswith('M'):
|
||||
duration = int(duration_input[:-1]) # Extract the number before 'M'
|
||||
elif duration_input.endswith('H'):
|
||||
duration = int(duration_input[:-1]) * 60 # Convert hours to minutes
|
||||
else:
|
||||
return "Invalid duration format. Use 'M' for minutes or 'H' for hours.", 400
|
||||
|
||||
# Parse due date (e.g., "2025-03-30")
|
||||
try:
|
||||
due_date = datetime.strptime(due_date_input, '%Y-%m-%d').date() if due_date_input else None
|
||||
except ValueError:
|
||||
return "Invalid due date format. Use 'YYYY-MM-DD'.", 400
|
||||
|
||||
# Create and save the new task
|
||||
new_task = Task(name=name, priority=priority, duration=duration, due_date=due_date)
|
||||
db.session.add(new_task)
|
||||
db.session.commit()
|
||||
|
||||
# Emit the new task to connected clients
|
||||
socketio.emit('task_update', {
|
||||
'action': 'add',
|
||||
'task': {
|
||||
'id': new_task.id,
|
||||
'name': name,
|
||||
'priority': priority,
|
||||
'duration': duration,
|
||||
'due_date': due_date_input,
|
||||
'status': 'pending'
|
||||
}
|
||||
})
|
||||
return redirect(url_for('index'))
|
||||
|
||||
@app.route('/complete_task/<int:task_id>')
|
||||
def complete_task(task_id):
|
||||
task = Task.query.get(task_id)
|
||||
if task:
|
||||
task.status = 'completed'
|
||||
task.completed_at = datetime.utcnow() # Store the timestamp in UTC
|
||||
db.session.commit()
|
||||
socketio.emit('task_update', {'action': 'complete', 'task_id': task_id})
|
||||
return redirect(url_for('index'))
|
||||
|
||||
@app.route('/completed_tasks')
|
||||
def completed_tasks():
|
||||
cleanup_completed_tasks() # Remove old completed tasks
|
||||
|
||||
# Get the sorting parameter from the query string (default is "completed_at")
|
||||
sort_by = request.args.get('sort_by', 'completed_at')
|
||||
|
||||
# Dynamically sort tasks based on the parameter
|
||||
if sort_by == 'priority':
|
||||
tasks = Task.query.filter(Task.status == 'completed').order_by(Task.priority).all()
|
||||
elif sort_by == 'due_date':
|
||||
tasks = Task.query.filter(Task.status == 'completed').order_by(Task.due_date).all()
|
||||
elif sort_by == 'duration':
|
||||
tasks = Task.query.filter(Task.status == 'completed').order_by(Task.duration).all()
|
||||
elif sort_by == 'completed_at':
|
||||
tasks = Task.query.filter(Task.status == 'completed').order_by(Task.completed_at.desc()).all()
|
||||
else:
|
||||
tasks = Task.query.filter(Task.status == 'completed').all() # Default: no sorting
|
||||
|
||||
return render_template('completed_tasks.html', tasks=tasks, sort_by=sort_by)
|
||||
|
||||
if __name__ == '__main__':
|
||||
with app.app_context():
|
||||
# Create database tables within the app context
|
||||
db.create_all()
|
||||
socketio.run(app, debug=True)
|
||||
4
init_db.py
Normal file
4
init_db.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
from app import db
|
||||
|
||||
db.create_all()
|
||||
print("Database and tables created successfully.")
|
||||
50
templates/completed_tasks.html
Normal file
50
templates/completed_tasks.html
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Completed Tasks</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Completed Tasks</h1>
|
||||
<a href="/" class="btn btn-primary mb-3">Back to Pending Tasks</a>
|
||||
|
||||
<!-- Sorting Options -->
|
||||
<div class="mb-3">
|
||||
<label for="sort_by" class="form-label">Sort By:</label>
|
||||
<select id="sort_by" class="form-select" onchange="sortTasks()">
|
||||
<option value="completed_at" {% if sort_by == 'completed_at' %}selected{% endif %}>Completed At</option>
|
||||
<option value="priority" {% if sort_by == 'priority' %}selected{% endif %}>Priority</option>
|
||||
<option value="due_date" {% if sort_by == 'due_date' %}selected{% endif %}>Due Date</option>
|
||||
<option value="duration" {% if sort_by == 'duration' %}selected{% endif %}>Duration</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Completed Task List -->
|
||||
<ul class="list-group">
|
||||
{% for task in tasks %}
|
||||
<li class="list-group-item d-flex justify-content-between align-items-center">
|
||||
<div>
|
||||
<strong>{{ task.name }}</strong>
|
||||
(Priority: {{ task.priority }}, Duration: {{ format_duration(task.duration) }})
|
||||
{% if task.due_date %}
|
||||
- Due: {{ task.due_date }}
|
||||
{% endif %}
|
||||
- Completed At: {{ task.completed_at }}
|
||||
</div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Redirect to the selected sorting option
|
||||
function sortTasks() {
|
||||
const sortBy = document.getElementById('sort_by').value;
|
||||
window.location.href = `/completed_tasks?sort_by=${sortBy}`;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
110
templates/index.html
Normal file
110
templates/index.html
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Task Manager</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<h1>Task Manager</h1>
|
||||
|
||||
<!-- Sorting Options -->
|
||||
<div class="mb-3">
|
||||
<label for="sort_by" class="form-label">Sort By:</label>
|
||||
<select id="sort_by" class="form-select" onchange="sortTasks()">
|
||||
<option value="priority" {% if sort_by == 'priority' %}selected{% endif %}>Priority</option>
|
||||
<option value="due_date" {% if sort_by == 'due_date' %}selected{% endif %}>Due Date</option>
|
||||
<option value="duration" {% if sort_by == 'duration' %}selected{% endif %}>Duration</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Add Task Form -->
|
||||
<form method="POST" action="/add_task" class="mb-4">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<input type="text" name="name" class="form-control" placeholder="Task Name" required>
|
||||
</div>
|
||||
<div class="col">
|
||||
<select name="priority" class="form-control" required>
|
||||
<option value="A">A</option>
|
||||
<option value="B">B</option>
|
||||
<option value="C">C</option>
|
||||
<option value="D">D</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col">
|
||||
<input type="text" name="duration" class="form-control" placeholder="Duration (e.g., 10M or 2H)" required>
|
||||
</div>
|
||||
<div class="col">
|
||||
<input type="date" name="due_date" class="form-control" placeholder="Due Date (YYYY-MM-DD)">
|
||||
</div>
|
||||
<div class="col">
|
||||
<button type="submit" class="btn btn-primary">Add Task</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<a href="/completed_tasks" class="btn btn-secondary mb-3">View Completed Tasks</a>
|
||||
|
||||
<!-- Task List -->
|
||||
<h2>Tasks</h2>
|
||||
<ul id="task-list" class="list-group">
|
||||
{% for task in tasks %}
|
||||
<li class="list-group-item d-flex justify-content-between align-items-center" id="task-{{ task.id }}">
|
||||
<div>
|
||||
<strong>{{ task.name }}</strong>
|
||||
(Priority: {{ task.priority }}, Duration: {{ task.duration }} mins / {{ format_duration(task.duration) }})
|
||||
{% if task.due_date %}
|
||||
- Due: {{ task.due_date }}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if task.status == 'pending' %}
|
||||
<a href="/complete_task/{{ task.id }}" class="btn btn-success btn-sm">Complete</a>
|
||||
{% else %}
|
||||
<span class="badge bg-success">Completed</span>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
|
||||
<script>
|
||||
const socket = io();
|
||||
|
||||
// Handle task updates
|
||||
socket.on('task_update', (data) => {
|
||||
if (data.action === 'add') {
|
||||
const task = data.task;
|
||||
const taskList = document.getElementById('task-list');
|
||||
const li = document.createElement('li');
|
||||
li.className = 'list-group-item d-flex justify-content-between align-items-center';
|
||||
li.id = `task-${task.id}`;
|
||||
li.innerHTML = `
|
||||
<div>
|
||||
<strong>${task.name}</strong>
|
||||
(Priority: ${task.priority}, Duration: ${task.duration} mins)
|
||||
${task.due_date ? `- Due: ${task.due_date}` : ''}
|
||||
</div>
|
||||
<a href="/complete_task/${task.id}" class="btn btn-success btn-sm">Complete</a>
|
||||
`;
|
||||
taskList.appendChild(li);
|
||||
} else if (data.action === 'complete') {
|
||||
const taskId = data.task_id;
|
||||
const taskElement = document.getElementById(`task-${taskId}`);
|
||||
if (taskElement) {
|
||||
taskElement.innerHTML += '<span class="badge bg-success">Completed</span>';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Redirect to the selected sorting option
|
||||
function sortTasks() {
|
||||
const sortBy = document.getElementById('sort_by').value;
|
||||
window.location.href = `/?sort_by=${sortBy}`;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Add table
Add a link
Reference in a new issue