refactor: Reformat admin view and update survey mapping database files.

This commit is contained in:
Marco Gallegos
2025-12-13 14:35:50 -06:00
parent 3a31818ca8
commit c711817e40
6 changed files with 485 additions and 408 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -6,10 +6,20 @@ const {
updateEnvironmentAlias, updateEnvironmentAlias,
getSurveysByEnvironment, getSurveysByEnvironment,
updateSurveySlug, updateSurveySlug,
refreshSurveyCache,
} = require("../services/formbricks"); } = require("../services/formbricks");
router.use(ensureAdminToken); router.use(ensureAdminToken);
router.post("/sync", async (req, res) => {
try {
await refreshSurveyCache();
res.json({ status: "ok", message: "Surveys synced successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.get("/environments", (req, res) => { router.get("/environments", (req, res) => {
try { try {
const environments = getAllEnvironments(); const environments = getAllEnvironments();

View File

@@ -1,55 +1,55 @@
require('dotenv').config(); require("dotenv").config();
const express = require('express'); const express = require("express");
const path = require('path'); const path = require("path");
const surveyRoutes = require('./routes/surveys'); const surveyRoutes = require("./routes/surveys");
const adminRoutes = require('./routes/admin'); const adminRoutes = require("./routes/admin");
const { refreshSurveyCache } = require('./services/formbricks'); const { refreshSurveyCache } = require("./services/formbricks");
const app = express(); const app = express();
const PORT = process.env.PORT || 3011; const PORT = process.env.PORT || 3011;
// Template Engine Setup // Template Engine Setup
app.set('view engine', 'ejs'); app.set("view engine", "ejs");
app.set('views', path.join(__dirname, 'views')); app.set("views", path.join(__dirname, "views"));
// Middleware // Middleware
app.use(express.json()); app.use(express.json());
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
// Health check endpoint // Health check endpoint
app.get('/health', (req, res) => { app.get("/health", (req, res) => {
res.status(200).json({ status: 'ok' }); res.status(200).json({ status: "ok" });
}); });
// Root landing page // Root landing page
app.get('/', (req, res) => { app.get("/", (req, res) => {
res.render('index', { res.render("index", {
title: 'Formbricks Survey Portal' title: "Formbricks Survey Portal",
}); });
}); });
// Admin UI // Admin UI
app.get('/admin', (req, res) => { app.get("/admin", (req, res) => {
res.render('admin', { res.render("admin", {
title: 'Admin - Formbricks Vanity' title: "Admin - Formbricks Vanity",
}); });
}); });
// Admin API routes // Admin API routes
app.use('/api/mappings', adminRoutes); app.use("/api/mappings", adminRoutes);
// Main survey routes (catch-all for vanity URLs) // Main survey routes (catch-all for vanity URLs)
app.use('/', surveyRoutes); app.use("/", surveyRoutes);
// Handle 404 for any other route // Handle 404 for any other route
app.use((req, res, next) => { app.use((req, res, next) => {
res.status(404).send('Sorry, that page does not exist.'); res.status(404).send("Sorry, that page does not exist.");
}); });
// Global error handler // Global error handler
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
console.error(err.stack); console.error(err.stack);
res.status(500).send('Something broke!'); res.status(500).send("Something broke!");
}); });
// Initialize the survey cache at startup // Initialize the survey cache at startup
@@ -59,7 +59,15 @@ refreshSurveyCache()
console.log(`Server is running at http://localhost:${PORT}`); console.log(`Server is running at http://localhost:${PORT}`);
}); });
}) })
.catch(error => { .catch((error) => {
console.error('Failed to initialize Formbricks survey cache. Please check API key and connection.', error); console.error(
process.exit(1); // Exit if we can't load the initial surveys "Failed to initialize Formbricks survey cache. Please check API key and connection.",
error.message
);
// process.exit(1); // Don't exit, allow the server to start even if sync fails
app.listen(PORT, () => {
console.log(
`Server is running at http://localhost:${PORT} (Survey sync failed)`
);
});
}); });

View File

