feat: implement admin-users management with super admin restriction

- Add /admin/admin-users routes for managing admin users (super admin only)
- Remove vendor role from user creation form (vendors created via company hierarchy)
- Add admin-users.html and admin-user-detail.html templates
- Add admin-users.js and admin-user-detail.js for frontend logic
- Move database operations to admin_platform_service (list, get, create, delete, toggle status)
- Update sidebar to show Admin Users section only for super admins
- Add isSuperAdmin computed property to init-alpine.js
- Fix /api/v1 prefix issues in JS files (apiClient already adds prefix)
- Update architecture rule JS-012 to catch more variable patterns (url, endpoint, path)
- Replace inline SVGs with $icon() helper in select-platform.html

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-24 21:28:46 +01:00
parent 9d28210cf1
commit 7e68b93132
16 changed files with 1691 additions and 325 deletions

View File

@@ -0,0 +1,196 @@
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/admin-user-detail.js
// Create custom logger for admin user detail
const adminUserDetailLog = window.LogConfig.createLogger('ADMIN-USER-DETAIL');
function adminUserDetailPage() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// Admin user detail page specific state
currentPage: 'admin-users',
adminUser: null,
loading: false,
saving: false,
error: null,
userId: null,
currentUserId: null,
// Initialize
async init() {
adminUserDetailLog.info('=== ADMIN USER DETAIL PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._adminUserDetailInitialized) {
adminUserDetailLog.warn('Admin user detail page already initialized, skipping...');
return;
}
window._adminUserDetailInitialized = true;
// Get current user ID
this.currentUserId = this.adminProfile?.id || null;
// Get user ID from URL
const path = window.location.pathname;
const match = path.match(/\/admin\/admin-users\/(\d+)$/);
if (match) {
this.userId = match[1];
adminUserDetailLog.info('Viewing admin user:', this.userId);
await this.loadAdminUser();
} else {
adminUserDetailLog.error('No user ID in URL');
this.error = 'Invalid admin user URL';
Utils.showToast('Invalid admin user URL', 'error');
}
adminUserDetailLog.info('=== ADMIN USER DETAIL PAGE INITIALIZATION COMPLETE ===');
},
// Load admin user data
async loadAdminUser() {
adminUserDetailLog.info('Loading admin user details...');
this.loading = true;
this.error = null;
try {
const url = `/admin/admin-users/${this.userId}`;
window.LogConfig.logApiCall('GET', url, null, 'request');
const startTime = performance.now();
const response = await apiClient.get(url);
const duration = performance.now() - startTime;
window.LogConfig.logApiCall('GET', url, response, 'response');
window.LogConfig.logPerformance('Load Admin User Details', duration);
// Transform API response to expected format
this.adminUser = {
...response,
platforms: (response.platform_assignments || []).map(pa => ({
id: pa.platform_id,
code: pa.platform_code,
name: pa.platform_name
})),
full_name: [response.first_name, response.last_name].filter(Boolean).join(' ') || null
};
adminUserDetailLog.info(`Admin user loaded in ${duration}ms`, {
id: this.adminUser.id,
username: this.adminUser.username,
is_super_admin: this.adminUser.is_super_admin,
is_active: this.adminUser.is_active
});
adminUserDetailLog.debug('Full admin user data:', this.adminUser);
} catch (error) {
window.LogConfig.logError(error, 'Load Admin User Details');
this.error = error.message || 'Failed to load admin user details';
Utils.showToast('Failed to load admin user details', 'error');
} finally {
this.loading = false;
}
},
// Format date
formatDate(dateString) {
if (!dateString) {
return '-';
}
return Utils.formatDate(dateString);
},
// Toggle admin user status
async toggleStatus() {
const action = this.adminUser.is_active ? 'deactivate' : 'activate';
adminUserDetailLog.info(`Toggle status: ${action}`);
// Prevent self-deactivation
if (this.adminUser.id === this.currentUserId) {
Utils.showToast('You cannot deactivate your own account', 'error');
return;
}
if (!confirm(`Are you sure you want to ${action} "${this.adminUser.username}"?`)) {
adminUserDetailLog.info('Status toggle cancelled by user');
return;
}
this.saving = true;
try {
const url = `/admin/admin-users/${this.userId}/status`;
window.LogConfig.logApiCall('PUT', url, null, 'request');
const response = await apiClient.put(url);
window.LogConfig.logApiCall('PUT', url, response, 'response');
this.adminUser.is_active = response.is_active;
Utils.showToast(`Admin user ${action}d successfully`, 'success');
adminUserDetailLog.info(`Admin user ${action}d successfully`);
} catch (error) {
window.LogConfig.logError(error, `Toggle Status (${action})`);
Utils.showToast(error.message || `Failed to ${action} admin user`, 'error');
} finally {
this.saving = false;
}
},
// Delete admin user
async deleteAdminUser() {
adminUserDetailLog.info('Delete admin user requested:', this.userId);
// Prevent self-deletion
if (this.adminUser.id === this.currentUserId) {
Utils.showToast('You cannot delete your own account', 'error');
return;
}
if (!confirm(`Are you sure you want to delete admin user "${this.adminUser.username}"?\n\nThis action cannot be undone.`)) {
adminUserDetailLog.info('Delete cancelled by user');
return;
}
// Second confirmation for safety
if (!confirm(`FINAL CONFIRMATION\n\nAre you absolutely sure you want to delete "${this.adminUser.username}"?`)) {
adminUserDetailLog.info('Delete cancelled by user (second confirmation)');
return;
}
this.saving = true;
try {
const url = `/admin/admin-users/${this.userId}`;
window.LogConfig.logApiCall('DELETE', url, null, 'request');
await apiClient.delete(url);
window.LogConfig.logApiCall('DELETE', url, null, 'response');
Utils.showToast('Admin user deleted successfully', 'success');
adminUserDetailLog.info('Admin user deleted successfully');
// Redirect to admin users list
setTimeout(() => window.location.href = '/admin/admin-users', 1500);
} catch (error) {
window.LogConfig.logError(error, 'Delete Admin User');
Utils.showToast(error.message || 'Failed to delete admin user', 'error');
} finally {
this.saving = false;
}
},
// Refresh admin user data
async refresh() {
adminUserDetailLog.info('=== ADMIN USER REFRESH TRIGGERED ===');
await this.loadAdminUser();
Utils.showToast('Admin user details refreshed', 'success');
adminUserDetailLog.info('=== ADMIN USER REFRESH COMPLETE ===');
}
};
}
adminUserDetailLog.info('Admin user detail module loaded');

