major refactoring adding vendor and customer features

This commit is contained in:
2025-10-11 09:09:25 +02:00
parent f569995883
commit dd16198276
126 changed files with 15109 additions and 3747 deletions

604
static/admin/dashboard.html Normal file
View File

@@ -0,0 +1,604 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Multi-Tenant Ecommerce Platform</title>
<link rel="stylesheet" href="/static/css/shared/base.css">
<link rel="stylesheet" href="/static/css/admin/admin.css">
</head>
<body>
<!-- Header -->
<header class="admin-header">
<div class="header-left">
<h1>🔐 Admin Dashboard</h1>
</div>
<div class="header-right">
<span class="user-info">Welcome, <strong id="adminUsername">Admin</strong></span>
<button class="btn-logout" onclick="handleLogout()">Logout</button>
</div>
</header>
<!-- Main Container -->
<div class="admin-container">
<!-- Sidebar -->
<aside class="admin-sidebar">
<nav>
<ul class="nav-menu">
<li class="nav-item">
<a href="#" class="nav-link active" onclick="showSection('dashboard')">
📊 Dashboard
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="showSection('vendors')">
🏪 Vendors
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="showSection('users')">
👥 Users
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="showSection('imports')">
📦 Import Jobs
</a>
</li>
</ul>
</nav>
</aside>
<!-- Main Content -->
<main class="admin-content">
<!-- Dashboard View -->
<div id="dashboardView">
<!-- Stats Grid -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-header">
<div>
<div class="stat-title">Total Vendors</div>
</div>
<div class="stat-icon">🏪</div>
</div>
<div class="stat-value" id="totalVendors">-</div>
<div class="stat-subtitle">
<span id="activeVendors">-</span> active
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div>
<div class="stat-title">Total Users</div>
</div>
<div class="stat-icon">👥</div>
</div>
<div class="stat-value" id="totalUsers">-</div>
<div class="stat-subtitle">
<span id="activeUsers">-</span> active
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div>
<div class="stat-title">Verified Vendors</div>
</div>
<div class="stat-icon"></div>
</div>
<div class="stat-value" id="verifiedVendors">-</div>
<div class="stat-subtitle">
<span id="verificationRate">-</span>% verification rate
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div>
<div class="stat-title">Import Jobs</div>
</div>
<div class="stat-icon">📦</div>
</div>
<div class="stat-value" id="totalImports">-</div>
<div class="stat-subtitle">
<span id="completedImports">-</span> completed
</div>
</div>
</div>
<!-- Recent Vendors -->
<div class="content-section">
<div class="section-header">
<h2 class="section-title">Recent Vendors</h2>
<button class="btn-primary" onclick="showSection('vendors')">View All</button>
</div>
<div id="recentVendorsList">
<div class="loading">Loading recent vendors...</div>
</div>
</div>
<!-- Recent Import Jobs -->
<div class="content-section">
<div class="section-header">
<h2 class="section-title">Recent Import Jobs</h2>
<button class="btn-primary" onclick="showSection('imports')">View All</button>
</div>
<div id="recentImportsList">
<div class="loading">Loading recent imports...</div>
</div>
</div>
</div>
<!-- Vendors View -->
<div id="vendorsView" style="display: none;">
<div class="content-section">
<div class="section-header">
<h2 class="section-title">Vendor Management</h2>
<button class="btn-primary" onclick="window.location.href='/static/admin/vendors.html'">
Create New Vendor
</button>
</div>
<div id="vendorsList">
<div class="loading">Loading vendors...</div>
</div>
</div>
</div>
<!-- Users View -->
<div id="usersView" style="display: none;">
<div class="content-section">
<div class="section-header">
<h2 class="section-title">User Management</h2>
</div>
<div id="usersList">
<div class="loading">Loading users...</div>
</div>
</div>
</div>
<!-- Imports View -->
<div id="importsView" style="display: none;">
<div class="content-section">
<div class="section-header">
<h2 class="section-title">Import Jobs</h2>
</div>
<div id="importsList">
<div class="loading">Loading import jobs...</div>
</div>
</div>
</div>
</main>
</div>
<script>
const API_BASE_URL = '/api/v1';
let currentSection = 'dashboard';
// Check authentication
function checkAuth() {
const token = localStorage.getItem('admin_token');
const user = localStorage.getItem('admin_user');
if (!token || !user) {
window.location.href = '/static/admin/login.html';
return false;
}
try {
const userData = JSON.parse(user);
if (userData.role !== 'admin') {
alert('Access denied. Admin privileges required.');
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
window.location.href = '/static/admin/login.html';
return false;
}
document.getElementById('adminUsername').textContent = userData.username;
return true;
} catch (e) {
window.location.href = '/static/admin/login.html';
return false;
}
}
// Logout
function handleLogout() {
if (confirm('Are you sure you want to logout?')) {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
window.location.href = '/static/admin/login.html';
}
}
// API Call with auth
async function apiCall(endpoint, options = {}) {
const token = localStorage.getItem('admin_token');
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
};
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers
}
});
if (response.status === 401) {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
window.location.href = '/static/admin/login.html';
throw new Error('Unauthorized');
}
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'API request failed');
}
return response.json();
}
// Load dashboard data
async function loadDashboard() {
try {
const data = await apiCall('/admin/dashboard');
// Update stats
document.getElementById('totalVendors').textContent = data.vendors.total_vendors || 0;
document.getElementById('activeVendors').textContent = data.vendors.active_vendors || 0;
document.getElementById('verifiedVendors').textContent = data.vendors.verified_vendors || 0;
document.getElementById('verificationRate').textContent = Math.round(data.vendors.verification_rate || 0);
document.getElementById('totalUsers').textContent = data.users.total_users || 0;
document.getElementById('activeUsers').textContent = data.users.active_users || 0;
// Display recent vendors
displayRecentVendors(data.recent_vendors || []);
// Display recent imports
displayRecentImports(data.recent_imports || []);
} catch (error) {
console.error('Failed to load dashboard:', error);
}
}
// Display recent vendors
function displayRecentVendors(vendors) {
const container = document.getElementById('recentVendorsList');
if (vendors.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🏪</div>
<p>No vendors yet</p>
</div>
`;
return;
}
const tableHTML = `
<table class="data-table">
<thead>
<tr>
<th>Vendor Code</th>
<th>Name</th>
<th>Subdomain</th>
<th>Status</th>
<th>Created</th>
</tr>
</thead>
<tbody>
${vendors.map(v => `
<tr>
<td><strong>${v.vendor_code}</strong></td>
<td>${v.name}</td>
<td>${v.subdomain}</td>
<td>
${v.is_verified ? '<span class="badge badge-success">Verified</span>' : '<span class="badge badge-warning">Pending</span>'}
${v.is_active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>'}
</td>
<td>${new Date(v.created_at).toLocaleDateString()}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
container.innerHTML = tableHTML;
}
// Display recent imports
function displayRecentImports(imports) {
const container = document.getElementById('recentImportsList');
if (imports.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📦</div>
<p>No import jobs yet</p>
</div>
`;
return;
}
const tableHTML = `
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Marketplace</th>
<th>Vendor</th>
<th>Status</th>
<th>Processed</th>
<th>Created</th>
</tr>
</thead>
<tbody>
${imports.map(j => `
<tr>
<td>#${j.id}</td>
<td>${j.marketplace}</td>
<td>${j.vendor_name || '-'}</td>
<td>
${j.status === 'completed' ? '<span class="badge badge-success">Completed</span>' :
j.status === 'failed' ? '<span class="badge badge-danger">Failed</span>' :
'<span class="badge badge-warning">Processing</span>'}
</td>
<td>${j.total_processed || 0}</td>
<td>${new Date(j.created_at).toLocaleDateString()}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
container.innerHTML = tableHTML;
}
// Show section
function showSection(section) {
// Update nav
document.querySelectorAll('.nav-link').forEach(link => {
link.classList.remove('active');
});
event.target.classList.add('active');
// Hide all views
document.getElementById('dashboardView').style.display = 'none';
document.getElementById('vendorsView').style.display = 'none';
document.getElementById('usersView').style.display = 'none';
document.getElementById('importsView').style.display = 'none';
// Show selected view
currentSection = section;
switch(section) {
case 'dashboard':
document.getElementById('dashboardView').style.display = 'block';
loadDashboard();
break;
case 'vendors':
document.getElementById('vendorsView').style.display = 'block';
loadVendors();
break;
case 'users':
document.getElementById('usersView').style.display = 'block';
loadUsers();
break;
case 'imports':
document.getElementById('importsView').style.display = 'block';
loadImports();
break;
}
}
// Load vendors
async function loadVendors() {
try {
const data = await apiCall('/admin/vendors?limit=100');
displayVendorsList(data.vendors);
} catch (error) {
console.error('Failed to load vendors:', error);
document.getElementById('vendorsList').innerHTML = `
<div class="empty-state">
<p>Failed to load vendors: ${error.message}</p>
</div>
`;
}
}
// Display vendors list
function displayVendorsList(vendors) {
const container = document.getElementById('vendorsList');
if (vendors.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🏪</div>
<p>No vendors found</p>
</div>
`;
return;
}
const tableHTML = `
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Vendor Code</th>
<th>Name</th>
<th>Subdomain</th>
<th>Email</th>
<th>Status</th>
<th>Created</th>
</tr>
</thead>
<tbody>
${vendors.map(v => `
<tr>
<td>${v.id}</td>
<td><strong>${v.vendor_code}</strong></td>
<td>${v.name}</td>
<td>${v.subdomain}</td>
<td>${v.contact_email || '-'}</td>
<td>
${v.is_verified ? '<span class="badge badge-success">Verified</span>' : '<span class="badge badge-warning">Pending</span>'}
${v.is_active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>'}
</td>
<td>${new Date(v.created_at).toLocaleDateString()}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
container.innerHTML = tableHTML;
}
// Load users
async function loadUsers() {
try {
const users = await apiCall('/admin/users?limit=100');
displayUsersList(users);
} catch (error) {
console.error('Failed to load users:', error);
document.getElementById('usersList').innerHTML = `
<div class="empty-state">
<p>Failed to load users: ${error.message}</p>
</div>
`;
}
}
// Display users list
function displayUsersList(users) {
const container = document.getElementById('usersList');
if (users.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">👥</div>
<p>No users found</p>
</div>
`;
return;
}
const tableHTML = `
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Created</th>
</tr>
</thead>
<tbody>
${users.map(u => `
<tr>
<td>${u.id}</td>
<td><strong>${u.username}</strong></td>
<td>${u.email}</td>
<td>${u.role}</td>
<td>
${u.is_active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>'}
</td>
<td>${new Date(u.created_at).toLocaleDateString()}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
container.innerHTML = tableHTML;
}
// Load imports
async function loadImports() {
try {
const imports = await apiCall('/admin/marketplace-import-jobs?limit=100');
displayImportsList(imports);
} catch (error) {
console.error('Failed to load imports:', error);
document.getElementById('importsList').innerHTML = `
<div class="empty-state">
<p>Failed to load import jobs: ${error.message}</p>
</div>
`;
}
}
// Display imports list
function displayImportsList(imports) {
const container = document.getElementById('importsList');
if (imports.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📦</div>
<p>No import jobs found</p>
</div>
`;
return;
}
const tableHTML = `
<table class="data-table">
<thead>
<tr>
<th>Job ID</th>
<th>Marketplace</th>
<th>Vendor</th>
<th>Status</th>
<th>Processed</th>
<th>Errors</th>
<th>Created</th>
</tr>
</thead>
<tbody>
${imports.map(j => `
<tr>
<td>#${j.job_id}</td>
<td>${j.marketplace}</td>
<td>${j.vendor_name || '-'}</td>
<td>
${j.status === 'completed' ? '<span class="badge badge-success">Completed</span>' :
j.status === 'failed' ? '<span class="badge badge-danger">Failed</span>' :
'<span class="badge badge-warning">Processing</span>'}
</td>
<td>${j.total_processed || 0}</td>
<td>${j.error_count || 0}</td>
<td>${new Date(j.created_at).toLocaleDateString()}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
container.innerHTML = tableHTML;
}
// Initialize
window.addEventListener('DOMContentLoaded', () => {
if (checkAuth()) {
loadDashboard();
}
});
</script>
</body>
</html>

200
static/admin/login.html Normal file
View File

@@ -0,0 +1,200 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Login - Multi-Tenant Ecommerce Platform</title>
<link rel="stylesheet" href="/static/css/shared/base.css">
<link rel="stylesheet" href="/static/css/shared/auth.css">
</head>
<body>
<div class="login-container">
<div class="login-header">
<h1>🔐 Admin Portal</h1>
<p>Multi-Tenant Ecommerce Platform</p>
</div>
<div id="alertBox" class="alert"></div>
<form id="loginForm">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
id="username"
name="username"
required
autocomplete="username"
placeholder="Enter your username"
>
<div class="error-message" id="usernameError"></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
name="password"
required
autocomplete="current-password"
placeholder="Enter your password"
>
<div class="error-message" id="passwordError"></div>
</div>
<button type="submit" class="btn-login" id="loginButton">
Sign In
</button>
</form>
<div class="login-footer">
<a href="/">← Back to Platform</a>
</div>
</div>
<script src="/static/js/shared/api-client.js"></script>
<script>
// API Client Configuration
const API_BASE_URL = '/api/v1';
// DOM Elements
const loginForm = document.getElementById('loginForm');
const loginButton = document.getElementById('loginButton');
const alertBox = document.getElementById('alertBox');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const usernameError = document.getElementById('usernameError');
const passwordError = document.getElementById('passwordError');
// Show alert message
function showAlert(message, type = 'error') {
alertBox.textContent = message;
alertBox.className = `alert alert-${type} show`;
if (type === 'success') {
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000);
}
}
// Show field error
function showFieldError(field, message) {
const input = field === 'username' ? usernameInput : passwordInput;
const errorDiv = field === 'username' ? usernameError : passwordError;
input.classList.add('error');
errorDiv.textContent = message;
errorDiv.classList.add('show');
}
// Clear field errors
function clearFieldErrors() {
usernameInput.classList.remove('error');
passwordInput.classList.remove('error');
usernameError.classList.remove('show');
passwordError.classList.remove('show');
alertBox.classList.remove('show');
}
// Set loading state
function setLoadingState(loading) {
loginButton.disabled = loading;
if (loading) {
loginButton.innerHTML = '<span class="loading-spinner"></span>Signing in...';
} else {
loginButton.innerHTML = 'Sign In';
}
}
// Handle login
async function handleLogin(event) {
event.preventDefault();
clearFieldErrors();
const username = usernameInput.value.trim();
const password = passwordInput.value;
// Basic validation
if (!username) {
showFieldError('username', 'Username is required');
return;
}
if (!password) {
showFieldError('password', 'Password is required');
return;
}
setLoadingState(true);
try {
const response = await fetch(`${API_BASE_URL}/admin/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.detail || 'Login failed');
}
// Check if user is admin
if (data.user.role !== 'admin') {
throw new Error('Access denied. Admin privileges required.');
}
// Store token
localStorage.setItem('admin_token', data.access_token);
localStorage.setItem('admin_user', JSON.stringify(data.user));
// Show success message
showAlert('Login successful! Redirecting...', 'success');
// Redirect to admin dashboard
setTimeout(() => {
window.location.href = '/static/admin/dashboard.html';
}, 1000);
} catch (error) {
console.error('Login error:', error);
showAlert(error.message || 'Login failed. Please try again.');
} finally {
setLoadingState(false);
}
}
// Event listeners
loginForm.addEventListener('submit', handleLogin);
// Clear errors on input
usernameInput.addEventListener('input', clearFieldErrors);
passwordInput.addEventListener('input', clearFieldErrors);
// Check if already logged in
window.addEventListener('DOMContentLoaded', () => {
const token = localStorage.getItem('admin_token');
const user = localStorage.getItem('admin_user');
if (token && user) {
try {
const userData = JSON.parse(user);
if (userData.role === 'admin') {
window.location.href = '/static/admin/dashboard.html';
}
} catch (e) {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
}
}
});
</script>
</body>
</html>

347
static/admin/vendors.html Normal file
View File

@@ -0,0 +1,347 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Vendor - Admin Portal</title>
<link rel="stylesheet" href="/static/css/shared/base.css">
<link rel="stylesheet" href="/static/css/admin/admin.css">
</head>
<body>
<header class="header">
<h1>Create New Vendor</h1>
<a href="/static/admin/dashboard.html" class="btn-back">← Back to Dashboard</a>
</header>
<div class="container">
<div class="form-card">
<h2 class="form-title">Vendor Information</h2>
<div id="alertBox" class="alert"></div>
<form id="createVendorForm">
<!-- Vendor Code -->
<div class="form-group">
<label for="vendorCode">
Vendor Code <span class="required">*</span>
</label>
<input
type="text"
id="vendorCode"
name="vendor_code"
required
placeholder="e.g., TECHSTORE"
pattern="[A-Z0-9_-]+"
maxlength="50"
>
<div class="form-help">Uppercase letters, numbers, underscores, and hyphens only</div>
<div class="error-message" id="vendorCodeError"></div>
</div>
<!-- Vendor Name -->
<div class="form-group">
<label for="name">
Vendor Name <span class="required">*</span>
</label>
<input
type="text"
id="name"
name="name"
required
placeholder="e.g., Tech Store Luxembourg"
maxlength="255"
>
<div class="form-help">Display name for the vendor</div>
<div class="error-message" id="nameError"></div>
</div>
<!-- Subdomain -->
<div class="form-group">
<label for="subdomain">
Subdomain <span class="required">*</span>
</label>
<input
type="text"
id="subdomain"
name="subdomain"
required
placeholder="e.g., techstore"
pattern="[a-z0-9][a-z0-9-]*[a-z0-9]"
maxlength="100"
>
<div class="form-help">Lowercase letters, numbers, and hyphens only (e.g., techstore.platform.com)</div>
<div class="error-message" id="subdomainError"></div>
</div>
<!-- Description -->
<div class="form-group">
<label for="description">Description</label>
<textarea
id="description"
name="description"
placeholder="Brief description of the vendor's business"
></textarea>
<div class="form-help">Optional description of the vendor</div>
</div>
<!-- Owner Email -->
<div class="form-group">
<label for="ownerEmail">
Owner Email <span class="required">*</span>
</label>
<input
type="email"
id="ownerEmail"
name="owner_email"
required
placeholder="owner@example.com"
>
<div class="form-help">Email for the vendor owner (login credentials will be sent here)</div>
<div class="error-message" id="ownerEmailError"></div>
</div>
<!-- Contact Phone -->
<div class="form-group">
<label for="contactPhone">Contact Phone</label>
<input
type="tel"
id="contactPhone"
name="contact_phone"
placeholder="+352 123 456 789"
>
<div class="form-help">Optional contact phone number</div>
</div>
<!-- Website -->
<div class="form-group">
<label for="website">Website</label>
<input
type="url"
id="website"
name="website"
placeholder="https://example.com"
>
<div class="form-help">Optional website URL</div>
</div>
<!-- Business Address -->
<div class="form-group">
<label for="businessAddress">Business Address</label>
<textarea
id="businessAddress"
name="business_address"
placeholder="Street, City, Country"
></textarea>
</div>
<!-- Tax Number -->
<div class="form-group">
<label for="taxNumber">Tax Number</label>
<input
type="text"
id="taxNumber"
name="tax_number"
placeholder="LU12345678"
>
</div>
<div class="form-actions">
<button type="button" class="btn btn-secondary" onclick="window.history.back()">
Cancel
</button>
<button type="submit" class="btn btn-primary" id="submitButton">
Create Vendor
</button>
</div>
</form>
<!-- Success credentials display -->
<div id="credentialsDisplay" style="display: none;">
<div class="credentials-card">
<h3>✅ Vendor Created Successfully!</h3>
<div class="credential-item">
<label>Vendor Code:</label>
<span class="value" id="displayVendorCode"></span>
</div>
<div class="credential-item">
<label>Subdomain:</label>
<span class="value" id="displaySubdomain"></span>
</div>
<div class="credential-item">
<label>Owner Username:</label>
<span class="value" id="displayUsername"></span>
</div>
<div class="credential-item">
<label>Owner Email:</label>
<span class="value" id="displayEmail"></span>
</div>
<div class="credential-item">
<label>Temporary Password:</label>
<span class="value" id="displayPassword"></span>
</div>
<div class="credential-item">
<label>Login URL:</label>
<span class="value" id="displayLoginUrl"></span>
</div>
<p class="warning-text">
⚠️ Important: Save these credentials! The password will not be shown again.
</p>
<div class="form-actions" style="margin-top: 20px;">
<button class="btn btn-primary" onclick="window.location.href='/static/admin/dashboard.html'">
Go to Dashboard
</button>
<button class="btn btn-secondary" onclick="location.reload()">
Create Another Vendor
</button>
</div>
</div>
</div>
</div>
</div>
<script>
const API_BASE_URL = '/api/v1';
// Check authentication
function checkAuth() {
const token = localStorage.getItem('admin_token');
const user = localStorage.getItem('admin_user');
if (!token || !user) {
window.location.href = '/static/admin/login.html';
return false;
}
try {
const userData = JSON.parse(user);
if (userData.role !== 'admin') {
alert('Access denied. Admin privileges required.');
window.location.href = '/static/admin/login.html';
return false;
}
return true;
} catch (e) {
window.location.href = '/static/admin/login.html';
return false;
}
}
// Show alert
function showAlert(message, type = 'error') {
const alertBox = document.getElementById('alertBox');
alertBox.textContent = message;
alertBox.className = `alert alert-${type} show`;
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// Clear all errors
function clearErrors() {
document.querySelectorAll('.error-message').forEach(el => {
el.classList.remove('show');
});
document.querySelectorAll('input, textarea').forEach(el => {
el.classList.remove('error');
});
document.getElementById('alertBox').classList.remove('show');
}
// Show field error
function showFieldError(fieldName, message) {
const input = document.querySelector(`[name="${fieldName}"]`);
const errorDiv = document.getElementById(`${fieldName.replace('_', '')}Error`);
if (input) input.classList.add('error');
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.classList.add('show');
}
}
// Auto-format inputs
document.getElementById('vendorCode').addEventListener('input', function(e) {
this.value = this.value.toUpperCase().replace(/[^A-Z0-9_-]/g, '');
});
document.getElementById('subdomain').addEventListener('input', function(e) {
this.value = this.value.toLowerCase().replace(/[^a-z0-9-]/g, '');
});
// Handle form submission
document.getElementById('createVendorForm').addEventListener('submit', async function(e) {
e.preventDefault();
clearErrors();
const submitButton = document.getElementById('submitButton');
submitButton.disabled = true;
submitButton.innerHTML = '<span class="loading-spinner"></span>Creating vendor...';
// Collect form data
const formData = {
vendor_code: document.getElementById('vendorCode').value.trim(),
name: document.getElementById('name').value.trim(),
subdomain: document.getElementById('subdomain').value.trim(),
description: document.getElementById('description').value.trim() || null,
owner_email: document.getElementById('ownerEmail').value.trim(),
contact_phone: document.getElementById('contactPhone').value.trim() || null,
website: document.getElementById('website').value.trim() || null,
business_address: document.getElementById('businessAddress').value.trim() || null,
tax_number: document.getElementById('taxNumber').value.trim() || null,
};
try {
const token = localStorage.getItem('admin_token');
const response = await fetch(`${API_BASE_URL}/admin/vendors`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(formData)
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.detail || 'Failed to create vendor');
}
// Display success and credentials
document.getElementById('createVendorForm').style.display = 'none';
document.getElementById('credentialsDisplay').style.display = 'block';
document.getElementById('displayVendorCode').textContent = data.vendor_code;
document.getElementById('displaySubdomain').textContent = data.subdomain;
document.getElementById('displayUsername').textContent = data.owner_username;
document.getElementById('displayEmail').textContent = data.owner_email;
document.getElementById('displayPassword').textContent = data.temporary_password;
document.getElementById('displayLoginUrl').textContent = data.login_url || `${data.subdomain}.platform.com/vendor/login`;
showAlert('Vendor created successfully!', 'success');
} catch (error) {
console.error('Error creating vendor:', error);
showAlert(error.message || 'Failed to create vendor');
submitButton.disabled = false;
submitButton.innerHTML = 'Create Vendor';
}
});
// Initialize
window.addEventListener('DOMContentLoaded', () => {
checkAuth();
});
</script>
</body>
</html>