Nessun oggetto della modifica
Nessun oggetto della modifica
(3 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1: Riga 1:
// Funzione per aprire e chiudere i box nella dashboard
// ============================================
window.toggleDashboardBox = function(id) {
// 🔧 CommonDashboard.js – versione GPT-4o + lettura file reale
// ============================================
 
// 🔄 Apri/chiudi box
window.toggleDashboardBox = function (id) {
   const box = document.getElementById(id);
   const box = document.getElementById(id);
   if (box) {
   if (box) box.style.display = box.style.display === "block" ? "none" : "block";
    box.style.display = (box.style.display === 'block') ? 'none' : 'block';
  }
};
};


// Funzione per testare connessione API
// ▶️ Test connessione API OpenAI
window.testAPIConnection = async function () {
window.testAPIConnection = async function () {
   const key = document.getElementById('api-key').value.trim();
   const key = document.getElementById('api-key').value.trim();
  const model = document.getElementById('model-select').value;
   const prompt = document.getElementById('test-prompt').value;
   const prompt = document.getElementById('test-prompt').value;
   const output = document.getElementById('api-result');
   const output = document.getElementById('api-result');
  const model = "gpt-4o-2024-05-13";


   if (!key || !prompt) {
   if (!key || !prompt) {
Riga 19: Riga 21:
   }
   }


   output.innerText = '⏳ Attendere...';
   output.innerText = '⏳ Attendere risposta da OpenAI...';
  logActivity(`🚀 Test API avviato – Modello: <strong>${model}</strong>`);


   try {
   try {
Riga 39: Riga 42:
     if (data.choices && data.choices.length > 0) {
     if (data.choices && data.choices.length > 0) {
       output.innerText = "✅ Risposta:\n" + data.choices[0].message.content;
       output.innerText = "✅ Risposta:\n" + data.choices[0].message.content;
       logActivity(`✅ Test API riuscito – Modello: <strong>${model}</strong>`);
       logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
     } else if (data.error) {
     } else if (data.error) {
       output.innerText = "❌ Errore: " + data.error.message;
       output.innerText = "❌ Errore: " + data.error.message;
Riga 48: Riga 51:
   } catch (e) {
   } catch (e) {
     output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
     output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
    logActivity(`❌ Errore di connessione: ${e.message}`);
   }
   }
};
};


// Funzione mock per salvataggio
// 📂 Accesso File Server – Leggi file reale dal server via API PHP
window.saveFileChanges = function() {
document.querySelector('#readFileBtn')?.addEventListener('click', async () => {
   const selectedFile = document.getElementById("file-select").value;
   const filenameInput = document.querySelector('#readFileName');
   const newContent = document.getElementById("file-preview").value;
   const fileContentDiv = document.querySelector('#readFileResult');
   alert("💾 Modifiche salvate per: " + selectedFile + "\n(contenuto simulato)");
  const filename = filenameInput.value.trim();
  logActivity(`💾 File salvato: <strong>${selectedFile}</strong>`);
 
};
   if (!filename) {
    fileContentDiv.innerHTML = '<span style="color:red;">⚠️ Inserisci un nome di file.</span>';
    return;
  }
 
  try {
    const response = await fetch('/wiki/dashboard/api/read_file.php?filename=' + encodeURIComponent(filename));
    const data = await response.json();


// Funzione per anteprima file simulata
    if (data.status === 'success') {
window.loadFilePreview = function(filename) {
      fileContentDiv.innerHTML = `<pre style="background:#f4f4f4;border:1px solid #ccc;padding:8px;max-height:400px;overflow:auto;font-size:14px;">${data.content}</pre>`;
  const contentArea = document.getElementById("file-preview");
      logActivity(`📂 File letto: <strong>${filename}</strong>`);
  const fakeContents = {
    } else {
    "common.css": "/* Contenuto di esempio per common.css */\nbody { background: #fff; }",
      fileContentDiv.innerHTML = `<span style="color:red;">❌ Errore: ${data.message}</span>`;
     "common.js": "// Contenuto JS\nconsole.log('JS attivo');",
      logActivity(`❌ Errore lettura file: ${data.message}`);
    "LocalSettings.php": "<?php\n# Impostazioni locali di MediaWiki\n$wgSitename = 'Masticationpedia';"
    }
   };
  } catch (error) {
  contentArea.value = fakeContents[filename] || "Contenuto non disponibile.";
     fileContentDiv.innerHTML = `<span style="color:red;">❌ Errore di connessione.</span>`;
};
    console.error('Errore JS:', error);
   }
});


// Funzione per aprire popup nuovo progetto
// 📦 Box progetti – apertura dialog
window.openProjectDialog = function () {
window.openProjectDialog = function () {
   document.getElementById("newProjectDialog").style.display = "block";
   document.getElementById("newProjectDialog").style.display = "block";
};
};
// Funzione per chiudere popup nuovo progetto
window.closeProjectDialog = function () {
window.closeProjectDialog = function () {
   document.getElementById("newProjectDialog").style.display = "none";
   document.getElementById("newProjectDialog").style.display = "none";
};
};


// Funzione per aggiungere nuovo progetto
// 📌 Aggiungi nuovo progetto alla tabella
window.addNewProject = function () {
window.addNewProject = function () {
   const title = document.getElementById("newProjectTitle").value.trim();
   const title = document.getElementById("newProjectTitle").value.trim();
Riga 96: Riga 107:
   table.appendChild(newRow);
   table.appendChild(newRow);
   window.closeProjectDialog();
   window.closeProjectDialog();
   logActivity(`📌 Nuovo progetto aggiunto: <strong>${title}</strong> – ${notes}`);
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
};
};


// Mini console per testare codice JS
// 🧪 Testa codice JS in tempo reale
window.runTestCode = function () {
window.runTestCode = function () {
   const code = document.getElementById('codeArea').value;
   const code = document.getElementById('codeArea').value;
Riga 111: Riga 122:
};
};


// Inizializzazione automatica dei comportamenti al caricamento
// 🧾 Registro attività – aggiungi evento
document.addEventListener("DOMContentLoaded", function () {
  const fileSelect = document.getElementById("fileSelect");
  if (fileSelect) {
    fileSelect.addEventListener("change", function () {
      const selected = this.value;
      window.loadFilePreview(selected);
    });
  }
});
 
// Funzione per scrivere nel registro attività
window.logActivity = function (messaggio) {
window.logActivity = function (messaggio) {
   const contenitore = document.getElementById("activityLogContent");
   const contenitore = document.getElementById("activityLogContent");
Riga 131: Riga 131:
   paragrafo.innerHTML = `<strong>[${ora}]</strong> ${messaggio}`;
   paragrafo.innerHTML = `<strong>[${ora}]</strong> ${messaggio}`;
   contenitore.appendChild(paragrafo);
   contenitore.appendChild(paragrafo);
  // Scorrimento automatico verso il basso
   contenitore.scrollTop = contenitore.scrollHeight;
   contenitore.scrollTop = contenitore.scrollHeight;
};
};


// Funzione per pulire il registro
// 🧹 Svuota log
window.clearActivityLog = function () {
window.clearActivityLog = function () {
   const contenitore = document.getElementById("activityLogContent");
   const contenitore = document.getElementById("activityLogContent");
Riga 143: Riga 141:
};
};


// ===================== CONNESSIONE API ==========================
// 🪄 Inizializza selettore file (box simulato)
function testAPIConnection() {
document.addEventListener("DOMContentLoaded", function () {
  const apiKey = document.getElementById('api-key').value.trim();
  const prompt = document.getElementById('test-prompt').value.trim();
  const model = document.getElementById('model-select').value;
 
  if (!apiKey || !prompt) {
    alert("⚠️ Inserisci sia la chiave API che il prompt.");
    return;
  }
 
  document.getElementById('api-result').textContent = "⏳ In attesa di risposta...";
 
  fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": "Bearer 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",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: model,
      messages: [{ role: "user", content: prompt }]
    })
  })
  .then(response => response.json())
  .then(data => {
    const output = data.choices?.[0]?.message?.content || "❌ Nessuna risposta ricevuta.";
    document.getElementById('api-result').textContent = output;
  })
  .catch(error => {
    console.error("Errore nella richiesta:", error);
    document.getElementById('api-result').textContent = "🚫 Errore nella connessione API.";
  });
}
 
 
 
// =================== Carica in OpenAI ? ==============
window.uploadToOpenAI = async function () {
  const log = document.getElementById("activityLogContent");
   const fileSelect = document.getElementById("fileSelect");
   const fileSelect = document.getElementById("fileSelect");
   const fileName = fileSelect ? fileSelect.value : "";
   if (fileSelect) {
 
    fileSelect.addEventListener("change", function () {
  if (!fileName) {
      const selected = this.value;
    logActivity("⚠️ Nessun file selezionato.");
      const preview = document.getElementById("file-preview");
     return;
      const mock = {
        "common.css": "/* Contenuto CSS di esempio */",
        "common.js": "// JS Demo",
        "LocalSettings.php": "<?php\n# Configurazione MediaWiki\n$wgSitename = 'Masticationpedia';"
      };
      preview.value = mock[selected] || "Contenuto non disponibile.";
     });
   }
   }
 
});
  try {
    const response = await fetch("/oauth/sync_to_openai.php?file=" + encodeURIComponent(fileName));
    const result = await response.text();
    logActivity(`🔄 File "${fileName}" → ${result}`);
  } catch (err) {
    logActivity(`❌ Errore sincronizzazione: ${err.message}`);
  }
};

