fix(tenancy): add CRUD actions to merchant-users page, fix view URL and icon

- Fix View link to point to /admin/merchant-users/{id} instead of
  /admin/admin-users/{id}
- Add toggle status and delete action buttons to list page
- Add merchant-user detail page with route, template, and JS
- Replace non-existent "briefcase" icon with "office-building"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-07 21:29:28 +01:00
parent 2250054ba2
commit d57f6a8ee6
6 changed files with 507 additions and 3 deletions

View File

@@ -267,6 +267,27 @@ async def admin_merchant_users_list_page(
)
@router.get(
"/merchant-users/{user_id}", response_class=HTMLResponse, include_in_schema=False
)
async def admin_merchant_user_detail_page(
request: Request,
user_id: int = Path(..., description="User ID"),
current_user: User = Depends(
require_menu_access("merchant-users", FrontendType.ADMIN)
),
db: Session = Depends(get_db),
):
"""
Render merchant user detail view.
Shows details for a merchant owner or store team member.
"""
return templates.TemplateResponse(
"tenancy/admin/merchant-user-detail.html",
get_admin_context(request, db, current_user, user_id=user_id),
)
# ============================================================================
# ADMIN USER MANAGEMENT ROUTES (Super Admin Only)
# ============================================================================

View File

@@ -374,7 +374,7 @@ class TenancyMetricsProvider:
value=merchant_owners,
label="Merchant Owners",
category="tenancy",
icon="briefcase",
icon="office-building",
description="Distinct merchant owners",
),
MetricValue(

View File

@@ -0,0 +1,177 @@
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/merchant-user-detail.js
// Create custom logger for merchant user detail
const merchantUserDetailLog = window.LogConfig.createLogger('MERCHANT-USER-DETAIL');
function merchantUserDetailPage() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// Merchant user detail page specific state
currentPage: 'merchant-users',
merchantUser: null,
loading: false,
saving: false,
error: null,
userId: null,
// Initialize
async init() {
// Load i18n translations
await I18n.loadModule('tenancy');
merchantUserDetailLog.info('=== MERCHANT USER DETAIL PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._merchantUserDetailInitialized) {
merchantUserDetailLog.warn('Merchant user detail page already initialized, skipping...');
return;
}
window._merchantUserDetailInitialized = true;
// Get user ID from URL
const path = window.location.pathname;
const match = path.match(/\/admin\/merchant-users\/(\d+)$/);
if (match) {
this.userId = match[1];
merchantUserDetailLog.info('Viewing merchant user:', this.userId);
await this.loadMerchantUser();
} else {
merchantUserDetailLog.error('No user ID in URL');
this.error = 'Invalid merchant user URL';
Utils.showToast('Invalid merchant user URL', 'error');
}
merchantUserDetailLog.info('=== MERCHANT USER DETAIL PAGE INITIALIZATION COMPLETE ===');
},
// Load merchant user data
async loadMerchantUser() {
merchantUserDetailLog.info('Loading merchant user details...');
this.loading = true;
this.error = null;
try {
const url = `/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 Merchant User Details', duration);
// Transform API response
this.merchantUser = {
...response,
full_name: [response.first_name, response.last_name].filter(Boolean).join(' ') || null
};
merchantUserDetailLog.info(`Merchant user loaded in ${duration}ms`, {
id: this.merchantUser.id,
username: this.merchantUser.username,
owned_merchants_count: this.merchantUser.owned_merchants_count,
store_memberships_count: this.merchantUser.store_memberships_count
});
} catch (error) {
window.LogConfig.logError(error, 'Load Merchant User Details');
this.error = error.message || 'Failed to load merchant user details';
Utils.showToast('Failed to load merchant user details', 'error');
} finally {
this.loading = false;
}
},
// Format date
formatDate(dateString) {
if (!dateString) {
return '-';
}
return Utils.formatDate(dateString);
},
// Toggle user status
async toggleStatus() {
const action = this.merchantUser.is_active ? 'deactivate' : 'activate';
merchantUserDetailLog.info(`Toggle status: ${action}`);
if (!confirm(`Are you sure you want to ${action} "${this.merchantUser.full_name || this.merchantUser.username}"?`)) {
merchantUserDetailLog.info('Status toggle cancelled by user');
return;
}
this.saving = true;
try {
const url = `/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.merchantUser.is_active = response.is_active;
Utils.showToast(`User ${action}d successfully`, 'success');
merchantUserDetailLog.info(`User ${action}d successfully`);
} catch (error) {
window.LogConfig.logError(error, `Toggle Status (${action})`);
Utils.showToast(error.message || `Failed to ${action} user`, 'error');
} finally {
this.saving = false;
}
},
// Delete user
async deleteUser() {
merchantUserDetailLog.info('Delete user requested:', this.userId);
if (!confirm(`Are you sure you want to delete "${this.merchantUser.full_name || this.merchantUser.username}"?\n\nThis action cannot be undone.`)) {
merchantUserDetailLog.info('Delete cancelled by user');
return;
}
// Second confirmation for safety
if (!confirm(`FINAL CONFIRMATION\n\nAre you absolutely sure you want to delete "${this.merchantUser.full_name || this.merchantUser.username}"?`)) {
merchantUserDetailLog.info('Delete cancelled by user (second confirmation)');
return;
}
this.saving = true;
try {
const url = `/admin/users/${this.userId}`;
window.LogConfig.logApiCall('DELETE', url, null, 'request');
await apiClient.delete(url);
window.LogConfig.logApiCall('DELETE', url, null, 'response');
Utils.showToast('User deleted successfully', 'success');
merchantUserDetailLog.info('User deleted successfully');
// Redirect to merchant users list
setTimeout(() => window.location.href = '/admin/merchant-users', 1500);
} catch (error) {
window.LogConfig.logError(error, 'Delete User');
Utils.showToast(error.message || 'Failed to delete user', 'error');
} finally {
this.saving = false;
}
},
// Refresh user data
async refresh() {
merchantUserDetailLog.info('=== MERCHANT USER REFRESH TRIGGERED ===');
await this.loadMerchantUser();
Utils.showToast('Merchant user details refreshed', 'success');
merchantUserDetailLog.info('=== MERCHANT USER REFRESH COMPLETE ===');
}
};
}
merchantUserDetailLog.info('Merchant user detail module loaded');

