MediaWiki:CommonDashboard.js: differenze tra le versioni
Nessun oggetto della modifica |
Nessun oggetto della modifica |
||
| Riga 331: | Riga 331: | ||
}; | }; | ||
// ▶️ Console JS interna (Strumenti di Test) | // ▶️ Console JS interna (Strumenti di Test) | ||
Versione delle 09:51, 7 set 2025
// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// ============================================
// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
const box = document.getElementById(id);
if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};
// ⚙️ CONNESSIONE API (via proxy server)
window.testAPIConnection = async function () {
const prompt = (document.getElementById("test-prompt")?.value || "").trim();
const output = document.getElementById("api-result");
const model =
document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
if (!prompt) {
output.innerText = "⚠️ Inserisci un prompt di test.";
return;
}
output.innerText = "⏳ Contatto il proxy sul server...";
logActivity(`🚀 Test API via proxy – Modello: <strong>${model}</strong>`);
try {
const res = await fetch("/dashboard/api/openai_project_gpt.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ prompt, model })
});
const data = await res.json();
if (data.status === "ok" && data.result) {
output.innerText = "✅ Risposta: " + data.result;
logActivity(`✅ Proxy OK – Modello: <strong>${model}</strong>`);
} else {
output.innerText = "❌ Errore: " + (data.error || "Risposta vuota");
logActivity(`❌ Errore proxy: ${data.error || "risposta vuota"}`);
}
} catch (e) {
output.innerText = "🚫 Errore di rete: " + e.message;
logActivity(`❌ Errore rete: ${e.message}`);
}
};
// 🎯 Analizza progetto con GPT (sempre via proxy)
window.analyzeProjectWithGPT = async function (title, notes) {
try {
const model =
document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
const prompt = `📌 Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci valutazione sintetica e suggerimenti operativi.`;
logActivity(`🤖 Analisi GPT via proxy – <strong>${title}</strong>`);
const res = await fetch("/dashboard/api/openai_project_gpt.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ prompt, model })
});
const data = await res.json();
if (data.status === "ok" && data.result) {
document.getElementById("response").value = data.result;
logActivity(`✅ Analisi completata – <strong>${title}</strong>`);
} else {
alert("Errore GPT: " + (data.error || "Risposta vuota"));
logActivity(`❌ Errore GPT: ${data.error || "risposta vuota"}`);
}
} catch (err) {
console.error("❌ Errore completo GPT:", err);
alert("Errore durante la richiesta a GPT:\n" + err.message);
logActivity(`❌ Errore richiesta GPT: ${err.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");
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>
</td>
`;
table.appendChild(newRow);
window.closeProjectDialog();
logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
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),
credentials: "include"
})
.then((r) => r.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/Salva prompt.txt
window.loadPrompt = function () {
fetch("/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt", {
credentials: "include"
})
.then((r) => r.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((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" },
credentials: "include",
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.");
});
};
// 💾 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" },
credentials: "include",
body: JSON.stringify({ projectName: project, subfolder, filename, content })
})
.then((r) => r.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((e) => {
console.error("❌ Errore:", e);
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)}`,
{ credentials: "include" }
)
.then((r) => r.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((e) => {
console.error("Errore:", e);
alert("Errore durante il caricamento del file.");
});
};
// 🚀 Carica automaticamente i progetti
window.loadAllProjects = function () {
fetch("/dashboard/api/read_all_projects.php", { credentials: "include" })
.then((r) => r.json())
.then((data) => {
if (!Array.isArray(data)) {
logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
return;
}
const table = document.getElementById("projectRows");
table.innerHTML = "";
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>
</td>`;
table.appendChild(row);
logActivity(`📌 Caricato progetto: <strong>${project.title}</strong>`);
});
})
.catch((e) => {
console.error("Errore nel caricamento progetti:", e);
alert("Errore nel caricamento dei progetti.");
logActivity("❌ Errore nel caricamento progetti.");
});
};
// 📂 Importa file dal server (preset directory)
window.importServerFileFromPresetDir = function () {
const baseDir = document.getElementById("baseDirSelect").value;
const fileName = document.getElementById("fileNameInput").value.trim();
const destFolder = document.getElementById("destinationPath").value.trim();
if (!fileName || !destFolder) {
alert("❌ Inserisci sia il nome file che la destinazione.");
return;
}
const fullSourcePath = baseDir + fileName;
fetch("/dashboard/api/copy_file_from_path.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ source: fullSourcePath, destination: destFolder })
})
.then((r) => r.json())
.then((data) => {
if (data.success) {
alert("✅ File copiato: " + (data.path || destFolder));
logActivity(`📁 Copiato: <code>${fullSourcePath}</code> → <strong>${destFolder}</strong>`);
} else {
alert("❌ Errore: " + data.error);
logActivity(`❌ Errore copia file: ${data.error}`);
}
})
.catch((e) => {
alert("Errore di rete: " + e.message);
console.error(e);
});
};
// ✅ Onload
window.addEventListener("load", function () {
loadAllProjects();
});
// 🧾 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.");
}
};
// ▶️ Console JS interna (Strumenti di Test)
window.runTestCode = function () {
const ta = document.getElementById('codeArea');
if (!ta) {
alert('Area di test non trovata (#codeArea).');
return;
}
const src = ta.value || '';
try {
const result = new Function(src)(); // sandbox, meglio di eval
console.log('▶ runTestCode: OK', result);
return result;
} catch (e) {
console.error('▶ runTestCode: errore', e);
alert('Errore nel codice:\n' + e.message);
}
};