feat: add dedicated admin user edit page with platform management

The admin user edit page now uses a dedicated template and JS file
that properly matches the /admin/admin-users/{id}/edit URL pattern.
The page allows super admins to:
- Toggle super admin status
- Toggle active status
- Manage platform assignments for platform admins
- Delete admin users

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-24 21:32:28 +01:00
parent 7e68b93132
commit 011744966b
3 changed files with 593 additions and 1 deletions

View File

@@ -499,7 +499,7 @@ async def admin_user_edit_page(
raise HTTPException(status_code=403, detail="Super admin access required")
return templates.TemplateResponse(
"admin/user-edit.html",
"admin/admin-user-edit.html",
{
"request": request,
"user": current_user,

View File

@@ -0,0 +1,259 @@
{# app/templates/admin/admin-user-edit.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/alerts.html' import loading_state %}
{% from 'shared/macros/headers.html' import edit_page_header %}
{% block title %}Edit Admin User{% endblock %}
{% block alpine_data %}adminUserEditPage(){% endblock %}
{% block content %}
{% call edit_page_header('Edit Admin User', '/admin/admin-users', subtitle_show='adminUser', back_label='Back to Admin Users') %}
@<span x-text="adminUser?.username"></span>
{% endcall %}
{{ loading_state('Loading admin user...', show_condition='loading') }}
<!-- Edit Content -->
<div x-show="!loading && adminUser">
<!-- Quick Actions Card -->
<div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
Quick Actions
</h3>
<div class="flex flex-wrap items-center gap-3">
<!-- Toggle Active Status -->
<button
@click="toggleStatus()"
:disabled="saving || adminUser?.id === currentUserId"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 rounded-lg focus:outline-none disabled:opacity-50"
:class="adminUser?.is_active ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700'"
:title="adminUser?.id === currentUserId ? 'Cannot deactivate yourself' : ''">
<span x-html="$icon(adminUser?.is_active ? 'user-x' : 'user-check', 'w-4 h-4 mr-2')"></span>
<span x-text="adminUser?.is_active ? 'Deactivate' : 'Activate'"></span>
</button>
<!-- Toggle Super Admin -->
<button
@click="toggleSuperAdmin()"
:disabled="saving || (adminUser?.id === currentUserId && adminUser?.is_super_admin)"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 rounded-lg focus:outline-none disabled:opacity-50"
:class="adminUser?.is_super_admin ? 'bg-yellow-600 hover:bg-yellow-700' : 'bg-purple-600 hover:bg-purple-700'"
:title="adminUser?.id === currentUserId && adminUser?.is_super_admin ? 'Cannot demote yourself' : ''">
<span x-html="$icon(adminUser?.is_super_admin ? 'shield-x' : 'shield-check', 'w-4 h-4 mr-2')"></span>
<span x-text="adminUser?.is_super_admin ? 'Demote from Super Admin' : 'Promote to Super Admin'"></span>
</button>
<!-- Status Badges -->
<div class="ml-auto flex items-center gap-2">
<span
x-show="adminUser?.is_super_admin"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-yellow-700 bg-yellow-100 rounded-full dark:bg-yellow-700 dark:text-yellow-100">
Super Admin
</span>
<span
x-show="!adminUser?.is_super_admin"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-purple-700 bg-purple-100 rounded-full dark:bg-purple-700 dark:text-purple-100">
Platform Admin
</span>
<span
x-show="adminUser?.is_active"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
Active
</span>
<span
x-show="!adminUser?.is_active"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
Inactive
</span>
</div>
</div>
</div>
<!-- Admin Info Card -->
<div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
Admin Information
</h3>
<div class="grid gap-6 md:grid-cols-2">
<!-- Left Column -->
<div class="space-y-4">
<div>
<span class="text-sm text-gray-600 dark:text-gray-400">User ID</span>
<p class="text-gray-800 dark:text-gray-200 font-medium" x-text="adminUser?.id"></p>
</div>
<div>
<span class="text-sm text-gray-600 dark:text-gray-400">Username</span>
<p class="text-gray-800 dark:text-gray-200 font-medium" x-text="adminUser?.username"></p>
</div>
<div>
<span class="text-sm text-gray-600 dark:text-gray-400">Email</span>
<p class="text-gray-800 dark:text-gray-200 font-medium" x-text="adminUser?.email"></p>
</div>
</div>
<!-- Right Column -->
<div class="space-y-4">
<div>
<span class="text-sm text-gray-600 dark:text-gray-400">First Name</span>
<p class="text-gray-800 dark:text-gray-200 font-medium" x-text="adminUser?.first_name || '-'"></p>
</div>
<div>
<span class="text-sm text-gray-600 dark:text-gray-400">Last Name</span>
<p class="text-gray-800 dark:text-gray-200 font-medium" x-text="adminUser?.last_name || '-'"></p>
</div>
</div>
</div>
</div>
<!-- Platform Assignments Card (Only for Platform Admins) -->
<template x-if="!adminUser?.is_super_admin">
<div class="px-4 py-3 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
Platform Assignments
</h3>
<button
@click="openPlatformModal()"
:disabled="saving || availablePlatformsForAssignment.length === 0"
class="flex items-center px-3 py-1.5 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50">
<span x-html="$icon('plus', 'w-4 h-4 mr-1')"></span>
Add Platform
</button>
</div>
<!-- Assigned Platforms List -->
<div x-show="adminUser?.platforms?.length > 0" class="space-y-2">
<template x-for="platform in adminUser?.platforms" :key="platform.id">
<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg dark:bg-gray-700">
<div class="flex items-center">
<div class="flex-shrink-0 w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center mr-3">
<span class="text-lg font-bold text-purple-600 dark:text-purple-400" x-text="platform.code.charAt(0).toUpperCase()"></span>
</div>
<div>
<p class="font-medium text-gray-800 dark:text-gray-200" x-text="platform.name"></p>
<p class="text-sm text-gray-500 dark:text-gray-400" x-text="platform.code"></p>
</div>
</div>
<button
@click="removePlatform(platform.id)"
:disabled="saving || adminUser?.platforms?.length <= 1"
class="p-2 text-red-600 hover:bg-red-100 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
:title="adminUser?.platforms?.length <= 1 ? 'Must have at least one platform' : 'Remove platform'">
<span x-html="$icon('x', 'w-5 h-5')"></span>
</button>
</div>
</template>
</div>
<!-- No Platforms Message -->
<div x-show="!adminUser?.platforms?.length" class="text-center py-6">
<span x-html="$icon('exclamation', 'mx-auto h-12 w-12 text-gray-400')"></span>
<p class="mt-2 text-sm text-gray-500 dark:text-gray-400">No platforms assigned</p>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
<span x-html="$icon('information-circle', 'w-4 h-4 inline mr-1')"></span>
Platform admins must be assigned to at least one platform.
</p>
</div>
</template>
<!-- Super Admin Notice -->
<template x-if="adminUser?.is_super_admin">
<div class="px-4 py-3 mb-6 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div class="flex items-center">
<span x-html="$icon('shield-check', 'w-6 h-6 text-yellow-600 dark:text-yellow-400 mr-3')"></span>
<div>
<h4 class="font-medium text-yellow-800 dark:text-yellow-200">Super Admin Access</h4>
<p class="text-sm text-yellow-700 dark:text-yellow-300">This user has full access to all platforms and administrative functions.</p>
</div>
</div>
</div>
</template>
<!-- Danger Zone Card -->
<div class="px-4 py-3 bg-white rounded-lg shadow-md dark:bg-gray-800 border border-red-200 dark:border-red-800">
<h3 class="mb-4 text-lg font-semibold text-red-700 dark:text-red-400">
Danger Zone
</h3>
<div class="flex flex-wrap items-center gap-3">
<!-- Delete Admin User Button -->
<button
@click="deleteAdminUser()"
:disabled="saving || adminUser?.id === currentUserId"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-white transition-colors duration-150 bg-red-600 border border-transparent rounded-lg hover:bg-red-700 focus:outline-none focus:shadow-outline-red disabled:opacity-50"
:title="adminUser?.id === currentUserId ? 'Cannot delete yourself' : 'Delete this admin user'">
<span x-html="$icon('delete', 'w-4 h-4 mr-2')"></span>
Delete Admin User
</button>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
<span x-html="$icon('exclamation', 'w-4 h-4 inline mr-1 text-red-500')"></span>
Deleting an admin user is permanent and cannot be undone.
</p>
</div>
</div>
<!-- Platform Assignment Modal -->
<div
x-show="showPlatformModal"
x-cloak
class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
@click.self="showPlatformModal = false"
@keydown.escape.window="showPlatformModal = false">
<div class="w-full max-w-md p-6 bg-white rounded-lg shadow-xl dark:bg-gray-800">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
Assign Platform
</h3>
<button
@click="showPlatformModal = false"
class="p-1 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
<span x-html="$icon('x', 'w-5 h-5')"></span>
</button>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Select Platform
</label>
<select
x-model="selectedPlatformId"
class="block w-full text-sm dark:text-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple form-select">
<option value="">Choose a platform...</option>
<template x-for="platform in availablePlatformsForAssignment" :key="platform.id">
<option :value="platform.id" x-text="`${platform.name} (${platform.code})`"></option>
</template>
</select>
</div>
<div x-show="availablePlatformsForAssignment.length === 0" class="mb-4 p-3 bg-gray-100 dark:bg-gray-700 rounded-lg">
<p class="text-sm text-gray-600 dark:text-gray-400">
All available platforms have been assigned to this admin.
</p>
</div>
<div class="flex justify-end gap-3">
<button
@click="showPlatformModal = false"
class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600">
Cancel
</button>
<button
@click="assignPlatform(selectedPlatformId)"
:disabled="!selectedPlatformId || saving"
class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50">
<span x-show="!saving">Assign Platform</span>
<span x-show="saving" class="flex items-center">
<span x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
Assigning...
</span>
</button>
</div>
</div>
</div>
{% endblock %}
{% block extra_scripts %}
<script src="{{ url_for('static', path='admin/js/admin-user-edit.js') }}"></script>
{% endblock %}

View File

@@ -0,0 +1,333 @@
// static/admin/js/admin-user-edit.js
// Create custom logger for admin user edit
const adminUserEditLog = window.LogConfig.createLogger('ADMIN-USER-EDIT');
function adminUserEditPage() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// Admin user edit page specific state
currentPage: 'admin-users',
loading: false,
adminUser: null,
platforms: [],
errors: {},
saving: false,
userId: null,
currentUserId: null,
// Platform assignment state
showPlatformModal: false,
availablePlatforms: [],
selectedPlatformId: null,
// Initialize
async init() {
adminUserEditLog.info('=== ADMIN USER EDIT PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._adminUserEditInitialized) {
adminUserEditLog.warn('Admin user edit page already initialized, skipping...');
return;
}
window._adminUserEditInitialized = 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+)\/edit/);
if (match) {
this.userId = parseInt(match[1], 10);
adminUserEditLog.info('Editing admin user:', this.userId);
await this.loadAdminUser();
await this.loadAllPlatforms();
} else {
adminUserEditLog.error('No user ID in URL');
Utils.showToast('Invalid admin user URL', 'error');
setTimeout(() => window.location.href = '/admin/admin-users', 2000);
}
adminUserEditLog.info('=== ADMIN USER EDIT PAGE INITIALIZATION COMPLETE ===');
},
// Load admin user data
async loadAdminUser() {
adminUserEditLog.info('Loading admin user data...');
this.loading = true;
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', duration);
// Transform API response
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
};
adminUserEditLog.info(`Admin user loaded in ${duration}ms`, {
id: this.adminUser.id,
username: this.adminUser.username,
is_super_admin: this.adminUser.is_super_admin
});
} catch (error) {
window.LogConfig.logError(error, 'Load Admin User');
Utils.showToast('Failed to load admin user', 'error');
setTimeout(() => window.location.href = '/admin/admin-users', 2000);
} finally {
this.loading = false;
}
},
// Load all platforms for assignment
async loadAllPlatforms() {
try {
adminUserEditLog.debug('Loading all platforms...');
const response = await apiClient.get('/admin/platforms');
this.platforms = response.platforms || response.items || [];
adminUserEditLog.debug(`Loaded ${this.platforms.length} platforms`);
} catch (error) {
adminUserEditLog.error('Failed to load platforms:', error);
this.platforms = [];
}
},
// Get available platforms (not yet assigned)
get availablePlatformsForAssignment() {
if (!this.adminUser || this.adminUser.is_super_admin) return [];
const assignedIds = (this.adminUser.platforms || []).map(p => p.id);
return this.platforms.filter(p => !assignedIds.includes(p.id));
},
// Format date
formatDate(dateString) {
if (!dateString) {
return '-';
}
return Utils.formatDate(dateString);
},
// Toggle super admin status
async toggleSuperAdmin() {
const newStatus = !this.adminUser.is_super_admin;
const action = newStatus ? 'promote to' : 'demote from';
adminUserEditLog.info(`Toggle super admin: ${action}`);
// Prevent self-demotion
if (this.adminUser.id === this.currentUserId && !newStatus) {
Utils.showToast('You cannot demote yourself from super admin', 'error');
return;
}
if (!confirm(`Are you sure you want to ${action} super admin "${this.adminUser.username}"?`)) {
adminUserEditLog.info('Super admin toggle cancelled by user');
return;
}
this.saving = true;
try {
const url = `/admin/admin-users/${this.userId}/super-admin`;
window.LogConfig.logApiCall('PUT', url, { is_super_admin: newStatus }, 'request');
const response = await apiClient.put(url, { is_super_admin: newStatus });
window.LogConfig.logApiCall('PUT', url, response, 'response');
this.adminUser.is_super_admin = response.is_super_admin;
// Clear platforms if promoted to super admin
if (response.is_super_admin) {
this.adminUser.platforms = [];
}
const actionDone = newStatus ? 'promoted to' : 'demoted from';
Utils.showToast(`Admin ${actionDone} super admin successfully`, 'success');
adminUserEditLog.info(`Admin ${actionDone} super admin successfully`);
} catch (error) {
window.LogConfig.logError(error, `Toggle Super Admin (${action})`);
Utils.showToast(error.message || `Failed to ${action} super admin`, 'error');
} finally {
this.saving = false;
}
},
// Toggle admin user status
async toggleStatus() {
const action = this.adminUser.is_active ? 'deactivate' : 'activate';
adminUserEditLog.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}"?`)) {
adminUserEditLog.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');
adminUserEditLog.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;
}
},
// Assign platform to admin
async assignPlatform(platformId) {
if (!platformId) return;
adminUserEditLog.info('Assigning platform:', platformId);
this.saving = true;
try {
const url = `/admin/admin-users/${this.userId}/platforms/${platformId}`;
window.LogConfig.logApiCall('POST', url, null, 'request');
const response = await apiClient.post(url);
window.LogConfig.logApiCall('POST', url, response, 'response');
// Reload admin user to get updated platforms
await this.loadAdminUser();
Utils.showToast('Platform assigned successfully', 'success');
adminUserEditLog.info('Platform assigned successfully');
this.showPlatformModal = false;
this.selectedPlatformId = null;
} catch (error) {
window.LogConfig.logError(error, 'Assign Platform');
Utils.showToast(error.message || 'Failed to assign platform', 'error');
} finally {
this.saving = false;
}
},
// Remove platform from admin
async removePlatform(platformId) {
const platform = this.adminUser.platforms.find(p => p.id === platformId);
const platformName = platform ? platform.name : platformId;
// Validate: platform admin must have at least one platform
if (this.adminUser.platforms.length <= 1) {
Utils.showToast('Platform admin must be assigned to at least one platform', 'error');
return;
}
if (!confirm(`Are you sure you want to remove "${platformName}" from this admin?`)) {
adminUserEditLog.info('Platform removal cancelled by user');
return;
}
adminUserEditLog.info('Removing platform:', platformId);
this.saving = true;
try {
const url = `/admin/admin-users/${this.userId}/platforms/${platformId}`;
window.LogConfig.logApiCall('DELETE', url, null, 'request');
await apiClient.delete(url);
window.LogConfig.logApiCall('DELETE', url, null, 'response');
// Reload admin user to get updated platforms
await this.loadAdminUser();
Utils.showToast('Platform removed successfully', 'success');
adminUserEditLog.info('Platform removed successfully');
} catch (error) {
window.LogConfig.logError(error, 'Remove Platform');
Utils.showToast(error.message || 'Failed to remove platform', 'error');
} finally {
this.saving = false;
}
},
// Open platform assignment modal
openPlatformModal() {
this.showPlatformModal = true;
this.selectedPlatformId = null;
},
// Delete admin user
async deleteAdminUser() {
adminUserEditLog.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.`)) {
adminUserEditLog.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}"?`)) {
adminUserEditLog.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');
adminUserEditLog.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;
}
}
};
}
adminUserEditLog.info('Admin user edit module loaded');