from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from datetime import date
import os
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler
import logging
import requests
def archive_tasks():
with app.app_context():
# Check last archive date
last_archived_date = ArchiveInfo.get_last_archive()
today = date.today()
code
# If the last archive was not today, archive and update the record
if last_archived_date is None or last_archived_date != today:
# Perform the archive
tasks = Task.query.filter(Task.status == 'finished')
for task in tasks:
task.status = 'archived'
db.session.commit()
# Update the archive info in the database
ArchiveInfo.update_last_archive(today)
logging.info(f"Archived tasks for {today}")
class ArchiveInfo(db.Model):
id = db.Column(db.Integer, primary_key=True)
last_archive = db.Column(db.Date, nullable=False)
code
Assistant
@staticmethod
def get_last_archive():
archive_info = ArchiveInfo.query.first()
if archive_info:
return archive_info.last_archive
return None
@staticmethod
def update_last_archive(new_archive_date):
archive_info = ArchiveInfo.query.first()
if not archive_info:
archive_info = ArchiveInfo(last_archive=new_archive_date)
db.session.add(archive_info)
else:
archive_info.last_archive = new_archive_date
db.session.commit()
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
status = db.Column(db.String(20), nullable=False)
completion_date = db.Column(db.Date)
column = db.Column(db.String(20), default='To Do')
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'status': self.status,
'completion_date': self.completion_date.isoformat() if self.completion_date else None,
'column': self.column
}
class Habit(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
#days that the habit is available
days = db.Column(db.String(100)) # Store as comma-separated string
#list of completed dates
dates = db.relationship('HabitDate', backref='habit', lazy=True)
class HabitDate(db.Model):
id = db.Column(db.Integer, primary_key=True)
habit_id = db.Column(db.Integer, db.ForeignKey('habit.id'), nullable=False)
date = db.Column(db.Date, nullable=False)
class JournalEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
date = db.Column(db.Date, nullable=False)
ai_comment = db.Column(db.Text)
@app.route('/api/tasks', methods=['GET', 'POST'])
def handle_tasks():
'''
POST request: Creates a new task in the database and returns its details.
GET request: Retrieves and returns all tasks from the database as a list in JSON format.
'''
if request.method == 'POST':
data = request.json
new_task = Task(
title=data['title'],
status=data['status'],
column=data.get('column', 'To Do')
)
db.session.add(new_task)
db.session.commit()
return jsonify(id=new_task.id, title=new_task.title, status=new_task.status, column=new_task.column)
else:
tasks = Task.query.all()
return jsonify([{
'id': task.id,
'title': task.title,
'status': task.status,
'completion_date': str(task.completion_date) if task.completion_date else None,
'column': task.column
} for task in tasks])
@app.route('/api/tasks/int:task_id', methods=['PUT', 'DELETE'])
def update_task(task_id):
task = Task.query.get_or_404(task_id)
if request.method == 'PUT':
data = request.json
if 'title' in data and not data['title'].strip():
# If the title is empty, delete the task
db.session.delete(task)
db.session.commit()
return jsonify({'success': True, 'deleted': True})
else:
task.title = data.get('title', task.title)
task.status = data.get('status', task.status)
task.column = data.get('column', task.column)
if data.get('status') == 'finished':
task.completion_date = date.today()
else:
task.completion_date = None
db.session.commit()
return jsonify({'success': True, 'deleted': False})
elif request.method == 'DELETE':
db.session.delete(task)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/tasks/archive', methods=["POST"])
def archive_completed_tasks():
tasks = Task.query.filter(Task.status == 'finished')
for task in tasks:
task.status = 'archived'
db.session.commit()
return jsonify({'success': True})
@app.route('/api/habits', methods=['GET', 'POST'])
def handle_habits():
'''
POST request: Creates a new habit in db and returns related JSON
GET request: Returns a JSON of all habits and related fields
'''
if request.method == 'POST':
data = request.json
new_habit = Habit(name=data['name'], days=','.join(data.get('days', [])))
db.session.add(new_habit)
db.session.commit()
return jsonify(id=new_habit.id, name=new_habit.name, days=new_habit.days.split(','))
else:
habits = Habit.query.all()
return jsonify([{
'id': habit.id,
'name': habit.name,
'days': habit.days.split(',') if habit.days else []
} for habit in habits])
if not task_id or new_order is None:
return jsonify({'success': False, 'error': 'Missing taskId or newOrder'}), 400
try:
task = Task.query.get(task_id)
if task:
if new_status and new_status != task.status:
# If the status has changed, move the task to the end of the new status
max_order = db.session.query(db.func.max(Task.order)).filter(Task.status == new_status).scalar() or 0
task.order = max_order + 1
task.status = new_status
else:
# Otherwise, just update the order
task.order = new_order
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/habits/int:habit_id', methods=['PUT', 'DELETE'])
def update_habit(habit_id):
'''
PUT request: Change Habit name and days
DELETE request: Delete the habit
'''
try:
habit = Habit.query.get_or_404(habit_id)
if request.method == 'PUT':
data = request.json
if 'name' in data:
habit.name = data['name']
if 'days' in data:
habit.days = ','.join(map(str, data['days']))
if 'toggle_date' in data:
toggle_date = date.fromisoformat(data['toggle_date'])
existing_date = HabitDate.query.filter_by(habit_id=habit.id, date=toggle_date).first()
if existing_date:
db.session.delete(existing_date)
else:
new_date = HabitDate(habit_id=habit.id, date=toggle_date)
db.session.add(new_date)
db.session.commit()
return jsonify({'success': True})
elif request.method == 'DELETE':
db.session.delete(habit)
db.session.commit()
return jsonify({'success': True})
except Exception as e:
app.logger.error(f"An error occurred while updating habit {habit_id}: {str(e)}")
return jsonify({'success': False, 'error': str(e)}), 500
yearly_data = {}
for habit in habits:
habit_dates = HabitDate.query.filter_by(habit_id=habit.id).all()
for habit_date in habit_dates:
date_str = str(habit_date.date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["completedHabits"].append(habit.name)
for task in tasks:
date_str = str(task.completion_date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["completedTasks"].append(task.title)
for entry in journal_entries:
date_str = str(entry.date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["journalEntries"].append(entry.title)
for date_str, data in yearly_data.items():
total_habits = len(habits)
completed_habits = len(data["completedHabits"])
data["completionRate"] = completed_habits / total_habits if total_habits > 0 else 0
# Return the data with date strings as keys
return jsonify(yearly_data)
if name == 'main':
with app.app_context():
db.create_all()
app.run(debug=True)
function addTask(status) {
const column = document.getElementById(status);
code
// Hide the "Add a card" button
const addCardButton = column.querySelector('.add-card');
addCardButton.style.display = 'none';
// Create a new task card div
const newCard = document.createElement('div');
newCard.classList.add('task-card');
newCard.contentEditable = 'true'; // Make the new card editable
// Add event listener to handle saving when 'Enter' is pressed
newCard.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // Prevent new lines when pressing Enter
const taskTitle = newCard.textContent.trim();
if (taskTitle) {
// Send task title and status to the backend
axios.post('/api/tasks', { title: taskTitle, status })
.then(() => {
loadTasks(); // Reload tasks after adding new one
addCardButton.style.display = 'block'; // Show "Add a card" button again
});
} else {
// Remove the card if no text was entered
newCard.remove();
addCardButton.style.display = 'block'; // Show "Add a card" button again
}
}
});
// Add event listener for "Escape" key to discard the card
newCard.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
newCard.remove(); // Discard the new card
addCardButton.style.display = 'block'; // Show "Add a card" button again
}
});
// Append the new card to the column
column.appendChild(newCard);
// Focus on the new card to allow typing immediately
newCard.focus();
function updateTaskTitle(taskId, element) {
const newTitle = element.textContent.trim();
axios.put(/api/tasks/${taskId}, { title: newTitle })
.then((response) => {
if (response.data.deleted) {
// If the task was deleted (empty title), remove it from the UI
element.closest('.task-card').remove();
} else {
// If the task was updated, reload tasks to reflect any changes
loadTasks();
}
})
.catch((error) => {
console.error('Error updating task:', error);
loadTasks(); // Reload tasks to ensure UI is in sync with server
});
}
function addHabit() {
const name = document.getElementById('new-habit').value;
const days = []; // You might want to add a way for users to select days
if (name) {
axios.post('/api/habits', { name, days })
.then(() => {
document.getElementById('new-habit').value = '';
loadHabits();
});
}
}
// Load tasks and habits on page load
loadTasks();
loadHabits();
Trello's To Do Today column that I am trying to emulate:
I want to make be able to reorder my tasks without making a call to my app.py, but I'm wondering if trello has a simpler way of doing it in their html style. Is there a better way to stylize my index.html to retain all my features, including adding tasks to a particular column and editing after adding a task, while being able to reorder my tasks?
To enable reordering tasks within columns without making server calls and while retaining all your features, you can simplify your frontend code by leveraging a JavaScript library like Sortable.js. This library makes it easy to implement drag-and-drop functionality, allowing you to manage the task order entirely on the client side.
Here's how you can implement this:
1. Include Sortable.js in Your Project
Add Sortable.js to your project by including it in your index.html:
Modify your script.js to initialize Sortable on each of your task columns:
javascript
function initializeSortable() {
columnOrder.forEach(columnId => {
const columnElement = document.getElementById(columnId);
Sortable.create(columnElement, {
group: 'columns', // Enable moving items between columns
animation: 150,
handle: '.task-card',
draggable: '.task-card',
onEnd: function (evt) {
// You can update your task order in the client-side state here
// Optionally, save the order to localStorage or send to the server when appropriate
},
});
});
}
3. Adjust Your loadTasks Function
Modify your loadTasks function to set up the tasks and initialize Sortable:
Since Sortable.js handles drag-and-drop events, you can remove the custom event handlers (handleDragStart, handleDragOver, etc.) from your script.js.
5. Manage Task Order on the Client Side
When tasks are reordered, you can update the order in a client-side data structure (like an array or object). If you want to persist the order, you can send the updated order to the server when appropriate (e.g., when the user logs out or clicks a "Save" button).
javascript
let tasksData = []; // Global variable to store tasks
function initializeSortable() {
columnOrder.forEach(columnId => {
const columnElement = document.getElementById(columnId);
Sortable.create(columnElement, {
group: 'columns',
animation: 150,
handle: '.task-card',
draggable: '.task-card',
onEnd: function (evt) {
const itemEl = evt.item; // dragged HTMLElement
const fromColumn = evt.from.id;
const toColumn = evt.to.id;
const taskId = itemEl.dataset.taskId;
// Update task's status in tasksData
const task = tasksData.find(t => t.id == taskId);
if (task) {
task.status = toColumn;
}
// Optionally, save tasksData to localStorage or send to server
},
});
});
}
6. Retain Features Like Adding and Editing Tasks
Your existing functions for adding and editing tasks can remain largely the same. Since we're managing the task order on the client side, these features will continue to work as expected.
7. Optional: Persist Task Order to the Server
If you eventually want to save the task order, you can batch updates and send them to the server when appropriate:
If you decide to persist the task order to the server, ensure your backend API can handle the batch update. Modify your /api/tasks/order endpoint in app.py to process the updated task statuses.
By using Sortable.js, you streamline your frontend code, reduce complexity, and improve performance by avoiding unnecessary server calls during drag-and-drop operations. This approach aligns with how Trello and similar applications handle client-side interactions, providing a smoother user experience.
Key Benefits:
Simplified Code: Let Sortable.js handle the complexities of drag-and-drop.
Improved Performance: Reduces server load by handling reordering on the client side.
Enhanced User Experience: Provides immediate visual feedback without waiting for server responses.
Flexibility: Allows you to decide when to persist changes to the server.
Remember: While client-side reordering improves performance and responsiveness, you'll need a strategy to persist changes if users expect their task order to be saved across sessions or devices. You can achieve this by:
Saving to Local Storage: For single-device persistence.
Batch Server Updates: Send updates at intervals or on specific events (e.g., user logs out).
Additional Tips:
Consistent IDs: Ensure your tasks have consistent IDs to track them accurately.
Error Handling: Implement error handling for cases where the server is unavailable when saving.
Feedback to Users: Provide visual cues or notifications when changes are saved or if an error occurs.
By adopting this approach, you'll create a more efficient and user-friendly application while retaining all your existing features. This method allows you to focus on building the core functionality without getting bogged down by intricate drag-and-drop implementations.