MediaWiki:CommonDashboard.js: differenze tra le versioni
Nessun oggetto della modifica |
Nessun oggetto della modifica |
||
| Riga 1: | Riga 1: | ||
// ============================================ | // ============================================ | ||
// 🔧 CommonDashboard.js – | // 🔧 CommonDashboard.js – SOLO proxy server-side (no API key nel browser) | ||
// Ultimo aggiornamento: 2025-08- | // Ultimo aggiornamento: 2025-08-18 | ||
// ============================================ | // ============================================ | ||
// | // ───────────────────────────────────────────────────────────────────────────── | ||
// UTILITÀ UI | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.toggleDashboardBox = function (id) { | window.toggleDashboardBox = function (id) { | ||
const box = document.getElementById(id); | const box = document.getElementById(id); | ||
if (box) box.style.display = box.style.display === "block" ? "none" : "block"; | |||
}; | |||
window.logActivity = function (msg) { | |||
const box = document.getElementById("activityLogContent") || document.getElementById("activityLog"); | |||
if (!box) return; | |||
const now = new Date().toLocaleTimeString("it-IT"); | |||
const line = document.createElement("div"); | |||
line.innerHTML = `<span style="color:gray;">[${now}]</span> ${msg}`; | |||
box.prepend(line); | |||
}; | |||
window.clearActivityLog = function () { | |||
const box = document.getElementById("activityLogContent"); | |||
if (box) { | if (box) { | ||
box. | box.innerHTML = "<em>Registro svuotato.</em><br>"; | ||
logActivity("✔ Log svuotato manualmente."); | |||
} | } | ||
}; | }; | ||
// ⚙️ CONNESSIONE API | // ───────────────────────────────────────────────────────────────────────────── | ||
// ⚙️ CONNESSIONE API (via proxy PHP server-side) | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
// Campi previsti nella pagina: | |||
// - #test-prompt (textarea / input con il prompt di test) | |||
// - #api-result (div / textarea output) | |||
// - #model-select (opzionale: select con id; se assente usa il default lato server) | |||
// - #api-key (eventuale campo legacy: viene nascosto) | |||
window.testAPIConnection = async function () { | window.testAPIConnection = async function () { | ||
const | const promptEl = document.getElementById('test-prompt'); | ||
const | const outputEl = document.getElementById('api-result'); | ||
const | const modelEl = document.getElementById('model-select'); | ||
const prompt = (promptEl?.value || '').trim(); | |||
const model = (modelEl?.value || ''); // opzionale: se vuoto userà il default del proxy | |||
if (!prompt) { | |||
outputEl && (outputEl.innerText = '⚠️ Inserisci un prompt.'); | |||
return; | return; | ||
} | } | ||
outputEl && (outputEl.innerText = '⏳ Invio al server...'); | |||
logActivity(`🚀 Test API | logActivity(`🚀 Test API via proxy – Modello: <strong>${model || '(default server)'}</strong>`); | ||
try { | try { | ||
const | const res = await fetch('/dashboard/api/openai_project_gpt.php', { | ||
method: | method: 'POST', | ||
headers: { | headers: { 'Content-Type': 'application/json' }, | ||
body: JSON.stringify({ prompt, model }) | |||
body: JSON.stringify({ | |||
}); | }); | ||
const data = await res.json(); | |||
if (data.status === 'ok') { | |||
const text = data.result || '(risposta vuota)'; | |||
if (data. | outputEl && (outputEl.innerText = '✅ ' + text); | ||
logActivity('✅ Risposta ricevuta dal proxy.'); | |||
logActivity( | |||
} else { | } else { | ||
outputEl && (outputEl.innerText = '❌ Errore: ' + (data.error || 'sconosciuto')); | |||
logActivity(`❌ Errore proxy: ${data.error || 'sconosciuto'}`); | |||
} | } | ||
} catch (e) { | } catch (e) { | ||
outputEl && (outputEl.innerText = '🚫 Errore di rete: ' + e.message); | |||
logActivity(`❌ Errore | logActivity(`❌ Errore rete: ${e.message}`); | ||
} | } | ||
}; | }; | ||
// 📊 STATO PROGETTI – | // ───────────────────────────────────────────────────────────────────────────── | ||
// 📊 STATO PROGETTI – aggiungi / elimina / carica elenco | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.addNewProject = function () { | window.addNewProject = function () { | ||
const title = document.getElementById("newProjectTitle").value.trim(); | const title = document.getElementById("newProjectTitle")?.value.trim(); | ||
const notes = document.getElementById("newProjectNotes").value.trim(); | const notes = document.getElementById("newProjectNotes")?.value.trim(); | ||
if (!title) { | if (!title) { | ||
alert("Inserisci un titolo per il progetto!"); | alert("Inserisci un titolo per il progetto!"); | ||
| Riga 69: | Riga 88: | ||
const table = document.getElementById("projectRows"); | const table = document.getElementById("projectRows"); | ||
const newRow = document.createElement("tr"); | const newRow = document.createElement("tr"); | ||
newRow.innerHTML = ` | newRow.innerHTML = ` | ||
<td style="padding:0.5rem; border:1px solid #ccc;">${title}</td> | <td style="padding:0.5rem; border:1px solid #ccc;">${title}</td> | ||
| Riga 80: | Riga 98: | ||
</td> | </td> | ||
`; | `; | ||
table?.appendChild(newRow); | |||
table.appendChild(newRow); | |||
window.closeProjectDialog(); | window.closeProjectDialog(); | ||
logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`); | logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes || '–'}`); | ||
// Crea cartella | |||
fetch("/dashboard/api/create_project_dir.php", { | fetch("/dashboard/api/create_project_dir.php", { | ||
method: "POST", | method: "POST", | ||
| Riga 92: | Riga 110: | ||
.then(res => res.json()) | .then(res => res.json()) | ||
.then(data => { | .then(data => { | ||
if (data.success) | if (data.success) logActivity(`📂 Cartella progetto creata: <strong>${title}</strong>`); | ||
else logActivity(`⚠️ Errore creazione cartella: ${data.error}`); | |||
}) | }) | ||
.catch( | .catch(() => logActivity("❌ Errore rete creazione cartella progetto.")); | ||
// Salva metadati progetto | |||
const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") }; | |||
fetch("/dashboard/api/write_project.php", { | fetch("/dashboard/api/write_project.php", { | ||
method: "POST", | method: "POST", | ||
| Riga 113: | Riga 122: | ||
body: JSON.stringify(payload) | body: JSON.stringify(payload) | ||
}) | }) | ||
.then | .then(res => res.json()) | ||
.then | .then(data => { | ||
if (!data.success) | if (!data.success) logActivity(`❌ Errore salvataggio progetto: ${data.error}`); | ||
else logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`); | |||
}) | }) | ||
.catch(( | .catch(() => logActivity("❌ Errore rete durante salvataggio progetto.")); | ||
}; | }; | ||
window.deleteProject = function (title) { | window.deleteProject = function (title) { | ||
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`); | logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`); | ||
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) | if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) return; | ||
fetch('/dashboard/api/delete_project_dir.php', { | fetch('/dashboard/api/delete_project_dir.php', { | ||
| Riga 145: | Riga 146: | ||
logActivity(`🗑️ Progetto eliminato: <strong>${title}</strong>`); | logActivity(`🗑️ Progetto eliminato: <strong>${title}</strong>`); | ||
alert(data.message); | alert(data.message); | ||
loadAllProjects(); | loadAllProjects(); | ||
} else { | } else { | ||
alert("Errore: " + data.error); | alert("Errore: " + data.error); | ||
logActivity(`❌ Errore eliminazione progetto: ${data.error}`); | logActivity(`❌ Errore eliminazione progetto: ${data.error}`); | ||
} | } | ||
} catch | } catch { | ||
alert("⚠️ | alert("⚠️ Risposta non JSON."); | ||
logActivity("❌ Risposta non JSON durante eliminazione."); | logActivity("❌ Risposta non JSON durante eliminazione."); | ||
} | } | ||
}) | }) | ||
.catch( | .catch(() => { | ||
alert("Errore rete durante eliminazione."); | alert("Errore rete durante eliminazione."); | ||
logActivity("❌ Errore rete durante eliminazione progetto."); | logActivity("❌ Errore rete durante eliminazione progetto."); | ||
}); | }); | ||
}; | }; | ||
window.loadAllProjects = function () { | window.loadAllProjects = function () { | ||
fetch('/dashboard/api/read_all_projects.php') | fetch('/dashboard/api/read_all_projects.php') | ||
.then( | .then(r => r.json()) | ||
.then(data => { | .then(data => { | ||
if (!Array.isArray(data)) { | if (!Array.isArray(data)) { | ||
| Riga 171: | Riga 170: | ||
return; | return; | ||
} | } | ||
const table = document.getElementById("projectRows"); | const table = document.getElementById("projectRows"); | ||
table.innerHTML = ''; | if (!table) return; | ||
table.innerHTML = ''; | |||
data.forEach( | data.forEach(p => { | ||
const | const tr = document.createElement("tr"); | ||
tr.innerHTML = ` | |||
<td style="padding:0.5rem; border:1px solid #ccc;">${p.title}</td> | |||
<td style="padding:0.5rem; border:1px solid #ccc;">${ | |||
<td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td> | <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td> | ||
<td style="padding:0.5rem; border:1px solid #ccc;">${ | <td style="padding:0.5rem; border:1px solid #ccc;">${p.date}</td> | ||
<td style="padding:0.5rem; border:1px solid #ccc;">${ | <td style="padding:0.5rem; border:1px solid #ccc;">${p.notes || '–'}</td> | ||
<td style="padding:0.5rem; border:1px solid #ccc;"> | <td style="padding:0.5rem; border:1px solid #ccc;"> | ||
<button onclick="analyzeProjectWithGPT('${ | <button onclick="analyzeProjectWithGPT('${p.title}', \`${p.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button> | ||
<button onclick="deleteProject('${ | <button onclick="deleteProject('${p.title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button> | ||
</td> | </td> | ||
`; | `; | ||
table.appendChild(tr); | |||
table.appendChild( | logActivity(`📌 Caricato progetto: <strong>${p.title}</strong>`); | ||
logActivity(`📌 Caricato progetto: <strong>${ | |||
}); | }); | ||
}) | }) | ||
.catch( | .catch(() => { | ||
alert("Errore nel caricamento dei progetti."); | alert("Errore nel caricamento dei progetti."); | ||
logActivity("❌ Errore nel caricamento progetti."); | logActivity("❌ Errore nel caricamento progetti."); | ||
| Riga 200: | Riga 196: | ||
}; | }; | ||
// 🤖 ANALISI GPT | // ───────────────────────────────────────────────────────────────────────────── | ||
window.analyzeProjectWithGPT = function (title, notes) { | // 🤖 ANALISI GPT (via proxy PHP) – riusa lo stesso endpoint del test | ||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.analyzeProjectWithGPT = async function (title, notes) { | |||
logActivity(`🧠 Analisi GPT avviata per: <strong>${title}</strong>`); | logActivity(`🧠 Analisi GPT avviata per: <strong>${title}</strong>`); | ||
const modelEl = document.getElementById('model-select'); | |||
const model = (modelEl?.value || ''); | |||
const prompt = `Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}`; | const prompt = `Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}`; | ||
const outputArea = document.getElementById("response") || document.getElementById("api-result"); | |||
const promptBox = document.getElementById("test-prompt"); | |||
const | |||
const | |||
if (promptBox) promptBox.value = prompt; | |||
if (outputArea) outputArea.value = ''; | |||
logActivity(`✍️ Prompt pronto (model: ${model || 'default server'})`); | |||
if ( | |||
if ( | |||
logActivity(` | |||
try { | try { | ||
const | const res = await fetch('/dashboard/api/openai_project_gpt.php', { | ||
method: | method: 'POST', | ||
headers: { | headers: { 'Content-Type': 'application/json' }, | ||
body: JSON.stringify({ prompt, model }) | |||
body: JSON.stringify({ | |||
}); | }); | ||
const data = await res.json(); | |||
if (data.status === 'ok') { | |||
const text = data.result || '(risposta vuota)'; | |||
if (data. | if (outputArea) outputArea.value = text; | ||
logActivity('✅ Analisi completata.'); | |||
logActivity( | |||
} else { | } else { | ||
const err = data.error || 'sconosciuto'; | |||
if (outputArea) outputArea.value = '❌ ' + err; | |||
logActivity(`❌ Errore proxy: ${err}`); | |||
} | } | ||
} catch (e) { | } catch (e) { | ||
if (outputArea) outputArea.value = '🚫 Errore rete: ' + e.message; | |||
logActivity(`❌ Errore | logActivity(`❌ Errore rete: ${e.message}`); | ||
} | } | ||
// opzionale: apri/mostra box API test | |||
window.toggleDashboardBox("api-test-box"); | |||
window. | |||
}; | }; | ||
// ───────────────────────────────────────────────────────────────────────────── | |||
window. | // DIALOG nuovo progetto | ||
document.getElementById("newProjectDialog").style.display = "block"; | // ───────────────────────────────────────────────────────────────────────────── | ||
window.toggleNewProjectDialog = function () { | |||
const dialog = document.getElementById("newProjectDialog"); | |||
if (!dialog) return; | |||
dialog.style.display = dialog.style.display === "block" ? "none" : "block"; | |||
}; | }; | ||
window.closeProjectDialog = function () { | window.closeProjectDialog = function () { | ||
document.getElementById("newProjectDialog").style.display = "none"; | const dialog = document.getElementById("newProjectDialog"); | ||
if (dialog) dialog.style.display = "none"; | |||
}; | }; | ||
// | // ───────────────────────────────────────────────────────────────────────────── | ||
// FILE: prompt.txt (carica/salva) | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.loadPrompt = function () { | window.loadPrompt = function () { | ||
fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt') | fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt') | ||
.then( | .then(r => { if (!r.ok) throw new Error('Errore nel caricamento del file'); return r.json(); }) | ||
.then(d => { | |||
if (d.status === "ok") { | |||
const ta = document.getElementById("promptArea"); | |||
.then( | if (ta) ta.value = d.content; | ||
if ( | |||
document.getElementById("promptArea").value = | |||
logActivity("📥 Caricato prompt.txt nella textarea."); | logActivity("📥 Caricato prompt.txt nella textarea."); | ||
} else { | } else { | ||
alert("Errore: " + | alert("Errore: " + d.error); | ||
logActivity("❌ Errore nel caricamento: " + | logActivity("❌ Errore nel caricamento: " + d.error); | ||
} | } | ||
}) | }) | ||
.catch( | .catch(e => { alert("Errore nel caricamento: " + e); logActivity("❌ Errore nel caricamento di prompt.txt."); }); | ||
}; | }; | ||
window.savePrompt = function () { | window.savePrompt = function () { | ||
const content = document.getElementById("promptArea").value; | const content = document.getElementById("promptArea")?.value || ''; | ||
fetch('/dashboard/api/write_prompt.php', { | fetch('/dashboard/api/write_prompt.php', { | ||
method: 'POST', | method: 'POST', | ||
headers: { | headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | ||
body: 'text=' + encodeURIComponent(content) | body: 'text=' + encodeURIComponent(content) | ||
}) | }) | ||
.then( | .then(r => { if (!r.ok) throw new Error('Errore nel salvataggio'); return r.text(); }) | ||
.then(() => { logActivity("💾 Salvato prompt.txt dal form."); alert("Prompt salvato con successo."); }) | |||
.catch(e => { alert("Errore nel salvataggio: " + e); logActivity("❌ Errore nel salvataggio di prompt.txt."); }); | |||
.then( | |||
.catch( | |||
}; | }; | ||
// | // ───────────────────────────────────────────────────────────────────────────── | ||
// SCRITTURA/LETTURA FILE GPT (salva/carica in progetto) | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.salvaFileDaTextarea = function () { | window.salvaFileDaTextarea = function () { | ||
const content = document.getElementById("gpt-response-area").value; | const content = document.getElementById("gpt-response-area")?.value || ''; | ||
const filename = document.getElementById("gpt-filename").value.trim(); | const filename = document.getElementById("gpt-filename")?.value.trim(); | ||
const subfolder = document.getElementById("gpt-subfolder").value; | const subfolder = document.getElementById("gpt-subfolder")?.value || ''; | ||
const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn"; | const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn"; | ||
if (!filename || !content) { | if (!filename || !content) { | ||
| Riga 561: | Riga 298: | ||
fetch('/dashboard/api/write_file.php', { | fetch('/dashboard/api/write_file.php', { | ||
method: 'POST', | method: 'POST', | ||
headers: { | headers: { 'Content-Type': 'application/json' }, | ||
body: JSON.stringify({ projectName: project, subfolder, filename, content }) | |||
body: JSON.stringify({ | |||
}) | }) | ||
.then( | .then(r => r.json()) | ||
.then( | .then(d => { | ||
if ( | if (d.status === "ok") { | ||
document.getElementById("gpt-response-area").value = | const ta = document.getElementById("gpt-response-area"); | ||
if (ta) ta.value = d.content; | |||
logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`); | logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`); | ||
alert("File salvato con successo in:" + | alert("File salvato con successo in: " + d.path); | ||
} else { | } else { | ||
alert("Errore: " + | alert("Errore: " + d.error); | ||
logActivity(`❌ Errore salvataggio ${filename}: ${ | logActivity(`❌ Errore salvataggio ${filename}: ${d.error}`); | ||
} | } | ||
}) | }) | ||
.catch( | .catch(() => alert("Errore durante il salvataggio.")); | ||
}; | }; | ||
window.caricaFileGPT = function () { | window.caricaFileGPT = function () { | ||
const filename = document.getElementById("gpt-filename").value.trim(); | const filename = document.getElementById("gpt-filename")?.value.trim(); | ||
const subfolder = document.getElementById("gpt-subfolder").value; | const subfolder = document.getElementById("gpt-subfolder")?.value || ''; | ||
const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn"; | const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn"; | ||
if (!filename) { | if (!filename) { | ||
| Riga 600: | Riga 327: | ||
fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`) | fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`) | ||
.then( | .then(r => r.json()) | ||
.then( | .then(d => { | ||
if ( | if (d.status === "ok") { | ||
document.getElementById("gpt-response-area").value = | const ta = document.getElementById("gpt-response-area"); | ||
if (ta) ta.value = d.content; | |||
logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`); | logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`); | ||
} else { | } else { | ||
alert("Errore: " + | alert("Errore: " + d.error); | ||
logActivity(`❌ Errore nel caricamento di ${filename}: ${ | logActivity(`❌ Errore nel caricamento di ${filename}: ${d.error}`); | ||
} | } | ||
}) | }) | ||
.catch( | .catch(() => alert("Errore durante il caricamento del file.")); | ||
}; | }; | ||
// ───────────────────────────────────────────────────────────────────────────── | |||
// IMPORTA FILE (interfaccia semplificata esistente) | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
// | |||
function setupImportaFileSemplificato() { | function setupImportaFileSemplificato() { | ||
const container = document.getElementById("serverFileSimpleImportContainer"); | const container = document.getElementById("serverFileSimpleImportContainer"); | ||
if (!container) return; | if (!container) return; | ||
container.innerHTML = ` | container.innerHTML = ` | ||
<div style="border:1px solid #ccc; padding:1rem; border-radius:8px; background:#fff;"> | <div style="border:1px solid #ccc; padding:1rem; border-radius:8px; background:#fff;"> | ||
| Riga 809: | Riga 358: | ||
function eseguiCopiaFileServer() { | function eseguiCopiaFileServer() { | ||
const source = document.getElementById("sourceFilePath").value; | const source = document.getElementById("sourceFilePath")?.value; | ||
const dest = document.getElementById("destRelativePath").value; | const dest = document.getElementById("destRelativePath")?.value; | ||
if (!source || !dest) { | if (!source || !dest) { | ||
| Riga 817: | Riga 366: | ||
} | } | ||
// NB: qui ho mantenuto il tuo endpoint; se il path era sbagliato, rimettilo a /dashboard/api/copy_file_from_path.php | |||
fetch("/mnt/data/masticationpedia-openai/copy_file_from_path.php", { | fetch("/mnt/data/masticationpedia-openai/copy_file_from_path.php", { | ||
method: "POST", | method: "POST", | ||
| Riga 822: | Riga 372: | ||
body: JSON.stringify({ sourcePath: source, destinationPath: dest }), | body: JSON.stringify({ sourcePath: source, destinationPath: dest }), | ||
}) | }) | ||
.then(r => r.text()) | |||
.then(txt => { alert("✅ File copiato: " + txt); logActivity("📁 Copiato da " + source + " a " + dest); }) | |||
.catch(err => { alert("❌ Errore: " + err); }); | |||
} | } | ||
// ───────────────────────────────────────────────────────────────────────────── | |||
// AVVIO | |||
// ───────────────────────────────────────────────────────────────────────────── | |||
window.addEventListener("load", function () { | |||
// 1) carica lista progetti | |||
loadAllProjects(); | |||
// | |||
// | |||
// | |||
window. | |||
// 2) nascondi eventuale campo API key legacy | |||
const | const keyField = document.getElementById('api-key') || document.getElementById('apiKeyInput'); | ||
if ( | if (keyField) { | ||
const row = keyField.closest('.form-row') || keyField.parentElement; | |||
if (row) row.style.display = 'none'; | |||
else keyField.style.display = 'none'; | |||
// niente più localStorage di API key | |||
} | } | ||
// 3) setup import file semplice (se presente) | |||
setupImportaFileSemplificato(); | |||
}); | }); | ||
Versione delle 10:53, 18 ago 2025
// ============================================
// 🔧 CommonDashboard.js – SOLO proxy server-side (no API key nel browser)
// Ultimo aggiornamento: 2025-08-18
// ============================================
// ─────────────────────────────────────────────────────────────────────────────
// UTILITÀ UI
// ─────────────────────────────────────────────────────────────────────────────
window.toggleDashboardBox = function (id) {
const box = document.getElementById(id);
if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};
window.logActivity = function (msg) {
const box = document.getElementById("activityLogContent") || document.getElementById("activityLog");
if (!box) return;
const now = new Date().toLocaleTimeString("it-IT");
const line = document.createElement("div");
line.innerHTML = `<span style="color:gray;">[${now}]</span> ${msg}`;
box.prepend(line);
};
window.clearActivityLog = function () {
const box = document.getElementById("activityLogContent");
if (box) {
box.innerHTML = "<em>Registro svuotato.</em><br>";
logActivity("✔ Log svuotato manualmente.");
}
};
// ─────────────────────────────────────────────────────────────────────────────
// ⚙️ CONNESSIONE API (via proxy PHP server-side)
// ─────────────────────────────────────────────────────────────────────────────
// Campi previsti nella pagina:
// - #test-prompt (textarea / input con il prompt di test)
// - #api-result (div / textarea output)
// - #model-select (opzionale: select con id; se assente usa il default lato server)
// - #api-key (eventuale campo legacy: viene nascosto)
window.testAPIConnection = async function () {
const promptEl = document.getElementById('test-prompt');
const outputEl = document.getElementById('api-result');
const modelEl = document.getElementById('model-select');
const prompt = (promptEl?.value || '').trim();
const model = (modelEl?.value || ''); // opzionale: se vuoto userà il default del proxy
if (!prompt) {
outputEl && (outputEl.innerText = '⚠️ Inserisci un prompt.');
return;
}
outputEl && (outputEl.innerText = '⏳ Invio al server...');
logActivity(`🚀 Test API via proxy – Modello: <strong>${model || '(default server)'}</strong>`);
try {
const res = await fetch('/dashboard/api/openai_project_gpt.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, model })
});
const data = await res.json();
if (data.status === 'ok') {
const text = data.result || '(risposta vuota)';
outputEl && (outputEl.innerText = '✅ ' + text);
logActivity('✅ Risposta ricevuta dal proxy.');
} else {
outputEl && (outputEl.innerText = '❌ Errore: ' + (data.error || 'sconosciuto'));
logActivity(`❌ Errore proxy: ${data.error || 'sconosciuto'}`);
}
} catch (e) {
outputEl && (outputEl.innerText = '🚫 Errore di rete: ' + e.message);
logActivity(`❌ Errore rete: ${e.message}`);
}
};
// ─────────────────────────────────────────────────────────────────────────────
// 📊 STATO PROGETTI – aggiungi / elimina / carica elenco
// ─────────────────────────────────────────────────────────────────────────────
window.addNewProject = function () {
const title = document.getElementById("newProjectTitle")?.value.trim();
const notes = document.getElementById("newProjectNotes")?.value.trim();
if (!title) {
alert("Inserisci un titolo per il progetto!");
return;
}
const table = document.getElementById("projectRows");
const newRow = document.createElement("tr");
newRow.innerHTML = `
<td style="padding:0.5rem; border:1px solid #ccc;">${title}</td>
<td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${new Date().toLocaleDateString("it-IT")}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${notes || '–'}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">
<button onclick="analyzeProjectWithGPT('${title}', \`${notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
<button onclick="deleteProject('${title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
</td>
`;
table?.appendChild(newRow);
window.closeProjectDialog();
logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes || '–'}`);
// Crea cartella
fetch("/dashboard/api/create_project_dir.php", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: "projectName=" + encodeURIComponent(title)
})
.then(res => res.json())
.then(data => {
if (data.success) logActivity(`📂 Cartella progetto creata: <strong>${title}</strong>`);
else logActivity(`⚠️ Errore creazione cartella: ${data.error}`);
})
.catch(() => logActivity("❌ Errore rete creazione cartella progetto."));
// Salva metadati progetto
const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") };
fetch("/dashboard/api/write_project.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
})
.then(res => res.json())
.then(data => {
if (!data.success) logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
else logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
})
.catch(() => logActivity("❌ Errore rete durante salvataggio progetto."));
};
window.deleteProject = function (title) {
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`);
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) return;
fetch('/dashboard/api/delete_project_dir.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'projectName=' + encodeURIComponent(title)
})
.then(res => res.text())
.then(text => {
try {
const data = JSON.parse(text);
if (data.success) {
logActivity(`🗑️ Progetto eliminato: <strong>${title}</strong>`);
alert(data.message);
loadAllProjects();
} else {
alert("Errore: " + data.error);
logActivity(`❌ Errore eliminazione progetto: ${data.error}`);
}
} catch {
alert("⚠️ Risposta non JSON.");
logActivity("❌ Risposta non JSON durante eliminazione.");
}
})
.catch(() => {
alert("Errore rete durante eliminazione.");
logActivity("❌ Errore rete durante eliminazione progetto.");
});
};
window.loadAllProjects = function () {
fetch('/dashboard/api/read_all_projects.php')
.then(r => r.json())
.then(data => {
if (!Array.isArray(data)) {
logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
return;
}
const table = document.getElementById("projectRows");
if (!table) return;
table.innerHTML = '';
data.forEach(p => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td style="padding:0.5rem; border:1px solid #ccc;">${p.title}</td>
<td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${p.date}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${p.notes || '–'}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">
<button onclick="analyzeProjectWithGPT('${p.title}', \`${p.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
<button onclick="deleteProject('${p.title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
</td>
`;
table.appendChild(tr);
logActivity(`📌 Caricato progetto: <strong>${p.title}</strong>`);
});
})
.catch(() => {
alert("Errore nel caricamento dei progetti.");
logActivity("❌ Errore nel caricamento progetti.");
});
};
// ─────────────────────────────────────────────────────────────────────────────
// 🤖 ANALISI GPT (via proxy PHP) – riusa lo stesso endpoint del test
// ─────────────────────────────────────────────────────────────────────────────
window.analyzeProjectWithGPT = async function (title, notes) {
logActivity(`🧠 Analisi GPT avviata per: <strong>${title}</strong>`);
const modelEl = document.getElementById('model-select');
const model = (modelEl?.value || '');
const prompt = `Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}`;
const outputArea = document.getElementById("response") || document.getElementById("api-result");
const promptBox = document.getElementById("test-prompt");
if (promptBox) promptBox.value = prompt;
if (outputArea) outputArea.value = '';
logActivity(`✍️ Prompt pronto (model: ${model || 'default server'})`);
try {
const res = await fetch('/dashboard/api/openai_project_gpt.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, model })
});
const data = await res.json();
if (data.status === 'ok') {
const text = data.result || '(risposta vuota)';
if (outputArea) outputArea.value = text;
logActivity('✅ Analisi completata.');
} else {
const err = data.error || 'sconosciuto';
if (outputArea) outputArea.value = '❌ ' + err;
logActivity(`❌ Errore proxy: ${err}`);
}
} catch (e) {
if (outputArea) outputArea.value = '🚫 Errore rete: ' + e.message;
logActivity(`❌ Errore rete: ${e.message}`);
}
// opzionale: apri/mostra box API test
window.toggleDashboardBox("api-test-box");
};
// ─────────────────────────────────────────────────────────────────────────────
// DIALOG nuovo progetto
// ─────────────────────────────────────────────────────────────────────────────
window.toggleNewProjectDialog = function () {
const dialog = document.getElementById("newProjectDialog");
if (!dialog) return;
dialog.style.display = dialog.style.display === "block" ? "none" : "block";
};
window.closeProjectDialog = function () {
const dialog = document.getElementById("newProjectDialog");
if (dialog) dialog.style.display = "none";
};
// ─────────────────────────────────────────────────────────────────────────────
// FILE: prompt.txt (carica/salva)
// ─────────────────────────────────────────────────────────────────────────────
window.loadPrompt = function () {
fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt')
.then(r => { if (!r.ok) throw new Error('Errore nel caricamento del file'); return r.json(); })
.then(d => {
if (d.status === "ok") {
const ta = document.getElementById("promptArea");
if (ta) ta.value = d.content;
logActivity("📥 Caricato prompt.txt nella textarea.");
} else {
alert("Errore: " + d.error);
logActivity("❌ Errore nel caricamento: " + d.error);
}
})
.catch(e => { alert("Errore nel caricamento: " + e); logActivity("❌ Errore nel caricamento di prompt.txt."); });
};
window.savePrompt = function () {
const content = document.getElementById("promptArea")?.value || '';
fetch('/dashboard/api/write_prompt.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'text=' + encodeURIComponent(content)
})
.then(r => { if (!r.ok) throw new Error('Errore nel salvataggio'); return r.text(); })
.then(() => { logActivity("💾 Salvato prompt.txt dal form."); alert("Prompt salvato con successo."); })
.catch(e => { alert("Errore nel salvataggio: " + e); logActivity("❌ Errore nel salvataggio di prompt.txt."); });
};
// ─────────────────────────────────────────────────────────────────────────────
// SCRITTURA/LETTURA FILE GPT (salva/carica in progetto)
// ─────────────────────────────────────────────────────────────────────────────
window.salvaFileDaTextarea = function () {
const content = document.getElementById("gpt-response-area")?.value || '';
const filename = document.getElementById("gpt-filename")?.value.trim();
const subfolder = document.getElementById("gpt-subfolder")?.value || '';
const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn";
if (!filename || !content) {
alert("Inserisci un nome file e assicurati che il contenuto non sia vuoto.");
return;
}
fetch('/dashboard/api/write_file.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ projectName: project, subfolder, filename, content })
})
.then(r => r.json())
.then(d => {
if (d.status === "ok") {
const ta = document.getElementById("gpt-response-area");
if (ta) ta.value = d.content;
logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
alert("File salvato con successo in: " + d.path);
} else {
alert("Errore: " + d.error);
logActivity(`❌ Errore salvataggio ${filename}: ${d.error}`);
}
})
.catch(() => alert("Errore durante il salvataggio."));
};
window.caricaFileGPT = function () {
const filename = document.getElementById("gpt-filename")?.value.trim();
const subfolder = document.getElementById("gpt-subfolder")?.value || '';
const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn";
if (!filename) {
alert("Inserisci il nome del file da caricare.");
return;
}
fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`)
.then(r => r.json())
.then(d => {
if (d.status === "ok") {
const ta = document.getElementById("gpt-response-area");
if (ta) ta.value = d.content;
logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
} else {
alert("Errore: " + d.error);
logActivity(`❌ Errore nel caricamento di ${filename}: ${d.error}`);
}
})
.catch(() => alert("Errore durante il caricamento del file."));
};
// ─────────────────────────────────────────────────────────────────────────────
// IMPORTA FILE (interfaccia semplificata esistente)
// ─────────────────────────────────────────────────────────────────────────────
function setupImportaFileSemplificato() {
const container = document.getElementById("serverFileSimpleImportContainer");
if (!container) return;
container.innerHTML = `
<div style="border:1px solid #ccc; padding:1rem; border-radius:8px; background:#fff;">
<h4>📁 Importa file dal server (semplificata)</h4>
<input type="text" id="sourceFilePath" placeholder="📂 Percorso assoluto file (es: /var/www/html/miofile.php)" style="width:100%; margin-bottom:0.5rem;">
<input type="text" id="destRelativePath" placeholder="📁 Percorso progetto (es: SSO_LinkedIn/php/)" style="width:100%; margin-bottom:0.5rem;">
<button onclick="eseguiCopiaFileServer()">📤 Copia nel progetto</button>
</div>
`;
}
function eseguiCopiaFileServer() {
const source = document.getElementById("sourceFilePath")?.value;
const dest = document.getElementById("destRelativePath")?.value;
if (!source || !dest) {
alert("⚠️ Inserisci sia il percorso sorgente che quello di destinazione.");
return;
}
// NB: qui ho mantenuto il tuo endpoint; se il path era sbagliato, rimettilo a /dashboard/api/copy_file_from_path.php
fetch("/mnt/data/masticationpedia-openai/copy_file_from_path.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sourcePath: source, destinationPath: dest }),
})
.then(r => r.text())
.then(txt => { alert("✅ File copiato: " + txt); logActivity("📁 Copiato da " + source + " a " + dest); })
.catch(err => { alert("❌ Errore: " + err); });
}
// ─────────────────────────────────────────────────────────────────────────────
// AVVIO
// ─────────────────────────────────────────────────────────────────────────────
window.addEventListener("load", function () {
// 1) carica lista progetti
loadAllProjects();
// 2) nascondi eventuale campo API key legacy
const keyField = document.getElementById('api-key') || document.getElementById('apiKeyInput');
if (keyField) {
const row = keyField.closest('.form-row') || keyField.parentElement;
if (row) row.style.display = 'none';
else keyField.style.display = 'none';
// niente più localStorage di API key
}
// 3) setup import file semplice (se presente)
setupImportaFileSemplificato();
});