feat: add merchant user edit page with editable profile fields
All checks were successful
CI / ruff (push) Successful in 11s
CI / pytest (push) Successful in 47m48s
CI / validate (push) Successful in 24s
CI / dependency-scanning (push) Successful in 30s
CI / docs (push) Successful in 40s
CI / deploy (push) Successful in 1m18s

- Add /admin/merchant-users/{id}/edit page route and template
- Replace toggle-status button with edit button on merchant-users list
- Editable fields: username, email, first name, last name
- Quick actions: toggle status, delete (with double confirm)
- Move RBAC two-phase plan to docs/proposals/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-19 23:30:50 +01:00
parent 51e512ec08
commit b9ac252a9f
6 changed files with 892 additions and 47 deletions

View File

@@ -288,6 +288,29 @@ async def admin_merchant_user_detail_page(
)
@router.get(
"/merchant-users/{user_id}/edit",
response_class=HTMLResponse,
include_in_schema=False,
)
async def admin_merchant_user_edit_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 edit form.
Allows editing merchant owner or store team member details.
"""
return templates.TemplateResponse(
"tenancy/admin/merchant-user-edit.html",
get_admin_context(request, db, current_user, user_id=user_id),
)
# ============================================================================
# ADMIN USER MANAGEMENT ROUTES (Super Admin Only)
# ============================================================================

View File

@@ -0,0 +1,254 @@
// static/admin/js/merchant-user-edit.js
// Create custom logger for merchant user edit
const merchantUserEditLog = window.LogConfig.createLogger('MERCHANT-USER-EDIT');
function merchantUserEditPage() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// Merchant user edit page specific state
currentPage: 'merchant-users',
loading: false,
merchantUser: null,
errors: {},
saving: false,
userId: null,
// Editable profile form
editForm: {
username: '',
email: '',
first_name: '',
last_name: ''
},
// Confirmation modal state
showToggleStatusModal: false,
showDeleteModal: false,
showDeleteFinalModal: false,
// Initialize
async init() {
try {
// Load i18n translations
await I18n.loadModule('tenancy');
merchantUserEditLog.info('=== MERCHANT USER EDIT PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._merchantUserEditInitialized) {
merchantUserEditLog.warn('Merchant user edit page already initialized, skipping...');
return;
}
window._merchantUserEditInitialized = true;
// Get user ID from URL
const path = window.location.pathname;
const match = path.match(/\/admin\/merchant-users\/(\d+)\/edit/);
if (match) {
this.userId = parseInt(match[1], 10);
merchantUserEditLog.info('Editing merchant user:', this.userId);
await this.loadMerchantUser();
} else {
merchantUserEditLog.error('No user ID in URL');
Utils.showToast('Invalid merchant user URL', 'error');
setTimeout(() => window.location.href = '/admin/merchant-users', 2000);
}
merchantUserEditLog.info('=== MERCHANT USER EDIT PAGE INITIALIZATION COMPLETE ===');
} catch (error) {
merchantUserEditLog.error('Init failed:', error);
this.error = 'Failed to initialize merchant user edit page';
}
},
// Load merchant user data
async loadMerchantUser() {
merchantUserEditLog.info('Loading merchant user data...');
this.loading = true;
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', duration);
// Transform API response
this.merchantUser = {
...response,
full_name: [response.first_name, response.last_name].filter(Boolean).join(' ') || null
};
// Populate editable form
this.editForm = {
username: this.merchantUser.username || '',
email: this.merchantUser.email || '',
first_name: this.merchantUser.first_name || '',
last_name: this.merchantUser.last_name || ''
};
merchantUserEditLog.info(`Merchant user loaded in ${duration}ms`, {
id: this.merchantUser.id,
username: this.merchantUser.username,
role: this.merchantUser.role
});
} catch (error) {
window.LogConfig.logError(error, 'Load Merchant User');
Utils.showToast('Failed to load merchant user', 'error');
setTimeout(() => window.location.href = '/admin/merchant-users', 2000);
} finally {
this.loading = false;
}
},
// Format date
formatDate(dateString) {
if (!dateString) {
return '-';
}
return Utils.formatDate(dateString);
},
// Check if profile form has unsaved changes
get profileDirty() {
if (!this.merchantUser) return false;
return this.editForm.username !== (this.merchantUser.username || '') ||
this.editForm.email !== (this.merchantUser.email || '') ||
this.editForm.first_name !== (this.merchantUser.first_name || '') ||
this.editForm.last_name !== (this.merchantUser.last_name || '');
},
// Save profile changes
async saveProfile() {
merchantUserEditLog.info('Saving profile changes...');
this.errors = {};
// Build update payload with only changed fields
const payload = {};
if (this.editForm.username !== (this.merchantUser.username || '')) {
payload.username = this.editForm.username;
}
if (this.editForm.email !== (this.merchantUser.email || '')) {
payload.email = this.editForm.email;
}
if (this.editForm.first_name !== (this.merchantUser.first_name || '')) {
payload.first_name = this.editForm.first_name;
}
if (this.editForm.last_name !== (this.merchantUser.last_name || '')) {
payload.last_name = this.editForm.last_name;
}
if (Object.keys(payload).length === 0) return;
this.saving = true;
try {
const url = `/admin/users/${this.userId}`;
window.LogConfig.logApiCall('PUT', url, payload, 'request');
const response = await apiClient.put(url, payload);
window.LogConfig.logApiCall('PUT', url, response, 'response');
// Update local state
this.merchantUser.username = response.username;
this.merchantUser.email = response.email;
this.merchantUser.first_name = response.first_name;
this.merchantUser.last_name = response.last_name;
this.merchantUser.full_name = [response.first_name, response.last_name].filter(Boolean).join(' ') || null;
// Re-sync form
this.editForm = {
username: response.username || '',
email: response.email || '',
first_name: response.first_name || '',
last_name: response.last_name || ''
};
Utils.showToast('Profile updated successfully', 'success');
merchantUserEditLog.info('Profile updated successfully');
} catch (error) {
window.LogConfig.logError(error, 'Save Profile');
if (error.details) {
for (const detail of error.details) {
const field = detail.loc?.[detail.loc.length - 1];
if (field) this.errors[field] = detail.msg;
}
}
Utils.showToast(error.message || 'Failed to save profile', 'error');
} finally {
this.saving = false;
}
},
// Toggle user status
async toggleStatus() {
const action = this.merchantUser.is_active ? 'deactivate' : 'activate';
merchantUserEditLog.info(`Toggle status: ${action}`);
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');
merchantUserEditLog.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;
}
},
// Intermediate step for double-confirm delete
confirmDeleteStep() {
merchantUserEditLog.info('First delete confirmation accepted, showing final confirmation');
this.showDeleteFinalModal = true;
},
// Delete user
async deleteUser() {
merchantUserEditLog.info('Delete user requested:', this.userId);
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');
merchantUserEditLog.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;
}
}
};
}
merchantUserEditLog.info('Merchant user edit module loaded');

View File

@@ -16,10 +16,8 @@ function merchantUsersPage() {
merchantUsers: [],
loading: false,
error: null,
showToggleStatusModal: false,
showDeleteModal: false,
showDeleteFinalModal: false,
userToToggle: null,
userToDelete: null,
filters: {
search: '',
@@ -230,30 +228,6 @@ function merchantUsersPage() {
}
},
// Toggle user active status
async toggleUserStatus(user) {
const action = user.is_active ? 'deactivate' : 'activate';
merchantUsersLog.info(`Toggle status: ${action} for user`, user.username);
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');
}
},
// Intermediate step for double-confirm delete
confirmDeleteStep() {
merchantUsersLog.info('First delete confirmation accepted, showing final confirmation');

View File

@@ -0,0 +1,251 @@
{# app/templates/admin/merchant-user-edit.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/alerts.html' import loading_state %}
{% from 'shared/macros/headers.html' import edit_page_header %}
{% from 'shared/macros/modals.html' import confirm_modal_dynamic %}
{% block title %}Edit Merchant User{% endblock %}
{% block alpine_data %}merchantUserEditPage(){% endblock %}
{% block content %}
{% call edit_page_header('Edit Merchant User', '/admin/merchant-users', subtitle_show='merchantUser', back_label='Back to Merchant Users') %}
@<span x-text="merchantUser?.username"></span>
{% endcall %}
{{ loading_state('Loading merchant user...', show_condition='loading') }}
<!-- Edit Content -->
<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">
<!-- Toggle Active Status -->
<button
@click="showToggleStatusModal = true"
:disabled="saving"
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="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>
<!-- Status Badges -->
<div class="ml-auto flex items-center gap-2">
<span
x-show="merchantUser?.role === 'merchant_owner'"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">
Merchant Owner
</span>
<span
x-show="merchantUser?.role === 'store_member'"
class="inline-flex items-center px-3 py-1 text-xs font-semibold leading-tight text-blue-700 bg-blue-100 rounded-full dark:bg-blue-700 dark:text-blue-100">
Store Member
</span>
<span
x-show="merchantUser?.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="!merchantUser?.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>
<!-- User Info Card (Editable) -->
<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">
User Information
</h3>
<span class="text-xs text-gray-500 dark:text-gray-400" x-text="'ID: ' + merchantUser?.id"></span>
</div>
<form @submit.prevent="saveProfile()">
<div class="grid gap-6 md:grid-cols-2">
<!-- Left Column -->
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Username</label>
<input
type="text"
x-model="editForm.username"
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-input"
required
minlength="3"
>
<p x-show="errors.username" x-text="errors.username" class="mt-1 text-xs text-red-600 dark:text-red-400"></p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Email</label>
<input
type="email"
x-model="editForm.email"
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-input"
required
>
<p x-show="errors.email" x-text="errors.email" class="mt-1 text-xs text-red-600 dark:text-red-400"></p>
</div>
</div>
<!-- Right Column -->
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">First Name</label>
<input
type="text"
x-model="editForm.first_name"
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-input"
placeholder="First name"
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Last Name</label>
<input
type="text"
x-model="editForm.last_name"
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-input"
placeholder="Last name"
>
</div>
</div>
</div>
<div class="flex items-center justify-end mt-6 gap-3">
<span x-show="profileDirty" class="text-xs text-orange-600 dark:text-orange-400">Unsaved changes</span>
<button
type="submit"
:disabled="saving || !profileDirty"
class="flex items-center 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 transition-colors">
<span x-show="!saving">Save Changes</span>
<span x-show="saving" class="flex items-center">
<span x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
Saving...
</span>
</button>
</div>
</form>
</div>
<!-- Owned Merchants -->
<template x-if="merchantUser?.owned_merchants?.length > 0">
<div class="mb-6">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('office-building', 'w-5 h-5 inline mr-2 text-orange-500')"></span>
Owned Merchants
</h3>
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<template x-for="merchant in merchantUser.owned_merchants" :key="merchant.id">
<a :href="'/admin/merchants/' + merchant.id"
class="block px-4 py-3 bg-white rounded-lg shadow-md dark:bg-gray-800 border border-transparent hover:border-orange-300 dark:hover:border-orange-600 transition-colors duration-150">
<div class="flex items-center justify-between mb-2">
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-200 truncate" x-text="merchant.name"></h4>
<span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full"
:class="merchant.is_active ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100'"
x-text="merchant.is_active ? 'Active' : 'Inactive'">
</span>
</div>
<div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
<span x-html="$icon('store', 'w-3.5 h-3.5 mr-1')"></span>
<span x-text="merchant.store_count + ' store(s)'"></span>
</div>
</a>
</template>
</div>
</div>
</template>
<!-- Store Memberships -->
<template x-if="merchantUser?.store_memberships?.length > 0">
<div class="mb-6">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('user-group', 'w-5 h-5 inline mr-2 text-blue-500')"></span>
Store Memberships
</h3>
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<template x-for="membership in merchantUser.store_memberships" :key="membership.store_id">
<a :href="'/admin/stores/' + membership.store_code"
class="block px-4 py-3 bg-white rounded-lg shadow-md dark:bg-gray-800 border border-transparent hover:border-blue-300 dark:hover:border-blue-600 transition-colors duration-150">
<div class="flex items-center justify-between mb-2">
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-200 truncate" x-text="membership.store_name"></h4>
<span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full"
:class="membership.is_active ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100'"
x-text="membership.is_active ? 'Active' : 'Inactive'">
</span>
</div>
<div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
<span x-text="membership.store_code"></span>
</div>
</a>
</template>
</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 User Button -->
<button
@click="showDeleteModal = true"
:disabled="saving"
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="Delete this user">
<span x-html="$icon('delete', 'w-4 h-4 mr-2')"></span>
Delete 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 a user is permanent and cannot be undone.
</p>
</div>
</div>
<!-- Toggle Status Confirmation Modal -->
{{ confirm_modal_dynamic(
'toggleStatusModal',
'Toggle User Status',
"'Are you sure you want to ' + (merchantUser?.is_active ? 'deactivate' : 'activate') + ' \"' + (merchantUser?.full_name || merchantUser?.username || '') + '\"?'",
'toggleStatus()',
'showToggleStatusModal',
'Confirm',
'Cancel',
'warning'
) }}
<!-- Delete User Confirmation Modal (Step 1) -->
{{ confirm_modal_dynamic(
'deleteUserModal',
'Delete User',
"'Are you sure you want to delete \"' + (merchantUser?.full_name || merchantUser?.username || '') + '\"? This action cannot be undone.'",
'confirmDeleteStep()',
'showDeleteModal',
'Delete',
'Cancel',
'danger'
) }}
<!-- Delete User Final Confirmation Modal (Step 2) -->
{{ confirm_modal_dynamic(
'deleteUserFinalModal',
'Final Confirmation',
"'FINAL CONFIRMATION: Are you absolutely sure you want to permanently delete \"' + (merchantUser?.full_name || merchantUser?.username || '') + '\"?'",
'deleteUser()',
'showDeleteFinalModal',
'Permanently Delete',
'Cancel',
'danger'
) }}
{% endblock %}
{% block extra_scripts %}
<script defer src="{{ url_for('tenancy_static', path='admin/js/merchant-user-edit.js') }}"></script>
{% endblock %}

View File

@@ -4,7 +4,7 @@
{% from 'shared/macros/headers.html' import page_header %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %}
{% from 'shared/macros/modals.html' import confirm_modal, confirm_modal_dynamic %}
{% from 'shared/macros/modals.html' import confirm_modal_dynamic %}
{% block title %}Merchant Users{% endblock %}
@@ -197,15 +197,14 @@
<span x-html="$icon('eye', 'w-5 h-5')"></span>
</a>
<!-- Toggle Status Button -->
<button
@click="userToToggle = user; showToggleStatusModal = true"
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'"
<!-- Edit Button -->
<a
:href="'/admin/merchant-users/' + user.id + '/edit'"
class="flex items-center justify-center p-2 text-purple-600 rounded-lg hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
title="Edit user"
>
<span x-html="$icon(user.is_active ? 'user-x' : 'user-check', 'w-5 h-5')"></span>
</button>
<span x-html="$icon('edit', 'w-5 h-5')"></span>
</a>
<!-- Delete Button -->
<button
@@ -225,18 +224,6 @@
{{ pagination() }}
</div>
<!-- Toggle Status Confirmation Modal -->
{{ confirm_modal_dynamic(
'toggleStatusModal',
'Toggle User Status',
"'Are you sure you want to ' + (userToToggle?.is_active ? 'deactivate' : 'activate') + ' \"' + (userToToggle?.full_name || userToToggle?.username || userToToggle?.email || '') + '\"?'",
'toggleUserStatus(userToToggle)',
'showToggleStatusModal',
'Confirm',
'Cancel',
'warning'
) }}
<!-- Delete User Confirmation Modal (Step 1) -->
{{ confirm_modal_dynamic(
'deleteUserModal',