Versione delle 18:08, 31 lug 2025

// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + lettura file reale
// ============================================

// 🔄 Apri/chiudi box
window.toggleDashboardBox = function (id) {
  const box = document.getElementById(id);
  if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};

// ▶️ Test connessione API OpenAI
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:\n" + 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}`);
  }
};

// 📂 Accesso File Server – Leggi file reale dal server via API PHP
document.querySelector('#readFileBtn')?.addEventListener('click', async () => {
  const filenameInput = document.querySelector('#readFileName');
  const fileContentDiv = document.querySelector('#readFileResult');
  const filename = filenameInput.value.trim();

  if (!filename) {
    fileContentDiv.innerHTML = '<span style="color:red;">⚠️ Inserisci un nome di file.</span>';
    return;
  }

  try {
    const response = await fetch('/wiki/dashboard/api/read_file.php?filename=' + encodeURIComponent(filename));
    const data = await response.json();

    if (data.status === 'success') {
      fileContentDiv.innerHTML = `<pre style="background:#f4f4f4;border:1px solid #ccc;padding:8px;max-height:400px;overflow:auto;font-size:14px;">${data.content}</pre>`;
      logActivity(`📂 File letto: <strong>${filename}</strong>`);
    } else {
      fileContentDiv.innerHTML = `<span style="color:red;">❌ Errore: ${data.message}</span>`;
      logActivity(`❌ Errore lettura file: ${data.message}`);
    }
  } catch (error) {
    fileContentDiv.innerHTML = `<span style="color:red;">❌ Errore di connessione.</span>`;
    console.error('Errore JS:', error);
  }
});

