Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

My app.py: app.py from flask import Flask, request, jsonify, rendertemplate from…

  1. User

    My app.py:

    app.py

    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

    app = Flask(name) basedir = os.path.abspath(os.path.dirname(file)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db = SQLAlchemy(app) migrate = Migrate(app, db)

    #####################################################################* ARCHIVING TASKS ##################################################################### def archive_tasks(): with app.app_context(): # Check last archive date last_archived_date = ArchiveInfo.get_last_archive() today = date.today()

        # 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}")
        
    

    Configure logging

    logging.basicConfig(level=logging.INFO) logging.getLogger('apscheduler').setLevel(logging.DEBUG)

    Initialize the scheduler

    executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) }

    job_defaults = { 'coalesce': True, 'max_instances': 1 }

    scheduler = BackgroundScheduler(executors=executors, job_defaults=job_defaults) scheduler.add_job(archive_tasks, 'cron', hour=0, minute=0) # Runs at 12:00 AM

    Periodic job to check every 15 minutes if archiving was missed

    scheduler.add_job(archive_tasks, 'interval', minutes=15) scheduler.start()

    #####################################################################* DB CLASSES ##################################################################### class ArchiveInfo(db.Model): id = db.Column(db.Integer, primary_key=True) last_archive = db.Column(db.Date, nullable=False)

    @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)

    #####################################################################* BASE ROUTES ##################################################################### @app.route('/') def index(): return render_template('index.html')

    @app.route('/yearly-grid') def yearly_grid(): return render_template('yearly_grid.html')

    #####################################################################* API routes ##################################################################### ############################################## TASKS ############################################## @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})

    ############################################## HABITS ##############################################

    @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])

    @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

    ############################################## JOURNAL ############################################## @app.route('/api/journal', methods=['GET', 'POST']) def handle_journal(): if request.method == 'POST': data = request.json new_entry = JournalEntry( title=data['title'], content=data['content'], date=date.today(), ai_comment=data.get('ai_comment', '') ) db.session.add(new_entry) db.session.commit() return jsonify(id=new_entry.id, title=new_entry.title, content=new_entry.content, date=str(new_entry.date), ai_comment=new_entry.ai_comment) else: entries = JournalEntry.query.all() return jsonify([{ 'id': entry.id, 'title': entry.title, 'content': entry.content, 'date': str(entry.date), 'ai_comment': entry.ai_comment } for entry in entries])

    @app.route('/api/journal/int:entry_id', methods=['PUT', 'DELETE']) def update_journal(entry_id): entry = JournalEntry.query.get_or_404(entry_id) if request.method == 'PUT': data = request.json entry.title = data.get('title', entry.title) entry.content = data.get('content', entry.content) entry.ai_comment = data.get('ai_comment', entry.ai_comment) db.session.commit() return jsonify({'success': True}) elif request.method == 'DELETE': db.session.delete(entry) db.session.commit() return jsonify({'success': True})

    ############################################## HISTORY ##############################################

    @app.route('/api/history', methods=['GET']) def get_yearly_data(): habits = Habit.query.all() tasks = Task.query.filter(Task.completion_date.isnot(None)).all() journal_entries = JournalEntry.query.all()

    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)

    templates/index.html:

    <div id="content">
        <div id="habit-tracker" class="page">
            <div class="habit-tracker">
                <h2>Habit Tracker</h2>
                <div class="habits-container" id="habits"></div>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div class="column" id="to-do-week">
            <div class="column-header">
                <span class="column-title">To Do This Week</span>
                <span>...</span>
            </div>
        </div>
        <div class="column" id="to-do-today">
            <div class="column-header">
                <span class="column-title">To Do Today</span>
                <span>...</span>
            </div>
        </div>
        <div class="column" id="in-progress">
            <div class="column-header">
                <span class="column-title">In Progress</span>
                <span>...</span>
            </div>
        </div>
        <div class="column" id="finished">
            <div class="column-header">
                <span class="column-title">Finished</span>
                <span>...</span>
            </div>
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script src="{{ url_for('static', filename='js/common.js') }}"></script>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
    

    templates/yearly_grid.html:

        <!-- Your custom CSS -->
        <link rel="stylesheet" href="{{ url_for('static', filename='common.css') }}">
        <link rel="stylesheet" href="{{ url_for('static', filename='yearly_grid.css') }}">
        <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    
    </head>
    
    <script src="{{ url_for('static', filename='js/common.js') }}"></script>
    

    static/js/script.js: const columnOrder = ['to-do-week', 'to-do-today', 'in-progress', 'finished'];

    function createTaskElement(task) { const taskElement = document.createElement('div'); taskElement.className = 'task-card'; taskElement.dataset.taskId = task.id;

    taskElement.innerHTML = <div class="task-title" contenteditable="true" onblur="updateTaskTitle(${task.id}, this)">${task.title}</div> <div class="task-buttons"> ${getButtonsForTask(task)} </div> ; return taskElement; }

    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) {
          // Update task order in the client-side state here
          // Optionally, save to localStorage or send to the server when appropriate
        },
      });
    });
    

    }

    function loadTasks() { axios.get('/api/tasks') .then(response => { const tasks = response.data;

        // Clear columns
        columnOrder.forEach(status => {
          const column = document.getElementById(status);
          column.innerHTML = `
            <div class="column-header">
              <span class="column-title">${column.id.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')}</span>
              <span>...</span>
            </div>
          `;
        });
    
        tasks.forEach(task => {
          const columnElement = document.getElementById(task.status);
          if (!columnElement) return;
    
          const taskElement = createTaskElement(task);
          columnElement.appendChild(taskElement);
        });
    
        // Add "Add a card" buttons to columns
        columnOrder.forEach(status => {
          const column = document.getElementById(status);
          const addCard = document.createElement('div');
          addCard.className = 'add-card';
          addCard.textContent = '+ Add a card';
          addCard.onclick = () => addTask(status);
          column.appendChild(addCard);
        });
    
        // Initialize Sortable
        initializeSortable();
      })
      .catch(error => {
        console.error('Error loading tasks:', error);
      });
    

    }

    function getButtonsForTask(task) { switch (task.status) { case 'to-do-week': return <button class="task-button" onclick="moveTask(${task.id}, 'to-do-today')">→ Today</button>; case 'to-do-today': return <button class="task-button" onclick="moveTask(${task.id}, 'in-progress')">▶ IP</button> <button class="task-button" onclick="moveTask(${task.id}, 'finished')">✓</button> ; case 'in-progress': return <button class="task-button" onclick="moveTask(${task.id}, 'to-do-week')">↺ Week</button> <button class="task-button" onclick="moveTask(${task.id}, 'to-do-today')">↺ Today</button> <button class="task-button" onclick="moveTask(${task.id}, 'finished')">✓</button> ; case 'finished': return <button class="task-button" onclick="moveTask(${task.id}, 'to-do-week')">↺ Week</button> <button class="task-button" onclick="moveTask(${task.id}, 'to-do-today')">↺ Today</button> ; default: return ''; } }

    function addTask(status) { const column = document.getElementById(status);

    // 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 moveTask(taskId, newStatus) { axios.put(/api/tasks/${taskId}, { status: newStatus }) .then(() => loadTasks()); }

    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 loadHabits() { axios.get('/api/habits') .then(response => { const habits = response.data; const habitsContainer = document.getElementById('habits'); habitsContainer.innerHTML = ''; const today = new Date(); habits.forEach(habit => { const habitElement = document.createElement('div'); const today = new Date().toISOString().split('T')[0]; const isAvailableToday = habit.days.includes(today.getDay().toString()); const isCompletedToday = habit.dates.some(date => new Date(date).toDateString() === today.toDateString() ); habitElement.className = habit ${isAvailableToday ? 'habit-available' : 'habit-unavailable'} ${isCompletedToday ? 'habit-complete' : 'habit-incomplete'}; habitElement.textContent = habit.name; //if (isAvailableToday) { habitElement.onclick = () => toggleHabit(habit.id); //} habitsContainer.appendChild(habitElement); }); }); }

    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(); }); } }

    function toggleHabit(habitId) { const today = new Date().toISOString().split('T')[0]; axios.put(/api/habits/${habitId}, { toggle_date: today }) .then(response => { if (response.data.success) { console.log(Habit ${habitId} toggled successfully); loadHabits(); } else { console.error(Failed to toggle habit ${habitId}); } }) .catch(error => { console.error('Error toggling habit:', error.response ? error.response.data : error.message); }); }

    document.addEventListener('DOMContentLoaded', function () { // Load tasks and habits on page load loadTasks(); loadHabits(); });

    static/js/common.js: document.addEventListener('DOMContentLoaded', function () {

    // Handle menu toggle
    const menuState = localStorage.getItem('menuState');
    if (menuState === 'open') {
        document.body.classList.add('menu-active');
    }
    
    // Handle menu toggle
    const menuToggle = document.getElementById('menu-toggle');
    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            document.body.classList.toggle('menu-active');
    
            // Save the new state to localStorage
            if (document.body.classList.contains('menu-active')) {
                localStorage.setItem('menuState', 'open');
            } else {
                localStorage.setItem('menuState', 'closed');
            }
        });
    }
    
    // Add any other common initialization code here
    

    });

    static/styles.css: body { font-family: Arial, sans-serif; background-color: #46474a; margin: 0; padding: 20px; } .container { display: flex; justify-content: space-between; gap: 20px; align-items: flex-start; /* Align columns at the top, not stretched */ }

    .column { width: 23%; background-color: #d0d4d9; /* Slightly darker than the add a card box */ border-radius: 8px; padding: 10px; } .column-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } .column-title { font-weight: bold; font-size: 14px; color: #172b4d; } .task-input { width: 100%; padding: 8px; font-size: 14px; border: 1px solid #ccc; border-radius: 3px; margin-bottom: 8px; } .task-card { border-radius: 3px; box-shadow: 0 1px 0 rgba(9,30,66,.25); padding: 10px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; position: relative; } .task-card:hover { filter: brightness(95%); }

    .task-card.dragging { opacity: 0.5; cursor: move; }

    .task-card.placeholder { background-color: #e0e0e0; border: 2px dashed #999; }

    #to-do-week .task-card, #to-do-today .task-card { background-color: #c22f2f; } #in-progress .task-card { background-color: #ffff99; } #finished .task-card { background-color: #99ff99; } .task-title { font-size: 14px; color: #172b4d; flex-grow: 1; margin-right: 10px; } .task-buttons { display: none; } .task-card:hover .task-buttons { display: flex; gap: 5px; } .task-button { background-color: #ffffff; border: none; border-radius: 3px; padding: 3px 6px; cursor: pointer; font-size: 12px; } .task-button:hover { background-color: #f4f5f7; } .add-card { color: #5e6c84; font-size: 14px; cursor: pointer; background-color: #ebecf0; padding: 5px; } .add-card:hover { background-color: rgba(9,30,66,.08); border-radius: 3px; } .habit-tracker { margin-top: 20px; align-items: center; text-align: center; } .habits-container { display: flex; gap: 10px; margin-top: 10px; white-space: nowrap; overflow-x: scroll; align-items: center; justify-content: center; } .habit { width: 300px; height: 300px; border-radius: 50%; display: flex; justify-content: center; align-items: center; cursor: pointer; font-size: 12px; text-align: center; word-wrap: break-word; flex-shrink: 0; } .habit-incomplete { background-color: #ffff99; } .habit-complete { background-color: #99ff99; }

    .slide-menu button { padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }

    .slide-menu button:hover { background-color: #45a049; }

    /* Modal styles / .modal { display: none; / Hidden by default / position: fixed; / Stay in place / z-index: 1; / Sit on top / left: 0; top: 0; width: 100%; / Full width / height: 100%; / Full height / overflow: auto; / Enable scroll if needed / background-color: rgba(0,0,0,0.4); / Black w/ opacity */ }

    .modal-content { background-color: #fefefe; margin: 15% auto; /* Centered / padding: 20px; border: 1px solid #888; width: 80%; / Could be more or less, depending on screen size */ }

    .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; }

    .close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }

    I want to add to my index.html habit tracker. Specifically, I want to be able to add habits to particular days of the week (all, some, or one), instead of having a habit show up every single day of the week by default. I also want to my my habit css prettier

  2. Assistant

    To achieve your goal of adding habits to particular days of the week and making your habit CSS prettier, we'll need to make several modifications to your code. Below, I'll guide you step-by-step on how to implement these features.


    1. Modify the Habit Creation Interface to Include Day Selection

    Update index.html

    First, we'll enhance the habit creation section to allow users to select the days of the week for each habit using checkboxes.

    Replace your existing habit input and button in index.html with the following code:

    <!-- In your slide-menu within index.html -->
    <nav id="slide-menu">
        <ul>
            <li><a href="/">Habit Tracker</a></li>
            <li><a href="/yearly-grid">Yearly Grid</a></li>
            <li>
                <input type="text" id="new-habit" placeholder="New habit">
                <div id="day-select">
                    <label><input type="checkbox" value="0"> Sun</label>
                    <label><input type="checkbox" value="1"> Mon</label>
                    <label><input type="checkbox" value="2"> Tue</label>
                    <label><input type="checkbox" value="3"> Wed</label>
                    <label><input type="checkbox" value="4"> Thu</label>
                    <label><input type="checkbox" value="5"> Fri</label>
                    <label><input type="checkbox" value="6"> Sat</label>
                </div>
                <button onclick="addHabit()">Add Habit</button>
            </li>
        </ul>
    </nav>
    

    This adds checkboxes for each day of the week, allowing users to select specific days when adding a habit.

    Update script.js

    Next, modify your addHabit() function in static/js/script.js to collect the selected days and send them to the backend:

    function addHabit() {
        const name = document.getElementById('new-habit').value;
        const dayCheckboxes = document.querySelectorAll('#day-select input[type="checkbox"]:checked');
        const days = Array.from(dayCheckboxes).map(cb => cb.value);
        if (name) {
            axios.post('/api/habits', { name, days })
                .then(() => {
                    document.getElementById('new-habit').value = '';
                    // Clear checkboxes
                    document.querySelectorAll('#day-select input[type="checkbox"]').forEach(cb => cb.checked = false);
                    loadHabits();
                });
        }
    }
    

    2. Update the Backend to Handle Selected Days

    Modify Habit Model in app.py

    Ensure your Habit model can store the selected days:

    class Habit(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(100), nullable=False)
        days = db.Column(db.String(100))  # Store as comma-separated string
        dates = db.relationship('HabitDate', backref='habit', lazy=True)
    

    Update /api/habits Route in app.py

    Modify the GET and POST methods to handle the days field properly:

    @app.route('/api/habits', methods=['GET', 'POST'])
    def handle_habits():
        if request.method == 'POST':
            data = request.json
            new_habit = Habit(name=data['name'], days=','.join(map(str, 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_data = []
            for habit in Habit.query.all():
                habit_data = {
                    'id': habit.id,
                    'name': habit.name,
                    'days': habit.days.split(',') if habit.days else [],
                    'dates': [str(hd.date) for hd in habit.dates]
                }
                habits_data.append(habit_data)
            return jsonify(habits_data)
    

    This ensures that when habits are fetched, the days and dates are included in the response as lists.


    3. Display Habits Only on Their Specified Days

    Update loadHabits() Function in script.js

    Modify the loadHabits() function to only display habits that are scheduled for the current day:

    function loadHabits() {
        axios.get('/api/habits')
            .then(response => {
                const habits = response.data;
                const habitsContainer = document.getElementById('habits');
                habitsContainer.innerHTML = '';
                const today = new Date();
                const todayWeekday = today.getDay().toString(); // '0' (Sunday) to '6' (Saturday)
    
                habits.forEach(habit => {
                    // Check if the habit is scheduled for today
                    const isAvailableToday = habit.days.includes(todayWeekday);
                    if (!isAvailableToday) {
                        // Skip habits not scheduled for today
                        return;
                    }
    
                    const habitElement = document.createElement('div');
    
                    const isCompletedToday = habit.dates.some(date => 
                        new Date(date).toDateString() === today.toDateString()
                    );
                    habitElement.className = `habit ${isCompletedToday ? 'habit-complete' : 'habit-incomplete'}`;
                    habitElement.textContent = habit.name;
                    habitElement.onclick = () => toggleHabit(habit.id);
                    habitsContainer.appendChild(habitElement);
                });
            });
    }
    

    This function now:

    • Filters out the habits not scheduled for the current day.
    • Displays only the habits that are available today.
    • Adds the click event handler to toggle the habit's completion status.

    4. Enhance the Habit CSS

    To make your habit CSS prettier, let's style the habits as cards with a modern look.

    Update CSS in styles.css

    Replace your existing habit styles with the following:

    .habits-container {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-top: 20px;
        justify-content: center;
    }
    
    .habit {
        background-color: #fff;
        border-radius: 8px;
        width: 150px;
        height: 100px;
        box-shadow: 0px 3px 6px rgba(0,0,0,0.16);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        position: relative;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }
    
    .habit:hover {
        transform: translateY(-5px);
        box-shadow: 0px 6px 12px rgba(0,0,0,0.2);
    }
    
    .habit-incomplete {
        background-color: #f9f9f9;
    }
    
    .habit-complete {
        background-color: #d4edda;
    }
    
    .habit::after {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 50%;
        transform: translateX(-50%);
        border-top: 10px solid #fff;
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
    }
    
    .habit h3 {
        margin: 0;
        font-size: 16px;
        text-align: center;
        color: #333;
    }
    
    .habit p {
        margin: 5px 0 0 0;
        font-size: 12px;
        color: #666;
    }
    

    This CSS:

    • Styles the habits as cards with shadows and hover effects.
    • Uses transitions for smooth animations.
    • Differentiates between completed and incomplete habits with background colors.

    Optional HTML Structure for Habits

    If you'd like to include more details within each habit card, such as the days it's scheduled, you can adjust the inner HTML when creating the habit element in loadHabits():

    habitElement.innerHTML = `
        <h3>${habit.name}</h3>
        <p>${formatDays(habit.days)}</p>
    `;
    

    And add the formatDays() function:

    function formatDays(days) {
        const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        return days.map(day => dayNames[parseInt(day)]).join(', ');
    }
    

    5. Full Updated script.js for Reference

    Here's the complete updated script.js for clarity:

    function addHabit() {
        const name = document.getElementById('new-habit').value;
        const dayCheckboxes = document.querySelectorAll('#day-select input[type="checkbox"]:checked');
        const days = Array.from(dayCheckboxes).map(cb => cb.value);
        if (name) {
            axios.post('/api/habits', { name, days })
                .then(() => {
                    document.getElementById('new-habit').value = '';
                    // Clear checkboxes
                    document.querySelectorAll('#day-select input[type="checkbox"]').forEach(cb => cb.checked = false);
                    loadHabits();
                });
        }
    }
    
    function loadHabits() {
        axios.get('/api/habits')
            .then(response => {
                const habits = response.data;
                const habitsContainer = document.getElementById('habits');
                habitsContainer.innerHTML = '';
                const today = new Date();
                const todayWeekday = today.getDay().toString(); // '0' (Sunday) to '6' (Saturday)
    
                habits.forEach(habit => {
                    // Check if the habit is scheduled for today
                    const isAvailableToday = habit.days.includes(todayWeekday);
                    if (!isAvailableToday) {
                        // Skip habits not scheduled for today
                        return;
                    }
    
                    const habitElement = document.createElement('div');
    
                    const isCompletedToday = habit.dates.some(date => 
                        new Date(date).toDateString() === today.toDateString()
                    );
                    habitElement.className = `habit ${isCompletedToday ? 'habit-complete' : 'habit-incomplete'}`;
                    habitElement.innerHTML = `<h3>${habit.name}</h3>`;
                    habitElement.onclick = () => toggleHabit(habit.id);
                    habitsContainer.appendChild(habitElement);
                });
            });
    }
    
    function toggleHabit(habitId) {
        const today = new Date().toISOString().split('T')[0];
        axios.put(`/api/habits/${habitId}`, { toggle_date: today })
            .then(response => {
                if (response.data.success) {
                    loadHabits();
                } else {
                    console.error(`Failed to toggle habit ${habitId}`);
                }
            })
            .catch(error => {
                console.error('Error toggling habit:', error.response ? error.response.data : error.message);
            });
    }
    
    document.addEventListener('DOMContentLoaded', function () {
        // Load tasks and habits on page load
        loadTasks();
        loadHabits();
    });
    

    6. Final Notes

    • Ensure all files are saved with the changes.
    • Restart your Flask app to reflect the backend changes.
    • Clear your browser cache or do a hard refresh to see the frontend updates.

    By following these steps, you should now have a habit tracker where habits can be assigned to specific days of the week, and the habits will only appear on those days. Additionally, the updated CSS should provide a nicer appearance for your habits.

    Feel free to further customize the CSS to match your preferred aesthetic. Happy coding!