MediaWiki:CommonDashboard.js: differenze tra le versioni
Nessun oggetto della modifica |
Nessun oggetto della modifica |
||
| Riga 1: | Riga 1: | ||
// ========================== | |||
// 📁 CommonDashboard.js – Dashboard Masticationpedia | |||
// ========================== | |||
document.addEventListener("DOMContentLoaded", function () { | |||
console.log("📦 CommonDashboard.js caricato correttamente"); | |||
// 📌 Hook pulsanti tools | |||
document.getElementById("testConnessioneBtn")?.addEventListener("click", testConnessioneGPT); | |||
document.getElementById("btnNuovoProgetto")?.addEventListener("click", creaNuovoProgetto); | |||
loadAllProjects(); // Carica all'avvio | |||
}); | |||
// 💬 Testa connessione API GPT | |||
function testConnessioneGPT() { | |||
const prompt = document.getElementById("promptInput").value; | |||
if (!prompt) return alert("Inserisci un prompt!"); | |||
fetch("/dashboard/api/test_prompt.php", { | |||
method: "POST", | |||
headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |||
body: "prompt=" + encodeURIComponent(prompt) | |||
}) | |||
.then(res => res.json()) | |||
.then(data => { | |||
document.getElementById("rispostaGPT").innerText = data.risposta || "⚠️ Nessuna risposta ricevuta."; | |||
}) | |||
.catch(err => { | |||
console.error("❌ Errore fetch:", err); | |||
alert("Errore nella connessione API."); | |||
}); | |||
} | |||
// 🟦 Carica tutti i progetti salvati | |||
function loadAllProjects() { | |||
const container = document.getElementById("statoProgetti"); | |||
if (!container) return; | |||
container.innerHTML = ""; // svuota | |||
fetch("/dashboard/api/list_projects.php") | |||
.then(res => res.json()) | |||
.then(projects => { | |||
if (projects.length === 0) { | |||
container.innerHTML = "<p>🕳️ Nessun progetto trovato.</p>"; | |||
return; | |||
} | |||
projects.forEach(title => { | |||
const projectDiv = document.createElement("div"); | |||
projectDiv.className = "project-entry"; | |||
const titoloSpan = document.createElement("span"); | |||
titoloSpan.innerHTML = "📘 " + title; | |||
titoloSpan.className = "project-title"; | |||
projectDiv.appendChild(titoloSpan); | |||
const analizzaBtn = document.createElement("button"); | |||
analizzaBtn.innerText = "📊"; | |||
analizzaBtn.title = "Analizza con GPT"; | |||
analizzaBtn.className = "analizza-progetto-btn"; | |||
analizzaBtn.onclick = function () { | |||
analyzeProjectWithGPT(title); | |||
}; | |||
projectDiv.appendChild(analizzaBtn); | |||
const eliminaBtn = document.createElement("button"); | |||
eliminaBtn.innerText = "🗑️"; | |||
eliminaBtn.title = "Elimina progetto"; | |||
eliminaBtn.className = "elimina-progetto-btn"; | |||
eliminaBtn.onclick = function () { | |||
deleteProject(title); | |||
}; | |||
projectDiv.appendChild(eliminaBtn); | |||
container.appendChild(projectDiv); | |||
}); | |||
}) | |||
.catch(err => { | |||
console.error("❌ Errore caricamento progetti:", err); | |||
container.innerHTML = "<p>❌ Errore nel caricamento dei progetti.</p>"; | |||
}); | |||
} | |||
// 🧠 Analizza progetto con GPT | |||
function analyzeProjectWithGPT(title) { | |||
logActivity(`🧠 Analisi avviata per <strong>${title}</strong>...`); | |||
fetch("/dashboard/api/analyze_project.php", { | |||
method: "POST", | |||
headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |||
body: "projectName=" + encodeURIComponent(title) | |||
}) | |||
.then(res => res.json()) | |||
.then(data => { | |||
const risposta = data.risposta || "⚠️ Nessuna risposta da GPT."; | |||
document.getElementById("rispostaAnalisiProgetto").innerText = risposta; | |||
logActivity(`✅ Analisi completata per: <strong>${title}</strong>`); | |||
}) | |||
.catch(err => { | |||
console.error("❌ Errore analisi:", err); | |||
logActivity(`❌ Errore durante analisi progetto <strong>${title}</strong>`); | |||
}); | |||
} | |||
// ➕ Crea nuovo progetto | |||
function creaNuovoProgetto() { | |||
const nome = prompt("Inserisci il nome del nuovo progetto:"); | |||
if (!nome) return; | |||
fetch("/dashboard/api/create_project.php", { | |||
method: "POST", | |||
headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |||
body: "projectName=" + encodeURIComponent(nome) | |||
}) | |||
.then(res => res.json()) | |||
.then(data => { | |||
if (data.success) { | |||
logActivity(`✅ Creato nuovo progetto: <strong>${nome}</strong>`); | |||
loadAllProjects(); | |||
} else { | |||
alert("Errore: " + data.error); | |||
} | |||
}) | |||
.catch(err => { | |||
console.error("❌ Errore creazione progetto:", err); | |||
alert("Errore rete durante creazione."); | |||
}); | |||
} | |||
// 🧾 Log attività nella textarea | |||
function logActivity(msg) { | |||
const area = document.getElementById("logAttivita"); | |||
if (!area) return; | |||
const now = new Date().toLocaleString(); | |||
area.value += `[${now}] ${msg}\n`; | |||
area.scrollTop = area.scrollHeight; | |||
} | |||
// 💾 Cancella cartella del progetto sul server | |||
window.deleteProject = function (title) { | |||
console.log("🧪 deleteProject chiamata con titolo:", title); | |||
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`); | |||
alert("🔧 Tentativo eliminazione progetto: " + title); | |||
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) { | |||
console.log("🛑 Eliminazione annullata da utente"); | |||
return; | |||
} | |||
console.log("🟡 Invio richiesta DELETE per:", title); | |||
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()) // grezzo | |||
.then(text => { | |||
console.log("📨 Risposta grezza:", 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 (err) { | |||
alert("⚠️ Errore parsing JSON."); | |||
console.error("❌ Risposta non JSON:", text); | |||
logActivity("❌ Risposta non JSON durante eliminazione."); | |||
} | |||
}) | |||
.catch(err => { | |||
alert("Errore rete durante eliminazione."); | |||
console.error("🌐 Errore fetch:", err); | |||
logActivity("❌ Errore rete durante eliminazione progetto."); | |||
}); | |||
}; | |||
/* Secondario | |||
// ============================================ | // ============================================ | ||
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti | // 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti | ||
| Riga 315: | Riga 506: | ||
/* | /* Primario | ||
// ============================================ | // ============================================ | ||
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti | // 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti | ||
Versione delle 16:33, 6 ago 2025
// ==========================
// 📁 CommonDashboard.js – Dashboard Masticationpedia
// ==========================
document.addEventListener("DOMContentLoaded", function () {
console.log("📦 CommonDashboard.js caricato correttamente");
// 📌 Hook pulsanti tools
document.getElementById("testConnessioneBtn")?.addEventListener("click", testConnessioneGPT);
document.getElementById("btnNuovoProgetto")?.addEventListener("click", creaNuovoProgetto);
loadAllProjects(); // Carica all'avvio
});
// 💬 Testa connessione API GPT
function testConnessioneGPT() {
const prompt = document.getElementById("promptInput").value;
if (!prompt) return alert("Inserisci un prompt!");
fetch("/dashboard/api/test_prompt.php", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: "prompt=" + encodeURIComponent(prompt)
})
.then(res => res.json())
.then(data => {
document.getElementById("rispostaGPT").innerText = data.risposta || "⚠️ Nessuna risposta ricevuta.";
})
.catch(err => {
console.error("❌ Errore fetch:", err);
alert("Errore nella connessione API.");
});
}
// 🟦 Carica tutti i progetti salvati
function loadAllProjects() {
const container = document.getElementById("statoProgetti");
if (!container) return;
container.innerHTML = ""; // svuota
fetch("/dashboard/api/list_projects.php")
.then(res => res.json())
.then(projects => {
if (projects.length === 0) {
container.innerHTML = "<p>🕳️ Nessun progetto trovato.</p>";
return;
}
projects.forEach(title => {
const projectDiv = document.createElement("div");
projectDiv.className = "project-entry";
const titoloSpan = document.createElement("span");
titoloSpan.innerHTML = "📘 " + title;
titoloSpan.className = "project-title";
projectDiv.appendChild(titoloSpan);
const analizzaBtn = document.createElement("button");
analizzaBtn.innerText = "📊";
analizzaBtn.title = "Analizza con GPT";
analizzaBtn.className = "analizza-progetto-btn";
analizzaBtn.onclick = function () {
analyzeProjectWithGPT(title);
};
projectDiv.appendChild(analizzaBtn);
const eliminaBtn = document.createElement("button");
eliminaBtn.innerText = "🗑️";
eliminaBtn.title = "Elimina progetto";
eliminaBtn.className = "elimina-progetto-btn";
eliminaBtn.onclick = function () {
deleteProject(title);
};
projectDiv.appendChild(eliminaBtn);
container.appendChild(projectDiv);
});
})
.catch(err => {
console.error("❌ Errore caricamento progetti:", err);
container.innerHTML = "<p>❌ Errore nel caricamento dei progetti.</p>";
});
}
// 🧠 Analizza progetto con GPT
function analyzeProjectWithGPT(title) {
logActivity(`🧠 Analisi avviata per <strong>${title}</strong>...`);
fetch("/dashboard/api/analyze_project.php", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: "projectName=" + encodeURIComponent(title)
})
.then(res => res.json())
.then(data => {
const risposta = data.risposta || "⚠️ Nessuna risposta da GPT.";
document.getElementById("rispostaAnalisiProgetto").innerText = risposta;
logActivity(`✅ Analisi completata per: <strong>${title}</strong>`);
})
.catch(err => {
console.error("❌ Errore analisi:", err);
logActivity(`❌ Errore durante analisi progetto <strong>${title}</strong>`);
});
}
// ➕ Crea nuovo progetto
function creaNuovoProgetto() {
const nome = prompt("Inserisci il nome del nuovo progetto:");
if (!nome) return;
fetch("/dashboard/api/create_project.php", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: "projectName=" + encodeURIComponent(nome)
})
.then(res => res.json())
.then(data => {
if (data.success) {
logActivity(`✅ Creato nuovo progetto: <strong>${nome}</strong>`);
loadAllProjects();
} else {
alert("Errore: " + data.error);
}
})
.catch(err => {
console.error("❌ Errore creazione progetto:", err);
alert("Errore rete durante creazione.");
});
}
// 🧾 Log attività nella textarea
function logActivity(msg) {
const area = document.getElementById("logAttivita");
if (!area) return;
const now = new Date().toLocaleString();
area.value += `[${now}] ${msg}\n`;
area.scrollTop = area.scrollHeight;
}
// 💾 Cancella cartella del progetto sul server
window.deleteProject = function (title) {
console.log("🧪 deleteProject chiamata con titolo:", title);
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`);
alert("🔧 Tentativo eliminazione progetto: " + title);
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) {
console.log("🛑 Eliminazione annullata da utente");
return;
}
console.log("🟡 Invio richiesta DELETE per:", title);
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()) // grezzo
.then(text => {
console.log("📨 Risposta grezza:", 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 (err) {
alert("⚠️ Errore parsing JSON.");
console.error("❌ Risposta non JSON:", text);
logActivity("❌ Risposta non JSON durante eliminazione.");
}
})
.catch(err => {
alert("Errore rete durante eliminazione.");
console.error("🌐 Errore fetch:", err);
logActivity("❌ Errore rete durante eliminazione progetto.");
});
};
/* Secondario
// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti
// ============================================
// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
const box = document.getElementById(id);
if (box) {
box.style.display = box.style.display === "block" ? "none" : "block";
}
};
// ⚙️ CONNESSIONE API
window.testAPIConnection = async function () {
const key = document.getElementById('api-key').value.trim();
const prompt = document.getElementById('test-prompt').value;
const output = document.getElementById('api-result');
const model = "gpt-4o-2024-05-13";
if (!key || !prompt) {
output.innerText = '⚠️ Inserisci una chiave valida e un prompt.';
return;
}
output.innerText = '⏳ Attendere risposta da OpenAI...';
logActivity(`🚀 Test API avviato – Modello: <strong>${model}</strong>`);
try {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + key
},
body: JSON.stringify({
model: model,
messages: [{ role: "user", content: prompt }],
temperature: 0.7
})
});
const data = await response.json();
if (data.choices && data.choices.length > 0) {
output.innerText = "✅ Risposta:" + data.choices[0].message.content;
logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
} else if (data.error) {
output.innerText = "❌ Errore: " + data.error.message;
logActivity(`❌ Errore API: ${data.error.message}`);
} else {
output.innerText = "❌ Nessuna risposta ricevuta.";
}
} catch (e) {
output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
logActivity(`❌ Errore di connessione: ${e.message}`);
}
};
// 📊 STATO PROGETTI
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}`);
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}`);
console.warn("Errore cartella:", data.error);
}
})
.catch(error => {
logActivity("❌ Errore rete creazione cartella progetto.");
console.error("Errore fetch:", error);
});
// ⬇️ Scrittura su server
const payload = {
title: title,
notes: 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) {
alert("⚠️ Errore salvataggio su server: " + data.error);
logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
} else {
logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
}
})
.catch((err) => {
alert("❌ Errore rete salvataggio progetto.");
console.error("Errore invio progetto:", err);
logActivity("❌ Errore rete durante salvataggio progetto.");
});
};
// 🗑️ DELETE PROJECT
window.deleteProject = function (title) {
console.log("🧪 deleteProject chiamata con titolo:", title);
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`);
alert("🔧 Tentativo eliminazione progetto: " + title);
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) {
console.log("🛑 Eliminazione annullata da utente");
return;
}
console.log("🟡 Invio richiesta DELETE per:", title);
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 => {
console.log("📨 Risposta grezza dal server:", 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 (err) {
alert("⚠️ Errore parsing JSON.");
console.error("❌ Risposta non JSON:", text);
logActivity("❌ Risposta non JSON durante eliminazione.");
}
})
.catch(err => {
alert("Errore rete durante eliminazione.");
console.error("🌐 Errore fetch:", err);
logActivity("❌ Errore rete durante eliminazione progetto.");
});
};
// ✍️ Altre funzioni (prompt, file GPT, sysnote, attività)...
// ✍️ [VEDI MESSAGGIO SEGUENTE]
// 💾 Salvataggio prompt
window.savePrompt = function () {
const prompt = document.getElementById("promptText").value;
const filename = document.getElementById("promptFileName").value;
if (!prompt || !filename) {
alert("Inserisci sia un prompt che un nome file!");
return;
}
fetch("/dashboard/api/write_prompt.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename: filename, content: prompt })
})
.then(res => res.json())
.then(data => {
if (data.success) {
alert("✅ Prompt salvato con successo!");
logActivity(`📝 Prompt <strong>${filename}</strong> salvato.`);
} else {
alert("⚠️ Errore salvataggio: " + data.error);
logActivity(`❌ Errore salvataggio prompt: ${data.error}`);
}
})
.catch(err => {
alert("Errore di rete.");
logActivity("❌ Errore rete durante salvataggio prompt.");
console.error("Errore:", err);
});
};
// 📂 Salvataggio manuale file da textarea
window.salvaFileDaTextarea = function () {
const percorso = document.getElementById("percorsoFileTextarea").value.trim();
const contenuto = document.getElementById("contenutoFileTextarea").value;
if (!percorso || !contenuto) {
alert("Inserisci un percorso e del contenuto.");
return;
}
fetch("/dashboard/api/write_file_from_textarea.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path: percorso, content: contenuto })
})
.then(res => res.json())
.then(data => {
if (data.success) {
alert("✅ File salvato correttamente!");
logActivity(`💾 File salvato: <code>${percorso}</code>`);
} else {
alert("Errore: " + data.error);
logActivity(`❌ Errore salvataggio file: ${data.error}`);
}
})
.catch(err => {
alert("❌ Errore di rete.");
console.error(err);
logActivity("❌ Errore rete durante salvataggio file.");
});
};
// 📥 Caricamento contenuto file
window.caricaFileGPT = function () {
const path = document.getElementById("gptPathInput").value.trim();
const area = document.getElementById("contenutoFileTextarea");
if (!path) {
alert("Inserisci un percorso valido.");
return;
}
fetch("/dashboard/api/read_file.php?path=" + encodeURIComponent(path))
.then(res => res.text())
.then(data => {
area.value = data;
logActivity(`📂 File caricato: <code>${path}</code>`);
})
.catch(err => {
alert("❌ Errore durante il caricamento.");
console.error(err);
logActivity(`❌ Errore lettura file: ${path}`);
});
};
// 📋 Registro attività (console visuale)
window.logActivity = function (msg) {
const logArea = document.getElementById("activity-log");
const timestamp = new Date().toLocaleTimeString("it-IT");
const entry = document.createElement("div");
entry.innerHTML = `<span style="color:#888;">[${timestamp}]</span> ${msg}`;
logArea.prepend(entry);
};
// 📑 Caricamento automatico progetti da file JSON
window.loadAllProjects = function () {
fetch("/dashboard/api/read_project_list.php")
.then(res => res.json())
.then(data => {
const table = document.getElementById("projectRows");
table.innerHTML = ""; // Pulisce
if (!Array.isArray(data)) {
console.warn("⚠️ Risposta non valida da read_project_list.php:", data);
return;
}
data.forEach(project => {
const row = document.createElement("tr");
row.innerHTML = `
<td style="padding:0.5rem; border:1px solid #ccc;">${project.title}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">✅ Completato</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${project.date || "–"}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${project.notes || "–"}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">
<button onclick="analyzeProjectWithGPT('${project.title}', \`${project.notes || ''}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
<button onclick="deleteProject('${project.title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
</td>
`;
table.appendChild(row);
});
logActivity("📋 Lista progetti caricata.");
})
.catch(err => {
console.error("Errore lettura lista progetti:", err);
logActivity("❌ Errore lettura lista progetti.");
});
};
// 🚀 Inizializzazione
document.addEventListener("DOMContentLoaded", function () {
loadAllProjects();
});
/* Primario
// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti
// ============================================
// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
const box = document.getElementById(id);
if (box) {
box.style.display = box.style.display === "block" ? "none" : "block";
}
};
// ⚙️ CONNESSIONE API
window.testAPIConnection = async function () {
const key = document.getElementById('api-key').value.trim();
const prompt = document.getElementById('test-prompt').value;
const output = document.getElementById('api-result');
const model = "gpt-4o-2024-05-13";
if (!key || !prompt) {
output.innerText = '⚠️ Inserisci una chiave valida e un prompt.';
return;
}
output.innerText = '⏳ Attendere risposta da OpenAI...';
logActivity(`🚀 Test API avviato – Modello: <strong>${model}</strong>`);
try {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + key
},
body: JSON.stringify({
model: model,
messages: [{ role: "user", content: prompt }],
temperature: 0.7
})
});
const data = await response.json();
if (data.choices && data.choices.length > 0) {
output.innerText = "✅ Risposta:" + data.choices[0].message.content;
logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
} else if (data.error) {
output.innerText = "❌ Errore: " + data.error.message;
logActivity(`❌ Errore API: ${data.error.message}`);
} else {
output.innerText = "❌ Nessuna risposta ricevuta.";
}
} catch (e) {
output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
logActivity(`❌ Errore di connessione: ${e.message}`);
}
};
// 📊 SEZIONE: STATO PROGETTI –
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");
// 🔹 Genera contenuto HTML per la nuova riga ===============================
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>
`;
// 🔹 Inserisce la nuova riga nella tabella HTML ============================
table.appendChild(newRow);
// 🔹 Chiude il dialog di inserimento =======================================
window.closeProjectDialog();
// 🔹 Log attività locale ===================================================
logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
// 💼 Crea la cartella del progetto sul server ==============================
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}`);
console.warn("Errore cartella:", data.error);
}
})
.catch(error => {
logActivity("❌ Errore rete creazione cartella progetto.");
console.error("Errore fetch:", error);
});
// 💾 Cancella cartella del progetto sul server =============================
window.deleteProject = function (title) {
console.log("🧪 deleteProject chiamata con titolo:", title);
logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`);
alert("🔧 Tentativo eliminazione progetto: " + title);
if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) {
console.log("🛑 Eliminazione annullata da utente");
return;
}
console.log("🟡 Invio richiesta DELETE per:", title);
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()) // 📥 prendi testo grezzo, NON .json()
.then(text => {
console.log("📨 Risposta grezza dal server:", 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 (err) {
alert("⚠️ Errore parsing JSON.");
console.error("❌ Risposta non JSON:", text);
logActivity("❌ Risposta non JSON durante eliminazione.");
}
})
.catch(err => {
alert("Errore rete durante eliminazione.");
console.error("🌐 Errore fetch:", err);
logActivity("❌ Errore rete durante eliminazione progetto.");
});
}; // ⬅️ ECCOLA QUI: questa mancava
// 💾 SEZIONE: Invio al server per salvataggio JSON =========================
const payload = {
title: title,
notes: 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) {
alert("⚠️ Errore salvataggio su server: " + data.error);
logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
} else {
logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
}
})
.catch((err) => {
alert("❌ Errore rete salvataggio progetto.");
console.error("Errore invio progetto:", err);
logActivity("❌ Errore rete durante salvataggio progetto.");
});
};
window.openProjectDialog = function () {
document.getElementById("newProjectDialog").style.display = "block";
};
window.closeProjectDialog = function () {
document.getElementById("newProjectDialog").style.display = "none";
};
// 📥 Carica prompt.txt
window.loadPrompt = function () {
fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt')
.then(response => {
if (!response.ok) throw new Error('Errore nel caricamento del file');
return response.json();
})
.then(data => {
if (data.status === "ok") {
document.getElementById("promptArea").value = data.content;
logActivity("📥 Caricato prompt.txt nella textarea.");
} else {
alert("Errore: " + data.error);
logActivity("❌ Errore nel caricamento: " + data.error);
}
})
.catch(error => {
alert("Errore nel caricamento: " + error);
logActivity("❌ Errore nel caricamento di prompt.txt.");
});
};
// 💾 Salva 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(response => {
if (!response.ok) throw new Error('Errore nel salvataggio');
return response.text();
})
.then(msg => {
logActivity("💾 Salvato prompt.txt dal form.");
alert("Prompt salvato con successo.");
})
.catch(error => {
alert("Errore nel salvataggio: " + error);
logActivity("❌ Errore nel salvataggio di prompt.txt.");
});
};
// 💾 Salva RISPOSTA GPT IN FILE
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: subfolder,
filename: filename,
content: content
})
})
.then(response => response.json())
.then(data => {
if (data.status === "ok") {
document.getElementById("gpt-response-area").value = data.content;
logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
alert("File salvato con successo in:" + data.path);
} else {
alert("Errore: " + data.error);
logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
}
})
.catch(error => {
console.error("❌ Errore:", error);
alert("Errore durante il salvataggio.");
});
};
// 📂 Carica File Salvato in Textarea GPT
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(res => res.json())
.then(data => {
if (data.status === "ok") {
document.getElementById("gpt-response-area").value = data.content;
logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
} else {
alert("Errore: " + data.error);
logActivity(`❌ Errore nel caricamento di ${filename}: ${data.error}`);
}
})
.catch(err => {
console.error("Errore:", err);
alert("Errore durante il caricamento del file.");
});
};
// 🚀 ========= Carica automaticamente tutti i progetti salvati ================
// 🚀 ========= Carica automaticamente tutti i progetti salvati ================
window.loadAllProjects = function () {
fetch('/dashboard/api/read_all_projects.php')
.then(response => response.json())
.then(data => {
if (!Array.isArray(data)) {
logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
return;
}
const table = document.getElementById("projectRows");
table.innerHTML = ''; // Pulisce la tabella prima di caricare
data.forEach(project => {
const row = document.createElement("tr");
row.innerHTML = `
<td style="padding:0.5rem; border:1px solid #ccc;">${project.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;">${project.date}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">${project.notes || '–'}</td>
<td style="padding:0.5rem; border:1px solid #ccc;">
<button onclick="analyzeProjectWithGPT('${project.title}', \`${project.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
<button onclick="deleteProject('${project.title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
</td>
`;
table.appendChild(row);
logActivity(`📌 Caricato progetto: <strong>${project.title}</strong>`);
});
})
.catch(err => {
console.error("Errore nel caricamento progetti:", err);
alert("Errore nel caricamento dei progetti.");
logActivity("❌ Errore nel caricamento progetti.");
});
};
// ✅ Al caricamento pagina: esegue tutte le funzioni necessarie
window.addEventListener("load", function () {
loadAllProjects();
// ✅ Recupera API Key da localStorage (se esiste)
const savedKey = localStorage.getItem("openai_api_key");
if (savedKey) {
document.getElementById("apiKeyInput").value = savedKey;
logActivity("🔐 API Key caricata dal browser.");
}
// ✅ Salva la chiave ogni volta che viene modificata
document.getElementById("apiKeyInput").addEventListener("input", function () {
localStorage.setItem("openai_api_key", this.value.trim());
logActivity("💾 API Key aggiornata nel browser.");
});
});
// 🎯 Analizza progetto con GPT
window.analyzeProjectWithGPT = async function (title, notes) {
console.log("🚀 Analisi GPT avviata per:", title, "con note:", notes);
try {
const model = "gpt-4o-2024-05-13";
const apiKey = document.getElementById("api-key").value.trim();
console.log("🔑 Chiave API letta:", apiKey ? "(presente)" : "(vuota)");
if (!apiKey) {
alert("❌ Inserisci prima una API key valida!");
return;
}
const prompt = `Titolo: ${title}\nNote: ${notes}`;
console.log("📌 Prompt costruito:", prompt);
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }] })
});
console.log("📡 Chiamata fetch completata. HTTP status:", response.status);
const result = await response.json();
console.log("📥 Risposta JSON da OpenAI:", result);
if (result.error) {
throw new Error(result.error.message);
}
const reply = result.choices?.[0]?.message?.content;
console.log("✅ Contenuto risposta GPT:", reply);
document.getElementById("response").value = reply;
} catch (err) {
console.error("❌ Errore completo GPT:", err);
alert("Errore durante la richiesta a GPT:\n" + err.message);
}
};
// 🧠 Toggle per mostrare/nascondere istruzioni sysadmin
window.toggleSysNote = function () {
const noteBox = document.getElementById("sysNote");
if (noteBox) {
noteBox.style.display = (noteBox.style.display === "none") ? "block" : "none";
}
};
// 📂 IMPORTA FILES DA SERVER =================================================
mw.loader.using('mediawiki.util', function () {
$(document).ready(function () {
console.log("✅ CommonDashboard.js caricato con successo!");
// 🧱 Inizializza il modulo di importazione semplificata dei file server
window.setupImportaFileSemplificato();
});
});
// ===================================================================
// 📁 IMPORTA FILE (SEMPLIFICATA)
// ===================================================================
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;
}
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(response => response.text())
.then(data => {
alert("✅ File copiato: " + data);
logAttivita("📁 Copiato da " + source + " a " + dest);
})
.catch(error => {
alert("❌ Errore: " + error);
});
}
document.addEventListener("DOMContentLoaded", function () {
if (typeof setupImportaFileSemplificato === 'function') {
setupImportaFileSemplificato();
}
});
// ===================================================================
// 📘 REGISTRO ATTIVITÀ
// ===================================================================
window.logActivity = function (messaggio) {
const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
if (!contenitore) return;
const ora = new Date().toLocaleTimeString("it-IT");
const entry = document.createElement("div");
entry.innerHTML = '<span style="color:gray;">[' + ora + ']</span> ' + messaggio;
contenitore.prepend(entry);
};
window.clearActivityLog = function () {
const contenitore = document.getElementById("activityLogContent");
if (contenitore) {
contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
logActivity("✔ Log svuotato manualmente.");
}
};
// ===================================================================
// 📂 IMPORTA FILES DA SERVER - AVVIO DOPO DEFINIZIONE FUNZIONI
// ===================================================================
mw.loader.using('mediawiki.util', function () {
$(document).ready(function () {
console.log("✅ CommonDashboard.js caricato con successo!");
setupImportaFileSemplificato();
});
});
*/