MediaWiki:CommonDashboard.js: differenze tra le versioni
Nessun oggetto della modifica |
Nessun oggetto della modifica |
||
| Riga 1: | Riga 1: | ||
// ============================================ | // ============================================ | ||
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client) | // 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client) | ||
// Pulito e coerente con "Gestione Progetti" (filesystem reale) | |||
// ============================================ | // ============================================ | ||
// | // ──────────────────────────────────────────── | ||
// 🧭 UTILITÀ GENERALI | |||
// ──────────────────────────────────────────── | |||
window.toggleDashboardBox = function (id) { | window.toggleDashboardBox = function (id) { | ||
const box = document.getElementById(id); | const box = document.getElementById(id); | ||
| Riga 9: | Riga 12: | ||
}; | }; | ||
// ⚙️ CONNESSIONE API (via proxy server) | // Mini-log visuale in pagina | ||
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."); | |||
} | |||
}; | |||
// Log persistente lato server (Basic Auth inclusa) | |||
function dashLog(msg, lvl='INFO', mod='Dashboard', act='') { | |||
const body = new URLSearchParams({ m: msg, lvl, mod, act }); | |||
return fetch('/dashboard/api/log.php', { | |||
method: 'POST', | |||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | |||
body, | |||
credentials: 'include' | |||
}).catch(e => console.error('dashLog fail:', e)); | |||
} | |||
function logInfo (m, extra={}) { return dashLog(m, 'INFO', extra.mod||'Dashboard', extra.act||''); } | |||
function logWarn (m, extra={}) { return dashLog(m, 'WARNING', extra.mod||'Dashboard', extra.act||''); } | |||
function logError(m, extra={}) { return dashLog(m, 'ERROR', extra.mod||'Dashboard', extra.act||''); } | |||
// ──────────────────────────────────────────── | |||
/* ⚙️ CONNESSIONE API (via proxy server) */ | |||
// ──────────────────────────────────────────── | |||
window.testAPIConnection = async function () { | window.testAPIConnection = async function () { | ||
const prompt = (document.getElementById("test-prompt")?.value || "").trim(); | const prompt = (document.getElementById("test-prompt")?.value || "").trim(); | ||
const output = document.getElementById("api-result"); | const output = document.getElementById("api-result"); | ||
const model = | const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13"; | ||
if (!prompt) { | if (!prompt) { output.innerText = "⚠️ Inserisci un prompt di test."; return; } | ||
output.innerText = "⏳ Contatto il proxy sul server..."; | output.innerText = "⏳ Contatto il proxy sul server..."; | ||
| Riga 31: | Riga 63: | ||
body: JSON.stringify({ prompt, model }) | body: JSON.stringify({ prompt, model }) | ||
}); | }); | ||
const data = await res.json(); | const data = await res.json(); | ||
| Riga 47: | Riga 78: | ||
}; | }; | ||
// | // ──────────────────────────────────────────── | ||
window.analyzeProjectWithGPT = async function ( | /* 🧠 ANALISI PROGETTO (render pulito in card) */ | ||
// ──────────────────────────────────────────── | |||
// Renderer stile ChatGPT per #gptResponse | |||
function renderGpt(text) { | |||
const box = document.getElementById('gptResponse'); | |||
if (!box) return; | |||
if (!text) { box.innerHTML = '<em style="opacity:.7">Nessuna risposta</em>'; return; } | |||
let html = (text || '').replace(/\r\n/g, '\n') | |||
.replace(/^\s*#{3}\s?(.*)$/gm, '<h3 style="font-size:18px;margin:14px 0 6px;">$1</h3>') | |||
.replace(/^\s*#{2}\s?(.*)$/gm, '<h2 style="font-size:20px;margin:16px 0 8px;">$1</h2>') | |||
.replace(/^\s*#\s?(.*)$/gm, '<h1 style="font-size:22px;margin:18px 0 10px;">$1</h1>') | |||
.replace(/^\s*-\s+(.*)$/gm, '<li>$1</li>'); | |||
html = html.replace(/(?:<li>.*<\/li>\n?)+/gs, m => `<ul style="margin:8px 0 14px 22px;">${m}</ul>`); | |||
html = html.split('\n').map(line => { | |||
if (/^<h\d|^<ul|^<li|^<\/ul>/.test(line)) return line; | |||
if (line.trim()==='') return ''; | |||
return `<p style="margin:8px 0;">${line}</p>`; | |||
}).join(''); | |||
box.innerHTML = html; | |||
} | |||
// Costruisce prompt dal form | |||
function buildPromptForGPT() { | |||
const title = (document.getElementById('newProjectTitle')?.value || '').trim(); | |||
const notes = (document.getElementById('newProjectNotes')?.value || '').trim(); | |||
const goal = (document.getElementById('p_goal')?.value || '').trim(); | |||
const audience = (document.getElementById('p_audience')?.value || '').trim(); | |||
const deliverable = (document.getElementById('p_deliverable')?.value || '').trim(); | |||
const constraints = (document.getElementById('p_constraints')?.value || '').trim(); | |||
const out = []; | |||
out.push(`You are a senior editor and project designer. Provide a clear, actionable plan.`); | |||
if (title) out.push(`\n# Title\n${title}`); | |||
if (notes) out.push(`\n# Notes\n${notes}`); | |||
if (goal) out.push(`\n# Goal\n${goal}`); | |||
if (audience) out.push(`\n# Audience\n${audience}`); | |||
if (deliverable) out.push(`\n# Deliverables\n${deliverable}`); | |||
if (constraints) out.push(`\n# Constraints\n${constraints}`); | |||
out.push(`\n# Output format | |||
- Executive Summary | |||
- Strengths & Risks | |||
- Step-by-step Plan (milestones) | |||
- Resources & Budget hints | |||
- Metrics of success`); | |||
return out.join('\n'); | |||
} | |||
// Bottone "Analizza con GPT" (via proxy server). Se vuoi la chiamata reale, basta usare questo handler. | |||
window.analyzeProjectWithGPT = async function () { | |||
const btn = document.getElementById('btnAnalyze'); | |||
const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13"; | |||
const prompt = buildPromptForGPT(); | |||
btn && (btn.disabled = true, btn.textContent = 'Analizzo…'); | |||
logActivity('🤖 Analisi GPT via proxy…'); | |||
try { | try { | ||
const res = await fetch("/dashboard/api/openai_project_gpt.php", { | const res = await fetch("/dashboard/api/openai_project_gpt.php", { | ||
method: "POST", | method: "POST", | ||
| Riga 61: | Riga 144: | ||
body: JSON.stringify({ prompt, model }) | body: JSON.stringify({ prompt, model }) | ||
}); | }); | ||
const data = await res.json(); | |||
if (data.status === "ok" && data.result) { | if (data.status === "ok" && data.result) { | ||
renderGpt(data.result); | |||
logActivity( | logActivity('✅ Analisi GPT completata'); | ||
logInfo('GPT analysis done', { mod:'GPT', act:'analyze' }); | |||
} else { | } else { | ||
renderGpt('❌ Errore GPT: ' + (data.error || 'Risposta vuota')); | |||
logError('GPT analysis failed', { mod:'GPT', act:'analyze' }); | |||
} | } | ||
} catch (err) { | } catch (err) { | ||
renderGpt('❌ Errore di rete: ' + err.message); | |||
logError('GPT network error', { mod:'GPT', act:'analyze' }); | |||
} finally { | |||
} | btn && (btn.disabled = false, btn.textContent = 'Analizza con GPT'); | ||
} | } | ||
}; | }; | ||
// | // ──────────────────────────────────────────── | ||
/* 📁 PROMPT / FILE (utility esistenti) */ | |||
// ──────────────────────────────────────────── | |||
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", { | ||
credentials: "include" | credentials: "include" | ||
}) | }) | ||
.then(r => r.json()) | |||
.then(data => { | |||
if (data.status === "ok") { | |||
const el = document.getElementById("promptArea"); | |||
if (el) el.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 () { | 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", | ||
| Riga 160: | Riga 194: | ||
body: "text=" + encodeURIComponent(content) | 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 / Carica files per GPT | ||
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) { alert("Nome file o contenuto mancante."); return; } | |||
if (!filename || !content) { | |||
fetch("/dashboard/api/write_file.php", { | fetch("/dashboard/api/write_file.php", { | ||
| Riga 192: | Riga 213: | ||
body: JSON.stringify({ projectName: project, subfolder, filename, content }) | body: JSON.stringify({ projectName: project, subfolder, filename, content }) | ||
}) | }) | ||
.then(r => r.json()) | |||
.then(data => { | |||
if (data.status === "ok") { | |||
logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`); | |||
alert("File salvato: " + (data.path || filename)); | |||
} else { | |||
alert("Errore: " + data.error); | |||
logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`); | |||
} | |||
}) | |||
.catch(e => { alert("Errore durante il salvataggio."); console.error(e); }); | |||
}; | }; | ||
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) { 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") { | |||
const ta = document.getElementById("gpt-response-area"); | |||
fetch( | if (ta) ta.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 => { alert("Errore durante il caricamento del file."); console.error(e); }); | |||
}; | }; | ||
// | // ──────────────────────────────────────────── | ||
/* 🧪 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 { return new Function(src)(); } | |||
catch (e) { alert('Errore nel codice:\n' + e.message); } | |||
}; | }; | ||
// ──────────────────────────────────────────── | |||
/* ======================= | /* ======================= | ||
* | * 📂 GESTIONE PROGETTI (REALE) | ||
* ======================= */ | * ======================= */ | ||
// ──────────────────────────────────────────── | |||
const API = { | const API = { | ||
list: '/dashboard/api/project_list.php', | list: '/dashboard/api/project_list.php', | ||
| Riga 285: | Riga 270: | ||
}; | }; | ||
let currentProject = null; | let currentProject = null; | ||
// Carica lista | |||
async function loadAllProjects() { | async function loadAllProjects() { | ||
try { | try { | ||
const r = await fetch( | const r = await fetch(API.list, { credentials:'include', cache:'no-store' }); | ||
const txt = await r.text(); | const txt = await r.text(); | ||
let j; | let j; try { j = JSON.parse(txt); } catch { throw new Error('Risposta non-JSON dalla lista progetti'); } | ||
if (!j.ok) throw new Error(j.error || 'Lista progetti fallita'); | if (!j.ok) throw new Error(j.error || 'Lista progetti fallita'); | ||
renderProjects(j.projects || []); | renderProjects(j.projects || []); | ||
| Riga 307: | Riga 286: | ||
} | } | ||
// Disegna lista | |||
function renderProjects(projects) { | function renderProjects(projects) { | ||
const ul = document.getElementById('projectsList'); | const ul = document.getElementById('projectsList'); | ||
if (!ul) return; | |||
ul.innerHTML = ''; | ul.innerHTML = ''; | ||
if (!projects.length) { | |||
ul.innerHTML = '<li style="color:#777;">Nessun progetto trovato.</li>'; | |||
return; | |||
} | |||
projects.forEach(p => { | projects.forEach(p => { | ||
| Riga 319: | Riga 304: | ||
li.style.margin = '6px 0'; | li.style.margin = '6px 0'; | ||
const name = p.name; | const label = document.createElement('span'); | ||
label.textContent = p.name; | |||
label.style.fontWeight = (p.name === currentProject ? '700' : '500'); | |||
const btnOpen = document.createElement('button'); | const btnOpen = document.createElement('button'); | ||
btnOpen.textContent = 'Apri'; | btnOpen.textContent = 'Apri'; | ||
btnOpen.onclick = () => { selectProject(name); }; | btnOpen.onclick = () => { selectProject(p.name); }; | ||
const btnZip = document.createElement('button'); | const btnZip = document.createElement('button'); | ||
btnZip.textContent = 'ZIP'; | btnZip.textContent = 'ZIP'; | ||
btnZip.title = 'Crea backup zip'; | btnZip.title = 'Crea backup zip'; | ||
btnZip.onclick = () => backupProject(name); | btnZip.onclick = () => backupProject(p.name); | ||
const btnDel = document.createElement('button'); | const btnDel = document.createElement('button'); | ||
btnDel.textContent = '🗑️'; | btnDel.textContent = '🗑️'; | ||
btnDel.title = 'Sposta nel cestino (soft delete)'; | btnDel.title = 'Sposta nel cestino (soft delete)'; | ||
btnDel.onclick = () => deleteProject( | btnDel.onclick = () => deleteProject(p.name); | ||
li.append(label, btnOpen, btnZip, btnDel); | li.append(label, btnOpen, btnZip, btnDel); | ||
| Riga 344: | Riga 327: | ||
} | } | ||
function selectProject(name) { | function selectProject(name) { | ||
currentProject = name; | currentProject = name; | ||
logInfo('Project selected', { mod:'Progetti', act:'select' }); | logInfo('Project selected', { mod:'Progetti', act:'select' }); | ||
loadAllProjects(); | loadAllProjects(); | ||
} | } | ||
// Crea | // Crea | ||
async function createProject() { | async function createProject() { | ||
const input = document.getElementById('newProjectName'); | const input = document.getElementById('newProjectName'); | ||
const name = (input.value || '').trim(); | const name = (input?.value || '').trim(); | ||
if (!name) return alert('Inserisci un nome progetto'); | if (!name) return alert('Inserisci un nome progetto'); | ||
try { | try { | ||
const r = await fetch(API.create, { | |||
const r = await fetch(API.create, { method:'POST', | method:'POST', | ||
credentials:'include', | |||
headers:{'Content-Type':'application/x-www-form-urlencoded'}, | |||
body: new URLSearchParams({ name }) | |||
}); | |||
const j = await r.json(); | const j = await r.json(); | ||
if (!j.ok) throw new Error(j.error || 'create failed'); | if (!j.ok) throw new Error(j.error || 'create failed'); | ||
| Riga 374: | Riga 359: | ||
} | } | ||
// | // Elimina (soft) | ||
async function deleteProject(name) { | async function deleteProject(name) { | ||
if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return; | if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return; | ||
try { | try { | ||
const r = await fetch(API.del, { | |||
const r = await fetch(API.del, { method:'POST', | method:'POST', | ||
credentials:'include', | |||
headers:{'Content-Type':'application/x-www-form-urlencoded'}, | |||
body: new URLSearchParams({ name }) | |||
}); | |||
const j = await r.json(); | const j = await r.json(); | ||
if (!j.ok) throw new Error(j.error || 'delete failed'); | if (!j.ok) throw new Error(j.error || 'delete failed'); | ||
| Riga 392: | Riga 381: | ||
} | } | ||
// Backup | // Backup | ||
async function backupProject(name) { | async function backupProject(name) { | ||
try { | try { | ||
const r = await fetch(API.backup, { | |||
const r = await fetch(API.backup, { method:'POST', | method:'POST', | ||
credentials:'include', | |||
headers:{'Content-Type':'application/x-www-form-urlencoded'}, | |||
body: new URLSearchParams({ name }) | |||
}); | |||
const j = await r.json(); | const j = await r.json(); | ||
if (!j.ok) throw new Error(j.error || 'backup failed'); | if (!j.ok) throw new Error(j.error || 'backup failed'); | ||
| Riga 412: | Riga 405: | ||
const btnCreate = document.getElementById('btnCreateProject'); | const btnCreate = document.getElementById('btnCreateProject'); | ||
if (btnCreate) btnCreate.addEventListener('click', createProject); | if (btnCreate) btnCreate.addEventListener('click', createProject); | ||
const | const analyzeBtn = document.getElementById('btnAnalyze'); | ||
if (analyzeBtn) analyzeBtn.addEventListener('click', window.analyzeProjectWithGPT); | |||
loadAllProjects(); // subito all’avvio | |||
}); | }); | ||
// | // ──────────────────────────────────────────── | ||
// FINE FILE | |||
// ──────────────────────────────────────────── | |||
// | |||
Versione delle 17:49, 14 set 2025
// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// Pulito e coerente con "Gestione Progetti" (filesystem reale)
// ============================================
// ────────────────────────────────────────────
// 🧭 UTILITÀ GENERALI
// ────────────────────────────────────────────
window.toggleDashboardBox = function (id) {
const box = document.getElementById(id);
if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};
// Mini-log visuale in pagina
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.");
}
};
// Log persistente lato server (Basic Auth inclusa)
function dashLog(msg, lvl='INFO', mod='Dashboard', act='') {
const body = new URLSearchParams({ m: msg, lvl, mod, act });
return fetch('/dashboard/api/log.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
credentials: 'include'
}).catch(e => console.error('dashLog fail:', e));
}
function logInfo (m, extra={}) { return dashLog(m, 'INFO', extra.mod||'Dashboard', extra.act||''); }
function logWarn (m, extra={}) { return dashLog(m, 'WARNING', extra.mod||'Dashboard', extra.act||''); }
function logError(m, extra={}) { return dashLog(m, 'ERROR', extra.mod||'Dashboard', extra.act||''); }
// ────────────────────────────────────────────
/* ⚙️ 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}`);
}
};
// ────────────────────────────────────────────
/* 🧠 ANALISI PROGETTO (render pulito in card) */
// ────────────────────────────────────────────
// Renderer stile ChatGPT per #gptResponse
function renderGpt(text) {
const box = document.getElementById('gptResponse');
if (!box) return;
if (!text) { box.innerHTML = '<em style="opacity:.7">Nessuna risposta</em>'; return; }
let html = (text || '').replace(/\r\n/g, '\n')
.replace(/^\s*#{3}\s?(.*)$/gm, '<h3 style="font-size:18px;margin:14px 0 6px;">$1</h3>')
.replace(/^\s*#{2}\s?(.*)$/gm, '<h2 style="font-size:20px;margin:16px 0 8px;">$1</h2>')
.replace(/^\s*#\s?(.*)$/gm, '<h1 style="font-size:22px;margin:18px 0 10px;">$1</h1>')
.replace(/^\s*-\s+(.*)$/gm, '<li>$1</li>');
html = html.replace(/(?:<li>.*<\/li>\n?)+/gs, m => `<ul style="margin:8px 0 14px 22px;">${m}</ul>`);
html = html.split('\n').map(line => {
if (/^<h\d|^<ul|^<li|^<\/ul>/.test(line)) return line;
if (line.trim()==='') return '';
return `<p style="margin:8px 0;">${line}</p>`;
}).join('');
box.innerHTML = html;
}
// Costruisce prompt dal form
function buildPromptForGPT() {
const title = (document.getElementById('newProjectTitle')?.value || '').trim();
const notes = (document.getElementById('newProjectNotes')?.value || '').trim();
const goal = (document.getElementById('p_goal')?.value || '').trim();
const audience = (document.getElementById('p_audience')?.value || '').trim();
const deliverable = (document.getElementById('p_deliverable')?.value || '').trim();
const constraints = (document.getElementById('p_constraints')?.value || '').trim();
const out = [];
out.push(`You are a senior editor and project designer. Provide a clear, actionable plan.`);
if (title) out.push(`\n# Title\n${title}`);
if (notes) out.push(`\n# Notes\n${notes}`);
if (goal) out.push(`\n# Goal\n${goal}`);
if (audience) out.push(`\n# Audience\n${audience}`);
if (deliverable) out.push(`\n# Deliverables\n${deliverable}`);
if (constraints) out.push(`\n# Constraints\n${constraints}`);
out.push(`\n# Output format
- Executive Summary
- Strengths & Risks
- Step-by-step Plan (milestones)
- Resources & Budget hints
- Metrics of success`);
return out.join('\n');
}
// Bottone "Analizza con GPT" (via proxy server). Se vuoi la chiamata reale, basta usare questo handler.
window.analyzeProjectWithGPT = async function () {
const btn = document.getElementById('btnAnalyze');
const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
const prompt = buildPromptForGPT();
btn && (btn.disabled = true, btn.textContent = 'Analizzo…');
logActivity('🤖 Analisi GPT via proxy…');
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) {
renderGpt(data.result);
logActivity('✅ Analisi GPT completata');
logInfo('GPT analysis done', { mod:'GPT', act:'analyze' });
} else {
renderGpt('❌ Errore GPT: ' + (data.error || 'Risposta vuota'));
logError('GPT analysis failed', { mod:'GPT', act:'analyze' });
}
} catch (err) {
renderGpt('❌ Errore di rete: ' + err.message);
logError('GPT network error', { mod:'GPT', act:'analyze' });
} finally {
btn && (btn.disabled = false, btn.textContent = 'Analizza con GPT');
}
};
// ────────────────────────────────────────────
/* 📁 PROMPT / FILE (utility esistenti) */
// ────────────────────────────────────────────
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") {
const el = document.getElementById("promptArea");
if (el) el.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 / Carica files per GPT
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("Nome file o contenuto mancante."); 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") {
logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
alert("File salvato: " + (data.path || filename));
} else {
alert("Errore: " + data.error);
logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
}
})
.catch(e => { alert("Errore durante il salvataggio."); console.error(e); });
};
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") {
const ta = document.getElementById("gpt-response-area");
if (ta) ta.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 => { alert("Errore durante il caricamento del file."); console.error(e); });
};
// ────────────────────────────────────────────
/* 🧪 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 { return new Function(src)(); }
catch (e) { alert('Errore nel codice:\n' + e.message); }
};
// ────────────────────────────────────────────
/* =======================
* 📂 GESTIONE PROGETTI (REALE)
* ======================= */
// ────────────────────────────────────────────
const API = {
list: '/dashboard/api/project_list.php',
create: '/dashboard/api/project_create.php',
del: '/dashboard/api/project_delete.php',
backup: '/dashboard/api/project_backup.php'
};
let currentProject = null;
// Carica lista
async function loadAllProjects() {
try {
const r = await fetch(API.list, { credentials:'include', cache:'no-store' });
const txt = await r.text();
let j; try { j = JSON.parse(txt); } catch { throw new Error('Risposta non-JSON dalla lista progetti'); }
if (!j.ok) throw new Error(j.error || 'Lista progetti fallita');
renderProjects(j.projects || []);
} catch (e) {
console.error('project_list error:', e);
alert('Errore nel caricamento dei progetti: ' + e.message);
}
}
// Disegna lista
function renderProjects(projects) {
const ul = document.getElementById('projectsList');
if (!ul) return;
ul.innerHTML = '';
if (!projects.length) {
ul.innerHTML = '<li style="color:#777;">Nessun progetto trovato.</li>';
return;
}
projects.forEach(p => {
const li = document.createElement('li');
li.style.display = 'flex';
li.style.alignItems = 'center';
li.style.gap = '8px';
li.style.margin = '6px 0';
const label = document.createElement('span');
label.textContent = p.name;
label.style.fontWeight = (p.name === currentProject ? '700' : '500');
const btnOpen = document.createElement('button');
btnOpen.textContent = 'Apri';
btnOpen.onclick = () => { selectProject(p.name); };
const btnZip = document.createElement('button');
btnZip.textContent = 'ZIP';
btnZip.title = 'Crea backup zip';
btnZip.onclick = () => backupProject(p.name);
const btnDel = document.createElement('button');
btnDel.textContent = '🗑️';
btnDel.title = 'Sposta nel cestino (soft delete)';
btnDel.onclick = () => deleteProject(p.name);
li.append(label, btnOpen, btnZip, btnDel);
ul.appendChild(li);
});
}
function selectProject(name) {
currentProject = name;
logInfo('Project selected', { mod:'Progetti', act:'select' });
loadAllProjects();
}
// Crea
async function createProject() {
const input = document.getElementById('newProjectName');
const name = (input?.value || '').trim();
if (!name) return alert('Inserisci un nome progetto');
try {
const r = await fetch(API.create, {
method:'POST',
credentials:'include',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body: new URLSearchParams({ name })
});
const j = await r.json();
if (!j.ok) throw new Error(j.error || 'create failed');
logInfo('Project created', { mod:'Progetti', act:'create' });
input.value = '';
await loadAllProjects();
selectProject(name);
} catch (e) {
console.error(e);
logError('Project create failed', { mod:'Progetti', act:'create' });
alert('Errore creazione: ' + e.message);
}
}
// Elimina (soft)
async function deleteProject(name) {
if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return;
try {
const r = await fetch(API.del, {
method:'POST',
credentials:'include',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body: new URLSearchParams({ name })
});
const j = await r.json();
if (!j.ok) throw new Error(j.error || 'delete failed');
logWarn('Project moved to trash', { mod:'Progetti', act:'delete' });
if (currentProject === name) currentProject = null;
await loadAllProjects();
} catch (e) {
console.error(e);
logError('Project delete failed', { mod:'Progetti', act:'delete' });
alert('Errore eliminazione: ' + e.message);
}
}
// Backup
async function backupProject(name) {
try {
const r = await fetch(API.backup, {
method:'POST',
credentials:'include',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body: new URLSearchParams({ name })
});
const j = await r.json();
if (!j.ok) throw new Error(j.error || 'backup failed');
logInfo('Project zipped', { mod:'Progetti', act:'backup' });
alert(`Backup creato: ${j.zip}`);
} catch (e) {
console.error(e);
logError('Project backup failed', { mod:'Progetti', act:'backup' });
alert('Errore backup: ' + e.message);
}
}
// Bind UI
document.addEventListener('DOMContentLoaded', () => {
const btnCreate = document.getElementById('btnCreateProject');
if (btnCreate) btnCreate.addEventListener('click', createProject);
const analyzeBtn = document.getElementById('btnAnalyze');
if (analyzeBtn) analyzeBtn.addEventListener('click', window.analyzeProjectWithGPT);
loadAllProjects(); // subito all’avvio
});
// ────────────────────────────────────────────
// FINE FILE
// ────────────────────────────────────────────