View File

@@ -223,6 +223,69 @@ function merchantUsersPage() {
merchantUsersLog.info('Go to page:', this.pagination.page);
this.loadMerchantUsers();
}
},
// Toggle user active status
async toggleUserStatus(user) {
const action = user.is_active ? 'deactivate' : 'activate';
merchantUsersLog.info(`Toggle status: ${action} for user`, user.username);
if (!confirm(`Are you sure you want to ${action} "${user.full_name || user.username || user.email}"?`)) {
merchantUsersLog.info('Status toggle cancelled by user');
return;
}
try {
const url = `/admin/users/${user.id}/status`;
window.LogConfig.logApiCall('PUT', url, null, 'request');
const response = await apiClient.put(url);
window.LogConfig.logApiCall('PUT', url, response, 'response');
user.is_active = response.is_active;
Utils.showToast(`User ${action}d successfully`, 'success');
merchantUsersLog.info(`User ${action}d successfully`);
await this.loadStats();
} catch (error) {
window.LogConfig.logError(error, `Toggle Status (${action})`);
Utils.showToast(error.message || `Failed to ${action} user`, 'error');
}
},
// Delete user
async deleteUser(user) {
merchantUsersLog.warn('Delete user requested:', user.username);
if (!confirm(`Are you sure you want to delete "${user.full_name || user.username || user.email}"?\n\nThis action cannot be undone.`)) {
merchantUsersLog.info('Delete cancelled by user');
return;
}
// Second confirmation for safety
if (!confirm(`FINAL CONFIRMATION\n\nAre you absolutely sure you want to delete "${user.full_name || user.username || user.email}"?`)) {
merchantUsersLog.info('Delete cancelled by user (second confirmation)');
return;
}
try {
const url = `/admin/users/${user.id}`;
window.LogConfig.logApiCall('DELETE', url, null, 'request');
await apiClient.delete(url);
window.LogConfig.logApiCall('DELETE', url, null, 'response');
Utils.showToast('User deleted successfully', 'success');
merchantUsersLog.info('User deleted successfully');
await this.loadMerchantUsers();
await this.loadStats();
} catch (error) {
window.LogConfig.logError(error, 'Delete User');
Utils.showToast(error.message || 'Failed to delete user', 'error');
}
}
};
}

