geqintan's picture
update
c16f98d
// static/js/admin/users.js
const { createApp } = Vue;
import { authData, authMethods, authMounted } from '../auth.js';
import { appData, appMethods, appMounted } from '../store.js';
import AdminNavbar from '../components/AdminNavbar.js'; // Import the new component
const UserManagementApp = {
components: {
AdminNavbar // Register the component
},
// template: document.querySelector('#app template').innerHTML, // Removed template option
data() {
return {
...authData(),
...appData(),
currentPath: window.location.pathname, // Add currentPath to data
// 用户管理相关数据
users: [],
userSearchQuery: '',
currentPage: 1,
pageSize: 10,
totalUsers: 0,
totalPages: 0,
userMessage: '',
editingUser: {
id: null,
email: '',
password: '',
email_verified: false,
is_admin: false,
disabled: false
},
isSavingUser: false,
editUserModal: null // Bootstrap Modal instance
};
},
methods: {
...authMethods(this),
...appMethods(this),
async fetchUsers() {
this.userMessage = '加载用户中...';
try {
const token = localStorage.getItem('access_token');
let url = `/api/admin/users?page=${this.currentPage}&page_size=${this.pageSize}`;
if (this.userSearchQuery) {
url += `&search=${encodeURIComponent(this.userSearchQuery)}`;
}
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
});
const responseData = await response.json();
if (response.ok) {
this.users = responseData.users;
this.totalUsers = responseData.total_count;
this.totalPages = Math.ceil(this.totalUsers / this.pageSize);
this.userMessage = '';
console.log('Fetched users successfully. totalUsers:', this.totalUsers, 'totalPages:', this.totalPages);
} else {
this.userMessage = responseData.detail || '获取用户失败。';
}
} catch (error) {
this.userMessage = '网络错误或服务器无响应。';
console.error('获取用户错误:', error);
}
},
changePage(pageNumber) {
if (pageNumber > 0 && pageNumber <= this.totalPages) {
this.currentPage = pageNumber;
this.fetchUsers();
}
},
editUser(user) {
this.editingUser = { ...user, password: '' }; // Clear password field for security
this.editUserModal.show();
},
async saveUserChanges() {
this.isSavingUser = true;
this.userMessage = '';
try {
const token = localStorage.getItem('access_token');
const updatePayload = {
email: this.editingUser.email,
email_verified: this.editingUser.email_verified,
is_admin: this.editingUser.is_admin,
disabled: this.editingUser.disabled
};
if (this.editingUser.password) {
updatePayload.password = this.editingUser.password;
}
const response = await fetch(`/api/admin/users/${this.editingUser.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(updatePayload)
});
const data = await response.json();
if (response.ok) {
this.userMessage = '用户更新成功!';
this.fetchUsers(); // Refresh user list
this.editUserModal.hide();
} else {
this.userMessage = data.detail || '用户更新失败。';
}
} catch (error) {
this.userMessage = '网络错误或服务器无响应。';
console.error('更新用户错误:', error);
} finally {
this.isSavingUser = false;
}
},
async deleteUser(userId) {
if (!confirm('确定要删除此用户吗?此操作不可逆!')) {
return;
}
this.userMessage = '删除用户中...';
try {
const token = localStorage.getItem('access_token');
const response = await fetch(`/api/admin/users/${userId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
this.userMessage = '用户删除成功!';
this.fetchUsers(); // Refresh user list
} else {
const data = await response.json();
this.userMessage = data.detail || '用户删除失败。';
}
} catch (error) {
this.userMessage = '网络错误或服务器无响应。';
console.error('删除用户错误:', error);
}
},
handleShowChangePasswordModal() {
this.showChangePasswordModal = true;
}
},
mounted() {
authMounted(this);
appMounted(this);
console.log('User management app mounted!');
this.editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
this.fetchUsers(); // Fetch users on page load
},
watch: {
// No specific watchers needed for this standalone page yet
}
};
createApp(UserManagementApp).mount('#app');
console.log('User management Vue app successfully mounted to #app element.');