@@ -64,6 +64,7 @@ async function fetchSurveysFromAPI() {
headers: { headers: {
"x-api-key": process.env.FORMBRICKS_API_KEY, "x-api-key": process.env.FORMBRICKS_API_KEY,
}, },
timeout: 15000, // 15 seconds timeout
} }
); );
@@ -108,6 +109,7 @@ async function refreshSurveyCache() {
console.log(`Successfully synced ${synced} surveys into the database.`); console.log(`Successfully synced ${synced} surveys into the database.`);
} catch (error) { } catch (error) {
console.error("Failed to refresh survey cache:", error.message); console.error("Failed to refresh survey cache:", error.message);
throw error; // Re-throw so server.js knows initialization failed
} }
} }

View File

@@ -1,12 +1,15 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= title %></title> <title><%= title %></title>
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"> <link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<style> <style>
:root { :root {
/* Catppuccin Mocha Palette */ /* Catppuccin Mocha Palette */
@@ -50,7 +53,7 @@
} }
body { body {
font-family: 'Inter', sans-serif; font-family: "Inter", sans-serif;
background-color: var(--bg-color); background-color: var(--bg-color);
color: var(--text-primary); color: var(--text-primary);
margin: 0; margin: 0;
@@ -97,7 +100,8 @@
margin: 0; margin: 0;
} }
input, select { input,
select {
background-color: var(--ctp-surface0); background-color: var(--ctp-surface0);
border: 1px solid var(--border); border: 1px solid var(--border);
color: var(--text-primary); color: var(--text-primary);
@@ -109,7 +113,8 @@
transition: border-color 0.2s, box-shadow 0.2s; transition: border-color 0.2s, box-shadow 0.2s;
} }
input:focus, select:focus { input:focus,
select:focus {
outline: none; outline: none;
border-color: var(--accent); border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(203, 166, 247, 0.1); box-shadow: 0 0 0 3px rgba(203, 166, 247, 0.1);
@@ -155,7 +160,8 @@
border-collapse: collapse; border-collapse: collapse;
} }
th, td { th,
td {
text-align: left; text-align: left;
padding: 0.75rem; padding: 0.75rem;
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
@@ -245,13 +251,15 @@
border-color: var(--success); border-color: var(--success);
} }
</style> </style>
</head> </head>
<body> <body>
<div id="auth-section" class="card"> <div id="auth-section" class="card">
<h2>Admin Authentication</h2> <h2>Admin Authentication</h2>
<p style="color: var(--text-secondary); margin-bottom: 1.5rem;">Enter your Admin Token to manage surveys.</p> <p style="color: var(--text-secondary); margin-bottom: 1.5rem">
Enter your Admin Token to manage surveys.
</p>
<div class="form-group"> <div class="form-group">
<input type="password" id="admin-token" placeholder="Admin Token"> <input type="password" id="admin-token" placeholder="Admin Token" />
</div> </div>
<button onclick="authenticate()">Login</button> <button onclick="authenticate()">Login</button>
</div> </div>
@@ -265,8 +273,13 @@
<div class="card"> <div class="card">
<div class="card-header"> <div class="card-header">
<h2>Environments & Aliases</h2> <h2>Environments & Aliases</h2>
<div style="display: flex; gap: 0.5rem">
<button onclick="syncSurveys()" class="secondary">
Sync Surveys
</button>
<button onclick="loadData()">Refresh</button> <button onclick="loadData()">Refresh</button>
</div> </div>
</div>
<div id="environments-container"> <div id="environments-container">
<!-- Environments will be inserted here --> <!-- Environments will be inserted here -->
</div> </div>
@@ -274,44 +287,44 @@
</div> </div>
<script> <script>
const API_BASE = '/api/mappings'; const API_BASE = "/api/mappings";
let token = localStorage.getItem('admin_token'); let token = localStorage.getItem("admin_token");
if (token) { if (token) {
showApp(); showApp();
} }
function authenticate() { function authenticate() {
const input = document.getElementById('admin-token').value; const input = document.getElementById("admin-token").value;
if (input) { if (input) {
token = input; token = input;
localStorage.setItem('admin_token', token); localStorage.setItem("admin_token", token);
showApp(); showApp();
} }
} }
function logout() { function logout() {
token = null; token = null;
localStorage.removeItem('admin_token'); localStorage.removeItem("admin_token");
document.getElementById('auth-section').classList.remove('hidden'); document.getElementById("auth-section").classList.remove("hidden");
document.getElementById('app-section').classList.add('hidden'); document.getElementById("app-section").classList.add("hidden");
} }
function showApp() { function showApp() {
document.getElementById('auth-section').classList.add('hidden'); document.getElementById("auth-section").classList.add("hidden");
document.getElementById('app-section').classList.remove('hidden'); document.getElementById("app-section").classList.remove("hidden");
loadData(); loadData();
} }
async function fetchWithAuth(url, options = {}) { async function fetchWithAuth(url, options = {}) {
const headers = { const headers = {
'Content-Type': 'application/json', "Content-Type": "application/json",
'x-admin-token': token, "x-admin-token": token,
...options.headers ...options.headers,
}; };
const response = await fetch(url, { ...options, headers }); const response = await fetch(url, { ...options, headers });
if (response.status === 403) { if (response.status === 403) {
alert('Invalid Token'); alert("Invalid Token");
logout(); logout();
return null; return null;
} }
@@ -326,40 +339,48 @@
} }
async function renderEnvironments(environments) { async function renderEnvironments(environments) {
const container = document.getElementById('environments-container'); const container = document.getElementById("environments-container");
container.innerHTML = ''; container.innerHTML = "";
for (const env of environments) { for (const env of environments) {
const div = document.createElement('div'); const div = document.createElement("div");
div.className = 'env-section'; div.className = "env-section";
// Fetch surveys for this environment // Fetch surveys for this environment
const surveyRes = await fetchWithAuth(`${API_BASE}/environments/${env.environment_id}/surveys`); const surveyRes = await fetchWithAuth(
`${API_BASE}/environments/${env.environment_id}/surveys`
);
const surveyData = await surveyRes.json(); const surveyData = await surveyRes.json();
const surveys = surveyData.surveys || []; const surveys = surveyData.surveys || [];
const aliasValue = env.alias || ''; const aliasValue = env.alias || "";
const hasAlias = !!aliasValue; const hasAlias = !!aliasValue;
let surveysHtml = ''; let surveysHtml = "";
if (surveys.length > 0) { if (surveys.length > 0) {
surveysHtml = '<div class="survey-list">'; surveysHtml = '<div class="survey-list">';
surveys.forEach(s => { surveys.forEach((s) => {
const displaySlug = s.custom_slug || s.name; const displaySlug = s.custom_slug || s.name;
const url = hasAlias ? `/${aliasValue}/${displaySlug}` : '#'; const url = hasAlias ? `/${aliasValue}/${displaySlug}` : "#";
const fullUrl = hasAlias ? `${window.location.origin}/${aliasValue}/${displaySlug}` : ''; const fullUrl = hasAlias
? `${window.location.origin}/${aliasValue}/${displaySlug}`
: "";
const link = hasAlias const link = hasAlias
? `<a href="${url}" target="_blank" class="survey-link">${url}</a>` ? `<a href="${url}" target="_blank" class="survey-link">${url}</a>`
: `<span style="color: var(--text-secondary);">(Set alias to generate URL)</span>`; : `<span style="color: var(--text-secondary);">(Set alias to generate URL)</span>`;
const copyBtn = hasAlias const copyBtn = hasAlias
? `<button class="copy-btn" onclick="copyToClipboard('${fullUrl}', this)">📋 Copy</button>` ? `<button class="copy-btn" onclick="copyToClipboard('${fullUrl}', this)">📋 Copy</button>`
: ''; : "";
surveysHtml += ` surveysHtml += `
<div class="survey-item" style="flex-direction: column; align-items: stretch; gap: 0.5rem; padding: 1rem 0; border-bottom: 1px solid var(--border);"> <div class="survey-item" style="flex-direction: column; align-items: stretch; gap: 0.5rem; padding: 1rem 0; border-bottom: 1px solid var(--border);">
<div style="display: flex; justify-content: space-between; align-items: center;"> <div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-weight: 500;">${s.name}</span> <span style="font-weight: 500;">${
<span style="font-size: 0.75rem; color: var(--text-secondary);">Type: ${s.type}</span> s.name
}</span>
<span style="font-size: 0.75rem; color: var(--text-secondary);">Type: ${
s.type
}</span>
</div> </div>
<div style="display: grid; grid-template-columns: 1fr auto auto; gap: 0.5rem; align-items: center;"> <div style="display: grid; grid-template-columns: 1fr auto auto; gap: 0.5rem; align-items: center;">
<input <input
@@ -369,16 +390,23 @@
placeholder="custom-slug" placeholder="custom-slug"
style="font-size: 0.875rem; padding: 0.375rem 0.5rem;" style="font-size: 0.875rem; padding: 0.375rem 0.5rem;"
/> />
<button onclick="saveSlug('${s.id}')" class="secondary" style="font-size: 0.875rem;">Save Slug</button> <button onclick="saveSlug('${
s.id
}')" class="secondary" style="font-size: 0.875rem;">Save Slug</button>
${copyBtn} ${copyBtn}
</div> </div>
${hasAlias ? `<div style="font-size: 0.875rem;">${link}</div>` : ''} ${
hasAlias
? `<div style="font-size: 0.875rem;">${link}</div>`
: ""
}
</div> </div>
`; `;
}); });
surveysHtml += '</div>'; surveysHtml += "</div>";
} else { } else {
surveysHtml = '<p style="color: var(--text-secondary); margin-top: 0.5rem;">No surveys found.</p>'; surveysHtml =
'<p style="color: var(--text-secondary); margin-top: 0.5rem;">No surveys found.</p>';
} }
div.innerHTML = ` div.innerHTML = `
@@ -403,20 +431,23 @@
const alias = input.value.trim(); const alias = input.value.trim();
if (!alias) { if (!alias) {
alert('Alias cannot be empty'); alert("Alias cannot be empty");
return; return;
} }
const res = await fetchWithAuth(`${API_BASE}/environments/${envId}/alias`, { const res = await fetchWithAuth(
method: 'PUT', `${API_BASE}/environments/${envId}/alias`,
body: JSON.stringify({ alias }) {
}); method: "PUT",
body: JSON.stringify({ alias }),
}
);
if (res.ok) { if (res.ok) {
loadData(); // Refresh to update URLs loadData(); // Refresh to update URLs
} else { } else {
const err = await res.json(); const err = await res.json();
alert(err.error || 'Failed to update alias'); alert(err.error || "Failed to update alias");
} }
} }
@@ -424,16 +455,16 @@
try { try {
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
const originalText = button.textContent; const originalText = button.textContent;
button.textContent = '✓ Copied!'; button.textContent = "✓ Copied!";
button.classList.add('copied'); button.classList.add("copied");
setTimeout(() => { setTimeout(() => {
button.textContent = originalText; button.textContent = originalText;
button.classList.remove('copied'); button.classList.remove("copied");
}, 2000); }, 2000);
} catch (err) { } catch (err) {
console.error('Failed to copy:', err); console.error("Failed to copy:", err);
alert('Failed to copy to clipboard'); alert("Failed to copy to clipboard");
} }
} }
@@ -442,22 +473,48 @@
const slug = input.value.trim(); const slug = input.value.trim();
if (!slug) { if (!slug) {
alert('Slug cannot be empty'); alert("Slug cannot be empty");
return; return;
} }
const res = await fetchWithAuth(`${API_BASE}/surveys/${surveyId}/slug`, { const res = await fetchWithAuth(
method: 'PUT', `${API_BASE}/surveys/${surveyId}/slug`,
body: JSON.stringify({ slug }) {
}); method: "PUT",
body: JSON.stringify({ slug }),
}
);
if (res.ok) { if (res.ok) {
loadData(); // Refresh to update URLs loadData(); // Refresh to update URLs
} else { } else {
const err = await res.json(); const err = await res.json();
alert(err.error || 'Failed to update slug'); alert(err.error || "Failed to update slug");
}
}
async function syncSurveys() {
const btn = document.querySelector('button[onclick="syncSurveys()"]');
const originalText = btn.textContent;
btn.textContent = 'Syncing...';
btn.disabled = true;
try {
const res = await fetchWithAuth(`${API_BASE}/sync`, { method: 'POST' });
if (res.ok) {
alert('Surveys synced successfully!');
loadData();
} else {
const err = await res.json();
alert('Sync failed: ' + (err.error || 'Unknown error'));
}
} catch (error) {
alert('Sync failed: ' + error.message);
} finally {
btn.textContent = originalText;
btn.disabled = false;
} }
} }
</script> </script>
</body> </body>
</html> </html>