View File

@@ -0,0 +1,330 @@
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/admin-users.js
// Create custom logger for admin users
const adminUsersLog = window.LogConfig.createLogger('ADMIN-USERS');
function adminUsersPage() {
return {
// Inherit base layout functionality
...data(),
// Set page identifier
currentPage: 'admin-users',
// State
adminUsers: [],
loading: false,
error: null,
currentUserId: null,
filters: {
search: '',
is_super_admin: '',
is_active: ''
},
stats: {
total_admins: 0,
super_admins: 0,
platform_admins: 0,
active_admins: 0
},
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Initialization
async init() {
adminUsersLog.info('=== ADMIN USERS PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._adminUsersInitialized) {
adminUsersLog.warn('Admin users page already initialized, skipping...');
return;
}
window._adminUsersInitialized = true;
// Get current user ID
this.currentUserId = this.adminProfile?.id || null;
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
await this.loadAdminUsers();
await this.loadStats();
adminUsersLog.info('=== ADMIN USERS PAGE INITIALIZATION COMPLETE ===');
},
// Format date helper
formatDate(dateString) {
if (!dateString) return '-';
return Utils.formatDate(dateString);
},
// Computed: Total number of pages
get totalPages() {
return this.pagination.pages;
},
// Computed: Start index for pagination display
get startIndex() {
if (this.pagination.total === 0) return 0;
return (this.pagination.page - 1) * this.pagination.per_page + 1;
},
// Computed: End index for pagination display
get endIndex() {
const end = this.pagination.page * this.pagination.per_page;
return end > this.pagination.total ? this.pagination.total : end;
},
// Computed: Generate page numbers array with ellipsis
get pageNumbers() {
const pages = [];
const totalPages = this.totalPages;
const current = this.pagination.page;
if (totalPages <= 7) {
// Show all pages if 7 or fewer
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
// Always show first page
pages.push(1);
if (current > 3) {
pages.push('...');
}
// Show pages around current page
const start = Math.max(2, current - 1);
const end = Math.min(totalPages - 1, current + 1);
for (let i = start; i <= end; i++) {
pages.push(i);
}
if (current < totalPages - 2) {
pages.push('...');
}
// Always show last page
pages.push(totalPages);
}
return pages;
},
// Load admin users from API
async loadAdminUsers() {
adminUsersLog.info('Loading admin users...');
this.loading = true;
this.error = null;
try {
const params = new URLSearchParams();
// Calculate skip for pagination
const skip = (this.pagination.page - 1) * this.pagination.per_page;
params.append('skip', skip);
params.append('limit', this.pagination.per_page);
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.is_super_admin === 'false') {
params.append('include_super_admins', 'false');
}
if (this.filters.is_active !== '') {
params.append('is_active', this.filters.is_active);
}
const url = `/admin/admin-users?${params}`;
window.LogConfig.logApiCall('GET', url, null, 'request');
const startTime = performance.now();
const response = await apiClient.get(url);
const duration = performance.now() - startTime;
window.LogConfig.logApiCall('GET', url, response, 'response');
window.LogConfig.logPerformance('Load Admin Users', duration);
// Transform API response to expected format
let admins = response.admins || [];
// Apply client-side filtering for search and super admin status
if (this.filters.search) {
const searchLower = this.filters.search.toLowerCase();
admins = admins.filter(admin =>
admin.username?.toLowerCase().includes(searchLower) ||
admin.email?.toLowerCase().includes(searchLower) ||
admin.first_name?.toLowerCase().includes(searchLower) ||
admin.last_name?.toLowerCase().includes(searchLower)
);
}
// Filter by super admin status
if (this.filters.is_super_admin === 'true') {
admins = admins.filter(admin => admin.is_super_admin);
}
// Filter by active status
if (this.filters.is_active !== '') {
const isActive = this.filters.is_active === 'true';
admins = admins.filter(admin => admin.is_active === isActive);
}
// Transform platform_assignments to platforms for template
this.adminUsers = admins.map(admin => ({
...admin,
platforms: (admin.platform_assignments || []).map(pa => ({
id: pa.platform_id,
code: pa.platform_code,
name: pa.platform_name
})),
full_name: [admin.first_name, admin.last_name].filter(Boolean).join(' ') || null
}));
this.pagination.total = response.total || this.adminUsers.length;
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page) || 1;
adminUsersLog.info(`Loaded ${this.adminUsers.length} admin users`);
} catch (error) {
window.LogConfig.logError(error, 'Load Admin Users');
this.error = error.message || 'Failed to load admin users';
Utils.showToast('Failed to load admin users', 'error');
} finally {
this.loading = false;
}
},
// Load statistics (computed from admin users data)
async loadStats() {
adminUsersLog.info('Loading admin user statistics...');
try {
// Fetch all admin users to compute stats
const url = '/admin/admin-users?skip=0&limit=1000';
window.LogConfig.logApiCall('GET', url, null, 'request');
const response = await apiClient.get(url);
window.LogConfig.logApiCall('GET', url, response, 'response');
const admins = response.admins || [];
// Compute stats from the data
this.stats = {
total_admins: admins.length,
super_admins: admins.filter(a => a.is_super_admin).length,
platform_admins: admins.filter(a => !a.is_super_admin).length,
active_admins: admins.filter(a => a.is_active).length
};
adminUsersLog.debug('Stats computed:', this.stats);
} catch (error) {
window.LogConfig.logError(error, 'Load Admin Stats');
// Stats are non-critical, don't show error toast
}
},
// Search with debounce
debouncedSearch() {
// Clear existing timeout
if (this._searchTimeout) {
clearTimeout(this._searchTimeout);
}
// Set new timeout
this._searchTimeout = setTimeout(() => {
adminUsersLog.info('Search triggered:', this.filters.search);
this.pagination.page = 1;
this.loadAdminUsers();
}, 300);
},
// Pagination
nextPage() {
if (this.pagination.page < this.pagination.pages) {
this.pagination.page++;
adminUsersLog.info('Next page:', this.pagination.page);
this.loadAdminUsers();
}
},
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
adminUsersLog.info('Previous page:', this.pagination.page);
this.loadAdminUsers();
}
},
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
adminUsersLog.info('Go to page:', this.pagination.page);
this.loadAdminUsers();
}
},
// Actions
viewAdminUser(admin) {
adminUsersLog.info('View admin user:', admin.username);
window.location.href = `/admin/admin-users/${admin.id}`;
},
editAdminUser(admin) {
adminUsersLog.info('Edit admin user:', admin.username);
window.location.href = `/admin/admin-users/${admin.id}/edit`;
},
async deleteAdminUser(admin) {
adminUsersLog.warn('Delete admin user requested:', admin.username);
// Prevent self-deletion
if (admin.id === this.currentUserId) {
Utils.showToast('You cannot delete your own account', 'error');
return;
}
if (!confirm(`Are you sure you want to delete admin user "${admin.username}"?\n\nThis action cannot be undone.`)) {
adminUsersLog.info('Delete cancelled by user');
return;
}
// Second confirmation for safety
if (!confirm(`FINAL CONFIRMATION\n\nAre you absolutely sure you want to delete "${admin.username}"?`)) {
adminUsersLog.info('Delete cancelled by user (second confirmation)');
return;
}
try {
const url = `/admin/admin-users/${admin.id}`;
window.LogConfig.logApiCall('DELETE', url, null, 'request');
await apiClient.delete(url);
Utils.showToast('Admin user deleted successfully', 'success');
adminUsersLog.info('Admin user deleted successfully');
await this.loadAdminUsers();
await this.loadStats();
} catch (error) {
window.LogConfig.logError(error, 'Delete Admin User');
Utils.showToast(error.message || 'Failed to delete admin user', 'error');
}
},
openCreateModal() {
adminUsersLog.info('Open create admin user page');
window.location.href = '/admin/admin-users/create';
}
};
}
adminUsersLog.info('Admin users module loaded');

