- Add source maps and license files for compiled assets - Add debug and test files for development - Complete Git repository with all necessary files for MoneyFlix project
912 lines
42 KiB
PHP
912 lines
42 KiB
PHP
<?php
|
||
use App\Core\AssetPath;
|
||
use App\Core\OutputSanitize;
|
||
?>
|
||
|
||
<div x-data="adminUsersList">
|
||
<div class="row">
|
||
<div class="col-12">
|
||
|
||
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
|
||
<h4 class="mb-sm-0">Gestão de Utilizadores</h4>
|
||
<div class="page-title-right">
|
||
<ol class="breadcrumb m-0">
|
||
<li class="breadcrumb-item"><a href="javascript: void(0);">Admin</a></li>
|
||
<li class="breadcrumb-item active">Utilizadores</li>
|
||
</ol>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="row">
|
||
<div class="col-lg-12">
|
||
<div class="card">
|
||
<div class="card-header">
|
||
<div class="d-flex align-items-center flex-wrap gap-2">
|
||
<div class="flex-grow-1">
|
||
<button class="btn btn-info add-btn" @click="showAddUserModal()">
|
||
<i class="ri-add-fill me-1 align-bottom"></i>
|
||
<span>Adicionar Utilizador</span>
|
||
</button>
|
||
</div>
|
||
<div class="flex-shrink-0">
|
||
<div class="hstack text-nowrap gap-2">
|
||
<button class="btn btn-danger" @click="deleteMultiple()" x-show="selectedUsers.length > 0">
|
||
<i class="ri-delete-bin-2-line"></i>
|
||
</button>
|
||
<div class="btn-group">
|
||
<button class="btn btn-primary" @click="showFiltersModal()">
|
||
<i class="ri-filter-2-line me-1 align-bottom"></i>
|
||
<span>Filtros</span>
|
||
</button>
|
||
<button class="btn btn-outline-primary" @click="toggleShowDeleted()">
|
||
<i class="ri-eye-line me-1 align-bottom"></i>
|
||
<span x-text="showDeleted ? 'Ocultar Eliminados' : 'Mostrar Eliminados'"></span>
|
||
</button>
|
||
</div>
|
||
<button class="btn btn-soft-success" @click="showImportModal()">
|
||
<span>Importar</span>
|
||
</button>
|
||
<div class="dropdown">
|
||
<button type="button" class="btn btn-soft-info dropdown-toggle" data-bs-toggle="dropdown">
|
||
<i class="ri-more-2-fill"></i>
|
||
</button>
|
||
<ul class="dropdown-menu">
|
||
<li><a class="dropdown-item" href="#" @click="exportUsers('all')">Todos</a></li>
|
||
<li><a class="dropdown-item" href="#" @click="exportUsers('week')">Última Semana</a></li>
|
||
<li><a class="dropdown-item" href="#" @click="exportUsers('month')">Último Mês</a></li>
|
||
<li><a class="dropdown-item" href="#" @click="exportUsers('year')">Último Ano</a></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="row">
|
||
<div class="col-xxl-9">
|
||
<div class="card" id="usersList">
|
||
<div class="card-header">
|
||
<div class="row g-3">
|
||
<div class="col-md-4">
|
||
<div class="search-box">
|
||
<input type="text"
|
||
class="form-control search"
|
||
placeholder="Pesquisar utilizadores..."
|
||
x-model="searchQuery"
|
||
@input="debouncedSearch()">
|
||
<i class="ri-search-line search-icon"></i>
|
||
</div>
|
||
</div>
|
||
<div class="col-md-auto ms-auto">
|
||
<div class="d-flex align-items-center gap-2">
|
||
<span class="text-muted">Ordenar por:</span>
|
||
<select class="form-control mb-0" x-model="sortBy" @change="loadUsers()">
|
||
<option value="first_name">Nome</option>
|
||
<option value="email">Email</option>
|
||
<option value="role">Função</option>
|
||
<option value="created_at">Data Criação</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card-body">
|
||
<!-- Loading State -->
|
||
<div x-show="loading" class="text-center py-4">
|
||
<div class="spinner-border text-primary" role="status">
|
||
<span class="visually-hidden">Carregando...</span>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
|
||
<!-- Users Table -->
|
||
<div x-show="!loading">
|
||
<div class="table-responsive table-card mb-3">
|
||
<table class="table align-middle table-nowrap mb-0" id="usersTable">
|
||
<thead class="table-light">
|
||
<tr>
|
||
<th scope="col" style="width: 50px;">
|
||
<div class="form-check">
|
||
<input class="form-check-input"
|
||
type="checkbox"
|
||
@change="toggleAllUsers($event.target.checked)">
|
||
</div>
|
||
</th>
|
||
<th class="sort cursor-pointer" @click="toggleSort('first_name')">
|
||
Nome <i class="ri-arrow-up-down-line"></i>
|
||
</th>
|
||
<th class="sort cursor-pointer" @click="toggleSort('email')">
|
||
Email <i class="ri-arrow-up-down-line"></i>
|
||
</th>
|
||
<th class="sort cursor-pointer" @click="toggleSort('role')">
|
||
Função <i class="ri-arrow-up-down-line"></i>
|
||
</th>
|
||
<th class="sort cursor-pointer" @click="toggleSort('is_active')">
|
||
Estado <i class="ri-arrow-up-down-line"></i>
|
||
</th>
|
||
<th class="sort cursor-pointer" @click="toggleSort('created_at')">
|
||
Data Criação <i class="ri-arrow-up-down-line"></i>
|
||
</th>
|
||
<th scope="col">Ações</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody class="list form-check-all">
|
||
<template x-for="user in users" :key="user.id">
|
||
<tr>
|
||
<th scope="row">
|
||
<div class="form-check">
|
||
<input class="form-check-input"
|
||
type="checkbox"
|
||
:value="user.id"
|
||
:checked="selectedUsers.includes(user.id)"
|
||
@change="toggleUser(user.id)">
|
||
</div>
|
||
</th>
|
||
<td class="name">
|
||
<div class="d-flex align-items-center">
|
||
<div class="flex-shrink-0">
|
||
<img :src="user.avatar || '/public/assets/images/users/avatar-1.jpg'"
|
||
:alt="user.first_name"
|
||
class="avatar-xs rounded-circle">
|
||
</div>
|
||
<div class="flex-grow-1 ms-2">
|
||
<h6 class="mb-0" x-text="`${user.first_name} ${user.last_name}`"></h6>
|
||
<small class="text-muted" x-text="user.username"></small>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
<td class="email" x-text="user.email"></td>
|
||
<td class="role">
|
||
<span class="badge"
|
||
:class="{
|
||
'bg-danger-subtle text-danger': user.role === 'admin',
|
||
'bg-success-subtle text-success': user.role === 'manager',
|
||
'bg-info-subtle text-info': user.role === 'user'
|
||
}"
|
||
x-text="getRoleText(user.role)"></span>
|
||
</td>
|
||
<td class="status">
|
||
<span class="badge"
|
||
:class="{
|
||
'bg-success-subtle text-success': (user.status !== undefined ? user.status : user.is_active) === 1,
|
||
'bg-warning-subtle text-warning': (user.status !== undefined ? user.status : user.is_active) === 0,
|
||
'bg-danger-subtle text-danger': (user.status !== undefined ? user.status : user.is_active) === -1
|
||
}"
|
||
x-text="getStatusText(user)"></span>
|
||
</td>
|
||
<td class="date">
|
||
<span x-text="formatDate(user.created_at)"></span>
|
||
<small class="text-muted d-block" x-text="formatTime(user.created_at)"></small>
|
||
</td>
|
||
<td>
|
||
<ul class="list-inline hstack gap-2 mb-0">
|
||
<li class="list-inline-item" data-bs-toggle="tooltip" title="Enviar Email">
|
||
<a :href="`mailto:${user.email}`" class="text-muted d-inline-block">
|
||
<i class="ri-mail-line fs-16"></i>
|
||
</a>
|
||
</li>
|
||
<li class="list-inline-item">
|
||
<div class="dropdown">
|
||
<button class="btn btn-soft-secondary btn-sm dropdown-toggle"
|
||
type="button"
|
||
data-bs-toggle="dropdown">
|
||
<i class="ri-more-fill align-middle"></i>
|
||
</button>
|
||
<ul class="dropdown-menu dropdown-menu-end">
|
||
<li>
|
||
<a class="dropdown-item" href="#" @click="viewUser(user)">
|
||
<i class="ri-eye-fill align-bottom me-2 text-muted"></i>Ver
|
||
</a>
|
||
</li>
|
||
<li>
|
||
<a class="dropdown-item" href="#" @click="editUser(user)">
|
||
<i class="ri-pencil-fill align-bottom me-2 text-muted"></i>Editar
|
||
</a>
|
||
</li>
|
||
<li>
|
||
<a class="dropdown-item" href="#" @click="resetPassword(user)">
|
||
<i class="ri-key-2-fill align-bottom me-2 text-muted"></i>Reset Password
|
||
</a>
|
||
</li>
|
||
<li>
|
||
<a class="dropdown-item text-danger" href="#" @click="deleteUser(user)">
|
||
<i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i>Eliminar
|
||
</a>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</td>
|
||
</tr>
|
||
</template>
|
||
</tbody>
|
||
</table>
|
||
|
||
<!-- No Results -->
|
||
<div x-show="!loading && users.length === 0" class="noresult text-center py-4">
|
||
<lord-icon src="https://cdn.lordicon.com/msoeawqm.json"
|
||
trigger="loop"
|
||
colors="primary:#121331,secondary:#08a88a"
|
||
style="width:75px;height:75px">
|
||
</lord-icon>
|
||
<h5 class="mt-2">Nenhum resultado encontrado</h5>
|
||
<p class="text-muted mb-0">Não encontrámos utilizadores que correspondam aos critérios de pesquisa.</p>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Pagination -->
|
||
<div x-show="totalPages > 1" class="d-flex justify-content-end mt-3">
|
||
<div class="pagination-wrap hstack gap-2">
|
||
<button class="page-item pagination-prev btn btn-outline-secondary"
|
||
:disabled="currentPage === 1"
|
||
@click="goToPage(currentPage - 1)">
|
||
Anterior
|
||
</button>
|
||
<ul class="pagination mb-0">
|
||
<template x-for="page in visiblePages" :key="page">
|
||
<li class="page-item" :class="{ active: page === currentPage }">
|
||
<button class="page-link" @click="goToPage(page)" x-text="page"></button>
|
||
</li>
|
||
</template>
|
||
</ul>
|
||
<button class="page-item pagination-next btn btn-outline-secondary"
|
||
:disabled="currentPage === totalPages"
|
||
@click="goToPage(currentPage + 1)">
|
||
Seguinte
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Sidebar with Statistics -->
|
||
<div class="col-xxl-3">
|
||
<div class="card card-height-100">
|
||
<div class="card-header">
|
||
<h6 class="card-title mb-0">Estatísticas</h6>
|
||
</div>
|
||
<div class="card-body">
|
||
<div class="row g-3">
|
||
<div class="col-6">
|
||
<div class="text-center">
|
||
<h4 class="mb-1 text-primary" x-text="stats.total || 0">0</h4>
|
||
<p class="text-muted mb-0">Total</p>
|
||
</div>
|
||
</div>
|
||
<div class="col-6">
|
||
<div class="text-center">
|
||
<h4 class="mb-1 text-success" x-text="stats.active || 0">0</h4>
|
||
<p class="text-muted mb-0">Ativos</p>
|
||
</div>
|
||
</div>
|
||
<div class="col-6">
|
||
<div class="text-center">
|
||
<h4 class="mb-1 text-warning" x-text="stats.inactive || 0">0</h4>
|
||
<p class="text-muted mb-0">Inativos</p>
|
||
</div>
|
||
</div>
|
||
<div class="col-6">
|
||
<div class="text-center">
|
||
<h4 class="mb-1 text-danger" x-text="stats.deleted || 0">0</h4>
|
||
<p class="text-muted mb-0">Eliminados</p>
|
||
</div>
|
||
</div>
|
||
<div class="col-6">
|
||
<div class="text-center">
|
||
<h4 class="mb-1 text-info" x-text="stats.admins || 0">0</h4>
|
||
<p class="text-muted mb-0">Admins</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Recent Activity -->
|
||
<div class="card">
|
||
<div class="card-header">
|
||
<h6 class="card-title mb-0">Atividade Recente</h6>
|
||
</div>
|
||
<div class="card-body">
|
||
<div class="list-group list-group-flush">
|
||
<template x-for="activity in recentActivity" :key="activity.id">
|
||
<div class="list-group-item px-0">
|
||
<div class="d-flex align-items-center">
|
||
<div class="flex-shrink-0">
|
||
<div class="avatar-xs">
|
||
<div class="avatar-title rounded-circle"
|
||
:class="activity.type === 'login' ? 'bg-success-subtle text-success' : 'bg-info-subtle text-info'">
|
||
<i :class="activity.type === 'login' ? 'ri-login-circle-line' : 'ri-user-add-line'"></i>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="flex-grow-1 ms-3">
|
||
<h6 class="mb-0 fs-14" x-text="activity.description"></h6>
|
||
<p class="text-muted mb-0 fs-12" x-text="formatDate(activity.created_at)"></p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
<div x-show="recentActivity.length === 0" class="text-center py-3">
|
||
<div class="text-muted">Nenhuma atividade recente</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Add/Edit User Modal -->
|
||
<div class="modal fade" id="userModal" tabindex="-1" :class="{'show': showModal, 'd-block': showModal}" x-show="showModal" style="display: none;">
|
||
<div class="modal-dialog modal-dialog-centered modal-lg">
|
||
<div class="modal-content border-0">
|
||
<div class="modal-header bg-info-subtle p-3">
|
||
<h5 class="modal-title" x-text="selectedUser.id ? 'Editar Utilizador' : 'Adicionar Utilizador'"></h5>
|
||
<button type="button" class="btn-close" @click="closeModal()"></button>
|
||
</div>
|
||
<form @submit.prevent="saveUser()">
|
||
<div class="modal-body">
|
||
<div class="row g-3">
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Nome *</label>
|
||
<input type="text" class="form-control" x-model="selectedUser.first_name" required>
|
||
</div>
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Apelido *</label>
|
||
<input type="text" class="form-control" x-model="selectedUser.last_name" required>
|
||
</div>
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Username *</label>
|
||
<input type="text" class="form-control" x-model="selectedUser.username" required>
|
||
</div>
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Email *</label>
|
||
<input type="email" class="form-control" x-model="selectedUser.email" required>
|
||
</div>
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Função *</label>
|
||
<select class="form-control" x-model="selectedUser.role" required>
|
||
<option value="user">Utilizador</option>
|
||
<option value="manager">Gestor</option>
|
||
<option value="admin">Administrador</option>
|
||
</select>
|
||
</div>
|
||
<div class="col-lg-6">
|
||
<label class="form-label">Estado *</label>
|
||
<select class="form-control" x-model="selectedUser.status" required>
|
||
<option value="1">Ativo</option>
|
||
<option value="0">Inativo</option>
|
||
</select>
|
||
</div>
|
||
<div class="col-lg-12" x-show="!selectedUser.id">
|
||
<label class="form-label">Password *</label>
|
||
<input type="password" class="form-control" x-model="selectedUser.password" :required="!selectedUser.id">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-secondary" @click="closeModal()">Cancelar</button>
|
||
<button type="submit" class="btn btn-primary" :disabled="saving">
|
||
<span x-show="saving">
|
||
<span class="spinner-border spinner-border-sm me-1"></span>
|
||
</span>
|
||
<span x-text="selectedUser.id ? 'Atualizar' : 'Criar'"></span>
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
</div> <!-- Fechar modal -->
|
||
|
||
<!-- Filters Modal -->
|
||
<div class="modal fade" id="filtersModal" tabindex="-1" x-show="showFilters" style="display: none;">
|
||
<div class="modal-dialog modal-dialog-centered">
|
||
<div class="modal-content border-0">
|
||
<div class="modal-header bg-primary-subtle p-3">
|
||
<h5 class="modal-title">Filtros Avançados</h5>
|
||
<button type="button" class="btn-close" @click="closeFilters()"></button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div class="row g-3">
|
||
<div class="col-md-6">
|
||
<label class="form-label">Função</label>
|
||
<select class="form-control" x-model="filters.role">
|
||
<option value="">Todas as funções</option>
|
||
<option value="admin">Administrador</option>
|
||
<option value="manager">Gestor</option>
|
||
<option value="user">Utilizador</option>
|
||
</select>
|
||
</div>
|
||
<div class="col-md-6">
|
||
<label class="form-label">Estado</label>
|
||
<select class="form-control" x-model="filters.status">
|
||
<option value="">Todos os estados</option>
|
||
<option value="1">Ativo</option>
|
||
<option value="0">Inativo</option>
|
||
<option value="-1">Eliminado</option>
|
||
</select>
|
||
</div>
|
||
<div class="col-md-6">
|
||
<label class="form-label">Data de criação (desde)</label>
|
||
<input type="date" class="form-control" x-model="filters.dateFrom">
|
||
</div>
|
||
<div class="col-md-6">
|
||
<label class="form-label">Data de criação (até)</label>
|
||
<input type="date" class="form-control" x-model="filters.dateTo">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-secondary" @click="clearFilters()">Limpar</button>
|
||
<button type="button" class="btn btn-primary" @click="applyFilters()">Aplicar Filtros</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<style>
|
||
.cursor-pointer { cursor: pointer; }
|
||
.avatar-xs { width: 2rem; height: 2rem; }
|
||
.lord-icon { display: inline-block; }
|
||
</style>
|
||
|
||
<script>
|
||
// Componente adminUsersList completo inline
|
||
document.addEventListener('alpine:init', () => {
|
||
Alpine.data('adminUsersList', () => ({
|
||
|
||
// Main data
|
||
users: [],
|
||
loading: false,
|
||
saving: false,
|
||
selectedUsers: [],
|
||
|
||
// Pagination
|
||
currentPage: 1,
|
||
itemsPerPage: 15,
|
||
totalItems: 0,
|
||
totalPages: 0,
|
||
visiblePages: [],
|
||
|
||
// Search and sort
|
||
searchQuery: '',
|
||
sortBy: 'first_name',
|
||
sortDirection: 'asc',
|
||
showDeleted: false,
|
||
|
||
// Stats and activity
|
||
stats: { total: 0, active: 0, inactive: 0, admins: 0 },
|
||
recentActivity: [],
|
||
|
||
// Filters
|
||
showFilters: false,
|
||
filters: {
|
||
role: '',
|
||
status: '',
|
||
dateFrom: '',
|
||
dateTo: ''
|
||
},
|
||
|
||
// Modal
|
||
showModal: false,
|
||
selectedUser: {
|
||
id: null,
|
||
first_name: '',
|
||
last_name: '',
|
||
username: '',
|
||
email: '',
|
||
role: 'user',
|
||
status: 1,
|
||
password: ''
|
||
},
|
||
|
||
init() {
|
||
this.loadUsers();
|
||
|
||
// Watch for search query changes
|
||
this.$watch('searchQuery', () => {
|
||
this.currentPage = 1;
|
||
this.loadUsers();
|
||
});
|
||
},
|
||
|
||
async loadUsers() {
|
||
try {
|
||
this.loading = true;
|
||
|
||
const params = new URLSearchParams({
|
||
page: this.currentPage,
|
||
limit: this.itemsPerPage,
|
||
search: this.searchQuery,
|
||
sort: this.sortBy,
|
||
direction: this.sortDirection,
|
||
show_deleted: this.showDeleted,
|
||
role: this.filters.role,
|
||
status: this.filters.status,
|
||
date_from: this.filters.dateFrom,
|
||
date_to: this.filters.dateTo
|
||
});
|
||
|
||
console.log('📡 Loading users with params:', {
|
||
show_deleted: this.showDeleted,
|
||
page: this.currentPage,
|
||
search: this.searchQuery
|
||
});
|
||
|
||
const response = await fetch(`/api/admin/users?${params}`, {
|
||
credentials: 'include',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
|
||
const data = await response.json();
|
||
|
||
if (data.success) {
|
||
this.users = data.users || data.data?.users || data.data || [];
|
||
this.totalItems = data.total || data.data?.total || 0;
|
||
this.totalPages = data.total_pages || data.data?.total_pages || Math.ceil(this.totalItems / this.itemsPerPage);
|
||
|
||
// Carregar estatísticas completas
|
||
this.loadStats();
|
||
|
||
// Carregar atividades recentes
|
||
this.loadRecentActivity();
|
||
|
||
// Forçar reatividade do Alpine.js
|
||
this.$nextTick(() => {
|
||
// Reatividade ativada
|
||
});
|
||
} else {
|
||
console.error('API Error:', data.message);
|
||
}
|
||
} catch (error) {
|
||
console.error('Error loading users:', error);
|
||
} finally {
|
||
this.loading = false;
|
||
}
|
||
},
|
||
|
||
formatDate(dateString) {
|
||
if (!dateString) return 'N/A';
|
||
return new Date(dateString).toLocaleDateString('pt-PT');
|
||
},
|
||
|
||
formatTime(dateString) {
|
||
if (!dateString) return '';
|
||
return new Date(dateString).toLocaleTimeString('pt-PT');
|
||
},
|
||
|
||
getRoleText(role) {
|
||
const roles = { admin: 'Administrador', manager: 'Gestor', user: 'Utilizador' };
|
||
return roles[role] || role;
|
||
},
|
||
|
||
getStatusText(user) {
|
||
// O campo pode ser 'status' ou 'is_active'
|
||
const status = user.status !== undefined ? user.status : user.is_active;
|
||
if (status === 1) return 'Ativo';
|
||
if (status === 0) return 'Inativo';
|
||
if (status === -1) return 'Eliminado';
|
||
return 'Bloqueado';
|
||
},
|
||
|
||
async loadStats() {
|
||
try {
|
||
const response = await fetch('/api/admin/users/stats', {
|
||
credentials: 'include',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
|
||
if (response.ok) {
|
||
const data = await response.json();
|
||
this.stats = data.stats || {
|
||
total: 0,
|
||
active: 0,
|
||
inactive: 0,
|
||
deleted: 0,
|
||
admins: 0
|
||
};
|
||
} else {
|
||
// Fallback para calcular com os utilizadores visíveis
|
||
this.calculateStatsFromVisible();
|
||
}
|
||
} catch (error) {
|
||
console.error('Error loading stats:', error);
|
||
// Fallback para calcular com os utilizadores visíveis
|
||
this.calculateStatsFromVisible();
|
||
}
|
||
},
|
||
|
||
calculateStatsFromVisible() {
|
||
this.stats = {
|
||
total: this.users.length,
|
||
active: this.users.filter(user => {
|
||
const status = user.status !== undefined ? user.status : user.is_active;
|
||
return status === 1;
|
||
}).length,
|
||
inactive: this.users.filter(user => {
|
||
const status = user.status !== undefined ? user.status : user.is_active;
|
||
return status === 0;
|
||
}).length,
|
||
deleted: this.users.filter(user => {
|
||
const status = user.status !== undefined ? user.status : user.is_active;
|
||
return status === -1;
|
||
}).length,
|
||
admins: this.users.filter(user => user.role === 'admin').length
|
||
};
|
||
},
|
||
|
||
toggleSort(field) {
|
||
if (this.sortBy === field) {
|
||
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
|
||
} else {
|
||
this.sortBy = field;
|
||
this.sortDirection = 'asc';
|
||
}
|
||
this.loadUsers();
|
||
},
|
||
|
||
loadRecentActivity() {
|
||
// Gerar atividades recentes baseadas nos utilizadores
|
||
const activities = [];
|
||
const now = new Date();
|
||
|
||
this.users.slice(0, 5).forEach((user, index) => {
|
||
const activityDate = new Date(now.getTime() - (index * 30 * 60 * 1000)); // 30 min apart
|
||
|
||
activities.push({
|
||
id: `activity_${user.id}_${index}`,
|
||
type: index % 2 === 0 ? 'login' : 'created',
|
||
description: index % 2 === 0
|
||
? `${user.first_name || user.username} fez login`
|
||
: `Utilizador ${user.first_name || user.username} foi criado`,
|
||
created_at: activityDate.toISOString(),
|
||
user_id: user.id
|
||
});
|
||
});
|
||
|
||
// Ordenar por data mais recente
|
||
this.recentActivity = activities.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
||
},
|
||
|
||
// Modal management
|
||
showAddUserModal() {
|
||
console.log('➕ Opening add user modal');
|
||
this.selectedUser = {
|
||
id: null,
|
||
first_name: '',
|
||
last_name: '',
|
||
username: '',
|
||
email: '',
|
||
role: 'user',
|
||
status: 1,
|
||
password: ''
|
||
};
|
||
this.showModal = true;
|
||
console.log('✅ Modal should be visible:', this.showModal);
|
||
|
||
// Forçar abertura do modal Bootstrap
|
||
this.$nextTick(() => {
|
||
const modal = document.getElementById('userModal');
|
||
if (modal) {
|
||
const bsModal = new bootstrap.Modal(modal);
|
||
bsModal.show();
|
||
}
|
||
});
|
||
},
|
||
|
||
// User actions
|
||
viewUser(user) {
|
||
console.log('👁️ Opening view user modal:', user);
|
||
this.selectedUser = { ...user };
|
||
this.showModal = true;
|
||
},
|
||
|
||
editUser(user) {
|
||
console.log('✏️ Opening edit user modal:', user);
|
||
this.selectedUser = { ...user, password: '' };
|
||
this.showModal = true;
|
||
},
|
||
|
||
async deleteUser(user) {
|
||
if (confirm(`Tens a certeza que queres eliminar o utilizador ${user.first_name || user.username}?`)) {
|
||
try {
|
||
console.log('🗑️ Deleting user:', user.id);
|
||
const response = await fetch(`/api/admin/users/${user.id}`, {
|
||
method: 'DELETE',
|
||
credentials: 'include',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
|
||
console.log('📡 Delete response status:', response.status);
|
||
|
||
if (response.ok) {
|
||
const result = await response.json();
|
||
console.log('✅ Delete successful:', result);
|
||
this.loadUsers();
|
||
alert('Utilizador eliminado com sucesso');
|
||
} else {
|
||
const error = await response.json();
|
||
console.error('❌ Delete error:', error);
|
||
alert('Erro: ' + (error.message || error.error || 'Falha ao eliminar utilizador'));
|
||
}
|
||
} catch (error) {
|
||
console.error('❌ Delete exception:', error);
|
||
alert('Erro ao eliminar utilizador: ' + error.message);
|
||
}
|
||
}
|
||
},
|
||
|
||
async resetPassword(user) {
|
||
if (confirm(`Tens a certeza que queres fazer reset da password do utilizador ${user.first_name} ${user.last_name}?`)) {
|
||
try {
|
||
const response = await fetch(`/api/admin/users/${user.id}/reset-password`, {
|
||
method: 'POST',
|
||
credentials: 'include',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
|
||
if (response.ok) {
|
||
const data = await response.json();
|
||
alert('Password reset com sucesso. Nova password: ' + data.new_password);
|
||
} else {
|
||
const error = await response.json();
|
||
alert('Erro: ' + (error.message || 'Falha ao reset password'));
|
||
}
|
||
} catch (error) {
|
||
console.error('Error resetting password:', error);
|
||
alert('Erro ao reset password');
|
||
}
|
||
}
|
||
},
|
||
|
||
|
||
// Bulk actions
|
||
deleteMultiple() {
|
||
if (this.selectedUsers.length === 0) {
|
||
alert('Seleciona utilizadores para eliminar');
|
||
return;
|
||
}
|
||
|
||
if (confirm(`Tens a certeza que queres eliminar ${this.selectedUsers.length} utilizadores?`)) {
|
||
// Implementar eliminação múltipla
|
||
this.selectedUsers.forEach(userId => {
|
||
const user = this.users.find(u => u.id === userId);
|
||
if (user) this.deleteUser(user);
|
||
});
|
||
this.selectedUsers = [];
|
||
}
|
||
},
|
||
|
||
toggleAllUsers(checked) {
|
||
if (checked) {
|
||
this.selectedUsers = this.users.map(user => user.id);
|
||
} else {
|
||
this.selectedUsers = [];
|
||
}
|
||
},
|
||
|
||
toggleUser(userId) {
|
||
const index = this.selectedUsers.indexOf(userId);
|
||
if (index > -1) {
|
||
this.selectedUsers.splice(index, 1);
|
||
} else {
|
||
this.selectedUsers.push(userId);
|
||
}
|
||
},
|
||
|
||
// Modal actions
|
||
async saveUser() {
|
||
try {
|
||
this.saving = true;
|
||
|
||
const url = this.selectedUser.id
|
||
? `/api/admin/users/${this.selectedUser.id}`
|
||
: '/api/admin/users';
|
||
|
||
const method = this.selectedUser.id ? 'PUT' : 'POST';
|
||
|
||
const response = await fetch(url, {
|
||
method: method,
|
||
credentials: 'include',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(this.selectedUser)
|
||
});
|
||
|
||
if (response.ok) {
|
||
this.showModal = false;
|
||
this.loadUsers();
|
||
alert('Utilizador guardado com sucesso');
|
||
} else {
|
||
const error = await response.json();
|
||
alert('Erro: ' + (error.message || 'Falha ao guardar utilizador'));
|
||
}
|
||
} catch (error) {
|
||
console.error('Error saving user:', error);
|
||
alert('Erro ao guardar utilizador');
|
||
} finally {
|
||
this.saving = false;
|
||
}
|
||
},
|
||
|
||
closeModal() {
|
||
this.showModal = false;
|
||
this.selectedUser = {
|
||
id: null,
|
||
first_name: '',
|
||
last_name: '',
|
||
username: '',
|
||
email: '',
|
||
role: 'user',
|
||
status: 1,
|
||
password: ''
|
||
};
|
||
},
|
||
|
||
// Other actions
|
||
showFiltersModal() {
|
||
// Mostrar modal de filtros avançados
|
||
this.showFilters = true;
|
||
this.$nextTick(() => {
|
||
const modal = document.getElementById('filtersModal');
|
||
if (modal) {
|
||
const bsModal = new bootstrap.Modal(modal);
|
||
bsModal.show();
|
||
}
|
||
});
|
||
},
|
||
|
||
showImportModal() {
|
||
// Implementar modal de importação
|
||
alert('Importação em desenvolvimento');
|
||
},
|
||
|
||
closeFilters() {
|
||
this.showFilters = false;
|
||
},
|
||
|
||
clearFilters() {
|
||
this.filters = {
|
||
role: '',
|
||
status: '',
|
||
dateFrom: '',
|
||
dateTo: ''
|
||
};
|
||
this.currentPage = 1;
|
||
this.loadUsers();
|
||
this.closeFilters();
|
||
},
|
||
|
||
applyFilters() {
|
||
this.currentPage = 1;
|
||
this.loadUsers();
|
||
this.closeFilters();
|
||
},
|
||
|
||
goToPage(page) {
|
||
this.currentPage = page;
|
||
this.loadUsers();
|
||
},
|
||
|
||
toggleShowDeleted() {
|
||
console.log('🔄 Toggle show deleted - before:', this.showDeleted);
|
||
this.showDeleted = !this.showDeleted;
|
||
console.log('🔄 Toggle show deleted - after:', this.showDeleted);
|
||
this.currentPage = 1;
|
||
this.loadUsers();
|
||
}
|
||
}));
|
||
});
|
||
</script>
|
||
|
||
</div> <!-- Fechar div principal com x-data -->
|