// Helper Functions
const createElement = (tag, attributes = {}, ...children) => {
const element = document.createElement(tag);
for (let key in attributes) {
if (key.startsWith('on') && typeof attributes[key] === 'function') {
element.addEventListener(key.substring(2).toLowerCase(), attributes[key]);
} else if (key === 'className') {
element.className = attributes[key];
} else if (key === 'innerHTML') {
element.innerHTML = attributes[key];
} else {
element.setAttribute(key, attributes[key]);
}
}
children.forEach(child => {
if (typeof child === 'string') {
element.appendChild(document.createTextNode(child));
} else if (child instanceof Node) {
element.appendChild(child);
}
});
return element;
};
// API Base URL (Modify if needed)
const API_BASE_URL = '/api';
// Fetch Login Data
const fetchLoginData = async (page = 1, limit = 10) => {
try {
const response = await fetch(`${API_BASE_URL}/login_data?limit=${limit}&page=${page}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching login data:', error);
return { data: [], total: 0 };
}
};
// Fetch Category Info
const fetchCategoryInfo = async (page = 1, limit = 10) => {
try {
const response = await fetch(`${API_BASE_URL}/category_info?limit=${limit}&page=${page}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching category info:', error);
return { data: [], total: 0 };
}
};
// Fetch Business Info
const fetchBusinessInfo = async (page = 1, limit = 10) => {
try {
const response = await fetch(`${API_BASE_URL}/business_info?limit=${limit}&page=${page}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching business info:', error);
return { data: [], total: 0 };
}
};
// Render Pagination
const renderPagination = (currentPage, totalPages, container, onPageChange) => {
container.innerHTML = '';
const prevButton = createElement('button', {
disabled: currentPage === 1,
onClick: () => onPageChange(currentPage - 1),
className: currentPage === 1 ? 'disabled' : ''
}, 'Prev');
container.appendChild(prevButton);
// Display up to 5 page numbers
let start = Math.max(1, currentPage - 2);
let end = Math.min(totalPages, currentPage + 2);
if (currentPage <= 2) {
end = Math.min(5, totalPages);
}
if (currentPage >= totalPages - 1) {
start = Math.max(1, totalPages - 4);
}
for (let i = start; i <= end; i++) {
const pageButton = createElement('button', {
className: i === currentPage ? 'active' : '',
onClick: () => onPageChange(i)
}, i.toString());
container.appendChild(pageButton);
}
const nextButton = createElement('button', {
disabled: currentPage === totalPages,
onClick: () => onPageChange(currentPage + 1),
className: currentPage === totalPages ? 'disabled' : ''
}, 'Next');
container.appendChild(nextButton);
};
// Initialize Login Data Section
const initLoginData = () => {
const tableBody = document.getElementById('login-data-table-body');
const paginationContainer = document.getElementById('login-pagination');
const limit = 10;
let currentPage = 1;
let totalPages = 1;
const loadData = async (page) => {
const data = await fetchLoginData(page, limit);
tableBody.innerHTML = '';
data.data.forEach(entry => {
const row = createElement('tr', {},
createElement('td', {}, entry.uuid),
createElement('td', {}, new Date(entry.create_date).toLocaleString())
);
tableBody.appendChild(row);
});
totalPages = Math.ceil(data.total / limit);
renderPagination(page, totalPages, paginationContainer, loadData);
};
loadData(currentPage);
};
// Initialize Category Info Section
const initCategoryInfo = () => {
const tableBody = document.getElementById('category-info-table-body');
const paginationContainer = document.getElementById('category-pagination');
const limit = 10;
let currentPage = 1;
let totalPages = 1;
const loadData = async (page) => {
const data = await fetchCategoryInfo(page, limit);
tableBody.innerHTML = '';
data.data.forEach(entry => {
const row = createElement('tr', {},
createElement('td', {}, entry.uuid),
createElement('td', {}, entry.category_name),
createElement('td', {}, entry.url_category),
createEditableCell('original', entry.original, entry.uuid),
createEditableCell('thumbnail', entry.thumbnail, entry.uuid),
createToggleCell('subcategory', entry.subcategory, entry.uuid),
createToggleCell('blocked', entry.blocked, entry.uuid),
createEditableCell('blacklist', entry.blacklist, entry.uuid, true),
createEditableTextarea('description', entry.description, entry.uuid),
createElement('td', {},
createElement('button', {
onClick: () => saveCategory(entry.uuid),
className: 'save-button'
}, 'Save')
)
);
tableBody.appendChild(row);
});
totalPages = Math.ceil(data.total / limit);
renderPagination(page, totalPages, paginationContainer, loadData);
};
loadData(currentPage);
};
// Create Editable Cell
const createEditableCell = (field, value, uuid, isList = false) => {
const input = createElement('input', {
type: 'text',
className: 'editable',
value: value || '',
'data-uuid': uuid,
'data-field': field,
placeholder: isList ? 'Comma separated values' : ''
});
return createElement('td', {}, input);
};
// Create Editable Textarea
const createEditableTextarea = (field, value, uuid) => {
const textarea = createElement('textarea', {
className: 'editable',
innerHTML: value || '',
'data-uuid': uuid,
'data-field': field
});
return createElement('td', {}, textarea);
};
// Create Toggle Cell
const createToggleCell = (field, value, uuid) => {
const toggle = createElement('label', { className: 'switch' },
createElement('input', {
type: 'checkbox',
checked: value,
'data-uuid': uuid,
'data-field': field
}),
createElement('span', { className: 'slider' })
);
return createElement('td', {}, toggle);
};
// Save Category Changes
const saveCategory = async (uuid) => {
const row = [...document.querySelectorAll(`input[data-uuid="${uuid}"], textarea[data-uuid="${uuid}"]`)].reduce((acc, input) => {
acc[input.dataset.field] = input.value;
if (input.type === 'checkbox') acc[input.dataset.field] = input.checked;
return acc;
}, { uuid });
try {
const response = await fetch('/edit_category', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(row)
});
if (response.ok) {
alert('Category updated successfully!');
} else {
alert('Failed to update category.');
}
} catch (error) {
console.error('Error updating category:', error);
alert('Error updating category.');
}
};
// Initialize Business Info Section
const initBusinessInfo = () => {
const tableBody = document.getElementById('business-info-table-body');
const paginationContainer = document.getElementById('business-pagination');
const limit = 10;
let currentPage = 1;
let totalPages = 1;
const loadData = async (page) => {
const data = await fetchBusinessInfo(page, limit);
tableBody.innerHTML = '';
data.data.forEach(entry => {
const shippingArray = entry.shipping ? JSON.parse(entry.shipping) : [];
const row = createElement('tr', {},
createElement('td', {}, entry.uuid),
createEditableCellBusiness('business_name', entry.business_name, entry.uuid),
createEditableCellBusiness('url_business', entry.url_business, entry.uuid),
createEditableTextareaBusiness('description', entry.description, entry.uuid),
createEditableCellBusiness('shipping', shippingArray.join(','), entry.uuid),
createElement('td', {},
createElement('button', {
onClick: () => saveBusiness(entry.uuid),
className: 'save-button'
}, 'Save')
)
);
tableBody.appendChild(row);
});
totalPages = Math.ceil(data.total / limit);
renderPagination(page, totalPages, paginationContainer, loadData);
};
loadData(currentPage);
};
// Create Editable Cell for Business Info
const createEditableCellBusiness = (field, value, uuid) => {
let input;
if (field === 'shipping') {
input = createElement('input', {
type: 'text',
className: 'editable',
value: value || '',
'data-uuid': uuid,
'data-field': field,
placeholder: 'e.g., US,CA,GB'
});
} else {
input = createElement('input', {
type: 'text',
className: 'editable',
value: value || '',
'data-uuid': uuid,
'data-field': field
});
}
return createElement('td', {}, input);
};
// Create Editable Textarea for Business Info
const createEditableTextareaBusiness = (field, value, uuid) => {
const textarea = createElement('textarea', {
className: 'editable',
innerHTML: value || '',
'data-uuid': uuid,
'data-field': field
});
return createElement('td', {}, textarea);
};
// Save Business Changes
const saveBusiness = async (uuid) => {
const row = [...document.querySelectorAll(`input[data-uuid="${uuid}"], textarea[data-uuid="${uuid}"]`)].reduce((acc, input) => {
acc[input.dataset.field] = input.value;
return acc;
}, { uuid });
// Validate shipping
if (row.shipping) {
const shippingArray = row.shipping.split(',').map(code => code.trim().toUpperCase());
const isValid = shippingArray.every(code => /^[A-Z]{2}$/.test(code));
if (!isValid) {
alert('Shipping must be a comma-separated list of 2-letter ISO country codes.');
return;
}
row.shipping = JSON.stringify(shippingArray);
}
try {
const response = await fetch('/edit_business', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(row)
});
if (response.ok) {
alert('Business updated successfully!');
} else {
alert('Failed to update business.');
}
} catch (error) {
console.error('Error updating business:', error);
alert('Error updating business.');
}
};
// Initialize Map for Shipping Selection
let selectedCountries = [];
const initMap = () => {
const map = L.map('shipping-map').setView([20, 0], 2);
// Add OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Function to toggle country selection
const onMapClick = (e) => {
// Normally, you'd need to determine which country was clicked.
// For simplicity, we'll simulate country selection with random ISO codes.
// This requires a GeoJSON map with country boundaries and ISO codes.
// For brevity, it's not implemented here.
alert('Country selection via map is not implemented in this demo.');
};
map.on('click', onMapClick);
// Alternatively, use a multi-select dropdown for selecting countries
// since map-based selection requires extensive GeoJSON data.
// Implementing a multi-select as a placeholder
const shippingInput = document.getElementById('shipping');
const placeholder = createElement('div', { style: 'margin-top:10px;' },
'Shipping countries selection is not implemented. Please enter 2-letter ISO codes manually.')
document.getElementById('shipping-map').appendChild(placeholder);
};
// Handle New Business Form Submission
const handleNewBusinessForm = () => {
const form = document.getElementById('new-business-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const business_name = form.business_name.value.trim();
const url_business = form.url_business.value.trim();
const description = form.description.value.trim();
const shipping = form.shipping.value.trim();
// Validate shipping
let shippingJSON = null;
if (shipping) {
const shippingArray = shipping.split(',').map(code => code.trim().toUpperCase());
const isValid = shippingArray.every(code => /^[A-Z]{2}$/.test(code));
if (!isValid) {
alert('Shipping must be a comma-separated list of 2-letter ISO country codes.');
return;
}
shippingJSON = JSON.stringify(shippingArray);
}
const payload = {
business_name,
url_business,
description: description || null,
shipping: shippingJSON
};
try {
const response = await fetch('/new_business', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
alert('New business added successfully!');
form.reset();
// Optionally, reload the business info table
initBusinessInfo();
} else {
alert('Failed to add new business.');
}
} catch (error) {
console.error('Error adding new business:', error);
alert('Error adding new business.');
}
});
};
// Tab Navigation
const initTabs = () => {
const loginTab = document.getElementById('login-data-tab');
const categoryTab = document.getElementById('category-info-tab');
const businessTab = document.getElementById('business-info-tab');
const sections = {
'login-data-tab': 'login-data-section',
'category-info-tab': 'category-info-section',
'business-info-tab': 'business-info-section'
};
const tabs = [loginTab, categoryTab, businessTab];
tabs.forEach(tab => {
tab.addEventListener('click', (e) => {
e.preventDefault();
// Remove active class from all tabs
tabs.forEach(t => t.classList.remove('active'));
// Add active class to clicked tab
tab.classList.add('active');
// Hide all sections
Object.values(sections).forEach(sec => {
document.getElementById(sec).classList.remove('active');
});
// Show the selected section
const activeSection = sections[tab.id];
document.getElementById(activeSection).classList.add('active');
});
});
};
// Initialize Dashboard
const initDashboard = () => {
initTabs();
initLoginData();
initCategoryInfo();
initBusinessInfo();
initMap();
handleNewBusinessForm();
};
// Run Dashboard Initialization on DOMContentLoaded
document.addEventListener('DOMContentLoaded', initDashboard);