View File

@@ -27,9 +27,11 @@ function data() {
// Default state: Platform Administration open, others closed
const defaultSections = {
superAdmin: true, // Super admin section (only visible to super admins)
platformAdmin: true,
vendorOps: false,
marketplace: false,
billing: false,
contentMgmt: false,
devTools: false,
platformHealth: false,
@@ -75,12 +77,28 @@ function data() {
}
}
// Helper to get admin profile from localStorage
function getAdminProfileFromStorage() {
try {
// Check admin_user first (set by login), then adminProfile (legacy)
const stored = window.localStorage.getItem('admin_user') ||
window.localStorage.getItem('adminProfile');
if (stored) {
return JSON.parse(stored);
}
} catch (e) {
console.warn('Failed to parse admin profile from localStorage:', e);
}
return null;
}
// Map pages to their parent sections
const pageSectionMap = {
// Super Admin section
'admin-users': 'superAdmin',
// Platform Administration
companies: 'platformAdmin',
vendors: 'platformAdmin',
users: 'platformAdmin',
messages: 'platformAdmin',
// Vendor Operations (Products, Customers, Inventory, Orders, Shipping)
'marketplace-products': 'vendorOps',
@@ -185,7 +203,16 @@ function data() {
// ─────────────────────────────────────────────────────────────────
// Page identifier - will be set by individual pages
// ─────────────────────────────────────────────────────────────────
currentPage: ''
currentPage: '',
// ─────────────────────────────────────────────────────────────────
// Admin profile and super admin flag
// ─────────────────────────────────────────────────────────────────
adminProfile: getAdminProfileFromStorage(),
get isSuperAdmin() {
return this.adminProfile?.is_super_admin === true;
}
}
}

View File

@@ -187,7 +187,7 @@ function adminLogin() {
// Check if platform selection is required
try {
loginLog.info('Checking accessible platforms...');
const platformsResponse = await apiClient.get('/api/v1/admin/auth/accessible-platforms');
const platformsResponse = await apiClient.get('/admin/auth/accessible-platforms');
loginLog.debug('Accessible platforms response:', platformsResponse);
if (platformsResponse.requires_platform_selection) {

View File

@@ -15,6 +15,13 @@ function selectPlatform() {
async init() {
platformLog.info('=== PLATFORM SELECTION PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._platformSelectInitialized) {
platformLog.warn('Platform selection page already initialized, skipping...');
return;
}
window._platformSelectInitialized = true;
// Set theme
this.dark = localStorage.getItem('theme') === 'dark';
@@ -36,7 +43,7 @@ function selectPlatform() {
try {
platformLog.info('Fetching accessible platforms...');
const response = await apiClient.get('/api/v1/admin/auth/accessible-platforms');
const response = await apiClient.get('/admin/auth/accessible-platforms');
platformLog.debug('Platforms response:', response);
this.isSuperAdmin = response.is_super_admin;
@@ -83,7 +90,7 @@ function selectPlatform() {
try {
const response = await apiClient.post(
`/api/v1/admin/auth/select-platform?platform_id=${platform.id}`
`/admin/auth/select-platform?platform_id=${platform.id}`
);
platformLog.debug('Platform selection response:', response);
@@ -125,25 +132,20 @@ function selectPlatform() {
}
},
logout() {
async logout() {
platformLog.info('Logging out...');
fetch('/api/v1/admin/auth/logout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
}
})
.catch((error) => {
try {
await apiClient.post('/admin/auth/logout');
} catch (error) {
platformLog.error('Logout API error:', error);
})
.finally(() => {
} finally {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
localStorage.removeItem('admin_platform');
localStorage.removeItem('token');
window.location.href = '/admin/login';
});
}
},
toggleDarkMode() {

View File

@@ -1,15 +1,15 @@
// static/admin/js/user-create.js
// Create custom logger for user create
const userCreateLog = window.LogConfig.createLogger('USER-CREATE');
// Create custom logger for admin user create
const userCreateLog = window.LogConfig.createLogger('ADMIN-USER-CREATE');
function adminUserCreate() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// User create page specific state
currentPage: 'user-create',
// Admin user create page specific state
currentPage: 'admin-users',
loading: false,
formData: {
username: '',
@@ -17,7 +17,6 @@ function adminUserCreate() {
password: '',
first_name: '',
last_name: '',
role: 'vendor',
is_super_admin: false,
platform_ids: []
},
@@ -27,11 +26,11 @@ function adminUserCreate() {
// Initialize
async init() {
userCreateLog.info('=== USER CREATE PAGE INITIALIZING ===');
userCreateLog.info('=== ADMIN USER CREATE PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._userCreateInitialized) {
userCreateLog.warn('User create page already initialized, skipping...');
userCreateLog.warn('Admin user create page already initialized, skipping...');
return;
}
window._userCreateInitialized = true;
@@ -39,7 +38,7 @@ function adminUserCreate() {
// Load platforms for admin assignment
await this.loadPlatforms();
userCreateLog.info('=== USER CREATE PAGE INITIALIZATION COMPLETE ===');
userCreateLog.info('=== ADMIN USER CREATE PAGE INITIALIZATION COMPLETE ===');
},
// Load available platforms
@@ -55,16 +54,6 @@ function adminUserCreate() {
}
},
// Handle role change
onRoleChange() {
userCreateLog.debug('Role changed to:', this.formData.role);
if (this.formData.role !== 'admin') {
// Reset admin-specific fields when switching away from admin
this.formData.is_super_admin = false;
this.formData.platform_ids = [];
}
},
// Validate form
validateForm() {
this.errors = {};
@@ -79,8 +68,8 @@ function adminUserCreate() {
this.errors.password = 'Password must be at least 6 characters';
}
// Admin-specific validation
if (this.formData.role === 'admin' && !this.formData.is_super_admin) {
// Platform admin validation: must have at least one platform
if (!this.formData.is_super_admin) {
if (!this.formData.platform_ids || this.formData.platform_ids.length === 0) {
this.errors.platform_ids = 'Platform admins must be assigned to at least one platform';
}
@@ -91,7 +80,7 @@ function adminUserCreate() {
// Submit form
async handleSubmit() {
userCreateLog.info('=== CREATING USER ===');
userCreateLog.info('=== CREATING ADMIN USER ===');
userCreateLog.debug('Form data:', { ...this.formData, password: '[REDACTED]' });
if (!this.validateForm()) {
@@ -103,55 +92,38 @@ function adminUserCreate() {
this.saving = true;
try {
let url, payload, response;
if (this.formData.role === 'admin') {
// Use admin-users endpoint for creating admin users
url = '/api/v1/admin/admin-users';
payload = {
email: this.formData.email,
username: this.formData.username,
password: this.formData.password,
first_name: this.formData.first_name || null,
last_name: this.formData.last_name || null,
is_super_admin: this.formData.is_super_admin,
platform_ids: this.formData.is_super_admin ? [] : this.formData.platform_ids.map(id => parseInt(id))
};
} else {
// Use regular users endpoint for vendor users
url = '/admin/users';
payload = {
email: this.formData.email,
username: this.formData.username,
password: this.formData.password,
first_name: this.formData.first_name || null,
last_name: this.formData.last_name || null,
role: this.formData.role
};
}
// Use admin-users endpoint for creating admin users
const url = '/admin/admin-users';
const payload = {
email: this.formData.email,
username: this.formData.username,
password: this.formData.password,
first_name: this.formData.first_name || null,
last_name: this.formData.last_name || null,
is_super_admin: this.formData.is_super_admin,
platform_ids: this.formData.is_super_admin ? [] : this.formData.platform_ids.map(id => parseInt(id))
};
window.LogConfig.logApiCall('POST', url, { ...payload, password: '[REDACTED]' }, 'request');
const startTime = performance.now();
response = await apiClient.post(url, payload);
const response = await apiClient.post(url, payload);
const duration = performance.now() - startTime;
window.LogConfig.logApiCall('POST', url, response, 'response');
window.LogConfig.logPerformance('Create User', duration);
window.LogConfig.logPerformance('Create Admin User', duration);
const userType = this.formData.role === 'admin'
? (this.formData.is_super_admin ? 'Super admin' : 'Platform admin')
: 'User';
const userType = this.formData.is_super_admin ? 'Super admin' : 'Platform admin';
Utils.showToast(`${userType} created successfully`, 'success');
userCreateLog.info(`${userType} created successfully in ${duration}ms`, response);
// Redirect to the new user's detail page
// Redirect to the admin users list
setTimeout(() => {
window.location.href = `/admin/users/${response.id}`;
window.location.href = `/admin/admin-users/${response.id}`;
}, 1500);
} catch (error) {
window.LogConfig.logError(error, 'Create User');
window.LogConfig.logError(error, 'Create Admin User');
// Handle validation errors
if (error.details && error.details.validation_errors) {
@@ -173,13 +145,13 @@ function adminUserCreate() {
}
}
Utils.showToast(error.message || 'Failed to create user', 'error');
Utils.showToast(error.message || 'Failed to create admin user', 'error');
} finally {
this.saving = false;
userCreateLog.info('=== USER CREATION COMPLETE ===');
userCreateLog.info('=== ADMIN USER CREATION COMPLETE ===');
}
}
};
}
userCreateLog.info('User create module loaded');
userCreateLog.info('Admin user create module loaded');