View File

@@ -0,0 +1,224 @@
{# app/templates/admin/merchant-user-detail.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/headers.html' import detail_page_header %}
{% block title %}Merchant User Details{% endblock %}
{% block alpine_data %}merchantUserDetailPage(){% endblock %}
{% block content %}
{% call detail_page_header("merchantUser?.full_name || merchantUser?.username || 'Merchant User Details'", '/admin/merchant-users', subtitle_show='merchantUser') %}
@<span x-text="merchantUser?.username"></span>
<span class="text-gray-400 mx-2">|</span>
<span x-text="merchantUser?.email"></span>
{% endcall %}
{{ loading_state('Loading merchant user details...') }}
{{ error_state('Error loading merchant user') }}
<!-- Merchant User Details -->
<div x-show="!loading && merchantUser">
<!-- 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">
<button
@click="toggleStatus()"
:disabled="saving"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 border border-transparent rounded-lg focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
:class="merchantUser?.is_active ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700'">
<span x-html="$icon(merchantUser?.is_active ? 'user-x' : 'user-check', 'w-4 h-4 mr-2')"></span>
<span x-text="merchantUser?.is_active ? 'Deactivate' : 'Activate'"></span>
</button>
<button
@click="deleteUser()"
:disabled="saving"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 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 disabled:cursor-not-allowed"
title="Delete user">
<span x-html="$icon('delete', 'w-4 h-4 mr-2')"></span>
Delete User
</button>
</div>
</div>
<!-- Status Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-4">
<!-- User Type -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 rounded-full"
:class="merchantUser?.owned_merchants_count > 0
? 'text-orange-500 bg-orange-100 dark:text-orange-100 dark:bg-orange-500'
: 'text-blue-500 bg-blue-100 dark:text-blue-100 dark:bg-blue-500'">
<span x-html="$icon(merchantUser?.owned_merchants_count > 0 ? 'office-building' : 'user-group', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
User Type
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200"
x-text="merchantUser?.owned_merchants_count > 0 ? 'Owner' : 'Team Member'">
-
</p>
</div>
</div>
<!-- Active Status -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 rounded-full"
:class="merchantUser?.is_active ? 'text-green-500 bg-green-100 dark:text-green-100 dark:bg-green-500' : 'text-red-500 bg-red-100 dark:text-red-100 dark:bg-red-500'">
<span x-html="$icon(merchantUser?.is_active ? 'check-circle' : 'x-circle', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Status
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="merchantUser?.is_active ? 'Active' : 'Inactive'">
-
</p>
</div>
</div>
<!-- Owned Merchants -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('office-building', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Merchants Owned
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="merchantUser?.owned_merchants_count || 0">
0
</p>
</div>
</div>
<!-- Store Memberships -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
<span x-html="$icon('store', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Store Memberships
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="merchantUser?.store_memberships_count || 0">
0
</p>
</div>
</div>
</div>
<!-- Main Info Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-2">
<!-- Account Information -->
<div class="px-4 py-3 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">
Account Information
</h3>
<div class="space-y-3">
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Username</p>
<p class="text-sm text-gray-700 dark:text-gray-300">@<span x-text="merchantUser?.username || '-'"></span></p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Email</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.email || '-'">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Role</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.role || '-'">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Email Verified</p>
<span
class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full"
:class="merchantUser?.is_email_verified ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100'"
x-text="merchantUser?.is_email_verified ? 'Verified' : 'Not Verified'">
</span>
</div>
</div>
</div>
<!-- Personal Information -->
<div class="px-4 py-3 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">
Personal Information
</h3>
<div class="space-y-3">
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Full Name</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.full_name || 'Not provided'">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">First Name</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.first_name || 'Not provided'">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase">Last Name</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.last_name || 'Not provided'">-</p>
</div>
</div>
</div>
</div>
<!-- Merchant Ownership Info -->
<template x-if="merchantUser?.owned_merchants_count > 0">
<div class="px-4 py-3 mb-8 bg-orange-50 dark:bg-orange-900/20 rounded-lg border border-orange-200 dark:border-orange-800">
<div class="flex items-center">
<span x-html="$icon('office-building', 'w-5 h-5 text-orange-500 mr-3')"></span>
<div>
<h4 class="text-sm font-medium text-orange-800 dark:text-orange-300">Merchant Owner</h4>
<p class="text-sm text-orange-600 dark:text-orange-400">
This user owns <span x-text="merchantUser?.owned_merchants_count"></span> merchant(s) and has full access to their stores.
</p>
</div>
</div>
</div>
</template>
<!-- Team Membership Info -->
<template x-if="merchantUser?.store_memberships_count > 0">
<div class="px-4 py-3 mb-8 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<div class="flex items-center">
<span x-html="$icon('user-group', 'w-5 h-5 text-blue-500 mr-3')"></span>
<div>
<h4 class="text-sm font-medium text-blue-800 dark:text-blue-300">Store Team Member</h4>
<p class="text-sm text-blue-600 dark:text-blue-400">
This user is a team member on <span x-text="merchantUser?.store_memberships_count"></span> store(s).
</p>
</div>
</div>
</div>
</template>
<!-- Activity Information -->
<div class="px-4 py-3 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">
Activity Information
</h3>
<div class="grid gap-6 md:grid-cols-3">
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase mb-2">Last Login</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="merchantUser?.last_login ? formatDate(merchantUser.last_login) : 'Never'">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase mb-2">Created At</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="formatDate(merchantUser?.created_at)">-</p>
</div>
<div>
<p class="text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase mb-2">Last Updated</p>
<p class="text-sm text-gray-700 dark:text-gray-300" x-text="formatDate(merchantUser?.updated_at)">-</p>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_scripts %}
<script src="{{ url_for('tenancy_static', path='admin/js/merchant-user-detail.js') }}"></script>
{% endblock %}

View File

@@ -36,7 +36,7 @@
<!-- Card: Merchant Owners -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('briefcase', 'w-5 h-5')"></span>
<span x-html="$icon('office-building', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
@@ -189,12 +189,31 @@
<div class="flex items-center space-x-2 text-sm">
<!-- View Button -->
<a
:href="'/admin/admin-users/' + user.id"
:href="'/admin/merchant-users/' + user.id"
class="flex items-center justify-center p-2 text-blue-600 rounded-lg hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
title="View user details"
>
<span x-html="$icon('eye', 'w-5 h-5')"></span>
</a>
<!-- Toggle Status Button -->
<button
@click="toggleUserStatus(user)"
class="flex items-center justify-center p-2 rounded-lg hover:bg-orange-50 dark:hover:bg-gray-700 focus:outline-none transition-colors"
:class="user.is_active ? 'text-orange-600 dark:text-orange-400' : 'text-green-600 dark:text-green-400'"
:title="user.is_active ? 'Deactivate user' : 'Activate user'"
>
<span x-html="$icon(user.is_active ? 'user-x' : 'user-check', 'w-5 h-5')"></span>
</button>
<!-- Delete Button -->
<button
@click="deleteUser(user)"
class="flex items-center justify-center p-2 text-red-600 rounded-lg hover:bg-red-50 dark:text-red-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
title="Delete user"
>
<span x-html="$icon('delete', 'w-5 h-5')"></span>
</button>
</div>
</td>
</tr>