// Modal instances
let addInstanceModal;
let editInstanceModal;
let addExistingInstanceModal;
let authModal;
let launchStepsModal;
let updateInstanceModal;
let currentStep = 1;
// Update the total number of steps
const totalSteps = 7;
document.addEventListener('DOMContentLoaded', function() {
addInstanceModal = new bootstrap.Modal(document.getElementById('addInstanceModal'));
editInstanceModal = new bootstrap.Modal(document.getElementById('editInstanceModal'));
addExistingInstanceModal = new bootstrap.Modal(document.getElementById('addExistingInstanceModal'));
authModal = new bootstrap.Modal(document.getElementById('authModal'));
launchStepsModal = new bootstrap.Modal(document.getElementById('launchStepsModal'));
updateInstanceModal = new bootstrap.Modal(document.getElementById('updateInstanceModal'));
// Initialize tooltips
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// Add refresh button to header
const headerButtons = document.querySelector('.header-buttons');
if (headerButtons) {
const refreshButton = document.createElement('button');
refreshButton.className = 'btn btn-outline-primary me-2';
refreshButton.innerHTML = ' Refresh All';
refreshButton.onclick = function() {
fetchCompanyNames();
};
headerButtons.appendChild(refreshButton);
const versionRefreshButton = document.createElement('button');
versionRefreshButton.className = 'btn btn-outline-info';
versionRefreshButton.innerHTML = ' Refresh Versions';
versionRefreshButton.onclick = function() {
refreshAllVersionInfo();
};
headerButtons.appendChild(versionRefreshButton);
}
// Wait a short moment to ensure the table is rendered
setTimeout(async () => {
// First fetch latest version information
await fetchLatestVersion();
// Then check statuses and fetch company names
checkAllInstanceStatuses();
fetchCompanyNames();
}, 100);
// Set up periodic status checks (every 30 seconds)
setInterval(checkAllInstanceStatuses, 30000);
// Set up periodic latest version checks (every 5 minutes)
setInterval(fetchLatestVersion, 300000);
// Update color picker functionality
const primaryColor = document.getElementById('primaryColor');
const secondaryColor = document.getElementById('secondaryColor');
const primaryColorRGB = document.getElementById('primaryColorRGB');
const secondaryColorRGB = document.getElementById('secondaryColorRGB');
const primaryPreview = document.getElementById('primaryPreview');
const secondaryPreview = document.getElementById('secondaryPreview');
function updateColorPreview() {
// Update preview boxes directly instead of using CSS variables
primaryPreview.style.backgroundColor = primaryColor.value;
secondaryPreview.style.backgroundColor = secondaryColor.value;
}
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ?
`${parseInt(result[1], 16)},${parseInt(result[2], 16)},${parseInt(result[3], 16)}` :
null;
}
function rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
primaryColor.addEventListener('input', function() {
primaryColorRGB.value = hexToRgb(this.value);
updateColorPreview();
});
secondaryColor.addEventListener('input', function() {
secondaryColorRGB.value = hexToRgb(this.value);
updateColorPreview();
});
// Initialize color preview
updateColorPreview();
});
// Function to check all instance statuses
async function checkAllInstanceStatuses() {
console.log('Checking all instance statuses...');
const instances = document.querySelectorAll('[data-instance-id]');
for (const badge of instances) {
const instanceId = badge.dataset.instanceId;
await checkInstanceStatus(instanceId);
// Also refresh version info when checking status
const instanceUrl = badge.closest('tr').querySelector('td:nth-child(7) a')?.href;
const apiKey = badge.dataset.token;
if (instanceUrl && apiKey) {
// Fetch version info in the background (don't await to avoid blocking status checks)
fetchVersionInfo(instanceUrl, instanceId).catch(error => {
console.error(`Error fetching version info for instance ${instanceId}:`, error);
});
}
}
}
// Function to check status of a single instance
async function checkInstanceStatus(instanceId) {
try {
const response = await fetch(`/instances/${instanceId}/status`);
if (!response.ok) throw new Error('Failed to check instance status');
const data = await response.json();
const badge = document.querySelector(`[data-instance-id="${instanceId}"]`);
if (badge) {
badge.className = `badge bg-${data.status === 'active' ? 'success' : 'danger'}`;
badge.textContent = data.status.charAt(0).toUpperCase() + data.status.slice(1);
// Parse the JSON string in status_details
let tooltipContent = data.status;
if (data.status_details) {
try {
const details = JSON.parse(data.status_details);
tooltipContent = `Status: ${details.status}\nTimestamp: ${details.timestamp}`;
if (details.database) {
tooltipContent += `\nDatabase: ${details.database}`;
}
} catch (e) {
tooltipContent = data.status_details;
}
}
badge.title = tooltipContent;
// Update tooltip
const tooltip = bootstrap.Tooltip.getInstance(badge);
if (tooltip) {
tooltip.dispose();
}
new bootstrap.Tooltip(badge);
}
} catch (error) {
console.error('Error checking instance status:', error);
}
}
// Function to get JWT token using API key
async function getJWTToken(instanceUrl, apiKey) {
try {
const response = await fetch(`${instanceUrl}/api/admin/management-token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'X-API-Key': apiKey
}
});
if (!response.ok) {
const errorText = await response.text();
console.error(`HTTP error ${response.status}:`, errorText);
throw new Error(`Server returned ${response.status}: ${errorText}`);
}
const data = await response.json();
return data.token;
} catch (error) {
console.error('Error getting JWT token:', error);
throw error;
}
}
// Function to fetch instance statistics
async function fetchInstanceStats(instanceUrl, instanceId, jwtToken) {
try {
const response = await fetch(`${instanceUrl}/api/admin/statistics`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${jwtToken}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error(`HTTP error ${response.status}:`, errorText);
throw new Error(`Server returned ${response.status}: ${errorText}`);
}
const data = await response.json();
console.log('Received stats data:', data);
const row = document.querySelector(`[data-instance-id="${instanceId}"]`).closest('tr');
// Update rooms count (3rd column)
const roomsCell = row.querySelector('td:nth-child(3)');
if (roomsCell) {
roomsCell.textContent = data.rooms || '0';
}
// Update conversations count (4th column)
const conversationsCell = row.querySelector('td:nth-child(4)');
if (conversationsCell) {
conversationsCell.textContent = data.conversations || '0';
}
// Update data usage (5th column)
const dataCell = row.querySelector('td:nth-child(5)');
if (dataCell) {
const dataSize = data.total_storage || 0;
const dataSizeGB = (dataSize / (1024 * 1024 * 1024)).toFixed(1);
dataCell.textContent = `${dataSizeGB} GB`;
}
return data;
} catch (error) {
console.error('Error fetching instance stats:', error);
throw error;
}
}
// Function to compare semantic versions and determine update type
function compareSemanticVersions(currentVersion, latestVersion) {
try {
// Parse versions into parts (handle cases like "1.0" or "1.0.0")
const parseVersion = (version) => {
const parts = version.split('.').map(part => {
const num = parseInt(part, 10);
return isNaN(num) ? 0 : num;
});
// Ensure we have at least 3 parts (major.minor.patch)
while (parts.length < 3) {
parts.push(0);
}
return parts.slice(0, 3); // Only take first 3 parts
};
const current = parseVersion(currentVersion);
const latest = parseVersion(latestVersion);
// Compare major version
if (current[0] < latest[0]) {
return 'major';
}
// Compare minor version
if (current[1] < latest[1]) {
return 'minor';
}
// Compare patch version
if (current[2] < latest[2]) {
return 'patch';
}
// If we get here, current version is newer or equal
return 'up_to_date';
} catch (error) {
console.error('Error comparing semantic versions:', error);
return 'unknown';
}
}
// Function to fetch version information for an instance
async function fetchVersionInfo(instanceUrl, instanceId) {
const row = document.querySelector(`[data-instance-id="${instanceId}"]`).closest('tr');
const versionCell = row.querySelector('td:nth-child(9)'); // Version column (adjusted after removing branch)
const paymentPlanCell = document.getElementById('payment-plan-' + instanceId); // Payment Plan column - use ID selector like initial load
// Show loading state
if (versionCell) {
versionCell.innerHTML = ' Loading...';
}
if (paymentPlanCell) {
paymentPlanCell.innerHTML = ' Loading...';
}
try {
const apiKey = document.querySelector(`[data-instance-id="${instanceId}"]`).dataset.token;
if (!apiKey) {
throw new Error('No API key available');
}
console.log(`Getting JWT token for instance ${instanceId} for version info`);
const jwtToken = await getJWTToken(instanceUrl, apiKey);
console.log('Got JWT token for version info');
// Fetch version information
console.log(`Fetching version info for instance ${instanceId} from ${instanceUrl}/api/admin/version-info`);
const response = await fetch(`${instanceUrl}/api/admin/version-info`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${jwtToken}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error(`HTTP error ${response.status}:`, errorText);
throw new Error(`Server returned ${response.status}: ${errorText}`);
}
const data = await response.json();
console.log('Received version data:', data);
// Update payment plan cell with pricing tier name
if (paymentPlanCell) {
const pricingTierName = data.pricing_tier_name || 'unknown';
console.log(`Instance ${instanceId}: API returned pricing_tier_name: "${pricingTierName}"`);
if (pricingTierName !== 'unknown') {
console.log(`Instance ${instanceId}: Setting payment plan to "${pricingTierName}" with badge styling`);
paymentPlanCell.innerHTML = `
${pricingTierName}
`;
// Add tooltip for payment plan
const paymentPlanBadge = paymentPlanCell.querySelector('[data-bs-toggle="tooltip"]');
if (paymentPlanBadge) {
new bootstrap.Tooltip(paymentPlanBadge);
}
} else {
console.log(`Instance ${instanceId}: API returned "unknown", setting badge to unknown`);
paymentPlanCell.innerHTML = 'unknown';
}
} else {
console.log(`Instance ${instanceId}: paymentPlanCell not found`);
}
// Update version cell
if (versionCell) {
const appVersion = data.app_version || 'unknown';
const gitCommit = data.git_commit || 'unknown';
const deployedAt = data.deployed_at || 'unknown';
if (appVersion !== 'unknown') {
// Get the latest version for comparison
const latestVersionBadge = document.getElementById('latestVersionBadge');
let latestVersion = latestVersionBadge ? latestVersionBadge.textContent.replace('Loading...', '').trim() : null;
// If latest version is not available yet, wait a bit and try again
if (!latestVersion || latestVersion === '') {
// Show loading state while waiting for latest version
versionCell.innerHTML = `
${appVersion.length > 8 ? appVersion.substring(0, 8) : appVersion}
`;
// Wait a bit and retry the comparison
setTimeout(() => {
fetchVersionInfo(instanceUrl, instanceId);
}, 2000);
return;
}
// Determine if this instance is up to date
let badgeClass = 'bg-secondary';
let statusIcon = 'fas fa-tag';
let tooltipText = `App Version: ${appVersion}
Git Commit: ${gitCommit}
Deployed: ${deployedAt}`;
if (latestVersion && appVersion === latestVersion) {
// Exact match - green
badgeClass = 'bg-success';
statusIcon = 'fas fa-check-circle';
tooltipText += '
✅ Up to date';
} else if (latestVersion && appVersion !== latestVersion) {
// Compare semantic versions
const versionComparison = compareSemanticVersions(appVersion, latestVersion);
switch (versionComparison) {
case 'patch':
// Only patch version different - yellow
badgeClass = 'bg-warning';
statusIcon = 'fas fa-exclamation-triangle';
tooltipText += `
🟡 Patch update available (Latest: ${latestVersion})`;
break;
case 'minor':
// Minor version different - orange
badgeClass = 'bg-orange';
statusIcon = 'fas fa-exclamation-triangle';
tooltipText += `
🟠 Minor update available (Latest: ${latestVersion})`;
break;
case 'major':
// Major version different - red
badgeClass = 'bg-danger';
statusIcon = 'fas fa-exclamation-triangle';
tooltipText += `
🔴 Major update available (Latest: ${latestVersion})`;
break;
default:
// Unknown format or comparison failed - red
badgeClass = 'bg-danger';
statusIcon = 'fas fa-exclamation-triangle';
tooltipText += `
🔴 Outdated (Latest: ${latestVersion})`;
break;
}
}
versionCell.innerHTML = `
${appVersion.length > 8 ? appVersion.substring(0, 8) : appVersion}
`;
} else {
versionCell.innerHTML = 'unknown';
}
}
// Update tooltips
const versionBadge = versionCell?.querySelector('[data-bs-toggle="tooltip"]');
if (versionBadge) {
new bootstrap.Tooltip(versionBadge);
}
} catch (error) {
console.error(`Error fetching version info for instance ${instanceId}:`, error);
// Show error state
if (versionCell) {
versionCell.innerHTML = `
Error
`;
}
if (paymentPlanCell) {
paymentPlanCell.innerHTML = `
Error
`;
}
// Add tooltips for error states
const errorBadge = versionCell?.querySelector('[data-bs-toggle="tooltip"]');
if (errorBadge) {
new bootstrap.Tooltip(errorBadge);
}
const paymentPlanErrorBadge = paymentPlanCell?.querySelector('[data-bs-toggle="tooltip"]');
if (paymentPlanErrorBadge) {
new bootstrap.Tooltip(paymentPlanErrorBadge);
}
}
}
// Function to fetch company name from instance settings
async function fetchCompanyName(instanceUrl, instanceId) {
const row = document.querySelector(`[data-instance-id="${instanceId}"]`).closest('tr');
const companyCell = row.querySelector('td:nth-child(2)');
// Show loading state
if (companyCell) {
companyCell.innerHTML = ' Loading...';
}
try {
const apiKey = document.querySelector(`[data-instance-id="${instanceId}"]`).dataset.token;
if (!apiKey) {
throw new Error('No API key available');
}
console.log(`Getting JWT token for instance ${instanceId}`);
const jwtToken = await getJWTToken(instanceUrl, apiKey);
console.log('Got JWT token');
// Fetch company name
console.log(`Fetching company name for instance ${instanceId} from ${instanceUrl}/api/admin/settings`);
const response = await fetch(`${instanceUrl}/api/admin/settings`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${jwtToken}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error(`HTTP error ${response.status}:`, errorText);
throw new Error(`Server returned ${response.status}: ${errorText}`);
}
const data = await response.json();
console.log('Received data:', data);
if (companyCell) {
companyCell.textContent = data.company_name || 'N/A';
}
// Fetch statistics using the same JWT token
await fetchInstanceStats(instanceUrl, instanceId, jwtToken);
} catch (error) {
console.error('Error fetching company name:', error);
if (companyCell) {
const errorMessage = error.message || 'Unknown error';
companyCell.innerHTML = `
Error
`;
// Initialize tooltip
new bootstrap.Tooltip(companyCell.querySelector('[data-bs-toggle="tooltip"]'));
// Also show error in stats cells
const row = document.querySelector(`[data-instance-id="${instanceId}"]`).closest('tr');
const statsCells = [
row.querySelector('td:nth-child(3)'), // Rooms
row.querySelector('td:nth-child(4)'), // Conversations
row.querySelector('td:nth-child(5)') // Data
];
statsCells.forEach(cell => {
if (cell) {
cell.innerHTML = `
Error
`;
new bootstrap.Tooltip(cell.querySelector('[data-bs-toggle="tooltip"]'));
}
});
}
}
}
// Function to fetch company names for all instances
async function fetchCompanyNames() {
console.log('Starting fetchCompanyNames...');
const instances = document.querySelectorAll('[data-instance-id]');
const loadingPromises = [];
for (const badge of instances) {
const instanceId = badge.dataset.instanceId;
const instanceUrl = badge.closest('tr').querySelector('td:nth-child(7) a')?.href;
const apiKey = badge.dataset.token;
if (instanceUrl && apiKey) {
console.log(`Fetching data for instance ${instanceId}`);
loadingPromises.push(
fetchCompanyName(instanceUrl, instanceId)
// Removed fetchVersionInfo call to prevent race conditions - checkAllInstanceStatuses handles this
);
} else {
const row = badge.closest('tr');
const cells = [
row.querySelector('td:nth-child(2)'), // Company
row.querySelector('td:nth-child(3)'), // Rooms
row.querySelector('td:nth-child(4)'), // Conversations
row.querySelector('td:nth-child(5)'), // Data
row.querySelector('td:nth-child(9)') // Version
];
cells.forEach(cell => {
if (cell) {
cell.innerHTML = `
Not configured
`;
new bootstrap.Tooltip(cell.querySelector('[data-bs-toggle="tooltip"]'));
}
});
}
}
try {
await Promise.all(loadingPromises);
console.log('Finished fetching all company names and stats');
} catch (error) {
console.error('Error in fetchCompanyNames:', error);
}
}
// Show modals
function showAddInstanceModal() {
document.getElementById('addInstanceForm').reset();
addInstanceModal.show();
}
function showAddExistingInstanceModal() {
document.getElementById('addExistingInstanceForm').reset();
addExistingInstanceModal.show();
}
// CRUD operations
async function submitAddInstance() {
const form = document.getElementById('addInstanceForm');
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
try {
const response = await fetch('/instances/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': formData.get('csrf_token')
},
body: JSON.stringify({
name: data.name,
company: data.name.charAt(0).toUpperCase() + data.name.slice(1),
rooms_count: 0,
conversations_count: 0,
data_size: 0.0,
payment_plan: 'Basic',
main_url: data.main_url,
status: 'inactive'
})
});
if (!response.ok) throw new Error('Failed to add instance');
const result = await response.json();
addInstanceModal.hide();
location.reload(); // Refresh to show new instance
} catch (error) {
alert('Error adding instance: ' + error.message);
}
}
async function editInstance(id) {
try {
// Find the row by looking for the edit button with the matching onclick handler
const editButton = document.querySelector(`button[onclick="editInstance(${id})"]`);
if (!editButton) {
throw new Error('Instance row not found');
}
const row = editButton.closest('tr');
if (!row) {
throw new Error('Instance row not found');
}
// Get the name from the first cell
const name = row.querySelector('td:first-child').textContent.trim();
// Get the main URL from the link in the URL cell (9th column after adding Version and Branch)
const urlCell = row.querySelector('td:nth-child(9)');
const urlLink = urlCell.querySelector('a');
const mainUrl = urlLink ? urlLink.getAttribute('href') : urlCell.textContent.trim();
// Populate form
document.getElementById('edit_instance_id').value = id;
document.getElementById('edit_name').value = name;
document.getElementById('edit_main_url').value = mainUrl;
editInstanceModal.show();
} catch (error) {
console.error('Error preparing instance edit:', error);
alert('Error: ' + error.message);
}
}
async function submitEditInstance() {
const form = document.getElementById('editInstanceForm');
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
const id = document.getElementById('edit_instance_id').value;
try {
const response = await fetch(`/instances/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': formData.get('csrf_token')
},
body: JSON.stringify({
name: data.name,
company: data.name.charAt(0).toUpperCase() + data.name.slice(1),
main_url: data.main_url
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to update instance: ${errorText}`);
}
editInstanceModal.hide();
location.reload(); // Refresh to show updated instance
} catch (error) {
console.error('Error updating instance:', error);
alert('Error: ' + error.message);
}
}
async function deleteInstance(id) {
if (!confirm('Are you sure you want to delete this instance?')) return;
const form = document.getElementById('editInstanceForm');
const formData = new FormData(form);
try {
const response = await fetch(`/instances/${id}`, {
method: 'DELETE',
headers: {
'X-CSRF-Token': formData.get('csrf_token')
}
});
if (!response.ok) throw new Error('Failed to delete instance');
location.reload(); // Refresh to show updated list
} catch (error) {
alert('Error deleting instance: ' + error.message);
}
}
function updateInstanceFields() {
const url = document.getElementById('existing_url').value;
if (url) {
try {
const urlObj = new URL(url);
const hostname = urlObj.hostname;
const name = hostname.split('.')[0];
document.getElementById('existing_name').value = name;
} catch (e) {
console.error('Invalid URL:', e);
}
}
}
async function submitAddExistingInstance() {
const form = document.getElementById('addExistingInstanceForm');
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
try {
const response = await fetch('/instances/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': formData.get('csrf_token')
},
body: JSON.stringify({
name: data.name,
company: data.name.charAt(0).toUpperCase() + data.name.slice(1),
rooms_count: 0,
conversations_count: 0,
data_size: 0.0,
payment_plan: 'Basic',
main_url: data.url,
status: 'inactive'
})
});
if (!response.ok) throw new Error('Failed to add instance');
addExistingInstanceModal.hide();
location.reload(); // Refresh to show new instance
} catch (error) {
alert('Error adding instance: ' + error.message);
}
}
function showAuthModal(instanceUrl, instanceId) {
document.getElementById('instance_url').value = instanceUrl;
document.getElementById('instance_id').value = instanceId;
document.getElementById('authForm').reset();
authModal.show();
}
async function authenticateInstance() {
const form = document.getElementById('authForm');
const formData = new FormData(form);
const instanceUrl = formData.get('instance_url').replace(/\/+$/, ''); // Remove trailing slashes
const instanceId = formData.get('instance_id');
const email = formData.get('email');
const password = formData.get('password');
try {
console.log('Attempting login to:', `${instanceUrl}/api/admin/login`);
// First login to get token
const loginResponse = await fetch(`${instanceUrl}/api/admin/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({ email, password })
});
// Check content type
const contentType = loginResponse.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
console.error('Unexpected content type:', contentType);
const text = await loginResponse.text();
console.error('Response text:', text);
throw new Error(`Server returned non-JSON response (${contentType}). Please check if the instance is properly configured.`);
}
let responseData;
try {
responseData = await loginResponse.json();
console.log('Login response:', responseData);
} catch (e) {
console.error('Failed to parse JSON response:', e);
throw new Error('Invalid JSON response from server');
}
if (!loginResponse.ok) {
throw new Error(responseData.message || 'Login failed');
}
if (responseData.status !== 'success') {
throw new Error(responseData.message || 'Login failed');
}
const token = responseData.token;
if (!token) {
throw new Error('No token received from server');
}
// Then create management API key
const keyResponse = await fetch(`${instanceUrl}/api/admin/management-api-key`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
name: `Connection from ${window.location.hostname}`
})
});
// Check content type for key response
const keyContentType = keyResponse.headers.get('content-type');
if (!keyContentType || !keyContentType.includes('application/json')) {
console.error('Unexpected content type for key response:', keyContentType);
const text = await keyResponse.text();
console.error('Key response text:', text);
throw new Error(`Server returned non-JSON response for API key (${keyContentType})`);
}
let keyData;
try {
keyData = await keyResponse.json();
console.log('API key response:', keyData);
} catch (e) {
console.error('Failed to parse JSON response for API key:', e);
throw new Error('Invalid JSON response from server for API key');
}
if (!keyResponse.ok) {
throw new Error(keyData.message || 'Failed to create API key');
}
const api_key = keyData.api_key;
if (!api_key) {
throw new Error('No API key received from server');
}
// Save the token to our database
const saveResponse = await fetch(`/instances/${instanceId}/save-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': formData.get('csrf_token')
},
body: JSON.stringify({ token: api_key })
});
let saveData;
try {
saveData = await saveResponse.json();
console.log('Save token response:', saveData);
} catch (e) {
console.error('Failed to parse JSON response for save token:', e);
throw new Error('Invalid JSON response from server for save token');
}
if (!saveResponse.ok) {
throw new Error(saveData.message || 'Failed to save token');
}
// Show success and refresh
authModal.hide();
location.reload();
} catch (error) {
console.error('Authentication error:', error);
alert('Error: ' + error.message);
}
}
function copyConnectionToken(button) {
const input = button.previousElementSibling;
input.select();
document.execCommand('copy');
// Show feedback
const originalText = button.innerHTML;
button.innerHTML = '';
setTimeout(() => {
button.innerHTML = originalText;
}, 2000);
}
function nextStepLaunchInstance() {
// Hide the initial modal
addInstanceModal.hide();
// Reset and show the steps modal
currentStep = 1;
updateStepDisplay();
launchStepsModal.show();
// Start verifying connections
verifyConnections();
}
function updateStepDisplay() {
// Hide all steps
document.querySelectorAll('.step-pane').forEach(pane => {
pane.classList.remove('active');
});
// Show current step
document.getElementById(`step${currentStep}`).classList.add('active');
// Update step indicators
document.querySelectorAll('.step-item').forEach(item => {
const step = parseInt(item.getAttribute('data-step'));
item.classList.toggle('active', step === currentStep);
item.classList.toggle('completed', step < currentStep);
});
// Get the modal footer
const modalFooter = document.getElementById('launchStepsFooter');
const prevButton = modalFooter.querySelector('.btn-secondary');
const nextButton = modalFooter.querySelector('.btn-primary');
// Always show the footer
modalFooter.style.display = 'block';
// Show/hide Previous button based on step
prevButton.style.display = currentStep === 1 ? 'none' : 'inline-block';
// Show/hide Next button based on step
if (currentStep === totalSteps) {
nextButton.style.display = 'none';
} else {
nextButton.style.display = 'inline-block';
nextButton.innerHTML = 'Next ';
}
// If we're on step 4, get the next available port
if (currentStep === 4) {
getNextAvailablePort();
}
// If we're on step 6, load pricing tiers
if (currentStep === 6) {
loadPricingTiers();
}
}
function nextStep() {
if (currentStep === 2 && !validateStep2()) {
return;
}
if (currentStep === 3 && !validateStep3()) {
return;
}
if (currentStep === 4 && !validateStep4()) {
return;
}
if (currentStep === 6 && !validateStep6()) {
return;
}
if (currentStep < totalSteps) {
currentStep++;
updateStepDisplay();
// Update review section if we're moving to the final step
if (currentStep === totalSteps) {
updateReviewSection();
}
}
}
function previousStep() {
if (currentStep > 1) {
currentStep--;
updateStepDisplay();
}
}
async function verifyConnections() {
// Verify Portainer connection
try {
const portainerResponse = await fetch('/api/admin/test-portainer-connection', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="csrf_token"]').value
},
body: JSON.stringify({
url: window.portainerSettings?.url || '',
api_key: window.portainerSettings?.api_key || ''
})
});
const portainerStatus = document.getElementById('portainerStatus');
const portainerDetails = document.getElementById('portainerDetails');
if (portainerResponse.ok) {
portainerStatus.innerHTML = ' Connected';
portainerStatus.className = 'connection-status success';
portainerDetails.innerHTML = 'Successfully connected to Portainer';
} else {
const error = await portainerResponse.json();
portainerStatus.innerHTML = ' Failed';
portainerStatus.className = 'connection-status error';
portainerDetails.innerHTML = `${error.error || 'Failed to connect to Portainer'}`;
}
} catch (error) {
const portainerStatus = document.getElementById('portainerStatus');
const portainerDetails = document.getElementById('portainerDetails');
portainerStatus.innerHTML = ' Error';
portainerStatus.className = 'connection-status error';
portainerDetails.innerHTML = `${error.message || 'Error checking Portainer connection'}`;
}
// Verify NGINX connection
try {
const nginxResponse = await fetch('/api/admin/test-nginx-connection', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="csrf_token"]').value
},
body: JSON.stringify({
url: window.nginxSettings?.url || '',
username: window.nginxSettings?.username || '',
password: window.nginxSettings?.password || ''
})
});
const nginxStatus = document.getElementById('nginxStatus');
const nginxDetails = document.getElementById('nginxDetails');
if (nginxResponse.ok) {
nginxStatus.innerHTML = ' Connected';
nginxStatus.className = 'connection-status success';
nginxDetails.innerHTML = 'Successfully connected to NGINX Proxy Manager';
} else {
const error = await nginxResponse.json();
nginxStatus.innerHTML = ' Failed';
nginxStatus.className = 'connection-status error';
nginxDetails.innerHTML = `${error.error || 'Failed to connect to NGINX Proxy Manager'}`;
}
} catch (error) {
const nginxStatus = document.getElementById('nginxStatus');
const nginxDetails = document.getElementById('nginxDetails');
nginxStatus.innerHTML = ' Error';
nginxStatus.className = 'connection-status error';
nginxDetails.innerHTML = `${error.message || 'Error checking NGINX connection'}`;
}
}
// Repository Selection Functions
async function loadRepositories() {
const repoSelect = document.getElementById('giteaRepoSelect');
const branchSelect = document.getElementById('giteaBranchSelect');
try {
const gitSettings = window.gitSettings || {};
if (!gitSettings.url || !gitSettings.token) {
throw new Error('No Git settings found. Please configure Git in the settings page.');
}
// Load repositories using the correct endpoint
const repoResponse = await fetch('/api/admin/list-gitea-repos', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
url: gitSettings.url,
token: gitSettings.token
})
});
if (!repoResponse.ok) {
throw new Error('Failed to load repositories');
}
const data = await repoResponse.json();
if (data.repositories) {
repoSelect.innerHTML = '' +
data.repositories.map(repo =>
``
).join('');
repoSelect.disabled = false;
// If we have a saved repository, load its branches
if (gitSettings.repo) {
loadBranches(gitSettings.repo);
}
} else {
repoSelect.innerHTML = '';
repoSelect.disabled = true;
}
} catch (error) {
console.error('Error loading repositories:', error);
repoSelect.innerHTML = ``;
repoSelect.disabled = true;
}
}
async function loadBranches(repoId) {
const branchSelect = document.getElementById('giteaBranchSelect');
try {
const gitSettings = window.gitSettings || {};
if (!gitSettings.url || !gitSettings.token) {
throw new Error('No Git settings found. Please configure Git in the settings page.');
}
const response = await fetch('/api/admin/list-gitea-branches', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
url: gitSettings.url,
token: gitSettings.token,
repo: repoId
})
});
if (!response.ok) {
throw new Error('Failed to load branches');
}
const data = await response.json();
if (data.branches) {
branchSelect.innerHTML = '' +
data.branches.map(branch =>
``
).join('');
branchSelect.disabled = false;
} else {
branchSelect.innerHTML = '';
branchSelect.disabled = true;
}
} catch (error) {
console.error('Error loading branches:', error);
branchSelect.innerHTML = ``;
branchSelect.disabled = true;
}
}
// Event Listeners for Repository Selection
document.getElementById('giteaRepoSelect').addEventListener('change', function() {
const repoId = this.value;
if (repoId) {
loadBranches(repoId);
} else {
document.getElementById('giteaBranchSelect').innerHTML = '';
document.getElementById('giteaBranchSelect').disabled = true;
}
});
// Load repositories when step 2 is shown
document.addEventListener('DOMContentLoaded', function() {
const step2Content = document.getElementById('step2');
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target.classList.contains('active')) {
loadRepositories();
}
});
});
observer.observe(step2Content, { attributes: true, attributeFilter: ['class'] });
});
// Function to get the next available port
async function getNextAvailablePort() {
try {
// Get all existing instances
const response = await fetch('/instances');
const text = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'text/html');
// Get all port numbers from the table
const portCells = doc.querySelectorAll('table tbody tr td:first-child');
const ports = Array.from(portCells)
.map(cell => {
const portText = cell.textContent.trim();
// Only parse if it's a number
return /^\d+$/.test(portText) ? parseInt(portText) : null;
})
.filter(port => port !== null)
.sort((a, b) => a - b); // Sort numerically
console.log('Found existing ports:', ports);
// Find the next available port
let nextPort = 10339; // Start from the next port after your highest
while (ports.includes(nextPort)) {
nextPort++;
}
console.log('Next available port:', nextPort);
// Set the suggested port
document.getElementById('port').value = nextPort;
} catch (error) {
console.error('Error getting next available port:', error);
// Default to 10339 if there's an error
document.getElementById('port').value = 10339;
}
}
// Function to validate step 2
function validateStep2() {
const repositorySelect = document.getElementById('giteaRepoSelect');
const branchSelect = document.getElementById('giteaBranchSelect');
if (!repositorySelect.value) {
alert('Please select a repository');
return false;
}
if (!branchSelect.value) {
alert('Please select a branch');
return false;
}
return true;
}
// Function to validate step 3
function validateStep3() {
const requiredFields = [
{ id: 'companyName', name: 'Company Name' },
{ id: 'streetAddress', name: 'Street Address' },
{ id: 'city', name: 'City' },
{ id: 'zipCode', name: 'ZIP Code' },
{ id: 'country', name: 'Country' },
{ id: 'email', name: 'Email' },
{ id: 'phone', name: 'Phone' }
];
const missingFields = requiredFields.filter(field => {
const element = document.getElementById(field.id);
return !element.value.trim();
});
if (missingFields.length > 0) {
const fieldNames = missingFields.map(field => field.name).join(', ');
alert(`Please fill in all required fields: ${fieldNames}`);
return false;
}
// Validate email format
const email = document.getElementById('email').value;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
alert('Please enter a valid email address');
return false;
}
// Validate phone format (basic validation)
const phone = document.getElementById('phone').value;
const phoneRegex = /^[\d\s\-\+\(\)]{10,}$/;
if (!phoneRegex.test(phone)) {
alert('Please enter a valid phone number');
return false;
}
return true;
}
// Function to validate step 4
function validateStep4() {
const port = document.getElementById('port').value;
const webAddresses = document.querySelectorAll('.web-address');
// Validate port
if (!port || port < 1024 || port > 65535) {
alert('Please enter a valid port number between 1024 and 65535');
return false;
}
// Validate web addresses
if (webAddresses.length === 0) {
alert('Please add at least one web address');
return false;
}
// Basic domain validation for each address
const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*\.[a-zA-Z]{2,}$/;
for (const address of webAddresses) {
if (!address.value) {
alert('Please fill in all web addresses');
return false;
}
if (!domainRegex.test(address.value)) {
alert(`Please enter a valid domain name for: ${address.value}`);
return false;
}
}
// Check for duplicate addresses
const addresses = Array.from(webAddresses).map(addr => addr.value.toLowerCase());
const uniqueAddresses = new Set(addresses);
if (addresses.length !== uniqueAddresses.size) {
alert('Please remove duplicate web addresses');
return false;
}
return true;
}
// Function to add a new web address input
function addWebAddress() {
const container = document.getElementById('webAddressesContainer');
const newAddress = document.createElement('div');
newAddress.className = 'input-group mb-2';
newAddress.innerHTML = `
https://
`;
container.appendChild(newAddress);
// Show remove buttons if there's more than one address
updateRemoveButtons();
}
// Function to remove a web address input
function removeWebAddress(button) {
button.closest('.input-group').remove();
updateRemoveButtons();
}
// Function to update remove buttons visibility
function updateRemoveButtons() {
const addresses = document.querySelectorAll('.web-address');
const removeButtons = document.querySelectorAll('.remove-address');
// Show remove buttons only if there's more than one address
removeButtons.forEach(button => {
button.style.display = addresses.length > 1 ? 'block' : 'none';
});
}
// Function to get all web addresses
function getAllWebAddresses() {
return Array.from(document.querySelectorAll('.web-address')).map(input => input.value);
}
// Function to update the review section
function updateReviewSection() {
// Get all the values
const repo = document.getElementById('giteaRepoSelect').value;
const branch = document.getElementById('giteaBranchSelect').value;
const company = document.getElementById('companyName').value;
const port = document.getElementById('port').value;
const webAddresses = Array.from(document.querySelectorAll('.web-address'))
.map(input => input.value)
.join(', ');
const pricingTier = document.getElementById('selectedPricingTierName').value;
// Update the review section
document.getElementById('reviewRepo').textContent = repo;
document.getElementById('reviewBranch').textContent = branch;
document.getElementById('reviewCompany').textContent = company;
document.getElementById('reviewPort').textContent = port;
document.getElementById('reviewWebAddresses').textContent = webAddresses;
document.getElementById('reviewPricingTier').textContent = pricingTier || 'Not selected';
}
// Function to launch the instance
function launchInstance() {
// Collect all the data
const instanceData = {
repository: document.getElementById('giteaRepoSelect').value,
branch: document.getElementById('giteaBranchSelect').value,
company: {
name: document.getElementById('companyName').value,
industry: document.getElementById('industry').value,
streetAddress: document.getElementById('streetAddress').value,
city: document.getElementById('city').value,
state: document.getElementById('state').value,
zipCode: document.getElementById('zipCode').value,
country: document.getElementById('country').value,
website: document.getElementById('website').value,
email: document.getElementById('email').value,
phone: document.getElementById('phone').value,
description: document.getElementById('companyDescription').value
},
port: document.getElementById('port').value,
webAddresses: Array.from(document.querySelectorAll('.web-address')).map(input => input.value),
colors: {
primary: document.getElementById('primaryColor').value,
secondary: document.getElementById('secondaryColor').value
},
pricingTier: {
id: document.getElementById('selectedPricingTierId').value,
name: document.getElementById('selectedPricingTierName').value
}
};
// Store the data in sessionStorage
sessionStorage.setItem('instanceLaunchData', JSON.stringify(instanceData));
// Close the modal
launchStepsModal.hide();
// Redirect to the launch progress page
window.location.href = '/instances/launch-progress';
}
// Function to refresh all version information
async function refreshAllVersionInfo() {
console.log('Refreshing all version information...');
const instances = document.querySelectorAll('[data-instance-id]');
const loadingPromises = [];
for (const badge of instances) {
const instanceId = badge.dataset.instanceId;
const instanceUrl = badge.closest('tr').querySelector('td:nth-child(7) a')?.href;
const apiKey = badge.dataset.token;
if (instanceUrl && apiKey) {
console.log(`Refreshing version info for instance ${instanceId}`);
loadingPromises.push(fetchVersionInfo(instanceUrl, instanceId));
}
}
try {
await Promise.all(loadingPromises);
console.log('Finished refreshing all version information');
} catch (error) {
console.error('Error refreshing version information:', error);
}
}
// Function to fetch latest version information
async function fetchLatestVersion() {
console.log('Fetching latest version information...');
const versionBadge = document.getElementById('latestVersionBadge');
const commitSpan = document.getElementById('latestCommit');
const checkedSpan = document.getElementById('lastChecked');
// Show loading state
if (versionBadge) {
versionBadge.innerHTML = ' Loading...';
versionBadge.className = 'badge bg-secondary fs-6';
}
try {
const response = await fetch('/api/latest-version', {
method: 'GET',
headers: {
'Accept': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
}
});
if (!response.ok) {
const errorText = await response.text();
console.error(`HTTP error ${response.status}:`, errorText);
throw new Error(`Server returned ${response.status}: ${errorText}`);
}
const data = await response.json();
console.log('Received latest version data:', data);
if (data.success) {
// Update version badge
if (versionBadge) {
const version = data.latest_version;
if (version !== 'unknown') {
versionBadge.innerHTML = `${version}`;
versionBadge.className = 'badge bg-success fs-6';
} else {
versionBadge.innerHTML = 'Unknown';
versionBadge.className = 'badge bg-warning fs-6';
}
}
// Update commit information
if (commitSpan) {
const commit = data.latest_commit;
if (commit !== 'unknown') {
commitSpan.textContent = commit.substring(0, 8);
commitSpan.title = commit;
} else {
commitSpan.textContent = 'Unknown';
}
}
// Update last checked time
if (checkedSpan) {
const lastChecked = data.last_checked;
if (lastChecked) {
const date = new Date(lastChecked);
checkedSpan.textContent = date.toLocaleString();
} else {
checkedSpan.textContent = 'Never';
}
}
} else {
// Handle error response
if (versionBadge) {
versionBadge.innerHTML = 'Error';
versionBadge.className = 'badge bg-danger fs-6';
}
if (commitSpan) {
commitSpan.textContent = 'Error';
}
if (checkedSpan) {
checkedSpan.textContent = 'Error';
}
console.error('Error in latest version response:', data.error);
}
} catch (error) {
console.error('Error fetching latest version:', error);
// Show error state
if (versionBadge) {
versionBadge.innerHTML = 'Error';
versionBadge.className = 'badge bg-danger fs-6';
}
if (commitSpan) {
commitSpan.textContent = 'Error';
}
if (checkedSpan) {
checkedSpan.textContent = 'Error';
}
}
}
// Function to refresh latest version (called by button)
async function refreshLatestVersion() {
console.log('Manual refresh of latest version requested');
await fetchLatestVersion();
}
// Function to load pricing tiers
async function loadPricingTiers() {
const container = document.getElementById('pricingTiersContainer');
try {
const response = await fetch('/api/admin/pricing-plans', {
method: 'GET',
headers: {
'Accept': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
}
});
if (!response.ok) {
throw new Error('Failed to load pricing tiers');
}
const data = await response.json();
if (data.plans && data.plans.length > 0) {
container.innerHTML = data.plans.map(plan => `
${plan.description}
` : ''}