diff --git a/routes/timer.py b/routes/timer.py index 3199e96..62f45ff 100644 --- a/routes/timer.py +++ b/routes/timer.py @@ -1,17 +1,356 @@ -from flask import Blueprint, render_template, redirect, url_for, flash +from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify from jinja2_fragments import render_block from werkzeug.security import generate_password_hash, check_password_hash -from flask_login import login_user, login_required, logout_user +from flask_login import current_user, login_required from extensions import db, htmx, environment +from datetime import datetime, timezone, timedelta +import json + +''' +CREATE TABLE timer_functions ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + code TEXT NOT NULL, + environment JSONB NOT NULL DEFAULT '{}'::jsonb, + version_number INT NOT NULL DEFAULT 1, + + user_id INT NOT NULL, -- the referencing column + + trigger_type VARCHAR(20) NOT NULL CHECK ( + trigger_type IN ('interval', 'date') + ), + frequency_minutes INT, -- used if trigger_type = 'interval' + run_date TIMESTAMPTZ, -- used if trigger_type = 'date' (one-off) + + next_run TIMESTAMPTZ, + last_run TIMESTAMPTZ, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + + -- Define the foreign key constraint + CONSTRAINT fk_timer_functions_user + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE CASCADE + ON UPDATE CASCADE +); + +CREATE TABLE timer_function_versions ( + id SERIAL PRIMARY KEY, + timer_function_id INT NOT NULL, + script TEXT NOT NULL, + version_number INT NOT NULL, + versioned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT fk_timer_function_versions + FOREIGN KEY (timer_function_id) + REFERENCES timer_functions (id) + ON DELETE CASCADE + ON UPDATE CASCADE +); + +CREATE OR REPLACE FUNCTION fn_timer_functions_versioning() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + next_version INT; +BEGIN + IF TG_OP = 'INSERT' THEN + -- In an AFTER INSERT, the row already has been inserted with version_number default (1). + -- We can optionally override that or ensure an initial version is recorded: + INSERT INTO timer_function_versions (timer_function_id, script, version_number) + VALUES (NEW.id, NEW.code, 1); + + -- If desired, ensure timer_functions.version_number is set explicitly: + UPDATE timer_functions + SET version_number = 1 + WHERE id = NEW.id; + + RETURN NEW; + + ELSIF TG_OP = 'UPDATE' THEN + -- Only version if the 'code' changed + IF NEW.code IS DISTINCT FROM OLD.code THEN + -- Determine the next version number based on existing versions + SELECT COALESCE(MAX(version_number), 0) + 1 + INTO next_version + FROM timer_function_versions + WHERE timer_function_id = NEW.id; + + -- Insert new version record + INSERT INTO timer_function_versions (timer_function_id, script, version_number) + VALUES (NEW.id, NEW.code, next_version); + + -- Manually update timer_functions to set version_number + -- This second UPDATE will cause the trigger to fire again, + -- but because code won't change, the trigger won't do another version bump. + UPDATE timer_functions + SET version_number = next_version + WHERE id = NEW.id; + END IF; + + RETURN NEW; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER tr_timer_functions_versioning +AFTER INSERT OR UPDATE +ON timer_functions +FOR EACH ROW +EXECUTE PROCEDURE fn_timer_functions_versioning(); +''' + +DEFAULT_SCRIPT = """async (req) => { + environment.count += 1 + console.log(`Executing ${environment.count}`) +}""" + +DEFAULT_ENVIRONMENT = """{ + "count": 0 +}""" timer = Blueprint('timer', __name__) @timer.route('/overview') @login_required def overview(): + timer_functions = db.execute(""" + SELECT id, name, code, environment, trigger_type, + frequency_minutes, run_date, next_run, + last_run, enabled + FROM timer_functions + WHERE user_id = %s + ORDER BY id DESC + """, [current_user.id]) if htmx: - return render_block(environment, 'dashboard/timer_functions/overview.html', 'page') - return render_template('dashboard/timer_functions/overview.html') + return render_block(environment, 'dashboard/timer_functions/overview.html', 'page', timer_functions=timer_functions) + return render_template('dashboard/timer_functions/overview.html', timer_functions=timer_functions) + +@timer.route('/new', methods=['GET', 'POST']) +@login_required +def new(): + if request.method == 'GET': + args = { + 'name': 'foo', + 'script': DEFAULT_SCRIPT, + 'environment_info': DEFAULT_ENVIRONMENT, + 'user_id': current_user.id + } + if htmx: + return render_block(environment, 'dashboard/timer_functions/new.html', 'page', **args) + return render_template('dashboard/timer_functions/new.html', **args) + + # Handle POST request + try: + data = request.json + trigger_type = data.get('trigger_type') + + # Validate trigger type + if trigger_type not in ('interval', 'date'): + return jsonify({ + "status": "error", + "message": "Invalid trigger type" + }), 400 + + # Calculate next_run based on trigger type + next_run = None + if trigger_type == 'interval': + frequency_minutes = int(data.get('frequency_minutes')) + next_run = datetime.now(timezone.utc) + timedelta(minutes=frequency_minutes) + elif trigger_type == 'date': + run_date = datetime.fromisoformat(data.get('run_date')) + next_run = run_date + + # Insert new timer function + db.execute(""" + INSERT INTO timer_functions + (name, code, environment, user_id, trigger_type, + frequency_minutes, run_date, next_run, enabled) + VALUES (%s, %s, %s::jsonb, %s, %s, %s, %s, %s, %s) + RETURNING id + """, [ + data.get('name'), + data.get('script_content'), + data.get('environment_info'), + current_user.id, + trigger_type, + frequency_minutes if trigger_type == 'interval' else None, + run_date if trigger_type == 'date' else None, + next_run, + True + ], + commit=True) + + return jsonify({ + "status": "success", + "message": "Timer function created successfully" + }), 200 + + except Exception as e: + return jsonify({ + "status": "error", + "message": f"Error creating timer function: {str(e)}" + }), 400 + +@timer.route('/edit/', methods=['GET', 'POST']) +@login_required +def edit(function_id): + if request.method == 'GET': + # Fetch the timer function + timer_function = db.execute(""" + SELECT id, name, code, environment, version_number, trigger_type, + frequency_minutes, run_date, next_run, + last_run, enabled + FROM timer_functions + WHERE id = %s AND user_id = %s + """, [function_id, current_user.id], one=True) + + if not timer_function: + return jsonify({ + "status": "error", + "message": "Timer function not found" + }), 404 + + # Format the environment JSON with indentation + timer_function['environment'] = json.dumps(timer_function['environment'], indent=2) + + args = { + 'function_id': function_id, + 'timer_function': timer_function + } + + if htmx: + return render_block(environment, 'dashboard/timer_functions/edit.html', 'page', **args) + return render_template('dashboard/timer_functions/edit.html', **args) + + # Handle POST request + try: + data = request.json + trigger_type = data.get('trigger_type') + + # Validate trigger type + if trigger_type not in ('interval', 'date'): + return jsonify({ + "status": "error", + "message": "Invalid trigger type" + }), 400 + + # Calculate next_run based on trigger type + next_run = None + if trigger_type == 'interval': + frequency_minutes = int(data.get('frequency_minutes')) + next_run = datetime.now(timezone.utc) + timedelta(minutes=frequency_minutes) + elif trigger_type == 'date': + run_date = datetime.fromisoformat(data.get('run_date')) + next_run = run_date + + # Update timer function + db.execute(""" + UPDATE timer_functions + SET name = %s, + code = %s, + environment = %s::jsonb, + trigger_type = %s, + frequency_minutes = %s, + run_date = %s, + next_run = %s, + enabled = %s + WHERE id = %s AND user_id = %s + RETURNING id + """, [ + data.get('name'), + data.get('script_content'), + data.get('environment_info'), + trigger_type, + frequency_minutes if trigger_type == 'interval' else None, + run_date if trigger_type == 'date' else None, + next_run, + data.get('is_enabled', True), # Default to True if not provided + function_id, + current_user.id + ], + commit=True) + + return jsonify({ + "status": "success", + "message": "Timer function updated successfully" + }), 200 + + except Exception as e: + return jsonify({ + "status": "error", + "message": f"Error updating timer function: {str(e)}" + }), 400 + +@timer.route('/delete/', methods=['DELETE']) +@login_required +def delete(function_id): + try: + # Delete the timer function, but only if it belongs to the current user + result = db.execute(""" + DELETE FROM timer_functions + WHERE id = %s AND user_id = %s + RETURNING id + """, [function_id, current_user.id], commit=True) + + if not result: + return jsonify({ + "status": "error", + "message": "Timer function not found or unauthorized" + }), 404 + + return jsonify({ + "status": "success", + "message": "Timer function deleted successfully" + }), 200 + + except Exception as e: + return jsonify({ + "status": "error", + "message": f"Error deleting timer function: {str(e)}" + }), 400 + +@timer.route('/toggle/', methods=['POST']) +@login_required +def toggle(function_id): + try: + # Toggle the enabled status + result = db.execute(""" + UPDATE timer_functions + SET enabled = NOT enabled + WHERE id = %s AND user_id = %s + RETURNING enabled + """, [function_id, current_user.id], commit=True, one=True) + + if not result: + return jsonify({ + "status": "error", + "message": "Timer function not found or unauthorized" + }), 404 + + # Fetch updated timer functions for the overview template + timer_functions = db.execute(""" + SELECT id, name, code, environment, trigger_type, + frequency_minutes, run_date, next_run, + last_run, enabled + FROM timer_functions + WHERE user_id = %s + ORDER BY id DESC + """, [current_user.id]) + + if htmx: + return render_block(environment, 'dashboard/timer_functions/overview.html', 'page', + timer_functions=timer_functions) + return render_template('dashboard/timer_functions/overview.html', timer_functions=timer_functions) + + except Exception as e: + return jsonify({ + "status": "error", + "message": f"Error toggling timer function: {str(e)}" + }), 400 diff --git a/static/js/mithril/editor.js b/static/js/mithril/editor.js index 09a2872..da2f8ad 100644 --- a/static/js/mithril/editor.js +++ b/static/js/mithril/editor.js @@ -55,6 +55,20 @@ const Editor = { this.deleteUrl = vnode.attrs.deleteUrl; this.dashboardUrl = vnode.attrs.dashboardUrl; + + // New timer-specific props + this.isTimer = vnode.attrs.isTimer || false; + this.triggerType = vnode.attrs.triggerType || 'interval'; // 'interval' or 'date' + this.frequencyMinutes = vnode.attrs.frequencyMinutes || 60; + this.runDate = vnode.attrs.runDate || ''; + + // Show timer settings panel + this.showTimerSettings = vnode.attrs.showTimerSettings === true; // default false + + this.cancelUrl = vnode.attrs.cancelUrl || '/dashboard/http_functions'; + + // Add enabled property for timer functions + this.isEnabled = vnode.attrs.isEnabled !== false; // default true }, oncreate() { @@ -122,7 +136,7 @@ const Editor = { this.error = null; try { - const payload = { + let payload = { name: this.name, script_content: this.jsValue, environment_info: this.jsonValue, @@ -131,6 +145,21 @@ const Editor = { log_response: this.logResponse }; + // Create payload based on whether this is a timer function + payload = this.isTimer ? { + name: this.name, + script_content: this.jsValue, + environment_info: this.jsonValue, + trigger_type: this.triggerType, + frequency_minutes: this.triggerType === 'interval' ? parseInt(this.frequencyMinutes) : null, + run_date: this.triggerType === 'date' ? this.runDate : null, + is_enabled: this.isEnabled // Add enabled status to payload + } : { + name: this.name, + script_content: this.jsValue, + environment_info: this.jsonValue + }; + const response = await m.request({ method: 'POST', url: this.saveUrl, @@ -175,7 +204,7 @@ const Editor = { if (response.status === 'success') { Alert.show(response.message || 'Function deleted successfully!', 'success'); // Optionally redirect to a different page after deletion - window.location.href = '/dashboard/http_functions'; + window.location.href = this.cancelUrl; } else { Alert.show(response.message || 'Error deleting function', 'error'); this.error = new Error(response.message); @@ -476,21 +505,85 @@ const Editor = { ]) ]), - /* ───────────────────────────────────────────────────────────────── + // Timer settings panel (shown only if isTimer is true) + this.isTimer && this.showTimerSettings && m("div", { + class: "bg-gray-100 dark:bg-gray-800 p-4 border-b" + }, [ + m("div", { class: "flex flex-col space-y-4" }, [ + // Add Enabled toggle at the top + m("label", { + class: "flex items-center space-x-3 text-sm text-gray-600 dark:text-gray-300 cursor-pointer mb-4" + }, [ + m("div", { class: "relative" }, [ + m("input[type=checkbox]", { + class: "sr-only peer", + checked: this.isEnabled, + onchange: (e) => this.isEnabled = e.target.checked + }), + m("div", { + class: "w-11 h-6 bg-gray-200 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600" + }) + ]), + m("span", "Enabled") + ]), + + // Trigger Type Selection + m("div", { class: "flex flex-col space-y-2" }, [ + m("label", { class: "text-sm font-medium text-gray-700 dark:text-gray-300" }, + "Trigger Type" + ), + m("select", { + class: "bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2", + value: this.triggerType, + onchange: (e) => this.triggerType = e.target.value + }, [ + m("option", { value: "interval" }, "Interval"), + m("option", { value: "date" }, "Specific Date") + ]) + ]), + + // Interval Settings (shown only if triggerType is 'interval') + this.triggerType === 'interval' && m("div", { class: "flex flex-col space-y-2" }, [ + m("label", { class: "text-sm font-medium text-gray-700 dark:text-gray-300" }, + "Frequency (minutes)" + ), + m("input[type=number]", { + class: "bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2", + value: this.frequencyMinutes, + min: 1, + onchange: (e) => this.frequencyMinutes = e.target.value + }) + ]), + + // Date Settings (shown only if triggerType is 'date') + this.triggerType === 'date' && m("div", { class: "flex flex-col space-y-2" }, [ + m("label", { class: "text-sm font-medium text-gray-700 dark:text-gray-300" }, + "Run Date" + ), + m("input[type=datetime-local]", { + class: "bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2", + value: this.runDate, + onchange: (e) => this.runDate = e.target.value + }) + ]) + ]) + ]), + + /* ───────────────────────────────────────────────────────────────── ResponseView (child) if needed ─────────────────────────────────────────────────────────────────*/ - !this.executeLoading && - !this.error && - this.response && - m(ResponseView, { - response: this.response, - responseTime: this.responseTime, - responseSize: this.responseSize, - envEditorValue: this.jsonValue, - onClose: () => { - this.response = null; - }, - }), + !this.executeLoading && + !this.error && + this.response && + m(ResponseView, { + response: this.response, + responseTime: this.responseTime, + responseSize: this.responseSize, + envEditorValue: this.jsonValue, + onClose: () => { + this.response = null; + }, + }), ]); }, }; diff --git a/static/js/mithril/responseView.js b/static/js/mithril/responseView.js index 9646a2a..3c6b0f8 100644 --- a/static/js/mithril/responseView.js +++ b/static/js/mithril/responseView.js @@ -315,8 +315,8 @@ const ResponseView = { : ""), }, response.status === "SUCCESS" - ? m.trust(response.result.body) - : JSON.stringify(response.result) + ? m.trust(response?.result?.body) + : JSON.stringify(response?.result) ), ]), diff --git a/templates/dashboard/timer_functions/edit.html b/templates/dashboard/timer_functions/edit.html new file mode 100644 index 0000000..1181938 --- /dev/null +++ b/templates/dashboard/timer_functions/edit.html @@ -0,0 +1,42 @@ +{% extends 'dashboard.html' %} + +{% block page %} + +{{ render_partial('dashboard/http_functions/header.html', function_id=function_id, +active_tab='edit', +show_edit_form=True, +show_logs=True, +show_client=True, +show_history=True, +edit_url=url_for('timer.edit', function_id=function_id), +cancel_url=url_for('timer.overview')) }} + + +
+ +
+ + + +{% endblock %} \ No newline at end of file diff --git a/templates/dashboard/timer_functions/new.html b/templates/dashboard/timer_functions/new.html new file mode 100644 index 0000000..11df49d --- /dev/null +++ b/templates/dashboard/timer_functions/new.html @@ -0,0 +1,42 @@ +{% extends 'dashboard.html' %} + +{% block page %} + +{{ render_partial('dashboard/http_functions/header.html', +user_id=user_id, +show_name=False, +show_refresh=False, +show_logs=False, +show_client=False, +show_link=False, +dashboardUrl=url_for('timer.overview'), +title='New Timer Function') +}} + +
+ +
+ + + +{% endblock %} \ No newline at end of file diff --git a/templates/dashboard/timer_functions/overview.html b/templates/dashboard/timer_functions/overview.html index 5405cf3..2fc14c7 100644 --- a/templates/dashboard/timer_functions/overview.html +++ b/templates/dashboard/timer_functions/overview.html @@ -3,12 +3,11 @@ {% block page %}
-
+

Timer Functions

-
+
- - + + + + - {% for function in http_functions %} + {% for function in timer_functions %} - + + {% endfor %} - {% if http_functions|length == 0 %} + {% if timer_functions|length == 0 %} - {% endif %}
NameURL - ScheduleNext RunStatusActions
+ hx-get="{{ url_for('timer.edit', function_id=function.id) }}" hx-target="#container" + hx-swap="innerHTML" hx-push-url="true"> {{ function.name }} - - #{{ function.invoked_count }} - + {% if function.last_run %} - v{{ function.version_number }} - - {% if function.is_public %} - - - - + Last run: {{ function.last_run.strftime('%Y-%m-%d %H:%M') }} {% endif %}
- + {% if function.trigger_type == 'interval' %} + + + + + Every {{ function.frequency_minutes }} minutes + + {% else %} + + + + + {{ function.run_date.strftime('%Y-%m-%d %H:%M') }} + + {% endif %} + {% if function.next_run %} + {{ function.next_run.strftime('%Y-%m-%d %H:%M') }} + {% else %} + - + {% endif %} + + {% if function.enabled %} + + + + + Active + + {% else %} + + + + + Paused + + {% endif %} + +
+

No functions found

+

Click the "Add Function" button to create your first + function