Initial commit: supabase-scheduler
Web app per gestire query automatiche verso database Supabase multipli. Features: - Login con credenziali fisse - Dashboard CRUD per configurazioni database - Scheduler node-cron per esecuzioni automatiche - SQLite per persistenza dati - Log esecuzioni per ogni database Stack: Node.js + Express + SQLite Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
7
.env.example
Normal file
7
.env.example
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
# Supabase Scheduler Environment Variables
|
||||||
|
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# Session secret (genera una stringa casuale)
|
||||||
|
SESSION_SECRET=your-secret-key-here
|
||||||
17
.gitattributes
vendored
Normal file
17
.gitattributes
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Auto detect text files and perform LF normalization
|
||||||
|
* text=auto
|
||||||
|
|
||||||
|
# Force LF for shell scripts (important for Docker)
|
||||||
|
*.sh text eol=lf
|
||||||
|
Dockerfile text eol=lf
|
||||||
|
docker-compose.yml text eol=lf
|
||||||
|
|
||||||
|
# Force CRLF for Windows batch files
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.cmd text eol=crlf
|
||||||
|
|
||||||
|
# Binary files
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.gif binary
|
||||||
|
*.ico binary
|
||||||
28
.gitignore
vendored
Normal file
28
.gitignore
vendored
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# Database
|
||||||
|
data/*
|
||||||
|
!data/.gitkeep
|
||||||
|
*.db
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Build
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
62
README.md
Normal file
62
README.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# Supabase Scheduler
|
||||||
|
|
||||||
|
Web app per gestire query automatiche verso database Supabase multipli.
|
||||||
|
|
||||||
|
## Funzionalita
|
||||||
|
|
||||||
|
- Login con credenziali fisse
|
||||||
|
- Dashboard per gestire configurazioni database
|
||||||
|
- CRUD per multiple istanze Supabase
|
||||||
|
- Scheduler automatico con frequenza personalizzabile
|
||||||
|
- Log esecuzioni per ogni database
|
||||||
|
- Esecuzione manuale on-demand
|
||||||
|
|
||||||
|
## Configurazione Database
|
||||||
|
|
||||||
|
Per ogni database Supabase puoi configurare:
|
||||||
|
|
||||||
|
- **Nome**: Identificativo per la configurazione
|
||||||
|
- **Supabase URL**: URL del progetto (es. `https://xxx.supabase.co`)
|
||||||
|
- **Anon Key**: Chiave pubblica del progetto
|
||||||
|
- **Query**: Tabella o RPC da interrogare (es. `users?select=*`)
|
||||||
|
- **Frequenza**: Intervallo in minuti tra le esecuzioni
|
||||||
|
- **Attivo**: Toggle per abilitare/disabilitare lo scheduler
|
||||||
|
|
||||||
|
## Stack Tecnologico
|
||||||
|
|
||||||
|
- Node.js + Express
|
||||||
|
- SQLite (better-sqlite3) per persistenza
|
||||||
|
- node-cron per scheduling
|
||||||
|
- HTML/CSS/JS vanilla per frontend
|
||||||
|
|
||||||
|
## URL
|
||||||
|
|
||||||
|
- **Live**: https://lab.mlhub.it/supabase-scheduler/
|
||||||
|
- **Repository**: https://git.mlhub.it/Michele/supabase-scheduler
|
||||||
|
|
||||||
|
## Sviluppo Locale
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Installa dipendenze
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# Crea directory data
|
||||||
|
mkdir data
|
||||||
|
|
||||||
|
# Avvia in development
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy
|
||||||
|
|
||||||
|
Il deploy avviene automaticamente tramite Git push + script VPS.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Dopo modifiche
|
||||||
|
git add .
|
||||||
|
git commit -m "Update feature"
|
||||||
|
git push origin main
|
||||||
|
|
||||||
|
# Deploy su VPS
|
||||||
|
ssh mic@72.62.49.98 "cd /opt/lab-supabase-scheduler && ./deploy.sh"
|
||||||
|
```
|
||||||
2
data/.gitkeep
Normal file
2
data/.gitkeep
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# This file ensures the data directory exists in the repository
|
||||||
|
# The actual database files are gitignored
|
||||||
27
docker-compose.yml
Normal file
27
docker-compose.yml
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
networks:
|
||||||
|
proxy_net:
|
||||||
|
external: true
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: node:18-alpine
|
||||||
|
container_name: lab-supabase-scheduler-app
|
||||||
|
working_dir: /app
|
||||||
|
volumes:
|
||||||
|
- ./:/app
|
||||||
|
- /app/node_modules
|
||||||
|
- ./data:/app/data
|
||||||
|
networks:
|
||||||
|
- proxy_net
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- PORT=3000
|
||||||
|
command: sh -c "npm install && npm start"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 300M
|
||||||
|
cpus: '0.25'
|
||||||
|
restart: unless-stopped
|
||||||
24
package.json
Normal file
24
package.json
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "supabase-scheduler",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Web app per gestire query automatiche verso database Supabase multipli",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.js",
|
||||||
|
"dev": "nodemon server.js"
|
||||||
|
},
|
||||||
|
"keywords": ["supabase", "scheduler", "query", "automation"],
|
||||||
|
"author": "Michele",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.3.1",
|
||||||
|
"better-sqlite3": "^9.2.2",
|
||||||
|
"node-cron": "^3.0.3",
|
||||||
|
"express-session": "^1.17.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"nodemon": "^3.0.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
766
public/index.html
Normal file
766
public/index.html
Normal file
@@ -0,0 +1,766 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="it">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Supabase Scheduler</title>
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--primary: #3ecf8e;
|
||||||
|
--primary-dark: #24b47e;
|
||||||
|
--bg: #1c1c1c;
|
||||||
|
--bg-light: #2a2a2a;
|
||||||
|
--bg-lighter: #3a3a3a;
|
||||||
|
--text: #f0f0f0;
|
||||||
|
--text-muted: #888;
|
||||||
|
--error: #ef4444;
|
||||||
|
--success: #22c55e;
|
||||||
|
--warning: #eab308;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Login Page */
|
||||||
|
.login-container {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-box {
|
||||||
|
background: var(--bg-light);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 40px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-box h1 {
|
||||||
|
color: var(--primary);
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-size: 1.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-box p {
|
||||||
|
color: var(--text-muted);
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dashboard */
|
||||||
|
.dashboard { display: none; }
|
||||||
|
.dashboard.active { display: block; }
|
||||||
|
.login-container.hidden { display: none; }
|
||||||
|
|
||||||
|
.header {
|
||||||
|
background: var(--bg-light);
|
||||||
|
padding: 16px 24px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
border-bottom: 1px solid var(--bg-lighter);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 1.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-badge {
|
||||||
|
background: var(--success);
|
||||||
|
color: white;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 20px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Forms */
|
||||||
|
.form-group { margin-bottom: 20px; }
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: var(--text);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group textarea,
|
||||||
|
.form-group select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px;
|
||||||
|
background: var(--bg-lighter);
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group textarea { resize: vertical; min-height: 80px; }
|
||||||
|
|
||||||
|
.form-group small {
|
||||||
|
display: block;
|
||||||
|
margin-top: 4px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
padding: 12px 24px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--primary);
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover { background: var(--primary-dark); }
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg-lighter);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover { background: #444; }
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background: var(--error);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover { background: #dc2626; }
|
||||||
|
|
||||||
|
.btn-sm {
|
||||||
|
padding: 8px 16px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cards */
|
||||||
|
.card {
|
||||||
|
background: var(--bg-light);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 24px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header h2 { font-size: 1.3rem; }
|
||||||
|
|
||||||
|
/* Database List */
|
||||||
|
.db-list { display: grid; gap: 16px; }
|
||||||
|
|
||||||
|
.db-item {
|
||||||
|
background: var(--bg-lighter);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.db-info { flex: 1; }
|
||||||
|
|
||||||
|
.db-info h3 {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.db-info h3 .status-dot {
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.db-info h3 .status-dot.inactive { background: var(--text-muted); }
|
||||||
|
.db-info h3 .status-dot.error { background: var(--error); }
|
||||||
|
|
||||||
|
.db-meta {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.db-meta code {
|
||||||
|
background: var(--bg);
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.db-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal {
|
||||||
|
display: none;
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0,0,0,0.7);
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 20px;
|
||||||
|
z-index: 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal.active { display: flex; }
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-light);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 30px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 500px;
|
||||||
|
max-height: 90vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content h2 { margin-bottom: 20px; }
|
||||||
|
|
||||||
|
.modal-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Logs */
|
||||||
|
.logs-container {
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
background: var(--bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item {
|
||||||
|
padding: 8px 0;
|
||||||
|
border-bottom: 1px solid var(--bg-lighter);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item:last-child { border-bottom: none; }
|
||||||
|
|
||||||
|
.log-item .log-time { color: var(--text-muted); }
|
||||||
|
.log-item .log-success { color: var(--success); }
|
||||||
|
.log-item .log-error { color: var(--error); }
|
||||||
|
|
||||||
|
/* Alert */
|
||||||
|
.alert {
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-error {
|
||||||
|
background: rgba(239, 68, 68, 0.2);
|
||||||
|
border: 1px solid var(--error);
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-success {
|
||||||
|
background: rgba(34, 197, 94, 0.2);
|
||||||
|
border: 1px solid var(--success);
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Empty State */
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 60px 20px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state svg {
|
||||||
|
width: 80px;
|
||||||
|
height: 80px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toggle Switch */
|
||||||
|
.toggle {
|
||||||
|
position: relative;
|
||||||
|
width: 50px;
|
||||||
|
height: 26px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle input {
|
||||||
|
opacity: 0;
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-slider {
|
||||||
|
position: absolute;
|
||||||
|
cursor: pointer;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: var(--bg-lighter);
|
||||||
|
border-radius: 26px;
|
||||||
|
transition: 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-slider:before {
|
||||||
|
position: absolute;
|
||||||
|
content: "";
|
||||||
|
height: 20px;
|
||||||
|
width: 20px;
|
||||||
|
left: 3px;
|
||||||
|
bottom: 3px;
|
||||||
|
background: white;
|
||||||
|
border-radius: 50%;
|
||||||
|
transition: 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle input:checked + .toggle-slider { background: var(--primary); }
|
||||||
|
.toggle input:checked + .toggle-slider:before { transform: translateX(24px); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<!-- Login Page -->
|
||||||
|
<div class="login-container" id="loginPage">
|
||||||
|
<div class="login-box">
|
||||||
|
<h1>Supabase Scheduler</h1>
|
||||||
|
<p>Gestione query automatiche per database Supabase</p>
|
||||||
|
|
||||||
|
<div id="loginError" class="alert alert-error" style="display: none;"></div>
|
||||||
|
|
||||||
|
<form id="loginForm">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username">Username</label>
|
||||||
|
<input type="text" id="username" name="username" required autocomplete="username">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<input type="password" id="password" name="password" required autocomplete="current-password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary" style="width: 100%;">Accedi</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Dashboard -->
|
||||||
|
<div class="dashboard" id="dashboard">
|
||||||
|
<header class="header">
|
||||||
|
<h1>Supabase Scheduler</h1>
|
||||||
|
<div class="header-right">
|
||||||
|
<span class="status-badge" id="schedulerStatus">Scheduler Attivo</span>
|
||||||
|
<button class="btn btn-secondary btn-sm" id="logoutBtn">Logout</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="main-content">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">
|
||||||
|
<h2>Database Configurati</h2>
|
||||||
|
<button class="btn btn-primary" id="addDbBtn">+ Aggiungi Database</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="dbList" class="db-list">
|
||||||
|
<!-- Database list will be rendered here -->
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="emptyState" class="empty-state" style="display: none;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"/>
|
||||||
|
</svg>
|
||||||
|
<h3>Nessun database configurato</h3>
|
||||||
|
<p>Clicca "Aggiungi Database" per iniziare</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Add/Edit Database Modal -->
|
||||||
|
<div class="modal" id="dbModal">
|
||||||
|
<div class="modal-content">
|
||||||
|
<h2 id="modalTitle">Aggiungi Database</h2>
|
||||||
|
|
||||||
|
<form id="dbForm">
|
||||||
|
<input type="hidden" id="dbId">
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="dbName">Nome</label>
|
||||||
|
<input type="text" id="dbName" required placeholder="Es: Produzione, Test, ecc.">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="dbUrl">Supabase URL</label>
|
||||||
|
<input type="url" id="dbUrl" required placeholder="https://xxx.supabase.co">
|
||||||
|
<small>L'URL del tuo progetto Supabase (Settings > API)</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="dbKey">Anon Key</label>
|
||||||
|
<input type="text" id="dbKey" required placeholder="eyJhbGciOiJIUzI1NiIs...">
|
||||||
|
<small>La chiave anon/public del progetto</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="dbQuery">Query (Tabella o RPC)</label>
|
||||||
|
<input type="text" id="dbQuery" required placeholder="Es: users?select=id,name">
|
||||||
|
<small>Es: users?select=* oppure rpc/mia_funzione</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="dbFrequency">Frequenza (minuti)</label>
|
||||||
|
<input type="number" id="dbFrequency" required min="1" max="1440" value="5">
|
||||||
|
<small>Ogni quanti minuti eseguire la query (1-1440)</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label style="display: flex; align-items: center; gap: 12px;">
|
||||||
|
<span>Attivo</span>
|
||||||
|
<label class="toggle">
|
||||||
|
<input type="checkbox" id="dbActive" checked>
|
||||||
|
<span class="toggle-slider"></span>
|
||||||
|
</label>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn btn-secondary" id="cancelBtn">Annulla</button>
|
||||||
|
<button type="submit" class="btn btn-primary">Salva</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Logs Modal -->
|
||||||
|
<div class="modal" id="logsModal">
|
||||||
|
<div class="modal-content">
|
||||||
|
<h2>Log Esecuzioni: <span id="logsDbName"></span></h2>
|
||||||
|
|
||||||
|
<div class="logs-container" id="logsContainer">
|
||||||
|
<!-- Logs will be rendered here -->
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn btn-secondary" id="closeLogsBtn">Chiudi</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Base URL for API (handles subpath routing)
|
||||||
|
const BASE_URL = window.location.pathname.replace(/\/$/, '');
|
||||||
|
|
||||||
|
// API helper
|
||||||
|
async function api(endpoint, options = {}) {
|
||||||
|
const url = `${BASE_URL}${endpoint}`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...options.headers
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Errore API');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// State
|
||||||
|
let databases = [];
|
||||||
|
|
||||||
|
// DOM Elements
|
||||||
|
const loginPage = document.getElementById('loginPage');
|
||||||
|
const dashboard = document.getElementById('dashboard');
|
||||||
|
const loginForm = document.getElementById('loginForm');
|
||||||
|
const loginError = document.getElementById('loginError');
|
||||||
|
const logoutBtn = document.getElementById('logoutBtn');
|
||||||
|
const dbList = document.getElementById('dbList');
|
||||||
|
const emptyState = document.getElementById('emptyState');
|
||||||
|
const addDbBtn = document.getElementById('addDbBtn');
|
||||||
|
const dbModal = document.getElementById('dbModal');
|
||||||
|
const dbForm = document.getElementById('dbForm');
|
||||||
|
const cancelBtn = document.getElementById('cancelBtn');
|
||||||
|
const logsModal = document.getElementById('logsModal');
|
||||||
|
const closeLogsBtn = document.getElementById('closeLogsBtn');
|
||||||
|
|
||||||
|
// Check auth status on load
|
||||||
|
async function checkAuth() {
|
||||||
|
try {
|
||||||
|
const { authenticated } = await api('/api/auth/status');
|
||||||
|
if (authenticated) {
|
||||||
|
showDashboard();
|
||||||
|
} else {
|
||||||
|
showLogin();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
showLogin();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showLogin() {
|
||||||
|
loginPage.classList.remove('hidden');
|
||||||
|
dashboard.classList.remove('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
function showDashboard() {
|
||||||
|
loginPage.classList.add('hidden');
|
||||||
|
dashboard.classList.add('active');
|
||||||
|
loadDatabases();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login
|
||||||
|
loginForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
loginError.style.display = 'none';
|
||||||
|
|
||||||
|
const username = document.getElementById('username').value;
|
||||||
|
const password = document.getElementById('password').value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api('/api/login', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ username, password })
|
||||||
|
});
|
||||||
|
showDashboard();
|
||||||
|
} catch (err) {
|
||||||
|
loginError.textContent = err.message;
|
||||||
|
loginError.style.display = 'block';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Logout
|
||||||
|
logoutBtn.addEventListener('click', async () => {
|
||||||
|
await api('/api/logout', { method: 'POST' });
|
||||||
|
showLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load databases
|
||||||
|
async function loadDatabases() {
|
||||||
|
try {
|
||||||
|
databases = await api('/api/databases');
|
||||||
|
renderDatabases();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading databases:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render database list
|
||||||
|
function renderDatabases() {
|
||||||
|
if (databases.length === 0) {
|
||||||
|
dbList.innerHTML = '';
|
||||||
|
emptyState.style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
emptyState.style.display = 'none';
|
||||||
|
|
||||||
|
dbList.innerHTML = databases.map(db => {
|
||||||
|
const statusClass = !db.is_active ? 'inactive' : (db.last_status === 'error' ? 'error' : '');
|
||||||
|
const lastRun = db.last_run ? new Date(db.last_run).toLocaleString('it-IT') : 'Mai';
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="db-item">
|
||||||
|
<div class="db-info">
|
||||||
|
<h3>
|
||||||
|
<span class="status-dot ${statusClass}"></span>
|
||||||
|
${escapeHtml(db.name)}
|
||||||
|
</h3>
|
||||||
|
<p class="db-meta">URL: <code>${escapeHtml(db.supabase_url)}</code></p>
|
||||||
|
<p class="db-meta">Query: <code>${escapeHtml(db.query)}</code></p>
|
||||||
|
<p class="db-meta">Frequenza: ogni ${db.frequency_minutes} min | Ultima esecuzione: ${lastRun}</p>
|
||||||
|
${db.last_error ? `<p class="db-meta" style="color: var(--error);">Errore: ${escapeHtml(db.last_error)}</p>` : ''}
|
||||||
|
</div>
|
||||||
|
<div class="db-actions">
|
||||||
|
<button class="btn btn-secondary btn-sm" onclick="executeNow(${db.id})">Esegui Ora</button>
|
||||||
|
<button class="btn btn-secondary btn-sm" onclick="viewLogs(${db.id}, '${escapeHtml(db.name)}')">Log</button>
|
||||||
|
<button class="btn btn-secondary btn-sm" onclick="editDb(${db.id})">Modifica</button>
|
||||||
|
<button class="btn btn-danger btn-sm" onclick="deleteDb(${db.id})">Elimina</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escape HTML
|
||||||
|
function escapeHtml(str) {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.textContent = str;
|
||||||
|
return div.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add database button
|
||||||
|
addDbBtn.addEventListener('click', () => {
|
||||||
|
document.getElementById('modalTitle').textContent = 'Aggiungi Database';
|
||||||
|
document.getElementById('dbId').value = '';
|
||||||
|
dbForm.reset();
|
||||||
|
document.getElementById('dbActive').checked = true;
|
||||||
|
dbModal.classList.add('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Cancel button
|
||||||
|
cancelBtn.addEventListener('click', () => {
|
||||||
|
dbModal.classList.remove('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close logs
|
||||||
|
closeLogsBtn.addEventListener('click', () => {
|
||||||
|
logsModal.classList.remove('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modals on background click
|
||||||
|
dbModal.addEventListener('click', (e) => {
|
||||||
|
if (e.target === dbModal) dbModal.classList.remove('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
logsModal.addEventListener('click', (e) => {
|
||||||
|
if (e.target === logsModal) logsModal.classList.remove('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save database
|
||||||
|
dbForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const id = document.getElementById('dbId').value;
|
||||||
|
const data = {
|
||||||
|
name: document.getElementById('dbName').value,
|
||||||
|
supabase_url: document.getElementById('dbUrl').value.replace(/\/$/, ''),
|
||||||
|
anon_key: document.getElementById('dbKey').value,
|
||||||
|
query: document.getElementById('dbQuery').value,
|
||||||
|
frequency_minutes: parseInt(document.getElementById('dbFrequency').value),
|
||||||
|
is_active: document.getElementById('dbActive').checked
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (id) {
|
||||||
|
await api(`/api/databases/${id}`, { method: 'PUT', body: JSON.stringify(data) });
|
||||||
|
} else {
|
||||||
|
await api('/api/databases', { method: 'POST', body: JSON.stringify(data) });
|
||||||
|
}
|
||||||
|
dbModal.classList.remove('active');
|
||||||
|
loadDatabases();
|
||||||
|
} catch (err) {
|
||||||
|
alert('Errore: ' + err.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Edit database
|
||||||
|
async function editDb(id) {
|
||||||
|
try {
|
||||||
|
const db = await api(`/api/databases/${id}`);
|
||||||
|
document.getElementById('modalTitle').textContent = 'Modifica Database';
|
||||||
|
document.getElementById('dbId').value = db.id;
|
||||||
|
document.getElementById('dbName').value = db.name;
|
||||||
|
document.getElementById('dbUrl').value = db.supabase_url;
|
||||||
|
document.getElementById('dbKey').value = db.anon_key;
|
||||||
|
document.getElementById('dbQuery').value = db.query;
|
||||||
|
document.getElementById('dbFrequency').value = db.frequency_minutes;
|
||||||
|
document.getElementById('dbActive').checked = !!db.is_active;
|
||||||
|
dbModal.classList.add('active');
|
||||||
|
} catch (err) {
|
||||||
|
alert('Errore: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete database
|
||||||
|
async function deleteDb(id) {
|
||||||
|
if (!confirm('Sei sicuro di voler eliminare questo database?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api(`/api/databases/${id}`, { method: 'DELETE' });
|
||||||
|
loadDatabases();
|
||||||
|
} catch (err) {
|
||||||
|
alert('Errore: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute now
|
||||||
|
async function executeNow(id) {
|
||||||
|
try {
|
||||||
|
const result = await api(`/api/databases/${id}/execute`, { method: 'POST' });
|
||||||
|
alert(result.status === 'success' ? 'Query eseguita con successo!' : 'Errore: ' + result.error);
|
||||||
|
loadDatabases();
|
||||||
|
} catch (err) {
|
||||||
|
alert('Errore: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// View logs
|
||||||
|
async function viewLogs(id, name) {
|
||||||
|
try {
|
||||||
|
const logs = await api(`/api/databases/${id}/logs`);
|
||||||
|
document.getElementById('logsDbName').textContent = name;
|
||||||
|
|
||||||
|
const container = document.getElementById('logsContainer');
|
||||||
|
if (logs.length === 0) {
|
||||||
|
container.innerHTML = '<p style="color: var(--text-muted);">Nessun log disponibile</p>';
|
||||||
|
} else {
|
||||||
|
container.innerHTML = logs.map(log => `
|
||||||
|
<div class="log-item">
|
||||||
|
<span class="log-time">${new Date(log.executed_at).toLocaleString('it-IT')}</span> -
|
||||||
|
<span class="${log.status === 'success' ? 'log-success' : 'log-error'}">${log.status}</span>
|
||||||
|
(${log.duration_ms}ms)
|
||||||
|
${log.error ? `<br><small style="color: var(--error);">${escapeHtml(log.error)}</small>` : ''}
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
logsModal.classList.add('active');
|
||||||
|
} catch (err) {
|
||||||
|
alert('Errore: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init
|
||||||
|
checkAuth();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
342
server.js
Normal file
342
server.js
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
require('dotenv').config();
|
||||||
|
const express = require('express');
|
||||||
|
const cors = require('cors');
|
||||||
|
const session = require('express-session');
|
||||||
|
const Database = require('better-sqlite3');
|
||||||
|
const cron = require('node-cron');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = process.env.PORT || 3000;
|
||||||
|
|
||||||
|
// Credenziali fisse
|
||||||
|
const AUTH_USERNAME = 'testlab';
|
||||||
|
const AUTH_PASSWORD = 'magarifunzione4';
|
||||||
|
|
||||||
|
// Database SQLite
|
||||||
|
const db = new Database('./data/scheduler.db');
|
||||||
|
|
||||||
|
// Inizializza database
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS databases (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
supabase_url TEXT NOT NULL,
|
||||||
|
anon_key TEXT NOT NULL,
|
||||||
|
query TEXT NOT NULL,
|
||||||
|
frequency_minutes INTEGER NOT NULL DEFAULT 5,
|
||||||
|
is_active INTEGER NOT NULL DEFAULT 1,
|
||||||
|
last_run TEXT,
|
||||||
|
last_status TEXT,
|
||||||
|
last_error TEXT,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS execution_logs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
database_id INTEGER NOT NULL,
|
||||||
|
executed_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
response TEXT,
|
||||||
|
error TEXT,
|
||||||
|
duration_ms INTEGER,
|
||||||
|
FOREIGN KEY (database_id) REFERENCES databases(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(express.static('public'));
|
||||||
|
app.use(session({
|
||||||
|
secret: process.env.SESSION_SECRET || 'supabase-scheduler-secret-key-2024',
|
||||||
|
resave: false,
|
||||||
|
saveUninitialized: false,
|
||||||
|
cookie: {
|
||||||
|
secure: false, // true in production con HTTPS
|
||||||
|
maxAge: 24 * 60 * 60 * 1000 // 24 ore
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Middleware auth check
|
||||||
|
const requireAuth = (req, res, next) => {
|
||||||
|
if (req.session && req.session.authenticated) {
|
||||||
|
next();
|
||||||
|
} else {
|
||||||
|
res.status(401).json({ error: 'Non autenticato' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ============ AUTH ROUTES ============
|
||||||
|
|
||||||
|
app.post('/api/login', (req, res) => {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
|
||||||
|
if (username === AUTH_USERNAME && password === AUTH_PASSWORD) {
|
||||||
|
req.session.authenticated = true;
|
||||||
|
req.session.username = username;
|
||||||
|
res.json({ success: true, message: 'Login effettuato' });
|
||||||
|
} else {
|
||||||
|
res.status(401).json({ error: 'Credenziali non valide' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/logout', (req, res) => {
|
||||||
|
req.session.destroy();
|
||||||
|
res.json({ success: true, message: 'Logout effettuato' });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/auth/status', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
authenticated: !!(req.session && req.session.authenticated),
|
||||||
|
username: req.session?.username || null
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============ DATABASE CONFIG ROUTES ============
|
||||||
|
|
||||||
|
app.get('/api/databases', requireAuth, (req, res) => {
|
||||||
|
try {
|
||||||
|
const databases = db.prepare('SELECT * FROM databases ORDER BY created_at DESC').all();
|
||||||
|
res.json(databases);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/databases/:id', requireAuth, (req, res) => {
|
||||||
|
try {
|
||||||
|
const database = db.prepare('SELECT * FROM databases WHERE id = ?').get(req.params.id);
|
||||||
|
if (!database) {
|
||||||
|
return res.status(404).json({ error: 'Database non trovato' });
|
||||||
|
}
|
||||||
|
res.json(database);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/databases', requireAuth, (req, res) => {
|
||||||
|
const { name, supabase_url, anon_key, query, frequency_minutes, is_active } = req.body;
|
||||||
|
|
||||||
|
if (!name || !supabase_url || !anon_key || !query) {
|
||||||
|
return res.status(400).json({ error: 'Campi obbligatori mancanti' });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
INSERT INTO databases (name, supabase_url, anon_key, query, frequency_minutes, is_active)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
const result = stmt.run(name, supabase_url, anon_key, query, frequency_minutes || 5, is_active !== false ? 1 : 0);
|
||||||
|
|
||||||
|
const newDb = db.prepare('SELECT * FROM databases WHERE id = ?').get(result.lastInsertRowid);
|
||||||
|
res.status(201).json(newDb);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.put('/api/databases/:id', requireAuth, (req, res) => {
|
||||||
|
const { name, supabase_url, anon_key, query, frequency_minutes, is_active } = req.body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const existing = db.prepare('SELECT * FROM databases WHERE id = ?').get(req.params.id);
|
||||||
|
if (!existing) {
|
||||||
|
return res.status(404).json({ error: 'Database non trovato' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
UPDATE databases
|
||||||
|
SET name = ?, supabase_url = ?, anon_key = ?, query = ?,
|
||||||
|
frequency_minutes = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = ?
|
||||||
|
`);
|
||||||
|
stmt.run(
|
||||||
|
name || existing.name,
|
||||||
|
supabase_url || existing.supabase_url,
|
||||||
|
anon_key || existing.anon_key,
|
||||||
|
query || existing.query,
|
||||||
|
frequency_minutes || existing.frequency_minutes,
|
||||||
|
is_active !== undefined ? (is_active ? 1 : 0) : existing.is_active,
|
||||||
|
req.params.id
|
||||||
|
);
|
||||||
|
|
||||||
|
const updated = db.prepare('SELECT * FROM databases WHERE id = ?').get(req.params.id);
|
||||||
|
res.json(updated);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/databases/:id', requireAuth, (req, res) => {
|
||||||
|
try {
|
||||||
|
const existing = db.prepare('SELECT * FROM databases WHERE id = ?').get(req.params.id);
|
||||||
|
if (!existing) {
|
||||||
|
return res.status(404).json({ error: 'Database non trovato' });
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare('DELETE FROM databases WHERE id = ?').run(req.params.id);
|
||||||
|
res.json({ success: true, message: 'Database eliminato' });
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============ EXECUTION LOGS ============
|
||||||
|
|
||||||
|
app.get('/api/databases/:id/logs', requireAuth, (req, res) => {
|
||||||
|
try {
|
||||||
|
const logs = db.prepare(`
|
||||||
|
SELECT * FROM execution_logs
|
||||||
|
WHERE database_id = ?
|
||||||
|
ORDER BY executed_at DESC
|
||||||
|
LIMIT 50
|
||||||
|
`).all(req.params.id);
|
||||||
|
res.json(logs);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============ MANUAL EXECUTION ============
|
||||||
|
|
||||||
|
app.post('/api/databases/:id/execute', requireAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const database = db.prepare('SELECT * FROM databases WHERE id = ?').get(req.params.id);
|
||||||
|
if (!database) {
|
||||||
|
return res.status(404).json({ error: 'Database non trovato' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await executeQuery(database);
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============ SCHEDULER STATUS ============
|
||||||
|
|
||||||
|
app.get('/api/scheduler/status', requireAuth, (req, res) => {
|
||||||
|
const activeCount = db.prepare('SELECT COUNT(*) as count FROM databases WHERE is_active = 1').get();
|
||||||
|
const totalCount = db.prepare('SELECT COUNT(*) as count FROM databases').get();
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
running: true,
|
||||||
|
active_databases: activeCount.count,
|
||||||
|
total_databases: totalCount.count,
|
||||||
|
check_interval: '1 minute'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============ QUERY EXECUTION LOGIC ============
|
||||||
|
|
||||||
|
async function executeQuery(database) {
|
||||||
|
const startTime = Date.now();
|
||||||
|
let status = 'success';
|
||||||
|
let response = null;
|
||||||
|
let error = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Costruisci URL per Supabase REST API
|
||||||
|
const url = `${database.supabase_url}/rest/v1/${database.query}`;
|
||||||
|
|
||||||
|
const fetchResponse = await fetch(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'apikey': database.anon_key,
|
||||||
|
'Authorization': `Bearer ${database.anon_key}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Prefer': 'return=representation'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await fetchResponse.json();
|
||||||
|
|
||||||
|
if (!fetchResponse.ok) {
|
||||||
|
throw new Error(data.message || data.error || `HTTP ${fetchResponse.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
response = JSON.stringify(data).substring(0, 5000); // Limita dimensione log
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
status = 'error';
|
||||||
|
error = err.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
const duration = Date.now() - startTime;
|
||||||
|
|
||||||
|
// Salva log esecuzione
|
||||||
|
db.prepare(`
|
||||||
|
INSERT INTO execution_logs (database_id, status, response, error, duration_ms)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
`).run(database.id, status, response, error, duration);
|
||||||
|
|
||||||
|
// Aggiorna stato database
|
||||||
|
db.prepare(`
|
||||||
|
UPDATE databases
|
||||||
|
SET last_run = CURRENT_TIMESTAMP, last_status = ?, last_error = ?
|
||||||
|
WHERE id = ?
|
||||||
|
`).run(status, error, database.id);
|
||||||
|
|
||||||
|
return { status, response: response ? JSON.parse(response) : null, error, duration_ms: duration };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ SCHEDULER ============
|
||||||
|
|
||||||
|
// Controlla ogni minuto quali query eseguire
|
||||||
|
cron.schedule('* * * * *', async () => {
|
||||||
|
const now = new Date();
|
||||||
|
console.log(`[${now.toISOString()}] Scheduler check...`);
|
||||||
|
|
||||||
|
const databases = db.prepare('SELECT * FROM databases WHERE is_active = 1').all();
|
||||||
|
|
||||||
|
for (const database of databases) {
|
||||||
|
const lastRun = database.last_run ? new Date(database.last_run) : null;
|
||||||
|
const frequencyMs = database.frequency_minutes * 60 * 1000;
|
||||||
|
|
||||||
|
// Esegui se mai eseguito o se passato tempo sufficiente
|
||||||
|
if (!lastRun || (now - lastRun) >= frequencyMs) {
|
||||||
|
console.log(`[${now.toISOString()}] Executing query for: ${database.name}`);
|
||||||
|
try {
|
||||||
|
await executeQuery(database);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[${now.toISOString()}] Error executing ${database.name}:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[SCHEDULER] Cron scheduler avviato - controllo ogni minuto');
|
||||||
|
|
||||||
|
// ============ HEALTH & INFO ============
|
||||||
|
|
||||||
|
app.get('/api/health', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
uptime: process.uptime()
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 404 handler
|
||||||
|
app.use((req, res) => {
|
||||||
|
// Se richiesta API, ritorna JSON
|
||||||
|
if (req.path.startsWith('/api/')) {
|
||||||
|
return res.status(404).json({ error: 'Endpoint non trovato' });
|
||||||
|
}
|
||||||
|
// Altrimenti serve index.html per SPA routing
|
||||||
|
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Error handler
|
||||||
|
app.use((err, req, res, next) => {
|
||||||
|
console.error(err.stack);
|
||||||
|
res.status(500).json({ error: 'Errore interno del server' });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.listen(PORT, '0.0.0.0', () => {
|
||||||
|
console.log(`[SERVER] Running on port ${PORT}`);
|
||||||
|
console.log(`[SERVER] Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user