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) # 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: [], merchantUsers: [],
loading: false, loading: false,
error: null, error: null,
showToggleStatusModal: false,
showDeleteModal: false, showDeleteModal: false,
showDeleteFinalModal: false, showDeleteFinalModal: false,
userToToggle: null,
userToDelete: null, userToDelete: null,
filters: { filters: {
search: '', 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 // Intermediate step for double-confirm delete
confirmDeleteStep() { confirmDeleteStep() {
merchantUsersLog.info('First delete confirmation accepted, showing final confirmation'); 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/headers.html' import page_header %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %} {% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %} {% 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 %} {% block title %}Merchant Users{% endblock %}
@@ -197,15 +197,14 @@
<span x-html="$icon('eye', 'w-5 h-5')"></span> <span x-html="$icon('eye', 'w-5 h-5')"></span>
</a> </a>
<!-- Toggle Status Button --> <!-- Edit Button -->
<button <a
@click="userToToggle = user; showToggleStatusModal = true" :href="'/admin/merchant-users/' + user.id + '/edit'"
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="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"
:class="user.is_active ? 'text-orange-600 dark:text-orange-400' : 'text-green-600 dark:text-green-400'" title="Edit user"
:title="user.is_active ? 'Deactivate user' : 'Activate user'"
> >
<span x-html="$icon(user.is_active ? 'user-x' : 'user-check', 'w-5 h-5')"></span> <span x-html="$icon('edit', 'w-5 h-5')"></span>
</button> </a>
<!-- Delete Button --> <!-- Delete Button -->
<button <button
@@ -225,18 +224,6 @@
{{ pagination() }} {{ pagination() }}
</div> </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) --> <!-- Delete User Confirmation Modal (Step 1) -->
{{ confirm_modal_dynamic( {{ confirm_modal_dynamic(
'deleteUserModal', 'deleteUserModal',

View File

@@ -0,0 +1,356 @@
# RBAC Cleanup: Two-Phase Plan
> **Phase 1 Status: COMPLETED** (2026-02-19) — All 13 steps implemented, migration `tenancy_003` applied, 1081 tests passing.
>
> **Phase 2 Status: PLANNED** — Pending future sprint.
## Context
The current role/permission system is fragmented across 4 mechanisms and 5 tables, creating confusion and bugs:
| Mechanism | Where | What it determines |
|-----------|-------|-------------------|
| `User.role` | `users.role` (String: "admin"/"store") | Admin vs Store user |
| `User.is_super_admin` | `users.is_super_admin` (Boolean) | Super admin privileges |
| `StoreUser.user_type` | `store_users.user_type` ("owner"/"member") | **STALE** — ownership moved to `Merchant.owner_user_id` |
| `StoreUser.role_id` -> `Role.permissions` | `store_users` + `roles` | Per-store granular permissions |
**Key issues:**
1. **Stale "store owner" concept** — ownership lives at `Merchant.owner_user_id`, but `StoreUser(user_type="owner")` entries are still created as redundant mirrors (~20 files)
2. **Bug:** `merchant_service.py:72` sets `role="user"` on new merchant owners — not a valid `UserRole` value, breaks store portal login
3. **Naming chaos** — UI shows "Type" for admins / "Role" for merchants, but DB field names are the opposite
4. **`is_super_admin` boolean** bolted onto a 2-value enum instead of being a proper role level
5. **147 references** to `is_super_admin` across 29 files; 30 auth dependency functions in `deps.py`
**This plan covers two phases — neither to be executed before the client demo:**
- **Phase 1** (post-demo): Pragmatic cleanup, ~50 files, fixes real bugs
- **Phase 2** (later sprint): Full unified role assignment system, ~80-100 files
---
## Phase 1 — Pragmatic Cleanup (~50 files) [COMPLETED]
**Goal:** Consolidate `User.role` + `User.is_super_admin` into a single 4-value enum. Remove stale `StoreUser.user_type`. Fix the `role="user"` bug. Keep `StoreUser.role_id` -> `Role.permissions` unchanged (it works fine for per-store granular perms).
### Step 1.1 — Expand `UserRole` enum
**File:** `app/modules/tenancy/models/user.py`
```python
# BEFORE
class UserRole(str, Enum):
ADMIN = "admin"
STORE = "store"
# AFTER
class UserRole(str, Enum):
SUPER_ADMIN = "super_admin" # Platform super administrator
PLATFORM_ADMIN = "platform_admin" # Platform admin (scoped to assigned platforms)
MERCHANT_OWNER = "merchant_owner" # Owns merchant(s) and all their stores
STORE_MEMBER = "store_member" # Team member on specific store(s)
```
**Mapping from old to new:**
| Old state | New `UserRole` |
|-----------|---------------|
| `role="admin"` + `is_super_admin=True` | `SUPER_ADMIN` |
| `role="admin"` + `is_super_admin=False` | `PLATFORM_ADMIN` |
| `role="store"` + owns merchant(s) | `MERCHANT_OWNER` |
| `role="store"` + no merchant ownership | `STORE_MEMBER` |
| `role="user"` (bug) | `MERCHANT_OWNER` (fix) |
### Step 1.2 — Migration: data migration + drop `is_super_admin` + drop `user_type`
**File:** `app/modules/tenancy/migrations/versions/tenancy_00X_consolidate_user_role.py` (NEW)
1. Widen `users.role` column to accept new values
2. Data migration:
```sql
UPDATE users SET role = 'super_admin' WHERE role = 'admin' AND is_super_admin = true;
UPDATE users SET role = 'platform_admin' WHERE role = 'admin' AND is_super_admin = false;
UPDATE users SET role = 'merchant_owner' WHERE role = 'store' AND id IN (SELECT owner_user_id FROM merchants);
UPDATE users SET role = 'merchant_owner' WHERE role = 'user'; -- fix bug
UPDATE users SET role = 'store_member' WHERE role = 'store' AND id NOT IN (SELECT owner_user_id FROM merchants);
```
3. Drop `users.is_super_admin` column
4. Drop `store_users.user_type` column
### Step 1.3 — Update User model
**File:** `app/modules/tenancy/models/user.py`
- Remove `is_super_admin` column definition
- Add backward-compat properties:
```python
@property
def is_super_admin(self):
return self.role == UserRole.SUPER_ADMIN.value
@property
def is_admin(self):
return self.role in (UserRole.SUPER_ADMIN.value, UserRole.PLATFORM_ADMIN.value)
@property
def is_merchant_owner(self):
return self.role == UserRole.MERCHANT_OWNER.value
```
**File:** `app/modules/tenancy/models/store.py`
- Remove `StoreUserType` enum
- Remove `StoreUser.user_type` column
- Update `StoreUser.is_owner` property to check via `User.is_owner_of(store_id)` instead of `user_type`
### Step 1.4 — Update auth dependencies
**File:** `app/api/deps.py` (~30 functions)
| Old check | New check |
|-----------|-----------|
| `role == "admin"` | `role in ("super_admin", "platform_admin")` |
| `role == "admin" and is_super_admin` | `role == "super_admin"` |
| `role == "store"` | `role in ("merchant_owner", "store_member")` |
Key functions:
- `get_current_admin_api()` -> check `is_admin` property
- `get_current_super_admin_api()` -> check `role == "super_admin"`
- `get_current_store_api()` -> check role in `(merchant_owner, store_member)`
- `get_current_merchant_api()` -> check `role == "merchant_owner"`
- `require_store_owner()` -> already uses `User.is_owner_of()` (no change needed)
- `require_store_permission()` -> already uses `User.has_store_permission()` (no change needed)
### Step 1.5 — Update JWT token creation + backward-compat shim
**File:** `app/middleware/auth.py`
- `create_access_token()`: Remove `is_super_admin` from payload — `role` field now carries all info
- `verify_token()`: Add backward-compat shim — if token has old `role="admin"` + `is_super_admin=True`, map to `"super_admin"`. Remove shim after 1 release cycle.
### Step 1.6 — Update auth service
**File:** `app/modules/core/services/auth_service.py`
- `login_user()` / `login_merchant()` — remove `is_super_admin` from token data
- `get_user_store_role()` — derive from `User.role` instead of checking `StoreUser.user_type`
### Step 1.7 — Fix merchant creation bug
**File:** `app/modules/tenancy/services/merchant_service.py`
- Line 72: Change `role="user"` -> `role=UserRole.MERCHANT_OWNER.value`
**File:** `app/modules/marketplace/services/platform_signup_service.py`
- Remove `StoreUser(user_type=StoreUserType.OWNER.value)` creation — ownership is via `Merchant.owner_user_id`
- Set `role=UserRole.MERCHANT_OWNER.value` on user creation
### Step 1.8 — Update store team service
**File:** `app/modules/tenancy/services/store_team_service.py`
- `remove_team_member()`: Replace `store_user.is_owner` check -> `user.is_owner_of(store_id)`
- `update_member_role()`: Same replacement
- `get_team_members()`: Derive `is_owner` from `User.is_owner_of()` instead of `StoreUser.user_type`
- `add_team_member()`: Remove `user_type` assignment, ensure new members get `role=STORE_MEMBER`
### Step 1.9 — Update seed data
**File:** `scripts/seed/seed_demo.py`
- Remove `StoreUser(user_type="owner")` creation for demo merchants
- Use new `UserRole` values for all seeded users
**File:** `scripts/seed/init_production.py`
- Update super admin creation: `role="super_admin"` instead of `role="admin", is_super_admin=True`
### Step 1.10 — Update admin API routes + responses
**Files:**
- `app/modules/tenancy/routes/api/admin_users.py` — `AdminUserResponse`: remove `is_super_admin`, the `role` field is sufficient
- `app/modules/tenancy/routes/api/admin_platform_users.py` — merchant user listing: derive owner status from `User.role == "merchant_owner"` not `owned_merchants_count`
### Step 1.11 — Update admin UI templates + JS
**Files:**
- `app/modules/tenancy/templates/tenancy/admin/admin-users.html` — Change "Type" header -> "Role", display role value (super_admin / platform_admin badge)
- `app/modules/tenancy/templates/tenancy/admin/merchant-users.html` — Display role value (merchant_owner / store_member badge) instead of deriving from `owned_merchants_count`
- `app/modules/tenancy/static/admin/js/admin-users.js` — Update role badge rendering
- `app/modules/tenancy/static/admin/js/merchant-users.js` — Update role badge rendering
### Step 1.12 — Bulk update remaining `is_super_admin` references (~29 files, 147 occurrences)
Search-and-replace across:
- All route files checking `is_super_admin` -> use `user.is_super_admin` property (backed by enum check, so these work as-is via the compat property)
- All template files displaying `is_super_admin` -> display `role` value
- All JS files referencing `is_super_admin` -> use `role` field
- All test files -> update assertions
**Key files by reference count:**
- `app/api/deps.py` — 15+ references
- `app/middleware/auth.py` — 8+ references
- `app/modules/tenancy/routes/api/admin_users.py` — 5+ references
- Various admin JS files — 3-5 references each
### Step 1.13 — Update RBAC documentation
**Files:**
- `docs/api/rbac.md` — Update role hierarchy, remove is_super_admin references
- `docs/api/rbac-visual-guide.md` — Update diagrams
- `docs/backend/rbac-quick-reference.md` — Update quick reference tables
- `docs/backend/store-rbac.md` — Update store-level section
- `docs/architecture/auth-rbac.md` — Update architecture overview
### Phase 1 File Summary
| Category | Files | Change |
|----------|-------|--------|
| Models | 2 | Modify User, StoreUser |
| Migration | 1 | New data migration |
| Auth (deps + middleware + service) | 3 | Modify |
| Services | 3 | Modify (merchant, signup, team) |
| API routes | 4-6 | Modify response schemas + checks |
| Admin templates (HTML) | 2-4 | Modify badges/labels |
| Admin JS | 4-6 | Modify role rendering |
| Seed scripts | 2-3 | Modify |
| Tests | 10-15 | Update assertions |
| Documentation | 5-6 | Update |
| **Total** | **~50** | |
### Phase 1 Verification
1. `alembic upgrade head` — migration applies, data migrated correctly
2. `SELECT role, count(*) FROM users GROUP BY role` — only 4 new values
3. `SELECT * FROM users WHERE role IN ('admin', 'store', 'user')` — empty (all migrated)
4. `is_super_admin` column gone from users table
5. `user_type` column gone from store_users table
6. Admin login still works (JWT backward compat shim)
7. Store login still works
8. Merchant creation sets `role="merchant_owner"`
9. Super admin can access all admin routes
10. Platform admin scoped correctly
11. Store team member permissions unchanged
12. `pytest` — all tests pass
---
## Phase 2 — Target State (Later Sprint, ~80-100 files)
**Goal:** Replace all current role mechanisms with a unified, context-aware role assignment system. One `roles` table, one `permissions` table, one `user_role_assignments` junction table that handles all contexts (platform, merchant, store).
### Target Schema
```
users user_role_assignments roles
+--------------+ +-------------------------+ +--------------+
| id |----< | user_id (FK) |>--| id |
| email | | role_id (FK) | | name |
| password_hash| | context_type (enum) | | context_type |
| first_name | | "platform" | | is_system |
| last_name | | "merchant" | | created_at |
| ... | | "store" | +------+-------+
| (NO role col)| | context_id (nullable) | |
| (NO is_super)| | NULL = global | role_permissions
+ + | platform.id | +--------------+
| merchant.id | | role_id (FK) |
| store.id | | permission |
| granted_by (FK->users) | | (string) |
| created_at | +--------------+
+-------------------------+
```
### Target Role Definitions
**System roles (seeded, immutable):**
| Role | context_type | Description |
|------|-------------|-------------|
| `super_admin` | platform | Full platform access, all permissions |
| `platform_admin` | platform | Scoped to assigned platform(s) |
| `merchant_owner` | merchant | Owns merchant, manages all stores |
| `store_manager` | store | Full store management |
| `store_staff` | store | Day-to-day operations |
| `store_support` | store | Customer support only |
| `store_viewer` | store | Read-only access |
| `store_marketing` | store | Marketing and content |
**Custom roles:** Merchants can create custom roles at store context level with specific permission sets.
### How Assignments Work
```
# Super admin — global platform access
user_role_assignments(user_id=1, role=super_admin, context_type="platform", context_id=NULL)
# Platform admin — scoped to platform 3
user_role_assignments(user_id=2, role=platform_admin, context_type="platform", context_id=3)
# Merchant owner — owns merchant 5
user_role_assignments(user_id=3, role=merchant_owner, context_type="merchant", context_id=5)
# Store member — staff role on store 12
user_role_assignments(user_id=4, role=store_staff, context_type="store", context_id=12)
# Same user, different stores, different roles
user_role_assignments(user_id=4, role=store_manager, context_type="store", context_id=15)
```
### Phase 2 Steps (High-Level)
**2.1 — New models**
- `Role` model (replaces current per-store `roles` table) — now context-aware
- `RolePermission` model — maps role -> permission strings
- `UserRoleAssignment` model — the unified junction table
**2.2 — Migration**
- Create new tables
- Migrate data from:
- `users.role` -> `user_role_assignments` (platform/merchant context)
- `store_users` + `store_users.role_id` -> `user_role_assignments` (store context)
- `admin_platforms` -> `user_role_assignments` (platform context)
- Current `roles` + `role.permissions` -> new `roles` + `role_permissions`
- Drop old tables: `store_users`, `admin_platforms`, old `roles`
- Drop `users.role` column
**2.3 — Auth service rewrite**
- `get_user_roles(user_id, context_type?, context_id?)` — query assignments
- `has_permission(user_id, permission, context_type, context_id)` — check via role -> permissions
- Permission inheritance: super_admin > platform_admin > merchant_owner > store roles
**2.4 — Auth dependencies rewrite**
- Replace all 30 dependency functions with a permission-based system:
```python
# Instead of: Depends(get_current_admin_api)
# Use: Depends(require_permission("stores.manage"))
```
- Role hierarchy handles escalation automatically
**2.5 — JWT simplification**
- Token payload: `{user_id, active_context: {type, id}, permissions: [...]}`
- No more role strings in token — permissions resolved at login
**2.6 — Admin UI**
- Role management page (CRUD roles + permissions)
- User role assignment UI (assign roles with context)
- Remove separate admin-users / merchant-users pages -> unified users page with role filter
**2.7 — Drop legacy**
- Remove `store_users` table
- Remove `admin_platforms` table
- Remove old `roles` table
- Remove `users.role` column
- Remove all backward-compat properties
### Phase 2 Benefits
1. **Single source of truth** — all role info in `user_role_assignments`
2. **Context-aware** — same user can have different roles in different stores/merchants
3. **Extensible** — add new contexts (e.g., "warehouse") without schema changes
4. **Auditable** — `granted_by` tracks who assigned roles
5. **Custom roles** — merchants define their own roles with specific permissions
6. **No derived logic** — no checking `owned_merchants_count` or `StoreUser.user_type`
---
## Execution Order
1. **Phase 1 first** (post-demo) — safe, incremental, fixes real bugs
2. **Phase 2 later** — larger refactor, needs dedicated sprint, ideally with test coverage from Phase 1
Phase 1 is designed so Phase 2 builds cleanly on top of it. The 4-value enum from Phase 1 maps 1:1 to the system roles in Phase 2.