MediaWiki:CommonDashboard.js: differenze tra le versioni
Nessun oggetto della modifica |
Nessun oggetto della modifica |
||
| Riga 330: | Riga 330: | ||
} | } | ||
}; | }; | ||
// === ChatGPT plus (solo UI) === | |||
(function(){ | |||
const $ = s => document.querySelector(s); | |||
const fileInput = $('#mpChatFile'); | |||
const drop = $('#mpChatDrop'); | |||
const filesBox = $('#mpChatFiles'); | |||
const promptEl = $('#mpChatPrompt'); | |||
const sendBtn = $('#mpChatSend'); | |||
const answerBox = $('#mpChatAnswer'); | |||
const clearBtn = $('#mpChatClear'); | |||
const copyBtn = $('#mpChatCopy'); | |||
if (!fileInput || !drop || !filesBox || !promptEl || !sendBtn || !answerBox) return; | |||
let attached = []; | |||
function renderFiles(){ | |||
filesBox.innerHTML = attached.map(n => ( | |||
`<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>` | |||
)).join(''); | |||
} | |||
function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); } | |||
fileInput.addEventListener('change', () => { | |||
if (fileInput.files?.length) addFiles(fileInput.files); | |||
fileInput.value = ''; | |||
}); | |||
['dragenter','dragover','dragleave','drop'].forEach(evt=>{ | |||
drop.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); }); | |||
}); | |||
drop.addEventListener('drop', e => { | |||
const dt = e.dataTransfer; | |||
if (dt?.files?.length) addFiles(dt.files); | |||
}); | |||
sendBtn.addEventListener('click', () => { | |||
const q = (promptEl.value||'').trim(); | |||
if (!q) { answerBox.textContent = 'Scrivi la domanda nel box sopra.'; return; } | |||
answerBox.textContent = | |||
'✅ Pannello ChatGPT plus pronto.\n\n' + | |||
'• Domanda:\n' + q + '\n\n' + | |||
'• Allegati (solo elenco, non inviati):\n' + (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)'); | |||
}); | |||
clearBtn?.addEventListener('click', () => { answerBox.textContent = ''; }); | |||
copyBtn?.addEventListener('click', async () => { | |||
const txt = answerBox.textContent || ''; | |||
if (!txt.trim()) return; | |||
try { await navigator.clipboard.writeText(txt); copyBtn.textContent = 'Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); } | |||
catch { alert('Impossibile copiare negli appunti.'); } | |||
}); | |||
})(); | |||
Versione delle 16:26, 6 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.");
}
};
// === ChatGPT plus (solo UI) ===
(function(){
const $ = s => document.querySelector(s);
const fileInput = $('#mpChatFile');
const drop = $('#mpChatDrop');
const filesBox = $('#mpChatFiles');
const promptEl = $('#mpChatPrompt');
const sendBtn = $('#mpChatSend');
const answerBox = $('#mpChatAnswer');
const clearBtn = $('#mpChatClear');
const copyBtn = $('#mpChatCopy');
if (!fileInput || !drop || !filesBox || !promptEl || !sendBtn || !answerBox) return;
let attached = [];
function renderFiles(){
filesBox.innerHTML = attached.map(n => (
`<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>`
)).join('');
}
function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); }
fileInput.addEventListener('change', () => {
if (fileInput.files?.length) addFiles(fileInput.files);
fileInput.value = '';
});
['dragenter','dragover','dragleave','drop'].forEach(evt=>{
drop.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); });
});
drop.addEventListener('drop', e => {
const dt = e.dataTransfer;
if (dt?.files?.length) addFiles(dt.files);
});
sendBtn.addEventListener('click', () => {
const q = (promptEl.value||'').trim();
if (!q) { answerBox.textContent = 'Scrivi la domanda nel box sopra.'; return; }
answerBox.textContent =
'✅ Pannello ChatGPT plus pronto.\n\n' +
'• Domanda:\n' + q + '\n\n' +
'• Allegati (solo elenco, non inviati):\n' + (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)');
});
clearBtn?.addEventListener('click', () => { answerBox.textContent = ''; });
copyBtn?.addEventListener('click', async () => {
const txt = answerBox.textContent || '';
if (!txt.trim()) return;
try { await navigator.clipboard.writeText(txt); copyBtn.textContent = 'Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); }
catch { alert('Impossibile copiare negli appunti.'); }
});
})();