// 📦 Box progetti – apertura dialog
window.openProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "block";
};
window.closeProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "none";
};

// 📌 Aggiungi nuovo progetto alla tabella
window.addNewProject = function () {
  const title = document.getElementById("newProjectTitle").value.trim();
  const notes = document.getElementById("newProjectNotes").value.trim();
  if (!title) 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>
  `;
  table.appendChild(newRow);
  window.closeProjectDialog();
  logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
};

// 🧪 Testa codice JS in tempo reale
window.runTestCode = function () {
  const code = document.getElementById('codeArea').value;
  const output = document.getElementById('consoleOutput');
  try {
    const result = eval(code);
    output.textContent = "✅ Output:\n" + result;
  } catch (err) {
    output.textContent = "❌ Errore:\n" + err;
  }
};

// 🧾 Registro attività – aggiungi evento
window.logActivity = function (messaggio) {
  const contenitore = document.getElementById("activityLogContent");
  if (!contenitore) return;

  const ora = new Date().toLocaleTimeString("it-IT");
  const paragrafo = document.createElement("p");
  paragrafo.innerHTML = `<strong>[${ora}]</strong> ${messaggio}`;
  contenitore.appendChild(paragrafo);
  contenitore.scrollTop = contenitore.scrollHeight;
};

// 🧹 Svuota log
window.clearActivityLog = function () {
  const contenitore = document.getElementById("activityLogContent");
  contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
  logActivity("🧹 Log svuotato manualmente.");
};

// 🪄 Inizializza selettore file (box simulato)
document.addEventListener("DOMContentLoaded", function () {
  const fileSelect = document.getElementById("fileSelect");
  if (fileSelect) {
    fileSelect.addEventListener("change", function () {
      const selected = this.value;
      const preview = document.getElementById("file-preview");
      const mock = {
        "common.css": "/* Contenuto CSS di esempio */",
        "common.js": "// JS Demo",
        "LocalSettings.php": "<?php\n# Configurazione MediaWiki\n$wgSitename = 'Masticationpedia';"
      };
      preview.value = mock[selected] || "Contenuto non disponibile.";
    });
  }
});