Working state before icon/utils fixes - Oct 22

This commit is contained in:
2025-10-21 21:56:54 +02:00
parent a7d9d44a13
commit 5be47b91a2
39 changed files with 6017 additions and 508 deletions

View File

@@ -1,72 +1,126 @@
/**
* Admin Dashboard Component
* Extends adminLayout with dashboard-specific functionality
*/
// static/admin/js/dashboard.js
// Log levels: 0 = None, 1 = Error, 2 = Warning, 3 = Info, 4 = Debug
const DASHBOARD_LOG_LEVEL = 3; // Set to 3 for production, 4 for full debugging
const dashLog = {
error: (...args) => DASHBOARD_LOG_LEVEL >= 1 && console.error('❌ [DASHBOARD ERROR]', ...args),
warn: (...args) => DASHBOARD_LOG_LEVEL >= 2 && console.warn('⚠️ [DASHBOARD WARN]', ...args),
info: (...args) => DASHBOARD_LOG_LEVEL >= 3 && console.info(' [DASHBOARD INFO]', ...args),
debug: (...args) => DASHBOARD_LOG_LEVEL >= 4 && console.log('🔍 [DASHBOARD DEBUG]', ...args)
};
function adminDashboard() {
return {
// Inherit all adminLayout functionality
...window.adminLayout(),
// Inherit base layout functionality from init-alpine.js
...data(),
// Dashboard-specific state
currentSection: 'dashboard',
currentPage: 'dashboard',
stats: {
vendors: {},
users: {},
imports: {}
totalVendors: 0,
activeUsers: 0,
verifiedVendors: 0,
importJobs: 0
},
vendors: [],
users: [],
imports: [],
recentVendors: [],
recentImports: [],
loading: false,
loading: true,
error: null,
/**
* Initialize dashboard
*/
async init() {
// Call parent init from adminLayout
this.currentPage = this.getCurrentPage();
await this.loadUserData();
dashLog.info('=== DASHBOARD INITIALIZING ===');
dashLog.debug('Current URL:', window.location.href);
dashLog.debug('Current pathname:', window.location.pathname);
// Load dashboard data
await this.loadDashboardData();
const token = localStorage.getItem('admin_token');
dashLog.debug('Has admin_token?', !!token);
if (token) {
dashLog.debug('Token preview:', token.substring(0, 20) + '...');
}
// Prevent multiple initializations
if (window._dashboardInitialized) {
dashLog.warn('Dashboard already initialized, skipping...');
return;
}
window._dashboardInitialized = true;
dashLog.debug('Dashboard initialization flag set');
await this.loadDashboard();
dashLog.info('=== DASHBOARD INITIALIZATION COMPLETE ===');
},
/**
* Load all dashboard data
*/
async loadDashboardData() {
async loadDashboard() {
dashLog.info('Loading dashboard data...');
this.loading = true;
this.error = null;
dashLog.debug('Dashboard state: loading=true, error=null');
try {
dashLog.info('Starting parallel data fetch...');
const startTime = Date.now();
// Load stats and vendors in parallel
await Promise.all([
this.loadStats(),
this.loadRecentVendors(),
this.loadRecentImports()
this.loadRecentVendors()
]);
const duration = Date.now() - startTime;
dashLog.info(`Dashboard data loaded successfully in ${duration}ms`);
} catch (error) {
console.error('Error loading dashboard data:', error);
this.showErrorModal({
message: 'Failed to load dashboard data',
details: error.message
dashLog.error('Dashboard load error:', error);
dashLog.error('Error details:', {
message: error.message,
name: error.name,
stack: error.stack
});
this.error = error.message;
Utils.showToast('Failed to load dashboard data', 'error');
} finally {
this.loading = false;
dashLog.debug('Dashboard state: loading=false');
dashLog.info('Dashboard load attempt finished');
}
},
/**
* Load statistics
* Load platform statistics
*/
async loadStats() {
dashLog.info('Loading platform statistics...');
dashLog.debug('API endpoint: /admin/dashboard/stats/platform');
try {
const response = await apiClient.get('/admin/stats');
this.stats = response;
const startTime = Date.now();
const data = await apiClient.get('/admin/dashboard/stats/platform');
const duration = Date.now() - startTime;
dashLog.info(`Stats loaded in ${duration}ms`);
dashLog.debug('Raw stats data:', data);
// Map API response to stats cards
this.stats = {
totalVendors: data.vendors?.total_vendors || 0,
activeUsers: data.users?.active_users || 0,
verifiedVendors: data.vendors?.verified_vendors || 0,
importJobs: data.imports?.total_imports || 0
};
dashLog.info('Stats mapped:', this.stats);
} catch (error) {
console.error('Failed to load stats:', error);
// Don't show error modal for stats, just log it
dashLog.error('Failed to load stats:', error);
throw error;
}
},
@@ -74,111 +128,32 @@ function adminDashboard() {
* Load recent vendors
*/
async loadRecentVendors() {
dashLog.info('Loading recent vendors...');
dashLog.debug('API endpoint: /admin/dashboard');
try {
const response = await apiClient.get('/admin/vendors', {
skip: 0,
limit: 5
const startTime = Date.now();
const data = await apiClient.get('/admin/dashboard');
const duration = Date.now() - startTime;
dashLog.info(`Recent vendors loaded in ${duration}ms`);
dashLog.debug('Vendors data:', {
count: data.recent_vendors?.length || 0,
hasData: !!data.recent_vendors
});
this.recentVendors = response.vendors || response;
this.recentVendors = data.recent_vendors || [];
if (this.recentVendors.length > 0) {
dashLog.info(`Loaded ${this.recentVendors.length} recent vendors`);
dashLog.debug('First vendor:', this.recentVendors[0]);
} else {
dashLog.warn('No recent vendors found');
}
} catch (error) {
console.error('Failed to load recent vendors:', error);
}
},
/**
* Load recent import jobs
*/
async loadRecentImports() {
try {
const response = await apiClient.get('/admin/imports', {
skip: 0,
limit: 5
});
this.recentImports = response.imports || response;
} catch (error) {
console.error('Failed to load recent imports:', error);
}
},
/**
* Show different sections
*/
async showSection(section) {
this.currentSection = section;
// Load data based on section
if (section === 'vendors' && this.vendors.length === 0) {
await this.loadAllVendors();
} else if (section === 'users' && this.users.length === 0) {
await this.loadAllUsers();
} else if (section === 'imports' && this.imports.length === 0) {
await this.loadAllImports();
}
},
/**
* Load all vendors
*/
async loadAllVendors() {
this.loading = true;
try {
const response = await apiClient.get('/admin/vendors', {
skip: 0,
limit: 100
});
this.vendors = response.vendors || response;
} catch (error) {
console.error('Failed to load vendors:', error);
this.showErrorModal({
message: 'Failed to load vendors',
details: error.message
});
} finally {
this.loading = false;
}
},
/**
* Load all users
*/
async loadAllUsers() {
this.loading = true;
try {
const response = await apiClient.get('/admin/users', {
skip: 0,
limit: 100
});
this.users = response.users || response;
} catch (error) {
console.error('Failed to load users:', error);
this.showErrorModal({
message: 'Failed to load users',
details: error.message
});
} finally {
this.loading = false;
}
},
/**
* Load all import jobs
*/
async loadAllImports() {
this.loading = true;
try {
const response = await apiClient.get('/admin/imports', {
skip: 0,
limit: 100
});
this.imports = response.imports || response;
} catch (error) {
console.error('Failed to load import jobs:', error);
this.showErrorModal({
message: 'Failed to load import jobs',
details: error.message
});
} finally {
this.loading = false;
dashLog.error('Failed to load recent vendors:', error);
throw error;
}
},
@@ -186,18 +161,35 @@ function adminDashboard() {
* Format date for display
*/
formatDate(dateString) {
if (!dateString) return '-';
try {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
} catch (error) {
return dateString;
if (!dateString) {
dashLog.debug('formatDate called with empty dateString');
return '-';
}
const formatted = Utils.formatDate(dateString);
dashLog.debug(`Date formatted: ${dateString} -> ${formatted}`);
return formatted;
},
/**
* Navigate to vendor detail page
*/
viewVendor(vendorCode) {
dashLog.info('Navigating to vendor:', vendorCode);
const url = `/admin/vendors?code=${vendorCode}`;
dashLog.debug('Navigation URL:', url);
window.location.href = url;
},
/**
* Refresh dashboard data
*/
async refresh() {
dashLog.info('=== DASHBOARD REFRESH TRIGGERED ===');
await this.loadDashboard();
Utils.showToast('Dashboard refreshed', 'success');
dashLog.info('=== DASHBOARD REFRESH COMPLETE ===');
}
};
}
}
dashLog.info('Dashboard module loaded');

View File

@@ -1,7 +1,18 @@
// Admin Login Component
// static/admin/js/login.js
// Log levels: 0 = None, 1 = Error, 2 = Warning, 3 = Info, 4 = Debug
const LOG_LEVEL = 4; // Set to 4 for full debugging, 1 for errors only
const log = {
error: (...args) => LOG_LEVEL >= 1 && console.error('❌ [ERROR]', ...args),
warn: (...args) => LOG_LEVEL >= 2 && console.warn('⚠️ [WARN]', ...args),
info: (...args) => LOG_LEVEL >= 3 && console.info(' [INFO]', ...args),
debug: (...args) => LOG_LEVEL >= 4 && console.log('🔍 [DEBUG]', ...args)
};
function adminLogin() {
return {
dark: false, // For dark mode toggle
dark: false,
credentials: {
username: '',
password: ''
@@ -12,119 +23,192 @@ function adminLogin() {
errors: {},
init() {
// Check if already logged in
this.checkExistingAuth();
log.info('Login page initializing...');
log.debug('Current pathname:', window.location.pathname);
log.debug('Current URL:', window.location.href);
// Check for dark mode preference
// Just set theme - NO auth checking, NO token clearing!
this.dark = localStorage.getItem('theme') === 'dark';
},
log.debug('Dark mode:', this.dark);
checkExistingAuth() {
const token = localStorage.getItem('admin_token') || localStorage.getItem('token');
// DON'T clear tokens on init!
// If user lands here with a valid token, they might be navigating manually
// or got redirected. Let them try to login or navigate away.
const token = localStorage.getItem('admin_token');
if (token) {
// Verify token is still valid
const userData = localStorage.getItem('admin_user');
if (userData) {
try {
const user = JSON.parse(userData);
if (user.role === 'admin') {
window.location.href = '/static/admin/dashboard.html';
}
} catch (e) {
// Invalid user data, clear storage
this.clearAuthData();
}
}
log.warn('Found existing token on login page');
log.debug('Token preview:', token.substring(0, 20) + '...');
log.info('Not clearing token - user may have navigated here manually');
} else {
log.debug('No existing token found');
}
log.info('Login page initialization complete');
},
clearAuthData() {
clearTokens() {
log.debug('Clearing all auth tokens...');
const tokensBefore = {
admin_token: !!localStorage.getItem('admin_token'),
admin_user: !!localStorage.getItem('admin_user'),
token: !!localStorage.getItem('token')
};
log.debug('Tokens before clear:', tokensBefore);
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
localStorage.removeItem('token');
const tokensAfter = {
admin_token: !!localStorage.getItem('admin_token'),
admin_user: !!localStorage.getItem('admin_user'),
token: !!localStorage.getItem('token')
};
log.debug('Tokens after clear:', tokensAfter);
},
clearErrors() {
log.debug('Clearing form errors');
this.error = null;
this.success = null;
this.errors = {};
},
validateForm() {
log.debug('Validating login form...');
this.clearErrors();
let isValid = true;
if (!this.credentials.username.trim()) {
this.errors.username = 'Username is required';
log.warn('Validation failed: Username is required');
isValid = false;
}
if (!this.credentials.password) {
this.errors.password = 'Password is required';
log.warn('Validation failed: Password is required');
isValid = false;
} else if (this.credentials.password.length < 6) {
this.errors.password = 'Password must be at least 6 characters';
log.warn('Validation failed: Password too short');
isValid = false;
}
log.info('Form validation result:', isValid ? 'VALID' : 'INVALID');
return isValid;
},
async handleLogin() {
log.info('=== LOGIN ATTEMPT STARTED ===');
if (!this.validateForm()) {
log.warn('Form validation failed, aborting login');
return;
}
this.loading = true;
this.clearErrors();
log.debug('Login state set to loading');
try {
// Use apiClient from api-client.js
log.info('Calling login API endpoint...');
log.debug('Username:', this.credentials.username);
log.debug('API endpoint: /api/v1/admin/auth/login');
const startTime = Date.now();
const response = await apiClient.post('/admin/auth/login', {
username: this.credentials.username.trim(),
password: this.credentials.password
});
const duration = Date.now() - startTime;
log.info(`Login API response received in ${duration}ms`);
log.debug('Response structure:', {
hasToken: !!response.access_token,
hasUser: !!response.user,
userRole: response.user?.role,
userName: response.user?.username
});
// Validate response
if (!response.access_token) {
throw new Error('Invalid response from server');
log.error('Invalid response: No access token');
throw new Error('Invalid response from server - no token');
}
// Check if user is admin (if user data is provided)
if (response.user && response.user.role !== 'admin') {
log.error('Authorization failed: User is not admin', {
actualRole: response.user.role
});
throw new Error('Access denied. Admin privileges required.');
}
log.info('Login successful, storing authentication data...');
// Store authentication data
localStorage.setItem('admin_token', response.access_token);
localStorage.setItem('token', response.access_token); // Backup
localStorage.setItem('token', response.access_token);
log.debug('Token stored, length:', response.access_token.length);
if (response.user) {
localStorage.setItem('admin_user', JSON.stringify(response.user));
log.debug('User data stored:', {
username: response.user.username,
role: response.user.role,
id: response.user.id
});
}
// Verify storage
const storedToken = localStorage.getItem('admin_token');
const storedUser = localStorage.getItem('admin_user');
log.info('Storage verification:', {
tokenStored: !!storedToken,
userStored: !!storedUser,
tokenLength: storedToken?.length
});
// Show success message
this.success = 'Login successful! Redirecting...';
log.info('Success message displayed to user');
// Redirect after short delay
setTimeout(() => {
window.location.href = '/static/admin/dashboard.html';
}, 1000);
log.info('Redirecting to dashboard immediately...');
log.info('=== EXECUTING REDIRECT ===');
log.debug('Target URL: /admin/dashboard');
log.debug('Redirect method: window.location.href');
// Use href instead of replace to allow back button
// But redirect IMMEDIATELY - don't wait!
window.location.href = '/admin/dashboard';
} catch (error) {
console.error('Login error:', error);
this.error = error.message || 'Invalid username or password. Please try again.';
log.error('Login failed:', error);
log.error('Error details:', {
message: error.message,
name: error.name,
stack: error.stack
});
this.error = error.message || 'Invalid username or password. Please try again.';
log.info('Error message displayed to user:', this.error);
// Only clear tokens on login FAILURE
this.clearTokens();
log.info('Tokens cleared after error');
// Clear any partial auth data
this.clearAuthData();
} finally {
this.loading = false;
log.debug('Login state set to not loading');
log.info('=== LOGIN ATTEMPT FINISHED ===');
}
},
toggleDarkMode() {
log.debug('Toggling dark mode...');
this.dark = !this.dark;
localStorage.setItem('theme', this.dark ? 'dark' : 'light');
log.info('Dark mode:', this.dark ? 'ON' : 'OFF');
}
}
}

View File

@@ -46,7 +46,7 @@ function vendorEdit() {
// Check authentication
if (!Auth.isAuthenticated() || !Auth.isAdmin()) {
console.log('Not authenticated as admin, redirecting to login');
window.location.href = '/static/admin/login.html';
window.location.href = '/admin/login';
return;
}
@@ -60,7 +60,7 @@ function vendorEdit() {
if (!this.vendorId) {
console.error('No vendor ID in URL');
alert('No vendor ID provided');
window.location.href = '/static/admin/dashboard.html#vendors';
window.location.href = '/admin/dashboard.html#vendors';
return;
}
@@ -95,7 +95,7 @@ function vendorEdit() {
} catch (error) {
console.error('❌ Failed to load vendor:', error);
Utils.showToast('Failed to load vendor details: ' + (error.message || 'Unknown error'), 'error');
window.location.href = '/static/admin/dashboard.html#vendors';
window.location.href = '/admin/dashboard';
} finally {
this.loadingVendor = false;
}
@@ -331,7 +331,7 @@ function vendorEdit() {
// Redirect to login after brief delay
setTimeout(() => {
window.location.href = '/static/admin/login.html';
window.location.href = '/admin/login';
}, 500);
},
};

View File

@@ -1,3 +1,4 @@
// static/admin/js/vendors.js
// Admin Vendor Creation Component
function vendorCreation() {
return {
@@ -26,7 +27,8 @@ function vendorCreation() {
checkAuth() {
if (!Auth.isAuthenticated()) {
window.location.href = '/static/admin/login.html';
// ← CHANGED: Use new Jinja2 route
window.location.href = '/admin/login';
return false;
}
@@ -34,7 +36,8 @@ function vendorCreation() {
if (!user || user.role !== 'admin') {
Utils.showToast('Access denied. Admin privileges required.', 'error');
Auth.logout();
window.location.href = '/static/admin/login.html';
// ← CHANGED: Use new Jinja2 route
window.location.href = '/admin/login';
return false;
}
@@ -52,11 +55,14 @@ function vendorCreation() {
Auth.logout();
Utils.showToast('Logged out successfully', 'success', 2000);
setTimeout(() => {
window.location.href = '/static/admin/login.html';
// ← CHANGED: Use new Jinja2 route
window.location.href = '/admin/login';
}, 500);
}
},
// ... rest of the methods stay the same ...
// Auto-format vendor code (uppercase)
formatVendorCode() {
this.formData.vendor_code = this.formData.vendor_code